branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># DS_kursapp
This simple Shiny-app will be used in a distance sampling class, aimed at volunteers conducting line-transect work for birds (mainly grouse in this case), and where the data will be analysed using Distance Sampling methods. The idea is that the course participants should be able to do simple analysis on their test-data, including looking at the distribution of distance-to-line data. So far, at this stage only "Half Normal" key function is implemented, and data is always truncated at 10%. <file_sep>
library(shiny)
library(knitr)
library(Distance)
shinyServer(function(input, output) {
output$contents <- renderTable({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, it will be a data frame with 'name',
# 'size', 'type', and 'datapath' columns. The 'datapath'
# column will contain the local filenames where the data can
# be found.
inFile <- input$file1
if (is.null(inFile))
return(NULL)
dat <- read.csv2(inFile$datapath, header=TRUE, sep=input$sep)
head(dat, 10)
}, include.rownames=FALSE)
###########################################################
my_dat <- reactive({
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}
read.csv2(inFile$datapath, header=TRUE, sep=input$sep)
})
############################################################
output$distPlot <- renderPlot({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, it will be a data frame with 'name',
# 'size', 'type', and 'datapath' columns. The 'datapath'
# column will contain the local filenames where the data can
# be found.
inFile <- input$file1
if (is.null(inFile))
return(NULL)
dat <- my_dat()
x <- dat$Linjeavstand # Distance data
# draw the histogram with the specified number of bins
hist(x, col = input$histcol, border = 'white', xlab="Linjeavstand",ylab="Antall observasjoner",
main="", nclass=input$bins1, cex=2)
})
#####################################################################
output$Deskr <- renderTable({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
dat <- my_dat()
temp <- sort(unique(dat$Linjenavn))
temp_1 <- length(temp)+1
desc <- as.data.frame(matrix(ncol=4, nrow=temp_1))
for(i in 1:length(temp)){
tempo <- subset(dat, Linjenavn==temp[i])
desc[i,1] <- temp[i]
desc[i,2] <- tempo$Linjelengde[1]
tempo1 <- subset(tempo, Antall>0)
desc[i,3] <- dim(tempo1)[1]
desc[i,4] <- sum(tempo1$Antall)
}
colnames(desc) <- c("Linjenavn", paste("Linjelengde i ", (input$Taks), sep=" "), "Antall obs", "Antall individer observert")
desc[temp_1,1] <- paste(length(temp), "linjer", sep=" ")
desc[temp_1,2] <- sum(desc[,2], na.rm=T)
desc[temp_1,3] <- sum(desc[,3], na.rm=T)
desc[temp_1,4] <- sum(desc[,4], na.rm=T)
colnames(desc) <- c("Linjenavn", paste("Linjelengde i ", (input$Taks), sep=" "), "Antall obs", "Antall individer observert")
#rownames(desc) <- c(rep(NULL, length(desc)[1]-1), "Totalt")
desc1 <- switch(input$desc1,
lin={colnames(desc) <- c("Linjenavn", paste("Linjelengde i ", (input$Taks), sep=" "), "Antall obs", "Antall individer observert")
desc <- desc[1:length(temp),]},
saml={colnames(desc) <- c("<NAME>", paste("Linjelengde i ", (input$Taks), sep=" "), "Antall obs", "Antall individer observert")
desc <- desc[temp_1,]}
)
desc1
}, include.rownames=FALSE)
###########################################################
Distance1 <- eventReactive(input$go_analyse, {
inFile <- input$file1
if (is.null(inFile))
return(NULL)
dat <- my_dat()
dat <- dat[,c(1:5)]
colnames(dat) <- c("Sample.Label", "Obs.nr", "distance", "size", "Effort")
dat$Region.Label <- rep(1, dim(dat)[1])
## Data table
temp1 <- subset(dat, distance!="NA")
temp1$object <- seq(1:dim(temp1)[1])
temp1 <- temp1[, c("object", "distance", "size")]
Data_tab <- temp1
## Region table
Reg_tab <- as.data.frame(matrix(ncol=2, nrow=1))
Reg_tab[1,1] <- dat$Region.Label[1]
Reg_tab[1,2] <- 1000
colnames(Reg_tab) <- c("Region.Label", "Area")
## Sample table
temp <- sort(unique(dat$Sample.Label))
Samp_tab <- as.data.frame(matrix(ncol=3, nrow=length(temp)))
colnames(Samp_tab) <- c("Sample.Label", "Region.Label", "Effort")
for(i in 1:length(temp)){
tempo <- subset(dat, Sample.Label==temp[i])
Samp_tab[i,1] <- temp[i]
Samp_tab[i,2] <- dat$Region.Label[1]
Samp_tab[i,3] <- tempo$Effort[1]
}
## Obs table
temp1 <- subset(dat, distance!="NA")
temp1$object <- seq(1:dim(temp1)[1])
obs_tab <- temp1[,c("object", "Region.Label", "Sample.Label")]
d_la <- ifelse(input$LiAv=="meter", 1, 0.001)
d_e <- ifelse(input$Taks=="meter", 1, 1000)
d_1 <- ifelse(input$Dens=="meter", 1, 0.000001)
temp <- d_1*d_la*d_e
ds.model1 <-ds(Data_tab, region.table=Reg_tab, sample.table=Samp_tab,
obs.table=obs_tab,
adjustment=NULL, transect="line", truncation="10%",
formula= ~1, key="hn", convert.units=temp)
})
##########################################
output$Distance <- renderTable({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
ds.model1 <- Distance1()
res <- matrix(ncol=5, nrow=3)
res[1,1] <- as.numeric(paste(ds.model1$dht$individuals$D[2]))
res[1,2] <- as.numeric(paste(ds.model1$dht$individuals$D[3]))
res[1,3] <- as.numeric(paste(ds.model1$dht$individuals$D[4]))
res[1,4] <- as.numeric(paste(ds.model1$dht$individuals$D[5]))
res[1,5] <- as.numeric(paste(ds.model1$dht$individuals$D[6]))
res[2,1] <- as.numeric(paste(ds.model1$dht$clusters$D[2]))
res[2,2] <- as.numeric(paste(ds.model1$dht$clusters$D[3]))
res[2,3] <- as.numeric(paste(ds.model1$dht$clusters$D[4]))
res[2,4] <- as.numeric(paste(ds.model1$dht$clusters$D[5]))
res[2,5] <- as.numeric(paste(ds.model1$dht$clusters$D[6]))
res[3,1] <- as.numeric(paste(ds.model1$dht$Expected.S[1,2]))
res[3,2] <- as.numeric(paste(ds.model1$dht$Expected.S[1,3]))
res[3,3] <- as.numeric(paste(res[3,2]/res[3,1]))
colnames(res) <- c("Estimat", "SE", "CV", "Nedre 95% CL", "Øvre 95% CL")
rownames(res) <- c("Total tetthet", "Tetthet av grupper", "Gjennomsnittlig gruppestørrelse")
res
}, caption = "Tabell 1: Oversikt over estimert tetthet (antall individer pr. arealenhet), tetthet av grupper
(antall grupper pr. arealenhet) og gruppestørrelse. Arealenhet velger du i feltet til venstre.",
caption.placement = getOption("xtable.caption.placement", "top"),
caption.width = getOption("xtable.caption.width", NULL))
######################################################################
output$Distance2 <- renderPlot({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
ds.model1 <- Distance1()
plot(ds.model1)
})
####################################
output$table.text <- renderText({
"Tabell 1: Oversikt over estimert tetthet (antall individer pr. arealenhet), tetthet av grupper
(antall grupper pr. arealenhet) og gruppestørrelse. Arealeneht velger du i feltet til venstre."
})
######################################################################
output$Distance3 <- renderPlot({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
model1 <- ds.model1 <- Distance1()
klasser<-input$bins2+1
model <- model1$ddf
ltmodel <- model$ds
width <- model$meta.data$width
left <- model$meta.data$left
ddfobj <- ltmodel$aux$ddfobj
point <- ltmodel$aux$point
int.range <- ltmodel$aux$int.range
Nhat <-model$Nhat
breaks <- seq(left,width, length.out=klasser)
nc <- length(breaks)-1
selected <- rep(TRUE,nrow(ddfobj$xmat))
xmat <- ddfobj$xmat
expected.counts <- (breaks[2:(nc+1)]-breaks[1:nc])*(Nhat/breaks[nc+1])
hdat <- xmat$distance
hist.obj <- hist(hdat, breaks=breaks, plot=FALSE)
hist.obj$density <- hist.obj$counts/expected.counts
hist.obj$density[expected.counts==0] <- 0
freq <- hist.obj$density
hist.obj$equidist <- FALSE
sigma <- exp( summary(ds.model1)$ds$coef$key.scale$estimate)
sigma_upper <- exp( (summary(ds.model1)$ds$coef$key.scale$estimate)+(summary(ds.model1)$ds$coef$key.scale$se) )
sigma_lower <- exp( (summary(ds.model1)$ds$coef$key.scale$estimate)-(summary(ds.model1)$ds$coef$key.scale$se) )
### ESTIMATION OF ESW:
E_P <- summary(ds.model1)$ds$average.p
ESW <- as.integer(E_P*as.numeric(width))
ESW_cv <- summary(ds.model1)$ds$average.p.se/summary(ds.model1)$ds$average.p
ESW_se <- as.integer(ESW*ESW_cv)
### Cramer von misen p verdi
### ESTIMATION OF g(x) FOR HALF-NORMAL MODEL;
x <- seq(left, width, length.out=1000)
x2 <- x^2
sigma2 <- sigma^2
sigma2_lower <- sigma_lower^2
sigma2_upper <- sigma_upper^2
gx <- exp(-x2/(2*sigma2))
gx_lower <- exp(-x2/(2*sigma2_lower))
gx_upper <- exp(-x2/(2*sigma2_upper))
par(mfrow=c(1,2))
#### Plottig gx and observations
par(bty="l")
plot(x=c(0, 0), y=c(0,0), xlim=c(0, max(breaks)), ylim=c(0, max(hist.obj$density)+0.1),
type="n", xlab=paste("Linjeavstand (", input$LiAv, ")", sep=""), ylab="Oppdagbarhet")
for(i in 1:nc){
temp1 <- hist.obj$density[i]
temp2 <- breaks[c(i, i+1)]
temp2 <- temp2
polygon(x=c(temp2[1], temp2[1], temp2[2], temp2[2]), y=c(0, temp1, temp1, 0), col="slategray2")
}
lines(x, gx, lwd=3, col="dark red")
#### plotting gx - with se
par(bty="l")
plot(x, gx, ylim=c(0,1), xlim=c(left, width), lwd=3, type="l", xlab=paste("Linjeavstand (", input$LiAv, ")", sep=""), ylab="Oppdagbarhet")
lines(x, gx_lower)
lines(x, gx_upper)
polygon(x=c(x, rev(x)), y=c(gx_upper, rev(gx_lower)), col=adjustcolor("blue", alpha=0.1), border=NA)
})
############################
})<file_sep>
library(shiny)
library(knitr)
library(rmarkdown)
shinyUI(fluidPage(
br(),
img(src = "logo_web.png", width = "300px", height = "50px"),
br(),
br(),
titlePanel(h2("DISTANCE-SAMPLING-ANALYSER: KURSMODUL")),
br(),
hr(),
br(),
br(),
br(),
sidebarLayout(position="left",
sidebarPanel(
helpText(h4("Oversikt"),p("Her dukker det opp hjelpefunksjoner som er tilpasset
den siden du er på. Dette gjør det mulig for deg å laste opp kursfila
og utforske datasettt på en enkel måte")),
tags$hr(),
conditionalPanel(
"$('li.active a').first().html()==='Last opp kursfil'",
helpText("Her kan du laste opp og se på kursfila. Dersom den ser merkelig ut
skyldes dette trolig at du ikke har valgt riktig filformat i menyen til venstre. Sørg
for at du har lastet opp fila i riktig format før du går videre"),
fileInput('file1', 'Se på kursfila',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
radioButtons('sep', 'Filformat',
c(Comma=',',
Semicolon=';',
Tab='\t'),
';'),
br(),
br()
),
conditionalPanel(
"$('li.active a').first().html()==='Histogram'",
helpText("Velg hvor mange grupperinger (søyler) du ønsker i hisogrammet som vises til høyre på siden"),
numericInput("bins1", 'Antall grupperinger', value=5, width="170px"),
selectInput("histcol", "Farge på histogram", choices=c(Blå="cornflowerblue", Grå="grey",
orange="darkgoldenrod"), width="170px")
),
conditionalPanel(
"$('li.active a').first().html()==='Summarisk oversikt'",
helpText("Velg hvilken målestokk som er benyttet for de oppgitte linjeavstander og
linjelengder, og hvorvidt du ønsker oversikt linje for linje eller samlet"),
br(),
radioButtons("desc1", 'Vis oversikt', c(Linjevis='lin', Samlet='saml'), 'lin'),
br(),
radioButtons("LiAv", 'Linjeavstand er oppgitt i', c(Meter='meter', Centimeter='cm'), 'meter'),
br(),
radioButtons("Taks", 'Linjelengde er oppgitt i', c(Meter='meter', Kilometer='km'), 'meter'),
br()
),
conditionalPanel(
"$('li.active a').first().html()==='Distance Sampling'",
helpText("Her kan du gjøre diverse valg knyttet til analysene og
hvordan du vil se på resultatene. Når du har gjort dine valg,
trykk på knappen Analyser data"),
br(),
br(),
radioButtons("Dens", 'Tetthet måles i', c(Kvadratmeter='meter', Kvadratkilometer='km'), 'km'),
br(),
br(),
numericInput("bins2", 'Antall grupperinger', value=7, width="170px"),
br(),
br(),
actionButton("go_analyse", "Analyser data!", icon("thumbs-up")),
br()
)
),
mainPanel(width=5,
tabsetPanel(type="pills",
tabPanel("Hjem",
includeHTML("testpage.html")
),
tabPanel("Last opp kursfil",
br(),
br(),
h4("Oversikt over kursfila"),
p(""),
br(),
tableOutput('contents')),
tabPanel("Histogram",
br(),
br(),
h4("Ovsersikt over linjeavstander"),
br(),
plotOutput("distPlot")),
tabPanel("Summarisk oversikt",
br(),
br(),
h4("Summarisk oversikt over datasettet"),
br(),
br(),
tableOutput("Deskr")),
tabPanel("Distance Sampling",
br(),
br(),
h4("Distance sampling-analyser"),
br(),
br(),
tableOutput("Distance"),
br(),
br(),
plotOutput("Distance3", width="600px"))
)
)
),
hr(),
h5("Koden til denne appen kan lastes ned på", tags$a(href="https://github.com/ErlendNilsen/DS_kursapp", "GitHub")),
h5("Har du spørsmål knyttet til denne applikasjonen finner du kontaktinformasjon", tags$a(href="http://honsefugl.nina.no/Innsyn/Home/Kurs", "her"))
)
)<file_sep>---
title: "Velkommen til Hønsefuglportalens analyseportal for takseringskurs"
author: ""
date: ""
output: html_document
---
Disse sidene er primært ment å være en hjelp i forbindelse med kurs i linjetaksering av hønsefugl basert på *Distance Sampling*. En nærmere beskrivelse av takseringene finner dere på [Hønsefuglportalen](http://honsefugl.nina.no/Innsyn/), og en nærmere beskrivelse av kursinnholdet finner dere på [Hønsefuglportalens kurssider](http://honsefugl.nina.no/Innsyn/Home/Kurs).
Det er viktig å merke seg at funksjonene her er forenklet og tilpasset testdata som samles inn i forbindelse med gjennomføring av kurs. Før du tar disse sidene i bruk har du vanligvis gjennomført en kursøvelse hvor man går langs linjer og registrerer "fugl" langs disse. Hver gang man ser et objekt vil man notere hvor mange det er (flokkstørrelse) samt hvor langt fra takseringslinja observasjonen er gjort. Dette er også helt sentral informasjon når man gjennomfører ekte linjetaksering av hønsefugl basert *Distance-sampling* metoden.
**Klargjøring av kursfila**
Før du starter må du ha klargjort en testfil. I kurssammenheng vil dette vanligvis være resultatet av test-gjennomføringen av linjetaksering. Det er viktig at fila inneholder følgende kolonner, i nevnte rekkefølge:
- *Linjenavn:* Her skrver du navnet på linja.
- *Obsnr:* Forkortelse for observasjonsnummer. Begynn gjerne med 1, og nummerer deretter fortløpende.
- *Linjeavstand:* Her skriver du inn astanden fra linja til den aktuelle observasjonen.
- *Antall:* Her oppgir du hvor mange individer (flokkstørrelse) det var i den aktuelle observasjonen. I kurssammenheng vil dette vanligvis være 1.
- *Linjelengde:* Her oppgir du hvor lang takseringslinja er.
Det er viktig at du fører inn eventuelle linjer hvor det ikke ble gjort noen observasjoner. I disse fører du kun inn feltene *Linjenavn* og *Linjelengde*.
**Lagring av kursfila**
Når du har lagt inn data fra kurs-øvelsen i f.eks. excel er det viktig at du lagrer fila i .txt eller .csv-format. Dette gjør du ved å velge "lagre som" under fil-menyen i Excel. Velg et egnet navn på fila, og velg riktig lagringsformat.
|
855f1e04b86c5f667f508a2289d0328bcb27edea
|
[
"Markdown",
"R",
"RMarkdown"
] | 4
|
Markdown
|
ErlendNilsen/DS_kursapp
|
a892f8d47972335774b96a6b6f14e26a3cfd6f96
|
a239f62f777fc2ffe54d2189b86b2e8ba449345f
|
refs/heads/master
|
<file_sep>import pyautogui
import time
import os
import tkinter as tk
from tkinter import filedialog
class TexttoType:
def __init__(self):
self.AskForFile()
def AskForFile(self):
Window = tk.Tk()
Window.withdraw()
rawtxt= filedialog.askopenfilename(
initialdir='/home/user/Desktop',
title='Select Image',
filetypes=(("txt files","*.txt"),("all files","*.*")))
self.opentext = open(rawtxt, "r")
self.AskForDelay()
self.TalktoTypeLoop()
def AskForDelay(self):
self.WaitTime=input('How long in seconds between each line?\n')
time.sleep(5)
return
def TalktoTypeLoop(self):
while True:
try:
for self.line in self.opentext:
self.CheckFailSafe()
pyautogui.typewrite(self.line)
time.sleep(int(self.WaitTime))
except KeyboardInterrupt:
input('~~Paused~~\nPlease press enter to continue...')
continue
def CheckFailSafe(self):
x, y = pyautogui.position()
if x is 0:
if y is 0:
print('~~Paused~~\nWould you like to continue?\nThe next printed line is {}'.format(self.line))
Ask=input('1 to continue ~ 2 to stop\n')
if Ask is '1':
time.sleep(5)
return
elif Ask is '2':
print('Would you like to change the text file or Change the Delay?')
Change=input('1 to change file. ~ 2 to change delay time.\n')
if Change is '1':
self.AskForFile()
elif Change is '2':
self.AskForDelay()
else:
quit()
else:
quit()
pyautogui.FAILSAFE = False
TexttoType()
<file_sep># BasicTools-TextToType
Asks user for .txt file with a window then types it out line by line.
Each line is delayed by X seconds via user setting on startup.
|
c2b99a5f9418e24a27960ba6b2171b0dca4b8e11
|
[
"Markdown",
"Python"
] | 2
|
Python
|
vizmiz/BasicTools-TextToType
|
a27eb49b893e3fdab680b90ff46dfa5bbe204348
|
61a7b551dccae94624b3c14a7f96e2376edf1320
|
refs/heads/master
|
<repo_name>NicolasBonduel/Google-Music-Control<file_sep>/lib/main.js
var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var pref = require('sdk/simple-prefs');
var { Hotkey } = require("sdk/hotkeys");
function resetHotKey() {
if (typeof playHotKey != 'undefined') {
playHotKey.destroy();
}
if (typeof prevHotKey != 'undefined') {
prevHotKey.destroy();
}
if (typeof nextHotKey != 'undefined') {
nextHotKey.destroy();
}
playHotKey = Hotkey({
combo: pref.prefs['play'],
onPress: function() {
sendPause();
}
});
prevHotKey = Hotkey({
combo: pref.prefs['previous'],
onPress: function() {
sendPrev();
}
});
nextHotKey = Hotkey({
combo: pref.prefs['next'],
onPress: function() {
sendNext();
}
});
}
resetHotKey();
pref.on("", resetHotKey);
function getGMusicTab(tabs) {
if (tabs != null) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.indexOf("play.google.com") != -1) {
return tabs[i]
}
}
return null;
}
}
function sendPause() {
var tab = getGMusicTab(tabs);
if (tab != null) {
tab.attach({
contentScript: getPauseScript()
});
}
}
function sendNext() {
var tab = getGMusicTab(tabs);
if (tab != null) {
tab.attach({
contentScript: getNextScript()
});
}
}
function sendPrev() {
var tab = getGMusicTab(tabs);
if (tab != null) {
tab.attach({
contentScript: getPrevScript()
});
}
}
function getPauseScript() {
var script = function () {
var buttons = document.getElementsByTagName('paper-icon-button');
for (var i = 0; i < buttons.length; i++) {
if(buttons[i].getAttribute("data-id") == "play-pause") {
buttons[i].click();
break;
}
}
}
return script.toSource() + "()";
}
function getPrevScript() {
var script = function () {
var buttons = document.getElementsByTagName('paper-icon-button');
for (var i = 0; i < buttons.length; i++) {
if(buttons[i].getAttribute("data-id") == "rewind") {
buttons[i].click();
break;
}
}
}
return script.toSource() + "()";
}
function getNextScript() {
var script = function () {
var buttons = document.getElementsByTagName('paper-icon-button');
for (var i = 0; i < buttons.length; i++) {
if(buttons[i].getAttribute("data-id") == "forward") {
buttons[i].click();
break;
}
}
}
return script.toSource() + "()";
}
<file_sep>/README.md
# Deprecated in favor of [google-music-hotkeys](https://github.com/lidel/google-music-hotkeys)
# Google-Music-Control
Control Google Music with Shortcuts!
With this add-on you can easily change (next/previous) or pause your music from Google Music from any tab!
You can also edit the shortcuts you want to use ;)
See more here :
https://addons.mozilla.org/fr/firefox/addon/google-music-control/
--------------------------------------------------
Changelog 0.2.3
-> Now support the new Google Music's material design.
Changelog 0.2.4
-> Updated after a Google Music's code change.
-> Switched from CFX to JPM.
|
e5e0e60d878884e0ee82c331ede8d9a86b7a76a3
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
NicolasBonduel/Google-Music-Control
|
733e246f7194209b0199ef868c9411a0612f65f2
|
1bd46a0776c323d65cd93a0f1010f85f52f2e2f0
|
refs/heads/master
|
<file_sep>import java.util.Scanner;
class TestaTamagochi{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Tamagochi t = new Tamagochi();
System.out.println("Defina os niveis de energia, fome e limpeza!");
t.energia = scan.nextInt();
t.fome = scan.nextInt();
t.limpeza = scan.nextInt();
t.energiaInicial = t.energia;
t.limpezaInicial = t.limpeza;
t.fomeInicial = t.fome;
t.energia(t.energia);
t.fome(t.fome);
t.limpeza(t.limpeza);
t.mostrar();
do{
System.out.println();
System.out.println("Comandos | brincar / comer / tomar banho / dormir / fim |:");
t.comando = scan.nextLine();
t.comandos(t.comando);
t.mostrar();
}while(!t.comando.equals("fim"));
}
}<file_sep> class Tamagochi {
int fome,limpeza,energia;
int diamantes = 0;
int idade = 0;
int energiaInicial,limpezaInicial,fomeInicial;
String comando;
void fome(int fome) {
this.fome = fome;
this.fomeInicial = this.fome;
}
void limpeza(int limpeza) {
this.limpeza = limpeza;
this.limpezaInicial = this.limpeza;
}
void energia(int energia) {
this.energia = energia;
this.energiaInicial = this.energia;
}
boolean comandos(String comando){
if(!comando.equals("brincar") && !comando.equals("dormir") && !comando.equals("mostrar") &&
!comando.equals("comer") && !comando.equals("tomar banho") && !comando.equals("fim")){
return false;
}
if(comando.equals("brincar")){
if(this.energia <= 0){
this.energia = 0;
System.out.println("Falhou: O bixinho morreu!");
}else if(this.limpeza <= 0){
limpeza = 0;
System.out.println("Falhou: O bixinho morreu de sujeira!");
}else if(this.fome <= 0){
this.fome = 0;
System.out.println("Falhou: O bixinho morreu de fome!");
}else{
this.energia -= 2;
this.fome -= 1;
this.limpeza -= 3;
this.diamantes++;
this.idade++;
}
}
if(comando.equals("comer")){
if(this.energia <= 0){
this.energia = 0;
System.out.println("Falhou: O bixinho morreu!");
}else if(this.limpeza <= 0){
limpeza = 0;
System.out.println("Falhou: O bixinho morreu de sujeira!");
}else if(this.fome <= 0){
this.fome = 0;
System.out.println("Falhou: O bixinho morreu de fome!");
}else{
this.energia -= 1;
this.energia -= 2;
this.fome += 4;
this.idade++;
if(this.fome > fomeInicial){
this.fome = fomeInicial;
}
}
}
if(comando.equals("dormir")){
if(this.energia <= 0){
this.energia = 0;
System.out.println("Falhou: O bixinho morreu!");
}else if(this.limpeza <= 0){
this.limpeza = 0;
System.out.println("Falhou: O bixinho morreu de sujeira!");
}else if(fome <= 0){
this.fome = 0;
System.out.println("Falhou: O bixinho morreu de fome!");
}else if(this.energiaInicial-this.energia < 5){
System.out.println("Falhou: O bichinho nao esta cansado!");
}else{
this.fome -= 1;
this.idade += (this.energiaInicial - energia);
this.energia = this.energiaInicial;
}
}
if(comando.equals("tomar banho")){
if(this.energia <= 0){
this.energia = 0;
System.out.println("Falhou: O bixinho morreu!");
}else if(this.limpeza <= 0){
this.limpeza = 0;
System.out.println("Falhou: O bixinho morreu de sujeira!");
}else if(this.fome <= 0){
this.fome = 0;
System.out.println("Falhou: O bixinho morreu de fome!");
}else{
this.fome -= 1;
this.energia -= 3;
this.idade += 2;
this.limpeza = limpezaInicial;
}
}
if(comando.equals("mostrar")){
mostrar();
}
return true;
}
void mostrar(){
System.out.println("E:" + this.energia + "/" + this.energiaInicial + ", F:" + this.fome + "/" + this.fomeInicial + ", L:" + this.limpeza + "/" + this.limpezaInicial + ", D:" + this.diamantes + ", I:" + this.idade);
}
}
|
e76ef8f068a8ce75565d88f538d028df84db7aaa
|
[
"Java"
] | 2
|
Java
|
Naelia/POO-Lista-de-Ferias
|
cf9e4ed2cd391ba106f3ed459f1bc0dad307eeef
|
b2fd4a3318532abac36f63b81caddcd2cdbc15a3
|
refs/heads/master
|
<file_sep>//post나 user를 감싸줄 root reducer
import {combineReducers} from 'redux';
import image from './image'
import menu from './menu'
import timetable from './timetable'
const rootReducer=combineReducers({
image,
menu,
timetable
})
export default rootReducer;<file_sep>const express=require('express');
const next =require('next');
const morgan=require('morgan');
const path=require('path');
const dev=process.env.NODE_ENV!=='production'
const prod = process.env.NODE_ENV === 'production'
const app=next({dev});
const handle=app.getRequestHandler();
app.prepare().then(()=>{
const server=express();
server.use(morgan('dev'));
server.use('/',express.static(path.join(__dirname,'public')));
server.use(express.json());
server.use(express.urlencoded({extended:true}));
server.get('*',(req,res)=>{
return handle(req,res);
})
server.listen(3000,()=>{
console.log('next+nodemon');
})
})
<file_sep>const express = require('express');
const db = require('../models');
const router = express.Router();
router.post('/',async(req,res,next)=>{//일정등록하기
try {
console.log(req.body);
const result=await db.Timetable.create({
scheduleDate:req.body.scheduleDate,
time:req.body.time,
schedule:req.body.schedule
})
if(result)
res.status(200).send("일정 등록 성공");
} catch (e) {
res.send(e)
}
})
router.delete('/:id',async(req,res,next)=>{
try{
const result=await db.Timetable.destroy({
where:{id:req.params.id}
});
if(result) res.send("삭제 성공!");
}catch(e){
res.send(e);
}
})
router.get('/date', async (req, res, next) => {
try {
const dateSchedule = await db.Timetable.aggregate( //타임테이블 일 보여주기
'scheduleDate',
'DISTINCT',
{plain:false}
)
res.json(dateSchedule);
} catch (e) {
res.send(e);
}
})
router.get('/',async (req,res,next)=>{
try {
const dateSchedule=await db.Timetable.findAll({//타임테이블 모두보여주기
where:{}
})
res.json(dateSchedule);
} catch (e) {
res.send(e);
}
})
module.exports = router;<file_sep>import {produce} from 'immer'
export const SCHEDULEGET_REQUEST='FRONT/SCHEDULTGET_REQUEST'
export const SCHEDULEGET_SUCCESS='FRONT/SCHEDULTGET_SUCCESS'
export const SCHEDULEGET_FAILURE='FRONT/SCHEDULTGET_FAILURE'
export const SCHEDULEPOST_REQUEST='FRONT/SCHEDULEPOST_REQUEST'
export const SCHEDULEPOST_SUCCESS='FRONT/SCHEDULEPOST_SUCCESS'
export const SCHEDULEPOST_FAILURE='FRONT/SCHEDULEPOST_FAILURE'
export const SCHEDULEDELETE_REQUEST='FRONT/SCHEDULEDELETE_REQUEST'
export const SCHEDULEDELETE_SUCCESS='FRONT/SCHEDULEDELETE_SUCCESS'
export const SCHEDULEDELETE_FAILURE='FRONT/SCHEDULEDELETE_FAILURE'
export const DATEGET_REQUEST = 'FRONT/DATEGET_REQUEST'
export const DATEGET_SUCCESS = 'FRONT/DATEGET_SUCCESS'
export const DATEGET_FAILURE = 'FRONT/DATEGET_FAILURE'
export const initialState={
scheduleRequest:false,
scheduleInfo:{},
scheduleError:{},
dateRequest:false,
dateInfo:{},
dateError:'',
schedulePostRequest:false,
schedulePostMessege:'',
schedulePostError:'',
scheduleDeleteRequest:false,
scheduleDeleteMessege:'',
scheduleDeleteError:''
}
export default (state=initialState,action)=>{
return produce(state,draft=>{
switch(action.type){
case SCHEDULEGET_REQUEST:{
draft.scheduleRequest=true;
draft.scheduleError='';
draft.scheduleInfo='';
break;
}
case SCHEDULEGET_SUCCESS:{
draft.scheduleRequest=false;
draft.scheduleInfo=action.data;
break;
}
case SCHEDULEGET_FAILURE:{
draft.scheduleRequest=false;
draft.scheduleError=action.error
break;
}
case SCHEDULEPOST_REQUEST:{
draft.schedulePostRequest=true;
draft.schedulePostError='';
draft.schedulePostMessege='';
break;
}
case SCHEDULEPOST_SUCCESS:{
draft.schedulePostRequest=false;
draft.schedulePostMessege=action.data;
break;
}
case SCHEDULEPOST_FAILURE:{
draft.schedulePostRequest=false;
draft.schedulePostError = action.error
break;
}
case SCHEDULEDELETE_REQUEST:{
draft.scheduleDeleteRequest=true;
draft.scheduleDeleteError='';
draft.scheduleDeleteMessege='';
break;
}
case SCHEDULEDELETE_SUCCESS:{
draft.scheduleDeleteRequest=false;
draft.scheduleDeleteMessege=action.data;
break;
}
case SCHEDULEDELETE_FAILURE:{
draft.scheduleDeleteRequest=false;
draft.scheduleDeleteError = action.error
break;
}
case DATEGET_REQUEST:{
draft.dateRequest=true;
draft.dateError='';
draft.dateInfo='';
break;
}
case DATEGET_SUCCESS:{
draft.dateRequest=false;
draft.dateInfo=action.data;
}
case DATEGET_FAILURE:{
draft.dateRequest=false;
draft.dateError=action.error
break;
}
default:{
return state
}
}
})
}<file_sep>import { all, fork } from 'redux-saga/effects';
import axios from 'axios';
import image from './image'
import menu from './menu'
import timetable from './timetable'
axios.defaults.baseURL = 'http://192.168.0.2:5000/api';
export default function* rootSaga() {
yield all([
fork(image),
fork(menu),
fork(timetable)
]);
}<file_sep>import styled from 'styled-components';
export const Nav = styled.nav `
display:flex;
justify-content:space-around;
border-bottom:1px solid gray;
margin-top:3rem;
padding-bottom:1.38rem
`
export const ScheduleDiv = styled.div `
padding:1rem;
border-bottom:1px solid #979797;
font-size:16px;
`
export const Strong=styled.strong`
color:${props=>props.color}
`
<file_sep>import React, { useCallback, useState,useRef, Children, useEffect } from 'react'
import Link from 'next/link'
import { useDispatch, useSelector } from 'react-redux'
import { SCHEDULEGET_REQUEST,DATEGET_REQUEST } from '../store/timetable'
import {Nav,ScheduleDiv,Strong} from '../styles/TimetableStyles'
const TimeTable=({children})=>{
const [date,setDate]=useState(null)
const [schedule,setSchedule]=useState([])
const {scheduleInfo,dateInfo}=useSelector(state=>state.timetable)
const dispatch=useDispatch();
const filterSchedule=useCallback((e)=>{
setDate(date.map((item,index)=>{
return item.day===e.target.textContent?{day:item.day,color:"#003e94"}:{day:item.day,color:"#9b9b9b"};
}))
setSchedule(scheduleInfo.filter((item,index)=>{
return item.scheduleDate===e.target.textContent
}))
},[schedule,scheduleInfo,date])
useEffect(()=>{
dateInfo&&setDate(dateInfo.map((item,index)=>{
return {day:item.DISTINCT,color:"#9b9b9b"};
}))
},[dateInfo])
return (
<>
<Nav>
{date&&date.map((item,index)=>{
return(
<Strong color={item.color} onClick={filterSchedule} key={index}>{item.day}</Strong>
)
})}
</Nav>
<main>
{schedule&&schedule.map((item,index)=>{
return(
<ScheduleDiv key={index}>
<span style={{margin:'1.5rem'}}><strong>{item.time}</strong></span>
<span style={{marginLeft:'5rem'}}>{item.schedule}</span>
</ScheduleDiv>
)
})}
</main>
</>
)
}
TimeTable.getInitialProps=async(context)=>{
context.store.dispatch({
type:DATEGET_REQUEST
})
context.store.dispatch({
type:SCHEDULEGET_REQUEST
})
}
export default TimeTable;<file_sep>module.exports = (sequelize, DataTypes) => {
const Timetable = sequelize.define('Timetable', {
scheduleDate:{
type:DataTypes.STRING,
allowNull:false
},
time:{
type:DataTypes.STRING
},
schedule: {
type: DataTypes.STRING
}
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
});
return Timetable;
};<file_sep>import {produce} from 'immer'
export const MENUPOST_REQUEST='FRONT/MENUPOST_REQUEST'
export const MENUPOST_SUCCESS = 'FRONT/MENUPOST_SUCCESS'
export const MENUPOST_FAILURE = 'FRONT/MENUPOST_FAILURE'
export const MENUGET_REQUEST = 'FRONT/MENUGET_REQUEST'
export const MENUGET_SUCCESS = 'FRONT/MENUGET_SUCCESS'
export const MENUGET_FAILURE = 'FRONT/MENUGET_FAILURE'
export const CODE_REQUEST = 'FRONT/CODE_REQUEST'
export const CODE_SUCCESS = 'FRONT/CODE_SUCCESS'
export const CODE_FAILURE = 'FRONT/CODE_FAILURE'
export const GETALLBOOTHINFO_REQUEST = 'FRONT/GETALLBOOTHINFO_REQUEST'
export const GETALLBOOTHINFO_SUCCESS = 'FRONT/GETALLBOOTHINFO_SUCCESS'
export const GETALLBOOTHINFO_FAILURE = 'FRONT/GETALLBOOTHINFO_FAILURE'
export const CODECREATE_REQUEST='FRONT/CODECREATE_REQUEST'
export const CODECREATE_SUCCESS='FRONT/CODECREATE_SUCCESS'
export const CODECREATE_FAILURE='FRONT/CODECREATE_FAILURE'
export const POSTSUCCESS='FRONT/POSTSUCCESS'
export const RESET='FRONT/RESET'
export const initialState={
menuPostRequest:false,
menuGetRequest:false,
menuInfo:null,//메뉴등록정보
menuPostError:{},
menuGetError:{},
codeRequest:false,
codeInfo:null, //코드조회정보
codeError:{},
boothRequst:false,
boothError:'',
allBoothInfo:null,
postSuccess:null,
codePostRequest:false,
codeMessege:'',
codePostError:''
}
export default (state=initialState,action)=>{
return produce(state,draft=>{
switch(action.type){
case MENUPOST_REQUEST:{
draft.menuPostRequest=true;
draft.menuPostError=''
break;
}
case MENUPOST_SUCCESS:{
draft.menuPostRequest=false;
draft.codeRequest=false;
draft.postSuccess=action.data
break;
}
case MENUPOST_FAILURE:{
draft.menuPostRequest=false;
draft.codeRequest=false;
draft.menuPostError=action.error
break;
}
case MENUGET_REQUEST:{
draft.menuGetRequest=true;
draft.menuGetError=''
draft.menuInfo=''
break;
}
case MENUGET_SUCCESS:{
draft.menuGetRequest=false;
draft.menuInfo=action.data;
break;
}
case MENUGET_FAILURE:{
draft.menuGetRequest=false;
draft.menuGetError=action.error
break;
}
case CODE_REQUEST:{
draft.codeRequest=true;
draft.codeError='';
draft.codeInfo=null
break;
}
case CODE_SUCCESS:{
draft.codeRequest=false;
draft.codeInfo=action.data;
break;
}
case CODE_FAILURE:{
draft.codeRequest=false;
draft.codeError=action.error
break;
}
case CODECREATE_REQUEST:{
draft.codeRequest=true;
draft.codeMessege='';
draft.codeError='';
break;
}
case CODECREATE_SUCCESS:{
draft.codePostRequest=false;
draft.codeMessege=action.data
break;
}
case CODECREATE_FAILURE:{
draft.codePostRequest=false;
draft.codePostError=action.error
break;
}
case GETALLBOOTHINFO_REQUEST:{
draft.boothRequest=true;
draft.boothError='';
break;
}
case GETALLBOOTHINFO_SUCCESS:{
draft.boothRequest=false;
draft.allBoothInfo=action.data;
break;
}
case GETALLBOOTHINFO_FAILURE:{
draft.bootheRequest=false;
draft.boothError=action.error
break;
}
case POSTSUCCESS:{
draft.postSuccess=action.data
draft.codeInfo=null
break;
}
case RESET:{
draft.codeInfo=null
draft.codeRequest=false
draft.postSuccess=false
break;
}
default:{
return state;
}
}
})
}<file_sep>import React,{ useState, useRef, useCallback } from 'react';
import styled from 'styled-components'
import Link from 'next/link'
import {useRouter} from 'next/router'
import {INDEXIMAGE_REQUEST} from '../store/image'
import {AppDiv,Drawer,Header,DrawerBack} from '../styles/AppLayoutStyle'
const AppLayout=({children})=>{
const Menu=['부스지도','야간 셔틀버스','타임테이블'];
const route=['boothmap','shuttle','timetable'];
const [title,setTitle]=useState('INU대동제');
const router=useRouter();
const [toggle,setToggle]=useState(false);//redux,contextAPI사용
const getToggle=useCallback(bool=>()=>{
return new Promise((resolve,reject)=>{
setToggle(bool);
resolve(toggle);
})
},[toggle])
// const header=useRef();
// const drawer=useCallback(()=>{
// if(!toggle){
// header.current.style.backgroundColor='rgba(35, 35, 35, 0.7)'
// header.current.style.opacity=0.7
// }else{
// header.current.style.backgroundColor = '#fff'
// header.current.style.opacity = 1
// }},[toggle])
return(
<AppDiv>
<Header >
{/* header */}
<span><img onClick={()=>{
setTitle('INU대동제');
router.push('/')}} style={{width:24,height:21,}} src='/path.png'></img></span>
<span style={{marginLeft:20,marginRight:20,}}><strong>{title}</strong></span>
<span><img onClick={ getToggle(true)} style={{width:24,height:21}} src='/more.png'></img></span>
</Header>
{/* drawer부분.. &&사용하기*/}
{toggle&&
<div onWheel={getToggle(false)} >
<DrawerBack onTouchMove={getToggle(false)} onClick={getToggle(false)} />
<Drawer>
<img style={{marginLeft:'82%',marginTop:15}} onClick={getToggle(false)} src='/xbtn.png'></img>
<div style={{marginTop:90,marginLeft:50}}>
{Menu.map((item,index)=>{
return <Link key={index} href={{pathname:`/${route[index]}`}} as={`/${route[index]}`}><a onClick={()=>{
setToggle(false)
setTitle(Menu[index]);
// drawer();
}}><p key={index} style={{borderBottom:'solid 1px #d3d3d3',width:132,paddingBottom:23.2}}>{item}</p></a></Link>
})}
</div>
<div style={{marginLeft:'17%',marginTop:'16rem'}}>
<Link href={{pathname:'/manager'}}><a onClick={()=>{
setTitle('운영자 페이지');
setToggle(false)
// drawer();
}}><strong>운영자페이지</strong></a></Link>
</div>
</Drawer>
</div>
}
<section>
{children}
</section>
</AppDiv>
)
}
export default AppLayout;<file_sep>import React,{useEffect} from 'react'
import {useDispatch,useSelector} from 'react-redux'
import { INDEXIMAGE_REQUEST } from '../store/image';
import {Img} from '../styles/AppLayoutStyle'
//toggle을 redux에 넣어주고 나면 opacaty를 0.7정도로주자
const startPage=()=>{
const {indexImage}=useSelector(state=>state.image);
console.log(indexImage);
return(
<>
<Img src={`http://192.168.43.157:5000/${indexImage.lineUp}`}></Img>
</>
)
}
startPage.getInitialProps=async(context)=>{
context.store.dispatch({
type:INDEXIMAGE_REQUEST
})
}
export default startPage;<file_sep>module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
userId:{
type:DataTypes.STRING,
allowNull:false,
primaryKey:true
},
password:{
type:DataTypes.STRING,
allowNull:false
}
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
});
return User;
};<file_sep>module.exports = (sequelize, DataTypes) => {
const Admin = sequelize.define('Admin', {
code:{
type:DataTypes.INTEGER,
allowNull:false,
primaryKey:true
},
boothName:{
type:DataTypes.STRING,
},
opTimeOpen:{
type:DataTypes.STRING
},
opTimeClose:{
type:DataTypes.STRING
},
full:{
type:DataTypes.BOOLEAN,
}
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
});
Admin.associate = (db) => {
db.Admin.hasMany(db.Menu);
};
return Admin;
};<file_sep>import React, { useState, useRef, useCallback, useEffect, Fragment } from 'react'
import styled from 'styled-components'
import {useSelector, useDispatch} from 'react-redux'
import {useRouter} from 'next/router'
import {MENUPOST_REQUEST, POSTSUCCESS} from '../../store/menu';
const BoothNameDiv=styled.div`
margin-top:2rem;
margin-bottom:2.7rem;
&>img{
margin-left:1.8rem;
width:12px;
height:12px;
}
&>div{
text-align-last:center;
margin-top:0.9rem;
&>input{
text-align:center;
width: 300px;
height: 36px;
border-radius: 7px;
background-color: #f0f0f0;
}
}
`
const Openingtime=styled.div`
&>img{
margin-left:1.8rem;
width:12px;
height:12px;
}
&>div{
text-align:center;
margin-top:0.9rem;
&>input{
text-align:center;
width:131px;
height:36px;
border-radius:7px;
background-color: #f0f0f0;
}
}
`
const FullDiv=styled.div`
margin-top:2.7rem;
margin-bottom:2.7rem;
&>img{
margin-left:1.8rem;
width:12px;
height:12px;
}
&>div{
text-align:center;
margin-top:0.9rem;
}
`
const FullBtn=styled.button`
margin-right:2.3rem;
text-align:center;
width:131px;
height:36px;
border-radius:7px;
background-color:#fff;
border:${props=>props.borderColor};
color:${props=>props.buttonColor};
`
const EmptyBtn=styled.button`
color:${props=>props.buttonColor};
border:${props=>props.borderColor};
text-align:center;
width:131px;
height:36px;
border-radius:7px;
background-color:#fff;
`
const MenuPost=styled.div`
&>img{
margin-left:1.7rem;
width:12px;
height:12px;
}
&>div{
margin-top:10px;
display:flex;
justify-content:center;
}
`
const Table=styled.table`
width:18.75rem;
border-radius:7px;
background-color:#f0f0f0;
text-align:center;
`
export const useInput = (initValue = null) => {
const [value, setter] = useState(initValue);
const handler = useCallback((e) => {
setter(e.target.value);
}, []);
return [value, handler];
};
const manager2=(props)=>{
const [rows,setRows]=useState([1,2,3,4,5]);
const [cols,setCols]=useState([0,1,2]);
const [fullBtn,setFullBtn]=useState(false);
const [emptyBtn,setEmptyBtn]=useState(true);
const [Menu, setMenu] = useState([{ food: '', price: '', soldOut: false },
{ food: '', price: '', soldOut: false },
{ food: '', price: '', soldOut: false },{ food: '', price: '', soldOut: false },
{ food: '', price: '', soldOut: false },{ food: '', price: '', soldOut: false },
{ food: '', price: '', soldOut: false },{ food: '', price: '', soldOut: false },
{ food: '', price: '', soldOut: false },{ food: '', price: '', soldOut: false }])
const [toggle,setToggle]=useState(false);
const [boothname,setBoothname]=useInput(null);
const [opTimeOpen,setopTimeOpen]=useInput(null);
const [opTimeClose,setopTimeClose]=useInput(null);
console.log(fullBtn,emptyBtn)
const router=useRouter();
const dispatch=useDispatch();
const {postSuccess,codeRequest,menuPostRequest,codeInfo}=useSelector(state=>state.menu);
const changeButton=useCallback((e)=>{
e.preventDefault();
if(e.target.textContent==='만석'){
setFullBtn(true);
setEmptyBtn(false);
}
else{
setEmptyBtn(true);
setFullBtn(false);
}
},[emptyBtn,fullBtn])
const onSubmitForm=useCallback(()=>{
const MenuList=Menu.map((item,index)=>{
if(item.food&&item.price) return item;
})
dispatch({
type:MENUPOST_REQUEST,
data:{
code:codeInfo.code,
boothName:boothname?boothname:codeInfo.boothName,
opTimeOpen:opTimeOpen?opTimeOpen:codeInfo.opTimeOpen,
opTimeClose:opTimeClose?opTimeClose:codeInfo.opTimeClose,
full:fullBtn,
menu:MenuList
}
})
alert("등록성공");
router.push('/manager');
return;
},[boothname,opTimeOpen,opTimeClose,Menu,codeInfo,fullBtn])
const addTable=useCallback((e)=>{
e.preventDefault();
setRows([...rows,1]);
console.log(rows.length);
},[rows])
useEffect(()=>{
if(!codeInfo){
router.push('/manager');
alert('잘못 된 접근입니다.');
return;
}
if(codeInfo.full){
setFullBtn(true);
setEmptyBtn(false);
}
codeInfo.Menus&&setMenu(Menu.map((item,index)=>{
return codeInfo.Menus[index]?Object.assign(item,codeInfo.Menus[index]):item;
}))
},[])
return(
<>
<form onSubmit={onSubmitForm}>
<BoothNameDiv>
<img src="/oval1.PNG" ></img>
<label>부스이름</label>
<div>
<input onChange={setBoothname} defaultValue={codeInfo?(codeInfo.boothName?codeInfo.boothName:''):''} name="boothName" type='text' placeholder='부스 이름을 적어주세요 (최대 15자)' >
</input>
</div>
</BoothNameDiv>
<Openingtime>
<img src="/oval1.PNG"></img>
<label>운영시간</label>
<div>
<input onChange={setopTimeOpen} defaultValue={codeInfo?(codeInfo.opTimeOpen?codeInfo.opTimeOpen:''):''} name="opTimeOpen" type='text' placeholder='00 : 00'>
</input>
<label> ~ </label>
<input onChange={setopTimeClose} defaultValue={codeInfo?(codeInfo.opTimeClose?codeInfo.opTimeClose:''):''} name="opTimeClose" type='text' placeholder='00 : 00' >
</input>
</div>
</Openingtime>
<FullDiv>
<img src="/oval1.PNG"></img>
<label>만석여부</label>
<div>
<FullBtn type='button' title='만석' onClick={changeButton} borderColor={fullBtn?'1px solid #f00':'1px solid gray'} buttonColor={fullBtn?'#f00':'gray'}>
만석
</FullBtn>
<EmptyBtn type='button' onClick={changeButton} borderColor={emptyBtn?'1px solid #64a5ff':'1px solid gray'} buttonColor={emptyBtn?"#64a5ff":'gray'}>
자리있음
</EmptyBtn>
</div>
</FullDiv>
<MenuPost>
<img src="/oval1.PNG"></img>
<label>메뉴판</label>
<div>
<Table>
<thead>
<tr>
<th style={{borderBottom:'1px solid white',width:'50%'}}>음식</th>
<th style={{borderLeft:'1px solid white',borderRight:'1px solid white',borderBottom:'1px solid white',
width:'31%'}}>가격</th>
<th style={{borderBottom:'1px solid white',width:'19%'}} >품질</th>
</tr>
</thead>
<tbody>
{rows.fill(rows.length).map((item,index)=>{
return(
<tr style={{height:36}} key={index}>
{cols.fill(cols.length).map((ele,i)=>{
return(
<Fragment>
<td suppressContentEditableWarning={true} contentEditable={true} onKeyUp={
(e)=>{
i===0?setMenu(
Menu.map((v,ind)=>{return ind===index?Object.assign(v,{food:e.target.textContent}) :v})
)
:
setMenu(
Menu.map((v,ind)=>{return ind===index?Object.assign(v,{price:e.target.textContent}) :v})
)
}
} style={{border:'1px solid white'}}>
{
i===0&&codeInfo&&<>{codeInfo.Menus.map((ele,j)=>{
return j===index?<>{ele.food}</>:<></>
})}</>
}
{
i===1&&codeInfo&&<>{codeInfo.Menus.map((ele,j)=>{
return j===index?<>{ele.price}</>:<></>
})}</>
}
{
i===2&&(Menu[index].soldOut
?<img onClick={()=>{
setMenu(
Menu.map((v,ind)=>{return ind===index?Object.assign(v,{soldOut:false}) :v})
)
}} src='/unreveal.png'/>
:<img onClick={()=>{
setMenu(
Menu.map((v,ind)=>{return ind===index?Object.assign(v,{soldOut:true}) :v})
)
}
} src='/reveal.png'/>
)}
</td>
</Fragment>
)
})}
</tr>
)
})
}
</tbody>
</Table>
</div>
</MenuPost>
<div style={{textAlign:'center'}}>
{rows.length<10&&<label style={{color:'#223ca3',fontSize:13}} onClick={addTable}>+추가하기</label>}
</div>
<footer style={{textAlign:'center'}}>
<img onClick={onSubmitForm} src='/group.png'/>
</footer>
</form>
</>
)
}
manager2.getInitialProps=async(ctx)=>{
return ctx.store.getState.codeInfo
}
export default manager2;<file_sep>const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const dotenv = require('dotenv');
const db = require('./models');
const app=express();
const prod = process.env.NODE_ENV === 'production';
// dotenv.config();
db.sequelize.sync();
app.use(cors());
app.use(morgan('dev'));
app.use('/',express.static('uploads'));
app.use(express.json())
app.use(express.urlencoded({
extended: true
}));
const adminAPI = require('./router/admin');
const timetableAPI = require('./router/timetable');
const imageAPI = require('./router/image');
app.use('/api/admin', adminAPI);
app.use('/api/timetable', timetableAPI);
app.use('/api/image', imageAPI);
// app.use('/api/hashtag', hashtagAPIRouter);
app.get('/', (req, res) => {
res.send('react nodebird 백엔드 정상 동작!');
});
// API는 다른 서비스가 내 서비스의 기능을 실행할 수 있게 열어둔 창구
app.listen(5000,()=>{
console.log("백엔드 정상작동")
})<file_sep>import styled from 'styled-components';
export const OriginMarker = styled.img `
position:absolute;
left:${props=>props.left};
top:${props=>props.top};
`
export const ClickMarker = styled.img `
position:absolute;
left:${props=>props.left};
top:${props=>props.top};
`
export const OverLay = styled.div `
z-index:500;
background-color:rgba(35,35,35,0.7);
display:flex;
justify-content:center;
position:absolute;
width:100%;
height:100%;
top:0;
left:0;
right:0;
bottom:0;
overflow:hidden;
`
export const Modal = styled.div `
z-index:501;
position:absolute;
background:white;
border-radius:22px;
width:18rem;
height:24rem;
text-align:center;
margin-top:6.6rem;
`
export const BoothInfo = styled.div `
margin-top:24px;
`
export const MenuInfo = styled.div `
margin-top:40px;
display:inline-block;
padding-bottom:8px;
width:16.5rem;
border-bottom:1px solid rgba(35,35,35,0.7);
overflow-y:auto
`
export const MenuInfoDetail = styled.div `
clear:both;
display:inline-block;
padding:7px;
width:15.6rem;
border-bottom:1px solid rgba(35,35,35,0.7);
`<file_sep>import React, { useEffect, useState, useCallback, useRef, Fragment} from "react";
import styled from 'styled-components'
import {useDispatch,useSelector} from 'react-redux'
import * as position from '../components/position'
import {GETALLBOOTHINFO_REQUEST} from '../store/menu'
import {OriginMarker,ClickMarker,OverLay,Modal,BoothInfo,MenuInfo,MenuInfoDetail}from '../styles/BoothmapStyles'
const Boothmap=()=>{
const [detail,setDetail]=useState(false)//부스 상세정보 보기
const [clear,setClear]=useState(false);//마커클릭시 클릭한 마커외에는 모두 사라짐
const [markerPosition,setMarkerPosition]=useState([
{code:1,left:position.CONS8_7_6_5_RIGHT,top:position.TOP2},
{code:2,left:position.CONS8_7_6_5_RIGHT,top:position.TOP3}
]);
//position.js참조 code와 position 위치를 넣는다.
const [toggle,setToggle]=useState(Array(markerPosition.length).fill(false));//true인것만 보여준다.
const [boothInfo,setBoothInfo]=useState();//클릭한 부스의 정보를 보여준다
const backgroundImage=useRef();//백그라운드 이미지 클릭시에 스타일을 건드려야한다
const {allBoothInfo}=useSelector(state=>state.menu)//모든 부스정보를 가져오는곳
const markerClick=useCallback((element,i)=>()=>{//마커클릭시 일어나는 메소드
setToggle(toggle.map((item,index)=>{
return index===i?true:item
}))
setClear(true);
backgroundImage.current.style.height='27rem'//-6rem을 해준값으로한다
setBoothInfo(allBoothInfo.filter((item,index)=>{
return item.code===element.code}));
setMarkerPosition(markerPosition.map((item,index)=>{
return Object.assign(item,{left:`${item.left.slice(0,2)-2}%`,top:`${item.top.slice(0,item.top.length-3)-3.75}rem`});
}))//마커클릭시 스타일 변환 left는 -2만큼 top은 -3.75만큼해준다
},[toggle,allBoothInfo,boothInfo,markerPosition])
const markerUnClick=useCallback(()=>{//마커 해제시 필요한부분
setToggle(
Array(markerPosition.length).fill(false)
);//모두 false로 돌린다
setClear(false);//파란색마커가 전부 다시 나오게한다
setMarkerPosition(markerPosition.map((item,index)=>{
return Object.assign(item,{left:`${Number(item.left.slice(0,2))+2}%`,top:`${Number(item.top.slice(0,item.top.length-3))+3.75}rem`});
}))//마커포지션 원상복귀
backgroundImage.current.style.height='33rem'
setBoothInfo(null);
},[toggle,boothInfo,markerPosition])
const more=useCallback(()=>{
setDetail(true);
},[detail])
const closeBtn=useCallback(()=>{
setDetail(false);
},[detail])
console.log(toggle)
return(
<>
<img src='/boothmap.jpg' ref={backgroundImage} style={{width:'100%',height:'33rem'}}/>
{toggle.map((element,i)=>{
return element?(
<Fragment>
{markerPosition.map((item,index)=>{
return i===index&&<ClickMarker key={index} left={item.left} top={item.top} src='/clickShape.png' onClick={markerUnClick}/>})}
{/* left는 -2 right는 -3.75해준다 i===index가없으면 element가 true이면 mp 모두 클릭상태로 출력됌 */}
<BoothInfo>
<div>
<span style={{fontSize:15,color:"#003e94",marginLeft:'2rem'}}><strong>{boothInfo[0].boothName}</strong></span>
<span style={{float:'right',fontSize:15,color:"#333",marginRight:'2rem'}}>{`${boothInfo[0].opTimeOpen}~${boothInfo[0].opTimeClose}`}</span>
</div>
{boothInfo[0].full&&<div><label style={{float:'right',fontSize:13,color:'#f00',marginTop:8,marginRight:'2rem'}}>만석</label></div>}
</BoothInfo>
{detail?
<OverLay>
<Modal>
<img style={{float:'right',margin:15}} src='/xbtn.png' onClick={closeBtn}/>
{
boothInfo[0].Menus&&
<>
<div style={{clear:'both',textAlign:'center'}}>
<div>
<strong style={{fontSize:15,color:"#003e94"}}>{boothInfo[0].boothName}</strong>
</div>
<div style={{margin:11}}><label>
{`${boothInfo[0].opTimeOpen}~${boothInfo[0].opTimeClose}`}
</label> </div>
<MenuInfo>
<strong>메뉴</strong>
</MenuInfo>
</div>
{boothInfo[0].Menus.map((item,index)=>{
return(
<>
<MenuInfoDetail key={index}>
{item.soldOut
?(
<>
<span style={{float:'left',padding:4,marginLeft:'1rem',color:'rgba(35,35,35,0.7)'}}>{item.food}</span>
<span style={{float:'right',padding:4,marginRight:'1rem',color:'#f00'}}>품절</span>
</>
)
:(
<>
<span style={{float:'left',padding:4,marginLeft:'1rem'}}>{item.food}</span>
<span style={{float:'right',padding:4,marginRight:'1rem'}}>{item.price}</span>
</>
)
}
</MenuInfoDetail>
</>
)
})}
</>
}
</Modal>
</OverLay>
:
<div style={{clear:'both',textAlign:'center',marginTop:'2rem'}}>
<img onClick={more} src="/moreMenu.png"/>
</div>
}
</Fragment>
)
:!clear&&markerPosition.map((item,index)=>{
return (
<OriginMarker key={index} left={item.left} top={item.top} src='/shape.png' onClick={markerClick(item,index)}/>)
}) })
}
</>
)
}
Boothmap.getInitialProps=async(context)=>{
context.store.dispatch({
type:GETALLBOOTHINFO_REQUEST
})
}
export default Boothmap;<file_sep>import React, { useState, Fragment, useCallback, useRef, useEffect } from 'react'
import {useDispatch,useSelector} from 'react-redux'
import { INDEXPOST_REQUEST ,SHUTTLEPOST_REQUEST} from '../store/image';
import {CODECREATE_REQUEST} from '../store/menu'
import {SCHEDULEGET_REQUEST,SCHEDULEPOST_REQUEST,SCHEDULEDELETE_REQUEST} from '../store/timetable'
const Admin=()=>{
const [index,setIndex]=useState();
const [shuttle,setShuttle]=useState();
const [code,setCode]=useState(0);
const {scheduleInfo}=useSelector(state=>state.timetable);
const [postSchedule,setPostSchedule]=useState();
const [updateSchedule,setUpdateSchedule]=useState();
const [userId,setUserId]=useState('');
const [password,setPassword]=useState('');
const dispatch=useDispatch();
const indexImgChange=useCallback((e)=>{
setIndex(e.target.files)
},[index])
const shuttleImgChange=useCallback((e)=>{
setShuttle(e.target.files)
},[shuttle])
const codeCreate=useCallback((e)=>{
setCode(e.target.value)
},[code]);
const onSubmitIndexImage=useCallback((e)=>{
e.preventDefault();
const imgFormData=new FormData();
console.log(index);
imgFormData.append('indexImage',index);
dispatch({
type:INDEXPOST_REQUEST,
data: imgFormData
})
},[index])
const onSubmitShuttleImage=useCallback((e)=>{
e.preventDefault();
const imgFormData = new FormData();
imgFormData.append('shuttleImage', shuttle);
dispatch({
type: SHUTTLEPOST_REQUEST,
data: imgFormData
})
}, [shuttle])
const onSubmitCode=useCallback((e)=>{
e.preventDefault();
dispatch({
type:CODECREATE_REQUEST,
data:Number(code)
})
})
const onChangeSchedule=useCallback((i)=>e=>{
e.preventDefault();
if(i===1) setPostSchedule({...postSchedule,scheduleDate:e.target.value});
else if(i===2) setPostSchedule({...postSchedule,time:e.target.value});
else setPostSchedule({...postSchedule,schedule:e.target.value});
},[postSchedule]);
const onSubmitSchedule=useCallback((e)=>{
e.preventDefault();
dispatch({
type:SCHEDULEPOST_REQUEST,
data:postSchedule
})
},[postSchedule])
const removeSchedule=useCallback(index=>e=>{
setUpdateSchedule(updateSchedule.filter((item,i)=>i!==index));
dispatch({
type:SCHEDULEDELETE_REQUEST,
data:Number(index+1)
})
}, [updateSchedule])
const onChangeUserId=useCallback((e)=>{
setUserId(e.target.value)
},[userId])
const onChangePwd=useCallback((e)=>{
setPassword(e.target.value)
},[password])
const onSubmitAdmin=useCallback(()=>{
dispatch({
type:SIGNUP_REQUEST,//만들기
data:{
userId,
password
}
})
},[userId,password])
useEffect(()=>{
setUpdateSchedule(scheduleInfo);
//user정보없을시에 다시 뒤로 되돌리기
},[scheduleInfo]);
return(
<>
<form encType="multipart/form-data" onSubmit={onSubmitIndexImage}>
<div>
<label>시작화면 사진등록하기</label>
<input type="file" onChange={indexImgChange} ></input>
<button htmlType="submit">등록하기</button>
</div>
</form>
<form encType="multipart/form-data" onSubmit={onSubmitShuttleImage}>
<div>
<label>셔틀버스 사진등록하기</label>
<input onChange={shuttleImgChange} type="file" ></input>
<button htmlType="submit">등록하기</button>
</div>
</form>
<form onSubmit={onSubmitCode}>
<div>
<label>코드생성하기(숫자만 입력)</label>
<input onChange={codeCreate} type="text"/>
<button htmlType="submit">생성하기</button>
</div>
</form>
<form onSubmit={onSubmitSchedule}>
<label>날짜 등록(28 월)</label><input type='text' onChange={onChangeSchedule(1)} />
<label>시간 등록(17:00)</label><input type='text' onChange={onChangeSchedule(2)}/>
<label>일정 등록</label><input type='text' onChange={onChangeSchedule(3)}/>
<button htmlType="submit">등록하기</button>
</form>
<form>
{updateSchedule&&updateSchedule.map((item,index)=>{
return(
<div>
<label>{item.scheduleDate}</label>
<label>{item.time}</label>
<label>{item.schedule}</label>
<button type="button" onClick={removeSchedule(index)}>삭제하기</button>
</div>
)
})}
</form>
<form onSubmit={onSubmitAdmin}>
<label>아이디입력</label>
<input type="text" onChange={onChangeUserId}/>
<label>비밀번호입력</label>
<input type="password" onChange={onChangePwd}/>
<button htmlType="submit">등록하기</button>
</form>
</>
)
}
Admin.getInitialProps=async(context)=>{
context.store.dispatch({
type:SCHEDULEGET_REQUEST
})
}
export default Admin;<file_sep>
import { fork,takeLatest,put,call,all} from 'redux-saga/effects'
import axios from 'axios'
import { SHUTTLEIMAGE_REQUEST, SHUTTLEIMAGE_SUCCESS, SHUTTLEIMAGE_FAILURE, INDEXIMAGE_REQUEST, INDEXIMAGE_SUCCESS, INDEXIMAGE_FAILURE,
SHUTTLEPOST_SUCCESS,SHUTTLEPOST_FAILURE,SHUTTLEPOST_REQUEST,INDEXPOST_FAILURE,INDEXPOST_REQUEST,INDEXPOST_SUCCESS
} from '../store/image'
function loadIndexAPI() {
return axios.get('/image',{});
}
function* loadIndex(action){
try{
const result=yield call(loadIndexAPI);
yield put({
type:INDEXIMAGE_SUCCESS,
data:result.data
//code정보를 보내줘야하나? code를 보내주면 한번에 정보를 보내줘야하지않을까?
})
}catch(e){
yield put({
type:INDEXIMAGE_FAILURE,
error:e
})
}
}
function* watchLoadIndex() {
yield takeLatest(INDEXIMAGE_REQUEST,loadIndex);
}
function postIndexAPI(indexImg) {
return axios.post('/image',indexImg);
}
function* postIndex(action){
try{
const result=yield call(postIndexAPI,action.data);
yield put({
type:INDEXPOST_SUCCESS,
data:result.data
//code정보를 보내줘야하나? code를 보내주면 한번에 정보를 보내줘야하지않을까?
})
}catch(e){
yield put({
type:INDEXPOST_FAILURE,
error:e
})
}
}
function* watchPostIndex() {
yield takeLatest(INDEXPOST_REQUEST,postIndex);
}
function loadShuttleAPI() {
return axios.get('/image/shuttle',{});
}
function* loadShuttle(action){
try{
const result=yield call(loadShuttleAPI,action.data);
yield put({
type:SHUTTLEIMAGE_SUCCESS,
data:result.data
//code정보를 보내줘야하나? code를 보내주면 한번에 정보를 보내줘야하지않을까?
})
}catch(e){
yield put({
type: SHUTTLEIMAGE_FAILURE,
error:e
})
}
}
function* watchLoadShuttle() {
yield takeLatest(SHUTTLEIMAGE_REQUEST,loadShuttle);
}
function postShuttleAPI(shuttleImg) {
return axios.post('/image/shuttle',shuttleImg);
}
function* postShuttle(action){
try{
const result=yield call(postShuttleAPI,action.data);
yield put({
type:SHUTTLEPOST_SUCCESS,
data:result.data
//code정보를 보내줘야하나? code를 보내주면 한번에 정보를 보내줘야하지않을까?
})
}catch(e){
yield put({
type: SHUTTLEPOST_FAILURE,
error:e
})
}
}
function* watchPostShuttle() {
yield takeLatest(SHUTTLEPOST_REQUEST,postShuttle);
}
export default function* imageSaga(){
yield all([
fork(watchLoadShuttle),
fork(watchLoadIndex),
fork(watchPostIndex),
fork(watchPostShuttle)
])
}<file_sep>const express = require('express');
const path = require('path');
const db = require('../models');
const router = express.Router();
router.get('/boothmap', async (req, res, next) => { //부스 조회
try {
const boothInfo = await db.Admin.findAll({
where:{},
include:[{
model:db.Menu,
attributes:['food','price','soldOut']
}]
});
console.log(boothInfo)
res.json(boothInfo)
} catch (e) {
console.error(e);
next(e);
}
})
router.get('/:code',async(req,res,next)=>{//부스 조회 api/admin
try{
const adminCode=await db.Admin.findOne({
where:{code:req.params.code},
include:[{
model:db.Menu,
attributes:['food','price','soldOut']
}]
});
console.log(adminCode);
res.status(200).json(adminCode)
}catch(e){
console.error(e);
next(e);
}
})
router.patch('/',async(req,res,next)=>{//부스 등록
try{
const Menus=await db.Menu.findAll({
where:{AdminCode:req.body.code}
})
console.log(Menus)
if(Menus){
await db.Menu.destroy({
where:{AdminCode:req.body.code}
})
}
const newAdmin=await db.Admin.update({
boothName:req.body.boothName,
opTimeOpen:req.body.opTimeOpen,
opTimeClose:req.body.opTimeClose,
full:req.body.full
},{
where:{code:req.body.code}
})
if(req.body.menu){
if(Array.isArray(req.body.menu)){
const menu = await Promise.all(req.body.menu.map((item,index) => {
return db.Menu.create({AdminCode:req.body.code, food: item.food,price:item.price,soldOut:item.soldOut});
}))
}
}
res.status(200).send("등록성공")
}catch(e){
res.send(e);
}
})
router.post('/code',async(req,res,next)=>{
try{
const codeFind=await db.Admin.findOne({
where:req.body.code
})
if(codeFind){
res.send("이미 존재하는 코드입니다")
return;
}
const codeCretate=await db.Admin.create({
code:req.body.code
})
res.send("코드등록 성공");
}catch(e){
res.send(e);
}
})
router.post('/', async (req, res, next) => { // POST /api/user 회원가입
try {
const exUser = await db.User.findAll({});
if(exUser){
return res.status(403).send('이미 존재 합니다.');
}
const hashedPassword = await bcrypt.hash(req.body.password, 12);
const newUser = await db.user.create({
userId: req.body.userId,
password: <PASSWORD>,
})
console.log(newUser);
return res.status(200).json(newUser).send('회원가입 성공!');
} catch (e) {
console.log(e);
return res.status(403).send(e);
}
});
router.post('/login', async (req,res, next)=>{ //POST /api/user/login
passport.authenticate('local', (err, userinfo, info)=>{
if(err){
console.error(err);
return next(err);
}
if(info){
return res.status(401).send(info.reason);
}
return req.login(userinfo, (loginErr)=>{
if(loginErr){
return next(loginErr);
}
const filteredUser = Object.assign({}, userinfo.toJSON());
delete filteredUser.password;
return res.status(200).json(filteredUser);
});
})(req,res,next);
});
module.exports = router;<file_sep>import React from 'react'
const drawerPage=()=>{
return(
<aside className='drawer' style={{position:'absolute',zIndex:20,width:'77%',height:'96%'
,backgroundColor:'#ffffff',top:32,left:'30%',border:'1px solid #d3d3d3'}}>
<img style={{marginLeft:'82%',marginTop:13.2}} onClick={async()=>{await getToggle(false);
await drawer()
}} src='/xbtn.png'></img>
<div style={{marginTop:90,marginLeft:50}}>
{Menu.map((item,index)=>{
return <Link href={{pathname:`/${route[index]}`}} as={`/${route[index]}`}><a onClick={()=>{
setToggle(false)
drawer();
}}><p key={index} style={{borderBottom:'solid 1px #d3d3d3',width:132,paddingBottom:23.2}}>{item}</p></a></Link>
})}
</div>
<div style={{marginLeft:'17%',marginTop:'21em'}}>
<Link href={{pathname:'/manager'}}><a onClick={()=>{ setToggle(false)
drawer();}}><strong>운영자페이지</strong></a></Link>
</div>
</aside>
)
}
export default drawerPage;<file_sep>module.exports = (sequelize, DataTypes) => {
const Menu = sequelize.define('Menu', {
food:{
type:DataTypes.STRING,
allowNull:false
},
price:{
type:DataTypes.STRING,
allowNull: false
},
soldOut:{
type: DataTypes.BOOLEAN,
allowNull: false
}
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
});
Menu.associate = (db) => {
db.Menu.belongsTo(db.Admin);
};
return Menu;
};
|
92d74253a30b344e9c64e2adf2a2523eb732193b
|
[
"JavaScript"
] | 22
|
JavaScript
|
jfmam/project1
|
1f2e2250e953a740dedfcfd26302afa02c34a93f
|
dfa433a8e5c38ffd550134ed386de647cf8540d0
|
refs/heads/master
|
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*
Route::get('/', function () {
return view('welcome');
});
*/
Route::get('/login', function () {
return view('auth.login');
});
Route::get('/logout', function () {
return "logout usuario";
});
Route::get('/','HomeController@getHome');
Route::get('productos','ProductoController@getIndex');
Route::get('productos/show/{id}','ProductoController@getShow')->where('id', '[0-9]+');
Route::get('productos/create','ProductoController@getCreate');
Route::get('productos/edit/{id}','ProductoController@getEdit')->where('id', '[0-9]+');
/*
Route::get('productos/show/{id}', function ($id) {
return view('productos.show', array('id'=>$id));
})->where('id', '[0-9]+');
*/
|
f4ea11e1b24ec4bbb60b81fc4ae2032888944a96
|
[
"PHP"
] | 1
|
PHP
|
3888592/listaCompra
|
1fe04d299debdcf3f6ee119c2435142a3fd4ce8c
|
f07f39854f118273d51f6117494e9e5118afdd19
|
refs/heads/master
|
<file_sep>package server;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Scanner;
public class Server {
public static final int PORT = 5000;
static HashMap<String,PrintWriter> pwMap;
public static void main(String[] args) {
// write your code here
ServerSocket serverSocket = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
OutputStreamWriter osw = null;
PrintWriter pw = null;
Scanner sc = new Scanner(System.in);
try{
serverSocket = new ServerSocket(PORT);
/*InetAddress inetAddress = InetAddress.getLocalHost();
String localhost = inetAddress.getHostAddress();
serverSocket.bind(new InetSocketAddress("localhost", PORT));*/
System.out.println("[server] binding:" + serverSocket.getInetAddress().getHostAddress());
pwMap = new HashMap<String,PrintWriter>();
while(true) {
Socket socket = serverSocket.accept();
InetSocketAddress socketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
//System.out.println("[server] connected to client");
//System.out.println("[server] connect with " + socketAddress.getHostString() + " " + socket.getPort());
Thread t = new Thread(new ServerThread(socket,pwMap));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if (serverSocket != null && !serverSocket.isClosed()){
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
sc.close();
}
}
}
<file_sep>#!/bin/bash
REPO=/home/ec2-user/chat
PROJECT=chatting
echo "> build 파일 복사"
cp $REPO/zip/*.jar $REPO/
echo "> 현재 구동 중인 애플리케이션 pid 확인"
CURRENT_PID=$(pgrep -f chatting)
echo "> 현재 구동 중인 애플리캐리션 pid: $CURRENT_PID"
if [ -z "$CURRENT_PID" ]; then
echo "> 현재 구동 중인 애플리케이션이 없습니다"
else
echo "> kill -15 $CURRENT_PID"
kill -15 "$CURRENT_PID"
sleep 5
fi
echo "> 새 애플리케이션 배포"
JAR_NAME=$(ls -tr $REPO/*.jar | tail -n 1)
echo "> JAR Name: $JAR_NAME"
echo " $JAR_NAME 에 실행 권한 추가"
chmod +x $JAR_NAME
echo "> $JAR_NAME 실행"
nohup java -jar $JAR_NAME > $REPO/nohup.out 2>&1 &
|
6c365c82dc332e4ef0c11b5a5323026cd9bc2ca9
|
[
"Java",
"Shell"
] | 2
|
Java
|
sciencemj/chatting
|
ff719562bc93a33f629179b9a555a76c5d138388
|
97853b3264532a013b8e68ad9f73cc30c407b8a2
|
refs/heads/master
|
<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#pragma once
#include <iostream>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//Missile class that is a Missile Sprite, just used to move the missile
class Missile : public Sprite
{
public:
//======================================================
// Missile: Missile Constructor
// parameters: none
// return type: Missile
//======================================================
Missile() {};
//======================================================
// shootMissile: shoots missile
// parameters:
// speed: speed of missile
// return type: none
//======================================================
void shootMissile(int speed)
{
int Y = getPosition().y;
move(0, speed);
}
};<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#include "alien.h"
#include "missile.h"
#include <iostream>
#include <list>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//======================================================
// Alien: Alien Contructor
// parameters:
// location: location of Alien
// return type: Alien
//======================================================
Alien::Alien(Vector2f location)
{
if (!enemyTexture.loadFromFile("haunter.png"))
{
cout << "Unable to load enemy texture!" << endl;
exit(EXIT_FAILURE);
}
if (!bomb.loadFromFile("shadow.png"))
{
cout << "Unable to load enemy texture!" << endl;
exit(EXIT_FAILURE);
}
setTexture(enemyTexture);
setPosition(location);
walk = 0;
};
//======================================================
// moveAlien: moves Alien
// parameters: none
// return type: none
//======================================================
void Alien::moveAlien()
{
const float dash = 3.0f;
const float slow = 0.25f;
if (walk == 0)
{
move(-dash, slow);//left and slowly downward
if (getPosition().x < initial.x - 50)
{
walk = 1;
}
}
else if (walk == 1)
{
move(dash, slow);//right and slowly downward
if (getPosition().x > initial.x + 50)
{
walk = 0;
}
}
}
//======================================================
// processAlien: processes the bomb functionality
// parameters:
// location: location of Alien
// return type: none
//======================================================
void Alien::processAlien(RenderWindow&)
{
list<Missile>::iterator bombIter;
for (bombIter = bombList.begin(); bombIter != bombList.end(); bombIter++)
if(bombIter == bombList.begin())
bombIter->shootMissile(5);
}
//======================================================
// setInitial: sets Initial Location of Alien
// parameters:
// loc: initial location of Alien
// return type: none
//======================================================
void Alien::setInitial(Vector2f loc)
{
initial = loc;
}
//======================================================
// dropBomb: drops bomb
// parameters: none
// return type: none
//======================================================
void Alien::dropBomb()
{
Missile alienBomb;
alienBomb.setPosition(getPosition().x, getPosition().y+40);
bombList.push_back(alienBomb);
}
//======================================================
// drawBomb: draws the bomb
// parameters:
// win: window rendered in main
// level: current level of the game
// return type: none
//======================================================
void Alien::drawBomb(RenderWindow& win, int level)
{
list<Missile>::iterator bombIter;
for (bombIter = bombList.begin(); bombIter != bombList.end(); bombIter++)
{
bombIter->setTexture(bomb);
if (level == 2)
{
bombIter->setScale(0.025, 0.025);
}
else
{
bombIter->setScale(0.02, 0.02);
}
if(bombIter == bombList.begin())
win.draw(*bombIter);
}
}
//======================================================
// playerHit: checks if player was hit
// parameters:
// player: the globalbounds of the player
// return type: bool
//======================================================
bool Alien::playerHit(FloatRect player)
{
bool hit = false;
list<Missile>::iterator bombIter;
vector<list<Missile>::iterator> bombDelete;
for (bombIter = bombList.begin(); bombIter != bombList.end(); bombIter++)
{
FloatRect bombBounds = bombIter->getGlobalBounds();
if (bombBounds.intersects(player))
{
bombDelete.push_back(bombIter);
hit = true;
}
}
for (int i = 0; i < bombDelete.size(); i++)
{
bombList.erase(bombDelete[i]);
}
return hit;
}
<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#include "ship.h"
#include "alien.h"
#include <iostream>
#include <string>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//======================================================
// Ship: ship constructor
// parameters: none
// return type: Ship
//======================================================
Ship::Ship()
{
reset = false; //reset for missileLaunch
//Loads Texture
if (!shipTexture.loadFromFile("trainer.png"))
{
cout << "Unable to load ship texture!" << endl;
exit(EXIT_FAILURE);
}
if (!missileTexture.loadFromFile("pokeball.png"))
{
cout << "Unable to load ship texture!" << endl;
exit(EXIT_FAILURE);
}
if (!master.loadFromFile("master.png"))
{
cout << "Unable to load ship texture!" << endl;
exit(EXIT_FAILURE);
}
if (!lifeTexture.loadFromFile("life.png"))
{
cout << "Unable to load ship texture!" << endl;
exit(EXIT_FAILURE);
}
scale(sf::Vector2f(0.15, 0.15));
setTexture(shipTexture); //set Texture of Ship
setPosition(400, 550); // initial position of the ship
//creates hearts/lives
Vector2f heartLoc(60, 5);
for (int i = 0; i < 3; i++)
{
life[i].setTexture(lifeTexture);
life[i].scale(sf::Vector2f(0.035, 0.035));
life[i].setPosition(heartLoc);
heartLoc.x += 30;
}
//sets missile texture
missile.setTexture(missileTexture);
missile.setScale(0.02, 0.02);
}
//======================================================
// play: calls functions from player to perform the game actions
// parameters:
// win: window rendered in main
// enemy: list of aliens
// return type: none
//======================================================
void Ship::play(RenderWindow& win, list<Alien>& enemy)
{
moveMissile();
drawMissile(win);
launchMissile();
checkHit(enemy);
drawKills(win);
}
//======================================================
// moveShip: moves ship sprite
// parameters: none
// return type: none
//======================================================
void Ship::moveShip()
{
const float DISTANCE = 5.0f;
if (Keyboard::isKeyPressed(Keyboard::Left))
{
// left arrow is pressed: move our ship left 5 pixels
move(-DISTANCE, 0);
}
else if (Keyboard::isKeyPressed(Keyboard::Right))
{
// right arrow is pressed: move our ship right 5 pixels
move(DISTANCE, 0);
}
}
//======================================================
// shipBounds: keeps the ship sprite in the bounds of the window
// parameters: none
// return type: none
//======================================================
void Ship::shipBounds()
{
if (getPosition().y > 599)
{
setPosition(getPosition().x, 580);
}
else if (getPosition().y < 480)
{
setPosition(getPosition().x, 480);
}
else if (getPosition().x < 0)
{
setPosition(1, getPosition().y);
}
else if (getPosition().x > 780)
{
setPosition(780, getPosition().y);
}
else
{
moveShip();
}
}
//======================================================
// moveMissile: moves the missile sprite
// parameters: none
// return type: none
//======================================================
void Ship::moveMissile()
{
list<Missile>::iterator missileIter;
for (missileIter = missileList.begin(); missileIter != missileList.end(); missileIter++)
{
missileIter->move(0, -10);
}
}
//======================================================
// launchMissile: detects if key is hit so missile will launch
// parameters: none
// return type: none
//======================================================
void Ship::launchMissile()
{
if (Keyboard::isKeyPressed(Keyboard::Space) && reset == true)
{
Vector2f missilePos(getPosition().x + 8, getPosition().y);
missile.setPosition(missilePos);
missileList.push_back(missile);
reset = false;
}
else if (!Keyboard::isKeyPressed(Keyboard::Space))
{
reset = true;
}
}
//======================================================
// drawMissile: calls functions from player to perform the game actions
// parameters:
// win: window rendered in main
// return type: none
//======================================================
void Ship::drawMissile(RenderWindow& win)
{
list<Missile>::iterator missileIter;
missileIter = missileList.begin();
for (missileIter; missileIter != missileList.end(); missileIter++)
{
win.draw(*missileIter);
}
}
//======================================================
// checkHit: checks to see if ship sprite is hit
// parameters:
// enemy: list of aliens
// return type: none
//======================================================
void Ship::checkHit(list<Alien>& enemy)
{
list<Missile>::iterator missileIter;
vector<list<Missile>::iterator> missileDelete;
list<Alien>::iterator alienIter;
vector<list<Alien>::iterator> aliensDelete;
for (missileIter = missileList.begin(); missileIter != missileList.end(); missileIter++)
{
FloatRect missileBounds = missileIter->getGlobalBounds();
for (alienIter = enemy.begin(); alienIter != enemy.end(); alienIter++)
{
FloatRect enemyBounds = alienIter->getGlobalBounds();
if (missileBounds.intersects(enemyBounds))
{
killCount++;
aliensDelete.push_back(alienIter);
missileDelete.push_back(missileIter);//bug
}
}
}
for (int i = 0; i < missileDelete.size(); i++)
missileList.erase(missileDelete[i]);
for (int i = 0; i < aliensDelete.size(); i++)
enemy.erase(aliensDelete[i]);
missileDelete.clear();
for (missileIter = missileList.begin(); missileIter != missileList.end(); missileIter++)
{
if (missileIter->getPosition().y < 0)
{
missileDelete.push_back(missileIter);
}
}
for (int i = 0; i < missileDelete.size(); i++)
missileList.erase(missileDelete[i]);
}
//======================================================
// displayLife: displays lives
// win: window rendered in main
// lifeCount: amount of lives
// return type: none
//======================================================
void Ship::displayLife(RenderWindow& win, int lifeCount)
{
for (int i = 0; i < lifeCount; i++)
{
win.draw(life[i]);
}
}
//======================================================
// drawKills: displays amount of kills
// parameters:
// win: window rendered in main
// return type: none
//======================================================
void Ship::drawKills(RenderWindow& win)
{
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
{
cout << "Not Loading" << endl;
}
string kill = "Alien Kills:";
kill += to_string(killCount);
Text killText(kill, font, 20);
killText.setPosition(670, 0);
win.draw(killText);
}
//======================================================
// setMissileTexture: sets Texture of missile
// parameters: none
// return type: none
//======================================================
void Ship::setMissileTexture()
{
missile.setTexture(master);
missile.setScale(0.06, 0.06);
}
//======================================================
// getKillCount: gets amount of kills
// parameters: none
// return type: int
//======================================================
int Ship::getKillCount()
{
return killCount;
}
//======================================================
// setKillCount: sets Kill Count
// parameters:
// kills: amount of kills
// return type: none
//======================================================
void Ship::setKillCount(int kills)
{
killCount = kills;
}
<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#pragma once
#include <iostream>
#include <list>
#include "missile.h"
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//Alien class that houses the actions and the variables used by Alien
class Alien : public Sprite
{
private:
//Alien
int walk; //walk integers used by moveAlien function
Vector2f initial; //initial position of Aliens
Texture enemyTexture;//texture of level 1 aliens
Texture level2Texture; //texture of level 2 aliens
//bomb
Texture bomb; //texture of bomb
list<Missile> bombList; //list of bombs
public:
Alien(Vector2f location);
void processAlien(RenderWindow&);
void moveAlien();
void setInitial(Vector2f);
void dropBomb();
void drawBomb(RenderWindow&, int);
bool playerHit(FloatRect);
};<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#include "alien.h"
#include "ship.h"
#include "Settings.h"
#include "missile.h"
#include <cstdlib>
#include <list>
#include <vector>
#include <iostream>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
//Window Size
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
//Player Initialization
Ship player;
//Setting Initialization and Variables that deal with Settings
Settings settings;
int frame = 0,
level = 1,
lifeCount = 3;
bool start = false,
end = false,
reset = false;
//Variables used with Alien Location and Move
Vector2f location(70, 50);
Vector2f initial[10];
//Renders Window
RenderWindow window(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Space Invaders!");
// Limit the framerate to 60 frames per second
window.setFramerateLimit(60);
// set up textures
Texture starsTexture;
if (!starsTexture.loadFromFile("background2.png"))
{
cout << "Unable to load stars texture!" << endl;
exit(EXIT_FAILURE);
}
Texture level2Texture;
if (!level2Texture.loadFromFile("gengar.png"))
{
cout << "Unable to load enemy texture!" << endl;
exit(EXIT_FAILURE);
}
//Sprite used to make the background
Sprite background;
background.setTexture(starsTexture);
background.setScale(0.5, 0.5);
//Alien and List Initialization
list<Alien> enemy;
Alien alien(location);
alien.scale(sf::Vector2f(0.2, 0.2));
//Fills list with Aliens
for (int i = 0; i < 10; i++)
{
alien.setPosition(location);
alien.setInitial(location);
enemy.push_back(alien);
location.x += 70;
}
// this is the main animation loop. The body of the loop runs ~ 60 times per second
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
else if (start == false) //Creates Start Screen
{
window.draw(background);
settings.drawDefaults(window);
window.display();
if (settings.processClick(window)) //if start button is pressed then start the game
{
start = true;
}
}
}
if (start == true) //If start is clicked
{
window.draw(background);
if (reset == true) //reset used for when a life is lost
{
reset = false;
enemy.clear();
lifeCount--;
if (level == 1) //if level is 1
{
Vector2f location(70, 50);
for (int i = 0; i < 10; i++)
{
alien.setPosition(location);
alien.setInitial(location);
enemy.push_back(alien);
location.x += 70;
}
player.setKillCount(0);
}
else if (level == 2) //if level is 2
{
Vector2f location(70, 50);
for (int i = 0; i < 10; i++)
{
alien.setTexture(level2Texture);
alien.setPosition(location);
alien.setInitial(location);
enemy.push_back(alien);
location.x += 70;
}
location.y += 100;
for (int i = 0; i < 10; i++)
{
location.x -= 70;
alien.setTexture(level2Texture);
alien.setPosition(location);
alien.setInitial(location);
enemy.push_back(alien);
}
player.setKillCount(10);
}
}
settings.drawStats(window); //Draws Lives and Alien Kill stats
player.displayLife(window, lifeCount); //Displays Lives
player.play(window, enemy); //Play function that does all Player/Ship functionality
frame++;
player.shipBounds(); //also keeps the ship within the global bounds
window.draw(player);// draw the ship on top of background
//Iterators used to find a certain Alien
list<Alien>::iterator iter;
vector<list<Alien>::iterator> toDelete;
//does all Alien and Bomb fuctionalities
for (iter = enemy.begin(); iter != enemy.end(); iter++)
{
iter->moveAlien(); //moves Alien
window.draw(*iter); //draws Alien
iter->processAlien(window); //process Alien
iter->drawBomb(window, level); //draws bomb
if (iter->playerHit(player.getGlobalBounds()) || iter->getPosition().y > 500) //If player losses a life it resets the original state of the current level
{
reset = true;
}
if (frame == 100 || frame == 50) //randomizer for bomb, drop bomb at random location every 50 to 100 seconds
{
list<Alien>::iterator bombIterator;
bombIterator = enemy.begin();
srand(time(NULL));
int randomizer = (rand() % enemy.size() - 1);
for (int i = 0; i < randomizer && bombIterator != enemy.end(); i++)
{
bombIterator++;
}
bombIterator->dropBomb(); //drops bomb
}
}
for (int i = 0; i < toDelete.size(); i++)
{
enemy.erase(toDelete[i]);
}
}
if (player.getKillCount() == 10 && level == 1) //sets level 1 to level 2 if beaten
{
level = 2;
reset = true;
lifeCount++;
}
if (player.getKillCount() == 30) //if game is won, display win screen
{
settings.drawWinScreen(window);
player.setMissileTexture();
}
if (lifeCount <= 0) //if you are out of lives, display lose screen
{
end == true;
while (!end)
{
window.draw(background);
settings.drawLoseScreen(window);
window.display();
if (event.type == Event::Closed)
window.close();
}
}
if (frame == 100) //resets frame counter
{
frame = 0;
}
window.display(); // end the current frame;
}
return 0;
}<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#pragma once
#include "Settings.h"
#include <iostream>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//======================================================
// Settings: Settings Contructor
// parameters: none
// return type: Settings
//======================================================
Settings::Settings()
{
Vector2f sqPos(300, 250);
start.setPosition(sqPos);
start.setOutlineColor(Color::White);
start.setOutlineThickness(2);
start.setSize(Vector2f(200, 50));
start.setFillColor(Color::Black);
}
//======================================================
// drawDefaults: draws startScreen
// parameters:
// win: window rendered in main
// return type: none
//======================================================
void Settings::drawDefaults(RenderWindow& win)
{
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
die("couldn't load font");
Text title("Start", font, 30);
title.setPosition(360, 255);
Text title2("Space Invaders", font, 100);
title2.setPosition(50, 100);
title2.setStyle(Text::Bold);
win.draw(start);
win.draw(title);
win.draw(title2);
}
//======================================================
// processClick: processes button click
// parameters:
// win: window rendered in main
// return type: bool
//======================================================
bool Settings::processClick(RenderWindow& win)
{
if (Mouse::isButtonPressed(Mouse::Left))
{
Vector2f mouse = win.mapPixelToCoords(Mouse::getPosition(win));
if (start.getGlobalBounds().contains(mouse))
{
cout << "Begin" << endl;
return true;
}
}
return false;
}
//======================================================
// die: tells when to exit
// parameters:
// msg: string of message
// return type: none
//======================================================
void Settings::die(string msg)
{
cout << msg << endl;
exit(-1);
}
//======================================================
// drawStats: draws Lives and Aliens killed
// parameters:
// win: window rendered in main
// return type: none
//======================================================
void Settings::drawStats(RenderWindow& win)
{
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
die("couldn't load font");
Text life("Lives:", font, 20);
life.setPosition(2, 0);
win.draw(life);
}
//======================================================
// drawWinScreen: draws win Screen
// parameters:
// win: window rendered in main
// return type: none
//======================================================
void Settings::drawWinScreen(RenderWindow& win)
{
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
die("couldn't load font");
Text end("You Win!", font, 100);
end.setPosition(200, 100);
end.setFillColor(Color::Black);
Text master("You are a Pokemon Master!", font, 20);
master.setPosition(270, 240);
master.setFillColor(Color::Black);
win.draw(master);
win.draw(end);
}
//======================================================
// drawWinScreen: draws lose Screen
// parameters:
// win: window rendered in main
// return type: none
//======================================================
void Settings::drawLoseScreen(RenderWindow& win)
{
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
die("couldn't load font");
Text lose("You Lose!", font, 100);
lose.setPosition(200, 100);
lose.setFillColor(Color::Black);
Text loser("You are not a Pokemon Master!", font, 20);
loser.setPosition(270, 240);
loser.setFillColor(Color::Black);
win.draw(loser);
win.draw(lose);
}<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#pragma once
#include <iostream>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//Settings class that sets the displays buttoms, and screens
class Settings
{
private:
RectangleShape start;//Start button
public:
Settings();
void drawDefaults(RenderWindow&);
bool processClick(RenderWindow&);
void die(string msg);
void drawStats(RenderWindow&);
void drawWinScreen(RenderWindow&);
void drawLoseScreen(RenderWindow&);
};<file_sep>//========================================================
//<NAME>
//4-20-2016
//Progamming Assignment #8
//Description: Space Invaders
//========================================================
#pragma once
#include <iostream>
#include <list>
#include "alien.h"
#include "missile.h"
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//Ship class that contains the ship and all its functionalities
class Ship :public Sprite
{
private:
//Ship
int killCount;//amount of kills
bool reset; //reset for launch missile
Texture shipTexture;//Texture of ship/pokemon trainer
//Life
Sprite life[3]; //array of Sprites of Lives
Texture lifeTexture;//Texture of life
//missile
Missile missile;
Texture missileTexture;//Texture of Missile
list<Missile> missileList;//list of missile
Texture master;//Texture of Winner Missile
public:
Ship();
void play(RenderWindow&, list<Alien>&);
void moveShip();
void shipBounds();
void moveMissile();
void launchMissile();
void drawMissile(RenderWindow&);
void checkHit(list<Alien>&);
void displayLife(RenderWindow&, int);
void drawKills(RenderWindow&);
void setMissileTexture();
int getKillCount();
void setKillCount(int);
};
|
8b4f3266eb8e409a007cde338caec538e6fc4702
|
[
"C++"
] | 8
|
C++
|
JeremyMarz/Space_Invaders
|
3632f71a4515f48555a7a2a0442f3c3453346ed3
|
642b6c8b393ffdebb7347a6b7063edc458248aab
|
refs/heads/master
|
<repo_name>Badu897/DiamantiGrezzi<file_sep>/SetVolume.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class SetVolume : MonoBehaviour
{
public AudioMixer audiomixer;
public void SetLevel(float volume)
{
audiomixer.SetFloat("Volume", Mathf.Log10(volume) * 20);
}
}
<file_sep>/README.md
# VOID
VOID è un survival game dove il protagonista principale è un **BUCO NERO** il cui obbiettivo è quello di mangiare i **Pianeti**
che esso stesso attrae, recuperando vita. All'interno della mappa spawneranno anche dei **Soli**, i quali dovrà schivare
per non perdere vita.
Un buon motivo per giocare a questo gioco è quello di poter sfidare i propri amici, chi riesce a rimanere vivo più tempo possibile
e fare il punteggio più alto, vince.
Oppure sfidare sé stessi nel migliorarsi di giorno in giorno, potendo arricchire le proprie capacità nel gioco.
**COMING SOON...**
Presto in arrivo nuovi livelli sempre più entusiasmanti e difficili, con nuove mappe e nuove skin per i personaggi del gioco.
### *LAYOUT DEL GIOCO*
Il gioco si compone di 3 diverse scene:
##### 1. Menù principale:

##### 2. Schermata di gioco:

##### 3. Menù Game Over:

### *Diagammi*
##### 1. Diagramma delle classi:

##### 1. Diagramma dei casi d'uso:

### *Credits*
**GRUPPO <NAME>:** <NAME>, <NAME>, <NAME>, <NAME>.
<file_sep>/Spawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
public Transform spawnPos;
public GameObject planet;
public GameObject missile;
const float spawnTime = 2;
float pauseTime = spawnTime;
void Update(){
if (pauseTime <= 0)
{
Spawn();
pauseTime = spawnTime;
}
else
{
pauseTime = pauseTime - Time.deltaTime;
}
}
void Spawn(){
if(Random.Range(1, 1000) <= 333)
{
Instantiate(planet, spawnPos.position, spawnPos.rotation);
}
else if(Random.Range(1, 1000) >= 666)
{
Instantiate(missile, spawnPos.position, spawnPos.rotation);
}
}
}
<file_sep>/Bars.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bars : MonoBehaviour
{
Transform bar;
void Start()
{
bar = transform.Find("Bar");
}
public void setSize(float sizeNormalized)
{
bar.localScale = new Vector3(sizeNormalized, 1f);
}
}
<file_sep>/OnCollisions.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class OnCollisions : MonoBehaviour
{
[SerializeField] private Bars healthBar;
[SerializeField] private Bars hungerBar;
const float damage = 0.2f;
const float bite = 0.1f;
float n = 0;
private float nCollisionsSun = -damage;
private float nCollisionsPlanet = bite;
void OnCollisionEnter(Collision collision){
if (collision.gameObject.name == "Sun(Clone)"){
healthBar.setSize(1 + nCollisionsSun);
nCollisionsSun -= damage;
FindObjectOfType<AudioManager>().Play("DamageSound");
if (nCollisionsSun == -1.2f)
{
FindObjectOfType<AudioManager>().Stop("MainTheme");
FindObjectOfType<AudioManager>().Play("DeathSound");
SceneManager.LoadScene(2);
}
}
if(collision.gameObject.name == "Planet(Clone)"){
FindObjectOfType<AudioManager>().Play("PopSound");
hungerBar.setSize(nCollisionsPlanet);
nCollisionsPlanet += bite;
n++;
if (n == 11)
{
FindObjectOfType<AudioManager>().Play("HealthSound");
hungerBar.setSize(0);
healthBar.setSize(1);
nCollisionsPlanet = bite;
n = 0;
nCollisionsSun = -damage;
nCollisionsPlanet = bite;
}
}
}
}
<file_sep>/Destroyer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroyer : MonoBehaviour {
public float lifetime = 10f;
public Transform spawnPos;
public GameObject particle;
void Update () {
if (lifetime > 0)
{
lifetime -= Time.deltaTime;
if (lifetime <= 0){
Destruction();
}
}
}
void OnCollisionEnter(Collision collision){
if (collision.gameObject.name == "Player" || collision.gameObject.name == "BackGround"){
Destruction();
Instantiate(particle, spawnPos.position, spawnPos.rotation);
}
}
void Destruction(){
Destroy(this.gameObject);
}
}
<file_sep>/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody rb;
private Vector3 moveVelocity;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveVelocity = moveInput * speed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
}
|
a6206abaeb7d10c0f14279fc4df46f863e7b4bad
|
[
"Markdown",
"C#"
] | 7
|
C#
|
Badu897/DiamantiGrezzi
|
f29a53d92ecd1e471bf8659676cbaef0a05b9f4b
|
1837b1a66269091d22307e42d850440a61664efd
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PostResult {
public string esito;
public int stato;
public string descrizione;
public string type;
public int timestamp;
public string nome;
public float tempo_rimasto;
}
<file_sep># ScriptsClassifica_v2.2
Version: 2.2
Data: 17/11
Scripts per la gestione e visualizzazione della classifica.
### Contenuto package
```
- CheckPunteggio.cs
- FivePunteggi.cs
- GetPunteggi.cs
- Punteggio.cs
- ResultCheckPunteggio.cs
- ResultFivePunteggi.cs
- ResultGetPunteggi.cs
- ResultSalvaPunteggio.cs
- SalvaPunteggio.cs
- PunteggioController (OBJ prefab, da mettere in scena per far funzionare tutto!)
- FirstFive.cs
- ResultFirstFive.cs
```
# CheckPunteggio.cs
Script che si occupa di controllare se il punteggio da salvare rientra tra i primi 250 in classifica
#### To-Do
- Modificare url_five con link indicato per mail
- aggiungere OnCollisionEnter2D() o OnTriggerEnter2D()
```
void OnCollisionEnter2D(Collision2D other) {
float nuovo_punteggio = /* variabile che indica il tempo rimasto/punteggio */;
checkPunteggio(nuovo_punteggio);
}
void OnTriggerEnter(Collider2D other) {
float nuovo_punteggio = /* variabile che indica il tempo rimasto/punteggio */;
checkPunteggio (nuovo_punteggio);
}
```
- modificare funzione inClassifica()
- modificare funzione nonInClassifica()
# SalvaPunteggio.cs
Script che si occupa di controllare se il punteggio da salvare rientra tra i primi 250 in classifica
#### To-Do
- Modificare url_save con link indicato per mail
- aggiungere OnCollisionEnter2D() o OnTriggerEnter2D()
```
void OnCollisionEnter2D(Collision2D other) {
salvaPunteggio(nome, tempo_rimasto);
}
void OnTriggerEnter(Collider2D other) {
salvaPunteggio(nome, tempo_rimasto);
}
```
- modificare la funzione success()
# FivePunteggi.cs
Script che si occupa di prendere i punteggi adiacenti a quelli del giocatore corrente, e del suo punteggio
#### To-Do
- Modificare url_check con link indicato per mail
- Modifica PunteggiTrovati()
# FirstFive.cs
Script che si occupa di prendere i primi 5 in classifica
#### To-Do
- Modificare url_check con link indicato per mail
- Modifica PunteggiTrovati()
<file_sep># ScriptsClassifica_v2
Version: 2
Data: 19/09
Script per la gestione e visualizzazione della classifica.
### Contenuto package
```
- GetPunteggi.cs
- Punteggio.cs
- ResultGetPunteggi.cs
- ResultSalvaPunteggio.cs
- SalvaPunteggio.cs
```
### GetPunteggi.cs
Script che si occupa di ottenere i primi 250 punteggi in classifica.
Modificabile in futuro nel caso cambi il brief.
### Punteggio.cs
Script Model
### ResultGetPunteggi.cs
Script Model
### ResultSalvaPunteggio.cs
Script Model
### SalvaPunteggio.cs
Script che si occupa di salvare il punteggio.
## Come usare il package
Gli unici file da toccare sono **GetPunteggi.cs** e **SalvaPunteggio.cs**
Contengono gli OnTriggerEnter.
### GetPunteggi.cs
Modificare la variabile url con quella fornita per mail.
### SalvaPunteggio.cs
Modificare le variabili url con quelle fornita per mail.<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SalvaPunteggio : MonoBehaviour {
private string url = "http://demo01.dsit.it/unitygames-test/gioco-natale-2016/salva-punteggio.php";
private PostResult response;
public bool testing;
void Start() {
if (testing) {
string nome = "testing";
float tempo_rimasto = 100f;
salvaPunteggio(nome, tempo_rimasto);
}
}
void OnCollisionEnter2D(Collision2D other) {
if (!testing) {
string nome = "not testing";
float tempo_rimasto = 100f;
salvaPunteggio(nome, tempo_rimasto);
}
}
private void success() {
// Qui tutto il codice da eseguire dopo il salvataggio
Debug.Log("punteggio memorizzato correttamente");
}
/* ============================== don't edit ================================ */
public void salvaPunteggio(string nome, float tempo_rimasto) {
IEnumerator salvaPunteggio = post_salvaPunteggio(nome, tempo_rimasto);
StartCoroutine (salvaPunteggio);
}
private IEnumerator post_salvaPunteggio(string nome, float tempo_rimasto) {
WWWForm post_salvaPunteggio = new WWWForm();
post_salvaPunteggio.AddField("nome", nome);
post_salvaPunteggio.AddField("tempo_rimasto", tempo_rimasto+"");
WWW www = new WWW(url, post_salvaPunteggio);
yield return www;
response = JsonUtility.FromJson<PostResult> (www.text);
switch(response.stato) {
case -1: // variabili non inserite
Debug.Log("Nome e tempo rimasto non passate allo script");
break;
case -2: // exception: query count punteggi
Debug.Log("Exception during counting");
break;
case -3: // db full
Debug.Log("Il database è pieno");
break;
case -4: // exception: salvataggio
Debug.Log("C'è stata una eccezione durante il salvataggio");
break;
case 200: // success
success();
break;
}
}
}
<file_sep># <NAME> - Roody
Questa è la repo Github con tutti gli script per il gioco!
# Timeline versioni
#### ScriptsClassifica_v1 (deprecated)
- Salvataggio punteggi
#### ScriptsClassifica_v2 (deprecated)
- Salvataggio punteggi
#### ScriptsClassifica_v2.1 (deprecated)
- Salvataggio punteggi
- Classifica
#### ScriptsClassifica_v2.2
- Salvataggio punteggi
- Classifica (con posizioni)
- Primi 5 punti (con posizioni)
|
991a634f94b42ae0bb3ab78b2b572c981fb8bd2c
|
[
"Markdown",
"C#"
] | 5
|
C#
|
oswvld/ds-roody-game
|
5b81dbcac1859bb20eb317883253da8d89087443
|
40dc76b907fb02a35fcdcf168c9fb6e3c8be8cf1
|
refs/heads/master
|
<repo_name>rbajaj1997/tic-tac-toe<file_sep>/client/src/components/NewSession.js
import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Alert from '@material-ui/lab/Alert';
//import io from 'socket.io-client';
import socket from '../api/port';
export default function NewSession(props) {
const [isDialogOpen, setDialogOpen] = useState(false);
const [username, setUsername] = useState('');
const [incomplete, setIncomplete] = useState(false);
const handleClickOpen = () => {
setDialogOpen(true);
};
const handleClose = () => {
setDialogOpen(false);
setIncomplete(false);
};
const handleSumbit = (event) => {
// Logic to Come Here
if (username !== '') {
setDialogOpen(false);
setIncomplete(false);
socket.emit("create-session", username);
} else {
event.preventDefault();
setIncomplete(true);
// TODO: Give a warning
}
};
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
return (
<div>
<Button variant="contained" color="primary" size="large" onClick={handleClickOpen}>
Create Session
</Button>
<Dialog open={isDialogOpen} onClose={handleClose} aria-labelledby="form-dialog-create-session">
{incomplete && <Alert severity="error">Please enter your username</Alert>}
<DialogTitle id="form-dialog-title"> Create a Session</DialogTitle>
<DialogContent>
<DialogContentText>
To create a new session, please enter your username and hit the join button
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="username"
label="Username"
type="text"
fullWidth
value={username}
onChange={handleUsernameChange}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button onClick={handleSumbit} color="primary">
Create & Join
</Button>
</DialogActions>
</Dialog>
</div>
);
}
<file_sep>/server.js
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const Session = require('./SessionObject').Session;
const path = require('path');
const express = require('express');
var roomToSessionMapping = {}; //only for joining lobbies
var socketToSessionMapping = {};
io.on('connection', (socket) => {
//Create Session (Player 1)
socket.on('create-session', (name) => {
console.log('Inside Create Session');
var roomKey = Math.floor(Math.random() * 1000000).toString();
const session = new Session(socket, roomKey);
session.SetPlayer1Name(name);
roomToSessionMapping = { ...roomToSessionMapping, [roomKey]: session };
socketToSessionMapping = { ...socketToSessionMapping, [socket]: session };
socket.emit("session-created", name, roomKey);
console.log('Session Created!');
socket.on("disconnect", () => {
try {
socketToSessionMapping[socket].p2_socket.emit("user-disconnected");
}
catch (err) {
console.log('Error while emiting session disconnected event', err);
}
delete roomToSessionMapping[roomKey];
delete socketToSessionMapping[socket];
})
});
// Join Session (Player 2)
socket.on('join-session', (roomKey, name) => {
console.log('Inside Join Session');
if (roomToSessionMapping[roomKey] === undefined) {
console.log('Invalid Room key');
socket.emit("invalid-roomkey");
} else {
roomToSessionMapping[roomKey].JoinSession(name, socket);
roomToSessionMapping[roomKey].Broadcast("valid-code", roomToSessionMapping[roomKey].gameState);
socketToSessionMapping = { ...socketToSessionMapping, [socket]: roomToSessionMapping[roomKey] };
delete roomToSessionMapping[roomKey];
console.log('Session Joined!');
socket.on("disconnect", () => {
try {
socketToSessionMapping[socket].p1_socket.emit("user-disconnected");
}
catch (err) {
console.log('Error while emiting session disconnected event', err);
}
delete socketToSessionMapping[socket];
})
}
});
// Game Logic
socket.on('player-move', (index, value) => {
// Update Grid on Player Move
socketToSessionMapping[socket].PlayerMove(index, value);
// Check Game Status
switch (socketToSessionMapping[socket].checkWinner()) {
case "p1":
socketToSessionMapping[socket].Broadcast("announcement", "p1");
break;
case "p2":
socketToSessionMapping[socket].Broadcast("announcement", "p2");
break;
case "tie":
socketToSessionMapping[socket].Broadcast("announcement", "tie");
break;
case "ongoing":
break;
default:
console.log("no switch cases hit");
}
socketToSessionMapping[socket].Broadcast("update", socketToSessionMapping[socket].gameState);
})
});
const port = process.env.PORT || 8090;
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
}
server.listen(port, () => {
console.log(`Listening to port ${port}`);
});<file_sep>/client/src/components/Game.js
import React, { useState, useEffect } from 'react';
import socket from '../api/port';
import Board from './Board';
import Typography from '@material-ui/core/Typography';
import Stats from './Stats';
/**
*
* 1 -> Player 1 i.e He is O
* -1 -> Player 2 i.e He is X
*/
export default function Game(props) {
const { gamestate, isp1 } = props;
const [announcement, setAnnouncement] = useState(false);
const [msg, setMsg] = useState('');
const [oppDisconnected, setOppDisconnected] = useState(false);
useEffect(() => {
socket.on("announcement", (text) => {
switch (text) {
case 'p1':
setAnnouncement(true);
if (isp1) {
setMsg('You Won!');
} else {
setMsg('You Lost');
}
break;
case 'p2':
setAnnouncement(true);
if (isp1) {
setMsg('You Lost');
} else {
setMsg('You Won!');
}
break;
case 'tie':
setAnnouncement(true);
setMsg('It\'s a tie! Play another one?');
break;
default:
break;
}
setTimeout(() => {
setAnnouncement(false);
}, 1250);
});
socket.on("user-disconnected", () => {
setOppDisconnected(true);
})
}, [isp1])
return (
<div className="arena">
{oppDisconnected && <div> <Typography variant="h4">Opponent Disconnected!</Typography> </div>}
{!oppDisconnected && <Board gamestate={gamestate} isp1={isp1} />}
{!oppDisconnected && announcement && <div className="arena-stats"><Typography variant="h4">{msg}</Typography></div>}
{!oppDisconnected && !announcement && <Stats gamestate={gamestate} isp1={isp1} />}
</div>
)
}<file_sep>/client/src/components/Lobby.js
import React, { useState, useEffect } from 'react'
import Waiting from './Waiting';
import socket from '../api/port';
import Game from './Game';
export default function Lobby(props) {
const { gameState, roomKey, waiting, isp1 } = props;
const [gamestate, setGameState] = useState(gameState)
useEffect(() => {
socket.on("update", (gamestate) => {
setGameState(gamestate);
})
}, [])
return (
<div>
{waiting && <Waiting roomKey={roomKey} />}
{!waiting && <Game gamestate={gamestate} isp1={isp1} />}
</div>
);
}<file_sep>/client/src/components/Board.js
import React from 'react';
import socket from '../api/port';
import CloseIcon from '@material-ui/icons/Close';
import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked';
export default function Board(props) {
const { gamestate, isp1 } = props;
const squareClicked = (index) => {
// Check if the square has already been clicked -> then return
if (gamestate.grid[index] !== 0) {
return;
} else {
// Check if it is the correct player's turn -> otherwise return
if ((gamestate.p1_turn && !isp1) || (!gamestate.p1_turn && isp1)) {
return;
}
if (isp1) {
socket.emit("player-move", index, 1);
} else {
socket.emit("player-move", index, -1);
}
}
}
const valueDecider = (val) => {
switch (val) {
case 1:
return <RadioButtonUncheckedIcon style={{ fontSize: 80 }} />;
case -1:
return <CloseIcon style={{ fontSize: 80 }} />;
default:
return null;
}
}
return (
<div class="arena-board">
<div class="arena-board_row1">
<button onClick={() => squareClicked(0)} className="square">
{valueDecider(gamestate.grid[0])}
</button>
<button onClick={() => squareClicked(1)} className="square square_rightLeft">
{valueDecider(gamestate.grid[1])}
</button>
<button onClick={() => squareClicked(2)} className="square">
{valueDecider(gamestate.grid[2])}
</button>
</div>
<div class="arena-board_row2">
<button onClick={() => squareClicked(3)} className="square square_topBottom">
{valueDecider(gamestate.grid[3])}
</button>
<button onClick={() => squareClicked(4)} className="square square_rightLeft square_topBottom">
{valueDecider(gamestate.grid[4])}
</button>
<button onClick={() => squareClicked(5)} className="square square_topBottom">
{valueDecider(gamestate.grid[5])}
</button>
</div>
<div class="arena-board_row3">
<button onClick={() => squareClicked(6)} className="square">
{valueDecider(gamestate.grid[6])}
</button>
<button onClick={() => squareClicked(7)} className="square square_rightLeft">
{valueDecider(gamestate.grid[7])}
</button>
<button onClick={() => squareClicked(8)} className="square">
{valueDecider(gamestate.grid[8])}
</button>
</div>
</div>
)
}<file_sep>/README.md
# tic-tac-toe
A multiplayer tic tac toe application.
- Frontend built using ReactJS, Material UI and vanilla CSS.
- Backend built using NodeJS and Socket.IO library for websockets.
Deployed at: https://rohit-tic-tac-toe.herokuapp.com/
<file_sep>/client/src/components/JoinSession.js
import React, { useState, useEffect } from 'react';
import Button from '@material-ui/core/Button';
import Alert from '@material-ui/lab/Alert';
import Snackbar from '@material-ui/core/Snackbar';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
//import io from 'socket.io-client';
import socket from '../api/port';
export default function JoinSession() {
const [isDialogOpen, setDialogOpen] = useState(false);
const [username, setUsername] = useState('');
const [roomKey, setRoomKey] = useState('');
const [invalid, setInvalid] = useState(false);
const [incomplete, setIncomplete] = useState(false);
const handleClickOpen = () => {
setDialogOpen(true);
};
const handleClose = () => {
setDialogOpen(false);
setIncomplete(false);
};
const handleSumbit = (event) => {
// Logic to Come Here
if (username !== '' && roomKey !== '') {
setDialogOpen(false);
setIncomplete(false);
socket.emit("join-session", roomKey, username);
} else {
event.preventDefault();
setIncomplete(true);
}
};
useEffect(() => {
socket.on("invalid-roomkey", () => {
setInvalid(true);
})
}, [])
const handleSnackBarClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setInvalid(false);
};
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handleRoomKeyChange = (event) => {
setRoomKey(event.target.value);
};
return (
<div>
<Button variant="contained" size="large" color="primary" onClick={handleClickOpen}>
Join a Session
</Button>
<Snackbar
open={invalid}
autoHideDuration={6000}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
onClose={handleSnackBarClose}
>
<Alert variant="filled" severity="error">Invalid Room Key. Please try again.</Alert>
</Snackbar>
<Dialog open={isDialogOpen} onClose={handleClose} aria-labelledby="form-dialog-create-session">
{incomplete && <Alert severity="error">Please enter username & room key</Alert>}
<DialogTitle id="form-dialog-title">Join a Session</DialogTitle>
<DialogContent>
<DialogContentText>
To join a session, please enter your username and room key
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="username"
label="Username"
type="text"
fullWidth
required
value={username}
onChange={handleUsernameChange}
/>
<TextField
margin="dense"
id="roomkey"
label="Room Key"
type="text"
fullWidth
required
value={roomKey}
onChange={handleRoomKeyChange}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button onClick={handleSumbit} color="primary">
Join
</Button>
</DialogActions>
</Dialog>
</div>
);
}
<file_sep>/client/src/components/MainContainer.js
import React, { useState, useEffect } from 'react';
import socket from '../api/port'
import Landing from './Landing';
import Lobby from './Lobby';
export default function Container() {
const [landing, setLanding] = useState(true);
const [lobby, setlobby] = useState(false);
const [waiting, setWaiting] = useState(true);
const [roomKey, setRoomKey] = useState('');
const [isp1, setIsp1] = useState(false);
const [gameState, setGameState] = useState({
p1_name: "",
p2_name: "",
p1_score: 0,
p2_score: 0,
ties: 0,
p1_turn: true,
grid: [0, 0, 0, 0, 0, 0, 0, 0, 0]
})
useEffect(() => {
socket.on("session-created", (name, newRoomKey) => {
setGameState(prevState => ({
...prevState,
p1_name: name
}));
setRoomKey(newRoomKey);
setLanding(false);
setlobby(true);
setIsp1(true);
});
socket.on("valid-code", (gameState) => {
setGameState(gameState);
setWaiting(false);
setLanding(false);
setlobby(true);
})
}, []);
return (
<div>
{landing && <Landing />}
{lobby && <Lobby gameState={gameState} roomKey={roomKey} waiting={waiting} isp1={isp1} />}
</div>
)
}
|
7df9de08eec0212d45adcc8ab37bb17dfe50d6a5
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
rbajaj1997/tic-tac-toe
|
b735bd9c2540a61c7982e74d968e40d562ac9fc6
|
21077fc3aa3229e94cd7f6c9fe59f571e2438bba
|
refs/heads/master
|
<repo_name>Magsun/YouTube8M_tools<file_sep>/data_transform.py
# tensorflow=1.14
import tensorflow as tf
import glob, os
import numpy
def _make_bytes(int_array):
if bytes == str: # Python2
return ''.join(map(chr, int_array))
else:
return bytes(int_array)
def quantize(features, min_quantized_value=-2.0, max_quantized_value=2.0):
"""Quantizes float32 `features` into string."""
assert features.dtype == 'float32'
assert len(features.shape) == 1 # 1-D array
features = numpy.clip(features, min_quantized_value, max_quantized_value)
quantize_range = max_quantized_value - min_quantized_value
features = (features - min_quantized_value) * (255.0 / quantize_range)
features = [int(round(f)) for f in features]
return _make_bytes(features)
# for parse feature.pb
contexts = {
'AUDIO/feature/dimensions': tf.io.FixedLenFeature([], tf.int64),
'AUDIO/feature/rate': tf.io.FixedLenFeature([], tf.float32),
'RGB/feature/dimensions': tf.io.FixedLenFeature([], tf.int64),
'RGB/feature/rate': tf.io.FixedLenFeature([], tf.float32),
'clip/data_path': tf.io.FixedLenFeature([], tf.string),
'clip/end/timestamp': tf.io.FixedLenFeature([], tf.int64),
'clip/start/timestamp': tf.io.FixedLenFeature([], tf.int64)
}
features = {
'AUDIO/feature/floats': tf.io.VarLenFeature(dtype=tf.float32),
'AUDIO/feature/timestamp': tf.io.VarLenFeature(tf.int64),
'RGB/feature/floats': tf.io.VarLenFeature(dtype=tf.float32),
'RGB/feature/timestamp': tf.io.VarLenFeature(tf.int64)
}
def parse_exmp(serial_exmp):
_, sequence_parsed = tf.io.parse_single_sequence_example(
serialized=serial_exmp,
context_features=contexts,
sequence_features=features)
sequence_parsed = tf.contrib.learn.run_n(sequence_parsed)[0]
audio = sequence_parsed['AUDIO/feature/floats'].values
rgb = sequence_parsed['RGB/feature/floats'].values
# print(audio.values)
# print(type(audio.values))
# audio is 128 8bit, rgb is 1024 8bit for every second
audio_slices = [audio[128 * i: 128 * (i + 1)] for i in range(len(audio) // 128)]
rgb_slices = [rgb[1024 * i: 1024 * (i + 1)] for i in range(len(rgb) // 1024)]
byte_audio = []
byte_rgb = []
for seg in audio_slices:
audio_seg = quantize(seg)
byte_audio.append(audio_seg)
for seg in rgb_slices:
rgb_seg = quantize(seg)
byte_rgb.append(rgb_seg)
return byte_audio, byte_rgb
def make_exmp(id, labels, audio, rgb):
audio_features = []
rgb_features = []
for embedding in audio:
embedding_feature = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[embedding]))
audio_features.append(embedding_feature)
for embedding in rgb:
embedding_feature = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[embedding]))
rgb_features.append(embedding_feature)
# for construct yt8m data
seq_exmp = tf.train.SequenceExample(
context=tf.train.Features(
feature={
'id': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[id.encode('utf-8')])),
'labels': tf.train.Feature(int64_list=tf.train.Int64List(
value=[labels]))
}),
feature_lists=tf.train.FeatureLists(
feature_list={
'audio': tf.train.FeatureList(
feature=audio_features
),
'rgb': tf.train.FeatureList(
feature=rgb_features
)
})
)
serialized = seq_exmp.SerializeToString()
return serialized
if __name__ == '__main__':
filename = 'feature.pb'
sequence_example = open(filename, 'rb').read()
audio, rgb = parse_exmp(sequence_example)
id = 'test_001'
labels = 1
tmp_example = make_exmp(id, labels, audio, rgb)
decoded = tf.train.SequenceExample.FromString(tmp_example)
print(decoded)
# then you can write tmp_example to tfrecord files
<file_sep>/batch_convert.py
import os, sys, re, subprocess as sb
import feature_extractor # old version
import tensorflow as tf
import glob
import numpy
import cv2
import shutil
"""
2 kinds of video:
1. video with audio --> use new extractor which extracts rgb&audio. *default*
2. video without audio --> use old extractor which only extracts rgb and put 0 into audio
"""
# old version
model_dir = '/data/thunder_video/ucf101/thunder/extract_model'
def _int64_feature(value):
"""Wrapper for inserting an int64 Feature into a SequenceExample proto."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
"""Wrapper for inserting a bytes Feature into a SequenceExample proto."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature_list(values):
"""Wrapper for inserting an int64 FeatureList into a SequenceExample proto."""
return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])
def _int64_list_feature(int64_list):
return tf.train.Feature(int64_list=tf.train.Int64List(value=int64_list))
def _bytes_feature_list(values):
"""Wrapper for inserting a bytes FeatureList into a SequenceExample proto."""
return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])
def _make_bytes(int_array):
if bytes == str: # Python2
return ''.join(map(chr, int_array))
else:
return bytes(int_array)
def quantize(features, min_quantized_value=-2.0, max_quantized_value=2.0):
"""Quantizes float32 `features` into string."""
assert features.dtype == 'float32'
assert len(features.shape) == 1 # 1-D array
features = numpy.clip(features, min_quantized_value, max_quantized_value)
quantize_range = max_quantized_value - min_quantized_value
features = (features - min_quantized_value) * (255.0 / quantize_range)
features = [int(round(f)) for f in features]
return _make_bytes(features)
def Dequantize(feat_vector, max_quantized_value=2, min_quantized_value=-2):
"""
Dequantize the feature from the byte format to the float format.
Args:
feat_vector: the input 1-d vector.
max_quantized_value: the maximum of the quantized value.
min_quantized_value: the minimum of the quantized value.
Returns:
A float vector which has the same shape as feat_vector.
"""
assert max_quantized_value > min_quantized_value
quantized_range = max_quantized_value - min_quantized_value
scalar = quantized_range / 255.0
bias = (quantized_range / 512.0) + min_quantized_value
return feat_vector * scalar + bias
def check_converted(file_name, dst_path):
"""
:param file_name: filename with full path
:param dst_path: tfrecord save path
:return: flag of converted or new file
"""
base_name = file_name.split('/')[-1]
base_name = base_name.split('.')[0]
dst_file = os.path.join(dst_path, base_name + '.tfrecord')
return os.path.exists(dst_file)
##### old version just extract rgb feature and put 0 verc in audio feature list
# In OpenCV3.X, this is available as cv2.CAP_PROP_POS_MSEC
# In OpenCV2.X, this is available as cv2.cv.CV_CAP_PROP_POS_MSEC
CAP_PROP_POS_MSEC = 0
def frame_iterator(filename, max_num_frames=300):
"""Uses OpenCV to iterate over all frames of filename at a given frequency.
Args:
filename: Path to video file (e.g. mp4)
every_ms: The duration (in milliseconds) to skip between frames.
max_num_frames: Maximum number of frames to process, taken from the
beginning of the video.
Yields:
RGB frame with shape (image height, image width, channels)
"""
video_capture = cv2.VideoCapture()
if not video_capture.open(filename):
print >> sys.stderr, 'Error: Cannot open video file ' + filename
return
last_ts = -99999 # The timestamp of last retrieved frame.
num_retrieved = 0
# Find OpenCV version
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver) < 3:
fps = video_capture.get(cv2.cv.CV_CAP_PROP_FPS)
print("Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps))
else:
fps = video_capture.get(cv2.CAP_PROP_FPS)
print("Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps))
every_ms = 1000.0 / fps
while num_retrieved < max_num_frames:
# Skip frames
while video_capture.get(CAP_PROP_POS_MSEC) < every_ms + last_ts:
if not video_capture.read()[0]:
return
last_ts = video_capture.get(CAP_PROP_POS_MSEC)
has_frames, frame = video_capture.read()
if not has_frames:
break
yield frame
num_retrieved += 1
def extract_rgb(video_file, output_tfrecords_file, labels, id,
model_dir=model_dir,
insert_zero_audio_features=True,
skip_frame_level_features=False):
extractor = feature_extractor.YouTube8MFeatureExtractor(model_dir)
writer = tf.python_io.TFRecordWriter(output_tfrecords_file)
total_written = 0
total_error = 0
rgb_features = []
sum_rgb_features = None
for rgb in frame_iterator(video_file):
features = extractor.extract_rgb_frame_features(rgb[:, :, ::-1])
if sum_rgb_features is None:
sum_rgb_features = features
else:
sum_rgb_features += features
rgb_features.append(_bytes_feature(quantize(features)))
if not rgb_features:
print('Could not get features for ' + video_file)
return
mean_rgb_features = sum_rgb_features / len(rgb_features)
# Create SequenceExample proto and write to output.
feature_list = {
'rgb': tf.train.FeatureList(feature=rgb_features),
}
context_features = {
'labels':
_int64_list_feature([labels]),
'id':
_bytes_feature(_make_bytes(id.encode('utf-8'))),
'mean_rgb':
tf.train.Feature(
float_list=tf.train.FloatList(value=mean_rgb_features)),
}
if insert_zero_audio_features:
zero_vec = [0] * 128
feature_list['audio'] = tf.train.FeatureList(
feature=[_bytes_feature(_make_bytes(zero_vec))] * len(rgb_features))
context_features['mean_audio'] = tf.train.Feature(
float_list=tf.train.FloatList(value=zero_vec))
if skip_frame_level_features:
example = tf.train.SequenceExample(
context=tf.train.Features(feature=context_features))
else:
example = tf.train.SequenceExample(
context=tf.train.Features(feature=context_features),
feature_lists=tf.train.FeatureLists(feature_list=feature_list))
print(example)
writer.write(example.SerializeToString())
total_written += 1
writer.close()
print('Successfully encoded %i out of %i videos' %
(total_written, total_written + total_error))
##### new extractor for mediapipe converted feature.pb include both rgb&audio features
contexts = {
'AUDIO/feature/dimensions': tf.io.FixedLenFeature([], tf.int64),
'AUDIO/feature/rate': tf.io.FixedLenFeature([], tf.float32),
'RGB/feature/dimensions': tf.io.FixedLenFeature([], tf.int64),
'RGB/feature/rate': tf.io.FixedLenFeature([], tf.float32),
'clip/data_path': tf.io.FixedLenFeature([], tf.string),
'clip/end/timestamp': tf.io.FixedLenFeature([], tf.int64),
'clip/start/timestamp': tf.io.FixedLenFeature([], tf.int64)
}
features = {
'AUDIO/feature/floats': tf.io.VarLenFeature(dtype=tf.float32),
'AUDIO/feature/timestamp': tf.io.VarLenFeature(tf.int64),
'RGB/feature/floats': tf.io.VarLenFeature(dtype=tf.float32),
'RGB/feature/timestamp': tf.io.VarLenFeature(tf.int64)
}
def parse_exmp(serial_exmp):
_, sequence_parsed = tf.io.parse_single_sequence_example(
serialized=serial_exmp,
context_features=contexts,
sequence_features=features)
sequence_parsed = tf.contrib.learn.run_n(sequence_parsed)[0]
# audio : [10, 128]
# rgb : [10, 1024]
audio = sequence_parsed['AUDIO/feature/floats'].values
rgb = sequence_parsed['RGB/feature/floats'].values
# print(audio.values)
# print(type(audio.values))
audio_slices = [audio[128 * i: 128 * (i + 1)] for i in range(len(audio) // 128)]
rgb_slices = [rgb[1024 * i: 1024 * (i + 1)] for i in range(len(rgb) // 1024)]
byte_audio = []
byte_rgb = []
for seg in audio_slices:
audio_seg = quantize(seg)
byte_audio.append(audio_seg)
for seg in rgb_slices:
rgb_seg = quantize(seg)
byte_rgb.append(rgb_seg)
return byte_audio, byte_rgb
def make_exmp(id, labels, audio, rgb):
audio_features = []
rgb_features = []
for embedding in audio:
embedding_feature = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[embedding]))
audio_features.append(embedding_feature)
for embedding in rgb:
embedding_feature = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[embedding]))
rgb_features.append(embedding_feature)
seq_exmp = tf.train.SequenceExample(
context=tf.train.Features(
feature={
'id': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[id.encode('utf-8')])),
'labels': tf.train.Feature(int64_list=tf.train.Int64List(
value=[labels]))
}),
feature_lists=tf.train.FeatureLists(
feature_list={
'audio': tf.train.FeatureList(
feature=audio_features
),
'rgb': tf.train.FeatureList(
feature=rgb_features
)
})
)
serialized = seq_exmp.SerializeToString()
return serialized
def single_convert(file_name, tmp_dir, dst_dir, rgb_dir, rgb_dst, labels):
full_name = file_name.split('/')[-1]
base_name = full_name.split('.')[0]
# new steps
step_1 = 'python -m mediapipe.examples.desktop.youtube8m.generate_input_sequence_example \
--path_to_input_video=' + file_name + '\
--clip_end_time_sec=10'
# print(step_1)
(status, output) = sb.getstatusoutput(step_1) # 获得shell命令执行后的状态status和控制台的所有输出output
# status:表示执行程序结果状态,值是0表示执行成功。
# output:就是打印到控制台一个以\n为拼接的字符串。
print(output)
if status == 0:
step_2 = 'GLOG_logtostderr=1 /root/.cache/bazel/_bazel_root/4884d566396e9b67b62185751879ad14/execroot/mediapipe/bazel-out/k8-opt/bin/mediapipe/examples/desktop/youtube8m/extract_yt8m_features \
--calculator_graph_config_file=/mediapipe/mediapipe/graphs/youtube8m/feature_extraction.pbtxt \
--input_side_packets=input_sequence_example=/tmp/mediapipe/metadata.pb \
--output_side_packets=output_sequence_example=' + tmp_dir + base_name + '.pb'
(status2, output2) = sb.getstatusoutput(step_2) # 获得shell命令执行后的状态status和控制台的所有输出output
print(output2)
print(status2)
no_audio = 'Could not find audio stream'
if no_audio in output2 or status2 == 1:
print('*********************************** no audio found! ***********************************')
print('*********************************** transform error! ***********************************')
print('*********************************** use old version! ***********************************')
# move only rgb video to another dir
rgb_file = os.path.join(rgb_dir, full_name)
shutil.move(file_name, rgb_file)
# convert
dst_name = base_name + '.tfrecord'
file_dst = os.path.join(rgb_dst, dst_name)
extract_rgb(rgb_file, file_dst, labels, base_name)
else:
filename = tmp_dir + base_name + '.pb'
sequence_example = open(filename, 'rb').read()
audio, rgb = parse_exmp(sequence_example)
id = base_name
tmp_example = make_exmp(id, labels, audio, rgb)
decoded = tf.train.SequenceExample.FromString(tmp_example)
print(decoded)
writer = tf.python_io.TFRecordWriter(dst_dir + id + '.tfrecord')
writer.write(tmp_example)
def batch_convert(data_root, tmp_dir, dst_dir, rgb_dir, rgb_dst, labels):
for file_name in glob.glob(data_root + '/*.mp4'):
# check converted or not
all_flag = check_converted(file_name, dst_dir)
rgb_flag = check_converted(file_name, rgb_dst)
if not all_flag and not rgb_flag:
single_convert(file_name, tmp_dir, dst_dir, rgb_dir, rgb_dst, labels)
if __name__ == '__main__':
# common
# data_root = '/data/rain_video/src_video'
data_root = '/data/thunder_video/ucf101/nothunder/'
tmp_dir = '/data/thunder_video/tmp_pb/'
dst_dir = '/data/thunder_video/tfrecord/nothunder/'
rgb_dst = '/data/thunder_video/tfrecord/rgb_nothunder/'
rgb_dir = '/data/thunder_video/ucf101/rgb_nothunder/'
# file_name = '/data/thunder_video/tmp_pb/thunder_0002.mp4' # no audio video
# file_name = '/data/thunder_video/ucf101/rgb_thunder/thunder_0002.mp4'
# print(base_name)
label_dict = {'positive': 0, 'negative': 1}
labels = 1 # positive=0 negative=1
batch_convert(data_root, tmp_dir, dst_dir, rgb_dir, rgb_dst, labels)
# only for new version
# for file_name in glob.glob(data_root + '/rain*.mp4'):
# for file_name in glob.glob(data_root + '/thunder_*.mp4'):
# # print(file_name)
#
# base_name = file_name.split('/')[-1]
# base_name = base_name.split('.')[0]
# # print(base_name)
#
#
#
# step_1 = 'python -m mediapipe.examples.desktop.youtube8m.generate_input_sequence_example \
# --path_to_input_video=' + file_name + '\
# --clip_end_time_sec=10'
#
# # print(step_1)
#
# (status, output) = sb.getstatusoutput(step_1) # 获得shell命令执行后的状态status和控制台的所有输出output
# # status:表示执行程序结果状态,值是0表示执行成功。
# # output:就是打印到控制台一个以\n为拼接的字符串。
# print(output)
#
# if status == 0:
# step_2 = 'GLOG_logtostderr=1 bazel-bin/mediapipe/examples/desktop/youtube8m/extract_yt8m_features \
# --calculator_graph_config_file=mediapipe/graphs/youtube8m/feature_extraction.pbtxt \
# --input_side_packets=input_sequence_example=/tmp/mediapipe/metadata.pb \
# --output_side_packets=output_sequence_example=' + tmp_dir + base_name + '.pb'
# (status, output) = sb.getstatusoutput(step_2) # 获得shell命令执行后的状态status和控制台的所有输出output
# print(output)
#
# filename = tmp_dir + base_name + '.pb'
#
# dst_dir = '/data/thunder_video/tfrecord/thunder/'
#
# sequence_example = open(filename, 'rb').read()
#
# audio, rgb = parse_exmp(sequence_example)
#
# id = base_name
#
# labels = 0 # positive=0 negative=1
#
# tmp_example = make_exmp(id, labels, audio, rgb)
#
# decoded = tf.train.SequenceExample.FromString(tmp_example)
# print(decoded)
#
# writer = tf.python_io.TFRecordWriter(dst_dir + base_name + '.tfrecord')
# writer.write(tmp_example)
<file_sep>/README.md
# YouTube8M_tools
Convert feature.pb to yt8m style tfrecord
1. This is a simple tool for data transformation of mediapipe feature.pb to yt8m tfrecord.
2. The version of mediapipe is 0.7.4, tensorflow=1.14.
3. Source data of this tool is feature.pb extracted from local video including auio&rgb features.
Kindly contact if any quesitons. lol
###################### updated 2020/06/23 ##########################
Newly added one script that can run under docker container mediapipe.
It helps you convert multiple files into single tfrecord.
p.s. now only works for video with audio, I'm working on script works for video without audio.
###################### updated 2020/06/29 ##########################
Now this script can process videos with or without audio in it.
Hint: need to modify the absolute path of bazel-bin and calculator_graph_config_file before you run the script.
|
3f915a0198d097a4f4e72ecef31c0e1eabdb2ef5
|
[
"Markdown",
"Python"
] | 3
|
Python
|
Magsun/YouTube8M_tools
|
c1e808887afb754e78323c02551ac2a0b679e7f0
|
fd6b89ee00eaaaa019ea8b126c2385488643a62c
|
refs/heads/master
|
<file_sep>import {Component, Input} from '@angular/core';
@Component({
selector: 'app-person-grid',
templateUrl: './app-person-grid.component.html',
styleUrls: ['./app-person-grid.component.css']
})
export class AppPersonGridComponent {
@Input() persons = [];
}
<file_sep>import {Component} from '@angular/core';
import {SelectItem} from 'primeng/primeng';
@Component({
selector: 'app-person-register',
templateUrl: './app-person-register.component.html',
styleUrls: ['./app-person-register.component.css']
})
export class AppPersonRegisterComponent {
status: SelectItem[];
val: string;
constructor() {
this.status = [];
this.status.push({label: 'Active', value: true});
this.status.push({label: 'Inactive', value: false});
}
createPerson() {
}
}
<file_sep>import {Component} from '@angular/core';
@Component({
selector: 'app-nav-bar',
templateUrl: './app-nav-bar.component.html',
styleUrls: ['./app-nav-bar.component.css']
})
export class AppNavBarComponent {
showMenu = false;
toggleMenu() {
this.showMenu = !this.showMenu;
}
}
<file_sep>import {NgModule} from '@angular/core';
import {
CalendarModule,
DataTableModule,
DropdownModule,
InputMaskModule,
InputTextareaModule,
SelectButtonModule,
TabViewModule,
TooltipModule
} from 'primeng/primeng';
// acording the PrimeNG documentation it could be better import the compoments one by one
import {InputTextModule} from 'primeng/components/inputtext/inputtext';
import {ButtonModule} from 'primeng/components/button/button';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {CurrencyMaskModule} from 'ng2-currency-mask';
import {FormsModule} from '@angular/forms';
import {CommonModule} from '@angular/common';
import {AppPersonGridComponent} from './app-person-grid/app-person-grid.component';
import {AppPersonRegisterComponent} from './app-person-register/app-person-register.component';
import {AppPersonsSearchComponent} from './app-persons-search/app-persons-search.component';
import {SharedModule} from '../shared/shared.module';
import {PersonsService} from './persons.service';
@NgModule({
imports: [
CommonModule,
FormsModule
, TabViewModule
, InputTextModule
, ButtonModule
, DataTableModule
, TooltipModule
, InputTextareaModule
, CalendarModule
, BrowserAnimationsModule
, SelectButtonModule
, DropdownModule
, InputMaskModule
, CurrencyMaskModule
, SharedModule
],
providers: [PersonsService],
declarations: [AppPersonGridComponent, AppPersonRegisterComponent, AppPersonsSearchComponent],
exports: [AppPersonsSearchComponent, AppPersonRegisterComponent]
})
export class PersonsModule { }
<file_sep>import { Injectable } from '@angular/core';
import {Headers, Http, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import * as moment from 'moment';
export class PersonFilter {
name: string;
page = 0;
size = 0;
}
@Injectable()
export class PersonsService {
url = 'http://localhost:8080/persons';
constructor(private http: Http) { }
search(filter: PersonFilter = new PersonFilter()): Promise <any[]> {
const params = new URLSearchParams();
const headers = new Headers();
if (filter.name) {
params.set('name', filter.name);
}
headers.append('Authorization', 'Basic YWRtaW46YWRtaW4=');
return this.http.get(`${this.url}`, { headers, search: params })
.toPromise()
.then(response => {
console.log('result:: ' + response.json());
return response.json();
});
}
public all(): Promise<any[]> {
const headers = new Headers();
headers.append('Authorization', 'Basic YWRtaW46YWRtaW4=');
return this.http.get(`${this.url}`, { headers })
.toPromise()
.then(response => response.json());
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {AppNavBarComponent} from './app-nav-bar/app-nav-bar.component';
@NgModule({
imports: [
CommonModule
],
declarations: [AppNavBarComponent],
exports: [AppNavBarComponent]
})
export class CoreModule { }
<file_sep>import {Injectable} from '@angular/core';
import {Headers, Http, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import * as moment from 'moment';
export class ActivityFilter {
description: string;
dueStartDate: Date;
dueEndDate: Date;
page = 0;
size = 3;
}
export interface ActivitySearchPage {
activities: any[];
totalElements: number;
}
export interface ActivitySummary {
code: string;
description: string;
observation: string;
payday: Date;
maturity: Date;
value: number;
type: string; // enum
categoryName: string;
personName: string;
}
@Injectable()
export class ActivityService {
url = 'http://localhost:8080/activities';
constructor(private http: Http) { }
search(filter: ActivityFilter): Promise<ActivitySearchPage> {
const params = new URLSearchParams();
const headers = new Headers();
if (filter.page) {
params.set('page', filter.page.toString(10));
}
if (filter.size) {
params.set('size', filter.size.toString());
}
if (filter.description) {
params.set('description', filter.description);
}
if (filter.dueStartDate) {
params.set('maturityFrom', moment(filter.dueStartDate).format('YYYY-MM-DD'));
}
if (filter.dueEndDate) {
params.set('maturityTo', moment(filter.dueEndDate).format('YYYY-MM-DD'));
}
headers.append('Authorization', 'Basic YWRtaW46YWRtaW4=');
return this.http.get(`${this.url}?summary`, { headers, search: params })
.toPromise()
.then(response => {
console.log('result:: ' + response.json().content);
const responseBody = response.json();
const result = {
activities: responseBody.content,
totalElements: responseBody.totalElements
};
// return response.json().content;
return result;
});
}
delete (code: string): Promise<void> {
const headers = new Headers();
headers.append('Authorization', 'Basic YWRtaW46YWRtaW4=');
return this.http.delete(`${this.url}/${code}`, { headers })
.toPromise()
.then(result => null);
}
}
<file_sep>import {Component} from '@angular/core';
import {SelectItem} from 'primeng/primeng';
@Component({
selector: 'app-activity-register',
templateUrl: './app-activity-register.component.html',
styleUrls: ['./app-activity-register.component.css']
})
export class AppActivityRegisterComponent {
types: SelectItem[];
categories = [
{ label: 'Alimentation', value: 1 },
{ label: 'Transport', value: 2 },
];
persons = [
{ label: '<NAME>', value: 3 },
{ label: '<NAME>', value: 2 },
{ label: '<NAME>', value: 1 }
];
constructor() {
this.types = [];
this.types.push({label: 'Recipe', value: 'RECIPE'});
this.types.push({label: 'Expense', value: 'EXPENSE'});
}
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { LazyLoadEvent } from 'primeng/components/common/api';
import { ConfirmationService } from 'primeng/primeng';
import { ToastyService } from 'ng2-toasty';
import { ActivityFilter, ActivityService } from '../activity.service';
@Component({
selector: 'app-activities-search',
templateUrl: './app-activities-search.component.html',
styleUrls: ['./app-activities-search.component.css']
})
export class AppActivitiesSearchComponent implements OnInit {
activities = [];
totalActivities = 0;
filter: ActivityFilter = new ActivityFilter();
@ViewChild('activitiesTable') activitiesGrid;
constructor(
private activityService: ActivityService,
private toasty: ToastyService,
private confirmationService: ConfirmationService) {}
ngOnInit(): void {}
search(page = 0) {
this.filter.page = page;
this.activityService.search(this.filter)
.then(b => {
this.activities = b.activities;
this.totalActivities = b.totalElements;
});
}
onPageChange(event: LazyLoadEvent) {
const page = event.first / event.rows;
this.search(page);
}
delete (activity: any) {
console.log(JSON.stringify(activity));
this.confirmationService.confirm({
header: 'Delete Confirmation',
icon: 'fa fa-trash',
message: 'Do you want to delete this record?',
accept: () => {
this.onConfirmDelete(activity);
}
});
}
onConfirmDelete(activity) {
console.log(JSON.stringify(activity));
this.activityService.delete(activity.code).then(() => {
// this.activityService.search(this.filter);
// we don't need the search method because by reset the grid paginantion we are going to execute the lazy load
if (this.activitiesGrid.first === 0) {
this.search();
} else {
this.activitiesGrid.first = 0;
}
// add message to display notification
this.toasty.success('Activity deleted successfully!');
});
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {PersonsService} from '../persons.service';
@Component({
selector: 'app-persons-search',
templateUrl: './app-persons-search.component.html',
styleUrls: ['./app-persons-search.component.css']
})
export class AppPersonsSearchComponent implements OnInit {
persons: any[] = [];
constructor(private personsServices: PersonsService) {}
ngOnInit(): void {
this.personsServices.search().then(ps => {
this.persons = ps;
});
}
}
<file_sep>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {AppActivitiesSearchComponent} from './app-activities-search/app-activities-search.component';
import {AppActivityRegisterComponent} from './app-activity-register/app-activity-register.component';
import {FormsModule} from '@angular/forms';
import {
ButtonModule,
CalendarModule,
DataTableModule,
DropdownModule,
InputMaskModule,
InputTextModule,
SelectButtonModule,
SharedModule,
TabViewModule,
TooltipModule
} from 'primeng/primeng';
import {InputTextareaModule} from 'primeng/components/inputtextarea/inputtextarea';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {CurrencyMaskModule} from 'ng2-currency-mask';
import {SharedModule as AppSharedModule} from '../shared/shared.module';
import {ActivityService} from "./activity.service";
@NgModule({
imports: [
CommonModule
, FormsModule
, TabViewModule
, InputTextModule
, ButtonModule
, DataTableModule
, SharedModule
, TooltipModule
, InputTextareaModule
, CalendarModule
, BrowserAnimationsModule
, SelectButtonModule
, DropdownModule
, InputMaskModule
, CurrencyMaskModule
, AppSharedModule
],
providers: [ActivityService],
declarations: [
AppActivitiesSearchComponent, AppActivityRegisterComponent
],
exports: [AppActivitiesSearchComponent, AppActivityRegisterComponent]
})
export class ActivitiesModule { }
<file_sep>import {BrowserModule} from '@angular/platform-browser';
import {NgModule, LOCALE_ID} from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {HttpModule} from '@angular/http';
import { ToastyModule } from 'ng2-toasty';
import {ConfirmDialogModule, ConfirmationService} from 'primeng/primeng';
import {AppComponent} from './app.component';
import {AppNavBarComponent} from './core/app-nav-bar/app-nav-bar.component';
import {PersonsModule} from './persons/persons.module';
import {ActivitiesModule} from './activities/activities.module';
import {CoreModule} from './core/core.module';
// acording the PrimeNG documentation it could be better import the compoments one by one
// import {InputTextModule} from 'primeng/components/inputtext/inputtext';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
, BrowserAnimationsModule
, HttpModule
, ToastyModule.forRoot()
, ConfirmDialogModule
, CoreModule
, PersonsModule
, ActivitiesModule
],
providers: [
ConfirmationService
, { provide: LOCALE_ID, useValue: 'en-US' }
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
5b78ffb2132f33e071795eefe6e5446a7985a64f
|
[
"TypeScript"
] | 12
|
TypeScript
|
jlmc/x-money-ui
|
f3b4d509680012663c53f56eb1dc96ee2e9c34f2
|
6f2365cfe590cff3c08971a0f5ccf926a895005e
|
refs/heads/master
|
<file_sep>/* npm run dev */
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/burgers', (req, res) => {
res.send('We have juicy cheese burgers!');
});
app.get('/pizza/pepperoni', (req, res) => {
res.send('Your pizza is on the way!');
});
app.get('/pizza/pineapple', (req, res) => {
res.send("We don't serve that here. Never call again!");
});
app.get('/echo', (req, res) => {
const responseText = `Here are some details of your request:
Base URL: ${req.baseUrl}
Host: ${req.hostname}
Path: ${req.path}
IP: ${req.ip}
`;
res.send(responseText);
});
app.get('/sum', (req, res) => {
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
if (!a) {
return res.status(400).send('Please enter a first number');
}
if (!b) {
return res.status(400).send('Please enter a second number');
}
const total = a + b;
const message = `The sum of ${a} and ${b} is ${total}.`;
res.send(message);
});
app.get('/greetings', (req, res) => {
//1. get values from the request
const name = req.query.name;
const race = req.query.race;
//2. validate the values
if(!name) {
//3. name was not provided
return res.status(400).send('Please provide a name');
}
if(!race) {
//3. race was not provided
return res.status(400).send('Please provide a race');
}
//4. and 5. both name and race are valid so do the processing.
const greeting = `Greetings ${name} the ${race}, you are not welcome to our kingdom.`;
//6. send the response
res.send(greeting);
});
app.get('/queryViewer', (req, res) => {
console.log(req.query);
res.end();
});
app.get('/cipher', (req, res) => {
const text = req.query.text;
const shift = parseInt(req.query.shift);
if (!text) {
return res.status(400).send('Please enter some text');
}
if (!shift) {
return res.status(400).send('Please enter a shift amount');
}
const regex = /./g;
let coded = text.replace(regex, (c) => {
return String.fromCharCode(c.charCodeAt(0) + shift);
});
res.send(coded);
});
app.get('/lotto', (req, res) => {
const { numbers } = req.query;
if (!numbers) {
return res.status(400).send('Please enter some numbers');
}
if (numbers.length != 6) {
return res.status(400).send('Please enter atleast 6 numbers');
}
const min = 1, max = 20, randomArr=[], foundArr=[];
let message = '';
while(randomArr.length < 6) {
let randomNum = Math.floor(Math.random() * (+max - +min))
if (!randomArr.includes(randomNum)) {
randomArr.push(randomNum);
}
};
numbers.map((number) => {
if (randomArr.includes(parseInt(number))) {
foundArr.push(number)
}
});
console.log('found: ', foundArr);
switch(foundArr.length){
case 6:
message = 'Wow! Unbelievable! You could have won the mega millions!';
break;
case 5:
message = 'Congratulations! You won $100!';
break;
case 4:
message = 'Congratulations, you win a free ticket!';
break;
default:
message = 'Sorry, you lose!';
}
res.send(message);
});
app.get('/hello', (req, res) => {
res
.status(200)
.send('Hello!!!');
});
app.get('/error', (req, res) => {
res.status(500).send('There was an issue!');
});
app.get('/nothing', (req, res) => {
res
.status(204)
.end();
});
app.get('/video', (req, res) => {
const video = {
title: 'Cats falling over',
description: '15 minutes of great videos',
length: '15.40'
};
res.json(video)
})
app.get('/colors', (req, res) => {
const colors = [
{
name: "red",
rgb: "FF0000"
},
{
name: "blue",
rgb: "0000FF"
},
{
name: "green",
rgb: "00FF00"
},
];
res.json(colors);
})
app.get('/grade', (req, res) => {
// get the mark from the query
const { mark } = req.query;
// do some validation
if(!mark) {
// mark is required
return res
.status(400)
.send("Please provide a mark");
}
const numericMark = parseFloat(mark);
if(Number.isNaN(numericMark)) {
// mark must be a number
return res
.status(400)
.send("Mark must be a numeric value");
}
if(numericMark < 0 || numericMark > 100) {
// mark must be in range 0 to 100
return res
.status(400)
.send("Mark must be in range 0 to 100");
}
if(numericMark >= 90) {
return res
.send("A");
}
if(numericMark => 80) {
return res
.send("B");
}
if(numericMark >= 70) {
return res
.send("C");
}
res
.send("F");
});
app.listen(8000, () => {
console.log('Express server is listening on port 8000!')
});
|
9478ba6c401d76922da0bcc452fd358a0a52f16d
|
[
"JavaScript"
] | 1
|
JavaScript
|
matrayu/express_modules
|
61f152e3bfc243fca7389e35d7fb36cc3b4030ee
|
43095833ce9ae99d3ba15e98ada77d861587b9f9
|
refs/heads/master
|
<file_sep># if ("hello" == "hello" or 3 == 8 or "brighticorn" == "code"):
# print "welcome to class today!"
# else:
# print "nothing is equal"
# x = 3
# if x == 3:
# x = 4
# if x == 4:
# print "x is 4"
# else:
# x = 10
# print "x is 10"
# input = raw_input("Do you know who Brighticorn is?")
# if (str.lower(input) == "yes"):
# print "Great! She is a wonderful mascot"
# else:
# print "Brighticorn is the Part Time Course Mascot!"
# "Defining" the function
# def my_function(name):
# return "This is " + name + "'s function!"
# # "Calling" the function
# print my_function("Brighticorn")
# print my_function("Molly")
# def find_average(num1, num2):
# total = num1 + num2
# average = total / 2
# return average
# def add(num1, num2):
# return num1 + num2
# def average(num1, num2):
# return add(num1, num2) / 2
# print average(5, 7)
# def average(num1, num2):
# return add(num1, num2) / 2
# def add(num1, num2):
# return num1 + num2
# print average(5, 7)
# def calculate_tip(bill_amount, percentage):
# tip = bill_amount * percentage * 0.1
# return tip
# def bill_splitter(bill_amount, tip_percentage, number_guests):
# tip_amount = calculate_tip(bill_amount, tip_percentage)
# bill_total = bill_amount + tip_amount
# cost_per_person = bill_total / number_guests
# return cost_per_person
# cost_per_guest = bill_splitter(138.46, 18, 4)
# print "Amount per person is: " + str(cost_per_guest)
def sum(number1, number2):
return number1 + number2
print sum(2,3)
<file_sep>#Functions Part 1:
def hello_print():
print "hello"
#print hello_print() #prints hello /n None
#print hello_print(hi) #error: 'hi' not defined
#greeting = hello_print()
#print greeting #prints hello /n None
def hello_return():
return "hello"
#print hello_return() #prints hello
#greeting = hello_return()
#print greeting #prints hello
def hello_name(name):
print "hello," , name
#print hello_name() #error: needs argument
#print hello_name(molly) #error: molly not defined
# partner_name = "Molly"
# print hello_name(partner_name) #prints hello, Molly
# print hello_name() #error: needs argument
#Functions Part 2:
def add(num1, num2):
return num1 + num2
#print add(4, 5) #prints 9
def subtract(num1, num2):
return num1 - num2
#print subtract(4, 5) #prints -1
def multiply(num1, num2):
return num1 * num2
#print multiply(4, 5) #prints 20
def divide(num1, num2):
return num1 / num2
#print divide(4.0, 5.0) #prints 0.8
def modulo(num1, num2):
return num1 % num2
#print modulo(4, 5) #prints 4
def power(base, exponent):
return base ** exponent
#print power(4, 5) #prints 1024
def square(num):
return power(num, 2)
#print square(4) #prints 16
def main():
#(4+5) + (9-6)
print add(4, 5) + subtract(9, 6) #prints 12
#(12/2) - 60
print divide(12, 2) - 60 #prints -54
#1 + 2 + 3
print add(add(1, 2), 3) #prints 6
#(1+2) ^ 2
print square(add(1, 2)) #prints 9
#(3%4) / (9*9)
print divide(modulo(3.0, 4.0), multiply(9, 9)) #prints 0.037
#(1+2) - 3 * (4+5)
print subtract(add(1, 2), multiply(3, add(4, 5))) #prints -24
#3 ^ (2+3)
print power(3, add(2, 3)) #prints 243
if __name__ == "__main__":
main()
|
caa9b6aa9eeef4f1b02371a037326e657f613585
|
[
"Python"
] | 2
|
Python
|
mccole1/functions
|
1689f7bf1de9b0dcf195f49350eadad661c4aa2c
|
b6d5a4814e3ac0bcf23cec158e7393bc87bb54d2
|
refs/heads/master
|
<file_sep>import PropTypes from 'prop-types';
const friendsShape = PropTypes.shape({
id: PropTypes.string.isRequired,
uid: PropTypes.string.isRequired,
friendUid: PropTypes.string.isRequired,
isAccepted: PropTypes.bool.isRequired,
isPending: PropTypes.bool.isRequired,
});
export default friendsShape;
<file_sep>import axios from 'axios';
import firebaseConfig from '../apiKeys.json';
const baseUrl = firebaseConfig.firebaseKeys.databaseURL;
const getMyTrips = uid => new Promise((resolve, reject) => {
axios
.get(`${baseUrl}/trips.json?orderBy="uid"&equalTo="${uid}"`)
.then((res) => {
const trips = [];
if (res.data !== null) {
Object.keys(res.data).forEach((fbKey) => {
res.data[fbKey].id = fbKey;
trips.push(res.data[fbKey]);
});
}
resolve(trips);
})
.catch(err => reject(err));
});
const getFriendTrips = friendUid => new Promise((resolve, reject) => {
axios
.get(`${baseUrl}/trips.json?orderBy="friendUid"&equalTo="${friendUid}"`)
.then((res) => {
const trips = [];
if (res.data !== null) {
Object.keys(res.data).forEach((fbKey) => {
res.data[fbKey].id = fbKey;
trips.push(res.data[fbKey]);
});
}
resolve(trips);
})
.catch(err => reject(err));
});
const getAllTrips = () => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/trips.json`)
.then((result) => {
const tripObject = result.data;
const tripArray = [];
if (tripObject != null) {
Object.keys(tripObject).forEach((tripId) => {
tripObject[tripId].id = tripId;
tripArray.push(tripObject[tripId]);
});
}
resolve(tripArray);
})
.catch((error) => {
reject(error);
});
});
const getSingleTrip = tripId => axios.get(`${baseUrl}/trips/${tripId}.json`);
const deleteTrip = tripId => axios.delete(`${baseUrl}/trips/${tripId}.json`);
const postTrip = newTrip => axios.post(`${baseUrl}/trips.json`, newTrip);
const putTrip = (updatedTrip, tripId) => axios.put(`${baseUrl}/trips/${tripId}.json`, updatedTrip);
export default {
getMyTrips,
getSingleTrip,
deleteTrip,
postTrip,
putTrip,
getAllTrips,
getFriendTrips,
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import upcomingShape from '../../helpers/propz/upcomingShape';
import authRequests from '../../helpers/data/authRequests';
import './UpcomingItem.scss';
class UpcomingItem extends React.Component {
static propTypes = {
future: upcomingShape.upcomingCardShape,
deleteSingleUpcoming: PropTypes.func,
passUpcomingToEdit: PropTypes.func,
}
deleteUpcomingTrip = (e) => {
e.preventDefault();
const { deleteUpcoming, future } = this.props;
deleteUpcoming(future.id);
}
editUpcomingTrip = (e) => {
e.preventDefault();
const { passUpcomingToEdit, future } = this.props;
passUpcomingToEdit(future.id);
}
render() {
const { future } = this.props;
const uid = authRequests.getCurrentUid();
const makeButtons = () => {
if (future.uid === uid) {
return (
<div className="col">
<button className="btn card_btn" onClick={this.editUpcomingTrip}>Edit</button>
<button className="btn card_btn" onClick={this.deleteUpcomingTrip}>Delete</button>
</div>
);
}
};
return (
<div className="UpcomingTripCard col-4">
<div className="upcoming-card">
<div className="cards-item">
<div className="card-upcoming">
<img className="card_image" src="https://www.pennmedicine.org/-/media/images/miscellaneous/random%20generic%20photos/person_at_airport_holding_coffee_and_luggage.ashx?mw=620&mh=408"/>
<div className="card_content">
<h4 className="card_title">{future.name}</h4>
<h4 className = "card_text">{future.city}</h4>
<p className = "card_text">{future.country}</p>
<p className = "card_text">{future.date}</p>
</div>
{ makeButtons() }
</div>
\ </div>
</div>
</div>
);
}
}
export default UpcomingItem;
<file_sep>import PropTypes from 'prop-types';
const tripCardShape = PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
imageUrl: PropTypes.string.isRequired,
startDate: PropTypes.string.isRequired,
endDate: PropTypes.string.isRequired,
city: PropTypes.string.isRequired,
country: PropTypes.string.isRequired,
uid: PropTypes.string.isRequired,
});
export default { tripCardShape };
<file_sep>import axios from 'axios';
import firebaseConfig from '../apiKeys.json';
const baseUrl = firebaseConfig.firebaseKeys.databaseURL;
const getAllUpcomingTrips = () => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/upcoming.json`)
.then((result) => {
const upcomingObject = result.data;
const upcomingArray = [];
if (upcomingObject != null) {
Object.keys(upcomingObject).forEach((futureId) => {
upcomingObject[futureId].id = futureId;
upcomingArray.push(upcomingObject[futureId]);
});
}
resolve(upcomingArray);
})
.catch((error) => {
reject(error);
});
});
const deleteUpcoming = futureId => axios.delete(`${baseUrl}/upcoming/${futureId}.json`);
const postUpcoming = newUpcoming => axios.post(`${baseUrl}/upcoming.json`, newUpcoming);
const singleUpcoming = futureId => axios.get(`${baseUrl}/upcoming/${futureId}.json`);
const updateUpcoming = (futureId, future) => axios.put(`${baseUrl}/upcoming/${futureId}.json`, future);
export default {
getAllUpcomingTrips,
deleteUpcoming,
postUpcoming,
singleUpcoming,
updateUpcoming,
};
<file_sep>This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Welcome to Le Voyage
## Application Overview
Le Voyage is a Responsive CRUD application that allows users to save all of their most recent trips and vacations in one centralized location. This application can be used as a social media platform and a scrapbook alternative. Users may view their most recent trips on their home page. They are able to see upcoming trips as well. There is a map that marks all of the places they have visited. In addition there is a countdown clock that allows users to see how far away their trip is. Users may add friends and receive friend requests. Once the friendship is developed users may see their friends trips.
## Installation Instructions
- Clone down this repo `<EMAIL>:westmary48/le-voyage-.git`
- At the root of the project, run `npm install`
- Create a project in Firebase
- Add a web app to the project and enable Google authentication
- Create a real-time database and seed it with the data from the database directory
- Create a file named `/helpers/data/apiKeys.json` and add your Firebase keys using the `apiKeys.example.json` as a template
- make sure your apiKeys are in your git ignore file
## How to Run
- In your terminal, type `npm start`
***Note**: if you want to make a production build of this project, type `npm run build`. This will create a folder called build with all the minified code you need.*
## How to deploy
- In your terminal, type `npm run deploy`
## Application Features
- Once you login with your google email, create a few trips that you have gone on in the past
- You are able to view the single view, edit, and delete
- You can view the place you have visited the map by inputting the lat and long in the add form
- You may add upcoming trips as well
- You can use the countdown to type in the upcoming trip date
- The countdown input should look like this May 20 2020
- You can go to your friends page( you can receive friend requests, delete friends, and request friends)
- Once your friend request has been approved, you may see your friends trips at the bottom of the page( flip cards)
Inline-style:






## Have fun!!!
<file_sep>/* eslint-disable array-callback-return */
import React from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
import smashRequests from '../../helpers/data/smashRequests';
import friendRequest from '../../helpers/data/friendData';
import authRequests from '../../helpers/data/authRequests';
import './Friends.scss';
import FriendTripCard from '../FriendTripCard/FriendTripCard';
class Friends extends React.Component {
state = {
undiscoveredFriends: [],
pendingFriendships: [],
myFriends: [],
trips: [],
}
userMegaSmash = () => {
const uid = authRequests.getCurrentUid();
smashRequests.usersAndFriends(uid)
.then((users) => {
const undiscoveredFriends = users.filter(x => x.friendRequest === '');
const pendingFriendships = users.filter(x => x.friendRequest !== '' && x.isPending);
const myFriends = users.filter(x => x.isAccepted);
this.setState({ undiscoveredFriends, pendingFriendships, myFriends });
})
.catch(err => console.error('err in usersAndFriends', err));
}
getFriendsTrips = () => {
const uid = authRequests.getCurrentUid();
smashRequests.getTripsFromMeAndFriends(uid)
.then((trips) => {
this.setState({ trips });
})
.catch(err => console.error('error with trips GET', err));
}
componentDidMount() {
this.userMegaSmash();
this.getFriendsTrips();
}
friendTrips = (e) => {
e.preventDefault();
const tripId = e.target.id;
smashRequests.getTripsFromMeAndFriends(tripId)
.then(() => {
this.getFriendsTrips();
})
.catch(err => console.error('problem getting friends trips', err));
};
addNewFriend = (e) => {
e.preventDefault();
const newFriend = {
friendUid: e.target.id,
isAccepted: false,
isPending: true,
uid: authRequests.getCurrentUid(),
};
friendRequest.addFriend(newFriend)
.then(() => {
this.userMegaSmash();
})
.catch(err => console.error('problem adding new friend', err));
};
friendshipOver = (e) => {
e.preventDefault();
const friendId = e.target.id;
friendRequest.deleteFriend(friendId)
.then(() => {
this.userMegaSmash();
})
.catch(err => console.error('problem deleting friend', err));
};
confirmFriendship = (e) => {
e.preventDefault();
const friendId = e.target.id;
friendRequest.acceptFriendship(friendId)
.then(() => {
this.userMegaSmash();
})
.catch(err => console.error('problem deleting friend', err));
}
render() {
const {
undiscoveredFriends,
pendingFriendships,
myFriends,
} = this.state;
const { uid } = firebase.auth().currentUser;
const friendsTrips = this.state.trips.filter(a => a.uid !== uid);
const undiscoveredFriendCards = undiscoveredFriends.map(undiscovered => (
<div className="card border-dark" key={undiscovered.id}>
<h5 className="card-header-undiscovered">{undiscovered.userName}</h5>
<div className="card-body">
<div className="double-wide">
<img className="profile-img" src={undiscovered.photo} alt={undiscovered.userName}/>
</div>
<div className="double-wide">
<button className="btn btn-primary request-button" id={undiscovered.uid} onClick={this.addNewFriend}>Request</button>
</div>
</div>
</div>
));
const pendingFriendshipsCards = pendingFriendships.map(pending => (
<div className="card border-dark" key={pending.id}>
<h5 className="card-header-pending">{pending.userName}</h5>
<div className="card-body">
<div className="double-wide">
<img className="profile-img" src={pending.photo} alt={pending.userName}/>
</div>
<div className="double-wide">
{ pending.friendRequest === 'me'
? <p>Waiting</p>
: <div>
<button className="btn btn-primary" id={pending.friendRequestId} onClick={this.confirmFriendship}>Accept!</button>
<button className="btn btn-danger" id={pending.friendRequestId} onClick={this.friendshipOver}>Nope</button>
</div>}
</div>
</div>
</div>
));
const myFriendsCards = myFriends.map(mine => (
<div className="card border-dark" key={mine.id}>
<h5 className="card-header-friends">{mine.userName}</h5>
<div className="card-body">
<div className="double-wide">
<img className="profile-img" src={mine.photo} alt={mine.userName}/>
</div>
<div className="double-wide">
<button className="btn btn-danger" id={mine.friendRequestId} onClick={this.friendshipOver}>Delete</button>
</div>
</div>
</div>
));
const myFriendsTripsCards = friendsTrips.map(trip => (
<FriendTripCard
key={trip.id}
trip={trip}
/>
));
return (
<div className="Friends text-center col">
<h1 className = "friends-title">Friends</h1>
<div className="row">
<div className="col-4">
<h3 className = "friends-sub"><strong>Undiscovered Friends</strong></h3>
<hr/>
{ undiscoveredFriendCards }
</div>
<div className="col-4">
<h3 className = "friends-sub"><strong>Pending Friendships</strong></h3>
<hr/>
{ pendingFriendshipsCards }
</div>
<div className="col-4">
<h3 className = "friends-sub"><strong>My Friends</strong></h3>
<hr/>
{ myFriendsCards }
</div>
<div className="row friends-trips-container">
<div className = "col">
<h3 className = "friends-sub"><strong>My Friends Trips</strong></h3>
<div className= "col">
<div className = "row">
{ myFriendsTripsCards }
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Friends;
<file_sep>import React from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
import L from 'leaflet';
import {
Map as LeafletMap, TileLayer, Marker, Popup,
} from 'react-leaflet';
import TripMapCard from '../TripMapCard/TripMapCard';
import tripData from '../../helpers/data/tripData';
// import mapRequests from '../../helpers/data/mapRequests';
import 'leaflet/dist/leaflet.css';
import './MapApplication.scss';
class MapApplication extends React.Component {
state = {
trips: [],
map: {},
}
setMap = (map) => {
this.setState({ map });
}
getMyTrips = () => {
const { uid } = firebase.auth().currentUser;
tripData.getMyTrips(uid).then((trips) => {
this.setState({ trips });
})
.catch(err => console.error('could not get trips', err));
}
componentDidMount() {
this.map = this.mapInstance.leafletElement;
this.setMap();
this.getMyTrips();
}
render() {
const icon = L.icon({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
iconUrl: require('leaflet/dist/images/marker-icon.png'),
shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
});
const { trips } = this.state;
const tripsMarker = trips.map(trip => (
<Marker
key={trip.id}
position={[trip.lat, trip.long]}
trips = {trips}
icon = {icon}
>
<Popup>
<TripMapCard trip={trip} />
</Popup>
</Marker>
));
return (
<LeafletMap
ref={(e) => { this.mapInstance = e; }}
center={[44.0902, 80.7129]}
zoom={2.5}
maxZoom={5}
attributionControl={true}
zoomControl={true}
doubleClickZoom={true}
scrollWheelZoom={true}
dragging={true}
animate={true}
easeLinearity={0.35}
>
<TileLayer
url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
{tripsMarker}
</LeafletMap>
);
}
}
export default MapApplication;
<file_sep>import { EsriProvider } from 'leaflet-geosearch';
const provider = new EsriProvider();
const getLatAndLong = city => new Promise((resolve, reject) => {
provider.search({ query: city })
.then((results) => {
const coordinates = results[0];
resolve(coordinates);
})
.catch(err => reject(err));
});
export default {
getLatAndLong,
};
<file_sep>
import friendsData from './friendData';
import usersRequest from './usersRequest';
import tripData from './tripData';
import upcomingRequests from './upcomingRequests';
const usersAndFriends = currentUid => new Promise((resolve, reject) => {
const users = [];
usersRequest.getAllUsers()
.then((usrs) => {
friendsData.getAllFriends()
.then((friends) => {
usrs.forEach((user) => {
const newUser = { ...user };
newUser.isAccepted = false;
newUser.isPending = false;
newUser.friendRequest = '';
newUser.friendRequestId = '';
friends.forEach((friend) => {
if (friend.uid === currentUid && friend.friendUid === newUser.uid) {
newUser.isAccepted = friend.isAccepted;
newUser.isPending = friend.isPending;
newUser.friendRequest = 'me';
newUser.friendRequestId = friend.id;
} else if (friend.friendUid === currentUid && newUser.uid === friend.uid) {
newUser.isAccepted = friend.isAccepted;
newUser.isPending = friend.isPending;
newUser.friendRequest = 'them';
newUser.friendRequestId = friend.id;
}
});
if (newUser.uid !== currentUid) {
users.push(newUser);
}
});
resolve(users);
});
})
.catch(err => reject(err));
});
const getTripsFromMeAndFriends = uid => new Promise((resolve, reject) => {
let allTrips = [];
tripData.getAllTrips()
.then((tripz) => {
allTrips = tripz;
friendsData.getMyFriends(uid).then((friendsArray) => {
friendsArray.push(uid);
const tripsToKeep = allTrips.filter(f => friendsArray.includes(f.uid));
resolve(tripsToKeep);
});
})
.catch(err => reject(err));
});
const getUpcomingFromMeAndFriends = uid => new Promise((resolve, reject) => {
let allUpcoming = [];
upcomingRequests.getAllUpcomingTrips()
.then((upcomingz) => {
allUpcoming = upcomingz;
friendsData.getMyFriends(uid).then((friendsArray) => {
friendsArray.push(uid);
const upcomingToKeep = allUpcoming.filter(f => friendsArray.includes(f.uid));
resolve(upcomingToKeep);
});
})
.catch(err => reject(err));
});
export default { usersAndFriends, getTripsFromMeAndFriends, getUpcomingFromMeAndFriends };
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import tripData from '../../helpers/data/tripData';
import './SingleTrip.scss';
class SingleTrip extends React.Component {
state = {
trip: {},
}
componentDidMount() {
const tripId = this.props.match.params.id;
tripData.getSingleTrip(tripId)
.then(tripPromise => this.setState({ trip: tripPromise.data }))
.catch(err => console.error('unable to get single trip', err));
}
deleteTrip = () => {
const tripId = this.props.match.params.id;
tripData.deleteTrip(tripId)
.then(() => this.props.history.push('/home'))
.catch(err => console.error('unable to delete', err));
}
render() {
const { trip } = this.state;
const editLink = `/edit/${this.props.match.params.id}`;
return (
<div className="SingleTrip">
<div className = "singleCard">
<h3 className = "singleName">{trip.name}</h3>
<div className = "col">
<h6 className = "singleColor">{trip.description}</h6>
</div>
<div className = "col">
<h6 className = "singleColor">{trip.startDate}</h6>
</div>
<div className = "col">
<h6 className = "singleColor">{trip.endDate}</h6>
</div>
<div className = "col">
<h6 className = "singleColor">{trip.city}</h6>
</div>
<div className = "col">
<h6 className = "singleColor">{trip.country}</h6>
</div>
<img className = "singleImg" src = {trip.imageUrl} alt = ""/>
<div className = "col">
<Link className="btn btn-info" to={editLink}>Edit</Link>
<button className="btn btn-danger" onClick={this.deleteTrip}>Delete</button>
</div>
</div>
</div>
);
}
}
export default SingleTrip;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import tripShape from '../../helpers/propz/tripShape';
import './TripCard.scss';
class TripCard extends React.Component {
static propTypes = {
trip: tripShape.tripCardShape,
deleteTrip: PropTypes.func.isRequired,
}
deleteThis = (e) => {
e.preventDefault();
const { trip, deleteTrip } = this.props;
deleteTrip(trip.id);
}
render() {
const { trip } = this.props;
const singleLink = `/trip/${trip.id}`;
const editLink = `/edit/${trip.id}`;
return (
<div href = "#" className="TripCard col-3">
<div className="card">
<div className="card-body">
<h5 className="card-title">{trip.name}</h5>
<div className = "singleView">
<Link className="singleLink" to={singleLink}>Single View</Link>
</div>
<img className = "card-img" src = {trip.imageUrl} alt = "" />
<p className="card-text">{trip.description}</p>
<div className = "row">
<div className = "col">
<h6 className="card-image">{trip.startDate}</h6>
</div>
<div className = "col">
<h6 className="card-title">{trip.endDate}</h6>
</div>
</div>
<div className = "row">
<div className = "col">
<h6 className="card-title">{trip.city}</h6>
</div>
<div className = "col">
<h6 className="card-title">{trip.country}</h6>
</div>
</div>
<button className="btn btn-danger" onClick={this.deleteThis}>Delete</button>
<Link className="btn btn-info" to={editLink}>Edit</Link>
</div>
</div>
</div>
);
}
}
export default TripCard;
<file_sep>import PropTypes from 'prop-types';
const upcomingCardShape = PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
city: PropTypes.string.isRequired,
country: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
uid: PropTypes.string.isRequired,
});
export default { upcomingCardShape };
<file_sep>import axios from 'axios';
import firebaseConfig from '../apiKeys.json';
const baseUrl = firebaseConfig.firebaseKeys.databaseURL;
const getAllUsers = () => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/users.json`)
.then((result) => {
const userObject = result.data;
const userArray = [];
if (userObject != null) {
Object.keys(userObject).forEach((userId) => {
userObject[userId].id = userId;
userArray.push(userObject[userId]);
});
}
resolve(userArray);
})
.catch((error) => {
reject(error);
});
});
const createUser = user => axios.post(`${baseUrl}/users.json`, user);
const getUserByUid = uid => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/users.json?orderBy="uid"&equalTo="${uid}"`)
.then((result) => {
const userObject = result.data;
const userArray = [];
if (userObject != null) {
Object.keys(userObject).forEach((userId) => {
userObject[userId].id = userId;
userArray.push(userObject[userId]);
});
}
resolve(userArray[0]);
})
.catch((error) => {
reject(error);
});
});
export default {
getAllUsers,
getUserByUid,
createUser,
};
<file_sep>import React from 'react';
import {
BrowserRouter,
Route,
Redirect,
Switch,
} from 'react-router-dom';
import firebase from 'firebase/app';
import 'firebase/auth';
import Auth from '../components/Auth/Auth';
import Home from '../components/Home/Home';
import MyNavbar from '../components/MyNavbar/MyNavbar';
import NewTrip from '../components/NewTrip/NewTrip';
import EditTrip from '../components/EditTrip/EditTrip';
import SingleTrip from '../components/SingleTrip/SingleTrip';
import Friends from '../components/Friends/Friends';
import MapApplication from '../components/MapApplication/MapApplication';
import authRequests from '../helpers/data/authRequests';
import UpcomingTrips from '../components/UpcomingTrips/UpcomingTrips';
import './App.scss';
import fbConnection from '../helpers/data/connection';
fbConnection();
const PublicRoute = ({ component: Component, authed, ...rest }) => {
const routeChecker = props => (authed === false
? (<Component {...props} />)
: (<Redirect to={{ pathname: '/home', state: { from: props.location } }} />)
);
return <Route {...rest} render = {props => routeChecker(props)} />;
};
const PrivateRoute = ({ component: Component, authed, ...rest }) => {
const routeChecker = props => (authed === true
? (<Component {...props} />)
: (<Redirect to={{ pathname: '/auth', state: { from: props.location } }} />)
);
return <Route {...rest} render = {props => routeChecker(props)} />;
};
class App extends React.Component {
state = {
authed: false,
pendingUser: true,
}
componentDidMount() {
fbConnection();
this.removeListener = firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({
authed: true,
pendingUser: false,
});
} else {
this.setState({
authed: false,
pendingUser: false,
});
}
});
}
componentWillUnmount() {
this.removeListener();
}
render() {
const { authed, pendingUser } = this.state;
const logoutClickEvent = () => {
authRequests.logoutUser();
this.setState({ authed: false });
};
if (pendingUser) {
return null;
}
return (
<div className="App">
<BrowserRouter>
<React.Fragment>
<MyNavbar authed={authed} logoutClickEvent={logoutClickEvent}/>
<div className='container'>
<div className="row">
<Switch>
<PrivateRoute path='/' exact component={Home} authed={this.state.authed} />
<PrivateRoute path='/home' component={Home} authed={this.state.authed} />
<PrivateRoute path='/new' component={NewTrip} authed={authed}/>
<PrivateRoute path='/upcoming' component={UpcomingTrips} authed={authed}/>
<PrivateRoute path='/edit/:id' component={EditTrip} authed={authed}/>
<PrivateRoute path='/trip/:id' component={SingleTrip} authed={authed}/>
<PrivateRoute path='/friends' component={Friends} authed={this.state.authed}/>
<PrivateRoute path='/map' component={MapApplication} authed={this.state.authed}/>
<PublicRoute path='/auth' component={Auth} authed={this.state.authed} />
<Redirect from="*" to="/auth" />
</Switch>
</div>
</div>
</React.Fragment>
</BrowserRouter>
</div>
);
}
}
export default App;
<file_sep>import React from 'react';
// import firebase from 'firebase/app';
import 'firebase/auth';
import PropTypes from 'prop-types';
import authRequests from '../../helpers/data/authRequests';
import upcomingRequests from '../../helpers/data/upcomingRequests';
import './UpcomingForm.scss';
const defaultUpcoming = {
uid: '',
name: '',
city: '',
country: '',
upcoming: '',
date: '',
endDate: '',
};
class UpcomingForm extends React.Component {
static propTypes = {
onSubmit: PropTypes.func,
isEditing: PropTypes.bool,
editId: PropTypes.string,
}
state = {
newUpcoming: defaultUpcoming,
}
formFieldStringState = (name, e) => {
e.preventDefault();
const tempUpcoming = { ...this.state.newUpcoming };
tempUpcoming[name] = e.target.value;
this.setState({ newUpcoming: tempUpcoming });
}
nameChange = e => this.formFieldStringState('name', e);
cityChange = e => this.formFieldStringState('city', e);
countryChange = e => this.formFieldStringState('country', e);
dateChange = e => this.formFieldStringState('date', e);
cityChange = e => this.formFieldStringState('city', e);
countryChange = e => this.formFieldStringState('country', e);
formSubmit = (e) => {
e.preventDefault();
const { onSubmit } = this.props;
const myUpcomingTrip = { ...this.state.newUpcoming };
myUpcomingTrip.uid = authRequests.getCurrentUid();
onSubmit(myUpcomingTrip);
this.setState({ newUpcoming: defaultUpcoming });
}
componentDidUpdate(prevProps) {
const { isEditing, editId } = this.props;
if (prevProps !== this.props && isEditing) {
upcomingRequests.singleUpcoming(editId)
.then((future) => {
const newUpcoming = {
upcoming: future.data.name,
city: future.data.city,
name: future.data.name,
country: future.data.country,
date: future.data.date,
uid: future.data.uid,
};
this.setState({ newUpcoming });
})
.catch(err => console.error('error with singleUpcoming', err));
}
}
render() {
const { newUpcoming } = this.state;
const { isEditing } = this.props;
const title = () => {
if (isEditing) {
return <h2 className = "upcomingtitle">EDIT UPCOMING TRIP</h2>;
}
return <h2 className = "upcomingtitle">ADD UPCOMING TRIP</h2>;
};
return (
<div className="upcoming-form col">
{title()}
<form onSubmit={this.formSubmit}>
<div className = "leftside">
<div className="form-group">
<label htmlFor="name"><strong>NAME:</strong></label>
<input
type="text"
className="form-control"
id="name"
aria-describedby="nameHelp"
placeholder="Trip 1"
value={newUpcoming.name}
onChange={this.nameChange}
/>
</div>
<div className="form-group">
<label htmlFor="city"><strong>CITY:</strong></label>
<input
type="text"
className="form-control"
id="city"
aria-describedby="cityHelp"
placeholder="Nashville"
value={newUpcoming.city}
onChange={this.cityChange}
/>
</div>
</div>
<div className = "rightside">
<div className="form-group">
<label htmlFor="country"><strong>COUNTRY:</strong></label>
<input
type="text"
className="form-control"
id="country"
aria-describedby="countryHelp"
placeholder="United States"
value={newUpcoming.country}
onChange={this.countryChange}
/>
</div>
<div className="form-group">
<label htmlFor="date"><strong>DATE:</strong></label>
<input
type="text"
className="form-control"
id="date"
aria-describedby="dateHelp"
placeholder="December 25 2020"
value={newUpcoming.date}
onChange={this.dateChange}
/>
</div>
</div>
<button className="btn btn-primary save">Save Upcoming Trip</button>
</form>
</div>
);
}
}
export default UpcomingForm;
<file_sep>import React from 'react';
import tripShape from '../../helpers/propz/tripShape';
import './FriendTripCard.scss';
{/* <div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="img_avatar.png" alt="Avatar" style="width:300px;height:300px;">
</div>
<div class="flip-card-back">
<h1><NAME></h1>
<p>Architect & Engineer</p>
<p>We love that guy</p>
</div>
</div>
</div> */}
class FriendTripCard extends React.Component {
static propTypes = {
trip: tripShape.tripCardShape,
}
render() {
const { trip } = this.props;
return (
<div className="FriendTripCard col">
{/* <div className="card"> */}
<div class="flip-card-inner">
<div class="flip-card-front">
{/* <div className="card-body"> */}
{/* <h5 className="card-title">{trip.name}</h5>
<p className="card-text">{trip.description}</p> */}
<img className = "card-img-friends" src = {trip.imageUrl} alt = "" />
</div>
<div class="flip-card-back">
<h5 className="card-title">{trip.name}</h5>
<p className="card-text">{trip.description}</p>
<h6 className="card-title">{trip.startDate}</h6>
<h6 className="card-title">{trip.endDate}</h6>
<h6 className="card-title">{trip.city}</h6>
<h6 className="card-title">{trip.country}</h6>
</div>
</div>
</div>
);
}
}
export default FriendTripCard;
<file_sep>import React from 'react';
import tripData from '../../helpers/data/tripData';
import './EditTrip.scss';
const defaultTrip = {
name: '',
description: '',
imageUrl: '',
startDate: '',
endDate: '',
lat: '',
long: '',
city: '',
country: '',
};
class EditTrip extends React.Component {
state = {
newTrip: defaultTrip,
}
componentDidMount() {
const tripId = this.props.match.params.id;
tripData.getSingleTrip(tripId)
.then(tripPromise => this.setState({ newTrip: tripPromise.data }))
.catch(err => console.error('could not find single trip', err));
}
formFieldStringState = (name, e) => {
const tempTrip = { ...this.state.newTrip };
tempTrip[name] = e.target.value;
this.setState({ newTrip: tempTrip });
}
nameChange = e => this.formFieldStringState('name', e);
descriptionChange = e => this.formFieldStringState('description', e);
imageChange = e => this.formFieldStringState('image', e);
startDateChange = e => this.formFieldStringState('startDate', e);
endDateChange = e => this.formFieldStringState('endDate', e);
cityChange = e => this.formFieldStringState('city', e);
countryChange = e => this.formFieldStringState('country', e);
latChange = e => this.formFieldStringState('lat', e);
longChange = e => this.formFieldStringState('long', e);
formSubmit = (e) => {
e.preventDefault();
const saveMe = { ...this.state.newTrip };
const tripId = this.props.match.params.id;
tripData.putTrip(saveMe, tripId)
.then(() => this.props.history.push('/home'))
.catch(err => console.error('unable to save', err));
}
render() {
const { newTrip } = this.state;
return (
<div className="editTrip-container">
<h1 className = "editTrip-title">EDIT TRIP</h1>
<form onSubmit={this.formSubmit}>
<div class = "leftside">
<div className="form-group">
<label htmlFor="name"><strong>NAME</strong></label>
<input
type="text"
className="form-control"
id="name"
placeholder="Trip 1"
value={newTrip.name}
onChange={this.nameChange}
/>
</div>
<div className="form-group">
<label htmlFor="description"><strong>DESCRIPTION</strong></label>
<input
type="text"
className="form-control"
id="description"
placeholder="Girls trip"
value={newTrip.description}
onChange={this.descriptionChange}
/>
</div>
<div className="form-group">
<label htmlFor="imageUrl"><strong>IMAGE</strong></label>
<input
type="img"
className="form-control"
id="imageUrl"
placeholder="url"
value={newTrip.imageUrl}
onChange={this.imageUrlChange}
/>
</div>
<div className="form-group">
<label htmlFor="startDate"><strong>START DATE</strong></label>
<input
type="text"
className="form-control"
id="startDate"
placeholder="10/15/2019"
value={newTrip.startDate}
onChange={this.startDateChange}
/>
</div>
<div className="form-group">
<label htmlFor="endDate"><strong>END DATE</strong></label>
<input
type="text"
className="form-control"
id="endDate"
placeholder="10/20/2019"
value={newTrip.endDate}
onChange={this.endDateChange}
/>
</div>
</div>
<div class = "rightside">
<div className="form-group">
<label htmlFor="lat"><strong>LATITUDE</strong></label>
<input
type="text"
className="form-control"
id="lat"
placeholder="48.8566"
value={newTrip.lat}
onChange={this.latChange}
/>
</div>
<div className="form-group">
<label htmlFor="long"><strong>LONGITUDE</strong></label>
<input
type="text"
className="form-control"
id="long"
placeholder="23.3522"
value={newTrip.long}
onChange={this.longChange}
/>
</div>
<div className="form-group">
<label htmlFor="city"><strong>CITY</strong></label>
<input
type="text"
className="form-control"
id="city"
placeholder="New York"
value={newTrip.city}
onChange={this.cityChange}
/>
</div>
<div className="form-group">
<label htmlFor="country"><strong>COUNTRY</strong></label>
<input
type="text"
className="form-control"
id="country"
placeholder="United Stated"
value={newTrip.country}
onChange={this.countryChange}
/>
</div>
</div>
<button type="submit" className="btn btn-primary save">UPDATE TRIP</button>
</form>
</div>
);
}
}
export default EditTrip;
<file_sep>import React from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/storage';
import FileUploader from 'react-firebase-file-uploader';
import tripData from '../../helpers/data/tripData';
import './NewTrip.scss';
const defaultTrip = {
name: '',
description: '',
imageUrl: '',
startDate: '',
endDate: '',
city: '',
country: '',
lat: '',
long: '',
};
class NewTrip extends React.Component {
state = {
newTrip: defaultTrip,
}
formFieldStringState = (name, e) => {
const tempTrip = { ...this.state.newTrip };
tempTrip[name] = e.target.value;
this.setState({ newTrip: tempTrip });
}
nameChange = e => this.formFieldStringState('name', e);
descriptionChange = e => this.formFieldStringState('description', e);
startDateChange = e => this.formFieldStringState('startDate', e);
endDateChange = e => this.formFieldStringState('endDate', e);
cityChange = e => this.formFieldStringState('city', e);
countryChange = e => this.formFieldStringState('country', e);
latChange = e => this.formFieldStringState('lat', e);
longChange = e => this.formFieldStringState('long', e);
handleUploadSuccess = (filename) => {
this.setState({
image: filename,
});
firebase.storage().ref('images').child(filename).getDownloadURL()
.then((url) => {
this.setState({ imageUrl: url });
this.props.imageUrl(url);
})
.catch(err => console.error('no image url', err));
};
formSubmit = (e) => {
e.preventDefault();
const saveForm = { ...this.state.newTrip };
saveForm.uid = firebase.auth().currentUser.uid;
saveForm.imageUrl = this.state.imageUrl;
tripData.postTrip(saveForm)
.then(() => this.props.history.push('/home'))
.catch(err => console.error('unable to save', err));
}
render() {
const { newTrip } = this.state;
return (
<div className="newTrip-container">
<h1 className = "newtrip-title">ADD NEW TRIP</h1>
<form onSubmit={this.formSubmit}>
<div className = "leftside">
<div className="form-group">
<label htmlFor="name"><strong>NAME</strong></label>
<input
type="text"
className="form-control"
id="name"
placeholder="Trip 1"
value={newTrip.name}
onChange={this.nameChange}
/>
</div>
<div className="form-group">
<label htmlFor="description"><strong>DESCRIPTION</strong></label>
<input
type="text"
className="form-control"
id="description"
placeholder="Girls trip"
value={newTrip.description}
onChange={this.descriptionChange}
/>
</div>
<div className="form-group">
<label htmlFor="itemImage"><strong>IMAGE</strong></label>
<FileUploader
accept='image/*'
name='image'
storageRef={firebase.storage().ref('images/')}
onUploadSuccess={this.handleUploadSuccess}
/>
</div>
<div className="form-group">
<label htmlFor="startDate"><strong>START DATE</strong></label>
<input
type="text"
className="form-control"
id="startDate"
placeholder="10/20/2019"
value={newTrip.startDate}
onChange={this.startDateChange}
/>
</div>
<div className="form-group">
<label htmlFor="endDate"><strong>END DATE</strong></label>
<input
type="text"
className="form-control"
id="endDate"
placeholder="10/20/2019"
value={newTrip.endDate}
onChange={this.endDateChange}
/>
</div>
</div>
<div className = "rightside">
<div className="form-group">
<label htmlFor="city"><strong>CITY</strong></label>
<input
type="text"
className="form-control"
id="city"
placeholder="New York"
value={newTrip.city}
onChange={this.cityChange}
/>
</div>
<div className="form-group">
<label htmlFor="country"><strong>COUNTRY</strong></label>
<input
type="text"
className="form-control"
id="country"
placeholder="United States"
value={newTrip.country}
onChange={this.countryChange}
/>
</div>
<div className="form-group">
<label htmlFor="lat"><strong>LATITUDE</strong></label>
<input
type="text"
className="form-control"
id="lat"
placeholder="48.8566"
value={newTrip.lat}
onChange={this.latChange}
/>
</div>
<div className="form-group">
<label htmlFor="long"><strong>LONGITUDE</strong></label>
<input
type="text"
className="form-control"
id="long"
placeholder="23.3522"
value={newTrip.long}
onChange={this.longChange}
/>
</div>
</div>
<button type="submit" className="btn btn-primary save">Save Trip</button>
</form>
</div>
);
}
}
export default NewTrip;
<file_sep>import axios from 'axios';
import firebaseConfig from '../apiKeys.json';
const baseUrl = firebaseConfig.firebaseKeys.databaseURL;
const getMyFriends = uid => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/friends.json`)
.then((result) => {
const friendObject = result.data;
const friendArray = [];
if (friendObject != null) {
Object.keys(friendObject).forEach((friendId) => {
friendObject[friendId].id = friendId;
if (friendObject[friendId].isAccepted && friendObject[friendId].friendUid === uid) {
friendArray.push(friendObject[friendId].uid);
}
if (friendObject[friendId].isAccepted && friendObject[friendId].uid === uid) {
friendArray.push(friendObject[friendId].friendUid);
}
});
}
resolve(friendArray);
})
.catch((error) => {
reject(error);
});
});
const getAllFriends = () => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/friends.json`)
.then((result) => {
const friendObject = result.data;
const friendArray = [];
if (friendObject != null) {
Object.keys(friendObject).forEach((friendId) => {
friendObject[friendId].id = friendId;
friendArray.push(friendObject[friendId]);
});
}
resolve(friendArray);
})
.catch((error) => {
reject(error);
});
});
const addFriend = newFriend => axios.post(`${baseUrl}/friends.json`, newFriend);
const deleteFriend = friendId => axios.delete(`${baseUrl}/friends/${friendId}.json`);
const acceptFriendship = friendId => axios.patch(`${baseUrl}/friends/${friendId}.json`, { isAccepted: true, isPending: false });
export default {
getMyFriends,
addFriend,
deleteFriend,
acceptFriendship,
getAllFriends,
};
|
92fadfbe29edb78720ef9acaf3bcb18158c26e53
|
[
"JavaScript",
"Markdown"
] | 20
|
JavaScript
|
westmary48/le-voyage-
|
23de82567b1151bc86fd7fd9e0e8da50f973bb28
|
c0cb0111f6b6a601962736e5b66ef14544f4db52
|
refs/heads/master
|
<repo_name>rayhanrjt/my-first-blog<file_sep>/college/blog/admin.py
from django.contrib import admin
from .models import Post
from .models import Classs
from .models import student
admin.site.register(Post)
admin.site.register(Classs)
admin.site.register(student)
<file_sep>/college/blog/models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Classs(models.Model):
name = models.CharField(max_length=200)
def __str__(self): # __unicode__ on Python 2
return self.name
class student(models.Model):
classs=models.ForeignKey(Classs,on_delete=models.CASCADE)
name = models.CharField(max_length=200)
std_id = models.CharField(max_length=200)
mobile = models.CharField(max_length=200)
email = models.CharField(max_length=200)
department = models.CharField(max_length=200)
def __str__(self): # __unicode__ on Python 2
return self.classs
<file_sep>/college/blog/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.shortcuts import redirect
from .forms import studentForm
from django.shortcuts import get_object_or_404
from .models import Post
from .models import Classs
from .models import student
@login_required
def index(request):
return render(request, 'blog/index.html', {})
def studentlist(request):
studentlists = student.objects.all();
return render(request, 'blog/studentlist.html', {'studentlists': studentlists})
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
def post_new(request):
if request.method == "POST":
form = studentForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog/index.html', pk=post.pk)
else:
form = studentForm()
return render(request, 'blog/post_edit.html', {'form': form})
def student_detail(request, pk):
post = get_object_or_404(student, pk=pk)
return render(request, 'blog/student_detail.html', {'post': post})
def contact(request):
return render(request,'blog/contact.html')
def scholarship(request):
return render(request,'blog/scholarship.html')
def course(request):
return render(request,'blog/course.html')
def gallery(request):
return render(request,'blog/gallery.html')
def blog(request):
return render(request,'blog/blog.html')
# Create your views here.
<file_sep>/college/blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^post/slist/$', views.studentlist, name='studentlist'),
url(r'^post/list/$', views.post_list, name='post_list'),
url(r'^post/new/$', views.post_new, name='post_new'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^scholarship/$', views.scholarship, name='scholarship'),
url(r'^course/$', views.course, name='course'),
url(r'^gallery/$', views.gallery, name='gallery'),
url(r'^blog/$', views.blog, name='blog'),
url(r'^student/(?P<pk>\d+)/$', views.student_detail, name='student_detail'),
]
<file_sep>/college/blog/forms.py
from django import forms
from .models import Post
from .models import student
class studentForm(forms.ModelForm):
class Meta:
model = student
fields = ('classs', 'name','std_id','mobile','email','department')
|
0303adde1c75aa1efe6db0e86b62dcc58bf02007
|
[
"Python"
] | 5
|
Python
|
rayhanrjt/my-first-blog
|
b368e8749bd86c72933662590ac751494a7d3f27
|
1b4ee8e7e87cd7a170b0193664afe2b77f7d8c52
|
refs/heads/master
|
<repo_name>pengfen/yii2<file_sep>/frontend/views/part/index.php
<?php if($this->beginCache('cache_div')){?>
<div id="cache_div">
<div>这里待会会被缓存1111</div>
</div>
<?php
$this->endCache();
}
?>
<div id="no_cache_div">
<div>这里不会被缓存1111</div>
</div><file_sep>/frontend/models/Test.php
<?php
namespace frontend\models;
use yii\db\ActiveRecord;
class Test extends ActiveRecord{
// 校验
public function rules(){
return[
['id', 'integer'],
['name', 'string', 'length'=>[0,5]]
];
}
}<file_sep>/frontend/views/part/duration.php
<?php
// 设置缓存时间
$duration = 15; // beginCache 第二个参数 ['duration'=>$duration]
// 缓存依赖 第二个参数 ['dependency'=>$depend]
$depend = [
'class' => 'yii\caching\FileDependency',
'fileName' => 'abc.txt'
];
// 缓存开关
$enabled = false;
?>
<?php if($this->beginCache('cache_div', ['dependency'=>$depend])){?>
<div id="cache_div">
<div>这里待会会被缓存1111</div>
</div>
<?php
$this->endCache();
}
?>
<div id="no_cache_div">
<div>这里不会被缓存1111</div>
</div><file_sep>/frontend/models/Member.php
<?php
namespace frontend\models;
use yii\db\ActiveRecord;
class Member extends ActiveRecord{
// 获取会员的订单信息
public function getOrders(){
// all() 调用getOrders 时需要 调用orders 时不需要
return $this->hasMany(Order::className(), ['member_id'=>'id'])->asArray();
}
}<file_sep>/frontend/views/wel/layout.php
<h1>welcome to yii world!</h1>
<?php echo $this->render('about'); ?><file_sep>/frontend/views/part/inner.php
<?php if($this->beginCache('cache_div', ['duration'=>20])){?>
<div id="cache_outer_div">
<div>这里是外层 待会会被缓存</div>
</div>
<?php if($this->beginCache('cache_div', ['duration'=>1])){?>
<div id="cache_inner_div">
<div>这里是内层 待会会被缓存</div>
</div>
<?php
$this->endCache();
}
?>
<?php
$this->endCache();
}
?>
<div id="no_cache_div">
<div>这里不会被缓存1111</div>
</div><file_sep>/frontend/views/layouts/public.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>视图文件</title>
</head>
<body>
<?php
// if(isset($this->blocks['name'])){
// echo $this->blocks['name'];
// } else {
// echo "<h1> 公共布局文件夹</h1>";
// }
if(isset($this->blocks['name'])):?>
<?=$this->blocks['name'];?>
<?php else:?>
<h1> 公共布局文件夹</h1>
<?php endif;?>
<?=$content;?>
</body>
</html><file_sep>/frontend/views/wel/data.php
<h1><?=$data?></h1>
<h1><?=$arr[0]?></h1><file_sep>/frontend/views/wel/block.php
<?php $this->beginBlock('name');?>
<h1>加载数据块</h1>
<?php $this->endBlock('name');?>
<h1>数据块</h1>
|
094a0fcddccb963c4e3b0ae21d6cfc3ab6c7146e
|
[
"PHP"
] | 9
|
PHP
|
pengfen/yii2
|
73f1260e144af11f9460d22144ebf1d0b73ea8a0
|
27aea5b6aceb9cb5e0a419fc26b2aff5bc257ba9
|
refs/heads/master
|
<repo_name>zekdeluca/ProgrammingAssignment2<file_sep>/cachematrix.R
# Matrix inversion is usually a costly computation and there may be some
# benefit to caching the inverse of a matrix rather than computing it
# repeatedly. The below functions cache the inverse of a matrix
# Function to create a special matrix object that can cache its inverse
makeCacheMatrix <- function(matrix = matrix()) {
inverse <- NULL
set <- function(y) {
matrix <<- y
inverse <<- NULL
}
get <- function() matrix
setInverse <- function(inverseMatrix) inverse <<- inverseMatrix
getInverse <- function() inverse
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
# Function to compute the inverse of a matrix returned by makeCacheMatrix.
# If the inverse has already been calculated (and the matrix has not changed),
# then retrieves the inverse from the cache
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getInverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setInverse(m)
m
}
|
e25c4e6b3ef2530845ec2895071c45d825cf816b
|
[
"R"
] | 1
|
R
|
zekdeluca/ProgrammingAssignment2
|
8667f5b18cd317e5a559c7807eeff91109d0c551
|
5492c96392a3ead985afe43af2ad6f2c8dcf4475
|
refs/heads/master
|
<file_sep><?php
$data_source='sqlconn';
$user='directorio';
$password='<PASSWORD>';
$conn=odbc_connect($data_source,$user,$password);
if (!$conn){
if (phpversion() < '4.0'){
exit("Connection Failed: . $php_errormsg" );
}
else{
exit("Connection Failed:" . odbc_errormsg() );
}
}
$sql="SELECT * FROM V_PASS_NOM";
$rs=odbc_exec($conn,$sql);
if (!$rs){
exit("Error in SQL");
}
while (odbc_fetch_row($rs)){
$col1=odbc_result($rs, "nombre");
echo "$col1\n";
}
odbc_close($conn);
?>
|
a78a742d1e1219333ef667aa754388da55599c08
|
[
"PHP"
] | 1
|
PHP
|
chchluko/prueagit
|
b3aa718a59f83938dd6523390ee04b5b802b7312
|
2f10866ed19c9543fb0b67e7556881e73ce04d0e
|
refs/heads/master
|
<repo_name>saadixl/connect4<file_sep>/js/main.js
// shorhand for document.getElementById
function gE(x) {
return document.getElementById(x);
}
// this function is for setting the name of the player who will play next
function turn(x){
return $("#selectPlayer1 p").text(x+"'s turn now");
}
//place for universal variables
var playerName = "";
var playerTurn = "";
var done = "no";
var grid = new Array(6);
grid[0] = new Array(7);
grid[1] = new Array(7);
grid[2] = new Array(7);
grid[3] = new Array(7);
grid[4] = new Array(7);
grid[5] = new Array(7);
// this function is for initialization grid by making them empty
function init(){
for(var i=0; i<6; i++){
for(var j=0; j<7; j++){
grid[i][j] = "empty";
}
}
}
// function for taking input & setting player name
function setPlayerName(){
init();
playerName = gE('pname').value;
if(playerName===""){
alert("Set your name if you really wanna play!");
return;
}
$("#pname").hide();
$("#playerInfo label").hide();
$("#sub").hide();
$("#playerInfo p").text(playerName+" is playing with the Robot.");
$("#playerRadio").text("Set "+playerName+" as first player");
$("#selectPlayer1").fadeIn();
}
$('input:radio[name="rad"]').change(function(){
if($(this).val() === 'robot'){
playerTurn = "robot";
$("#selectPlayer1 form").fadeOut();
turn("robot");
ifRobotFirst();
}
else{
playerTurn = "player";
$("#selectPlayer1 form").fadeOut();
turn(playerName);
}
});
// id to index parsers
function idToRow(x){
var xStr = x.charAt(1);
var xInt = parseInt(xStr);
return xInt;
}
function idToCol(x){
var xStr = x.charAt(2);
var xInt = parseInt(xStr);
return xInt;
}
// index to id parser
function indexToId(r,c){
var ind = "";
ind+="#";
ind+="i";
ind+= r.toString();
ind+= c.toString();
return ind;
}
function ifRobotFirst(){
var row = 5;
var col = Math.floor((Math.random()*6)+1);
grid[row][col] = "robot";
var targetedId = indexToId(row,col);
$(targetedId).css("background","#800000");
playerTurn = "player";
turn(playerName);
}
// this funtion is for geting the id name and returning index for a 2d array
$("li").click(function (){
if(playerName==="" || playerTurn==="" || playerTurn==="robot"){ //stoping the player from cheating :P
return;
}
var theId = $(this).attr('id');
var row = idToRow(theId);
var col = idToCol(theId);
var isValid = true;
for(var a=5; a >= row; a--){
if(grid[a][col]==="empty"){
grid[a][col] = "player";
var targetedId = indexToId(a,col);
$(targetedId).css("background","#6666FF");
isValid = true;
winCheck("player");
break;
}
else{
isValid = false;
}
}
if(isValid===false){
alert("This position is not valid. Try again.");
}
playerTurn = "robot";
robotPlay();
});
// this function will play as robot
function robotPlay(){
var winTry = true, defendTry = true,lightTry=true, progressTry = true;
winTry = winMove();
if(winTry===false){
defendTry = defendMove();
}
if(defendTry===false){
lightTry = lightMove();
}
if(lightTry===false){
progressTry = progressMove();
}
playerTurn = "player";
}
// this function is for making the winning move
function defendMove(){
for(var i=5; i>=0; i--){ // loop for traversing rows
for(var j=6; j>=0; j--){ //loop for traversing cols
if( grid[i][j]==="empty"){
if(i<5 && grid[i+1][j]==="empty"){ // checking gravity here
continue;
}
//horizontal check block starts
/*
_ppp
p_pp
pp_p
ppp_
*/
if(
(j+3<=6 && grid[i][j+1]==="player" && grid[i][j+2]==="player" && grid[i][j+3]==="player")||
(j-1>=0 && j+2<=6 && grid[i][j-1]==="player" && grid[i][j+1]==="player" && grid[i][j+2]==="player")||
(j-2>=0 && j+1<=6 && grid[i][j-2]==="player" && grid[i][j-1]==="player" && grid[i][j+1]==="player")||
(j-3>=0 && grid[i][j-3]==="player" && grid[i][j-2]==="player" && grid[i][j-1]==="player")
){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
//horizontal check block ends
// vertical block starts
/*
_
p
p
p
*/
if( i+3<=5 && grid[i+1][j]==="player" && grid[i+2][j]==="player" && grid[i+3][j]==="player"){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
//vertical block ends
//diagonal block starts here
if(
/* 1 */ ( j+3<=6 && i-3>=0 && grid[i-1][j+1]==="player" && grid[i-2][j+2]==="player" && grid[i-3][j+3]==="player" )||
/* 2 */ ( j+2<=6 && i-2>=0 && i+1<=5 && j-1>=0 && grid[i+1][j-1]==="player" && grid[i-1][j+1]==="player" && grid[i-2][j+2]==="player" )||
/* 3 */ ( j+1<=6 && i-1>=0 && i+2<=5 && j-2>=0 && grid[i+2][j-2]==="player" && grid[i+1][j-1]==="player" && grid[i-1][j+1]==="player" )||
/* 4 */ ( j-3>=0 && i+3<=5 && grid[i+3][j-3]==="player" && grid[i+2][j-2]==="player" && grid[i+1][j-1]==="player" )||
/* 5 */ ( i-3>=0 && j-3>=0 && grid[i-3][j-3]==="player" && grid[i-2][j-2]==="player" && grid[i-1][j-1]==="player" )||
/* 6 */ ( i-2>=0 && j-2>=0 && i+1<=5 && j+1<=6 && grid[i-2][j-2]==="player" && grid[i-1][j-1]==="player" && grid[i+1][j+1]==="player" )||
/* 7 */ ( i-1>=0 && j-1>=0 && i+2<=5 && j+2<=6 && grid[i-1][j-1]==="player" && grid[i+1][j+1]==="player" && grid[i+2][j+2]==="player" )||
/* 8 */ ( i+3<=5 && j+3<=6 && grid[i+3][j+3]==="player" && grid[i+2][j+2]==="player" && grid[i+1][j+1]==="player" )
){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
//diagonal block ends here
}//empty check ends
}//col loop ends
}//row loop ends
return false;
}// defendMove() ends here
// winMove start here
function winMove(){
for(var i=5; i>=0; i--){ // loop for traversing rows
for(var j=6; j>=0; j--){ //loop for traversing cols
if( grid[i][j]==="empty"){
if(i<5 && grid[i+1][j]==="empty"){ // checking gravity here
continue;
}
//horizontal check block starts
/*
_ppp
p_pp
pp_p
ppp_
*/
if(
(j+3<=6 && grid[i][j+1]==="robot" && grid[i][j+2]==="robot" && grid[i][j+3]==="robot")||
(j-1>=0 && j+2<=6 && grid[i][j-1]==="robot" && grid[i][j+1]==="robot" && grid[i][j+2]==="robot")||
(j-2>=0 && j+1<=6 && grid[i][j-2]==="robot" && grid[i][j-1]==="robot" && grid[i][j+1]==="robot")||
(j-3>=0 && grid[i][j-3]==="robot" && grid[i][j-2]==="robot" && grid[i][j-1]==="robot")
){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
//horizontal check block ends
// vertical block starts
/*
_
p
p
p
*/
if( i+3<=5 && grid[i+1][j]==="robot" && grid[i+2][j]==="robot" && grid[i+3][j]==="robot"){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
//vertical block ends
//diagonal block starts here
if(
/* 1 */ ( j+3<=6 && i-3>=0 && grid[i-1][j+1]==="robot" && grid[i-2][j+2]==="robot" && grid[i-3][j+3]==="robot" )||
/* 2 */ ( j+2<=6 && i-2>=0 && i+1<=5 && j-1>=0 && grid[i+1][j-1]==="robot" && grid[i-1][j+1]==="robot" && grid[i-2][j+2]==="robot" )||
/* 3 */ ( j+1<=6 && i-1>=0 && i+2<=5 && j-2>=0 && grid[i+2][j-2]==="robot" && grid[i+1][j-1]==="robot" && grid[i-1][j+1]==="robot" )||
/* 4 */ ( j-3>=0 && i+3<=5 && grid[i+3][j-3]==="robot" && grid[i+2][j-2]==="robot" && grid[i+1][j-1]==="robot" )||
/* 5 */ ( i-3>=0 && j-3>=0 && grid[i-3][j-3]==="robot" && grid[i-2][j-2]==="robot" && grid[i-1][j-1]==="robot" )||
/* 6 */ ( i-2>=0 && j-2>=0 && i+1<=5 && j+1<=6 && grid[i-2][j-2]==="robot" && grid[i-1][j-1]==="robot" && grid[i+1][j+1]==="robot" )||
/* 7 */ ( i-1>=0 && j-1>=0 && i+2<=5 && j+2<=6 && grid[i-1][j-1]==="robot" && grid[i+1][j+1]==="robot" && grid[i+2][j+2]==="robot" )||
/* 8 */ ( i+3<=5 && j+3<=6 && grid[i+3][j+3]==="robot" && grid[i+2][j+2]==="robot" && grid[i+1][j+1]==="robot" )
){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
//diagonal block ends here
}//empty check ends
}//col loop ends
}//row loop ends
return false;
}// winMove() ends here
function lightMove(){
for(var i=5; i>=0; i--){ // loop for traversing rows
for(var j=6; j>=0; j--){ //loop for traversing cols
if( grid[i][j]==="empty"){
if(i<5 && grid[i+1][j]==="empty"){ // checking gravity here
continue;
}
if(
(i+2<=5 && grid[i+2][j]==="player" && grid[i+1][j]==="player")||
(j-2>=0 && grid[i][j-2]==="player" && grid[i][j-1]==="player")||
(j+2<=6 && grid[i][j+2]==="player" && grid[i][j+1]==="player")||
(j+1<=6 && j-1>=0 && grid[i][j+1]==="player" && grid[i][j-1]==="player")
){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
if(
(i+2<=5 && grid[i+2][j]==="robot" && grid[i+1][j]==="robot")||
(j-2>=0 && grid[i][j-2]==="robot" && grid[i][j-1]==="robot")||
(j+2<=6 && grid[i][j+2]==="robot" && grid[i][j+1]==="robot")||
(j+1<=6 && j-1>=0 && grid[i][j+1]==="robot" && grid[i][j-1]==="robot")
){
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
}
}//end loop
}//end loop
return false;
}
function progressMove(){
for(var p=5; p>=0; p--){
for(var q=6; q>=0; q--){
if(grid[p][q]==="empty"){
if(p<5 && grid[p+1][q]==="empty"){ // checking gravity here
continue;
}
grid[p][q] = "robot";
var targetedId = indexToId(p,q);
$(targetedId).css("background","#800000");
done = "yes";
winCheck("robot");
return true;
}
}
}
return false;
}
/* winCheck block starts here*/
function winCheck(x){
for(var i=5; i>=0; i--){ // loop for traversing rows
for(var j=6; j>=0; j--){ //loop for traversing cols
//horizontal check block starts
/*
_ppp
p_pp
pp_p
ppp_
*/
if( j+3<=6 && grid[i][j]===x && grid[i][j+1]===x && grid[i][j+2]===x && grid[i][j+3]===x ){
var targetedId1 = indexToId(i,j);
var targetedId2 = indexToId(i,j+1);
var targetedId3 = indexToId(i,j+2);
var targetedId4 = indexToId(i,j+3);
$(targetedId1).css("background","black");
$(targetedId2).css("background","black");
$(targetedId3).css("background","black");
$(targetedId4).css("background","black");
$("#result").fadeIn();
if(x==="player"){
x = playerName;
}
$("#result p").text(x+ " won.");
$("#selectPlayer1").hide();
$( "body" )
.off( "click", "#grid", flash )
.find( "#grid" )
.text( "game over" );
return;
}
//horizontal check block ends
// vertical block starts
/*
_
p
p
p
*/
if( i+3<=5 && grid[i][j]===x && grid[i+1][j]===x && grid[i+2][j]===x && grid[i+3][j]===x){
var targetedId1 = indexToId(i,j);
var targetedId2 = indexToId(i+1,j);
var targetedId3 = indexToId(i+2,j);
var targetedId4 = indexToId(i+3,j);
$(targetedId1).css("background","black");
$(targetedId2).css("background","black");
$(targetedId3).css("background","black");
$(targetedId4).css("background","black");
$("#result").fadeIn();
if(x==="player"){
x = playerName;
}
$("#result p").text(x+ " won.");
$("#selectPlayer1").hide();
$( "body" )
.off( "click", "#grid", flash )
.find( "#grid" )
.text( "game over" );
return;
}
//vertical block ends
//diagonal block starts here
if(j+3<=6 && i-3>=0 && grid[i][j]===x && grid[i-1][j+1]===x && grid[i-2][j+2]===x && grid[i-3][j+3]===x){
var targetedId1 = indexToId(i,j);
var targetedId2 = indexToId(i-1,j+1);
var targetedId3 = indexToId(i-2,j+2);
var targetedId4 = indexToId(i-3,j+3);
$(targetedId1).css("background","black");
$(targetedId2).css("background","black");
$(targetedId3).css("background","black");
$(targetedId4).css("background","black");
$("#result").fadeIn();
if(x==="player"){
x = playerName;
}
$("#result p").text(x+ " won.");
$("#selectPlayer1").hide();
$( "body" )
.off( "click", "#grid", flash )
.find( "#grid" )
.text( "game over" );
return;
}
if( i+3<=5 && j+3<=6 && grid[i][j]===x && grid[i+3][j+3]===x && grid[i+2][j+2]===x && grid[i+1][j+1]===x){
var targetedId1 = indexToId(i,j);
var targetedId2 = indexToId(i+3,j+3);
var targetedId3 = indexToId(i+2,j+2);
var targetedId4 = indexToId(i+1,j+1);
$(targetedId1).css("background","black");
$(targetedId2).css("background","black");
$(targetedId3).css("background","black");
$(targetedId4).css("background","black");
$("#result").fadeIn();
if(x==="player"){
x = playerName;
}
$("#result p").text(x+ " won.");
$("#selectPlayer1").hide();
$( "body" )
.off( "click", "#grid", flash )
.find( "#grid" )
.text( "game over" );
return;
}
//diagonal block ends here
}//col loop ends
}//row loop ends
return;
}
/* winCheck block ends here*/
/*
grid[i][j] = "robot";
var targetedId = indexToId(i,j);
$(targetedId).css("background","#800000");
*/
|
5c373899b3db587a36a13f94df2e16529a04c8e6
|
[
"JavaScript"
] | 1
|
JavaScript
|
saadixl/connect4
|
dc42e81307c50699aeb25b96f86a92f92afdab94
|
8de975fed8029a0a51883d7a9e189c46c098b404
|
refs/heads/master
|
<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: ESIndexController
* version: 1.0.0
* date: 2019/3/28
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.web.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bkjk.es.ops.common.PageVO;
import com.bkjk.es.ops.common.ResultVO;
import com.bkjk.es.ops.model.IndexInfoVo;
import com.bkjk.es.ops.model.JobInfoPo;
import com.bkjk.es.ops.model.QueryDateReq;
import com.bkjk.es.ops.model.SimpleData;
import com.bkjk.es.ops.service.ESIndexService;
import com.bkjk.es.ops.util.DataTransferUtil;
import com.bkjk.es.ops.util.LocalDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
/**
* @author Tyson
* @version V1.0
* @Description: TODO
* @date 2019/3/28下午3:54
*/
@RestController
@RequestMapping("/es")
@Slf4j
public class ESIndexController {
@Resource
private ESIndexService esIndexService;
@GetMapping("/indexs")
public PageVO<IndexInfoVo> getAllBackend(@RequestParam(value = "offset", defaultValue = "0") Integer offset,
@RequestParam(value = "limit", defaultValue = "10") Integer limit) {
return esIndexService.getAllIndex(offset, limit);
}
@GetMapping(value = "/exportESInfo")
public void export(HttpServletRequest request, HttpServletResponse response,
String str) {
QueryDateReq queryDateReq = new QueryDateReq();
queryDateReq.setIndexs(Arrays.asList(str.split(",")));
StringBuilder file = new StringBuilder("ES数据").append("%s.txt");
String fileName = String.format(file.toString(), LocalDateTimeUtils.formatNow("yyyyMMdd"));
String agent = request.getHeader("USER-AGENT").toLowerCase();
OutputStream out = null;
try {
List<SimpleData> esData = esIndexService.getEsData(queryDateReq);
out = response.getOutputStream();
JSONArray jsonObject = JSON.parseArray(JSON.toJSONString(esData));
byte[] bytes = jsonObject.toJSONString().getBytes("UTF-8");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
out.write(bytes);
out.flush();
} catch (Exception ex) {
log.error("导出失败:", ex);
}
}
@PostMapping(value = "/import", produces = "application/json;charset=UTF-8")
public ResultVO fileUpload(HttpServletRequest request, @RequestParam(required = false) MultipartFile file) throws IOException {
if (file.isEmpty()) {
return new ResultVO(false);
}
List<SimpleData> esData = null;
try {
JSONArray jsonArray = DataTransferUtil.ConvertToJsonArray(file);
List<SimpleData> simpleDataList = jsonArray.toJavaList(SimpleData.class);
esIndexService.batchCreateESData(simpleDataList);
} catch (Exception e) {
return new ResultVO(false, e.getMessage());
}
return new ResultVO(true);
}
@PostMapping("/job")
public ResultVO addJobInfo(@Validated @RequestBody JobInfoPo jobInfoPo, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ResultVO(false, bindingResult.getFieldError().getDefaultMessage());
}
try {
esIndexService.addJob(jobInfoPo);
} catch (Exception e) {
return new ResultVO(false, e.getMessage());
}
return new ResultVO(true);
}
}
<file_sep>SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for job_info
-- ----------------------------
-- DROP TABLE IF EXISTS `job_info`;
CREATE TABLE `job_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`corn` varchar(255) DEFAULT NULL,
`index_name` varchar(255) DEFAULT NULL,
`operate_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE SPRING_SESSION (
PRIMARY_ID CHAR(36) NOT NULL,
SESSION_ID CHAR(36) NOT NULL,
CREATION_TIME BIGINT NOT NULL,
LAST_ACCESS_TIME BIGINT NOT NULL,
MAX_INACTIVE_INTERVAL INT NOT NULL,
EXPIRY_TIME BIGINT NOT NULL,
PRINCIPAL_NAME VARCHAR(100),
CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID)
) ENGINE=InnoDB ROW_FORMAT=DYNAMIC;
CREATE UNIQUE INDEX SPRING_SESSION_IX1 ON SPRING_SESSION (SESSION_ID);
CREATE INDEX SPRING_SESSION_IX2 ON SPRING_SESSION (EXPIRY_TIME);
CREATE INDEX SPRING_SESSION_IX3 ON SPRING_SESSION (PRINCIPAL_NAME);
CREATE TABLE SPRING_SESSION_ATTRIBUTES (
SESSION_PRIMARY_ID CHAR(36) NOT NULL,
ATTRIBUTE_NAME VARCHAR(200) NOT NULL,
ATTRIBUTE_BYTES BLOB NOT NULL,
CONSTRAINT SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY (SESSION_PRIMARY_ID, ATTRIBUTE_NAME),
CONSTRAINT SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY (SESSION_PRIMARY_ID) REFERENCES SPRING_SESSION(PRIMARY_ID) ON DELETE CASCADE
) ENGINE=InnoDB ROW_FORMAT=DYNAMIC;<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: QuartzConfig
* version: 1.0.0
* date: 2019/3/29
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.config;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
/**
* @author Tyson
* @version V1.0
* @Description: TODO
* @date 2019/3/29下午8:12
*/
@Configuration
public class QuartzConfig {
@Bean(name = "Scheduler")
public Scheduler scheduler() throws IOException {
Scheduler scheduler = null;
try {
scheduler = new StdSchedulerFactory().getScheduler();
} catch (SchedulerException e) {
e.printStackTrace();
}
return scheduler;
}
}
<file_sep>$("#f_upload").change(function(){
var file = this.files[0];
var formData = new FormData(); //$('#file')[0].files[0]
formData.append("file",file);
$.ajax({
type:"post",
url:"/es/import",
data:formData,
contentType: false,
processData: false,
cache: false,
success: function (data) {
if (ajaxIsSuccess(data)) {
swal({
title: "上传成功!",
text: "上传成功!",
type: "success"
}, function (e) {
removeIframe();
});
} else {
swal("上传失败!", "上传失败。", "error");
}
}
})
})<file_sep># 开发
开发机启动参数 `-Xmx1G -Xms1G -Dspring.profiles.active=local `
当`spring.profiles.active=dev`且数据库中无数据时,会自动创建两条测试数据
## 数据库
修改`pom.xml`中`flyway-maven-plugin`的数据库链接信息后,执行下面命令初始化数据库
```text
mvn flyway:migrate
```
## 使用步骤
* 构建Docker镜像
```
mvn -DskipTests=true install
docker build . -t influx-proxy-ops:latest
```
* 登录权限配置
可以通过启动参数来指定AD配置。其中LDAP_URL、LDAP_DOMAIN是必须字段,LDAP_ADMIN_USER_NAME用来配置哪个账号是管理员(只有管理员有增删改权限)。
```yaml
ldap:
url: ${LDAP_URL:ldap://corp.bkjk.com:389}
adminUserName: ${LDAP_ADMIN_USER_NAME:shaoze.wang,admin}
domain: ${LDAP_DOMAIN:corp.bkjk.com}
userDNPattern: ${LDAP_USER_DN_PATTERN:}
```
* 运行容器
```
docker run --name es-ops -d -p 8080:8080 -p 8081:8081 -e JAVA_OPTS="-Xmx1G -Xms1G" -e MYSQL_HOST=10.241.1.167:3306 -e MYSQL_USER=admin -e MYSQL_PASSWORD=<PASSWORD> es-ops
```
<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: DataTransferUtil
* version: 1.0.0
* date: 2019/3/29
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author Tyson
* @version V1.0
* @Description: TODO
* @date 2019/3/29下午3:24
*/
@Slf4j
public class DataTransferUtil {
public static JSONArray ConvertToJsonArray(MultipartFile file) {
JSONArray jsonArray = null;
BufferedReader reader = null;
StringBuilder jsonStrs = new StringBuilder();
InputStream inputStream = null;
try {
InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream(), "UTF-8");
reader = new BufferedReader(inputStreamReader);
String tempStr = null;
while ((tempStr = reader.readLine()) != null) {
jsonStrs.append(tempStr);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info(jsonStrs.toString());
try {
jsonArray = JSONArray.parseArray(jsonStrs.toString().trim());
} catch (IllegalStateException ex) {
log.error("JSON File is wrong");
} catch (JSONException ex) {
log.error("JSON File is wrong");
}
return jsonArray;
}
}
<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: SimpleData
* version: 1.0.0
* date: 2019/3/28
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/**
* @author Tyson
* @version V1.0
* @Description: 导出数据样本
* @date 2019/3/28上午11:07
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SimpleData {
private String index;
private String type;
private Map<String, String> data;
}
<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: LocalDateTimeUtils
* version: 1.0.0
* date: 2018/8/14
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.util;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
/**
* @author Tyson
* @version V1.0
* @Description: LocalDateTime时间工具类
* @date 2018/8/14上午10:45
*/
public class LocalDateTimeUtils {
//默认使用系统当前时区
private static final ZoneId ZONE = ZoneId.systemDefault();
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
private static final String TIME_NOFUII_FORMAT = "yyyyMMddHHmmss";
private static final String REGEX = "\\:|\\-|\\s";
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//Date转换为LocalDateTime
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
//LocalDateTime转换为Date
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
//获取指定日期的毫秒
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
//获取指定日期的秒
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
//获取指定时间的指定格式
public static String formatTime(LocalDateTime time, String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
//获取当前时间的指定格式
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
//日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
//日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
return time.minus(number, field);
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) {
return period.getYears();
}
if (field == ChronoUnit.MONTHS) {
return period.getYears() * 12 + period.getMonths();
}
return field.between(startTime, endTime);
}
//获取一天的开始时间,2017,7,22 00:00
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
}
//获取一天的结束时间,2017,7,22 23:59:59.999999999
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999999);
}
/**
* 根据传入的时间格式返回系统当前的时间
*
* @param format string
* @return
*/
public static String timeByFormat(String format) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
LocalDateTime now = LocalDateTime.now();
return now.format(dateTimeFormatter);
}
/**
* 将Date转换成LocalDateTime
*
* @param d date
* @return
*/
public static LocalDateTime dateToLocalDateTime(Date d) {
Instant instant = d.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZONE);
return localDateTime;
}
/**
* 将Date转换成LocalDate
*
* @param d date
* @return
*/
public static LocalDate dateToLocalDate(Date d) {
Instant instant = d.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZONE);
return localDateTime.toLocalDate();
}
/**
* 将Date转换成LocalTime
*
* @param d date
* @return
*/
public static LocalTime dateToLocalTime(Date d) {
Instant instant = d.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZONE);
return localDateTime.toLocalTime();
}
/**
* 获取当前时间的整点时间
*
* @return
*/
public static LocalDateTime getHourTime() {
return LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
}
/**
* 将LocalDate转换成Date
*
* @param localDate
* @return date
*/
public static Date localDateToDate(LocalDate localDate) {
Instant instant = localDate.atStartOfDay().atZone(ZONE).toInstant();
return Date.from(instant);
}
/**
* 将LocalDateTime转换成Date
*
* @param localDateTime
* @return date
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
Instant instant = localDateTime.atZone(ZONE).toInstant();
return Date.from(instant);
}
/**
* 将相应格式yyyy-MM-dd yyyy-MM-dd HH:mm:ss 时间字符串转换成Date
*
* @param time string
* @param format string
* @return date
*/
public static Date stringToDate(String time, String format) {
DateTimeFormatter f = DateTimeFormatter.ofPattern(format);
if (DATE_FORMAT_DEFAULT.equals(format)) {
return LocalDateTimeUtils.localDateTimeToDate(LocalDateTime.parse(time, f));
} else if (DATE_FORMAT.equals(format)) {
return LocalDateTimeUtils.localDateToDate(LocalDate.parse(time, f));
}
return null;
}
/**
* 将相应格式yyyy-MM-dd yyyy-MM-dd HH:mm:ss 时间字符串转换成Date
*
* @param time string
* @return date
*/
public static LocalDate stringToLocalDate(String time) {
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyyMMdd");
return LocalDate.parse(time, f);
}
public static void main(String[] args) {
String yyyyMMdd = formatNow("yyyyMMdd");
LocalDateTime localDateTime = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
LocalDate localDate = stringToLocalDate("20181217");
String s = LocalDateTimeUtils.formatTime(localDateTime, "yyyy-MM-dd HH:mm");
int i = LocalDate.now().compareTo(localDate);
String s1 = LocalDateTimeUtils.formatTime(localDateTime.plusHours(1), "HH:mm");
String s2 = new StringBuilder(LocalDateTimeUtils.formatTime(localDateTime, "yyyy-MM-dd HH:mm")).append("~").append(LocalDateTimeUtils.formatTime(localDateTime.plusHours(1), "HH:mm")).toString();
System.out.println(yyyyMMdd);
}
}
<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: QueryDateReq
* version: 1.0.0
* date: 2019/3/28
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.model;
import lombok.Data;
import java.util.List;
/**
* @author Tyson
* @version V1.0
* @Description: TODO
* @date 2019/3/28上午11:27
*/
@Data
public class QueryDateReq {
private List<String> indexs;
}
<file_sep>/**
* =============================================================
* Copyright 2018 Lianjia Group All Rights Reserved
* CompanyName: 上海链家有限公司
* SystemName: 贝壳
* ClassName: ESBanckupJob
* version: 1.0.0
* date: 2019/3/29
* author: Tyson
* =============================================================
*/
package com.bkjk.es.ops.job;
import com.bkjk.es.ops.service.ESIndexService;
import com.sun.tools.javac.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
/**
*
* @Description: TODO
* @author Tyson
* @date 2019/3/29下午4:38
* @version V1.0
*/
@Slf4j
public class ESBanckupJob {
@Autowired
private ESIndexService esIndexService;
@Scheduled(cron = "0 0 23 * * ?")
public void execute() {
try {
log.info("导出数据生成文件开始");
Assert.check(esIndexService.getAllEsData(), "导出失败");
} catch (Exception e){
log.error("导出失败:{}",e.getMessage());
}
finally {
log.info("导出数据生成文件结束 ...");
}
}
}
|
6e34b0e6b81619f1bc1a940cbc0c272fda51fc49
|
[
"JavaScript",
"Java",
"Markdown",
"SQL"
] | 10
|
Java
|
Tangjinquan/es-ops
|
657d224853cf1b9dddcea4f62d08a7609d206d6c
|
ccf52c6dae00585985024370a15576f6ac03fcd6
|
refs/heads/master
|
<repo_name>fbonilla/tableSportEvent<file_sep>/BasicTable/BasicTable/MyEventListViewAdapter.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
namespace BasicTable
{
public class MyEventListViewAdapter : BaseAdapter<SportEvent>
{
private List<SportEvent> mItems;
private Context mContext;
private EntrySportEvent entrySportEvent;
private SportEventSeparator separator;
//private LayoutInflater vi;
public MyEventListViewAdapter (Context context, List<SportEvent> Items)
{
mContext = context;
mItems = Items;
//vi = (LayoutInflater)context.GetSystemService (Context.LayoutInflaterService);
}
public override int Count
{
get {return mItems.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override SportEvent this[int position]
{
get {return mItems[position]; }
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
View row = convertView;
//if (row == null) {
// row = LayoutInflater.FromContext (mContext).Inflate (Resource.Layout.ListEvents_row, null, false);
//}
SportEvent se = mItems[position];
//Checks if it's a seperator
if (se.isSection()) {
separator = (SportEventSeparator)se;
row = LayoutInflater.FromContext (mContext).Inflate (Resource.Layout.ListEventsSeparator, null, false);
TextView sectionView = row.FindViewById<TextView> (Resource.Id.listItemSection);
sectionView.Text = separator.mDate;
} else {
row = LayoutInflater.FromContext (mContext).Inflate (Resource.Layout.ListEvents_row, null, false);
TextView textEventTitle = row.FindViewById<TextView> (Resource.Id.textEventTitle);
TextView textEventTime = row.FindViewById<TextView> (Resource.Id.textEventTime);
ImageView imageViewIcon = row.FindViewById<ImageView> (Resource.Id.iconSport);
entrySportEvent = (EntrySportEvent)mItems [position];
textEventTitle.Text = entrySportEvent.mEventTitle;
textEventTime.Text = entrySportEvent.mEventTime;
imageViewIcon.SetImageDrawable (entrySportEvent.mEventIcon);
}
return row;
}
}
}
<file_sep>/BasicTable/BasicTable/SportEventSeparator.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace BasicTable
{
//The class SportEventSeparator is used to seperates events by a given date
public class SportEventSeparator : SportEvent
{
public String mDate { get; set;}
public SportEventSeparator (String date)
{
mDate = date;
}
public Boolean isSection()
{
return true;
}
}
}
<file_sep>/BasicTable/BasicTable/SportEvent.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace BasicTable
{
public interface SportEvent
{
Boolean isSection ();
}
}
<file_sep>/BasicTable/BasicTable/MainActivity.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using Android.Views.Animations;
namespace BasicTable
{
[Activity (Label = "BasicTable", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
// int count = 1;
private List<SportEvent> mItems;
private ListView mListView;
private MyEventListViewAdapter adapter;
private LinearLayout layoutMonthEvent;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
layoutMonthEvent = FindViewById<LinearLayout> (Resource.Id.layoutMonthEvent);
mListView = FindViewById<ListView> (Resource.Id.listViewEvents);
mItems = new List<SportEvent>();
mItems.Add (new SportEventSeparator("Tomorrow/Wednesday. January 18"));
mItems.Add (new EntrySportEvent ("Predators @ Oilers", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Toronto FC @ Impact", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_soccer)));
mItems.Add (new SportEventSeparator("Thursday. January 19"));
mItems.Add (new EntrySportEvent ("Patriots @ Packers", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_american_football)));
mItems.Add (new EntrySportEvent ("Kovalev vs Jean-Pascal", "9:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_boxing)));
mItems.Add (new EntrySportEvent ("Canadiens @ Flyers ", "9:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Bruins @ Predators", "10:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new SportEventSeparator("Friday. January 20"));
mItems.Add (new EntrySportEvent ("FC Barcelona @ Real Madrid", "1:00 PM", this.Resources.GetDrawable(Resource.Drawable.icon_soccer)));
mItems.Add (new EntrySportEvent ("<NAME> vs <NAME>", "4:00 PM", this.Resources.GetDrawable(Resource.Drawable.icon_tennis)));
mItems.Add (new EntrySportEvent ("Maple Leafs @ Bruins", "7:00 PM", this.Resources.GetDrawable (Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Cannucks @ Kings", "10:00 PM", this.Resources.GetDrawable (Resource.Drawable.icon_icehockey)));
adapter = new MyEventListViewAdapter (this, mItems);
mListView.Adapter = adapter;
var slideToTheRight = AnimationUtils.LoadAnimation (this, Resource.Animation.right_swipe);
var slideToTheLeft = AnimationUtils.LoadAnimation (this, Resource.Animation.left_swipe);
var backSwipe = AnimationUtils.LoadAnimation (this, Resource.Animation.back_swipe);
Button btnNextMonth = FindViewById<Button> (Resource.Id.buttonNextMonth);
btnNextMonth.Click += delegate {
//Normally, a server request would replace all this to refresh the data for ths list of events to show.
layoutMonthEvent.StartAnimation(slideToTheRight);
TextView txtMonth = FindViewById<TextView> (Resource.Id.textMonth);
txtMonth.Text = "February 2015";
mItems.Clear();
//mItems = new List<SportEvent>();
mItems.Add (new SportEventSeparator("Tomorrow/Wednesday. February 18"));
mItems.Add (new EntrySportEvent ("Jets @ Flames", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("New York FC @ Toronto FC", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_soccer)));
mItems.Add (new SportEventSeparator("Thursday. February 19"));
mItems.Add (new EntrySportEvent ("Steelers @ NY Giants", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_american_football)));
mItems.Add (new EntrySportEvent ("<NAME> vs <NAME>", "9:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_boxing)));
mItems.Add (new EntrySportEvent ("Canadiens @ Bruins ", "9:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Senators @ Maple Leafs", "10:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new SportEventSeparator("Friday. February 20"));
mItems.Add (new EntrySportEvent ("Juventus @ Atletico Madrid", "1:00 PM", this.Resources.GetDrawable(Resource.Drawable.icon_soccer)));
mItems.Add (new EntrySportEvent ("<NAME> vs <NAME>", "4:00 PM", this.Resources.GetDrawable(Resource.Drawable.icon_tennis)));
mItems.Add (new EntrySportEvent ("Blackhawls @ Panthers", "7:00 PM", this.Resources.GetDrawable (Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Sharks @ Avalanche", "10:00 PM", this.Resources.GetDrawable (Resource.Drawable.icon_icehockey)));
adapter.NotifyDataSetChanged();
//layoutMonthEvent.StartAnimation(backSwipe);
};
Button btnPreviousMonth = FindViewById<Button> (Resource.Id.buttonPreviousMonth);
btnPreviousMonth.Click += delegate {
//Normally, a server request would replace all this to refresh the data for ths list of events to show.
layoutMonthEvent.StartAnimation(slideToTheLeft);
TextView txtMonth = FindViewById<TextView> (Resource.Id.textMonth);
txtMonth.Text = "January 2015";
mItems.Clear();
mItems.Add (new SportEventSeparator("Tomorrow/Wednesday. January 18"));
mItems.Add (new EntrySportEvent ("Predators @ Oilers", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Toronto FC @ Impact", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_soccer)));
mItems.Add (new SportEventSeparator("Thursday. January 19"));
mItems.Add (new EntrySportEvent ("Patriots @ Packers", "7:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_american_football)));
mItems.Add (new EntrySportEvent ("Kovalev vs Jean-Pascal", "9:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_boxing)));
mItems.Add (new EntrySportEvent ("Canadiens @ Flyers ", "9:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Bruins @ Predators", "10:30 PM", this.Resources.GetDrawable(Resource.Drawable.icon_icehockey)));
mItems.Add (new SportEventSeparator("Friday. January 20"));
mItems.Add (new EntrySportEvent ("FC Barcelona @ Real Madrid", "1:00 PM", this.Resources.GetDrawable(Resource.Drawable.icon_soccer)));
mItems.Add (new EntrySportEvent ("<NAME> vs <NAME>", "4:00 PM", this.Resources.GetDrawable(Resource.Drawable.icon_tennis)));
mItems.Add (new EntrySportEvent ("Maple Leafs @ Bruins", "7:00 PM", this.Resources.GetDrawable (Resource.Drawable.icon_icehockey)));
mItems.Add (new EntrySportEvent ("Cannucks @ Kings", "10:00 PM", this.Resources.GetDrawable (Resource.Drawable.icon_icehockey)));
adapter.NotifyDataSetChanged();
};
}
}
}
<file_sep>/BasicTable/BasicTable/EntrySportEvent.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Graphics.Drawables;
namespace BasicTable
{
public class EntrySportEvent : SportEvent
{
//Attributs of a SportEvent represented by a title, a time and a sport icon
public String mEventTitle{ get; set;}
public String mEventTime{ get; set;}
public Drawable mEventIcon{ get; set;}
//Conctrustor of the SportEvent Modal represented inside the ListView located in the event section
public EntrySportEvent (String eventTitle, String eventTime, Drawable eventIcon)
{
mEventTitle = eventTitle;
mEventTime = eventTime;
mEventIcon = eventIcon;
}
//Implemenation by interface SportEventInterface
public Boolean isSection()
{
return false;
}
}
}
|
60aa6c29356e3234619eb9821f322b8f9cf5b27c
|
[
"C#"
] | 5
|
C#
|
fbonilla/tableSportEvent
|
a180aa6eac9476cce2bb9990a533f29e41e050c7
|
c9648432a30cbf96dac3c7aca9d7f920ce1e2935
|
refs/heads/main
|
<file_sep>from tkinter import *
import mysql.connector
def view_func():
conn = mysql.connector.connect(host="localhost", user="root", password="", db="bookstore")
cursor = conn.cursor()
s = "SELECT * FROM booksrecord"
cursor.execute(s)
r=cursor.fetchall()
#print(r[0][0])
#print(len(r))
for i in range(0,len(r)):
listbox.insert(i,r[i])
def add():
print(title1.get())
print(author.get())
print(year.get())
print(isbn.get())
conn = mysql.connector.connect(host ="localhost",user = "root",password = "",db ="bookstore")
cursor = conn.cursor()
s="INSERT INTO booksrecord(title,auther,year,isbn) VALUES (%s, %s ,%s,%s)"
b1=(title1.get(),author.get(),year.get(),isbn.get())
cursor.execute(s,b1)
conn.commit()
print("thank you")
def delete():
conn = mysql.connector.connect(host="localhost", user="root", password="", db="bookstore")
cursor = conn.cursor()
s="delete from booksrecord"
cursor.execute(s)
conn.commit()
print("record gayab")
def update():
conn = mysql.connector.connect(host="localhost", user="root", password="", db="bookstore")
cursor = conn.cursor()
s=("UPDATE booksrecord SET title='test',auther='sudhanshu' where id=9")
cursor.execute(s)
conn.commit()
print("aa gya naya record")
win=Tk()
win.title("Book Store System")
lable1= Label(win,text="Title")
lable2= Label(win,text="Auther")
lable3=Label(win,text="Year")
lable4=Label(win,text="ISBN")
title_text = StringVar()
title1 = Entry(win, textvariable= title_text)
author_text = StringVar()
author = Entry(win, textvariable= author_text)
year_text = StringVar()
year = Entry(win, textvariable= year_text)
isbn_text = StringVar()
isbn = Entry(win, textvariable= isbn_text)
listbox = Listbox(win, height=6, width=35)
listbox.grid(row=2, column =0, rowspan=6, columnspan=2)
sb1 =Scrollbar(win)
sb1.grid(row=2, column=2 ,rowspan = 6)
listbox.configure(yscrollcommand=sb1.set)
sb1.configure(command=listbox.yview)
b1 =Button(win, text= "View All", width=12,command=view_func)
b1.grid(row=2, column=3)
b2 =Button(win, text= "Search Book", width=12)
b2.grid(row=3, column=3)
b3 =Button(win, text= "Add Book", width=12, command=add)
b3.grid(row=4, column=3)
b4 =Button(win, text= "Update", width=12,command=update)
b4.grid(row=5, column=3)
b5 =Button(win, text= "Delete", width=12,command=delete)
b5.grid(row=6, column=3)
b6 =Button(win, text= "Close", width=12,command=win.destroy)
b6.grid(row=7, column=3)
lable1.grid(row=0,column=0)
lable2.grid(row=0,column=2)
lable3.grid(row=1,column=0)
lable4.grid(row=1,column=2)
title1.grid(row=0, column=1)
author.grid(row=0, column=3)
year.grid(row=1, column=1)
isbn.grid(row=1, column=3)
win.mainloop()<file_sep>import mysql.connector
conn = mysql.connector.connect(host ="localhost",user = "root",password = "",db ="bookstore")
cursor = conn.cursor()
print(conn)
|
a31da67dd03a53c8e4c9d42d3a99fdc988d33e9f
|
[
"Python"
] | 2
|
Python
|
vijay19956757/bookstoretkinter-web-application
|
09ae9e83a9b1eb7f66db5bee0ec47501ad9f45bf
|
8c39bd5a28e0a3acd36988d1be79c4ce17363491
|
refs/heads/master
|
<repo_name>schubalibre/coding-challenges<file_sep>/Backend/mapping/src/test/java/com/mhp/coding/challenges/mapping/mappers/ArticleMapperTest.java
package com.mhp.coding.challenges.mapping.mappers;
import com.mhp.coding.challenges.mapping.Application;
import com.mhp.coding.challenges.mapping.models.db.Article;
import com.mhp.coding.challenges.mapping.models.dto.ArticleDto;
import com.mhp.coding.challenges.mapping.models.dto.blocks.ArticleBlockDto;
import com.mhp.coding.challenges.mapping.repositories.ArticleRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Application.class)
public class ArticleMapperTest {
@Autowired
private ArticleMapper mapper;
private Article article;
@Before
public void setUp() {
ArticleRepository repository = new ArticleRepository();
List<Article> list = repository.all();
article = list.get(0);
}
@Test
public void map_can_convert_an_Article_to_an_ArticleDto() {
ArticleDto dto = mapper.map(article);
assertEquals("ID have to match", article.getId(), dto.getId());
assertEquals("description have to match", article.getDescription(), dto.getDescription());
assertEquals("Author have to match", article.getAuthor(), dto.getAuthor());
assertEquals("Title have to match", article.getTitle(), dto.getTitle());
assertEquals("Number of block elements have to match", article.getBlocks().size(), dto.getBlocks().size());
}
@Test
public void it_returns_the_article_blocks_in_the_right_order() {
ArticleDto dto = mapper.map(article);
Collection<ArticleBlockDto> blocks = dto.getBlocks();
int prevSortIndex = -1;
for (ArticleBlockDto block : blocks) {
if (prevSortIndex == -1) {
prevSortIndex = block.getSortIndex();
} else {
int curr = block.getSortIndex();
assertTrue("Previous SortIndex (" + prevSortIndex + ") should be lower than current (" + curr + ")", prevSortIndex <= curr);
}
}
}
}
<file_sep>/Backend/mapping/src/main/java/com/mhp/coding/challenges/mapping/mappers/ArticleBlockMapper.java
package com.mhp.coding.challenges.mapping.mappers;
import com.mhp.coding.challenges.mapping.exceptions.UnknownArticleBlockTypeException;
import com.mhp.coding.challenges.mapping.models.db.Image;
import com.mhp.coding.challenges.mapping.models.db.blocks.ArticleBlock;
import com.mhp.coding.challenges.mapping.models.db.blocks.GalleryBlock;
import com.mhp.coding.challenges.mapping.models.dto.ImageDto;
import com.mhp.coding.challenges.mapping.models.dto.blocks.*;
import org.springframework.stereotype.Component;
import static java.util.stream.Collectors.toList;
@Component
public class ArticleBlockMapper {
private ImageDto getImageDto(Image image) {
ImageDto imageDto = new ImageDto();
imageDto.setId(image.getId());
imageDto.setImageSize(image.getImageSize());
imageDto.setUrl(image.getUrl());
return imageDto;
}
public ImageBlock mapToDto(com.mhp.coding.challenges.mapping.models.db.blocks.ImageBlock imageBlock) {
ImageBlock block = new ImageBlock();
ImageDto dto = getImageDto(imageBlock.getImage());
block.setImage(dto);
block.setSortIndex(imageBlock.getSortIndex());
return block;
}
public GalleryBlockDto mapToDto(GalleryBlock galleryBlock) {
GalleryBlockDto dto = new GalleryBlockDto();
dto.setImages(galleryBlock
.getImages()
.stream()
.map(this::getImageDto)
.collect(toList())
);
dto.setSortIndex(galleryBlock.getSortIndex());
return dto;
}
public TextBlock mapToDto(com.mhp.coding.challenges.mapping.models.db.blocks.TextBlock textBlock) {
TextBlock block = new TextBlock();
block.setSortIndex(textBlock.getSortIndex());
block.setText(textBlock.getText());
return block;
}
public VideoBlock mapToDto(com.mhp.coding.challenges.mapping.models.db.blocks.VideoBlock videoBlock) {
VideoBlock block = new VideoBlock();
block.setType(videoBlock.getType());
block.setUrl(videoBlock.getUrl());
block.setSortIndex(videoBlock.getSortIndex());
return block;
}
public ArticleBlockDto mapToDto(ArticleBlock articleBlock) {
throw new UnknownArticleBlockTypeException(articleBlock.getClass().getSimpleName());
}
}
<file_sep>/Backend/dependency/inquiry/src/main/java/com/mhp/coding/challenges/dependency/inquiry/InquiryServiceInterface.java
package com.mhp.coding.challenges.dependency.inquiry;
public interface InquiryServiceInterface {
void notify(final Inquiry inquiry);
}
|
c8db90e34ca076a685f89643f8a614fa908af5f3
|
[
"Java"
] | 3
|
Java
|
schubalibre/coding-challenges
|
8290f843363432d446af0282b8ddc0847b28b33c
|
c2f36280e7f51325c5d0484cb72fd97274678127
|
refs/heads/master
|
<repo_name>PostRecommenderProject/WebSpider<file_sep>/WebSpider/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class JobPipeline(object):
quotes_name = 'quotes'
author_name = 'author'
def __init__(self, settings):
self.settings = settings
def process_item(self, item, spider):
print(item)
if spider.name == "zlzp":
sql = "insert into job (job_name,job_pay,job_workplace,job_dec,job_min_edu,job_exp,company_welfare,company_name,company_ind,company_size) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# 执行sql语句
self.cursor.execute(sql, (item['job_name'], item['job_pay'],item['job_workplace'], item['job_dec'],
item['job_min_edu'],item['job_exp'],item['company_welfare'],item['company_name'],
item['company_ind'],item['company_size'],))
elif spider.name == "author":
pass
# sqltext = self.authorInsert.format(
# name=pymysql.escape_string(item['name']),
# birthdate=pymysql.escape_string(item['birthdate']),
# bio=pymysql.escape_string(item['bio']))
# self.cursor.execute(sqltext)
else:
spider.log('Undefined name: %s' % spider.name)
return item
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def open_spider(self, spider):
# 连接数据库
self.connect = pymysql.connect(
host=self.settings.get('MYSQL_HOST'),
port=self.settings.get('MYSQL_PORT'),
db=self.settings.get('MYSQL_DBNAME'),
user=self.settings.get('MYSQL_USER'),
passwd=self.settings.get('MYSQL_PASSWD'),
charset='utf8',
use_unicode=True)
# 通过cursor执行增删查改
self.cursor = self.connect.cursor()
self.connect.autocommit(True)
def close_spider(self, spider):
self.cursor.close()
self.connect.close()
|
0566112a63de0172049e29ba7a72d2efe4b784fc
|
[
"Python"
] | 1
|
Python
|
PostRecommenderProject/WebSpider
|
bf334f8f4c27a218ebd517cb7677c8d8cd1f6a26
|
1f1aa4a6d8a4eeb5ee37b160806c63762842b810
|
refs/heads/development/master
|
<repo_name>yannikVole/cms<file_sep>/src/Controller/MediaController.php
<?php
namespace App\Controller;
use App\Entity\MediaItem;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @Route("/media")
* Class MediaController
* @package App\Controller
*/
class MediaController extends AbstractController{
/**
* @Route("/upload", name="media_upload")
*/
public function upload(Request $request){
$mediaItem = new MediaItem();
$form = $this->createFormBuilder($mediaItem)
->add("filename", FileType::class)
->add("description", TextType::class,[
"required" => false
])
->add("submit", SubmitType::class,[
"label" => "Upload"
])
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$mediaItem->setUser($this->getUser());
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = new UploadedFile($mediaItem->getFilename(),$mediaItem->getFilename());
// handle file upload and save path to database
$fileName = $this->generateUniqueFilename().'.'.$file->guessExtension();
try {
$file->move(
$this->getParameter("media_directory"),
$fileName
);
} catch (FileException $e){
die($e);
}
$mediaItem->setFilename($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($mediaItem);
$em->flush();
//redirect to uploaded media
return $this->redirect($this->generateUrl("media_show_item",[
"fileName" => $fileName
]));
}
return $this->render("media/upload.html.twig",[
"form" => $form->createView(),
]);
}
/**
* @Route("/all",name="media_show_all")
*/
public function all(){
$em = $this->getDoctrine()->getManager();
$mediaItems = $em->getRepository(MediaItem::class)->findAll();
return $this->render("media/show_all.html.twig",[
"mediaItems" => $mediaItems
]);
}
/**
* @Route("/show/{fileName}", name="media_show_item")
*/
public function show($fileName){
return $this->render("media/show.html.twig",[
"fileName" => $fileName
]);
}
private function generateUniqueFilename()
{
return md5(uniqid('', true));
}
}
|
7cf95a469e79357269b422f4680d8d8e552cbf05
|
[
"PHP"
] | 1
|
PHP
|
yannikVole/cms
|
d33d2cd3eacc43c50c17dbb7a4d96154989346ae
|
75396a9808249698a8bb155772aa4520f024a815
|
refs/heads/master
|
<repo_name>Wangyupeng-a/wdFriedchicken<file_sep>/wdFriedchicken/src/javabean/Adminly.java
package javabean;
public class Adminly {
public int adminlyid;
public Users user;
public String adminlytel;
public String adminlyemail;
public String adminlyneirong;
public String adminlytime;
public String getAdminlytime() {
return adminlytime;
}
public void setAdminlytime(String adminlytime) {
this.adminlytime = adminlytime;
}
public int getAdminlyid() {
return adminlyid;
}
public void setAdminlyid(int adminlyid) {
this.adminlyid = adminlyid;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public String getAdminlytel() {
return adminlytel;
}
public void setAdminlytel(String adminlytel) {
this.adminlytel = adminlytel;
}
public String getAdminlyemail() {
return adminlyemail;
}
public void setAdminlyemail(String adminlyemail) {
this.adminlyemail = adminlyemail;
}
public String getAdminlyneirong() {
return adminlyneirong;
}
public void setAdminlyneirong(String adminlyneirong) {
this.adminlyneirong = adminlyneirong;
}
@Override
public String toString() {
return "Adminly [adminlyid=" + adminlyid + ", user=" + user
+ ", adminlytel=" + adminlytel + ", adminlyemail="
+ adminlyemail + ", adminlyneirong=" + adminlyneirong
+ ", adminlytime=" + adminlytime + "]";
}
}
<file_sep>/wdFriedchicken/src/action/FukuanServlet.java
package action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javabean.Address;
import javabean.Shopcar;
import javabean.Users;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Addressdao;
import dao.Shopcardao;
import dao.Usersdao;
public class FukuanServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public FukuanServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int userid =Integer.parseInt(request.getParameter("userid"));
if ((userid==0)) {
request.getRequestDispatcher("/users/login.jsp").forward(request, response);
}else{
List<Shopcar> listshopcar = new ArrayList<Shopcar>();
Shopcardao shopcardao = new Shopcardao();
listshopcar = shopcardao.queryidShopcar(userid,0);
request.setAttribute("listshopcar", listshopcar);
//返回页面地址信息
List<Address> listaddress = new ArrayList<Address>();
Addressdao addressdao = new Addressdao();
listaddress = addressdao.queryuseridaddress(userid);
if (listaddress!=null&&listaddress.size()>0) {
request.setAttribute("addressshiqu", listaddress.get(0).getAddressshiqu().substring(3));
request.setAttribute("addressxiangxi", listaddress.get(0).getAddressxiangxi());
request.setAttribute("addresstel", listaddress.get(0).getAddresstel());
}
request.getRequestDispatcher("/checkout.jsp").forward(request, response);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
<file_sep>/wdFriedchicken/src/javabean/Shopcar.java
package javabean;
public class Shopcar {
public int carid;
public Users user;
public Sp sp;
public int carspnumber;
public int catok;
public String cartime;
public String getCartime() {
return cartime;
}
public void setCartime(String cartime) {
this.cartime = cartime;
}
public int getCarid() {
return carid;
}
public void setCarid(int carid) {
this.carid = carid;
}
public int getCarspnumber() {
return carspnumber;
}
public void setCarspnumber(int carspnumber) {
this.carspnumber = carspnumber;
}
public int getCatok() {
return catok;
}
public void setCatok(int catok) {
this.catok = catok;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public Sp getSp() {
return sp;
}
public void setSp(Sp sp) {
this.sp = sp;
}
@Override
public String toString() {
return "Shopcar [carid=" + carid + ", user=" + user + ", sp=" + sp
+ ", carspnumber=" + carspnumber + ", catok=" + catok
+ ", cartime=" + cartime + "]";
}
}
<file_sep>/wdFriedchicken/src/action/AdminupspServlet.java
package action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javabean.Sp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Spdao;
public class AdminupspServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public AdminupspServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int spid = Integer.parseInt(request.getParameter("spid"));
String spname = request.getParameter("spname");
String spimg = request.getParameter("spimg");
String spjieshao = request.getParameter("spjieshao");
int spjiage =Integer.parseInt(request.getParameter("spjiage"));
String spzhonglei = request.getParameter("spzhonglei");
Sp sp = new Sp();
sp.setSpid(spid);
sp.setSpname(spname);
sp.setSpjieshao(spjieshao);
sp.setSpjiage(spjiage);
sp.setSpimg("images/my/"+spimg);
sp.setSpzhonglei(spzhonglei);
Spdao sdao = new Spdao();
int n = sdao.updatesp(sp);
if (n==1) {
List<Sp> list = new ArrayList<Sp>();
list = sdao.queryallSp();
request.setAttribute("splist", list);
request.setAttribute("massage", "Ð޸ijɹ¦£¡");
request.getRequestDispatcher("/admin/allsp.jsp").forward(request, response);
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
<file_sep>/wdFriedchicken/src/action/SpinputServlet.java
package action;
import java.io.IOException;
import java.io.PrintWriter;
import javabean.Sp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Spdao;
public class SpinputServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public SpinputServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String spname = request.getParameter("spname");
String spimg = request.getParameter("spimg");
String spjieshao = request.getParameter("spjieshao");
int spjiage =Integer.parseInt(request.getParameter("spjiage")) ;
String spzhonglei = request.getParameter("spzhonglei");
Sp sp = new Sp();
sp.setSpname(spname);
sp.setSpimg("images/my/"+spimg);
sp.setSpjieshao(spjieshao);
sp.setSpjiage(spjiage);
sp.setSpzhonglei(spzhonglei);
Spdao spdao = new Spdao();
int n = spdao.addsp(sp);
if (n==1) {
request.setAttribute("massage", "Ìí¼Ó³É¹¦£¡");
request.getRequestDispatcher("/admin/addsp.jsp").forward(request, response);
}else{
request.setAttribute("massage", "Ìí¼Óʧ°Ü£¡");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
<file_sep>/wdFriedchicken/src/dao/Spdao.java
package dao;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import javabean.Sp;
public class Spdao extends Basedao {
// 显示所有的商品
public List<Sp> queryallSp() {
List<Sp> list = new ArrayList<Sp>();
super.getconn();
try {
pst = conn.prepareStatement("select * from sp ");
rs = pst.executeQuery();
while (rs.next()) {
Sp sp = new Sp();
sp.setSpid(rs.getInt("spid"));
sp.setSpname(rs.getString("spname"));
sp.setSpimg(rs.getString("spimg"));
sp.setSpjieshao(rs.getString("spjieshao"));
sp.setSptime(rs.getString("sptime"));
sp.setSpjiage(rs.getInt("spjiage"));
sp.setSpdianjinumber(rs.getInt("spdianjinumber"));
sp.setSpchengjiaonumber(rs.getInt("spchengjiaonumber"));
sp.setSpzhonglei(rs.getString("spzhonglei"));
list.add(sp);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return list;
}
// 根据id查商品
public Sp queryidSp(int id) {
Sp sp = new Sp();
super.getconn();
try {
pst = conn.prepareStatement("select * from sp where spid = ?");
pst.setInt(1, id);
rs = pst.executeQuery();
while (rs.next()) {
sp.setSpid(rs.getInt("spid"));
sp.setSpname(rs.getString("spname"));
sp.setSpimg(rs.getString("spimg"));
sp.setSpjieshao(rs.getString("spjieshao"));
sp.setSptime(rs.getString("sptime"));
sp.setSpjiage(rs.getInt("spjiage"));
sp.setSpdianjinumber(rs.getInt("spdianjinumber"));
sp.setSpchengjiaonumber(rs.getInt("spchengjiaonumber"));
sp.setSpzhonglei(rs.getString("spzhonglei"));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return sp;
}
// 根据类型查商品
public List<Sp> queryzhongleiSp(String spzhonglei) {
List<Sp> list = new ArrayList<Sp>();
super.getconn();
try {
pst = conn
.prepareStatement("select * from sp where spzhonglei = ?");
pst.setString(1, spzhonglei);
rs = pst.executeQuery();
while (rs.next()) {
Sp sp = new Sp();
sp.setSpid(rs.getInt("spid"));
sp.setSpname(rs.getString("spname"));
sp.setSpimg(rs.getString("spimg"));
sp.setSpjieshao(rs.getString("spjieshao"));
sp.setSptime(rs.getString("sptime"));
sp.setSpjiage(rs.getInt("spjiage"));
sp.setSpdianjinumber(rs.getInt("spdianjinumber"));
sp.setSpchengjiaonumber(rs.getInt("spchengjiaonumber"));
sp.setSpzhonglei(rs.getString("spzhonglei"));
list.add(sp);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return list;
}
// 根据商品名模糊查询
public List<Sp> querymohuSp(String spname) {
List<Sp> list = new ArrayList<Sp>();
super.getconn();
try {
pst = conn
.prepareStatement("select * from sp where spname like ?");
pst.setString(1, "%"+spname+"%");
rs = pst.executeQuery();
while (rs.next()) {
Sp sp = new Sp();
sp.setSpid(rs.getInt("spid"));
sp.setSpname(rs.getString("spname"));
sp.setSpimg(rs.getString("spimg"));
sp.setSpjieshao(rs.getString("spjieshao"));
sp.setSptime(rs.getString("sptime"));
sp.setSpjiage(rs.getInt("spjiage"));
sp.setSpdianjinumber(rs.getInt("spdianjinumber"));
sp.setSpchengjiaonumber(rs.getInt("spchengjiaonumber"));
sp.setSpzhonglei(rs.getString("spzhonglei"));
list.add(sp);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return list;
}
// 添加商品
public int addsp(Sp sp) {
int n = 0;
super.getconn();
try {
pst = conn
.prepareStatement("insert into sp VALUES(null,?,?,?,?,?,0,0,?)");
pst.setString(1, sp.getSpname());
pst.setString(2, sp.getSpimg());
pst.setString(3, sp.getSpjieshao());
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String shijian = dateFormat.format(now);
pst.setString(4, shijian);
pst.setInt(5, sp.getSpjiage());
pst.setString(6, sp.getSpzhonglei());
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return n;
}
// 修改商品信息
public int updatesp(Sp sp) {
int n = 0;
super.getconn();
try {
pst = conn
.prepareStatement("UPDATE sp SET spname = ?,spimg = ?,spjieshao=?,sptime=?,spjiage=?,spzhonglei=? "
+ "WHERE spid = ?");
pst.setString(1, sp.getSpname());
pst.setString(2, sp.getSpimg());
pst.setString(3, sp.getSpjieshao());
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String shijian = dateFormat.format(now);
pst.setString(4, shijian);
pst.setInt(5, sp.getSpjiage());
pst.setString(6, sp.getSpzhonglei());
pst.setInt(7, sp.getSpid());
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return n;
}
// 商品点击量
public int updatespdianjinumber(int spid, int number) {
int n = 0;
super.getconn();
try {
pst = conn
.prepareStatement("UPDATE sp SET spdianjinumber=? where spid =?");
pst.setInt(1, number);
pst.setInt(2, spid);
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return n;
}
// 商品成交量
public int updatespchengjiaonumber(int spid, int number) {
int n = 0;
super.getconn();
try {
pst = conn
.prepareStatement("UPDATE sp SET spchengjiaonumber=? where spid =?");
pst.setInt(1, number);
pst.setInt(2, spid);
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return n;
}
// 查询每种类型商品数量 1炸鸡 2汉堡 3小食 4饮料
public int[] queryzhongleinumber() {
int[] n ={0,0,0,0};
int m =0;
super.getconn();
try {
pst = conn
.prepareStatement("select * from sp where spzhonglei = ?");
for (int i = 0; i < 4; i++) {
if (i==0) {
pst.setString(1, "炸鸡");
}
if (i==1) {
pst.setString(1, "汉堡");
}
if (i==2) {
pst.setString(1, "小食");
}
if (i==3) {
pst.setString(1, "饮料");
}
rs = pst.executeQuery();
while(rs.next()){
m++;
}
n[i]=m;
m=0;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return n;
}
// 删除商品
public int deletesp(int id) {
int n = 0;
super.getconn();
try {
pst = conn.prepareStatement("delete from sp where spid = ?");
pst.setInt(1, id);
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.closeAll();
return n;
}
}
|
f508ea827d36370cf6643f758a7527e2e0aa4353
|
[
"Java"
] | 6
|
Java
|
Wangyupeng-a/wdFriedchicken
|
7af94efc2f811aad4a5db829f97bcde409735a18
|
0645eb9e969b70d9b65bd1011afb1417726cf8b9
|
refs/heads/master
|
<repo_name>dmedora/ExamSchedule<file_sep>/schedule_table.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
################### START NOTES ###################
# Current alternative to manually going through the list - check the syllabus for each class. But doesn't give you a nice visual representation easily.
################### END NOTES ###################
from bs4 import BeautifulSoup, SoupStrainer
# from selenium import webdriver
import requests, re
##########
## http://stackoverflow.com/questions/25539330/speeding-up-beautifulsoup
session = requests.Session()
response = session.get("http://registrar.berkeley.edu/sis-SC-message")
strainer = SoupStrainer("table")
soup = BeautifulSoup(response.content, "lxml", parse_only=strainer)
##########
# # driver = webdriver.Firefox()
# driver = webdriver.PhantomJS()
# # driver.save_screenshot("screen.png")
# driver.get("http://registrar.berkeley.edu/sis-SC-message")
# html = driver.page_source
# soup = BeautifulSoup(html, "lxml")
##########
table = soup.find("table")
# table_body = table.find("tbody")
# for row in table.find_all("tr")[1:]:
# for col in row.find_all("td"):
# print(col.get_text())
row_data = []
for row in table.find_all("tr")[2:-1]:
temp = []
cols = row.find_all("td")
cols = [ele.text.strip() for ele in cols]
# row_data.append([ele for ele in cols if ele])
row_data.append(cols)
# print(row_data)
for i in range(0, len(row_data)):
# if i == 2 or i == 8 or i == 13:
# continue
temp = row_data[i][4] # string
# temp = row_data[i][4].split(",")
temp = temp.replace(",", " ").replace("&", " ").replace(";", " ").replace("pm", " ").replace("am", " ").replace("MTWTH", "MTWTF").split() # list
row_data[i][4] = temp
# print(row_data)
def main():
return row_data
################### SCRAPYARD ###################
# result = soup.find_all("div", class_="product-review")
# for link in soup.find_all("a"):
# print(link.get("href",None),link.get_text())
# for tag in soup.find_all("title"):
# print(tag.text)
# print("~end~")
<file_sep>/app.py
#!/usr/bin/env/python3
from flask import Flask, render_template, request, json
import schedule_table
import pandas as pd
import random
import os
################# NOTES ##################
# add alerts for exam schedule conflicts #
##########################################
app = Flask(__name__)
@app.route("/")
def main():
return render_template('index.html')
@app.route("/showSchedule", methods=["GET"])
def refreshGet():
return render_template('index.html')
@app.errorhandler(Exception)
def handle_invalid_usage(response):
return response
@app.errorhandler(404)
def not_found(e):
return Response('Page not found!')
@app.route("/showSchedule", methods=["POST"])
def showSchedule():
exams = []
num_vals = len(request.form)
form_vals = []
i = 0
while (3*i) < (num_vals - 1): # -1 to exclude the submit button
temp_name = request.form["ClassName" + str(i)] # works fine
temp_day = request.form["Day" + str(i)] # don't work fine
temp_time = request.form["Time" + str(i)]
temp_trio = (temp_name, temp_day, temp_time)
form_vals.append(temp_trio)
i += 1
for triplet in form_vals:
try:
toappend = search(triplet[1], triplet[2], triplet[0])
except Exception as e:
# return render_template('test_page.html', test_var=e)
return render_template('index.html', error="Classes filled out incorrectly")
exams.append(toappend)
exams = [val for val in exams if val != None]
# to handle exams at the same time
seen = [None for i in range(0, len(exams))]
for i in range(0, len(exams)):
flag = False
for j in range(0, len(seen)):
if (seen[j] != None) and (exams[i][0] == seen[j][0] and exams[i][1] == seen[j][1]):
if "Time conflict" in seen[j][2]:
seen[j][2] = seen[j][2] + " / " + exams[i][2]
else:
seen[j][2] = "Time conflict: " + seen[j][2] + " / " + exams[i][2]
flag = True
break
if flag == False:
seen[i] = list(exams[i]) #because outside loop...
exams = [val for val in seen if val != None]
df = pd.DataFrame(index = ["8-11am", "11:30-2:30pm", "3-6pm", "7-10pm"], columns = ["Mon", "Tues", "Weds", "Thurs", "Fri"]).fillna(" ")
for exam_tup in exams:
# df.loc[exam_tup[1], exam_tup[0]] = classname
df.loc[exam_tup[1], exam_tup[0]] = exam_tup[2]
df.columns = ["Mon 5/8", "Tues 5/9", "Weds 5/10", "Thurs 5/11", "Fri 5/12"]
# df.style.applymap(color)
return render_template("index.html", data=df.style.applymap(color).render())
# return render_template("schedule.html", name=showSchedule, data=df.style.applymap(color).render())
############################################
row_data = schedule_table.main()
covered = {}
def color(s):
global covered
boolsq = s != " "
if boolsq == True:
if s in covered.keys():
# print(s, 'COVERED AGAIN')
return 'background-color: '+ covered[s]
else:
# print(s, 'FINDING COLOR AND GIVING TO COVERED')
colors = ['#BBE3FF', '#ff6347', 'rgb(187,227,255)', 'rgb(220,170,225)', 'rgb(188,255,166)',
'rgb(255,231,166)', 'rgb(139,211,178)', 'rgb(164,195,243)', 'rgb(252,157,145)',
'rgb(255,214,163)', 'rgb(205,206,255)', 'rgb(228,215,246)']
randindex = int(random.random() * len(colors) // 1)
randcolor = colors[randindex]
colors.remove(randcolor)
# print(randcolor, '\n')
covered[s] = randcolor
return 'background-color: ' + randcolor + ';'
else:
return ''
def search(day, time, classname):
day = day.replace(",", " ").replace("&", " ").replace(";", " ").split()
day = day[0]
if day == "Foreign":
return (row_data[13][1], row_data[13][3], classname)
if day == "Econ":
return (row_data[2][1], row_data[2][3], classname)
if day == "Chem":
return (row_data[8][1], row_data[8][3], classname)
if time == "--" and day == "--":
return None
for row in row_data:
if day in row[4] and time in row[4]:
return [row[1], row[3], classname]
# easygui.msgbox("Classes filled out incorrectly", title="ERROR")
# @app.route("/signUp", methods=["POST"])
# def signUp():
# # read posted values from the UI
# _name = request.form["inputName"]
# _email = request.form["inputEmail"]
# _password = request.form["inputPassword"]
# # validate received values
# if _name and _email and _password:
# return json.dumps({"html":"<span>All fields good!</span>"})
# else:
# return json.dumps({"html":"<span>Fields not completed.</span>"})
if __name__ == "__main__":
# app.run(debug=True)
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
#################### SCRAPYARD ####################
# for i in range(0, len(request.form)+1):
# day = request.form["Day" + i]
# time = request.form["Time" + i]
# classname = request.form["ClassName" + i]
# exams.append(search(day, time, classname))
# day = request.form["Day0"]
# time = request.form["Time0"]
# classname = request.form["ClassName0"]
# original working try-except
# try:
# toappend = search(day, time, classname)
# except Exception as e:
# return render_template('index.html', error = "Classes filled out incorrectly")
# exams.append(toappend)
# except Exception as e:
# # list index out of range...
# return render_template('test_page.html', test_var=e, test2=exams, test3=seen)
# # return render_template('test_page.html', test2=exams, test3=seen)
<file_sep>/requirements.txt
appdirs==1.4.3
beautifulsoup4==4.5.3
bs4==0.0.1
click==6.7
Flask==0.12.1
itsdangerous==0.24
Jinja2==2.9.6
lxml==3.7.3
MarkupSafe==1.0
numpy==1.12.1
packaging==16.8
pandas==0.19.2
pyparsing==2.2.0
python-dateutil==2.6.0
pytz==2017.2
requests==2.13.0
six==1.10.0
Werkzeug==0.12.1
|
124eaed79aefdc06ed1f69afdbb6cd1f94085c26
|
[
"Python",
"Text"
] | 3
|
Python
|
dmedora/ExamSchedule
|
b65a4f84242da78bb6486095e7e383558a905721
|
7cdf7aa70de5d0de22e0b798540248cb340915a5
|
refs/heads/master
|
<file_sep>module github.com/taishi8117/go-money
go 1.12
require (
github.com/Rhymond/go-money v0.4.0
go.mongodb.org/mongo-driver v1.4.1
)
<file_sep>package money
import (
"encoding/json"
"errors"
"strings"
)
// Currency represents money currency information required for formatting.
type Currency struct {
Code string
Fraction int
Grapheme string
Template string
Decimal string
Thousand string
}
// currencies represents a collection of currency.
var currencies = map[string]*Currency{
"AED": {Decimal: ".", Thousand: ",", Code: "AED", Fraction: 2, Grapheme: ".\u062f.\u0625", Template: "1 $"},
"AFN": {Decimal: ".", Thousand: ",", Code: "AFN", Fraction: 2, Grapheme: "\u060b", Template: "1 $"},
"ALL": {Decimal: ".", Thousand: ",", Code: "ALL", Fraction: 2, Grapheme: "L", Template: "$1"},
"AMD": {Decimal: ".", Thousand: ",", Code: "AMD", Fraction: 2, Grapheme: "\u0564\u0580.", Template: "1 $"},
"ANG": {Decimal: ",", Thousand: ".", Code: "ANG", Fraction: 2, Grapheme: "\u0192", Template: "$1"},
"AOA": {Decimal: ".", Thousand: ",", Code: "AOA", Fraction: 2, Grapheme: "Kz", Template: "1$"},
"ARS": {Decimal: ".", Thousand: ",", Code: "ARS", Fraction: 2, Grapheme: "$", Template: "$1"},
"AUD": {Decimal: ".", Thousand: ",", Code: "AUD", Fraction: 2, Grapheme: "$", Template: "$1"},
"AWG": {Decimal: ".", Thousand: ",", Code: "AWG", Fraction: 2, Grapheme: "\u0192", Template: "1$"},
"AZN": {Decimal: ".", Thousand: ",", Code: "AZN", Fraction: 2, Grapheme: "\u20bc", Template: "$1"},
"BAM": {Decimal: ".", Thousand: ",", Code: "BAM", Fraction: 2, Grapheme: "KM", Template: "$1"},
"BBD": {Decimal: ".", Thousand: ",", Code: "BBD", Fraction: 2, Grapheme: "$", Template: "$1"},
"BDT": {Decimal: ".", Thousand: ",", Code: "BDT", Fraction: 2, Grapheme: "\u09f3", Template: "$1"},
"BGN": {Decimal: ".", Thousand: ",", Code: "BGN", Fraction: 2, Grapheme: "\u043b\u0432", Template: "$1"},
"BHD": {Decimal: ".", Thousand: ",", Code: "BHD", Fraction: 3, Grapheme: ".\u062f.\u0628", Template: "1 $"},
"BIF": {Decimal: ".", Thousand: ",", Code: "BIF", Fraction: 0, Grapheme: "Fr", Template: "1$"},
"BMD": {Decimal: ".", Thousand: ",", Code: "BMD", Fraction: 2, Grapheme: "$", Template: "$1"},
"BND": {Decimal: ".", Thousand: ",", Code: "BND", Fraction: 2, Grapheme: "$", Template: "$1"},
"BOB": {Decimal: ".", Thousand: ",", Code: "BOB", Fraction: 2, Grapheme: "Bs.", Template: "$1"},
"BRL": {Decimal: ".", Thousand: ",", Code: "BRL", Fraction: 2, Grapheme: "R$", Template: "$1"},
"BSD": {Decimal: ".", Thousand: ",", Code: "BSD", Fraction: 2, Grapheme: "$", Template: "$1"},
"BTN": {Decimal: ".", Thousand: ",", Code: "BTN", Fraction: 2, Grapheme: "Nu.", Template: "1$"},
"BWP": {Decimal: ".", Thousand: ",", Code: "BWP", Fraction: 2, Grapheme: "P", Template: "$1"},
"BYN": {Decimal: ",", Thousand: " ", Code: "BYN", Fraction: 2, Grapheme: "p.", Template: "1 $"},
"BYR": {Decimal: ",", Thousand: " ", Code: "BYR", Fraction: 0, Grapheme: "p.", Template: "1 $"},
"BZD": {Decimal: ".", Thousand: ",", Code: "BZD", Fraction: 2, Grapheme: "BZ$", Template: "$1"},
"CAD": {Decimal: ".", Thousand: ",", Code: "CAD", Fraction: 2, Grapheme: "$", Template: "$1"},
"CDF": {Decimal: ".", Thousand: ",", Code: "CDF", Fraction: 2, Grapheme: "FC", Template: "1$"},
"CHF": {Decimal: ".", Thousand: ",", Code: "CHF", Fraction: 2, Grapheme: "CHF", Template: "1 $"},
"CLF": {Decimal: ",", Thousand: ".", Code: "CLF", Fraction: 4, Grapheme: "UF", Template: "$1"},
"CLP": {Decimal: ",", Thousand: ".", Code: "CLP", Fraction: 0, Grapheme: "$", Template: "$1"},
"CNY": {Decimal: ".", Thousand: ",", Code: "CNY", Fraction: 2, Grapheme: "\u5143", Template: "1 $"},
"COP": {Decimal: ",", Thousand: ".", Code: "COP", Fraction: 2, Grapheme: "$", Template: "$1"},
"CRC": {Decimal: ".", Thousand: ",", Code: "CRC", Fraction: 2, Grapheme: "\u20a1", Template: "$1"},
"CUC": {Decimal: ".", Thousand: ",", Code: "CUC", Fraction: 2, Grapheme: "$", Template: "1$"},
"CUP": {Decimal: ".", Thousand: ",", Code: "CUP", Fraction: 2, Grapheme: "$MN", Template: "$1"},
"CVE": {Decimal: ".", Thousand: ",", Code: "CVE", Fraction: 2, Grapheme: "$", Template: "1$"},
"CZK": {Decimal: ".", Thousand: ",", Code: "CZK", Fraction: 2, Grapheme: "K\u010d", Template: "1 $"},
"DJF": {Decimal: ".", Thousand: ",", Code: "DJF", Fraction: 0, Grapheme: "Fdj", Template: "1 $"},
"DKK": {Decimal: ".", Thousand: ",", Code: "DKK", Fraction: 2, Grapheme: "kr", Template: "1 $"},
"DOP": {Decimal: ".", Thousand: ",", Code: "DOP", Fraction: 2, Grapheme: "RD$", Template: "$1"},
"DZD": {Decimal: ".", Thousand: ",", Code: "DZD", Fraction: 2, Grapheme: ".\u062f.\u062c", Template: "1 $"},
"EEK": {Decimal: ".", Thousand: ",", Code: "EEK", Fraction: 2, Grapheme: "kr", Template: "$1"},
"EGP": {Decimal: ".", Thousand: ",", Code: "EGP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"ERN": {Decimal: ".", Thousand: ",", Code: "ERN", Fraction: 2, Grapheme: "Nfk", Template: "1 $"},
"ETB": {Decimal: ".", Thousand: ",", Code: "ETB", Fraction: 2, Grapheme: "Br", Template: "1 $"},
"EUR": {Decimal: ".", Thousand: ",", Code: "EUR", Fraction: 2, Grapheme: "\u20ac", Template: "$1"},
"FJD": {Decimal: ".", Thousand: ",", Code: "FJD", Fraction: 2, Grapheme: "$", Template: "$1"},
"FKP": {Decimal: ".", Thousand: ",", Code: "FKP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"GBP": {Decimal: ".", Thousand: ",", Code: "GBP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"GEL": {Decimal: ".", Thousand: ",", Code: "GEL", Fraction: 2, Grapheme: "\u10da", Template: "1 $"},
"GGP": {Decimal: ".", Thousand: ",", Code: "GGP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"GHC": {Decimal: ".", Thousand: ",", Code: "GHC", Fraction: 2, Grapheme: "\u00a2", Template: "$1"},
"GHS": {Decimal: ".", Thousand: ",", Code: "GHS", Fraction: 2, Grapheme: "\u20b5", Template: "$1"},
"GIP": {Decimal: ".", Thousand: ",", Code: "GIP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"GMD": {Decimal: ".", Thousand: ",", Code: "GMD", Fraction: 2, Grapheme: "D", Template: "1 $"},
"GNF": {Decimal: ".", Thousand: ",", Code: "GNF", Fraction: 0, Grapheme: "FG", Template: "1 $"},
"GTQ": {Decimal: ".", Thousand: ",", Code: "GTQ", Fraction: 2, Grapheme: "Q", Template: "$1"},
"GYD": {Decimal: ".", Thousand: ",", Code: "GYD", Fraction: 2, Grapheme: "$", Template: "$1"},
"HKD": {Decimal: ".", Thousand: ",", Code: "HKD", Fraction: 2, Grapheme: "$", Template: "$1"},
"HNL": {Decimal: ".", Thousand: ",", Code: "HNL", Fraction: 2, Grapheme: "L", Template: "$1"},
"HRK": {Decimal: ",", Thousand: ".", Code: "HRK", Fraction: 2, Grapheme: "kn", Template: "1 $"},
"HTG": {Decimal: ",", Thousand: ".", Code: "HTG", Fraction: 2, Grapheme: "G", Template: "1 $"},
"HUF": {Decimal: ".", Thousand: ",", Code: "HUF", Fraction: 0, Grapheme: "Ft", Template: "$1"},
"IDR": {Decimal: ".", Thousand: ",", Code: "IDR", Fraction: 2, Grapheme: "Rp", Template: "$1"},
"ILS": {Decimal: ".", Thousand: ",", Code: "ILS", Fraction: 2, Grapheme: "\u20aa", Template: "$1"},
"IMP": {Decimal: ".", Thousand: ",", Code: "IMP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"INR": {Decimal: ".", Thousand: ",", Code: "INR", Fraction: 2, Grapheme: "\u20b9", Template: "$1"},
"IQD": {Decimal: ".", Thousand: ",", Code: "IQD", Fraction: 3, Grapheme: ".\u062f.\u0639", Template: "1 $"},
"IRR": {Decimal: ".", Thousand: ",", Code: "IRR", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"},
"ISK": {Decimal: ",", Thousand: ".", Code: "ISK", Fraction: 0, Grapheme: "kr", Template: "$1"},
"JEP": {Decimal: ".", Thousand: ",", Code: "JEP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"JMD": {Decimal: ".", Thousand: ",", Code: "JMD", Fraction: 2, Grapheme: "J$", Template: "$1"},
"JOD": {Decimal: ".", Thousand: ",", Code: "JOD", Fraction: 3, Grapheme: ".\u062f.\u0625", Template: "1 $"},
"JPY": {Decimal: ".", Thousand: ",", Code: "JPY", Fraction: 0, Grapheme: "\u00a5", Template: "$1"},
"KES": {Decimal: ".", Thousand: ",", Code: "KES", Fraction: 2, Grapheme: "KSh", Template: "$1"},
"KGS": {Decimal: ".", Thousand: ",", Code: "KGS", Fraction: 2, Grapheme: "\u0441\u043e\u043c", Template: "$1"},
"KHR": {Decimal: ".", Thousand: ",", Code: "KHR", Fraction: 2, Grapheme: "\u17db", Template: "$1"},
"KMF": {Decimal: ".", Thousand: ",", Code: "KMF", Fraction: 0, Grapheme: "CF", Template: "$1"},
"KPW": {Decimal: ".", Thousand: ",", Code: "KPW", Fraction: 0, Grapheme: "\u20a9", Template: "$1"},
"KRW": {Decimal: ".", Thousand: ",", Code: "KRW", Fraction: 0, Grapheme: "\u20a9", Template: "$1"},
"KWD": {Decimal: ".", Thousand: ",", Code: "KWD", Fraction: 3, Grapheme: ".\u062f.\u0643", Template: "1 $"},
"KYD": {Decimal: ".", Thousand: ",", Code: "KYD", Fraction: 2, Grapheme: "$", Template: "$1"},
"KZT": {Decimal: ".", Thousand: ",", Code: "KZT", Fraction: 2, Grapheme: "\u20b8", Template: "$1"},
"LAK": {Decimal: ".", Thousand: ",", Code: "LAK", Fraction: 2, Grapheme: "\u20ad", Template: "$1"},
"LBP": {Decimal: ".", Thousand: ",", Code: "LBP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"LKR": {Decimal: ".", Thousand: ",", Code: "LKR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"},
"LRD": {Decimal: ".", Thousand: ",", Code: "LRD", Fraction: 2, Grapheme: "$", Template: "$1"},
"LSL": {Decimal: ".", Thousand: ",", Code: "LSL", Fraction: 2, Grapheme: "L", Template: "$1"},
"LTL": {Decimal: ".", Thousand: ",", Code: "LTL", Fraction: 2, Grapheme: "Lt", Template: "$1"},
"LVL": {Decimal: ".", Thousand: ",", Code: "LVL", Fraction: 2, Grapheme: "Ls", Template: "1 $"},
"LYD": {Decimal: ".", Thousand: ",", Code: "LYD", Fraction: 3, Grapheme: ".\u062f.\u0644", Template: "1 $"},
"MAD": {Decimal: ".", Thousand: ",", Code: "MAD", Fraction: 2, Grapheme: ".\u062f.\u0645", Template: "1 $"},
"MDL": {Decimal: ".", Thousand: ",", Code: "MDL", Fraction: 2, Grapheme: "lei", Template: "1 $"},
"MKD": {Decimal: ".", Thousand: ",", Code: "MKD", Fraction: 2, Grapheme: "\u0434\u0435\u043d", Template: "$1"},
"MMK": {Decimal: ".", Thousand: ",", Code: "MMK", Fraction: 2, Grapheme: "K", Template: "$1"},
"MNT": {Decimal: ".", Thousand: ",", Code: "MNT", Fraction: 2, Grapheme: "\u20ae", Template: "$1"},
"MOP": {Decimal: ".", Thousand: ",", Code: "MOP", Fraction: 2, Grapheme: "P", Template: "1 $"},
"MUR": {Decimal: ".", Thousand: ",", Code: "MUR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"},
"MVR": {Decimal: ".", Thousand: ",", Code: "MVR", Fraction: 2, Grapheme: "MVR", Template: "1 $"},
"MWK": {Decimal: ".", Thousand: ",", Code: "MWK", Fraction: 2, Grapheme: "MK", Template: "$1"},
"MXN": {Decimal: ".", Thousand: ",", Code: "MXN", Fraction: 2, Grapheme: "$", Template: "$1"},
"MYR": {Decimal: ".", Thousand: ",", Code: "MYR", Fraction: 2, Grapheme: "RM", Template: "$1"},
"MZN": {Decimal: ".", Thousand: ",", Code: "MZN", Fraction: 2, Grapheme: "MT", Template: "$1"},
"NAD": {Decimal: ".", Thousand: ",", Code: "NAD", Fraction: 2, Grapheme: "$", Template: "$1"},
"NGN": {Decimal: ".", Thousand: ",", Code: "NGN", Fraction: 2, Grapheme: "\u20a6", Template: "$1"},
"NIO": {Decimal: ".", Thousand: ",", Code: "NIO", Fraction: 2, Grapheme: "C$", Template: "$1"},
"NOK": {Decimal: ".", Thousand: ",", Code: "NOK", Fraction: 2, Grapheme: "kr", Template: "1 $"},
"NPR": {Decimal: ".", Thousand: ",", Code: "NPR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"},
"NZD": {Decimal: ".", Thousand: ",", Code: "NZD", Fraction: 2, Grapheme: "$", Template: "$1"},
"OMR": {Decimal: ".", Thousand: ",", Code: "OMR", Fraction: 3, Grapheme: "\ufdfc", Template: "1 $"},
"PAB": {Decimal: ".", Thousand: ",", Code: "PAB", Fraction: 2, Grapheme: "B/.", Template: "$1"},
"PEN": {Decimal: ".", Thousand: ",", Code: "PEN", Fraction: 2, Grapheme: "S/", Template: "$1"},
"PGK": {Decimal: ".", Thousand: ",", Code: "PGK", Fraction: 2, Grapheme: "K", Template: "1 $"},
"PHP": {Decimal: ".", Thousand: ",", Code: "PHP", Fraction: 2, Grapheme: "\u20b1", Template: "$1"},
"PKR": {Decimal: ".", Thousand: ",", Code: "PKR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"},
"PLN": {Decimal: ".", Thousand: ",", Code: "PLN", Fraction: 2, Grapheme: "z\u0142", Template: "1 $"},
"PYG": {Decimal: ".", Thousand: ",", Code: "PYG", Fraction: 0, Grapheme: "Gs", Template: "1$"},
"QAR": {Decimal: ".", Thousand: ",", Code: "QAR", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"},
"RON": {Decimal: ".", Thousand: ",", Code: "RON", Fraction: 2, Grapheme: "lei", Template: "$1"},
"RSD": {Decimal: ".", Thousand: ",", Code: "RSD", Fraction: 2, Grapheme: "\u0414\u0438\u043d.", Template: "$1"},
"RUB": {Decimal: ".", Thousand: ",", Code: "RUB", Fraction: 2, Grapheme: "\u20bd", Template: "1 $"},
"RUR": {Decimal: ".", Thousand: ",", Code: "RUR", Fraction: 2, Grapheme: "\u20bd", Template: "1 $"},
"RWF": {Decimal: ".", Thousand: ",", Code: "RWF", Fraction: 0, Grapheme: "FRw", Template: "1 $"},
"SAR": {Decimal: ".", Thousand: ",", Code: "SAR", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"},
"SBD": {Decimal: ".", Thousand: ",", Code: "SBD", Fraction: 2, Grapheme: "$", Template: "$1"},
"SCR": {Decimal: ".", Thousand: ",", Code: "SCR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"},
"SDG": {Decimal: ".", Thousand: ",", Code: "SDG", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"SEK": {Decimal: ".", Thousand: ",", Code: "SEK", Fraction: 2, Grapheme: "kr", Template: "1 $"},
"SGD": {Decimal: ".", Thousand: ",", Code: "SGD", Fraction: 2, Grapheme: "$", Template: "$1"},
"SHP": {Decimal: ".", Thousand: ",", Code: "SHP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"SKK": {Decimal: ".", Thousand: ",", Code: "SKK", Fraction: 2, Grapheme: "Sk", Template: "$1"},
"SLL": {Decimal: ".", Thousand: ",", Code: "SLL", Fraction: 2, Grapheme: "Le", Template: "1 $"},
"SOS": {Decimal: ".", Thousand: ",", Code: "SOS", Fraction: 2, Grapheme: "Sh", Template: "1 $"},
"SRD": {Decimal: ".", Thousand: ",", Code: "SRD", Fraction: 2, Grapheme: "$", Template: "$1"},
"SSP": {Decimal: ".", Thousand: ",", Code: "SSP", Fraction: 2, Grapheme: "\u00a3", Template: "1 $"},
"STD": {Decimal: ".", Thousand: ",", Code: "STD", Fraction: 2, Grapheme: "Db", Template: "1 $"},
"SVC": {Decimal: ".", Thousand: ",", Code: "SVC", Fraction: 2, Grapheme: "\u20a1", Template: "$1"},
"SYP": {Decimal: ".", Thousand: ",", Code: "SYP", Fraction: 2, Grapheme: "\u00a3", Template: "1 $"},
"SZL": {Decimal: ".", Thousand: ",", Code: "SZL", Fraction: 2, Grapheme: "\u00a3", Template: "$1"},
"THB": {Decimal: ".", Thousand: ",", Code: "THB", Fraction: 2, Grapheme: "\u0e3f", Template: "$1"},
"TJS": {Decimal: ".", Thousand: ",", Code: "TJS", Fraction: 2, Grapheme: "SM", Template: "1 $"},
"TMT": {Decimal: ".", Thousand: ",", Code: "TMT", Fraction: 2, Grapheme: "T", Template: "1 $"},
"TND": {Decimal: ".", Thousand: ",", Code: "TND", Fraction: 3, Grapheme: ".\u062f.\u062a", Template: "1 $"},
"TOP": {Decimal: ".", Thousand: ",", Code: "TOP", Fraction: 2, Grapheme: "T$", Template: "$1"},
"TRL": {Decimal: ".", Thousand: ",", Code: "TRL", Fraction: 2, Grapheme: "\u20a4", Template: "$1"},
"TRY": {Decimal: ".", Thousand: ",", Code: "TRY", Fraction: 2, Grapheme: "\u20ba", Template: "$1"},
"TTD": {Decimal: ".", Thousand: ",", Code: "TTD", Fraction: 2, Grapheme: "TT$", Template: "$1"},
"TWD": {Decimal: ".", Thousand: ",", Code: "TWD", Fraction: 0, Grapheme: "NT$", Template: "$1"},
"TZS": {Decimal: ".", Thousand: ",", Code: "TZS", Fraction: 0, Grapheme: "TSh", Template: "$1"},
"UAH": {Decimal: ".", Thousand: ",", Code: "UAH", Fraction: 2, Grapheme: "\u20b4", Template: "1 $"},
"UGX": {Decimal: ".", Thousand: ",", Code: "UGX", Fraction: 0, Grapheme: "USh", Template: "1 $"},
"USD": {Decimal: ".", Thousand: ",", Code: "USD", Fraction: 2, Grapheme: "$", Template: "$1"},
"UYU": {Decimal: ".", Thousand: ",", Code: "UYU", Fraction: 2, Grapheme: "$U", Template: "$1"},
"UZS": {Decimal: ".", Thousand: ",", Code: "UZS", Fraction: 2, Grapheme: "so\u2019m", Template: "$1"},
"VEF": {Decimal: ".", Thousand: ",", Code: "VEF", Fraction: 2, Grapheme: "Bs", Template: "$1"},
"VND": {Decimal: ".", Thousand: ",", Code: "VND", Fraction: 0, Grapheme: "\u20ab", Template: "1 $"},
"VUV": {Decimal: ".", Thousand: ",", Code: "VUV", Fraction: 0, Grapheme: "Vt", Template: "$1"},
"WST": {Decimal: ".", Thousand: ",", Code: "WST", Fraction: 2, Grapheme: "T", Template: "1 $"},
"XAF": {Decimal: ".", Thousand: ",", Code: "XAF", Fraction: 0, Grapheme: "Fr", Template: "1 $"},
"XAG": {Decimal: ".", Thousand: ",", Code: "XAG", Fraction: 0, Grapheme: "oz t", Template: "1 $"},
"XAU": {Decimal: ".", Thousand: ",", Code: "XAU", Fraction: 0, Grapheme: "oz t", Template: "1 $"},
"XCD": {Decimal: ".", Thousand: ",", Code: "XCD", Fraction: 2, Grapheme: "$", Template: "$1"},
"XDR": {Decimal: ".", Thousand: ",", Code: "XDR", Fraction: 0, Grapheme: "SDR", Template: "1 $"},
"YER": {Decimal: ".", Thousand: ",", Code: "YER", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"},
"ZAR": {Decimal: ".", Thousand: ",", Code: "ZAR", Fraction: 2, Grapheme: "R", Template: "$1"},
"ZMW": {Decimal: ".", Thousand: ",", Code: "ZMW", Fraction: 2, Grapheme: "ZK", Template: "$1"},
"ZWD": {Decimal: ".", Thousand: ",", Code: "ZWD", Fraction: 2, Grapheme: "Z$", Template: "$1"},
// https://github.com/yonilevy/crypto-currency-symbols
"BTC": {Decimal: ".", Thousand: ",", Code: "BTC", Fraction: 8, Grapheme: "\u0e3f", Template: "$1"},
"ETH": {Decimal: ".", Thousand: ",", Code: "ETH", Fraction: 8, Grapheme: "\u039e", Template: "$1"},
"USDT": {Decimal: ".", Thousand: ",", Code: "USDT", Fraction: 2, Grapheme: "₮", Template: "$1"},
"XRP": {Decimal: ".", Thousand: ",", Code: "XRP", Fraction: 6, Grapheme: "✕", Template: "$1"},
"LTC": {Decimal: ".", Thousand: ",", Code: "LTC", Fraction: 8, Grapheme: "Ł", Template: "$1"},
// from binance pairs
"DASH": {Decimal: ".", Thousand: ",", Code: "DASH", Fraction: 8, Grapheme: "DASH", Template: "$1"},
"OGN": {Decimal: ".", Thousand: ",", Code: "OGN", Fraction: 8, Grapheme: "OGN", Template: "$1"},
"BTCUP": {Decimal: ".", Thousand: ",", Code: "BTCUP", Fraction: 8, Grapheme: "BTCUP", Template: "$1"},
"RLC": {Decimal: ".", Thousand: ",", Code: "RLC", Fraction: 8, Grapheme: "RLC", Template: "$1"},
"PPT": {Decimal: ".", Thousand: ",", Code: "PPT", Fraction: 8, Grapheme: "PPT", Template: "$1"},
"ZIL": {Decimal: ".", Thousand: ",", Code: "ZIL", Fraction: 8, Grapheme: "ZIL", Template: "$1"},
"ONG": {Decimal: ".", Thousand: ",", Code: "ONG", Fraction: 8, Grapheme: "ONG", Template: "$1"},
"KAVA": {Decimal: ".", Thousand: ",", Code: "KAVA", Fraction: 8, Grapheme: "KAVA", Template: "$1"},
"BTS": {Decimal: ".", Thousand: ",", Code: "BTS", Fraction: 8, Grapheme: "BTS", Template: "$1"},
"NXS": {Decimal: ".", Thousand: ",", Code: "NXS", Fraction: 8, Grapheme: "NXS", Template: "$1"},
"ENG": {Decimal: ".", Thousand: ",", Code: "ENG", Fraction: 8, Grapheme: "ENG", Template: "$1"},
"GTO": {Decimal: ".", Thousand: ",", Code: "GTO", Fraction: 8, Grapheme: "GTO", Template: "$1"},
"AION": {Decimal: ".", Thousand: ",", Code: "AION", Fraction: 8, Grapheme: "AION", Template: "$1"},
"BAND": {Decimal: ".", Thousand: ",", Code: "BAND", Fraction: 8, Grapheme: "BAND", Template: "$1"},
"ONT": {Decimal: ".", Thousand: ",", Code: "ONT", Fraction: 8, Grapheme: "ONT", Template: "$1"},
"LRC": {Decimal: ".", Thousand: ",", Code: "LRC", Fraction: 8, Grapheme: "LRC", Template: "$1"},
"REP": {Decimal: ".", Thousand: ",", Code: "REP", Fraction: 8, Grapheme: "REP", Template: "$1"},
"ONE": {Decimal: ".", Thousand: ",", Code: "ONE", Fraction: 8, Grapheme: "ONE", Template: "$1"},
"FET": {Decimal: ".", Thousand: ",", Code: "FET", Fraction: 8, Grapheme: "FET", Template: "$1"},
"SKY": {Decimal: ".", Thousand: ",", Code: "SKY", Fraction: 8, Grapheme: "SKY", Template: "$1"},
"KMD": {Decimal: ".", Thousand: ",", Code: "KMD", Fraction: 8, Grapheme: "KMD", Template: "$1"},
"NAS": {Decimal: ".", Thousand: ",", Code: "NAS", Fraction: 8, Grapheme: "NAS", Template: "$1"},
"SOL": {Decimal: ".", Thousand: ",", Code: "SOL", Fraction: 8, Grapheme: "SOL", Template: "$1"},
"GNT": {Decimal: ".", Thousand: ",", Code: "GNT", Fraction: 8, Grapheme: "GNT", Template: "$1"},
"ADX": {Decimal: ".", Thousand: ",", Code: "ADX", Fraction: 8, Grapheme: "ADX", Template: "$1"},
"VIBE": {Decimal: ".", Thousand: ",", Code: "VIBE", Fraction: 8, Grapheme: "VIBE", Template: "$1"},
"BUSD": {Decimal: ".", Thousand: ",", Code: "BUSD", Fraction: 8, Grapheme: "BUSD", Template: "$1"},
"DGB": {Decimal: ".", Thousand: ",", Code: "DGB", Fraction: 8, Grapheme: "DGB", Template: "$1"},
"CVC": {Decimal: ".", Thousand: ",", Code: "CVC", Fraction: 8, Grapheme: "CVC", Template: "$1"},
"WAVES": {Decimal: ".", Thousand: ",", Code: "WAVES", Fraction: 8, Grapheme: "WAVES", Template: "$1"},
"WIN": {Decimal: ".", Thousand: ",", Code: "WIN", Fraction: 8, Grapheme: "WIN", Template: "$1"},
"MANA": {Decimal: ".", Thousand: ",", Code: "MANA", Fraction: 8, Grapheme: "MANA", Template: "$1"},
"QSP": {Decimal: ".", Thousand: ",", Code: "QSP", Fraction: 8, Grapheme: "QSP", Template: "$1"},
"ARDR": {Decimal: ".", Thousand: ",", Code: "ARDR", Fraction: 8, Grapheme: "ARDR", Template: "$1"},
"HOT": {Decimal: ".", Thousand: ",", Code: "HOT", Fraction: 8, Grapheme: "HOT", Template: "$1"},
"NAV": {Decimal: ".", Thousand: ",", Code: "NAV", Fraction: 8, Grapheme: "NAV", Template: "$1"},
"CHZ": {Decimal: ".", Thousand: ",", Code: "CHZ", Fraction: 8, Grapheme: "CHZ", Template: "$1"},
"MTH": {Decimal: ".", Thousand: ",", Code: "MTH", Fraction: 8, Grapheme: "MTH", Template: "$1"},
"FTT": {Decimal: ".", Thousand: ",", Code: "FTT", Fraction: 8, Grapheme: "FTT", Template: "$1"},
"BNB": {Decimal: ".", Thousand: ",", Code: "BNB", Fraction: 8, Grapheme: "BNB", Template: "$1"},
"INS": {Decimal: ".", Thousand: ",", Code: "INS", Fraction: 8, Grapheme: "INS", Template: "$1"},
"POA": {Decimal: ".", Thousand: ",", Code: "POA", Fraction: 8, Grapheme: "POA", Template: "$1"},
"DATA": {Decimal: ".", Thousand: ",", Code: "DATA", Fraction: 8, Grapheme: "DATA", Template: "$1"},
"EOS": {Decimal: ".", Thousand: ",", Code: "EOS", Fraction: 8, Grapheme: "EOS", Template: "$1"},
"ZEN": {Decimal: ".", Thousand: ",", Code: "ZEN", Fraction: 8, Grapheme: "ZEN", Template: "$1"},
"TCT": {Decimal: ".", Thousand: ",", Code: "TCT", Fraction: 8, Grapheme: "TCT", Template: "$1"},
"XZC": {Decimal: ".", Thousand: ",", Code: "XZC", Fraction: 8, Grapheme: "XZC", Template: "$1"},
"QTUM": {Decimal: ".", Thousand: ",", Code: "QTUM", Fraction: 8, Grapheme: "QTUM", Template: "$1"},
"TNB": {Decimal: ".", Thousand: ",", Code: "TNB", Fraction: 8, Grapheme: "TNB", Template: "$1"},
"PAX": {Decimal: ".", Thousand: ",", Code: "PAX", Fraction: 8, Grapheme: "PAX", Template: "$1"},
"BNT": {Decimal: ".", Thousand: ",", Code: "BNT", Fraction: 8, Grapheme: "BNT", Template: "$1"},
"SC": {Decimal: ".", Thousand: ",", Code: "SC", Fraction: 8, Grapheme: "SC", Template: "$1"},
"COTI": {Decimal: ".", Thousand: ",", Code: "COTI", Fraction: 8, Grapheme: "COTI", Template: "$1"},
"SNT": {Decimal: ".", Thousand: ",", Code: "SNT", Fraction: 8, Grapheme: "SNT", Template: "$1"},
"BLZ": {Decimal: ".", Thousand: ",", Code: "BLZ", Fraction: 8, Grapheme: "BLZ", Template: "$1"},
"TUSD": {Decimal: ".", Thousand: ",", Code: "TUSD", Fraction: 8, Grapheme: "TUSD", Template: "$1"},
"WTC": {Decimal: ".", Thousand: ",", Code: "WTC", Fraction: 8, Grapheme: "WTC", Template: "$1"},
"CHR": {Decimal: ".", Thousand: ",", Code: "CHR", Fraction: 8, Grapheme: "CHR", Template: "$1"},
"MTL": {Decimal: ".", Thousand: ",", Code: "MTL", Fraction: 8, Grapheme: "MTL", Template: "$1"},
"BCH": {Decimal: ".", Thousand: ",", Code: "BCH", Fraction: 8, Grapheme: "BCH", Template: "$1"},
"PHB": {Decimal: ".", Thousand: ",", Code: "PHB", Fraction: 8, Grapheme: "PHB", Template: "$1"},
"XEM": {Decimal: ".", Thousand: ",", Code: "XEM", Fraction: 8, Grapheme: "XEM", Template: "$1"},
"NULS": {Decimal: ".", Thousand: ",", Code: "NULS", Fraction: 8, Grapheme: "NULS", Template: "$1"},
"ERD": {Decimal: ".", Thousand: ",", Code: "ERD", Fraction: 8, Grapheme: "ERD", Template: "$1"},
"XTZ": {Decimal: ".", Thousand: ",", Code: "XTZ", Fraction: 8, Grapheme: "XTZ", Template: "$1"},
"GO": {Decimal: ".", Thousand: ",", Code: "GO", Fraction: 8, Grapheme: "GO", Template: "$1"},
"ARK": {Decimal: ".", Thousand: ",", Code: "ARK", Fraction: 8, Grapheme: "ARK", Template: "$1"},
"DCR": {Decimal: ".", Thousand: ",", Code: "DCR", Fraction: 8, Grapheme: "DCR", Template: "$1"},
"ICX": {Decimal: ".", Thousand: ",", Code: "ICX", Fraction: 8, Grapheme: "ICX", Template: "$1"},
"LOOM": {Decimal: ".", Thousand: ",", Code: "LOOM", Fraction: 8, Grapheme: "LOOM", Template: "$1"},
"DENT": {Decimal: ".", Thousand: ",", Code: "DENT", Fraction: 8, Grapheme: "DENT", Template: "$1"},
"BRD": {Decimal: ".", Thousand: ",", Code: "BRD", Fraction: 8, Grapheme: "BRD", Template: "$1"},
"RVN": {Decimal: ".", Thousand: ",", Code: "RVN", Fraction: 8, Grapheme: "RVN", Template: "$1"},
"CDT": {Decimal: ".", Thousand: ",", Code: "CDT", Fraction: 8, Grapheme: "CDT", Template: "$1"},
"STPT": {Decimal: ".", Thousand: ",", Code: "STPT", Fraction: 8, Grapheme: "STPT", Template: "$1"},
"COMP": {Decimal: ".", Thousand: ",", Code: "COMP", Fraction: 8, Grapheme: "COMP", Template: "$1"},
"CND": {Decimal: ".", Thousand: ",", Code: "CND", Fraction: 8, Grapheme: "CND", Template: "$1"},
"VITE": {Decimal: ".", Thousand: ",", Code: "VITE", Fraction: 8, Grapheme: "VITE", Template: "$1"},
"PIVX": {Decimal: ".", Thousand: ",", Code: "PIVX", Fraction: 8, Grapheme: "PIVX", Template: "$1"},
"BKRW": {Decimal: ".", Thousand: ",", Code: "BKRW", Fraction: 8, Grapheme: "BKRW", Template: "$1"},
"USDC": {Decimal: ".", Thousand: ",", Code: "USDC", Fraction: 8, Grapheme: "USDC", Template: "$1"},
"MCO": {Decimal: ".", Thousand: ",", Code: "MCO", Fraction: 8, Grapheme: "MCO", Template: "$1"},
"BQX": {Decimal: ".", Thousand: ",", Code: "BQX", Fraction: 8, Grapheme: "BQX", Template: "$1"},
"LEND": {Decimal: ".", Thousand: ",", Code: "LEND", Fraction: 8, Grapheme: "LEND", Template: "$1"},
"BAT": {Decimal: ".", Thousand: ",", Code: "BAT", Fraction: 8, Grapheme: "BAT", Template: "$1"},
"DUSK": {Decimal: ".", Thousand: ",", Code: "DUSK", Fraction: 8, Grapheme: "DUSK", Template: "$1"},
"BTG": {Decimal: ".", Thousand: ",", Code: "BTG", Fraction: 8, Grapheme: "BTG", Template: "$1"},
"ANKR": {Decimal: ".", Thousand: ",", Code: "ANKR", Fraction: 8, Grapheme: "ANKR", Template: "$1"},
"GXS": {Decimal: ".", Thousand: ",", Code: "GXS", Fraction: 8, Grapheme: "GXS", Template: "$1"},
"STORJ": {Decimal: ".", Thousand: ",", Code: "STORJ", Fraction: 8, Grapheme: "STORJ", Template: "$1"},
"AMB": {Decimal: ".", Thousand: ",", Code: "AMB", Fraction: 8, Grapheme: "AMB", Template: "$1"},
"CMT": {Decimal: ".", Thousand: ",", Code: "CMT", Fraction: 8, Grapheme: "CMT", Template: "$1"},
"RCN": {Decimal: ".", Thousand: ",", Code: "RCN", Fraction: 8, Grapheme: "RCN", Template: "$1"},
"LTO": {Decimal: ".", Thousand: ",", Code: "LTO", Fraction: 8, Grapheme: "LTO", Template: "$1"},
"EVX": {Decimal: ".", Thousand: ",", Code: "EVX", Fraction: 8, Grapheme: "EVX", Template: "$1"},
"NKN": {Decimal: ".", Thousand: ",", Code: "NKN", Fraction: 8, Grapheme: "NKN", Template: "$1"},
"POWR": {Decimal: ".", Thousand: ",", Code: "POWR", Fraction: 8, Grapheme: "POWR", Template: "$1"},
"ENJ": {Decimal: ".", Thousand: ",", Code: "ENJ", Fraction: 8, Grapheme: "ENJ", Template: "$1"},
"KNC": {Decimal: ".", Thousand: ",", Code: "KNC", Fraction: 8, Grapheme: "KNC", Template: "$1"},
"OAX": {Decimal: ".", Thousand: ",", Code: "OAX", Fraction: 8, Grapheme: "OAX", Template: "$1"},
"GAS": {Decimal: ".", Thousand: ",", Code: "GAS", Fraction: 8, Grapheme: "GAS", Template: "$1"},
"IDRT": {Decimal: ".", Thousand: ",", Code: "IDRT", Fraction: 8, Grapheme: "IDRT", Template: "$1"},
"OST": {Decimal: ".", Thousand: ",", Code: "OST", Fraction: 8, Grapheme: "OST", Template: "$1"},
"ELF": {Decimal: ".", Thousand: ",", Code: "ELF", Fraction: 8, Grapheme: "ELF", Template: "$1"},
"COCOS": {Decimal: ".", Thousand: ",", Code: "COCOS", Fraction: 8, Grapheme: "COCOS", Template: "$1"},
"IOTX": {Decimal: ".", Thousand: ",", Code: "IOTX", Fraction: 8, Grapheme: "IOTX", Template: "$1"},
"AGI": {Decimal: ".", Thousand: ",", Code: "AGI", Fraction: 8, Grapheme: "AGI", Template: "$1"},
"XLM": {Decimal: ".", Thousand: ",", Code: "XLM", Fraction: 8, Grapheme: "XLM", Template: "$1"},
"XMR": {Decimal: ".", Thousand: ",", Code: "XMR", Fraction: 8, Grapheme: "XMR", Template: "$1"},
"STEEM": {Decimal: ".", Thousand: ",", Code: "STEEM", Fraction: 8, Grapheme: "STEEM", Template: "$1"},
"PERL": {Decimal: ".", Thousand: ",", Code: "PERL", Fraction: 8, Grapheme: "PERL", Template: "$1"},
"TNT": {Decimal: ".", Thousand: ",", Code: "TNT", Fraction: 8, Grapheme: "TNT", Template: "$1"},
"GRS": {Decimal: ".", Thousand: ",", Code: "GRS", Fraction: 8, Grapheme: "GRS", Template: "$1"},
"ZRX": {Decimal: ".", Thousand: ",", Code: "ZRX", Fraction: 8, Grapheme: "ZRX", Template: "$1"},
"KEY": {Decimal: ".", Thousand: ",", Code: "KEY", Fraction: 8, Grapheme: "KEY", Template: "$1"},
"MITH": {Decimal: ".", Thousand: ",", Code: "MITH", Fraction: 8, Grapheme: "MITH", Template: "$1"},
"SYS": {Decimal: ".", Thousand: ",", Code: "SYS", Fraction: 8, Grapheme: "SYS", Template: "$1"},
"TROY": {Decimal: ".", Thousand: ",", Code: "TROY", Fraction: 8, Grapheme: "TROY", Template: "$1"},
"THETA": {Decimal: ".", Thousand: ",", Code: "THETA", Fraction: 8, Grapheme: "THETA", Template: "$1"},
"OMG": {Decimal: ".", Thousand: ",", Code: "OMG", Fraction: 8, Grapheme: "OMG", Template: "$1"},
"FTM": {Decimal: ".", Thousand: ",", Code: "FTM", Fraction: 8, Grapheme: "FTM", Template: "$1"},
"BEAM": {Decimal: ".", Thousand: ",", Code: "BEAM", Fraction: 8, Grapheme: "BEAM", Template: "$1"},
"NCASH": {Decimal: ".", Thousand: ",", Code: "NCASH", Fraction: 8, Grapheme: "NCASH", Template: "$1"},
"WABI": {Decimal: ".", Thousand: ",", Code: "WABI", Fraction: 8, Grapheme: "WABI", Template: "$1"},
"DOGE": {Decimal: ".", Thousand: ",", Code: "DOGE", Fraction: 8, Grapheme: "DOGE", Template: "$1"},
"ARPA": {Decimal: ".", Thousand: ",", Code: "ARPA", Fraction: 8, Grapheme: "ARPA", Template: "$1"},
"SNGLS": {Decimal: ".", Thousand: ",", Code: "SNGLS", Fraction: 8, Grapheme: "SNGLS", Template: "$1"},
"CELR": {Decimal: ".", Thousand: ",", Code: "CELR", Fraction: 8, Grapheme: "CELR", Template: "$1"},
"DOCK": {Decimal: ".", Thousand: ",", Code: "DOCK", Fraction: 8, Grapheme: "DOCK", Template: "$1"},
"HIVE": {Decimal: ".", Thousand: ",", Code: "HIVE", Fraction: 8, Grapheme: "HIVE", Template: "$1"},
"AST": {Decimal: ".", Thousand: ",", Code: "AST", Fraction: 8, Grapheme: "AST", Template: "$1"},
"DLT": {Decimal: ".", Thousand: ",", Code: "DLT", Fraction: 8, Grapheme: "DLT", Template: "$1"},
"DNT": {Decimal: ".", Thousand: ",", Code: "DNT", Fraction: 8, Grapheme: "DNT", Template: "$1"},
"TFUEL": {Decimal: ".", Thousand: ",", Code: "TFUEL", Fraction: 8, Grapheme: "TFUEL", Template: "$1"},
"DREP": {Decimal: ".", Thousand: ",", Code: "DREP", Fraction: 8, Grapheme: "DREP", Template: "$1"},
"GVT": {Decimal: ".", Thousand: ",", Code: "GVT", Fraction: 8, Grapheme: "GVT", Template: "$1"},
"STRAT": {Decimal: ".", Thousand: ",", Code: "STRAT", Fraction: 8, Grapheme: "STRAT", Template: "$1"},
"ADA": {Decimal: ".", Thousand: ",", Code: "ADA", Fraction: 8, Grapheme: "ADA", Template: "$1"},
"POE": {Decimal: ".", Thousand: ",", Code: "POE", Fraction: 8, Grapheme: "POE", Template: "$1"},
"ALGO": {Decimal: ".", Thousand: ",", Code: "ALGO", Fraction: 8, Grapheme: "ALGO", Template: "$1"},
"WAN": {Decimal: ".", Thousand: ",", Code: "WAN", Fraction: 8, Grapheme: "WAN", Template: "$1"},
"CTXC": {Decimal: ".", Thousand: ",", Code: "CTXC", Fraction: 8, Grapheme: "CTXC", Template: "$1"},
"BGBP": {Decimal: ".", Thousand: ",", Code: "BGBP", Fraction: 8, Grapheme: "BGBP", Template: "$1"},
"ZEC": {Decimal: ".", Thousand: ",", Code: "ZEC", Fraction: 8, Grapheme: "ZEC", Template: "$1"},
"NEO": {Decimal: ".", Thousand: ",", Code: "NEO", Fraction: 8, Grapheme: "NEO", Template: "$1"},
"FUEL": {Decimal: ".", Thousand: ",", Code: "FUEL", Fraction: 8, Grapheme: "FUEL", Template: "$1"},
"AE": {Decimal: ".", Thousand: ",", Code: "AE", Fraction: 8, Grapheme: "AE", Template: "$1"},
"ARN": {Decimal: ".", Thousand: ",", Code: "ARN", Fraction: 8, Grapheme: "ARN", Template: "$1"},
"FUN": {Decimal: ".", Thousand: ",", Code: "FUN", Fraction: 8, Grapheme: "FUN", Template: "$1"},
"QKC": {Decimal: ".", Thousand: ",", Code: "QKC", Fraction: 8, Grapheme: "QKC", Template: "$1"},
"WPR": {Decimal: ".", Thousand: ",", Code: "WPR", Fraction: 8, Grapheme: "WPR", Template: "$1"},
"MDT": {Decimal: ".", Thousand: ",", Code: "MDT", Fraction: 8, Grapheme: "MDT", Template: "$1"},
"PNT": {Decimal: ".", Thousand: ",", Code: "PNT", Fraction: 8, Grapheme: "PNT", Template: "$1"},
"MATIC": {Decimal: ".", Thousand: ",", Code: "MATIC", Fraction: 8, Grapheme: "MATIC", Template: "$1"},
"NEBL": {Decimal: ".", Thousand: ",", Code: "NEBL", Fraction: 8, Grapheme: "NEBL", Template: "$1"},
"NANO": {Decimal: ".", Thousand: ",", Code: "NANO", Fraction: 8, Grapheme: "NANO", Template: "$1"},
"POLY": {Decimal: ".", Thousand: ",", Code: "POLY", Fraction: 8, Grapheme: "POLY", Template: "$1"},
"COS": {Decimal: ".", Thousand: ",", Code: "COS", Fraction: 8, Grapheme: "COS", Template: "$1"},
"SNM": {Decimal: ".", Thousand: ",", Code: "SNM", Fraction: 8, Grapheme: "SNM", Template: "$1"},
"VIB": {Decimal: ".", Thousand: ",", Code: "VIB", Fraction: 8, Grapheme: "VIB", Template: "$1"},
"REQ": {Decimal: ".", Thousand: ",", Code: "REQ", Fraction: 8, Grapheme: "REQ", Template: "$1"},
"TRX": {Decimal: ".", Thousand: ",", Code: "TRX", Fraction: 8, Grapheme: "TRX", Template: "$1"},
"ATOM": {Decimal: ".", Thousand: ",", Code: "ATOM", Fraction: 8, Grapheme: "ATOM", Template: "$1"},
"CTSI": {Decimal: ".", Thousand: ",", Code: "CTSI", Fraction: 8, Grapheme: "CTSI", Template: "$1"},
"BTT": {Decimal: ".", Thousand: ",", Code: "BTT", Fraction: 8, Grapheme: "BTT", Template: "$1"},
"MDA": {Decimal: ".", Thousand: ",", Code: "MDA", Fraction: 8, Grapheme: "MDA", Template: "$1"},
"LUN": {Decimal: ".", Thousand: ",", Code: "LUN", Fraction: 8, Grapheme: "LUN", Template: "$1"},
"MBL": {Decimal: ".", Thousand: ",", Code: "MBL", Fraction: 8, Grapheme: "MBL", Template: "$1"},
"BTCDOWN": {Decimal: ".", Thousand: ",", Code: "BTCDOWN", Fraction: 8, Grapheme: "BTCDOWN", Template: "$1"},
"BCPT": {Decimal: ".", Thousand: ",", Code: "BCPT", Fraction: 8, Grapheme: "BCPT", Template: "$1"},
"BCD": {Decimal: ".", Thousand: ",", Code: "BCD", Fraction: 8, Grapheme: "BCD", Template: "$1"},
"VIA": {Decimal: ".", Thousand: ",", Code: "VIA", Fraction: 8, Grapheme: "VIA", Template: "$1"},
"ETC": {Decimal: ".", Thousand: ",", Code: "ETC", Fraction: 8, Grapheme: "ETC", Template: "$1"},
"HC": {Decimal: ".", Thousand: ",", Code: "HC", Fraction: 8, Grapheme: "HC", Template: "$1"},
"STMX": {Decimal: ".", Thousand: ",", Code: "STMX", Fraction: 8, Grapheme: "STMX", Template: "$1"},
"RDN": {Decimal: ".", Thousand: ",", Code: "RDN", Fraction: 8, Grapheme: "RDN", Template: "$1"},
"MFT": {Decimal: ".", Thousand: ",", Code: "MFT", Fraction: 8, Grapheme: "MFT", Template: "$1"},
"LINK": {Decimal: ".", Thousand: ",", Code: "LINK", Fraction: 8, Grapheme: "LINK", Template: "$1"},
"IQ": {Decimal: ".", Thousand: ",", Code: "IQ", Fraction: 8, Grapheme: "IQ", Template: "$1"},
"VET": {Decimal: ".", Thousand: ",", Code: "VET", Fraction: 8, Grapheme: "VET", Template: "$1"},
"TOMO": {Decimal: ".", Thousand: ",", Code: "TOMO", Fraction: 8, Grapheme: "TOMO", Template: "$1"},
"HBAR": {Decimal: ".", Thousand: ",", Code: "HBAR", Fraction: 8, Grapheme: "HBAR", Template: "$1"},
"IOST": {Decimal: ".", Thousand: ",", Code: "IOST", Fraction: 8, Grapheme: "IOST", Template: "$1"},
"YOYO": {Decimal: ".", Thousand: ",", Code: "YOYO", Fraction: 8, Grapheme: "YOYO", Template: "$1"},
"LSK": {Decimal: ".", Thousand: ",", Code: "LSK", Fraction: 8, Grapheme: "LSK", Template: "$1"},
"APPC": {Decimal: ".", Thousand: ",", Code: "APPC", Fraction: 8, Grapheme: "APPC", Template: "$1"},
"IOTA": {Decimal: ".", Thousand: ",", Code: "IOTA", Fraction: 8, Grapheme: "IOTA", Template: "$1"},
"XVG": {Decimal: ".", Thousand: ",", Code: "XVG", Fraction: 8, Grapheme: "XVG", Template: "$1"},
"QLC": {Decimal: ".", Thousand: ",", Code: "QLC", Fraction: 8, Grapheme: "QLC", Template: "$1"},
"REN": {Decimal: ".", Thousand: ",", Code: "REN", Fraction: 8, Grapheme: "REN", Template: "$1"},
"WRX": {Decimal: ".", Thousand: ",", Code: "WRX", Fraction: 8, Grapheme: "WRX", Template: "$1"},
"STX": {Decimal: ".", Thousand: ",", Code: "STX", Fraction: 8, Grapheme: "STX", Template: "$1"},
"NPXS": {Decimal: ".", Thousand: ",", Code: "NPXS", Fraction: 8, Grapheme: "NPXS", Template: "$1"},
}
// AddCurrency lets you insert or update currency in currencies list.
func AddCurrency(Code, Grapheme, Template, Decimal, Thousand string, Fraction int) *Currency {
currencies[Code] = &Currency{
Code: Code,
Grapheme: Grapheme,
Template: Template,
Decimal: Decimal,
Thousand: Thousand,
Fraction: Fraction,
}
return currencies[Code]
}
func newCurrency(code string) *Currency {
return &Currency{Code: strings.ToUpper(code)}
}
// GetCurrency returns the currency given the code.
func GetCurrency(code string) *Currency {
return currencies[code]
}
// Formatter returns currency formatter representing
// used currency structure.
func (c *Currency) Formatter() *Formatter {
return &Formatter{
Fraction: c.Fraction,
Decimal: c.Decimal,
Thousand: c.Thousand,
Grapheme: c.Grapheme,
Template: c.Template,
}
}
// getDefault represent default currency if currency is not found in currencies list.
// Grapheme and Code fields will be changed by currency code.
func (c *Currency) getDefault() *Currency {
return &Currency{Decimal: ".", Thousand: ",", Code: c.Code, Fraction: 2, Grapheme: c.Code, Template: "1$"}
}
// get extended currency using currencies list.
func (c *Currency) get() *Currency {
if curr, ok := currencies[c.Code]; ok {
return curr
}
return c.getDefault()
}
func (c *Currency) equals(oc *Currency) bool {
return c.Code == oc.Code
}
func (c *Currency) UnmarshalJSON(b []byte) error {
var code string
if err := json.Unmarshal(b, &code); err != nil {
return err
}
*c = *GetCurrency(strings.ToUpper(code))
if c == nil {
return errors.New("currency not found")
}
return nil
}
func (c Currency) MarshalJSON() ([]byte, error) {
return json.Marshal(c.Code)
}
func (c *Currency) Equals(oc *Currency) bool {
return c.equals(oc)
}
|
c37db4957661d68928e236b3e3fea86dc4b34880
|
[
"Go",
"Go Module"
] | 2
|
Go Module
|
taishi8117/go-money
|
68d959ed934d77af3113b68df6786ddccac45a7c
|
ec4d793e765cb8941bee76fc0257359354681bfb
|
refs/heads/master
|
<repo_name>irahel/Long-Wings<file_sep>/Assets/Scripts/enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour {
[SerializeField] int hp;
[SerializeField] float speed, fire_time;
[SerializeField] float destroy_time;
bool can_fire;
[SerializeField] int hit_damage;
[SerializeField] GameObject bullet;
[SerializeField] Transform fire_point_1, fire_point_2;
float fire_time_elapsed;
enum behaviour { ONLY_DOWN, DIAG, ZIG }
enum diag { LEFT, RIGHT }
[SerializeField] diag atual_diag;
[SerializeField] behaviour atual;
public bool changed;
[SerializeField] float init_zig, end_zig;
float zig_time , zig_time_elapsed;
[SerializeField] GameObject explo;
bool damaged;
[SerializeField] float total_time_damaged;
private float time_elapsed;
bool colided;
float time_col, time_col_elapsed;
// Use this for initialization
void Start ()
{
colided = false;
changed = false;
float rand_behaviour = Random.Range(0, 9);
if (rand_behaviour <= 3) atual = behaviour.ONLY_DOWN;
else if (rand_behaviour <= 6) atual = behaviour.DIAG;
else atual = behaviour.ZIG;
float rand_dir = Random.Range(0, 10);
if (rand_dir < 5) atual_diag = diag.LEFT;
else atual_diag = diag.RIGHT;
can_fire = true;
Destroy(gameObject, destroy_time);
zig_time_elapsed = 0;
float rand_zig = Random.Range(init_zig, end_zig);
zig_time = rand_zig;
damaged = false;
}
// Update is called once per frame
void Update ()
{
move();
fire();
death();
change_color();
atualize_time();
}
void move()
{
if(atual == behaviour.ONLY_DOWN)
{
GetComponent<Transform>().Translate(Vector2.down * Time.deltaTime * speed);
}
else if(atual == behaviour.DIAG)
{
if(atual_diag == diag.LEFT)
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.left) * Time.deltaTime * speed);
}
else
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.right) * Time.deltaTime * speed);
}
}
else
{
actualize_zig();
if (atual_diag == diag.LEFT)
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.left) * Time.deltaTime * speed);
}
else
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.right) * Time.deltaTime * speed);
}
}
}
void fire()
{
if (can_fire)
{
Instantiate(bullet, fire_point_1.position, fire_point_1.rotation);
Instantiate(bullet, fire_point_2.position, fire_point_2.rotation);
can_fire = false;
fire_time_elapsed = 0;
}
if (!can_fire)
{
fire_time_elapsed += Time.deltaTime;
if (fire_time_elapsed >= fire_time)
{
can_fire = true;
fire_time_elapsed = 0;
}
}
}
public void change_dir()
{
if (atual_diag == diag.LEFT) atual_diag = diag.RIGHT;
else atual_diag = diag.LEFT;
}
void actualize_zig()
{
zig_time_elapsed += Time.deltaTime;
if(zig_time_elapsed >= zig_time)
{
change_dir();
zig_time_elapsed = 0;
}
}
void death()
{
if (hp <= 0)
{
Destroy(gameObject);
Instantiate(explo, GetComponent<Transform>().position, GetComponent<Transform>().rotation);
}
}
public void take_damage(int damage)
{
hp -= damage;
death();
damaged = true;
}
void change_color()
{
if (this.damaged)
{
GetComponentInChildren<SpriteRenderer>().color = Color.red;
}
else
{
GetComponentInChildren<SpriteRenderer>().color = Color.white;
}
this.time_elapsed += Time.deltaTime;
if ((this.time_elapsed >= this.total_time_damaged) && this.damaged)
{
damaged = false;
this.time_elapsed = 0;
}
}
void atualize_time()
{
if (colided)
{
time_col_elapsed += Time.deltaTime;
if (time_col_elapsed >= time_col)
{
colided = false;
time_col_elapsed = 0;
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (!colided)
{
collision.gameObject.GetComponent<naveA>().take_damage(hit_damage);
colided = true;
}
}
}
public int get_hp()
{
return hp;
}
}
<file_sep>/Assets/Scripts/shootEnemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shootEnemy : MonoBehaviour
{
[SerializeField] float speed;
[SerializeField] int damage;
[SerializeField] float destroy_time;
// Use this for initialization
void Start()
{
Destroy(gameObject, destroy_time);
}
// Update is called once per frame
void Update()
{
move();
}
void move()
{
GetComponent<Transform>().Translate(Vector2.up * Time.deltaTime * speed);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
collision.gameObject.GetComponent<naveA>().take_damage(damage);
}
}
}
<file_sep>/README.md
# Long-Wings
A Galaga like, a arcade game, made for game work



<file_sep>/Assets/Scripts/limit_right.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class limit_right : MonoBehaviour
{
[SerializeField] float force;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "enemy")
{
if (!collision.gameObject.GetComponent<enemy>().changed) collision.gameObject.GetComponent<enemy>().change_dir();
}
if (collision.gameObject.tag == "ptero")
{
if (!collision.gameObject.GetComponent<pteros>().changed) collision.gameObject.GetComponent<pteros>().change_dir();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (collision.gameObject.GetComponent<naveA>().last_move_g() == "R")
{
collision.gameObject.GetComponent<naveA>().stop_force();
collision.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.left * force);
}
if (collision.gameObject.GetComponent<naveA>().last_move_g() == "L")
{
collision.gameObject.GetComponent<naveA>().stop_force();
collision.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.right * force);
}
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "enemy")
{
if (collision.gameObject.GetComponent<enemy>().changed) collision.gameObject.GetComponent<enemy>().changed = false;
}
if (collision.gameObject.tag == "ptero")
{
if (collision.gameObject.GetComponent<pteros>().changed) collision.gameObject.GetComponent<pteros>().changed = false;
}
}
}
<file_sep>/Assets/Scripts/gameover.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gameover : MonoBehaviour
{
[SerializeField] GameObject start, quit;
public int state;
// Use this for initialization
void Start()
{
state = 1;
}
// Update is called once per frame
void Update()
{
controller();
updater();
}
void updater()
{
if (state == 1)
{
start.SetActive(true);
quit.SetActive(false);
}
if (state == 2)
{
start.SetActive(false);
quit.SetActive(true);
}
}
void controller()
{
if (Input.GetButtonDown("accept"))
{
if (state == 1)
{
Application.LoadLevel("init");
}
else
{
Application.Quit();
}
}
if(Input.GetAxisRaw("Vertical") > 0)
{
if(state == 2)
{
state = 1;
}
}
if (Input.GetAxisRaw("Vertical") < 0)
{
if (state == 1)
{
state = 2;
}
}
}
}
<file_sep>/Assets/Scripts/pteros.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pteros : MonoBehaviour
{
[SerializeField] int hp;
[SerializeField] float speed;
[SerializeField] float destroy_time;
[SerializeField] int hit_damage;
enum behaviour { ONLY_DOWN, DIAG, ZIG }
enum diag { LEFT, RIGHT }
[SerializeField] diag atual_diag;
[SerializeField] behaviour atual;
public bool changed;
[SerializeField] float init_zig, end_zig;
float zig_time, zig_time_elapsed;
bool damaged;
[SerializeField] float total_time_damaged;
private float time_elapsed;
bool colided;
float time_col, time_col_elapsed;
// Use this for initialization
void Start()
{
time_col = 1f;
colided = false;
changed = false;
float rand_behaviour = Random.Range(0, 9);
if (rand_behaviour <= 3) atual = behaviour.ONLY_DOWN;
else if (rand_behaviour <= 6) atual = behaviour.DIAG;
else atual = behaviour.ZIG;
float rand_dir = Random.Range(0, 10);
if (rand_dir < 5) atual_diag = diag.LEFT;
else atual_diag = diag.RIGHT;
Destroy(gameObject, destroy_time);
zig_time_elapsed = 0;
float rand_zig = Random.Range(init_zig, end_zig);
zig_time = rand_zig;
damaged = false;
}
// Update is called once per frame
void Update()
{
move();
death();
change_color();
atualize_time();
}
void move()
{
if (atual == behaviour.ONLY_DOWN)
{
GetComponent<Transform>().Translate(Vector2.down * Time.deltaTime * speed);
}
else if (atual == behaviour.DIAG)
{
if (atual_diag == diag.LEFT)
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.left) * Time.deltaTime * speed);
}
else
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.right) * Time.deltaTime * speed);
}
}
else
{
actualize_zig();
if (atual_diag == diag.LEFT)
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.left) * Time.deltaTime * speed);
}
else
{
GetComponent<Transform>().Translate((Vector2.down + Vector2.right) * Time.deltaTime * speed);
}
}
}
public void change_dir()
{
if (atual_diag == diag.LEFT) atual_diag = diag.RIGHT;
else atual_diag = diag.LEFT;
}
void actualize_zig()
{
zig_time_elapsed += Time.deltaTime;
if (zig_time_elapsed >= zig_time)
{
change_dir();
zig_time_elapsed = 0;
}
}
void death()
{
if (hp <= 0) Destroy(gameObject);
}
public void take_damage(int damage)
{
hp -= damage;
death();
damaged = true;
}
void change_color()
{
if (this.damaged)
{
GetComponentInChildren<SpriteRenderer>().color = Color.red;
}
else
{
GetComponentInChildren<SpriteRenderer>().color = Color.white;
}
this.time_elapsed += Time.deltaTime;
if ((this.time_elapsed >= this.total_time_damaged) && this.damaged)
{
damaged = false;
this.time_elapsed = 0;
}
}
void atualize_time()
{
if (colided)
{
time_col_elapsed += Time.deltaTime;
if(time_col_elapsed >= time_col)
{
colided = false;
time_col_elapsed = 0;
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
if (!colided)
{
collision.gameObject.GetComponent<naveA>().take_damage(hit_damage);
colided = true;
}
}
}
public int get_hp()
{
return hp;
}
}
<file_sep>/Assets/Scripts/respawn.cs
//using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class respawn : MonoBehaviour {
[SerializeField] float respawn_time;
[SerializeField] bool can_spawn;
[SerializeField] GameObject nave_enemy, ptero;
[SerializeField] Transform Initial, Final;
enum type { enemy, ptero}
type atual_type;
float respawn_time_elapsed;
// Use this for initialization
void Start ()
{
float rand_type = Random.Range(0, 10);
if (rand_type <= 5) atual_type = type.enemy;
else atual_type = type.ptero;
can_spawn = true;
}
// Update is called once per frame
void Update ()
{
float rand_type = Random.Range(0, 10);
if (rand_type <= 5) atual_type = type.enemy;
else atual_type = type.ptero;
if (can_spawn)
{
float rand_x = Random.Range(Initial.position.x, Final.position.x);
if(atual_type == type.enemy) Instantiate(nave_enemy, new Vector2(rand_x, Initial.position.y), Initial.rotation);
else Instantiate(ptero, new Vector2(rand_x, Initial.position.y), Initial.rotation);
can_spawn = false;
respawn_time_elapsed = 0;
}
else
{
respawn_time_elapsed += Time.deltaTime;
if(respawn_time_elapsed >= respawn_time)
{
can_spawn = true;
respawn_time_elapsed = 0;
}
}
}
}
<file_sep>/Assets/Scripts/shoot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shoot : MonoBehaviour
{
[SerializeField] float speed;
[SerializeField] int damage;
[SerializeField] float destroy_time;
// Use this for initialization
void Start ()
{
Destroy(gameObject, destroy_time);
}
// Update is called once per frame
void Update ()
{
move();
}
void move()
{
GetComponent<Transform>().Translate(Vector2.up * Time.deltaTime * speed);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "enemy")
{
collision.gameObject.GetComponent<enemy>().take_damage(damage);
Destroy(gameObject);
}
if (collision.gameObject.tag == "ptero")
{
collision.gameObject.GetComponent<pteros>().take_damage(damage);
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/titulo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class titulo : MonoBehaviour
{
[SerializeField] GameObject[] naves;
[SerializeField] GameObject start, quit, h, v, screen;
int state;
enum types { AFONSO, HUGO, VINICIUS}
types type;
bool inited, ok;
// Use this for initialization
void Start ()
{
type = types.AFONSO;
state = 1;
ok = false;
inited = false;
}
// Update is called once per frame
void Update ()
{
update_indicator();
if (!inited && !ok)
{
Controller();
}
if (ok)
{
update_indicator2();
Controller2();
}
}
void update_indicator()
{
if(state == 1)
{
start.SetActive(true);
quit.SetActive(false);
}
else
{
start.SetActive(false);
quit.SetActive(true);
}
}
void update_indicator2()
{
if (type == types.AFONSO)
{
start.SetActive(true);
h.SetActive(false);
v.SetActive(false);
}
else if(type == types.HUGO)
{
start.SetActive(false);
h.SetActive(true);
v.SetActive(false);
}
else
{
start.SetActive(false);
h.SetActive(false);
v.SetActive(true);
}
}
void Controller()
{
if (Input.GetButtonDown("accept"))
{
if (state == 1)
{
inited = true;
naves[0].GetComponent<Animator>().SetTrigger("init");
naves[1].GetComponent<Animator>().SetTrigger("init");
naves[2].GetComponent<Animator>().SetTrigger("init");
screen.GetComponent<Animator>().SetTrigger("init");
start.GetComponent<Animator>().SetTrigger("init");
Invoke("get_ok", 1);
}
else
{
Application.Quit();
}
}
if (Input.GetAxisRaw("Vertical") >0 )
{
if (state == 2)
{
state = 1;
}
}
if (Input.GetAxisRaw("Vertical") < 0)
{
if (state == 1)
{
state = 2;
}
}
}
void get_ok()
{
ok = true;
}
void Controller2()
{
if (Input.GetButtonDown("accept"))
{
if (type == types.AFONSO)
{
naves[0].GetComponent<Animator>().SetTrigger("go");
naves[1].GetComponent<Animator>().SetTrigger("back");
naves[2].GetComponent<Animator>().SetTrigger("back");
Invoke("load_a", 0.8f);
}
else if (type == types.HUGO)
{
naves[0].GetComponent<Animator>().SetTrigger("back");
naves[1].GetComponent<Animator>().SetTrigger("go");
naves[2].GetComponent<Animator>().SetTrigger("back");
Invoke("load_h", 0.8f);
}
else
{
naves[0].GetComponent<Animator>().SetTrigger("back");
naves[1].GetComponent<Animator>().SetTrigger("back");
naves[2].GetComponent<Animator>().SetTrigger("go");
Invoke("load_v", 0.8f);
}
}
if (Input.GetButtonDown("Right"))
{
if (type == types.AFONSO)
{
type = types.VINICIUS;
}
else if (type == types.HUGO)
{
type = types.AFONSO;
}
}
if (Input.GetButtonDown("Left"))
{
if (type == types.AFONSO)
{
type = types.HUGO;
}
else if (type == types.VINICIUS)
{
type = types.AFONSO;
}
}
}
void load_a()
{
Application.LoadLevel("fase1_a");
}
void load_h()
{
Application.LoadLevel("fase1_h");
}
void load_v()
{
Application.LoadLevel("fase1_v");
}
}
<file_sep>/Assets/Scripts/ilha1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ilha1 : MonoBehaviour {
float step;
[SerializeField] Sprite[] ilhas;
// Use this for initialization
void Start()
{
float x = Random.Range(0, 10);
if(x < 2.5)
{
GetComponent<SpriteRenderer>().sprite = ilhas[0];
}
else if(x < 5)
{
GetComponent<SpriteRenderer>().sprite = ilhas[1];
}
else if (x < 7.5)
{
GetComponent<SpriteRenderer>().sprite = ilhas[2];
}
else
{
GetComponent<SpriteRenderer>().sprite = ilhas[3];
}
step = Random.Range(1, 3);
}
// Update is called once per frame
void Update()
{
GetComponent<Transform>().Translate(Vector2.down * Time.deltaTime * step);
}
}<file_sep>/Assets/Scripts/life_h.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class life_h : MonoBehaviour
{
GameObject player;
[SerializeField] GameObject[] lifes;
[SerializeField] Sprite full, empty;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
if (player.GetComponent<naveA>().get_hp() == 5)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = full;
lifes[2].GetComponent<SpriteRenderer>().sprite = full;
lifes[3].GetComponent<SpriteRenderer>().sprite = full;
lifes[4].GetComponent<SpriteRenderer>().sprite = full;
}
else if (player.GetComponent<naveA>().get_hp() == 4)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = full;
lifes[2].GetComponent<SpriteRenderer>().sprite = full;
lifes[3].GetComponent<SpriteRenderer>().sprite = full;
lifes[4].GetComponent<SpriteRenderer>().sprite = empty;
}
else if (player.GetComponent<naveA>().get_hp() == 3)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = full;
lifes[2].GetComponent<SpriteRenderer>().sprite = full;
lifes[3].GetComponent<SpriteRenderer>().sprite = empty;
lifes[4].GetComponent<SpriteRenderer>().sprite = empty;
}
else if (player.GetComponent<naveA>().get_hp() == 2)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = full;
lifes[2].GetComponent<SpriteRenderer>().sprite = empty;
lifes[3].GetComponent<SpriteRenderer>().sprite = empty;
lifes[4].GetComponent<SpriteRenderer>().sprite = empty;
}
else if (player.GetComponent<naveA>().get_hp() == 1)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = empty;
lifes[2].GetComponent<SpriteRenderer>().sprite = empty;
lifes[3].GetComponent<SpriteRenderer>().sprite = empty;
lifes[4].GetComponent<SpriteRenderer>().sprite = empty;
}
else
{
lifes[0].GetComponent<SpriteRenderer>().sprite = empty;
lifes[1].GetComponent<SpriteRenderer>().sprite = empty;
lifes[2].GetComponent<SpriteRenderer>().sprite = empty;
lifes[3].GetComponent<SpriteRenderer>().sprite = empty;
lifes[4].GetComponent<SpriteRenderer>().sprite = empty;
}
}
}
<file_sep>/Assets/Scripts/ninbus.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ninbus : MonoBehaviour {
float step;
// Use this for initialization
void Start () {
step = Random.Range(1, 3);
}
// Update is called once per frame
void Update () {
GetComponent<Transform>().Translate(Vector2.down * Time.deltaTime * step);
}
}
<file_sep>/Assets/Scripts/resp_ninbus.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class resp_ninbus : MonoBehaviour
{
public Transform []points;
[SerializeField] GameObject ninbus;
[SerializeField] float respawn_time;
float respawn_time_elapsed;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
respawn_time_elapsed += Time.deltaTime;
if(respawn_time_elapsed >= respawn_time)
{
int index = Random.Range(0,8);
Instantiate(ninbus, points[index].position, points[index].rotation);
respawn_time_elapsed = 0;
}
}
}
<file_sep>/Assets/Scripts/life_ene.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class life_ene : MonoBehaviour {
enemy player;
[SerializeField] GameObject[] lifes;
[SerializeField] Sprite full, empty;
// Use this for initialization
void Start () {
player = GetComponentInParent<enemy>();
}
// Update is called once per frame
void Update () {
if (player.get_hp() == 3)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = full;
lifes[2].GetComponent<SpriteRenderer>().sprite = full;
}
else if (player.get_hp() == 2)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = full;
lifes[2].GetComponent<SpriteRenderer>().sprite = empty;
}
else if (player.get_hp() == 1)
{
lifes[0].GetComponent<SpriteRenderer>().sprite = full;
lifes[1].GetComponent<SpriteRenderer>().sprite = empty;
lifes[2].GetComponent<SpriteRenderer>().sprite = empty;
}
else
{
lifes[0].GetComponent<SpriteRenderer>().sprite = empty;
lifes[1].GetComponent<SpriteRenderer>().sprite = empty;
lifes[2].GetComponent<SpriteRenderer>().sprite = empty;
}
}
}
<file_sep>/Assets/Scripts/naveA.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class naveA : MonoBehaviour
{
[SerializeField] int hp;
[SerializeField] bool can_fire;
[SerializeField] float step, fire_time;
[SerializeField] GameObject explo;
[SerializeField] GameObject bullet, bullet_h, bullet_v;
[SerializeField] Transform fire_point_1, fire_point_2, fire_point_3, fire_point_4, fire_point_5, max_y, min_y;
float fire_time_elapsed;
enum moves { RIGHT, LEFT, UP, DOWN}
moves last_move;
bool dead;
bool coliding;
bool damaged;
[SerializeField] float total_time_damaged;
private float time_elapsed;
[SerializeField] Animator sprite , lab;
[SerializeField] bool init;
[SerializeField] AudioSource shoot_sound;
enum types { AFONSO, HUGO, VINICIUS}
[SerializeField] types my_type;
// Use this for initialization
void Start ()
{
dead = false;
coliding = false;
can_fire = true;
}
// Update is called once per frame
void Update ()
{
if (!init)
{
move();
fire();
death();
change_color();
}
}
public void take_damage(int damage)
{
hp -= damage;
death();
damaged = true;
}
void move()
{
if (Input.GetAxisRaw("Horizontal") != 0)
{
if (Input.GetAxisRaw("Horizontal") > 0)
{
if (!coliding)
{
GetComponent<Transform>().Translate(Vector2.right * Time.deltaTime * step);
last_move = moves.RIGHT;
}
}
else
{
if (!coliding)
{
GetComponent<Transform>().Translate(Vector2.left * Time.deltaTime * step);
last_move = moves.LEFT;
}
}
}
if(Input.GetAxisRaw("Vertical") != 0)
{
if(Input.GetAxisRaw("Vertical") > 0)
{
if(GetComponent<Transform>().position.y < max_y.position.y)
{
transform.Translate(Vector2.up * Time.deltaTime * step);
}
}
else
{
if (GetComponent<Transform>().position.y > min_y.position.y)
{
transform.Translate(Vector2.down * Time.deltaTime * step);
}
}
}
}
void fire()
{
if (my_type == types.AFONSO)
{
if (Input.GetButtonDown("Fire1") && can_fire)
{
Instantiate(bullet, fire_point_1.position, fire_point_1.rotation);
Instantiate(bullet, fire_point_2.position, fire_point_2.rotation);
shoot_sound.Play();
can_fire = false;
fire_time_elapsed = 0;
}
}else if(my_type == types.HUGO)
{
if (Input.GetButtonDown("Fire1") && can_fire)
{
Instantiate(bullet_h, fire_point_1.position, fire_point_1.rotation);
Instantiate(bullet_h, fire_point_2.position, fire_point_2.rotation);
Instantiate(bullet_h, fire_point_3.position, fire_point_3.rotation);
Instantiate(bullet_h, fire_point_4.position, fire_point_4.rotation);
Instantiate(bullet_h, fire_point_5.position, fire_point_5.rotation);
shoot_sound.Play();
can_fire = false;
fire_time_elapsed = 0;
}
}
else
{
if (Input.GetButtonDown("Fire1") && can_fire)
{
Instantiate(bullet_v, fire_point_1.position, fire_point_1.rotation);
shoot_sound.Play();
can_fire = false;
fire_time_elapsed = 0;
}
}
if (!can_fire)
{
fire_time_elapsed += Time.deltaTime;
if(fire_time_elapsed >= fire_time)
{
can_fire = true;
fire_time_elapsed = 0;
}
}
}
void death()
{
if (hp <= 0 && !dead)
{
dead = true;
sprite.SetTrigger("death");
lab.SetTrigger("death");
//Destroy(gameObject, 1f);
Instantiate(explo, GetComponent<Transform>().position, GetComponent<Transform>().rotation);
Invoke("gameover", 1);
}
}
void gameover()
{
Application.LoadLevel("gameover");
}
void change_color()
{
if (this.damaged)
{
GetComponentInChildren<SpriteRenderer>().color = Color.red;
}
else
{
GetComponentInChildren<SpriteRenderer>().color = Color.white;
}
this.time_elapsed += Time.deltaTime;
if ((this.time_elapsed >= this.total_time_damaged) && this.damaged)
{
damaged = false;
this.time_elapsed = 0;
}
}
public string last_move_g()
{
if (last_move == moves.LEFT) return "L";
else if (last_move == moves.RIGHT) return "R";
else if (last_move == moves.DOWN) return "D";
else return "U";
}
public void stop_force()
{
Invoke("stops", 1);
coliding = true;
}
void stops()
{
GetComponent<Rigidbody2D>().Sleep();
GetComponent<Rigidbody2D>().WakeUp();
coliding = false;
}
public int get_hp()
{
return hp;
}
}
|
107031d2fc7cc3a281c10440f8fe3ea775bd4c78
|
[
"Markdown",
"C#"
] | 15
|
C#
|
irahel/Long-Wings
|
05e156f0b4a6951dce0bbc5a474a72faff1e2eab
|
22245a5f0e9db80f92116de1ebc41d706a30820a
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MVC.Models;
namespace MVC.Controllers
{
public class StudentAdministratieController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult SearchStudents(string id)
{
if (id == null)
{
return View("Index");
}
ViewData["StudentsSearched"] = id;
List<Student> students = new List<Student>()
{
new Student() {name = "Jimmy", age = 23 },
new Student() {name = "Frank", age = 19 },
new Student() {name = "Albert", age = 22 },
new Student() {name = "James", age = 29 }
};
List<Student> searchStudents = students
.Where(s => s.name.ToLower().StartsWith(id.ToLower()))
.OrderBy(s => s.name)
.ToList();
return View(searchStudents);
}
}
}
|
26c119301dfa68423567003e826f648f4dd9f6b6
|
[
"C#"
] | 1
|
C#
|
Umit99/MVC
|
3bf06b4ce34664d9aecd466d2df27ad33d4f469a
|
dbd4d384dd6df8a45f6ee7e1d28abc27e94ae292
|
refs/heads/master
|
<file_sep>import nflstats from '../../images/nflstats.webp'
import smitechart from '../../images/smitechart.webp'
import memorygame from '../../images/memorygame.webp'
import tictactoe from '../../images/tictactoe.webp'
import brainage from '../../images/brainage.webp'
import letterbox from '../../images/letterbox.webp'
import stackoverko from '../../images/stackoverko.webp'
import fizzbuzz from '../../images/fizzbuzz.webp'
import weatherapp from '../../images/weatherapp.webp'
import momentum from '../../images/momentum.webp'
import resume0 from '../../images/resume0.webp'
import resume from '../../images/resume.webp'
import portfolio0 from '../../images/portfolio0.webp'
import portfolio from '../../images/portfolio.webp'
export const projectsData = [
{ name: 'NFL Stats',
deployed: 'https://nfl-stats-davidko.herokuapp.com',
repo: 'https://github.com/davidholyko/NFLstats',
image: nflstats,
description: 'Very first project, written in Python',
goal: 'Display NFL data and try to do some stats about trends',
status: 'No longer maintaining'
},
{ name: 'SmiteChart',
deployed: 'https://smitechart.herokuapp.com',
repo: 'https://github.com/davidholyko/SmiteChart',
image: smitechart,
description: 'Personal Project to help quantify character strengths',
goal: 'Visualize strengths of each character to help team in Picks and Bans phase for scrims',
status: 'No longer maintaining'
},
{ name: 'Card Memory Game',
deployed: 'https://davidholyko.github.io/dko-memory-game',
repo: 'https://github.com/davidholyko/dko-memory-game',
image: memorygame,
description: 'General Assembly Pre-Work mini project',
goal: 'Practice JavaScript, HTML, CSS',
status: 'Completed and Refactored. No longer maintaining'
},
{ name: 'Tic-Tac-Toe',
deployed: 'https://davidholyko.github.io/dko-tic-tac-toe-client',
repo: 'https://github.com/davidholyko/dko-tic-tac-toe-client',
image: tictactoe,
description: 'General Assembly Project (1)',
goal: 'Practice jQuery, API requests, hide/show at correct times',
status: 'Completed. No longer maintaining'
},
{ name: 'Brain Age',
deployed: 'https://davidholyko.github.io/dko-brain-age-front-end',
repo: 'https://github.com/davidholyko/dko-brain-age-front-end',
image: brainage,
description: 'General Assembly Project (2)',
goal: 'Practice Ruby on Rails, Node packages like Chart.js',
status: 'Completed. No longer maintaining'
},
{ name: 'LetterBox',
deployed: 'https://m-d-h-s.github.io/mdhs-blog-frontend',
repo: 'https://github.com/m-d-h-s/mdhs-blog-frontend',
image: letterbox,
description: 'General Assembly Team Project (3)',
goal: 'Practice Teamwork, Agile Methodologies, Express.js',
status: 'Completed. No longer maintaining'
},
{ name: 'StackOverKo',
deployed: 'https://davidholyko.github.io/dko-stackoverko-client',
repo: 'https://github.com/davidholyko/dko-stackoverko-client',
image: stackoverko,
description: 'General Assembly Capstone Project (4)',
goal: 'Practice React.js, importing Components from other libraries',
status: 'Completed. Currently maintaining'
},
{ name: 'Fizzbuzz',
deployed: 'https://davidholyko.github.io/dko-fizzbuzz',
repo: 'https://github.com/davidholyko/dko-fizzbuzz',
image: fizzbuzz,
description: 'Visualization of Fizzbuzz produced dynamically',
goal: 'Practice Advanced JavaScript Syntax',
status: 'Completed. No longer maintaining'
},
{ name: 'Weather App',
deployed: 'https://davidholyko.github.io/dko-weather-app/',
repo: 'https://github.com/davidholyko/dko-weather-app',
image: weatherapp,
description: 'A simple weather application',
goal: 'Practice using third party APIs',
status: 'Completed. No longer maintaining'
},
{ name: 'Momentum',
deployed: 'https://davidholyko.github.io/dko-momentum',
repo: 'https://github.com/davidholyko/dko-momentum',
image: momentum,
description: 'Remake of the popular Google Chrome Extension Momentum',
goal: 'Practice React.js, CSS',
status: 'Completed. No longer maintaining'
},
{ name: 'Resume (deprecated)',
deployed: 'https://davidholyko.github.io/dko-resume-deprecated',
repo: 'https://github.com/davidholyko/dko-resume-deprecated',
image: resume0,
description: 'Web Application that mimics a US letter size resume',
goal: 'Practice CSS',
status: 'Completed. No longer maintaining'
},
{ name: 'Resume',
deployed: 'https://davidholyko.github.io/resume',
repo: 'https://github.com/davidholyko/resume',
image: resume,
description: 'Web Application that mimics a US letter size resume',
goal: 'Practice React.js, CSS',
status: 'Completed. Currently maintaining'
},
{ name: 'Portfolio (deprecated)',
deployed: 'https://davidholyko.github.io/davidholyko.github.io-deprecated',
repo: 'https://github.com/davidholyko/davidholyko.github.io-deprecated',
image: portfolio0,
description: 'Ultra flashy portfolio with heavy animations and colors',
goal: 'Practice Handlebars.js, Animations, Bootstrap, CSS',
status: 'Completed. No longer maintaining'
},
{ name: 'Portfolio',
deployed: 'https://davidholyko.github.io',
repo: 'https://github.com/davidholyko/davidholyko.github.io',
image: portfolio,
description: 'Minimialist portfolio, designed for readability',
goal: 'Practice React.js, UX/UI, Mobile Design',
status: 'Completed. Currently maintaining'
}
]
|
89110ec986050aa74d74504d1b8a8fbf439d2dc3
|
[
"JavaScript"
] | 1
|
JavaScript
|
davidholyko/dko-projects
|
e3757475dd3c64397353c9353359910df4ad17e2
|
60c961f04bbd3ed8ef6e9d0f1f1d30be8126fc68
|
refs/heads/master
|
<file_sep>package de.onlineshop.main;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
/**
* Description
*
* @author <NAME>
* @version 1.0
*/
public class JdbcServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String jdbc_properties = getInitParameter("jdbc_properties");
final ServletContext app = getServletContext();
final InputStream in = app.getResourceAsStream(jdbc_properties);
final Properties p = new Properties();
p.load(in);
response.setContentType(
"text/html;charset=UTF-8");
PrintWriter out =
response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<body>");
out.println(
"<br>driver: " + p.getProperty("driver"));
out.println(
"<br>Your url: " + p.getProperty("url"));
out.println(
"<br>username: " + p.getProperty("username"));
out.println(
"<br>password: " + p.getProperty("password"));
out.println("</body>");
out.println("</html>");
}
}
<file_sep>package de.onlineshop.main.listeners;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Description
*
* @author <NAME>
* @version 1.0
*/
@WebListener
public class OnlineshopListener implements HttpSessionListener{
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
context.log("Session created: " + se.toString());
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
context.log("Session destroyed: " + se.toString());
}
}
<file_sep>package de.onlineshop.main;
import de.onlineshop.main.model.Customer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* Description
*
* @author <NAME>
* @version 1.0
*/
@WebServlet(urlPatterns = {"/register"}, loadOnStartup = 1)
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<body>");
out.println("<h1>Registrierung</h1>");
out.println("Datum: " + new Date());
out.println("Remote address: " + request.getRemoteAddr());
out.println("</body>");
out.println("</html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Context-Type","text/html;charset=UTF-8");
final String email = request.getParameter("email");
final String password = request.getParameter("password");
final PrintWriter out = response.getWriter();
final HttpSession session = request.getSession();
final Customer customer = new Customer();
final Cookie cookieMail = new Cookie("email", email);
final Cookie cookiePasswd = new Cookie("password", password);
response.addCookie(cookieMail);
response.addCookie(cookiePasswd);
customer.setEmail(email);
customer.setPassword(<PASSWORD>);
session.setAttribute("customer", customer);
final RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request,response);
}
}
<file_sep>package de.onlineshop.main;
import de.onlineshop.main.service.FotoService;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Description
*
* @author <NAME>
* @version 1.0
*/
@WebServlet(value = "/sell", asyncSupported = true)
@MultipartConfig(
maxFileSize = 1024*1024*10,
maxRequestSize = 1024*1024*30,
location = "/tmp",
fileSizeThreshold = 1024*1024)
public class SellServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext ac = request.startAsync();
ac.start(new FotoService(ac));
}
}
|
3e94ff7f3e2852873308b9fee6b41956e813000c
|
[
"Java"
] | 4
|
Java
|
ValeryOster/Onlineshop
|
6bf01cee29df9d6b5cb94c806a7f9df33ff351e7
|
37b1bc8fb05996f518e9a9f10364b535ca9effed
|
refs/heads/main
|
<file_sep>void setup() {
Serial.begin(2400);
}
void loop() {
Serial.print('<');
Serial.print(analogRead(A0));
Serial.print(',');
Serial.print(analogRead(A1));
Serial.print('>');
Serial.flush();
}
<file_sep>import cv2, time
import numpy as np
import socket
# Socket Constants
#=======================================================================================
UDP_IP = "127.0.0.1"
UDP_PORT = 5006
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
# OpenCV Constants
#=======================================================================================
RED = (0, 0, 255)
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
ORANGE = (0, 69, 255)
MAGENTA = (240, 0, 159)
FONT = cv2.FONT_HERSHEY_SIMPLEX
# Functions
#=======================================================================================
def parse(data_string):
start0 = data_string.find('<')+1
len0 = data_string[start0:].find(',')
end0 = start0+len0
start1 = end0+1
len1 = data_string[start1:].find('>')
end1 = start1+len1
param0 = data_string[start0:end0]
param1 = data_string[start1:end1]
return param0, param1
# Main Loop
#=======================================================================================
while True:
if cv2.waitKey(1) == 27:
cv2.destroyAllWindows()
break
try:
data, addr = sock.recvfrom(128)
data_string1 = "".join([chr(asc_d) for asc_d in data])
# data, addr = sock.recvfrom(1024)
# data_string2 = "".join([chr(asc_d) for asc_d in data])
# param0, param1 = parse(data_string1+data_string2)
# print(data_string1)
param0, param1 = parse(data_string1)
rect_size0 = int(param0)/1023.0*325
rect_size1 = int(param1)/1023.0*325
except:
param0, param1 = "None", "None"
rect_size0, rect_size1 = 0, 0
INTERFACE = np.zeros((200,350,3))
cv2.putText(INTERFACE, "Received Parameters", (10,55), FONT, 1, RED, 2, cv2.LINE_AA)
cv2.putText(INTERFACE, "param0 |", (10,98), FONT, 0.6, GREEN, 1, cv2.LINE_AA)
cv2.putText(INTERFACE, param0, (110,98), FONT, 0.6, GREEN, 1, cv2.LINE_AA)
cv2.rectangle(INTERFACE, (10,108), (int(11+rect_size0), 120), GREEN, -1)
cv2.putText(INTERFACE, "param1 |", (10,140), FONT, 0.6, ORANGE, 1, cv2.LINE_AA)
cv2.putText(INTERFACE, param1, (110,140), FONT, 0.6, ORANGE, 1, cv2.LINE_AA)
cv2.rectangle(INTERFACE, (10,150), (int(11+rect_size1), 162), ORANGE, -1)
cv2.imshow("GUI - Receiver", INTERFACE)
<file_sep>import socket
import sqlite3 as sql
import time
from os import system
system("title "+"UDP-to-Database")
# CREATE DATABASE & TABLE
#=======================================================================================
conn = sql.connect('./udp_sink.db')
curr = conn.cursor()
table = """CREATE TABLE IF NOT EXISTS UDP_SINK
(id, received)"""
curr.execute(table)
conn.commit()
# RESET
#=======================================================================================
curr.execute("""DELETE FROM UDP_SINK""")
conn.commit()
curr.execute("""INSERT INTO UDP_SINK VALUES
(?,?)""", (1,0))
conn.commit()
# UDP CONNECTION
#=======================================================================================
UDP_IP = "127.0.0.1"
UDP_PORT = 5006
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
print("Transferring UDP Sink to Database...")
while True:
data, addr = sock.recvfrom(128)
data = (data,)
query = """Update UDP_SINK set received = ? where id = 1"""
curr.execute(query, data)
conn.commit()
time.sleep(0.001) # 5ms delay
<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: BPSK 2 Parametre
# Description: 2 parametreyi UDP'den BPSK ile iletir; yine UDP'ye yonlendirir
# GNU Radio version: 3.7.13.5
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
from PyQt4 import Qt
from gnuradio import analog
from gnuradio import blocks
from gnuradio import digital
from gnuradio import eng_notation
from gnuradio import filter
from gnuradio import gr
from gnuradio import qtgui
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from grc_gnuradio import blks2 as grc_blks2
from optparse import OptionParser
import limesdr
import sip
import sys
from gnuradio import qtgui
class bpsk_servo_kontrol_vFinal(gr.top_block, Qt.QWidget):
def __init__(self):
gr.top_block.__init__(self, "BPSK 2 Parametre")
Qt.QWidget.__init__(self)
self.setWindowTitle("BPSK 2 Parametre")
qtgui.util.check_set_qss()
try:
self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
except:
pass
self.top_scroll_layout = Qt.QVBoxLayout()
self.setLayout(self.top_scroll_layout)
self.top_scroll = Qt.QScrollArea()
self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
self.top_scroll_layout.addWidget(self.top_scroll)
self.top_scroll.setWidgetResizable(True)
self.top_widget = Qt.QWidget()
self.top_scroll.setWidget(self.top_widget)
self.top_layout = Qt.QVBoxLayout(self.top_widget)
self.top_grid_layout = Qt.QGridLayout()
self.top_layout.addLayout(self.top_grid_layout)
self.settings = Qt.QSettings("GNU Radio", "bpsk_servo_kontrol_vFinal")
self.restoreGeometry(self.settings.value("geometry").toByteArray())
##################################################
# Variables
##################################################
self.sps = sps = 15
self.nfilts = nfilts = 180
self.samp_rate = samp_rate = 100e3
self.rrc_taps = rrc_taps = firdes.root_raised_cosine(nfilts, nfilts, 1.0/float(sps), 0.35, 45*nfilts)
self.payload = payload = 21
self.interpolation = interpolation = 20
self.baseband_LO = baseband_LO = 20e3
self.access_code = access_code = '010110011011101100010101011111101001001110001011010001101010001'
self.BPSK = BPSK = digital.constellation_bpsk().base()
##################################################
# Blocks
##################################################
self.rational_resampler_xxx_1 = filter.rational_resampler_ccc(
interpolation=1,
decimation=interpolation,
taps=None,
fractional_bw=None,
)
self.qtgui_sink_x_0 = qtgui.sink_c(
1024, #fftsize
firdes.WIN_BLACKMAN_hARRIS, #wintype
0, #fc
samp_rate, #bw
"", #name
True, #plotfreq
True, #plotwaterfall
True, #plottime
True, #plotconst
)
self.qtgui_sink_x_0.set_update_time(1.0/10)
self._qtgui_sink_x_0_win = sip.wrapinstance(self.qtgui_sink_x_0.pyqwidget(), Qt.QWidget)
self.top_grid_layout.addWidget(self._qtgui_sink_x_0_win)
self.qtgui_sink_x_0.enable_rf_freq(False)
self.low_pass_filter_0 = filter.fir_filter_ccf(1, firdes.low_pass(
1, samp_rate, 10e3, 1.6E3, firdes.WIN_HAMMING, 6.76))
self.limesdr_source_0 = limesdr.source('', 1, '')
self.limesdr_source_0.set_sample_rate(samp_rate*interpolation)
self.limesdr_source_0.set_center_freq(850e6, 0)
self.limesdr_source_0.set_bandwidth(5e6,1)
self.limesdr_source_0.set_gain(30,1)
self.limesdr_source_0.set_antenna(2,1)
self.limesdr_source_0.calibrate(5e6, 1)
self.digital_pfb_clock_sync_xxx_0 = digital.pfb_clock_sync_ccf(sps, .062, (rrc_taps), nfilts, nfilts/2, 1.5, 2)
self.digital_lms_dd_equalizer_cc_0 = digital.lms_dd_equalizer_cc(8, .01, 2, BPSK)
self.digital_diff_decoder_bb_0 = digital.diff_decoder_bb(2)
self.digital_costas_loop_cc_0 = digital.costas_loop_cc(0.0628, 2, False)
self.digital_constellation_decoder_cb_0 = digital.constellation_decoder_cb(BPSK)
self.blocks_unpack_k_bits_bb_0 = blocks.unpack_k_bits_bb(1)
self.blocks_udp_sink_0 = blocks.udp_sink(gr.sizeof_char*1, '127.0.0.1', 5006, payload, False)
self.blocks_multiply_xx_0_0 = blocks.multiply_vcc(1)
self.blks2_packet_decoder_0 = grc_blks2.packet_demod_b(grc_blks2.packet_decoder(
access_code='',
threshold=-1,
callback=lambda ok, payload: self.blks2_packet_decoder_0.recv_pkt(ok, payload),
),
)
self.analog_sig_source_x_0_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, -baseband_LO, 0.5, 0)
self.analog_feedforward_agc_cc_0 = analog.feedforward_agc_cc(1024, 1.55)
##################################################
# Connections
##################################################
self.connect((self.analog_feedforward_agc_cc_0, 0), (self.digital_pfb_clock_sync_xxx_0, 0))
self.connect((self.analog_sig_source_x_0_0, 0), (self.blocks_multiply_xx_0_0, 1))
self.connect((self.blks2_packet_decoder_0, 0), (self.blocks_udp_sink_0, 0))
self.connect((self.blocks_multiply_xx_0_0, 0), (self.low_pass_filter_0, 0))
self.connect((self.blocks_unpack_k_bits_bb_0, 0), (self.blks2_packet_decoder_0, 0))
self.connect((self.digital_constellation_decoder_cb_0, 0), (self.digital_diff_decoder_bb_0, 0))
self.connect((self.digital_costas_loop_cc_0, 0), (self.digital_lms_dd_equalizer_cc_0, 0))
self.connect((self.digital_diff_decoder_bb_0, 0), (self.blocks_unpack_k_bits_bb_0, 0))
self.connect((self.digital_lms_dd_equalizer_cc_0, 0), (self.digital_constellation_decoder_cb_0, 0))
self.connect((self.digital_lms_dd_equalizer_cc_0, 0), (self.qtgui_sink_x_0, 0))
self.connect((self.digital_pfb_clock_sync_xxx_0, 0), (self.digital_costas_loop_cc_0, 0))
self.connect((self.limesdr_source_0, 0), (self.rational_resampler_xxx_1, 0))
self.connect((self.low_pass_filter_0, 0), (self.analog_feedforward_agc_cc_0, 0))
self.connect((self.rational_resampler_xxx_1, 0), (self.blocks_multiply_xx_0_0, 0))
def closeEvent(self, event):
self.settings = Qt.QSettings("GNU Radio", "bpsk_servo_kontrol_vFinal")
self.settings.setValue("geometry", self.saveGeometry())
event.accept()
def get_sps(self):
return self.sps
def set_sps(self, sps):
self.sps = sps
self.set_rrc_taps(firdes.root_raised_cosine(self.nfilts, self.nfilts, 1.0/float(self.sps), 0.35, 45*self.nfilts))
def get_nfilts(self):
return self.nfilts
def set_nfilts(self, nfilts):
self.nfilts = nfilts
self.set_rrc_taps(firdes.root_raised_cosine(self.nfilts, self.nfilts, 1.0/float(self.sps), 0.35, 45*self.nfilts))
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.qtgui_sink_x_0.set_frequency_range(0, self.samp_rate)
self.low_pass_filter_0.set_taps(firdes.low_pass(1, self.samp_rate, 10e3, 1.6E3, firdes.WIN_HAMMING, 6.76))
self.analog_sig_source_x_0_0.set_sampling_freq(self.samp_rate)
def get_rrc_taps(self):
return self.rrc_taps
def set_rrc_taps(self, rrc_taps):
self.rrc_taps = rrc_taps
self.digital_pfb_clock_sync_xxx_0.update_taps((self.rrc_taps))
def get_payload(self):
return self.payload
def set_payload(self, payload):
self.payload = payload
def get_interpolation(self):
return self.interpolation
def set_interpolation(self, interpolation):
self.interpolation = interpolation
def get_baseband_LO(self):
return self.baseband_LO
def set_baseband_LO(self, baseband_LO):
self.baseband_LO = baseband_LO
self.analog_sig_source_x_0_0.set_frequency(-self.baseband_LO)
def get_access_code(self):
return self.access_code
def set_access_code(self, access_code):
self.access_code = access_code
def get_BPSK(self):
return self.BPSK
def set_BPSK(self, BPSK):
self.BPSK = BPSK
def main(top_block_cls=bpsk_servo_kontrol_vFinal, options=None):
from distutils.version import StrictVersion
if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"):
style = gr.prefs().get_string('qtgui', 'style', 'raster')
Qt.QApplication.setGraphicsSystem(style)
qapp = Qt.QApplication(sys.argv)
tb = top_block_cls()
tb.start()
tb.show()
def quitting():
tb.stop()
tb.wait()
qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
qapp.exec_()
if __name__ == '__main__':
main()
<file_sep>import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5006
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print(":> %s" % data)
# print(":> %s" % bytearray.fromhex(data).decode())
# print([chr(c) for c in data])<file_sep>#include <Servo.h>
//#define SERIAL_BUFFER_SIZE 2
Servo servo;
int servoPin = 9;
int pos;
int dly;
void setup() {
servo.attach(servoPin);
Serial.begin(3200);
// Serial.setTimeout(100);
// Serial.print(SERIAL_BUFFER_SIZE);
}
void loop() {
if (Serial.available()>0){
int inChar = Serial.read();
if (inChar == '<'){
delay(80);
int param0 = Serial.readStringUntil(',').toInt()/100;
int param1 = Serial.readStringUntil('>').toInt()/100;
pos = map(param0, 0, 10, 0, 180);
dly = map(param1, 0, 10, 5, 40);
Serial.print("P:");
Serial.print(pos);
Serial.print("D:");
Serial.println(dly);
// servo.write(pos);
// delay(dly);
}
else{
delay(1);
}
}
}
<file_sep>import serial, time
import sqlite3 as sql
from os import system
system("title "+"Database-to-Serial")
COM_PORT = 'COM9'
print(f"Transfer Database > {COM_PORT}")
try:
conn = sql.connect('./udp_sink.db')
ser = serial.Serial(COM_PORT, baudrate=3200, timeout=1)
except:
print("Error!")
while True:
curr = conn.execute("SELECT id, received from UDP_SINK")
for row in curr:
data = row[1]
ser.write(data)
print(ser.readline())
<file_sep>import socket, serial
from os import system
system("title "+"Serial-to-UDP")
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
COM_PORT = 'COM10'
print(f"Transfer {COM_PORT} > {UDP_IP} {UDP_PORT}")
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
ser = serial.Serial(COM_PORT, baudrate=2400, timeout=None)
while True:
MESSAGE = ser.read(21)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
print(MESSAGE)<file_sep># Servo kontrolü için uçtan uca haberleşme kanalı tasarımı
Proje arkadaşım Bengü BİLGİÇ ile hazırladığımız final sunumu [linktedir](assets/final_sunum.pdf).
<p align="center">
<img src="https://github.com/001honi/design-of-comm-channel/blob/main/assets/scheme.png" />
</p>
## Dosya Hiyerarşisi
#### arduino
- receiver.ino <br> _Servoya bağlı alıcı Arduino kodlarını içerir_
- transmitter.ino <br> _Potansiyometrelere bağlı verici Arduino kodlarını içerir_
#### share
- db.py <br> _GNU Radio alıcı tarafında UDP’ye bağlanarak yaratılan udp_sink.db’ye veri akışı yapar_
- db2ser.py <br> _Veritabanından Seri Porta veri akışı yapar_
- gui_receiver_db.py <br> _Veritabanındaki bilgileri arayüze yazar_
- gui_receiver_db2.py <br> _Veritabanındaki bilgileri arayüze yazar - Türkçe_
- ser2udp.py <br> _Verici tarafı için Seri Porttan GNU Radio UDP Source için köprü oluşturur_
#### utils
- gui_receiver.py <br> _UDP’deki bilgileri arayüze yazar_
- listen_receiver.py <br> _UDP’deki bilgileri konsola yazar_
- udp2ser.py <br> _Alıcı tarafı için UDP Sink’ten servo kontrolü yapacak Arduino’ya veri akışı yapar_
## Program Akışı
- **Verici bilgisayarda GNU Radio ve udp2ser.py çalıştırılır.**
- **Alıcı bilgisayarda GNU Radio ardından;**
- UDP'den veri tabanına akış sağlayacak db.py,
- Veritabanı bilgisini okuyacak arayüz gui_receiver_db.py,
- Veritabanından alıcı Arduino için db2ser.py çalıştırılır.
<file_sep>import socket, serial, time
from os import system
system("title "+"UDP-to-Serial")
UDP_IP = "127.0.0.1"
UDP_PORT = 5006
COM_PORT = 'COM9'
print(f"Transfer {UDP_IP} {UDP_PORT} > {COM_PORT}")
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
ser = serial.Serial(COM_PORT, baudrate=4800, timeout=0)
while True:
data, addr = sock.recvfrom(128) # buffer size is 1024 bytes
ser.write(data)
# print(len(data))
print(ser.readline())
|
ea53c63a4958601fbf2758c9ab86ac42925c1bc4
|
[
"Markdown",
"Python",
"C++"
] | 10
|
C++
|
001honi/design-of-comm-channel
|
dc7aab2508691303dacb5eddd1060ce0a43b74c1
|
406cc9510dfea917d0cfb3ead085fb278e962246
|
refs/heads/master
|
<repo_name>danielmoder/gsr<file_sep>/mysite/gsr/views.py
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template import loader
from django.contrib.auth.models import User
def index(request):
userlist = User.objects.all()
template = loader.get_template('gsr/index.html')
context = {'userlist': userlist }
return HttpResponse(template.render(context, request))
def home(request):
return HttpResponse("GSR WEB HOME PAGE")
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('<PASSWORD>')
user = authenticate(username=username, password=<PASSWORD>)
login(request, user)
return redirect('index')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
<file_sep>/mysite/gsr/models.py
from django.db import models
from django.contrib.postgres.fields import ArrayField
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
def __str__(self):
return self.username
class Stratum(models.Model):
question = models.CharField(max_length=200)
choices = ArrayField(
base_field=models.TextField(),
size=10
)
class Project(models.Model):
name = models.CharField(max_length=50)
participants = ArrayField(
base_field=models.TextField(),
size=None
)
strata = models.ManyToManyField(Stratum)
<file_sep>/mysite/gsr/apps.py
from django.apps import AppConfig
class GsrConfig(AppConfig):
name = 'gsr'
|
347e734e3776f5374c85c2b04d168e197c2dd95c
|
[
"Python"
] | 3
|
Python
|
danielmoder/gsr
|
7531631c4c5e45554b0307e7e5b29f89d9a1d7a7
|
39e7a286f4cfb33125ae26af07dde1b3a3e83b04
|
refs/heads/main
|
<file_sep>#include<stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10],i,j;
printf("Enter the elements of the matrix A : \n");
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of the matrix B :\n");
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("Addition of two matrix : \n");
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
c[i][j]= a[i][j] + b[i][j];
}
}
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
printf("%4d",c[i][j]);
}
printf("\n");
}
}
|
7eab517370c13f5a753fb79691525c39697b4ffb
|
[
"C"
] | 1
|
C
|
vikkyvivek2002/matrix_addition
|
c6b58f0d9c5629b9fa4c85457280ae15e46e7ca6
|
4fc703a1dd2618369dd3c7b14f0b84ff055f0553
|
refs/heads/master
|
<repo_name>FoFBode4/ICan<file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://sql7.freemysqlhosting.net:3306/sql7362479?useUnicode=true&serverTimezone=UTC
spring.datasource.username=sql7362479
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
jwt.secret=litsedu
<file_sep>/src/main/java/edu/lits/testapi/service/PotentialWorkerService.java
package edu.lits.testapi.service;
import edu.lits.testapi.pojo.PotentialWorker;
public interface PotentialWorkerService {
PotentialWorker readByID(Long user_id);
}
<file_sep>/src/main/java/edu/lits/testapi/repository/CardRepository.java
package edu.lits.testapi.repository;
import edu.lits.testapi.pojo.Card;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CardRepository extends JpaRepository<Card, Long> {
}
|
089c00e6ffc844bce3a536fdad41d7a8894a95e4
|
[
"Java",
"INI"
] | 3
|
INI
|
FoFBode4/ICan
|
2128dddeadfed638a9dde6579b64039404516cfb
|
998618fccd420f34b8c5181f8715760f570c29df
|
refs/heads/master
|
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
</parent>
<groupId>com.deepak</groupId>
<artifactId>cicuit-breaker-resilience4j</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<lombok.version>1.18.10</lombok.version>
<maven.compiler.plugin.version>3.8.0</maven.compiler.plugin.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<resilience4j.version>1.5.0</resilience4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-reactor</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.0.0</version>
<configuration>
<failOnError>false</failOnError>
<spotbugsXmlOutputDirectory>${project.build.directory}/findbugs</spotbugsXmlOutputDirectory>
<spotbugsXmlOutputFilename>findbugs.xml</spotbugsXmlOutputFilename>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.8</version>
</plugin>
</plugins>
</reporting>
</project><file_sep>package com.deepak.models;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
@Getter
@Builder
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class User {
String id;
String name;
}
<file_sep># Resilience4j-Circuitbreaker with Spring-Boot example.
This project will help you implement Circuit breaker using Resilience4j library in Spring-Boot application. This sample project has all the use cases which are common in any of the project based on circuit-breaker implementation.
##### Prerequisites
* Java Development Kit (JDK), version 8 or higher.
* Maven
##### Getting the Project
https://github.com/knoldus/resilience4j-circuitbreaker.git
##### Command to start the project
**mvn spring-boot:run**
Json Formats for different Rest services are mentioned below :
**1. Success Case:**
> Route(Method - GET) : localhost:9080/success/users
Rawdata(json): { "id": "1", "name": "Deepak" }
**2. Failure Case:**
>Route(Method - GET) : localhost:9080/failure/users
**3. Fallback User:**
> Route(Method - GET) : localhost:9080/fallback/users
Rawdata(json): { "id": "1", "name": "Deepak" }
|
b677603582fa345eaac73a2416f1592d88283d93
|
[
"Markdown",
"Java",
"Maven POM"
] | 3
|
Maven POM
|
knoldus/resilience4j-circuitbreaker
|
7c16610c312a53ac63ed08e0d8728d6774632847
|
2046e3079bffc8ec865d13b2940611c43647f9ed
|
refs/heads/master
|
<file_sep>package io.bpoller.unilend.service;
import io.bpoller.unilend.model.Bid;
import io.bpoller.unilend.model.BidHistory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.reactivestreams.Publisher;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toSet;
@Service
public class BidHistoryRetriever {
Publisher<BidHistory> retrieveHistory(String projectId) {
Map<String, String> params = new HashMap<>();
params.put("id", projectId);
params.put("tri", "ordre");
params.put("direction", "1");
try {
Document doc = Jsoup.connect("https://www.unilend.fr/ajax/displayAll").data(params).post();
Elements bidsRows = doc.select("tr");
Set<Bid> bids = bidsRows.stream().skip(1).map(this::toBid).collect(toSet());
return Mono.just(new BidHistory(projectId, bids, new Date()));
} catch (IOException e) {
return Mono.error(e);
}
}
private Bid toBid(Element element) {
Elements tds = element.select("td");
String sequence = tds.get(0).text();
String interest = tds.get(1).text().replace("%", "").replace(",", ".").trim();
int amount = Integer.parseInt(tds.get(2).text().replace("€", "").replace(" ", ""));
return new Bid(sequence, amount, interest, new Date());
}
}<file_sep>package io.bpoller.unilend.service;
import reactor.core.tuple.Tuple;
import reactor.core.tuple.Tuple2;
import reactor.core.tuple.Tuple3;
import java.util.ArrayList;
public class AmountSummarizer extends ArrayList<Tuple3> {
private Integer accumulator;
public AmountSummarizer() {
accumulator = 0;
}
Integer getValue() {
return accumulator;
}
void acc(Integer i) {
accumulator += i;
}
public static void accept(AmountSummarizer summarizer, Tuple2<String, Integer> stringIntegerTuple2) {
summarizer.acc(stringIntegerTuple2.getT2());
summarizer.add(Tuple.of(stringIntegerTuple2.t1, stringIntegerTuple2.t2, summarizer.getValue()));
}
public static void combine(AmountSummarizer o, AmountSummarizer o1) {
System.out.println();
}
}
<file_sep>package io.bpoller.unilend.model.project;
import io.bpoller.unilend.model.CQRSEvent;
public abstract class ProjectEvent extends CQRSEvent<String>{
public ProjectEvent(String aggregateId) {
super(aggregateId);
}
}<file_sep>package io.bpoller.unilend.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.bpoller.unilend.model.BidHistory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.tuple.Tuple;
import static org.slf4j.LoggerFactory.getLogger;
@Service
public class DisplayDude {
private Logger logger = getLogger(getClass());
private ObjectMapper objectMapper;
@Autowired
public DisplayDude(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
void show(BidHistory bidHistory) {
logger.info("Project {}", bidHistory.getProjectId());
bidHistory.reduceByInterestRate().entrySet()
.stream()
.map(entry -> Tuple.of(entry.getKey(), entry.getValue()))
.sorted(this::sort)
.collect(AmountSummarizer::new, AmountSummarizer::accept, AmountSummarizer::combine)
.stream()
.forEach((entry) -> logger.info("{}%-{}€---{}€", entry.get(0), entry.get(1), entry.get(2)));
logger.info("----------------");
}
private int sort(Tuple left, Tuple right) {
Float leftF = Float.parseFloat((String) left.get(0));
Float rightF = Float.parseFloat((String) right.get(0));
return Float.compare(leftF, rightF);
}
private String toJSON(Object bid) {
try {
return objectMapper.writeValueAsString(bid);
} catch (JsonProcessingException e) {
e.printStackTrace();
return "error";
}
}
}<file_sep>package io.bpoller.unilend.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
public abstract class CQRSEvent<I extends Serializable> {
@JsonProperty("_id")
public final String eventId;
public CQRSEvent(I aggregateId) {
this.eventId = generateEventId(aggregateId);
}
/**
* This method must be implemented by all sub classes. It generates an event
* id that must be equal if two events of the same type with similar properties
* shall be considered equal. The event id is used for implementing idem potent
* behaviour of an event store.
*
* @param aggregateId
* @return
*/
protected abstract String generateEventId(I aggregateId);
}<file_sep>package io.bpoller.unilend.model;
import java.util.Date;
public class Bid {
private String sequence;
private int amount;
private String interest;
private Date timestamp;
private Bid() {
}
public Bid(String sequence, int amount, String interest, Date timestamp) {
this.sequence = sequence;
this.amount = amount;
this.interest = interest;
this.timestamp = timestamp;
}
public String getSequence() {
return sequence;
}
public int getAmount() {
return amount;
}
public String getInterest() {
return interest;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Bid)) return false;
Bid bid = (Bid) o;
return getSequence().equals(bid.getSequence());
}
@Override
public int hashCode() {
return getSequence().hashCode();
}
}<file_sep>package io.bpoller.unilend.controller;
import io.bpoller.unilend.model.SayHi;
import org.slf4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@RestController
public class HelloController {
private Logger logger = getLogger(getClass());
@RequestMapping(path = "/api/hello", method = GET)
public ResponseEntity<SayHi> sayHello() {
logger.info("Hello {}", "world");
return new ResponseEntity<>(new SayHi("Hello World"), OK);
}
@RequestMapping(path = "/", method = GET)
public ResponseEntity<String> index() {
return new ResponseEntity<>("Up and running", OK);
}
}<file_sep>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'spring-boot'
jar {
baseName = 'unilendViz'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url 'http://repo.spring.io/snapshot' }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile "org.springframework.boot:spring-boot-starter-web"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "io.projectreactor:reactor-core:2.5.0.M2"
compile "org.mongodb:mongodb-driver-reactivestreams:1.2.0"
compile "com.fasterxml.jackson.core:jackson-databind:2.6.3"
compile 'org.jsoup:jsoup:1.8.3'
testCompile "junit:junit"
testCompile 'org.mockito:mockito-core:2.0.43-beta'
testCompile 'org.springframework.boot:spring-boot-starter-test'
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
task stage(type: Copy, dependsOn: [clean, build]) {
from jar.archivePath
into project.rootDir
rename {
'app.jar'
}
}
stage.mustRunAfter(clean)
clean << {
project.file('app.jar').delete()
}<file_sep>package io.bpoller.unilend;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoDatabase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
public class AppConfiguration {
@Value("${mongo.connectionurl}")
private String mongoConnectionURL;
@Value("${mongo.dbname}")
private String mongoDbName;
@Bean
ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder.json().build();
}
@Bean
MongoDatabase mongoDatabase() {
return MongoClients.create(mongoConnectionURL).getDatabase(mongoDbName);
}
}<file_sep>package io.bpoller.unilend.service;
import io.bpoller.unilend.model.BidHistory;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import reactor.core.publisher.Flux;
import reactor.core.tuple.Tuple;
import java.io.IOException;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.slf4j.LoggerFactory.getLogger;
public class BidHistoryRetrieverTest {
private Logger logger = getLogger(getClass());
private BidHistoryRetriever bidHistoryRetriever;
@Before
public void init() {
initMocks(this);
bidHistoryRetriever = new BidHistoryRetriever();
}
@Test
public void shouldRetrieveIds() throws IOException, InterruptedException {
long t = System.currentTimeMillis();
Flux
.from(bidHistoryRetriever.retrieveHistory("30559"))
.map(bidHisto -> {
logger.info("Request Delay : {}", System.currentTimeMillis() - t);
return bidHisto.reduceByInterestRate();
})
.consume(histoValues -> histoValues.entrySet()
.stream()
.map(entry -> Tuple.of(entry.getKey(), entry.getValue()))
.sorted(this::sort)
.collect(AmountSummarizer::new, AmountSummarizer::accept, AmountSummarizer::combine)
.stream()
.forEach((entry) -> logger.info("{}%-{}€---{}€", entry.get(0), entry.get(1), entry.get(2))));
}
private int sort(Tuple left, Tuple right) {
Float leftF = Float.parseFloat((String) left.get(0));
Float rightF = Float.parseFloat((String) right.get(0));
return Float.compare(leftF, rightF);
}
}<file_sep># nowave-backend
# Technical architecture
cf [https://docs.google.com/drawings/d/1xATnbuzua3EMhTeWH-zYjkRyXPwhS6P7tRI8Lb1MT6k/edit](https://docs.google.com/drawings/d/1xATnbuzua3EMhTeWH-zYjkRyXPwhS6P7tRI8Lb1MT6k/edit)
# Deployment in production (Heroku)
## Setting up for deployment
Add the Heroku Git repo:
`$> git remote add heroku https://git.heroku.com/nowave-backend.git`
## Deploy
`git push heroku master `
|
c04ba3072f8e98abe444255dd303b3db744721a1
|
[
"Markdown",
"Java",
"Gradle"
] | 11
|
Java
|
bpoller/unilend_viz
|
476137e82b6d59d2d32062a6d8ca85ef2b915fc3
|
910ad54f3b716d8c4cbc0f1a2cc2382882f68633
|
refs/heads/master
|
<file_sep>'use strict';
import { AssetManager } from './assets.es6';
import { Display } from './display.es6';
import { Engine } from './engine.es6';
import { World } from './world.es6';
function onReady() {
new Promise((resolve) => {
document.addEventListener('DOMContentLoaded', () => {
resolve();
});
});
}
(async () => {
//wait for dom rendering
await onReady();
//wait for assets to load
let image = await AssetManager.loadSprite('data/rabbit-trap.png');
let zone = await AssetManager.loadJSON('data/zone00.json');
//start the setup
const display = new Display(document.querySelector('canvas'));
display.tilesheet.image = image;
//set world size
let world_width = display.tilesheet.tile_size * zone.columns;
let world_height = display.tilesheet.tile_size * zone.rows;
display.setWorldSize(world_width, world_height);
display.resize();
const world = new World( world_width, world_height);
const engine = new Engine( () => {
world.update();
}, () => {
display.drawTileMap(zone.graphical_map, zone.columns);
display.render();
}, 1000 / 30);
engine.start();
})();
<file_sep>'use strict';
class Rectangle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
get left() {
return this.x;
}
get right() {
return this.x + this.width;
}
get top() {
return this.y;
}
get bottom() {
return this.y + this.height;
}
set left (val) {
this.x = val;
}
set right (val) {
this.x = val - this.width;
}
set top (val) {
this.y = val;
}
set bottom (val) {
this.y = val - this.height;
}
}
export class World extends Rectangle {
constructor(width, height) {
super(0, 0, width, height);
this.friction = .9;
this.gravity = 3;
this.player = new Player(30, 80, 12, 16);
}
collide (object) {
if (object.left < this.left) {
object.left = this.left;
object.velocity_x = 0;
}
else if (object.right > this.right) {
object.right = this.right;
object.velocity_x = 0;
}
if (object.top < this.top) {
object.top = this.top;
object.velocity_y = 0;
}
else if (object.bottom > this.bottom) {
object.bottom = this.bottom;
object.velocity_y = 0;
}
}
update () {
this.player.velocity_y += this.gravity;
this.player.update();
this.player.velocity_y *= this.friction;
this.player.velocity_x *= this.friction;
this.collide(this.player);
}
}
class Player extends Rectangle {
constructor(x, y, width, height) {
super(x, y, width, height);
this.velocity_x = 0;
this.velocity_y = 0;
this.jumping = false;
}
//clamp the velocities to avoid tunneling
set vel_x (vel_x) {
if (vel_x > 0)
this.velocity_x = Math.min(vel_x, 14);
else
this.velocity_x = Math.max(vel_x, -14);
}
set vel_y (vel_y) {
if (vel_y > 0)
this.velocity_y = Math.min(vel_y, 14);
else
this.velocity_y = Math.max(vel_y, -14);
}
get vel_x () {
return this.velocity_x;
}
get vel_y () {
return this.velocity_y;
}
update() {
this.x += this.vel_x;
this.y += this.vel_y;
}
moveLeft() {
this.vel_x += 0.5;
}
moveRight() {
this.vel_x -= 0.5;
}
jump() {
if (!this.jumping) {
this.vel_y += 20;
this.jumping = true;
}
}
}
<file_sep>
## Development Setup
### es6 build pipeline inspired from [here](https://developers.google.com/web/shows/ttt/series-2/es2015)
prerequisites:
1. npm
2. gulp v4
### Instructions
1. Clone repo
```git clone https://github.com/suneetfcc/rabbit-trap```
1. Install dependencies
```npm install```
2. Build project
```gulp```
3. Run and watch on dev server
```gulp watch```
<file_sep>'use strict';
export class Display {
constructor(canvas) {
this.context = canvas.getContext('2d');
this.buffer = document.createElement('canvas').getContext('2d');
this.tilesheet = new TileSheet(16, 8);
}
setWorldSize (width, height) {
this.buffer.canvas.width = width;
this.buffer.canvas.height = height;
}
render() {
this.context.drawImage(this.buffer.canvas, 0, 0, this.buffer.canvas.width, this.buffer.canvas.height, 0, 0, this.context.canvas.width, this.context.canvas.height);
}
_resize(width, height, aspect_ratio) {
if (width / height > aspect_ratio) {
width = height * aspect_ratio;
}
else {
height = width / aspect_ratio;
}
this.context.canvas.width = width;
this.context.canvas.height = height;
this.context.imageSmoothingEnabled = false;
this.render();
}
resize () {
this._resize(document.documentElement.clientWidth - 32, document.documentElement.clientHeight - 32, this.buffer.canvas.width / this.buffer.canvas.height);
}
drawTileMap(map, columns) {
map.forEach((tile, index) => {
let src_x = this.tilesheet.tile_x(tile);
let src_y = this.tilesheet.tile_y(tile);
let size = this.tilesheet.tile_size;
let dest_x = (index % columns) * size;
let dest_y = Math.floor(index / columns) * size;
this.buffer.drawImage(this.tilesheet.image, src_x, src_y, size, size, dest_x, dest_y, size, size);
});
}
}
export class TileSheet {
//change this handle size of different widht and height
constructor (tile_size, columns) {
this.tile_size = tile_size;
this.columns = columns;
this.image = null;
}
//return the x, y position of a tile (numbered from 0 to n) from the tilesheet
tile_x(tile) {
return (tile % this.columns) * this.tile_size;
}
tile_y(tile) {
return Math.floor(tile / this.columns) * this.tile_size;
}
}
<file_sep>'use strict';
export class Engine {
constructor(update, render, time_step) {
this.accumulated_time = 0;
this.time_step = time_step;
this.animation_frame = null;
this.update = update;
this.render = render;
this.time = 0;
}
start () {
this.time = window.performance.now();
this.animation_frame = window.requestAnimationFrame(this.run.bind(this));
}
run (time) {
let updated = false;
let dt = time - this.time;
this.time = time;
this.accumulated_time += dt;
while (this.accumulated_time >= this.time_step) {
updated = true;
this.update();
this.accumulated_time -= this.time_step;
}
if (updated)
this.render();
this.animation_frame = window.requestAnimationFrame(this.run.bind(this));
}
stop () {
this.accumulated_time = 0;
this.time = 0;
window.cancelAnimationFrame(this.animation_frame);
}
}
|
1f9fc1b1a6f96465981f47fac9bbb007760ec46f
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
suneetfcc/rabbit-trap
|
395c526dc7b1901340917269f1c7383e9342c226
|
540f63c9d97a1d06229044551410b9078f7f28ef
|
refs/heads/master
|
<file_sep>import React, { useEffect, useState } from "react";
import uniqid from "uniqid";
import styles from "./photo-gallery.module.scss";
import LightBox from "../light-box/light-box.component";
import { connect } from "react-redux";
import {
showLightBox,
setCurrentImageIndex,
} from "../../redux/light-box/light-box.actions";
import range from "lodash.range";
function PhotoGallery({ imageName, showLightBox, setCurrentImageIndex }) {
const imagesCount = 4;
const [imageURLs, setImageURLs] = useState([]);
const handleOnClick = (e) => {
showLightBox();
setCurrentImageIndex(parseInt(e.currentTarget.dataset.id));
};
useEffect(() => {
try {
const URLsToAdd = [];
const mainImageUrl = require(`../../assets/images/boardgames/${imageName}/${imageName}.jpg`);
URLsToAdd.push(mainImageUrl);
range(1, imagesCount).forEach((imgNumber) => {
try {
const url = require(`../../assets/images/boardgames/${imageName}/${imageName}_${imgNumber}.jpg`);
URLsToAdd.push(url);
} catch (error) {
console.error(error.message);
}
});
setImageURLs(URLsToAdd);
} catch (error) {
console.error(error.message);
}
}, [imageName]);
return (
<>
<div className={styles.container}>
<div className={styles.mainImageWrapper}>
<img
src={imageURLs[0]}
alt="board game"
onClick={handleOnClick}
data-id={0}
className={styles.mainImage}
/>
</div>
<div className={styles.extraImagesContainer}>
{imageURLs.slice(1).map((url, index) => (
<div
key={uniqid()}
onClick={handleOnClick}
data-id={index + 1}
className={styles.extraImage}
style={{
backgroundImage: `url(${url})`,
}}
></div>
))}
</div>
</div>
{<LightBox imageURLs={imageURLs} />}
</>
);
}
const mapDispatchToProps = (dispatch) => ({
showLightBox: () => dispatch(showLightBox()),
setCurrentImageIndex: (newIndex) => dispatch(setCurrentImageIndex(newIndex)),
});
export default connect(null, mapDispatchToProps)(PhotoGallery);
<file_sep>import React from "react";
import MultipleRange from "../../components/multiple-range/multiple-range.component";
import { filterValues } from "./filter.utils";
import { connect } from "react-redux";
import {
resetFilter,
setGameTime,
setPlayersCount,
toggleIsInStock,
} from "../../redux/filter/filter.actions";
import {
selectGameTime,
selectIsInStock,
selectPlayersCount,
selectDebouncedPriceValues,
selectItemsFound,
selectPriceLimits,
} from "../../redux/filter/filter.selectors";
import range from "lodash.range";
import { createStructuredSelector } from "reselect";
import OptionSelector from "../option-selector/option-selector.component";
import styles from "./filter.module.scss";
import { CSSTransition, SwitchTransition } from "react-transition-group";
import ButtonCustom from "../button-custom/button-custom.component";
import { buttonStyleTypes } from "../button-custom/button-custom.utils";
import useHistoryChange from "../../custom-hooks/useHistoryChange";
function Filter({
isInStock,
resetFilter,
setGameTime,
toggleIsInStock,
setPlayersCount,
itemsFound,
}) {
useHistoryChange(() => {
resetFilter();
});
return (
<div className="row">
<div className="col-6 col-xl-12">
<div className={styles.section}>
<h2 className={styles.sectionTitle}>Время партии:</h2>
<OptionSelector
options={[
{ value: filterValues.gameTime.UNSET, text: "Не указано" },
{ value: filterValues.gameTime.SHORT, text: "Короткая" },
{ value: filterValues.gameTime.MEDIUM, text: "Средняя" },
{ value: filterValues.gameTime.LONG, text: "Долгая" },
{
value: filterValues.gameTime.VERY_LONG,
text: "Очень долгая",
},
{ value: filterValues.gameTime.DIFFERENT, text: "Различная" },
]}
onChange={(value) => {
setGameTime(value);
}}
/>
</div>
</div>
<div className="col-6 col-xl-12">
<div className={styles.section}>
<h2 className={styles.sectionTitle}>Кол-во игроков:</h2>
<OptionSelector
options={[
{ value: filterValues.playersCount.ALL, text: "Все" },
...range(1, filterValues.playersCount.COUNT + 1).map((count) => {
return { value: count, text: count };
}),
{
value: filterValues.playersCount.MORE,
text: `\u003E ${filterValues.playersCount.COUNT}`,
},
]}
onChange={(value) => {
setPlayersCount(value);
}}
/>
</div>
</div>
<div className="col-12 ">
<div className={styles.section}>
<h2 className={styles.sectionTitle}>Цена:</h2>
<MultipleRange />
</div>
</div>
<div className="col-12">
<div className={styles.inStock}>
<div className="mr-2">
<div
className={styles.checkbox}
onClick={() => {
toggleIsInStock();
}}
tabIndex={0}
>
{isInStock && (
<span className={`material-icons ${styles.checkboxTickIcon}`}>
check
</span>
)}
</div>
</div>
<div>
<div>В наличии</div>
</div>
</div>
<div className={styles.found}>
<span className={styles.foundTitle}>Найдено:</span>
<SwitchTransition>
<CSSTransition
key={itemsFound}
timeout={0}
classNames={{
enterDone: styles.enterDone,
}}
>
<span className={styles.foundNumber}>{itemsFound}</span>
</CSSTransition>
</SwitchTransition>
</div>
<ButtonCustom
onClick={() => {
resetFilter();
}}
styleType={buttonStyleTypes.SECONDARY}
fullWidth
>
Сбросить фильтр
</ButtonCustom>
</div>
</div>
);
}
const mapStateToProps = createStructuredSelector({
gameTime: selectGameTime,
isInStock: selectIsInStock,
playersCount: selectPlayersCount,
priceLimits: selectPriceLimits,
debouncedPriceValues: selectDebouncedPriceValues,
itemsFound: selectItemsFound,
});
const mapDispatchToProps = (dispatch) => ({
resetFilter: () => dispatch(resetFilter()),
toggleIsInStock: () => dispatch(toggleIsInStock()),
setGameTime: (gameTime) => dispatch(setGameTime(gameTime)),
setPlayersCount: (playersCount) => dispatch(setPlayersCount(playersCount)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Filter);
<file_sep>const userActionTypes = {
TOGGLE_USER_DROPDOWN_VISIBILITY: "TOGGLE_USER_DROPDOWN_VISIBILITY",
HIDE_USER_DROPDOWN: "HIDE_USER_DROPDOWN",
SIGN_IN_WITH_GOOGLE_START: "SIGN_IN_WITH_GOOGLE_START",
SIGN_IN_SUCCESS: "SIGN_IN_SUCCESS",
SIGN_IN_FAILURE: "SIGN_IN_FAILURE",
SIGN_IN_WITH_EMAIL_START: "SIGN_IN_WITH_EMAIL_START",
SIGN_UP_START: "SIGN_UP_START",
SIGN_UP_SUCCESS: "SIGN_UP_SUCCESS",
SIGN_UP_FAILURE: "SIGN_UP_FAILURE",
FETCH_AUTH_STATE_START: "FETCH_AUTH_STATE_START",
FETCH_AUTH_STATE_SUCCESS: "FETCH_AUTH_STATE_SUCCESS",
FETCH_AUTH_STATE_FAILURE: "FETCH_AUTH_STATE_FAILURE",
FETCH_CURRENT_USER_SUCCESS: "FETCH_CURRENT_USER_SUCCESS",
FETCH_CURRENT_USER_FAILURE: "FETCH_CURRENT_USER_FAILURE",
SIGN_OUT_START: "SIGN_OUT_START",
SIGN_OUT_SUCCESS: "SIGN_OUT_SUCCESS",
SIGN_OUT_FAILURE: "SIGN_OUT_FAILURE",
CLEAR_ERROR: "CLEAR_ERROR",
};
export default userActionTypes;
<file_sep>import React from "react";
import styles from "./form-submit-spinner.module.scss";
function FormSubmitSpinner() {
return (
<div className={styles.container}>
<div className={styles.bars}>
<div></div>
<div></div>
<div></div>
</div>
</div>
);
}
export default FormSubmitSpinner;
<file_sep>import paginationActionTypes from "./pagination.types";
export const setCurrentPage = (page) => ({
type: paginationActionTypes.SET_CURRENT_PAGE,
payload: page,
});
export const setPaginatedCollection = (paginatedCollection) => ({
type: paginationActionTypes.SET_PAGINATED_COLLECTION,
payload: paginatedCollection,
});
export const setItemsCount = (itemsCount) => ({
type: paginationActionTypes.SET_ITEMS_COUNT,
payload: itemsCount,
});
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import uniqid from "uniqid";
import styles from "./footer.module.scss";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faInstagram,
faFacebookF,
faTelegramPlane,
faVk,
} from "@fortawesome/free-brands-svg-icons";
import { selectMainMenuDirectory } from "../../redux/directories/directories.selectors";
function Footer({ mainMenuDirectory }) {
return (
<footer className={styles.container}>
<div className={styles.topSection}>
<div className="container-lg">
<ul className={styles.navList}>
{mainMenuDirectory.map(({ path, title }) => (
<li key={uniqid()} className={styles.navItem}>
<Link to={`/${path}`} className={styles.navItemText}>
{title}
</Link>
</li>
))}
</ul>
</div>
</div>
<div className="container-lg">
<div className={styles.contactInfo}>
<div className={styles.phoneNumber}>
<a href="tel:+7000000XX">+7 (000) 000-ХХ</a>
</div>
<div className={styles.email}>
<a href="mailto:<EMAIL>"><EMAIL></a>
</div>
<ul className={styles.socialMediaList}>
<li className={styles.socialMediaItem}>
<Link to="/">
<FontAwesomeIcon
icon={faInstagram}
className={styles.instFontIcon}
/>
</Link>
</li>
<li className={styles.socialMediaItem}>
<Link to="/">
<FontAwesomeIcon
icon={faFacebookF}
className={styles.fbFontIcon}
/>
</Link>
</li>
<li className={styles.socialMediaItem}>
<Link to="/">
<FontAwesomeIcon
icon={faTelegramPlane}
className={styles.fontIcon}
/>
</Link>
</li>
<li className={styles.socialMediaItem}>
<Link to="/">
<FontAwesomeIcon icon={faVk} className={styles.fontIcon} />
</Link>
</li>
</ul>
</div>
</div>
<div className={styles.bottomSection}>
<div className="container-lg">
<div className={styles.companyInfo}>© BoardLords, 2020-2020</div>
</div>
</div>
</footer>
);
}
const mapStateToProps = createStructuredSelector({
mainMenuDirectory: selectMainMenuDirectory,
});
export default connect(mapStateToProps)(Footer);
<file_sep>import sortingActionTypes from "./sorting.types";
export const setSortType = (sortType) => ({
type: sortingActionTypes.SET_SORT_TYPE,
payload: sortType,
});
export const setItemsToSortCount = (itemsToSortCount) => ({
type: sortingActionTypes.SET_ITEMS_TO_SORT_COUNT,
payload: itemsToSortCount,
});
<file_sep>const cartActionTypes = {
ADD_ITEM_TO_CART: "ADD_ITEM_TO_CART",
REMOVE_ITEM_FROM_CART: "REMOVE_ITEM_FROM_CART",
CLEAR_ITEM_FROM_CART: "CLEAR_ITEM_FROM_CART",
TOGGLE_CART_DROPDOWN_VISIBILITY: "TOGGLE_CART_DROPDOWN_VISIBILITY",
HIDE_CART_DROPDOWN: "HIDE_CART_DROPDOWN",
CLEAR_CART: "CLEAR_CART",
FETCH_USER_CART_ITEMS_SUCCESS: "FETCH_USER_CART_ITEMS_SUCCESS",
FETCH_USER_CART_ITEMS_FAILURE: "FETCH_USER_CART_ITEMS_FAILURE",
UPDATE_USER_CART_ITEMS_SUCCESS: "UPDATE_USER_CART_ITEMS_SUCCESS",
UPDATE_USER_CART_ITEMS_FAILURE: "UPDATE_USER_CART_ITEMS_FAILURE",
};
export default cartActionTypes;
<file_sep>import React, { useEffect } from "react";
import { connect } from "react-redux";
import {
selectItemsPerPage,
selectCurrentPage,
} from "../../redux/pagination/pagination.selectiors";
import { setItemsCount } from "../../redux/pagination/pagination.actions";
import { createStructuredSelector } from "reselect";
const withPagination = (WrappedComponent) => {
const WithPaginationComponent = ({
collection,
currentPage,
itemsPerPage,
setItemsCount,
...otherProps
}) => {
const firstPageItem = (currentPage - 1) * itemsPerPage;
const lastPageItem = currentPage * itemsPerPage;
const paginatedCollection = collection.slice(firstPageItem, lastPageItem);
useEffect(() => {
setItemsCount(collection.length);
}, [collection.length, setItemsCount]);
return (
<>
<WrappedComponent collection={paginatedCollection} {...otherProps} />
</>
);
};
return connect(mapStateToProps, mapDispatchToProps)(WithPaginationComponent);
};
const mapStateToProps = createStructuredSelector({
itemsPerPage: selectItemsPerPage,
currentPage: selectCurrentPage,
});
const mapDispatchToProps = (dispatch) => ({
setItemsCount: (itemsCount) => dispatch(setItemsCount(itemsCount)),
});
export default withPagination;
<file_sep>const filterActionTypes = {
RESET_FILTER: "RESET_FILTER",
SET_GAME_TIME: "SET_GAME_TIME",
SET_PLAYERS_COUNT: "SET_PLAYERS_COUNT",
TOGGLE_IS_IN_STOCK: "TOGGLE_IS_IN_STOCK",
SET_PRICE_VALUES: "SET_PRICE_VALUES",
SET_DEBOUNCED_PRICE_VALUES: "SET_DEBOUNCED_PRICE_VALUES",
SET_SHOW_FILTER: "SET_SHOW_FILTER",
RESET_PRICE_LIMITS: "RESET_PRICE_LIMITS",
SET_ITEMS_FOUND: "SET_ITEMS_FOUND",
};
export default filterActionTypes;
<file_sep>import React from "react";
import styles from "./form.module.scss";
function Form({ children, ...otherProps }) {
return (
<form className={styles.container} {...otherProps}>
{children}
</form>
);
}
export default Form;
<file_sep>import React from "react";
import ButtonCustom from "../button-custom/button-custom.component";
import { buttonStyleTypes } from "../button-custom/button-custom.utils";
import styles from "./return-to-shop.module.scss";
function ReturnToShop() {
return (
<div className={styles.container}>
<ButtonCustom to="/shop" styleType={buttonStyleTypes.SECONDARY}>
<span className={`material-icons ${styles.returnArrow}`}>
keyboard_return
</span>
В каталог
</ButtonCustom>
</div>
);
}
export default ReturnToShop;
<file_sep>## Boardlord | boardgame store
### Сайт проекта:
https://boardlord.web.app/
### Используемые технологии:
- HTML / CSS (SCSS, CSS modules, React Transition Group) / JavaScript
- React / Redux, reselect, saga
- Firebase
- Bootstrap (layout)
- Git
### Краткое описание проекта
Этот проект представляет из себя упрощенный интернет-магазин настольных игр. Это SPA. В нем реализован простой поиск, с применением debounce, фильтрация, пагинация и сортировка товаров. Создана корзина, возможность добавления товаров в список избранных. База данных, аутентентификация, авторизация пользователей.
### На примере данного проекта я продемонстрировал следующие навыки:
- Умение работать с React, использование React Hooks, создание кастомных хуков, создание собственных HOC компонентов
- Стейт менеджмент с помощью Redux, для более оптимизированной работы также использовал библиотеку reselect. Для работы с асинхронными запросами, такими как Google аутентификация, обращение к базе данных, использовал Redux-saga, с ее помощью реализовал живое взаимодействие с базой данных - при обновлении данных в базе, мой сайт мгновенно реагирует на изменения.
- В качестве базы данных использовал Firebase Firestore. В базе данных содержатся данные пользователей, содержимое корзины пользователей, список избранных товаров, а также коллекция игр магазина в общем. Создал авторизацию с помощью правил безопасности в Firestore, чтобы пользователи смогли иметь доступ только к своим товарам, причем они должны быть зарегистрированными на сайте.
- Для улучшения user experience для незарегистрированных пользователей, реализовал хранение списка покупок и избранного в браузере, чтобы не терять их в случае, если сессия прервется
- Для стилизации сайта использовал css modules, SCSS, для анимации реакт компонентов использовал React Transition Group). Для layout сайта использовал сетку Bootstrap.
- Deployment сайта делал с помощью хостинга firebase
<file_sep>import transform from "lodash.transform";
import sortBy from "lodash.sortby";
import isEmpty from "lodash.isempty";
export const defineViewportAlias = (breakpoints) => {
if (!isEmpty(breakpoints)) {
const breakpointsArray = mapBreakpointsObjectToArray(breakpoints);
let found;
found = breakpointsArray.findIndex(
(item) =>
window.matchMedia(`(max-width: ${getProperMaxWidth(item.value)}px)`)
.matches
);
if (found < 0) return breakpointsArray[breakpointsArray.length - 1].alias;
if (found > 0) return breakpointsArray[found - 1].alias;
if (found === 0) return "";
} else {
return "";
}
};
const getProperMaxWidth = (maxWidth) => {
return maxWidth - 0.02; // work around the limitations of min- and max- prefixes and viewports with fractional widths
};
const mapBreakpointsObjectToArray = (breakpoints) => {
const breakpointsArray = transform(
breakpoints,
(result, value, key) => {
return result.push({ alias: key, value });
},
[]
);
const sortedArray = sortBy(breakpointsArray, ["value"]);
return sortedArray;
};
export const breakpointsDown = (
breakpoints,
breakpoint,
currentViewportAlias
) => {
const breakpointsArray = mapBreakpointsObjectToArray(breakpoints);
const breakpointIndex = breakpointsArray.findIndex(
(item) => item.value === breakpoint
);
const currentViewportAliasIndex = breakpointsArray.findIndex(
(item) => item.alias === currentViewportAlias
);
return currentViewportAliasIndex <= breakpointIndex;
};
export const breakpointsUp = (
breakpoints,
breakpoint,
currentViewportAlias
) => {
const breakpointsArray = mapBreakpointsObjectToArray(breakpoints);
const breakpointIndex = breakpointsArray.findIndex(
(item) => item.value === breakpoint
);
const currentViewportAliasIndex = breakpointsArray.findIndex(
(item) => item.alias === currentViewportAlias
);
return currentViewportAliasIndex >= breakpointIndex;
};
export const breakpointsOnly = (
breakpoints,
breakpoint,
currentViewportAlias
) => {
const breakpointsArray = mapBreakpointsObjectToArray(breakpoints);
const breakpointIndex = breakpointsArray.findIndex(
(item) => item.value === breakpoint
);
const currentViewportAliasIndex = breakpointsArray.findIndex(
(item) => item.alias === currentViewportAlias
);
return currentViewportAliasIndex === breakpointIndex;
};
export const breakpointsBetween = (
breakpoints,
breakpointFrom,
breakpointBefore,
currentViewportAlias
) => {
const breakpointsArray = mapBreakpointsObjectToArray(breakpoints);
const breakpointIndexFrom = breakpointsArray.findIndex(
(item) => item.value === breakpointFrom
);
const breakpointIndexBefore = breakpointsArray.findIndex(
(item) => item.value === breakpointBefore
);
const currentViewportAliasIndex = breakpointsArray.findIndex(
(item) => item.alias === currentViewportAlias
);
return (
currentViewportAliasIndex >= breakpointIndexFrom &&
currentViewportAliasIndex < breakpointIndexBefore
);
};
<file_sep>export const alertTypes = { ERROR: 1 };
<file_sep>const paginationActionTypes = {
SET_CURRENT_PAGE: "SET_CURRENT_PAGE",
SET_PAGINATED_COLLECTION: "SET_PAGINATED_COLLECTION",
SET_ITEMS_COUNT: "SET_ITEMS_COUNT",
};
export default paginationActionTypes;
<file_sep>const sidebarMenuActionTypes = {
TOGGLE_SHOW_SIDEBAR_MENU: "TOGGLE_SHOW_SIDEBAR_MENU",
HIDE_SIDEBAR_MENU: "HIDE_SIDEBAR_MENU",
};
export default sidebarMenuActionTypes;
<file_sep>const sortingActionTypes = {
SET_SORT_TYPE: "SET_SORT_TYPE",
SET_ITEMS_TO_SORT_COUNT: "SET_ITEMS_TO_SORT_COUNT",
};
export default sortingActionTypes;
<file_sep>export const toggleItem = (favoriteItems, itemToToggle) => {
const found = favoriteItems.find((item) => item.id === itemToToggle.id);
if (found) {
return favoriteItems.filter((item) => item.id !== itemToToggle.id);
}
return [...favoriteItems, itemToToggle];
};
export const mergeFavoriteItems = (favoriteItems1, favoriteItems2) => {
const _favoriteItems1 = [...favoriteItems1];
const _favoriteItems2 = [...favoriteItems2];
_favoriteItems1.forEach((itemFrom1) => {
const foundIndex = _favoriteItems2.findIndex(
(itemFrom2) => itemFrom1.id === itemFrom2.id
);
if (foundIndex !== -1) {
_favoriteItems2.splice(foundIndex, 1);
}
});
const mergedFavoriteItems = _favoriteItems1.concat(_favoriteItems2);
return mergedFavoriteItems;
};
<file_sep>import { createSelector } from "reselect";
export const selectSorting = (state) => state.sorting;
export const selectSortType = createSelector(
[selectSorting],
(sorting) => sorting.sortType
);
export const selectItemsToSortCount = createSelector(
[selectSorting],
(sorting) => sorting.itemsToSortCount
);
<file_sep>import React from "react";
import { connect } from "react-redux";
import { selectIsItemInCart } from "../../redux/cart/cart.selectors";
import { addItemToCart } from "../../redux/cart/cart.actions";
import styles from "./purchase-button.module.scss";
import ButtonCustom from "../button-custom/button-custom.component";
import { buttonStyleTypes } from "../button-custom/button-custom.utils";
function PurchaseButton({ item, isItemInCart, addItemToCart }) {
return (
<>
{item.inStockCount > 0 ? (
!isItemInCart ? (
<ButtonCustom
styleType={buttonStyleTypes.DARK}
onClick={() => {
addItemToCart(item);
}}
>
Купить
</ButtonCustom>
) : (
<ButtonCustom
to="/cart"
styleType={buttonStyleTypes.MAIN}
title="перейти в корзину"
>
Товар в корзине{" "}
<span className={`material-icons ${styles.goToCartArrow}`}>
arrow_right_alt
</span>
</ButtonCustom>
)
) : (
<ButtonCustom styleType={buttonStyleTypes.MAIN} outline>
Нет в наличии
</ButtonCustom>
)}
</>
);
}
const mapStateToProps = (state, ownProps) => ({
isItemInCart: selectIsItemInCart(ownProps.item)(state),
});
const mapDispatchToProps = (dispatch) => ({
addItemToCart: (item) => dispatch(addItemToCart(item)),
});
export default connect(mapStateToProps, mapDispatchToProps)(PurchaseButton);
<file_sep>import breakpointsActionTypes from "./breakpoints-provider.types";
export const setBreakpoints = (breakpoints) => ({
type: breakpointsActionTypes.SET_BREAKPOINTS,
payload: breakpoints,
});
export const setCurrentViewportAlias = (breakpoint) => ({
type: breakpointsActionTypes.SET_CURRENT_BREAKPOINT,
payload: breakpoint,
});
<file_sep>import sortingActionTypes from "./sorting.types";
import { sortTypeValues } from "../../components/sorting/sorting.utils";
const initialState = {
sortType: sortTypeValues.POPULAR,
itemsToSortCount: 0,
};
const sortingReducer = (state = initialState, { type, payload }) => {
switch (type) {
case sortingActionTypes.SET_SORT_TYPE:
return { ...state, sortType: payload };
case sortingActionTypes.SET_ITEMS_TO_SORT_COUNT:
return { ...state, itemsToSortCount: payload };
default:
return state;
}
};
export default sortingReducer;
<file_sep>import React from "react";
import { useEffect } from "react";
import { useRef } from "react";
import { useCallback } from "react";
function EscapeOutsideWrapper({
children,
onEscapeOutside,
isNodeToEscapeVisible = true,
nodesToIgnore = [],
...otherProps
}) {
const nodeToEscape = useRef();
const handleClick = useCallback(
(e) => {
if (
nodeToEscape.current &&
!nodeToEscape.current.contains(e.target) &&
(nodesToIgnore.length > 0
? !nodesToIgnore.some((node) =>
node ? node.contains(e.target) : false
)
: true)
) {
isNodeToEscapeVisible && onEscapeOutside();
}
},
[nodesToIgnore, isNodeToEscapeVisible, onEscapeOutside]
);
const handlePressEscape = useCallback(
(e) => {
if (e.keyCode === 27) onEscapeOutside(); // Esc key
},
[onEscapeOutside]
);
useEffect(() => {
window.addEventListener("click", handleClick, true);
window.addEventListener("touchend", handleClick, true);
window.addEventListener("keydown", handlePressEscape, true);
return () => {
window.removeEventListener("click", handleClick, true);
window.removeEventListener("touchend", handleClick, true);
window.removeEventListener("keydown", handlePressEscape, true);
};
}, [handleClick, handlePressEscape]);
return (
<span
ref={(node) => {
nodeToEscape.current = node;
}}
{...otherProps}
>
{children}
</span>
);
}
export default EscapeOutsideWrapper;
<file_sep>import searchActionTypes from "./search.types";
export const hideSearchDropdown = () => ({
type: searchActionTypes.HIDE_SEARCH_DROPDOWN,
});
export const showSearchDropdown = () => ({
type: searchActionTypes.SHOW_SEARCH_DROPDOWN,
});
export const hideSearchModal = () => ({
type: searchActionTypes.HIDE_SEARCH_MODAL,
});
export const showSearchModal = () => ({
type: searchActionTypes.SHOW_SEARCH_MODAL,
});
export const setCurrentListItemIndex = (listItemIndex) => ({
type: searchActionTypes.SET_CURRENT_LIST_ITEM_INDEX,
payload: listItemIndex,
});
export const increaseCurrentListItemIndex = () => ({
type: searchActionTypes.INCREASE_CURRENT_LIST_ITEM_INDEX,
});
export const decreaseCurrentListItemIndex = () => ({
type: searchActionTypes.DECREASE_CURRENT_LIST_ITEM_INDEX,
});
export const resetCurrentListItemIndex = () => ({
type: searchActionTypes.RESET_CURRENT_LIST_ITEM_INDEX,
});
export const setSearchQuery = (searchQuery) => ({
type: searchActionTypes.SET_SEARCH_INPUT,
payload: searchQuery,
});
<file_sep>import React, { useState, useCallback } from "react";
import styles from "./option-selector.module.scss";
import { useEffect } from "react";
import uniqid from "uniqid";
import EscapeOutsideWrapper from "../escape-outside/escape-outside-wrapper.component";
import useHistoryChange from "../../custom-hooks/useHistoryChange";
function OptionSelector({ options, onChange, disabled = false }) {
const [isDropdownVisible, setIsDropdownVisible] = useState(false);
const [currentOption, setCurrentOption] = useState(options[0]);
const INITIAL_LIST_ITEM_INDEX = -1;
const [currentListItemIndex, setCurrentListItemIndex] = useState(
INITIAL_LIST_ITEM_INDEX
);
const resetCurrentListItemIndex = useCallback(() => {
setCurrentListItemIndex(INITIAL_LIST_ITEM_INDEX);
}, [INITIAL_LIST_ITEM_INDEX]);
const increaseCurrentListItemIndex = () => {
setCurrentListItemIndex((prevState) => prevState + 1);
};
const decreaseCurrentListItemIndex = () => {
setCurrentListItemIndex((prevState) => prevState - 1);
};
const hideDropdown = useCallback(() => {
setIsDropdownVisible(false);
}, []);
const handleOptionSet = useCallback(
(option) => {
setCurrentOption(option);
hideDropdown();
},
[hideDropdown]
);
const handleOnChange = useCallback(onChange, []);
useEffect(() => {
handleOnChange(currentOption.value);
}, [currentOption.value, handleOnChange]);
useEffect(() => {
!isDropdownVisible && resetCurrentListItemIndex();
}, [isDropdownVisible, resetCurrentListItemIndex]);
useHistoryChange(() => {
handleOptionSet(options[0]);
});
return (
<EscapeOutsideWrapper onEscapeOutside={hideDropdown}>
<div className={styles.container}>
{!disabled ? (
<div
name={currentOption.value}
className={styles.currentOption}
tabIndex={0}
onClick={() => {
if (isDropdownVisible) {
setIsDropdownVisible(false);
} else {
setIsDropdownVisible(true);
}
}}
onKeyDown={(e) => {
switch (e.keyCode) {
case 40: // DOWN arrow
e.preventDefault();
if (currentListItemIndex < options.length - 1) {
increaseCurrentListItemIndex();
} else {
setCurrentListItemIndex(0);
}
break;
case 38: // UP arrow
e.preventDefault();
if (currentListItemIndex > 0) {
decreaseCurrentListItemIndex();
} else {
setCurrentListItemIndex(options.length - 1);
}
break;
case 13: // Enter key
currentListItemIndex >= 0
? handleOptionSet(options[currentListItemIndex])
: isDropdownVisible
? hideDropdown()
: setIsDropdownVisible(true);
break;
default:
break;
}
}}
>
{currentOption.text}
</div>
) : (
<div className={styles.disabled}>{currentOption.text}</div>
)}
{isDropdownVisible && (
<div className={styles.dropdown}>
{options.map(({ value, text }, index) => (
<div
key={uniqid()}
name={value}
onMouseEnter={() => setCurrentListItemIndex(index)}
onMouseLeave={() => resetCurrentListItemIndex()}
onClick={() => {
handleOptionSet(options[currentListItemIndex]);
}}
className={`${styles.option} ${
index === currentListItemIndex && styles.optionActive
}`}
>
{text}
</div>
))}
</div>
)}
</div>
</EscapeOutsideWrapper>
);
}
export default OptionSelector;
<file_sep>export const addItem = (cartItems, itemToAdd) => {
const found = cartItems.find((item) => item.id === itemToAdd.id);
if (found) {
return cartItems.map((item) =>
item.id === itemToAdd.id ? { ...item, quantity: item.quantity + 1 } : item
);
}
return [...cartItems, { ...itemToAdd, quantity: 1 }];
};
export const removeItem = (cartItems, itemToRemove) => {
const found = cartItems.find((item) => item.id === itemToRemove.id);
if (found) {
return found.quantity <= 1
? cartItems.filter((item) => item.id !== itemToRemove.id)
: cartItems.map((item) =>
item.id === itemToRemove.id
? { ...item, quantity: item.quantity - 1 }
: item
);
}
return cartItems;
};
export const clearItem = (cartItems, itemToClear) => {
return cartItems.filter((item) => item.id !== itemToClear.id);
};
export const mergeCartItems = (cartItems1, cartItems2) => {
const _cartItems1 = [...cartItems1];
const _cartItems2 = [...cartItems2];
_cartItems1.forEach((itemFrom1) => {
const foundIndex = _cartItems2.findIndex(
(itemFrom2) => itemFrom1.id === itemFrom2.id
);
if (foundIndex !== -1) {
const sameCartItem = _cartItems2.splice(foundIndex, 1)[0];
itemFrom1.quantity = itemFrom1.quantity + sameCartItem.quantity;
}
});
const mergedCartItems = _cartItems1.concat(_cartItems2);
return mergedCartItems;
};
<file_sep>import React from "react";
import { useLocation } from "react-router-dom";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectDirectoriesForSectionTitle } from "../../redux/directories/directories.selectors";
import styles from "./section-title.module.scss";
function SectionTitle({ directories }) {
const location = useLocation();
const paths = location.pathname.split("/").filter((path) => path);
const last = paths[paths.length - 1];
const currentPath = directories[last];
return (
<>
{currentPath ? (
<h1 className={styles.title}>{currentPath.title}</h1>
) : null}
</>
);
}
const mapStateToProps = createStructuredSelector({
directories: selectDirectoriesForSectionTitle,
});
export default connect(mapStateToProps)(SectionTitle);
<file_sep>import { all, call, put, select, takeLatest } from "redux-saga/effects";
import userActionTypes from "../user/user.types";
import { getUserCartRef } from "../../firebase/firebase.utils";
import { selectCartItems } from "./cart.selectors";
import cartActionTypes from "./cart.types";
import {
fetchUserCartItemsFailure,
fetchUserCartItemsSuccess,
clearCart,
updateUserCartItemsFailure,
updateUserCartItemsSuccess,
} from "./cart.actions";
import { selectCurrentUser } from "../user/user.selectors";
import { mergeCartItems } from "./cart.utils";
export function* fetchUserCartItems({ payload }) {
const userAuth = payload;
try {
if (!userAuth) return;
const userId = userAuth.uid;
const userCartRef = yield call(getUserCartRef, userId);
const userCartSnapshot = yield userCartRef.get();
const cartItemsFromDB = userCartSnapshot.data().cartItems;
const cartItemsLocal = yield select(selectCartItems);
let cartItems;
if (cartItemsLocal.length > 0) {
cartItems = yield mergeCartItems(cartItemsFromDB, cartItemsLocal);
yield userCartRef.update({ cartItems });
} else {
cartItems = cartItemsFromDB;
}
yield put(fetchUserCartItemsSuccess(cartItems));
} catch (error) {
yield put(fetchUserCartItemsFailure(error));
}
}
export function* updateUserCartInDB() {
const currentUser = yield select(selectCurrentUser);
if (currentUser) {
try {
const userCartRef = yield call(getUserCartRef, currentUser.id);
const cartItems = yield select(selectCartItems);
yield userCartRef.update({ cartItems });
yield put(updateUserCartItemsSuccess());
} catch (error) {
yield put(updateUserCartItemsFailure(error));
}
}
}
export function* clearCartOnSignOut() {
yield put(clearCart());
}
export function* onFetchAuthStateSuccess() {
yield takeLatest(
userActionTypes.FETCH_AUTH_STATE_SUCCESS,
fetchUserCartItems
);
}
export function* onSignOutSuccess() {
yield takeLatest(userActionTypes.SIGN_OUT_SUCCESS, clearCartOnSignOut);
}
export function* onCartChange() {
yield takeLatest(
[
cartActionTypes.ADD_ITEM_TO_CART,
cartActionTypes.REMOVE_ITEM_FROM_CART,
cartActionTypes.CLEAR_ITEM_FROM_CART,
cartActionTypes.CLEAR_CART,
],
updateUserCartInDB
);
}
export function* cartSagas() {
yield all([onFetchAuthStateSuccess(), onCartChange(), onSignOutSuccess()]);
}
<file_sep>import React, { useEffect, useCallback, useState, useRef } from "react";
import styles from "./fixed-header-wrapper.module.scss";
import { connect } from "react-redux";
import { selectIsHeaderVisible } from "../../redux/fixed-header-wrapper/fixed-header-wrapper.selectors";
import { createStructuredSelector } from "reselect";
import {
showHeader,
hideHeader,
} from "../../redux/fixed-header-wrapper/fixed-header-wrapper.actions";
function FixedHeaderWrapper({
children,
isHeaderVisible,
showHeader,
hideHeader,
}) {
const headerElement = useRef();
const [pageOffset, setPageOffset] = useState(0);
const [headerHeight, setHeaderHeight] = useState(0);
const DOWN_DIRECTION = 1;
const UP_DIRECTION = 2;
const [currentDirection, setCurrentDirection] = useState(DOWN_DIRECTION);
const handleScroll = useCallback(() => {
const currentPageOffset = window.pageYOffset;
let newDirection = currentDirection;
const isGoingDown = currentPageOffset > pageOffset;
if (isGoingDown) {
pageOffset > headerHeight && hideHeader();
if (currentDirection === UP_DIRECTION) newDirection = DOWN_DIRECTION;
} else {
showHeader();
if (currentDirection === DOWN_DIRECTION) newDirection = UP_DIRECTION;
}
setCurrentDirection(newDirection);
setPageOffset(currentPageOffset);
}, [currentDirection, headerHeight, hideHeader, pageOffset, showHeader]);
const handleResize = useCallback(() => {
if (headerHeight !== headerElement.current.clientHeight)
setHeaderHeight(headerElement.current.clientHeight);
}, [headerHeight]);
useEffect(() => {
document.addEventListener("scroll", handleScroll);
return () => {
document.removeEventListener("scroll", handleScroll);
};
}, [handleScroll]);
useEffect(() => {
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, [handleResize]);
useEffect(() => {
setPageOffset(window.pageYOffset);
setHeaderHeight(headerElement.current.clientHeight);
}, []);
useEffect(() => {
document.body.style.paddingTop = `${headerHeight}px`;
}, [headerHeight]);
return (
<div
ref={headerElement}
className={`${styles.header} ${
isHeaderVisible ? styles.visible : styles.invisible
}`}
>
{children}
</div>
);
}
const mapStateToProps = createStructuredSelector({
isHeaderVisible: selectIsHeaderVisible,
});
const mapDispatchToProps = (dispatch) => ({
showHeader: () => dispatch(showHeader()),
hideHeader: () => dispatch(hideHeader()),
});
export default connect(mapStateToProps, mapDispatchToProps)(FixedHeaderWrapper);
<file_sep>import { firebaseError } from "../../firebase/firebase.utils";
export const isEmpty = (value) => {
return value.trim() === "";
};
export const isLengthLessThan = (value, min) => {
return value.length < min;
};
export const isEmailCorrect = (value) => {
const emailRegex = RegExp(
/^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/
);
return emailRegex.test(value);
};
export const validationErrorMessages = {
REQUIRED: "Обязательно для заполнения",
INVALID_EMAIL: "Некорректный email адрес",
PASSWORD_DOESNT_MATCH: "Пароли должны совпадать",
MIN_CHARACTERS_COUNT: "Минимальное кол-во символов:",
};
export const getFirebaseErrorMessageByCode = (errorCode) => {
const { userDoesntExists, wrongPassword, userAlreadyExists } = firebaseError;
switch (errorCode) {
case userDoesntExists.code:
return userDoesntExists.message;
case wrongPassword.code:
return wrongPassword.message;
case userAlreadyExists.code:
return userAlreadyExists.message;
default:
return "";
}
};
<file_sep>import cartActionTypes from "./cart.types";
import { addItem, removeItem, clearItem } from "./cart.utils";
const initialState = {
cartItems: [],
isDropdownVisible: false,
error: null,
};
const cartReducer = (state = initialState, { type, payload }) => {
switch (type) {
case cartActionTypes.ADD_ITEM_TO_CART:
return { ...state, cartItems: addItem(state.cartItems, payload) };
case cartActionTypes.REMOVE_ITEM_FROM_CART:
return { ...state, cartItems: removeItem(state.cartItems, payload) };
case cartActionTypes.CLEAR_ITEM_FROM_CART:
return { ...state, cartItems: clearItem(state.cartItems, payload) };
case cartActionTypes.TOGGLE_CART_DROPDOWN_VISIBILITY:
return { ...state, isDropdownVisible: !state.isDropdownVisible };
case cartActionTypes.HIDE_CART_DROPDOWN:
return { ...state, isDropdownVisible: false };
case cartActionTypes.FETCH_USER_CART_ITEMS_SUCCESS:
return { ...state, cartItems: payload, error: null };
case cartActionTypes.UPDATE_USER_CART_ITEMS_SUCCESS:
return { ...state, error: null };
case cartActionTypes.FETCH_USER_CART_ITEMS_FAILURE:
case cartActionTypes.UPDATE_USER_CART_ITEMS_FAILURE:
return { ...state, error: payload };
case cartActionTypes.CLEAR_CART:
return { ...state, cartItems: [] };
default:
return state;
}
};
export default cartReducer;
<file_sep>import { createSelector } from "reselect";
export const selectSearch = (state) => state.search;
export const selectIsSearchFieldVisible = createSelector(
[selectSearch],
(search) => search.isSearchFieldVisible
);
export const selectIsSearchDropdownVisible = createSelector(
[selectSearch],
(search) => search.isSearchDropdownVisible
);
export const selectIsSearchModalVisible = createSelector(
[selectSearch],
(search) => search.isSearchModalVisible
);
export const selectCurrenListItemIndex = createSelector(
[selectSearch],
(search) => search.currenListItemIndex
);
export const selectSearchQuery = createSelector(
[selectSearch],
(search) => search.searchQuery
);
<file_sep>import { createSelector } from "reselect";
export const selectFilter = (state) => state.filter;
export const selectGameTime = createSelector(
[selectFilter],
(filter) => filter.gameTime
);
export const selectPlayersCount = createSelector(
[selectFilter],
(filter) => filter.playersCount
);
export const selectIsInStock = createSelector(
[selectFilter],
(filter) => filter.isInStock
);
export const selectShowFilter = createSelector(
[selectFilter],
(filter) => filter.showFilter
);
export const selectPriceValues = createSelector(
[selectFilter],
(filter) => filter.priceValues
);
export const selectDebouncedPriceValues = createSelector(
[selectFilter],
(filter) => filter.debouncedPriceValues
);
export const selectItemsFound = createSelector(
[selectFilter],
(filter) => filter.itemsFound
);
export const selectPriceLimits = createSelector(
[selectFilter],
(filter) => filter.priceLimits
);
export const selectNeedResetPriceLimits = createSelector(
[selectFilter],
(filter) => filter.needResetPriceLimits
);
<file_sep>import filterActionTypes from "./filter.types";
export const resetFilter = () => ({
type: filterActionTypes.RESET_FILTER,
});
export const setGameTime = (gameTime) => ({
type: filterActionTypes.SET_GAME_TIME,
payload: gameTime,
});
export const setPlayersCount = (playersCount) => ({
type: filterActionTypes.SET_PLAYERS_COUNT,
payload: playersCount,
});
export const toggleIsInStock = () => ({
type: filterActionTypes.TOGGLE_IS_IN_STOCK,
});
export const setPriceValues = (priceValues) => ({
type: filterActionTypes.SET_PRICE_VALUES,
payload: priceValues,
});
export const setDebouncedPriceValues = (debouncedPriceValues) => ({
type: filterActionTypes.SET_DEBOUNCED_PRICE_VALUES,
payload: debouncedPriceValues,
});
export const setShowFilter = (showFilter) => ({
type: filterActionTypes.SET_SHOW_FILTER,
payload: showFilter,
});
export const resetPriceLimits = (newPriceLimits) => ({
type: filterActionTypes.RESET_PRICE_LIMITS,
payload: newPriceLimits,
});
export const setItemsFound = (itemsFound) => ({
type: filterActionTypes.SET_ITEMS_FOUND,
payload: itemsFound,
});
<file_sep>import React, { useEffect } from "react";
import { connect } from "react-redux";
import { selectIsSidebarMenuVisible } from "../../redux/sidebar-menu/sidebar-menu.selectors";
import { createStructuredSelector } from "reselect";
import EscapeOutsideWrapper from "../escape-outside/escape-outside-wrapper.component";
import { hideSidebarMenu } from "../../redux/sidebar-menu/sidebar-menu.actions";
import { Link } from "react-router-dom";
import styles from "./sidebar-menu.module.scss";
import {
selectBreakpoints,
selectCurrentViewportAlias,
} from "../../redux/breakpoints-provider/breakpoints-provider.selectors";
import { breakpointsDown } from "../breakpoints-provider/breakpoints-provider.utils";
import { CSSTransition } from "react-transition-group";
import uniqid from "uniqid";
import useHistoryChange from "../../custom-hooks/useHistoryChange";
import { selectMainMenuDirectory } from "../../redux/directories/directories.selectors";
function SidebarMenu({
isSidebarMenuVisible,
hideSidebarMenu,
mainMenuDirectory,
breakpoints,
currentViewportAlias,
}) {
useHistoryChange(() => {
hideSidebarMenu();
});
useEffect(() => {
if (
!breakpointsDown(breakpoints, breakpoints.md, currentViewportAlias) &&
isSidebarMenuVisible
)
hideSidebarMenu();
}, [
breakpoints,
currentViewportAlias,
hideSidebarMenu,
isSidebarMenuVisible,
]);
return (
<CSSTransition
in={isSidebarMenuVisible}
unmountOnExit
timeout={{
appear: 0,
enter: 0,
exit: 200,
}}
classNames={{
enter: styles.enter,
enterActive: styles.enterActive,
enterDone: styles.enterDone,
exit: styles.exit,
exitActive: styles.exitActive,
exitDone: styles.exitDone,
}}
onEntered={() => {
document.body.style.overflow = "hidden";
}}
onExiting={() => {
document.body.style.overflow = "visible";
}}
>
<div>
<div className={styles.modalOverlay}>
<EscapeOutsideWrapper
onEscapeOutside={hideSidebarMenu}
isNodeToEscapeVisible={isSidebarMenuVisible}
>
<div className={styles.modal}>
<div className={styles.closeBtnWrapper}>
<button className={styles.closeBtn} onClick={hideSidebarMenu}>
<span className={`material-icons ${styles.closeIcon}`}>
clear
</span>
</button>
</div>
{mainMenuDirectory.map(({ path, title }) => (
<div key={uniqid()} className={styles.menuItem}>
<Link to={`/${path}`}>{title}</Link>
</div>
))}
</div>
</EscapeOutsideWrapper>
</div>
</div>
</CSSTransition>
);
}
const mapStateToProps = createStructuredSelector({
isSidebarMenuVisible: selectIsSidebarMenuVisible,
mainMenuDirectory: selectMainMenuDirectory,
breakpoints: selectBreakpoints,
currentViewportAlias: selectCurrentViewportAlias,
});
const mapDispatchToProps = (dispatch) => ({
hideSidebarMenu: () => dispatch(hideSidebarMenu()),
});
export default connect(mapStateToProps, mapDispatchToProps)(SidebarMenu);
<file_sep>import React from "react";
import { connect } from "react-redux";
import { setCurrentPage } from "../../redux/pagination/pagination.actions";
import {
selectItemsPerPage,
selectVisiblePageCount,
selectCurrentPage,
selectItemsCount,
} from "../../redux/pagination/pagination.selectiors";
import range from "lodash.range";
import { createStructuredSelector } from "reselect";
import styles from "./pagination.module.scss";
import { animateScroll as scroll } from "react-scroll";
import uniqid from "uniqid";
function Pagination({
itemsPerPage,
visiblePagesCount,
currentPage,
setCurrentPage,
itemsCount,
}) {
const onPageChanged = (pageNumber) => {
setCurrentPage(pageNumber);
scroll.scrollToTop({
duration: 0,
});
};
const pagesCount = Math.ceil(itemsCount / itemsPerPage);
const hasInvisiblePages = pagesCount > visiblePagesCount;
let firstVisiblePage = 1;
let lastVisiblePage = pagesCount;
if (hasInvisiblePages) {
if (
currentPage >= Math.ceil(visiblePagesCount / 2) &&
currentPage <= pagesCount - Math.floor(visiblePagesCount / 2)
) {
firstVisiblePage = currentPage - Math.floor(visiblePagesCount / 2);
} else if (currentPage < Math.ceil(visiblePagesCount / 2)) {
firstVisiblePage = 1;
} else if (currentPage > pagesCount - Math.floor(visiblePagesCount / 2)) {
firstVisiblePage = pagesCount - (visiblePagesCount - 1);
}
lastVisiblePage = firstVisiblePage + visiblePagesCount - 1;
}
return (
pagesCount > 1 && (
<div className={styles.btnContainer}>
<button
className={`${styles.nonCountBtn} ${
hasInvisiblePages ? "" : "d-none"
}`}
onClick={() => {
onPageChanged(1);
}}
>
<span className="material-icons">first_page</span>
</button>
<button
onClick={() => {
if (currentPage - 1 > 0) {
onPageChanged(currentPage - 1);
}
}}
className={styles.nonCountBtn}
>
<span className="material-icons">chevron_left</span>
</button>
{range(firstVisiblePage, lastVisiblePage + 1).map((pageNumber) => (
<button
className={`${styles.pageBtn} ${
currentPage === pageNumber ? styles.pageBtnActive : ""
}`}
key={uniqid()}
onClick={() => {
onPageChanged(pageNumber);
}}
>
{pageNumber}
</button>
))}
<button
onClick={() => {
if (currentPage + 1 <= pagesCount) {
onPageChanged(currentPage + 1);
}
}}
className={styles.nonCountBtn}
>
<span className="material-icons">chevron_right</span>
</button>
<button
className={`${styles.nonCountBtn} ${
hasInvisiblePages ? "" : "d-none"
}`}
onClick={() => {
onPageChanged(pagesCount);
}}
>
<span className="material-icons">last_page</span>
</button>
</div>
)
);
}
const mapStateToProps = createStructuredSelector({
itemsPerPage: selectItemsPerPage,
visiblePagesCount: selectVisiblePageCount,
currentPage: selectCurrentPage,
itemsCount: selectItemsCount,
});
const mapDispatchToProps = (dispatch) => ({
setCurrentPage: (pageNumber) => dispatch(setCurrentPage(pageNumber)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Pagination);
<file_sep>import React, { useCallback, useEffect } from "react";
import styles from "./light-box.module.scss";
import uniqid from "uniqid";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
selectIsLightBoxVisible,
selectCurrentImageIndex,
} from "../../redux/light-box/light-box.selectors";
import {
hideLightBox,
increaseCurrentImageIndex,
decreaseCurrentImageIndex,
setCurrentImageIndex,
} from "../../redux/light-box/light-box.actions";
import { SwitchTransition, CSSTransition } from "react-transition-group";
import { useState } from "react";
function LightBox({
imageURLs,
isLightBoxVisible,
increaseCurrentImageIndex,
decreaseCurrentImageIndex,
setCurrentImageIndex,
currentImageIndex,
hideLightBox,
}) {
const [isMoving, setIsMoving] = useState(false);
const [initialTouchPosition, setInitialTouchPosition] = useState(null);
const circleForward = useCallback(() => {
if (currentImageIndex < imageURLs.length - 1) {
increaseCurrentImageIndex();
} else {
setCurrentImageIndex(0);
}
}, [
currentImageIndex,
imageURLs.length,
increaseCurrentImageIndex,
setCurrentImageIndex,
]);
const circleBackward = useCallback(() => {
if (currentImageIndex > 0) {
decreaseCurrentImageIndex();
} else {
setCurrentImageIndex(imageURLs.length - 1);
}
}, [
currentImageIndex,
decreaseCurrentImageIndex,
imageURLs.length,
setCurrentImageIndex,
]);
const handleKeyDown = useCallback(
(e) => {
switch (e.keyCode) {
case 37: // LEFT arrow
case 40: // DOWN arrow
if (imageURLs.length > 0) {
e.preventDefault();
circleBackward();
}
break;
case 39: // RIGHT arrow
case 38: // UP arrow
if (imageURLs.length > 0) {
e.preventDefault();
circleForward();
}
break;
case 27: // ESC
hideLightBox();
break;
default:
break;
}
},
[circleBackward, circleForward, hideLightBox, imageURLs.length]
);
const handleThumbnailClick = (e) => {
const newIndex = parseInt(e.currentTarget.dataset.id);
if (newIndex !== currentImageIndex) setCurrentImageIndex(newIndex);
};
useEffect(() => {
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [handleKeyDown]);
const nodesToIgnoreEscaping = [];
const addNodeToIgnoreEscaping = (node) => {
node && nodesToIgnoreEscaping.push(node);
};
const handleClick = useCallback(
(e) => {
if (
!nodesToIgnoreEscaping.some((node) => node.contains(e.target)) &&
!isMoving
) {
hideLightBox();
}
setIsMoving(false);
},
[hideLightBox, isMoving, nodesToIgnoreEscaping]
);
const handleTouchMove = useCallback(
(e) => {
if (!isMoving) {
setIsMoving(true);
const touchX = e.changedTouches[0].pageX;
let diff = initialTouchPosition - touchX;
if (diff > 0) {
circleBackward();
} else {
circleForward();
}
}
},
[circleBackward, circleForward, initialTouchPosition, isMoving]
);
const handleTouchStart = useCallback((e) => {
const touchX = e.changedTouches[0].pageX;
setInitialTouchPosition(touchX);
}, []);
useEffect(() => {
window.addEventListener("click", handleClick, true);
window.addEventListener("touchend", handleClick, true);
window.addEventListener("touchmove", handleTouchMove, true);
window.addEventListener("touchstart", handleTouchStart, true);
return () => {
window.removeEventListener("click", handleClick, true);
window.removeEventListener("touchend", handleClick, true);
window.removeEventListener("touchmove", handleTouchMove, true);
window.removeEventListener("touchstart", handleTouchStart, true);
};
}, [handleClick, handleTouchStart, handleTouchMove]);
return (
<CSSTransition
in={isLightBoxVisible}
unmountOnExit
timeout={{
appear: 0,
enter: 0,
exit: 200,
}}
appear
classNames={{
enterDone: styles.visible,
}}
onEntered={() => {
document.body.style.overflow = "hidden";
}}
onExiting={() => {
document.body.style.overflow = "visible";
}}
>
<div
className={styles.container}
onWheel={(e) => {
e.deltaY < 0 ? circleForward() : circleBackward();
}}
>
<SwitchTransition>
<CSSTransition
key={currentImageIndex}
timeout={{
appear: 0,
enter: 0,
exit: 200,
}}
appear
classNames={{
appearDone: styles.appearDone,
enterDone: styles.enterDone,
exit: styles.exit,
exitActive: styles.exitActive,
}}
>
<div className={styles.content}>
<div className={styles.currentImageContainer}>
<img
ref={addNodeToIgnoreEscaping}
src={imageURLs[currentImageIndex]}
height="450"
alt="board game"
data-id={currentImageIndex}
className={styles.currentImage}
/>
<button
className={styles.arrowLeft}
onClick={circleBackward}
ref={addNodeToIgnoreEscaping}
>
<span className="material-icons">arrow_back</span>
</button>
<button
className={styles.arrowRight}
onClick={circleForward}
ref={addNodeToIgnoreEscaping}
>
<span className="material-icons">arrow_forward</span>
</button>
</div>
<button
className={styles.closeBtn}
onClick={hideLightBox}
ref={addNodeToIgnoreEscaping}
>
<span className={`material-icons ${styles.closeIcon}`}>
clear
</span>
</button>
<div className={styles.thumbnailsContainer}>
{imageURLs.map((url, index) => (
<div
onClick={handleThumbnailClick}
data-id={index}
key={uniqid()}
ref={addNodeToIgnoreEscaping}
className={`${styles.thumbnail} ${
currentImageIndex === index ? styles.thumbnailActive : ""
}`}
style={{
backgroundImage: `url(${url})`,
}}
></div>
))}
</div>
</div>
</CSSTransition>
</SwitchTransition>
</div>
</CSSTransition>
);
}
const mapStateToProps = createStructuredSelector({
isLightBoxVisible: selectIsLightBoxVisible,
currentImageIndex: selectCurrentImageIndex,
});
const mapDispatchToProps = (dispatch) => ({
hideLightBox: () => dispatch(hideLightBox()),
increaseCurrentImageIndex: () => dispatch(increaseCurrentImageIndex()),
decreaseCurrentImageIndex: () => dispatch(decreaseCurrentImageIndex()),
setCurrentImageIndex: (newIndex) => dispatch(setCurrentImageIndex(newIndex)),
});
export default connect(mapStateToProps, mapDispatchToProps)(LightBox);
<file_sep>import shopActionTypes from "./shop.types";
export const fetchCollectionStart = () => ({
type: shopActionTypes.FETCH_COLLECTION_START,
});
export const fetchCollectionSuccess = (collection) => ({
type: shopActionTypes.FETCH_COLLECTION_SUCCESS,
payload: collection,
});
export const fetchCollectionFailure = (error) => ({
type: shopActionTypes.FETCH_COLLECTION_FAILURE,
payload: error,
});
<file_sep>import React from "react";
import { useEffect } from "react";
import styles from "./alert.module.scss";
import { alertTypes } from "./alert.utils";
import { Element, scroller } from "react-scroll";
function Alert({ alertMessage, type = alertTypes.ERROR }) {
let alertStyle;
const scrollToName = "alert";
const show = !!alertMessage;
useEffect(() => {
if (show) {
scroller.scrollTo(scrollToName, {
duration: 0,
offset: -150,
});
}
}, [show]);
switch (type) {
case alertTypes.ERROR:
alertStyle = styles.errorMessage;
break;
default:
break;
}
return (
show && (
<Element name={scrollToName} className={alertStyle}>
{alertMessage}
</Element>
)
);
}
export default Alert;
<file_sep>import React, { useEffect } from "react";
import { withRouter } from "react-router-dom";
import CollectionPage from "./collection-page.component";
import { findCollectionItems } from "../../components/search/search.utils";
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selectors";
import { setShowFilter } from "../../redux/filter/filter.actions";
import { createStructuredSelector } from "reselect";
function CollectionPageSearchContainer({
location,
collection,
setShowFilter,
...otherProps
}) {
const searchQuery = decodeURI(location.search.split("=")[1]);
let newCollection = findCollectionItems(collection, searchQuery);
useEffect(() => {
setShowFilter(false);
});
return <CollectionPage collection={newCollection} {...otherProps} />;
}
const mapStateToProps = createStructuredSelector({
collection: selectCollection,
});
const mapDispatchToProps = (dispatch) => ({
setShowFilter: (showFilter) => dispatch(setShowFilter(showFilter)),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(withRouter(CollectionPageSearchContainer));
<file_sep>import React from "react";
import styles from "./form-input.module.scss";
function FormInput({ onChange, label, errorMessage = "", ...otherProps }) {
return (
<div className={styles.group}>
{label && <label className={styles.label}>{label}</label>}
<input
className={errorMessage ? styles.inputError : styles.input}
onChange={onChange}
{...otherProps}
/>
<div className={styles.errorMessage}>{errorMessage}</div>
</div>
);
}
export default FormInput;
<file_sep>import fixedHeaderWrapperActionTypes from "./fixed-header-wrapper.types";
const initialState = {
isHeaderVisible: true,
};
const fixedHeaderWrapperReducer = (state = initialState, { type, payload }) => {
switch (type) {
case fixedHeaderWrapperActionTypes.SHOW_HEADER:
return { ...state, isHeaderVisible: true };
case fixedHeaderWrapperActionTypes.HIDE_HEADER:
return { ...state, isHeaderVisible: false };
default:
return state;
}
};
export default fixedHeaderWrapperReducer;
<file_sep>import React from "react";
import { withRouter } from "react-router-dom";
import CollectionPage from "./collection-page.component";
import { selectCollection } from "../../redux/shop/shop.selectors";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { hasDiscount, isNew, isTop } from "../../redux/shop/shop.utils";
import PageNotFound from "../page-not-found/page-not-found.component";
function CollectionPageSelectionContainer({
match,
collection,
...otherProps
}) {
const selection = match.params.selectionId;
let newCollection = [];
switch (selection) {
case "top":
newCollection = collection.filter((item) =>
isTop(item.num_user_ratings, item.average_user_rating)
);
break;
case "new-games":
newCollection = collection.filter((item) => isNew(item.published));
break;
case "discounts":
newCollection = collection.filter((item) =>
hasDiscount(item.discount_pirce)
);
break;
default:
return <PageNotFound />;
}
return <CollectionPage collection={newCollection} {...otherProps} />;
}
const mapStateToProps = createStructuredSelector({
collection: selectCollection,
});
export default connect(mapStateToProps)(
withRouter(CollectionPageSelectionContainer)
);
<file_sep>import { getDiscountedPriceIfExist } from "../../redux/shop/shop.utils";
export const filterValues = {
gameTime: {
UNSET: "unset",
SHORT: "short",
MEDIUM: "medium",
LONG: "long",
VERY_LONG: "very_long",
DIFFERENT: "different",
},
playersCount: {
ALL: "all",
COUNT: 8,
MORE: "more",
},
};
export const filterGameTime = (collection, gameTime) => {
const { SHORT, MEDIUM, LONG, VERY_LONG, DIFFERENT } = filterValues.gameTime;
let filteredCollection = collection;
switch (gameTime) {
case SHORT:
filteredCollection = filteredCollection.filter((item) => {
const average = (item.max_playtime + item.min_playtime) / 2;
return average <= 45;
});
break;
case MEDIUM:
filteredCollection = filteredCollection.filter((item) => {
const average = (item.max_playtime + item.min_playtime) / 2;
return average > 45 && average <= 90;
});
break;
case LONG:
filteredCollection = filteredCollection.filter((item) => {
const average = (item.max_playtime + item.min_playtime) / 2;
return average > 90 && average <= 120;
});
break;
case VERY_LONG:
filteredCollection = filteredCollection.filter((item) => {
const average = (item.max_playtime + item.min_playtime) / 2;
return average > 120;
});
break;
case DIFFERENT:
filteredCollection = filteredCollection.filter(
(item) => item.max_playtime - item.min_playtime >= 30
);
break;
default:
break;
}
return filteredCollection;
};
export const filterPrice = (collection, priceValues) => {
let filteredCollection = collection.filter((item) => {
const ItemPrice = getDiscountedPriceIfExist(item);
return ItemPrice >= priceValues[0] && ItemPrice <= priceValues[1];
});
return filteredCollection;
};
export const filterPlayersCount = (collection, playersCount) => {
const { MORE } = filterValues.playersCount;
let filteredCollection = collection;
if (parseInt(playersCount)) {
filteredCollection = filteredCollection.filter(
(item) =>
item.max_players >= parseInt(playersCount) &&
parseInt(playersCount) >= item.min_players
);
} else if (playersCount === MORE) {
filteredCollection = filteredCollection.filter(
(item) => parseInt(playersCount) > item.max_players
);
}
return filteredCollection;
};
export const filterInStock = (collection, isInStock) => {
let filteredCollection = collection;
if (isInStock) {
filteredCollection = filteredCollection.filter(
(item) => item.inStockCount > 0
);
}
return filteredCollection;
};
<file_sep>import paginationActionTypes from "./pagination.types";
const initialState = {
itemsPerPage: 12,
currentPage: 1,
visiblePagesCount: 5,
paginatedCollection: [],
itemsCount: 0,
};
const paginationReducer = (state = initialState, { type, payload }) => {
switch (type) {
case paginationActionTypes.SET_CURRENT_PAGE:
return { ...state, currentPage: payload };
case paginationActionTypes.SET_PAGINATED_COLLECTION:
return { ...state, paginatedCollection: payload };
case paginationActionTypes.SET_ITEMS_COUNT:
return {
...state,
itemsCount: payload,
currentPage: initialState.currentPage,
};
default:
return state;
}
};
export default paginationReducer;
<file_sep>import lightBoxActionTypes from "./light-box.types";
const initialState = {
isLightBoxVisible: false,
currentImageIndex: 0,
};
const lightBoxReducer = (state = initialState, { type, payload }) => {
switch (type) {
case lightBoxActionTypes.HIDE_LIGHT_BOX:
return { ...state, isLightBoxVisible: false };
case lightBoxActionTypes.SHOW_LIGHT_BOX:
return { ...state, isLightBoxVisible: true };
case lightBoxActionTypes.INCREASE_CURRENT_IMAGE_INDEX:
return { ...state, currentImageIndex: state.currentImageIndex + 1 };
case lightBoxActionTypes.DECREASE_CURRENT_IMAGE_INDEX:
return { ...state, currentImageIndex: state.currentImageIndex - 1 };
case lightBoxActionTypes.SET_CURRENT_IMAGE_INDEX:
return { ...state, currentImageIndex: payload };
default:
return state;
}
};
export default lightBoxReducer;
<file_sep>import React from "react";
import styles from "./quantity-selector.module.scss";
function QuantitySelector({ handleAdd, handleRemove, quantity }) {
return (
<div className={styles.container}>
<button onClick={handleRemove} className={styles.btn}>
<span className="material-icons">remove</span>
</button>
<div className={styles.count}>{quantity}</div>
<button onClick={handleAdd} className={styles.btn}>
<span className="material-icons">add</span>
</button>
</div>
);
}
export default QuantitySelector;
<file_sep>import { createSelector } from "reselect";
import { getDiscountedPriceIfExist, hasDiscount } from "../shop/shop.utils";
export const selectCart = (state) => state.cart;
export const selectCartItems = createSelector(
[selectCart],
(cart) => cart.cartItems
);
export const selectCartItemsCount = createSelector(
[selectCartItems],
(cartItems) => cartItems.reduce((acc, item) => acc + item.quantity, 0)
);
export const selectCartItemsOverallDiscount = createSelector(
[selectCartItems],
(cartItems) =>
cartItems.reduce(
(acc, item) =>
acc +
(hasDiscount(item.discount_pirce)
? (item.price - item.discount_pirce) * item.quantity
: 0),
0
)
);
export const selectCartItemsTotal = createSelector(
[selectCartItems],
(cartItems) =>
cartItems.reduce((acc, item) => acc + item.price * item.quantity, 0)
);
export const selectCartItemsTotalWithDiscount = createSelector(
[selectCartItems],
(cartItems) =>
cartItems.reduce(
(acc, item) => acc + getDiscountedPriceIfExist(item) * item.quantity,
0
)
);
export const selectIsCartDropdownVisible = createSelector(
[selectCart],
(cart) => cart.isDropdownVisible
);
export const selectIsItemInCart = (itemToFind) =>
createSelector(
[selectCartItems],
(cartItems) => !!cartItems.find((item) => item.id === itemToFind.id)
);
<file_sep>import searchActionTypes from "./search.types";
const initialState = {
currenListItemIndex: -1,
searchQuery: "",
isSearchDropdownVisible: false,
isSearchFieldVisible: true,
isSearchModalVisible: false,
};
const searchReducer = (state = initialState, { type, payload }) => {
switch (type) {
case searchActionTypes.HIDE_SEARCH_FIELD:
return { ...state, isSearchFieldVisible: false };
case searchActionTypes.HIDE_SEARCH_DROPDOWN:
return {
...state,
isSearchDropdownVisible: false,
currenListItemIndex: initialState.currenListItemIndex,
};
case searchActionTypes.SHOW_SEARCH_DROPDOWN:
return { ...state, isSearchDropdownVisible: true };
case searchActionTypes.HIDE_SEARCH_MODAL:
return {
...state,
isSearchModalVisible: false,
};
case searchActionTypes.SHOW_SEARCH_MODAL:
return { ...state, isSearchModalVisible: true };
case searchActionTypes.TOGGLE_SEARCH_FIELD_VISIBILITY:
return { ...state, isSearchFieldVisible: !state.isSearchFieldVisible };
case searchActionTypes.SET_CURRENT_LIST_ITEM_INDEX:
return { ...state, currenListItemIndex: payload };
case searchActionTypes.INCREASE_CURRENT_LIST_ITEM_INDEX:
return {
...state,
currenListItemIndex: state.currenListItemIndex + 1,
};
case searchActionTypes.DECREASE_CURRENT_LIST_ITEM_INDEX:
return {
...state,
currenListItemIndex: state.currenListItemIndex - 1,
};
case searchActionTypes.RESET_CURRENT_LIST_ITEM_INDEX:
return {
...state,
currenListItemIndex: initialState.currenListItemIndex,
};
case searchActionTypes.SET_SEARCH_INPUT:
return {
...state,
searchQuery: payload,
currenListItemIndex: initialState.currenListItemIndex,
};
default:
return state;
}
};
export default searchReducer;
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import styles from "./button-custom.module.scss";
import { buttonStyleTypes } from "./button-custom.utils";
function ButtonCustom({
children,
to,
styleType,
outline,
fullWidth,
...otherProps
}) {
let buttonStyle;
switch (styleType) {
case buttonStyleTypes.MAIN:
buttonStyle = styles.main;
break;
case buttonStyleTypes.SECONDARY:
buttonStyle = styles.secondary;
break;
case buttonStyleTypes.DANGER:
buttonStyle = styles.danger;
break;
case buttonStyleTypes.DARK:
buttonStyle = styles.dark;
break;
case buttonStyleTypes.WHITE:
buttonStyle = styles.white;
break;
case buttonStyleTypes.GOOGLE:
buttonStyle = styles.google;
break;
default:
buttonStyle = styles.dark;
break;
}
if (outline) buttonStyle = `${buttonStyle} ${styles.outline}`;
if (fullWidth) buttonStyle = `${buttonStyle} ${styles.fullWidth}`;
if (to) {
return (
<Link to={to} className={buttonStyle} {...otherProps}>
{children}
</Link>
);
} else {
return (
<button className={buttonStyle} {...otherProps}>
{children}
</button>
);
}
}
export default ButtonCustom;
<file_sep>import { createSelector } from "reselect";
export const selectPagination = (state) => state.pagination;
export const selectCurrentPage = createSelector(
[selectPagination],
(pagination) => pagination.currentPage
);
export const selectItemsPerPage = createSelector(
[selectPagination],
(pagination) => pagination.itemsPerPage
);
export const selectVisiblePageCount = createSelector(
[selectPagination],
(pagination) => pagination.visiblePagesCount
);
export const selectPaginatedCollection = createSelector(
[selectPagination],
(pagination) => pagination.paginatedCollection
);
export const selectItemsCount = createSelector(
[selectPagination],
(pagination) => pagination.itemsCount
);
<file_sep>const favoritesActionTypes = {
TOGGLE_FAVORITE: "TOGGLE_FAVORITE",
CLEAR_FAVORITES: "CLEAR_FAVORITES",
FETCH_USER_FAVORITE_ITEMS_SUCCESS: "FETCH_USER_FAVORITE_ITEMS_SUCCESS",
FETCH_USER_FAVORITE_ITEMS_FAILURE: "FETCH_USER_FAVORITE_ITEMS_FAILURE",
UPDATE_USER_FAVORITE_ITEMS_SUCCESS: "UPDATE_USER_FAVORITE_ITEMS_SUCCESS",
UPDATE_USER_FAVORITE_ITEMS_FAILURE: "UPDATE_USER_FAVORITE_ITEMS_FAILURE",
};
export default favoritesActionTypes;
<file_sep>import userActionTypes from "./user.types";
export const setCurrentUser = (payload) => ({
type: userActionTypes.SET_CURRENT_USER,
payload,
});
export const signInWithGoogleStart = () => ({
type: userActionTypes.SIGN_IN_WITH_GOOGLE_START,
});
export const signInWithEmailStart = (emailAndPassword) => ({
type: userActionTypes.SIGN_IN_WITH_EMAIL_START,
payload: emailAndPassword,
});
export const signUpStart = (userCredentials) => ({
type: userActionTypes.SIGN_UP_START,
payload: userCredentials,
});
export const fetchAuthStateStart = () => ({
type: userActionTypes.FETCH_AUTH_STATE_START,
});
export const signUpSuccess = ({ userAuth, extraData }) => ({
type: userActionTypes.SIGN_UP_SUCCESS,
payload: { userAuth, extraData },
});
export const signUpFailure = (error) => ({
type: userActionTypes.SIGN_UP_FAILURE,
payload: error,
});
export const signInSuccess = () => ({
type: userActionTypes.SIGN_IN_SUCCESS,
});
export const signInFailure = (error) => ({
type: userActionTypes.SIGN_IN_FAILURE,
payload: error,
});
export const fetchCurrentUserSuccess = (currentUser) => ({
type: userActionTypes.FETCH_CURRENT_USER_SUCCESS,
payload: currentUser,
});
export const fetchCurrentUserFailure = (error) => ({
type: userActionTypes.FETCH_CURRENT_USER_FAILURE,
payload: error,
});
export const fetchAuthStateSuccess = (userAuth) => ({
type: userActionTypes.FETCH_AUTH_STATE_SUCCESS,
payload: userAuth,
});
export const fetchAuthStateFailure = (error) => ({
type: userActionTypes.FETCH_AUTH_STATE_FAILURE,
payload: error,
});
export const signOutStart = () => ({
type: userActionTypes.SIGN_OUT_START,
});
export const signOutSuccess = () => ({
type: userActionTypes.SIGN_OUT_SUCCESS,
});
export const signOutFailure = (error) => ({
type: userActionTypes.SIGN_OUT_FAILURE,
payload: error,
});
export const clearError = () => ({
type: userActionTypes.CLEAR_ERROR,
});
export const toggleUserDropdownVisibility = () => ({
type: userActionTypes.TOGGLE_USER_DROPDOWN_VISIBILITY,
});
export const hideUserDropdown = () => ({
type: userActionTypes.HIDE_USER_DROPDOWN,
});
<file_sep>export const buttonStyleTypes = {
MAIN: "MAIN",
SECONDARY: "SECONDARY",
DANGER: "DANGER",
DARK: "DARK",
WHITE: "WHITE",
GOOGLE: "GOOGLE",
};
<file_sep>import React from "react";
import Range from "rc-slider/lib/Range";
import "./rc-slider.theme.scss";
import { connect } from "react-redux";
import {
setDebouncedPriceValues,
setPriceValues,
} from "../../redux/filter/filter.actions";
import styles from "./multiple-range.module.scss";
import {
selectPriceValues,
selectPriceLimits,
} from "../../redux/filter/filter.selectors";
import { createStructuredSelector } from "reselect";
function MultipleRange({
priceValues,
priceLimits,
step,
setPriceValues,
setDebouncedPriceValues,
}) {
const [minPrice, maxPrice] = priceLimits;
const needDisable = minPrice === maxPrice;
const UNDEFINED_CHAR = "--";
return (
<>
<div className={styles.priceContainer}>
<div className={styles.minPrice}>
{needDisable
? UNDEFINED_CHAR
: new Intl.NumberFormat("ru-RU").format(priceValues[0])}
</div>
<span className={styles.priceDivider}>-</span>
<div className={styles.maxPrice}>
{needDisable
? UNDEFINED_CHAR
: new Intl.NumberFormat("ru-RU").format(priceValues[1])}
</div>
</div>
{needDisable ? (
<Range value={[0, 1]} min={0} max={1} disabled />
) : (
<Range
allowCross={false}
value={priceValues}
min={minPrice}
max={maxPrice}
step={step ? step : "1"}
onChange={(newPrices) => {
setPriceValues(newPrices);
}}
onAfterChange={(newPrices) => {
setDebouncedPriceValues(newPrices);
}}
/>
)}
</>
);
}
const mapStateToProps = createStructuredSelector({
priceValues: selectPriceValues,
priceLimits: selectPriceLimits,
});
const mapDispatchToProps = (dispatch) => ({
setPriceValues: (newPrices) => dispatch(setPriceValues(newPrices)),
setDebouncedPriceValues: (newPrices) =>
dispatch(setDebouncedPriceValues(newPrices)),
});
export default connect(mapStateToProps, mapDispatchToProps)(MultipleRange);
<file_sep>import React from "react";
import { selectIsCollectionLoaded } from "../../redux/shop/shop.selectors";
import { createStructuredSelector } from "reselect";
import { connect } from "react-redux";
import Spinner from "./spinner.component";
const withSpinner = (WrappedComponent) => {
const WithSpinnerComponent = ({ isLoading, ...otherProps }) => {
return (
<>{isLoading ? <Spinner /> : <WrappedComponent {...otherProps} />}</>
);
};
return connect(mapStateToProps)(WithSpinnerComponent);
};
const mapStateToProps = createStructuredSelector({
isLoading: (state) => !selectIsCollectionLoaded(state),
});
export default withSpinner;
<file_sep>import { createSelector } from "reselect";
export const selectBreakpointsProvider = (state) => state.breakpointsProvider;
export const selectCurrentViewportAlias = createSelector(
[selectBreakpointsProvider],
(breakpointsProvider) => breakpointsProvider.currentViewportAlias
);
export const selectBreakpoints = createSelector(
[selectBreakpointsProvider],
(breakpointsProvider) => breakpointsProvider.breakpoints
);
<file_sep>import React from "react";
import { sortTypeValues } from "./sorting.utils";
import { connect } from "react-redux";
import { selectItemsToSortCount } from "../../redux/sorting/sorting.selectors";
import { setSortType } from "../../redux/sorting/sorting.actions";
import { createStructuredSelector } from "reselect";
import styles from "./sorting.module.scss";
import OptionSelector from "../option-selector/option-selector.component";
function Sorting({ setSortType, itemsToSortCount }) {
const {
POPULAR,
NAME_ASC,
NAME_DESC,
PRICE_ASC,
PRICE_DESC,
} = sortTypeValues;
return (
itemsToSortCount > 0 && (
<div className={styles.container}>
<span className={styles.title}>Сортировать по:</span>
<OptionSelector
options={[
{ value: POPULAR, text: "Популярности" },
{ value: PRICE_DESC, text: "Цене \u2193" },
{ value: PRICE_ASC, text: "Цене \u2191" },
{ value: NAME_DESC, text: "Названию \u2193" },
{ value: NAME_ASC, text: "Названию \u2191" },
]}
onChange={(value) => setSortType(value)}
disabled={itemsToSortCount <= 1}
/>
</div>
)
);
}
const mapStateToProps = createStructuredSelector({
itemsToSortCount: selectItemsToSortCount,
});
const mapDispatchToProps = (dispatch) => ({
setSortType: (sortType) => dispatch(setSortType(sortType)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Sorting);
<file_sep>import filterActionTypes from "./filter.types";
import { filterValues } from "../../components/filter/filter.utils";
const initialState = {
debouncedPriceValues: [0, 0],
priceValues: [0, 0],
priceLimits: [0, 0],
gameTime: filterValues.gameTime.UNSET,
playersCount: filterValues.playersCount.ALL,
isInStock: true,
showFilter: true,
needResetPriceLimits: true,
itemsFound: 0,
};
const filterReducer = (state = initialState, { type, payload }) => {
switch (type) {
case filterActionTypes.RESET_FILTER:
return initialState;
case filterActionTypes.SET_DEBOUNCED_PRICE_VALUES:
return { ...state, debouncedPriceValues: payload };
case filterActionTypes.SET_PRICE_VALUES:
return { ...state, priceValues: payload };
case filterActionTypes.RESET_PRICE_LIMITS:
return {
...state,
needResetPriceLimits: false,
debouncedPriceValues: payload,
priceValues: payload,
priceLimits: payload,
};
case filterActionTypes.SET_GAME_TIME:
return { ...state, gameTime: payload, needResetPriceLimits: true };
case filterActionTypes.SET_SHOW_FILTER:
return { ...state, showFilter: payload };
case filterActionTypes.TOGGLE_IS_IN_STOCK:
return {
...state,
isInStock: !state.isInStock,
needResetPriceLimits: true,
};
case filterActionTypes.SET_PLAYERS_COUNT:
return { ...state, playersCount: payload, needResetPriceLimits: true };
case filterActionTypes.SET_ITEMS_FOUND:
return { ...state, itemsFound: payload };
default:
return state;
}
};
export default filterReducer;
<file_sep>import React, { useEffect, useCallback } from "react";
import {
filterInStock,
filterGameTime,
filterPlayersCount,
filterPrice,
} from "./filter.utils";
import { connect } from "react-redux";
import intersectionBy from "lodash.intersectionby";
import {
selectGameTime,
selectIsInStock,
selectPlayersCount,
selectDebouncedPriceValues,
selectNeedResetPriceLimits,
selectShowFilter,
} from "../../redux/filter/filter.selectors";
import {
resetPriceLimits,
setShowFilter,
setItemsFound,
} from "../../redux/filter/filter.actions";
import { getDiscountedPriceIfExist } from "../../redux/shop/shop.utils";
import { createStructuredSelector } from "reselect";
const withFilter = (WrappedComponent) => {
const WithFilterComponent = ({
collection,
isInStock,
gameTime,
playersCount,
needResetPriceLimits,
debouncedPriceValues,
resetPriceLimits,
resetFilter,
showFilter,
setShowFilter,
setItemsFound,
...otherProps
}) => {
const applyFilter = useCallback(() => {
let filteredCollection;
filteredCollection = intersectionBy(
filterInStock(collection, isInStock),
filterGameTime(collection, gameTime),
filterPlayersCount(collection, playersCount),
"id"
);
if (!needResetPriceLimits) {
filteredCollection = intersectionBy(
filterPrice(collection, debouncedPriceValues),
filteredCollection,
"id"
);
}
return filteredCollection;
}, [
collection,
debouncedPriceValues,
gameTime,
isInStock,
needResetPriceLimits,
playersCount,
]);
const filteredCollection = showFilter ? applyFilter() : collection;
useEffect(() => {
if (needResetPriceLimits) {
let newMin;
let newMax;
if (filteredCollection.length > 0) {
newMin = Math.min(
...filteredCollection.map((item) => getDiscountedPriceIfExist(item))
);
newMax = Math.max(
...filteredCollection.map((item) => getDiscountedPriceIfExist(item))
);
} else {
newMin = 0;
newMax = 0;
}
resetPriceLimits([newMin, newMax]);
}
}, [filteredCollection, needResetPriceLimits, resetPriceLimits]);
useEffect(() => {
setShowFilter(!!collection.length);
}, [collection.length, setShowFilter]);
useEffect(() => {
setItemsFound(filteredCollection.length);
});
return (
<WrappedComponent
collection={filteredCollection}
showFilter={showFilter}
{...otherProps}
/>
);
};
return connect(mapStateToProps, mapDispatchToProps)(WithFilterComponent);
};
const mapStateToProps = createStructuredSelector({
gameTime: selectGameTime,
isInStock: selectIsInStock,
playersCount: selectPlayersCount,
debouncedPriceValues: selectDebouncedPriceValues,
needResetPriceLimits: selectNeedResetPriceLimits,
showFilter: selectShowFilter,
});
const mapDispatchToProps = (dispatch) => ({
resetPriceLimits: (newPriceLimits) =>
dispatch(resetPriceLimits(newPriceLimits)),
setShowFilter: (showFilter) => dispatch(setShowFilter(showFilter)),
setItemsFound: (itemsFound) => dispatch(setItemsFound(itemsFound)),
});
export default withFilter;
<file_sep>import { all, call, put, select, takeLatest } from "redux-saga/effects";
import userActionTypes from "../user/user.types";
import { selectCurrentUser } from "../user/user.selectors";
import { selectFavoriteItems } from "./favorites.selectors";
import { getUserFavoritesRef } from "../../firebase/firebase.utils";
import {
clearFavorites,
fetchUserFavoriteItemsFailure,
fetchUserFavoriteItemsSuccess,
updateUserFavoriteItemsFailure,
updateUserFavoriteItemsSuccess,
} from "./favorites.actions";
import favoritesActionTypes from "./favorites.types";
import { mergeFavoriteItems } from "./favorites.utils";
export function* fetchUserFavoriteItems({ payload }) {
const userAuth = payload;
try {
if (!userAuth) return;
const userId = userAuth.uid;
const favoritesRef = yield call(getUserFavoritesRef, userId);
const favoritesSnapshot = yield favoritesRef.get();
const favoriteItemsFromDB = favoritesSnapshot.data().favoriteItems;
const favoriteItemsLocal = yield select(selectFavoriteItems);
let favoriteItems;
if (favoriteItemsLocal.length > 0) {
favoriteItems = yield mergeFavoriteItems(
favoriteItemsFromDB,
favoriteItemsLocal
);
yield favoritesRef.update({ favoriteItems });
} else {
favoriteItems = favoriteItemsFromDB;
}
yield put(fetchUserFavoriteItemsSuccess(favoriteItems));
} catch (error) {
yield put(fetchUserFavoriteItemsFailure(error));
}
}
export function* updateUserFavoritesInDB() {
const currentUser = yield select(selectCurrentUser);
if (currentUser) {
try {
const favoriteItemsRef = yield call(getUserFavoritesRef, currentUser.id);
const favoriteItems = yield select(selectFavoriteItems);
yield favoriteItemsRef.update({ favoriteItems });
yield put(updateUserFavoriteItemsSuccess());
} catch (error) {
yield put(updateUserFavoriteItemsFailure(error));
}
}
}
export function* clearFavoritesOnSignOut() {
yield put(clearFavorites());
}
export function* onSignInSuccess() {
yield takeLatest(
userActionTypes.FETCH_AUTH_STATE_SUCCESS,
fetchUserFavoriteItems
);
}
export function* onSignOutSuccess() {
yield takeLatest(userActionTypes.SIGN_OUT_SUCCESS, clearFavoritesOnSignOut);
}
export function* onFavoritesChange() {
yield takeLatest(
[
favoritesActionTypes.CLEAR_FAVORITES,
favoritesActionTypes.TOGGLE_FAVORITE,
],
updateUserFavoritesInDB
);
}
export function* favoritesSagas() {
yield all([onSignInSuccess(), onFavoritesChange(), onSignOutSuccess()]);
}
<file_sep>import React from "react";
import { Link, useLocation } from "react-router-dom";
import styles from "./breadcrumbs.module.scss";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectDirectoriesForBreadcrumbs } from "../../redux/directories/directories.selectors";
import uniqid from "uniqid";
function Breadcrumbs({ directories }) {
const location = useLocation();
const paths = location.pathname.split("/").filter((path) => path);
return (
<div className={styles.linkList}>
<div className={styles.nonActive}>
<Link to="/" className={styles.title}>
Главная
</Link>
</div>
{paths.map((path, index) => {
const isLast = index === paths.length - 1;
const currentPath = directories[path];
const to = `/${paths.slice(0, index + 1).join("/")}`;
if (currentPath) {
if (isLast) {
return (
<div key={uniqid()} className={styles.active}>
<span className={styles.title}>{currentPath.title}</span>
</div>
);
} else {
return (
<div className={styles.nonActive} key={uniqid()}>
<Link to={to} className={styles.title}>
{currentPath.title}
</Link>
</div>
);
}
}
return null;
})}
</div>
);
}
const mapStateToProps = createStructuredSelector({
directories: selectDirectoriesForBreadcrumbs,
});
export default connect(mapStateToProps)(Breadcrumbs);
<file_sep>export const currencyTypes = {
RUB: "RUB",
};
export const getDiscountedPriceIfExist = (item) => {
return hasDiscount(item.discount_pirce) ? item.discount_pirce : item.price;
};
export const getFormatedPrice = (currency, price) => {
switch (currency) {
case currencyTypes.RUB:
return new Intl.NumberFormat("ru-RU", {
style: "currency",
currency: `${currency}`,
minimumFractionDigits: 0,
}).format(price);
default:
break;
}
};
export const hasDiscount = (discountPrice) => {
return !!discountPrice;
};
export const isNew = (publishedString) => {
const [month, year] = publishedString.split("/");
const publishedDate = new Date(year, month);
// hardcoded the today date on purpose to always show "New" tags, in real project don't pass anything to the constructor
const today = new Date("2020", "06");
const dateToCompareFreshness = new Date(today);
dateToCompareFreshness.setMonth(today.getMonth() - 6);
const isNew = publishedDate >= dateToCompareFreshness;
return isNew;
};
export const isTop = (numUserRatings, averageUserRating) => {
const isTop = numUserRatings >= 100 && averageUserRating >= 4.5;
return isTop;
};
<file_sep>import React from "react";
import ReactDOM from "react-dom";
import "./globals/styles/index.scss";
import App from "./components/app/app";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { store } from "./redux/store";
import BreakpointsProviderBootstrapContainer from "./components/breakpoints-provider/breakpoints-provider-bootstrap.container";
import PersistManager from "./components/persist-manager/persist-manager.component";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<PersistManager>
<BreakpointsProviderBootstrapContainer>
<App />
</BreakpointsProviderBootstrapContainer>
</PersistManager>
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
<file_sep>import fixedHeaderWrapperActionTypes from "./fixed-header-wrapper.types";
export const showHeader = () => ({
type: fixedHeaderWrapperActionTypes.SHOW_HEADER,
});
export const hideHeader = () => ({
type: fixedHeaderWrapperActionTypes.HIDE_HEADER,
});
<file_sep>import React from "react";
import styles from "./empty-block.module.scss";
function EmptyBlock({ children }) {
return <div className={styles.container}>{children}</div>;
}
export default EmptyBlock;
<file_sep>import React, { useState } from "react";
import styles from "./favorite-icon.module.scss";
import { connect } from "react-redux";
import { toggleFavorite } from "../../redux/favorites/favorites.actions";
import { selectIsItemFavorite } from "../../redux/favorites/favorites.selectors";
function FavoriteIcon({ item, toggleFavorite, isItemFavorite }) {
const [isActive, setIsActive] = useState(false);
return (
<div
className={styles.container}
onMouseEnter={() => {
setIsActive(true);
}}
onMouseLeave={() => {
setIsActive(false);
}}
onClick={toggleFavorite.bind(null, item)}
>
<span className={`material-icons ${styles.fontIcon}`}>
{isActive || isItemFavorite ? "favorite" : "favorite_border"}
</span>
</div>
);
}
const mapStateToProps = (state, ownProps) => ({
isItemFavorite: selectIsItemFavorite(ownProps.item)(state),
});
const mapDispatchToProps = (dispatch) => ({
toggleFavorite: (item) => dispatch(toggleFavorite(item)),
});
export default connect(mapStateToProps, mapDispatchToProps)(FavoriteIcon);
<file_sep>import cartActionTypes from "./cart.types";
export const addItemToCart = (item) => ({
type: cartActionTypes.ADD_ITEM_TO_CART,
payload: item,
});
export const removeItemFromCart = (item) => ({
type: cartActionTypes.REMOVE_ITEM_FROM_CART,
payload: item,
});
export const clearItemFromCart = (item) => ({
type: cartActionTypes.CLEAR_ITEM_FROM_CART,
payload: item,
});
export const toggleCartDropdownVisibility = () => ({
type: cartActionTypes.TOGGLE_CART_DROPDOWN_VISIBILITY,
});
export const hideCartDropdown = () => ({
type: cartActionTypes.HIDE_CART_DROPDOWN,
});
export const clearCart = () => ({
type: cartActionTypes.CLEAR_CART,
});
export const fetchUserCartItemsSuccess = (cartItems) => ({
type: cartActionTypes.FETCH_USER_CART_ITEMS_SUCCESS,
payload: cartItems,
});
export const fetchUserCartItemsFailure = (error) => ({
type: cartActionTypes.FETCH_USER_CART_ITEMS_FAILURE,
payload: error,
});
export const updateUserCartItemsSuccess = () => ({
type: cartActionTypes.UPDATE_USER_CART_ITEMS_SUCCESS,
});
export const updateUserCartItemsFailure = (error) => ({
type: cartActionTypes.UPDATE_USER_CART_ITEMS_FAILURE,
payload: error,
});
<file_sep>import { createSelector } from "reselect";
export const selectSidebarMenu = (state) => state.sidebarMenu;
export const selectIsSidebarMenuVisible = createSelector(
[selectSidebarMenu],
(sidebarMenu) => sidebarMenu.isSidebarMenuVisible
);
<file_sep>import React from "react";
import { withRouter } from "react-router-dom";
import { selectCollection } from "../../redux/shop/shop.selectors";
import { connect } from "react-redux";
import CollectionPage from "./collection-page.component";
import { createStructuredSelector } from "reselect";
import PageNotFound from "../page-not-found/page-not-found.component";
import { selectCategoriesDirectory } from "../../redux/directories/directories.selectors";
function CollectionPageCategoryContainer({
match,
collection,
categoriesDirectory,
...otherProps
}) {
const category = match.params.categoryId;
let newCollection = [];
if (
categoriesDirectory
.map((directoryItem) => directoryItem.path)
.includes(category)
) {
newCollection = collection.filter((item) =>
item.categories.includes(category)
);
} else {
return <PageNotFound />;
}
return <CollectionPage collection={newCollection} {...otherProps} />;
}
const mapStateToProps = createStructuredSelector({
collection: selectCollection,
categoriesDirectory: selectCategoriesDirectory,
});
export default connect(mapStateToProps)(
withRouter(CollectionPageCategoryContainer)
);
<file_sep>import { useEffect } from "react";
import { useHistory } from "react-router-dom";
const useHistoryChange = (callback) => {
const history = useHistory();
useEffect(() => {
const unlisten = history.listen(callback);
return () => {
unlisten();
};
}, [callback, history]);
};
export default useHistoryChange;
<file_sep>const fixedHeaderWrapperActionTypes = {
SHOW_HEADER: "SHOW_HEADER",
HIDE_HEADER: "HIDE_HEADER",
};
export default fixedHeaderWrapperActionTypes;
<file_sep>import { takeLatest, take, put, cancelled, all } from "redux-saga/effects";
import shopActionTypes from "./shop.types";
import {
firestore,
convertSnapshotToProperCollection,
} from "../../firebase/firebase.utils";
import { fetchCollectionSuccess, fetchCollectionFailure } from "./shop.actions";
import { eventChannel } from "redux-saga";
export function* onFetchCollectionStart() {
yield takeLatest(shopActionTypes.FETCH_COLLECTION_START, fetchCollection);
}
export function* fetchCollection() {
const firestoreChannel = new eventChannel((emiter) => {
const collectionRef = firestore.collection("collection");
const unsubscribeFromSnapshot = collectionRef.onSnapshot(
(snapshot) => {
const collection = convertSnapshotToProperCollection(snapshot);
emiter({ data: collection });
},
(error) => {
emiter({ error });
}
);
return () => {
unsubscribeFromSnapshot();
};
});
try {
while (true) {
const { data, error } = yield take(firestoreChannel);
if (error) {
yield put(fetchCollectionFailure(error));
} else {
yield put(fetchCollectionSuccess(data));
}
}
} catch (error) {
yield put(fetchCollectionFailure(error));
} finally {
if (yield cancelled()) {
firestoreChannel.close();
}
}
}
export function* shopSagas() {
yield all([onFetchCollectionStart()]);
}
<file_sep>import userActionTypes from "./user.types";
const initialState = {
currentUser: null,
isAuthentificationChecked: false,
isCurrenUserAuthentificated: false,
isUserDropdownVisible: false,
error: null,
isLoading: false,
};
const userReducer = (state = initialState, { type, payload }) => {
switch (type) {
case userActionTypes.TOGGLE_USER_DROPDOWN_VISIBILITY:
return { ...state, isUserDropdownVisible: !state.isUserDropdownVisible };
case userActionTypes.HIDE_USER_DROPDOWN:
return { ...state, isUserDropdownVisible: false };
case userActionTypes.CLEAR_ERROR:
return { ...state, error: null };
case userActionTypes.SIGN_UP_START:
case userActionTypes.SIGN_IN_WITH_EMAIL_START:
case userActionTypes.SIGN_IN_WITH_GOOGLE_START:
return { ...state, error: null, isLoading: true };
case userActionTypes.SIGN_OUT_START:
case userActionTypes.FETCH_AUTH_STATE_START:
return { ...state, error: null };
case userActionTypes.FETCH_CURRENT_USER_SUCCESS:
return { ...state, currentUser: payload };
case userActionTypes.FETCH_AUTH_STATE_SUCCESS:
return {
...state,
isAuthentificationChecked: true,
isCurrenUserAuthentificated: !!payload,
};
case userActionTypes.SIGN_OUT_SUCCESS:
return {
...state,
currentUser: null,
isCurrenUserAuthentificated: false,
};
case userActionTypes.SIGN_IN_SUCCESS:
return { ...state, isLoading: false };
case userActionTypes.SIGN_IN_FAILURE:
case userActionTypes.SIGN_UP_FAILURE:
return { ...state, error: payload, isLoading: false };
case userActionTypes.SIGN_OUT_FAILURE:
case userActionTypes.FETCH_CURRENT_USER_FAILURE:
case userActionTypes.FETCH_AUTH_STATE_FAILURE:
return { ...state, error: payload };
default:
return state;
}
};
export default userReducer;
|
7baba43c7a85dc0c298ca835cd982c64e3aa6410
|
[
"JavaScript",
"Markdown"
] | 75
|
JavaScript
|
Shramkoalexander/boardlord-boardgame-store
|
17a6497e7de5aa15d129c53ff217108e27e3fdb1
|
842732f9ee72a62774b690c522c2a2cb63a11f16
|
refs/heads/master
|
<repo_name>Castanha69/noSQL<file_sep>/Term_Frequency.py
import operator
import string
import pymongo
from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords
from nltk import bigrams
from collections import Counter
def process(text: object, tokenizer: object = TweetTokenizer(), stopwords: object = []):
#Process the text of a tweet:
#- Lowercase
#- Tokenize
#- Stopword removal
#- Digits removal
#Return: list of strings
text = text.lower()
tokens = tokenizer.tokenize(text)
return [tok for tok in tokens if tok not in stopwords and not tok.isdigit()]
if __name__ == '__main__':
tweet_tokenizer = TweetTokenizer()
punct = list(string.punctuation)
stopword_list = stopwords.words('portuguese') + punct + ['rt', 'via']
client = pymongo.MongoClient('localhost', 27017)
db = client.tweet_database
collection = db.tweet_collection
count_all = Counter()
tweets_iterator = collection.find()
for tweet in tweets_iterator:
# Create a list with all the terms
tokens = process(text=tweet.get('text', ''),
tokenizer=tweet_tokenizer,
stopwords=stopword_list)
terms_all = [term for term in tokens]
terms_bigram = bigrams(terms_all) #juntei dois tokens dos mesmos tweets, buscando mais sentido.
# Update the counter
count_all.update(terms_bigram)
print(count_all.most_common(300))
<file_sep>/Trabalho Prático.md
# Trabalho prático de Banco de Dados noSQL
## Coletar informações de redes sociais e armazenar no mínimo 1MM de dados.
### Extrair informações do tipo:
1. Termos mais frequentes:
2. Volume por dia:
3. Volume por hora do dia:
###[1] **termos mais frequentes:**
Escolhemos a rede social TWITTER como objeto de nosso trabalho, por já termos tido uma experiência inicial com a mesma em aula.
Para a captura dos dados, foi desenvolvido um código em Python para capturar tweets e em seguida armazená-los. Como efeito de estudo armazenamos estes dados em dois formatos: arquivo json e dentro do Banco de Dados MongoDB para que pudéssemos praticar os dois métodos.
Um segundo código foi gerado para acessar os dados armazenados e então fazer a identificação dos temos mais frequentes.
As linguagens utilizadas foram Python e Java Script, sendo que a segunda era necessária para trabalharmos os dados no MongoDB.
#### Acesso ao Twitter
Para termos acesso ao Twitter, tivemos que primeiramente criar uma conta e em seguida criar um aplicativo para então termos condições de escutarmos o que era "twitado" na internet. Para evitarmos os bloqueios que poderíamos sofrer, criamos dois aplicativos, de forma a burlar o "xerife" do Twitter. Assim, de tempos em tempos alterávamos o aplicativos que utilizávamos.
O primeiro aplicativo se chamava [**TweetyMining69**](https://apps.twitter.com/app/13191380).
O segundo aplicativo se chamava [**tweety mining**](https://apps.twitter.com/app/13170132/show)
#### Definição de Armazenamento
Conforme mencionado anteriormente utilizamos dois métodos distintos de armazenamento, sendo o primeiro um arquivo texto, com extensão json e o segundo um arquivo no banco de dados MongoDB.
Arquivo Json: with open("c:\\Users\\Marcelo\\Documents\\noSQL-twt.json",'a') as file:
MongoDB:
```python
client = pymongo.MongoClient('localhost', 27017)
db = client.tweet_database
collection = db.tweet_collection
```
O Armazenamento dos dados em ambos os ambientes é muito simples e fácil de fazer.
Armazenamos os dados no arquivo texto, em formato json, para que os dados já ficassem estruturados e assim pudéssemos depois trabalhar com os mesmos. No caso do MongoDB isto é mais simples, pois ele sozinho já arquiva os dados em formato Json.
Como é de se esperar nesta fase não há diferença, perceptível, de velocidade entre uma atividade e a outra.
O armazenamento no arquivo de texto é feito pelo comando: __file.write(testdata2)__ sendo testdata2 os dados do twitter capturado.
Já no caso do MongoDB, é feito pelo comando: __tweetind = collection.insert_one(testdata2).inserted_id__.
### PALAVRAS DE BUSCA
Para este trabalho prático escolhemos palavras de busca voltadas para o momento em que estamos vivendo - Natal, Fim de Ano, Festas.
Assim as palavras selecionadas foram:
```python
Words_to_Track = ['Natal','felicidade','amor','paz','alegria','árvore','família','união',
'champagne','luz','trenó','presentes','beijos','abraços','renas',
'papai noel','saco de presentes',
'bebedeira','festa de fim de ano','fim de ano','sexo','camisinha','suruba',
'ano novo', 'dinheiro']
```
Vemos que o range de palavras variam bastante indo de uma noção religiosa cristã à termos mais associados a festas pagãs. Com isto buscávamos abordar os diferentes grupos de indivíduos que se comunicaram durante o período.
### A COLETA E TRATAMENTO dos TWEETS
A coleta dos tweets é feita através do acesso ao Twitter, pela aplicação que foi criada inicialmente no twitter.
Quando criamos a aplicação no twitter chaves e tokens de acesso são criados para que apenas o dono da aplicação possa fazer uso da mesma.
Ex.:
ConsumerKey (API Key) -> rPQLXBYOnk3TbKgzX2Qe8TfJx
`Consumer Secret (API Secret) -> <KEY>`
Access Token -> <KEY>
`Access Token Secret -> <KEY>`
Assim temos de passar tokens e dados de acesso a aplicação para que nosso acesso seja liberado.
Isto é feito enviando via APIs ao Twitter os dados acima:
```python
consumer_Key = "rPQLXBYOnk3TbKgzX2Qe8TfJx"
consumer_Secret = "<KEY>"
access_Token = "<KEY>"
access_Secret = "<KEY>"
auth = OAuthHandler(consumer_Key, consumer_Secret)
auth.set_access_token(access_Token, access_Secret)
stream = Stream(auth, l)
```
Após isto podemos começar a coletar os twitters com o comando abaixo:
```python
stream.filter(track=Words_to_Track)
```
Através do comando stream.filter iremos coletar todos os twitters que contenham as palavras que definimos anteriormente. Um fato interessante é que dependendo da hora e das palavras a coleta será rápida ou lenta.
Um fato que observamos após as coletas é que forma coletados twitters de todas as linguas, que contivessem alguma das palavras de busca. Assim foram coletados twitters em português, inglês e espanhol. Isto irá afetar, mais a frente, o tratamento das frequências dos termos, pois teremos três idiomas.
#### Tratamento dos Twitters
Aproveitamos para já dar um tratamento aos twitters tão logo os capturássemos, atuando sobre o campo 'texto' que é a mensagem que é tuitada e já a dividindo em termos independentes e não mais como uma frase. Isto quer dizer, desconsideramos as pontuações e outros caracteres.
Fizemos isto com o intuito de ganhar tempo já que o nosso objetivo neste trabalho prático é determinar com que frequência alguns termos são utilizados.
Assim, tão logo capturavamos o twitter, já transformávamos o texto em TOKENS, ou melhor, uma lista de palavras. Isto era feito com o comando:
```python
tokens = process(text=tweet.get('text', ''),
tokenizer=tweet_tokenizer,
stopwords=stopword_list)
```
Para esta tarefa de transformar em TOKENS o texto utilizamos os pacotes NLTK, que é uma plataforma líder para construir programas em Python para trabalhar com dados de linguagem humana.
O código completo pode ser visto no arquivo Coleta_Tweets.py.
Para efeito de estudo, fizemos duas coletas distintas de twitters, sendo uma coletando e armazenando os twitters sem tratamento e a segunda com o texto já transformado em tokens. Assim foram criados no MongoDB duas coleções: **tweet_collection** e **tweet_coll_token** respectivamente.
### IDENTIFICAÇÃO DOS TERMOS MAIS FREQUENTES.
Para então tratarmos os twitters que foram coletados foram desenvolvidos dois códigos distintos, sendo um em Python e o segundo em Java Script, para rodar direto do MongoDB, ou seja, utilizando as "engines" do banco de dados.
#### 1. Código Python
Nesta fase, não mais precisamos acessar o Twitter, logo só acessamos o MongoDB:
```python
client = pymongo.MongoClient('localhost', 27017)
db = client.tweet_database
collection = db.tweet_collection
```
Como vê, estamos utilizando a coleção que contem o twitter puro, com seus campos intactos, por isto, fizemos a tokenização do texto na hora de contar os termos. Esta contagem é feita utilizando-se um contador, count_all = Counter().
Buscando um conhecimento melhor do sentido que as palavras teriam, utilizamos a função "bigrams" para contar dois tokens que aparecam juntos na mesma frase, desta forma conseguimos ter alguma idéia do que significado do twitter.
No código contamos os termos da sequinte forma:
```python
terms_all = [term for term in tokens]
terms_bigram = bigrams(terms_all) #juntei dois tokens dos mesmos tweets, buscando mais sentido.
# Update the counter
count_all.update(terms_bigram)
```
Por INCRÍVEL que pareça, o código em Python rodou com sucesso, porém demorou mais de uma hora para chegar ao fim.
O resultado desta análise foi a seguinte:
[(('el', 'amor'), 73273),
(('mi', 'amor'), 31323),
(('❤', '️'), 26471),
(('en', 'el'), 26029),
(('amor', 'y'), 18267),
(('amor', 'es'), 15639),
(('😂', '😂'), 13190),
(('un', 'amor'), 12408),
(('jesus', 'christ'), 12024),
(('amor', 'vida'), 11841),
(('amor', 'deus'), 11255)]
Um fato interessante a se notar aqui é que as palavras mais "pagans" ou de baixo calão, não aparecem entre as 10 primeiras. Logo, podemos inferir que as pessoas neste período em que estamos dão mais valor ao sentido religioso e a união de suas famílias.
O código deste processo pode ser encontrado em **Term_Frequency.py**
#### 2. Código Java Script - MongoDB
Em um segundo momento fizemos a contagem dos termos mais frequentes utilizando a própria "engine" do MongoDB, que nos dá muita performance.
Um ponto importante aqui: É necessário criar-se um ÍNDICE antes para que o MongoDB possa operar com performance.
Outro ponto importante é que o código que roda no MongoDB está em JAVA SCRIPT.
Assim primeiramente no Shell do MongoDB criamos o Índice:
```js
db.tweet_coll_token.createIndex({'text':1})
```
Para fazermos a identificação dos termos utilizamos então a função de mapReduce do MongoDB que permite identificar os termos e somá-los.
```js
var map = function() {
var text = this.text;
if (text) {
// quick lowercase to normalize per your requirements
// text = text.toLowerCase();
for (var i = text.length - 1; i >= 0; i--) {
if (text[i]) { // make sure there's something
emit(text[i], 1); // store a 1 for each word
}
}
}
};
var reduce = function( key, values ) {
var count = 0;
values.forEach(function(v) {
count +=v;
});
return count;
}
db.tweet_coll_token.mapReduce(map, reduce, {out: "word_count"})
db.word_count.find().sort({value:-1})
```
Como vêem utilizamos a collection tweet_coll_token pois ela já estava tratada e não continga pontuação e seus termos já estavam em forma de token.
O mesmo procedimento que demorou mais de uma hora para ser concluído no Python, dentro do MongoDB demorou **menos de 05 minutos**.
O resultado foi o seguinte:
```js
> db.word_count.find().limit(100).sort({'value':-1})
{ "_id" : "amor", "value" : 461860 }
{ "_id" : "deus", "value" : 193588 }
{ "_id" : "…", "value" : 177886 }
{ "_id" : "el", "value" : 161307 }
{ "_id" : "é", "value" : 146218 }
{ "_id" : "jesus", "value" : 131832 }
{ "_id" : "y", "value" : 123877 }
{ "_id" : "la", "value" : 90653 }
{ "_id" : "en", "value" : 84001 }
{ "_id" : "oi", "value" : 83701 }
{ "_id" : "...", "value" : 83104 }
{ "_id" : "es", "value" : 73122 }
{ "_id" : "mi", "value" : 70555 }
{ "_id" : "natal", "value" : 65515 }
{ "_id" : "to", "value" : 65463 }
{ "_id" : "pra", "value" : 63406 }
{ "_id" : "❤", "value" : 60484 }
{ "_id" : "the", "value" : 60424 }
{ "_id" : "q", "value" : 52856 }
{ "_id" : "vida", "value" : 51512 }
```
Infelizmente não consegui fazer a mesma análise de bigrams com o Js e MongoDB.
###[2] **VOLUME POR DIA:**
Para descobrirmos o volume de tweets por dia teríamos de trabalhar com as datas e horas em que os twitters foram postados. Isto apresenta um novo desafio, porém passível de solução.
A solução é similar a anterior, porém ao invés de termos similares, temos de encontrar dias similares.
Assim temos de trabalhar com o timestamp dos twitters.
Utilizando-se Python e a biblioteca PANDA esta tafefa fica muito fácil, pois a panda já traz muitos algorítmos prontos para executar este tipo de tarefa. No entanto, devido ao grande tamanho do arquivo, a tarefa não pode ser concluída utilizando-se este método, pois há consumo excessivo de memória e por fim estouro, causando a parada do processo.
A solução é trabalhar diretamente com o MongoDB que possui performance e engine para tal. Como temos de trabalhar com o tempo, temos de buscar os timestamps de cada twitter e somar os que são do mesmo dia. Isto pode ser feito com a função getTimestamp() e de novo utilizando-se a função mapReduce do MongoDB.
Utilizamos a coleção tweet_collection que contém os twitters completos e sem tratamento, já que o que estamos buscando é apenas o período em que o mesmo foi postado.
Novamente, é imprescindível criarmos um Índice, pois sem o mesmo teremos um problema com o mapReduce.
```js
var map = function() {
var datetime = this._id.getTimestamp();
var created_at_Day = new Date(datetime.getFullYear(),
datetime.getMonth(),
datetime.getDate());
emit(created_at_Day, {count: 1});
}
var reduce = function(key, values) {
var total = 0;
for(var i = 0; i < values.length; i++) { total += values[i].count; }
return {count: total};
}
db.tweet_collection.mapReduce( map, reduce, { "out": "tweet_perDay" } );
db.tweet_perDay.find().limit(10).sort({"_id":-1})
```
Para a minha grande surpresa, esta pesquisa tomou menos de 1 minuto, o que aponta o poder do MongoDB em executar estas tarefas de memória e CPU intensivas.
Segue o resultado:
```js
""" Resultado: """
> db.tweet_collection.mapReduce( map, reduce, { "out": "tweet_perDay" } );
{
"result" : "tweet_perDay",
"timeMillis" : 41389,
"counts" : {
"input" : 1294918,
"emit" : 1294918,
"reduce" : 12952,
"output" : 3
},
"ok" : 1
}
> db.tweet_perDay.find().limit(10).sort({"_id":-1})
{ "_id" : ISODate("2016-12-**12**T02:00:00Z"), "value" : { "count" : 586075 } }
{ "_id" : ISODate("2016-12-**11**T02:00:00Z"), "value" : { "count" : 687865 } }
{ "_id" : ISODate("2016-12-**10**T02:00:00Z"), "value" : { "count" : 20978 } }
```
Acredito que esta operação também possa ser conseguida com a função AGGREGATE, no entanto a Aggregate não tem a função de pegar o timestamp do twitter.
###[3] **VOLUME POR HORA:**
A solução é igual a anterior. Novamente utilizaremos a collection tweet_collection.
O Código e resultados estão apresentados abaixo:
```js
var map = function() {
var datetime = this._id.getTimestamp();
var created_at_hour = new Date(datetime.getFullYear(),
datetime.getMonth(),
datetime.getDate(),
datetime.getHours());
emit(created_at_hour, {count: 1});
}
var reduce = function(key, values) {
var total = 0;
for(var i = 0; i < values.length; i++) { total += values[i].count; }
return {count: total};
}
db.tweet_collection.mapReduce( map, reduce, { "out": "tweet_perHour" } );
db.tweet_perHour.find().limit(10).sort({"_id":-1})
```
#### Resultado:
```js
> db.tweet_collection.mapReduce( map, reduce, { "out": "tweet_perHour" } );
{
"result" : "tweet_perHour",
"timeMillis" : 22658,
"counts" : {
"input" : 1294918,
"emit" : 1294918,
"reduce" : 12976,
"output" : 27
},
"ok" : 1
> db.tweet_perHour.find().sort({"value":-1})
{ "_id" : ISODate("2016-12-12T02:00:00Z"), "value" : { "count" : 138047 } }
{ "_id" : ISODate("2016-12-12T03:00:00Z"), "value" : { "count" : 127166 } }
{ "_id" : ISODate("2016-12-11T02:00:00Z"), "value" : { "count" : 98605 } }
{ "_id" : ISODate("2016-12-12T04:00:00Z"), "value" : { "count" : 83084 } }
{ "_id" : ISODate("2016-12-11T19:00:00Z"), "value" : { "count" : 74931 } }
{ "_id" : ISODate("2016-12-11T18:00:00Z"), "value" : { "count" : 66356 } }
{ "_id" : ISODate("2016-12-11T21:00:00Z"), "value" : { "count" : 62524 } }
{ "_id" : ISODate("2016-12-11T20:00:00Z"), "value" : { "count" : 59585 } }
{ "_id" : ISODate("2016-12-11T17:00:00Z"), "value" : { "count" : 58072 } }
{ "_id" : ISODate("2016-12-11T14:00:00Z"), "value" : { "count" : 54621 } }
{ "_id" : ISODate("2016-12-12T05:00:00Z"), "value" : { "count" : 54373 } }
{ "_id" : ISODate("2016-12-12T00:00:00Z"), "value" : { "count" : 52339 } }
{ "_id" : ISODate("2016-12-11T04:00:00Z"), "value" : { "count" : 50691 } }
{ "_id" : ISODate("2016-12-12T10:00:00Z"), "value" : { "count" : 42768 } }
{ "_id" : ISODate("2016-12-11T03:00:00Z"), "value" : { "count" : 40784 } }
{ "_id" : ISODate("2016-12-12T06:00:00Z"), "value" : { "count" : 36294 } }
{ "_id" : ISODate("2016-12-12T09:00:00Z"), "value" : { "count" : 35908 } }
{ "_id" : ISODate("2016-12-11T10:00:00Z"), "value" : { "count" : 33995 } }
{ "_id" : ISODate("2016-12-12T08:00:00Z"), "value" : { "count" : 28108 } }
{ "_id" : ISODate("2016-12-12T07:00:00Z"), "value" : { "count" : 27482 } }
Type "it" for more
>
> it
{ "_id" : ISODate("2016-12-11T01:00:00Z"), "value" : { "count" : 20978 } }
{ "_id" : ISODate("2016-12-11T15:00:00Z"), "value" : { "count" : 19617 } }
{ "_id" : ISODate("2016-12-12T11:00:00Z"), "value" : { "count" : 12707 } }
{ "_id" : ISODate("2016-12-12T01:00:00Z"), "value" : { "count" : 9821 } }
{ "_id" : ISODate("2016-12-11T16:00:00Z"), "value" : { "count" : 5691 } }
{ "_id" : ISODate("2016-12-11T11:00:00Z"), "value" : { "count" : 233 } }
{ "_id" : ISODate("2016-12-12T13:00:00Z"), "value" : { "count" : 138 } }
```
### FONTES DE PESQUISA
Para executar este trabalho práticos foram utilizadas as seguintes fontes de pesquisa:
a. Mining Twitter Data with Python - <NAME> - (https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/)
b. Twitter Data Analytics - <NAME>, <NAME>, and <NAME> - (http://tweettracker.fulton.asu.edu/tda/)
c. StackOverflow - um ótimo lugar para se buscar soluções para problemas já conhecidos.
As duas primeiras fontes de pesquisa são muito boas, pois lhe municiam de conceitos o que lhe permite depois criar. Já o StackOverflow é um bom lugar para se buscar soluções, códigos ou novos algorítimos para desenvolver os conceitos que você aprendeu.
O item (a) tem foco apenas em Python e arquivos txt ou Json, no entanto é muito rico no que tange a text mining, indo além da frequência de termos e entrando no sentimento dos textos. Muito interessante.
O item (b) tem já o foco sobre o MongoDB e tal como o primeiro lhe municia de muitos conceitos e também vai muito além da análise simples de termos.
<file_sep>/Aula 05.md
#Aula 05 - Resolução de exercícios
##Instruções:
Para cada uma das situações dos exercícios escolha a infraestrutura que você acha mais adequada e justifique sua escolha.
###Exercício 01
Você e um grupo de amigos da faculdade decidem-se juntar e criar uma empresa de na área de IoT. Todos seus amigos são excelentes programadores porém estão em dúvida como montar a infraestrutura para suportar a grande quantidade de dados gerados pelos sensores da aplicação. O que vocês devem fazer?
###Resposta
Devido a característica da solução, de se trabalhar com coleta de dados de sensore em real-time e da grande quantidade de dados gerados a solução deverá obrigatóriamente considerar uma infraestrutura robusta o bastante para ter velocidade e diversidade de armazenamento.
Assim a Solução seria a utilização de um Ambiente com um banco de dados não relacional (noSQL) e um ambiente de processamento real-time, como SPARK. Através desta configuração, criaríamos estruturas de filas para receber os dados enviados pelos sensores e estes seriam então tratados e armazenados no bando de dados, permitindo que o recebimento dos dados e seu armazenamento ocorressem de forma assíncrona, evitando impactos na performance da aplicação.
### Exercício 02
Dentro de sua empresa certamente existem pontos que podem ser adaptados para uma arquitetura Big Data. Explique a infraestrutura atual e o que você mudaria para melhorar a eficiência.
<file_sep>/Coleta_Tweets.py
# -*- coding: utf-8 -*-
import json
import sys
import time
import pymongo
import re
import string
from tweepy import Stream
from tweepy.auth import OAuthHandler
from tweepy.streaming import StreamListener
from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords
"""consumer_Key = "rPQLXBYOnk3TbKgzX2Qe8TfJx"
consumer_Secret = "<KEY>"
access_Token = "<KEY>"
access_Secret = "<KEY>" """
consumer_Key = "QfJBnPZnqMnitJDNloKHlUYrj"
consumer_Secret = "<KEY>"
access_Token = "<KEY>"
access_Secret = "<KEY>"
emoticons_str = r"""
(?:
[:=;] # Eyes
[oO\-]? # Nose (optional)
[D\)\]\(\]/\\OpP] # Mouth
)"""
regex_str = [emoticons_str, r'<[^>]+>', # HTML tags
r'(?:@[\w_]+)', # @-mentions
r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags
r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs
r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers
r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and '
r'(?:[\w_]+)', # other words
r'(?:\S)'] # anything else
Words_to_Track = ['Natal','felicidade','amor','paz','alegria','árvore','família','união',
'champagne','luz','trenó','presentes','beijos','abraços','renas',
'papai noel','saco de presentes',
'bebedeira','festa de fim de ano','fim de ano','sexo','camisinha','suruba',
'ano novo', 'dinheiro']
Qtd_id = 1
tokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE)
emoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE)
def process(text: object, tokenizer: object = TweetTokenizer(), stopwords: object = []):
"""Process the text of a tweet:
- Lowercase
- Tokenize
- Stopword removal
- Digits removal
Return: list of strings
"""
text = text.lower()
tokens = tokenizer.tokenize(text)
# If we want to normalize contraction, uncomment this
# tokens = normalize_contractions(tokens)
return [tok for tok in tokens if tok not in stopwords and not tok.isdigit()]
class StdOutListener(StreamListener):
def on_data(self, testdata2):
# Retrieving the details like Id, tweeted text and created at.
global Qtd_id
tweet = json.loads(testdata2)
try:
#with open("c:\\Users\\Marcelo\\Documents\\noSQL-twt.json",'a') as file:
#file.write(testdata2)
created_at = tweet["created_at"]
lingua = tweet["lang"]
dt = time.strptime(created_at,'%a %b %d %H:%M:%S +0000 %Y')
dia = dt.tm_mday
mes = dt.tm_mon
ano = dt.tm_year
hora = dt.tm_hour
id_str = tweet['id_str']
#text = preprocess(tweet['text'])
tokens = process(text=tweet.get('text', ''),
tokenizer=tweet_tokenizer,
stopwords=stopword_list)
obj = {'created_at':dt, 'id_str': id_str, 'text': tokens, 'language': lingua}
tweetind = collection.insert_one(obj).inserted_id
Qtd_id += 1
print("id: %d" % Qtd_id)
#print (hora)
#print ("dia:%d" % dia)
#print ("mes:%d" % mes)
print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", dt))
return True
except BaseException as e:
sys.stderr.write("Error on_data: {}\n".format(e))
time.sleep(15)
return True
def on_error(self, status):
print(status)
if __name__ == '__main__':
tweet_tokenizer = TweetTokenizer()
punct = list(string.punctuation)
stopword_list = stopwords.words('portuguese') + punct + ['rt', 'via']
# Below code is for making connection with mongoDB
client = pymongo.MongoClient('localhost', 27017)
db = client.tweet_database
print("db name = %s" % db.name)
collection = db.tweet_mega
print("db Collection name = %s" % db.collection)
# This handles Twitter authetification and the connection to Twitter Streaming AP
l = StdOutListener()
auth = OAuthHandler(consumer_Key, consumer_Secret)
auth.set_access_token(access_Token, access_Secret)
stream = Stream(auth, l)
# This line filter Twitter Streams to capture data
stream.filter(track=Words_to_Track)
|
6b637ddd2f718c69093247884f5f7781a60c96b4
|
[
"Markdown",
"Python"
] | 4
|
Python
|
Castanha69/noSQL
|
e8912d7433137daebe8c1c2524824faafdf6cc47
|
be53be2838a3b90bff0ac60ca8544c3f1f99bcfa
|
refs/heads/master
|
<file_sep>module ActivityTracker
class NotificationBatchSender
def initialize(notification_batch)
@notification_batch = notification_batch
@activity_type_repository = ActivityTypeRepository.instance
@default_mailer = ActivityTracker.configuration.default_mailer
end
def process
return false if @notification_batch.is_sent
return false if @notification_batch.amendable?
@notifications = @notification_batch.notifications.select(&:send_mail)
@activities = @notifications.map(&:activity).compact
unless @activities.count.zero?
send_mail(@notification_batch.receiver, @activities)
end
set_as_sent
true
end
protected
def send_mail(receiver, activities)
types = activities.map(&:activity_type).uniq
if types.count == 1
activity_type = @activity_type_repository.get(types.first)
if activity_type.mailer
return activity_type.mailer.call(receiver, activities)
end
end
@default_mailer.call(receiver, activities)
end
def set_as_sent
return if @notification_batch.is_sent
@notification_batch.is_sent = true
@notification_batch.save(validate: false)
end
end
end
<file_sep>require 'active_support/concern'
module ActivityTracker
module UserModel
extend ActiveSupport::Concern
included do
has_many ActivityTracker.configuration.activity_class.underscore.pluralize.to_sym, foreign_key: 'sender_id', dependent: :nullify
has_many ActivityTracker.configuration.notification_batch_class.underscore.pluralize.to_sym, foreign_key: 'receiver_id', dependent: :destroy
has_many ActivityTracker.configuration.notification_class.underscore.pluralize.to_sym, through: ActivityTracker.configuration.notification_batch_class.underscore.pluralize.to_sym
store :notification_settings, coder: JSON
before_save :cleanup_notification_settings
def notification_level(activity_type)
user_level = notification_settings[activity_type]
user_level || ActivityTracker::ActivityTypeRepository.instance.get(activity_type).level
end
protected
def cleanup_notification_settings
notification_settings.each do |k, v|
self.notification_settings[k] = v.to_i
end
end
end
end
end
<file_sep>FactoryGirl.define do
factory :user do
sequence :name do |n|
"user_#{n}"
end
trait(:skip_notifications) { skip_notifications true }
end
end
<file_sep>namespace 'activity_tracker' do
desc 'Send e-mail notifications'
task send_notifications: :environment do
repo = ActivityTracker::NotificationBatchRepository.new
batches = repo.pending_to_send
batches.each do |batch|
ActivityTracker::NotificationBatchSenderWorker.perform_wrapper(batch.id)
end
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::ActivityFilter do
let(:user1) { create :user }
let(:type1_activity) do
{
activity_type: :type1,
receivers: [user1],
property1: :value1,
property2: :value1
}
end
let(:type2_activity) do
{
activity_type: :type2,
receivers: [user1],
property1: :value2,
property2: :value2
}
end
let(:type3_activity) do
{
activity_type: :type3,
receivers: [user1],
property1: :value3
}
end
let(:all_activities) { [type1_activity, type2_activity, type3_activity] }
it 'raises error if initialized with more than 1 param' do
expect do
ActivityTracker::ActivityFilter.new(99, 100)
end.to raise_error(ArgumentError)
end
it 'raises error if initialized with unsupported params' do
expect do
ActivityTracker::ActivityFilter.new(99)
end.to raise_error(ArgumentError)
end
it 'matches everything if filter empty' do
filter1 = ActivityTracker::ActivityFilter.new
filter2 = ActivityTracker::ActivityFilter.new(true)
all_activities.each do |activity|
expect(filter1.match?(activity)).to eq(true)
expect(filter2.match?(activity)).to eq(true)
end
end
it 'does not match anything if filter is false' do
filter1 = ActivityTracker::ActivityFilter.new(false)
all_activities.each do |activity|
expect(filter1.match?(activity)).to eq(false)
end
end
it 'filters by :activity_type if passed a single type' do
filter1 = ActivityTracker::ActivityFilter.new(:type1)
filter2 = ActivityTracker::ActivityFilter.new([:type1])
filter3 = ActivityTracker::ActivityFilter.new('type1')
[filter1, filter2, filter3].each do |filter|
expect(filter.match?(type1_activity)).to eq(true)
expect(filter.match?(type2_activity)).to eq(false)
expect(filter.match?(type3_activity)).to eq(false)
end
end
it 'filters by :activity_type if several types passed' do
filter1 = ActivityTracker::ActivityFilter.new([:type1, :type2])
expect(filter1.match?(type1_activity)).to eq(true)
expect(filter1.match?(type2_activity)).to eq(true)
expect(filter1.match?(type3_activity)).to eq(false)
end
it 'filters by :activity_type if activity type is passed in hash' do
filter1 = ActivityTracker::ActivityFilter.new(activity_type: :type1)
filter2 = ActivityTracker::ActivityFilter.new(activity_type: [:type1, :type2])
expect(filter1.match?(type1_activity)).to eq(true)
expect(filter1.match?(type2_activity)).to eq(false)
expect(filter1.match?(type3_activity)).to eq(false)
expect(filter2.match?(type1_activity)).to eq(true)
expect(filter2.match?(type2_activity)).to eq(true)
expect(filter2.match?(type3_activity)).to eq(false)
end
it 'accepts filtering by other properties' do
filter1 = ActivityTracker::ActivityFilter.new(property1: :value1)
filter2 = ActivityTracker::ActivityFilter.new(property2: [:value1, :value2])
expect(filter1.match?(type1_activity)).to eq(true)
expect(filter1.match?(type2_activity)).to eq(false)
expect(filter1.match?(type3_activity)).to eq(false)
expect(filter2.match?(type1_activity)).to eq(true)
expect(filter2.match?(type2_activity)).to eq(true)
expect(filter2.match?(type3_activity)).to eq(false)
end
end
<file_sep>FactoryGirl.define do
factory :activity do
association :sender, factory: :user, strategy: :build
created_at Time.zone.now
activity_type 'type1'
association :scope, factory: :task, strategy: :build
end
end
<file_sep>require 'spec_helper'
FactoryGirl.define do
factory :activity_type, class: ::ActivityTracker::ActivityType do
name 'test1'
end
end
<file_sep>ActiveRecord::Schema.define do
self.verbose = false
create_table :users, force: true do |t|
t.string :name
t.boolean :skip_notifications, required: true, default: false
t.timestamps
end
create_table :tasks, force: true do |t|
t.string :name
t.timestamps
end
create_table :notification_batches do |t|
t.belongs_to :receiver, null: false, required: true, index: true, foreign_key: true, on_delete: :cascade
t.datetime :created_at, null: false, required: true
t.timestamp :last_activity, required: true, null: false
t.boolean :is_closed, required: true, null: false, default: false
t.boolean :is_sent, required: true, null: false, default: false
end
create_table :activities do |t|
t.string :activity_type, required: true, null: false
t.belongs_to :sender, index: true, foreign_key: true, on_delete: :nullify
t.belongs_to :scope, polymorphic: true, null: false, required: true
t.belongs_to :resource, polymorphic: true, null: false, required: true
t.boolean :is_hidden, required: true, default: false
t.datetime :created_at, null: false, required: true
t.text :metadata
end
create_table :notifications do |t|
t.belongs_to :activity, required: true, null: false, index: true
t.belongs_to :notification_batch, required: true, null: false, index: true
t.boolean :is_read, required: true, null: false, default: false
t.boolean :send_mail, required: true, null: false
end
add_column :users, :notification_settings, :text
end
<file_sep>module ActivityTracker
module NotificationLevels
DISABLED = 0
NOTIFICATION_ONLY = 1
EMAIL = 2
VALUES = {
DISABLED => 'Disabled',
NOTIFICATION_ONLY => 'App notification only',
EMAIL => 'E-mail and App notification'
}.freeze
end
end
<file_sep>require 'activity_tracker/railtie' if defined?(Rails)
require 'activity_tracker/configuration'
require 'activity_tracker/notification_levels'
require 'activity_tracker/models/activity_type'
require 'activity_tracker/repositories/activity_repository'
require 'activity_tracker/repositories/activity_type_repository'
require 'activity_tracker/repositories/notification_batch_repository'
require 'activity_tracker/repositories/collector_repository'
require 'activity_tracker/activity_filter'
require 'activity_tracker/batch'
require 'activity_tracker/batcher'
require 'activity_tracker/collector'
require 'activity_tracker/concerns/has_activities'
require 'activity_tracker/concerns/activity_model'
require 'activity_tracker/concerns/notification_model'
require 'activity_tracker/concerns/notification_batch_model'
require 'activity_tracker/concerns/user_model'
require 'activity_tracker/track_activity'
require 'activity_tracker/define_activity'
require 'activity_tracker/notification_batch_sender'
require 'activity_tracker/workers/notification_batch_sender_worker'
require 'tasks.rb' if defined?(Rails)
require 'activity_tracker/version'
module ActivityTracker
end
<file_sep>module ActivityTracker
class ActivityRepository
def initialize(class_name = nil)
class_name ||= ActivityTracker.configuration.activity_class
class_name = class_name
@klass = class_name.constantize
@foreign_key = "#{class_name.underscore}_id".to_sym
@relation_name = class_name.underscore.to_sym
@plural_relation_name = class_name.underscore.pluralize.to_sym
end
def add(activity)
raise ArgumentError unless activity.is_a?(@klass)
activity.save!
end
def all
@klass.all
end
def factory(params)
activity = @klass.new
params.each { |k, v| activity.send("#{k}=".to_sym, v) }
activity
end
end
end
<file_sep>module ActivityTracker
class ActivityFilter
def initialize(*args)
raise ArgumentError if args.count > 1
@reject_all = false
@filters = {}
return if args.count == 0
arg = args[0]
if arg.is_a?(TrueClass) || arg.is_a?(FalseClass)
init_bool_arg(arg)
elsif arg.is_a?(Symbol)
init_symbol_arg(arg)
elsif arg.is_a?(String)
init_symbol_arg(arg.to_sym)
elsif arg.is_a?(Array)
init_array_arg(arg)
elsif arg.is_a?(Hash)
init_hash_arg(arg)
else
raise ArgumentError
end
end
def match?(activity)
return false if @reject_all
return true if @filters.count.zero?
@filters.each do |key, value|
return false unless value.include?(activity[key])
end
return true
end
private
def init_bool_arg(arg)
@reject_all = true unless arg
end
def init_symbol_arg(arg)
@filters[:activity_type] = [arg]
end
def init_array_arg(arg)
@filters[:activity_type] = arg
end
def init_hash_arg(arg)
arg.each { |key, val| arg[key] = val.is_a?(Array) ? val : [val] }
@filters = arg
end
end
end
<file_sep>require 'spec_helper'
describe 'ActivityTracker.define_activity' do
specify 'when block given' do
ActivityTracker::ActivityTypeRepository.reset
repository = ActivityTracker::ActivityTypeRepository.instance
ActivityTracker.define_activity do
name 'type1'
end
expect(repository.all.count).to eq(1)
end
end
<file_sep>module ActivityTracker
def self.batch(options = {}, &block)
b = Batcher.new(options, &block)
b.process
end
end
<file_sep>FactoryGirl.define do
factory :notification do
association :activity, factory: :activity, strategy: :build
association :notification_batch, factory: :notification_batch, strategy: :build
send_mail true
end
end
<file_sep>module ActivityTracker
class Collector
def initialize
@activities = []
end
def add(params)
@activities << params
end
def activities
@activities
end
end
end
<file_sep>FactoryGirl.define do
factory :notification_batch do
association :receiver, factory: :user, strategy: :build
trait :old do
created_at 1.week.ago
last_activity 1.week.ago
end
end
end
<file_sep>require 'sidekiq'
module ActivityTracker
class NotificationBatchSenderWorker
include ::Sidekiq::Worker
def perform(notification_batch_id)
repository = NotificationBatchRepository.new
notification_batch = repository.get_by_id(notification_batch_id)
return unless notification_batch
sender = NotificationBatchSender.new(notification_batch)
sender.process
end
def self.perform_wrapper(id)
if ActivityTracker.configuration.send_mails_async
NotificationBatchSenderWorker.perform_async(id)
else
NotificationBatchSenderWorker.new.perform(id)
end
end
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::HasActivities do
before :all do
load File.dirname(__FILE__) + '/support/activity_types.rb'
end
specify 'client class instances has track_activity method mixed in' do
t = Task.new
users = [create(:user), create(:user)]
expect(t.instance_eval { track_activity(users, :type1) }).to eq(nil)
end
specify 'client class has track_activity method mixed in' do
users = [create(:user), create(:user)]
expect(Task.instance_eval { track_activity(users, :type1) }).to eq(nil)
end
end
<file_sep>require 'active_support/concern'
module ActivityTracker
module HasActivities
extend ActiveSupport::Concern
included do
def track_activity(receivers, type, options = {})
if self.is_a?(ActiveRecord::Base) && !options.include?(:scope)
options[:scope] = self
end
::ActivityTracker.track_activity(receivers, type, options)
end
end
module ClassMethods
def track_activity(receivers, type, options = {})
::ActivityTracker.track_activity(receivers, type, options)
end
end
end
end
<file_sep>module ActivityTracker
class ActivityTypeRepository
def metadata_fields
@metadata_fields
end
def add(activity_type = nil)
raise ArgumentError unless activity_type.is_a?(ActivityType)
type = activity_type.name.try(:to_sym)
raise ArgumentError unless type
@activity_types[type] = activity_type
changed_metadata = false
if activity_type.metadata_fields
activity_type.metadata_fields.each do |field|
unless @metadata_fields.include?(field)
@metadata_fields << field
changed_metadata = true
end
end
end
# inject_metadata_fields if changed_metadata
end
def get(activity_type_name)
raise ArgumentError unless activity_type_name.is_a?(String) ||
activity_type_name.is_a?(Symbol)
activity_type_name = activity_type_name.to_sym
result = @activity_types[activity_type_name]
raise ArgumentError unless result
result
end
def all
@activity_types.values
end
def no_notifications
all.reject(&:no_notifications)
end
def self.instance
@instance ||= ActivityTypeRepository.new
end
def self.reset
@instance = nil
end
private
def inject_metadata_fields
return if @metadata_fields.nil? || @metadata_fields.empty?
m = @metadata_fields
ActivityTracker.configuration.activity_class.constantize.instance_eval do
store :metadata, accessors: m, coder: JSON
end
end
def initialize
@activity_types = {}
@metadata_fields = []
end
end
end
<file_sep>ActivityTracker::ActivityTypeRepository.reset
ActivityTracker.define_activity do
name 'type1'
end
ActivityTracker.define_activity do
name 'type2'
end
ActivityTracker.define_activity do
name 'type3'
end
ActivityTracker.define_activity do
name 'unbatchable_type_1'
batchable false
end
ActivityTracker.define_activity do
name 'no_skip_sender_type_1'
skip_sender false
end
ActivityTracker.define_activity do
name 'notifications_disabled'
level ActivityTracker::NotificationLevels::DISABLED
end
ActivityTracker.define_activity do
name 'notifications_notification_only'
level ActivityTracker::NotificationLevels::NOTIFICATION_ONLY
end
ActivityTracker.define_activity do
name 'notifications_email'
level ActivityTracker::NotificationLevels::EMAIL
end
<file_sep>ActivityTracker.configure do |c|
c.activity_class = 'Activity'
c.notification_batch_class = 'NotificationBatch'
c.notification_class = 'Notification'
c.user_class = 'User'
end
<file_sep>require 'active_support/concern'
module ActivityTracker
module NotificationBatchModel
extend ActiveSupport::Concern
included do
has_many ActivityTracker.configuration.notification_class.underscore.pluralize.to_sym
has_many ActivityTracker.configuration.activity_class.underscore.pluralize.to_sym, after_add: :update_last_activity, through: ActivityTracker.configuration.notification_class.underscore.pluralize.to_sym
belongs_to :receiver, class_name: ActivityTracker.configuration.user_class
validates_presence_of :receiver
validates_inclusion_of :is_closed, in: [true, false]
validates_inclusion_of :is_sent, in: [true, false]
before_validation :update_last_activity
def amendable?
!is_closed &&
created_at > (Time.zone.now - ActivityTracker.configuration.lifetime.seconds) &&
last_activity > (Time.zone.now - ActivityTracker.configuration.idle_time.seconds)
end
protected
def update_last_activity(activity = nil)
self.last_activity = [
activity.try(:created_at), last_activity].compact.max || Time.zone.now
end
end
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::ActivityType do
before :each do
ActivityTracker::ActivityTypeRepository.reset
@instance = ActivityTracker::ActivityTypeRepository.instance
end
let(:activity_type) do
ActivityTracker::ActivityType.new do
name 'activity_type_1'
end
end
let(:activity_type_metadata) do
ActivityTracker::ActivityType.new do
name 'activity_type_1'
metadata_fields [:metadata1, :metadata2]
end
end
let(:activity_type_metadata_2) do
ActivityTracker::ActivityType.new do
name 'activity_type_1'
metadata_fields [:metadata1, :metadata3]
end
end
let(:activity_type_no_notifications) do
ActivityTracker::ActivityType.new do
name 'activity_type_no_notifications'
no_notifications true
end
end
describe '.instance' do
it 'returns a repository object' do
expect(@instance).to be_a(ActivityTracker::ActivityTypeRepository)
end
it 'returns the same instance every time' do
instance1 = ActivityTracker::ActivityTypeRepository.instance
instance2 = ActivityTracker::ActivityTypeRepository.instance
expect(instance1).to eq(instance2)
end
end
describe '.reset' do
it 'resets the instance' do
instance1 = ActivityTracker::ActivityTypeRepository.instance
ActivityTracker::ActivityTypeRepository.reset
instance2 = ActivityTracker::ActivityTypeRepository.instance
expect(instance1).not_to eq(instance2)
end
end
describe '#add' do
it 'expects an ActivityType instance' do
expect { @instance.add }.to raise_error(ArgumentError)
expect { @instance.add(123) }.to raise_error(ArgumentError)
end
it 'replaces existing ActivityType' do
@instance.add(activity_type)
@instance.add(activity_type)
expect(@instance.all.count).to eq(1)
end
end
describe '#all' do
it 'returns empty array if nothing added' do
expect(@instance.all).to eq([])
end
end
describe '#no_notifications' do
it 'returns empty array if nothing added' do
expect(@instance.no_notifications).to eq([])
end
it 'excludes no notifications activity types' do
@instance.add(activity_type)
@instance.add(activity_type_no_notifications)
result = [activity_type]
expect(@instance.no_notifications).to eq(result)
end
end
describe '#add' do
end
describe '#get' do
it 'raises ArgumentError if activity type does not exist' do
expect { @instance.get }.to raise_error(ArgumentError)
expect { @instance.get(123) }.to raise_error(ArgumentError)
expect { @instance.get('does-not-exist') }.to raise_error(ArgumentError)
end
it 'gets the instance both with string and symbol arguments' do
@instance.add(activity_type)
expect(@instance.get('activity_type_1')).to eq(activity_type)
expect(@instance.get(:activity_type_1)).to eq(activity_type)
end
end
describe '#metadata_fields' do
it 'returns empty array if nothing set' do
expect(@instance.metadata_fields).to eq([])
end
it 'adds no metadata when actiivty type without metadata added' do
@instance.add(activity_type)
expect(@instance.metadata_fields).to eq([])
end
it 'adds metadata when activity_type has metadata fields' do
@instance.add(activity_type_metadata)
@instance.add(activity_type_metadata_2)
expect(@instance.metadata_fields).to eq([:metadata1, :metadata2, :metadata3])
end
end
end
<file_sep>FactoryGirl.define do
factory :task do
sequence :name do |n|
"task_#{n}"
end
end
end
<file_sep>require 'simplecov'
SimpleCov.start
require 'activity_tracker'
require 'support/config'
require 'support/db'
require 'support/factory_girl'
require 'support/database_cleaner'
Time.zone = 'UTC'
<file_sep>require 'spec_helper'
describe ActivityTracker::NotificationBatchRepository do
let(:instance) { ActivityTracker::NotificationBatchRepository.new }
let(:user) { create :user }
let(:user_id) { user.id }
let(:user2) { create :user }
let(:user2_id) { user2.id }
describe '#add' do
it 'requires an NotificationBatch object' do
expect { instance.add }.to raise_exception(ArgumentError)
expect { instance.add('abc') }.to raise_exception(ArgumentError)
expect { instance.add(222.33) }.to raise_exception(ArgumentError)
end
it 'saves the activity' do
notification_batch = build :notification_batch
expect(instance.add(notification_batch)).to eq(true)
expect(instance.all.count).to eq(1)
end
end
describe '#all' do
it 'returns no objects if empty' do
expect(instance.all.count).to eq(0)
end
end
describe '#create' do
it 'creates an NotificationBatch object' do
notification_batch = instance.create(user_id)
expect(notification_batch).to be_a(NotificationBatch)
expect(notification_batch.persisted?).to eq(false)
end
end
describe '#pending_to_send' do
let!(:notification_batch) { create :notification_batch }
let!(:notification_batch_old) { create :notification_batch, :old }
it 'fetches only old ones' do
expect(instance.pending_to_send).to eq([notification_batch_old])
end
end
end
<file_sep>require 'spec_helper'
describe 'ActivityTracker.batch' do
before(:each) do
load File.dirname(__FILE__) + '/support/activity_types.rb'
ActivityTracker.configure do |c|
c.default_mailer = lambda do |user, activities|
probe << [user, activities]
end
end
end
before(:each) { probe = [] }
let(:probe) { [] }
let(:user1) { create :user }
let(:user2) { create :user }
let(:user3) { create :user }
let(:user4) { create :user }
let(:user_skip_notifications) { create :user, :skip_notifications }
let(:task) { create :task }
let(:task2) { create :task }
let(:task3) { create :task }
specify 'when batch called without any activities' do
ActivityTracker.batch { 2 + 2 }
expect(ActivityTracker::ActivityRepository.new.all.count).to eq(0)
expect(ActivityTracker::NotificationBatchRepository.new.all.count).to eq(0)
end
specify 'when batch called with one activity and one receiver' do
user1.id
returned_activities = ActivityTracker.batch do
user = user1
task.instance_eval { track_activity(user, :type1) }
end
activities = Activity.all
activity = activities.first
expect(returned_activities.count).to eq(1)
expect(returned_activities).to eq(activities)
expect(activities.count).to eq(1)
expect(activity.notification_batches.count).to eq(1)
expect(activity.notification_batches.first.receiver_id).to eq(user1.id)
end
specify 'when batch called with batch param' do
user1.id
ActivityTracker.batch(sender: user2) do
user = user1
task.instance_eval { track_activity(user, :type1) }
end
activities = Activity.all
activity = activities.first
expect(activities.count).to eq(1)
expect(activity.sender).to eq(user2)
expect(activity.notification_batches.count).to eq(1)
expect(activity.notification_batches.first.is_closed).to eq(false)
expect(activity.notification_batches.first.receiver_id).to eq(user1.id)
expect(probe.count).to eq(0)
end
specify 'when batch called with close_batches param' do
user1.id
returned_activities = ActivityTracker.batch(close_batches: true) do
user = user1
task.instance_eval { track_activity(user, :type1) }
end
activities = Activity.all
activity = activities.first
expect(returned_activities.count).to eq(1)
expect(returned_activities).to eq(activities)
expect(activities.count).to eq(1)
expect(activity.notification_batches.count).to eq(1)
expect(activity.notification_batches.first.is_closed).to eq(true)
expect(activity.notification_batches.first.receiver_id).to eq(user1.id)
end
describe 'type filters - activities' do
specify 'when batch called with both :only and :without params' do
expect do
ActivityTracker.batch(only: [:type1], without: [:type2])
end.to raise_error(ArgumentError)
end
it 'skips all activities except the :only ones' do
user1.id
ActivityTracker.batch(sender: user2, only: [:type1]) do
user = user1
task.instance_eval { track_activity(user, :type1) }
task.instance_eval { track_activity(user, :type2) }
end
activities = Activity.all
activities_hidden = Activity.where(is_hidden: true)
activity = activities.first
expect(activities.count).to eq(1)
expect(activities_hidden.count).to eq(0)
expect(activity.activity_type.to_sym).to eq(:type1)
expect(activity.is_hidden).to eq(false)
end
it 'skips the :without specified activities' do
user1.id
ActivityTracker.batch(sender: user2, without: [:type1]) do
user = user1
task.instance_eval { track_activity(user, :type1) }
task.instance_eval { track_activity(user, :type2) }
end
activities = Activity.all
activities_hidden = Activity.where(is_hidden: true)
activity = activities.first
expect(activities.count).to eq(1)
expect(activities_hidden.count).to eq(0)
expect(activity.activity_type.to_sym).to eq(:type2)
expect(activity.is_hidden).to eq(false)
end
end
describe 'unbatchable activities' do
it 'does not batch unbatchable activities' do
ActivityTracker.batch(sender: user2, without: [:type1]) do
user = user1
task.instance_eval { track_activity(user, :type2) }
task.instance_eval { track_activity(user, :unbatchable_type_1) }
end
expect(NotificationBatch.all.count).to eq(2)
expect(NotificationBatch.where(is_closed: true).count).to eq(1)
expect(NotificationBatch.where(is_closed: false).count).to eq(1)
expect(probe.count).to eq(1)
end
end
describe 'skip_sender option' do
it 'is enabled by default' do
ActivityTracker.batch(sender: user1) do
users = [user1, user2]
task.instance_eval { track_activity(users, :type2) }
end
expect(NotificationBatch.all.count).to eq(1)
end
it 'does not skip senders if disabled' do
ActivityTracker.batch(sender: user1) do
users = [user1, user2]
task.instance_eval { track_activity(users, :no_skip_sender_type_1) }
end
expect(NotificationBatch.all.count).to eq(2)
end
end
describe 'global receivers filter' do
before do
ActivityTracker.configure do |c|
c.receivers_filter = ->(user) { !user.skip_notifications }
end
end
after do
ActivityTracker.configure do |c|
c.receivers_filter = nil
end
end
it 'skips users' do
ActivityTracker.batch do
users = [user1, user_skip_notifications]
task.instance_eval { track_activity(users, :type1) }
end
activities = Activity.all
activity = activities.first
expect(activities.count).to eq(1)
expect(activity.notification_batches.count).to eq(1)
expect(activity.notification_batches.first.receiver_id).to eq(user1.id)
end
end
describe 'scope filters' do
it 'skips skips scopes' do
ActivityTracker.batch(sender: user1, scope_filter: task) do
users = [user2, user3]
task.instance_eval { track_activity(users.dup, :type1, scope: self) }
task2.instance_eval { track_activity(users.dup, :type1, scope: self) }
task3.instance_eval { track_activity(users.dup, :type1, scope: self) }
end
activities = Activity.all
activities_hidden = Activity.where(is_hidden: true)
expect(activities.count).to eq(3)
expect(activities_hidden.count).to eq(2)
cnt = Notification.all.reject { |n| n.activity.scope == task }.count
expect(cnt).to eq(0)
end
it 'skips skips scopes when array passed' do
ActivityTracker.batch(sender: user1, scope_filter: [task, task2]) do
users = [user2, user3]
task.instance_eval { track_activity(users.dup, :type1, scope: self) }
task2.instance_eval { track_activity(users.dup, :type1, scope: self) }
task3.instance_eval { track_activity(users.dup, :type1, scope: self) }
end
activities = Activity.all
activities_hidden = Activity.where(is_hidden: true)
expect(activities.count).to eq(3)
expect(activities_hidden.count).to eq(1)
expect(Notification.all.select { |n| n.activity.scope == task3 }.count).to eq(0)
end
end
describe 'type filters - notifications' do
specify 'when batch called with both :only and :without params' do
expect do
ActivityTracker.batch(notifications: { only: [:type1], without: [:type2] })
end.to raise_error(ArgumentError)
end
it 'skips all activities except the :only ones' do
user1.id
ActivityTracker.batch(sender: user2, notifications: { only: [:type1] }) do
user = user1
task.instance_eval { track_activity(user, :type1) }
task.instance_eval { track_activity(user, :type2) }
end
activities = Activity.all
activities_hidden = Activity.where(is_hidden: true)
expect(activities.count).to eq(2)
expect(activities_hidden.count).to eq(1)
expect(activities.first.activity_type.to_sym).to eq(:type1)
expect(activities.first.is_hidden).to eq(false)
expect(activities.second.activity_type.to_sym).to eq(:type2)
expect(activities.second.is_hidden).to eq(true)
end
it 'skips the :without specified activities' do
user1.id
ActivityTracker.batch(sender: user2, notifications: { without: [:type1] }) do
user = user1
task.instance_eval { track_activity(user, :type1) }
task.instance_eval { track_activity(user, :type2) }
end
activities = Activity.all
activities_hidden = Activity.where(is_hidden: true)
activity = activities.first
expect(activities.count).to eq(2)
expect(activities_hidden.count).to eq(1)
expect(activities.first.activity_type.to_sym).to eq(:type1)
expect(activities.first.is_hidden).to eq(true)
expect(activities.second.activity_type.to_sym).to eq(:type2)
expect(activities.second.is_hidden).to eq(false)
end
end
describe 'notification levels' do
it 'skips sending notifications if disabled by default' do
ActivityTracker.batch do
users = [user1, user2]
task.instance_eval { track_activity(users, :notifications_disabled) }
end
expect(NotificationBatch.all.count).to eq(0)
end
end
describe 'user level notification levels' do
specify 'when default actiivty level is disabled' do
user1.notification_settings[:notifications_disabled] = ActivityTracker::NotificationLevels::DISABLED
user2.notification_settings[:notifications_disabled] = ActivityTracker::NotificationLevels::NOTIFICATION_ONLY
user3.notification_settings[:notifications_disabled] = ActivityTracker::NotificationLevels::EMAIL
user1.save
user2.save
user3.save
ActivityTracker.batch do
users = [user1, user2, user3, user4]
task.instance_eval { track_activity(users, :notifications_disabled) }
end
notification_batches = NotificationBatch.all
notifications = Notification.all
expect(notification_batches.count).to eq(2)
expect(notification_batches.first.receiver_id).to eq(user2.id)
expect(notification_batches.second.receiver_id).to eq(user3.id)
expect(notifications.first.send_mail).to eq(false)
expect(notifications.second.send_mail).to eq(true)
end
specify 'when default actiivty level is notifications only' do
user1.notification_settings[:notifications_notification_only] = ActivityTracker::NotificationLevels::DISABLED
user2.notification_settings[:notifications_notification_only] = ActivityTracker::NotificationLevels::NOTIFICATION_ONLY
user3.notification_settings[:notifications_notification_only] = ActivityTracker::NotificationLevels::EMAIL
user1.save
user2.save
user3.save
ActivityTracker.batch do
users = [user1, user2, user3, user4]
task.instance_eval { track_activity(users, :notifications_notification_only) }
end
notification_batches = NotificationBatch.all
notifications = Notification.all
expect(notification_batches.count).to eq(3)
expect(notification_batches.first.receiver_id).to eq(user2.id)
expect(notification_batches.second.receiver_id).to eq(user3.id)
expect(notification_batches.third.receiver_id).to eq(user4.id)
expect(notifications.first.send_mail).to eq(false)
expect(notifications.second.send_mail).to eq(true)
expect(notifications.third.send_mail).to eq(false)
end
specify 'when default actiivty level is email' do
user1.notification_settings[:notifications_email] = ActivityTracker::NotificationLevels::DISABLED
user2.notification_settings[:notifications_email] = ActivityTracker::NotificationLevels::NOTIFICATION_ONLY
user3.notification_settings[:notifications_email] = ActivityTracker::NotificationLevels::EMAIL
user1.save
user2.save
user3.save
ActivityTracker.batch do
users = [user1, user2, user3, user4]
task.instance_eval { track_activity(users, :notifications_email) }
end
notification_batches = NotificationBatch.all
notifications = Notification.all
expect(notification_batches.count).to eq(3)
expect(notification_batches.first.receiver_id).to eq(user2.id)
expect(notification_batches.second.receiver_id).to eq(user3.id)
expect(notification_batches.third.receiver_id).to eq(user4.id)
expect(notifications.first.send_mail).to eq(false)
expect(notifications.second.send_mail).to eq(true)
expect(notifications.third.send_mail).to eq(true)
end
end
end
<file_sep>module ActivityTracker
class NotificationBatchRepository
def initialize(class_name = nil)
class_name ||= ActivityTracker.configuration.notification_batch_class
@class_name = class_name
@klass = class_name.constantize
@foreign_key = "#{class_name.underscore}_id".to_sym
@relation_name = class_name.underscore.to_sym
@plural_relation_name = class_name.underscore.pluralize.to_sym
end
def create(user_id, is_closed = false)
@klass.new(
receiver_id: user_id,
is_closed: is_closed
)
end
def get_by_id(id)
@klass.find_by_id(id)
end
def pending_to_send
@klass.where(
'is_sent = ? AND (created_at <= ? OR last_activity <= ? OR is_closed = ?)',
false,
Time.zone.now - ActivityTracker.configuration.lifetime.seconds,
Time.zone.now - ActivityTracker.configuration.idle_time.seconds,
true
)
end
def find_or_create(user_id, is_closed = false)
return create(user_id, true) if is_closed
@klass.where(
'receiver_id = ? AND (created_at > ? or last_activity > ?) AND is_closed = ?',
user_id,
Time.zone.now - ActivityTracker.configuration.lifetime.seconds,
Time.zone.now - ActivityTracker.configuration.idle_time.seconds,
false
).order('last_activity desc').first || create(user_id, is_closed)
end
def add(notification_batch)
raise ArgumentError unless notification_batch.is_a?(@klass)
notification_batch.save!
end
def all
@klass.all
end
end
end
<file_sep>module ActivityTracker
class Railtie
end
end
<file_sep>require 'active_support/concern'
module ActivityTracker
module NotificationModel
extend ActiveSupport::Concern
included do
belongs_to ActivityTracker.configuration.notification_batch_class.underscore.to_sym
belongs_to ActivityTracker.configuration.activity_class.underscore.to_sym
end
end
end
<file_sep>module ActivityTracker
def self.track_activity(receivers, type, options = {})
return unless ::ActivityTracker::CollectorRepository.instance.exists?
collector = ::ActivityTracker::CollectorRepository.instance.get
options[:receivers] = receivers.is_a?(Array) ? receivers : [receivers]
options[:activity_type] = type
collector.add(options)
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::NotificationBatchSender do
let(:activity_type_probe) { [] }
let(:activity_type_probe_block) do
lambda do |user, activities|
activity_type_probe << [user, activities]
end
end
let(:probe) { [] }
let(:probe_block) do
lambda do |user, activities|
probe << [user, activities]
end
end
let(:notification1) { build :notification }
let(:notification_custom_mailer) do
build :notification, activity: custom_mailer_activity
end
let(:notification_batch_amendable) do
create :notification_batch, created_at: Time.zone.now, is_sent: false
end
let(:custom_mailer_activity) do
build :activity, activity_type: :custom_mailer_type
end
let(:notification_batch_empty) do
create :notification_batch, :old, is_closed: true
end
let(:notification_batch_single_notification) do
nb = create :notification_batch, :old, is_closed: true
nb.notifications << notification1
nb.last_activity = 1.week.ago
nb.save
nb
end
let(:notification_batch_multiple_notifications) do
nb = create :notification_batch, :old, is_closed: true
nb.notifications << notification1
nb.notifications << notification_custom_mailer
nb.last_activity = 1.week.ago
nb.save
nb
end
let(:notification_batch_custom_mailer) do
nb = create :notification_batch, :old, is_closed: true
nb.notifications << notification_custom_mailer
nb.last_activity = 1.week.ago
nb.save
nb
end
before(:each) do
ActivityTracker.configure do |c|
c.default_mailer = probe_block
end
type = ActivityTracker::ActivityType.new(
name: 'custom_mailer_type',
mailer: activity_type_probe_block
)
ActivityTracker::ActivityTypeRepository.instance.add(type)
end
specify 'when initialised with no params' do
expect do
ActivityTracker::NotificationBatchSender.new
end.to raise_error(ArgumentError)
end
specify 'when notification is not closed' do
ns = ActivityTracker::NotificationBatchSender.new(
notification_batch_amendable
)
expect(ns.process).to eq(false)
expect(probe.count).to eq(0)
notification_batch_single_notification.reload
expect(notification_batch_amendable.is_sent).to eq(false)
end
specify 'when initialised without any notifications' do
ns = ActivityTracker::NotificationBatchSender.new(notification_batch_empty)
expect(ns.process).to eq(true)
expect(probe).to eq([])
notification_batch_empty.reload
expect(notification_batch_empty.is_sent).to eq(true)
end
specify 'when initialised with a single notification' do
ns = ActivityTracker::NotificationBatchSender.new(
notification_batch_single_notification
)
expect(ns.process).to eq(true)
expect(probe.count).to eq(1)
expect(probe.first).to eq(
[notification_batch_single_notification.receiver,
notification_batch_single_notification.activities]
)
notification_batch_single_notification.reload
expect(notification_batch_single_notification.is_sent).to eq(true)
end
specify 'when initialised with a multiple notifications' do
ns = ActivityTracker::NotificationBatchSender.new(
notification_batch_multiple_notifications
)
expect(ns.process).to eq(true)
expect(probe.count).to eq(1)
expect(probe.first).to eq(
[notification_batch_multiple_notifications.receiver,
notification_batch_multiple_notifications.activities]
)
notification_batch_multiple_notifications.reload
expect(notification_batch_multiple_notifications.is_sent).to eq(true)
end
specify 'when initialised with a custom mailer notification' do
ns = ActivityTracker::NotificationBatchSender.new(
notification_batch_custom_mailer
)
expect(ns.process).to eq(true)
expect(probe.count).to eq(0)
expect(activity_type_probe.count).to eq(1)
expect(activity_type_probe.first).to eq(
[notification_batch_custom_mailer.receiver,
notification_batch_custom_mailer.activities]
)
notification_batch_custom_mailer.reload
expect(notification_batch_custom_mailer.is_sent).to eq(true)
end
end
<file_sep>require 'active_support/concern'
module ActivityTracker
module ActivityModel
extend ActiveSupport::Concern
included do
has_many ActivityTracker.configuration.notification_class.underscore.pluralize.to_sym, dependent: :destroy
has_many ActivityTracker.configuration.notification_batch_class.underscore.pluralize.to_sym, through: ActivityTracker.configuration.notification_class.underscore.pluralize.to_sym
belongs_to :sender, class_name: ActivityTracker.configuration.user_class
belongs_to :scope, polymorphic: true
belongs_to :resource, polymorphic: true
validates_presence_of :activity_type, :scope, :resource
before_validation :auto_scope_resource
def type
activity_type ? ::ActivityTracker::ActivityTypeRepository.instance.get(activity_type) : nil
end
protected
def auto_scope_resource
self.resource = scope if scope && !resource
self.scope = resource if !scope && resource
end
end
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::ActivityType do
describe 'initializer' do
specify 'init with hash' do
obj = ActivityTracker::ActivityType.new(name: 'test1')
expect(obj).to be_a(ActivityTracker::ActivityType)
expect(obj.name).to eq('test1')
end
specify 'without params' do
obj = ActivityTracker::ActivityType.new
expect(obj).to be_a(ActivityTracker::ActivityType)
expect(obj.name).to be_nil
end
specify 'with block' do
obj = ActivityTracker::ActivityType.new do
name 'test2'
end
expect(obj.name).to eq(:test2)
end
end
describe 'accessors' do
it 'gets attribute values' do
obj = ActivityTracker::ActivityType.new(name: 'test1')
expect(obj.name).to eq('test1')
end
it 'does not allow modifying the object' do
obj = ActivityTracker::ActivityType.new
expect { obj.name 'test' }.to raise_exception(RuntimeError)
end
end
describe 'notification levels' do
it 'is set to email by default' do
obj = ActivityTracker::ActivityType.new
expect(obj.level).to eq(ActivityTracker::NotificationLevels::EMAIL)
end
it 'is possible to set other value' do
obj = ActivityTracker::ActivityType.new(level: ActivityTracker::NotificationLevels::DISABLED)
expect(obj.level).to eq(ActivityTracker::NotificationLevels::DISABLED)
end
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::ActivityRepository do
let(:instance) { ActivityTracker::ActivityRepository.new }
describe '#add' do
it 'requires an Activity object' do
expect { instance.add }.to raise_exception(ArgumentError)
expect { instance.add('abc') }.to raise_exception(ArgumentError)
expect { instance.add(222.33) }.to raise_exception(ArgumentError)
end
it 'saves the activity' do
activity = build :activity
expect(instance.add(activity)).to eq(true)
expect(instance.all.count).to eq(1)
end
end
describe '#factory' do
it 'returns the right object types' do
activity = instance.factory(activity_type: 'type1')
expect(activity).to be_a(Activity)
expect(activity.type).to be_a(ActivityTracker::ActivityType)
end
end
describe '#all' do
it 'returns no objects if empty' do
expect(instance.all.count).to eq(0)
end
end
end
<file_sep>module ActivityTracker
class CollectorRepository
def initialize
@collectors = {}
end
def get(thread_id = Thread.current.object_id)
@collectors[thread_id] ||= ::ActivityTracker::Collector.new
end
def exists?(thread_id = Thread.current.object_id)
@collectors.include?(thread_id)
end
def clear(thread_id = Thread.current.object_id)
@collectors.delete(thread_id)
end
def self.instance
@instance ||= CollectorRepository.new
end
end
end
<file_sep>require 'spec_helper'
describe ActivityTracker::CollectorRepository do
let(:instance) { ActivityTracker::CollectorRepository.instance }
describe '.instance' do
it 'returns a repository object' do
expect(instance).to be_a(ActivityTracker::CollectorRepository)
end
end
describe '#exists?' do
it 'returns false initially' do
expect(instance.exists?).to eq(false)
end
it 'returns true after calling get' do
instance.get
expect(instance.exists?).to eq(true)
end
it 'returns false after calling clear' do
instance.get
instance.clear
expect(instance.exists?).to eq(false)
end
end
end
<file_sep>class NotificationBatch < ActiveRecord::Base
include ActivityTracker::NotificationBatchModel
end
class Activity < ActiveRecord::Base
include ActivityTracker::ActivityModel
end
class Notification < ActiveRecord::Base
include ActivityTracker::NotificationModel
end
class User < ActiveRecord::Base
include ActivityTracker::UserModel
def to_s
name
end
end
class Task < ActiveRecord::Base
include ActivityTracker::HasActivities
end
<file_sep>module ActivityTracker
module Generators
class ActivityTrackerGenerator < Rails::Generators::Base
Rails::Generators::ResourceHelpers
source_root File.expand_path('../templates', __FILE__)
argument :activity_class,
type: :string,
default: 'Activity',
banner: 'Activity class name'
argument :notification_batch_class,
type: :string,
default: 'NotificationBatch',
banner: 'NotificationBatch class name'
argument :notification_class,
type: :string,
default: 'Notification',
banner: 'Notification class name'
argument :user_class,
type: :string,
default: 'User',
banner: 'User class name'
namespace :activity_tracker
hook_for(:orm, required: true) do |invoked|
invoke invoked, [
'activity_tracker_models',
activity_class,
notification_batch_class,
notification_class,
user_class
]
end
desc 'Generates the required models and migration files.'
def create_initializer
template 'initializer.rb.erb', 'config/initializers/activity_tracker.rb'
end
end
end
end
<file_sep>module ActivityTracker
class ActivityType
def initialize(params = {}, &block)
@batchable = true
@skip_sender = true
@level = NotificationLevels::EMAIL
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
instance_eval(&block) if block
freeze
end
def name(val = nil)
if val.nil?
instance_variable_get(:@name)
else
instance_variable_set(:@name, val.to_sym)
end
end
def self.field_setter(field)
define_method field do |val = nil, &block|
var_name = "@#{field}"
if val.nil? && !block
instance_variable_get(var_name)
else
instance_variable_set(var_name, block || val)
end
end
end
%i[
metadata_fields batchable skip_sender level label mailer
description no_notifications
].each do |field|
field_setter(field.to_sym)
end
end
end
<file_sep>require 'rails/generators/active_record'
require 'active_support/core_ext'
module ActiveRecord
module Generators
class ActivityTrackerGenerator < ActiveRecord::Generators::Base
source_root File.expand_path('../templates', __FILE__)
argument :activity_class,
type: :string,
default: 'Activity',
banner: 'Activity class name'
argument :notification_batch_class,
type: :string,
default: 'NotificationBatch',
banner: 'NotificationBatch class name'
argument :notification_class,
type: :string,
default: 'Notification',
banner: 'Notification class name'
argument :user_class,
type: :string,
default: 'User',
banner: 'User class name'
def generate_activity_model
template 'activity.rb.erb', activity_model_path
end
def generate_notification_batch_model
template 'notification_batch.rb.erb', notification_batch_model_path
end
def generate_notification_model
template 'notification.rb.erb', notification_model_path
end
def create_migrations
migration_template 'migrations.rb.erb', migration_path
end
private
def activity_model_path
File.join('app', 'models', "#{activity_class.underscore.downcase}.rb")
end
def notification_batch_model_path
File.join(
'app',
'models',
"#{notification_batch_class.underscore.downcase}.rb"
)
end
def notification_model_path
File.join(
'app',
'models',
"#{notification_class.underscore.downcase}.rb"
)
end
def migration_path
File.join('db', 'migrate', "#{name}.rb")
end
end
end
end
<file_sep>module ActivityTracker
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
class Configuration
attr_accessor :activity_class, :notification_batch_class,
:notification_class, :notification_setting_class,
:user_class, :idle_time, :lifetime, :default_mailer,
:receivers_filter, :send_mails_async
def initialize
@activity_class = 'Activity'
@notification_batch_class = 'NotificationBatch'
@notification_class = 'Notification'
@user_class = 'User'
@idle_time = 600
@lifetime = 3600
@send_mails_async = false
end
def activity_type_custom_fields(fields = [])
fields.each do |field|
ActivityType.instance_eval do
field_setter(field.to_sym)
end
end
end
end
end
<file_sep>module ActivityTracker
def self.define_activity(&block)
repository = ActivityTypeRepository.instance
activity_type = ActivityType.new(&block)
repository.add(activity_type)
end
end
<file_sep>module ActivityTracker
class Batcher
def initialize(options, &block)
@options = options
@block = block
options_init
@activity_repository = ActivityRepository.new
@notification_batch_repository = NotificationBatchRepository.new
@receivers_filter = ActivityTracker.configuration.receivers_filter
@activity_params = []
@activity_receiver_pairs = []
@new_batch = false
@to_close = []
end
def process
return false unless @block
CollectorRepository.instance.clear
@collector = CollectorRepository.instance.get
begin
@block.call
load_from_collector
filter_by_scope
filter_by_activity_type
build_activities
filter_receivers
insert_activities
send_closed
rescue StandardError => e
# :nocov:
raise e
# :nocov:
ensure
CollectorRepository.instance.clear
end
@activity_receiver_pairs.map { |activity, _receivers| activity }
end
protected
def options_init
if @options.include?(:only)
only = @options.delete(:only)
@activity_receiver_pairs_only = ActivityFilter.new(only)
end
if @options.include?(:without)
without = @options.delete(:without)
@activity_receiver_pairs_without = ActivityFilter.new(without)
end
if @options.include?(:notifications)
notifications_options = @options.delete(:notifications)
if notifications_options.include?(:only)
only = notifications_options[:only]
@notifications_only = ActivityFilter.new(only)
end
if notifications_options.include?(:without)
without = notifications_options[:without]
@notifications_without = ActivityFilter.new(without)
end
end
if @options.include?(:scope_filter)
scope_filter = @options.delete(:scope_filter)
@scope_filter = scope_filter.is_a?(Array) ? scope_filter : [scope_filter]
end
if @options.include?(:close_batches)
@close_batches = @options.delete(:close_batches)
end
raise ArgumentError if @activity_receiver_pairs_only && @activity_receiver_pairs_without
raise ArgumentError if @notifications_only && @notifications_without
end
def load_from_collector
@activity_params = @collector.activities.to_a
end
def filter_by_scope
return unless @scope_filter
@activity_params.map! do |activity_params|
unless @scope_filter.include?(activity_params[:scope])
activity_params[:receivers] = []
activity_params[:is_hidden] = true
end
activity_params
end
end
def filter_by_activity_type
@activity_params.reject! do |activity_params|
(@activity_receiver_pairs_only && !@activity_receiver_pairs_only.match?(activity_params)) ||
(@activity_receiver_pairs_without && @activity_receiver_pairs_without.match?(activity_params))
end
@activity_params.map! do |activity_params|
if (@notifications_only && !@notifications_only.match?(activity_params)) ||
(@notifications_without && @notifications_without.match?(activity_params))
activity_params[:receivers] = []
activity_params[:is_hidden] = true
end
activity_params
end
end
def build_activities
@activity_receiver_pairs = @activity_params.map do |activity_params|
receivers = activity_params[:receivers] || []
activity_params.delete(:receivers)
activity_params = @options.merge(activity_params)
[
@activity_repository.factory(activity_params),
receivers
]
end.compact
end
def filter_receivers
@activity_receiver_pairs.each do |activity, receivers|
type_string = activity.activity_type
type_obj = ActivityTypeRepository.instance.get(type_string)
receivers.compact!
receivers.select!(&@receivers_filter) if @receivers_filter
if type_obj.skip_sender && activity.sender && !receivers.count.zero?
receivers.reject! { |r| r.id == activity.sender_id }
end
receivers.map! do |receiver|
level = receiver.notification_level(type_string)
next if level == ActivityTracker::NotificationLevels::DISABLED
[receiver, level]
end.compact!
[activity, receivers]
end
@activity_receiver_pairs.reject! do |activity, receivers|
receivers.empty? && !activity.scope
end
end
def insert_activities
@activity_receiver_pairs.each do |activity, receivers|
type = ActivityTypeRepository.instance.get(activity.activity_type)
batchable = type.batchable
receivers.each do |receiver, level|
batch = @notification_batch_repository.find_or_create(receiver.id, !batchable)
@notification_batch_repository.add(batch)
activity.notifications.build(
notification_batch: batch,
send_mail: level == ActivityTracker::NotificationLevels::EMAIL
)
if (!batchable || @close_batches) && !@to_close.include?(batch)
@to_close << batch
end
end
@activity_repository.add(activity)
end
end
def send_closed
@to_close.each do |batch|
unless batch.is_closed?
batch.is_closed = true
@notification_batch_repository.add(batch)
end
NotificationBatchSenderWorker.perform_wrapper(batch.id)
end
end
end
end
|
5e2c9dad6459a11dcf1271f2c5dc5ad3670c33a6
|
[
"Ruby"
] | 46
|
Ruby
|
manageplaces/activity_tracker
|
a57305a6dc3955feae49397ae77f38f4e2862039
|
7c07a0b906017679e26a04955e94a8cc4bb23491
|
refs/heads/master
|
<repo_name>samedzadesamil/JavaEE-Login-Registration<file_sep>/src/main/java/login/sumbit/registration/LoginRegisterServlet.java
package login.sumbit.registration;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/loginRegister")
public class LoginRegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CustomerDAO cd=new CustomerDAOImpl();
String username=request.getParameter("username");
String password=request.getParameter("password");
String name=request.getParameter("name");
String sumbitType=request.getParameter("sumbit");
Customer c=cd.getCustomer(username, password);
if(sumbitType.equals("login")&&c!=null &&c.getName()!=null) {
request.setAttribute("message", c.getName());
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}else if(sumbitType.equals("register")) {
Customer customer=new Customer();
customer.setName(name);
customer.setUsername(username);
customer.setPassword(<PASSWORD>);
cd.insertCustomer(customer);
request.setAttribute("successMessage", "Indi daxil ola bilersiniz");
request.getRequestDispatcher("login.jsp").forward(request, response);
}else {
request.setAttribute("message", "giris bilgileri sehvdir qeydiyyatdan kecin");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
<file_sep>/src/main/java/login/sumbit/registration/CustomerDAOImpl.java
package login.sumbit.registration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CustomerDAOImpl implements CustomerDAO {
static Connection conn;
static PreparedStatement ps;
static Statement st;
@Override
public int insertCustomer(Customer customer) {
int status=0;
try {
conn=MyConnectionProvider.getConnect();
ps=conn.prepareStatement("insert into customer(username,password,name) values(?,?,?)");
ps.setString(1, customer.getUsername());
ps.setString(2, customer.getPassword());
ps.setString(3, customer.getName());
status=ps.executeUpdate();
conn.close();
} catch (SQLException e) {
System.out.println(e);
}
return status;
}
@Override
public Customer getCustomer(String username, String password) {
Customer customer=new Customer();
try {
conn=MyConnectionProvider.getConnect();
ps=conn.prepareStatement("select * from customer where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet resultSet=ps.executeQuery();
while(resultSet.next()) {
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
customer.setName(resultSet.getString("name"));
}
} catch (SQLException e) {
System.out.println(e);
}
return customer;
}
}
|
bb267017f1e27028d565d0d09d2645827efe7fd2
|
[
"Java"
] | 2
|
Java
|
samedzadesamil/JavaEE-Login-Registration
|
c50a5d790980b89893a2888a2f5a2b6ec742433e
|
de705d4eaaa19b2495aec9aae6dc87b99bf2dbff
|
refs/heads/master
|
<repo_name>zolza/ToDoList<file_sep>/js/todo.js
var list = {
tasks: [],
add: function(task_name) {
var item = $("<li></li>");
var checkbox = $("<input type='checkbox'>");
item.append(checkbox);
item.append(task_name);
$('#list').prepend(item);
$("#list li").on('click', 'input', function(){
var checked = $(this).prop('checked');
if (checked) {
$(this).parent().css('text-decoration', 'line-through');
} else {
$(this).parent().css('text-decoration', 'none');
}
});
var task = {
name: task_name,
completed: false
};
this.tasks.push(task);
}
};
$(document).ready(function() {
$('input').on('keydown', function(event) {
if (event.keyCode == 13) {
var task_name = $('input').val();
list.add(task_name);
$('input').val("");
}
});
});
<file_sep>/README.md
# ToDoList
The editable list of future duties. The file was created with use of basics of javaScript and jQuery.
|
8082b79eb3c262d13407b0312aba36d3e67913cb
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
zolza/ToDoList
|
20cf4fa2b8ccb82e2a34db6edd3713416099222e
|
5bb16993e6fe1f9019be26738b528b47d4f28fdd
|
refs/heads/master
|
<repo_name>syting/playlists<file_sep>/songs/management/commands/import_songs.py
from django.core.management.base import BaseCommand
import re
from songs.models import RankingList, SongRanking
from songs.utils import get_or_create_artists, fuzzy_get_or_create_ranking_org, fuzzy_get_or_create_song
class Command(BaseCommand):
help = 'Import a song list from file'
def add_arguments(self, parser):
parser.add_argument('--org', type=str, required=True, help='Name of the ranking organization')
parser.add_argument('--year', type=int, help='Year covered in the rankings')
parser.add_argument('--begin', type=int, required=True, help='First year covered in the rankings')
parser.add_argument('--end', type=int, help='Last year covered in the rankings, set to the beginning year if omitted')
parser.add_argument('--file', type=str, required=True, help='Location of file containing the list')
def handle(self, *args, **options):
ranking_org = fuzzy_get_or_create_ranking_org(options['org'])
begin_year = options['begin']
year = None
if options['year'] is not None:
year = options['year']
if options['end'] is not None:
end_year = options['end']
else:
end_year = begin_year
year = end_year
self.ranking_list = RankingList.objects.get_or_create(organization=ranking_org, begin_year=begin_year, end_year=end_year)[0]
entries = read_list_from_file(options['file'])
for entry in entries:
self.add_entry(entry[0], entry[1], entry[2], year=year)
def add_entry(self, rank, title, artist, year=None):
print('Adding {rank}. "{title}" by {artist}'.format(rank=rank, title=title, artist=artist))
artists_models, featured_models = get_or_create_artists(artist)
song_model = fuzzy_get_or_create_song(title, artists_models, featured_models, year)
song_ranking = SongRanking.objects.get_or_create(song=song_model, ranking_list=self.ranking_list, rank=rank)
if song_ranking[1] is False:
print('Already exists!')
def read_list_from_file(file_name):
with open(file_name, 'r') as infile:
parser = re.compile(r'^(?P<rank>\d+)\|(?P<song>.*)\|(?P<artist>.*)$')
entries = [(int(p.group('rank')), p.group('song'), p.group('artist')) for p in (parser.match(entry) for entry in infile)]
return entries
<file_sep>/songs/management/commands/convert.py
from django.core.management.base import BaseCommand
from songs.models import Song, SongRanking
from songs.utils import fuzzy_get_or_create_song
class Command(BaseCommand):
help = 'Clean featured and duet artists in database'
def handle(self, *args, **options):
songs = Song.objects.filter(title__contains='/')
for song in songs:
proceed = input("Split {song}? ".format(song=song))
song_title = song.title
try:
if proceed in ['y', 'Y']:
titles = song.title.split('/')
song.title = 'EDITING'
song.save()
song_rankings = song.songranking_set.all()
artists = song.artists.all()
featured_artists = song.featuring.all()
for title in titles:
split_song = fuzzy_get_or_create_song(title, artists, featured_artists, song.year)
for sr in song_rankings:
rl = sr.ranking_list
rank = sr.rank
SongRanking.objects.create(rank=rank, ranking_list=rl, song=split_song)
for sr in song_rankings:
sr.delete()
song.delete()
except:
song.title = song_title
song.save()
<file_sep>/songs/management/commands/import_acclaimed_songs.py
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand
from pickle import dump, load
from requests import get
import re
from songs.models import RankingList, SongRanking
from songs.utils import get_or_create_artists, fuzzy_get_or_create_ranking_org, fuzzy_get_or_create_song
class Command(BaseCommand):
help = 'Import a song list from file'
def add_arguments(self, parser):
parser.add_argument('--begin', type=int, required=True, help='Year covered in the rankings')
parser.add_argument('--end', type=int, required=True, help='First year covered in the rankings')
def handle(self, *args, **options):
song_parser = re.compile('(?P<artist>^.*[^\s])[\s\r][\s\r]+(?P<title>.*)$')
list_parser = re.compile('(?P<list_name>.*[^\s\r])\s\s+(?P<rank>[^\s][No Order\d]*)$')
eoy_parser = re.compile('End of Year Lists')
try:
with open('list_dict.txt', 'rb') as ifile:
list_dict = load(ifile)
except:
list_dict = {}
try:
with open('eoy_dict.txt', 'rb') as ifile:
eoy_dict = load(ifile)
except:
eoy_dict = {}
for i in range(options['begin'], options['end']):
r = get('http://www.acclaimedmusic.net/Current/S{index}.htm'.format(index=i))
if r.status_code == 404:
continue
soup = BeautifulSoup(r.text)
artist = song_parser.match(soup.find('caption').text.strip()).group('artist')
title = song_parser.match(soup.find('caption').text.strip()).group('title')
print("Importing data for {title} by {artist}".format(title=title, artist=artist))
artists_models, featured_models = get_or_create_artists(artist)
song = fuzzy_get_or_create_song(title, artists_models, featured_models)
entries = [entry.text.strip() for entry in soup.findAll('tr')]
all_time = True
for entry in entries:
if all_time and eoy_parser.match(entry):
all_time = False
continue
groups = list_parser.match(entry)
if not groups:
continue
try:
rank = int(groups.group('rank'))
except:
rank = 0
if all_time:
if groups.group('list_name') not in list_dict:
org = fuzzy_get_or_create_ranking_org(groups.group('list_name'))
begin = int(input("What is the first year covered by the list? "))
end = int(input("What is the last year covered by the list? "))
list_dict[groups.group('list_name')] = RankingList.objects.get_or_create(organization=org, begin_year=begin, end_year=end)[0]
if org.name == 'Q':
continue
ranking_list = list_dict[groups.group('list_name')]
if ranking_list.organization.name == 'Q':
continue
with open('list_dict.txt', 'wb') as ofile:
dump(list_dict, ofile)
else:
if groups.group('list_name') not in eoy_dict:
eoy_dict[groups.group('list_name')] = fuzzy_get_or_create_ranking_org(groups.group('list_name'))
org = eoy_dict[groups.group('list_name')]
year = song.year
if org.name == 'Q':
continue
ranking_list = RankingList.objects.get_or_create(organization=org, begin_year=year, end_year=year)[0]
with open('eoy_dict.txt', 'wb') as ofile:
dump(eoy_dict, ofile)
if not SongRanking.objects.filter(ranking_list=ranking_list, song=song).exists():
sr = SongRanking.objects.get_or_create(rank=rank, ranking_list=ranking_list, song=song)
if sr[1] is False:
print('Already exists')
else:
print("\tAdded {rank} to {list}".format(rank=rank, list=ranking_list))
with open('list_dict.txt', 'wb') as ofile:
dump(list_dict, ofile)
with open('eoy_dict.txt', 'wb') as ofile:
dump(eoy_dict, ofile)
<file_sep>/songs/utils.py
from fuzzywuzzy import fuzz, process
from operator import attrgetter, itemgetter
from .models import Artist, Song, RankingOrganization
def fuzzy_get_or_create_ranking_org(ranking_org_name):
print("Fuzzy match or creating for {org}".format(org=ranking_org_name))
organizations = RankingOrganization.objects.all().values_list('name')
for match in ((match[0][0], match[1]) for match in sorted(process.extractBests(ranking_org_name, organizations, processor=itemgetter(0), scorer=fuzz.WRatio, score_cutoff=50, limit=20), key=itemgetter(1), reverse=True)):
if match[1] > 90:
return RankingOrganization.objects.get(name=match[0])
else:
if input("\tMatch to {org_name}? ".format(org_name=match[0])) in ['y', 'Y']:
return RankingOrganization.objects.get(name=match[0])
ranking_org_name = input("What is the name of the organization matching {org}? ".format(org=ranking_org_name))
prestige = input("Creating {org}, please set their prestige (0.0-5.0): ".format(org=ranking_org_name))
return RankingOrganization.objects.create(name=ranking_org_name, prestige=prestige)
def get_or_create_artists(artist):
artists, featured_artists = split_featured_artists(artist)
artists_models = fuzzy_get_or_create_artists(artists)
featured_models = None
if featured_artists is not None:
featured_models = fuzzy_get_or_create_artists(featured_artists)
return artists_models, featured_models
def split_featured_artists(artists):
feature_strings = [' featuring ', ' feat ', ' Feat ', ' Feat. ', ', Feat. ', ', feat. ', ' feat. ', ' Featuring ', ' Ft ', ' ft ']
for split_str in feature_strings:
try:
main_artists, featuring = artists.split(split_str)
return main_artists, featuring
except ValueError:
continue
return artists, None
def fuzzy_match_artist(artist, score_cutoff=88):
artist_matches = sorted(((match[0][0], match[1]) for match in process.extractBests(artist, Artist.objects.all().values_list('name'), processor=itemgetter(0), scorer=fuzz.WRatio, score_cutoff=score_cutoff)), key=itemgetter(1), reverse=True)
for match in artist_matches:
if match[1] > 94:
print("MATCHING ARTIST {artist} to {match}".format(artist=artist, match=match[0]))
return Artist.objects.get(name=match[0])
else:
accept = input("\tMatch {artist} to {match}? ".format(artist=artist, match=match[0]))
if accept in ['x', 'b']:
break
elif accept in ['y', 'Y']:
return Artist.objects.get(name=match[0])
return None
def fuzzy_get_or_create_artist(artist, score_cutoff=88, create=True):
match = fuzzy_match_artist(artist, score_cutoff=score_cutoff)
if match is not None:
return match
if create:
return Artist.objects.create(name=artist)
else:
accept = input("\tCreate {artist}? ".format(artist=artist))
if accept in ['y', 'Y']:
return Artist.objects.create(name=artist)
elif accept != '':
return Artist.objects.create(name=accept)
return None
def fuzzy_get_or_create_artists(artists_str):
artists = artists_str
match = fuzzy_match_artist(artists, score_cutoff=94)
if match:
print("Matching to {name}".format(name=match.name))
return [match]
artists = artists.split(', ')
if artists[-1][:4] == 'and ':
artists[-1] = artists[-1][4:]
else:
last_two_artists = artists[-1].split(' and ')
if len(last_two_artists) == 1:
last_two_artists = artists[-1].split(' & ')
if len(last_two_artists) == 1:
last_two_artists = artists[-1].split(' With ')
if len(last_two_artists) == 1:
last_two_artists = artists[-1].split(' with ')
if len(last_two_artists) == 2:
artists.extend(last_two_artists)
del artists[-3]
artists_models = []
for artist in artists:
artist_model = fuzzy_get_or_create_artist(artist, create=(len(artists) == 1))
if artist_model is not None:
artists_models.append(artist_model)
if len(artists_models) == 0:
artists_models = [fuzzy_get_or_create_artist(artists_str, score_cutoff=75, create=True)]
return artists_models
def fuzzy_get_or_create_song(title, artists, featured_artists, year=None):
song_matches = sorted(process.extractBests(title, Song.objects.filter(artists__in=artists), processor=attrgetter('title'), scorer=fuzz.WRatio, score_cutoff=88), key=itemgetter(1), reverse=True)
matched_song = None
for (match, score) in song_matches:
if score > 90 and (score == 100 or year == match.year):
matched_song = Song.objects.filter(title=match.title, artists__in=artists, year=match.year).first()
break
else:
if input("\tMatch {song} to {match}? ".format(song=title, match=match.title)) in ['y', 'Y']:
matched_song = Song.objects.filter(title=match.title, artists__in=artists, year=match.year).first()
break
if matched_song is None:
if year is None:
year = int(input("What year did this song peak? "))
matched_song = Song.objects.create(title=title, year=year)
for artist in artists:
if artist not in matched_song.artists.all():
matched_song.artists.add(artist)
if featured_artists is not None:
for featuring in featured_artists:
if featuring not in matched_song.featuring.all():
matched_song.featuring.add(featuring)
matched_song.save()
return matched_song
<file_sep>/songs/management/commands/convert_artists.py
from django.core.management.base import BaseCommand
from songs.models import Artist, SongRanking
from songs.utils import fuzzy_get_or_create_song, fuzzy_get_or_create_artist
class Command(BaseCommand):
help = 'Clean featured and duet artists in database'
def handle(self, *args, **options):
artists = Artist.objects.filter(name__contains=' vs ')
for artist in artists:
print("Splitting {artist}".format(artist=artist))
song = artist.song_set.first()
song_title = song.title
artist_list = artist.name.split(' vs ')
proceed = input("Split {song}? ".format(song=song))
try:
if proceed in ['y', 'Y']:
song.title = "EDITTING"
song.save()
artists_models = []
for artist in artist_list:
artists_models.append(fuzzy_get_or_create_artist(artist))
new_song = fuzzy_get_or_create_song(song_title, artists_models, artists_models[1:], song.year)
rank = song.songranking_set.first().rank
rl = song.songranking_set.first().ranking_list
SongRanking.objects.create(rank=rank, ranking_list=rl, song=new_song)
song.artists.all().delete()
song.delete()
except:
song.title = song_title
song.save()
<file_sep>/songs/models.py
from __future__ import unicode_literals
from django.db import models
from django.utils.functional import cached_property
class Artist(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return '{name}'.format(name=self.name)
class Song(models.Model):
title = models.CharField(max_length=255)
artists = models.ManyToManyField(Artist)
featuring = models.ManyToManyField(Artist, related_name='featured_on')
year = models.PositiveSmallIntegerField(null=True, blank=True)
def __str__(self):
artists = list(self.artists.all())
artist_name = ''
if len(artists) >= 1:
artist_name += artists[0].name
if len(artists) >= 2:
for artist in artists[1:-1]:
artist_name += ", {artist}".format(artist=artist.name)
artist_name += " and {artist}".format(artist=artists[-1].name)
featured_artists = list(self.featuring.all())
if len(featured_artists) >= 1:
artist_name += " featuring {featured}".format(featured=featured_artists[0].name)
if len(featured_artists) >= 2:
for artist in featured_artists[1:-1]:
artist_name += ", {featured}".format(featured=artist.name)
artist_name += " and {featured}".format(featured=featured_artists[-1].name)
return '"{title}" by {artist} ({year})'.format(title=self.title, artist=artist_name, year=self.year)
class RankingOrganization(models.Model):
name = models.CharField(max_length=255)
prestige = models.FloatField(default=1.0)
def __str__(self):
return '{name}'.format(name=self.name)
def tri_solve(x):
return -.5 + (.25 + 2*x)**.5
class RankingList(models.Model):
organization = models.ForeignKey(RankingOrganization)
begin_year = models.PositiveSmallIntegerField()
end_year = models.PositiveSmallIntegerField()
url = models.URLField(null=True, blank=True)
class Meta:
unique_together = ('organization', 'begin_year', 'end_year')
def __str__(self):
if self.begin_year == self.end_year:
return '{organization} Best Songs of {year}'.format(organization=self.organization, year=self.begin_year)
else:
return '{organization} Best Songs of {begin_year}-{end_year}'.format(organization=self.organization, begin_year=self.begin_year, end_year=self.end_year)
@cached_property
def song_base_size(self):
return Song.objects.filter(year__gte=self.begin_year, year__lte=self.end_year).count()
@cached_property
def score_base(self):
return tri_solve(self.song_base_size)
class SongRanking(models.Model):
song = models.ForeignKey(Song)
ranking_list = models.ForeignKey(RankingList)
rank = models.PositiveSmallIntegerField()
url = models.URLField(null=True, blank=True)
description = models.TextField(null=True, blank=True)
class Meta:
unique_together = ('song', 'ranking_list')
def __str__(self):
return '{rank}. {song}'.format(rank=self.rank, song=self.song)
@cached_property
def score(self):
return self.ranking_list.score_base - tri_solve(self.rank)
<file_sep>/songs/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-13 08:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Artist',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='RankingList',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('begin_year', models.PositiveSmallIntegerField()),
('end_year', models.PositiveSmallIntegerField()),
('url', models.URLField(blank=True, null=True)),
],
),
migrations.CreateModel(
name='RankingOrganization',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('prestige', models.FloatField(default=1.0)),
],
),
migrations.CreateModel(
name='Song',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('year', models.PositiveSmallIntegerField(blank=True, null=True)),
('artists', models.ManyToManyField(to='songs.Artist')),
('featuring', models.ManyToManyField(related_name='featured_on', to='songs.Artist')),
],
),
migrations.CreateModel(
name='SongRanking',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rank', models.PositiveSmallIntegerField()),
('url', models.URLField(blank=True, null=True)),
('description', models.TextField(blank=True, null=True)),
('ranking_list', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='songs.RankingList')),
('song', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='songs.Song')),
],
),
migrations.AddField(
model_name='rankinglist',
name='organization',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='songs.RankingOrganization'),
),
migrations.AlterUniqueTogether(
name='songranking',
unique_together=set([('song', 'ranking_list')]),
),
migrations.AlterUniqueTogether(
name='rankinglist',
unique_together=set([('organization', 'begin_year', 'end_year')]),
),
]
|
34c9ca9436e2291662b62e58a15149c28c2a85e7
|
[
"Python"
] | 7
|
Python
|
syting/playlists
|
b9daaabeb8e13b4e42e9a4383b310f759c7c8ff6
|
fdbf81eb7bab7a43390a42c75205e57bb041e1e8
|
refs/heads/master
|
<file_sep>namespace Snake.Models.Parts
{
using System;
public class SnakePart : Part
{
private const char SnakeCharacter = ' ';
private const ConsoleColor DefaultColor = ConsoleColor.DarkCyan;
public SnakePart(int x, int y)
: this(x, y, DefaultColor)
{
}
public SnakePart(int x, int y, ConsoleColor color)
: base(x, y, color)
{
}
public override void Paint()
{
Console.SetCursorPosition(this.X, this.Y);
Console.BackgroundColor = this.Color;
Console.Write(SnakeCharacter);
}
}
}<file_sep>namespace Snake.Models.Parts
{
using System;
using Interfaces;
public abstract class Part : IPosition, IPaintable
{
protected Part()
{
}
protected Part(int x, int y, ConsoleColor color)
{
this.X = x;
this.Y = y;
this.Color = color;
}
public ConsoleColor Color
{
get;
}
public int X
{
get;
set;
}
public int Y
{
get;
set;
}
public abstract void Paint();
}
}<file_sep>namespace Snake.Models.Parts
{
using System;
public class FoodPart : Part
{
private const char FoodCharacter = '*';
private const ConsoleColor DefaultColor = ConsoleColor.Green;
private const ConsoleColor BackgrounColor = ConsoleColor.Black;
private readonly int leftBorder;
private readonly int rightBorder;
private readonly int upBorder;
private readonly int downBorder;
public FoodPart(int leftBorder, int rightBorder, int upBorder, int downBorder)
: this(leftBorder, rightBorder, upBorder, downBorder, DefaultColor)
{
}
public FoodPart(int leftBorder, int rightBorder, int upBorder, int downBorder, ConsoleColor color)
: base(0, 0, color)
{
this.leftBorder = leftBorder;
this.rightBorder = rightBorder;
this.upBorder = upBorder;
this.downBorder = downBorder;
}
public override void Paint()
{
this.X = Utilites.GenerateNumber(this.leftBorder + 1, this.rightBorder - 1);
this.Y = Utilites.GenerateNumber(this.upBorder + 1, this.downBorder - 1);
Console.SetCursorPosition(this.X, this.Y);
Console.BackgroundColor = BackgrounColor;
Console.ForegroundColor = DefaultColor;
Console.Write(FoodCharacter);
}
}
}<file_sep>namespace Snake.Interfaces
{
public interface IPaintable
{
void Paint();
}
}<file_sep>namespace Snake.Models
{
using System;
using Interfaces;
public class Playground : IPaintable
{
private const string Title = "Developer: <NAME>";
private const char BorderCharacter = ' ';
private const ConsoleColor TitleColor = ConsoleColor.Cyan;
private const ConsoleColor BorderColor = ConsoleColor.DarkMagenta;
private readonly int leftBorder;
private readonly int rightBorder;
private readonly int upBorder;
private readonly int downBoder;
public Playground(int leftBorder, int rightBorder, int upBorder, int downBoder)
{
this.leftBorder = leftBorder;
this.rightBorder = rightBorder;
this.upBorder = upBorder;
this.downBoder = downBoder;
}
public void Paint()
{
Console.ForegroundColor = TitleColor;
Console.SetCursorPosition(this.leftBorder, this.upBorder - 1);
Console.Write(Title);
Console.BackgroundColor = BorderColor;
for (var i = this.leftBorder; i <= this.rightBorder; i++)
{
Console.SetCursorPosition(i, this.upBorder);
Console.Write(BorderCharacter);
Console.SetCursorPosition(i, this.downBoder);
Console.Write(BorderCharacter);
}
for (var i = this.upBorder; i <= this.downBoder; i++)
{
Console.SetCursorPosition(this.leftBorder, i);
Console.Write(BorderCharacter);
Console.SetCursorPosition(this.rightBorder, i);
Console.Write(BorderCharacter);
}
}
}
}<file_sep>namespace Snake.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using Enumerations;
using Parts;
public class Snake
{
private const int MinInterval = 100;
private const int MaxInterval = 300;
private const int IntervalDifference = 25;
private const Direction DefaultDirection = Direction.Right;
private const ConsoleColor HeadColor = ConsoleColor.DarkRed;
private readonly int leftBorder;
private readonly int rightBorder;
private readonly int upBorder;
private readonly int downBorder;
private readonly List<SnakePart> body;
private int interval;
public Snake(int leftBorder, int rightBorder, int upBorder, int downBorder)
{
this.leftBorder = leftBorder;
this.rightBorder = rightBorder;
this.upBorder = upBorder;
this.downBorder = downBorder;
this.body = new List<SnakePart>
{
new SnakePart(Utilites.GenerateNumber(this.leftBorder + 1, this.rightBorder - 1),
Utilites.GenerateNumber(this.upBorder + 1, this.downBorder - 1),
HeadColor)
};
this.Interval = MaxInterval;
this.Direction = DefaultDirection;
}
public int Interval
{
get => this.interval;
private set
{
if ((value >= MinInterval) && (value <= MaxInterval))
{
this.interval = value;
}
}
}
public Direction Direction
{
get;
set;
}
public void Move()
{
this.EraseLastPosition();
this.BodyInheritance();
switch (this.Direction)
{
case Direction.Up:
this.body[0]
.Y--;
break;
case Direction.Down:
this.body[0]
.Y++;
break;
case Direction.Left:
this.body[0]
.X--;
break;
case Direction.Right:
this.body[0]
.X++;
break;
}
this.CheckBorder();
for (var i = this.body.Count - 1; i >= 0; i--)
{
this.body[i]
.Paint();
}
}
public bool CheckEatFood(FoodPart food)
{
foreach (var snakePart in this.body)
{
if ((snakePart.X == food.X) && (snakePart.Y == food.Y))
{
this.AddSnakePart();
this.Interval -= IntervalDifference;
return true;
}
}
return false;
}
public void CheckBiteItself(ref bool isGameOver)
{
var head = this.body.First();
foreach (var snakePart in this.body.Skip(1))
{
if ((snakePart.X == head.X) && (snakePart.Y == head.Y))
{
isGameOver = true;
return;
}
}
}
private void AddSnakePart()
{
var last = this.body.Last();
this.body.Add(new SnakePart(last.X, last.Y));
}
private void BodyInheritance()
{
for (var i = this.body.Count - 1; i > 0; i--)
{
this.body[i]
.X = this.body[i - 1]
.X;
this.body[i]
.Y = this.body[i - 1]
.Y;
}
}
private void EraseLastPosition()
{
var lastSnakePart = this.body.Last();
Console.SetCursorPosition(lastSnakePart.X, lastSnakePart.Y);
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(' ');
}
private void CheckBorder()
{
var head = this.body.First();
if (head.X == this.leftBorder)
{
head.X = this.rightBorder - 1;
}
else if (head.X == this.rightBorder)
{
head.X = this.leftBorder + 1;
}
else if (head.Y == this.upBorder)
{
head.Y = this.downBorder - 1;
}
else if (head.Y == this.downBorder)
{
head.Y = this.upBorder + 1;
}
}
}
}<file_sep>namespace Snake
{
using System;
public static class Utilites
{
private static readonly Random Randomizer = new Random();
private static readonly ConsoleColor ExitBackgroundColor = ConsoleColor.Black;
private static readonly ConsoleColor ExitForegroungColor = ConsoleColor.White;
public static int GenerateNumber(int min, int max)
{
return Randomizer.Next(min, max + 1);
}
public static void ConsoleDefaultColors()
{
Console.BackgroundColor = ExitBackgroundColor;
Console.ForegroundColor = ExitForegroungColor;
}
}
}<file_sep>namespace Snake
{
using Core;
public class StartUp
{
private static void Main()
{
new Engine().Run();
}
}
}<file_sep>namespace Snake.Core
{
using System;
using System.Threading;
using Enumerations;
using Models;
using Models.Parts;
public class Engine
{
private const int PlaygroundBorderUp = 2;
private const int PlaygroundBorderDown = 25;
private const int PlaygroundBorderLeft = 5;
private const int PlaygroundBorderRight = 60;
private readonly Playground playground;
private readonly Snake snake;
private readonly FoodPart food;
private bool isGameOver;
public Engine()
{
this.playground = new Playground(PlaygroundBorderLeft,
PlaygroundBorderRight,
PlaygroundBorderUp,
PlaygroundBorderDown);
this.snake = new Snake(PlaygroundBorderLeft,
PlaygroundBorderRight,
PlaygroundBorderUp,
PlaygroundBorderDown);
this.food = new FoodPart(PlaygroundBorderLeft,
PlaygroundBorderRight,
PlaygroundBorderUp,
PlaygroundBorderDown);
this.isGameOver = false;
}
public void Run()
{
this.playground.Paint();
this.food.Paint();
while (!this.isGameOver)
{
this.CheckKey();
this.snake.Move();
if (this.snake.CheckEatFood(this.food))
{
this.food.Paint();
}
else
{
this.snake.CheckBiteItself(ref this.isGameOver);
}
Thread.Sleep(this.snake.Interval);
}
this.Exit();
}
private void CheckKey()
{
while (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.UpArrow:
case ConsoleKey.W:
if ((this.snake.Direction == Direction.Left) || (this.snake.Direction == Direction.Right))
{
this.snake.Direction = Direction.Up;
}
return;
case ConsoleKey.DownArrow:
case ConsoleKey.S:
if ((this.snake.Direction == Direction.Left) || (this.snake.Direction == Direction.Right))
{
this.snake.Direction = Direction.Down;
}
return;
case ConsoleKey.LeftArrow:
case ConsoleKey.A:
if ((this.snake.Direction == Direction.Up) || (this.snake.Direction == Direction.Down))
{
this.snake.Direction = Direction.Left;
}
return;
case ConsoleKey.RightArrow:
case ConsoleKey.D:
if ((this.snake.Direction == Direction.Up) || (this.snake.Direction == Direction.Down))
{
this.snake.Direction = Direction.Right;
}
return;
}
}
}
private void Exit()
{
Utilites.ConsoleDefaultColors();
Console.SetCursorPosition(PlaygroundBorderLeft, PlaygroundBorderDown + 2);
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
}
}<file_sep>namespace Snake.Interfaces
{
public interface IPosition
{
int X
{
get;
set;
}
int Y
{
get;
set;
}
}
}
|
0312481672b05e784996ee768ef0d737e246410b
|
[
"C#"
] | 10
|
C#
|
AdrianYordanov/Snake-CSharp
|
f2a3e4129ecaf261544a7b8321133657ce454a16
|
2cd25a699a225fb8de216b78d7e86829ea1be2c6
|
refs/heads/master
|
<file_sep>package main
import (
"errors"
"flag"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/golang/glog"
"golang.org/x/net/publicsuffix"
"k8s.io/kubernetes/pkg/client/transport"
"k8s.io/client-go/kubernetes"
api "k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/rest"
)
// Don't actually commit the changes to route53 records, just print out what we would have done.
var dryRun bool
var currentRecords map[string]string
func init() {
dryRunStr := os.Getenv("DRY_RUN")
if dryRunStr != "" {
dryRun = true
}
}
func main() {
flag.Parse()
glog.Info("Route53 Update Service")
config, err := rest.InClusterConfig()
if err != nil {
kubernetesService := os.Getenv("KUBERNETES_SERVICE_HOST")
kubernetesServicePort := os.Getenv("KUBERNETES_SERVICE_PORT")
if kubernetesService == "" {
glog.Fatal("Please specify the Kubernetes server via KUBERNETES_SERVICE_HOST")
}
if kubernetesServicePort == "" {
kubernetesServicePort = "443"
}
apiServer := fmt.Sprintf("https://%s:%s", kubernetesService, kubernetesServicePort)
caFilePath := os.Getenv("CA_FILE_PATH")
certFilePath := os.Getenv("CERT_FILE_PATH")
keyFilePath := os.Getenv("KEY_FILE_PATH")
if caFilePath == "" || certFilePath == "" || keyFilePath == "" {
glog.Fatal("You must provide paths for CA, Cert, and Key files")
}
tls := transport.TLSConfig{
CAFile: caFilePath,
CertFile: certFilePath,
KeyFile: keyFilePath,
}
// tlsTransport := transport.New(transport.Config{TLS: tls})
tlsTransport, err := transport.New(&transport.Config{TLS: tls})
if err != nil {
glog.Fatalf("Couldn't set up tls transport: %s", err)
}
config = &rest.Config{
Host: apiServer,
Transport: tlsTransport,
}
}
c, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Fatalf("Failed to make client: %v", err)
}
glog.Infof("Connected to kubernetes @ %s", config.Host)
metadata := ec2metadata.New(session.New())
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: metadata},
})
region := os.Getenv("AWS_DEFAULT_REGION")
if region == "" {
region, err = metadata.Region()
if err != nil {
glog.Fatalf("Unable to retrieve the region from environment or the EC2 instance %v\n", err)
}
}
awsConfig := aws.NewConfig()
awsConfig.WithCredentials(creds)
awsConfig.WithRegion(region)
sess := session.New(awsConfig)
r53Api := route53.New(sess)
if r53Api == nil {
glog.Fatal("Failed to make AWS connection")
}
selector := "dns=route53"
listOptions := api.ListOptions{
LabelSelector: selector,
}
glog.Infof("Starting Service Polling every 30s")
// TODO(ouziel): delete record if necessary
currentRecords = make(map[string]string)
for {
services, err := c.Services(api.NamespaceAll).List(listOptions)
if err != nil {
glog.Fatalf("Failed to list pods: %v", err)
}
glog.Infof("Found %d DNS services in all namespaces with selector %q", len(services.Items), selector)
for i := range services.Items {
s := &services.Items[i]
recordValue, recordType, err := serviceRecord(s)
if err != nil || recordValue == "" {
glog.Warningf("Couldn't find hostname or IP for %s: %s", s.Name, err)
continue
}
annotation, ok := s.ObjectMeta.Annotations["domainName"]
if !ok {
glog.Warningf("Domain name not set for %s", s.Name)
continue
}
domains := strings.Split(annotation, ",")
for j := range domains {
recordName := domains[j]
currentValue, _ := currentRecords[recordName]
if currentValue == recordValue {
glog.Infof("DNS already exists for %s service: %s -> %s", s.Name, recordValue, recordName)
continue
}
glog.Infof("Creating DNS for %s service: %s -> %s", s.Name, recordValue, recordName)
zoneID, err := getDestinationZoneID(r53Api, recordName)
if err != nil {
glog.Warningf("Couldn't find destination zone for %s: %s", recordName, err)
continue
}
if err = updateDNS(r53Api, recordValue, recordType, recordName, zoneID); err != nil {
glog.Warning(err)
continue
}
currentRecords[recordName] = recordValue
glog.Infof("Created dns record set: domain=%s, zoneID=%s", recordName, zoneID)
}
}
time.Sleep(30 * time.Second)
}
}
func getDestinationZoneID(r53Api *route53.Route53, domain string) (string, error) {
zone, err := publicsuffix.EffectiveTLDPlusOne(domain)
if err != nil {
return "", err
}
// Since Route53 returns it with dot at the end when listing zones.
zone += "."
params := &route53.ListHostedZonesByNameInput{
DNSName: aws.String(zone),
}
resp, err := r53Api.ListHostedZonesByName(params)
if err != nil {
return "", err
}
// Does binary search on lexicographically ordered hosted zones slice, in
// order to find the correspondent Route53 zone ID for the given zone name.
l := len(resp.HostedZones)
i := sort.Search(l, func(i int) bool {
return *resp.HostedZones[i].Name == zone
})
var zoneID string
if i < l && *resp.HostedZones[i].Name == zone {
zoneID = strings.Split(*resp.HostedZones[i].Id, "/")[2]
} else {
return "", fmt.Errorf("unable to find hosted zone %q in Route53", zone)
}
return zoneID, nil
}
func serviceRecord(service *api.Service) (string, string, error) {
ingress := service.Status.LoadBalancer.Ingress
if len(ingress) < 1 {
return "", "", errors.New("No ingress defined for ELB")
}
if len(ingress) > 1 {
return "", "", errors.New("Multiple ingress points found for ELB, not supported")
}
if ingress[0].IP != "" {
return ingress[0].IP, "A", nil
}
if ingress[0].Hostname != "" {
return ingress[0].Hostname, "CNAME", nil
}
return "", "", nil
}
func updateDNS(r53Api *route53.Route53, recordValue, recordType, recordName, zoneID string) error {
params := &route53.ChangeResourceRecordSetsInput{
ChangeBatch: &route53.ChangeBatch{ // Required
Changes: []*route53.Change{ // Required
{ // Required
Action: aws.String("UPSERT"), // Required
ResourceRecordSet: &route53.ResourceRecordSet{ // Required
Name: aws.String(recordName), // Required
Type: aws.String(recordType), // Required
TTL: aws.Int64(300),
ResourceRecords: []*route53.ResourceRecord{
{ // Required
Value: aws.String(recordValue), // Required
},
},
},
},
},
Comment: aws.String("Kubernetes Update to Service"),
},
HostedZoneId: aws.String(zoneID), // Required
}
resp, err := r53Api.ChangeResourceRecordSets(params)
glog.Infof("Response: %v", resp)
if err != nil {
return fmt.Errorf("Failed to update record set: %v", err)
}
return nil
}
|
13da4649da6862c67668a742834a052e4efb5891
|
[
"Go"
] | 1
|
Go
|
symbiont-io/route53-kubernetes
|
34c7892898aa0e15e0aa83c41e362cd4153da4a7
|
d80c6b76dd9bb117994031d092803c19411f6e7d
|
refs/heads/master
|
<file_sep>AWS_REGION="us-east-1"
VPC_NAME="VPC_Assignment2"
VPC_CIDR="10.0.0.0/16"
SUBNET_PUBLIC_CIDR1="10.0.1.0/24"
SUBNET_PUBLIC_AZ1="us-east-1a"
SUBNET_PUBLIC_NAME1="10.0.1.0 - us-east-1a"
SUBNET_PRIVATE_CIDR1="10.0.2.0/24"
SUBNET_PRIVATE_AZ1="us-east-1a"
SUBNET_PRIVATE_NAME1="10.0.2.0 - us-east-1a"
SUBNET_PUBLIC_CIDR2="10.0.3.0/24"
SUBNET_PUBLIC_AZ2="us-east-1b"
SUBNET_PUBLIC_NAME2="10.0.3.0 - us-east-1b"
SUBNET_PRIVATE_CIDR2="10.0.4.0/24"
SUBNET_PRIVATE_AZ2="us-east-1b"
SUBNET_PRIVATE_NAME2="10.0.4.0 - us-east-1b"
SUBNET_PUBLIC_CIDR3="10.0.5.0/24"
SUBNET_PUBLIC_AZ3="us-east-1c"
SUBNET_PUBLIC_NAME3="10.0.5.0 - us-east-1c"
SUBNET_PRIVATE_CIDR3="10.0.6.0/24"
SUBNET_PRIVATE_AZ3="us-east-1c"
SUBNET_PRIVATE_NAME3="10.0.6.0 - us-east-1c"
CHECK_FREQUENCY=5
# Create VPC
echo "Creating VPC in preferred region..."
VPC_ID=$(aws ec2 create-vpc \
--cidr-block $VPC_CIDR \
--query 'Vpc.{VpcId:VpcId}' \
--output text \
--region $AWS_REGION)
echo " VPC ID '$VPC_ID' CREATED in '$AWS_REGION' region."
# Add Name tag to VPC
aws ec2 create-tags \
--resources $VPC_ID \
--tags "Key=Name,Value=$VPC_NAME" \
--region $AWS_REGION
echo " VPC ID '$VPC_ID' NAMED as '$VPC_NAME'."
# Create Public Subnet1
echo "Creating Public Subnet..."
SUBNET_PUBLIC_ID=$(aws ec2 create-subnet \
--vpc-id $VPC_ID \
--cidr-block $SUBNET_PUBLIC_CIDR1 \
--availability-zone $SUBNET_PUBLIC_AZ1 \
--query 'Subnet.{SubnetId:SubnetId}' \
--output text \
--region $AWS_REGION)
echo " Subnet ID '$SUBNET_PUBLIC_ID' CREATED in '$SUBNET_PUBLIC_AZ1'" \
"Availability Zone."
# Add Name tag to Public Subnet1
aws ec2 create-tags \
--resources $SUBNET_PUBLIC_ID \
--tags "Key=Name,Value=$SUBNET_PUBLIC_NAME1" \
--region $AWS_REGION
echo " Subnet ID '$SUBNET_PUBLIC_ID' NAMED as" \
"'$SUBNET_PUBLIC_NAME1'."
# Create Private Subnet1
echo "Creating Private Subnet..."
SUBNET_PRIVATE_ID=$(aws ec2 create-subnet \
--vpc-id $VPC_ID \
--cidr-block $SUBNET_PRIVATE_CIDR1 \
--availability-zone $SUBNET_PRIVATE_AZ1 \
--query 'Subnet.{SubnetId:SubnetId}' \
--output text \
--region $AWS_REGION)
echo " Subnet ID '$SUBNET_PRIVATE_ID' CREATED in '$SUBNET_PRIVATE_AZ1'" \
"Availability Zone."
# Add Name tag to Private Subnet1
aws ec2 create-tags \
--resources $SUBNET_PRIVATE_ID \
--tags "Key=Name,Value=$SUBNET_PRIVATE_NAME1" \
--region $AWS_REGION
echo " Subnet ID '$SUBNET_PRIVATE_ID' NAMED as '$SUBNET_PRIVATE_NAME1'."
# Create Public Subnet2
echo "Creating Public Subnet..."
SUBNET_PUBLIC_ID=$(aws ec2 create-subnet \
--vpc-id $VPC_ID \
--cidr-block $SUBNET_PUBLIC_CIDR2 \
--availability-zone $SUBNET_PUBLIC_AZ2 \
--query 'Subnet.{SubnetId:SubnetId}' \
--output text \
--region $AWS_REGION)
echo " Subnet ID '$SUBNET_PUBLIC_ID' CREATED in '$SUBNET_PUBLIC_AZ2'" \
"Availability Zone."
# Add Name tag to Public Subnet2
aws ec2 create-tags \
--resources $SUBNET_PUBLIC_ID \
--tags "Key=Name,Value=$SUBNET_PUBLIC_NAME2" \
--region $AWS_REGION
echo " Subnet ID '$SUBNET_PUBLIC_ID' NAMED as" \
"'$SUBNET_PUBLIC_NAME2'."
# Create Private Subnet2
echo "Creating Private Subnet..."
SUBNET_PRIVATE_ID=$(aws ec2 create-subnet \
--vpc-id $VPC_ID \
--cidr-block $SUBNET_PRIVATE_CIDR2 \
--availability-zone $SUBNET_PRIVATE_AZ2 \
--query 'Subnet.{SubnetId:SubnetId}' \
--output text \
--region $AWS_REGION)
echo " Subnet ID '$SUBNET_PRIVATE_ID' CREATED in '$SUBNET_PRIVATE_AZ2'" \
"Availability Zone."
# Add Name tag to Private Subnet2
aws ec2 create-tags \
--resources $SUBNET_PRIVATE_ID \
--tags "Key=Name,Value=$SUBNET_PRIVATE_NAME2" \
--region $AWS_REGION
echo " Subnet ID '$SUBNET_PRIVATE_ID' NAMED as '$SUBNET_PRIVATE_NAME2'."
# Create Public Subnet3
echo "Creating Public Subnet..."
SUBNET_PUBLIC_ID=$(aws ec2 create-subnet \
--vpc-id $VPC_ID \
--cidr-block $SUBNET_PUBLIC_CIDR3 \
--availability-zone $SUBNET_PUBLIC_AZ3 \
--query 'Subnet.{SubnetId:SubnetId}' \
--output text \
--region $AWS_REGION)
echo " Subnet ID '$SUBNET_PUBLIC_ID' CREATED in '$SUBNET_PUBLIC_AZ3'" \
"Availability Zone."
# Add Name tag to Public Subnet3
aws ec2 create-tags \
--resources $SUBNET_PUBLIC_ID \
--tags "Key=Name,Value=$SUBNET_PUBLIC_NAME3" \
--region $AWS_REGION
echo " Subnet ID '$SUBNET_PUBLIC_ID' NAMED as" \
"'$SUBNET_PUBLIC_NAME3'."
# Create Private Subnet3
echo "Creating Private Subnet..."
SUBNET_PRIVATE_ID=$(aws ec2 create-subnet \
--vpc-id $VPC_ID \
--cidr-block $SUBNET_PRIVATE_CIDR3 \
--availability-zone $SUBNET_PRIVATE_AZ3 \
--query 'Subnet.{SubnetId:SubnetId}' \
--output text \
--region $AWS_REGION)
echo " Subnet ID '$SUBNET_PRIVATE_ID' CREATED in '$SUBNET_PRIVATE_AZ3'" \
"Availability Zone."
# Add Name tag to Private Subnet3
aws ec2 create-tags \
--resources $SUBNET_PRIVATE_ID \
--tags "Key=Name,Value=$SUBNET_PRIVATE_NAME3" \
--region $AWS_REGION
echo " Subnet ID '$SUBNET_PRIVATE_ID' NAMED as '$SUBNET_PRIVATE_NAME3'."
# Create Internet gateway
echo "Creating Internet Gateway..."
IGW_ID=$(aws ec2 create-internet-gateway \
--query 'InternetGateway.{InternetGatewayId:InternetGatewayId}' \
--output text \
--region $AWS_REGION)
echo " Internet Gateway ID '$IGW_ID' CREATED."
# Attach Internet gateway to your VPC
aws ec2 attach-internet-gateway \
--vpc-id $VPC_ID \
--internet-gateway-id $IGW_ID \
--region $AWS_REGION
echo " Internet Gateway ID '$IGW_ID' ATTACHED to VPC ID '$VPC_ID'."
# Create Route Table
echo "Creating Route Table..."
ROUTE_TABLE_ID=$(aws ec2 create-route-table \
--vpc-id $VPC_ID \
--query 'RouteTable.{RouteTableId:RouteTableId}' \
--output text \
--region $AWS_REGION)
echo " Route Table ID '$ROUTE_TABLE_ID' CREATED."
# Create route to Internet Gateway
RESULT=$(aws ec2 create-route \
--route-table-id $ROUTE_TABLE_ID \
--destination-cidr-block 0.0.0.0/0 \
--gateway-id $IGW_ID \
--region $AWS_REGION)
echo " Route to '0.0.0.0/0' via Internet Gateway ID '$IGW_ID' ADDED to" \
"Route Table ID '$ROUTE_TABLE_ID'."
# Associate Public Subnet with Route Table
RESULT=$(aws ec2 associate-route-table \
--subnet-id $SUBNET_PUBLIC_ID \
--route-table-id $ROUTE_TABLE_ID \
--region $AWS_REGION)
echo " Public Subnet ID '$SUBNET_PUBLIC_ID' ASSOCIATED with Route Table ID" \
"'$ROUTE_TABLE_ID'."
# Enable Auto-assign Public IP on Public Subnet
aws ec2 modify-subnet-attribute \
--subnet-id $SUBNET_PUBLIC_ID \
--map-public-ip-on-launch \
--region $AWS_REGION
echo " 'Auto-assign Public IP' ENABLED on Public Subnet ID" \
"'$SUBNET_PUBLIC_ID'."
# Allocate Elastic IP Address for NAT Gateway
echo "Creating NAT Gateway..."
EIP_ALLOC_ID=$(aws ec2 allocate-address \
--domain vpc \
--query '{AllocationId:AllocationId}' \
--output text \
--region $AWS_REGION)
echo " Elastic IP address ID '$EIP_ALLOC_ID' ALLOCATED."
# Create NAT Gateway
NAT_GW_ID=$(aws ec2 create-nat-gateway \
--subnet-id $SUBNET_PUBLIC_ID \
--allocation-id $EIP_ALLOC_ID \
--query 'NatGateway.{NatGatewayId:NatGatewayId}' \
--output text \
--region $AWS_REGION)
FORMATTED_MSG="Creating NAT Gateway ID '$NAT_GW_ID' and waiting for it to "
FORMATTED_MSG+="become available.\n Please BE PATIENT as this can take some "
FORMATTED_MSG+="time to complete.\n ......\n"
printf " $FORMATTED_MSG"
FORMATTED_MSG="STATUS: %s - %02dh:%02dm:%02ds elapsed while waiting for NAT "
FORMATTED_MSG+="Gateway to become available..."
SECONDS=0
LAST_CHECK=0
STATE='PENDING'
until [[ $STATE == 'AVAILABLE' ]]; do
INTERVAL=$SECONDS-$LAST_CHECK
if [[ $INTERVAL -ge $CHECK_FREQUENCY ]]; then
STATE=$(aws ec2 describe-nat-gateways \
--nat-gateway-ids $NAT_GW_ID \
--query 'NatGateways[*].{State:State}' \
--output text \
--region $AWS_REGION)
STATE=$(echo $STATE | tr '[:lower:]' '[:upper:]')
LAST_CHECK=$SECONDS
fi
SECS=$SECONDS
STATUS_MSG=$(printf "$FORMATTED_MSG" \
$STATE $(($SECS/3600)) $(($SECS%3600/60)) $(($SECS%60)))
printf " $STATUS_MSG\033[0K\r"
sleep 1
done
printf "\n ......\n NAT Gateway ID '$NAT_GW_ID' is now AVAILABLE.\n"
# Create route to NAT Gateway
MAIN_ROUTE_TABLE_ID=$(aws ec2 describe-route-tables \
--filters Name=vpc-id,Values=$VPC_ID Name=association.main,Values=true \
--query 'RouteTables[*].{RouteTableId:RouteTableId}' \
--output text \
--region $AWS_REGION)
echo " Main Route Table ID is '$MAIN_ROUTE_TABLE_ID'."
RESULT=$(aws ec2 create-route \
--route-table-id $MAIN_ROUTE_TABLE_ID \
--destination-cidr-block 0.0.0.0/0 \
--gateway-id $NAT_GW_ID \
--region $AWS_REGION)
echo " Route to '0.0.0.0/0' via NAT Gateway with ID '$NAT_GW_ID' ADDED to" \
"Route Table ID '$MAIN_ROUTE_TABLE_ID'."
echo "COMPLETED"
|
2aa1c345475a3add5e899aca7da7a77b73a64013
|
[
"Shell"
] | 1
|
Shell
|
HarshK333/aws_assignment_2
|
4f0e064064450f2f87b3fed07779d0be391eb708
|
4ba800ec46a78396677e7bcf88c9fd1566ecbbf5
|
refs/heads/master
|
<file_sep>#include<iostream>
#include "math_tools.h"
#include "display_tools.h"
using namespace std;
int main() {
//Vector zeroes_vector;
Matrix example_matrix;
//zeroes(zeroes_vector,5);
zeroes(example_matrix,3);
//showVector(zeroes_vector);
showMatrix(example_matrix);
example_matrix.at(0).at(0)=2;
example_matrix.at(0).at(1)=2;
example_matrix.at(0).at(2)=3;
example_matrix.at(1).at(0)=4;
example_matrix.at(1).at(1)=5;
example_matrix.at(1).at(2)=6;
example_matrix.at(2).at(0)=7;
example_matrix.at(2).at(1)=8;
example_matrix.at(2).at(2)=9;
cout<<endl;
showMatrix(example_matrix);
cout<<endl;
cout<<"determinante: "<<determinant(example_matrix);
return 0;
}
|
eb73a332a8e643accb4b2e6c0491380f399b3a4c
|
[
"C++"
] | 1
|
C++
|
alexiessaenz/tarea1simu
|
07c1581566cf9b7b235da46d5e8e8ff2fbc59f52
|
a150bf9791bffaadfe2b5d81da5a3bf65db97626
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CuadrosTexto
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NombreTextBox_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.F1)
{
if (NombreClienteTextBlock.Visibility == Visibility.Visible)
{
NombreClienteTextBlock.Visibility = Visibility.Hidden;
}
else
{
NombreClienteTextBlock.Visibility = Visibility.Visible;
}
}
}
private void ApellidoTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.F1)
{
if (ApellidoClienteTextBlock.Visibility == Visibility.Visible)
{
ApellidoClienteTextBlock.Visibility = Visibility.Hidden;
}
else
{
ApellidoClienteTextBlock.Visibility = Visibility.Visible;
}
}
}
private void EdadTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.F2)
{
if (Int32.TryParse(CasillaEdadTextBox.Text, out _))
{
EdadClienteTextBlock.Visibility = Visibility.Hidden;
}
else
{
EdadClienteTextBlock.Visibility = Visibility.Visible;
}
}
}
}
}
|
fe5659ba11ceb78092329922e9c673131d7db0ca
|
[
"C#"
] | 1
|
C#
|
Deluxeluisete/CuadrosTexto
|
c5027be48b0fff4548b5d9c927ca5c852a6671a3
|
15608135d8d765da59faae4d9d6724d2dd7d6dff
|
refs/heads/master
|
<file_sep>package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"mime/multipart"
"net/http"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func init() {
log.SetFormatter(&log.TextFormatter{})
log.SetLevel(log.InfoLevel)
}
func main() {
err := run()
if err != nil {
log.Warn(err)
os.Exit(1)
}
os.Exit(0)
}
func run() error {
if len(os.Args) < 3 {
return errors.New("引数がおかしい")
}
p := os.Args[1]
buf := bytes.Buffer{}
w := multipart.NewWriter(&buf)
_, filename := filepath.Split(p)
ferr := w.WriteField("filename", filename)
if ferr != nil {
return ferr
}
w.Close() // 閉じることでPOSTデータが出来上がる模様
res, err := http.Post("http://127.0.0.1:10616/task/add", w.FormDataContentType(), &buf)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", res.Status)
}
var data interface{}
if err = json.Unmarshal([]byte(os.Args[2]), &data); err != nil {
return err
}
log.WithField("data", data).Info("タスク追加に成功しました。")
return nil
}
|
9ba29d01645ac7dd28058e7e06d1f157d86f6f07
|
[
"Go"
] | 1
|
Go
|
tanaton/himawari-add
|
140b0b4c82718c71b6eedf40050b365e4f347d84
|
273629f54a1bbfd0d2f1fcfd1234911f6cc10d9f
|
refs/heads/master
|
<file_sep>package it.alfasoft.francesca.dao;
import hibernateUtil.HibernateUtil;
import it.alfasoft.francesca.bean.Ristorante;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class RistoranteDao {
public boolean aggiungiRistorante(Ristorante r)
{
boolean b=false;
Session session =HibernateUtil.openSession();
Transaction tx=null;
try{
tx=session.getTransaction();
tx.begin();
session.persist(r);
b=true;
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return b;
}
public Ristorante trovaRistorante(String nome)
{
Ristorante r=null;
Session session =HibernateUtil.openSession();
Transaction tx=null;
try{
tx=session.getTransaction();
tx.begin();
Query query=session.createQuery("from Ristorante where nome=:x1");
query.setString("x1", nome);
r=(Ristorante) query.uniqueResult();
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return r;
}
public Ristorante trovaRistoranteConId(long id)
{
Ristorante r=null;
Session session =HibernateUtil.openSession();
Transaction tx=null;
try{
tx=session.getTransaction();
tx.begin();
Query query=session.createQuery("from Ristorante where id_Ristorante=:x1");
query.setLong("x1", id);
r=(Ristorante) query.uniqueResult();
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return r;
}
public boolean aggiornaRistorante(Ristorante r)
{
boolean result=false;
Session session =HibernateUtil.openSession();
Transaction tx=null;
try{
tx=session.getTransaction();
tx.begin();
session.update(r);
result=true;
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return result;
}
public boolean eliminaRistorante(Ristorante r)
{
boolean result=false;
Session session =HibernateUtil.openSession();
Transaction tx=null;
try{
tx=session.getTransaction();
tx.begin();
session.delete(r);
result=true;
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return result;
}
}
<file_sep>package it.alfasoft.francesca.servizi;
public class RistoranteController {
}
<file_sep>package it.alfasoft.francesca.bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Embeddable
@ManagedBean
public class Prodotto implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String nomeProdotto;
private double prezzo;
public Prodotto() {
}
public Prodotto(String nomeProdotto, double prezzo) {
this.nomeProdotto = nomeProdotto;
this.prezzo = prezzo;
}
public String getNomeProdotto() {
return nomeProdotto;
}
public void setNomeProdotto(String nomeProdotto) {
this.nomeProdotto = nomeProdotto;
}
public double getPrezzo() {
return prezzo;
}
public void setPrezzo(double prezzo) {
this.prezzo = prezzo;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
<file_sep>package it.alfasoft.francesca.servizi;
public class ProdottoController {
}
<file_sep>import it.alfasoft.francesca.bean.Prodotto;
import it.alfasoft.francesca.bean.Ristorante;
import it.alfasoft.francesca.dao.RistoranteDao;
public class MainProva {
public static void main(String[] args) {
Ristorante r= new Ristorante("Ristorante");
Prodotto p=new Prodotto("<NAME>",3.50);
r.addPrimo(p);
RistoranteDao rdao= new RistoranteDao();
rdao.aggiornaRistorante(r);
}
}
|
2bfdef573b4b2402aa7f6cb8bd02d7ed0c1fb514
|
[
"Java"
] | 5
|
Java
|
francesca2/Ristorante
|
8c71c70adcb8f65edf34bae5df9298c1ba1311b1
|
d494580a1d0c56f35769e2bafd4a2df6fbcf6ab4
|
refs/heads/master
|
<repo_name>filiphosko/pdsnd-bikeshare-project<file_sep>/constants.py
DATA_DIR = "data"
CITY_DATA = {
"chicago": "chicago.csv",
"new york city": "new_york_city.csv",
"washington": "washington.csv",
}
MONTHS = ["january", "february", "march", "april", "may", "june"]
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
GENERATIONS = [
((2000, 0), "Generation Z"),
((1980, 1999), "Generation Y (Millenials)"),
((1965, 1979), "Generation X"),
((1946, 1964), "Baby Boomers"),
((1925, 1945), "the Silent Generation"),
((1900, 1924), "the G.I. Generation"),
((0, 1899), "born before year 1900"),
]
<file_sep>/bikeshare.py
import streamlit as st
import time
import pandas as pd
import altair as alt
import plotly.express as px
from constants import *
def main():
st.title("Bikeshare dataset: insights")
st.markdown("Hope you'll enjoy going through all these visualizations 😎")
# Filter for cities
cities = list(CITY_DATA.keys())
city = st.selectbox(
label="Choose your city", options=cities, format_func=format_label
)
# Load the CSV data and create additional columns
df = prepare_data(city)
# Create visualizations for 'general overview' stats
st.markdown("### Raw data for {} bike trips".format(city.title()))
number_of_rows = st.number_input(
label="Please select the number of rows you'd like to see",
min_value=5,
max_value=len(df.index),
value=5,
step=5,
)
st.write(df.iloc[0:number_of_rows])
missing_values = df.isnull().sum().where(lambda x: x > 0).dropna()
if not missing_values.empty:
st.write(
"### Missing values per column",
missing_values.sort_values(ascending=False).rename(
"Number of missing values"
),
)
# Visualize data about trips before month/day filters are applied
trip_duration_per_month = df[["Trip Duration", "Month"]].groupby("Month").sum()
trip_duration_per_month_df = trip_duration_per_month.reset_index()
trip_duration_per_month_df["Trip Duration"] = pd.Series(
map(
lambda x: round(x / (3600 * 24), 2),
trip_duration_per_month_df["Trip Duration"],
)
)
st.markdown("### Total monthly trip duration")
trip_duration_per_month_chart = (
alt.Chart(trip_duration_per_month_df)
.mark_bar()
.encode(
x=alt.X("Month:O", title="Month number"),
y=alt.Y("Trip Duration:Q", title="Trip Duration (days)"),
)
)
st.altair_chart(trip_duration_per_month_chart, use_container_width=True)
if "Generation" in df.columns:
trip_duration_per_generation = (
df[["Trip Duration", "Generation"]].groupby("Generation").sum()
)
trip_duration_per_generation_df = trip_duration_per_generation.reset_index()
st.markdown("### Total trip duration per generation")
trip_duration_per_generation_chart = px.pie(
trip_duration_per_generation_df, values="Trip Duration", names="Generation"
)
st.plotly_chart(trip_duration_per_generation_chart, use_container_width=True)
trip_count_per_generation = df["Generation"].value_counts()
trip_count_per_generation_df = trip_count_per_generation.reset_index()
st.markdown("### Number of trips per generation")
trip_count_per_generation_chart = (
alt.Chart(
trip_count_per_generation_df.rename(
columns={"index": "Generation", "Generation": "Number of trips"}
)
)
.mark_bar()
.encode(x=alt.X("Generation:O", sort="y"), y=alt.Y("Number of trips:Q"),)
)
st.altair_chart(trip_count_per_generation_chart, use_container_width=True)
# Create and apply month/day filters
st.markdown("## Month/day filters")
months = st.multiselect(
label="Choose a month (if left unselected, it will get all months)",
options=MONTHS,
default=MONTHS,
format_func=format_label,
)
days = st.multiselect(
label="Choose a day (if left unselected, it will get all days)",
options=DAYS,
default=DAYS,
format_func=format_label,
)
# Filter by month if applicable
if months and len(months) != len(MONTHS):
month_numbers = map(lambda x: MONTHS.index(x) + 1, months)
df = df[df["Month"].isin(month_numbers)]
# Filter by day of week if applicable
if days and len(days) != len(DAYS):
day_numbers = map(lambda x: DAYS.index(x) + 1, days)
df = df[df["Day of Week"].isin(day_numbers)]
# Most common dates and times
st.markdown("### Most frequent times of travel")
# Most common month
st.markdown(
"* The most common month is: {}".format(
MONTHS[df["Month"].value_counts().idxmax() - 1].title()
)
)
# Most common day of week
st.markdown(
"* The most common day of week is: {}".format(
DAYS[df["Day of Week"].value_counts().idxmax() - 1].title()
)
)
# Most common start hour
st.markdown(
"* The most common start hour is: {}".format(
df["Start Hour"].value_counts().idxmax()
)
)
# Trip duration stats
st.markdown("### Trip duration")
st.markdown(
"* The total travel time is: {} hours".format(
round(df["Trip Duration"].sum() / 3600, 2)
)
)
st.markdown(
"* The average (mean) travel time is: {} minutes".format(
round(df["Trip Duration"].mean() / 60, 2)
)
)
# Most frequent start stations chart
start_station_counts = df["Start Station"].value_counts()
most_frequent_start_stations = start_station_counts.head()
most_frequent_start_stations_df = (
most_frequent_start_stations.to_frame().reset_index()
)
most_frequent_start_stations_chart_data = most_frequent_start_stations_df.rename(
columns={"index": "Start Station", "Start Station": "Number of Trips"}
)
st.markdown("### Most commonly used start stations")
most_frequent_start_stations_chart = (
alt.Chart(most_frequent_start_stations_chart_data)
.mark_bar()
.encode(x="Number of Trips", y=alt.Y("Start Station", sort="-x"))
.properties(width="container", height=200)
)
st.altair_chart(most_frequent_start_stations_chart, use_container_width=True)
# Most frequent end stations chart
start_station_counts = df["End Station"].value_counts()
most_frequent_start_stations = start_station_counts.head()
most_frequent_start_stations_df = (
most_frequent_start_stations.to_frame().reset_index()
)
most_frequent_start_stations_chart_data = most_frequent_start_stations_df.rename(
columns={"index": "End Station", "End Station": "Number of Trips"}
)
st.markdown("### Most commonly used end stations")
most_frequent_start_stations_chart = (
alt.Chart(most_frequent_start_stations_chart_data)
.mark_bar()
.encode(x="Number of Trips", y=alt.Y("End Station", sort="-x"))
.properties(width="container", height=200)
)
st.altair_chart(most_frequent_start_stations_chart, use_container_width=True)
st.markdown("### Most common combination of start and end stations")
st.write(
df.groupby(["Start Station", "End Station"])
.size()
.sort_values(ascending=False)
.head()
.to_frame()
.reset_index()
.rename(columns={0: "Number of Trips"})
)
# User stats (by Gender and Birth Year only if applicable)
st.write("### Count of users per user type", df["User Type"].value_counts())
if "Gender" in df.columns:
st.write("### Count of users per gender", df["Gender"].value_counts())
if "Birth Year" in df.columns:
st.markdown("### User stats by birth")
st.markdown(
"* The earliest year of birth is: {}".format(int(df["Birth Year"].min()))
)
st.markdown(
"* The most recent year of birth is: {}".format(int(df["Birth Year"].min()))
)
st.markdown(
"* The most common year of birth is: {}".format(
int(df["Birth Year"].value_counts().idxmax())
)
)
def load_data(city):
try:
df = pd.read_csv(DATA_DIR + "/" + CITY_DATA[city.lower()])
return df
except FileNotFoundError as e:
st.error("The CSV file for the city you selected is not available.")
def create_additional_columns(df):
# From Start Time
df["Start Time"] = pd.to_datetime(df["Start Time"])
df["Month"] = df["Start Time"].dt.month
df["Day of Week"] = df["Start Time"].dt.dayofweek
df["Start Hour"] = df["Start Time"].dt.hour
if "Birth Year" in df.columns:
generations = list()
# Adds a new computed column (note: probably not very efficient and can be optimized?)
for index, birth_year in df["Birth Year"].iteritems():
for generation in GENERATIONS:
years, generation_name = generation
min_year, max_year = years
if max_year and min_year:
if birth_year >= min_year and birth_year <= max_year:
generations.append((index, generation_name))
elif not min_year:
if birth_year <= max_year:
generations.append((index, generation_name))
else:
if birth_year >= min_year:
generations.append((index, generation_name))
df["Generation"] = pd.Series(
data=map(lambda x: x[1], generations),
index=map(lambda x: x[0], generations),
)
return df
@st.cache
def prepare_data(city):
df = load_data(city)
df = create_additional_columns(df)
return df
def format_label(item):
return item.title()
if __name__ == "__main__":
main()
<file_sep>/README.md
# Bikeshare project for Udacity's Programming for Data Science with Python
Created on May 21, 2020
## What's this repository about?
The purpose is to showcase the final Python project of this Nanodegree that focuses mostly on Pythons's libraries that are frequently used in the data science domain (here it's especially Pandas).
Except Pandas I also used the Streamlit framework for data visualization https://www.streamlit.io/. With it I was able to put together a basic Python app with charts and filtering based on select boxes - from the UX standpoint I liked it much more than just having the user to interact with the shell environment 😉
## So we can look at some charts? That's exciting!
Yep, I can feel your excitement. The app was built to visualize data provided by the US bike sharing provider Motivate https://www.motivateco.com. It was tested using a small subset of data for three cities: Chicago, New York and Washington.
The dataset contained these columns:
Start Time, End Time, Trip Duration (in seconds), Start Station, End Station, User Type, Gender (only for Chicago and New York), Birth Year (only for Chicago and New York)
As you can see there's plenty of information to look into 😎 So let's dive in!
## Awesome, can't wait. But how can I run this stuff?
No worries, it's pretty easy. You just have to install the Python libraries that are the dependencies for this project - you can see them at the top of `bikeshare.py`. After you'll have them installed in your Python environment, just run `streamlit run bikeshare.py` and you should be good to go!
## Inspiration aka resources
I had to read a bunch of articles, go through documentation and sometimes wander into coding oriented forums to put this all together since I never worked with Streamlit before (with Pandas too, and Python in general). These are the resources that helped the most:
Streamlit docs
https://docs.streamlit.io/en/latest/api.html
Cool guide into Streamlit with examples
https://analyticsindiamag.com/a-beginners-guide-to-streamlit-convert-python-code-into-an-app/
Another cool article about Streamlit (with examples)
https://towardsdatascience.com/quickly-build-and-deploy-an-application-with-streamlit-988ca08c7e83
Plotly knows charts (I used the Pie)
https://plotly.com/python/pie-charts/
Filtering a Pandas DataFrame (very handy)
https://www.listendata.com/2019/07/how-to-filter-pandas-dataframe.html
|
5bae3647c95d6319b86a2e1b1eb655c41e880c5f
|
[
"Markdown",
"Python"
] | 3
|
Python
|
filiphosko/pdsnd-bikeshare-project
|
540808ab8f1726e6a247461b6cdabf38dd01e5c3
|
268a30dea02cc57ac526597d121c0f32360b1082
|
refs/heads/master
|
<file_sep><?php
namespace Itkee/WechatSDK;
class WeChat{
private $appid;
private $appsecret;
private $redirect_url;
public function __construct($appid, $appsecret,$redirect_url)
{
$this->appid = $appid;
$this->appsecret = $appsecret;
// $this->redirect_url = $redirect_url;
$this->redirect_url = request()->url();
}
/**
* 微信登录
*/
public function wx_pc_login(){
$appid = $this->appid;
$redirect_uri = $this->appsecret;
$redirect_uri = urlencode($this->redirect_url);
if(!$_GET['code']){
//获取code
$wx_login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
header('Location:'.$wx_login_url);
}else{
$code = $_GET['code'];
//获取access_token
$get_access_token = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
$data = http_request($get_access_token);
$access_token_info = json_decode($data,true);
//获取用户信息
$get_user_info = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token_info['access_token']}&openid={$access_token_info['openid']}&lang=zh_CN";
$user_info = http_request($get_user_info);
$user_info = json_decode($user_info,true);
return $user_info;
}
}
}
function http_request($url){
//初始化
$ch = curl_init();
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//执行并获取HTML文档内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
//打印获得的数据
return $output;
}
?>
|
55a2d9f58fa924a37b028fd6e5d91551542ec77b
|
[
"PHP"
] | 1
|
PHP
|
itkee/thinkphp5_wechat
|
053c82405c07f0ebaa03da066729afe6c8fc033b
|
2c61d7cf581c11b61e7505edbbf7db3fa4c092e8
|
refs/heads/master
|
<repo_name>SrcHndWng/go-learning-webapp-auth<file_sep>/auth/token.go
package auth
import (
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
)
var secretKey = "your-secret-key"
// CreateToken creates signed token.
func CreateToken(user LoginUser) (tokenString string, err error) {
// Set algorithm
token := jwt.New(jwt.GetSigningMethod("HS256"))
// Set user, period.
token.Claims = jwt.MapClaims{
"user": user.Name,
"exp": time.Now().Add(time.Hour * 1).Unix(),
}
// Sigin to token.
tokenString, err = token.SignedString([]byte(secretKey))
return
}
// ValidateToken valid token in request.
func ValidateToken(w http.ResponseWriter, r *http.Request) (*jwt.Token, error) {
token, err := request.ParseFromRequest(r, request.OAuth2Extractor, func(token *jwt.Token) (interface{}, error) {
b := []byte(secretKey)
return b, nil
})
if err != nil {
log.Printf("raise token error : %v\n", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(401)
w.Write([]byte("your token is not authorized."))
return nil, err
}
return token, nil
}
<file_sep>/handlers/productsHandler.go
package handlers
import (
"encoding/json"
"net/http"
"github.com/SrcHndWng/go-learning-webapp-auth/auth"
)
// ProductsHandler will be called when the user makes a GET request to the /products endpoint.
// This handler will return a list of products available for users to review.
var ProductsHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := auth.ValidateToken(w, r); err != nil {
return
}
// Here we are converting the slice of products to JSON
w.Header().Set("Content-Type", "application/json")
payload, _ := json.Marshal(products)
w.Write([]byte(payload))
})
<file_sep>/main.go
package main
import (
"net/http"
"os"
appHandlers "github.com/SrcHndWng/go-learning-webapp-auth/handlers"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func main() {
// Here we are instantiating the gorilla/mux router
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./views/")))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
r.Handle("/status", appHandlers.StatusHandler).Methods("GET")
r.Handle("/products", appHandlers.ProductsHandler).Methods("GET")
r.Handle("/products/{slug}/feedback", appHandlers.AddFeedbackHandler).Methods("POST")
r.Handle("/get-token", appHandlers.GetTokenHandler).Methods("GET")
http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r))
}
<file_sep>/handlers/product.go
package handlers
// Product contains information about VR experiences.
type Product struct {
ID int
Name string
Slug string
Description string
}
/* We will create our catalog of VR experiences and store them in a slice. */
var products = []Product{
Product{ID: 1, Name: "Hover Shooters", Slug: "hover-shooters", Description: "Shoot your way to the top on 14 different hoverboards"},
Product{ID: 2, Name: "Ocean Explorer", Slug: "ocean-explorer", Description: "Explore the depths of the sea in this one of a kind underwater experience"},
Product{ID: 3, Name: "Dinosaur Park", Slug: "dinosaur-park", Description: "Go back 65 million years in the past and ride a T-Rex"},
Product{ID: 4, Name: "Cars VR", Slug: "cars-vr", Description: "Get behind the wheel of the fastest cars in the world."},
Product{ID: 5, Name: "<NAME>", Slug: "robin-hood", Description: "Pick up the bow and arrow and master the art of archery"},
Product{ID: 6, Name: "Real World VR", Slug: "real-world-vr", Description: "Explore the seven wonders of the world in VR"},
}
<file_sep>/README.md
# go-learning-webapp-auth
## About This
https://auth0.com/blog/authentication-in-golang/
こちらの記事のサーバ側処理を学習のために写経したもの。
JWTによる認証は以下の記事を参考にした。
https://blog.motikan2010.com/entry/2017/05/12/jwt-go%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%81%BF%E3%82%8B
またget-tokenには、Basic認証を実装している。
## API Call
```
$ curl -v http://localhost:8080/status
$ curl -v http://localhost:8080/products # not authorized error.
$ curl -u username:password -v http://localhost:8080/get-token
$ TOKEN=上記で取得したトークン
$ curl -v http://localhost:8080/products -H "Authorization: $TOKEN"
```
<file_sep>/handlers/getTokenHandler.go
package handlers
import (
"net/http"
"github.com/SrcHndWng/go-learning-webapp-auth/auth"
)
// GetTokenHandler authenticate with basic auth, creates token and return.
var GetTokenHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, isLogin := auth.Login(r)
if !isLogin {
w.WriteHeader(401)
w.Write([]byte("Authentication failed."))
return
}
tokenString, err := auth.CreateToken(user)
if err == nil {
w.Write([]byte(tokenString))
} else {
w.Write([]byte("Could not generate token"))
}
})
<file_sep>/auth/login.go
package auth
import (
"crypto/md5"
"encoding/hex"
"net/http"
)
// LoginUser describes User.
type LoginUser struct {
Name string
Password string
}
// Password is MD5 hash from 'password'.
var onlyUser = LoginUser{Name: "username", Password: "<PASSWORD>"}
// Login executes authentication.
func Login(r *http.Request) (LoginUser, bool) {
userName, password, authOK := r.BasicAuth()
if authOK == false {
return LoginUser{}, false
}
hasher := md5.New()
hasher.Write([]byte(password))
hashed := hex.EncodeToString(hasher.Sum(nil))
if (userName != onlyUser.Name) || (hashed != onlyUser.Password) {
return LoginUser{}, false
}
return onlyUser, true
}
<file_sep>/handlers/statusHandler.go
package handlers
import "net/http"
// StatusHandler will be invoked when the user calls the /status route.
// It will simply return a string with the message "API is up and running"
var StatusHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("API is up and running"))
})
<file_sep>/handlers/notImplemented.go
package handlers
import "net/http"
// NotImplemented handler, Whenever an API endpoint is hit
// we will simply return the message "Not Implemented"
var NotImplemented = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Not Implemented"))
})
|
7e1dc7d0cdc8cceeb44be9062cb97f41fc751fc2
|
[
"Markdown",
"Go"
] | 9
|
Go
|
SrcHndWng/go-learning-webapp-auth
|
2fef4e69bec326c4afbad3a8465a1b4731fa4240
|
b4042acee07c70d7e88d25bf5b740322e026cb20
|
refs/heads/master
|
<repo_name>mba811/dash-manpages-zh<file_sep>/manpages.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@contact:
@date: 2014/06/23
"""
import os
import sqlite3
import urllib2
import shutil
import tarfile
import hashlib
import codecs
from mako.template import Template
from pyquery import PyQuery
currentPath = os.path.join(os.path.dirname(os.path.realpath(__file__)))
name = "manpages"
baseName = "manpages-zh"
output = baseName + ".docset"
appName = "dash-" + baseName
tarFileName = baseName + ".tgz"
feedName = baseName + ".xml"
version = "1.5.0"
docsetPath = os.path.join(currentPath, output, "Contents", "Resources", "Documents")
# Step 2: Copy the HTML Documentation
fin = codecs.open(os.path.join(docsetPath, "index.html"), "r", "utf-8")
content = fin.read()
fin.close()
jQuery = PyQuery(content)
jQuery.find("body").empty()
fileNames = []
itemTemplate = Template("<a href='html/${fileName}'>${name}</a><br />\n")
for fileName in os.listdir(os.path.join(docsetPath, "html")):
fileNames.append({
"name": fileName.split(".")[0],
"fileName": fileName
})
jQuery.find("body").append(itemTemplate.render(name = fileName.split(".")[0], fileName = fileName))
fin = codecs.open(os.path.join(docsetPath, "index.html"), "w", "utf-8")
newContent = jQuery.html()
fin.write(newContent)
fin.close()
# Step 3: create the Info.plist file
infoTemplate = Template('''<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>${name}</string>
<key>CFBundleName</key>
<string>${name}</string>
<key>DocSetPlatformFamily</key>
<string>${name}</string>
<key>dashIndexFilePath</key>
<string>index.html</string>
<key>dashIndexFilePath</key>
<string>index.html</string>
<key>isDashDocset</key><true/>
<key>isJavaScriptEnabled</key><true/>
</dict>
</plist>''')
infoPlistFile = os.path.join(currentPath, output, "Contents", "Info.plist")
fin = open(infoPlistFile, "w")
fin.write(infoTemplate.render(name = name))
fin.close()
# Step 4: Create the SQLite Index
dbFile = os.path.join(currentPath, output, "Contents", "Resources", "docSet.dsidx")
if os.path.exists(dbFile):
os.remove(dbFile)
db = sqlite3.connect(dbFile)
cursor = db.cursor()
try:
cursor.execute("DROP TABLE searchIndex;")
except Exception:
pass
cursor.execute('CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT);')
cursor.execute('CREATE UNIQUE INDEX anchor ON searchIndex (name, type, path);')
insertTemplate = Template("INSERT OR IGNORE INTO searchIndex(name, type, path) VALUES ('${name}', '${type}', '${path}');")
# Step 5: Populate the SQLite Index
for result in fileNames:
sql = insertTemplate.render(name = result["name"], type = "Builtin", path = "html/" + result["fileName"])
print sql
cursor.execute(sql)
db.commit()
db.close()
# Step 6: copy icon
shutil.copyfile(os.path.join(currentPath, "icon.png"),
os.path.join(currentPath, output, "icon.png"))
shutil.copyfile(os.path.join(currentPath, "icon@2x.png"),
os.path.join(currentPath, output, "icon@2x.png"))
# Step 7: 打包
if not os.path.exists(os.path.join(currentPath, "dist")):
os.makedirs(os.path.join(currentPath, "dist"))
tarFile = tarfile.open(os.path.join(currentPath, "dist", tarFileName), "w:gz")
for root, dirNames, fileNames in os.walk(output):
for fileName in fileNames:
fullPath = os.path.join(root, fileName)
tarFile.add(fullPath)
tarFile.close()
# Step 8: 更新feed url
feedTemplate = Template('''<entry>
<version>${version}</version>
<sha1>${sha1Value}</sha1>
<url>https://raw.githubusercontent.com/magicsky/${appName}/master/dist/${tarFileName}</url>
</entry>''')
fout = open(os.path.join(currentPath, "dist", tarFileName), "rb")
sha1Value = hashlib.sha1(fout.read()).hexdigest()
fout.close()
fin = open(os.path.join(currentPath, feedName), "w")
fin.write(feedTemplate.render(sha1Value = sha1Value, appName = appName, tarFileName = tarFileName, version = version))
fin.close()
<file_sep>/README.md
# dash-manpages-zh
中文 Linux manpages for Dash
|
769b55219929ad1d3a2b0e9337bc3d1d56691ddc
|
[
"Markdown",
"Python"
] | 2
|
Python
|
mba811/dash-manpages-zh
|
94f7345f48084c2fa22ae00996920d1309458649
|
65d26410f78e261c89b42e7a955d2421fe841d9e
|
refs/heads/master
|
<repo_name>LariTauana/PaymentContext<file_sep>/PaymentContext.Shared/Entities/Entity.cs
using System;
namespace PaymentContext.Shared.Entities
{
public abstract class Entity : Notifiable //abstrata pois não posso estanciar entidade
{
protected Entity()
{
Id = Guid.NewGuid();
}
public Guid Id { get; private set; } //Entidade tem ID, ValueObject não
}
}
|
f4fbeffcc63a668b21fa7c62e363fbe9ebf8c01b
|
[
"C#"
] | 1
|
C#
|
LariTauana/PaymentContext
|
b186e87456c6dc8470f4140f5235e51438373577
|
b87dda94c822af6f4d64e0e5b275441423715019
|
refs/heads/main
|
<file_sep>export default function Home(){
return(
<h1>This is NextJS</h1>
)
}
|
8d580ab34103811a3f19828d5019158b94f78250
|
[
"JavaScript"
] | 1
|
JavaScript
|
01101011karthik/nextjs-blob
|
0d08924a1c1a80d3524c45416b931bbb6c77ddff
|
8d9ef98bb54673b1f6f00ff503aeb85fc7f218f5
|
refs/heads/develop
|
<file_sep>/**
* Copyright 2017 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Net.Appclusive.Models.Constants
{
public static class Inventory
{
public static class OrganisationalUnit
{
public const string NAME_NAME = "Net.Appclusive.Models.Constants.Inventory.OrganisationalUnit.Name";
public const string NAME_DEFAULT = "OrganisationalUnit";
public const int NAME_MIN = 1;
public const int NAME_MAX = 1024;
public const string DESCRIPTION_NAME = "Net.Appclusive.Models.Constants.Inventory.OrganisationalUnit.Description";
public const string DESCRIPTION_DEFAULT = "OrganisationalUnit";
public const int DESCRIPTION_MIN = 0;
public const int DESCRIPTION_MAX = 4096;
}
}
}
<file_sep># Net.Appclusive.Models
[](https://github.com/Appclusive/Net.Appclusive.Models/blob/master/LICENSE)
[](http://docs.appclusive.net/en/latest/)
[](https://www.nuget.org/packages/Net.Appclusive.Models/)
Models for the Appclusive Blueprint Modelling and Automation Engine
Models and Behaviours in this repository are pre-defined by Appclusive such as `OrganisationalUnit`, `Folder` etc.
<file_sep>/**
* Copyright 2017 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Net.Appclusive.Public.Engine;
namespace Net.Appclusive.Models.V001
{
[ExecutionType(ExecutionType.CSharpScript)]
public class OrganisationalUnit : BaseModel
{
private static readonly Lazy<StateMachine> _stateMachine = new Lazy<StateMachine>(() =>
StateMachineBuilder
.For<OrganisationalUnit>()
.GetStateMachine()
);
public override StateMachine GetStateMachine()
{
return _stateMachine.Value;
}
[AttributeName(Constants.Inventory.OrganisationalUnit.NAME_NAME)]
[Required]
[DefaultValue(Constants.Inventory.OrganisationalUnit.NAME_DEFAULT)]
[StringLength(Constants.Inventory.OrganisationalUnit.NAME_MAX, MinimumLength = Constants.Inventory.OrganisationalUnit.NAME_MIN)]
public string Name { get; set; }
[AttributeName(Constants.Inventory.OrganisationalUnit.DESCRIPTION_NAME)]
[DefaultValue(Constants.Inventory.OrganisationalUnit.DESCRIPTION_DEFAULT)]
[StringLength(Constants.Inventory.OrganisationalUnit.DESCRIPTION_MAX, MinimumLength = Constants.Inventory.OrganisationalUnit.DESCRIPTION_MIN)]
public string Description { get; set; }
public class Edit : BaseModelAction
{
[AttributeName(Constants.Inventory.OrganisationalUnit.NAME_NAME)]
[Required]
[StringLength(Constants.Inventory.OrganisationalUnit.NAME_MAX, MinimumLength = Constants.Inventory.OrganisationalUnit.NAME_MIN)]
public string Name { get; set; }
[AttributeName(Constants.Inventory.OrganisationalUnit.DESCRIPTION_NAME)]
[StringLength(Constants.Inventory.OrganisationalUnit.DESCRIPTION_MAX, MinimumLength = Constants.Inventory.OrganisationalUnit.DESCRIPTION_MIN)]
public string Description { get; set; }
}
}
}
|
182b6c18aa955803f2e3fc24a09f077527caf201
|
[
"Markdown",
"C#"
] | 3
|
C#
|
Appclusive/Net.Appclusive.Models
|
3d5f4bc2f49441d2b903c11a736f531ebc3f4256
|
9170130287dea60305071a9f6f9af3f87d1cc7b3
|
refs/heads/master
|
<repo_name>padawanYoung/MSP100<file_sep>/README.md
# MSP100
pressure transducer
<file_sep>/msp100_i2c_driver.h
#include "i2c.h"
#include "gpio.h"
#include "debug.h"
#ifndef H_MSP100_I2C_DRIVER
#define H_MSP100_I2C_DRIVER
typedef enum {
READ_DF2_BYTES = 2,
READ_DF3_BYTES = 3,
READ_DF4_BYTES = 4
}RECEIVING_DATA_BYTES_AMOUNT;
typedef enum {
slaveType0 = 0x28,
slaveType1 = 0x36,
slaveType2 = 0x46,
slaveType3 = 0x48,
slaveType4 = 0x51
}slaveAddress;
typedef enum{
GOOD_PACKET = 0, // 00
RESERVED, // 01
STALE_DATA, // 10
FAULT // 11
}Status_bit;
typedef enum {
ATMASPHERES,
K_PASCALS,
KG_per_square_CM
}meassuring_points;
typedef union{
uint16_t d16;
uint8_t d8[2];
}Bridge_data;
typedef union{
uint16_t t16;
uint8_t t8[2];
}Temperature_data;
typedef struct {
float t_k;
float p_k;
uint16_t t_z;
uint16_t p_z;
meassuring_points points;
}interpolation_data;
typedef struct package{
slaveAddress addr;
Status_bit statusBit;
Bridge_data bd;
Temperature_data td;
float temperature ;
float pressure ;
RECEIVING_DATA_BYTES_AMOUNT bytesAmount;
uint8_t buffer [4];
interpolation_data mesurment;
}I2C_Package;
void MSP100_Reset();
void MSP100_Init(I2C_HandleTypeDef * I2Cx, I2C_Package * package);
Status_bit PRESSURE_I2C_READ_DFn_BYTES (I2C_HandleTypeDef * I2Cx, I2C_Package * package);
#endif
/**
* @}
*/
/**
* @}
*/
<file_sep>/msp100_i2c_driver.c
#include "msp100_i2c_driver.h"
void MSP100_Reset(){
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_8,GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_8,GPIO_PIN_SET);
}
void MSP100_Init(I2C_HandleTypeDef * I2Cx, I2C_Package * package){
package->addr = slaveType0;
package->bytesAmount = READ_DF4_BYTES;
package->mesurment.p_z = 0x3e8; // 1000d
package->mesurment.t_z = 0x200; // 512d
package->mesurment.p_k = 123.0F/1000.0F;
package->mesurment.t_k = 0.0976F;
}
Status_bit PRESSURE_I2C_READ_DFn_BYTES (I2C_HandleTypeDef * I2Cx, I2C_Package * package){
uint8_t tick = 10; //quantity of attemts
HAL_StatusTypeDef state;
while(((state = HAL_I2C_IsDeviceReady(I2Cx, package->addr<<1,1,10))!=HAL_OK) && tick){
//catch an Exception...
tick--;
}
package->buffer[2] = 0;
package->buffer[3] = 0;
state = HAL_I2C_Master_Receive(I2Cx, (package->addr)<<1,package->buffer, package->bytesAmount, 100);
package->statusBit = (Status_bit)(package->buffer[0] >> 6);
//if (package->statusBit == RESERVED || package->statusBit == STALE_DATA){
// return package->statusBit;
//}
package->bd.d8[0] = package->buffer[1];
package->bd.d8[1] = package->buffer[0]& (~(0xc0));
if(package->bytesAmount == READ_DF4_BYTES || package->bytesAmount == READ_DF3_BYTES){
package->td.t8[0] = package->buffer[3];
package->td.t8[1] = package->buffer[2];
package->td.t16 = (package->td.t16)>>5;
}
if (package->statusBit == GOOD_PACKET){
package->pressure = (float)package->bd.d16;
package->temperature = (float)package->td.t16;
package->pressure = (package->pressure - package->mesurment.p_z);
package->pressure = package->pressure * package->mesurment.p_k;
package->temperature = (package->temperature - package->mesurment.t_z);
package->temperature = package->temperature * package->mesurment.t_k;
}else if (package->statusBit == FAULT){
return package->statusBit;
}
return package->statusBit;
}
|
94fd1530eb725919024995a8e0c0dcdb483d7fc8
|
[
"Markdown",
"C"
] | 3
|
Markdown
|
padawanYoung/MSP100
|
1e88525d77449e97be0b620f9c470cd5e68aab9b
|
02ef8894d9d50184f64f8906ebe1f865e7483ce2
|
refs/heads/master
|
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let userService = require('../services/users.service')
router.get('/me', ensureAuthorized, userService.getPersonnalInformation)
router.get('/getId/:email', ensureAuthorized, userService.findUserByEmail)
router.get('/disableUser/:email', ensureAuthorized, userService.disableUser)
router.get('/activeUser/:email', ensureAuthorized, userService.activeUser)
router.post('/changeMDP', ensureAuthorized, userService.changeMDP)
router.post('/saveInfo', ensureAuthorized, userService.saveUserInformation)
router.post('/saveBilingInfo', ensureAuthorized, userService.saveBilingInfo)
router.post('/saveNotificationInfo', ensureAuthorized, userService.saveNotification)
router.get('/listUser', ensureAuthorized, userService.listUser)
router.post('/changePP', ensureAuthorized, userService.updateUserProfilPhoto)
router.post('/upload', ensureAuthorized, userService.uploadProfilePhoto)
module.exports = router
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
let User = require('./../models/Users')
let Bucket = require('./../models/Bucket')
let Article = require('./../models/Article')
let Historique = require('./../models/History')
let listArticleHistory = (req, res) => {
Article.findOne({"_id" : req.params.article_id}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Article not found"
})
}
else {
Historique.findOne({"_id" : rep.history}, (err, rep) => {
if (err || !rep) {
res.json({
type: true,
data: "No history found"
})
}
else {
res.json({
type:true,
data: rep
})
}
})
}
})
}
let addHistory = (req, res) => {
Article.findOne({"_id" : req.params.article_id}, (err, rep) => {
let article = rep;
if (err || !rep) {
res.json({
type: false,
data: "Article not found"
})
}
else {
Historique.findOne({"_id" : rep.history}, (err, rep) => {
if (err || !rep) {
let newHistory = new Historique({
price_history: [
{
price: req.body.price,
date: req.body.price_dated
}
],
stock_history: [
{
stock: req.body.stock,
date: req.body.stock_dated
}
]
})
newHistory.save((err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't create history"
})
}
else {
let newValues = { $set: {
history : rep._id
}}
Article.updateOne({"_id" : req.params.article_id}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "History created but cant be attached to article"
})
}
else {
res.json({
type: true,
data: "History created"
})
}
})
}
})
}
else {
let newPriceValues = {
price : req.body.price,
date : req.body.price_dated
}
rep.price_history.push(newPriceValues);
let newStockValues = {
stock : req.body.stock,
date : req.body.stock_dated
}
rep.stock_history.push(newStockValues);
let newPrice = rep.price_history;
let newStock = rep.stock_history;
let newValues = { $set : {
price_history : newPrice,
stock_history : newStock
}};
Historique.updateOne({"_id" : rep._id}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't update History"
})
}
else {
res.json({
type: true,
data: "History saved correctly"
})
}
})
}
})
}
})
}
let parseDate = async (date) => {
let new_date = date;
new_date = new_date.substr(6) + '-' + new_date.substr(0, 5);
new_date = new_date.substr(0, 4) + '-' + new_date.substr(8, 9) + '-' + new_date.substr(5, 6)
new_date = new_date.substr(0, 10);
return (new_date);
}
let placeLabel = async (data, date) => {
let new_data = data;
let new_date = await parseDate(date);
new_date = new Date(new_date);
let index = 0;
if (data.length > 0){
for(let all_date of data) {
all_date = await parseDate(all_date);
all_date = new Date (all_date)
if (all_date > new_date && data.length > 1) {
}
else if (all_date > new_date && data.length == 1) {
new_data.splice(0, 1, date);
}
else {
new_data.splice(0, index, date);
break;
}
index++;
}
}
else {
new_data.push(date);
}
return (new_data);
}
let associateLabel = async (history, label) => {
let new_label = label;
for (let date of history.price_history) {
if (date.price != -2) {
let indexOf = new_label.indexOf(date.date)
if (indexOf <= -1) {
new_label = await placeLabel(new_label, date.date)
}
}
}
return (new_label)
}
let placePrice = async (label, data, date, price) => {
if (price == undefined) {
return (data);
}
let indexOf = await label.indexOf(date);
if (indexOf <= -1) {
return data;
}
let average = data[indexOf];
if (average == null || average == undefined || average == '') {
if (indexOf > 0 && average != '') {
let index = 0;
while (index != indexOf) {
if (data[index] == null || data[index] == undefined) {
data[index] = ''
}
index++;
}
await data.splice(indexOf, 1, price);
}
else if (average == '') {
await data.splice(indexOf, 1, price);
}
else {
await data.push(price)
}
}
else {
let new_average = (average + price) / 2;
await data.splice(indexOf, 1, new_average)
}
return (data);
}
let associateAverage = async (history, label, data) => {
let new_data = data;
let average_price = 0;
let average_date = 0;
for (let price of history.price_history) {
if (price.price != -2) {
new_data = await placePrice(label, new_data, price.date, price.price)
}
}
return (new_data);
}
let statsArticle = async (req, res) => {
let user = await User.findOne({token: req.token})
let data = [];
let label = [];
for (let bucket of user.bucket) {
bucket = await Bucket.findOne({"_id" : bucket})
let article = await Article.findOne({"_id" : bucket.article})
let history = await Historique.findOne({"_id" : article.history})
if (history != null) {
label = await associateLabel(history, label)
data = await associateAverage(history, label, data)
}
}
label = label.reverse()
data = data.reverse();
res.json({
data : data,
label : label
})
}
let statsConcurents = async (req, res) => {
let user = await User.findOne({token: req.token})
let data = [];
let label = [];
for (let bucket of user.bucket) {
bucket = await Bucket.findOne({"_id" : bucket})
for (let concurent of bucket.concurent) {
let article = await Article.findOne({"_id" : concurent})
let history = await Historique.findOne({"_id" : article.history})
if (history != null) {
label = await associateLabel(history, label)
data = await associateAverage(history, label, data)
}
}
}
label = label.reverse()
data = data.reverse();
res.json({
data : data,
label : label
})
}
let article_line = async(article, label) => {
let to_return = {
label : 'Our Price',
data : [],
borderWidth : 1,
fill : false
}
let history = await Historique.findOne({"_id" : article.history})
to_return.data = await associateAverage(history, label, to_return.data)
to_return.data = to_return.data.reverse()
return (to_return)
}
let addConcurentLine = async(priceLine, concurent, labels) => {
let newPriceLine = priceLine
let newLabelsLength = labels.length
let to_multiplicate = false;
if (labels.length == 1) {
newLabelsLength++;
to_multiplicate = true;
}
let to_return = {
label : concurent.name,
data : new Array(newLabelsLength),
borderWidth : 1,
fill : false
}
let history = await Historique.findOne({"_id" : concurent.history})
for (let price of history.price_history) {
let indexOf = labels.indexOf(price.date);
if (indexOf <= -1) {
console.log("index of -1");
}
else {
if (to_multiplicate) {
to_return.data.splice(indexOf, 1, price.price)
to_return.data.splice(indexOf + 1, 1, price.price)
}
to_return.data.splice(indexOf, 1, price.price)
}
}
to_return.data = to_return.data.reverse();
//pour chaque labels placé une valeur
//to_return.label = concurent.name
newPriceLine.push(to_return);
return (newPriceLine);
}
let articleLabels = async (article) => {
let label = [];
let history = await Historique.findOne({"_id" : article.history})
if (history != null) {
label = await associateLabel(history, label)
}
return (label);
}
let statsBucket = async (req, res) => {
let bucket = await Bucket.findOne({"_id" : req.params.bucket_id})
let priceLine = [];
let labels = [];
let article = await Article.findOne({"_id" : bucket.article})
labels = await articleLabels(article);
let to_insert = await article_line(article, labels)
priceLine.push(to_insert);
for (let concurent of bucket.concurent) {
concurent = await Article.findOne({"_id" : concurent})
priceLine = await addConcurentLine(priceLine, concurent, labels)
}
labels = labels.reverse();
res.json({
priceLine : priceLine,
labels : labels
})
}
module.exports = {
statsArticle,
statsConcurents,
listArticleHistory,
addHistory,
statsBucket
}
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let reportService = require('../services/report.service')
router.get('/generateReport', reportService.reportAllUser)
module.exports = router
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
let User = require('./../models/Users')
let sha256 = require('sha256')
let changeMDP = async (req, res) => {
User.findOne({token : req.token, password: <PASSWORD>(req.body.password)}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Bad Password"
})
}
else {
let newpassord = req.body.new_password
let hashpassword = <PASSWORD>56(<PASSWORD>);
let newValues = { $set : {
password : <PASSWORD>
}}
User.updateOne({token: req.token}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't update new password"
})
}
else {
res.json({
type: true,
data: "User correctly change password"
})
}
})
}
})
}
let saveNotification = async (req, res) => {
let user = await User.findOne({token : req.token})
let new_notification_info = {
report_email : req.body.report_email,
delay : req.body.delay,
alert_email : req.body.alert_email,
newletters : req.body.newletters,
app_notification : user.notification.app_notification != null ? user.notification.app_notification : []
}
let newValues = { $set : {
notification : new_notification_info
}}
await User.updateOne({token: req.token}, newValues)
res.json({
type: true,
data: "Notification info saved"
})
}
let saveBilingInfo = async (req, res) => {
let user = await User.findOne({token : req.token})
let new_biling_info = {
company_name : req.body.company_name,
address_1 : req.body.address_1,
address_2 : req.body.address_2,
city : req.body.city,
state : req.body.state,
zip_code : req.body.zip_code,
phone : req.body.phone,
email : req.body.email
}
let newValues = { $set : {
biling_info : new_biling_info
}}
await User.updateOne({token: req.token}, newValues)
res.json({
type: true,
data: "Biling info saved"
})
}
let disableUser = (req, res) => {
User.findOne({"email" : req.params.email}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't find this user"
})
}
else {
let newValues = { $set: {
disable: true
}}
User.updateOne({"email" : req.params.email}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't disable this account"
})
}
else {
res.json({
type: true,
data: "This user is now disable"
})
}
})
}
})
}
let activeUser = (req, res) => {
User.findOne({"email" : req.params.email}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't find this user"
})
}
else {
let newValues = { $set: {
disable: false
}}
User.updateOne({"email" : req.params.email}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't active this account"
})
}
else {
res.json({
type: true,
data: "This user is now active"
})
}
})
}
})
}
let getPersonnalInformation = (req, res) => {
User.findOne({token: req.token}, (err, user) => {
if (err) {
res.json({
type: false,
data: "Error occured: " + err
})
} else {
res.json({
type: true,
data: user
})
}
})
}
let findUserByEmail = (req, res) => {
User.findOne({email: req.params.email}, (err, user) => {
if (err) throw err
res.json({
type: true,
data: user
})
})
}
let saveUserInformation = (req, res) => {
let newValues = { $set : {
first_name : req.body.first_name,
last_name : req.body.last_name,
email : req.body.email,
} }
User.updateOne({"token" : req.token}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't find this user"
})
}
else {
User.findOne({"token": req.token}, (err, user) => {
res.json({
type: true,
data: user
})
})
}
})
}
let listUser = (req, res) => {
User.find({}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "No user"
})
}
else {
res.json({
type: true,
data: rep
})
}
})
}
//Save photo de profile
let updateUserProfilPhoto = (req, res) => {
let newValues = { $set : {
photoProfile : '/public/pdp/' + req.body.photoProfile
} }
User.updateOne({"_id" : ObjectId(req.body.id)}, newValues, (err, response) => {
if (err) throw err
res.json({
type: true,
data: '/public/pdp/' + req.body.photoProfile
})
})
}
let uploadProfilePhoto = (req, res) => {
let file = req.files.file
if (file.name === undefined)
file.name = "newPdp.jpg"
let newpath = path.resolve(path.resolve(__dirname) + '/../public/pdp/' + file.name)
fs.rename(file.path, newpath, err => {
if (err) throw err
res.json({
type: true,
data: '/public/pdp/' + file.name
})
})
}
module.exports = {
uploadProfilePhoto,
updateUserProfilPhoto,
saveUserInformation,
findUserByEmail,
getPersonnalInformation,
disableUser,
activeUser,
listUser,
saveBilingInfo,
saveNotification,
changeMDP
}
<file_sep>let Article = require('./../models/Article');
class Article() {
}<file_sep>// 1 - Import de puppeteer
const puppeteer = require('puppeteer')
/*
// 2 - Récupération des URLs de toutes les pages à visiter
- waitFor("body"): met le script en pause le temps que la page se charge
- document.querySelectorAll(selector): renvoie tous les noeuds qui vérifient le selecteur
- [...document.querySelectorAll(selector)]: caste les réponses en tableau
- Array.map(link => link.href): récupère les attributs href de tous les liens
*/
const getAllUrl = async (browser , item) => {
var url = item.url;
const page = await browser.newPage();
try {
await page.goto(url);
await page.waitFor('body');
}
catch (err) {
var obj_selector = {
price: -1,
text_content: boolean = false,
price_cms: boolean = false,
meta_content: boolean = false,
stock: undefined,
stock_content: boolean = false,
stock_cms: boolean = false,
stock_text: undefined,
InStock_interpretation: undefined,
OutStock_interpretation: undefined,
image: undefined,
img_content: boolean = false,
image_src: boolean = false,
};
console.log("TIMEOUT")
return (obj_selector);
}
console.log("getALLUrl")
const result = await page.evaluate(() =>
{
var obj_selector = {
price: undefined,
text_content: boolean = false,
price_cms: boolean = false,
meta_content: boolean = false,
stock: undefined,
stock_content: boolean = false,
stock_cms: boolean = false,
stock_text: undefined,
InStock_interpretation: undefined,
OutStock_interpretation: undefined,
image: undefined,
img_content: boolean = false,
image_src: boolean = false,
};
const inStock_list = ["stock", "disponible", "disponibles", "commandez vite", "il reste"];
const outOfStock_list = ["3 à 5 jours", "ou plus", "rupture", "prévenez-moi", "10 jours", "15 jours", "1 mois", "en stock fournisseur", "8 jours", "4 jours", "sur commande", "n'est plus en stock", "Out of stock"];
function get_pageinfo() {
var selector_cms_list_price = [
".price.typeNew.spacerBottomXs",
".price-pricesup",
"span.price_withVat",
".price-block__amount.qa-price-value",
".SFR_Price_euros",
"pix-price-int",
"tarif_sejour",
".pix-price",
".attribute_price",
".PricesalesPrice",
".price.typeNew.spacerBottomXs",
".current_price",
".product-price.nowrap",
".prix.rebours-prix.rebours-inited",
"#our_price_display",
".wording.a-cpo-pricetag",
".price.MutColor04",
".price.product-page-price",
"ins > span.woocommerce-Price-amount.amount",
".f-priceBox-price.f-priceBox-price--reco.checked",
".ProductShowPrice",
"span[id^='product-price-']"];
var selector_meta_list_price = ['.attribute_price', 'meta[property="og:price:standard_amount"]',
'[itemprop="price"]', '[itemprop="lowPrice"]', '[itemprop="highPrice"]'];
var selector_list_price = [".pricing",
".price",
"p.price",
".span.price",
".newPrix",
".fp-bloc-resa-devis-prix",
".cart-total-price",
".prix > p",
".a-color-price",
".tarif_sejour",
"pix-price-int",
"#prix-promo-prix",
".price_with_discount",
".priceWithDiscount",
".SFR_Price_euros",
".pix-price",
".price_area",
".f-priceBox-price",
"span.price",
".p-price",
".price",
"span[id^='price']", ".archive_price_product",
".node-prix-actuel", "#price"];
var selector_cms_list_stock = ['[id="availability_value"]',
'[id="availability"]', '[itemprop="availability"]',
'[id="pQuantityAvailable"]'];
var selector_meta_list_stock = ['[id="availability_delay"]',
'[id="fraseStockMostrar"]'];
var selector_list_stock = [".stock", ".delay", ".availability",
".product-availability", ".fpStock",
".ProductShowEnStockMessageGreen", ".productPageContentInfosTop_stock"];
var selector_meta_list_img = ['[id="bigpic"]', ['[id="productMainPicture"]'],
'.attribute_image', '.attribute_img',
"meta[name='images-url']",
'[itemprop="picture"]', '[itemprop="img"]', '.image--media > img',
"image-gallery-image > img", '[id="landingImage"]',
'[id="picture0"]', '[id="image"]', '[itemprop="image"]', '[style="display: block;"]', '.image-gallery-image > img'];
var selector_list_img = [".slik-item.slick-slide.slick-current.slick-active img", ".image",
".mz-figure.white-bg.mz-click-zoom.mz-ready.mz-no-zoom img",
".pic",
".pics",
".picture",
".image-carousel",
"span[id^='image']",
".img-responsive",
".zoomImg",
".zoomContainer",
"image_article",
".img-product",
".gallery-main-image",
".gallery-image",
".productPageContentSliderElements_image",
".illustration-node.image-link.fancy-thumb > img",
".medias-zoom img",
".f-productVisuals-mainMedia.js-ProductVisuals-imagePreview.xzoom",
"img", '#productMainImage'];
var return_price = price_cms_test(selector_cms_list_price, selector_meta_list_price, selector_list_price);
var return_stock = stock_cms_test(selector_cms_list_stock, selector_meta_list_stock, selector_list_stock);
var return_image = image_meta_test(selector_meta_list_img, selector_list_img);
var script = create_script();
var script_array = create_script_array();
var func = false;
var image_src = false;
if (obj_selector.price_cms == true || obj_selector.stock_cms == true)
func = true;
if (obj_selector.image_src === true)
image_src = true;
return {
price: return_price,
stock: return_stock,
html: false,
image_type: 2,
img_url: return_image,
script: script,
script_array: script_array,
func: func,
image_src: image_src,
};
};
function image_selector_test(selector_list) {
console.log("image_selector_test")
var image = image_content(check_other_selector(selector_list, image, 'image'));
var return_image = (image && image != "") ? image : "";
return (return_image);
}
function image_meta_test(meta_list, selector_list) {
console.log("image_meta_test")
var image = image_content(check_meta(meta_list, image, 'image'));
var return_image = (image && image != "") ? image : image_selector_test(selector_list);
return (return_image);
}
function stock_selector_test(selector_list) {
console.log("stock_selectot_test")
var stock = stock_textcontent(check_other_selector(selector_list, stock, 'stock'));
stockInterpretation(stock);
var return_stock = (stock && stock != "") ? stock : "";
return (return_stock);
}
function stock_meta_test(meta_list, selector_list) {
console.log("stock_meta_test")
var stock = stock_textcontent(check_meta(meta_list, stock, 'stock'));
stockInterpretation(stock);
var return_stock = (stock && stock != "") ? stock : stock_selector_test(selector_list);
return (return_stock);
}
function stock_cms_test(cms_list, meta_list, selector_list) {
console.log("stock_cms_test")
var stock = stock_textcontent(check_cms_stock(cms_list, stock));
stockInterpretation(stock);
var return_stock = (stock && stock != "") ? stock : stock_meta_test(meta_list, selector_list);
return (return_stock);
}
function price_selector_test(selector_list) {
console.log("price_selector_test")
var price = price_textcontent(check_other_selector(selector_list, price, 'price'));
var return_price = (price && price != "" && price != -2) ? price : "-2";
return (return_price);
}
function price_meta_test(meta_list, selector_list) {
console.log("price_meta_test")
var price_container = check_meta(meta_list, price, 'price');
var price = price_metacontent(price_container);
if (price == -2) {
price = price_textcontent(price_container);
obj_selector.meta_content = false;
}
console.log("PRICE");
var return_price = (price && price != "-2" && price != "") ? price : price_selector_test(selector_list);
return (return_price);
}
function price_cms_test(cms_list, meta_list, selector_list) {
console.log("price_cms_test")
var price = price_textcontent(check_cms_price(cms_list, price));
var return_price = (price && price != "-2" && price != "") ? price : price_meta_test(meta_list, selector_list);
return (return_price);
}
function create_script_array() {
console.log("create_script_array")
var script_array = ["", "", "", "", ""];
if (obj_selector.price !== undefined) {
script_array[0] += '\n\n\tvar price = ' + obj_selector.price + ';\n';
if (obj_selector.price_cms === true)
script_array[0] += '\tprice = (price) ? get_container_text(price) : null;\n';
if (obj_selector.text_content === true)
script_array[0] += '\tprice = (price && price.textContent) ? price.textContent : "-2";\n';
if (obj_selector.meta_content === true) {
script_array[0] += '\tprice = (price) ? price.getAttribute("content") : "-2";\n\tprice = (price !== "-2") ? parseFloat(price) : "-2";\n\tprice = (price !== "-2" && !isNaN(parseFloat(price)) && isFinite(price)) === true ? price : "-2";\n\tprice = (price !== "-2") ? price.toFixed(2) : "-2";\n'
}
if (obj_selector.text_content === true) {
script_array[0] += '\tif (price && price !== "-2") {\n\t\tprice = price.replace(/([a-zA-Zàéçùè:/])/g, "");\n\t\tprice = price.replace(/([,])/g, ".");\n\t\tprice = price.replace(/\s/g,"");\n\t\tprice = price.replace(/([$€£])/g, ".");\n\t\tprice = parseFloat(price).toFixed(2).toString();\n\t}\n';
}
}
if (obj_selector.stock != undefined) {
script_array[1] += '\n\n\tvar stock = ' + obj_selector.stock + ';';
if (obj_selector.stock_cms === true)
script_array[1] += '\n\tstock = (stock) ? get_container_text(stock) : null;';
if (obj_selector.stock_content === true) {
script_array[1] += '\n\tstock = (stock' + ((obj_selector.stock_text) ? ' && stock' + obj_selector.stock_text + ' ' : '') + ') ? stock' + obj_selector.stock_text + ': "";';
}
script_array[1] += '\n\treturn_availability = (stock !== "") ? stock : return_availability;\n\t';
}
if (obj_selector.image != undefined) {
script_array[2] += '\n\n\tvar image = ' + obj_selector.image + ';\n';
}
if (obj_selector.InStock_interpretation != undefined)
script_array[3] = obj_selector.InStock_interpretation;
if (obj_selector.OutStock_interpretation != undefined)
script_array[4] = obj_selector.OutStock_interpretation;
return (script_array);
}
function create_script() {
console.log("crete_script")
var script = "";
if (obj_selector.price_cms == true || obj_selector.stock_cms == true) {
script = 'function get_container_text(container) {\n\tif (container.length === 0)\n\t\treturn null;\n\tvar selector = container[0];\n\n\tfor (var x = 0; x !== container.length; x++) {\n\t\tif (selector.id.length > container[x].id.length)\n\t\t\tselector = container[x];\n\t}\n\treturn selector;\n}\n\n';
}
script += 'window.get_pageinfo =function() {\n\n\tvar return_price = "-2";\n\tvar return_stock = "";\n\tvar return_img_url = "";';
if (obj_selector.price !== undefined) {
script += '\n\n\tvar price = ' + obj_selector.price + ';\n';
if (obj_selector.price_cms === true)
script += '\tprice = (price) ? get_container_text(price) : null;\n';
if (obj_selector.text_content === true)
script += '\tprice = (price && price.textContent) ? price.textContent : "-2";\n';
if (obj_selector.meta_content === true) {
script += '\tprice = (price) ? price.getAttribute("content") : "-2";\n\tprice = (price !== "-2") ? parseFloat(price) : "-2";\n\tprice = (price !== "-2" && !isNaN(parseFloat(price)) && isFinite(price)) === true ? price : "-2";\n\tprice = (price !== "-2") ? price.toFixed(2) : "-2";\n'
}
if (obj_selector.text_content === true) {
script += '\tif (price && price !== "-2") {\n\t\tprice = price.replace(/([a-zA-Zàéçùè:/])/g, "");\n\t\tprice = price.replace(/([,])/g, ".");\n\t\tprice = price.replace(/\s/g,"");\n\t\tprice = price.replace(/([$€£])/g, ".");\n\t\tprice = parseFloat(price).toFixed(2).toString();\n\t}\n';
}
script += '\treturn_price = (price && price !== "-2") ? price : return_price;';
}
if (obj_selector.stock != undefined) {
script += '\n\n\tvar stock = ' + obj_selector.stock + ';\n';
if (obj_selector.stock_cms === true)
script += '\tstock = (stock) ? get_container_text(stock) : null;\n';
if (obj_selector.stock_content === true) {
script += '\tstock = (stock) ? stock' + obj_selector.stock_text + ': "";\n';
}
script += '\treturn_stock = (stock && stock !== "") ? stock : return_stock;';
}
if (obj_selector.image != undefined) {
script += '\n\n\tvar image = ' + obj_selector.image + ';\n';
script += '\treturn_img_url = (image';
if (obj_selector.image_src === true)
script += ' && image.src';
script += ') ? image';
if (obj_selector.image_src === true)
script += '.src';
script += ' : return_img_url;';
}
script += '\n\n\treturn {\n\t\tprice: return_price,\n\t\tstock: return_stock,\n\t\thtml: false,\n\t\timage_type: 2,\n\t\timg_url: return_img_url\n\t};\n\n}';
return (script);
}
function price_textcontent(my_price) {
console.log("price_textcontent")
var rt = undefined;
if (my_price && my_price !== "") {
rt = my_price && my_price.textContent ? my_price.textContent : "-2";
rt = rt.replace(/([a-zA-Zàéçùè:/])/g, "");
rt = rt.replace(/([,])/g, ".");
rt = rt.replace(/\s/g, '');
rt = rt.replace(/([$€£])/g, ".");
rt = parseFloat(rt).toFixed(2).toString();
}
if (rt && rt != "") {
//obj_selector.price += ".textContent";
obj_selector.text_content = true;
}
return rt;
}
function stock_textcontent(my_stock) {
console.log("stock_textcontent")
var rt = "";
var text_container = "";
if (my_stock && my_stock !== "") {
if (my_stock.innerText) {
rt = my_stock.innerText
text_container = ".innerText";
} else if (my_stock.innerHTML) {
rt = my_stock.innerHTML;
text_container = ".innerHTML";
}
}
if (rt && rt != "") {
obj_selector.stock_text = text_container;
obj_selector.stock_content = true;
}
return rt;
}
function price_metacontent(my_price) {
console.log("price_metacontent")
var rt;
rt = my_price ? my_price.getAttribute('content') : -2;
rt = rt !== -2 ? parseFloat(rt) : -2;
rt = (rt !== -2 && !isNaN(parseFloat(rt)) && isFinite(rt)) === true ? rt : -2;
rt = (rt !== -2) ? rt.toFixed(2) : -2;
if (rt && rt > -1)
obj_selector.meta_content = true;
return rt;
}
function image_content(my_image) {
console.log("image_content")
var rt = undefined;
if (my_image && my_image !== "") {
rt = my_image && my_image.src ? my_image.src : "";
}
if (rt && rt != "") {
obj_selector.image_src = true;
}
if (typeof(my_image) === 'string')
rt = my_image;
return rt;
}
function check_meta(meta_list, my_element, type) {
console.log("check_meta")
var tmp;
for (var i = 0; i !== meta_list.length; i++) {
tmp = document.querySelector(meta_list[i]);
if (tmp) {
my_element = tmp;
if (type == 'image')
obj_selector.image = "document.querySelector(" + quote_adjust(meta_list[i]) + ")";
if (type == 'price')
obj_selector.price = "document.querySelector(" + quote_adjust(meta_list[i]) + ")";
if (type == 'stock')
obj_selector.stock = "document.querySelector(" + quote_adjust(meta_list[i]) + ")";
break;
}
}
return my_element;
}
function check_cms_stock(cms_list, my_stock) {
console.log("check_cms_stock")
var my_stock_str;
for (var i = 0; i !== cms_list.length; i++) {
my_stock = document.querySelectorAll(cms_list[i]);
if (my_stock) {
my_stock_str = "document.querySelectorAll(" + quote_adjust(cms_list[i]) + ")";
var stock_selector = my_stock[0];
for (var x = 0; x !== my_stock.length; x++) {
if (stock_selector.id.length > my_stock[x].id.length) {
stock_selector = my_stock[x];
my_stock_str = "document.querySelectorAll(" + quote_adjust(cms_list[i]) + ")";
} else if (cms_list[i] !== "span[id^='product-stock-']") {
stock_selector = my_stock[x];
my_stock_str = "document.querySelectorAll(" + quote_adjust(cms_list[i]) + ")";
if (stock_textcontent(stock_selector) && stock_textcontent(stock_selector) !== "") {
my_stock = stock_selector;
obj_selector.stock = my_stock_str;
obj_selector.stock_cms = true;
return my_stock;
}
}
}
my_stock = stock_selector;
}
}
if (my_stock) {
obj_selector.price_cms = true;
obj_selector.stock = my_stock_str;
}
return my_stock;
}
function check_cms_price(cms_list, my_price) {
console.log("check_cms_price")
var my_price_str;
for (var i = 0; i !== cms_list.length; i++) {
my_price = document.querySelectorAll(cms_list[i]);
if (my_price) {
my_price_str = "document.querySelectorAll(" + quote_adjust(cms_list[i]) + ")";
var price_selector = my_price[0];
for (var x = 0; x !== my_price.length; x++) {
if (price_selector.id.length > my_price[x].id.length) {
price_selector = my_price[x];
my_price_str = "document.querySelectorAll(" + quote_adjust(cms_list[i]) + ")";
} else if (cms_list[i] !== "span[id^='product-price-']") {
price_selector = my_price[x];
my_price_str = "document.querySelectorAll(" + quote_adjust(cms_list[i]) + ")";
if (price_textcontent(price_selector) && price_textcontent(price_selector) !== "") {
my_price = price_selector;
obj_selector.price = my_price_str;
obj_selector.price_cms = true;
return my_price;
}
}
}
my_price = price_selector;
}
}
if (my_price) {
obj_selector.price_cms = true;
obj_selector.price = my_price_str;
}
return my_price;
}
function check_other_selector(selector_list, my_element, type) {
console.log("check other selector")
var tmp;
for (var i = 0; i !== selector_list.length; i++) {
tmp = document.querySelector(selector_list[i]);
if (tmp) {
my_element = tmp;
if (type == 'image')
obj_selector.image = "document.querySelector(" + quote_adjust(selector_list[i]) + ")";
if (type == 'price')
obj_selector.price = "document.querySelector(" + quote_adjust(selector_list[i]) + ")";
if (type == 'stock')
obj_selector.stock = "document.querySelector(" + quote_adjust(selector_list[i]) + ")";
break;
}
}
return my_element;
}
function stockInterpretation(stock) {
console.log("stockInterpretation")
if (!stock)
return;
low_stock = stock.toLowerCase();
for (var i = 0; i != outOfStock_list.length; i++) {
if (low_stock.indexOf(outOfStock_list[i]) !== -1) {
obj_selector.OutStock_interpretation = stock.replace(/\n/g, '\\\n');
return;
}
}
for (var i = 0; i != inStock_list.length; i++) {
if (low_stock.indexOf(inStock_list[i]) !== -1) {
obj_selector.InStock_interpretation = stock.replace(/\n/g, '\\\n');
return;
}
}
}
function quote_adjust(selector) {
console.log("quote_adjust")
if (selector.indexOf("'") != -1) {
selector = '"' + selector + '"';
return selector;
}
selector = "'" + selector + "'";
return selector;
}
console.log("return get page info")
return get_pageinfo();
});
console.log("return result")
return result
};
// 3 - Récupération du prix et du tarif d'un livre à partir d'une url (voir exo #2)
const getDataFromUrl = async (browser, url) => {
console.log("getDataFromUrl")
const page = await browser.newPage();
await page.goto(url);
await page.waitFor('body');
return page.evaluate(() => {
let title = document.querySelector('h1').innerText;
let price = document.querySelector('.price_color').innerText;
return { title, price }
})
};
/*
// 4 - Fonction principale : instanciation d'un navigateur et renvoi des résultats
- urlList.map(url => getDataFromUrl(browser, url)):
appelle la fonction getDataFromUrl sur chaque URL de `urlList` et renvoi un tableau
- await Promise.all(promesse1, promesse2, promesse3):
bloque de programme tant que toutes les promesses ne sont pas résolues
*/
const scrap = async (item) => {
const browser = await puppeteer.launch({headless: true , timeout : 360000});
/*const results = await Promise.all(
urlList.map(url => getDataFromUrl(browser, url)),
);
browser.close();*/
console.log("init Scrapping: ", item.name);
var result = await getAllUrl(browser, item);
browser.close();
return result
};
// 5 - Appel la fonction `scrap()`, affichage les résulats et catch les erreurs
function scrap_article(item) {
console.log("Scrapper");
return scrap(item);
}
module.exports = scrap_article;
<file_sep>let nodemailer = require('nodemailer')
let config = require('./../config/index')
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '<EMAIL>',
pass: config.EMAIL_PASSWORD
}
})
module.exports = transporter
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
let User = require('./../models/Users')
let Notifications = require('./../models/Notification')
let listNotification = async (req, res) => {
let user = await User.findOne({token : req.token})
if (user.notification.app_notification == undefined || user.notification.app_notification.length == 0) {
res.json({
type: false,
data : "No notification"
})
}
let index = 0;
let notifications = []
let until = user.notification.app_notification.length
let from = until - 6;
if (from < 0 ) {
from = 0;
}
index = user.notification.app_notification.length - 1
while (index != 0) {
if (index == from) {
break;
}
let new_notif = await Notifications.findOne({"_id" : user.notification.app_notification[index]})
notifications.push(new_notif)
index--;
}
// for (let notification of user.notification.app_notification) {
// if (index >= from && index <= until) {
// let new_notif = await Notifications.findOne({"_id" : notification})
// notifications.push(new_notif)
// }
// index++;
// }
res.json({
type: true,
data: notifications,
number : notifications.length
})
}
let addNotification = async (req, res) => {
let user = await User.findOne({token: req.token})
let newNotif = new Notifications ({
icon : req.body.icon,
title : req.body.title,
text : req.body.text
})
let notification = await newNotif.save();
user.notification.app_notification.push(notification._id)
let newValues = { $set : {
notification : user.notification
}}
user = await User.updateOne({"_id" : user._id}, newValues)
res.json({
type: true,
data: notification
})
}
module.exports = {
listNotification,
addNotification
}
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let articleService = require('../services/article.service')
router.post('/addArticle', ensureAuthorized, articleService.addArtcile)
router.get('/addMarkConcurent/:concurent_name', ensureAuthorized, articleService.addMarkConcurent)
router.get('/listOrganisedConcurent/:bucket_id', ensureAuthorized, articleService.listOrganisedConcurent)
router.get('/listMarkConcurent', ensureAuthorized, articleService.listMarkConcurent)
router.post('/deleteArticle', ensureAuthorized, articleService.deleteArticle)
router.post('/modifyArticle', ensureAuthorized, articleService.modifyArticle)
router.post('/addConcurent', ensureAuthorized, articleService.addConcurent)
router.post('/deleteConcurent', ensureAuthorized, articleService.deleteConcurent)
router.get('/listConcurent/:bucket_id', ensureAuthorized, articleService.listConcurent)
router.get('/listArticleAndConcurent/:bucket_id', ensureAuthorized, articleService.listArticleAndConcurent)
router.get('/listArticle/:bucket_id', ensureAuthorized, articleService.listArticle)
router.get('/infoArticle/:article_id', ensureAuthorized, articleService.infoArticle)
module.exports = router
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
let User = require('./../models/Users')
let Bucket = require('./../models/Bucket')
let Article = require('./../models/Article')
let Historique = require('./../models/History')
let Bilan = require('./../models/Bilan')
let transporter = require('./../utils/mail')
let emailReport = async (req, res) => {
let bilan = await Bilan.findOne({"_id" : req.params.bilan_id})
let user = await User.findOne({token : req.token})
let mailOptions = {
from: '<<EMAIL>>',
to: user.email,
subject: 'Your report of ' + bilan.created_at + ' | Trend-Comparator',
text: 'Hello,'
+ '\n\n' + 'Your new report of' + bilan.created_at
+ '\n\n' + 'Thank you !'
+ '\n\n' + 'Trend-Comparator'
+ '\n' + 'app.trend-comparator.com',
attachments: [
{
path : bilan.url
}
]
};
let mail = transporter.sendMail(mailOptions)
res.json({
type: true,
data: "Email sent"
})
}
let findFile = async (req, res) => {
let bilan = await Bilan.findOne({"_id" : req.params.bilan_id})
res.download(bilan.url);
}
let exportCSV = async (req, res) => {
let bucket_id = req.params.bucket_id.split(',')
var number_article = 0;
var reponse = {
bucket : [
{
bucket_id : "",
bucket_name : "",
article : [],
concurent : []
}
]
}
let index = 0;
let analysed = 0;
for (let bucket of bucket_id) {
let new_bucket = await Bucket.findOne({"_id" : bucket})
reponse.bucket[index].bucket_id = bucket;
reponse.bucket[index].bucket_name = new_bucket.name;
let article = await Article.findOne({"_id" : new_bucket.article})
reponse.bucket[index].article.push(article)
analysed++;
number_article++;
for (let concurent of new_bucket.concurent) {
let new_concurent = await Article.findOne({"_id" : concurent})
reponse.bucket[index].concurent.push(new_concurent)
analysed++;
number_article++;
}
index ++;
if (index == bucket_id.length){
}
else {
reponse.bucket.push({
bucket_id : "",
bucket_name : "",
article : [],
concurent : []
})
}
}
let all_data = reponse
let user = await User.findOne({token: req.params.token})
var concurents = user.concurent;
var new_index_bucket = 0;
var new_index_concurent = 0;
var test_array = [];
for (let bucket of all_data.bucket) {
new_index_concurent = 0;
var new_array_concurent = new Array(concurents.length).fill([]);
for (let concurent of bucket.concurent) {
let indexOfArticle = concurents.indexOf(concurent.name)
new_array_concurent[indexOfArticle] = concurent;
new_index_concurent++;
}
test_array.push(new_array_concurent);
new_index_bucket++;
}
new_index_bucket = 0;
for (let bucket of all_data.bucket) {
all_data.bucket[new_index_bucket].concurent = test_array[new_index_bucket]
new_index_bucket++;
}
var csv = {
line : [[]]
}
csv.line[0] = user.concurent;
csv.line[0].unshift("Your");
csv.line[0].unshift("article");
let line = 1;
for (let bucket of all_data.bucket) {
var new_line = []
for (let concurent of bucket.concurent) {
if (concurent.price != -2) {
new_line.push(concurent.price)
}
}
csv.line.push(new_line);
new_line.unshift(bucket.article[0].price);
new_line.unshift(bucket.bucket_name);
index++;
}
let date = new Date();
date = convertDate(date);
to_save = true;
today = 0;
for (let bilan of user.bilan) {
let new_bilan = await Bilan.findOne({"_id" : bilan, "created_at" : date.toString()})
if (new_bilan != null) {
to_save = false
today++;
}
}
console.log(user.biling_info.company_name);
let fileName = '';
if (to_save == false) {
fileName = "bilan_" + user.biling_info.company_name + '_' + date.toString() + '_' + today + ".csv"
}
else {
fileName = "bilan_" + user.biling_info.company_name + '_' + date.toString() + ".csv"
}
let file_path = './src/public/report/' + fileName
var file = fs.createWriteStream(file_path);
fs.writeFileSync(file_path, csv.line, "UTF-8");
file.on('error', function(err) {
console.log(err)
});
csv.line.forEach(function(v) {
file.write(v.join(',') + '\n');
});
file.end();
let bilan = new Bilan ({
url : file_path,
created_at : date.toString(),
nb_articles : analysed,
moyenne : 0
})
let bilanSaved = await bilan.save()
user.bilan.push(bilanSaved._id)
let newValues = { $set : {
bilan : user.bilan
}}
let new_user = await User.updateOne({token : req.params.token}, newValues)
res.download(file_path);
}
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('-');
}
let listAllBilan = async (req, res) => {
let user = await User.findOne({token : req.token})
var reponse = []
for (let bilan of user.bilan) {
let full_bilan = await Bilan.findOne({"_id" : bilan})
reponse.splice(0, 0, full_bilan);
}
res.json({
type: true,
data: reponse
})
}
//Fonction synchrone
let listBilan = async (req, res) => {
let user = (await User.findOne({token: req.token}, ['bucket']))
let all_bucket = []
for (let bucket of user.bucket) {
let rep = await Bucket.findOne({"_id" : bucket}, ['concurent', 'article', 'name'])
all_bucket.push(rep);
}
let all_history = []
for (let bucket of all_bucket) {
for (let concurent of bucket.concurent) {
let article = await Article.findOne({"_id" : concurent}, ['history', 'name'])
let history = await Historique.findOne({"_id" : article.history})
let new_history = {
concurent : concurent,
history : history
}
all_history.push(new_history)
}
}
let article_history = []
for (let bucket of all_bucket) {
let article = await Article.findOne({"_id": bucket.article}, ['history', 'name'])
let history = await Historique.findOne({"_id" : article.history})
let new_history = {
article : bucket.article,
name : article.name,
history : history
}
article_history.push(new_history)
}
res.json({
type : true,
bucket: all_bucket,
article_history: article_history,
concurent_history: all_history
})
}
let deleteBilan = async (req, res) => {
let user = await User.findOne({token : req.token})
var index = user.bilan.indexOf(req.params.bilan_id);
if (index > -1) {
user.bilan.splice(index, 1);
}
let newValues = { $set: {bilan : user.bilan}}
await User.updateOne({"_id" : user._id}, newValues)
await Bilan.deleteOne({"_id" : req.params.bilan_id})
res.json({
data : user.bilan
})
}
module.exports = {
exportCSV,
listBilan,
listAllBilan,
findFile,
emailReport,
deleteBilan
}
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let bilanService = require('../services/bilan.service')
router.get('/test/:bucket_id/:token', bilanService.exportCSV)
router.get('/deleteReport/:bilan_id', ensureAuthorized, bilanService.deleteBilan)
router.get('/findReport/:bilan_id', bilanService.findFile)
router.get('/sendReportByMail/:bilan_id', ensureAuthorized, bilanService.emailReport)
router.get('/listAllBilan', ensureAuthorized, bilanService.listAllBilan)
router.get('/exportCSV', ensureAuthorized, bilanService.exportCSV)
router.get('/listBilan', ensureAuthorized, bilanService.listBilan)
module.exports = router
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
var scraper = require("../robot/lib/puppeteer");
let User = require('./../models/Users')
let Bucket = require('./../models/Bucket')
let Article = require('./../models/Article')
let Historique = require('./../models/History')
// GET Comparaison
let listCompare = (req, res) => {
}
let listCompareOnOneArticle = (req, res) => {
}
let launchAll = async (req, res) => {
let all_bucket = await Bucket.find({});
for (let the_bucket of all_bucket) {
if (the_bucket.active) {
let bucket = await Bucket.findOne({"_id" : the_bucket._id});
if(bucket) {
let article = await getArticleOfBucket(bucket);
console.log(article);
for(var i = 0; article.length !== i; i++)
{
console.log(article[i]);
let result = await scraper(article[i]);
article[i].price = result.price;
article[i].stock = result.stock;
article[i].img = [ result.img_url ];
var done = await UpdateArticle(article[i]);
var history = await UpdateHistory(article[i]);
console.log("update bucket " + (i + 1) + "/" + article.length);
}
}
}
}
res.json({type: "Success"})
}
//POST Lancée les comparaisons
let launchCompare = async (req, res) => {
let bucket = await Bucket.findOne({"_id" : req.params.id});
if(bucket) {
let article = await getArticleOfBucket(bucket);
for(var i = 0; article.length !== i; i++)
{
let result = await scraper(article[i]);
if (article[i].price) {
article[i].price = result.price;
article[i].stock = result.stock;
article[i].img = [ result.img_url ];
var done = await UpdateArticle(article[i]);
var history = await UpdateHistory(article[i]);
}
console.log("update bucket " + (i + 1) + "/" + article.length);
}
if(done)
res.json({type: true, data: "refresh bucket done"});
else
res.json({type: false , data: "bot: error update"})
}
else {
res.json({type: false , data: "bot: can't find article by id"})
}
};
function getArticleOfBucket(bucket) {
var reponse = {
article: [],
concurent: []
};
let bucket_concurent = bucket.concurent;
return new Promise(resolve => {
Article.findOne({"_id": ObjectId(bucket.article)}, (err, rep) => {
reponse.article.push(rep);
if (bucket_concurent.length != 0) {
bucket_concurent.forEach(function (values, index) {
Article.findOne({"_id": values}, (err, rep) => {
if (err || !rep) {
reject(err);
}
else {
reponse.article.push(rep);
}
if (index === bucket_concurent.length - 1) {
resolve(reponse.article);
}
});
});
}
else {
resolve(reponse.article);
}
})
});
}
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('-');
}
//Trouvé l'historique de l'article
//Verifier qu'il a pas deja un historique d'aujourdhui
//Set les nouvelles valeurs
//push dans les array de l'History
//Update history
let UpdateHistory = async (article) => {
let historique_id = article.history;
let date = new Date();
date = await convertDate(date);
let toSave = true;
let moyenne = 0;
let index = 0;
let toCheck = false;
let historique = await Historique.findOne({"_id" : historique_id})
if (historique == null) {
let new_historique = new Historique ();
new_historique = await new_historique.save();
article.history = new_historique._id;
historique = await Historique.findOne({"_id" : new_historique._id})
await Article.updateOne({_id: article._id}, {$set:{"history" : new_historique._id}});
}
else {
for (let price_history of historique.price_history) {
if (price_history.date == date) {
toSave = false;
}
moyenne += price_history.price;
index++;
}
toCheck = true;
}
moyenne = moyenne / index + 1
console.log("Moyenne" + moyenne);
// si prix < moyenne * 60
// prix = -2
// not save
if (toSave) {
if (toCheck == true && article.price < moyenne * 0.60)
{
await Article.updateOne({_id: article._id}, {$set:{"price" : -2}});
}
else {
if (article.price != -2) {
let new_price_history = {
price : article.price,
date : date
}
let new_stock_history = {
stock : article.stock,
date : date
}
historique.price_history.push(new_price_history);
historique.stock_history.push(new_stock_history);
await Historique.updateOne({"_id" : historique._id}, {$set: {"price_history" : historique.price_history, "stock_history" : historique.stock_history}})
}
}
}
return;
}
function UpdateArticle(article) {
return new Promise(resolve => {
Article.updateOne({_id: article._id}, {$set:{"price" : article.price, "stock" : article.stock, "img": article.img}}, (err, data) => resolve(data));
})
}
let launchCompareOnOneArticle = async (req, res) => {
let article = await Article.findOne({"_id" : req.params.id})
if(article)
{
let result = await scraper(article);
console.log(result.price);
article.price = result.price;
article.stock = result.stock;
article.img = [ result.img_url ];
let done = await UpdateArticle(article);
var history = await UpdateHistory(article);
if(done)
res.json({type: true, data: "done"});
else
res.json({type: false , data: "bot: error update"})
}
else {
res.json({type: false , data: "bot: can't find article by id"})
}
};
//POST Delete des comparaisons
let deleteCompareOnOneArticle = (req, res) => {
};
let deleteCompare = (req, res) => {
};
//POST Regénerer les comparaisons
let LaunchAndDeleteCompare = (req, res) => {
}
let LaunchAndDeleteCompareOnOneArticle = (req, res) => {
}
module.exports = {
launchCompare,
listCompare,
listCompareOnOneArticle,
launchCompareOnOneArticle,
deleteCompareOnOneArticle,
deleteCompare,
LaunchAndDeleteCompare,
LaunchAndDeleteCompareOnOneArticle,
launchAll,
getArticleOfBucket,
UpdateHistory,
UpdateArticle
}
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
var jsonexport = require('jsonexport');
let User = require('./../models/Users')
let Bucket = require('./../models/Bucket')
let Article = require('./../models/Article')
let Historique = require('./../models/History')
let listOrganisedConcurent = async (req, res) => {
let bucket_id = req.params.bucket_id.split(',')
var number_article = 0;
var reponse = {
bucket : [
{
bucket_id : "",
bucket_name : "",
article : [],
concurent : []
}
]
}
let index = 0;
for (let bucket of bucket_id) {
let new_bucket = await Bucket.findOne({"_id" : bucket})
reponse.bucket[index].bucket_id = bucket;
reponse.bucket[index].bucket_name = new_bucket.name;
let article = await Article.findOne({"_id" : new_bucket.article})
reponse.bucket[index].article.push(article)
number_article++;
for (let concurent of new_bucket.concurent) {
let new_concurent = await Article.findOne({"_id" : concurent})
reponse.bucket[index].concurent.push(new_concurent)
number_article++;
}
index ++;
if (index == bucket_id.length){
}
else {
reponse.bucket.push({
bucket_id : "",
bucket_name : "",
article : [],
concurent : []
})
}
}
let all_data = reponse
let user = await User.findOne({token : req.token})
var concurents = user.concurent;
var new_index_bucket = 0;
var new_index_concurent = 0;
var test_array = [];
for (let bucket of all_data.bucket) {
new_index_concurent = 0;
var new_array_concurent = new Array(concurents.length).fill([]);
for (let concurent of bucket.concurent) {
let indexOfArticle = concurents.indexOf(concurent.name)
new_array_concurent[indexOfArticle] = concurent;
new_index_concurent++;
}
test_array.push(new_array_concurent);
new_index_bucket++;
}
new_index_bucket = 0;
for (let bucket of all_data.bucket) {
all_data.bucket[new_index_bucket].concurent = test_array[new_index_bucket]
new_index_bucket++;
}
res.json({
type: true,
data: all_data,
number_article : number_article
})
return (all_data);
}
let addMarkConcurent = async (req, res) => {
let user = await User.findOne({token : req.token})
if (user.nb_concurent_free == 0) {
res.json({
type: false,
data : "You can't add an other concurent"
})
}
else {
let new_concurent = user.concurent;
new_concurent.push(req.params.concurent_name)
let newValues = { $set : {
concurent : new_concurent,
nb_concurent : user.nb_concurent + 1,
nb_concurent_free : user.nb_concurent_free - 1
}}
let new_user = await User.updateOne({token: req.token}, newValues)
res.json({
type: true,
data: "Concurent added"
})
}
}
let listMarkConcurent = async (req, res) => {
let user = await User.findOne({token : req.token})
res.json({
type: true,
data: user.concurent
})
}
let listArticleAndConcurent = async (req, res) => {
let bucket_id = req.params.bucket_id.split(',')
var number_article = 0;
var reponse = {
bucket : [
{
bucket_id : "",
bucket_name : "",
article : [],
concurent : []
}
]
}
let index = 0;
for (let bucket of bucket_id) {
let new_bucket = await Bucket.findOne({"_id" : bucket})
reponse.bucket[index].bucket_id = bucket;
reponse.bucket[index].bucket_name = new_bucket.name;
let article = await Article.findOne({"_id" : new_bucket.article})
reponse.bucket[index].article.push(article)
number_article++;
for (let concurent of new_bucket.concurent) {
let new_concurent = await Article.findOne({"_id" : concurent})
reponse.bucket[index].concurent.push(new_concurent)
number_article++;
}
index ++;
if (index == bucket_id.length){
}
else {
reponse.bucket.push({
bucket_id : "",
bucket_name : "",
article : [],
concurent : []
})
}
}
res.json({
type: true,
data: reponse,
number_article : number_article
})
return (reponse);
}
let modifyArticle = (req, res) => {
let newValues = { $set: {
url: req.body.url,
name: req.body.name,
ref: req.body.ref,
price: req.body.price,
stock: req.body.stock
}}
Article.updateOne({"_id" : req.body.article_id}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't update this article"
})
}
else {
res.json({
type: true,
data: "Article updated"
})
}
})
}
let listConcurent = (req, res) => {
Bucket.findOne({"_id" : req.params.bucket_id}, (err, rep) => {
if (err || !rep) {
res.json({
type:false,
data: "Can't find this bucket"
})
}
else {
var bar = new Promise((resolve, reject) => {
var concurent_array = [];
var len = rep.concurent.length;
rep.concurent.forEach(function(values, index) {
Article.findOne({"_id" : values}, (err, rep) => {
if (err) {console.log(err);}
else {
concurent_array.push(rep);
}
if (index == len - 1) resolve(concurent_array);
})
})
})
bar.then((rep, err) => {
res.json({
type: true,
data: rep,
number: rep.length
})
})
}
})
}
let addConcurent = (req, res) => {
let newConcurent = new Article({
url: req.body.concurent_url,
name: req.body.concurent_name
})
newConcurent.save((err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't create concurent"
})
}
else {
let article_id = rep._id;
Bucket.findOne({"_id" : req.body.bucket_id}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't find this bucket"
})
}
else {
if (rep.concurent == undefined) {
rep.concurent = [article_id];
}
else {
rep.concurent.push(article_id);
}
let newValues = { $set: {
concurent: rep.concurent
}}
Bucket.updateOne({"_id" : req.body.bucket_id}, newValues, (err, rep) => {
console.log(err);
if (err || !rep) {
res.json({
type: false,
data: "Can't update bucket concurent array"
})
}
else {
res.json({
type: true,
data: "Concurent created and attached to bucket",
concurent_id : article_id
})
}
})
}
})
}
})
}
let deleteHistoriqueOfArticle = async(article_id) => {
let article = await Article.findOne({"_id" : article_id})
await Historique.deleteOne({"_id" : article.history})
return;
}
let deleteConcurent = (req, res) => {
Bucket.findOne({"_id" : req.body.bucket_id}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't find this bucket"
})
}
else {
deleteHistoriqueOfArticle(rep.article);
let newArray = rep.concurent;
let index = newArray.indexOf(req.body.concurent_id);
newArray.splice(index, 1);
let newValues = { $set: {
concurent: newArray
}}
Bucket.updateOne({"_id" : rep._id}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't update Bucket"
})
}
else {
Article.deleteOne({"_id" : req.body.concurent_id}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't delete this article"
})
}
else {
res.json({
type: true,
data: "Concurent succesfully deleted"
})
}
})
}
})
}
})
}
let addArtcile = (req, res) => {
let url = req.body.url;
let name = req.body.name;
let bucket_id = req.body.bucket_id;
let token = req.token;
let newArticle = new Article({
url: url,
name: name
})
newArticle.save((err, rep) => {
let article_id = rep._id;
Bucket.findOne({"_id" : bucket_id}, (err, rep) => {
if (err || !rep) {
Article.deleteOne({"_id" : article_id}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't delete article"
})
}
else {
res.json({
type: false,
data: "Bucket not found"
})
}
})
}
else {
let new_article = article_id;
let new_values = { $set : {
article : new_article
}}
Bucket.updateOne({"_id" : bucket_id}, new_values, (err, rep) => {
User.findOne({token : token}, (err, rep) => {
let nb_articles = parseInt(rep.nb_articles);
let nb_articles_free = parseInt(rep.nb_articles_free);
nb_articles += 1;
nb_articles_free -= 1;
if (nb_articles <= rep.limit_articles) {
let newValues = { $set : {
nb_articles: nb_articles.toString(),
nb_articles_free: nb_articles_free.toString()
}}
User.updateOne({token: token}, newValues, (err, rep) => {
res.json ({
type: true,
data: "Article added successfully",
article_id : article_id
})
})
}
else {
res.json({
type: false,
data: "No more slots for an other article"
})
}
})
})
}
})
})
}
let deleteArticle = (req, res) => {
let article_id = req.body.article_id;
let bucket_id = req.body.bucket_id;
Article.deleteOne({"_id" : article_id}, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "Can't delete article"
})
}
else {
Bucket.findOne({"_id": bucket_id}, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "Can't find Bucket"
})
}
else {
let new_article;
let new_values = { $set: {
article : new_article
}}
Bucket.updateOne({"_id" : bucket_id}, new_values, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't remove article from bucket"
})
}
else {
res.json({
type: true,
data: "Corretly deleted article"
})
}
})
}
})
}
})
}
async function listArticle(req, res) {
let bucket_id = req.params.bucket_id.split(",");
let article = [];
var bar = new Promise((resolve, reject) => {
bucket_id.forEach(function(values, index) {
Bucket.findOne({"_id" : values}, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "Can't find Bucket id" + values
})
reject();
}
else {
let bucket = rep;
Article.findOne({"_id" : rep.article}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Error occured when trying to find article"
})
reject();
}
else {
article.push(rep);
}
if (index == bucket_id.length - 1) resolve(article);
})
}
})
})
})
bar.then((rep, err) => {
if (err || !rep) {
res.json({
type: false,
data: "Error occured"
})
}
else {
res.json({
type: true,
data: rep
})
}
})
}
let infoArticle = (req, res) => {
Article.findOne({"_id" : req.params.article_id}, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "Can't find this article"
})
}
else {
res.json({
type: true,
data: rep
})
}
})
}
module.exports = {
addArtcile,
deleteArticle,
addConcurent,
deleteConcurent,
listArticle,
infoArticle,
listConcurent,
modifyArticle,
listArticleAndConcurent,
listMarkConcurent,
listOrganisedConcurent,
addMarkConcurent
}
<file_sep>let ObjectId = require('mongodb').ObjectID
let fs = require('fs')
let path = require('path')
let User = require('./../models/Users')
let Bucket = require('./../models/Bucket')
let Article = require('./../models/Article')
let Historique = require('./../models/History')
let addBucket = (req, res) => {
User.findOne({token : req.token}, (err, rep) => {
let created_at = new Date();
let newBucket = new Bucket({
name: req.body.name,
active: true,
delay: 0,
created_at: created_at,
});
let user = rep;
newBucket.save((err, rep) => {
let id_bucket = rep._id;
let new_array = user.bucket;
if (new_array) {
new_array.push(id_bucket);
}
else {
new_array = [id_bucket];
}
let newValues = { $set : {bucket: new_array}}
User.updateOne({"_id" : ObjectId(user._id)}, newValues, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "Can't add the new bucket"
})
}
else {
res.json ({
type: true,
data: "Bucket added succesfully",
bucket_id : id_bucket
})
}
})
})
})
}
let deleteAllArticle = async (bucket_id) => {
let bucket = await Bucket.findOne({"_id" : bucket_id})
let article = await Article.findOne({"_id" : bucket.article})
await Article.deleteOne({"_id" : bucket.article})
await Historique.deleteOne({"_id" : article.history})
for (let concurent of bucket.concurent) {
article = await Article.findOne({"_id" : concurent})
await Article.deleteOne({"_id" : concurent})
await Historique.deleteOne({"_id" : article.history})
}
return;
}
let deleteBucketId = (req, res) => {
let bucket_id = req.params.bucket_id;
let token = req.token
deleteAllArticle(bucket_id);
Bucket.deleteOne({"_id" : bucket_id}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't delete this bucket"
})
}
else {
User.findOne({token: token}, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't find user"
})
}
else {
let bucket_array = rep.bucket;
let index = bucket_array.indexOf(bucket_id);
if (index > - 1) {
bucket_array.splice(index, 1);
}
let nbr_articles = parseInt(rep.nb_articles) - 1;
let nbr_articles_free = parseInt(rep.nb_articles_free) + 1;
let newValues = { $set : {
bucket : bucket_array,
nb_articles : nbr_articles.toString(),
nb_articles_free : nbr_articles_free.toString()
}}
User.updateOne({token: token}, newValues, (err, rep) => {
if (err || !rep) {
res.json({
type: false,
data: "Can't update profile"
})
}
else {
res.json({
type: true,
data: "Profile updated"
})
}
})
}
})
}
})
}
let deleteBucket = (req, res) => {
User.findOne({token: req.token}, (err, rep) => {
var user = rep;
var bar = new Promise((resolve, reject) => {
rep.bucket.forEach(function(values, index) {
Bucket.deleteOne({"_id": values}, (err, rep) => {})
if (index == user.bucket.length - 1) resolve();
})
})
bar.then((rep, err) => {
let newValues = { $set: {
bucket: null
}}
User.updateOne({"_id" : ObjectId(user._id)}, newValues, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "Can't delete actual list of bucket"
})
}
else {
res.json({
type: true,
data: "Deleted succesfully all bucket"
})
}
})
})
})
}
let listBucketId = (req, res) => {
Bucket.findOne({"_id": req.params.bucket_id}, (err, rep) => {
if (err || !rep) {
res.json ({
type: false,
data: "No Bucket with this id found"
})
}
else {
res.json({
type: true,
data: rep
})
}
})
}
let listBucket = async (req, res) => {
let user = await User.findOne({token: req.token})
if (!user.bucket || user.bucket.length == 0 || user.bucket == undefined) {
var bucket_length = 0;
res.json({
type: true,
data: [],
number: 0
})
return;
}
var bucket_length = user.bucket.length;
let all_bucket = []
for (let bucket of user.bucket) {
let new_bucket = await Bucket.findOne({"_id" : bucket})
all_bucket.push(new_bucket)
}
res.json({
type: true,
data: all_bucket,
number: all_bucket.length
})
}
module.exports = {
addBucket,
deleteBucketId,
deleteBucket,
listBucket,
listBucketId
}
<file_sep># Trend-Comparator-Back
## DEV MODE
```sh
$ export NODE_ENV=development
$ npm install
$ npm start
```
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let historyService = require('../services/history.service')
router.get('/history/:article_id', ensureAuthorized, historyService.listArticleHistory)
router.get('/statsArticle', ensureAuthorized, historyService.statsArticle)
router.get('/statsConcurents', ensureAuthorized, historyService.statsConcurents)
router.get('/statsOnBucket/:bucket_id', ensureAuthorized, historyService.statsBucket)
router.put('/addArticleHistory/:article_id', ensureAuthorized, historyService.addHistory)
module.exports = router
<file_sep>var mongojs = require('mongojs');
var ObjectId = mongojs.ObjectID;
var db = mongojs("mongodb://" + "fluorz:<EMAIL>:45923/trend-comparator");
var Bucket = db.collection('buckets');
var Article = db.collection('articles');
class BucketHelper {
constructor() {
}
getAllBucket() {
console.log("find Bucket ... ");
return new Promise((resolve => {
Bucket.find({}, (err, data) => {
console.log("find done");
resolve(data)
});
}));
}
getArticleOfBucket(bucket) {
var reponse = {
article: [],
concurent: []
};
let bucket_concurent = bucket.concurent;
return new Promise(resolve => {
Article.findOne({"_id": ObjectId(bucket.article)}, (err, rep) => {
reponse.article.push(rep);
bucket_concurent.forEach(function (values, index) {
Article.findOne({"_id": values}, (err, rep) => {
if (err || !rep) {
reject(err);
}
else {
reponse.article.push(rep);
}
if (index === bucket_concurent.length - 1) {
resolve(reponse.article);
}
});
});
})
});
}
UpdateArticle(article)
{
return new Promise(resolve => {
Article.updateOne({_id: article._id}, {$set:{"price" : article.price, "stock" : article.stock, "img": article.img}}, (err, data) => resolve(data));
})
}
}
var scraper = require("../lib/puppeteer");
async function exec_robot() {
let bucketHelper = new BucketHelper();
let b = await bucketHelper.getAllBucket();
console.log("buckets:", b.length);
let articlesOfBucket = [];
for(var i = 0; b.length !== i; i++)
{
let res;
res = await bucketHelper.getArticleOfBucket(b[i]);
Array.prototype.push.apply(articlesOfBucket ,res);
}
console.log("Jobs", articlesOfBucket.length);
let result = [];
for(var x = 0; articlesOfBucket.length !== x; x++) {
console.log("goto scrap => ", articlesOfBucket[x].url);
result = await scraper(articlesOfBucket[x]);
articlesOfBucket[x].price = result.price;
articlesOfBucket[x].stock = result.stock;
articlesOfBucket[x].img = [ result.img_url ];
}
for(var z = 0; articlesOfBucket.length !== z; z++) {
result = await bucketHelper.UpdateArticle(articlesOfBucket[z]);
console.log((result) ? ("update " + (z + 1) + "/" + articlesOfBucket.length) : ("fail " + (z + 1) + "/" + articlesOfBucket.length));
}
process.exit(0);
}
exec_robot();
<file_sep>module.exports = {
db:{
uri: ""
}
};<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let stripeService = require('../services/stripe.service')
router.post('/subscriptionPlan/:plan', ensureAuthorized, stripeService.subscriptionPlan)
router.post('/upgradePlan/:plan', ensureAuthorized, stripeService.upgradePlan)
router.post('/stopPlan/:plan', ensureAuthorized, stripeService.stopPlan)
module.exports = router
<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var HistorySchema = mongoose.Schema({
price_history: [
{
price : Number,
date: String
}
],
stock_history: [
{
stock: String,
date: String
}
]
});
var Historique = module.exports = mongoose.model('Historique', HistorySchema);
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let signinService = require('../services/signin.service')
router.post('/signin', signinService.signin)
router.get('/logout', ensureAuthorized, signinService.logout)
router.post('/register', signinService.register)
router.get('/checkLogin', signinService.checkLogin)
router.post('/forgotPassword', signinService.forgotPassword)
module.exports = router
<file_sep>let server, serverHttp
let express = require("express")
let morgan = require("morgan")
let path = require("path")
let app = express()
let bodyParser = require("body-parser")
let compression = require('compression')
let mongoose = require("mongoose")
let https = require("https")
let fs = require("fs")
let users = require('./routes/users')
let signin = require('./routes/signin')
let article = require('./routes/article')
let comparator = require('./routes/comparator')
let bucket = require('./routes/bucket')
let history = require('./routes/history')
let bilan = require('./routes/bilan')
let notification = require('./routes/notification')
let stripe = require('./routes/stripe')
let report = require('./routes/report')
let config = require(path.resolve(path.resolve(__dirname) + '/config/index.js'))
let port = config.PORT
// Connect to DB
try {
mongoose.connect("mongodb://" + "fluorz:le<EMAIL>@ds145923.mlab.com:45923/trend-comparator" , { useNewUrlParser: true })
}
catch (err) {
console.log("Erreur of connection")
stop();
}
app.use(compression())
app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))
app.use(morgan("tiny"))
app.use('/public/', express.static("./src/public/"));
app.use('/assets/', express.static("./src/assets/"));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization')
next()
})
app.use('/', users)
app.use('/', signin)
app.use('/', article)
app.use('/', comparator)
app.use('/', bucket)
app.use('/', history)
app.use('/', bilan)
app.use('/', notification)
app.use('/', stripe)
app.use('/', report)
server = app.listen(port, () => {console.log( "Express server listening on port " + port)})
process.on('uncaughtException', err => {
console.log(err)
})
app.get('/', (req, res) => {
res.json("Trend Comparator API V1.0")
})
function stop() {
server.close()
}
module.exports = app
module.exports.stop = stop
<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = mongoose.Schema({
first_name: String,
last_name: String,
email: String,
password: String,
bucket: Array,
report_email: Boolean,
nb_articles_free: String,
nb_articles: String,
limit_articles: String,
limit_concurent : Number,
nb_concurent : Number,
nb_concurent_free : Number,
concurent : Array,
haveSubscribe : Boolean,
bilan : Array,
info : {
username : String,
profile_picture : String
},
offre : {
plan : String,
last_payment : Date,
stripeToken : String,
stripeEmail : String,
stripeSub : String
},
biling_info: {
company_name : String,
address_1 : String,
address_2 : String,
city : String,
state : String,
zip_code : String,
phone : String,
email : String
},
notification : {
report_email : Boolean,
delay : String,
alert_email : Boolean,
newletters : Boolean,
app_notification : Array
},
disable: Boolean,
token: String
});
var User = module.exports = mongoose.model('User', UserSchema);
<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BucketSchema = mongoose.Schema({
article: String,
concurent: Array,
created_at: Date,
delay: String,
name: String,
active: Boolean
});
var Bucket = module.exports = mongoose.model('Bucket', BucketSchema);
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let notificationService = require('../services/notification.service')
router.get('/listNotification', ensureAuthorized, notificationService.listNotification)
router.post('/addNotification', ensureAuthorized, notificationService.addNotification)
module.exports = router
<file_sep>var mongoose = require('mongoose');
let ObjectId = require('mongodb').ObjectID
var Schema = mongoose.Schema;
var NotificationSchema = mongoose.Schema({
icon : String,
title : String,
text : String
});
var Notifications = module.exports = mongoose.model('Notification', NotificationSchema);
<file_sep>let express = require("express")
let router = express.Router()
let ensureAuthorized = require("./../middlewares/ensureAuthorized")
let multiparty = require('connect-multiparty')
let multipartyMiddleware = multiparty()
let compareService = require('../services/comparator.service')
router.get('/launchCompareOnAllBucket', compareService.launchAll)
router.get('/listCompare', ensureAuthorized, compareService.listCompare)
router.get('/listCompare/:article_id', ensureAuthorized, compareService.listCompareOnOneArticle)
router.get('/fillCompareBucket/:id', ensureAuthorized, compareService.launchCompare)
router.get('/fillCompare/:id', ensureAuthorized, compareService.launchCompareOnOneArticle)
router.post('/deleteCompare/:id', ensureAuthorized, compareService.deleteCompareOnOneArticle)
router.post('/deleteCompare', ensureAuthorized, compareService.deleteCompare)
router.post('/reFillCompare', ensureAuthorized, compareService.LaunchAndDeleteCompare)
router.post('/reFillCompare/:id', ensureAuthorized, compareService.LaunchAndDeleteCompareOnOneArticle)
module.exports = router
<file_sep>var mongoose = require('mongoose');
let ObjectId = require('mongodb').ObjectID
var Schema = mongoose.Schema;
var BilanSchema = mongoose.Schema({
url : String,
created_at : String,
nb_articles : Number,
moyenne : Number
});
var Bilan = module.exports = mongoose.model('Bilan', BilanSchema);
|
634f7c17096ee793749732673bcd092787a820ee
|
[
"JavaScript",
"Markdown"
] | 28
|
JavaScript
|
EpitechTeam/Trend-Comparator-Back
|
3216839f158c7d87091f2553fb243c980b8fcb43
|
ca0fd56d7a1197ef2af32cfa8ce9e0b16b1e4900
|
refs/heads/main
|
<repo_name>Martin-EG/prestamos_app_react<file_sep>/src/componentes/Resultado.js
import React from 'react';
const Resultado = ({ cantidad, plazo, total }) => (
<div className="u-full-width resultado">
<h2>Resumen</h2>
<p>La cantidad solicitada es de: ${cantidad}</p>
<p>A pagar en: {plazo} meses</p>
<p>En pagos mensuales de: ${(total/plazo).toFixed(2)}</p>
<p>Su total a pagar es de: ${(total).toFixed(2)} meses</p>
</div>
);
export default Resultado;
|
2746ad7b52ae8ab16b132d2b0e66371d1ff6384b
|
[
"JavaScript"
] | 1
|
JavaScript
|
Martin-EG/prestamos_app_react
|
4e639e8e4315964ea143ada21c8885c7b23b86fd
|
55f908d101adc8c066d144bdb40167c9fa8158a7
|
refs/heads/master
|
<repo_name>udallmo/breakout<file_sep>/main.py
import pygame
from paddle import Paddle
from ball import Ball
from brick import Brick
pygame.init()
# define colors
WHITE = (255, 255, 255)
DARKBLUE = (36, 90, 190)
LIGHTBLUE = (0, 176, 240)
ORANGE = (255, 100, 0)
RED = (255, 0 ,0)
YELLOW = (255, 255, 0)
score = 0
lives = 3
# open a new window
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Breakout Game")
paddleA = Paddle(WHITE, 10, 100)
paddleA.rect.x = 20
paddleA.rect.y = 200
paddleB = Paddle(WHITE, 10, 100)
paddleB.rect.x = 670
paddleB.rect.y = 200
all_sprites_list = pygame.sprite.Group()
paddle = Paddle(LIGHTBLUE, 100, 10)
paddle.rect.x = 350
paddle.rect.y = 560
ball = Ball(WHITE, 10, 10)
ball.rect.x = 345
ball.rect.y = 195
all_bricks = pygame.sprite.Group()
for i in range(7):
brick = Brick(RED, 80, 30)
brick.rect.x = 60 + i*100
brick.rect.y = 60
all_sprites_list.add(brick)
all_bricks.add(brick)
for i in range(7):
brick = Brick(ORANGE, 80, 30)
brick.rect.x = 60 + i*100
brick.rect.y = 100
all_sprites_list.add(brick)
all_bricks.add(brick)
for i in range(7):
brick = Brick(RED, 80, 30)
brick.rect.x = 60 + i*100
brick.rect.y = 140
all_sprites_list.add(brick)
all_bricks.add(brick)
all_sprites_list.add(paddle)
all_sprites_list.add(ball)
carryOn = True
clock = pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type == pygame.QUIT:
carryOn = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
carryOn = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
paddle.moveLeft(5)
if keys[pygame.K_RIGHT]:
paddle.moveRight(5)
# game logical
all_sprites_list.update()
if ball.rect.x >= 790:
ball.velocity[0] = -ball.velocity[0]
if ball.rect.x <= 0:
ball.velocity[0] = -ball.velocity[0]
if ball.rect.y > 590:
ball.velocity[1] = -ball.velocity[1]
lives -= 1
if lives == 0:
font = pygame.font.Font(None, 74)
text = font.render("Game Over", 1, WHITE)
screen.blit(text, (250, 300))
pygame.display.flip()
pygame.time.wait(3000)
carryOn = False
if ball.rect.y < 40:
ball.velocity[1] = -ball.velocity[1]
if pygame.sprite.collide_mask(ball, paddle):
ball.rect.x -= ball.velocity[0]
ball.rect.y -= ball.velocity[1]
ball.bounce()
brick_collision_list = pygame.sprite.spritecollide(ball, all_bricks, False)
for brick in brick_collision_list:
ball.bounce()
score +=1
brick.kill()
if len(all_bricks) == 0:
font = pygame.font.Font(None, 74)
text = font.render("LVL complete", 1, WHITE)
screen.blit(text, (200, 300))
pygame.display.flip()
pygame.time.wait(3000)
carryOn = False
screen.fill(DARKBLUE)
pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
font = pygame.font.Font(None, 34)
text = font.render("SCORE: " + str(score), 1, WHITE)
screen.blit(text, (20, 10))
text = font.render("LIVES: " + str(lives), 1, WHITE)
screen.blit(text, (650, 10))
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
2c356cfa79f4c981350527ba7c05f228759618f5
|
[
"Python"
] | 1
|
Python
|
udallmo/breakout
|
2bf6f566843664cd99e2e4bcf0c10f80e511bde3
|
eb1edd1b9e3bd81fa0a47da46d6e0731f26f5707
|
refs/heads/master
|
<file_sep>package common;
public class Protocol {
public static final String CLOSED_GAME = "CLOSED_GAME";
public static int PUERTO_SERVER_SOCKET = 1075;
public static int PUERTO_SERVER_RMI=1069;
public static String HOST_SERVER="localhost";
public static String ID_SERVER_RMI="SERVER";
public static String NEW_GAME="NEW_GAME";
public static String NEW_GAME_CARD="NEW_GAME_CARD";
public static String REFRESH="REFRESH";
public static String WORKSPACE_REJECTED ="WORKSPACE_REJECTED";
public static String SEPARATOR1 = ";;;";
public static String SEPARATOR2 = ":::";
}
<file_sep>package common;
import java.io.Serializable;
public class Card implements Serializable{
public static final String PROPOSED = "PROPOSED";
public static final String ACCEPTED = "ACCEPTED";
private int id;
private String name;
private String description;
private String imageUrl;
private String category;
private String place;
private String owner;
private int votes;
public Card(int id, String name, String description, String imageUrl,
String category, String place, String owner, int votes) {
super();
this.id = id;
this.name = name;
this.description = description;
this.imageUrl = imageUrl;
this.category = category;
this.place = place;
this.owner = owner;
this.votes = votes;
}
public int getVotes() {
return votes;
}
public void setVotes(int votes) {
this.votes = votes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String toString()
{
return id + " - " + name;
}
}
<file_sep>CardGamesServer
===============
CardGames servidor
<file_sep>package common;
import java.rmi.Remote;
import java.util.ArrayList;
public interface InterfaceServer extends Remote
{
public boolean login(String user, String password) throws Exception;
public boolean signUp(String username, String name, String password, String email) throws Exception;
public User getUser(String username) throws Exception;
public Card getCard(int id) throws Exception;
public Workspace getWorkspace(int id) throws Exception;
public ArrayList<User> getActiveUsers(String username) throws Exception;
public ArrayList<Card> getCards(String username) throws Exception;
public ArrayList<Workspace> getMyWorkspaces( String username) throws Exception;
public boolean createCard( String name, String description, String imageUrl, String place, String owner, String category) throws Exception;
public boolean addCardToDeck( String username, int cardId) throws Exception;
public boolean removeCardFromDeck(String username, int cardId)throws Exception;
public boolean startGame(String username, ArrayList<String> guests)throws Exception;
public boolean startGame(int cardId, String username, ArrayList<String> guests)throws Exception;
public boolean proposeCard( int workspaceId, int cardId)throws Exception;
public boolean voteCard( int workspaceId, int cardId)throws Exception;
public boolean sendMessage( int workspaceId, String username, String message)throws Exception;
public boolean acceptGame(String threadId, String username)throws Exception;
public boolean rejectGame(String threadId, String username)throws Exception;
public void quit(String username)throws Exception;
public ArrayList<Card> getMyCards(String username) throws Exception;
public void quitWorkspace(String username, int workspace) throws Exception;
}<file_sep>package server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import common.Card;
public class ThreadNewWorkspace extends Thread {
// -----------------------------------------------------------------
// Atributos
// -----------------------------------------------------------------
/**
* constante que indica que el workspace no se creara a partir de una carta
*/
public final static int NO_CARD=-1;
/**
* numero de participantes que han confirmado
*/
private int confirms;
/**
* numero de rechazos, con 1 es mas que suficiente para cancelar la partida
*/
private int rejects;
/**
* El canal usado para comunicarse con el jugador 1
*/
private ArrayList<UserSession> users;
/**
* La sesssion del creador del workspace
*/
private UserSession userCreator;
/**
* marca de tiempo para el timeout
*/
private long timeStamp;
/**
* id temporal del workspace (thread) que se cargara
*/
private String idThread;
/**
* numero de la carta que se invita, -1 si no se crea partir de una carta
*/
private int cardId;
// -----------------------------------------------------------------
// Constructores
// -----------------------------------------------------------------
/**
* constructor del thread que se encarga de coordinar la creacion de workspaces
* @param userSessionCreator session del creado
* @param users los participantes del workspaces, excluyendo al creador
* @param card carta inicial que se motiva a usar, puede ser -1 y no haber ninguna carta
*/
public ThreadNewWorkspace (UserSession userSessionCreator, ArrayList<UserSession> users, int card)
{
// 1 voto del creador
confirms = 0;
userCreator = userSessionCreator;
this.users = users;
timeStamp = System.currentTimeMillis();
idThread= userSessionCreator.getUserName() + " inviting to: " + users.toString();
this.cardId=card;
rejects=0;
}
// -----------------------------------------------------------------
// Métodos
// -----------------------------------------------------------------
/**
* Método que se invoca cuando inicia la ejecución del thread
* envia un mensaje de invitacion a la partida
* coordina la creacion de workspace
*/
public void run( )
{
try
{
//se envia por socket a los participantes de la nueva partida
for (int i = 0; i < users.size(); i++) {
UserSession tmp = users.get(i);
if(cardId!=NO_CARD)
{
tmp.sendPushNewGameCard(userCreator.getUserName(), cardId, idThread);
}
else
{
tmp.sendPushNewGame(userCreator.getUserName(), idThread);
}
}
// se inicia un temporizador, si alguien cancela o pasan 15 seg se termina
int confirmsNeeded=users.size();
long millisPassed = System.currentTimeMillis()-timeStamp;
while(confirms<confirmsNeeded && millisPassed < 1500000 && rejects==0)
{
millisPassed = System.currentTimeMillis()-timeStamp;
}
// en caso de que haya pasado el tiempo y uno no haya respondido, se cancela del error por timeout
if(confirms!=confirmsNeeded && rejects==0)
{
sendCancelation("Time Out: se ha agotado el tiempo de espera \n" +
"uno de los participantes no respondio a la solicitud \n" +
"La partida: \n" + idThread + " no se cargara");
}
//se acaba el thread, la confirmacion o rechazo se llaman desde el servidor
}
catch( Exception e )
{
//enviar un error en caso de alguna excepcion no contemplada
sendCancelation("Error cargando la partida " + idThread + " no se cargara");
}
}
public int getCardId() {
return cardId;
}
/**
* envia a todos los particiapntes un anuncion de cancelacion de la partida
* @param message el motivo de la cancelacion
*/
public void sendCancelation(String message)
{
userCreator.sendPushCancel(message);
for (int i = 0; i < users.size(); i++) {
UserSession tmp = users.get(i);
tmp.sendPushCancel(message);
}
}
/**
* envia una notificacion de refrescar con el id del workspace creado o cargado
* @param idWorkspace el id del workspace a refrescar (el reciente cargado o creado)
*/
public void sendConfirmation(int idWorkspace)
{
userCreator.sendPushRefresh(idWorkspace,true);
for (int i = 0; i < users.size(); i++) {
UserSession tmp = users.get(i);
tmp.sendPushRefresh(idWorkspace,true);
}
}
/**
* confirmacion de un particiapnte
*/
public void confirm() {
confirms++;
}
/**
* rechazo de un participante
*/
public void reject() {
rejects++;
}
/**
* tomar el id temporal del threat
* @return id del threat
*/
public String getIdThreat() {
return idThread;
}
/**
* metodo que valida si ya esta listo para crear el workspace
* @return true si ya todos confirmaron, false en caso contrario
*/
public boolean readyToCreate() {
return (users.size()<=confirms);
}
/**
* Método que retorna los usernames de los usuarios asociados al workspace como una lista
* @return Lista que contiene los usernames
*/
public ArrayList<String> getUsernamesList()
{
ArrayList<String> list = new ArrayList<String>();
for(UserSession session: users)
{
list.add(session.getUserName());
}
list.add(userCreator.getUserName());
return list;
}
}
|
da266e5d6dcf4bc4a4e7c63b70fb5e92c009f1f4
|
[
"Markdown",
"Java"
] | 5
|
Java
|
sct1992/CardGamesServer
|
c95c9c8186389caa7f084ea7e529b3f6b8d55da7
|
e95cad22a08f3adc8499a8009e584d287920f54e
|
refs/heads/master
|
<repo_name>JosePedroDias/paste<file_sep>/serve.php
<?php
$id = $_REQUEST['id'];
function is_valid_id($id) {
return preg_match('/^[a-z0-9_]{1,32}$/', $id);
}
// validate id
if ($op !== 'list' && !is_valid_id($id)) {
echo 'invalid id!';
exit(0);
}
$dn = 'pastes';
$fn = $dn . '/' . $id;
// process operation
if (file_exists($fn)) {
header('Content-Type: text/html');
echo file_get_contents($fn);
}
else {
echo 'inexistant id!';
}
<file_sep>/paste.js
(function(window) {
'use strict';
/*jshint browser:true, eqeqeq:true, undef:true, curly:true, laxbreak:true, forin:false, smarttabs:true */
/*global console:false, Showdown:false */
(function() {
var writer = new stmd.HtmlRenderer();
var reader = new stmd.DocParser();
window.markdown2html = function(md) {
var parsed = reader.parse(md);
return writer.renderBlock(parsed);
};
})();
// relevant DOM elements
var divEl = document.getElementsByTagName('div')[0];
var taEl = document.getElementsByTagName('textarea')[0];
var btnEl = document.getElementsByTagName('button')[0];
var btnServeEl = document.getElementsByTagName('button')[1];
var src, markup, id, endpoint = 'storage.php';
// converts source to markup
var slashNRgx = /\n/g;
var uriRgx = /(\S+:\/\/\S+)/g;
var firstLineRgx = /^(.*)$/gm;
var processDefault= function(src) {
var res = src.replace(uriRgx, '<a href="$1">$1</a>');
res = res.replace(slashNRgx, '<br/>');
return ['<pre>', res, '</pre>'].join('');
};
var processMarkdown = window.markdown2html;
var formats = {
md: processMarkdown
};
var processSource = function(src) {
firstLineRgx.lastIndex = 0;
var format = firstLineRgx.exec(src)[1] || '';
var formatter = formats[format];
var src2;
if (formatter) {
src2 = src.substring(format.length);
}
else {
formatter = processDefault;
src2 = src;
}
markup = formatter(src2);
divEl.className = format;
divEl.innerHTML = markup;
};
// AJAX POST implementation
var post = function(uri, params, cb) {
var r = new XMLHttpRequest();
r.open('POST', uri, true);
r.onreadystatechange = function () {
if (r.readyState !== 4 || r.status !== 200) { return; }
cb(null, r.responseText);
};
var v, qs = [];
for (var k in params) {
if (!params.hasOwnProperty(k)) { continue; }
v = params[k];
qs.push( [k, encodeURIComponent(v)].join('=') );
}
qs = qs.join('&');
r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
r.send(qs);
};
// gets source from storage
var getSource = function(id, cb) {
post(endpoint, {op:'load', id:id}, function(err, o) {
//console.log(err, o);
cb(err, o);
});
};
// saves source to storage
var saveSource = function(id, src, cb) {
post(endpoint, {op:'save', id:id, t:src}, function(err, o) {
//console.log(err, o);
cb(err || o);
});
};
var sourceExists = function(id, cb) {
post(endpoint, {op:'exists', id:id}, function(err, o) {
//console.log(err, o);
cb(null, o === 'true');
});
};
// fetches/creates id, sets initial state
var init = function() {
id = window.location.hash ? window.location.hash.substring(1) : Math.floor(Math.random() * Math.pow(36, 4)).toString(36);
if (!window.location.hash) { window.location.hash = id; }
getSource(id, function(err, s) {
if (err) {
return console.log('error getting source for id ' + id);
}
src = s;
taEl.value = src;
processSource(src);
document.title = 'paste - ' + id;
btnEl.focus();
/*console.log('got source:');
console.log(src);*/
});
};
init();
var cmdEdit = function() {
taEl.style.display = '';
divEl.style.display = 'none';
btnEl.innerHTML = 'save';
taEl.focus();
};
var cmdSave = function(skipSwitch) {
src = taEl.value;
saveSource(id, src, function(err) {
if (err) { return console.log('error saving source'); }
if (!skipSwitch) {
processSource(src);
taEl.style.display = 'none';
divEl.style.display = '';
btnEl.innerHTML = 'edit';
}
console.log('saved source');
});
};
var cmdServe = function() {
window.open('serve.php?id=' + id, '_blank');
};
var onBtnClick = function(ev) {
var cmd = ev.target.innerHTML;
if (cmd === 'edit') { cmdEdit(); }
else if (cmd === 'save') { cmdSave(); }
else if (cmd === 'serve') { cmdServe(); }
};
var onHashChange = function() {
init();
};
var onKeyDown = function(ev) {
if (ev.ctrlKey && ev.keyCode === 83) {
ev.preventDefault();
if (btnEl.innerHTML === 'save') { cmdSave(true); }
}
};
btnEl.addEventListener('click', onBtnClick);
btnServeEl.addEventListener('click', onBtnClick);
window.addEventListener('hashchange', onHashChange);
window.addEventListener('keydown', onKeyDown);
// http://jakiestfu.github.io/Behave.js/ for indentation
var editor = new Behave({
textarea: document.querySelector('textarea')
});
//document.body.app
})(window, undefined);
<file_sep>/README.md
# summary
Minimalistic web clipboard based on files.
Server-side endpoint in PHP. Can be easily ported to other languages.
WARNING: **There were no concerns whatsoever with OS protection XSS, etc. Use at your own risk.**
# purpose
I got fed up with sending URIs to mobile devices.
Wanted a REALLY simple solution for posting URIs and text content to paste on them.
# how it works
* hash tags serve as ids for documents.
* if no hash is given, a new one is randomized for you.
* by default you get the document slightly parsed (uris become A elements, \ns become BR elements).
* if one clicks edit a textarea appears, when one clicks save the server stores a file with its contents.
# setup
i. the current directorymust be served by a PHP-capable webserver such as Apache 2.
ii. in it create a directory named pastes
mkdir pastes
iiia. its ownership to the apache user
chown www-data pastes
iiib. (alternative) add permission for everyone to write in it
chmod a+w pastes
|
d4114f7019ceccfd553718d82b0b4121b9cb71d0
|
[
"JavaScript",
"Markdown",
"PHP"
] | 3
|
PHP
|
JosePedroDias/paste
|
f4cbbd41809851c34ffa20062f5f7a9bc3018a23
|
fb62d0aa65baf35d8f109b1996882722c3f804fa
|
refs/heads/master
|
<repo_name>darshgup139/Placement-Management-System-integration<file_sep>/PMS_v2-master(edited)/src/org/crce/interns/service/impl/SendEmailServiceImpl.java
package org.crce.interns.service.impl;
import java.io.File;
import java.io.IOException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.crce.interns.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Service("sendEmailServiceImpl")
public class SendEmailServiceImpl implements SendEmailService {
@Autowired
private JavaMailSender javaMailSender;
@Override
public ModelAndView sendMail(HttpServletRequest request,
@RequestParam(value = "fileUpload") CommonsMultipartFile[] file)
{
System.out.println(request.getParameter("message"));
System.out.println(request.getParameter("subject"));
System.out.println(request.getParameter("receiver"));
String path = "C:\\Users\\Crystal\\Desktop\\Email_Temp\\";
if (file.length > 0 && file != null) {
System.out.println("Inside If");
for (CommonsMultipartFile f : file) {
if (!f.getOriginalFilename().equals("")) {
System.out.println(path + f.getOriginalFilename());
try {
f.transferTo(new File(path + f.getOriginalFilename()));
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
String input = request.getParameter("receiver");
String[] emailIds = input.split(" ");
javaMailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage)
throws javax.mail.MessagingException, IllegalStateException, IOException {
System.out.println("Throws Exception");
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
//mimeMessageHelper.setTo(request.getParameter("receiver"));
mimeMessageHelper.setTo(emailIds);
mimeMessageHelper.setSubject(request.getParameter("subject"));
mimeMessageHelper.setText(request.getParameter("message"));
for (CommonsMultipartFile f:file) {
if (checkFile(f.getOriginalFilename()))
mimeMessageHelper.addAttachment(f.getOriginalFilename(), new File(path+f.getOriginalFilename()));
}
}
});
deleteFiles();
return new ModelAndView("EmailForm");
}
/*
Return Type: Boolean-True/False
Function: Checks for Files
*/
public boolean checkFile(String name) {
String path = "C:\\Users\\Crystal\\Desktop\\Email_Temp";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i=0;i<listOfFiles.length;i++) {
System.out.println(listOfFiles[i].getName());
if (listOfFiles[i].getName().equals(name))
return true;
}
return false;
}
/*
Return Type: Void
Function: Deletes the copy of the file made for uploading in Email_Temp directory
*/
public void deleteFiles() {
String path = "C:\\Users\\Crystal\\Desktop\\Email_Temp";
File folder = new File(path);
File[] files = folder.listFiles();
for (File f:files)
f.delete();
}
}
|
cf012a72cf9a03d0511d996502438cff9bdd8e27
|
[
"Java"
] | 1
|
Java
|
darshgup139/Placement-Management-System-integration
|
0fffc096c9ae5fd9d7b242b59667c99afc985954
|
0311afd63a383e6e48d4ac1e2630f8d092eaaf4f
|
refs/heads/master
|
<repo_name>negra1m/angular-marvel-final<file_sep>/src/app/components/main/main.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
title = 'MARVEL CHARACTERS API'; // to be set into main page after
hero = {
name: 'SPIDER-MAN',
description: 'Spider-Man is a character created by <NAME> in...',
image: 'spider.jpg'
};
constructor() { }
ngOnInit() {
}
}
<file_sep>/src/app/services/main.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MainService {
url: 'https://gateway.marvel.com/v1/public/characters';
constructor(
private http: HttpClient,
private params: HttpParams, // to be defined after key exposed
private headers: HttpHeaders) { }
getAllCharacters(): Observable<{}> {
const body = { someInfo: 'bla' };
const headers = this.headers.set('key', 'KEY-EXAMPLE');
return this.http.get(this.url, { headers });
}
}
|
5e87eea02eefaa6003333d450247a3bd29d436ad
|
[
"TypeScript"
] | 2
|
TypeScript
|
negra1m/angular-marvel-final
|
b9c0391fbf2b0a83a4e4928d387ee6bde5a3b346
|
67aad85429af8a942af0be99824bf21e598b9f7c
|
refs/heads/master
|
<repo_name>konraadkan/SPR-Builder<file_sep>/inputs.cpp
#include "inputs.h"
bool inputs::getKeyStateImmediate(DWORD vKey)
{
if (GetKeyState(vKey) < 0)
return true;
return false;
}
bool inputs::getKeyStateDelay(DWORD vKey, float delay)
{
timer->Update();
if (timer->GetTimeTotal() > delay)
{
if (GetKeyState(vKey) < 0)
{
timer->Reset();
return true;
}
}
return false;
}<file_sep>/SpriteSheet.h
#pragma once
#include <wincodec.h>
#include "Graphics.h"
class SpriteSheet
{
private:
Graphics * gfx;
ID2D1Bitmap* bmp;
public:
char* DataBuffer = NULL;
size_t Bufferlen = 0;
D2D1_SIZE_F size = {};
wchar_t* FilePath = NULL;
//constructor
SpriteSheet(const wchar_t* filename, Graphics* gfx, D2D1_SIZE_F SpriteSize = {});
SpriteSheet(char* buffer, size_t bufferlen, Graphics* gfx, D2D1_SIZE_F SpriteSize = {});
//deconstructor
~SpriteSheet();
//draw
D2D1_RECT_F Draw(D2D1_RECT_F _src, D2D1_RECT_F _dest, bool keepRatio = false, RenderTarget target = RenderTarget::renderTarget);
};<file_sep>/SpriteSheet.cpp
#include "SpriteSheet.h"
#include <vector>
SpriteSheet::SpriteSheet(const wchar_t* filename, Graphics* gfx, D2D1_SIZE_F SpriteSize)
{
FilePath = new wchar_t[lstrlenW(filename) + 1];
memcpy(FilePath, filename, (lstrlenW(filename) + 1) * sizeof(wchar_t));
this->gfx = gfx; //save gfx
bmp = NULL;
//create factory
IWICImagingFactory *wicFactory = NULL;
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&wicFactory);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create WIC factory!", "Error", MB_OK | MB_ICONERROR);
}
//create decoder
IWICBitmapDecoder *wicDecoder = NULL;
hr = wicFactory->CreateDecoderFromFilename(filename, NULL, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &wicDecoder);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create wic decoder!", "Error", MB_OK | MB_ICONERROR);
}
//read frame from teh image
IWICBitmapFrameDecode* wicFrame = NULL;
hr = wicDecoder->GetFrame(0, &wicFrame); //0 = number frame, in this case there is only 1 frame so zero
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to get WIC deocder frame!", "Error", MB_OK | MB_ICONERROR);
}
//create a converter
IWICFormatConverter *wicConverter = NULL;
hr = wicFactory->CreateFormatConverter(&wicConverter);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create WIC Format Converter!", "Error", MB_OK | MB_ICONERROR);
}
hr = wicConverter->Initialize(
wicFrame, //frame
GUID_WICPixelFormat32bppPBGRA, //output Pixel format (P means packed; pixels are represented by 4 byts packed into an int: 0xRRGGBBAA
WICBitmapDitherTypeNone, //Irrelevant
NULL, //no palette needed
0.0, //alpha transparency % irrelevent
WICBitmapPaletteTypeCustom //irrelevant
);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to initialize WIC Converter!", "Error", MB_OK | MB_ICONERROR);
}
//use converter to create D2D1Bitmap
hr = gfx->GetRenderTarget()->CreateBitmapFromWicBitmap(
wicConverter, //converter
NULL, //D2D1_BITMAP_PROPERTIES
&bmp //destination D2D1 bitmap
);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create D2D1Bitmap!", "Error", MB_OK | MB_ICONERROR);
}
if (wicFactory) wicFactory->Release();
if (wicDecoder) wicDecoder->Release();
if (wicConverter) wicConverter->Release();
if (wicFrame) wicFrame->Release();
if (bmp)
{
size.width = bmp->GetSize().width;
size.height = bmp->GetSize().height;
}
if (SpriteSize.height && SpriteSize.width)
{
this->size.width = SpriteSize.width;
this->size.height = SpriteSize.height;
}
}
SpriteSheet::SpriteSheet(char* buffer, size_t bufferlen, Graphics* gfx, D2D1_SIZE_F SpriteSize)
{
//FilePath = new wchar_t[lstrlenW(filename) + 1];
//memcpy(FilePath, filename, (lstrlenW(filename) + 1) * sizeof(wchar_t));
IWICStream *pIWICStream = NULL;
DataBuffer = new char[bufferlen];
Bufferlen = bufferlen;
memcpy(DataBuffer, buffer, bufferlen);
this->gfx = gfx; //save gfx
bmp = NULL;
//create factory
IWICImagingFactory *wicFactory = NULL;
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&wicFactory);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create WIC factory!", "Error", MB_OK | MB_ICONERROR);
}
hr = wicFactory->CreateStream(&pIWICStream);
if (hr != S_OK)
MessageBox(NULL, "Failed to create stream", "Error", MB_OK | MB_ICONERROR);
hr = pIWICStream->InitializeFromMemory(reinterpret_cast<BYTE*>(buffer), bufferlen);
if (hr != S_OK)
MessageBox(NULL, "InitFromMemory Failed", "Error", MB_OK | MB_ICONERROR);
//create decoder
IWICBitmapDecoder *wicDecoder = NULL;
//hr = wicFactory->CreateDecoderFromFilename(filename, NULL, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &wicDecoder);
hr = wicFactory->CreateDecoderFromStream(pIWICStream, NULL, WICDecodeMetadataCacheOnLoad, &wicDecoder);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create wic decoder!", "Error", MB_OK | MB_ICONERROR);
}
//read frame from teh image
IWICBitmapFrameDecode* wicFrame = NULL;
hr = wicDecoder->GetFrame(0, &wicFrame); //0 = number frame, in this case there is only 1 frame so zero
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to get WIC deocder frame!", "Error", MB_OK | MB_ICONERROR);
}
//create a converter
IWICFormatConverter *wicConverter = NULL;
hr = wicFactory->CreateFormatConverter(&wicConverter);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create WIC Format Converter!", "Error", MB_OK | MB_ICONERROR);
}
hr = wicConverter->Initialize(
wicFrame, //frame
GUID_WICPixelFormat32bppPBGRA, //output Pixel format (P means packed; pixels are represented by 4 byts packed into an int: 0xRRGGBBAA
WICBitmapDitherTypeNone, //Irrelevant
NULL, //no palette needed
0.0, //alpha transparency % irrelevent
WICBitmapPaletteTypeCustom //irrelevant
);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to initialize WIC Converter!", "Error", MB_OK | MB_ICONERROR);
}
//use converter to create D2D1Bitmap
hr = gfx->GetRenderTarget()->CreateBitmapFromWicBitmap(
wicConverter, //converter
NULL, //D2D1_BITMAP_PROPERTIES
&bmp //destination D2D1 bitmap
);
if (hr != S_OK)
{
//error control
MessageBox(NULL, "Unable to create D2D1Bitmap!", "Error", MB_OK | MB_ICONERROR);
}
if (wicFactory) wicFactory->Release();
if (wicDecoder) wicDecoder->Release();
if (wicConverter) wicConverter->Release();
if (wicFrame) wicFrame->Release();
if (pIWICStream) pIWICStream->Release();
if (bmp)
{
size.width = bmp->GetSize().width;
size.height = bmp->GetSize().height;
}
if (SpriteSize.height && SpriteSize.width)
{
this->size.width = SpriteSize.width;
this->size.height = SpriteSize.height;
}
}
SpriteSheet::~SpriteSheet()
{
if (FilePath) delete[] FilePath;
if (DataBuffer) delete[] DataBuffer;
if (bmp) bmp->Release();
}
D2D1_RECT_F SpriteSheet::Draw(D2D1_RECT_F src, D2D1_RECT_F dest, bool keepRatio, RenderTarget target)
{
float xMod = 0.0f;
float yMod = 0.0f;
if (src.left > src.right) std::swap(src.left, src.right);
if (src.top > src.bottom) std::swap(src.top, src.bottom);
D2D1_RECT_F size = { 0.0f, 0.0f, dest.right - dest.left, dest.bottom - dest.top };
if (keepRatio)
{
if ((src.bottom - src.top) > (src.right - src.left))
{
float ratio = (src.right - src.left) / (src.bottom - src.top);
if (ratio < 0.0f) ratio *= -1;
xMod = (dest.right - dest.left) - (dest.right - dest.left) * ratio;
xMod /= 2;
if (xMod < 0.0f) xMod *= -1;
size.right = (size.right - size.left) * ratio;
size.left = 0.0f;
}
else
{
float ratio = (src.bottom - src.top) / (src.right - src.left);
if (ratio < 0.0f) ratio *= -1;
yMod = (size.bottom - size.top) - (size.bottom - size.top) * ratio;
yMod /= 2;
if (yMod < 0.0f) yMod *= -1;
size.bottom = (size.bottom - size.top) * ratio;
size.top = 0.0f;
}
}
dest = { dest.left + xMod, dest.top + yMod, dest.left + size.right + xMod, dest.top + size.bottom + yMod };
switch (target)
{
case RenderTarget::renderTarget:
gfx->GetRenderTarget()->DrawBitmap(
bmp,
dest,
1.0f,
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
src
);
break;
case RenderTarget::drawArea:
gfx->GetDrawArea()->DrawBitmap(
bmp,
dest,
1.0f,
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
src
);
break;
case RenderTarget::previewArea:
gfx->GetPreviewArea()->DrawBitmap(
bmp,
dest,
1.0f,
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
src
);
}
return dest;
}<file_sep>/defines.h
#pragma once
#define MENU_EXIT 0xFEFF
#define MENU_OPEN 0xFEFE
#define MENU_NEW 0xFEFD
#define MENU_TOGGLE_GRID 0xFEFC
#define MENU_CHANGE_BGC 0xFEFB
#define MENU_EXPORT 0xFEFA
#define MENU_EDITSPR3 0xFEF9
#define MENU_25 0x1000
const double version = 4.1;<file_sep>/Level1.h
#pragma once
#include "Graphics.h"
#include "SpriteSheet.h"
#include "HPTimer.h"
#include "Level.h"
#include "inputs.h"
#include "defines.h"
#include <vector>
class Level1 : public Level
{
private:
float scale;
D2D1_SIZE_F translation;
D2D1_MATRIX_3X2_F transform;
D2D1_RECT_F selectionArea;
D2D1::Matrix3x2F transformMatrix;
std::vector<D2D1_RECT_F> frames;
SpriteSheet* sprite;
wchar_t* wTempFilePath = NULL;
ID2D1Bitmap* bGrid = NULL;
private:
bool newbutton;
D2D1_POINT_2F speed;
float precisionSpeed;
inputs* keys;
float previewSize;
long currentFrame;
public:
Level1(Graphics* _gfx);
~Level1();
public:
void LoadLevel() override;
void UnloadLevel() override;
bool OpenImage(HWND hWnd) override;
bool OpenImage(const wchar_t* filePath) override;
void Render() override;
void RenderDrawArea() override;
void RenderPreviewArea() override;
void Update(WPARAM wParam, LPARAM lParam) override;
void Export(const char *FilePath) override;
void OpenSPR3(const char* filePath) override;
void BuildGrid();
void ToggleGrid() override;
public:
void Move(Direction direction, double deltaTime, float _speed = 0.0f) override;
void Resize(Direction direction, double deltaTime, float _speed = 0.0f);
void ShiftSelectionArea(Direction direction, double deltaTime, float _speed = 0.0f) override;
void Zoom(bool in = true) override;
void ChangeSpeed(bool increase = true) override;
HPTimer* timer, *previewTimer;
public:
void DrawPreviewMovement(D2D1_RECT_F area);
void DrawLastFramePreview(D2D1_RECT_F area);
double LastTimeValue, CurrentTimeValue;
float FrameSpeed;
char* getExt(wchar_t* wpath);
char* getExt(char* path);
bool bShowGrid = false;
bool doit = false;
};<file_sep>/Graphics.h
#pragma once
#include <Windows.h>
#include <dxgi.h>
#include <d2d1_1.h>
#include <dwrite.h>
#pragma comment(lib, "dwrite.lib")
#pragma comment (lib, "windowscodecs.lib")
#pragma comment (lib, "d2d1.lib")
enum class RenderTarget
{
renderTarget,
drawArea,
previewArea
};
class Graphics
{
private:
ID2D1Factory* factory = NULL;
ID2D1HwndRenderTarget* renderTarget = NULL;
ID2D1SolidColorBrush* brush = NULL;
ID2D1SolidColorBrush* previewBrush = NULL;
ID2D1SolidColorBrush* drawBrush = NULL;
ID2D1BitmapRenderTarget* pDrawArea = NULL;
ID2D1BitmapRenderTarget* pPreviewArea = NULL;
IDWriteFactory* writeFactory = NULL;
IDWriteTextFormat* writeFormat = NULL;
public:
Graphics() {}
~Graphics();
bool Init(HWND hWnd);
ID2D1Factory* GetFactory() { return factory; }
ID2D1RenderTarget* GetRenderTarget() { return renderTarget; }
ID2D1BitmapRenderTarget* GetDrawArea() { return pDrawArea; }
ID2D1BitmapRenderTarget* GetPreviewArea() { return pPreviewArea; }
void BeginDraw(RenderTarget target = RenderTarget::renderTarget);
void EndDraw(RenderTarget target = RenderTarget::renderTarget);
void ClearScreen(D2D1_COLOR_F color, RenderTarget target = RenderTarget::renderTarget);
void DrawLine(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_COLOR_F color, float thickness = 3.0f, RenderTarget target = RenderTarget::renderTarget);
void FillRect(D2D1_RECT_F area, D2D1_COLOR_F color, RenderTarget target = RenderTarget::renderTarget);
void DrawRect(D2D1_RECT_F area, D2D1_COLOR_F color, float thickness = 3.0f, RenderTarget target = RenderTarget::renderTarget);
void DrawText(const wchar_t* text, D2D1_RECT_F area, D2D1_COLOR_F color, RenderTarget target = RenderTarget::renderTarget);
};<file_sep>/inputs.h
#pragma once
#include "HPTimer.h"
class inputs
{
private:
HPTimer* timer;
public:
inputs() { timer = new HPTimer; }
~inputs() { delete timer; }
public:
bool getKeyStateImmediate(DWORD vKey);
bool getKeyStateDelay(DWORD vKey, float delay = 0.10f);
};<file_sep>/Level1.cpp
#include "Level1.h"
#include<string>
Level1::Level1(Graphics* _gfx)
{
gfx = _gfx;
LoadLevel();
}
Level1::~Level1()
{
UnloadLevel();
}
void Level1::LoadLevel()
{
scale = 1.0f;
translation = {};
selectionArea = {};
sprite = NULL;
timer = new HPTimer();
previewTimer = new HPTimer();
speed.x = 50.0f;
speed.y = speed.x * (1080.0f / 1920.0f);
precisionSpeed = 10.0f;
keys = new inputs;
previewSize = 128.0f;
currentFrame = 0;
FrameSpeed = 0.10f;
LastTimeValue = CurrentTimeValue = timer->GetTimeTotal();
wTempFilePath = NULL;
BuildGrid();
}
void Level1::UnloadLevel()
{
scale = 1.0f;
translation = {};
selectionArea = {};
if (sprite) delete sprite;
sprite = NULL;
delete timer;
delete previewTimer;
delete keys;
if (wTempFilePath) //legacy, should never be called
{
_wremove(wTempFilePath);
delete[] wTempFilePath;
wTempFilePath = NULL;
}
if (bGrid) bGrid->Release();
}
bool Level1::OpenImage(HWND hWnd)
{
wchar_t imagePath[512] = {};
OPENFILENAMEW ofn = {};
imagePath[0] = L'\0';
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hWnd;
ofn.lpstrFilter = L"Image Files (*.bmp, *.png, *.jpg)\0*.bmp;*.png;*.jpg\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = imagePath;
ofn.nMaxFile = 512;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
ofn.lpstrDefExt = L"bmp";
if (GetOpenFileNameW(&ofn))
{
if (imagePath[wcslen(imagePath) - 1] == '3')
{
//spr3 decode
}
else
{
if (sprite) delete sprite;
FILE* file;
_wfopen_s(&file, imagePath, L"rb");
fseek(file, 0, SEEK_END);
size_t len = ftell(file);
fseek(file, 0, SEEK_SET);
char* buffer = new char[len];
fread(buffer, len, 1, file);
fclose(file);
//sprite = new SpriteSheet(imagePath, gfx);
sprite = new SpriteSheet(buffer, len, gfx);
delete[] buffer;
doit = true;
if (sprite) return true;
}
}
return false;
}
bool Level1::OpenImage(const wchar_t* filePath)
{
if (sprite) delete sprite;
sprite = new SpriteSheet(filePath, gfx);
if (sprite) return true;
return false;
}
void Level1::RenderDrawArea()
{
D2D1_MATRIX_3X2_F scaling, translating;
D2D1_POINT_2F pp = transformMatrix.TransformPoint({ 1920.0f * 0.75f / 2.0f, 1080.0f / 2.0f });
scaling = D2D1::Matrix3x2F::Scale(D2D1::Size(scale, scale), pp);
translating = D2D1::Matrix3x2F::Translation(translation);
transform = scaling * translating;
gfx->BeginDraw(RenderTarget::drawArea);
gfx->GetDrawArea()->SetTransform(transform);
gfx->GetDrawArea()->GetTransform(&transformMatrix);
transformMatrix.Invert();
gfx->ClearScreen({ 0.0f, 0.0f, 0.33f, 1.0f }, RenderTarget::drawArea);
if (sprite)
{
gfx->DrawRect({ 0.0f, 0.0f, sprite->size.width, sprite->size.height }, { 0.0f, 0.0f, 0.0f, 0.8f }, 1.0f, RenderTarget::drawArea);
sprite->Draw({ 0.0f, 0.0f, sprite->size.width, sprite->size.height }, { 0.0f, 0.0f, sprite->size.width, sprite->size.height }, false, RenderTarget::drawArea);
gfx->DrawRect(selectionArea, { 0.66f, 0.1f, 0.33f, 1.0f }, 1.0f, RenderTarget::drawArea);
}
if (bShowGrid && bGrid)
gfx->GetDrawArea()->DrawBitmap(bGrid, { 0.0f, 0.0f, 1920.0f * 0.75f, 1080.0f }, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, { 0.0f, 0.0f, 1920.0f * 0.75f, 1080.0f });
gfx->EndDraw(RenderTarget::drawArea);
}
void Level1::RenderPreviewArea()
{
gfx->BeginDraw(RenderTarget::previewArea);
gfx->ClearScreen({ 1.0f, 0.0f, 0.33f, 1.0f }, RenderTarget::previewArea);
if (sprite)
{
D2D1_RECT_F tArea = { 0.0f, 0.0f, 1920.0f * 0.25f, 1920.0f * 0.25f };
tArea = sprite->Draw(selectionArea, tArea, true, RenderTarget::previewArea);
gfx->DrawRect(tArea, { 0.0f, 0.0f, 0.0f, 0.80f }, 2.0f, RenderTarget::previewArea);
gfx->DrawLine({ (tArea.right + tArea.left) / 2.0f, tArea.top }, { (tArea.right + tArea.left) / 2.0f, tArea.bottom }, { 0.0f, 0.0f, 0.0f, 0.80f }, 2.0f, RenderTarget::previewArea);
gfx->DrawLine({ tArea.left, (tArea.bottom + tArea.top) / 2.0f }, { tArea.right, (tArea.bottom + tArea.top) / 2.0f }, { 0.0f, 0.0f, 0.0f, 0.80f }, 2.0f, RenderTarget::previewArea);
tArea = { 0.0f, 0.0f, 1920.0f * 0.25f, 1920.0f * 0.25f };
DrawPreviewMovement({ 5.0f, tArea.bottom, previewSize + 5.0f, tArea.bottom + previewSize });
DrawLastFramePreview({ previewSize + 8.0f, tArea.bottom, previewSize + 8.0f + previewSize, tArea.bottom + previewSize });
wchar_t sText[512];
swprintf_s(sText, 512, L"%.2f x %.2f", selectionArea.right - selectionArea.left, selectionArea.bottom - selectionArea.top);
gfx->DrawText(sText, { previewSize + 8.0f + previewSize + 2.0f, tArea.bottom + previewSize - 16.0f, 1920.0f * 0.25f, tArea.bottom + previewSize }, { 0.0f, 0.0f, 0.0f, 1.0f }, RenderTarget::previewArea);
D2D1_RECT_F textRect = { 1.0f, tArea.bottom + previewSize, 1920.0f * 0.25f, 0.0f };
textRect.bottom = textRect.top + 16.0f;
for (size_t i = 0; i < frames.size(); i++)
{
wchar_t coord[512];
swprintf_s(coord, 512, L"%.2f, %.2f, %.2f, %.2f", frames[i].left, frames[i].top, frames[i].right, frames[i].bottom);
gfx->DrawText(coord, { textRect.left, textRect.top + i * 16.0f, textRect.right, textRect.bottom + i * 33.0f }, { 0.0f, 0.0f, 0.0f, 1.0f }, RenderTarget::previewArea);
}
}
gfx->EndDraw(RenderTarget::previewArea);
}
void Level1::Render()
{
//graphic stuff
RenderDrawArea();
RenderPreviewArea();
ID2D1Bitmap* o = NULL;
ID2D1Bitmap* oo = NULL;
gfx->GetDrawArea()->GetBitmap(&o);
gfx->GetPreviewArea()->GetBitmap(&oo);
/*************************experimental area***************************************/
D2D1_POINT_2U rect2 = D2D1::Point2U(0, 0);
D2D1_SIZE_U size = D2D1::SizeU(o->GetSize().width, o->GetSize().height);
D2D1_BITMAP_PROPERTIES1 bp = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS::D2D1_BITMAP_OPTIONS_CPU_READ, o->GetPixelFormat());
UINT32 pitch = o->GetSize().width > o->GetSize().height ? o->GetSize().width * 4 : o->GetSize().height * 4;
if (doit)
{
size_t s = o->GetSize().width > o->GetSize().height ? o->GetSize().width : o->GetSize().height;
s *= 4;
char* w = new char[s];
memcpy(w, o, s);
/*
FILE* file = NULL;
if (fopen_s(&file, "thisonedumbass.txt", "wb")) MessageBox(NULL, "Failed to open file","",MB_OK);
fwrite(w, s, 1, file);
fclose(file);*/
//MessageBox(NULL, std::to_string(o->GetSize().width).c_str(), std::to_string(o->GetSize().height).c_str(), MB_OK);
}
/***********************end experimental area************************************/
gfx->BeginDraw();
gfx->ClearScreen({ 0.0f, 1.0f, 0.0f, 1.0f });
gfx->GetRenderTarget()->DrawBitmap(o, { 0.0f, 0.0f, 1920.0f * 0.75f, 1080.0f }, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, { 0.0f, 0.0f, 1920.0f * 0.75f, 1080.0f });
gfx->GetRenderTarget()->DrawBitmap(oo, { 1920.0f * 0.75f, 0.0f, 1920.0f, 1080.0f }, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, { 0.0f, 0.0f, 1920.0f * 0.25f, 1080.0f });
gfx->EndDraw();
o->Release();
oo->Release();
}
void Level1::DrawPreviewMovement(D2D1_RECT_F area)
{
if (frames.empty())
return;
if (currentFrame + 1 > frames.size())
currentFrame = 0;
sprite->Draw(frames[currentFrame], area, true, RenderTarget::previewArea);
gfx->DrawRect(area, { 0.0f, 0.0f, 0.0f, 1.0f }, 1.0f, RenderTarget::previewArea);
if (CurrentTimeValue - LastTimeValue > FrameSpeed)
{
LastTimeValue = CurrentTimeValue;
currentFrame++;
}
}
void Level1::DrawLastFramePreview(D2D1_RECT_F area)
{
if (frames.empty())
return;
sprite->Draw(frames.back(), area, true, RenderTarget::previewArea);
gfx->DrawRect(area, { 0.0f, 0.0f, 0.0f, 1.0f }, 1.0f, RenderTarget::previewArea);
gfx->DrawLine({ (area.left + area.right) / 2.0f, area.top }, { (area.left + area.right) / 2.0f, area.bottom }, { 0.0f, 0.0f, 0.0f, 0.8f }, 1.0f, RenderTarget::previewArea);
gfx->DrawLine({ area.left, (area.top + area.bottom) / 2.0f }, { area.right, (area.top + area.bottom) / 2.0f }, { 0.0f, 0.0f, 0.0f, 0.8f }, 1.0f, RenderTarget::previewArea);
}
void Level1::Resize(Direction direction, double deltaTime, float _speed)
{
D2D1_POINT_2F cspeed = speed;
if (_speed)
{
cspeed.x = _speed;
cspeed.y = cspeed.x * (1080.0f / 1920.0f);
}
if (keys->getKeyStateImmediate(VK_RBUTTON))
{
switch (direction)
{
case Direction::up:
selectionArea.bottom -= (float)(cspeed.y * deltaTime);
break;
case Direction::down:
selectionArea.bottom += (float)(cspeed.y * deltaTime);
break;
case Direction::left:
selectionArea.right -= (float)(cspeed.x * deltaTime);
break;
case Direction::right:
selectionArea.right += (float)(cspeed.x * deltaTime);
break;
}
}
else
{
switch (direction)
{
case Direction::up:
selectionArea.top -= (float)(cspeed.y * deltaTime);
break;
case Direction::down:
selectionArea.top += (float)(cspeed.y * deltaTime);
break;
case Direction::left:
selectionArea.left -= (float)(cspeed.x * deltaTime);
break;
case Direction::right:
selectionArea.left += (float)(cspeed.x * deltaTime);
break;
}
}
}
void Level1::Update(WPARAM wParam, LPARAM lParam)
{
timer->Update();
CurrentTimeValue = timer->GetTimeTotal();
D2D1_POINT_2F p = GetMousePositionForCurrentDpi(lParam, gfx->GetFactory());
D2D1_POINT_2F pp = transformMatrix.TransformPoint(p);
float cSpeed = 0.0f;
if (keys->getKeyStateImmediate(VK_CONTROL))
cSpeed = precisionSpeed;
else
cSpeed = 0.0f;
if (keys->getKeyStateImmediate(VK_MBUTTON))
{
if (keys->getKeyStateImmediate(VK_LEFT))
Resize(Direction::left, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_RIGHT))
Resize(Direction::right, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_UP))
Resize(Direction::up, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_DOWN))
Resize(Direction::down, timer->GetTimeDelta(), cSpeed);
}
else if (keys->getKeyStateImmediate(VK_SHIFT))
{
if (keys->getKeyStateImmediate(VK_LEFT))
ShiftSelectionArea(Direction::left, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_RIGHT))
ShiftSelectionArea(Direction::right, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_UP))
ShiftSelectionArea(Direction::up, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_DOWN))
ShiftSelectionArea(Direction::down, timer->GetTimeDelta(), cSpeed);
}
else
{
if (keys->getKeyStateImmediate(VK_LEFT))
Move(Direction::left, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_RIGHT))
Move(Direction::right, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_UP))
Move(Direction::up, timer->GetTimeDelta(), cSpeed);
if (keys->getKeyStateImmediate(VK_DOWN))
Move(Direction::down, timer->GetTimeDelta(), cSpeed);
}
if (keys->getKeyStateImmediate(VK_MULTIPLY))
Zoom();
if (keys->getKeyStateImmediate(VK_DIVIDE))
Zoom(false);
if (keys->getKeyStateDelay(VK_ADD))
ChangeSpeed();
if (keys->getKeyStateDelay(VK_SUBTRACT))
ChangeSpeed(false);
if (keys->getKeyStateImmediate(VK_LBUTTON))
{
if (newbutton)
{
selectionArea.left = selectionArea.right = pp.x;
selectionArea.top = selectionArea.bottom = pp.y;
newbutton = false;
}
else
{
selectionArea.right = pp.x;
selectionArea.bottom = pp.y;
}
if (selectionArea.left < 0) selectionArea.left = 0;
if (selectionArea.top < 0) selectionArea.top = 0;
if (selectionArea.right < 0) selectionArea.right = 0;
if (selectionArea.bottom < 0) selectionArea.bottom = 0;
if (sprite)
{
if (selectionArea.left > sprite->size.width)
selectionArea.left = sprite->size.width;
if (selectionArea.right > sprite->size.width)
selectionArea.right = sprite->size.width;
if (selectionArea.top > sprite->size.height)
selectionArea.top = sprite->size.height;
if (selectionArea.bottom > sprite->size.height)
selectionArea.bottom = sprite->size.height;
}
}
else if (!newbutton)
newbutton = true;
if (keys->getKeyStateDelay(VK_RETURN, 0.33f))
{
if (selectionArea.left > selectionArea.right) std::swap(selectionArea.left, selectionArea.right);
if (selectionArea.top > selectionArea.bottom) std::swap(selectionArea.bottom, selectionArea.top);
frames.push_back(selectionArea);
}
if (keys->getKeyStateDelay(VK_BACK))
{
if (!frames.empty())
frames.pop_back();
}
if (wParam >= MENU_25 && wParam < MENU_25 + 40)
{
Level::ClearChecks();
CheckMenuItem(GetMenu(Level::hWnd), (UINT)wParam, MF_CHECKED);
FrameSpeed = (((wParam - MENU_25) + 1) * 25.0f) / 1000.0f;
}
if (wParam == MENU_EXPORT)
{
char sFilePath[512] = {};
sFilePath[0] = '\0';
OPENFILENAME ofn = {};
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "SpriteFile (*.spr3)\0*.spr3\0";
ofn.lpstrFile = sFilePath;
ofn.nMaxFile = 512;
ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
ofn.lpstrDefExt = "spr3";
if (GetSaveFileName(&ofn))
{
Export(sFilePath);
}
}
if (wParam == MENU_EDITSPR3)
{
char sFilePath[512] = {};
sFilePath[0] = '\0';
OPENFILENAME ofn = {};
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "SpriteFile (*.spr3)\0*.spr3\0";
ofn.lpstrFile = sFilePath;
ofn.nMaxFile = 512;
ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
ofn.lpstrDefExt = "spr3";
if (GetOpenFileName(&ofn))
{
OpenSPR3(sFilePath);
}
}
}
void Level1::ToggleGrid()
{
if (bShowGrid) bShowGrid = false;
else bShowGrid = true;
}
char* Level1::getExt(char* path)
{
char* ext = NULL;
for (int i = (int)strlen(path); i > 0; i--)
{
if (path[i] == '.')
{
ext = new char[strlen(path) - i + 1];
memcpy(ext, &path[i], strlen(path) - i + 1);
return ext;
}
}
return ext;
}
char* Level1::getExt(wchar_t* wpath)
{
if (!wpath)
{
char* w = new char[1];
w[0] = '\0';
return w;
}
int len = (int)wcslen(wpath);
len++;
size_t numConverted;
char* path = new char[len];
wcstombs_s(&numConverted, path, len, wpath, len);
char* result = getExt(path);
delete[] path;
return result;
}
void Level1::OpenSPR3(const char* filePath)
{
FILE* file;
errno_t error = fopen_s(&file, filePath, "rb");
if (error) return;
if (sprite) delete sprite;
fseek(file, 0, SEEK_END);
size_t bufferLen = ftell(file);
fseek(file, 0, SEEK_SET);
char* buffer = new char[bufferLen];
fread(buffer, bufferLen, 1, file);
fclose(file);
size_t position = 0;
position += sizeof(float) * 4;
memcpy(&FrameSpeed, buffer + position, sizeof(float));
Level::ClearChecks();
CheckMenuItem(GetMenu(Level::hWnd), MENU_25 + (UINT)(FrameSpeed / 25) - 1, MF_CHECKED);
FrameSpeed /= 1000.0f;
position += sizeof(float);
double dVersion;
memcpy(&dVersion, buffer + position, sizeof(double)); //this is in case i need the version information for some reason
position += sizeof(double);
int numFrames = 0;
memcpy(&numFrames, buffer + position, sizeof(int));
position += sizeof(int);
position += sizeof(bool); //legacy, not used
std::vector<D2D1_RECT_F> empty;
std::swap(empty, frames);
for (int i = 0; i < numFrames; i++)
{
D2D1_RECT_F tFrames;
memcpy(&tFrames.left, buffer + position, sizeof(float));
position += sizeof(float);
memcpy(&tFrames.top, buffer + position, sizeof(float));
position += sizeof(float);
memcpy(&tFrames.right, buffer + position, sizeof(float));
position += sizeof(float);
memcpy(&tFrames.bottom, buffer + position, sizeof(float));
position += sizeof(float);
frames.push_back(tFrames);
}
int extLen = 0;
memcpy(&extLen, buffer + position, sizeof(int));
position += sizeof(int);
char* ext = new char[extLen + 1];
ext[extLen] = '\0';
memcpy(ext, buffer + position, extLen);
position += extLen;
memcpy(&bufferLen, buffer + position, sizeof(int));
position += sizeof(int);
/* old method
std::string tempFilePath = filePath;
tempFilePath.append(ext);
delete[] ext;
fopen_s(&file, tempFilePath.c_str(), "wb");
fwrite(buffer + position, bufferLen, 1, file);
fclose(file);
delete[] buffer;
if (wTempFilePath)
{
delete[] wTempFilePath;
}
size_t numConverted;
int len = (int)tempFilePath.size() + 1;
wTempFilePath = new wchar_t[len];
mbstowcs_s(&numConverted, wTempFilePath, len, tempFilePath.c_str(), len);
sprite = new SpriteSheet(wTempFilePath, Level::gfx);*/
sprite = new SpriteSheet(buffer + position, bufferLen, Level::gfx);
}
void Level1::Export(const char *FilePath)
{
/*
FILE* file;
std::wstring wFilePath = sprite->FilePath;
delete sprite;
errno_t error = _wfopen_s(&file, wFilePath.c_str(), L"rb");
if (error)
{
MessageBox(NULL, "Failed to open file.", "Error", MB_OK | MB_ICONERROR);
return;
}
fseek(file, 0, SEEK_END);
int bufferLen = (int)ftell(file);
fseek(file, 0, SEEK_SET);
char* databuffer = new char[bufferLen];
fread(databuffer, bufferLen, 1, file);
fclose(file);
sprite = new SpriteSheet(wFilePath.c_str(), gfx);
*/
FILE* file = NULL;
errno_t error = fopen_s(&file, FilePath, "wb");
if (error)
{
MessageBox(NULL, "Failed to open file.", "Error", MB_OK | MB_ICONERROR);
return;
}
if (!sprite->DataBuffer)
{
MessageBox(NULL, "Failed to export the file. DataBuffer is NULL.", "Error", MB_OK | MB_ICONERROR);
return;
}
char* buffer = new char[sizeof(double) + sizeof(int) + sizeof(float) * 5 + sizeof(bool)];
size_t position = 0;
float null = 0;
memcpy(buffer, &null, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &null, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &null, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &null, sizeof(float));
position += sizeof(float);
float FrameSpeedConverted = FrameSpeed * 1000.0f;
memcpy(buffer + position, &FrameSpeedConverted, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &version, sizeof(double));
position += sizeof(double);
int maxframe = (int)frames.size();
memcpy(buffer + position, &maxframe, sizeof(int));
position += sizeof(int);
bool custom = true;
memcpy(buffer + position, &custom, sizeof(bool));
position += sizeof(bool);
fwrite(buffer, position, 1, file);
delete[] buffer;
size_t totalPosition = position;
position = 0;
buffer = new char[maxframe * 4 * sizeof(float)];
for (int i = 0; i < maxframe; i++)
{
memcpy(buffer + position, &frames[i].left, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &frames[i].top, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &frames[i].right, sizeof(float));
position += sizeof(float);
memcpy(buffer + position, &frames[i].bottom, sizeof(float));
position += sizeof(float);
}
fwrite(buffer, position, 1, file);
delete[] buffer;
char* ext = getExt(sprite->FilePath);
int extLen = (int)strlen(ext);
fwrite(&extLen, sizeof(int), 1, file);
fwrite(ext, extLen, 1, file);
delete[] ext;
fwrite(&sprite->Bufferlen, sizeof(int), 1, file);
fwrite(sprite->DataBuffer, sprite->Bufferlen, 1, file);
fclose(file);
}
void Level1::ShiftSelectionArea(Direction direction, double deltaTime, float _speed)
{
D2D1_POINT_2F cspeed = speed;
if (_speed)
{
cspeed.x = _speed;
cspeed.y = cspeed.x * (1080.0f / 1920.0f);
}
switch (direction)
{
case Direction::up:
selectionArea.top -= (float)(cspeed.y * deltaTime);
selectionArea.bottom -= (float)(cspeed.y * deltaTime);
break;
case Direction::down:
selectionArea.top += (float)(cspeed.y * deltaTime);
selectionArea.bottom += (float)(cspeed.y * deltaTime);
break;
case Direction::left:
selectionArea.left -= (float)(cspeed.x * deltaTime);
selectionArea.right -= (float)(cspeed.x * deltaTime);
break;
case Direction::right:
selectionArea.left += (float)(cspeed.x * deltaTime);
selectionArea.right += (float)(cspeed.x * deltaTime);
break;
}
}
void Level1::Move(Direction direction, double deltaTime, float _speed)
{
D2D1_POINT_2F cspeed = speed;
if (_speed)
{
cspeed.x = _speed;
cspeed.y = cspeed.x * (1080.0f / 1920.0f);
}
switch (direction)
{
case Direction::up:
translation.height += (float)(cspeed.y * deltaTime);
break;
case Direction::down:
translation.height -= (float)(cspeed.y * deltaTime);
break;
case Direction::left:
translation.width += (float)(cspeed.x * deltaTime);
break;
case Direction::right:
translation.width -= (float)(cspeed.x * deltaTime);
break;
}
}
void Level1::Zoom(bool in)
{
if (in)
scale += 0.01f;
else
scale -= 0.01f;
}
void Level1::ChangeSpeed(bool increase)
{
if (increase)
{
speed.x += 50.0f;
}
else
{
speed.x -= 50.0f;
}
if (speed.x < 0)
speed.x = 0;
speed.y = speed.x * (1080.0f / 1920.0f);
}
void Level1::BuildGrid()
{
if (bGrid) bGrid->Release();
ID2D1BitmapRenderTarget* t = NULL;
ID2D1SolidColorBrush* tbrush = NULL;
gfx->GetDrawArea()->CreateCompatibleRenderTarget(&t);
t->CreateSolidColorBrush({ 0.0f, 0.0f, 0.0f,1.0f }, &tbrush);
t->BeginDraw();
t->Clear({});
for (long i = 0; i < 1920; i += 5)
{
t->DrawLine(D2D1::Point2F((float)i, 0), D2D1::Point2F((float)i, 1080), tbrush, 0.25f);
}
for (long i = 0; i < 1080; i += 5)
{
t->DrawLine(D2D1::Point2F(0, (float)i), D2D1::Point2F(1920, (float)i), tbrush, 0.25f);
}
t->EndDraw();
t->GetBitmap(&bGrid);
tbrush->Release();
t->Release();
}<file_sep>/README.md
# SPR-Builder
This is used in to build the .spr3 image files used in Map-Build
Much like Map-Build, mainly storing this here for version control.
<file_sep>/Level.h
#pragma once
#include "Graphics.h"
#include "SpriteSheet.h"
#include "defines.h"
enum class Direction
{
up,
down,
left,
right
};
class Level
{
public:
static D2D1_POINT_2F GetMousePositionForCurrentDpi(LPARAM lParam, ID2D1Factory* factory)
{
static D2D1_POINT_2F dpi = { 96,96 }; //default dpi
factory->GetDesktopDpi(&dpi.x, &dpi.y);
return D2D1::Point2F(static_cast<int>(static_cast<short>(LOWORD(lParam))) * 96 / dpi.x,
static_cast<int>(static_cast<short>(HIWORD(lParam))) * 96 / dpi.y);
}
static void ClearChecks()
{
for (int i = MENU_25; i < MENU_25 + 40; i++)
{
CheckMenuItem(GetMenu(Level::hWnd), i, MF_UNCHECKED);
}
}
public:
virtual void LoadLevel() = 0;
virtual void UnloadLevel() = 0;
virtual bool OpenImage(HWND hWnd) = 0;
virtual bool OpenImage(const wchar_t* filePath) = 0;
virtual void Render() = 0;
virtual void RenderDrawArea() = 0;
virtual void RenderPreviewArea() = 0;
virtual void Update(WPARAM wParam, LPARAM lParam) = 0;
virtual void Move(Direction direction, double deltaTime, float _speed) = 0;
virtual void ShiftSelectionArea(Direction direction, double deltaTime, float _speed = 0.0f) = 0;
virtual void Zoom(bool in = true) = 0;
virtual void ChangeSpeed(bool increase = true) = 0;
virtual void Export(const char* FilePath) = 0;
virtual void OpenSPR3(const char* filePath) = 0;
virtual void ToggleGrid() = 0;
public:
static Graphics* gfx;
static HWND hWnd;
};<file_sep>/Graphics.cpp
#include "Graphics.h"
Graphics::~Graphics()
{
if (factory) factory->Release();
if (renderTarget) renderTarget->Release();
if (pDrawArea) pDrawArea->Release();
if (pPreviewArea) pPreviewArea->Release();
if (brush) brush->Release();
if (writeFactory) writeFactory->Release();
if (writeFormat) writeFormat->Release();
if (drawBrush) drawBrush->Release();
if (previewBrush) previewBrush->Release();
}
bool Graphics::Init(HWND hWnd)
{
HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &factory);
if (hr != S_OK) return false;
RECT rect;
GetClientRect(hWnd, &rect);
hr = factory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, D2D1::SizeU(rect.right, rect.bottom), D2D1_PRESENT_OPTIONS_NONE), &renderTarget);
if (hr != S_OK) return false;
hr = renderTarget->CreateSolidColorBrush(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f), &brush);
if (hr != S_OK) return false;
hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown**>(&writeFactory));
if (hr != S_OK) return false;
hr = writeFactory->CreateTextFormat(L"Arial", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 16.0f, L"en-us", &writeFormat);
if (hr != S_OK) return false;
hr = renderTarget->CreateCompatibleRenderTarget(D2D1::SizeF((float)rect.right * 0.75f, (float)rect.bottom), &pDrawArea);
if (hr != S_OK) return false;
hr = pDrawArea->CreateSolidColorBrush(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f), &drawBrush);
if (hr != S_OK) return false;
hr = renderTarget->CreateCompatibleRenderTarget(D2D1::SizeF((float)rect.right * 0.25f, (float)rect.bottom), &pPreviewArea);
if (hr != S_OK) return false;
hr = pPreviewArea->CreateSolidColorBrush(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f), &previewBrush);
if (hr != S_OK) return false;
return true;
}
void Graphics::ClearScreen(D2D1_COLOR_F color, RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
renderTarget->Clear(color);
break;
case RenderTarget::previewArea:
pPreviewArea->Clear(color);
break;
case RenderTarget::drawArea:
pDrawArea->Clear(color);
break;
}
}
void Graphics::DrawLine(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_COLOR_F color, float thickness, RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
brush->SetColor(color);
renderTarget->DrawLine(p1, p2, brush, thickness);
break;
case RenderTarget::drawArea:
drawBrush->SetColor(color);
pDrawArea->DrawLine(p1, p2, drawBrush, thickness);
break;
case RenderTarget::previewArea:
previewBrush->SetColor(color);
pPreviewArea->DrawLine(p1, p2, previewBrush, thickness);
}
}
void Graphics::FillRect(D2D1_RECT_F area, D2D1_COLOR_F color, RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
brush->SetColor(color);
renderTarget->FillRectangle(area, brush);
break;
case RenderTarget::drawArea:
drawBrush->SetColor(color);
pDrawArea->FillRectangle(area, drawBrush);
break;
case RenderTarget::previewArea:
previewBrush->SetColor(color);
pPreviewArea->FillRectangle(area, previewBrush);
break;
}
}
void Graphics::DrawRect(D2D1_RECT_F area, D2D1_COLOR_F color, float thickness, RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
brush->SetColor(color);
renderTarget->DrawRectangle(area, brush, thickness);
break;
case RenderTarget::drawArea:
drawBrush->SetColor(color);
pDrawArea->DrawRectangle(area, drawBrush, thickness);
break;
case RenderTarget::previewArea:
previewBrush->SetColor(color);
pPreviewArea->DrawRectangle(area, previewBrush, thickness);
break;
}
}
void Graphics::DrawText(const wchar_t* text, D2D1_RECT_F area, D2D1_COLOR_F color, RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
brush->SetColor(color);
renderTarget->DrawTextA(text, lstrlenW(text), writeFormat, area, brush, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
break;
case RenderTarget::drawArea:
drawBrush->SetColor(color);
pDrawArea->DrawTextA(text, lstrlenW(text), writeFormat, area, drawBrush, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
break;
case RenderTarget::previewArea:
previewBrush->SetColor(color);
pPreviewArea->DrawTextA(text, lstrlenW(text), writeFormat, area, previewBrush, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
break;
}
}
void Graphics::BeginDraw(RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
renderTarget->BeginDraw();
break;
case RenderTarget::drawArea:
pDrawArea->BeginDraw();
break;
case RenderTarget::previewArea:
pPreviewArea->BeginDraw();
break;
}
}
void Graphics::EndDraw(RenderTarget target)
{
switch (target)
{
case RenderTarget::renderTarget:
renderTarget->EndDraw();
break;
case RenderTarget::drawArea:
pDrawArea->EndDraw();
break;
case RenderTarget::previewArea:
pPreviewArea->EndDraw();
break;
}
}<file_sep>/Source.cpp
#include "Graphics.h"
#include "SpriteSheet.h"
#include "Level1.h"
#include "defines.h"
#include <string>
#include <vector>
#define MYCLASSNAME "MainWindow"
#define MYWINDOWNAME "SPR Builder 4"
static Level* CurrentLevel;
HMENU createMenu()
{
HMENU menu = CreateMenu();
HMENU smenu = CreatePopupMenu();
AppendMenu(smenu, MF_STRING, MENU_NEW, "New");
AppendMenu(smenu, MF_STRING, MENU_OPEN, "Open Image");
AppendMenu(smenu, MF_STRING, MENU_EDITSPR3, "Edit SPR3");
AppendMenu(smenu, MF_STRING, MENU_EXPORT, "Export");
AppendMenu(smenu, MF_STRING, MENU_EXIT, "Exit");
AppendMenu(menu, MF_STRING | MF_POPUP, reinterpret_cast<UINT_PTR>(smenu), "File");
smenu = CreatePopupMenu();
for (int i = MENU_25; i < MENU_25 + 40; i++)
{
std::string text = std::to_string(((i - MENU_25) + 1) * 25);
text.append(" Ticks");
AppendMenu(smenu, MF_STRING, i, text.c_str());
}
AppendMenu(menu, MF_STRING | MF_POPUP, reinterpret_cast<UINT_PTR>(smenu), "Speed");
smenu = CreatePopupMenu();
AppendMenu(smenu, MF_STRING, MENU_TOGGLE_GRID, "Toggle Grid");
//AppendMenu(smenu, MF_STRING, MENU_CHANGE_BGC, "Change Background Color");
AppendMenu(menu, MF_STRING | MF_POPUP, reinterpret_cast<UINT_PTR>(smenu), "Advanced");
return menu;
}
LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_DESTROY) { PostQuitMessage(0); return 0; }
if (wParam)
{
switch (wParam)
{
case MENU_NEW:
{
Graphics* gfx = CurrentLevel->gfx;
if (gfx)
{
delete CurrentLevel;
CurrentLevel = new Level1(gfx);
Level::ClearChecks();
CheckMenuItem(GetMenu(hWnd), MENU_25 + 3, MF_CHECKED);
}
break;
}
case MENU_EXIT:
CurrentLevel->UnloadLevel();
PostQuitMessage(0);
return 0;
case MENU_OPEN:
//load image
CurrentLevel->OpenImage(hWnd);
break;
case MENU_TOGGLE_GRID:
CurrentLevel->ToggleGrid();
break;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevious, LPWSTR cmd, int iCmdShow)
{
WNDCLASSEX wndClass = {};
ZeroMemory(&wndClass, sizeof(WNDCLASSEX));
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = wndProc;
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndClass.lpszClassName = MYCLASSNAME;
HMENU menu = createMenu();
RegisterClassEx(&wndClass);
RECT rect = { 0, 0, 1920, 1080 };
RECT desktop = { 0, 0, 0, 0 };
AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME, true, WS_EX_OVERLAPPEDWINDOW);
const HWND hDesktop = GetDesktopWindow();
GetWindowRect(hDesktop, &desktop);
HWND hWnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, MYCLASSNAME, MYWINDOWNAME, WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME, (desktop.right / 2) - (rect.right / 2), (desktop.bottom / 2) - (rect.bottom / 2), rect.right - rect.left, rect.bottom - rect.top, NULL, menu, hInstance, 0);
if (!hWnd)
{
return -1;
}
Level::hWnd = hWnd;
Level::ClearChecks();
CheckMenuItem(GetMenu(hWnd), MENU_25 + 3, MF_CHECKED);
Graphics* gfx = new Graphics();
if (!gfx->Init(hWnd))
{
delete gfx;
return -1;
}
Graphics* graphics = gfx;
CurrentLevel = new Level1(gfx);
ShowWindow(hWnd, iCmdShow);
UpdateWindow(hWnd);
MSG msg;
msg.message = WM_NULL;
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
CurrentLevel->Update(msg.wParam, msg.lParam);
CurrentLevel->Render();
}
}
delete CurrentLevel;
delete gfx;
return 0;
}
|
4924522acca2179e686c624c6df50ba87bc75ccb
|
[
"Markdown",
"C",
"C++"
] | 12
|
C++
|
konraadkan/SPR-Builder
|
5b12e3389bef0100f6e5c6f26bc1f2d9f2e2b4c7
|
2c3113df4280869afbfe4b3de8eee6337e2c409f
|
refs/heads/master
|
<file_sep>#include <string>
#include <iostream>
#include <thread>
#include <math.h>
#include <chrono>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
typedef std::chrono::high_resolution_clock Clock;
#define defaultM 10000
#define defaultN 10000
#define defaultThreads 4
using namespace std;
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<std::chrono::microseconds>
(clock_::now() - beg_).count();
}
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
void Initiate(int** Array, int* Vector, long* ResultVector, int M, int N){
for(int i = 0; i < M; i++){
for(int j = 0; j< N; j++){
Array[i][j] = rand() % 99 + 1;
}
ResultVector[i] = 0;
}
for(int i = 0; i< N; i++){
Vector[i] = rand() % 99 + 1;
}
}
int** Make2DIntArray(int arraySizeX, int arraySizeY) {
int** theArray;
theArray = (int**) malloc(arraySizeX*sizeof(int*));
for (int i = 0; i < arraySizeX; i++)
theArray[i] = (int*) malloc(arraySizeY*sizeof(int));
return theArray;
}
void MultiplyByVector(long* ResultVector, int** theArray, int* Vector, int M, int N, int length, int offset){
int limit = 0 + offset + length;
limit = (limit > M) ? M : limit;
long temp = 0;
for(int i = 0 + offset; i < limit; i++){
for(int j = 0; j < N; j++){
temp += theArray[i][j] * Vector[j];
}
ResultVector[i] = temp;
temp = 0;
}
}
void VerticalMultiplyByVector(long* ResultVector, int** theArray, int* Vector, int M, int N, int length, int offset){
int limit = 0 + offset + length;
limit = (limit > N) ? N : limit;
long temp = 0;
for(int i = 0; i < M; i++){
for(int j = 0 + offset; j < limit; j++){
temp += theArray[i][j] * Vector[j];
}
ResultVector[i] += temp;
temp = 0;
}
}
void DumbVerticalMultiplyByVector(long* ResultVector, int** theArray, int* Vector, int M, int N, int length, int offset){
int limit = 0 + offset + length;
limit = (limit > N) ? N : limit;
long temp = 0;
for(int j = 0 + offset; j < limit; j++){
int quick = Vector[j];
for(int i = 0; i< M; i++){
temp += theArray[i][j] * quick;
ResultVector[i] += temp;
temp = 0;
}
}
}
int main(int argc, char* argv[])
{
int M = (argc >= 2) ? atoi(argv[1]) : defaultM;
int N = (argc >= 3) ? atoi(argv[2]) : defaultN;
int Threads = (argc >= 4) ? atoi(argv[3]) : defaultThreads;
Threads = (Threads >= 32) ? 32 : Threads;
cout << "<NAME>: [" << M << "][" << N << "]" << endl;
cout << "Broj threadova: " << Threads << endl;
double t1, t2, tt1, tt2;
int length, offset;
thread p[33];
Timer tmr;
srand (time(NULL));
// Inicijalizacija array-a MxN i vektora N
t1 = tmr.elapsed();
int** Array = Make2DIntArray(M, N);
int* Vector = (int*) malloc( N *sizeof(int));
long* ResultVector = (long*) malloc( M *sizeof(long));
Initiate(Array, Vector, ResultVector, M, N);
t2 = tmr.elapsed();
cout << "Inicijalizacija (vrijeme): " << (t2-t1) << endl;
// Thread incrementing and looping:
for(int t = 1; t< Threads; t = t*2){
cout << "========================================= \n" << "Broj niti: " << t << " \n=========================================" << endl;
tt1 = tmr.elapsed();
// Mnozenje matrice s vektorom - sekvencijalno
Initiate(Array, Vector, ResultVector, M, N);
t1 = tmr.elapsed();
MultiplyByVector(ResultVector, Array, Vector, M, N, M, 0);
t2 = tmr.elapsed();
cout << "Horizontalno - sekvencijalno (vrijeme): " << (t2-t1) << endl;
cout << "Par rezultata mnozenja: " << ResultVector[1] << ", " << ResultVector[2] << endl;
// Mnozenje matrice s vektorom - paralelno
Initiate(Array, Vector, ResultVector, M, N);
length = M / t;
t1 = tmr.elapsed();
for( int z = 0; z < t; z++){
offset = z * length;
p[z] = std::thread(MultiplyByVector, ResultVector, Array, Vector, M, N, length, offset);
p[z].join();
}
for( int z = 0; z < t; z++){
}
t2 = tmr.elapsed();
cout << "Horizontalno - paralelno (vrijeme): " << (t2-t1) << endl;
cout << "Par rezultata mnozenja: " << ResultVector[1] << ", " << ResultVector[2] << endl;
// Mnozenje matrice s vektorom - vertikalno - sekvencijalno
Initiate(Array, Vector, ResultVector, M, N);
t1 = tmr.elapsed();
VerticalMultiplyByVector(ResultVector, Array, Vector, M, N, N, 0);
t2 = tmr.elapsed();
cout << "Vertikalno - sekvencijalno (vrijeme): " << (t2-t1) << endl;
cout << "Par rezultata mnozenja: " << ResultVector[1] << ", " << ResultVector[2] << endl;
// Mnozenje matrice s vektorom - vertikalno - paralelno
Initiate(Array, Vector, ResultVector, M, N);
length = N / t;
t1 = tmr.elapsed();
for( int z = 0; z < t; z++){
offset = z * length;
p[z] = std::thread(VerticalMultiplyByVector, ResultVector, Array, Vector, M, N, length, offset);
}
for( int z = 0; z < t; z++){
p[z].join();
}
t2 = tmr.elapsed();
cout << "Vertikalno - paralelno (vrijeme): " << (t2-t1) << endl;
cout << "Par rezultata mnozenja: " << ResultVector[1] << ", " << ResultVector[2] << endl;
// Mnozenje matrice s vektorom - vertikalno - sekvencijalno - glupo
Initiate(Array, Vector, ResultVector, M, N);
t1 = tmr.elapsed();
DumbVerticalMultiplyByVector(ResultVector, Array, Vector, M, N, N, 0);
t2 = tmr.elapsed();
cout << "Ne-ef. vertikalno - sekv (vrijeme): " << (t2-t1) << endl;
cout << "Par rezultata mnozenja: " << ResultVector[1] << ", " << ResultVector[2] << endl;
// Mnozenje matrice s vektorom - vertikalno - paralelno
Initiate(Array, Vector, ResultVector, M, N);
length = N / t;
t1 = tmr.elapsed();
for( int z = 0; z < t; z++){
offset = z * length;
p[z] = std::thread(DumbVerticalMultiplyByVector, ResultVector, Array, Vector, M, N, length, offset);
}
for( int z = 0; z < t; z++){
p[z].join();
}
t2 = tmr.elapsed();
cout << "Ne-ef. vertikalno - prll (vrijeme): " << (t2-t1) << endl;
cout << "Par rezultata mnozenja: " << ResultVector[1] << ", " << ResultVector[2] << endl;
tt2 = tmr.elapsed();
cout << "========================================= \n" << "Za " << t << " niti potrebno je totalno " << tt2 - tt1 << " \n=========================================" << endl;
}
}
<file_sep>#!/bin/bash
echo "Initiated testing..."
for i in `seq 1 20`;
do
echo Test number $i
./Program.out >> TestRecords
echo "Saved."
done
echo "Finished testing..."<file_sep>#pragma once
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <vector>
//PROGRAM PARAMETERS!
//Matrix sizes: A[M][N], x[N], b[M] (A*x=b)
#define N 10000
#define M 7000
#define MAX_NUMBER_OF_THREADS 32 //everything above this is ignored
#define PRINTING_ENABLED false //set true for displaying data
#define GRAPH_OUTPUT true
short* MakeVector(short size)
{
short *b;
b = (short*)malloc(size * sizeof(short));
return b;
}
short** MakeMatrix(short sizeX, short sizeY)
{
short **A;
A = (short**)malloc(sizeX * sizeof(short*));
for (short i = 0; i < sizeX; i++)
A[i] = MakeVector(sizeY);
return A;
}
void printMatrix(short sizeX, short sizeY, short **A)
{
for (short i = 0; i < sizeX; i++)
{
for (short j = 0; j < sizeY; j++)
{
std::cout << A[i][j] << "\t";
}
std::cout << std::endl;
}
}
void printVector(short size, short *vec)
{
for (short i = 0; i < size; i++)
{
std::cout << vec[i] << std::endl;
}
}
void initZero(short size, short *vec)
{
for (short i = 0; i < size; i++)
{
vec[i] = 0;
}
}
void initRandomNumbers(short size, short range, short *vec)
{
for (short i = 0; i < size; i++)
{
vec[i] = rand() % range;
}
}
void initRandomNumbers(short sizeX, short sizeY, short range, short **A)
{
for (short i = 0; i < sizeX; i++)
{
for (short j = 0; j < sizeY; j++)
{
A[i][j] = rand() % range;
}
}
}
void transposeMatrix(short sizeX, short sizeY, short **A, short **AT)
{
for (short i = 0; i < sizeX; i++)
{
for (short j = 0; j < sizeY; j++)
{
AT[j][i] = A[i][j];
}
}
}
void multiplyVectorWithConstant(short size, short *vec, short number, short *result)
{
for (short i = 0; i < size; i++)
{
result[i] = vec[i] * number;
}
}
void addVectorToVector(short size, short *vec1, short *vec2)
{
for (short i = 0; i < size; i++)
{
vec1[i] += vec2[i];
}
}
void multiplyByRows(short start, short end, short sizeX, short sizeY, short **A, short *x, short *b)
{
for (short i = start; i < end; i++)
{
for (short j = 0; j < sizeY; j++)
{
b[i] += A[i][j] * x[j];
}
}
}
void multiplyByColumns(short start, short end, short sizeX, short sizeY, short **A, short *x, short *b)
{
for (short i = start; i < end; i++)
{
short *tempA = MakeVector(sizeX);
for (short j = 0; j < sizeX; j++)
{
tempA[j] = A[j][i] * x[i];
}
addVectorToVector(sizeX, b, tempA);
free(tempA);
}
}
void multiplyByRowsDivideByCollumns(short start, short end, short sizeX, short sizeY, short **A, short *x, short *b)
{
for (short i = 0; i < sizeX; i++)
{
short temp = 0;
for (short j = start; j < end; j++)
{
temp += A[i][j] * x[j];
}
b[i] += temp;
}
}
void multiplyByColumnsTransposed(short start, short end, short sizeX, short sizeY, short **AT, short *x, short *b)
{
short *temp_result = MakeVector(sizeX);
for (short i = start; i < end; i++)
{
multiplyVectorWithConstant(sizeX, AT[i], x[i], temp_result);
addVectorToVector(sizeX, b, temp_result);
}
free(temp_result);
}
<file_sep>#include <string>
#include <iostream>
#include <thread>
#include <math.h>
#include <chrono>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <vector>
#include "Functions.h"
//PROGRAM PARAMETERS-inside Functions.h!
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
//Timers
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<std::chrono::microseconds>
(clock_::now() - beg_).count();
}
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
vector<short> broj_niti = { 2, 4, 8, 16, M, N};
short **A, *x, *b; //A*x=b
short **AT; //A transposed
double timer_start, timer_end;
Timer tmr;
void Sequential(string poruka, void(*fun)(short par1, short par2, short par3, short par4, short** par5, short* par6, short *par7), short par2, short** par5)
{
if (!GRAPH_OUTPUT) cout << poruka << endl;
timer_start = tmr.elapsed();
initZero(M, b);
(*fun)(0, par2, M, N, par5, x, b);
if (PRINTING_ENABLED)
{
cout << "Vektor b:" << endl;
printVector(M, b);
}
timer_end = tmr.elapsed();
if (!GRAPH_OUTPUT) std::cout << "->proteklo vrijeme: " << timer_end - timer_start << endl;
if (GRAPH_OUTPUT) std::cout << timer_end - timer_start << ", ";
if (!GRAPH_OUTPUT) std::cout << endl << "--------------------------------------------" << endl << endl;
}
void Parallel(string poruka, void(*fun)(short par1, short par2, short par3, short par4, short** par5, short* par6, short *par7), short par22, short** par5, int par7)
{
if (!GRAPH_OUTPUT) cout << poruka << endl;
if (!GRAPH_OUTPUT) std::cout << endl << "******************" << endl;
for (unsigned short nit = 0; nit < broj_niti.size(); nit++)
{
if (broj_niti[nit] <= MAX_NUMBER_OF_THREADS)
{
thread threads[MAX_NUMBER_OF_THREADS];
short result[MAX_NUMBER_OF_THREADS][M];
short segment_size = 0;
if (par7 == 1)
segment_size = M / broj_niti[nit];
else if (par7 == 2)
segment_size = N / broj_niti[nit];
if (!GRAPH_OUTPUT) cout << "Broj niti: " << broj_niti[nit] << endl;
timer_start = tmr.elapsed();
initZero(M, b);
unsigned short i = 0;
for (i = 0; i < broj_niti[nit] - 1; i++)
{
initZero(M, result[i]);
if(par7 == 1)
threads[i] = thread((*fun), i *segment_size, i*segment_size + segment_size, M, N, par5, x, b);
else if(par7 == 2)
threads[i] = thread((*fun), i *segment_size, i*segment_size + segment_size, M, N, par5, x, result[i]);
}
initZero(M, result[i]);
if (par7 == 1)
threads[i] = thread((*fun), i *segment_size, par22, M, N, par5, x, b);
else if (par7 == 2)
threads[i] = thread((*fun), i *segment_size, par22, M, N, par5, x, result[i]);
for (short i = 0; i < broj_niti[nit]; i++)
{
threads[i].join();
}
for (short i = 0; i < broj_niti[nit]; i++)
{
addVectorToVector(M, b, result[i]);
}
if (PRINTING_ENABLED)
{
cout << "Vektor b:" << endl;
printVector(M, b);
}
timer_end = tmr.elapsed();
if (!GRAPH_OUTPUT) std::cout << "->proteklo vrijeme: " << timer_end - timer_start << endl;
if (GRAPH_OUTPUT) std::cout << timer_end - timer_start << ", ";
if (!GRAPH_OUTPUT) std::cout << "******************" << endl;
}
}
if (!GRAPH_OUTPUT) std::cout << endl << "--------------------------------------------" << endl << endl;
}
int main()
{
A = MakeMatrix(M, N);
x = MakeVector(N);
b = MakeVector(M);
AT = MakeMatrix(N, M);
srand(time(NULL));
if (GRAPH_OUTPUT) std::cout << std::fixed;
#pragma region Inicijalizacije podataka
if (!GRAPH_OUTPUT) cout << "Inicijalizacija matrica:" << endl;
timer_start = tmr.elapsed();
initRandomNumbers(M, N, 10, A);
initRandomNumbers(N, 10, x);
if (PRINTING_ENABLED)
{
cout << "Matrica A:" << endl;
printMatrix(M, N, A);
cout << "Vektor x:" << endl;
printVector(N, x);
}
timer_end = tmr.elapsed();
if (!GRAPH_OUTPUT) std::cout << "->proteklo vrijeme: " << timer_end - timer_start << endl;
if (GRAPH_OUTPUT) std::cout << timer_end - timer_start << ", ";
if (!GRAPH_OUTPUT) std::cout << endl << "--------------------------------------------" << endl<<endl;
#pragma endregion
Sequential("Sekvencijalno mnozenje Ax=b po redcima matrice A:", &multiplyByRows, M, A);
Parallel("Paralelno mnozenje Ax=b po redcima matrice A:", multiplyByRows, M, A, 1);
Sequential("Sekvencijalno mnozenje Ax=b po stupcima matrice A:", multiplyByColumns, N, A);
Parallel("Paralelno mnozenje Ax=b po stupcima matrice A:", multiplyByColumns, N, A, 2);
Sequential("Sekvencijalno mnozenje Ax=b po redcima matrice A (podjeljene po stupcima):", multiplyByRowsDivideByCollumns, N, A);
Parallel("Paralelno mnozenje Ax=b po stupcima matrice A:", multiplyByRowsDivideByCollumns, N, A, 2);
transposeMatrix(M, N, A, AT);
Sequential("Sekvencijalno mnozenje Ax=b po stupcima matrice A(s transponiranjem):", multiplyByColumnsTransposed, N, AT);
Parallel("Paralelno mnozenje Ax=b po stupcima matrice A(s transponiranjem):", multiplyByColumnsTransposed, N, AT, 2);
if (GRAPH_OUTPUT) std::cout << "0 \n";
}
|
0d72f787b6e9a9f9cbbb7af439e3116c33d5825e
|
[
"C++",
"Shell"
] | 4
|
C++
|
ZrinkaFiamengo/NAR_Matrix-Multiplication
|
f23cb1e3dd0ff2159bf62b2906112210dfe4d1e1
|
aac784f393ebd1765d9f37234324a0c555bf9aaf
|
refs/heads/master
|
<file_sep>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#ifndef DAWN_OPTIMIZER_STENCIL_H
#define DAWN_OPTIMIZER_STENCIL_H
#include "dawn/Optimizer/MultiStage.h"
#include "dawn/SIR/SIR.h"
#include "dawn/SIR/Statement.h"
#include <functional>
#include <list>
#include <memory>
#include <unordered_set>
#include <vector>
namespace dawn {
class StencilInstantiation;
class DependencyGraphStage;
class StatementAccessesPair;
/// @brief A Stencil is represented by a collection of MultiStages
/// @ingroup optimizer
class Stencil {
StencilInstantiation& stencilInstantiation_;
const std::shared_ptr<sir::Stencil> SIRStencil_;
/// Identifier of the stencil. Note that this ID is only for code-generation to associate the
/// stencil with a stencil-call in the run() method
int StencilID_;
/// Dependency graph of the stages of this stencil
std::shared_ptr<DependencyGraphStage> stageDependencyGraph_;
/// List of multi-stages in the stencil
std::list<std::shared_ptr<MultiStage>> multistages_;
public:
struct FieldInfo {
bool IsTemporary;
std::string Name;
int AccessID;
};
/// @brief Position of a stage
///
/// The position first identifies the multi-stage (`MultiStageIndex`) and afterwards the stage
/// within the multi-stage (`StageOffset`). A `StageOffset` of -1 means @b before the first stage
/// in the multi-stage.
///
/// @b Example:
/** @verbatim
+- MultiStage0-+
| | <------ Position(0, -1)
| +----------+ |
| | Stage0 | | <----- Position(0, 0)
| +----------+ |
| |
| +----------+ |
| | Stage1 | | <----- Position(0, 1)
| +----------+ |
+--------------+
+- MultiStage1-+
| | <------ Position(1, -1)
| +----------+ |
| | Stage0 | | <------ Position(1, 0)
| +----------+ |
+--------------+
@endverbatim
*/
struct StagePosition {
StagePosition(int multiStageIndex, int stageOffset)
: MultiStageIndex(multiStageIndex), StageOffset(stageOffset) {}
StagePosition() : MultiStageIndex(-1), StageOffset(-1) {}
StagePosition(const StagePosition&) = default;
StagePosition(StagePosition&&) = default;
StagePosition& operator=(const StagePosition&) = default;
StagePosition& operator=(StagePosition&&) = default;
bool operator<(const StagePosition& other) const;
bool operator==(const StagePosition& other) const;
bool operator!=(const StagePosition& other) const;
/// Index of the Multi-Stage
int MultiStageIndex;
/// Index of the Stage inside the Multi-Stage, -1 indicates one before the first
int StageOffset;
friend std::ostream& operator<<(std::ostream& os, const StagePosition& position);
};
/// @brief Position of a statement inside a stage
struct StatementPosition {
StatementPosition(StagePosition stagePos, int doMethodIndex, int statementIndex)
: StagePos(stagePos), DoMethodIndex(doMethodIndex), StatementIndex(statementIndex) {}
StatementPosition() : StagePos(), DoMethodIndex(-1), StatementIndex(-1) {}
StatementPosition(const StatementPosition&) = default;
StatementPosition(StatementPosition&&) = default;
StatementPosition& operator=(const StatementPosition&) = default;
StatementPosition& operator=(StatementPosition&&) = default;
bool operator<(const StatementPosition& other) const;
bool operator<=(const StatementPosition& other) const;
bool operator==(const StatementPosition& other) const;
bool operator!=(const StatementPosition& other) const;
/// @brief Check if `other` is in the same Do-Method as `this`
bool inSameDoMethod(const StatementPosition& other) const;
/// Position of the Stage
StagePosition StagePos;
/// Index of the Do-Method inside the Stage, -1 indicates one before the first
int DoMethodIndex;
/// Index of the Statement inside the Do-Method, -1 indicates one before the first
int StatementIndex;
friend std::ostream& operator<<(std::ostream& os, const StatementPosition& position);
};
/// @brief Lifetime of a field or variable, given as an interval of `StatementPosition`s
///
/// The field lifes between [Begin, End].
struct Lifetime {
Lifetime(StatementPosition begin, StatementPosition end) : Begin(begin), End(end) {}
Lifetime() = default;
Lifetime(const Lifetime&) = default;
Lifetime(Lifetime&&) = default;
Lifetime& operator=(const Lifetime&) = default;
Lifetime& operator=(Lifetime&&) = default;
StatementPosition Begin;
StatementPosition End;
/// @brief Check if `this` overlaps with `other`
bool overlaps(const Lifetime& other) const;
friend std::ostream& operator<<(std::ostream& os, const Lifetime& lifetime);
};
/// @name Constructors and Assignment
/// @{
Stencil(StencilInstantiation& stencilInstantiation,
const std::shared_ptr<sir::Stencil>& SIRStencil, int StencilID,
const std::shared_ptr<DependencyGraphStage>& stageDependencyGraph = nullptr);
Stencil(const Stencil&) = default;
Stencil(Stencil&&) = default;
Stencil& operator=(const Stencil&) = default;
Stencil& operator=(Stencil&&) = default;
/// @}
/// @brief Compute a set of intervals for this stencil
std::unordered_set<Interval> getIntervals() const;
/// @brief Get the fields referenced by this stencil (temporary fields are listed first if
/// requested)
std::vector<FieldInfo> getFields(bool withTemporaries = true) const;
/// @brief Get the global variables referenced by this stencil
std::vector<std::string> getGlobalVariables() const;
/// @brief Get the stencil instantiation
StencilInstantiation& getStencilInstantiation() const { return stencilInstantiation_; }
/// @brief Get the multi-stages of the stencil
std::list<std::shared_ptr<MultiStage>>& getMultiStages() { return multistages_; }
const std::list<std::shared_ptr<MultiStage>>& getMultiStages() const { return multistages_; }
/// @brief Get the enclosing interval of accesses of temporaries used in this stencil
std::shared_ptr<Interval> getEnclosingIntervalTemporaries() const;
/// @brief Get the multi-stage at given multistage index
const std::shared_ptr<MultiStage>& getMultiStageFromMultiStageIndex(int multiStageIdx) const;
/// @brief Get the multi-stage at given stage index
const std::shared_ptr<MultiStage>& getMultiStageFromStageIndex(int stageIdx) const;
/// @brief Get the position of the stage which is identified by the linear stage index
StagePosition getPositionFromStageIndex(int stageIdx) const;
int getStageIndexFromPosition(const StagePosition& position) const;
/// @brief Get the stage at given linear stage index or position
/// @{
const std::shared_ptr<Stage>& getStage(int stageIdx) const;
const std::shared_ptr<Stage>& getStage(const StagePosition& position) const;
/// @}
/// @brief Get the unique `StencilID`
int getStencilID() const { return StencilID_; }
/// @brief Insert the `stage` @b after the given `position`
void insertStage(const StagePosition& position, const std::shared_ptr<Stage>& stage);
/// @brief Get number of stages
int getNumStages() const;
/// @brief Run `func` on each StatementAccessesPair of the stencil (or on the given
/// StatementAccessesPair of the stages specified in `lifetime`)
///
/// @param func Function to run on all statements of each Do-Method
/// @param updateFields Update the fields afterwards
/// @{
void forEachStatementAccessesPair(
std::function<void(ArrayRef<std::shared_ptr<StatementAccessesPair>>)> func,
bool updateFields = false);
void forEachStatementAccessesPair(
std::function<void(ArrayRef<std::shared_ptr<StatementAccessesPair>>)> func,
const Lifetime& lifetime, bool updateFields = false);
/// @}
/// @brief Update the fields of the stages in the stencil (or the stages specified in `lifetime`)
/// @{
void updateFields();
void updateFields(const Lifetime& lifetime);
/// @}
/// @brief Get/Set the dependency graph of the stages
/// @{
const std::shared_ptr<DependencyGraphStage>& getStageDependencyGraph() const;
void setStageDependencyGraph(const std::shared_ptr<DependencyGraphStage>& stageDAG);
/// @}
/// @brief Get the axis of the stencil (i.e the interval of all stages)
///
/// @param useExtendedInterval Merge the extended intervals
Interval getAxis(bool useExtendedInterval = true) const;
/// @brief Rename all occurences of field `oldAccessID` to `newAccessID`
void renameAllOccurrences(int oldAccessID, int newAccessID);
/// @brief Compute the life-time of the fields (or variables) given as a set of `AccessID`s
std::unordered_map<int, Lifetime> getLifetime(const std::unordered_set<int>& AccessID) const;
/// @brief Check if the stencil is empty (i.e contains no statements)
bool isEmpty() const;
/// @brief Get the SIR Stencil
const std::shared_ptr<sir::Stencil> getSIRStencil() const;
/// @brief Apply the visitor to all statements in the stencil
void accept(ASTVisitor& visitor);
/// @brief Convert stencil to string (i.e print the list of multi-stage -> stages)
friend std::ostream& operator<<(std::ostream& os, const Stencil& stencil);
/// @brief Method to compute and return the maximum extents for all the used accessors/fields
std::unordered_map<int, Extents> const computeEnclosingAccessExtents() const;
private:
void forEachStatementAccessesPairImpl(
std::function<void(ArrayRef<std::shared_ptr<StatementAccessesPair>>)> func, int startStageIdx,
int endStageIdx, bool updateFields);
void updateFieldsImpl(int startStageIdx, int endStageIdx);
};
} // namespace dawn
#endif
<file_sep>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/Optimizer/Stencil.h"
#include "dawn/Optimizer/DependencyGraphStage.h"
#include "dawn/Optimizer/Renaming.h"
#include "dawn/Optimizer/StencilInstantiation.h"
#include "dawn/SIR/SIR.h"
#include "dawn/Support/StringUtil.h"
#include "dawn/Support/Unreachable.h"
#include <algorithm>
#include <iostream>
#include <numeric>
namespace dawn {
std::ostream& operator<<(std::ostream& os, const Stencil::StagePosition& position) {
return (os << "(" << position.MultiStageIndex << ", " << position.StageOffset << ")");
}
std::ostream& operator<<(std::ostream& os, const Stencil::StatementPosition& position) {
return (os << "(Stage=" << position.StagePos << ", DoMethod=" << position.DoMethodIndex
<< ", Statement=" << position.StatementIndex << ")");
}
std::ostream& operator<<(std::ostream& os, const Stencil::Lifetime& lifetime) {
return (os << "[Begin=" << lifetime.Begin << ", End=" << lifetime.End << "]");
}
bool Stencil::StagePosition::operator<(const Stencil::StagePosition& other) const {
return MultiStageIndex < other.MultiStageIndex ||
(MultiStageIndex == other.MultiStageIndex && StageOffset < other.StageOffset);
}
bool Stencil::StagePosition::operator==(const Stencil::StagePosition& other) const {
return MultiStageIndex == other.MultiStageIndex && StageOffset == other.StageOffset;
}
bool Stencil::StagePosition::operator!=(const Stencil::StagePosition& other) const {
return !(*this == other);
}
bool Stencil::StatementPosition::operator<(const Stencil::StatementPosition& other) const {
return StagePos < other.StagePos ||
(StagePos == other.StagePos && DoMethodIndex == other.DoMethodIndex &&
StatementIndex < other.StatementIndex);
}
bool Stencil::StatementPosition::operator<=(const Stencil::StatementPosition& other) const {
return operator<(other) || operator==(other);
}
bool Stencil::StatementPosition::operator==(const Stencil::StatementPosition& other) const {
return StagePos == other.StagePos && DoMethodIndex == other.DoMethodIndex &&
StatementIndex == other.StatementIndex;
}
bool Stencil::StatementPosition::operator!=(const Stencil::StatementPosition& other) const {
return !(*this == other);
}
bool Stencil::StatementPosition::inSameDoMethod(const Stencil::StatementPosition& other) const {
return StagePos == other.StagePos && DoMethodIndex == other.DoMethodIndex;
}
bool Stencil::Lifetime::overlaps(const Stencil::Lifetime& other) const {
// Note: same stage but different Do-Method are treated as overlapping!
bool lowerBoundOverlap = false;
if(Begin.StagePos == other.End.StagePos && Begin.DoMethodIndex != other.End.DoMethodIndex)
lowerBoundOverlap = true;
else
lowerBoundOverlap = Begin <= other.End;
bool upperBoundOverlap = false;
if(other.Begin.StagePos == End.StagePos && other.Begin.DoMethodIndex != End.DoMethodIndex)
upperBoundOverlap = true;
else
upperBoundOverlap = other.Begin <= End;
return lowerBoundOverlap && upperBoundOverlap;
}
Stencil::Stencil(StencilInstantiation& stencilInstantiation,
const std::shared_ptr<sir::Stencil>& SIRStencil, int StencilID,
const std::shared_ptr<DependencyGraphStage>& stageDependencyGraph)
: stencilInstantiation_(stencilInstantiation), SIRStencil_(SIRStencil), StencilID_(StencilID),
stageDependencyGraph_(stageDependencyGraph) {}
std::unordered_set<Interval> Stencil::getIntervals() const {
std::unordered_set<Interval> intervals;
for(const auto& multistage : multistages_)
for(const auto& stage : multistage->getStages())
for(const auto& doMethod : stage->getDoMethods())
intervals.insert(doMethod->getInterval());
return intervals;
}
std::vector<Stencil::FieldInfo> Stencil::getFields(bool withTemporaries) const {
std::set<int> fieldAccessIDs;
for(const auto& multistage : multistages_) {
for(const auto& stage : multistage->getStages()) {
for(const auto& field : stage->getFields()) {
fieldAccessIDs.insert(field.getAccessID());
}
}
}
std::vector<FieldInfo> fields;
for(const auto& AccessID : fieldAccessIDs) {
std::string name = stencilInstantiation_.getNameFromAccessID(AccessID);
bool isTemporary = stencilInstantiation_.isTemporaryField(AccessID);
if(isTemporary) {
if(withTemporaries) {
fields.insert(fields.begin(), FieldInfo{isTemporary, name, AccessID});
}
} else {
fields.emplace_back(FieldInfo{isTemporary, name, AccessID});
}
}
return fields;
}
std::vector<std::string> Stencil::getGlobalVariables() const {
std::set<int> globalVariableAccessIDs;
for(const auto& multistage : multistages_) {
for(const auto& stage : multistage->getStages()) {
globalVariableAccessIDs.insert(stage->getAllGlobalVariables().begin(),
stage->getAllGlobalVariables().end());
}
}
std::vector<std::string> globalVariables;
for(const auto& AccessID : globalVariableAccessIDs)
globalVariables.push_back(stencilInstantiation_.getNameFromAccessID(AccessID));
return globalVariables;
}
int Stencil::getNumStages() const {
return std::accumulate(multistages_.begin(), multistages_.end(), int(0),
[](int numStages, const std::shared_ptr<MultiStage>& MS) {
return numStages + MS->getStages().size();
});
}
void Stencil::forEachStatementAccessesPair(
std::function<void(ArrayRef<std::shared_ptr<StatementAccessesPair>>)> func, bool updateFields) {
forEachStatementAccessesPairImpl(func, 0, getNumStages(), updateFields);
}
void Stencil::forEachStatementAccessesPair(
std::function<void(ArrayRef<std::shared_ptr<StatementAccessesPair>>)> func,
const Stencil::Lifetime& lifetime, bool updateFields) {
int startStageIdx = getStageIndexFromPosition(lifetime.Begin.StagePos);
int endStageIdx = getStageIndexFromPosition(lifetime.End.StagePos);
forEachStatementAccessesPairImpl(func, startStageIdx, endStageIdx + 1, updateFields);
}
void Stencil::forEachStatementAccessesPairImpl(
std::function<void(ArrayRef<std::shared_ptr<StatementAccessesPair>>)> func, int startStageIdx,
int endStageIdx, bool updateFields) {
for(int stageIdx = startStageIdx; stageIdx < endStageIdx; ++stageIdx) {
auto stage = getStage(stageIdx);
for(const auto& doMethodPtr : stage->getDoMethods())
func(doMethodPtr->getStatementAccessesPairs());
if(updateFields)
stage->update();
}
}
void Stencil::updateFields(const Stencil::Lifetime& lifetime) {
int startStageIdx = getStageIndexFromPosition(lifetime.Begin.StagePos);
int endStageIdx = getStageIndexFromPosition(lifetime.End.StagePos);
updateFieldsImpl(startStageIdx, endStageIdx + 1);
}
void Stencil::updateFields() { updateFieldsImpl(0, getNumStages()); }
void Stencil::updateFieldsImpl(int startStageIdx, int endStageIdx) {
for(int stageIdx = startStageIdx; stageIdx < endStageIdx; ++stageIdx)
getStage(stageIdx)->update();
}
void Stencil::setStageDependencyGraph(const std::shared_ptr<DependencyGraphStage>& stageDAG) {
stageDependencyGraph_ = stageDAG;
}
const std::shared_ptr<DependencyGraphStage>& Stencil::getStageDependencyGraph() const {
return stageDependencyGraph_;
}
const std::shared_ptr<MultiStage>&
Stencil::getMultiStageFromMultiStageIndex(int multiStageIdx) const {
DAWN_ASSERT_MSG(multiStageIdx < multistages_.size(), "invalid multi-stage index");
auto msIt = multistages_.begin();
std::advance(msIt, multiStageIdx);
return *msIt;
}
const std::shared_ptr<MultiStage>& Stencil::getMultiStageFromStageIndex(int stageIdx) const {
return getMultiStageFromMultiStageIndex(getPositionFromStageIndex(stageIdx).MultiStageIndex);
}
Stencil::StagePosition Stencil::getPositionFromStageIndex(int stageIdx) const {
DAWN_ASSERT(!multistages_.empty());
if(stageIdx == -1)
return StagePosition(0, -1);
int curIdx = 0, multiStageIdx = 0;
for(const auto& MS : multistages_) {
// Is our stage in this multi-stage?
int numStages = MS->getStages().size();
if((curIdx + numStages) <= stageIdx) {
curIdx += numStages;
multiStageIdx++;
continue;
} else {
int stageOffset = stageIdx - curIdx;
DAWN_ASSERT_MSG(stageOffset < numStages, "invalid stage index");
return StagePosition(multiStageIdx, stageOffset);
}
}
dawn_unreachable("invalid stage index");
}
int Stencil::getStageIndexFromPosition(const Stencil::StagePosition& position) const {
auto curMSIt = multistages_.begin();
std::advance(curMSIt, position.MultiStageIndex);
// Count the number of stages in the multistages before our current MS
int numStagesInMSBeforeCurMS =
std::accumulate(multistages_.begin(), curMSIt, int(0),
[&](int numStages, const std::shared_ptr<MultiStage>& MS) {
return numStages + MS->getStages().size();
});
// Add the current stage offset
return numStagesInMSBeforeCurMS + position.StageOffset;
}
const std::shared_ptr<Stage>& Stencil::getStage(const StagePosition& position) const {
// Get the multi-stage ...
DAWN_ASSERT_MSG(position.MultiStageIndex < multistages_.size(), "invalid multi-stage index");
auto msIt = multistages_.begin();
std::advance(msIt, position.MultiStageIndex);
const auto& MS = *msIt;
// ... and the requested stage inside the given multi-stage
DAWN_ASSERT_MSG(position.StageOffset == -1 || position.StageOffset < MS->getStages().size(),
"invalid stage offset");
auto stageIt = MS->getStages().begin();
std::advance(stageIt, position.StageOffset == -1 ? 0 : position.StageOffset);
return *stageIt;
}
const std::shared_ptr<Stage>& Stencil::getStage(int stageIdx) const {
int curIdx = 0;
for(const auto& MS : multistages_) {
// Is our stage in this multi-stage?
int numStages = MS->getStages().size();
if((curIdx + numStages) <= stageIdx) {
// No... continue
curIdx += numStages;
continue;
} else {
// Yes... advance to our stage
int stageOffset = stageIdx - curIdx;
DAWN_ASSERT_MSG(stageOffset < MS->getStages().size(), "invalid stage index");
auto stageIt = MS->getStages().begin();
std::advance(stageIt, stageOffset);
return *stageIt;
}
}
dawn_unreachable("invalid stage index");
}
void Stencil::insertStage(const StagePosition& position, const std::shared_ptr<Stage>& stage) {
// Get the multi-stage ...
DAWN_ASSERT_MSG(position.MultiStageIndex < multistages_.size(), "invalid multi-stage index");
auto msIt = multistages_.begin();
std::advance(msIt, position.MultiStageIndex);
const auto& MS = *msIt;
// ... and the requested stage inside the given multi-stage
DAWN_ASSERT_MSG(position.StageOffset == -1 || position.StageOffset < MS->getStages().size(),
"invalid stage offset");
auto stageIt = MS->getStages().begin();
// A stage offset of -1 indicates *before* the first element (thus nothing to do).
// Otherwise we advance one beyond the requested stage as we insert *after* the specified
// stage and `std::list::insert` inserts *before*.
if(position.StageOffset != -1) {
std::advance(stageIt, position.StageOffset);
if(stageIt != MS->getStages().end())
stageIt++;
}
MS->getStages().insert(stageIt, stage);
}
Interval Stencil::getAxis(bool useExtendedInterval) const {
int numStages = getNumStages();
DAWN_ASSERT_MSG(numStages, "need atleast one stage");
Interval axis = getStage(0)->getEnclosingExtendedInterval();
for(int stageIdx = 1; stageIdx < numStages; ++stageIdx)
axis.merge(useExtendedInterval ? getStage(stageIdx)->getEnclosingExtendedInterval()
: getStage(stageIdx)->getEnclosingInterval());
return axis;
}
void Stencil::renameAllOccurrences(int oldAccessID, int newAccessID) {
for(const auto& multistage : getMultiStages()) {
multistage->renameAllOccurrences(oldAccessID, newAccessID);
}
}
std::unordered_map<int, Stencil::Lifetime>
Stencil::getLifetime(const std::unordered_set<int>& AccessIDs) const {
std::unordered_map<int, StatementPosition> Begin;
std::unordered_map<int, StatementPosition> End;
int multiStageIdx = 0;
for(const auto& multistagePtr : multistages_) {
int stageOffset = 0;
for(const auto& stagePtr : multistagePtr->getStages()) {
int doMethodIndex = 0;
for(const auto& doMethodPtr : stagePtr->getDoMethods()) {
DoMethod& doMethod = *doMethodPtr;
for(int statementIdx = 0; statementIdx < doMethod.getStatementAccessesPairs().size();
++statementIdx) {
const Accesses& accesses =
*doMethod.getStatementAccessesPairs()[statementIdx]->getAccesses();
auto processAccessMap = [&](const std::unordered_map<int, Extents>& accessMap) {
for(const auto& AccessIDExtentPair : accessMap) {
int AccessID = AccessIDExtentPair.first;
if(AccessIDs.count(AccessID)) {
StatementPosition pos(StagePosition(multiStageIdx, stageOffset), doMethodIndex,
statementIdx);
if(!Begin.count(AccessID))
Begin.emplace(AccessID, pos);
End[AccessID] = pos;
}
}
};
processAccessMap(accesses.getWriteAccesses());
processAccessMap(accesses.getReadAccesses());
}
doMethodIndex++;
}
stageOffset++;
}
multiStageIdx++;
}
std::unordered_map<int, Lifetime> lifetimeMap;
for(int AccessID : AccessIDs) {
auto& begin = Begin[AccessID];
auto& end = End[AccessID];
lifetimeMap.emplace(AccessID, Lifetime(begin, end));
}
return lifetimeMap;
}
bool Stencil::isEmpty() const {
for(const auto& MS : getMultiStages())
for(const auto& stage : MS->getStages())
for(auto& doMethod : stage->getDoMethods())
if(!doMethod->getStatementAccessesPairs().empty())
return false;
return true;
}
std::shared_ptr<Interval> Stencil::getEnclosingIntervalTemporaries() const {
std::shared_ptr<Interval> tmpInterval;
for(auto mss : getMultiStages()) {
auto mssInterval = mss->getEnclosingAccessIntervalTemporaries();
if(tmpInterval != nullptr && mssInterval != nullptr) {
tmpInterval->merge(*mssInterval);
} else if(mssInterval != nullptr) {
tmpInterval = mssInterval;
}
}
return tmpInterval;
}
const std::shared_ptr<sir::Stencil> Stencil::getSIRStencil() const { return SIRStencil_; }
void Stencil::accept(ASTVisitor& visitor) {
for(const auto& multistagePtr : multistages_)
for(const auto& stagePtr : multistagePtr->getStages())
for(const auto& doMethodPtr : stagePtr->getDoMethods())
for(const auto& stmtAcessesPairPtr : doMethodPtr->getStatementAccessesPairs())
stmtAcessesPairPtr->getStatement()->ASTStmt->accept(visitor);
}
std::ostream& operator<<(std::ostream& os, const Stencil& stencil) {
int multiStageIdx = 0;
for(const auto& MS : stencil.getMultiStages()) {
os << "MultiStage " << (multiStageIdx++) << ": (" << MS->getLoopOrder() << ")\n";
for(const auto& stage : MS->getStages())
os << " " << stencil.getStencilInstantiation().getNameFromStageID(stage->getStageID()) << " "
<< RangeToString()(stage->getFields(),
[&](const Field& field) {
return stencil.getStencilInstantiation().getNameFromAccessID(
field.getAccessID());
})
<< "\n";
}
return os;
}
std::unordered_map<int, Extents> const Stencil::computeEnclosingAccessExtents() const {
std::unordered_map<int, Extents> maxExtents_;
// iterate through multistages
for(const auto& MS : multistages_) {
// iterate through stages
for(const auto& stage : MS->getStages()) {
std::size_t accessorIdx = 0;
for(; accessorIdx < stage->getFields().size(); ++accessorIdx) {
const auto& field = stage->getFields()[accessorIdx];
// add the stage extent to the field extent
Extents e = field.getExtents();
e.add(stage->getExtents());
// merge with the current minimum/maximum extent for the given field
maxExtents_[stage->getFields()[accessorIdx].getAccessID()].merge(e);
}
}
}
return maxExtents_;
}
} // namespace dawn
<file_sep>#!/bin/bash
module load git
module load cmake
module load gcc/5.4.0-2.26
module load python/3.6.2-gmvolf-17.02
export CXX=`which g++`
export CC=`which gcc`
export BOOST_DIR=/project/c14/install/kesch/boost/boost_1_67_0/
export PROTOBUFDIR="/scratch/jenkins/workspace/protobuf/slave/kesch/install/lib64/cmake/protobuf/"
<file_sep>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/Optimizer/DoMethod.h"
#include "dawn/Optimizer/Accesses.h"
#include "dawn/Optimizer/DependencyGraphAccesses.h"
#include "dawn/Optimizer/StatementAccessesPair.h"
#include "dawn/SIR/Statement.h"
#include <boost/optional.hpp>
namespace dawn {
DoMethod::DoMethod(Stage* stage, Interval interval)
: stage_(stage), interval_(interval), dependencyGraph_(nullptr) {}
std::vector<std::shared_ptr<StatementAccessesPair>>& DoMethod::getStatementAccessesPairs() {
return statementAccessesPairs_;
}
const std::vector<std::shared_ptr<StatementAccessesPair>>&
DoMethod::getStatementAccessesPairs() const {
return statementAccessesPairs_;
}
Interval& DoMethod::getInterval() { return interval_; }
const Interval& DoMethod::getInterval() const { return interval_; }
Stage* DoMethod::getStage() { return stage_; }
void DoMethod::setDependencyGraph(const std::shared_ptr<DependencyGraphAccesses>& DG) {
dependencyGraph_ = DG;
}
std::shared_ptr<DependencyGraphAccesses>& DoMethod::getDependencyGraph() {
return dependencyGraph_;
}
boost::optional<Extents> DoMethod::computeMaximumExtents(const int accessID) const {
boost::optional<Extents> extents;
for(auto& stmtAccess : getStatementAccessesPairs()) {
auto extents_ = stmtAccess->computeMaximumExtents(accessID);
if(!extents_.is_initialized())
continue;
if(extents.is_initialized()) {
extents->merge(*extents_);
} else {
extents = extents_;
}
}
return extents;
}
boost::optional<Interval> DoMethod::computeEnclosingAccessInterval(const int accessID) const {
boost::optional<Interval> interval;
boost::optional<Extents>&& extents = computeMaximumExtents(accessID);
if(extents.is_initialized()) {
auto interv = getInterval();
return boost::make_optional<Interval>(std::move(interv))->extendInterval(*extents);
}
return interval;
}
const std::shared_ptr<DependencyGraphAccesses>& DoMethod::getDependencyGraph() const {
return dependencyGraph_;
}
} // namespace dawn
<file_sep>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/CodeGen/GridTools/GTCodeGen.h"
#include "dawn/CodeGen/CXXUtil.h"
#include "dawn/CodeGen/GridTools/ASTStencilBody.h"
#include "dawn/CodeGen/GridTools/ASTStencilDesc.h"
#include "dawn/Optimizer/OptimizerContext.h"
#include "dawn/Optimizer/StatementAccessesPair.h"
#include "dawn/Optimizer/StencilFunctionInstantiation.h"
#include "dawn/Optimizer/StencilInstantiation.h"
#include "dawn/SIR/SIR.h"
#include "dawn/Support/Assert.h"
#include "dawn/Support/Logging.h"
#include "dawn/Support/StringUtil.h"
#include <boost/optional.hpp>
#include <unordered_map>
namespace dawn {
namespace codegen {
namespace gt {
namespace {
class BCFinder : public ASTVisitorForwarding {
public:
using Base = ASTVisitorForwarding;
BCFinder() : BCsFound_(0) {}
void visit(const std::shared_ptr<BoundaryConditionDeclStmt>& stmt) {
BCsFound_++;
Base::visit(stmt);
}
void resetFinder() { BCsFound_ = 0; }
int reportBCsFound() { return BCsFound_; }
private:
int BCsFound_;
};
}
GTCodeGen::GTCodeGen(OptimizerContext* context) : CodeGen(context), mplContainerMaxSize_(20) {}
GTCodeGen::~GTCodeGen() {}
GTCodeGen::IntervalDefinitions::IntervalDefinitions(const Stencil& stencil)
: Intervals(stencil.getIntervals()), Axis(*Intervals.begin()) {
DAWN_ASSERT(!Intervals.empty());
// Add intervals for the stencil functions
for(const auto& stencilFun : stencil.getStencilInstantiation().getStencilFunctionInstantiations())
Intervals.insert(stencilFun->getInterval());
// Compute axis and populate the levels
// Notice we dont take into account caches in order to build the axis
Axis = *Intervals.begin();
for(const Interval& interval : Intervals) {
Levels.insert(interval.lowerLevel());
Levels.insert(interval.upperLevel());
Axis.merge(interval);
}
// inserting the intervals of the caches
for(const auto& mss : stencil.getMultiStages()) {
for(const auto& cachePair : mss->getCaches()) {
const boost::optional<Interval> interval = cachePair.second.getInterval();
if(interval.is_initialized())
Intervals.insert(*interval);
}
}
// Generate the name of the enclosing intervals of each multi-stage (required by the K-Caches)
for(const auto& interval : Intervals) {
IntervalToNameMap.emplace(interval, Interval::makeCodeGenName(interval));
}
// Compute the intervals required by each stage. Note that each stage needs to have Do-Methods
// for the entire axis, this means we may need to add empty Do-Methods
// See https://github.com/eth-cscs/gridtools/issues/330
int numStages = stencil.getNumStages();
for(int i = 0; i < numStages; ++i) {
const std::shared_ptr<Stage>& stagePtr = stencil.getStage(i);
auto iteratorSuccessPair = StageIntervals.emplace(
stagePtr, Interval::computeGapIntervals(Axis, stagePtr->getIntervals()));
DAWN_ASSERT(iteratorSuccessPair.second);
std::vector<Interval>& DoMethodIntervals = iteratorSuccessPair.first->second;
// Generate unique names for the intervals
for(const Interval& interval : DoMethodIntervals)
IntervalToNameMap.emplace(interval, Interval::makeCodeGenName(interval));
}
}
/// @brief The StencilFunctionAsBCGenerator class parses a stencil function that is used as a
/// boundary
/// condition into it's stringstream. In order to use stencil_functions as boundary conditions, we
/// need them to be members of the stencil-wrapper class. The goal is to template the function s.t
/// every field is a template argument.
class StencilFunctionAsBCGenerator : public ASTCodeGenCXX {
private:
std::shared_ptr<sir::StencilFunction> function;
const StencilInstantiation* instantiation_;
public:
using Base = ASTCodeGenCXX;
StencilFunctionAsBCGenerator(const StencilInstantiation* stencilInstantiation,
const std::shared_ptr<sir::StencilFunction>& functionToAnalyze)
: function(functionToAnalyze), instantiation_(stencilInstantiation) {}
void visit(const std::shared_ptr<FieldAccessExpr>& expr) {
auto printOffset = [](const Array3i& argumentoffsets) {
std::string retval = "";
std::array<std::string, 3> dims{"i", "j", "k"};
for(int i = 0; i < 3; ++i) {
retval +=
dims[i] + (argumentoffsets[i] != 0 ? " + " + std::to_string(argumentoffsets[i]) + ", "
: (i < 2 ? ", " : ""));
}
return retval;
};
expr->getName();
auto getArgumentIndex = [&](const std::string& name) {
size_t pos =
std::distance(function->Args.begin(),
std::find_if(function->Args.begin(), function->Args.end(),
[&](const std::shared_ptr<sir::StencilFunctionArg>& arg) {
return arg->Name == name;
}));
DAWN_ASSERT_MSG(pos < function->Args.size(), "");
return pos;
};
ss_ << dawn::format("data_field_%i(%s)", getArgumentIndex(expr->getName()),
printOffset(expr->getOffset()));
}
void visit(const std::shared_ptr<VerticalRegionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "VerticalRegionDeclStmt not allowed in this context");
}
void visit(const std::shared_ptr<StencilCallDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "StencilCallDeclStmt not allowed in this context");
}
void visit(const std::shared_ptr<BoundaryConditionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "BoundaryConditionDeclStmt not allowed in this context");
}
void visit(const std::shared_ptr<StencilFunCallExpr>& expr) {
DAWN_ASSERT_MSG(0, "StencilFunCallExpr not allowed in this context");
}
void visit(const std::shared_ptr<StencilFunArgExpr>& expr) {
DAWN_ASSERT_MSG(0, "StencilFunArgExpr not allowed in this context");
}
void visit(const std::shared_ptr<ReturnStmt>& stmt) {
DAWN_ASSERT_MSG(0, "ReturnStmt not allowed in this context");
}
void visit(const std::shared_ptr<VarAccessExpr>& expr) {
if(instantiation_->isGlobalVariable(instantiation_->getAccessIDFromExpr(expr)))
ss_ << "globals::get().";
ss_ << getName(expr);
if(expr->isArrayAccess()) {
ss_ << "[";
expr->getIndex()->accept(*this);
ss_ << "]";
}
}
std::string getName(const std::shared_ptr<Stmt>& stmt) const {
return instantiation_->getNameFromAccessID(instantiation_->getAccessIDFromStmt(stmt));
}
std::string getName(const std::shared_ptr<Expr>& expr) const {
return instantiation_->getNameFromAccessID(instantiation_->getAccessIDFromExpr(expr));
}
};
std::string
GTCodeGen::generateStencilInstantiation(const StencilInstantiation* stencilInstantiation) {
using namespace codegen;
std::stringstream ssSW, ssMS, tss;
Namespace gridtoolsNamespace("gridtools", ssSW);
// K-Cache branch changes the signature of Do-Methods
const char* DoMethodArg = "Evaluation& eval";
Class StencilWrapperClass(stencilInstantiation->getName(), ssSW);
StencilWrapperClass.changeAccessibility(
"public"); // The stencils should technically be private but nvcc doesn't like it ...
bool isEmpty = true;
// Functions for boundary conditions
for(auto usedBoundaryCondition : stencilInstantiation->getBoundaryConditions()) {
for(const auto& sf : stencilInstantiation->getSIR()->StencilFunctions) {
if(sf->Name == usedBoundaryCondition.second->getFunctor()) {
Structure BoundaryCondition = StencilWrapperClass.addStruct(Twine(sf->Name));
std::string templatefunctions = "typename Direction ";
std::string functionargs = "Direction ";
// A templated datafield for every function argument
for(int i = 0; i < usedBoundaryCondition.second->getFields().size(); i++) {
templatefunctions += dawn::format(",typename DataField_%i", i);
functionargs += dawn::format(", DataField_%i &data_field_%i", i, i);
}
functionargs += ", int i , int j, int k";
auto BC = BoundaryCondition.addMemberFunction(
Twine("GT_FUNCTION void"), Twine("operator()"), Twine(templatefunctions));
BC.isConst(true);
BC.addArg(functionargs);
BC.startBody();
StencilFunctionAsBCGenerator reader(stencilInstantiation, sf);
sf->Asts[0]->accept(reader);
std::string output = reader.getCodeAndResetStream();
BC << output;
BC.commit();
break;
}
}
}
// Generate stencils
auto& stencils = stencilInstantiation->getStencils();
for(std::size_t stencilIdx = 0; stencilIdx < stencils.size(); ++stencilIdx) {
const Stencil& stencil = *stencilInstantiation->getStencils()[stencilIdx];
if(stencil.isEmpty())
continue;
isEmpty = false;
Structure StencilClass = StencilWrapperClass.addStruct(Twine("stencil_") + Twine(stencilIdx));
std::string StencilName = StencilClass.getName();
//
// Interval typedefs
//
StencilClass.addComment("Intervals");
IntervalDefinitions intervalDefinitions(stencil);
std::size_t maxLevel = intervalDefinitions.Levels.size() - 1;
auto makeLevelName = [&](int level, int offset) {
clear(tss);
int gt_level =
(level == sir::Interval::End ? maxLevel
: std::distance(intervalDefinitions.Levels.begin(),
intervalDefinitions.Levels.find(level)));
int gt_offset =
(level != sir::Interval::End) ? offset + 1 : (offset <= 0) ? offset - 1 : offset;
tss << "gridtools::level<" << gt_level << ", " << gt_offset << ">";
return tss.str();
};
// Generate typedefs for the individual intervals
for(const auto& intervalNamePair : intervalDefinitions.IntervalToNameMap)
StencilClass.addTypeDef(intervalNamePair.second)
.addType(c_gt() + "interval")
.addTemplates(makeArrayRef({makeLevelName(intervalNamePair.first.lowerLevel(),
intervalNamePair.first.lowerOffset()),
makeLevelName(intervalNamePair.first.upperLevel(),
intervalNamePair.first.upperOffset())}));
ASTStencilBody stencilBodyCGVisitor(stencilInstantiation,
intervalDefinitions.IntervalToNameMap);
// Generate typedef for the axis
const Interval& axis = intervalDefinitions.Axis;
StencilClass.addTypeDef(Twine("axis_") + StencilName)
.addType(c_gt() + "interval")
.addTemplates(makeArrayRef(
{makeLevelName(axis.lowerLevel(), axis.lowerOffset() - 2),
makeLevelName(axis.upperLevel(),
(axis.upperOffset() + 1) == 0 ? 1 : (axis.upperOffset() + 1))}));
// Generate typedef of the grid
StencilClass.addTypeDef(Twine("grid_") + StencilName)
.addType(c_gt() + "grid")
.addTemplate(Twine("axis_") + StencilName);
// Generate code for members of the stencil
StencilClass.addComment("Members");
StencilClass.addMember("std::shared_ptr< gridtools::stencil<gridtools::notype> >", "m_stencil");
//
// Generate stencil functions code for stencils instantiated by this stencil
//
std::unordered_set<std::string> generatedStencilFun;
for(const auto& stencilFun : stencilInstantiation->getStencilFunctionInstantiations()) {
std::string stencilFunName = StencilFunctionInstantiation::makeCodeGenName(*stencilFun);
if(generatedStencilFun.emplace(stencilFunName).second) {
Structure StencilFunStruct = StencilClass.addStruct(stencilFunName);
// Field declaration
const auto& fields = stencilFun->getCalleeFields();
std::vector<std::string> arglist;
if(fields.empty() && !stencilFun->hasReturn()) {
DiagnosticsBuilder diag(DiagnosticsKind::Error, stencilFun->getStencilFunction()->Loc);
diag << "no storages referenced in stencil function '" << stencilFun->getName()
<< "', this would result in invalid gridtools code";
context_->getDiagnostics().report(diag);
return "";
}
// If we have a return argument, we generate a special `__out` field
int accessorID = 0;
if(stencilFun->hasReturn()) {
StencilFunStruct.addStatement("using __out = gridtools::accessor<0, "
"gridtools::enumtype::inout, gridtools::extent<0, 0, 0, 0, "
"0, 0>>");
arglist.push_back("__out");
accessorID++;
}
// Generate field declarations
for(std::size_t m = 0; m < fields.size(); ++m, ++accessorID) {
std::string paramName =
stencilFun->getOriginalNameFromCallerAccessID(fields[m].getAccessID());
// Generate parameter of stage
codegen::Type extent(c_gt() + "extent", clear(tss));
for(auto& e : fields[m].getExtents().getExtents())
extent.addTemplate(Twine(e.Minus) + ", " + Twine(e.Plus));
StencilFunStruct.addTypeDef(paramName)
.addType(c_gt() + "accessor")
.addTemplate(Twine(accessorID))
.addTemplate(c_gt_enum() +
((fields[m].getIntend() == Field::IK_Input) ? "in" : "inout"))
.addTemplate(extent);
arglist.push_back(std::move(paramName));
}
// Global accessor declaration
for(auto accessID : stencilFun->getAccessIDSetGlobalVariables()) {
std::string paramName = stencilFun->getNameFromAccessID(accessID);
StencilFunStruct.addTypeDef(paramName)
.addType(c_gt() + "global_accessor")
.addTemplate(Twine(accessorID));
accessorID++;
arglist.push_back(std::move(paramName));
}
// Generate arglist
StencilFunStruct.addTypeDef("arg_list").addType("boost::mpl::vector").addTemplates(arglist);
mplContainerMaxSize_ = std::max(mplContainerMaxSize_, arglist.size());
// Generate Do-Method
auto DoMethod = StencilFunStruct.addMemberFunction("GT_FUNCTION static void", "Do",
"typename Evaluation");
auto interveralIt = intervalDefinitions.IntervalToNameMap.find(stencilFun->getInterval());
DAWN_ASSERT_MSG(intervalDefinitions.IntervalToNameMap.end() != interveralIt,
"non-existing interval");
DoMethod.addArg(DoMethodArg);
DoMethod.addArg(interveralIt->second);
DoMethod.startBody();
stencilBodyCGVisitor.setCurrentStencilFunction(stencilFun);
stencilBodyCGVisitor.setIndent(DoMethod.getIndent());
for(const auto& statementAccessesPair : stencilFun->getStatementAccessesPairs()) {
statementAccessesPair->getStatement()->ASTStmt->accept(stencilBodyCGVisitor);
DoMethod.indentStatment();
DoMethod << stencilBodyCGVisitor.getCodeAndResetStream();
}
DoMethod.commit();
}
}
// Done generating stencil functions ...
stencilBodyCGVisitor.setCurrentStencilFunction(nullptr);
std::vector<std::string> makeComputation;
//
// Generate code for stages and assemble the `make_computation`
//
std::size_t multiStageIdx = 0;
for(auto multiStageIt = stencil.getMultiStages().begin(),
multiStageEnd = stencil.getMultiStages().end();
multiStageIt != multiStageEnd; ++multiStageIt, ++multiStageIdx) {
const MultiStage& multiStage = **multiStageIt;
// Generate `make_multistage`
ssMS << "gridtools::make_multistage(gridtools::enumtype::execute<gridtools::enumtype::";
if(!context_->getOptions().UseParallelEP &&
multiStage.getLoopOrder() == LoopOrderKind::LK_Parallel)
ssMS << LoopOrderKind::LK_Forward << " /*parallel*/ ";
else
ssMS << multiStage.getLoopOrder();
ssMS << ">(),";
// Add the MultiStage caches
if(!multiStage.getCaches().empty()) {
ssMS << RangeToString(", ", "gridtools::define_caches(", "),")(
multiStage.getCaches(),
[&](const std::pair<int, Cache>& AccessIDCachePair) -> std::string {
auto const& cache = AccessIDCachePair.second;
DAWN_ASSERT(cache.getInterval().is_initialized() ||
cache.getCacheIOPolicy() == Cache::local);
if(cache.getInterval().is_initialized())
DAWN_ASSERT(intervalDefinitions.IntervalToNameMap.count(*(cache.getInterval())));
return (c_gt() + "cache<" +
// Type: IJ or K
c_gt() + cache.getCacheTypeAsString() + ", " +
// IOPolicy: local, fill, bpfill, flush, epflush or flush_and_fill
c_gt() + "cache_io_policy::" + cache.getCacheIOPolicyAsString() +
// Interval: if IOPolicy is not local, we need to provide the interval
(cache.getCacheIOPolicy() != Cache::local
? ", " + intervalDefinitions.IntervalToNameMap[*(cache.getInterval())]
: std::string()) +
// Placeholder which will be cached
">(p_" + stencilInstantiation->getNameFromAccessID(AccessIDCachePair.first) +
"())")
.str();
});
}
std::size_t stageIdx = 0;
for(auto stageIt = multiStage.getStages().begin(), stageEnd = multiStage.getStages().end();
stageIt != stageEnd; ++stageIt, ++stageIdx) {
const auto& stagePtr = *stageIt;
const Stage& stage = *stagePtr;
Structure StageStruct =
StencilClass.addStruct(Twine("stage_") + Twine(multiStageIdx) + "_" + Twine(stageIdx));
ssMS << "gridtools::make_stage_with_extent<" << StageStruct.getName() << ", extent< ";
auto extents = stage.getExtents().getExtents();
ssMS << extents[0].Minus << ", " << extents[0].Plus << ", " << extents[1].Minus << ", "
<< extents[1].Plus << "> >(";
// Field declaration
const auto& fields = stage.getFields();
std::vector<std::string> arglist;
if(fields.empty()) {
DiagnosticsBuilder diag(DiagnosticsKind::Error,
stencilInstantiation->getSIRStencil()->Loc);
diag << "no storages referenced in stencil '" << stencilInstantiation->getName()
<< "', this would result in invalid gridtools code";
context_->getDiagnostics().report(diag);
return "";
}
std::size_t accessorIdx = 0;
for(; accessorIdx < fields.size(); ++accessorIdx) {
const auto& field = fields[accessorIdx];
std::string paramName = stencilInstantiation->getNameFromAccessID(field.getAccessID());
// Generate parameter of stage
codegen::Type extent(c_gt() + "extent", clear(tss));
for(auto& e : field.getExtents().getExtents())
extent.addTemplate(Twine(e.Minus) + ", " + Twine(e.Plus));
StageStruct.addTypeDef(paramName)
.addType(c_gt() + "accessor")
.addTemplate(Twine(accessorIdx))
.addTemplate(c_gt_enum() + ((field.getIntend() == Field::IK_Input) ? "in" : "inout"))
.addTemplate(extent);
// Generate placeholder mapping of the field in `make_stage`
ssMS << "p_" << paramName << "()"
<< ((!stage.hasGlobalVariables() && (accessorIdx == fields.size() - 1)) ? "" : ", ");
arglist.push_back(std::move(paramName));
}
// Global accessor declaration
std::size_t maxAccessors = fields.size() + stage.getAllGlobalVariables().size();
for(int AccessID : stage.getAllGlobalVariables()) {
std::string paramName = stencilInstantiation->getNameFromAccessID(AccessID);
StageStruct.addTypeDef(paramName)
.addType(c_gt() + "global_accessor")
.addTemplate(Twine(accessorIdx));
accessorIdx++;
// Generate placeholder mapping of the field in `make_stage`
ssMS << "p_" << paramName << "()" << (accessorIdx == maxAccessors ? "" : ", ");
arglist.push_back(std::move(paramName));
}
ssMS << ")" << ((stageIdx != multiStage.getStages().size() - 1) ? "," : ")");
// Generate arglist
StageStruct.addTypeDef("arg_list").addType("boost::mpl::vector").addTemplates(arglist);
mplContainerMaxSize_ = std::max(mplContainerMaxSize_, arglist.size());
// Generate Do-Method
for(const auto& doMethodPtr : stage.getDoMethods()) {
const DoMethod& doMethod = *doMethodPtr;
auto DoMethodCodeGen =
StageStruct.addMemberFunction("GT_FUNCTION static void", "Do", "typename Evaluation");
DoMethodCodeGen.addArg(DoMethodArg);
DoMethodCodeGen.addArg(intervalDefinitions.IntervalToNameMap[doMethod.getInterval()]);
DoMethodCodeGen.startBody();
stencilBodyCGVisitor.setIndent(DoMethodCodeGen.getIndent());
for(const auto& statementAccessesPair : doMethod.getStatementAccessesPairs()) {
statementAccessesPair->getStatement()->ASTStmt->accept(stencilBodyCGVisitor);
DoMethodCodeGen << stencilBodyCGVisitor.getCodeAndResetStream();
}
}
// Generate empty Do-Methods
// See https://github.com/eth-cscs/gridtools/issues/330
const auto& stageIntervals = stage.getIntervals();
for(const auto& interval : intervalDefinitions.StageIntervals[stagePtr])
if(std::find(stageIntervals.begin(), stageIntervals.end(), interval) ==
stageIntervals.end())
StageStruct.addMemberFunction("GT_FUNCTION static void", "Do", "typename Evaluation")
.addArg(DoMethodArg)
.addArg(intervalDefinitions.IntervalToNameMap[interval]);
}
makeComputation.push_back(ssMS.str());
clear(ssMS);
}
//
// Generate constructor/destructor and methods of the stencil
//
std::vector<Stencil::FieldInfo> StencilFields = stencil.getFields();
std::vector<std::string> StencilGlobalVariables = stencil.getGlobalVariables();
std::size_t numFields = StencilFields.size();
mplContainerMaxSize_ = std::max(mplContainerMaxSize_, numFields);
std::vector<std::string> StencilConstructorTemplates;
int numTemporaries = 0;
for(int i = 0; i < numFields; ++i)
if(StencilFields[i].IsTemporary)
numTemporaries += 1;
else
StencilConstructorTemplates.push_back("S" + std::to_string(i + 1 - numTemporaries));
// Generate constructor
auto StencilConstructor = StencilClass.addConstructor(RangeToString(", ", "", "")(
StencilConstructorTemplates, [](const std::string& str) { return "class " + str; }));
StencilConstructor.addArg("const gridtools::clang::domain& dom");
for(int i = 0; i < numFields; ++i)
if(!StencilFields[i].IsTemporary)
StencilConstructor.addArg(StencilConstructorTemplates[i - numTemporaries] + " " +
StencilFields[i].Name);
StencilConstructor.startBody();
// Add static asserts to check halos against extents
StencilConstructor.addComment("Check if extents do not exceed the halos");
std::unordered_map<int, Extents> const& exts =
(*stencilInstantiation->getStencils()[stencilIdx]).computeEnclosingAccessExtents();
for(int i = 0; i < numFields; ++i) {
if(!StencilFields[i].IsTemporary) {
auto const& ext = exts.at(StencilFields[i].AccessID);
for(int dim = 0; dim < ext.getSize(); ++dim) {
std::string at_call = "template at<" + std::to_string(dim) + ">()";
std::string storage = StencilConstructorTemplates[i - numTemporaries];
// assert for + accesses
StencilConstructor.addStatement("static_assert((static_cast<int>(" + storage +
"::storage_info_t::halo_t::" + at_call + ") >= " +
std::to_string(ext[dim].Plus) + ") || " + "(" + storage +
"::storage_info_t::layout_t::" + at_call + " == -1)," +
"\"Used extents exceed halo limits.\")");
// assert for - accesses
StencilConstructor.addStatement("static_assert(((-1)*static_cast<int>(" + storage +
"::storage_info_t::halo_t::" + at_call + ") <= " +
std::to_string(ext[dim].Minus) + ") || " + "(" + storage +
"::storage_info_t::layout_t::" + at_call + " == -1)," +
"\"Used extents exceed halo limits.\")");
}
}
}
// Generate domain
StencilConstructor.addComment("Domain");
int accessorIdx = 0;
for(; accessorIdx < numFields; ++accessorIdx)
// Fields
StencilConstructor.addTypeDef("p_" + StencilFields[accessorIdx].Name)
.addType(c_gt() + (StencilFields[accessorIdx].IsTemporary ? "tmp_arg" : "arg"))
.addTemplate(Twine(accessorIdx))
.addTemplate(StencilFields[accessorIdx].IsTemporary
? "storage_t"
: StencilConstructorTemplates[accessorIdx - numTemporaries]);
for(; accessorIdx < (numFields + StencilGlobalVariables.size()); ++accessorIdx) {
// Global variables
const auto& varname = StencilGlobalVariables[accessorIdx - numFields];
StencilConstructor.addTypeDef("p_" + StencilGlobalVariables[accessorIdx - numFields])
.addType(c_gt() + "arg")
.addTemplate(Twine(accessorIdx))
.addTemplate("typename std::decay<decltype(globals::get()." + varname +
".as_global_parameter())>::type");
}
std::vector<std::string> ArglistPlaceholders;
for(const auto& field : StencilFields)
ArglistPlaceholders.push_back("p_" + field.Name);
for(const auto& var : StencilGlobalVariables)
ArglistPlaceholders.push_back("p_" + var);
StencilConstructor.addTypeDef("domain_arg_list")
.addType("boost::mpl::vector")
.addTemplates(ArglistPlaceholders);
// Placeholders to map the real storages to the placeholders (no temporaries)
std::vector<std::string> DomainMapPlaceholders;
std::transform(StencilFields.begin() + numTemporaries, StencilFields.end(),
std::back_inserter(DomainMapPlaceholders), [](const Stencil::FieldInfo& field) {
return "(p_" + field.Name + "() = " + field.Name + ")";
});
for(const auto& var : StencilGlobalVariables)
DomainMapPlaceholders.push_back("(p_" + var + "() = globals::get()." + var +
".as_global_parameter())");
// This is a memory leak.. but nothing we can do ;)
StencilConstructor.addStatement(c_gt() + "aggregator_type<domain_arg_list> gt_domain{" +
RangeToString(", ", "", "}")(DomainMapPlaceholders));
// Generate grid
StencilConstructor.addComment("Grid");
StencilConstructor.addStatement("gridtools::halo_descriptor di = {dom.iminus(), dom.iminus(), "
"dom.iplus(), dom.isize() - 1 - dom.iplus(), dom.isize()}");
StencilConstructor.addStatement("gridtools::halo_descriptor dj = {dom.jminus(), dom.jminus(), "
"dom.jplus(), dom.jsize() - 1 - dom.jplus(), dom.jsize()}");
auto getLevelSize = [](int level) -> std::string {
switch(level) {
case sir::Interval::Start:
return "dom.kminus()";
case sir::Interval::End:
return "dom.ksize() == 0 ? 0 : dom.ksize() - dom.kplus()";
default:
return std::to_string(level);
}
};
StencilConstructor.addStatement("auto grid_ = grid_stencil_" + std::to_string(stencilIdx) +
"(di, dj)");
int levelIdx = 0;
// notice we skip the first level since it is kstart and not included in the GT grid definition
for(auto it = intervalDefinitions.Levels.begin(), end = intervalDefinitions.Levels.end();
it != end; ++it, ++levelIdx)
StencilConstructor.addStatement("grid_.value_list[" + std::to_string(levelIdx) + "] = " +
getLevelSize(*it));
// Generate make_computation
StencilConstructor.addComment("Computation");
StencilConstructor.addStatement(
Twine("m_stencil = gridtools::make_computation<gridtools::clang::backend_t>(gt_domain, "
"grid_") +
RangeToString(", ", ", ", ")")(makeComputation));
StencilConstructor.commit();
// Generate destructor
auto dtor = StencilClass.addDestructor();
dtor.addStatement("m_stencil->finalize()");
dtor.commit();
// Generate stencil getter
StencilClass.addMemberFunction("gridtools::stencil<gridtools::notype>*", "get_stencil")
.addStatement("return m_stencil.get()");
}
if(isEmpty) {
DiagnosticsBuilder diag(DiagnosticsKind::Error, stencilInstantiation->getSIRStencil()->Loc);
diag << "empty stencil '" << stencilInstantiation->getName()
<< "', this would result in invalid gridtools code";
context_->getDiagnostics().report(diag);
return "";
}
//
// Generate constructor/destructor and methods of the stencil wrapper
//
StencilWrapperClass.addComment("Members");
StencilWrapperClass.addComment("Fields that require Boundary Conditions");
// add all fields that require a boundary condition as members since they need to be called from
// this class and not from individual stencils
std::unordered_set<std::string> memberfields;
for(auto usedBoundaryCondition : stencilInstantiation->getBoundaryConditions()) {
for(const auto& field : usedBoundaryCondition.second->getFields()) {
memberfields.emplace(field->Name);
}
}
for(const auto& field : memberfields) {
StencilWrapperClass.addMember(Twine("storage_t"), Twine(field));
}
StencilWrapperClass.addComment("Stencil-Data");
// Define allocated memebers if necessary
if(stencilInstantiation->hasAllocatedFields()) {
StencilWrapperClass.addMember(c_gtc() + "meta_data_t", "m_meta_data");
for(int AccessID : stencilInstantiation->getAllocatedFieldAccessIDs())
StencilWrapperClass.addMember(c_gtc() + "storage_t",
"m_" + stencilInstantiation->getNameFromAccessID(AccessID));
}
// Stencil members
std::vector<std::string> stencilMembers;
for(std::size_t i = 0; i < stencils.size(); ++i) {
StencilWrapperClass.addMember("stencil_" + Twine(i), "m_stencil_" + Twine(i));
stencilMembers.emplace_back("m_stencil_" + std::to_string(i));
}
StencilWrapperClass.addMember("static constexpr const char* s_name =",
Twine("\"") + StencilWrapperClass.getName() + Twine("\""));
StencilWrapperClass.changeAccessibility("public");
StencilWrapperClass.addCopyConstructor(Class::Deleted);
// Generate stencil wrapper constructor
auto SIRFieldsWithoutTemps = stencilInstantiation->getSIRStencil()->Fields;
for(auto it = SIRFieldsWithoutTemps.begin(); it != SIRFieldsWithoutTemps.end();)
if((*it)->IsTemporary)
it = SIRFieldsWithoutTemps.erase(it);
else
++it;
std::vector<std::string> StencilWrapperConstructorTemplates;
for(int i = 0; i < SIRFieldsWithoutTemps.size(); ++i)
StencilWrapperConstructorTemplates.push_back("S" + std::to_string(i + 1));
auto StencilWrapperConstructor = StencilWrapperClass.addConstructor(RangeToString(", ", "", "")(
StencilWrapperConstructorTemplates, [](const std::string& str) { return "class " + str; }));
StencilWrapperConstructor.addArg("const " + c_gtc() + "domain& dom");
for(int i = 0; i < SIRFieldsWithoutTemps.size(); ++i)
StencilWrapperConstructor.addArg(StencilWrapperConstructorTemplates[i] + " " +
SIRFieldsWithoutTemps[i]->Name);
// Initialize allocated fields
if(stencilInstantiation->hasAllocatedFields()) {
std::vector<std::string> tempFields;
for(auto accessID : stencilInstantiation->getAllocatedFieldAccessIDs()) {
tempFields.push_back(stencilInstantiation->getNameFromAccessID(accessID));
}
addTmpStorageInit_wrapper(StencilWrapperConstructor, stencils, tempFields);
}
// Initialize storages that require boundary conditions
for(const auto& memberfield : memberfields) {
StencilWrapperConstructor.addInit(memberfield + "(" + memberfield + ")");
}
// Initialize stencils
for(std::size_t i = 0; i < stencils.size(); ++i)
StencilWrapperConstructor.addInit(
"m_stencil_" + Twine(i) +
RangeToString(", ", "(dom, ",
")")(stencils[i]->getFields(false), [&](const Stencil::FieldInfo& field) {
if(stencilInstantiation->isAllocatedField(field.AccessID))
return "m_" + field.Name;
else
return field.Name;
}));
for(int i = 0; i < SIRFieldsWithoutTemps.size(); ++i)
StencilWrapperConstructor.addStatement(
"static_assert(gridtools::is_data_store<" + StencilWrapperConstructorTemplates[i] +
">::value, \"argument '" + SIRFieldsWithoutTemps[i]->Name +
"' is not a 'gridtools::data_store' (" + decimalToOrdinal(i + 2) + " argument invalid)\")");
StencilWrapperConstructor.commit();
// Generate make_steady method
MemberFunction MakeSteadyMethod = StencilWrapperClass.addMemberFunction("void", "make_steady");
for(std::size_t i = 0; i < stencils.size(); ++i) {
MakeSteadyMethod.addStatement(Twine(stencilMembers[i]) + ".get_stencil()->ready()");
MakeSteadyMethod.addStatement(Twine(stencilMembers[i]) + ".get_stencil()->steady()");
}
MakeSteadyMethod.commit();
// Generate the run method by generate code for the stencil description AST
MemberFunction RunMethod = StencilWrapperClass.addMemberFunction("void", "run");
RunMethod.addArg("bool make_steady = true");
RunMethod.addStatement("if(make_steady) this->make_steady()");
// Create the StencilID -> stencil name map
std::unordered_map<int, std::vector<std::string>> stencilIDToStencilNameMap;
for(std::size_t i = 0; i < stencils.size(); ++i)
stencilIDToStencilNameMap[stencils[i]->getStencilID()].emplace_back(stencilMembers[i]);
ASTStencilDesc stencilDescCGVisitor(stencilInstantiation, stencilIDToStencilNameMap);
stencilDescCGVisitor.setIndent(RunMethod.getIndent());
for(const auto& statement : stencilInstantiation->getStencilDescStatements()) {
statement->ASTStmt->accept(stencilDescCGVisitor);
RunMethod << stencilDescCGVisitor.getCodeAndResetStream();
}
RunMethod.commit();
// Generate stencil getter
StencilWrapperClass
.addMemberFunction("std::vector<gridtools::stencil<gridtools::notype>*>", "get_stencils")
.addStatement(
"return " +
RangeToString(", ", "std::vector<gridtools::stencil<gridtools::notype>*>({", "})")(
stencilMembers, [](const std::string& member) { return member + ".get_stencil()"; }));
// Generate name getter
StencilWrapperClass.addMemberFunction("const char*", "get_name")
.isConst(true)
.addStatement("return s_name");
StencilWrapperClass.commit();
gridtoolsNamespace.commit();
// Remove trailing ';' as this is retained by Clang's Rewriter
std::string str = ssSW.str();
str[str.size() - 2] = ' ';
return str;
}
std::string GTCodeGen::generateGlobals(std::shared_ptr<SIR> const& Sir) {
using namespace codegen;
const auto& globalsMap = *(Sir->GlobalVariableMap);
if(globalsMap.empty())
return "";
std::stringstream ss;
Namespace gridtoolsNamespace("gridtools", ss);
std::string StructName = "globals";
std::string BaseName = "gridtools::clang::globals_impl<" + StructName + ">";
Struct GlobalsStruct(StructName + ": public " + BaseName, ss);
GlobalsStruct.addTypeDef("base_t").addType("gridtools::clang::globals_impl<globals>");
for(const auto& globalsPair : globalsMap) {
sir::Value& value = *globalsPair.second;
std::string Name = globalsPair.first;
std::string Type = sir::Value::typeToString(value.getType());
std::string AdapterBase = std::string("base_t::variable_adapter_impl") + "<" + Type + ">";
Structure AdapterStruct = GlobalsStruct.addStructMember(Name + "_adapter", Name, AdapterBase);
AdapterStruct.addConstructor().addArg("").addInit(
AdapterBase + "(" + Type + "(" + (value.empty() ? std::string() : value.toString()) + "))");
auto AssignmentOperator =
AdapterStruct.addMemberFunction(Name + "_adapter&", "operator=", "class ValueType");
AssignmentOperator.addArg("ValueType&& value");
if(value.isConstexpr())
AssignmentOperator.addStatement(
"throw std::runtime_error(\"invalid assignment to constant variable '" + Name + "'\")");
else
AssignmentOperator.addStatement("get_value() = value");
AssignmentOperator.addStatement("return *this");
AssignmentOperator.commit();
}
GlobalsStruct.commit();
// Add the symbol for the singleton
codegen::Statement(ss) << "template<> " << StructName << "* " << BaseName
<< "::s_instance = nullptr";
gridtoolsNamespace.commit();
// Remove trailing ';' as this is retained by Clang's Rewriter
std::string str = ss.str();
str[str.size() - 2] = ' ';
return str;
}
std::unique_ptr<TranslationUnit> GTCodeGen::generateCode() {
mplContainerMaxSize_ = 20;
DAWN_LOG(INFO) << "Starting code generation for GTClang ...";
// Generate StencilInstantiations
std::map<std::string, std::string> stencils;
for(const auto& nameStencilCtxPair : context_->getStencilInstantiationMap()) {
std::string code = generateStencilInstantiation(nameStencilCtxPair.second.get());
if(code.empty())
return nullptr;
stencils.emplace(nameStencilCtxPair.first, std::move(code));
}
// Generate globals
std::string globals = generateGlobals(context_->getSIR());
std::vector<std::string> ppDefines;
auto makeDefine = [](std::string define, int value) {
return "#define " + define + " " + std::to_string(value);
};
auto makeIfNotDefined = [](std::string define, int value) {
return "#ifndef " + define + "\n #define " + define + " " + std::to_string(value) + "\n#endif";
};
ppDefines.push_back(makeDefine("GRIDTOOLS_CLANG_GENERATED", 1));
ppDefines.push_back(makeIfNotDefined("BOOST_RESULT_OF_USE_TR1", 1));
ppDefines.push_back(makeIfNotDefined("BOOST_NO_CXX11_DECLTYPE", 1));
ppDefines.push_back(
makeIfNotDefined("GRIDTOOLS_CLANG_HALO_EXTEND", context_->getOptions().MaxHaloPoints));
// If we need more than 20 elements in boost::mpl containers, we need to increment to the nearest
// multiple of ten
// http://www.boost.org/doc/libs/1_61_0/libs/mpl/doc/refmanual/limit-vector-size.html
if(mplContainerMaxSize_ > 20) {
mplContainerMaxSize_ += (10 - mplContainerMaxSize_ % 10);
DAWN_LOG(INFO) << "increasing boost::mpl template limit to " << mplContainerMaxSize_;
ppDefines.push_back(makeIfNotDefined("BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS", 1));
}
DAWN_ASSERT_MSG(mplContainerMaxSize_ % 10 == 0,
"boost::mpl template limit needs to be multiple of 10");
ppDefines.push_back(makeIfNotDefined("FUSION_MAX_VECTOR_SIZE", mplContainerMaxSize_));
ppDefines.push_back(makeIfNotDefined("FUSION_MAX_MAP_SIZE", mplContainerMaxSize_));
ppDefines.push_back(makeIfNotDefined("BOOST_MPL_LIMIT_VECTOR_SIZE", mplContainerMaxSize_));
BCFinder finder;
for(const auto& stencilInstantiation : context_->getStencilInstantiationMap()) {
for(const auto& stmt : stencilInstantiation.second->getStencilDescStatements()) {
stmt->ASTStmt->accept(finder);
}
}
if(finder.reportBCsFound()) {
ppDefines.push_back("#ifdef __CUDACC__\n#include "
"<boundary-conditions/apply_gpu.hpp>\n#else\n#include "
"<boundary-conditions/apply.hpp>\n#endif\n");
}
DAWN_LOG(INFO) << "Done generating code";
return make_unique<TranslationUnit>(context_->getSIR()->Filename, std::move(ppDefines),
std::move(stencils), std::move(globals));
}
} // namespace gt
} // namespace codegen
} // namespace dawn
|
353a46475c631af9b0172340ae2cdcd4fb750395
|
[
"C++",
"Shell"
] | 5
|
C++
|
stefanmoosbrugger/dawn
|
5f0726a6165ecd603f0ef7c15ec571bf43c014e6
|
a64b5af36ea7ff715ed0a03b3f9cbed4b2c449ef
|
refs/heads/master
|
<repo_name>vizzybhagat/AppDevelopment<file_sep>/app/src/main/java/com/vizzy/bmicalculator/ThirdActivity.java
package com.vizzy.bmicalculator;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
public class ThirdActivity extends AppCompatActivity {
DatabaseHandler db;
SharedPreferences sp;
TextView tvData,tvData1,tvData2,tvData3,tvData4;
Button btnShare,btnSave,btnBack;
@SuppressLint("ResourceAsColor")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
db=new DatabaseHandler(this);
tvData=(TextView)findViewById(R.id.tvData);
tvData1=(TextView)findViewById(R.id.tvData1);
tvData2=(TextView)findViewById(R.id.tvData2);
tvData3=(TextView)findViewById(R.id.tvData3);
tvData4=(TextView)findViewById(R.id.tvData4);
btnShare=(Button)findViewById(R.id.btnShare);
btnBack=(Button)findViewById(R.id.btnBack);
btnSave=(Button)findViewById(R.id.btnSave);
sp=getSharedPreferences("myp1",MODE_PRIVATE);
String bmi =sp.getString("bmi","");
tvData.setText("Your bmi is "+bmi);
double bmivalue=Double.parseDouble(bmi);
if(bmivalue<18.5) {
tvData.setText("Your bmi is "+bmi+" and you are underweight");
SharedPreferences.Editor editor = sp.edit();
editor.putString("d","You are underweight");
editor.commit();
}
if(bmivalue>=18.5 && bmivalue<25) {
tvData.setText("Your bmi is "+bmi+" and you are normal");
SharedPreferences.Editor editor = sp.edit();
editor.putString("d","You are normal");
editor.commit();
}
if(bmivalue>=25 && bmivalue<30) {
tvData.setText("Your bmi is "+bmi+" and you are overweight");
SharedPreferences.Editor editor = sp.edit();
editor.putString("d","You are overweight");
editor.commit();
}
if(bmivalue>=30) {
tvData.setText("Your bmi is "+bmi+" and you are obese");
SharedPreferences.Editor editor = sp.edit();
editor.putString("d","You are obese");
editor.commit();
}
if(bmivalue<18.5) {
tvData1.setTextColor(Color.parseColor("#ff0000"));
tvData1.setText("below 18.5 is underweight");
}
else
{
tvData1.setText("below 18.5 is underweight");
}
if(bmivalue>=18.5 && bmivalue<25) {
tvData2.setTextColor(Color.parseColor("#ff0000"));
tvData2.setText("between 18.5 to 25 is Normal");
}
else
{
tvData2.setText("between 18.5 to 25 is Normal");
}
if(bmivalue>=25 && bmivalue<30) {
tvData3.setTextColor(Color.parseColor("#ff0000"));
tvData3.setText("between 25 to 30 is overweight");
}
else
{
tvData3.setText("between 25 to 30 is overweight");
}
if(bmivalue>30) {
tvData4.setTextColor(Color.parseColor("#ff0000"));
tvData4.setText("greater than 30 is obese");
}
else
{
tvData4.setText("greater than 30 is obese");
}
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
btnShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name="Name:"+sp.getString("n","");
String age="Age:"+sp.getString("a","");
String phone="Phone:"+sp.getString("p","");
String gender="Gender:"+sp.getString("g","");
String bmi="BMI:"+sp.getString("bmi","");
String msg=sp.getString("d","");
Intent i=new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:"+""));
i.putExtra(Intent.EXTRA_TEXT,name+"\n"+age+"\n"+phone+"\n"+gender+"\n"+bmi+"\n"+msg);
startActivity(i);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Date current=Calendar.getInstance().getTime();
SharedPreferences.Editor editor=sp.edit();
editor.putString("time",current.toString());
editor.commit();
db.add(sp.getString("time"," "),sp.getString("bmi"," "));
Intent i=new Intent(ThirdActivity.this,FourthActivity.class);
startActivity(i);
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
<file_sep>/app/src/main/java/com/vizzy/bmicalculator/SecondActivity.java
package com.vizzy.bmicalculator;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class SecondActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
TextView tvData,tvHeight,tvWeight,tvFeet,tvInch;
EditText etWeight;
Spinner spnFeet,spnInch;
Button btnCalculate,btnViewHistory;
SharedPreferences sp;
TextView tvLocation;
GoogleApiClient gac;
Location loc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tvData=(TextView)findViewById(R.id.tvData);
tvHeight=(TextView)findViewById(R.id.tvHeight);
tvWeight=(TextView)findViewById(R.id.tvWeight);
tvFeet=(TextView)findViewById(R.id.tvFeet);
tvInch=(TextView)findViewById(R.id.tvInch);
tvLocation=(TextView)findViewById(R.id.tvLocation);
etWeight=(EditText)findViewById(R.id.etWeight);
spnFeet=(Spinner)findViewById(R.id.spnFeet);
spnInch=(Spinner)findViewById(R.id.spnInch);
btnCalculate=(Button)findViewById(R.id.btnCalculate);
btnViewHistory=(Button)findViewById(R.id.btnViewHistory);
sp=getSharedPreferences("myp1",MODE_PRIVATE);
final String feet[]={"1","2","3","4","5","6"};
final String inch[]={"0","1","2","3","4","5","6","7","8","9","10","11"};
ArrayAdapter feetAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,feet);
ArrayAdapter inchAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,inch);
spnFeet.setAdapter(feetAdapter);
spnInch.setAdapter(inchAdapter);
Intent i=getIntent();
String msg=sp.getString("n","");
tvData.setText(" Welcome "+msg);
GoogleApiClient.Builder builder=new GoogleApiClient.Builder(this);
builder.addOnConnectionFailedListener(this);
builder.addConnectionCallbacks(this);
builder.addApi(LocationServices.API);
gac=builder.build();
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String weight=etWeight.getText().toString();
if(weight.length()==0)
{
etWeight.setError("Weight is empty");
etWeight.requestFocus();
return;
}
int in=spnFeet.getSelectedItemPosition();
double f=Double.parseDouble(feet[in]);
int a=spnInch.getSelectedItemPosition();
double inc=Double.parseDouble(inch[a]);
final double meter=((f*12)+inc)*0.0254;
double wt=Double.parseDouble(weight);
double bmi=(wt/(meter*meter));
String bmivalue=String.format("%4.2f",bmi);
SharedPreferences.Editor editor = sp.edit();
editor.putString("bmi",bmivalue);
editor.commit();
Intent i=new Intent(SecondActivity.this,ThirdActivity.class);
startActivity(i);
}
});
btnViewHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(SecondActivity.this,FourthActivity.class);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m1,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.Website)
{
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+"www.myfitnesspal.com"));
startActivity(i);
}
if(item.getItemId()==R.id.About)
{
Toast.makeText(this, "Developed by Vizzy", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage("Do you want to close this application?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
dialog.cancel();
}
});
builder.setNeutralButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.setTitle("exit");
alert.show();
}
@Override
protected void onStart() {
super.onStart();
if(gac!=null)
gac.connect();
}
@Override
protected void onStop() {
super.onStop();
if(gac!=null)
{
gac.disconnect();
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
loc=LocationServices.FusedLocationApi.getLastLocation(gac);
if(loc!=null)
{
Geocoder g=new Geocoder(SecondActivity.this, Locale.ENGLISH);
try {
List<Address> a=g.getFromLocation(loc.getLatitude(),loc.getLongitude(),1);
Address add=a.get(0);
String msg=add.getCountryName()+" "+add.getPostalCode()+" "+add.getLocality()+" "+
add.getSubLocality()+" "+add.getThoroughfare()+" "+add.getSubThoroughfare()+" "+
add.getAdminArea()+" "+add.getSubAdminArea();
tvLocation.setText("You are at "+msg);
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(this, "check gps", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "Connection Suspended", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
}
<file_sep>/app/src/main/java/com/vizzy/bmicalculator/WelcomeActivity.java
package com.vizzy.bmicalculator;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {
TextView tvAppName;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
tvAppName=(TextView)findViewById(R.id.tvAppName);
image=(ImageView)findViewById(R.id.image);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
}).start();
}
}
|
f4c840104101e929cc7af84e50159222846808af
|
[
"Java"
] | 3
|
Java
|
vizzybhagat/AppDevelopment
|
187f6d029eff25fa912aba816957ab0322b8d4ba
|
cdf5c84eade1a2b5dec39feff2ab0c9057e29183
|
refs/heads/master
|
<repo_name>gaissa/modular-angular<file_sep>/src/components/author/component.js
define([], function () {
'use strict';
angular.module('author', [])
.directive('author', function () {
return {
scope: {
author: '='
},
template: require('./template.html'),
controller: function () {
require('./style.less');
}
};
});
});
<file_sep>/src/services/post-service.js
define([], function () {
'use strict';
var postsUrl = require('file!./../data/posts.json');
angular.module('postService', [])
.service('postService', ['$q', '$http', function ($q, $http) {
var posts = null;
this.getAll = function () {
if (posts) {
return $q(function(resolve) {
resolve(posts);
});
}
return $http.get(postsUrl).then(function (response) {
posts = response.data;
return posts;
});
};
this.getBySlug = function (slug) {
return this.getAll().then(function (posts) {
var matchingPosts = posts.filter(function (post) {
return post.slug === slug;
});
if (matchingPosts.length < 1) {
throw new Error('No matching post');
}
return matchingPosts[0];
});
};
}]);
});
<file_sep>/src/components/post-edit/component.js
define(['../../services/post-service', '../author/component'], function () {
'use strict';
angular.module('postEdit', ['ngRoute', 'postService', 'author'])
.directive('postEdit', function () {
return {
scope: {},
template: require('./template.html'),
controller: ['$scope', 'postService', '$routeParams', '$sce',
function($scope, postService, $routeParams, $sce) {
require('./style.less');
$scope.post = null;
postService.getBySlug($routeParams.slug).then(function(post) {
$scope.content = $sce.trustAsHtml('<p>' + post.content.replace('\n', '</p><p>') + '</p>');
$scope.post = post;
});
}
]
};
});
});
<file_sep>/src/components/mouseover-preview/component.js
define([], function () {
'use strict';
angular.module('mouseoverPreview', ['ngRoute', 'postService'])
.directive('mouseoverPreview', function () {
return {
scope: {},
transclude: true,
template: require('./template.html'),
controller: function() {
require('./style.less');
}
};
});
});
<file_sep>/src/app.js
define(
[
'./components/post-edit/component',
'./components/post-list/component'
],
function () {
'use strict';
angular
.module(
'app',
[
'ngRoute',
'postList',
'postEdit'
]
)
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {template: '<div post-list></div>'})
.when('/:slug', {template: '<div post-edit></div>'})
.otherwise({redirectTo: '/'});
//$locationProvider.html5Mode(true);
}
]);
angular.bootstrap(document, ['app']);
}
);
<file_sep>/src/components/post-list/component.js
define(['../../services/post-service', '../mouseover-preview/component', '../author/component'], function () {
'use strict';
angular.module('postList', ['postService', 'mouseoverPreview', 'author'])
.filter('reverseName', function() {
return function(value) {
var parts = value.split(' ');
parts.unshift(parts.pop());
return parts.join(' ');
};
})
.directive('postList', ['postService', function (postService) {
var getPostsForList = function () {
return postService.getAll()
.then(function(posts) {
return posts.map(function(post) {
var listPost = _.pick(post, 'slug', 'title');
listPost.author = _.pick(post.author, 'name', 'email', 'picture');
return listPost;
});
});
};
return {
scope: {},
template: require('./template.html'),
controller: ['$scope', function($scope) {
require('./style.less');
$scope.posts = [];
getPostsForList().then(function (posts) {
$scope.posts = posts;
});
$scope.refreshPosts = function() {
getPostsForList().then(function (posts) {
$scope.posts = posts;
});
};
$scope.touchPostProperty = function(prop) {
$scope.posts = $scope.posts.map(function(post) {
post[prop] += ' test';
return post;
})
};
}]
};
}]);
});
<file_sep>/README.md
Install requirements:
npm install -g grunt-cli bower
npm install
bower install
In one shell:
grunt dev
In another shell:
grunt http-server
Navigate to http://localhost:9999/
|
2d6d38c4d19306995aa3c6007014d943a1681d8a
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
gaissa/modular-angular
|
e0bbd822c94d5bf5a5293edb596a634000b9acab
|
24eef2ae53d9c930b10e8779eab0871d2148e1f0
|
refs/heads/master
|
<repo_name>balapitchuka/webdevelopment<file_sep>/css/css/basics/links_styling.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
a{
background-color:yellowgreen;
height: 10px;
width : 50px;
padding : 2px;
text-decoration: none;
}
a:link{
background-color: gold;
}
a:visited{
background-color: red;
text-decoration: line-through; /* not working */
}
a:hover{
background-color: white;
}
a:active{
background-color: grey;
}
nav #brand{
text-align : center;
float: right;
font-family: Georgia, 'Times New Roman', Times, serif;
font-size: 30px;
font-weight: 100;
}
nav{
padding : 20px;
height : 50px;
background-color: aqua;
}
</style>
<body>
<nav>
<a href="#1">link 1</a>
<a href="#2">link 2</a>
<a href="#3">link 3</a>
<a href="#4">link 4</a>
<a href="#5">link 5</a>
<a href="#">link 6</a>
<div id="brand">Navigation Bar</div>
</nav>
<main>
<section id="1">
<h2>Section 1</h2>
<p>A fantastic start for the West Indies with the early wickets of Rahul and Pujara
today before Agarwal and Kohli consolidated with a solid partnership, the former getting
to his third fifty. Rahane then joined Kohli before he was nicked off by Roach.
Kohli seemed to be coasting towards yet another hundred before he was squared up by a
Holder away-seamer. Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!</p>
</section>
<hr />
<section id="2">
<h2>Section 2</h2>
<p>Kohli seemed to be coasting towards yet another hundred before he was squared up by a
Holder away-seamer. Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!.Kohli seemed to be coasting towards yet another hundred before he was squared up by a
Holder away-seamer. Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!</p>
</section>
<hr />
<section id="3">
<h2>Section 3</h2>
<p>Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!</p>
</section>
<hr />
<section id="4">
<h2>Section 4</h2>
<p>overage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!</p>
</section>
<hr />
<section id="5">
<h2>Section 5</h2>
<p>and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!Vihari and Pant then played some fluent strokes to take the Indians
through to stumps. Holder was easily the pick of the bowlers, scalping three Indians,
featuring Cornwall and Roach picking up a wicket each. That's it from our team on Day 1.
We'll be back with continued coverage tomorrow. Ciao!</p>
</section>
</main>
</body>
</html><file_sep>/README.md
# webdevelopment
html, css and javascript bootcamps practice
<file_sep>/bootcamps/build_realworld_responsive_websites_with_html_and_css3/practice/README.md
### Course Udemy : Build Responsive real world websites with HTML5 and CSS3
#### Course Notes:
###### HTML:
1. HTML is a markup language not a programming language.
2. Markup language : Markup means to structure it in a specific format that distinguishes itself from normal text. In html these are tags.
3.
<file_sep>/css/css/README.md
# CSS
### References
1. [segregagated colors with name, hexcode, rgb](http://colours.neilorangepeel.com/)
2. [color schemes and color palettes](https://coolors.co/)
3. [placeholder text](https://meettheipsums.com/)
<file_sep>/javascript/es6/array_helper_methods.js
/* array helper methods */
// 1. forEach
let colors = ['red', 'blue', 'green', 'orange']
for(let index = 0; index<colors.length;index++)
{
console.log(colors[index]);
}
console.log("-------");
// passing iterator function to forEach method
colors.forEach(function(color){
console.log(color)
});
let primes = [2, 3, 5, 7, 11, 13]
let sum = 0;
function adder(num){
sum += num;
}
primes.forEach(adder)
console.log(`The sum of primes is ${sum}`);
//2.map
let nums = [1, 2, 3, 4, 5, 6];
let doubled = nums.map(function(num){
return num * 2;
})
console.log(`The doubled nums array is : ${doubled}`);
// 3. filter
//4.find
//5. every
//6. some
//7. reduce
|
4ecf8cfb628827ea18ae4bd3b8f2b2d7fbd35312
|
[
"Markdown",
"JavaScript",
"HTML"
] | 5
|
HTML
|
balapitchuka/webdevelopment
|
ee2f2a7729b06fd19637ee057987fd278628c4de
|
80a0c32939f6d78950a7516a7b36be38502517f3
|
refs/heads/master
|
<repo_name>joemicmc/Tests<file_sep>/CustomerTests/StandardIMS/Components/Posting.cs
using Framework;
using System;
namespace CustomerTests.Components
{
public class Posting : StandardIMS.Components.Posting
{
public Posting(Enable enable) : base(enable)
{
}
public override void CheckOutput()
{
base.CheckOutput();
Console.WriteLine(">> Custom: Customer posting checks!");
}
}
}
<file_sep>/StandardIMSTests/TestManager_3_14.cs
using Framework;
using StandardIMS.Components;
namespace StandardIMSTests
{
public class TestManager_3_14 : TestManager
{
public TestManager_3_14() : base ()
{
enable = new Enable_3_14();
navigation = new Navigation(enable);
dataEntry = new DataEntry(enable);
authorisation = new Authorisation(enable, navigation);
posting = new Posting(enable);
}
}
}
<file_sep>/NewSolutionTests/Tests/EndToEnd.cs
namespace NewSolutionTests.Tests
{
class EndToEnd
{
}
}
<file_sep>/Framework/Enable_3_14.cs
using System;
namespace Framework
{
public class Enable_3_14 : Enable_3_12
{
public override void Login()
{
Console.WriteLine(">> Enable 3.14: Brand new login activity overides base method");
}
}
}
<file_sep>/Framework/Enable.cs
using System;
namespace Framework
{
public class Enable
{
public virtual void Login()
{
Console.WriteLine(">> Enable: The user has logged in");
}
public virtual void SelectDocument()
{
Console.WriteLine(">> Enable: The user has selected a document");
}
public virtual void IndexField(string field)
{
Console.WriteLine(string.Format(">> Enable: The user indexed field '{0}'", field));
}
public virtual void SelectButton(string button)
{
Console.WriteLine(string.Format(">> Enable: The user selected button '{0}'", button));
}
public virtual void RunSystemMonitor()
{
Console.WriteLine(">> Enable: The user runs system monitor");
}
public virtual void CheckDocumentPosted()
{
Console.WriteLine(">> Enable: The document has been posted");
}
}
}
<file_sep>/NewSolutionTests/TestCases/EndToEnd.cs
namespace NewSolutionTests.TestCases
{
class EndToEnd
{
}
}
<file_sep>/Framework/Enable_3_12.cs
using System;
namespace Framework
{
public class Enable_3_12 : Enable
{
public override void Login()
{
base.Login();
Console.WriteLine(">> Enable 3.12: Additional login activity calls base method");
}
}
}
<file_sep>/StandardIMS/Components/Navigation.cs
using Framework;
namespace StandardIMS.Components
{
public class Navigation
{
public Enable enable = new Enable();
public Navigation(Enable enable)
{
this.enable = enable;
}
public virtual void LoginAndSelectDocument()
{
enable.Login();
enable.SelectDocument();
}
}
}
<file_sep>/StandardIMSTests/TestCases/EndToEnd.cs
using NUnit.Framework;
using StandardIMS.Data;
using System.Collections.Generic;
namespace StandardIMSTests.TestCases
{
public class EndToEnd
{
public static IEnumerable<TestCaseData> NonPo
{
get
{
yield return new TestCaseData(Field.recipient);
}
}
}
}
<file_sep>/CustomerTests/StandardIMS/Tests/EndToEnd.cs
using NUnit.Framework;
using StandardIMSTests.Tests;
namespace CustomerTests.Tests
{
[TestFixture]
public class EndToEnd : StandardIMSTests.Tests.EndToEnd
{
TestManager testManager = new TestManager();
public EndToEnd() : base()
{
enable = testManager.enable;
navigation = testManager.navigation;
dataEntry = testManager.dataEntry;
authorisation = testManager.authorisation;
posting = testManager.posting;
}
}
}
<file_sep>/NewSolution/Data/Button.cs
namespace NewSolution.Data
{
public class Button
{
public static string createWorkflow = "Create Workflow";
}
}
<file_sep>/StandardIMSTests/TestManager.cs
using Framework;
using StandardIMS.Components;
namespace StandardIMSTests
{
public class TestManager
{
public Enable enable;
public Navigation navigation;
public DataEntry dataEntry;
public Authorisation authorisation;
public Posting posting;
public TestManager()
{
enable = new Enable();
navigation = new Navigation(enable);
dataEntry = new DataEntry(enable);
authorisation = new Authorisation(enable, navigation);
posting = new Posting(enable);
}
}
}
<file_sep>/StandardIMS/Components/Authorisation.cs
using Framework;
using StandardIMS.Data;
namespace StandardIMS.Components
{
public class Authorisation
{
public Enable enable;
public Navigation navigation;
public Authorisation(Enable enable, Navigation navigation)
{
this.enable = enable;
this.navigation = navigation;
}
public virtual void AuthoriseDocument()
{
navigation.LoginAndSelectDocument();
enable.SelectButton(Button.authorise);
}
}
}
<file_sep>/StandardIMS/Components/DataEntry.cs
using Framework;
using StandardIMS.Data;
namespace StandardIMS.Components
{
public class DataEntry
{
public Enable enable;
public DataEntry(Enable enable)
{
this.enable = enable;
}
public virtual void IndexDocument(string field)
{
enable.IndexField(field);
enable.SelectButton(Button.sendForAuthorisation);
}
}
}
<file_sep>/StandardIMSTests/Tests/EndToEnd_3_14.cs
using NUnit.Framework;
namespace StandardIMSTests.Tests
{
[TestFixture]
public class EndToEnd_3_14 : EndToEnd
{
TestManager testManager = new TestManager_3_14();
public EndToEnd_3_14() : base()
{
enable = testManager.enable;
navigation = testManager.navigation;
dataEntry = testManager.dataEntry;
authorisation = testManager.authorisation;
posting = testManager.posting;
}
}
}
<file_sep>/CustomerTests/TestManager.cs
using Framework;
using StandardIMS.Components;
using CustomerTests.Components;
namespace CustomerTests
{
public class TestManager : StandardIMSTests.TestManager
{
public TestManager()
{
enable = new Enable_3_14();
navigation = new StandardIMS.Components.Navigation(enable);
dataEntry = new StandardIMS.Components.DataEntry(enable);
authorisation = new StandardIMS.Components.Authorisation(enable, navigation);
posting = new CustomerTests.Components.Posting(enable);
}
}
}
<file_sep>/StandardIMSTests/Tests/EndToEnd.cs
using NUnit.Framework;
using Framework;
using StandardIMS.Components;
namespace StandardIMSTests.Tests
{
[TestFixture]
public class EndToEnd
{
TestManager testManager = new TestManager();
public Enable enable;
public Navigation navigation;
public DataEntry dataEntry;
public Authorisation authorisation;
public Posting posting;
public EndToEnd()
{
enable = testManager.enable;
navigation = testManager.navigation;
dataEntry = testManager.dataEntry;
authorisation = testManager.authorisation;
posting = testManager.posting;
}
[Test, TestCaseSource(typeof(TestCases.EndToEnd), "NonPo")]
public virtual void NonPo(string field)
{
navigation.LoginAndSelectDocument();
dataEntry.IndexDocument(field);
authorisation.AuthoriseDocument();
posting.CheckOutput();
}
}
}
<file_sep>/StandardIMS/Data/Button.cs
namespace StandardIMS.Data
{
public class Button
{
public static string sendForAuthorisation = "Send For Authorisation";
public static string authorise = "Authorise";
}
}
<file_sep>/StandardIMS/Components/Posting.cs
using Framework;
namespace StandardIMS.Components
{
public class Posting
{
public Enable enable;
public Posting(Enable enable)
{
this.enable = enable;
}
public virtual void CheckOutput()
{
enable.RunSystemMonitor();
enable.CheckDocumentPosted();
}
}
}
<file_sep>/NewSolution/Data/Field.cs
namespace NewSolution.Data
{
public class Field
{
public static string recipient = "Recipient";
}
}
|
c53c75c320caeeb495bf6546e1b8ebd5cea91d63
|
[
"C#"
] | 20
|
C#
|
joemicmc/Tests
|
55e09e62a9f1535b9ae040a9ff0a03645a17ebfd
|
4c3e34877f7663c751c79646950e825b91be28c3
|
refs/heads/master
|
<file_sep>cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"id": "cordova-plugin-morphus.morphusSDK",
"file": "plugins/cordova-plugin-morphus/www/morphusSDK.js",
"pluginId": "cordova-plugin-morphus",
"clobbers": [
"cordova.plugins.morphusSDK"
]
},
{
"id": "cordova-plugin-splashscreen.SplashScreen",
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"pluginId": "cordova-plugin-splashscreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"id": "at.modalog.cordova.plugin.cache.Cache",
"file": "plugins/at.modalog.cordova.plugin.cache/www/Cache.js",
"pluginId": "at.modalog.cordova.plugin.cache",
"clobbers": [
"cache"
]
},
{
"id": "cordova-plugin-android-permissions.Permissions",
"file": "plugins/cordova-plugin-android-permissions/www/permissions.js",
"pluginId": "cordova-plugin-android-permissions",
"clobbers": [
"cordova.plugins.permissions"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-whitelist": "1.2.2",
"cordova-plugin-crosswalk-webview": "1.8.0",
"cordova-plugin-morphus": "0.0.1",
"cordova-plugin-splashscreen": "4.0.0",
"at.modalog.cordova.plugin.cache": "1.1.0",
"cordova-plugin-android-permissions": "0.10.0"
};
// BOTTOM OF METADATA
});<file_sep>var changeURL = function(target) {
var iframe = document.getElementById('iframe');
iframe.src = target.value;
}
var toggle = function() {
var controls = document.getElementById('controls');
if (controls.style.display === 'none') {
controls.style.display = 'block';
} else {
controls.style.display = 'none';
}
};
<file_sep>var exec = require('cordova/exec');
navigator.echo = function(str) {
cordova.exec(
function(msg) {
alert(msg);
},
function(err) {
alert(err);
},
"morphusSDK",
"echo",
[str]);
};
navigator.is3DModeSupported = function() {
cordova.exec(
function(msg) {
console.log(msg);
var event = new Event('Support3DMode', {res: true});
window.dispatchEvent(event);
},
function(err) {
console.log("Don't support 3d mode!");
var event = new Event('Support3DMode', {res: false});
window.dispatchEvent(event);
},
"morphusSDK",
"is3DModeSupported",
[]);
};
/*
example: navigator.set3DModeParallel(3, function(msg){alert(msg);});
*/
navigator.set3DModeParallel = function(mode) {
cordova.exec(
function(msg) {
console.log(msg);
},
function(err) {
console.log("Don't support 3d mode!");
},
"morphusSDK",
"set3DModeParallel",
[mode]);
};
navigator.set3DModeSideBySide = function(mode) {
cordova.exec(
function(msg) {
console.log(msg);
},
function(err) {
alert("not support");
console.log("Don't support 3d mode!");
},
"morphusSDK",
"set3DModeSideBySide",
[mode]);
};
|
f6e05205cbb0039d489b4e817ec119274f58df45
|
[
"JavaScript"
] | 3
|
JavaScript
|
talentstar0428/FreeViStationWorldView
|
802f4f75c42acf89a1c6e89b1dbd0a1364f2c792
|
82156ced3e0719ac5d827316f7dd3745c29b0f9c
|
refs/heads/master
|
<file_sep><?php
$file = "data.txt";
$data = file_get_contents($file);
$baris = explode("[R]", $data);
@$nama = $_POST['nama'];
@$nim = $_POST['nim'];
@$email = $_POST['email'];
@$phone = $_POST['nomor'];
@$status = $_POST['status'];
@$alamat = $_POST['alamat'];
@$line = $_POST['line'];
$dataUp= @$nama . "|F|".
@$nim . "|F|".
@$email . "|F|".
@$phone . "|F|".
@$status . "|F|".
@$alamat . "|F|".
@$line . "[R]";
$rowUP = $_POST['index'];
$databaru = $dataUp;
for($i = 0; $i<count($baris)-1; $i++) {
if($i == $rowUP)continue;
$databaru .= $baris[$i] . "[R]";
}
file_put_contents($file, $databaru);
header('location:baca.php');
?><file_sep><?php
$file = "data.txt";
@$nama = $_POST['nama'];
@$nim = $_POST['nim'];
@$email = $_POST['email'];
@$phone = $_POST['nomor'];
@$status = $_POST['status'];
@$alamat = $_POST['alamat'];
@$line = $_POST['line'];
$data = @$nama . "|F|".
@$nim . "|F|".
@$email . "|F|" .
@$phone . "|F|".
@$status . "|F|".
@$alamat . "|F|".
@$line . "[R]";
$handle = fopen($file, "a+");
fwrite($handle, $data);
fclose($handle);
echo "Data berhasil disimpan!";<file_sep><!DOCTYPE html>
<html>
<head>
<title>Data</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, tr,th {
border: 3px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
body {
background-image: url(https://buonline.beasiswaunggulan.kemdikbud.go.id/assets/img/pattern_1.png);
background-repeat: repeat;
background-attachment: scroll;
background-clip: border-box;
background-origin: padding-box;
background-position-x: 100%;
background-position-y: 100%;
background-size: auto auto;
}
table {
border : 1px;
margin:0 auto;
width:90%
}
.container {
background-color : white;
background-repeat: repeat;
background-attachment: scroll;
background-clip: border-box;
background-origin: padding-box;
background-position-x: 100%;
background-position-y: 100%;
background-size: auto auto;
height:900px
}
.title{
background-color:#DDD6FF;
background-position: 100%;
background-position-y: 100%;
background-size: auto auto;
}
</style>
</head>
<body>
<div class = "container">
<br>
<div class = "title"><center><h2><br>REKAP DATA </h2></center><br></div><br>
<?php
$file = "data.txt";
$data = file_get_contents($file);
$baris = explode("[R]", $data);
echo "<table border=1>";
echo "<tr>";
echo " <th><h4>Nama</h4></th><th><h4>NIM</h4></th>";
echo " <th><h4>Email</h4></th><th><h4>Phone</h4></th>";
echo " <th><h4>Status</h4></th>";
echo " <th><h4>Kota Asal</h4></th><th><h4>Id_Line</h4></th>";
echo "<th><h4>Delete</h4></th><th><h4>Update</h4></th>";
echo "</tr>";
for($i =0; $i<count($baris)-1; $i++) {
//echo $b . "<br>";
$col = explode("|F|", $baris[$i]);
echo "<tr>";
echo " <td>" . $col[0] . "</td>";
echo " <td>" . $col[1] . "</td>";
echo " <td>" . $col[2] . "</td>";
echo " <td>" . $col[3] . "</td>";
echo " <td>" . $col[4] . "</td>";
echo " <td>" . $col[5] . "</td>";
echo " <td>" . $col[6] . "</td>";
echo ' <td> <a href="Delete.php?row='.$i.'">DELETE</a> </td>';
echo ' <td> <a href="Update.php?rowUp='.$i.'">UPDATE</a> </td>';
echo "</tr>";
}
echo "</table>";
echo "</center>";
?>
</div>
</body>
</html>
|
3757c5d11a92c9ed6cbb8c0fc193b3b206f23628
|
[
"PHP"
] | 3
|
PHP
|
VrishiMagridira/FileHandling
|
2f670cce282f2db271e21f386037740e9b821a35
|
32a512e03287ca408f764cfda905efc34e161a4a
|
refs/heads/master
|
<file_sep>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanelControl extends JPanel {
private ImagePanel imagePanel;
private JButton appleBtn, orangeBtn, tomatoBtn;
PanelControl(ImagePanel imagePanel) {
this.imagePanel = imagePanel;
// Initialize buttons
appleBtn = new JButton("Apple");
appleBtn.setEnabled(false);
appleBtn.setMnemonic('a');
appleBtn.setToolTipText("Show Apple");
appleBtn.addActionListener(new AppleListener());
orangeBtn = new JButton("Orange");
orangeBtn.setEnabled(true);
orangeBtn.setMnemonic('o');
orangeBtn.setToolTipText("Show Orange");
orangeBtn.addActionListener(new OrangeListener());
tomatoBtn = new JButton("Tomato");
tomatoBtn.setEnabled(true);
tomatoBtn.setMnemonic('t');
tomatoBtn.setToolTipText("Show Tomato");
tomatoBtn.addActionListener(new TomatoListener());
setBackground(Color.WHITE);
// Add the buttons to the main window
add(appleBtn);
add(orangeBtn);
add(tomatoBtn);
}
////// Action listeners
private class AppleListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
imagePanel.setState("a");
appleBtn.setEnabled(false);
orangeBtn.setEnabled(true);
tomatoBtn.setEnabled(true);
imagePanel.repaint();
}
}
private class OrangeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
imagePanel.setState("o");
appleBtn.setEnabled(true);
orangeBtn.setEnabled(false);
tomatoBtn.setEnabled(true);
imagePanel.repaint();
}
}
private class TomatoListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
imagePanel.setState("t");
appleBtn.setEnabled(true);
orangeBtn.setEnabled(true);
tomatoBtn.setEnabled(false);
imagePanel.repaint();
}
}
}
<file_sep>import javax.swing.*;
import java.awt.*;
public class ImagePanel extends JPanel {
private String state;
private ImageIcon apple, orange, tomato;
private JLabel imageLabel;
ImagePanel() {
// Load images
apple = new ImageIcon("apple.png");
orange = new ImageIcon("orange.png");
tomato = new ImageIcon("tomato.png");
setBackground(Color.WHITE);
state = "a";
imageLabel = new JLabel(apple);
add(imageLabel);
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
// Set image based of selection input by user
if (state.equals("a"))
imageLabel.setIcon(apple);
else if (state.equals("o"))
imageLabel.setIcon(orange);
else if (state.equals("t"))
imageLabel.setIcon(tomato);
}
public void setState(String state) {
this.state = state;
}
}
<file_sep># Image-Decoder
Optional course work for Object Oriented Programming at Kwame Nkrumah University of Science and Technology.
|
eb1d74664edce79cabb91e52bb268ed67a9ba32f
|
[
"Markdown",
"Java"
] | 3
|
Java
|
aibenStunner/Image-Decoder
|
2003f4089537a2aa2e21fd66c16a31015a923fd7
|
fb09c623d4db301e2441feebf2152435adebdda4
|
refs/heads/master
|
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_deep_copy.dir/test_deep_copy.c.o"
"test_deep_copy"
"test_deep_copy.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_deep_copy.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_cast.dir/test_cast.c.o"
"test_cast"
"test_cast.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_cast.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_strerror.dir/__/strerror_override.c.o"
"CMakeFiles/test_strerror.dir/test_strerror.c.o"
"test_strerror"
"test_strerror.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_strerror.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>Right now it just displays a statically drawn cube bouncing back and forth. What do I mean by statically drawn? I malloc a buffer that’s 4x as large as the screen and draw the cube **once**. Then on each frame I index into the buffer at incremental memory locations so that the cube appears to move. (I change the area of the buffer that's reflected on the screen.)
A little more about how it works: when the app launches, it triggers the callback function onNativeWindowCreated() in android_native_app_glue.c, which captures a handle to the ANativeWindow (C++ version of Android's Surface class) that the app is displaying. We can leverage that ANativeWindow's raw pixel buffer by calling ANativeWindow_lock(), which in turn calls Surface::lock() in Surface.cpp, which gives us a pointer to the raw memory containing the bits of the actual GraphicBuffer (a wrapper around a raw buffer allocated as needed by Gralloc3). Then we can do our software rendering and call ANativeWindow_unlockAndPost(), which queues the buffer back up to the BufferQueue, where it will await processing by SurfaceFlinger on the next VSYNC pulse from the display hardware.
Compare this to my DRM dumb buffer repository, which is doing lower-level rendering by interacting with the kernel and the device's DRM driver. That code shuts down SurfaceFlinger/hwcomposer and assumes the role of the display server.
# TODO #
Currently, the main issue is that I’m still using memcpy to copy all of the pixel data from my malloced buffer into the window buffer (just adjusting the source address in the memcpy() call). I can set the window’s bitbuffer address to point to my malloced buffer, and it appears to change when I check it inside my program, but that’s futile--when the window is posted to the display queue (sent back into the Android graphics pipeline files like Surface.cpp), the system still looks for the pixels at the original address where the window’s bitbuffer was allocated. The reason for that is as follows: when ANativeWindow_lock(ANativeWindow\* window) is called, it ends up just getting the underlying Surface instance from `window`, which contains the original instance of GraphicBuffer that's attached to the Surface, which still holds the original bits address. The `buffer->bits` pointer that we get in main.cpp is really just a copy of the original pointer, as we can see here in Surface::lock():
```
//a copy of the ptr to the raw bits of the window
void* vaddr;
//populate vaddr with pointer to the raw buffer bits by calling lockAsync() on our GraphicBuffer, reading bits address into vaddr. lockAsync() is just getting a copy of the original pointer held by the GraphicBuffer
status_t res = backBuffer->lockAsync(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN, newDirtyRegion.bounds(), &vaddr, fenceFd);
```
So I have no choice but to write pixels into that address in my program. I'm currently trying to, within my program, get access to that original bits address and change it to point to my allocated pixel memory. Then I'd be able to save more rendering time by just adjusting the pointer (which I **can** do in the DRM dumb buffer version of this app) and not having to use memcpy.
UPDATE(02/02/21): I drew some text into the ANativeWindow_Buffer. For a sample text, go to my text pixel coordinate generator at [this](http://serviceberry3.github.io/text_eng.html), download the json, and ```adb push``` it to /system/files/text_coords.json on the Android device. I will soon update the text engine page to take input for custom text.
Example:

UPDATE(01/07/21): I created a new version of the unlockAndPost() function in Surface.cpp (in AOSP source code) which avoids setting mLockedBuffer back to null after each unlock. So it reuses the same buffer. Then I also needed to comment out the isDequeued() check in BufferQueueProducer.cpp. Using Surface::perform() with SET_BUFFERS_USER_DIMENSIONS, I can force gralloc to create a buffer 4x as large as the screen, and then on each frame I just adjust the crop rectangle and unlockAndPost() the same buffer over and over again. I also created a custom version of Surface::lock() that doesn't call dequeueBufer(); it just reuses the last buffer and calls lockAsync() on that.
However, something interesting was happening after I made these changes: the app started rendering at the expected speed, but then the time it took for my custom unlockAndPost() function to run gradually increases and the rendering gradually slows down.
After doing some deep diving, including running '''dumpsys SurfaceFlinger''' and using the Android systrace tool, I discovered that I was flooding the BufferQueue: queueBuffer() calls were running rampant. Normally, the queue/dequeue pairs are spaced out about as far apart as the VSYNCS, and "fence wait" happens in the lockAsync() function. "fence wait" ends in sync with "operation id," whatever that is...anyway, the issue is that in my hacked version, the queueBuffer() calls aren't timed correctly, because the lockAsync() function in Surface::lock() isn't waiting for a HWC release fence anymore. I'm trying to figure out why.
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/testReplaceExisting.dir/testReplaceExisting.c.o"
"testReplaceExisting"
"testReplaceExisting.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/testReplaceExisting.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_set_value.dir/test_set_value.c.o"
"test_set_value"
"test_set_value.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_set_value.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># CMake generated Testfile for
# Source directory: /home/nodog/docs/asp/android_native_win_buff/json-c
# Build directory: /home/nodog/docs/asp/android_native_win_buff/json-c-build
#
# This file includes the relevant testing commands required for
# testing this directory and lists subdirectories to be tested as well.
subdirs("tests")
subdirs("apps")
subdirs("doc")
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_null.dir/test_null.c.o"
"test_null"
"test_null.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_null.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_json_pointer.dir/test_json_pointer.c.o"
"test_json_pointer"
"test_json_pointer.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_json_pointer.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_object_iterator.dir/test_object_iterator.c.o"
"test_object_iterator"
"test_object_iterator.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_object_iterator.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test2Formatted.dir/parse_flags.c.o"
"CMakeFiles/test2Formatted.dir/test2.c.o"
"test2Formatted"
"test2Formatted.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test2Formatted.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#ifndef _TEAPOTRENDERER_H
#define _TEAPOTRENDERER_H
//--------------------------------------------------------------------------------
// Include files
//--------------------------------------------------------------------------------
#include <jni.h>
#include <errno.h>
#include <vector>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/native_window_jni.h>
#include <stdlib.h>
#define CLASS_NAME "android/app/NativeActivity"
#define APPLICATION_CLASS_NAME "com/sample/teapot/TeapotApplication"
//include verbose logs
#undef LOG_NDEBUG
#define LOG_NDEBUG 0
//#include "/home/nodog/Documents/aosp2/working/system/core/include/log/log.h"
#undef LOG_TAG
#define LOG_TAG "libgl2jni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define BUFFER_OFFSET(i) ((char*)NULL + (i))
struct TEAPOT_VERTEX {
float pos[3];
float normal[3];
};
enum SHADER_ATTRIBUTES {
ATTRIB_VERTEX,
ATTRIB_NORMAL,
ATTRIB_UV,
};
struct SHADER_PARAMS {
GLuint program_;
GLuint light0_;
GLuint material_diffuse_;
GLuint material_ambient_;
GLuint material_specular_;
GLuint matrix_projection_;
GLuint matrix_view_;
};
struct TEAPOT_MATERIALS {
float diffuse_color[3];
float specular_color[4];
float ambient_color[3];
};
class Renderer {
int32_t num_indices_;
int32_t num_vertices_;
GLuint ibo_;
GLuint vbo_;
SHADER_PARAMS shader_param_;
bool LoadShaders(SHADER_PARAMS* params, const char* strVsh,
const char* strFsh);
public:
Renderer(int w, int h);
~Renderer();
bool Init(int w, int h);
void Render();
void Update(float dTime);
void Unload();
void UpdateViewport();
GLuint gProgram;
GLuint gvPositionHandle;
};
#endif<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test1Formatted.dir/parse_flags.c.o"
"CMakeFiles/test1Formatted.dir/test1.c.o"
"test1Formatted"
"test1Formatted.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test1Formatted.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <initializer_list>
#include <memory>
#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <jni.h>
#include <cerrno>
#include <cassert>
#include <iostream>
//Android uses the OpenGL ES (GLES) API to render graphics. To create GLES contexts and provide a windowing system for GLES renderings,
//Android uses the EGL library. GLES calls render textured polygons, while EGL calls put renderings on screens
#include <EGL/egl.h>
#include <GLES/gl.h>
#include "Renderer.h"
#include "glyphs.h"
#include "json.hpp"
#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/bitmap.h>
#include <fstream>
typedef uint16_t color_16bits_t;
typedef uint8_t color_8bits_channel_t;
typedef uint16_t window_pixel_t;
//#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__))
#define PIXEL_COLORS_MAX 5
#define PIXEL_COLORS_MAX_MASK 0b11
#define ANDROID_NATIVE_MAKE_CONSTANT(a,b,c,d) (((unsigned)(a)<<24)|((unsigned)(b)<<16)|((unsigned)(c)<<8)|(unsigned)(d))
#define ANDROID_NATIVE_WINDOW_MAGIC ANDROID_NATIVE_MAKE_CONSTANT('_','w','n','d')
#define ANDROID_NATIVE_BUFFER_MAGIC ANDROID_NATIVE_MAKE_CONSTANT('_','b','f','r')
//#define OG
//quick function that takes some values r g b and manipulates them to get RGB565 result
#define make565(r,g,b) ( (color_16bits_t) ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3) )
#ifndef __cplusplus
enum bool { false, true };
typedef enum bool bool;
#endif
using json = nlohmann::json;
/**
* Our saved state data (accelerometer reading)
*/
struct saved_state {
float angle;
int32_t x;
int32_t y;
};
//TAKE DEFINITIONS FROM system/window.h TO AVOID COMPILER ERRORS------------------------------------------------------------------------------------------------
typedef struct android_native_rect_t
{
int32_t left;
int32_t top;
int32_t right;
int32_t bottom;
} android_native_rect_t;
typedef struct android_native_base_t
{
/* a magic value defined by the actual EGL native type */
int magic;
/* the sizeof() of the actual EGL native type */
int version;
void* reserved[4];
/* reference-counting interface */
void (*incRef)(struct android_native_base_t* base);
void (*decRef)(struct android_native_base_t* base);
} android_native_base_t;
coord text_coords[63659] = {};
struct ANativeWindow
{
#ifdef __cplusplus
//constructor
ANativeWindow(): flags(0), minSwapInterval(0), maxSwapInterval(0), xdpi(0), ydpi(0)
{
common.magic = ANDROID_NATIVE_WINDOW_MAGIC;
common.version = sizeof(ANativeWindow);
memset(common.reserved, 0, sizeof(common.reserved));
}
/* Implement the methods that sp<ANativeWindow> expects so that it
can be used to automatically refcount ANativeWindow's. */
void incStrong(const void* id) const {
common.incRef(const_cast<android_native_base_t*>(&common));
}
void decStrong(const void* id) const {
common.decRef(const_cast<android_native_base_t*>(&common));
}
#endif
struct android_native_base_t common;
/* flags describing some attributes of this surface or its updater */
const uint32_t flags;
/* min swap interval supported by this updated */
const int minSwapInterval;
/* max swap interval supported by this updated */
const int maxSwapInterval;
/* horizontal and vertical resolution in DPI */
const float xdpi;
const float ydpi;
/* Some storage reserved for the OEM's driver. */
intptr_t oem[4];
/*
* Set the swap interval for this surface.
*
* Returns 0 on success or -errno on error.
*/
int (*setSwapInterval)(struct ANativeWindow* window,
int interval);
/*
* Hook called by EGL to acquire a buffer. After this call, the buffer
* is not locked, so its content cannot be modified. This call may block if
* no buffers are available.
*
* The window holds a reference to the buffer between dequeueBuffer and
* either queueBuffer or cancelBuffer, so clients only need their own
* reference if they might use the buffer after queueing or canceling it.
* Holding a reference to a buffer after queueing or canceling it is only
* allowed if a specific buffer count has been set.
*
* Returns 0 on success or -errno on error.
*/
int (*dequeueBuffer)(struct ANativeWindow* window,
struct ANativeWindowBuffer** buffer);
/*
* hook called by EGL to lock a buffer. This MUST be called before modifying
* the content of a buffer. The buffer must have been acquired with
* dequeueBuffer first.
*
* Returns 0 on success or -errno on error.
*/
int (*lockBuffer)(struct ANativeWindow* window,
struct ANativeWindowBuffer* buffer);
/*
* Hook called by EGL when modifications to the render buffer are done.
* This unlocks and post the buffer.
*
* The window holds a reference to the buffer between dequeueBuffer and
* either queueBuffer or cancelBuffer, so clients only need their own
* reference if they might use the buffer after queueing or canceling it.
* Holding a reference to a buffer after queueing or canceling it is only
* allowed if a specific buffer count has been set.
*
* Buffers MUST be queued in the same order than they were dequeued.
*
* Returns 0 on success or -errno on error.
*/
int (*queueBuffer)(struct ANativeWindow* window,
struct ANativeWindowBuffer* buffer);
/*
* hook used to retrieve information about the native window.
*
* Returns 0 on success or -errno on error.
*/
int (*query)(const struct ANativeWindow* window,
int what, int* value);
/*
* hook used to perform various operations on the surface.
* (*perform)() is a generic mechanism to add functionality to
* ANativeWindow while keeping backward binary compatibility.
*
* DO NOT CALL THIS HOOK DIRECTLY. Instead, use the helper functions
* defined below.
*
* (*perform)() returns -ENOENT if the 'what' parameter is not supported
* by the surface's implementation.
*
* The valid operations are:
* NATIVE_WINDOW_SET_USAGE
* NATIVE_WINDOW_CONNECT (deprecated)
* NATIVE_WINDOW_DISCONNECT (deprecated)
* NATIVE_WINDOW_SET_CROP
* NATIVE_WINDOW_SET_BUFFER_COUNT
* NATIVE_WINDOW_SET_BUFFERS_GEOMETRY (deprecated)
* NATIVE_WINDOW_SET_BUFFERS_TRANSFORM
* NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP
* NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS
* NATIVE_WINDOW_SET_BUFFERS_FORMAT
* NATIVE_WINDOW_SET_SCALING_MODE
* NATIVE_WINDOW_LOCK (private)
* NATIVE_WINDOW_UNLOCK_AND_POST (private)
* NATIVE_WINDOW_API_CONNECT (private)
* NATIVE_WINDOW_API_DISCONNECT (private)
*
*/
int (*perform)(struct ANativeWindow* window,
int operation, ... );
/*
* Hook used to cancel a buffer that has been dequeued.
* No synchronization is performed between dequeue() and cancel(), so
* either external synchronization is needed, or these functions must be
* called from the same thread.
*
* The window holds a reference to the buffer between dequeueBuffer and
* either queueBuffer or cancelBuffer, so clients only need their own
* reference if they might use the buffer after queueing or canceling it.
* Holding a reference to a buffer after queueing or canceling it is only
* allowed if a specific buffer count has been set.
*/
int (*cancelBuffer)(struct ANativeWindow* window,
struct ANativeWindowBuffer* buffer);
void* reserved_proc[2];
};
//END COPIED DECLARATIONS--------------------------------------------------------------------------------------------------------------
//create array of 4 16-bit unsigned ints (will always be same value)
static color_16bits_t const pixel_colors[PIXEL_COLORS_MAX] = {
make565(255, 0, 0), //0b1111100000000000, //pure red
make565( 0,255, 0), //pure green
make565( 0, 0,255), //pure blue
make565(255,255, 0),
make565(255, 255, 255),
};
int frameNum = 0;
//test cropping rectangle for screen
android_native_rect_t original {0, 0, 1080, 2280};
android_native_rect_t test_rect {0, 0, 2280, 1080};
//oscillation direction
int dir = 0;
//we want to start the buffer
int oscillator = 0;
window_pixel_t* large_buff; //2462400
//Layer is the most important unit of composition. A layer is a combination of a surface and an instance of SurfaceControl
/*
static inline window_pixel_t * buffer_first_pixel_of_next_line
(ANativeWindow_Buffer const * __restrict const buffer,
window_pixel_t const * __restrict const line_start)
{
return (window_pixel_t *) (line_start + buffer->stride);
}
*/
/*
static inline uint_fast32_t pixel_colors_next (uint_fast32_t current_index)
{
return (rand() & PIXEL_COLORS_MAX_MASK);
}*/
static void get_txt_coords() {
std::ifstream ifs("/system/files/text_coords.json");
json jf = json::parse(ifs);
LOGI("Size is %d\n", (int)jf.size());
for (int i = 0; i < jf.size(); i++) {
text_coords[i].x = (int)jf[i]["x"];
text_coords[i].y = (int)jf[i]["y"];
}
LOGI("JSON Success\n");
}
//draw some text on the background
//draw some text on the background
//@param x_off - x offset from left of screen where we want to start drawing text
//@param y_off - y offset from top of screen where we want to start drawing text
static void drawText(int x_off, int y_off, color_16bits_t text_color, window_pixel_t* bits, int32_t stride) {
int initial_adjust = 4452660;
initial_adjust -= ((y_off - 1) * stride) + x_off;
//draw text
int this_pix;
for (auto & text_coord : text_coords) {
this_pix = ((text_coord.y - 1) * stride + text_coord.x) - initial_adjust; //first would be 4719600, which is way too big 4608 was 2176
bits[this_pix] = text_color;
}
}
#ifdef OG
//the coord list comes from the basic pixel coordinates found by
static void fill_pixels(ANativeWindow_Buffer* buffer)
{
LOGI("Mem address of large_buff is %p", large_buff);
//create array of 4 16-bit unsigned ints (will always be same value)
static color_16bits_t const pixel_colors[PIXEL_COLORS_MAX] = {
make565(255, 0, 0), //0b1111100000000000, //pure red
make565( 0,255, 0), //pure green
make565( 0, 0,255), //pure blue
make565(255,255, 0)
};
//NOTE***: each pixel takes up 2 bytes in memory, so we need a memory array of 2 * 1080 * 2280
//Current pixel colors index
//p_c is a result of bitwise AND of random integer with 0b11 (the max index). In other words, pick a random index into pixel_colors
//uint_fast32_t p_c = rand() & PIXEL_COLORS_MAX_MASK;
color_16bits_t current_pixel_color;
//pointer to buffer of uint16_t
auto* current_pixel = (window_pixel_t *)buffer->bits;
LOGI("current_pixel (or initial buffer->bits) address is %p", current_pixel);
//number of pixels per line
uint_fast32_t const line_width = buffer->width;
//stride
uint_fast32_t const line_stride = buffer->stride;
//number of pixel lines we have available
uint_fast32_t n_lines = buffer->height;
LOGI("Num lines is %d, width of lines is %d, stride is %d", (int)n_lines, (int)line_width, (int)line_stride);
//EXPERIMENTAL: DOESN'T WORK.
//Right off, I've noticed something interesting about this. Above, we set current_pixel to point to the address of buffer->bits. So now when we set buffer->bits to point
//to large_buff, current_pixel remains at the original address of buffer->bits, while buffer->bits address does change to the address of large_buff (I checked this with the
//logging). So in the while loop below, we're writing pixels at the original address of buffer->bits. And although we've supposedly changed the address of buffer->bits
//to point to large_buff, that doesn't hold up once ANativeWindow_unlockAndPost() is called: what we see posted to the display queue is still what's written in the while loop
//below.
//So in conclusion, apparently we can't just set buffer.bits to some mem we allocated on the heap in this app. That doesn't do anything once the ANativeWindow
//is pushed to the display. We need to do some diggin in the Android source to find a way to actually set that pointer. Then we could render even faster by having all the
//pixels pre-rendered and just modifying the address.
//buffer->bits = large_buff;
LOGI("After setting buffer->bits = large_buff, current_pixel address is now %p, and buffer->bits is %p", current_pixel, buffer->bits);
//stops when n_lines is at 0 (have iterated through every line
while (n_lines--) { //starts at 2280
//pointer to start of the current pixel line (starts at beginning of buffer->bits)
window_pixel_t const* current_line_start = current_pixel;
//pointer to the last pixel in the line
window_pixel_t const* last_pixel_of_the_line = current_line_start + line_width;
//current_pixel_color = (n_lines % 1 == 0) ? 1200 : 5000;
//get the desired color, choosing randomly from the 4 available
//CHANGED to always pick red for now
current_pixel_color = pixel_colors[0];
/*
///////////////////
if (n_lines >= 1000 && n_lines <= 1300) {
while (((uintptr_t) current_pixel <= (uintptr_t) last_pixel_of_the_line - 800)) {
if ((uintptr_t) current_pixel >= (uintptr_t) current_line_start + 800) {
*current_pixel = current_pixel_color;
}
current_pixel++;
}
}
/////////////////*/
if (n_lines % 20 == 0) {
//write first 1080 bytes in the line (5040 pixels)
while ((uintptr_t)current_pixel <= (uintptr_t)last_pixel_of_the_line - 1080) {
*current_pixel = current_pixel_color;
//since current_pixel is an uint16_t ptr (2 bytes), this advances the read by 2 bytes
current_pixel++;
}
//switch over to green about halfway across screen
current_pixel_color = pixel_colors[1];
//write second 1080 bytes in the line (5040 pixels)
while ((uintptr_t)current_pixel <= (uintptr_t)last_pixel_of_the_line) {
*current_pixel = current_pixel_color;
//since current_pixel is an uint16_t ptr (2 bytes), this advances the read by 2 bytes
current_pixel++;
}
}
//change the random index (color selector)
//p_c = pixel_colors_next(p_c);
//move to next pixel line. Unsigned short is 2 bytes, line_stride is 1088. Since current_line_start is uin16_t ptr, adding 1088 advances the read by 1088*2 bytes,
//bringing us to the first pixel in the next line
current_pixel = (unsigned short *) (current_line_start + (line_stride));
}
//copy our pixels from large_buff over to the bits of the window
memcpy(buffer->bits, large_buff + oscillator, sizeof(window_pixel_t) * 1080 * 2280);
//bounce the red box back and forth across the screen
if (dir == 0) {
oscillator += 50;
}
else {
oscillator -= 50;
}
if (oscillator == 750 && dir==0) {
dir = 1;
}
else if (oscillator==0 && dir==1) {
dir = 0;
}
}
#endif
/**
* Shared state for our app.
*/
struct engine {
struct android_app* app;
Renderer* renderer;
ASensorManager* sensorManager;
const ASensor* accelerometerSensor;
ASensorEventQueue* sensorEventQueue;
int animating;
//display is another important unit of composition. A system can have multiple displays and displays can be added or
//removed during normal system operations. Displays are added/removed at request of the HWC or the framework.
EGLDisplay display;
//Before you draw with GLES, need to create GL context. In EGL, this means creating EGLContext and EGLSurface.
//EGLSurface can be off-screen buffer allocated by EGL, called a pbuffer, or window allocated by the operating system.
//Only one EGLSurface can be associated with a surface at a time (you can have only one producer connected to a BufferQueue),
// but if you destroy the EGLSurface it disconnects from the BufferQueue and lets something else connect.
//A given thread can switch between multiple EGLSurfaces by changing what's CURRENT. An EGLSurface must be CURRENT on
// only one thread at a time.
//
//EGL isn't another aspect of a surface (like SurfaceHolder). EGLSurf is a related but independent concept. You can draw on an
//EGLSurface that isn't backed by a surface, and can use a surface without EGL. EGLSurface just provides GLES with place to draw
EGLSurface surface;
EGLContext context;
int32_t initial_window_format;
int32_t width;
int32_t height;
struct saved_state state;
};
static inline bool engine_have_a_window (struct engine const * __restrict const engine)
{
return engine->app->window != nullptr;
}
//terminate the display
static inline void engine_term_display (struct engine * __restrict const engine)
{
//no longer animating
engine->animating = 0;
}
void produce_txt_pixels() {
};
void eglErrorString(EGLint error)
{
switch(error)
{
case EGL_SUCCESS: LOGI("ERROR AFTER CREATEWINDSURF: success"); return;
case EGL_NOT_INITIALIZED: LOGI("ERROR AFTER CREATEWINDSURF: not initialized"); return;
case EGL_BAD_ACCESS: LOGI("ERROR AFTER CREATEWINDSURF: bad access"); return;
case EGL_BAD_ALLOC: LOGI("ERROR AFTER CREATEWINDSURF: bad alloc"); return;
case EGL_BAD_ATTRIBUTE: LOGI("ERROR AFTER CREATEWINDSURF: bad attribute"); return;
case EGL_BAD_CONTEXT: LOGI("ERROR AFTER CREATEWINDSURF: bad context"); return;
case EGL_BAD_CONFIG: LOGI("ERROR AFTER CREATEWINDSURF: bad config");return;
case EGL_BAD_CURRENT_SURFACE: LOGI("ERROR AFTER CREATEWINDSURF: bad current surface");return;
case EGL_BAD_DISPLAY: LOGI("ERROR AFTER CREATEWINDSURF: bad display");return;
case EGL_BAD_SURFACE: LOGI("ERROR AFTER CREATEWINDSURF: bad surface");return;
case EGL_BAD_MATCH: LOGI("ERROR AFTER CREATEWINDSURF: bad match");return;
case EGL_BAD_PARAMETER: LOGI("ERROR AFTER CREATEWINDSURF: bad parameter");return;
case EGL_BAD_NATIVE_PIXMAP: LOGI("ERROR AFTER CREATEWINDSURF: bad native pixmap");return;
case EGL_BAD_NATIVE_WINDOW: LOGI("ERROR AFTER CREATEWINDSURF: bad native window");return;
case EGL_CONTEXT_LOST: LOGI("ERROR AFTER CREATEWINDSURF: lost context");return;
}
LOGI("CURRENT ERROR: %d", error);
}
/**
* Initialize an EGL context for the current display.
*/
/*
static int engine_init_display(struct engine* engine) {
LOGI("engine_init_display called");
// initialize OpenGL ES and EGL
//specify the attributes of the desired configuration.
//Below, we select an EGLConfig with at least 8 bits per color
//component compatible with on-screen windows
const EGLint attribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint w, h, format;
EGLint numConfigs;
EGLConfig config = nullptr;
EGLSurface surface;
EGLContext context;
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display, nullptr, nullptr);
//Here, the application chooses the configuration it desires.
//find the best match if possible based on attribs list, otherwise use the very first one
eglChooseConfig(display, attribs, nullptr,0, &numConfigs);
//unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object
//when the unique_ptr goes out of scope.
std::unique_ptr<EGLConfig[]> supportedConfigs(new EGLConfig[numConfigs]);
assert(supportedConfigs);
eglChooseConfig(display, attribs, supportedConfigs.get(), numConfigs, &numConfigs);
assert(numConfigs);
auto i = 0;
for (; i < numConfigs; i++) {
auto& cfg = supportedConfigs[i];
EGLint r, g, b, d;
//get color data through EGLints from the display
if (eglGetConfigAttrib(display, cfg, EGL_RED_SIZE, &r) &&
eglGetConfigAttrib(display, cfg, EGL_GREEN_SIZE, &g) &&
eglGetConfigAttrib(display, cfg, EGL_BLUE_SIZE, &b) &&
eglGetConfigAttrib(display, cfg, EGL_DEPTH_SIZE, &d) &&
r == 8 && g == 8 && b == 8 && d == 0 ) {
config = supportedConfigs[i];
break;
}
}
if (i == numConfigs) {
config = supportedConfigs[0];
}
if (config == nullptr) {
LOGW("Unable to initialize EGLConfig");
return -1;
}
EGLint AttribList[] = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL_NONE
};
//EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
//guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
//As soon as we picked a EGLConfig, we can safely reconfigure the
//ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID.
eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
EGLint windowAttributes[] = {
EGL_RENDER_BUFFER, EGL_BACK_BUFFER,
EGL_NONE
};
// Calling eglCreateWindowSurface() creates EGL window surfaces. eglCreateWindowSurface() takes a window
// object as an argument, which on Android is a SURFACE (aka ANativeWindow.cpp). A SURFACE is the "PRODUCER" side of a BufferQueue.
// "CONSUMERS," whichare SurfaceView, SurfaceTexture, TextureView, or ImageReader, create surfaces. When you call eglCreateWindowSurface(),
// EGL creates new EGLSurface object and connects it to "PRODUCER" interface of window object's BufferQueue. From
// that point onward, rendering to that EGLSurface results in buffer being dequeued, rendered into, and queued for use by consumer
//native_window_set_buffers_user_dimensions(engine->app->window, 1080*3, 2280*3);
//@param engine->app->window a pointer to an ANativeWindow
surface = eglCreateWindowSurface(display, config, engine->app->window, windowAttributes);
eglErrorString(eglGetError());
context = eglCreateContext(display, config, nullptr, AttribList);
if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
LOGW("Unable to eglMakeCurrent");
return -1;
}
//get width and height data of the surface through more EGLints w and h
eglQuerySurface(display, surface, EGL_WIDTH, &w);
eglQuerySurface(display, surface, EGL_HEIGHT, &h);
w = 1080*3;
h = 2280*3;
engine->display = display;
engine->context = context;
engine->surface = surface;
engine->width = 1080*3;
engine->height = 2280*3;
engine->state.angle = 0;
// Check openGL on the system
auto opengl_info = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_EXTENSIONS};
for (auto name : opengl_info) {
auto info = glGetString(name);
LOGI("OpenGL Info: %s", info);
}
//Initialize GL state.
//glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
//glEnable(GL_CULL_FACE);
//glShadeModel(GL_SMOOTH);
//glDisable(GL_DEPTH_TEST);
frameNum = 0;
LOGI("Finished initDisplay");
return 0;
}
*/
/*
void drawBitmap(JNIEnv *env, jobject obj, jobject surface, jobject bitmap) {
//Get the information of the bitmap, such as width and height
AndroidBitmapInfo info;
if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
LOGI("java/lang/RuntimeException: unable to get bitmap info");
return;
}
char *data = nullptr;
//Get the native pointer corresponding to the bitmap
if (AndroidBitmap_lockPixels(env, bitmap, (void **) &data) < 0) {
LOGI("java/lang/RuntimeException: unable to lock pixels");
return;
}
if (AndroidBitmap_unlockPixels(env, bitmap) < 0) {
LOGI("java/lang/RuntimeException: unable to unlock pixels");
return;
}
//Get the target surface
ANativeWindow* window = ANativeWindow_fromSurface(env, surface);
if (window == nullptr) {
LOGI("java/lang/RuntimeException: unable to get native window");
return;
}
//Here is set to RGBA way, a total of 4 bytes 32 bits
int32_t result = ANativeWindow_setBuffersGeometry(window, info.width, info.height,WINDOW_FORMAT_RGBA_8888);
if (result < 0) {
LOGI("java/lang/RuntimeException: unable to set buffers geometry");
//release the window
ANativeWindow_release(window);
window = nullptr;
return;
}
ANativeWindow_acquire(window);
ANativeWindow_Buffer buffer;
//Lock the drawing surface of the window
if (ANativeWindow_lock(window, &buffer, nullptr) < 0) {
LOGI("java/lang/RuntimeException: unable to lock native window");
//release the window
ANativeWindow_release(window);
window = nullptr;
return;
}
//Convert to a pixel to handle
auto* bitmapPixels = (int32_t *) data;
auto* line = (uint32_t *) buffer.bits;
for (int y = 0; y < buffer.height; y++) {
for (int x = 0; x < buffer.width; x++) {
line[x] = bitmapPixels[buffer.height * y + x];
}
line = line + buffer.stride;
}
//Unlock the drawing surface of the window
if (ANativeWindow_unlockAndPost(window) < 0) {
LOGI("java/lang/RuntimeException: unable to unlock and post to native window");
}
//free the reference to the Surface
ANativeWindow_release(window);
}*/
/*
* native_window_set_crop(..., crop)
* Sets which region of the next queued buffers needs to be considered.
* Depending on the scaling mode, a buffer's crop region is scaled and/or
* cropped to match the surface's size. This function sets the crop in
* pre-transformed buffer pixel coordinates.
*
* The specified crop region applies to all buffers queued after it is called.
*
* If 'crop' is NULL, subsequently queued buffers won't be cropped.
*
* An error is returned if for instance the crop region is invalid, out of the
* buffer's bound or if the window is invalid.
*/
/*
int native_window_set_crop(struct ANativeWindow* window, android_native_rect_t const* crop)
{
return window->perform(window, NATIVE_WINDOW_SET_CROP, crop);
}*/
int first = 1;
//draw a frame
static void engine_draw_frame(struct engine* engine) {
/*
if (engine->display == nullptr) {
LOGI("engine->display is NULL");
//No display.
return;
}
//Just fill the screen with a color.
//glClearColor(((float)engine->state.x)/engine->width, engine->state.angle,((float)engine->state.y)/engine->height, 1);
//glClearColor(220, 0, 0, 0);
if (frameNum==0) {
//first frame, do rendering
glClear(GL_COLOR_BUFFER_BIT);
//LOGI("Attempting render");
//invokes the GPU ONCE to do rendering/shading
engine->renderer->Render();
//LOGI("Finsihed render");
}
eglSwapBuffers(engine->display, engine->surface);*/
//make sure we have a window
if (!engine_have_a_window(engine))
{
LOGI("The engine doesn't have a window !?\n");
//abort
goto draw_frame_end;
}
//ANativeWindow_Buffer in which to store the current frame's bits buffer
ANativeWindow_Buffer buffer;
#ifdef OG
//make sure we can lock this ANativeWindow_Buffer so that we can edit pixels
if (ANativeWindow_lock(engine->app->window, &buffer, nullptr) < 0)
{
LOGI("Could not lock the window... :C\n");
//abort
goto draw_frame_end;
}
//fill the raw bits buffer
fill_pixels(&buffer);
//release the lock on our window's buffer and post the window to the screen
ANativeWindow_unlockAndPost(engine->app->window);
#else
if (dir == 0) {
//adjust crop
test_rect.left+=30;
test_rect.right+=30;
if (test_rect.left==900) {
dir = 1;
}
}
else {
test_rect.left-=30;
test_rect.right-=30;
if (test_rect.left==0) {
dir = 0;
}
}
if (first == 1) {
if (ANativeWindow_lock(engine->app->window, &buffer, nullptr) < 0)
{
LOGI("Could not lock the window... :C\n");
//abort
goto draw_frame_end;
}
}
else {
//lock the same buffer
engine->app->window->perform(engine->app->window, 49, &buffer, nullptr);
}
//adjust the crop of the GraphicBuffer and push it to the screen
LOGI("Calling set crop\n");
engine->app->window->perform(engine->app->window, 3, &test_rect);
//code 48 is a custom function we created in Surface.cpp
engine->app->window->perform(engine->app->window, 48, false);
#endif
//LOGI("Frame number %d", frameNum);
frameNum++;
draw_frame_end:
return;
}
/*
//destroy EGL context currently associated with the display
static void engine_term_display(struct engine* engine) {
if (engine->display != EGL_NO_DISPLAY) {
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (engine->context != EGL_NO_CONTEXT) {
eglDestroyContext(engine->display, engine->context);
}
if (engine->surface != EGL_NO_SURFACE) {
eglDestroySurface(engine->display, engine->surface);
}
eglTerminate(engine->display);
}
engine->animating = 0;
engine->display = EGL_NO_DISPLAY;
engine->context = EGL_NO_CONTEXT;
engine->surface = EGL_NO_SURFACE;
}*/
//process the next input event
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
auto* const engine = (struct engine*) app->userData;
int32_t const current_event_type = AInputEvent_getType(event);
//if the incoming event is a MotionEvent
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
//set animating to true
//IGNORE TOUCH EVENTS FOR NOW
engine->animating = 1;
engine->state.x = AMotionEvent_getX(event, 0);
engine->state.y = AMotionEvent_getY(event, 0);
return 1;
}
//if the incoming event is a KeyEvent
else if (current_event_type == AINPUT_EVENT_TYPE_KEY) {
LOGI("Key event: action=%d keyCode=%d metaState=0x%x", AKeyEvent_getAction(event), AKeyEvent_getKeyCode(event), AKeyEvent_getMetaState(event));
}
return 0;
}
/*REFERENCE
enum {
// clang-format off
NATIVE_WINDOW_SET_USAGE = ANATIVEWINDOW_PERFORM_SET_USAGE
NATIVE_WINDOW_CONNECT = 1,
NATIVE_WINDOW_DISCONNECT = 2,
NATIVE_WINDOW_SET_CROP = 3,
NATIVE_WINDOW_SET_BUFFER_COUNT = 4,
NATIVE_WINDOW_SET_BUFFERS_GEOMETRY = ANATIVEWINDOW_PERFORM_SET_BUFFERS_GEOMETRY,
NATIVE_WINDOW_SET_BUFFERS_TRANSFORM = 6,
NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP = 7,
NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS = 8,
NATIVE_WINDOW_SET_BUFFERS_FORMAT = ANATIVEWINDOW_PERFORM_SET_BUFFERS_FORMAT,
NATIVE_WINDOW_SET_SCALING_MODE = 10,
NATIVE_WINDOW_LOCK = 11,
NATIVE_WINDOW_UNLOCK_AND_POST = 12,
NATIVE_WINDOW_API_CONNECT = 13,
NATIVE_WINDOW_API_DISCONNECT = 14,
NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS = 15,
NATIVE_WINDOW_SET_POST_TRANSFORM_CROP = 16,
NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM = 17,
NATIVE_WINDOW_SET_SIDEBAND_STREAM = 18,
NATIVE_WINDOW_SET_BUFFERS_DATASPACE = 19,
NATIVE_WINDOW_SET_SURFACE_DAMAGE = 20,
NATIVE_WINDOW_SET_SHARED_BUFFER_MODE = 21,
NATIVE_WINDOW_SET_AUTO_REFRESH = 22,
NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION = 23,
NATIVE_WINDOW_GET_NEXT_FRAME_ID = 24,
NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS = 25,
NATIVE_WINDOW_GET_COMPOSITOR_TIMING = 26,
NATIVE_WINDOW_GET_FRAME_TIMESTAMPS = 27,
NATIVE_WINDOW_GET_WIDE_COLOR_SUPPORT = 28,
NATIVE_WINDOW_GET_HDR_SUPPORT = 29,
NATIVE_WINDOW_SET_USAGE64 = ANATIVEWINDOW_PERFORM_SET_USAGE64,
NATIVE_WINDOW_GET_CONSUMER_USAGE64 = 31,
NATIVE_WINDOW_SET_BUFFERS_SMPTE2086_METADATA = 32,
NATIVE_WINDOW_SET_BUFFERS_CTA861_3_METADATA = 33,
NATIVE_WINDOW_SET_BUFFERS_HDR10_PLUS_METADATA = 34,
NATIVE_WINDOW_SET_AUTO_PREROTATION = 35,
NATIVE_WINDOW_GET_LAST_DEQUEUE_START = 36,
NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT = 37,
NATIVE_WINDOW_GET_LAST_DEQUEUE_DURATION = 38,
NATIVE_WINDOW_GET_LAST_QUEUE_DURATION = 39,
NATIVE_WINDOW_SET_FRAME_RATE = 40,
NATIVE_WINDOW_SET_CANCEL_INTERCEPTOR = 41,
NATIVE_WINDOW_SET_DEQUEUE_INTERCEPTOR = 42,
NATIVE_WINDOW_SET_PERFORM_INTERCEPTOR = 43,
NATIVE_WINDOW_SET_QUEUE_INTERCEPTOR = 44,
NATIVE_WINDOW_ALLOCATE_BUFFERS = 45,
NATIVE_WINDOW_GET_LAST_QUEUED_BUFFER = 46,
NATIVE_WINDOW_SET_QUERY_INTERCEPTOR = 47,
// clang-format on
};*/
/*FOR REFERENCE
* parameter for NATIVE_WINDOW_SET_SCALING_MODE
* keep in sync with Surface.java in frameworks/base
enum {
//the window content is not updated (frozen) until a buffer of
//the window size is received (enqueued)
NATIVE_WINDOW_SCALING_MODE_FREEZE = 0,
//the buffer is scaled in both dimensions to match the window size
NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW = 1,
//the buffer is scaled uniformly such that the smaller dimension
//of the buffer matches the window size (cropping in the process)
NATIVE_WINDOW_SCALING_MODE_SCALE_CROP = 2,
//the window is clipped to the size of the buffer's crop rectangle; pixels
//outside the crop rectangle are treated as if they are completely
//transparent.
NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP = 3,
};
*/
//process the next main command
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
//get our custom state engine that's attached to the passed android_app
auto * __restrict const engine = (struct engine *) app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
// The system has asked us to save our current state. Do so.
engine->app->savedState = malloc(sizeof(struct saved_state));
*((struct saved_state*)engine->app->savedState) = engine->state;
engine->app->savedStateSize = sizeof(struct saved_state);
break;
//if initialize window has been called for. The window is being shown, get it ready.
case APP_CMD_INIT_WINDOW:
LOGI("CMD_INIT_WINDOW found");
//make sure engine->app->window is non-null
if (engine_have_a_window(engine))
{
//ORIGINAL
/*
engine_init_display(engine);
engine->renderer = new Renderer(1080, 2280);
LOGI("New REnderer created");
engine_draw_frame(engine);*/
#ifndef OG
LOGI("INIT_WINDOW: Getting initial format");
engine->initial_window_format = ANativeWindow_getFormat(app->window);
LOGI("INIT_WINDOW: Setting buffer user dimensions to 2x");
//set buffer user dimensions (trickles down to initial gralloc allocation request)
engine->app->window->perform(engine->app->window, 15, 2280 * 2, 1080 * 2); //2160, 4560
#else
//This one probably shouldn't be used, because it sets users dimensions, format, and scaling mode all in one
//LOGI("INIT_WINDOW: setBuffersGeomoetry");
ANativeWindow_setBuffersGeometry(app->window, ANativeWindow_getWidth(app->window) , ANativeWindow_getHeight(app->window) ,WINDOW_FORMAT_RGB_565);
#endif
#ifndef OG
LOGI("INIT_WINDOW: Setting scaling mode...");
//set scaling mode to crop no scale
engine->app->window->perform(engine->app->window, 10, 3);
LOGI("INIT_WINDOW: Setting color format");
//set color format
engine->app->window->perform(engine->app->window, 9, WINDOW_FORMAT_RGB_565);
ANativeWindow_Buffer buffer;
LOGI("INIT_WINDOW: calling ANativeWindow_lock()");
//make sure we can lock this ANativeWindow_Buffer so that we can edit pixels
if (ANativeWindow_lock(engine->app->window, &buffer, nullptr) < 0)
{
LOGI("Could not lock the window... :C\n");
break;
}
//draw text once
auto* current_pixel = (window_pixel_t *)buffer.bits;
//draw white background
for (int i = 0; i < 1080 * 2280 * 4; i++) {
current_pixel[i] = pixel_colors[4];
}
//draw actual text from the json coords
drawText(200, 425, pixel_colors[2], current_pixel, buffer.stride);
//adjust the crop of the GraphicBuffer
LOGI("Calling set crop to crop size of screen\n");
engine->app->window->perform(engine->app->window, 3, &test_rect);
//LOGI("INIT_WINDOW: calling ANativeWindow_unlockAndPost()");
//release the lock on our window's buffer and post the window to the screen
//ANativeWindow_unlockAndPost(engine->app->window);
engine->app->window->perform(engine->app->window, 48, false);
#endif
//LOGI("engine_draw_frame for init_window");
engine_draw_frame(engine);
first = 0;
}
break;
//window shutdown has been called for. The window is being hidden or closed, clean it up.
case APP_CMD_TERM_WINDOW:
//ORIGINAL
/*if (engine->renderer) {
auto* pRenderer = reinterpret_cast<Renderer*>(engine->renderer);
engine->renderer = nullptr;
delete pRenderer;
}
engine_term_display(engine);*/
engine_term_display(engine);
ANativeWindow_setBuffersGeometry(app->window, ANativeWindow_getWidth(app->window), ANativeWindow_getHeight(app->window), engine->initial_window_format);
break;
//When the app comes into focus (I think this is like onResume())
case APP_CMD_GAINED_FOCUS:
//When our app gains focus, we start monitoring the accelerometer.
if (engine->accelerometerSensor != nullptr) {
//Enable the accelerometer sensor
ASensorEventQueue_enableSensor(engine->sensorEventQueue, engine->accelerometerSensor);
// We'd like to get 60 events per second (in us).
ASensorEventQueue_setEventRate(engine->sensorEventQueue, engine->accelerometerSensor,(1000L/60)*1000);
}
break;
//When our app loses focus, we stop monitoring the accelerometer.
//This is to avoid consuming battery while app is not being used.
case APP_CMD_LOST_FOCUS:
//disable accelerometer
if (engine->accelerometerSensor != nullptr) {
ASensorEventQueue_disableSensor(engine->sensorEventQueue, engine->accelerometerSensor);
}
//Stop animating
engine->animating = 0;
engine_draw_frame(engine);
break;
//"else"
default:
break;
}
}
/*
* AcquireASensorManagerInstance(void)
* Workaround ASensorManager_getInstance() deprecation false alarm
* for Android-N and before, when compiling with NDK-r15
*/
#include <dlfcn.h>
ASensorManager* AcquireASensorManagerInstance(android_app* app) {
//make sure the passed ptr to android_app is non-null
if (!app)
return nullptr;
typedef ASensorManager* (*PF_GETINSTANCEFORPACKAGE)(const char *name);
void* androidHandle = dlopen("libandroid.so", RTLD_NOW);
auto getInstanceForPackageFunc = (PF_GETINSTANCEFORPACKAGE) dlsym(androidHandle, "ASensorManager_getInstanceForPackage");
if (getInstanceForPackageFunc) {
JNIEnv* env = nullptr;
app->activity->vm->AttachCurrentThread(&env, nullptr);
jclass android_content_Context = env->GetObjectClass(app->activity->clazz);
jmethodID midGetPackageName = env->GetMethodID(android_content_Context,"getPackageName","()Ljava/lang/String;");
auto packageName = (jstring)env->CallObjectMethod(app->activity->clazz, midGetPackageName);
const char *nativePackageName = env->GetStringUTFChars(packageName, nullptr);
ASensorManager* mgr = getInstanceForPackageFunc(nativePackageName);
env->ReleaseStringUTFChars(packageName, nativePackageName);
app->activity->vm->DetachCurrentThread();
if (mgr) {
dlclose(androidHandle);
return mgr;
}
}
typedef ASensorManager *(*PF_GETINSTANCE)();
auto getInstanceFunc = (PF_GETINSTANCE) dlsym(androidHandle, "ASensorManager_getInstance");
//By all means at this point, ASensorManager_getInstance should be available
assert(getInstanceFunc);
dlclose(androidHandle);
return getInstanceFunc();
}
//************************MAIN FXN**************************************************************************************************************************
/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
* event loop for receiving input events and doing other things.
*
* The android_native_app_glue library calls this fxn, passing it a predefined state structure. It also serves as a wrapper that simplifies handling of NativeActivity callbacks.
*/
void android_main(struct android_app* state) {
//allocate memory on the heap for a window_pixel_t buffer 4x the size of screen
large_buff = (window_pixel_t *)malloc(sizeof(window_pixel_t) * 2280 * 1080 * 4);
get_txt_coords();
//Next, the program handles events queued by the glue library. The event handler follows the state structure.
//initialize a blank engine struct
struct engine engine = {nullptr};
//application can place a pointer to its own state object in userData (userData is just a void*)
state->userData = &engine;
//set callback function for activity lifecycle events (e.g. "pause", "resume")
state->onAppCmd = engine_handle_cmd;
//set callback fxn for input events coming from the AInputQueue attached to the activity
state->onInputEvent = engine_handle_input;
//assign our engine's "struct android_app" instance as the one that was passed into this function
engine.app = state;
//prep to monitor accelerometer
//get an instance of SensorManager and assign it to the engine
engine.sensorManager = AcquireASensorManagerInstance(state);
//get the accelerometer and assign it to the engine
engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,ASENSOR_TYPE_ACCELEROMETER);
//create a sensor EventQueue using our app's ALooper and the SensorManager we got
engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager, state->looper, LOOPER_ID_USER,nullptr, nullptr);
//possibly restore engine.state from a previously saved state
if (state->savedState != nullptr) {
//We are starting with a previous saved state; restore from it.
engine.state = *(struct saved_state*)state->savedState;
}
//Next, a loop begins, in which application polls system for messages (sensor events). It sends messages to android_native_app_glue, which checks to see whether they
//match any onAppCmd events defined in android_main. When a match occurs, the message is sent to the handler for execution
//int result = system("sh /system/bin/stop vendor.hwcomposer-2-4");
//LOGI("Result of call is %d", result);
//loop waiting for stuff to do.
while (true) {
//Read all pending events.
int ident;
int events;
//this will be filled by ALooper_pollAll
struct android_poll_source* source;
/*ALooper_pollOnce() fxn
Waits for events to be available, with optional timeout in milliseconds.
Invokes callbacks for all file descriptors on which an event occurred.
If the timeout is zero, returns immediately without blocking. If the timeout is negative, waits indefinitely until an event appears.
Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before the timeout expired and no callbacks were invoked and no other file descriptors were ready.
Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
Returns ALOOPER_POLL_TIMEOUT if there was no data before the given timeout expired.
Returns ALOOPER_POLL_ERROR if an error occurred.
Returns a value >= 0 containing an identifier (the same identifier ident passed to ALooper_addFd()) if its file descriptor has data and
it has no callback function (requiring the caller here to handle it).
In this (and only this) case, outFd, outEvents and outData will contain the poll events and data associated with the fd, otherwise they will be set to NULL.
This method does not return until it has finished invoking the appropriate callbacks for all file descriptors that were signalled.
*/
//ALooper_pollAll() is like ALooper_pollOnce(), but performs all pending callbacks until all data has been consumed or a file descriptor is available with no callback.
//It will never return ALOOPER_POLL_CALLBACK
//If not animating, we will block forever waiting for events.
//If animating, we loop until all events are read, then continue to draw the next frame of animation.
while ((ident = ALooper_pollAll(engine.animating ? 0 : -1, nullptr, &events, (void **) &source)) >= 0) //outFd, outEvents, outData
{
//A return value >=0 means we need to handle the callback. outFd, outEvents, and outData now contain the poll events and data associated with the file descriptor
//Process this event, which will call appropriate engine_handle_ fxn
if (source != nullptr) {
source->process(state, source);
}
//If a sensor has data, process it now.
if (ident == LOOPER_ID_USER) {
//make sure we've assigned the engine an accelerometerSensor and it's non-null
if (engine.accelerometerSensor != nullptr) {
//new ASensorEvent
ASensorEvent event;
//get one single ASensorEvent off the queue
while (ASensorEventQueue_getEvents(engine.sensorEventQueue, &event, 1) > 0) {
//log the accelerometer data
//LOGI("accelerometer: x=%f y=%f z=%f", event.acceleration.x, event.acceleration.y, event.acceleration.z);
}
}
}
//Check if we are exiting
if (state->destroyRequested != 0) {
LOGI("Engine thread destroy requested!");
//terminate the display and return
engine_term_display(&engine);
return;
}
}
//Once queue is empty, and the program exits the polling loop, the program calls OpenGL (or in our case uses ANativeWindow) to draw the screen
//see if we're animating, and draw the next frame if so
if (engine.animating) {
//Done with events; draw next animation frame
engine.state.angle += .01f;
if (engine.state.angle > 1) {
engine.state.angle = 0;
}
// Drawing is throttled to the screen update rate, so there is no need to do timing here.
//LOGI("Engine animating");
engine_draw_frame(&engine);
}
}
}
/*A little about Looper, Handler, Messages/MessageQueue...
*
* Looper can be attached to a background thread to manage a MessageQueue and constantly read the queue executing the queued work.
* Only one Looper and one MessageQueue per thread.
* A Handler is part of a thread and associated with the thread's looper. There can be multiple Handlers per thread.
* The Handler can post runnables (using post() method) to be queued and run by the Looper
* The Handler's handleMessages() callback fxn can be configured so that Messages with data can be sent to the background thread from outside that thread using the Handler's sendMessage() fxn.
*
* */
//********************************************************END MAIN FXN**********************************************************
//END_INCLUDE(all)
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_compare.dir/test_compare.c.o"
"test_compare"
"test_compare.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_compare.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_parse.dir/test_parse.c.o"
"test_parse"
"test_parse.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_parse.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include "Renderer.h"
//--------------------------------------------------------------------------------
// Teapot model data
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Constructor
//--------------------------------------------------------------------------------
Renderer::Renderer(int w, int h) {
LOGI("Renderer calling Init");
Init(w, h);
}
//--------------------------------------------------------------------------------
// Deconstructor
//--------------------------------------------------------------------------------
Renderer::~Renderer() {};
//error logging
static void printGLString(const char *name, GLenum s) {
const char *v = (const char *) glGetString(s);
LOGI("GL %s = %s\n", name, v);
}
static void checkGlError(const char* op) {
for (GLint error = glGetError(); error; error = glGetError()) {
LOGI("after %s() glError (0x%x)\n", op, error);
}
}
auto gVertexShader =
"attribute vec4 vPosition;\n"
"void main() {\n"
" gl_Position = vPosition;\n"
"}\n";
auto gFragmentShader =
"precision mediump float;\n"
"void main() {\n"
" gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
//create and compile a single shader code
GLuint loadShader(GLenum shaderType, const char* pSource) {
LOGI("Running glCreateShader...");
GLuint shader = glCreateShader(shaderType);
LOGI("glCreateShader done");
if (shader) {
LOGE("glCreateShader worked");
glShaderSource(shader, 1, &pSource, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen) {
char* buf = (char*) malloc(infoLen);
if (buf) {
glGetShaderInfoLog(shader, infoLen, NULL, buf);
LOGE("Could not compile shader %d:\n%s\n",
shaderType, buf);
free(buf);
}
glDeleteShader(shader);
shader = 0;
}
}
}
else {
LOGE("glCreateShader failed");
}
return shader;
}
//link the shader program and attach the shaders
GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) {
LOGI("Welcome to createProgram");
GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
if (!vertexShader) {
LOGE("Vertexshader NULL after loadShader");
return 0;
}
LOGI("Running loadShader...");
GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
if (!pixelShader) {
return 0;
}
GLuint program = glCreateProgram();
if (program) {
glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
glLinkProgram(program);
GLint linkStatus = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
LOGI("linkStatus NOT GL_TRUE");
GLint bufLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
if (bufLength) {
char* buf = (char*) malloc(bufLength);
if (buf) {
glGetProgramInfoLog(program, bufLength, NULL, buf);
LOGE("Could not link program:\n%s\n", buf);
free(buf);
}
}
glDeleteProgram(program);
program = 0;
}
LOGI("createProgram all good");
}
return program;
}
static float triangleCoords[] = { // in counterclockwise order:
20.0f, 20.0f, 0.0f, // top
15.0f, 0.0, 0.0f, // bottom left
15.0f, 15.0, 0.0f // bottom right
};
/*
static float triangleCoords[] = { // in counterclockwise order:
0.5f, 0.5f,
0.0f, 0.0f, //top, bottom left, bottom right
1.0f, 0.0f
};
*/
/*
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.25f,
-0.5f, -0.25f, //top, bottom left, bottom right
0.5f, -0.25f
};
*/
bool Renderer::Init(int w, int h) {
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
printGLString("Extensions", GL_EXTENSIONS);
LOGI("Init(%d, %d)", w, h);
//create an entire drawing program
gProgram = createProgram(gVertexShader, gFragmentShader);
if (!gProgram) {
LOGE("Could not create program.");
return false;
}
LOGI("Attempting glGetAttribLocation");
gvPositionHandle = glGetAttribLocation(gProgram, "vPosition");
LOGI("glGetAttribLocation done");
checkGlError("glGetAttribLocation");
LOGI("glGetAttribLocation(\"vPosition\") = %d\n",
gvPositionHandle);
glViewport(0, 0, w, h);
checkGlError("glViewport");
return true;
}
void Renderer::UpdateViewport() {
// Init Projection matrices
int32_t viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
}
void Renderer::Unload() {
if (vbo_) {
glDeleteBuffers(1, &vbo_);
vbo_ = 0;
}
if (ibo_) {
glDeleteBuffers(1, &ibo_);
ibo_ = 0;
}
if (shader_param_.program_) {
glDeleteProgram(shader_param_.program_);
shader_param_.program_ = 0;
}
}
void Renderer::Update(float fTime) {
}
void Renderer::Render() {
static float grey;
grey += 0.01f;
if (grey > 1.0f) {
grey = 0.0f;
}
glClearColor(grey, grey, grey, 1.0f);
checkGlError("glClearColor");
glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
checkGlError("glClear");
glUseProgram(gProgram);
checkGlError("glUseProgram");
glVertexAttribPointer(gvPositionHandle, 2, GL_FLOAT, GL_FALSE, 0, triangleCoords);
checkGlError("glVertexAttribPointer");
glEnableVertexAttribArray(gvPositionHandle);
checkGlError("glEnableVertexAttribArray");
glDrawArrays(GL_TRIANGLES, 0, 3);
checkGlError("glDrawArrays");
}<file_sep>set(CMAKE_HOST_SYSTEM "Linux-5.8.0-41-generic")
set(CMAKE_HOST_SYSTEM_NAME "Linux")
set(CMAKE_HOST_SYSTEM_VERSION "5.8.0-41-generic")
set(CMAKE_HOST_SYSTEM_PROCESSOR "x86_64")
include("/home/nodog/VENV/opt/android-ndk-r15c/build/cmake/android.toolchain.cmake")
set(CMAKE_SYSTEM "Android-21")
set(CMAKE_SYSTEM_NAME "Android")
set(CMAKE_SYSTEM_VERSION "21")
set(CMAKE_SYSTEM_PROCESSOR "x86_64")
set(CMAKE_ANDROID_NDK "/home/nodog/VENV/opt/android-ndk-r15c")
set(CMAKE_ANDROID_STANDALONE_TOOLCHAIN "")
set(CMAKE_ANDROID_ARCH "x86_64")
set(CMAKE_ANDROID_ARCH_ABI "x86_64")
set(CMAKE_ANDROID_ARCH_HEADER_TRIPLE "x86_64-linux-android")
set(CMAKE_ANDROID_NDK_DEPRECATED_HEADERS "0")
set(CMAKE_CROSSCOMPILING "TRUE")
set(CMAKE_SYSTEM_LOADED 1)
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/test_charcase.dir/test_charcase.c.o"
"test_charcase"
"test_charcase.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/test_charcase.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
|
97ea0eeb200aa3fc8f2f2bdf509c80b7422c05a3
|
[
"Markdown",
"CMake",
"C++"
] | 19
|
CMake
|
serviceberry3/android_native_win_buff
|
b93a32eb8f5641bf4a0ca580a0264af511d968e5
|
6be089a10559833eff069d1f7da27bffea836050
|
refs/heads/master
|
<file_sep>import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser as wb
import os
import pyautogui
import psutil
import pyjokes
engine = pyttsx3.init()
def speak(audio):
engine.say(audio)
engine.runAndWait()
def time():
time = datetime.datetime.now().strftime("%I:%M:%S")
speak("The current time is")
speak(time)
def date():
year = int(datetime.datetime.now().year)
month = int(datetime.datetime.now().month)
date = int(datetime.datetime.now().day)
speak("Today's date is")
speak(date)
speak(month)
speak(year)
def wishme():
speak("Welcome back sir!")
time()
date()
hour = datetime.datetime.now().hour
if hour >= 6 and hour<12:
speak("Good Morning Sir!")
elif hour >= 12 and hour<15:
speak("Good afternoon Sir!")
elif hour >= 15 and hour<19:
speak("Good Evening Sir!")
else:
speak("Good Night Sir!")
speak("This is PINN at your service, How can I help You Sir??")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening....")
r.pause_threshold = 0.5
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"User said:{query}\n")
except Exception as e:
print(e)
speak("Anything else Sir?")
return "None"
return query
def screenshot():
img = pyautogui.screenshot()
img.save("C:\\Users\\dharm\\Desktop\\AI Assistant\\ss.png")
def cpu():
usage = str(psutil.cpu_percent())
speak('Cpu usage is'+ usage)
def jokes():
speak(pyjokes.get_joke())
if __name__ == "__main__":
wishme()
while True:
query = takeCommand().lower()
if 'time' in query:
time()
elif 'date' in query:
date()
elif 'wikipedia' in query:
speak("Searching")
query = query.replace("wikipedia","")
result = wikipedia.summary(query, sentences=2)
print(result)
speak(result)
elif 'search in chrome' in query:
speak("What should i search sir?")
chromepath = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
search = takeCommand().lower()
wb.get(chromepath).open_new_tab(search + '.com')
elif 'logout' in query:
os.system("shutdown -l")
elif 'shutdown' in query:
os.system("shutdown /s /t 1")
elif 'restart' in query:
os.system("shutdown /r /t 1")
elif 'play songs' in query:
songs_dir = 'D:\\Music'
songs = os.listdir(songs_dir)
os.startfile(os.path.join(songs_dir, songs[0]))
elif 'remember that' in query:
speak("What should i remember sir??")
data = takeCommand()
speak("You told to remember"+data)
remember = open('data.txt', 'w')
remember.write(data)
remember.close()
elif 'do you remember what i told you before' in query:
remember =open('data.txt', 'r')
speak("Yes Sir, You told me that..."+remember.read())
elif 'take screenshot' in query:
screenshot()
speak("Done Sir!")
elif 'cpu' in query:
cpu()
elif 'jokes' in query:
jokes()
elif 'offline' in query:
speak("Ok Sir")
quit()
<file_sep># AI-Assistant-PINN
# Introduction
PINN is an simple open-source AI assistant which can be customised
He does stuff when you ask him for.
# Commands
He Can take screenshots
He can ShutDown/Restart/Sleep the system
He can send E-Mails to other persons
He can open certain websites from the web
He can save the data for you
He can tell you automated jokes ( Which is Somewhat funny Lol Xd)
He Can read certain documents for you
# Why?
If you are a developer (or not), you may want to build many things that could help in your daily life. Instead of building a dedicated project for each of those ideas, PINN can help you with his packages/modules (skills) structure.
With this generic structure, everyone can create their own modules and share them with others. Therefore there is only one core (to rule them all).
PINN uses AI concepts, which is pretty cool & simple.
# What is this repository for?
This repository contains the following nodes of PINN:
PINN.py
# Installation
Download the repositories as zip https://github.com/aarkeshsharma/AI-Assistant-PINN.git
Download Microsoft VS Code for Smooth Functioning
# Author
aarkeshsharma
# License
Copyright (c) 2020-present, <NAME> <EMAIL>
|
22d663275f5bb2bcb940dd8b714a04f6bcf1c5a4
|
[
"Markdown",
"Python"
] | 2
|
Python
|
aarkeshsharma/AI-Assistant-PINN
|
0886438dbfec0dcd205d94873338c0cbe1309bd0
|
fd804d1b84cbbae638d95f48742e91350b189b37
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react'
import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
export class Home extends Component {
render() {
return (
<div>
<Button>Home</Button>
</div>
)
}
}
export default Home
|
4b8cbc92cbe11c72c309b05722b68349a8dd1265
|
[
"JavaScript"
] | 1
|
JavaScript
|
SVinay27/gitdemo
|
7cb6145945e2d6381e28dc723d5aebc5bdb2d266
|
34dcb6bbda5781ccf4012e168ba79a3e950aac2c
|
refs/heads/master
|
<file_sep>package com.icebns.web;
import com.icebns.pojo.User;
import com.icebns.service.UserService;
import com.icebns.service.UserServiceImpl;
import com.icebns.utils.CookieUtils;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException{
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException,ServletException{
servletRequest.setCharacterEncoding("utf-8");
// UserService service = new UserServiceImpl();
// HttpServletRequest req = (HttpServletRequest)servletRequest;
// HttpSession session = req.getSession();
// User user = (User)session.getAttribute("sessionuser");
// Cookie[] cookies = req.getCookies();
// Map<String,Cookie> cookieMap = CookieUtils.toCookie(cookies);
//// Cookie cookie = cookieMap.get("username");
// if (user == null){
// Cookie cookie = cookieMap.get("username");
// if (cookie==null){
// req.getRequestDispatcher("index.jsp").forward(req,servletResponse);
// filterChain.doFilter(servletRequest,servletResponse);
// }else{
// String username = cookie.getValue();
// User selectuser = service.getUserByUsername(username);
// if (selectuser==null){
// req.getRequestDispatcher("index.jsp").forward(req,servletResponse);
// filterChain.doFilter(servletRequest,servletResponse);
// }else{
// session.setAttribute("sessionuser",selectuser);
// filterChain.doFilter(servletRequest,servletResponse);
// }
// }
// }else{
filterChain.doFilter(servletRequest,servletResponse);
// }
// if (cookie==null){
// req.getRequestDispatcher("index.jsp").forward(req,servletResponse);
// }else if(user!=null){
// req.getRequestDispatcher("main.jsp").forward(req,servletResponse);
// }else{
// String username = cookie.getValue();
// User selectuser = service.getUserByUsername(username);
// if (selectuser==null){
// req.getRequestDispatcher("index.jsp").forward(req,servletResponse);
//
// }else{
// session.setAttribute("sessionuser",user);
// }
// }
// System.out.println(c.getName());
//
// filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
<file_sep>package com.icebns.web;
import com.icebns.service.IregisterService;
import com.icebns.service.PayService;
import com.icebns.service.PayServiceImpl;
import com.icebns.service.RegisterServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class PayItWeb extends HttpServlet {
private PayService service = new PayServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer costId = Integer.parseInt(req.getParameter("costId"));
System.out.println(costId);
int a = service.change(costId);
System.out.println("改变"+a);
resp.sendRedirect("/getPay");
}
}
<file_sep>package com.icebns.web;
import com.icebns.pojo.User;
import com.icebns.service.UserService;
import com.icebns.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginWeb extends HttpServlet {
private UserService service = new UserServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer userType = Integer.parseInt(req.getParameter("userType"));
String userName = req.getParameter("userName");
String password = req.getParameter("password");
// System.out.println(userType+userName+password);
User user = service.getUser(userName,password,userType);
if(user==null){
String message = "填写有误!";
req.setAttribute("mess",message);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}else if(user.getDelMark()==0){
String message = "用户已注销";
req.setAttribute("mess",message);
req.getRequestDispatcher("index.jsp").forward(req,resp);
} else if(userType==1){
String message = "你好,管理员用户:";
req.setAttribute("mess",message);
req.setAttribute("type",userType);
req.setAttribute("username",userName);
HttpSession session = req.getSession();
session.setAttribute("sessionuser",user);
req.getRequestDispatcher("main.jsp").forward(req,resp);
}else if(userType==2) {
String message = "你好,挂号员用户:";
req.setAttribute("type",userType);
req.setAttribute("mess",message);
req.setAttribute("username",userName);
HttpSession session = req.getSession();
session.setAttribute("sessionuser",user);
req.getRequestDispatcher("main.jsp").forward(req,resp);
// resp.sendRedirect("main.jsp");
}
else if(userType==3) {
String message = "你好,医生用户:";
req.setAttribute("type",userType);
req.setAttribute("mess",message);
req.setAttribute("username",userName);
HttpSession session = req.getSession();
session.setAttribute("sessionuser",user);
req.getRequestDispatcher("main.jsp").forward(req,resp);
// resp.sendRedirect("main.jsp");
}
}
}
<file_sep>package servlet;
import model.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class LoginCl extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
// public void doPost(HttpServletRequest request, HttpServletResponse response)
// throws ServletException, IOException {
//
// response.setContentType("text/html");
// response.setCharacterEncoding("utf-8");
// PrintWriter out = response.getWriter();
//
//
// //得到用户名和密码
// String u=request.getParameter("username");
// String p=request.getParameter("password");
//
//
// //验证用户
// UserBeanBO ubb=new UserBeanBO();
//
// if(ubb.checkUser(u, p)){
// //用户合法
// request.getRequestDispatcher("MedicineSelectServlet").forward(request, response);
// }else{
// //用户不合法
//
// request.getRequestDispatcher("login.jsp").forward(request, response);
//
// }
// }
}
<file_sep>package com.icebns.web;
import com.icebns.pojo.User;
import com.icebns.service.UserService;
import com.icebns.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class AddUserWeb extends HttpServlet {
private UserService service = new UserServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("AddUserWeb begin");
String userName = req.getParameter("userName");
String passwd = req.getParameter("passwd");
Integer userType = Integer.parseInt(req.getParameter("userType"));
User user = new User();
user.setUserName(userName);
user.setPassword(<PASSWORD>);
user.setUserType(userType);
System.out.println(user);
int a = service.add(user);
System.out.println(a);
resp.sendRedirect("addcount.jsp");
}
}
<file_sep>package servlet;
import model.UserBean;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
public class MedicineDelServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ArrayList<UserBean> list = new ArrayList<UserBean>();
request.setAttribute("list", list);
request.getRequestDispatcher("showuser.jsp").forward(request, response);
}
}
<file_sep>/**
* 这是一个model 代表着数据库中的users表
*/
package model;
import entity.User;
public class UserBean {
private long userId ;
private String username ;
private String passwd ;
private String realName;
private Integer userType;
private Integer docTitleid;
private String isScheduling;
private Integer deptId;
private Integer delMark;
private Integer registLeid;
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public Integer getDelMark() {
return delMark;
}
public void setDelMark(Integer delMark) {
this.delMark = delMark;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public UserBean(long userId, String username, String passwd, Integer userType, Integer delMark) {
super();
this.userId = userId;
this.username = username;
this.passwd = <PASSWORD>;
this.userType = userType;
this.delMark = delMark;
}
// public UserBeanShow(long userId, String username, String passwd, Integer userType, String delMark) {
// super();
// this.userId = userId;
// this.username = username;
// this.passwd = <PASSWORD>;
// this.userType = userType;
// this.delMark = na;
//
// }
//
// public UserBeanNew(long userId, String username, String passwd) {
// super();
// this.userId = userId;
// this.username = username;
// this.passwd = <PASSWORD>;
// }
public UserBean() {
super();
// TODO Auto-generated constructor stub
}
public User User(UserBean user) {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>package com.icebns.service;
import com.icebns.dao.MediDao;
import com.icebns.dao.MediDaoImpl;
import entity.Medicine;
public class MediServiceImpl implements MediService {
private MediDao dao = new MediDaoImpl();
@Override
public int add(Medicine medi) {
return dao.add(medi);
}
}
<file_sep>package com.icebns.service;
import com.icebns.pojo.User;
public interface UserService {
public User getUser(String userName, String password, Integer userType);
public User getUserByUsername(String username);
public int add(User user);
}
<file_sep>package com.icebns.service;
import entity.Medicine;
public interface MediService {
public int add(Medicine medi);
}
<file_sep>package com.icebns.service;
import com.icebns.pojo.Register;
import java.util.List;
public interface IregisterService {
public int add(Register register);
public int del(String caseNumber);
public Register getOne(String caseNumber);
}
<file_sep>package com.icebns.service;
import com.icebns.pojo.Pay;
public interface PayService {
public int add(Pay pay);
public int del(Integer costId);
public Pay getTwo(String caseNumber);
public Pay getAll(String caseNumber);
public int change(Integer costId);
}
<file_sep>package com.icebns.utils;
import com.mysql.jdbc.Driver;
import java.sql.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class JdbcUtils {
//静态代码块,只执行一次
private static final String URL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
private static final String USER="root";
private static final String PWD="<PASSWORD>";
static {
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(URL,USER,PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
private static void close(ResultSet rs,PreparedStatement pstmt,Connection conn){
try {
if(rs != null) {
rs.close();
}
if (pstmt!=null){
pstmt.close();
}
if (conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static int excuteUpdate(String sql,Object...objs){
int result = 0;
Connection conn = null;
PreparedStatement pstm = null;
try{
conn = getConnection();
pstm = conn.prepareStatement(sql);
for (int i=0;i<objs.length;i++){
pstm.setObject(i+1,objs[i]);
}
result = pstm.executeUpdate();
System.out.println("excuteUpdate result:"+result+"pstm:"+pstm+"conn:"+conn);
System.out.println("pstm:"+pstm);
System.out.println("conn:"+conn);
conn.close();
}catch(SQLException e){
e.printStackTrace();
}finally {
close(null,pstm,conn);
}
return result;
}
// 泛型<T>
public static <T> List<T> excuteQuery(String sql,RowMap<T> rowMap,Object...objs){
List<T> lists = new ArrayList<T>();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(URL,USER,PWD);
pstm = conn.prepareStatement(sql);
if (objs!=null){
for (int i=0;i<objs.length;i++){
pstm.setObject(i+1,objs[i]);
}
}
rs = pstm.executeQuery();
while (rs.next()){
T t = rowMap.rowMapping(rs);
lists.add(t);
}
//查询
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(null,pstm,conn);
}
return lists;
}
public static <T> T queryOne(String sql,RowMap<T> rowMap,Object...objs){
T t = null;
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(URL,USER,PWD);
pstm = conn.prepareStatement(sql);
if (objs!=null){
for (int i=0;i<objs.length;i++){
pstm.setObject(i+1,objs[i]);
}
}
rs = pstm.executeQuery();
while (rs.next()){
t = rowMap.rowMapping(rs);
}
//查询
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(null,pstm,conn);
}
return t;
}
}
// static {
// //加载驱动
// try {
// Class.forName("com.mysql.jdbc.Driver");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
//
//// try {
//// Class.forName("com.mysql.jdbc.Driver");
//// } catch (ClassNotFoundException e) {
//// e.printStackTrace();
//// }
//// try {
//// new Driver();
//// } catch (SQLException e) {
//// e.printStackTrace();
//// }
// }
// private static Connection getConnection(){
// Connection conn = null;
// try {
// conn = DriverManager.getConnection(URL,USER,PWD);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return conn;
// }
// private static void close(ResultSet rs,PreparedStatement pstmt,Connection conn){
// try {
// if(rs != null){
// rs.close();
// }
// if(pstmt != null){
// pstmt.close();
// }
// if (conn != null){
// conn.close();
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// public void add(String sql, Object... objs) {
// System.out.println(sql);
// Connection conn = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement(sql);
// for(int i =0;i<objs.length;i++){
// pstm.setObject(i+1,objs[i]);
// }
// int result=pstm.executeUpdate();
// System.out.println(result);
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(null,pstm,conn);
// }
// }
// public void update() {
// Connection conn = null;
//// Statement state = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement("update `test`.`names` set name=? where id = ?");
// pstm.setString(1,"b5");
// pstm.setInt(2,5);
//// String sql = "update `test`.`names` set name='张武阳' where id = 2";
//// int result = state.executeUpdate(sql);
// int result = pstm.executeUpdate();
// System.out.println(result);
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(null,pstm,conn);
// }
// }
// public void delete() {
// Connection conn = null;
//// Statement state = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement("delete from `test`.`names` where id = ?");
// pstm.setInt(1,6);
//// String sql = "delete from `test`.`names` where id = 1";
// int result = pstm.executeUpdate();
// System.out.println(result);
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(null,pstm,conn);
// }
// }
//
// //泛型,定义时不指定数据实际类型,在使用时再指明实际类型。
//// public interface List<E> extends Collection<E> {
//// int size();
//// }
// public static <T> List<T> excuteQuery(String sql, RowMap<T> rowMap, Object... objs) {
// List<T> lists = new ArrayList<T>();
// Connection conn = null;
//// Statement state = null;
// ResultSet rs = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement(sql);
// if(objs!=null){
// for(int i =0;i<objs.length;i++){
// pstm.setObject(i+1,objs[i]);
// }
// }
// rs = pstm.executeQuery();
// while (rs.next()){
// T t = rowMap.rowMapping(rs);
// lists.add(t);
// }
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(rs,pstm,conn);
// }
// return lists;
// }
//
//
// public static <T> List<T> excuteQuery(String sql, RowMap<T> rowMap, Object... objs) {
// List<T> t = new ArrayList<T>();
// Connection conn = null;
//// Statement state = null;
// ResultSet rs = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement(sql);
// if(objs!=null){
// for(int i =0;i<objs.length;i++){
// pstm.setObject(i+1,objs[i]);
// }
// }
// rs = pstm.executeQuery();
// while (rs.next()){
// T t = rowMap.rowMapping(rs);
//
// }
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(rs,pstm,conn);
// }
// return t;
// }
//
// public static int excuteUpdate(String sql,Object... objs) {
// int result = 0;
// Connection conn = null;
//// Statement state = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement("update `test`.`names` set name=? where id = ?");
// pstm.setString(1,"b5");
// pstm.setInt(2,5);
// result = pstm.executeUpdate();
// System.out.println(result);
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(null,pstm,conn);
// }
// return result;
// }
// public void insert() {
// Connection conn = null;
// PreparedStatement pstm = null;
// try {
// conn = getConnection();
// pstm = conn.prepareStatement("insert into `test`.`names`(name,age) value(?,?)");
// pstm.setString(1,"ab3");
// pstm.setInt(2,5);
// int result=pstm.executeUpdate();
// System.out.println(result);
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(null,pstm,conn);
// }
// }
//}
<file_sep>package com.icebns.web;
import com.icebns.pojo.Pay;
import com.icebns.service.PayService;
import com.icebns.service.PayServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class PutPayWeb extends HttpServlet {
private PayService service = new PayServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("PutPayWebbegin");
String caseNumber = req.getParameter("caseNumber");
System.out.println("caseNumber"+caseNumber);
String realName = req.getParameter("realName");
String costName = req.getParameter("costName");
Integer costPay = Integer.parseInt(req.getParameter("costPay"));
Integer costNumber = Integer.parseInt(req.getParameter("costNumber"));
String costState = req.getParameter("costState");
Calendar calendar= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(calendar.getTime()));
String costTime = dateFormat.format(calendar.getTime());
System.out.println("--发票号-"+0+"--病历号-"+caseNumber+"--姓名-"+realName+"--costName-"+
costName+"--costPay-"+costPay+"--costNumber-"+costNumber+"--costState-"+costState+"--costTime-"+costTime
);
Pay pay = new Pay();
pay.setCaseNumber(caseNumber);
pay.setRealName(realName);
pay.setCostName(costName);
pay.setCostPay(costPay);
pay.setCostNumber(costNumber);
pay.setCostState(costState);
pay.setCostTime(costTime);
System.out.println("pay="+pay);
int a = service.add(pay);
System.out.println(a);
resp.sendRedirect("getPay");
}
}
<file_sep>package com.icebns.web;
import com.icebns.service.PayService;
import com.icebns.service.PayServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class delPayWeb extends HttpServlet {
private PayService service = new PayServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer costId = Integer.parseInt(req.getParameter("costId"));
System.out.println(costId);
int a = service.del(costId);
System.out.println("删除cost"+a);
resp.sendRedirect("getPay");
}
}
<file_sep>//得到数据库的链接
package model;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnDB {
private Connection ct = null;
public Connection getConn() {
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 得到链接
Connection ct = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/Hospital", "root", "<PASSWORD>");
return ct;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return ct;
}
}
<file_sep>package com.icebns.dao;
import com.icebns.pojo.User;
import com.icebns.service.UserService;
import com.icebns.utils.JdbcUtils;
import com.icebns.utils.RowMap;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
public User getUser(String userName, String password, Integer userType){
return JdbcUtils.queryOne("select * from user where user_name=?and password=?and user_type=?", new RowMap<User>(){
@Override
public User rowMapping(ResultSet rs) {
User user = new User();
try {
user.setRealName(rs.getString("real_name"));
user.setId(rs.getInt("id"));
user.setUserName(rs.getString("user_name"));
user.setPassword(<PASSWORD>("<PASSWORD>"));
user.setUserType(rs.getInt("user_type"));
user.setDocTitleid(rs.getInt("doc_titleid"));
user.setIsScheduling(rs.getString("is_scheduling"));
user.setDeptId(rs.getInt("dept_id"));
user.setRegistLeid(rs.getInt("regist_leid"));
user.setDelMark(rs.getInt("del_mark"));
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}, userName,password,userType);
}
@Override
public User getUserByUsername(String username) {
return JdbcUtils.queryOne("select * from user where user_name=?", new RowMap<User>(){
@Override
public User rowMapping(ResultSet rs) {
User user = new User();
try {
user.setId(rs.getInt("id"));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.<PASSWORD>("<PASSWORD>"));
user.setUserType(rs.getInt("user_type"));
user.setDocTitleid(rs.getInt("doc_titleid"));
user.setIsScheduling(rs.getString("is_scheduling"));
user.setDeptId(rs.getInt("dept_id"));
user.setRegistLeid(rs.getInt("regist_leid"));
user.setDelMark(rs.getInt("del_mark"));
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}, username);
}
@Override
public int add(User user) {
return JdbcUtils.excuteUpdate("INSERT INTO `user`(`user_name`, `password`, `user_type`, `del_mark`)" +
" VALUES ( ?,?,?,1);",user.getUserName(),
user.getPassword(),user.getUserType());
}
}
<file_sep>package com.icebns.dao;
import com.icebns.pojo.Register;
public interface RegisterDao {
public int add(Register register);
public Register getOne(String caseNumber);
public int remove(String caseNumber);
}
<file_sep>package dao;
import entity.Medicine;
import java.sql.SQLException;
import java.util.ArrayList;
public class MedicineDao extends BaseDao {
public ArrayList<Medicine> select(String mname, int priceFrom, int priceTo) {
ArrayList<Medicine> list = new ArrayList<Medicine>();
String sql = "select * from Medicine where 1=1";
if (!mname.equals("")) {
sql += " and mname like ?";
}
if (priceFrom != 0) {
sql += " and mprice > ?";
}
if (priceTo != 0) {
sql += " and mprice < ?";
}
try {
this.getCon();
ps = con.prepareStatement(sql);
int i = 1;
if (!mname.equals("")) {
ps.setString(i++, "%" + mname + "%");
}
if (priceFrom != 0) {
ps.setInt(i++, priceFrom);
}
if (priceTo != 0) {
ps.setInt(i++, priceTo);
}
rs = ps.executeQuery();
while(rs.next()){
Medicine m = new Medicine(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),rs.getInt(5),rs.getInt(6), rs.getString(7), rs.getString(8));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeAll();
}
return list;
}
public Medicine getById(int id) {
Medicine m = null;
String sql = "select * from Medicine where mid=?";
try {
this.getCon();
ps = con.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
while(rs.next()){
m = new Medicine(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),rs.getInt(5),rs.getInt(6), rs.getString(7), rs.getString(8));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeAll();
}
return m;
}
public int add(Medicine m) {
String sql = "insert into Medicine values(null,?,?,?,?,?,?,?)";
return this.execute(sql, m.getMname(), m.getMsort(), m.getMshop(), m.getMcount(), m.getMprice(), m.getMdesc(), m.getMphoto());
}
public int addcount(Medicine m) {
String sql = "update Medicine set mcount=? where mid=?";
return this.execute(sql, m.getMprice(), m.getMid());
}
public int update(Medicine m) {
String sql = "update Medicine set mname=?, msort=?, mshop=?, mcount=?, mprice=?, mdesc=?, mphoto=? where mid=?";
return this.execute(sql, m.getMname(), m.getMsort(), m.getMshop(), m.getMcount(), m.getMprice(), m.getMdesc(), m.getMphoto(), m.getMid());
}
public int delete(int id) {
String sql = "delete from Medicine where mid=?";
return this.execute(sql, id);
}
}
<file_sep>package com.icebns.web;
import com.icebns.pojo.Register;
import com.icebns.service.IregisterService;
import com.icebns.service.RegisterServiceImpl;
import com.sun.javaws.exceptions.JRESelectException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import static com.sun.deploy.config.JREInfo.getAll;
public class RegisterListWeb extends HttpServlet{
// private IregisterService service = new RegisterServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// List<Register> registers = service.getAll();
// req.setAttribute("registers",registers);
req.getRequestDispatcher("register.jsp").forward(req,resp);
}
}
<file_sep>package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UserBeanBO {
private ResultSet rs = null;
private Connection ct = null;
private PreparedStatement ps = null;
public UserBean getUserBean(String u){
UserBean ub=new UserBean();
try {
ct=new ConnDB().getConn();
ps=ct.prepareStatement("select * from users where username=?");
ps.setString(1, u);
rs=ps.executeQuery();
if(rs.next()){
ub.setUserId(rs.getLong(1));
ub.setUsername(rs.getString(2));
ub.setPasswd(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally{
this.close();
}
return ub;
}
public boolean checkUser(String u, String p) {
boolean b = false;
try {
ct=new ConnDB().getConn();
ps=ct.prepareStatement("select passwd from users where username=?");
ps.setString(1,u);
rs=ps.executeQuery();
if(rs.next()){
//取出数据库中的密码
String dbPasswd=rs.getString(1);
if(dbPasswd.equals(p)){
b=true;
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
} finally {
//关闭资源
this.close();
}
return b;
}
// 关闭资源
public void close() {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (ps != null) {
ps.close();
ps = null;
}
if (!ct.isClosed()) {
ct.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
<file_sep>package com.icebns.pojo;
public class Pay {
private Integer costId;
private String caseNumber;
private String realName;
private String costName;
private Integer costPay;
private Integer costNumber;
private String costTime;
private String costState;
public Integer getCostId() {
return costId;
}
public void setCostId(Integer costId) {
this.costId = costId;
}
public String getCaseNumber() {
return caseNumber;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getCostName() {
return costName;
}
public void setCostName(String costName) {
this.costName = costName;
}
public Integer getCostPay() {
return costPay;
}
public void setCostPay(Integer costPay) {
this.costPay = costPay;
}
public Integer getCostNumber() {
return costNumber;
}
public void setCostNumber(Integer costNumber) {
this.costNumber = costNumber;
}
public String getCostTime() {
return costTime;
}
public void setCostTime(String costTime) {
this.costTime = costTime;
}
public String getCostState() {
return costState;
}
public void setCostState(String costState) {
this.costState = costState;
}
@Override
public String toString() {
return "Pay{" +
"costId=" + costId +
", caseNumber='" + caseNumber + '\'' +
", realName='" + realName + '\'' +
", costName='" + costName + '\'' +
", costPay=" + costPay +
", costNumber=" + costNumber +
", costTime='" + costTime + '\'' +
", costState='" + costState + '\'' +
'}';
}
}
<file_sep>package com.icebns.service;
import com.icebns.dao.RegisterDao;
import com.icebns.dao.RegisterDaoImpl;
import com.icebns.pojo.Register;
import java.util.List;
public class RegisterServiceImpl implements IregisterService {
private RegisterDao dao = new RegisterDaoImpl();
@Override
public int add(Register register) {
return dao.add(register);
}
@Override
public int del(String caseNumber) {
return dao.remove(caseNumber);
}
@Override
public Register getOne(String caseNumber) {
return dao.getOne(caseNumber);
}
}
<file_sep>package com.icebns.test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class TestWeb extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
// System.out.println("执行了");
// PrintWriter pw = resp.getWriter();
// pw.print("success");
List<String> lists = new ArrayList<>();
for(int i = 0;i<100;i++){
lists.add(i+"abc");
}
req.setAttribute("data",lists);
req.getRequestDispatcher("test.jsp").forward(req,resp);
}
}
<file_sep>package servlet;
import dao.MedicineDao;
import entity.Medicine;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
public class MedicineInventory extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
MedicineDao md = new MedicineDao();
String mname = "";
if (request.getParameter("keyname") != null && request.getParameter("keyname") != "") {
mname = request.getParameter("keyname");
}
int priceFrom = 0;
if (request.getParameter("priceFrom") != null && request.getParameter("priceFrom") != "") {
priceFrom = Integer.parseInt(request.getParameter("priceFrom"));
}
int priceTo = 0;
if (request.getParameter("priceTo") != null && request.getParameter("priceTo") != "") {
priceTo = Integer.parseInt(request.getParameter("priceTo"));
}
ArrayList<Medicine> list = md.select(mname, priceFrom, priceTo);
request.setAttribute("keyname", mname);
request.setAttribute("priceFrom", priceFrom);
request.setAttribute("priceTo", priceTo);
request.setAttribute("list", list);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
<file_sep>package servlet;
import dao.UserDao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserOpenServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
UserDao md = new UserDao();
int mid = Integer.parseInt(request.getParameter("userId"));
int result = md.update(mid);
System.out.println("update = [" + result + "]");
request.getRequestDispatcher("UserSelectServlet").forward(request, response);
}
}
<file_sep>package com.icebns.web;
import com.icebns.pojo.Register;
import com.icebns.service.IregisterService;
import com.icebns.service.RegisterServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class delRegisterWeb extends HttpServlet {
private IregisterService service = new RegisterServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String caseNumber = req.getParameter("caseNumber");
System.out.println(caseNumber);
int a = service.del(caseNumber);
System.out.println("删除"+a);
resp.sendRedirect("/getRegister");
}
}
|
016aecf8556c1232a48d78f9ce95f32e65a4a7fa
|
[
"Java"
] | 27
|
Java
|
icebns/HisTest
|
1a481d3b06e36db70fc105ccfe6b66b71e40ba65
|
b8f8621ee2a8332b9d26159ce9b3a6835a345d72
|
refs/heads/master
|
<repo_name>harryac07/kukhura-ui<file_sep>/src/components/login/index.js
import React, { Component } from 'react'
import { compose } from "redux";
import { connect } from "react-redux";
import { withRouter } from 'react-router-dom'
import LoginForm from './component/LoginForm'
import { Divider } from 'components/common/components/Divider'
import SloganBanner from 'components/common/components/SloganBanner'
import { authenticateUser } from './action'
class Login extends Component {
constructor(props) {
super(props);
}
handleLogin = (credentials) => {
this.props.authenticateUser(credentials);
}
render() {
const { router, login } = this.props;
const { loggedIn } = login;
if (loggedIn) {
this.props.history.push('/admin')
// return;
}
return (
<div>
{/* Login form */}
<LoginForm handleLogin={this.handleLogin} />
<Divider />
{/* Slogan banner */}
<SloganBanner
bgImageUrl="https://dummyimage.com/1200x300/cccccc/000.jpg"
sloganText="Consume fresh egg everyday! Quality can't be compromised."
textSizeLevel={2}
/>
</div>
)
}
}
const mapStateToProps = state => {
return {
login: state.login,
router: state.router
};
};
const withConnect = connect(mapStateToProps, {
authenticateUser
});
export default compose(withRouter, withConnect)(Login);
<file_sep>/src/components/about/component/WhatWeOffer.js
import React from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import ImageTitleTextButton from 'components/common/components/ImageTitleTextButton'
import Title from 'components/common/components/Title'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
const useStyles = makeStyles(theme => ({
maindiv: {
padding: '100px 0px',
width: '100%',
background: '#f0f0f0'
},
}));
const WhatWeCanOffer = (props) => {
const classes = useStyles();
return (
<ComponentWrapper backgroundColor="#f0f0f0">
<Title text={"What we can offer"} padding={"0px 0px 24px 0px"} />
<Grid container spacing={3}>
<Grid item xs={12} sm={3}>
<ImageTitleTextButton
bgImageUrl={"https://dummyimage.com/250x250/cccccc/000.jpg"}
title={"VESTIBULUM ANTE IPSUM PRIMIS"}
text={"Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae Suspendisse sollicitudin velit sed leo."}
button={true}
buttonText={"read more"}
textBgColor={"#f0f0f0"}
/>
</Grid>
<Grid item xs={12} sm={3}>
<ImageTitleTextButton
bgImageUrl={"https://dummyimage.com/250x250/cccccc/000.jpg"}
title={"VESTIBULUM ANTE IPSUM PRIMIS"}
text={"Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae Suspendisse sollicitudin velit sed leo."}
button={true}
buttonText={"read more"}
textBgColor={"#f0f0f0"}
/>
</Grid>
<Grid item xs={12} sm={3}>
<ImageTitleTextButton
bgImageUrl={"https://dummyimage.com/250x250/cccccc/000.jpg"}
title={"VESTIBULUM ANTE IPSUM PRIMIS"}
text={"Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae Suspendisse sollicitudin velit sed leo."}
button={true}
buttonText={"read more"}
textBgColor={"#f0f0f0"}
/>
</Grid>
<Grid item xs={12} sm={3}>
<ImageTitleTextButton
bgImageUrl={"https://dummyimage.com/250x250/cccccc/000.jpg"}
title={"VESTIBULUM ANTE IPSUM PRIMIS"}
text={"Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae Suspendisse sollicitudin velit sed leo."}
button={true}
buttonText={"read more"}
textBgColor={"#f0f0f0"}
/>
</Grid>
</Grid>
</ComponentWrapper>
)
}
export default WhatWeCanOffer<file_sep>/src/components/common/components/ComponentWrapper.js
import React from 'react'
import { WrapperDiv } from 'components/common/commonStyle'
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => ({
maindiv: {
padding: '100px 0px',
width: '100%',
background: props => props.backgroundColor ? props.backgroundColor : '#fff',
color: props => props.color
},
}));
/**
* ComponentWrapper
* @param {node}children - children node
*/
const ComponentWrapper = ({ children, backgroundColor, color }) => {
const classes = useStyles({ backgroundColor, color });
return (
<div className={classes.maindiv}>
<WrapperDiv>
{children}
</WrapperDiv>
</div>
);
}
ComponentWrapper.propTypes = {
children: PropTypes.node.isRequired
};
export default ComponentWrapper;<file_sep>/src/components/home/component/NewsAndOffer.js
import React from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import { StyledLink } from 'components/common/components/Link'
import Title from 'components/common/components/Title'
import { makeStyles } from '@material-ui/core/styles';
import { Grid, Typography } from '@material-ui/core';
import moment from 'moment';
import { truncate } from 'lodash';
const useStyles = makeStyles(theme => ({
textBold: {
fontWeight: 'bold'
},
item: {
position: 'relative',
padding: '30px 0px 0px 0px',
minHeight: 150,
background: '#fff',
color: '#000'
},
serviceTextColor: {
color: '#7c7c7c'
}
}));
const NewsAndOffer = ({ recentPosts }) => {
const classes = useStyles();
return (
<ComponentWrapper>
<Title text={"News and offers"} />
<Grid container spacing={3}>
{
/* Loop through recent posts */
recentPosts.map(each => {
const {
id = "",
title = "",
description = "",
post_primary_image = "https://dummyimage.com/250x250/cccccc/000.jpg",
created = ""
} = each;
return (
<Grid item xs={12} sm={4} key={id}>
<div className={classes.item}>
<StyledLink to={'/blog/' + id}>
<Typography className={classes.textBold} variant="p">
{
truncate(title.toUpperCase() || "", {
'length': 80,
})
}
</Typography>
</StyledLink>
<p>{moment(created).format('LL')}</p>
<p className={classes.serviceTextColor}>
{
truncate(description || "", {
'length': 150,
})
}
</p>
</div>
</Grid>
);
})
}
</Grid>
</ComponentWrapper>
)
}
export default NewsAndOffer<file_sep>/src/components/common/components/SloganBanner.js
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components';
import { Typography } from '@material-ui/core';
const SloganDiv = styled.div`
background-image: ${props => props.bgImageUrl ? props.bgImageUrl : ''};
background-repeat: no-repeat;
background-size: 100% 100%;
min-height: 300px;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
h2{
font-weight: inherit;
@media (max-width: 768px) {
font-size: 2rem;
}
}
`;
/**
* SloganBanner
* @param {String}bgImageUrl - background image url
*/
const SloganBanner = ({ bgImageUrl, sloganText, textSizeLevel }) => {
const variantLevel = textSizeLevel || 2
return (
<SloganDiv bgImageUrl={`url("${bgImageUrl}")`}>
<Typography variant={`h${variantLevel}`}>
{sloganText}
</Typography>
</SloganDiv>
);
}
SloganBanner.propTypes = {
bgImageUrl: PropTypes.string,
sloganText: PropTypes.string,
textSizeLevel: PropTypes.number || PropTypes.string
};
export default SloganBanner;<file_sep>/src/components/common/components/Title.js
import React from 'react'
import PropTypes from 'prop-types'
import { P } from 'components/common/commonStyle'
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => ({
titleText: {
marginTop: 0,
},
}));
/**
* Title
* @param {String}padding - Not required if called inside MUI Grid
* @param {String}text - Title text
* @param {String}fontSize - Default fontsize is 36px. Override default
*/
const Title = ({ padding, text, fontSize = "36px" }) => {
const classes = useStyles();
return (
<P
padding={padding ? padding : "0px"}
display="block"
fontSize={fontSize}
className={classes.titleText}
>
{text}
</P>
);
}
Title.propTypes = {
text: PropTypes.string,
padding: PropTypes.string
};
export default Title;<file_sep>/src/components/home/reducer.js
import { TEST_SUCCEED, TEST_REQUEST, GET_RECENT_POSTS_SUCCEED } from './constant'
const initialState = {
test: '',
loading: false,
recentPosts: []
}
const homeReducer = (state = initialState, action) => {
switch (action.type) {
case TEST_REQUEST:
return {
...state,
loading: true
}
case TEST_SUCCEED:
return {
...state,
test: action.payload,
loading: false
}
case GET_RECENT_POSTS_SUCCEED:
return {
...state,
recentPosts: action.payload
}
default:
return state;
}
}
export default homeReducer<file_sep>/src/components/blogDetail/action.js
import { FETCH_BLOG_DETAIL, CREATE_BLOG_POST_COMMENT, CREATE_POST_COMMENT_REPLY } from './constant'
export const fetchBlogDetail = (id, type = "blog") => {
return {
type: FETCH_BLOG_DETAIL,
data: {
id,
type
}
}
}
export const createPostComment = (data, type = "blog") => {
return {
type: CREATE_BLOG_POST_COMMENT,
data: {
data,
type
}
}
}
export const createCommentReply = (data, postId, type = "blog") => {
return {
type: CREATE_POST_COMMENT_REPLY,
data: {
postId,
data,
type
}
}
}<file_sep>/src/components/blogDetail/saga.js
import { call, put, takeEvery } from "redux-saga/effects";
import axios from "axios"
import { API_URL } from 'env'
import {
FETCH_BLOG_DETAIL_SUCCEED,
FETCH_BLOG_DETAIL_FAILED,
FETCH_BLOG_DETAIL,
CREATE_BLOG_POST_COMMENT,
CREATE_BLOG_POST_COMMENT_SUCCEED,
CREATE_BLOG_POST_COMMENT_FAILED,
CREATE_POST_COMMENT_REPLY,
CREATE_POST_COMMENT_REPLY_SUCCEED,
CREATE_POST_COMMENT_REPLY_FAILED
} from "./constant"
const fetchBlogById = ({ type, id }) => {
const postTypeUrl = type === 'product'
? 'products'
: 'blogposts'
return axios
.get(`${API_URL}/${postTypeUrl}/${id}/`)
.then(response => {
return response.data
});
};
export function* fetchBlogByIdSaga(action) {
try {
const data = yield call(fetchBlogById, action.data);
yield put({
type: FETCH_BLOG_DETAIL_SUCCEED,
payload: data
});
} catch (error) {
yield put({
type: FETCH_BLOG_DETAIL_FAILED,
error: 'Something went wrong!'
});
}
}
/* create comment */
const createBlogPostComment = ({ data }) => {
return axios
.post(`${API_URL}/comments/`, data)
.then(response => {
return response.data
});
};
export function* createBlogPostCommentSaga(action) {
try {
const data = yield call(createBlogPostComment, action.data);
yield put({
type: CREATE_BLOG_POST_COMMENT_SUCCEED,
payload: data
});
/* fetch blogpost again to include comment */
yield put({
type: FETCH_BLOG_DETAIL,
data: {
id: action.data.data.blogpost,
type: action.data.type
}
});
} catch (error) {
yield put({
type: CREATE_BLOG_POST_COMMENT_FAILED,
error: 'Something went wrong!'
});
}
}
/* Create comment reply */
/* create comment */
const createPostCommentReply = ({ data }) => {
return axios
.post(`${API_URL}/reply/`, data)
.then(response => {
return response.data
});
};
export function* createPostCommentReplySaga(action) {
try {
const data = yield call(createPostCommentReply, action.data);
yield put({
type: CREATE_POST_COMMENT_REPLY_SUCCEED,
payload: data
});
/* fetch blogpost again to include comment */
yield put({
type: FETCH_BLOG_DETAIL,
data: {
id: action.data.postId,
type: action.data.type
}
});
} catch (error) {
yield put({
type: CREATE_POST_COMMENT_REPLY_FAILED,
error: 'Something went wrong!'
});
}
}
export const blogDetailSaga = [
takeEvery(FETCH_BLOG_DETAIL, fetchBlogByIdSaga),
takeEvery(CREATE_BLOG_POST_COMMENT, createBlogPostCommentSaga),
takeEvery(CREATE_POST_COMMENT_REPLY, createPostCommentReplySaga),
];
<file_sep>/src/components/admin/index.js
import React, { Component } from 'react';
import styled from 'styled-components';
import { Tabs, Tab, Paper } from '@material-ui/core';
import { compose } from "redux";
import { connect } from "react-redux";
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import Profile from './component/Profile'
import CreatePost from './component/CreatePost'
import { fetchPostCategories, createPost } from './action'
import { checkAuthentication } from '../login/action';
import { OrangeButton } from 'components/common/components/Button'
class Admin extends Component {
constructor(props) {
super(props);
this.state = {
selectedValue: 0
}
}
componentDidMount() {
const auth_token = localStorage.getItem('auth_token');
if (!auth_token) {
this.handleLogout();
return;
} else {
/* check authentication */
this.props.checkAuthentication();
}
this.props.fetchPostCategories();
}
handleChange = (e, newValue) => {
e.preventDefault();
this.setState({
selectedValue: newValue
})
}
handleLogout = () => {
localStorage.clear();
this.props.history.push('/');
}
render() {
const { postCategories, post_created } = this.props.admin;
const { loggedIn } = this.props.login;
/* redirect to home page if not logged in */
if (!loggedIn) {
this.handleLogout();
return <p />;
}
return (
<ComponentWrapper>
{/* Tab menu */}
<Paper elevation={3}>
<div style={{ position: 'relative' }}>
<Tabs
value={this.state.selectedValue}
indicatorColor="primary"
textColor="primary"
onChange={this.handleChange}
>
<Tab label="Profile" />
<Tab label="Posts" />
<Tab label="More" />
<OrangeButton
Primary={true}
style={{
backgroundColor: '#f65314',
position: 'relative',
padding: '5px',
fontSize: '16px',
position: 'absolute',
right: '30px',
top: '5px',
textTransform: 'capitalize'
}}
onClick={this.handleLogout}
>
Logout
</OrangeButton>
</Tabs>
</div>
</Paper>
<Wrapper>
{
this.state.selectedValue === 0
? <Profile />
: this.state.selectedValue === 1
? <CreatePost
postCategories={postCategories}
createPost={this.props.createPost}
post_created={post_created}
/>
: 'Noooo'
}
</Wrapper>
</ComponentWrapper>
)
}
}
const mapStateToProps = state => {
return {
app: state.home,
admin: state.admin,
router: state.router,
login: state.login,
};
};
const withConnect = connect(mapStateToProps, {
fetchPostCategories,
createPost,
checkAuthentication
});
export default compose(withConnect)(Admin);
const Wrapper = styled.div`
margin: 20px auto;
`;<file_sep>/src/components/about/component/AboutOurFarm.js
import React from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import TitleTextButtonfrom from 'components/common/components/ImageTitleTextButton'
import Title from 'components/common/components/Title'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
const useStyles = makeStyles(theme => ({
item: {
position: 'relative',
padding: '30px 0px 0px 0px',
minHeight: 150,
background: '#fff',
color: '#000'
},
backgroundImage: {
background: 'url("https://dummyimage.com/300x250/cccccc/000.jpg")',
backgroundRepeat: 'no-repeat',
backgroundSize: '100% 100%',
minHeight: '230px',
},
spacingColumn: {
[theme.breakpoints.down('md')]: {
display: 'none',
},
[theme.breakpoints.down('sm')]: {
display: 'none',
},
},
}));
const AboutOurFarm = (props) => {
const classes = useStyles();
return (
<ComponentWrapper>
<Title text={"About our farm"} />
<Grid container spacing={3}>
<Grid item xs={12} sm={4}>
<div className={classes.item}>
<div className={classes.backgroundImage} />
</div>
</Grid>
<Grid item xs={12} sm={8}>
<TitleTextButtonfrom
title={"AENEAN AUCTOR WISI ET URNA. ALIQUAM ERAT VOLUTPAT. DUIS AC TURPIS. INTEGER RUTRUM ANTE EU LACUS. LOREM IPSUM DOLOR SIT AMET, CONSECTETUER ADIPISCING ELIT."}
textDom={
<span>
Donec sit amet eros. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris fermentum dictum magna. Sed laoreet aliquam leo. Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit auctor wisi et urna. Aliquam erat volutpat. Duis ac turpis. Integer rutrum ante eu lacus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus hendrerit mauris porta.
<br /><br />
Fusce suscipit varius mi. Quisque nulla. Vestibulum libero nisl, porta vel, scelerisque eget, malesuada at, neque. Vivamus eget nibh. Etiam cursus leo vel metus. Nulla facilisi. Aenean nec eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse sollicitudin velit .
</span>
}
button={false}
buttonText={"read more"}
/>
</Grid>
</Grid>
</ComponentWrapper>
)
}
export default AboutOurFarm<file_sep>/src/components/blog/constant.js
export const FETCH_BLOG_LIST = 'FETCH_BLOG_LIST'
export const FETCH_BLOG_LIST_SUCCEED = 'FETCH_BLOG_LIST_SUCCEED'
export const FETCH_BLOG_LIST_FAILED = 'FETCH_BLOG_LIST_FAILED'
export const SET_BLOG_END_PAGINATION = 'SET_BLOG_END_PAGINATION'<file_sep>/src/components/contact/index.js
import React, { Component } from 'react'
import { Divider } from 'components/common/components/Divider'
import SloganBanner from 'components/common/components/SloganBanner'
import GoogleMap from './component/GoogleMap';
import ContactInfo from './component/ContactDetailAndForm';
class Contact extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{/* Google Map */}
<GoogleMap />
<Divider />
<ContactInfo />
{/* Slogan banner */}
<SloganBanner
bgImageUrl="https://dummyimage.com/1200x300/cccccc/000.jpg"
sloganText="Consume fresh egg everyday! Quality can't be compromised."
textSizeLevel={2}
/>
</div>
)
}
}
export default Contact;<file_sep>/src/components/home/constant.js
export const TEST_REQUEST = 'TEST_REQUEST'
export const TEST_SUCCEED = 'TEST_SUCCEED'
export const TEST_FAILED = 'TEST_FAILED'
export const GET_RECENT_POSTS = 'GET_RECENT_POSTS'
export const GET_RECENT_POSTS_SUCCEED = 'GET_RECENT_POSTS_SUCCEED'
export const GET_RECENT_POSTS_FAILED = 'GET_RECENT_POSTS_FAILED'<file_sep>/src/components/common/components/Button.js
import { Button } from '@material-ui/core';
import { styled, ThemeProvider } from '@material-ui/styles';
export const OrangeButton = styled(Button)({
backgroundColor: props => props.bgColor ? props.bgColor : '#f65314',
padding: props => props.padding ? props.padding : '18px 25px',
display: props => props.display ? props.display : 'inline',
width: props => props.width ? props.width : null,
color: '#fff',
fontWeight: 300,
borderRadius: 0,
fontSize: 18,
'&:hover': {
backgroundColor: props => props.bgColor ? props.bgColor : '#f65314',
},
'@media (max-width: 1280px)': {
padding: '6px 12px',
fontWeight: 200,
borderRadius: 0,
fontSize: 12,
},
'@media (max-width: 960px)': {
padding: '6px 12px',
fontWeight: 200,
borderRadius: 0,
fontSize: 12,
}
});<file_sep>/src/components/blog/reducer.js
import { FETCH_BLOG_LIST, FETCH_BLOG_LIST_SUCCEED, SET_BLOG_END_PAGINATION } from './constant'
import { orderBy } from 'lodash'
import moment from 'moment'
const initialState = {
blogList: [],
loading: false,
heroBlogPost: [], // single most recent post
blogPaginationEndOffset: 4 // bring max 4 posts on first load
}
const blogReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_BLOG_LIST:
return {
...state,
loading: true
}
case FETCH_BLOG_LIST_SUCCEED:
const mostRecentPost = action.payload.filter(each => each.hero_post).sort(
(a, b) => moment(b.created).format('YYYYMMDDHHmmss') - moment(a.created).format('YYYYMMDDHHmmss')
)
return {
...state,
loading: false,
blogList: action.payload.filter(each => !each.hero_post),
blogPaginationEndOffset: action.paginationOffset,
heroBlogPost: mostRecentPost[0]
}
default:
return state;
}
}
export default blogReducer<file_sep>/src/components/admin/constant.js
export const FETCH_POST_CATEGORIES = 'FETCH_POST_CATEGORIES'
export const FETCH_POST_CATEGORIES_SUCCEED = 'FETCH_POST_CATEGORIES_SUCCEED'
export const FETCH_POST_CATEGORIES_FAILED = 'FETCH_POST_CATEGORIES_FAILED'
export const CREATE_POST = 'CREATE_POST'
export const CREATE_POST_SUCCEED = 'CREATE_POST_SUCCEED'
export const CREATE_POST_FAILED = 'CREATE_POST_FAILED'
<file_sep>/src/components/blog/action.js
import { FETCH_BLOG_LIST, SET_BLOG_END_PAGINATION } from './constant'
// blogDetail constant
import { FETCH_BLOG_DETAIL_SUCCEED } from '../blogDetail/constant'
export const fetchBlogList = (pageOffsetEnd = 4) => {
return {
type: FETCH_BLOG_LIST,
pageOffsetEnd
}
}
/* Update reducer in blogDetail view */
export const addSelectedBlogDetail = (data = []) => {
return {
type: FETCH_BLOG_DETAIL_SUCCEED,
payload: data
}
}<file_sep>/src/components/common/header.js
import React, { useState } from 'react'
import { withRouter } from 'react-router-dom'
import { TinyButton as ScrollUpButton } from "react-scroll-up-button";
import imageLogo from './logo.jpg'
import { makeStyles } from '@material-ui/core/styles'
import { Menu } from '@material-ui/icons'
import {
Link
} from "react-router-dom";
const useStyles = makeStyles(theme => ({
mainNav: {
backgroundColor: '#fff',
borderTop: '3px solid red',
borderBottom: '1px solid #c3c3c3',
[theme.breakpoints.down('sm')]: {
borderTop: '1px solid rgba(255, 0, 0, 0.8)',
borderOpacity: 0.1,
borderBottom: 'none',
},
},
navigation: {
display: 'flex',
flexFlow: 'row wrap',
justifyContent: 'flex-end',
listStyle: 'none',
padding: '20px',
'& li': {
marginLeft: '20px',
},
'& li.active > a': {
color: 'red'
},
'& li a': {
textDecoration: 'none',
color: '#7c7c7c',
fontSize: '18px',
lineHeight: '31px',
padding: '40px 18px',
letterSpacing: '1px',
},
'& li:not(:first-child) > a:hover': {
background: '#323232',
border: '#323232',
color: '#fff',
},
'& li:first-child': {
marginRight: 'auto'
},
[theme.breakpoints.down('sm')]: {
flexDirection: 'column',
padding: 0,
backgroundColor: '#49515C',
margin: 0,
'& li:not(:first-child) > a:hover': {
background: 'none',
border: 'none',
},
'& li a': {
textDecoration: 'none',
color: '#fff',
lineHeight: '31px',
padding: '0px 0px',
fontSize: '16px',
}
},
},
showMenuDropdown: {
display: 'block',
},
hideMenuDropdown: {
display: 'none',
[theme.breakpoints.up('md')]: {
display: 'block'
},
},
navigationMenuBar: {
display: 'none',
position: 'relative',
top: 0,
right: 0,
cursor: 'pointer',
padding: '10px 10px 5px 0px',
textAlign: 'right',
backgroundColor: '#49515C',
color: '#eee',
[theme.breakpoints.down('sm')]: {
display: 'block',
cursor: 'pointer',
},
},
logoImage: {
height: '80px',
position: 'absolute',
top: 10,
[theme.breakpoints.down('sm')]: {
display: 'none'
},
},
logoDot: {
position: 'absolute',
top: 25,
left: 90,
fontSize: 40,
fontWeight: 'bold',
color: '#7c7c7c',
[theme.breakpoints.down('sm')]: {
display: 'none'
},
}
}));
const Header = (props) => {
const [activeMenu, setActiveMenu] = useState('logo');
const [mobileView, setMobileView] = useState(false);
const classes = useStyles();
const { pathname = "" } = props.location;
const username = localStorage.getItem('username');
const email = localStorage.getItem('email');
return (
<div>
<div className={classes.navigationMenuBar} onClick={() => setMobileView(!mobileView)}>
<Menu fontSize="large" ></Menu>
</div>
<div className={
`${mobileView
? classes.showMenuDropdown
: classes.hideMenuDropdown} ${classes.mainNav}`}
>
<ul className={classes.navigation}>
<li className="logo" onClick={() => setActiveMenu('home')} >
<Link to="/">
<img
className={classes.logoImage}
src={imageLogo} />
<span
className={classes.logoDot}
>.</span>
</Link>
</li>
<li onClick={() => setActiveMenu('home')}>
<Link
style={pathname === '/' ? { color: 'red' } : {}}
to="/">HOME</Link>
</li>
<li onClick={() => setActiveMenu('about')}>
<Link
style={pathname === '/about' ? { color: 'red' } : {}}
to="/about">ABOUT</Link>
</li>
<li onClick={() => setActiveMenu('products')}>
<Link
style={pathname === '/products' ? { color: 'red' } : {}}
to="/products">PRODUCTS</Link>
</li>
<li onClick={() => setActiveMenu('contact')}>
<Link
style={pathname === '/contact' ? { color: 'red' } : {}}
to="/contact">CONTACT</Link>
</li>
<li onClick={() => setActiveMenu('blog')}>
<Link
style={pathname === '/blog' ? { color: 'red' } : {}}
to="/blog">BLOG</Link>
</li>
{
username && email
? <li onClick={() => setActiveMenu('admin')}>
<Link
style={pathname === '/admin'
? { color: 'red' } : {}
}
to="/admin">
ADMIN (<span style={{color: 'red'}}>{username}</span>)
</Link>
</li>
: null
}
</ul>
</div>
<ScrollUpButton
StopPosition={0}
ShowAtPosition={150}
EasingType='easeOutCubic'
AnimationDuration={500}
style={{ background: '#f65314', color: '#fff', padding: 5 }}
/>
</div>
)
}
export default withRouter(Header)<file_sep>/src/components/Main/reducer.js
import { FETCH_USER, FETCH_USER_SUCCEED } from './constant'
const initialState = {
loading: false,
current_user: []
}
const AppReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_USER:
return {
...state,
loading: true
}
case FETCH_USER_SUCCEED:
return {
...state,
current_user: action.payload,
loading: false
}
default:
return state;
}
}
export default AppReducer<file_sep>/src/components/Main/constant.js
export const FETCH_USER = 'FETCH_USER'
export const FETCH_USER_SUCCEED = 'FETCH_USER_SUCCEED'
export const FETCH_USER_FAILED = 'FETCH_USER_FAILED'<file_sep>/src/components/blogDetail/component/Comment.js
import React, { useState } from 'react'
import { OrangeButton } from 'components/common/components/Button'
import CommentForm from './CommentForm'
import CommentBox from './CommentBox'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import { AddComment } from '@material-ui/icons';
const useStyles = makeStyles(theme => ({
mainDiv: {
marginTop: 30,
[theme.breakpoints.down('sm')]: {
marginTop: 20,
},
},
AddCommentIcon: {
textAlign: 'center',
position: 'relative',
left: 0,
top: 5,
[theme.breakpoints.down('md')]: {
top: 5,
},
}
}));
const Comment = (props) => {
const classes = useStyles();
const { submitComment,dispatchReplyCreate, blogId } = props;
const [showCommentForm, onToggleCommentButton] = useState(false);
return (
<div className={classes.mainDiv}>
{
!showCommentForm
? <OrangeButton
variant="contained"
color="primary"
padding="5px 10px"
className={classes.button}
onClick={() => {
onToggleCommentButton(!showCommentForm);
}}
endIcon={<AddComment
className={classes.AddCommentIcon}
color="#000"
/>}
>
Add comment
</OrangeButton>
: null
}
<Grid container spacing={3}>
{/* Form Grid */}
<Grid item xs={12} sm={12} md={12}>
<br />
{
showCommentForm
? <CommentForm
submitComment={submitComment}
blogId={blogId}
handleCancel={() => {
onToggleCommentButton(!showCommentForm);
}}
/>
: <CommentBox
comments={props.postComments}
dispatchReplyCreate={dispatchReplyCreate}
/>
}
</Grid>
</Grid>
</div>
)
}
export default Comment;<file_sep>/src/components/login/constant.js
export const LOGIN = 'LOGIN'
export const LOGIN_SUCCEED = 'LOGIN_SUCCEED'
export const LOGIN_FAILED = 'LOGIN_FAILED'
export const CHECK_AUTHENTICATION = 'CHECK_AUTHENTICATION'
export const CHECK_AUTHENTICATION_SUCCEED = 'CHECK_AUTHENTICATION_SUCCEED'
export const CHECK_AUTHENTICATION_FAILED = 'CHECK_AUTHENTICATION_FAILED'
export const FETCH_USER = 'FETCH_USER'
export const FETCH_USER_SUCCEED = 'FETCH_USER_SUCCEED'
export const FETCH_USER_FAILED = 'FETCH_USER_FAILED'<file_sep>/src/components/contact/component/ContactDetailAndForm.js
import React, { useState } from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import { OrangeButton } from 'components/common/components/Button'
import Title from 'components/common/components/Title'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import { Typography, TextField, Button, FormControl } from '@material-ui/core';
const useStyles = makeStyles(theme => ({
paraColor: {
color: '#7c7c7c'
},
textField: {
width: '100%',
[`& fieldset`]: {
borderRadius: 0,
},
}
}));
const ContactForm = (props) => {
const classes = useStyles();
const [name, onNameChange] = useState('');
const [phone, onPhoneChange] = useState('');
const [email, onEmailChange] = useState('');
const [message, onMessageChange] = useState('');
const [errorPayload, onErrorFind] = useState({});
/* form rest */
const formReset = () => {
onNameChange('');
onPhoneChange('');
onEmailChange('');
onMessageChange('');
}
/* Handle submit */
const handleSubmit = (e) => {
e.preventDefault();
const payload = {
name, phone, email, message
}
/* Validate Form */
if (!payload.name || !payload.email || !payload.message) {
// ERROR
const errorData = {};
errorData.name = !payload.name ? 'Required' : ''
errorData.email = !payload.email ? 'Required' : ''
errorData.message = !payload.message ? 'Required' : ''
onErrorFind(errorData);
} else {
// NO ERROR
console.log(payload);
formReset();
}
}
return (
<ComponentWrapper>
<Grid container spacing={3}>
{/* Address Grid */}
<Grid item xs={12} sm={3} md={3}>
<Title fontSize={"28px"} text={"Contact Info"} padding={"0px 0px 24px 0px"} />
<Typography variant="paragraph" display="block">
8901 Marmora Road,
<br />
Glasgow, D04 89GR.
</Typography>
<p className={classes.paraColor}>
Freephone: +1 800 559 6580<br />
Telephone: +1 800 603 6035<br />
FAX: +1 800 889 9898<br />
E-mail: <EMAIL><br />
</p>
</Grid>
{/* Form Grid */}
<Grid item xs={12} sm={9} md={9}>
<Title fontSize={"28px"} text={"Give us a feedback"} padding={"0px 0px 24px 0px"} />
<form className={classes.form} noValidate autoComplete="off" onSubmit={e => handleSubmit(e)}>
<FormControl>
<Grid container spacing={2}>
<Grid item xs={12} sm={4} md={4}>
<TextField
value={name}
label="Name"
onChange={(e) => {
onNameChange(e.target.value);
onErrorFind({
...errorPayload,
name: ''
})
}}
className={classes.textField}
margin="normal"
variant="outlined"
error={!!errorPayload.name}
helperText={errorPayload.name}
/>
</Grid>
<Grid item xs={12} sm={4} md={4}>
<TextField
value={email}
label="Email"
onChange={(e) => {
onEmailChange(e.target.value);
onErrorFind({
...errorPayload,
email: ''
})
}}
className={classes.textField}
margin="normal"
variant="outlined"
error={!!errorPayload.email}
helperText={errorPayload.email}
/>
</Grid>
<Grid item xs={12} sm={4} md={4}>
<TextField
value={phone}
label="Phone"
onChange={(e) => onPhoneChange(e.target.value)}
className={classes.textField}
margin="normal"
variant="outlined"
/>
</Grid>
<Grid item xs={12} sm={12} md={12}>
<TextField
value={message}
label="Message"
onChange={(e) => {
onMessageChange(e.target.value);
onErrorFind({
...errorPayload,
message: ''
})
}}
multiline
rows="12"
className={classes.textField}
margin="normal"
variant="outlined"
error={!!errorPayload.message}
helperText={errorPayload.message}
/>
<Grid item xs={12} sm={12} md={12}>
<OrangeButton
Primary={true}
label={"submit"}
type={"submit"}
style={{ backgroundColor: '#f65314' }}
>
Submit
</OrangeButton>
</Grid>
</Grid>
</Grid>
</FormControl>
</form>
</Grid>
</Grid>
</ComponentWrapper>
)
}
export default ContactForm;<file_sep>/src/components/admin/reducer.js
import { FETCH_POST_CATEGORIES_SUCCEED, CREATE_POST, CREATE_POST_SUCCEED, CREATE_POST_FAILED } from './constant'
const initialState = {
loading: false,
postCategories: []
}
const adminReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_POST_CATEGORIES_SUCCEED:
return {
...state,
postCategories: action.payload
}
case CREATE_POST:
return {
...state,
post_created: false
}
case CREATE_POST_SUCCEED:
return {
...state,
post_created: true
}
default:
return state;
}
}
export default adminReducer<file_sep>/src/components/home/component/Products.js
import React from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import TitleTextArrow from 'components/common/components/TitleTextArrow'
import { Grid } from '@material-ui/core';
const Product = (props) => {
return (
<ComponentWrapper>
<Grid container spacing={3}>
<Grid item xs={12} sm={4}>
<TitleTextArrow
title={"Best hens"}
text={"Lorem ipsum dolor sit amet, consetue ipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris."}
arrow={true}
bgColor={"blue"}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TitleTextArrow
title={"Organic eggs"}
text={"Lorem ipsum dolor sit amet, consetue ipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris."}
arrow={true}
bgColor={"green"}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TitleTextArrow
title={"Our farm"}
text={"Lorem ipsum dolor sit amet, consetue ipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris."}
arrow={true}
bgColor={"orange"}
/>
</Grid>
</Grid>
</ComponentWrapper>
)
}
export default Product<file_sep>/src/components/blogDetail/component/CommentForm.js
import React, { useState } from 'react'
import { OrangeButton } from 'components/common/components/Button'
import Title from 'components/common/components/Title'
import { makeStyles } from '@material-ui/core/styles';
import { TextField, FormControl } from '@material-ui/core';
import { Cancel } from '@material-ui/icons';
const useStyles = makeStyles(theme => ({
textField: {
width: '100%',
[`& fieldset`]: {
borderRadius: 0,
},
},
loginForm: {
width: '100%',
margin: '0 auto !important',
[theme.breakpoints.down('sm')]: {
width: '100%',
margin: '0 auto',
},
},
commentForm: {
margin: props => props.margin ? props.margin : '20px auto',
padding: props => props.padding ? props.padding : '20px',
position: 'relative',
backgroundColor: props => props.backgroundColor,
},
CancelIcon: {
position: 'absolute',
color: '#f65314',
right: 20,
cursor: 'pointer',
zIndex: 999,
height: 40,
width: 40,
}
}));
const CommentForm = (props) => {
const classes = useStyles({
backgroundColor: props.backgroundColor ? props.backgroundColor : 'inherit'
});
const {
submitComment,
blogId,
commentId, // only for replying comments
handleCancel,
headerText = "Leave a comment",
headerFontSize = "28px",
headerPadding = "0px 0px 24px 0px"
} = props;
const [email, onEmailChange] = useState('');
const [comment, onCommentChange] = useState('');
const [errorPayload, onErrorFind] = useState({});
/* form rest */
const formReset = () => {
onEmailChange('');
onCommentChange('');
}
/* Handle submit */
const handleSubmit = (e) => {
e.preventDefault();
const payload = {
email,
comment,
blogpost: blogId
}
/* Validate Form */
if (!payload.email || !payload.comment) {
// ERROR
const errorData = {};
errorData.email = !payload.email ? 'Email required' : ''
errorData.comment = !payload.comment ? 'Comment required' : ''
onErrorFind(errorData);
} else {
// Submit comment or reply
if (commentId) {
payload.reply = payload.comment;
payload.comment = commentId;
delete payload.blogpost;
}
submitComment(payload)
formReset();
}
}
return (
<form
className={classes.commentForm}
noValidate
autoComplete="off"
onSubmit={e => handleSubmit(e)}
>
<Cancel
className={classes.CancelIcon}
onClick={() => handleCancel()}
/>
<FormControl fullWidth className={classes.loginForm}>
<Title
fontSize={headerFontSize}
text={headerText}
padding={headerPadding}
/>
<TextField
value={email}
label="Email"
required
onChange={(e) => {
onEmailChange(e.target.value);
onErrorFind({
...errorPayload,
email: ''
})
}}
type="email"
className={classes.textField}
margin="normal"
variant="outlined"
error={!!errorPayload.email}
helperText={errorPayload.email}
/>
<TextField
value={comment}
label="Comment"
required
name="comment"
onChange={(e) => {
onCommentChange(e.target.value);
onErrorFind({
...errorPayload,
comment: ''
})
}}
className={classes.textField}
margin="normal"
variant="outlined"
multiline
rowsMax={10}
rows={6}
error={!!errorPayload.comment}
helperText={errorPayload.comment}
/>
<OrangeButton
Primary={true}
display={'inline-block'}
width={'100%'}
label={"submit"}
type={"submit"}
style={{
backgroundColor: '#f65314',
marginTop: '16px'
}}
>
Submit
</OrangeButton>
</FormControl>
</form>
)
}
export default CommentForm;<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, compose, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { routerMiddleware, ConnectedRouter } from 'connected-react-router'
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history'
import { toast } from 'react-toastify';
import rootReducer from 'store/reducers'
import saga from 'store/sagas'
import './index.css';
import App from 'components/Main';
import * as serviceWorker from './serviceWorker';
/* react loader spinner CSS */
import "react-loader-spinner/dist/loader/css/react-spinner-loader.css"
/* react toastify css */
import 'react-toastify/dist/ReactToastify.css';
// configure react toastify
toast.configure()
const history = createBrowserHistory()
// create the saga middleware
const sagaMiddleware = createSagaMiddleware()
// redux dev tool
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer(history), // root reducer with router state
composeEnhancers(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
sagaMiddleware,
// ... other middlewares ...
)
)
);
// run the saga
sagaMiddleware.run(saga)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register();
<file_sep>/src/components/blog/index.js
import React, { Component } from 'react'
import { compose } from "redux";
import { connect } from "react-redux";
import { take } from 'lodash'
import Bloglist from './component/Bloglist'
import LatestPost from './component/LatestPost'
import { Divider } from 'components/common/components/Divider'
import SloganBanner from 'components/common/components/SloganBanner'
import Loader from 'components/common/components/CommonLoader'
import { fetchBlogList, addSelectedBlogDetail } from './action'
class Blog extends Component {
constructor(props) {
super(props);
this.state = {
morePostRequested: false
}
}
componentDidMount() {
//Dispatch action
this.props.fetchBlogList();
}
loadMoreBlogPosts = () => {
const { blogPaginationEndOffset } = this.props.blog;
//Dispatch action
this.props.fetchBlogList(blogPaginationEndOffset + 4);
this.setState({
morePostRequested: true
});
}
render() {
const {
blogList,
blogPaginationEndOffset,
heroBlogPost,
loading } = this.props.blog;
const { history } = this.props;
if (blogList.length === 0) {
return <Loader showLoader={true} />
}
return (
<div>
{/* Recent post */}
<LatestPost
recentPost={heroBlogPost}
history={history}
addSelectedBlogDetail={this.props.addSelectedBlogDetail}
/>
{/* Newsroom bloglist */}
<Bloglist
blogList={take(blogList, blogPaginationEndOffset)}
loadMoreBlogPosts={this.loadMoreBlogPosts}
isMoreBlog={blogPaginationEndOffset < blogList.length}
addSelectedBlogDetail={this.props.addSelectedBlogDetail}
history={history}
morePostRequestedLoading={this.state.morePostRequested && loading}
/>
<Divider />
{/* Slogan banner */}
<SloganBanner
bgImageUrl="https://dummyimage.com/1200x300/cccccc/000.jpg"
sloganText="Consume fresh egg everyday! Quality can't be compromised."
textSizeLevel={2}
/>
</div>
)
}
}
const mapStateToProps = state => {
return {
blog: state.blog,
router: state.router
};
};
const withConnect = connect(mapStateToProps, {
fetchBlogList,
addSelectedBlogDetail
});
export default compose(withConnect)(Blog);<file_sep>/src/components/common/components/TitleTextArrow.js
import React from 'react'
import PropTypes from 'prop-types'
import { P } from 'components/common/commonStyle'
import { makeStyles } from '@material-ui/core/styles';
import { Typography } from '@material-ui/core';
import { ArrowForward } from '@material-ui/icons';
const useStyles = makeStyles(theme => ({
item: {
background: '#00a1f1',
position: 'relative',
borderRadius: 10,
padding: '30px 35px 30px 35px',
color: '#fff',
minHeight: 150,
[theme.breakpoints.down('md')]: {
padding: '30px 10px',
height: 'auto',
},
[theme.breakpoints.down('sm')]: {
padding: '20px 10px',
height: 'auto',
minHeight: 200,
},
},
arrowIcon: {
fontWeight: 67,
},
blueBackground: {
background: '#00a1f1',
},
greenBackground: {
background: '#7cbb00', // f65314 // #7cbb00
},
orangeBackground: {
background: '#f65314'
}
}));
const TitleTextArrow = ({ title, text, arrow, bgColor }) => {
const classes = useStyles();
const bgClass = `${bgColor ? bgColor : 'orange'}Background`
return (
<div className={`${classes.item + ' ' + classes[bgClass]}`}>
<Typography variant="h4">
{title}
</Typography>
<p>
{text}
</p>
{
arrow
? <P right><ArrowForward fontSize={"large"} ArrowForward /></P>
: null
}
</div>
);
}
TitleTextArrow.propTypes = {
title: PropTypes.string,
text: PropTypes.string,
arrow: PropTypes.bool,
bgColor: PropTypes.string
};
export default TitleTextArrow;<file_sep>/src/components/home/component/HeroCarousel.js
import React from 'react'
import Slider from "react-slick";
// Import css files for react click carousel
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
const HeroCarousel = (props) => {
const settings = {
centerMode: true,
dots: true,
infinite: true,
arrows: false,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000
};
return (
<div
style={{
backgroundImage: 'url("https://hips.hearstapps.com/countryliving.cdnds.net/16/25/4000x2000/landscape-1466594288-hen-chicken.jpg?resize=1200:650")',
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
// backgroundPosition: 'center',
minHeight: '500px',
maxHeight: '650px'
}}
>
<div
style={{
backgroundColor: 'green',
minHeight: '500px',
maxHeight: '650px',
opacity: 0.2
}}
/>
</div>
)
}
export default HeroCarousel<file_sep>/src/components/admin/saga.js
import { call, put, takeLatest, takeEvery, all } from "redux-saga/effects";
import axios from "axios"
import { API_URL } from 'env'
import {
FETCH_POST_CATEGORIES,
FETCH_POST_CATEGORIES_SUCCEED,
FETCH_POST_CATEGORIES_FAILED,
CREATE_POST,
CREATE_POST_SUCCEED,
CREATE_POST_FAILED
} from "./constant"
/* fetchPostCategories */
const fetchPostCategories = () => {
return axios
.get(`${API_URL}/categories/`)
.then(response => {
return response.data
});
};
export function* fetchPostCategoriesSaga(action) {
try {
const data = yield call(fetchPostCategories);
yield put({
type: FETCH_POST_CATEGORIES_SUCCEED,
payload: data
});
} catch (error) {
yield put({
type: FETCH_POST_CATEGORIES_FAILED,
error: 'Something went wrong!'
});
}
}
/* createPost */
const createPost = ({ data, postType }) => {
console.log(postType, data)
let postUrl = '';
if (postType === 'blog') {
postUrl = `${API_URL}/blogposts/`;
} else {
postUrl = `${API_URL}/products/`;
}
return axios
.post(postUrl, data, {
headers: {
"Authorization": `Token ${localStorage.getItem('auth_token')}`,
"Content-type": "multipart/form-data",
},
})
.then(response => {
console.log('blog post created')
return response.data
});
};
export function* createPostSaga(action) {
try {
const data = yield call(createPost, action);
yield put({
type: CREATE_POST_SUCCEED,
payload: data
});
} catch (error) {
console.log(error.response.data)
yield put({
type: CREATE_POST_FAILED,
error: 'Something went wrong!'
});
}
}
export const adminSaga = [
takeEvery(FETCH_POST_CATEGORIES, fetchPostCategoriesSaga),
takeEvery(CREATE_POST, createPostSaga),
];
<file_sep>/src/components/blogDetail/reducer.js
import {
FETCH_BLOG_DETAIL,
FETCH_BLOG_DETAIL_SUCCEED,
CREATE_BLOG_POST_COMMENT,
CREATE_BLOG_POST_COMMENT_SUCCEED,
CREATE_BLOG_POST_COMMENT_FAILED,
CREATE_POST_COMMENT_REPLY,
CREATE_POST_COMMENT_REPLY_SUCCEED,
CREATE_POST_COMMENT_REPLY_FAILED
} from './constant'
const initialState = {
blogDetail: [],
loading: false,
}
const blogDetailReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_BLOG_DETAIL:
return {
...state,
loading: true
}
case FETCH_BLOG_DETAIL_SUCCEED:
return {
...state,
loading: false,
blogDetail: action.payload
}
case CREATE_BLOG_POST_COMMENT:
return {
...state,
commentCreated: false
}
case CREATE_BLOG_POST_COMMENT_SUCCEED:
return {
...state,
commentCreated: true
}
case CREATE_BLOG_POST_COMMENT_FAILED:
return {
...state,
commentCreated: false
}
case CREATE_POST_COMMENT_REPLY:
return {
...state,
replyCreated: false
}
case CREATE_POST_COMMENT_REPLY_SUCCEED:
return {
...state,
replyCreated: true
}
case CREATE_POST_COMMENT_REPLY_FAILED:
return {
...state,
replyCreated: false
}
default:
return state;
}
}
export default blogDetailReducer<file_sep>/src/store/reducers.js
// reducers.js
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
import homeReducer from '../components/home/reducer';
import blogReducer from '../components/blog/reducer'
import blogDetailReducer from '../components/blogDetail/reducer'
import productReducer from '../components/products/reducer'
import loginReducer from '../components/login/reducer'
import adminReducer from '../components/admin/reducer'
export default (history) => combineReducers({
router: connectRouter(history),
home: homeReducer,
blog: blogReducer,
blogDetail: blogDetailReducer,
product: productReducer,
login: loginReducer,
admin: adminReducer,
})<file_sep>/src/components/about/index.js
import React, { Component } from 'react'
import AboutOurFarm from './component/AboutOurFarm'
import WhatWeCanOffer from './component/WhatWeOffer'
import Principle from './component/OurPrinciple'
import { Divider } from 'components/common/components/Divider'
import SloganBanner from 'components/common/components/SloganBanner'
class About extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{/* About farm */}
<AboutOurFarm />
<Divider />
{/* What we offer */}
<WhatWeCanOffer />
{/* Slogan banner */}
<SloganBanner
bgImageUrl="https://dummyimage.com/1200x300/cccccc/000.jpg"
sloganText="Egg is all we need when we feel low"
textSizeLevel={2}
/>
{/* Our Goal and Principle */}
<Principle />
{/* Slogan banner */}
<SloganBanner
bgImageUrl="https://dummyimage.com/1200x300/cccccc/000.jpg"
sloganText="Consume fresh egg everyday! Quality can't be compromised."
textSizeLevel={2}
/>
</div>
)
}
}
export default About;<file_sep>/src/components/Main/index.js
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import { compose } from "redux";
import { connect } from "react-redux";
import Home from 'components/home';
import About from 'components/about';
import Products from 'components/products';
import Contact from 'components/contact';
import Blog from 'components/blog';
import Login from 'components/login';
import BlogPostDetail from 'components/blogDetail';
import Admin from 'components/admin';
import Header from 'components/common/header'
import Footer from 'components/common/footer'
import ScrollToTop from 'components/common/components/ScrollToTop'
import { fetchCurrentUser } from './action'
import { checkAuthentication } from '../login/action'
class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// this.props.fetchCurrentUser();
this.props.checkAuthentication();
}
render() {
return (
<div>
{/* Scroll to top of the page on page transition */}
<ScrollToTop />
{/* navigation */}
< Header />
{/* router */}
< Switch >
<Route exact path="/" render={(routerProps) => <Home {...routerProps} />} />
<Route path="/about" render={(routerProps) => <About {...routerProps} />} />
<Route path="/products" render={(routerProps) => <Products {...routerProps} />} />
<Route path="/contact" render={(routerProps) => <Contact {...routerProps} />} />
<Route path="/admin" render={(routerProps) => <Admin {...routerProps} />} />
<Route path="/(blog|product|service)/:id" render={(routerProps) => <BlogPostDetail {...routerProps} />} />
<Route path="/blog" render={(routerProps) => <Blog {...routerProps} />} />
<Route path="/(login|admin)" render={(routerProps) => <Login {...routerProps} />} />
</Switch >
{/* Footer */}
< Footer />
</div >
);
}
}
const mapStateToProps = state => {
return {
app: state.home,
// router: state.router
};
};
const withConnect = connect(mapStateToProps, {
fetchCurrentUser,
checkAuthentication
});
export default compose(withConnect)(App);
<file_sep>/src/components/blogDetail/constant.js
export const FETCH_BLOG_DETAIL = 'FETCH_BLOG_DETAIL'
export const FETCH_BLOG_DETAIL_SUCCEED = 'FETCH_BLOG_DETAIL_SUCCEED'
export const FETCH_BLOG_DETAIL_FAILED = 'FETCH_BLOG_DETAIL_FAILED'
export const CREATE_BLOG_POST_COMMENT = 'CREATE_BLOG_POST_COMMENT'
export const CREATE_BLOG_POST_COMMENT_SUCCEED = 'CREATE_BLOG_POST_COMMENT_SUCCEED'
export const CREATE_BLOG_POST_COMMENT_FAILED = 'CREATE_BLOG_POST_COMMENT_FAILED'
export const CREATE_POST_COMMENT_REPLY = 'CREATE_POST_COMMENT_REPLY'
export const CREATE_POST_COMMENT_REPLY_SUCCEED = 'CREATE_POST_COMMENT_REPLY_SUCCEED'
export const CREATE_POST_COMMENT_REPLY_FAILED = 'CREATE_POST_COMMENT_REPLY_FAILED'<file_sep>/src/components/common/components/CommonLoader.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Loader from 'react-loader-spinner'
const CommonLoader = ({ showLoader = false, height, width, type }) => {
return (
<Loader
visible={showLoader}
type="ThreeDots"
color="#f65314"
height={500}
width={'5%'}
timeout={0}
style={{
position: 'relative',
left: '47%'
}}
/>
);
}
CommonLoader.propTypes = {
showLoader: PropTypes.bool,
height: PropTypes.string,
width: PropTypes.string,
type: PropTypes.string,
}
export default CommonLoader;<file_sep>/src/components/about/component/OurPrinciple.js
import React from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import Title from 'components/common/components/Title'
import IconTitleText from 'components/common/components/IconTitleText'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
const useStyles = makeStyles(theme => ({
customIcon: {
backgroundColor: 'gray',
height: '80px',
width: '80px',
borderRadius: '50%',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
textAlign: 'center',
margin: '30px auto'
}
}));
const Principle = (props) => {
const classes = useStyles();
return (
<ComponentWrapper backgroundColor="#f0f0f0">
<Title text={"Our goal and principle"} padding={"0px 0px 24px 0px"} />
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<IconTitleText
titleText={"AENEAN NONUMMY HENDRERIT MAURIS PHASELLUS PORTA FUSCE"}
iconText={"1"}
text={"Phasellus porta. Fusce suscipit varius mi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio. Morbi nunc odio, gravida at, cursus nec, luctus a, lorem. Maecenas tristique orci ac sem. Duis ultricies pharetra"}
textBgColor={"inherit"}
iconTextColor="#fff"
iconBgColor="#7cbb00"
/>
</Grid>
<Grid item xs={12} sm={6}>
<IconTitleText
titleText={"AENEAN NONUMMY HENDRERIT MAURIS PHASELLUS PORTA FUSCE"}
iconText={"2"}
text={"Phasellus porta. Fusce suscipit varius mi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio. Morbi nunc odio, gravida at, cursus nec, luctus a, lorem. Maecenas tristique orci ac sem. Duis ultricies pharetra"}
textBgColor={"inherit"}
iconTextColor="#fff"
iconBgColor="#7cbb00"
/>
</Grid>
<Grid item xs={12} sm={6}>
<IconTitleText
titleText={"<NAME>IS PHASELLUS PORTA FUSCE"}
iconText={"3"}
text={"Phasellus porta. Fusce suscipit varius mi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio. Morbi nunc odio, gravida at, cursus nec, luctus a, lorem. Maecenas tristique orci ac sem. Duis ultricies pharetra"}
textBgColor={"inherit"}
iconTextColor="#fff"
iconBgColor="#7cbb00"
/>
</Grid>
<Grid item xs={12} sm={6}>
<IconTitleText
titleText={"<NAME>ASELLUS PORTA FUSCE"}
iconText={"4"}
text={"Phasellus porta. Fusce suscipit varius mi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio. Morbi nunc odio, gravida at, cursus nec, luctus a, lorem. Maecenas tristique orci ac sem. Duis ultricies pharetra"}
textBgColor={"inherit"}
iconTextColor="#fff"
iconBgColor="#7cbb00"
/>
</Grid>
</Grid>
</ComponentWrapper>
)
}
export default Principle<file_sep>/src/components/Main/action.js
import { FETCH_USER } from './constant'
export const fetchCurrentUser = () => {
return {
type: FETCH_USER
}
}<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
Front end for kukhura CMS. (In progress)<file_sep>/src/components/products/index.js
import React, { Component } from 'react'
import { compose } from "redux";
import { connect } from "react-redux";
import Loader from 'components/common/components/CommonLoader'
import OurProducts from './component/OurProducts'
import EggsAndChiken from './component/EggsAndChicken'
import { Divider } from 'components/common/components/Divider'
import SloganBanner from 'components/common/components/SloganBanner'
import { getProducts } from './action'
class Products extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.getProducts();
}
render() {
const { products, hero_product } = this.props.product;
if(products.length===0){
return <Loader showLoader />
}
return (
<div>
{/* OurProducts */}
<OurProducts heroProduct={hero_product} />
{/* organic Eggs */}
<EggsAndChiken allProducts={products} />
<Divider />
{/* Slogan banner */}
<SloganBanner
bgImageUrl="https://dummyimage.com/1200x300/cccccc/000.jpg"
sloganText="Consume fresh egg everyday! Quality can't be compromised."
textSizeLevel={2}
/>
</div>
)
}
}
const mapStateToProps = state => {
return {
product: state.product
// router: state.router
};
};
const withConnect = connect(mapStateToProps, {
getProducts
});
export default compose(withConnect)(Products);
<file_sep>/src/components/home/saga.js
import { call, put, takeLatest, takeEvery, all } from "redux-saga/effects";
import axios from "axios"
import { take } from "lodash"
import { API_URL } from 'env'
import {
TEST_SUCCEED,
TEST_FAILED,
TEST_REQUEST,
GET_RECENT_POSTS,
GET_RECENT_POSTS_SUCCEED,
GET_RECENT_POSTS_FAILED
} from "./constant"
const fetchTestData = () => {
return axios
.get(`https://jsonplaceholder.typicode.com/comments?postId=1`)
.then(response => {
return response.data
});
};
export function* fetchTestDataSaga(action) {
try {
const data = yield call(fetchTestData);
yield put({
type: TEST_SUCCEED,
payload: data
});
} catch (error) {
yield put({
type: TEST_FAILED,
error: 'Something went wrong!'
});
}
}
const getRecentPosts = (rowCount) => {
const fakeData = [
{
id: '1',
title: 'ULUM MOLESTIE LACUS AENEAN NOMY HENDRERIT MAURIS PHASELLUS PORTA FUSCE SUSCIPIT',
created_on: '2019-11-27 00:00:00',
post_content: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris.',
post_image_url: 'https://dummyimage.com/250x250/cccccc/000.jpg',
post_author: '<NAME>'
}, {
id: '2',
title: 'ULUM MOLESTIE LACUS AENEAN NOMY HENDRERIT MAURIS PHASELLUS PORTA FUSCE SUSCIPIT',
created_on: '2019-11-26 00:00:00',
post_content: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris.',
post_image_url: 'https://dummyimage.com/250x250/cccccc/000.jpg',
post_author: '<NAME>'
}, {
id: '3',
title: 'ULUM MOLESTIE LACUS AENEAN NOMY HENDRERIT MAURIS PHASELLUS PORTA FUSCE SUSCIPIT',
created_on: '2019-11-26 00:00:00',
post_content: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris.',
post_image_url: 'https://dummyimage.com/250x250/cccccc/000.jpg',
post_author: '<NAME>'
}, {
id: '4',
title: 'ULUM MOLESTIE LACUS AENEAN NOMY HENDRERIT MAURIS PHASELLUS PORTA FUSCE SUSCIPIT',
created_on: '2019-11-26 00:00:00',
post_content: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nommy hendrerit mauris.',
post_image_url: 'https://dummyimage.com/250x250/cccccc/000.jpg',
post_author: '<NAME>'
},
];
return take(fakeData, rowCount);
};
export function* getRecentPostsSaga(action) {
try {
const data = yield call(getRecentPosts, action.rowCount);
yield put({
type: GET_RECENT_POSTS_SUCCEED,
payload: data
});
} catch (error) {
yield put({
type: GET_RECENT_POSTS_FAILED,
error: 'Something went wrong!'
});
}
}
export const homeSaga = [
takeEvery(TEST_REQUEST, fetchTestDataSaga),
takeEvery(GET_RECENT_POSTS, getRecentPostsSaga),
];
<file_sep>/src/components/common/footer.js
import React from 'react'
import { P, WrapperDiv } from 'components/common/commonStyle'
import { OrangeButton } from 'components/common/components/Button'
import { makeStyles } from '@material-ui/core/styles';
import { Grid, TextField, Link } from '@material-ui/core';
import { Facebook, Mail, Call, WhatsApp, YouTube } from '@material-ui/icons';
import { StyledLink } from './components/Link';
const useStyles = makeStyles(theme => ({
maindiv: {
padding: '100px 0px',
width: '100%',
background: '#49515C',
color: '#eee',
fontSize: 16
},
textField: {
width: '100%',
border: '1px solid #eee',
color: '#ccc'
},
titleText: {
marginTop: 0,
},
icons: {
background: '#eee',
margin: '5px',
padding: 5,
color: '#000',
cursor: 'pointer',
borderRadius: '50%',
'& :hover': {
background: '#000',
color: 'rgb(246, 83, 20)'
}
},
ServicesH3: {
fontWeight: 'bold'
},
backgroundImageOne: {
backgroundImage: 'url("https://dummyimage.com/400x250/cccccc/000.jpg")',
backgroundRepeat: 'no-repeat',
backgroundSize: '100% 100%',
minHeight: '250px',
},
serviceTextColor: {
color: '#7c7c7c'
},
readMoreButton: {
fontSize: '14px',
},
MailLink: {
textDecoration: 'none',
color: '#fff'
}
}));
const Footer = (props) => {
const classes = useStyles();
return (
<div className={classes.maindiv}>
<WrapperDiv className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12} sm={3}>
<P fontSize={'36px'} className={classes.titleText}>
Contact us
</P>
<div>
Tokha Road<br />
Kathmandu<br />
<a className={classes.MailLink} href="mailto:<EMAIL>"><EMAIL></a>
<br /><br />
(+977)9841010101<br />
(+977)9841010101<br />
NEPAL
</div>
</Grid>
<Grid item xs={12} sm={3}>
<P fontSize={'36px'} className={classes.titleText}>
Follow us
</P>
<Facebook className={classes.icons} circled fontSize={"large"} />
<Mail className={classes.icons} circled fontSize={"large"} />
<Call className={classes.icons} circled fontSize={"large"} />
<WhatsApp className={classes.icons} circled fontSize={"large"} />
</Grid>
<Grid item xs={12} sm={2}>
<P fontSize={'36px'} className={classes.titleText}>
Menu
</P>
<StyledLink block>Home</StyledLink>
<StyledLink block>About</StyledLink>
<StyledLink block>Services</StyledLink>
<StyledLink block>Products</StyledLink>
<StyledLink block>Contact Us</StyledLink>
<StyledLink block>Blogs</StyledLink>
</Grid>
<Grid item xs={12} sm={4}>
<P fontSize={'36px'} className={classes.titleText}>
Join our newsletter
</P>
<p>
Don't miss anything from us. Always stay informed of our products and offers!
</p>
<TextField
id="outlined-basic"
className={classes.textField}
label="Enter your email here"
type="email"
color="primary"
margin="normal"
variant="outlined"
onChange={(e) => console.log(e.target.value)}
InputLabelProps={{
style: {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
color: '#ccc'
}
}}
/>
</Grid>
</Grid>
</WrapperDiv>
</div>
)
}
export default Footer<file_sep>/src/components/home/action.js
import { TEST_REQUEST, TEST_SUCCEED, GET_RECENT_POSTS } from './constant'
export const test = () => {
return {
type: TEST_REQUEST
}
}
export const testSuccess = (data) => {
return {
type: TEST_SUCCEED,
payload: data
}
}
export const getRecentPosts = (count = 3) => {
return {
type: GET_RECENT_POSTS,
rowCount: count
}
}<file_sep>/src/components/Main/saga.js
import { call, put, takeLatest, takeEvery, all } from "redux-saga/effects";
import axios from "axios"
import { take } from "lodash"
import { API_URL } from 'env'
import {
FETCH_USER,
FETCH_USER_SUCCEED,
FETCH_USER_FAILED
} from "./constant"
const fetchCurrentUser = () => {
return axios
.get(`${API_URL}/users/`)
.then(response => {
return response.data
});
};
export function* fetchCurrentUserSaga(action) {
try {
const data = yield call(fetchCurrentUser);
console.log('users ', data)
yield put({
type: FETCH_USER_SUCCEED,
payload: data
});
} catch (error) {
yield put({
type: FETCH_USER_FAILED,
error: 'Something went wrong!'
});
}
}
export const appSaga = [
takeEvery(FETCH_USER, fetchCurrentUserSaga),
];<file_sep>/src/components/admin/action.js
import { FETCH_POST_CATEGORIES, CREATE_POST } from './constant'
export const fetchPostCategories = () => {
return {
type: FETCH_POST_CATEGORIES
}
}
export const createPost = (data, postType = "blog") => {
return {
type: CREATE_POST,
data: data,
postType: postType
}
}<file_sep>/src/components/blogDetail/component/BlogPostDetail.js
import React from 'react'
import ComponentWrapper from 'components/common/components/ComponentWrapper'
import Comment from './Comment'
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import moment from 'moment';
import { startCase } from 'lodash';
import { Typography } from '@material-ui/core';
import { KeyboardArrowLeft } from '@material-ui/icons';
import { Link } from 'react-router-dom'
const useStyles = makeStyles(theme => ({
fadedTextColor: {
color: '#7c7c7c',
},
blackTextColor: {
color: '#000',
whiteSpace: 'pre-wrap'
},
ServicesH3: {
fontWeight: 'bold'
},
item: {
backgroundColor: props => props.textBgColor,
position: 'relative',
// borderRadius: 10,
padding: '30px 0px 0px 0px',
minHeight: 150,
background: 'transparent',
color: '#000'
},
backgroundImage: {
background: props => props.bgImageUrl,
backgroundRepeat: 'no-repeat !important',
backgroundSize: 'cover !important',
minHeight: '500px'
},
centerDiv: {
width: '100%',
display: 'block',
textAlign: 'center'
},
readMoreButton: {
width: '40%',
borderRadius: '15px',
margin: '40px 0px 0px 0px'
},
backIcon: {
textAlign: 'center',
position: 'relative',
left: 0,
top: 7,
[theme.breakpoints.down('md')]: {
top: 7,
},
},
backLink: {
textDecoration: 'none',
display: 'inline-block',
color: '#000',
position: 'relative',
padding: '0px 12px 10px 0px',
background: '#fff',
margin: '0px 0px 10px 0px',
'&:hover': {
color: '#f65314'
},
}
}));
const BlogPostDetail = ({
post = {},
postType = "blog",
submitComment,
dispatchReplyCreate }) => {
const {
id = "",
title = "",
description = "",
author = "Admin",
primary_image = "",
created = "Admin",
} = post;
const classes = useStyles(
{
bgImageUrl: `url("${primary_image}")`
}
);
const postTypesCategory = postType === 'product'
? 'products'
: 'posts'
const goBackcategoryUrl = postType === 'product'
? 'products'
: 'blog'
return (
<ComponentWrapper>
<Link to={`/${goBackcategoryUrl}`} className={classes.backLink}>
<KeyboardArrowLeft
color={"action"}
className={classes.backIcon}
/>
<span style={{ marginLeft: 10 }}>View all {postTypesCategory}</span>
</Link>
<br />
<Grid container spacing={3}>
<Grid item xs={12} sm={12} key={id}>
{/* image background */}
<div className={classes.backgroundImage} />
<div className={classes.item}>
{
/* title */
<Typography className={classes.ServicesH3} variant="p">
{title.toUpperCase()}
</Typography>
}
{/* text */}
<p className={classes.serviceTextColor}>
<div>
<p className={classes.fadedTextColor}>
{moment(created).format('LL')}
, By
<span className={classes.fadedTextColor}> {startCase(author)}
</span>
</p>
<br />
<p className={classes.blackTextColor}>
{description}
</p>
</div>
</p>
</div>
</Grid>
</Grid>
{/* Comment section */}
<Comment
submitComment={submitComment}
blogId={id}
postComments={post && post.comments ? post.comments : []}
dispatchReplyCreate={dispatchReplyCreate}
/>
</ComponentWrapper>
)
}
BlogPostDetail.propTypes = {
post: PropTypes.object
}
export default BlogPostDetail
<file_sep>/src/components/admin/component/UpdateProfile.js
import React, { useState } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import { TextField, FormControl, Grid, Button } from '@material-ui/core';
import Title from 'components/common/components/Title'
const useStyles = makeStyles(theme => ({
root: {
color: 'red'
},
textField: {
width: '100%',
[`& fieldset`]: {
borderRadius: 0,
},
display: 'inline-block'
}
}));
export const UpdateProfile = ({ cancelUpdate }) => {
const classes = useStyles();
// hooks
const [userName, onUserNameChange] = useState('');
const [email, onEmailChange] = useState('');
const [errorPayload, onErrorFind] = useState({});
/* form rest */
const formReset = () => {
onUserNameChange('');
onEmailChange('');
}
/* Handle submit */
const handleSubmit = (e) => {
e.preventDefault();
const payload = {
userName, email
}
/* Validate Form */
if (!payload.userName || !payload.email) {
// ERROR
const errorData = {};
errorData.userName = !payload.userName ? 'Required' : ''
errorData.email = !payload.email ? 'Required' : ''
onErrorFind(errorData);
} else {
// NO ERROR
console.log(payload);
formReset();
}
}
return (
<div>
<Title fontSize={"28px"} text={"Profile"} />
<form
className={classes.root}
noValidate
autoComplete="off"
onSubmit={e => handleSubmit(e)}
>
<FormControl>
<Grid container spacing={3}>
<Grid item xs={6} sm={6} md={6}>
<TextField
value={userName}
label="username"
onChange={(e) => {
onUserNameChange(e.target.value);
onErrorFind({
...errorPayload,
userName: ''
})
}}
className={classes.textField}
margin="normal"
variant="outlined"
error={!!errorPayload.userName}
helperText={errorPayload.userName}
/>
</Grid>
<Grid item xs={6} sm={6} md={6}>
<TextField
value={email}
label="email"
onChange={(e) => {
onEmailChange(e.target.value);
onErrorFind({
...errorPayload,
email: ''
})
}}
className={classes.textField}
margin="normal"
variant="outlined"
error={!!errorPayload.email}
helperText={errorPayload.email}
/>
</Grid>
</Grid>
<br />
{/* Action buttons */}
<Grid container spacing={0}>
<Grid item xs={6} sm={5} md={5}>
<Button
color={"primary"}
variant={"contained"}
type={"submit"}
>
Update Profile
</Button>
</Grid>
<Grid item xs={6} sm={4} md={4}>
<Button
color={"secondary"}
variant={"contained"}
onClick={() => cancelUpdate(false)}
>
Cancel
</Button>
</Grid>
</Grid>
</FormControl>
</form>
</div>
)
}
export default UpdateProfile;<file_sep>/src/components/products/constant.js
export const GET_PRODUCTS = 'GET_PRODUCTS'
export const GET_PRODUCTS_SUCCEED = 'GET_PRODUCTS_SUCCEED'
export const GET_PRODUCTS_FAILED = 'GET_PRODUCTS_FAILED'<file_sep>/src/components/login/action.js
import { LOGIN, CHECK_AUTHENTICATION } from './constant'
export const authenticateUser = (credentials) => {
return {
type: LOGIN,
data: credentials
}
}
export const checkAuthentication = () => {
const token = localStorage.getItem('auth_token');
return {
type: CHECK_AUTHENTICATION,
data: token || ""
}
}
|
381d931a5c742d094a101f5608e5445a00d39774
|
[
"JavaScript",
"Markdown"
] | 51
|
JavaScript
|
harryac07/kukhura-ui
|
9905a99157ab218f597dd7d2c666a79b26b8d7f2
|
ecaf5e21f75489b7d33ff8f7783463698b579461
|
refs/heads/master
|
<repo_name>omezaf/ExamenJS<file_sep>/calculadora/js/app.js
var Calculadora = {};
Calculadora = ( function () {
var teclaActiva, pantalla, valor, decimal, numero1, numero2, operacion;
iniciarCalculadora();
function presionarTecla() {
teclaActiva = this;
this.style.borderWidth = '2px';
switch ( this.id ) {
case "on":
valor = 0;
numero2 = null;
decimal = null;
operacion = null;
break;
case "sign":
valor *= -1;
break;
case "punto":
decimal = ( decimal == 0 ) ? -1 : decimal;
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
valor = Math.abs( valor );
if ( decimal == 0 )
valor = valor * 10 + parseInt( this.id );
else
valor += parseInt( this.id ) * Math.pow( 10, decimal-- );
numero2 = null;
break;
case "mas":
case "menos":
case "por":
case "dividido":
if ( valor == 0 ) return;
numero1 = valor;
numero2 = null;
valor = 0;
decimal = 0;
operacion = this.id;
break;
case "igual":
if ( operacion == null || numero1 == null ) return;
if ( numero2 == null )
numero2 = valor;
else
numero1 = valor;
switch ( operacion ) {
case "mas":
valor = numero1 + numero2;
break;
case "menos":
valor = numero1 - numero2;
break;
case "por":
valor = numero1 * numero2;
break;
case "dividido":
valor = numero1 / numero2;
break;
}
break;
}
actualizarPantalla();
}
function soltarTecla() {
teclaActiva.style.borderWidth = '0';
}
function actualizarPantalla() {
var literal = valor.toString(), pos = literal.indexOf( '.' );
if ( literal.length > 10 ) {
decimal = pos ? -Math.min( 7, literal.length - pos - 1 ) : 0;
valor = valor.toFixed( -decimal );
}
literal = valor.toString() + ( decimal < 0 && literal.indexOf( "." ) < 0 ? "." : "" );
literal = ( literal == "0" && operacion != null ) ? "" : literal.substring( 0, 8 );
pantalla.innerHTML = literal.substring( 0, 8 );
valor = Number( literal );
}
function iniciarCalculadora() {
valor = 0;
decimal = 0;
operacion = null;
numero2 = null;
pantalla = document.getElementById( 'display' );
var teclas = document.querySelectorAll( '.tecla' );
for ( var i = 0; i < teclas.length; i++ ) {
teclas[i].style.width = "78px";
teclas[i].style.border = '0px solid #999';
teclas[i].onmousedown = presionarTecla;
teclas[i].onmouseup = soltarTecla;
}
actualizarPantalla();
}
}());
|
efe283830edf60bc61bb83ebf89d01eca28f7532
|
[
"JavaScript"
] | 1
|
JavaScript
|
omezaf/ExamenJS
|
788586cec50fd47cc4e796c58768fe59c8361a7c
|
61ebe827530e490de57ec2b99df041543d180990
|
refs/heads/master
|
<file_sep>#-*- coding: utf_8 -*-
import random
import numpy as np
class Graphe :
"""
n : nombre de sommets
p : probabilité pour les voisins
r : probabilité pour les couleurs
"""
def __init__(self, n, p, r):
# self.graphe = np.random.random_sample((n,n)) # dictionnaire ou liste adjacence
self.graphe = None
self.n = n # nombre de sommet -> aléatoire
self.p = p # probabilité -> attribution des voisins
self.r = r # probabilité -> attribution des couleurs
self.couleurs = []
self.generer_matrice()
def generer_matrice(self):
self.graphe = np.random.binomial(1, self.p, self.n*self.n).reshape((self.n,self.n))
self.couleurs = np.random.binomial(1,self.r,self.n)
for i in range(self.n):
for j in range(self.n):
if self.graphe[i][j] == 1 and i != j:
self.graphe[j][i] == 1
if i == j :
self.graphe[i][i] = 0
"""
for i in range(self.n):
for j in range(self.n):
if random.random() <= self.p and i != j:
self.graphe[j][i] = 1
self.graphe[j][i] = 1
else :
self.graphe[i][j] = 0
self.graphe[j][i] = 0
for i in range(self.n):
if random.random() <= self.r :
self.couleurs.append(1)
else :
self.couleurs.append(0)
"""
# for i in range(self.n):
# for j in range(self.n):
# # aretes
# if self.graphe[i][j] != 1 and self.graphe[i][j] != 0 and i != j and self.graphe[i][j] <= self.p :
# # print("t")
# # print(self.graphe[i][j])
# # print(i,j)
# self.graphe[i][j] = 1
# self.graphe[j][i] = 1
# elif self.graphe[i][j] != 1 and self.graphe[i][j] != 0 and i != j :
# self.graphe[i][j] = 0
# self.graphe[j][i] = 0
# # couleurs
# if i == j and self.graphe[i][j] < self.r :
# self.couleurs.append(1) # rouge = 1
# self.graphe[i][j] = 0
# elif i == j:
# self.couleurs.append(0)
# self.graphe[i][j] = 0
# trouver une sequence 2-destructrice pour le graphe
def trouverSequence(self) :
sequence = list()
listeSommet = list(range(self.n))
nbVoisins = np.sum(self.graphe,axis=1)
sommetsRestants = list()
degreInferieur = True
while degreInferieur :
degreInferieur = False
for i in listeSommet :
if nbVoisins[i] <= 2 :
degreInferieur = True
sequence.append(i)
listeSommet.remove(i)
# on s'occupe ensuite des sommets qui possède plus de 2 voisins rouge
# on compte le nombre de voisins rouge qu'ils possèdent et ceux qui en ont le moins
# sont disposé dans la séquence en premier
for sommet in listeSommet :
nbVoisinsRougeRestant = 0
for i in listeSommet :
# on regarde si i est voisin de s
if self.couleurs[i] == 1 and self.graphe[sommet][i] == 1 :
nbVoisinsRougeRestant += 1
sommetsRestants.append((sommet,nbVoisinsRougeRestant))
# on trie les valeurs des tuples selon le plus petit nombre de voisins rouge
sommetsRestants.sort(key=lambda tup: tup[1])
# on ajoute ensuite les sommets restants à la séquence
for i in sommetsRestants :
sequence.append(i[0])
return sequence
# verifie que la sequence est 2-Destructrice
def verifSequenceDestructrice(self, sequence):
"""
Pour chaque sommet de la séquence, on regarde si dans la séquence le sommet posssède un voisin de couleur rouge,
si c'est le cas alors on incrémente le compteur nbVoisinsRougeApres, qui compte le nombre de voisins rouges d'un sommet
présent après lui dans la séquence
"""
for i in range(len(sequence)) :
v = sequence[i]
nbVoisinsRougeApres = 0 # compteur de voisins rouges après v dans la séquence
for j in range(i, len(sequence)):
if self.couleurs[sequence[j]] == 1 and self.graphe[v,sequence[j]] == 1 :
nbVoisinsRougeApres += 1
if nbVoisinsRougeApres > 2 :
return False
return True
# calcul de la probabilite d'avoir une séquence 2-destructrice
def repeteRandom(n,p,r,nbExperiences):
nbCasPositif = 0
for i in range(nbExperiences):
graphe = Graphe(n,p,r) # generation du graphe aléatoire
if graphe.verifSequenceDestructrice(graphe.trouverSequence()) :
nbCasPositif += 1
print("Nombres d'experiences : " +str(nbExperiences))
print("Nombres de cas positif : "+str(nbCasPositif))
print("Probabilité d'avoir une séquence 2-destructrice est : %.4f" %(nbCasPositif/nbExperiences))
return nbCasPositif/nbExperiences
"""
TrouverR prend en paramêtre le nombre de sommets n du graphe, p la probabilité pour la création de sommets et arêtes,
et nbExperiences le nombre de d'experiences effectuées dans la fonction repeteRandom pour affiner la variable varR
"""
def trouverR(n,p,nbExperiences):
prob = 0.0 # probabilite qui doit etre le plus proche de 0.5
varR = 0.0 # valeur particuliere de r à trouver
inc = 0.005
while prob < 0.495 or prob > 0.515:
prob = repeteRandom(n,p,varR,nbExperiences)
varR += inc # vitesse d'incrementation
print(" r = %.4f"%varR)
# si varR est supérieur à 1 on recommence, idem si la probabilité d'avoir une séquence 2-d est inférieur à 0.45
# Cela veut dire que l'on a pas trouvé de varR pour lequel prob ~ 0.5 donc on recommence
if prob < 0.6 and prob > 0.5:
inc = 0.005
if prob < 0.495 :
inc = -0.005
print("n = " + str(n) + " p = "+ str(p) + " r = %.4f"%varR)
def main():
trouverR(50,0.1,100)
# graphe = Graphe(10,0.5,0.5)
# graphe.generer_matrice()
# print(graphe.graphe)
# print(graphe.couleurs)
# a = np.random.binomial(1,0.5,16).reshape((4,4))
# print(a)
# c = np.random.binomial(1,0.5,4)
# print(c)
# print(np.sum(a,axis=1))
# t = list([(1,2),(2,3),(1,4),(4,1)])
# t.sort(key=lambda tup: tup[1])
# print(t)
main()
exit()
# # print(a[:,1])
# d = np.dot(a[:,1],c.reshape(4,))
# print(d)<file_sep>#-*- coding: utf_8 -*-
from graphe import *
# Optionnel, graphe aleatoire où chaque arete a une probabilité p d'appartenir au graphe
# Attention utilise la librairie igraph
def visualisationGrapheAleatoire(n,p,r) :
graphe = Graphe()
graphe.intialiserGrapheAleatoire(n,p,r)
# graphe.affichageGrapheAleatoire()
# calcul de la probabilite d'avoir une séquence 2-destructrice
def repeteRandom(n,p,r,nbExperiences):
nbCasPositif = 0
for _ in range(nbExperiences):
graphe = Graphe() # generation du graphe aléatoire
graphe.intialiserGrapheAleatoire(n,p,r)
sequence = graphe.trouverSequence()
# print(resultat)
if graphe.verifSequenceDestructrice(sequence) :
nbCasPositif += 1
# print("Nombres d'experiences : " +str(nbExperiences))
# print("Nombres de cas positif : "+str(nbCasPositif))
# print("Probabilité d'avoir une séquence 2-destructrice est : %.4f" %(nbCasPositif/nbExperiences))
return nbCasPositif/nbExperiences
"""
TrouverR prend en paramêtre le nombre de sommets n du graphe, p la probabilité pour la création de sommets et arêtes,
et nbExperiences le nombre de d'experiences effectuées dans la fonction repeteRandom pour affiner la variable varR
version dichotomique
# Ici, on fait varier la variable sur deux intervalles
# la variable r qui obtient une probabilité plus proche de 0.5 est sélectionner
# puis on recrée un nouvel intervalle à partir de cette variable r
"""
def trouverRDichotomie(n,p,nbExperiences):
varR = 0.0 # valeur particuliere de r à trouver
interval_r = 1
interval_sup_r = interval_r
interval_inf_r = interval_r/2
prob_inf = 0
prob_sup = 0
while (prob_sup < 0.4951 or prob_sup > 0.5051) and (prob_inf < 0.4951 or prob_inf > 0.5051) :
prob_sup = repeteRandom(n,p,interval_sup_r,nbExperiences)
prob_inf = repeteRandom(n,p,interval_inf_r,nbExperiences)
# print(interval_sup_r, prob_sup)
# print(interval_inf_r, prob_inf)
interval_r = interval_r/2
if abs(0.5 - prob_sup) < abs(0.5 - prob_inf) :
interval_sup_r = abs(interval_sup_r + interval_r/2)
interval_inf_r = abs(interval_sup_r - interval_r)
else :
interval_sup_r = abs(interval_inf_r + interval_r/2)
interval_inf_r = abs(interval_inf_r - interval_r/2)
if prob_sup > 0.4951 and prob_sup < 0.5051 :
# print("n = " + str(n) + " p = "+ str(p) + " r = %.2f"%(interval_sup_r*100))
return interval_sup_r
if prob_inf > 0.4951 and prob_inf < 0.5051 :
# print("n = " + str(n) + " p = "+ str(p) + " r = %.2f"%(interval_inf_r*100))
return interval_inf_r
"""
version itérative
# Ici, on fait varier la valeur varR pour trouver une valeur de la variable prob proche de 0.5
# Si prob est supérieur à 0.6, l'incrémentation se fait plus rapidement
# Si prob est inférieur à 0.6, on diminue le rithme d'incrémentation pour être plus précis
# Si prob est inférieur à 0.4, on incrémente à l'envers pour revenir vers des valeur de prob proche de 0.5
"""
def trouverRIteratif(n,p,nbExperiences) :
varR = 0.0 # valeur particuliere de r à trouver
interval_r = 1
prob = 0.0 # probabilite qui doit etre le plus proche de 0.5
inc = 0.01
while prob < 0.495 or prob > 0.505:
prob = repeteRandom(n,p,varR,nbExperiences)
varR += inc # vitesse d'incrementation
# print(" r = %.4f"%varR)
# si varR est supérieur à 1 on recommence, idem si la probabilité d'avoir une séquence 2-d est inférieur à 0.45
# Cela veut dire que l'on a pas trouvé de varR pour lequel prob ~ 0.5 donc on recommence
if prob < 0.6 and prob > 0.5:
inc = 0.0001
if prob < 0.495 :
inc = -0.0001
print("n = " + str(n) + " p = "+ str(p) + " r = %.2f"%(varR*100))
def algoTrouverLesRD() :
trouverRDichotomie(50,0.1,800)
trouverRDichotomie(100,0.1,800)
trouverRDichotomie(50,0.3,800)
trouverRDichotomie(100,0.3,800)
trouverRDichotomie(50,0.5,800)
trouverRDichotomie(100,0.5,800)
trouverRDichotomie(50,0.7,800)
trouverRDichotomie(100,0.7,800)
def algoTrouverLesRI() :
trouverRIteratif(50,0.1,800)
trouverRIteratif(100,0.1,800)
trouverRIteratif(50,0.3,800)
trouverRIteratif(100,0.3,800)
trouverRIteratif(50,0.5,800)
trouverRIteratif(100,0.5,800)
trouverRIteratif(50,0.7,800)
trouverRIteratif(100,0.7,800)
"""
Qui étant donné n,p,r en paramètre, retourne la probabilité qu'un graphe, où chaque sommet a une probabilité r d'être rouge,
admette une séquence 2-destructrice.
"""
def testA(n,p,r) :
moyenne = repeteRandom(n,p,r,800)
print("TestA : probabilité d'avoir une séquence 2-destructrice = %.2f" %(moyenne*100))
"""
Qui étant donné n,p,r en paramètre, retourne la valeur de r pour laquelle si la proportion de sommets rouges est r, alors le graphe a une probabilité proche de 1/2
d'avoir une séquence 2-destructrice
"""
def testB(n,p) :
r = trouverRDichotomie(n,p,800)
print("TestB : n = " + str(n) + " p = "+ str(p) + " r = %.2f"%(r*100))
def main() :
testA(50,0.5,0.2)
# testB(50,0.5)
main()
exit()
<file_sep>import random
import numpy as np
# from igraph import *
class Graphe():
def __init__(self):
self.graphe = [] # liste adjacence
self.n = None # nombre de sommet
self.p = None # probabilité pour l'attribution des voisins
self.r = None # probabilité pour l'attribution des couleurs
self.couleurs = []
def ajouterArrete(self, a, b):
self.graphe[a][1].append(b)
self.graphe[b][1].append(a)
"""
Initialisation du graphe selon une loi binomiale pour les couleurs de chaque sommet
et une loi binomiale pour les arêtes
La fonction np.random.binomiale nous renvoie un tableau comprenant le resultat d'experience d'une loi binomiale selon
l'interval des valeurs, ici 0 ou 1, la probabilité d'avoir 1 dans le tableau (self.r ou self.p) et le nombre d'experience
à effectuer, c'est à dire la taille du tableau de sortie
"""
def intialiserGrapheAleatoire(self, n, p, r):
self.n = n
self.p = p
self.r = r
self.couleurs = np.random.binomial(1,self.r,self.n)
for i in range(self.n):
self.graphe.append((i,list()))
voisins_aleatoire = np.random.binomial(1, self.p, int(self.n*(self.n-1)/2))
iter = 0
for i in range(self.n) :
# on ne veut aucun doublon
for j in range(i+1,self.n):
if voisins_aleatoire[iter] == 1 :
self.graphe[i][1].append(j)
self.graphe[j][1].append(i)
iter += 1
"""
retourne le nombre de voisins rouge de s au total ou dans la liste donnée en paramètre
"""
def voisinsRouge(self, s, list = None):
if list :
nbVoisins = 0
for i in list:
if self.couleurs[i] == 1 and i in self.graphe[s][1]:
nbVoisins += 1
return nbVoisins
else :
iter = 0
for i in self.graphe[s][1]:
if self.couleurs[i] == 1 :
iter+= 1
return iter
"""
verifie si s2 est voisin de s1
"""
def estVoisin(self, s1, s2):
if s2 in self.graphe[s1][1] : return True
else : return False
"""
verifie que la sequence est 2-Destructrice
"""
def verifSequenceDestructrice(self, sequence):
"""
Pour chaque sommet de la séquence, on regarde si dans la séquence le sommet posssède un voisin de couleur rouge,
si c'est le cas alors on incrémente le compteur nbVoisinsRougeApres, qui compte le nombre de voisins rouges d'un sommet
présent après lui dans la séquence
"""
if len(sequence) < self.n or len(sequence) > self.n:
return False
for i in range(len(sequence)) :
v = sequence[i]
nbVoisinsRougeApres = 0 # compteur de voisins rouges après v dans la séquence
for j in range(i, len(sequence)):
if self.couleurs[sequence[j]] == 1 and self.estVoisin(v,sequence[j]) :
nbVoisinsRougeApres += 1
if nbVoisinsRougeApres > 2 :
return False
return True
"""
trouver une sequence 2-destructrice dans le graphe
"""
def trouverSequence(self) :
sequence = list()
listeSommet = [i for i in range(self.n)]
degreInferieur = True
"""
on regarde si le sommet a un nb de voisins rouge inferieur ou egale à 2 selon la listeSommet
c'est à dire les sommets qui n'ont pas encore été disposé dans la séquence
si c'est le cas, on met la var booleenne à True car on enleve un sommet de la liste
et on réitère la boucle jusqu'à ce qu'on n'ajoute plus de sommet à la séquence
"""
while degreInferieur :
degreInferieur = False
for i in listeSommet :
if self.voisinsRouge(i, listeSommet) <= 2 :
degreInferieur = True
sequence.append(i)
listeSommet.remove(i)
"""
On s'occupe ensuite des sommets qui possèdent plus de 2 voisins rouge.
On va compter le nombre de voisins rouge que possède un sommet dans la liste des sommets n'ayant pas
été ajouté à la séquence. Si un sommet possède au plus de 2 voisins rouge restant alors on l'ajoute à la séquence et on réitère la boucle
sinon on termine la boucle
"""
fin = False
while fin == False :
fin = True
for sommet in listeSommet :
nbVoisinsRougeRestant = 0
for i in listeSommet :
# on regarde si i est voisin de s
if i != sommet and self.couleurs[i] == 1 and self.estVoisin(sommet,i) :
nbVoisinsRougeRestant += 1
if nbVoisinsRougeRestant <= 2 :
fin = False
sequence.append(sommet)
listeSommet.remove(sommet)
return sequence
# fonction optionnelle de visualisation de graphe
# def affichageGrapheAleatoire(self):
# visualisation = Graph()
# # on ajoute les sommets
# visualisation.add_vertices(self.n)
# # on ajoute les aretes
# for i in range(self.n) :
# for j in range(i+1,self.n):
# if j in self.graphe[i][1] :
# visualisation.add_edges([(i,j)])
# # permet de ne pas avoir de doublons
# # si l'arete existe déjà on ne l'a crée pas
# # if visualisation.get_eid(j, i, directed=False, error=False) == -1 :
# # sequence aléatoire
# sequence = random.sample(range(0,self.n), self.n)
# result = self.verifSequenceDestructrice(sequence)
# print('sequence : ' + ' ' .join(str(sequence[i]) for i in sequence))
# print('La séquence est 2-Destructrice : ' + str(result))
# sequenceTrouver = self.trouverSequence()
# VerfiSequenceTrouver = self.verifSequenceDestructrice(sequenceTrouver)
# print("Sequence trouver : " + ' '.join(str(i) for i in sequenceTrouver))
# if VerfiSequenceTrouver : print("Le graphe possède une séquence 2-destructrice !")
# else : print("Le graphe ne possède pas de séquence 2-destructrice !")
# visual_style = {}
# visualisation.vs['label'] = range(self.n)
# visualisation.vs['color'] = [ "red" if couleur == 1 else "blue" for couleur in self.couleurs]
# layout = visualisation.layout("kk")
# plot(visualisation, layout = layout, vertex_label_color = "white")
# visualisation.write_dot("todo.dot")
|
355e2881f9b5528b4a083f26b970cafd42f3196d
|
[
"Python"
] | 3
|
Python
|
FournierBastien/Graphes
|
c344ee93d79a6227ededc5d0c21bd6bb3276908b
|
b65a978d7486a6fc15c28bf54ccb2f819a764404
|
refs/heads/master
|
<repo_name>khlyestovillarion/amazon_spider<file_sep>/spiders/spiders/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class ProductItem(Item):
# define the fields for your item here like:
keyword = Field()
total_matches = Field()
product_image = Field()
title = Field()
rank = Field()
brand = Field()
price = Field()
asin = Field()
prime = Field()
shipping_price = Field()
new_price = Field()
new_offers = Field()
used_price = Field()
used_offers = Field()
rating = Field()
number_of_reviews = Field()
category = Field()
number_of_items = Field()
<file_sep>/spiders/spiders/spiders/__init__.py
def identity(x):
return x
def cond_set(item, key, values, conv=identity):
"""Conditionally sets the first element of the given iterable to the given
dict.
The condition is that the key is not set in the item or its value is None.
Also, the value to be set must not be None.
"""
try:
if values:
value = next(iter(values))
cond_set_value(item, key, value, conv)
except StopIteration:
pass
def cond_set_value(item, key, value, conv=identity):
"""Conditionally sets the given value to the given dict.
The condition is that the key is not set in the item or its value is None.
Also, the value to be set must not be None.
"""
if item.get(key) is None and value is not None and conv(value) is not None:
item[key] = conv(value)<file_sep>/spiders/spiders/spiders/amazon.py
import string
import urllib
import urlparse
from itertools import islice
from scrapy.http import Request, FormRequest
from scrapy.spider import Spider
from scrapy.log import ERROR, WARNING, INFO, DEBUG
from spiders.items import ProductItem
from __init__ import cond_set, cond_set_value
try:
from captcha_solver import CaptchaBreakerWrapper
except Exception as e:
print '!!!!!!!!Captcha breaker is not available due to: %s' % e
class CaptchaBreakerWrapper(object):
@staticmethod
def solve_captcha(url):
msg("CaptchaBreaker in not available for url: %s" % url,
level=WARNING)
return None
class AmazonSpider(Spider):
name = 'amazon'
allowed_domains = ["amazon.com"]
start_urls = []
SEARCH_URL = 'http://www.amazon.com/s/ref=sr_as_oo?' \
'rh=i%3Aaps%2Ck%3A{search_term}&keywords={search_term}'
MAX_RETRIES = 3
user_agent = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:35.0) Gecko'
'/20100101 Firefox/35.0')
USER_AGENTS = {
'default': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:35.0) '\
'Gecko/20100101 Firefox/35.0',
'desktop': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:35.0) '\
'Gecko/20100101 Firefox/35.0',
'iphone_ipad': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_6 '\
'like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) '\
'Version/7.0 Mobile/11B651 Safari/9537.53',
'android_phone': 'Mozilla/5.0 (Android; Mobile; rv:35.0) '\
'Gecko/35.0 Firefox/35.0',
'android_pad': 'Mozilla/5.0 (Android; Tablet; rv:35.0) '\
'Gecko/35.0 Firefox/35.0',
'android': 'Mozilla/5.0 (Android; Tablet; rv:35.0) '\
'Gecko/35.0 Firefox/35.0',
}
def __init__(self,
url_formatter=None,
quantity=None,
page=None,
searchterms_str=None, searchterms_fn=None,
site_name=None,
product_url=None,
user_agent=None,
captcha_retries='10',
*args, **kwargs):
if user_agent is None or user_agent not in self.USER_AGENTS.keys():
self.log("Not available user agent type or it wasn't set."
" Default user agent will be used.", INFO)
user_agent = 'default'
if user_agent:
self.user_agent = self.USER_AGENTS[user_agent]
self.user_agent_key = user_agent
super(AmazonSpider, self).__init__(*args, **kwargs)
if site_name is None:
assert len(self.allowed_domains) == 1, \
"A single allowed domain is required to auto-detect site name."
self.site_name = self.allowed_domains[0]
else:
self.site_name = site_name
if url_formatter is None:
self.url_formatter = string.Formatter()
else:
self.url_formatter = url_formatter
if quantity is None:
self.log("No quantity specified. Will retrieve all products.",
INFO)
import sys
self.quantity = sys.maxint
else:
self.quantity = int(quantity)
if page is None:
self.log("No page specified. Will retrieve all products.",
INFO)
import sys
self.page = sys.maxint
else:
self.page = int(page)
self.product_url = product_url
self.searchterms = []
if searchterms_str is not None:
self.searchterms = searchterms_str.decode('utf-8').split(',')
elif searchterms_fn is not None:
with open(searchterms_fn, encoding='utf-8') as f:
self.searchterms = f.readlines()
else:
self.log("No search terms provided!", ERROR)
self.log("Created for %s with %d search terms."
% (self.site_name, len(self.searchterms)), INFO)
self.captcha_retries = int(captcha_retries)
self._cbw = CaptchaBreakerWrapper()
def make_requests_from_url(self, _):
"""This method does not apply to this type of spider so it is overriden
and "disabled" by making it raise an exception unconditionally.
"""
raise AssertionError("Need a search term.")
def start_requests(self):
"""Generate Requests from the SEARCH_URL and the search terms."""
for st in self.searchterms:
yield Request(
self.url_formatter.format(
self.SEARCH_URL,
search_term=urllib.quote_plus(st.encode('utf-8')),
),
meta={'search_term': st, 'remaining': self.quantity},
)
def parse(self, response):
if self._has_captcha(response):
result = self._handle_captcha(response, self.parse)
else:
result = self.parse_without_captcha(response)
return result
def parse_without_captcha(self, response):
if self._search_page_error(response):
remaining = response.meta['remaining']
search_term = response.meta['search_term']
self.log("For search term '%s' with %d items remaining,"
" failed to retrieve search page: %s"
% (search_term, remaining, response.request.url),
WARNING)
else:
prods_count = -1 # Also used after the loop.
for prods_count, request_or_prod in enumerate(
self._get_products(response)):
yield request_or_prod
prods_count += 1 # Fix counter.
request = self._get_next_products_page(response, prods_count)
if request is not None:
yield request
def _get_products(self, response):
remaining = response.meta['remaining']
search_term = response.meta['search_term']
total_matches = response.meta.get('total_matches')
prods = self._scrape_product_links(response)
if total_matches is None:
total_matches = self._scrape_total_matches(response)
if total_matches is not None:
response.meta['total_matches'] = total_matches
self.log("Found %d total matches." % total_matches, INFO)
else:
if hasattr(self, 'is_nothing_found'):
if not self.is_nothing_found(response):
self.log(
"Failed to parse total matches for %s" %
response.url,ERROR)
for i, (prod_item) in enumerate(islice(prods, 0, remaining)):
prod_item['keyword'] = search_term
prod_item['total_matches'] = total_matches
prod_item['rank'] = (i + 1) + (self.quantity - remaining)
yield prod_item
def _get_next_products_page(self, response, prods_found):
page_number = int(response.meta.get('page_number', 1))
link_page_attempt = response.meta.get('link_page_attempt', 1)
result = None
if prods_found is not None:
# This was a real product listing page.
if page_number < self.page:
remaining = response.meta['remaining']
remaining -= prods_found
next_page = self._scrape_next_results_page_link(response)
if next_page is None:
pass
else:
url = urlparse.urljoin(response.url, next_page)
new_meta = dict(response.meta)
new_meta['remaining'] = remaining
new_meta['page_number'] = page_number + 1
result = Request(url, self.parse, meta=new_meta, priority=1)
elif link_page_attempt > self.MAX_RETRIES:
self.log(
"Giving up on results page after %d attempts: %s" % (
link_page_attempt, response.request.url),
ERROR
)
else:
self.log(
"Will retry to get results page (attempt %d): %s" % (
link_page_attempt, response.request.url),
WARNING
)
# Found no product links. Probably a transient error, lets retry.
new_meta = response.meta.copy()
new_meta['link_page_attempt'] = link_page_attempt + 1
result = response.request.replace(
meta=new_meta, cookies={}, dont_filter=True)
return result
def _scrape_total_matches(self, response):
if response.css('#noResultsTitle'):
return 0
values = response.css('#s-result-count ::text').re(
'([0-9,]+)\s[Rr]esults for')
if not values:
values = response.css('#resultCount > span ::text').re(
'\s+of\s+(\d+(,\d\d\d)*)\s+[Rr]esults')
if not values:
values = response.css(
'#result-count-only-next'
).xpath(
'comment()'
).re(
'\s+of\s+(\d+(,\d\d\d)*)\s+[Rr]esults\s+'
)
if values:
total_matches = int(values[0].replace(',', ''))
else:
if not self.is_nothing_found(response):
self.log(
"Failed to parse total number of matches for: %s"
% response.url,
level=ERROR
)
total_matches = None
return total_matches
def _scrape_product_links(self, response):
products = response.xpath('//li[@class="s-result-item"]')
for pr in products:
if pr.xpath('.//h5[contains(@class, "s-sponsored-list-header")]'):
continue
product = ProductItem()
cond_set(product, 'title',
pr.xpath('.//h2/../@title').extract())
cond_set(product, 'product_image',
pr.xpath('.//img[@alt="Product Details"]/@src').extract())
cond_set(product, 'brand',
pr.xpath(
'.//div[@class="a-fixed-left-grid-col a-col-right"]'
'/div/div/span[2]/text()').extract())
cond_set(product, 'price',
pr.xpath(
'.//span[contains(@class,"s-price")]/text()'
).extract())
cond_set(product, 'asin', pr.xpath('@data-asin').extract())
if pr.xpath('.//i[contains(@class, "a-icon-prime")]'):
cond_set_value(product, 'prime', True)
else:
cond_set_value(product, 'prime', False)
cond_set(product, 'shipping_price', pr.xpath(
'.//span[contains(@class,"s-price")]/'
'following::span[2]/text()').re('(\d+.?\d+) shipping'))
new = pr.xpath('.//a[contains(text(),"new")]/span/text()')
if new:
cond_set(product, 'new_price', new.extract())
cond_set(product, 'new_offers', new[1].re('\d+'))
used = pr.xpath('.//a[contains(text(),"used")]/span/text()')
if used:
cond_set(product, 'used_price', used.extract())
cond_set(product, 'used_offers', used[1].re('\d+'))
cond_set(product, 'rating', pr.xpath(
'.//span[contains(@name,"'+product['asin']+'")]/span/a/i/span'
).re('(\d+.?\d+)'))
cond_set(product, 'number_of_reviews', pr.xpath(
'.//span[contains(@name,"'+product['asin']+'")]/'
'following::a[1]/text()').re('([\d+,?]+\d+)'))
cond_set(product, 'category', pr.xpath(
'.//span[contains(@class,"a-text-bold")]/text()'
).re('(.*):'))
number_of_items = pr.xpath(
'.//span[contains(@class,"a-text-bold")]/../text()'
).re('([\d+,?]+\d+)')
if number_of_items:
cond_set_value(product, 'number_of_items', number_of_items[0])
# product['url'] = pr.xpath('.//h2/../@href')[0].extract()
# cond_set(product, 'url', pr.xpath('.//h2/../@href').extract())
yield product
def _scrape_next_results_page_link(self, response):
next_pages = response.css('#pagnNextLink ::attr(href)').extract()
next_page_url = None
if len(next_pages) == 1:
next_page_url = next_pages[0]
elif len(next_pages) > 1:
self.log("Found more than one 'next page' link.", ERROR)
return next_page_url
def is_nothing_found(self, response):
txt = response.xpath('//h1[@id="noResultsTitle"]/text()').extract()
txt = ''.join(txt)
return 'did not match any products' in txt
def _search_page_error(self, response):
body = response.body_as_unicode()
return "Your search" in body \
and "did not match any products." in body
# Captcha handling functions.
def _has_captcha(self, response):
return '.images-amazon.com/captcha/' in response.body_as_unicode()
def _solve_captcha(self, response):
forms = response.xpath('//form')
assert len(forms) == 1, "More than one form found."
captcha_img = forms[0].xpath(
'//img[contains(@src, "/captcha/")]/@src').extract()[0]
self.log("Extracted capcha url: %s" % captcha_img, level=DEBUG)
return self._cbw.solve_captcha(captcha_img)
def _handle_captcha(self, response, callback):
captcha_solve_try = response.meta.get('captcha_solve_try', 0)
url = response.url
self.log("Captcha challenge for %s (try %d)."
% (url, captcha_solve_try),
level=INFO)
captcha = self._solve_captcha(response)
if captcha is None:
self.log(
"Failed to guess captcha for '%s' (try: %d)." % (
url, captcha_solve_try),
level=ERROR
)
result = None
else:
self.log(
"On try %d, submitting captcha '%s' for '%s'." % (
captcha_solve_try, captcha, url),
level=INFO
)
meta = response.meta.copy()
meta['captcha_solve_try'] = captcha_solve_try + 1
result = FormRequest.from_response(
response,
formname='',
formdata={'field-keywords': captcha},
callback=callback,
dont_filter=True,
meta=meta)
return result<file_sep>/requirements.txt
Scrapy==1.0.0
Twisted==15.2.1
argparse==1.2.1
cffi==1.1.2
cryptography==0.9.1
cssselect==0.9.1
enum34==1.0.4
idna==2.0
ipaddress==1.0.7
lxml==3.4.4
numpy==1.9.2
pyOpenSSL==0.15.1
pyasn1==0.1.7
pycparser==2.14
queuelib==1.2.2
six==1.9.0
w3lib==1.11.0
wsgiref==0.1.2
zope.interface==4.1.2
|
df7414f33642dc6e45645cdf957b2d9926d44fd4
|
[
"Python",
"Text"
] | 4
|
Python
|
khlyestovillarion/amazon_spider
|
d7c99c238bad3c15b026e26230808934b6fc6141
|
ec8e8d127103bbe0772e68430dd8d574f5b91463
|
refs/heads/master
|
<file_sep># This file is part of pyEPR: Energy participation ratio (EPR) design of quantum circuits in python
#
# Copyright (c) 2015 and later, <NAME> and <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the pyEPR nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
### Compatibility with python 2.7 and 3
from __future__ import division, print_function, absolute_import
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
### Configure logging
import logging
logger = logging.getLogger('pyEPR') # singleton
if not len(logger.handlers):
c_handler = logging.StreamHandler()
logger.propagate = False
# Jupyter notebooks already has a stream handler on the default log,
# Do not propage upstream to the root logger. https://stackoverflow.com/questions/31403679/python-logging-module-duplicated-console-output-ipython-notebook-qtconsole
# Format
c_handler.setLevel(logging.WARNING)
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s\n ::%(pathname)s:%(lineno)d: %(funcName)s\n') # unlike the root logger, a custom logger can’t be configured using basicConfig().
c_handler.setFormatter(c_format)
logger.addHandler(c_handler)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
# Import Checks Matplotlib & core packages
__STD_END_MSG = """\n Please install it and provide the system.PATH reference.
See online setup instructions at
https://github.com/zlatko-minev/pyEPR"""
try:
import matplotlib as mpl
except (ImportError, ModuleNotFoundError):
logger.warning("""IMPORT WARNING:
Could not find package `matplotlib`.
Plotting will not work unless you install it. """ + __STD_END_MSG)
try:
import pandas as pd
import warnings
warnings.filterwarnings('ignore', category=pd.io.pytables.PerformanceWarning)
except (ImportError, ModuleNotFoundError):
logger.warning("""IMPORT WARNING:
`pandas` python package not found.""" + __STD_END_MSG)
# Check for qutip
try:
import qutip
except (ImportError, ModuleNotFoundError):
logger.warning("""IMPORT WARNING:
`qutip` package not found.
Numerical diagonalization will not work.
You could try `conda install -c conda-forge qutip`
""" + __STD_END_MSG)
else:
del qutip, warnings
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
# pyEPR Specific
### Config setup
from . import config
try: # Check if we're in IPython.
__IPYTHON__
config.ipython = True
except:
config.ipython = False
config.__STD_END_MSG = __STD_END_MSG
### Convenience variable and function imports
from collections import OrderedDict
from .toolbox import *
from .toolbox_plotting import *
from .hfss import load_HFSS_project, get_active_design, get_active_project,\
HfssProject
from .hfss import release as hfss_release
from .core import Project_Info, pyEPR_HFSS, pyEPR_Analysis<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 19:30:12 2017
@author: Zlatko
"""
from __future__ import division, print_function, absolute_import # Python 2.7 and 3 compatibility
import numpy as np
#import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import rgb2hex
from .config import Plotting_Options
#==============================================================================
# Plotting
#==============================================================================
def legend_translucent(ax, values = [], loc = 0, alpha = 0.5, leg_kw = {}):
'''
values = [ ["%.2f" %k for k in RES] ]
Also, you can use the following:
leg_kw = dict(fancybox =True, fontsize = 9,
framealpha =0.5, ncol = 1)
blah.plot().legend(**leg_kw )
'''
if ax.get_legend_handles_labels() == ([], []):
return None
leg = ax.legend(*values, loc = loc, fancybox=True, **leg_kw)
leg.get_frame().set_alpha(alpha)
return leg
def cmap_discrete(n, cmap_kw = {}):
''' Discrete colormap.
cmap_kw = dict(colormap = plt.cm.gist_earth, start = 0.05, stop = .95)
cmap_kw
-----------------------
helix = True, Allows us to instead call helix from here
'''
if cmap_kw.pop('helix', False):
return cmap_discrete_CubeHelix(n, helix_kw = cmap_kw)
cmap_KW = dict(colormap = Plotting_Options.default_color_map, start = 0.05, stop = .95)
cmap_KW.update(cmap_kw)
return get_color_cycle(n+1, **cmap_KW)
def get_color_cycle(n, colormap=Plotting_Options.default_color_map, start=0., stop=1., format='hex'):
pts = np.linspace(start, stop, n)
if format == 'hex':
colors = [rgb2hex(colormap(pt)) for pt in pts]
return colors
def cmap_discrete_CubeHelix(n, helix_kw = {}):
'''
https://github.com/jiffyclub/palettable/blob/master/demo/Cubehelix%20Demo.ipynb
cube.show_discrete_image()
'''
from palettable import cubehelix
helix_KW = dict(start_hue=240., end_hue=-300.,min_sat=1., max_sat=2.5,
min_light=0.3, max_light=0.8, gamma=.9)
helix_KW.update(helix_kw)
cube = cubehelix.Cubehelix.make(n=n, **helix_KW)
return cube.mpl_colors
def xarr_heatmap(fg, title = None, kwheat = {}, fmt = ('%.3f', '%.2f'), fig = None):
''' Needs seaborn and xarray'''
fig = plt.figure() if fig == None else fig
df = fg.to_pandas()
# format indecies
df.index = [float(fmt[0]%x) for x in df.index]
df.columns = [float(fmt[1]%x) for x in df.columns]
import seaborn as sns
ax = sns.heatmap(df, annot=True, **kwheat)
ax.invert_yaxis()
ax.set_title(title)
ax.set_xlabel(fg.dims[1])
ax.set_ylabel(fg.dims[0])
__all__ = [ 'legend_translucent', 'cmap_discrete', 'get_color_cycle', 'xarr_heatmap']<file_sep>"""
Python (py) Energy-Participation-Ratio (EPR) package
"""
from setuptools import setup, find_packages
doclines = __doc__.split('\n')
setup(name='pyEPR',
version='0.6',
description = doclines[0],
long_description = '\n'.join(doclines[2:]),
author='<NAME>',
packages=['pyEPR'],
author_email='<EMAIL>',
license=' BSD-3-Clause',
install_requires=['numpy','pandas','pint','matplotlib']
)
<file_sep>"""
Created on Fri Oct 30 14:21:45 2015
@author: <NAME>
"""
#------------------------------------------------------------
# Directories
root_dir = r'D:\hfss\pyEPR'
class Dissipation_params:
''' Loss properties of various materials and surfaces '''
# bulk dielectric:
# refs: https://arxiv.org/abs/1308.1743
# http://arxiv.org/pdf/1509.01854.pdf
tan_delta_sapp = 1e-6 # tan(delta) for bulk surface
epsi = 10 # dielectric
# surface dielectric:
# ref: http://arxiv.org/pdf/1509.01854.pdf
th = 3e-9 # surface dielectric (dirt) thickness
eps_r = 10 # surface dielectric (dirt) constant
tan_delta_surf = 1e-3 # surface dielectric (dirt) loss tangent, tan(delta)
# thin-film surface loss:
# ref: https://arxiv.org/abs/1308.1743
surface_Rs = 250e-9# Ohms
# seams current loss:
# ref: http://arxiv.org/pdf/1509.01119.pdf
gseam = 1.0e3 # per Ohm meter: seam conductance
import matplotlib.pyplot as plt
class Plotting_Options:
default_color_map = plt.cm.viridis
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Internal
ipython = None
|
aa71dc54fafc264cd3a097f43c010fef95539c77
|
[
"Python"
] | 4
|
Python
|
jeffgertler/pyEPR
|
8810938d338fe1d17d24036f85bf6253ca5c9e76
|
178d943c46cbb48dfbc4c06d93cecd44033fa9e2
|
refs/heads/master
|
<repo_name>ArshGamare/mynewrepository<file_sep>/basics.py
student_grades = [3, 4, 5]
student_grades2 = (3, 4, 5)
student_grades.append(6)
print(student_grades)
|
263f27de82e55009cc83a9023693502c061d35de
|
[
"Python"
] | 1
|
Python
|
ArshGamare/mynewrepository
|
98facfb4748fe28f231d6aae3d69dab9de382a5c
|
5501869d6b156e52be81d7ef75a427d56e88df50
|
refs/heads/master
|
<repo_name>bittarani/Update<file_sep>/src/main/java/app/pp/TeamPlanningPage.java
package app.pp;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.Select;
public class TeamPlanningPage extends Page {
WebDriver driver;
public TeamPlanningPage(WebDriver driver) {
super(driver);
}
/**
* All WebElements are identified by @FindBy Annotation
*/
@FindBy(css = "a[title='Team Planning']")
WebElement teamPlanningbutton;
@FindBy(css = "h1[class='smb-HeaderGroup-title']")
WebElement getTitle;
@FindBy(css = "button[class ='smb-Button smb-Button--primary smb-Button--xs chr-AddNew-expand']")
WebElement addNewuserStory;
@FindBy(css = "span.chr-AddNew-label")
WebElement findNewkeyword;
@FindBy(css = "span[class='smb-Select-selectedValue']")
WebElement selectStory;
@FindBy(css = "button[aria-label='Filter']")
WebElement filterButton;
@FindBy(xpath = "//h3[text()='Sample Project Plan']")
WebElement textIsPresent;
/**
* WebElements for Adding new Button is clicked identified by @FindBy Annotation
*/
@FindBy(css = "span.chr-AddNew-label")
WebElement verifyText;
@FindBy(css = "//span[text()='Defect']")
WebElement addNewtype;
@FindBy(css = "span[aria-label='Collapse']")
WebElement navigateBackfromaddNewtype;
/**
* WebElements for Adding new Story by entering details identified by @FindBy Annotation
*/
@FindBy(css = "button[aria-label='Add with Details']")
WebElement creatingNewStory;
@FindBy(css = "a.chr-QuickDetailFormattedId-link")
WebElement AddnewDetailsText;
public String clickTeamplanningButton() {
teamPlanningbutton.click();
return getTitle.getText();
}
public boolean verifyAddnewbuttonisDisplayed() {
return addNewuserStory.isDisplayed();
}
public boolean verifyFilterbutton() {
return filterButton.isDisplayed();
}
public boolean verifySelectDropdownListButton() {
return selectStory.isDisplayed();
}
public String verifyText() {
return textIsPresent.getText();
}
//The addNew button is clicked
public String isAddnewButtonClicked() {
addNewuserStory.click();
return verifyText.getText();
}
public boolean selectDropdownlistOfstory(String story) {
Select userStory = new Select(selectStory);
userStory.selectByVisibleText(story);
return true;
}
public void clickFilterbutton() {
filterButton.click();
}
public void selectstoryTypefromList(String text) {
Select addtype = new Select(addNewtype);
addtype.selectByVisibleText(text);
}
public void navigateBack() {
navigateBackfromaddNewtype.click();
}
// creating a new story
public void addStorytypeWithdetails() {
creatingNewStory.click();
}
public String addNewtext() {
return AddnewDetailsText.getText();
}
}
<file_sep>/test-output/old/Default suite/methods.html
<h2>Methods run, sorted chronologically</h2><h3>>> means before, << means after</h3><p/><br/><em>Default suite</em><p/><small><i>(Hover the method name to see the test class name)</i></small><p/>
<table border="1">
<tr><th>Time</th><th>Delta (ms)</th><th>Suite<br>configuration</th><th>Test<br>configuration</th><th>Class<br>configuration</th><th>Groups<br>configuration</th><th>Method<br>configuration</th><th>Test<br>method</th><th>Thread</th><th>Instances</th></tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:05</td> <td>0</td> <td> </td><td title=">>TeamPlanningTestPage.setUp()[pri:0, instance:app.pp.TeamPlanningTestPage@66a3ffec]">>>setUp</td>
<td> </td><td> </td><td> </td><td> </td> <td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:12</td> <td>6976</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.clickMenubutton()[pri:1, instance:app.pp.TeamPlanningTestPage@66a3ffec]">clickMenubutton</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:14</td> <td>9385</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.isTeamplanningButtonclicked()[pri:2, instance:app.pp.TeamPlanningTestPage@66a3ffec]">isTeamplanningButtonclicked</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:15</td> <td>9832</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.isAddnewButtonDisplayed()[pri:3, instance:app.pp.TeamPlanningTestPage@66a3ffec]">isAddnewButtonDisplayed</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:16</td> <td>10830</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.isFilterButtonisDisplayed()[pri:4, instance:app.pp.TeamPlanningTestPage@66a3ffec]">isFilterButtonisDisplayed</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:16</td> <td>10980</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.isSelectdDropdownListPresent()[pri:5, instance:app.pp.TeamPlanningTestPage@66a3ffec]">isSelectdDropdownListPresent</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:16</td> <td>11022</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.isAddNewbuttonClicked()[pri:7, instance:app.pp.TeamPlanningTestPage@66a3ffec]">isAddNewbuttonClicked</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:16</td> <td>11158</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TeamPlanningTestPage.isAddwithDetailsButtonclicked()[pri:9, instance:app.pp.TeamPlanningTestPage@66a3ffec]">isAddwithDetailsButtonclicked</td>
<td>main@1845904670</td> <td></td> </tr>
<tr bgcolor="76ae94"> <td>19/02/22 20:57:16</td> <td>11269</td> <td> </td><td title="<<TeamPlanningTestPage.shutDownPage()[pri:0, instance:app.pp.TeamPlanningTestPage@66a3ffec]"><<shutDownPage</td>
<td> </td><td> </td><td> </td><td> </td> <td>main@1845904670</td> <td></td> </tr>
</table>
|
3a58731d466894b02c9954ab984e954f4292eb07
|
[
"Java",
"HTML"
] | 2
|
Java
|
bittarani/Update
|
bad21a8a31decf223646825e2c1f0cdb351e5035
|
f500cfe21eb8263619c296da4dbd3e6c52e89bf7
|
refs/heads/master
|
<repo_name>naokomada/AndroidRealmSample<file_sep>/README.md
# AndroidRealmSample
- reference
- https://realm.io/jp/docs/java/latest/
<file_sep>/app/src/main/java/com/example/admin/androidrealmsample/MainActivity.kt
package com.example.admin.androidrealmsample
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import io.realm.*
import io.realm.annotations.PrimaryKey
import java.nio.file.Files.size
import io.realm.Realm.Transaction.OnSuccess
import io.realm.RealmObject
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
useRealm()
}
fun useRealm() {
// 通常のJavaオブジェクトのようにモデルクラスを使用
val dog = Dog()
dog.name = "Rex"
dog.age = 1
// Realm全体の初期化
Realm.init(this)
// このスレッドのためのRealmインスタンスを取得
val realm = Realm.getDefaultInstance()
// 年齢が2未満のすべてのDogオブジェクトを取得する問い合わせを発行
val puppies = realm.where(Dog::class.java).lessThan("age", 2).findAll()
puppies.size // => まだRealmへは一つもオブジェクトが保存されていないので0を返します
// トランザクションの中でデータを永続化します
realm.beginTransaction()
val managedDog = realm.copyToRealm(dog) // unmanagedなオブジェクトを永続化
val person = realm.createObject(Person::class.java, UUID.randomUUID().toString()) // managedなオブジェクトを直接作成
person.dogs!!.add(managedDog)
realm.commitTransaction()
// データが更新されると、リスナーが呼びだされて更新を受け取ることができます。
puppies.addChangeListener(OrderedRealmCollectionChangeListener<RealmResults<Dog>> { results, changeSet ->
// Query results are updated in real time with fine grained notifications.
changeSet.insertions // => [0] is added.
})
// 別のスレッドから非同期に更新を実行することもできます
// realm.executeTransactionAsync(object : Realm.Transaction() {
// fun execute(bgRealm: Realm) {
// // トランザクションの開始とコミットは自動的に行われます
// val dog = bgRealm.where(Dog::class.java).equalTo("age", 1).findFirst()
// dog.setAge(3)
// }
// }, object : Realm.Transaction.OnSuccess() {
// fun onSuccess() {
// // 既存のクエリやRealmObjectは自動的に最新の情報に更新されます
// puppies.size // => 0("age"が2未満の犬は存在しなくなったので)
// managedDog.getAge() // => 3(既存オブジェクトは最新の状態に更新されるため)
// }
// })
}
}
// RealmObjectを継承することでモデルクラスを定義
public open class Dog(
public open var name: String = "",
public open var age: Int = 0
) : RealmObject()
public open class Person(
@PrimaryKey public open var id: String = "",
public open var name: String = "",
public open var dogs: RealmList<Dog>? = null // 1対多の関連をもつ
) : RealmObject()
|
a860e59d0821945882e67f5af68471b414ce0270
|
[
"Markdown",
"Kotlin"
] | 2
|
Markdown
|
naokomada/AndroidRealmSample
|
52e298f40e2e8b294eba9190fac9336cc30f4a83
|
094f2e81c12039538065ccc70b8098b92f99e479
|
refs/heads/master
|
<repo_name>emirhanakman/OtomasyonKutuphane<file_sep>/OtomasyonKutuphane/P_uye.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace OtomasyonKutuphane
{
public partial class P_uye : Form
{
public P_uye()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void P_uye_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from uyeler where aktifmi='P'";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
}
}
<file_sep>/OtomasyonKutuphane/yazarEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class yazarEkle : Form
{
public yazarEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
if ((textBox2.Text != null) && (textBox3.Text != null))
{
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into yazar(yazarAdi,yazarSoyadi,iletisim) values(@yazarAdi,@yazarSoyadi,@iletisim)";
sorgu2.Parameters.AddWithValue("@yazarAdi",textBox2.Text);
sorgu2.Parameters.AddWithValue("@yazarSoyadi",textBox3.Text);
sorgu2.Parameters.AddWithValue("@iletisim",textBox4.Text);
sorgu2.ExecuteNonQuery();
MessageBox.Show(" Kayıt Başarıyla Eklendi ! ");
}
baglanti.Close();
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
}
<file_sep>/OtomasyonKutuphane/oduncEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class oduncEkle : Form
{
public oduncEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;MultipleActiveResultSets=True;");
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void oduncEkle_Load(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "SELECT odunc.odID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,odunc.alkitadedi, DATEDIFF(day,vtarih,getdate()) as fark from odunc,personel,uyeler,kitapAdedi,kitaplar,iade where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='H' and odunc.odID=iade.odID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
DataTable dt3 = new DataTable();
using (SqlDataAdapter da3 = new SqlDataAdapter(@"select personel.perNO,personel.perAdi from personel",baglanti))
da3.Fill(dt3);
comboBox2.DataSource = new BindingSource(dt3, null);
comboBox2.DisplayMember = "perAdi";
comboBox2.ValueMember = "perNO";
//--------------- Üye TC no ve bilgileri çekildi
DataTable dt4 = new DataTable();
using (SqlDataAdapter da4 = new SqlDataAdapter(@"select uyeler.uyeTC,uyeler.uyeAdi from uyeler", baglanti))
da4.Fill(dt4);
comboBox3.DataSource = new BindingSource(dt4, null);
comboBox3.DisplayMember = "uyeAdi";
comboBox3.ValueMember = "uyeTC";
baglanti.Close();
}
int kayitsayisi;
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
int kayitsayisi;
if ((textBox2.Text != null) && (textBox3.Text != null))
{
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into odunc(kitapID,perNo,uyeTC,vTarih,vSure,alKitAdedi) values(@kitapID,@perNO,@uyeTC,@vTarih,@vSure,@alKitAdedi)";
sorgu2.Parameters.AddWithValue("@kitapID", comboBox1.SelectedValue);
sorgu2.Parameters.AddWithValue("@perNO", comboBox2.SelectedValue);
sorgu2.Parameters.AddWithValue("@uyeTC", comboBox3.SelectedValue);
sorgu2.Parameters.AddWithValue("@vTarih", dateTimePicker1.Value);
sorgu2.Parameters.AddWithValue("@vSure", textBox2.Text);
sorgu2.Parameters.AddWithValue("@alKitAdedi", textBox3.Text);
sorgu2.ExecuteNonQuery();
dataGridView1.Refresh();
oduncEkle_Load(null, null);
kayitsayisi = dataGridView1.RowCount;
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu3 = new SqlCommand();
sorgu3.Connection = baglanti;
sorgu3.CommandText = "insert into iade (odID,verdimi) values (@odID,@verdimi)";
sorgu3.Parameters.AddWithValue("@odID", kayitsayisi);
string verdimi = "H";
sorgu3.Parameters.AddWithValue("@verdimi", verdimi.ToString());
sorgu3.ExecuteNonQuery();
MessageBox.Show("Kitap " + comboBox3.SelectedValue + " No'lu Kullanıcıya Başarı İle Verildi. !");
oduncEkle_Load(null, null);
}
baglanti.Close();
}
private void button2_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
SqlCommand sorgu2 = new SqlCommand("SELECT odunc.odID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,kitapAdedi.kitAdedi, DATEDIFF(day,vtarih,getdate()) as fark from odunc,personel,uyeler,kitapAdedi,kitaplar,iade where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='H' and iade.odID=odunc.odID", baglanti);
SqlDataAdapter adp2 = new SqlDataAdapter(sorgu2);
DataTable dt2 = new DataTable();
adp2.Fill(dt2);
for (int i = 0; i < dt2.Rows.Count; i++)
{
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 0 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 14)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
}
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 15 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 30)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 31 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 60)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Orange;
}
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 61 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 250)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}
}
baglanti.Close();
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlDataAdapter da = new SqlDataAdapter("select kitapAdi,kitapID from kitaplar where kitapadi lIKE '%" + textBox1.Text + "%'",baglanti);
DataSet ds = new DataSet();
da.Fill(ds);
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "kitapAdi";
comboBox1.ValueMember = "kitapID";
baglanti.Close();
}
private void button3_Click(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void groupBox1_Enter_1(object sender, EventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged_2(object sender, EventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/yayIslemleri.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class yayIslemleri : Form
{
public yayIslemleri()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void yayIslemleri_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from yayinevi";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
string yayno;
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DialogResult tus = MessageBox.Show("Seçili Alandaki Yayınevi Bilgilerini Değiştirmek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
yayno = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from yayinevi where yayinID=@yayinID";
sorgu.Parameters.AddWithValue("@yayinID", yayno);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
textBox1.Text = dr["yayinID"].ToString();
textBox2.Text = dr["yayAdi"].ToString();
textBox3.Text = dr["adres"].ToString();
textBox4.Text = dr["tel"].ToString();
textBox5.Text = dr["mail"].ToString();
dr.Close();
}
baglanti.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update yayinevi set yayAdi=@yayAdi,adres=@adres,tel=@tel,mail=@mail where yayinID=@yayinID";
sorgu.Parameters.AddWithValue("@yayinID", textBox1.Text);
sorgu.Parameters.AddWithValue("@yayAdi", textBox2.Text);
sorgu.Parameters.AddWithValue("@adres", textBox3.Text);
sorgu.Parameters.AddWithValue("@tel", textBox4.Text);
sorgu.Parameters.AddWithValue("@mail", textBox5.Text);
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
yayIslemleri_Load(null, null);
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/yazarIslemleri.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class yazarIslemleri : Form
{
public yazarIslemleri()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void yazarIslemleri_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from yazar";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update yazar set yazarAdi=@yazarAdi,yazarSoyadi=@yazarSoyadi,iletisim=@iletisim where yazarID=@yazarID";
sorgu.Parameters.AddWithValue("@yazarID", textBox1.Text);
sorgu.Parameters.AddWithValue("@yazarAdi", textBox2.Text);
sorgu.Parameters.AddWithValue("@yazarSoyadi", textBox3.Text);
sorgu.Parameters.AddWithValue("@iletisim", textBox4.Text);
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
yazarIslemleri_Load(null, null);
}
string yazarno;
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DialogResult tus = MessageBox.Show("Seçili Alandaki Yazar Bilgilerini Değiştirmek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
yazarno = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from yazar where yazarID=@yazarID";
sorgu.Parameters.AddWithValue("@yazarID", yazarno);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
textBox1.Text = dr["yazarID"].ToString();
textBox2.Text = dr["yazarAdi"].ToString();
textBox3.Text = dr["yazarSoyadi"].ToString();
textBox4.Text = dr["iletisim"].ToString();
dr.Close();
baglanti.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult tus = MessageBox.Show("Seçili Alandaki Yazar Bilgilerini Silmek İstiyor Musunuz ? ", " - Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
yazarno = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "delete from yazar where yazarID=@yazarID";
sorgu.Parameters.AddWithValue("@yazarID", yazarno);
sorgu.ExecuteNonQuery();
yazarIslemleri_Load(null,null);
baglanti.Close();
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}<file_sep>/OtomasyonKutuphane/personelIslemleri.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class personelIslemleri : Form
{
public personelIslemleri()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void personelIslemleri_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from personel";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update personel set perAdi=@perAdi,perSoyad=@perSoyad,Tel=@Tel,perKadi=@perKadi,perSifre=@perSifre,yetki=@yetki,cinsiyet=@cinsiyet where perNO=@perNO";
sorgu.Parameters.AddWithValue("@perNO", textBox1.Text);
sorgu.Parameters.AddWithValue("@perAdi", textBox2.Text);
sorgu.Parameters.AddWithValue("@perSoyad", textBox3.Text);
sorgu.Parameters.AddWithValue("@Tel", textBox4.Text);
sorgu.Parameters.AddWithValue("@perKadi", textBox5.Text);
sorgu.Parameters.AddWithValue("@perSifre", textBox6.Text);
sorgu.Parameters.AddWithValue("@yetki", comboBox1.SelectedItem);
sorgu.Parameters.AddWithValue("@cinsiyet", comboBox2.SelectedItem);
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
personelIslemleri_Load(null, null);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
string perNO;
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DataTable dt2 = new DataTable();
using (SqlDataAdapter da2 = new SqlDataAdapter(@"select distinct personel.yetki from personel", baglanti))
da2.Fill(dt2);
comboBox1.DataSource = new BindingSource(dt2, null);
comboBox1.DisplayMember = "yetki"; //kolon adi görüntülenecek
comboBox1.ValueMember = "yetki"; //arkaplanda saklanacak veri
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(@"select distinct personel.cinsiyet from personel", baglanti))
da.Fill(dt);
comboBox2.DataSource = new BindingSource(dt, null);
comboBox2.DisplayMember = "cinsiyet"; //kolon adi görüntülenecek
comboBox2.ValueMember = "cinsiyet"; //arkaplanda saklanacak veri
//---------------------------------------------------------------------------------------------------------------
DialogResult tus = MessageBox.Show("Seçili Alandaki Personel Bilgilerini Değiştirmek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
perNO = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from personel where perNO=@perNO";
sorgu.Parameters.AddWithValue("@perNO", perNO);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
textBox1.Text = dr["perNO"].ToString();
textBox2.Text = dr["perAdi"].ToString();
textBox3.Text = dr["perSoyad"].ToString();
textBox4.Text = dr["Tel"].ToString();
textBox5.Text = dr["perKadi"].ToString();
textBox6.Text = dr["perSifre"].ToString();
comboBox1.SelectedItem = dr["yetki"].ToString();
comboBox2.SelectedItem = dr["cinsiyet"].ToString();
dr.Close();
}
baglanti.Close();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "delete from personel where perNO=@perNO";
sorgu.Parameters.AddWithValue("@perNO", textBox1.Text);
//---------
DialogResult tus = MessageBox.Show("Silme İşlemini Onaylıyor Musunuz ? ", " Silme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
sorgu.ExecuteNonQuery();
}
baglanti.Close();
personelIslemleri_Load(null, null);
}
}
}
<file_sep>/OtomasyonKutuphane/kitapEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class kitapEkle : Form
{
public kitapEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void kitapEkle_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select kitaplar.kitapID,kitaplar.kitapAdi,kitaplar.yazarID,kitaplar.kitSayfasi,kitaplar.yayinID,kitaplar.basimTarihi,kitapAdedi.kitAdedi from kitapAdedi,kitaplar where kitapAdedi.kitapID=kitaplar.kitapID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dtp = new DataTable();
adp.Fill(dtp);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dtp.Columns[i].ToString();
}
dataGridView1.DataSource = dtp;
dataGridView1.Refresh();
SqlCommand yukle = new SqlCommand("select kitaplar.kitapID from kitaplar", baglanti);
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT yazarID, yazarAdi FROM yazar", baglanti))
da.Fill(dt);
comboBox1.DataSource = new BindingSource(dt, null);
comboBox1.DisplayMember = "yazarAdi"; //kolon adi görüntülenecek
comboBox1.ValueMember = "yazarID"; //arkaplanda saklanacak veri
DataTable dtb = new DataTable();
using (SqlDataAdapter ad = new SqlDataAdapter(@"SELECT yayinID, yayAdi FROM yayinevi", baglanti))
ad.Fill(dtb);
comboBox2.DataSource = new BindingSource(dtb, null);
comboBox2.DisplayMember = "yayAdi"; //kolon adi görüntülenecek
comboBox2.ValueMember = "yayinID"; //arkaplanda saklanacak veri
DataTable dtbl = new DataTable();
using (SqlDataAdapter ad = new SqlDataAdapter(@"SELECT katID, cesit FROM kategori", baglanti))
ad.Fill(dtbl);
comboBox3.DataSource = new BindingSource(dtbl, null);
comboBox3.DisplayMember = "cesit"; //kolon adi görüntülenecek
comboBox3.ValueMember = "katID"; //arkaplanda saklanacak veri
}
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
int kayitsayisi;
if ((textBox2.Text != null) && (adet.Text !=null))
{
dataGridView1.Refresh();
DateTime dtarih = dateTimePicker1.Value;
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into kitaplar(kitapAdi,yazarID,kitSayfasi,basimTarihi,yayinID,katID) values(@kitapAdi,@yazarID,@kitSayfasi,@basimTarihi,@yayinID,@katID)";
sorgu2.Parameters.AddWithValue("@kitapAdi",textBox2.Text);
sorgu2.Parameters.AddWithValue("@yazarID",comboBox1.SelectedValue);
sorgu2.Parameters.AddWithValue("@kitSayfasi",textBox4.Text);
sorgu2.Parameters.AddWithValue("@basimTarihi",dateTimePicker1.Value);
sorgu2.Parameters.AddWithValue("@yayinID",comboBox2.SelectedValue);
sorgu2.Parameters.AddWithValue("@katID",comboBox3.SelectedValue);
sorgu2.ExecuteNonQuery(); // kitap ekleme işlemi tamamlandı.
//------------------ KİTAP ADEDİ EKLEME KISMI
kitapEkle_Load(null, null);
dataGridView1.Refresh();
kayitsayisi = dataGridView1.RowCount;
// MessageBox.Show(kayitsayisi.ToString()); en son eklenen kayıtın id değeri
SqlCommand sorgu3 = new SqlCommand();
sorgu3.Connection = baglanti;
sorgu3.CommandText = "insert into kitapAdedi(kitapID,kitAdedi) values(@kitID,@kitAdedi)";
sorgu3.Parameters.AddWithValue("@kitID", kayitsayisi);
sorgu3.Parameters.AddWithValue("@kitAdedi", adet.Text);
sorgu3.ExecuteNonQuery(); // kitap ekleme işlemi tamamlandı.
MessageBox.Show(" Kayıt Başarıyla Eklendi ! ");
textBox2.Text = "";
adet.Text = "";
textBox4.Text = "";
comboBox1.Text = "";
comboBox2.Text = "";
comboBox3.Text = "";
baglanti.Close();
kitapEkle_Load(null,null);
dataGridView1.Refresh();
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
textBox4.Text = "";
comboBox1.Text = "";
comboBox2.Text = "";
comboBox3.Text = "";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/odIade.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class odIade : Form
{
public odIade()
{
InitializeComponent();
}
string iade = "E";
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;MultipleActiveResultSets=True;");
private void odIade_Load(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "SELECT odunc.odID,odunc.kitapID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,odunc.alkitadedi, DATEDIFF(day,vtarih,getdate()) as fark from odunc,personel,uyeler,kitapAdedi,kitaplar,iade where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='H' and odunc.odID=iade.odID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update iade set verdimi=@verdimi where odID=@odID";
sorgu.Parameters.AddWithValue("@odID", dataGridView1.SelectedCells[0].Value.ToString());
sorgu.Parameters.AddWithValue("@verdimi", iade);
SqlCommand sorgu3 = new SqlCommand("Insert into iade(verdimi,iadeTarih) values(@verdimi,@iadeTarih)", baglanti);
sorgu3.Parameters.AddWithValue("@verdimi", iade);
sorgu3.Parameters.AddWithValue("@iadeTarih", DateTime.Now.Date);
sorgu3.Parameters.AddWithValue("@odID", dataGridView1.SelectedCells[0].Value.ToString());
sorgu3.ExecuteNonQuery();
sorgu.ExecuteNonQuery();
SqlCommand sorgu2 = new SqlCommand("Update kitapAdedi set kitAdedi+=1 where kitapID=@kitapID", baglanti);
sorgu2.Parameters.AddWithValue("@kitapID",dataGridView1.SelectedCells[1].Value.ToString());
sorgu2.ExecuteNonQuery();
baglanti.Close();
odIade_Load(null, null);
dataGridView1.Refresh();
MessageBox.Show("Kitap Başarı İle İade Edildi ! ");
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.Refresh();
}
}
}
<file_sep>/OtomasyonKutuphane/kitapListesi.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace OtomasyonKutuphane
{
public partial class kitapListesi : Form
{
public kitapListesi()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void kitapListesi_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select kitaplar.kitapID,kitaplar.kitapAdi,yazar.yazarAdi+' '+yazar.yazarSoyadi,kitaplar.kitSayfasi,yayinevi.yayAdi,kitaplar.basimTarihi,kitapAdedi.kitAdedi,kategori.cesit from yazar,kitapAdedi,kitaplar,yayinevi,kategori where kitapAdedi.kitapID=kitaplar.kitapID and yazar.yazarID=kitaplar.yazarID and kitaplar.yayinID=yayinevi.yayinID and kategori.katID=kitaplar.katID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/adminForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class adminForm : Form
{
public adminForm()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void pasifÜyeListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
P_uye pasifUye = new P_uye();
pasifUye.MdiParent = this;
pasifUye.WindowState = FormWindowState.Maximized;
pasifUye.Show();
}
private void kitapSorgulaToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void kitapListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
kitapListesi listeKitap = new kitapListesi();
listeKitap.MdiParent = this;
listeKitap.WindowState = FormWindowState.Maximized;
listeKitap.Show();
}
private void aktifÜyeListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
A_uye aktifUye = new A_uye();
aktifUye.MdiParent = this;
aktifUye.WindowState = FormWindowState.Maximized;
aktifUye.Show();
}
private void üyeListesiTamamıToolStripMenuItem_Click(object sender, EventArgs e)
{
uyeListesi uyeler = new uyeListesi();
uyeler.MdiParent = this;
uyeler.WindowState = FormWindowState.Maximized;
uyeler.Show();
}
private void personelListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
personeListe personel = new personeListe();
personel.MdiParent = this;
personel.WindowState = FormWindowState.Maximized;
personel.Show();
}
private void adminForm_Load(object sender, EventArgs e)
{
string isimm = Form1.isim;
this.Text = " - Kütüphane Otomasyonu - Yönetici Arayüzüne Hoşgeldiniz Sayın " + isimm;
baglanti.Open();
SqlCommand sorgu = new SqlCommand("select uyetc,DATEDIFF(day,vtarih,getdate()) as fark from odunc", baglanti);
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (Convert.ToInt32(dt.Rows[i]["fark"]) > 15)
{
DialogResult tus = MessageBox.Show("Gününde Geri İade Edilmemiş Kitaplar Var. Ayrıntılı Bilgi İçin Evet Tuşuna Basınız..", "Uyarı ! ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
oduncEkle odunc = new oduncEkle();
odunc.MdiParent = this;
odunc.WindowState = FormWindowState.Maximized;
odunc.Show();
}
break;
}
}
baglanti.Close();
baglanti.Close();
}
private void yayıneviEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
yayineviEkle yayineviEkle = new yayineviEkle();
yayineviEkle.MdiParent = this;
yayineviEkle.WindowState = FormWindowState.Maximized;
yayineviEkle.Show();
}
private void personelEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
personelEkle perEkle = new personelEkle();
perEkle.MdiParent = this;
perEkle.WindowState = FormWindowState.Maximized;
perEkle.Show();
}
private void yazarEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
yazarEkle ekleYazar = new yazarEkle();
ekleYazar.MdiParent = this;
ekleYazar.WindowState = FormWindowState.Maximized;
ekleYazar.Show();
}
private void kitapEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
kitapEkle eklekitap = new kitapEkle();
eklekitap.MdiParent = this;
eklekitap.WindowState = FormWindowState.Maximized;
eklekitap.Show();
}
private void yazarListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
yazarListesi YazarListe = new yazarListesi();
YazarListe.MdiParent = this;
YazarListe.WindowState = FormWindowState.Maximized;
YazarListe.Show();
}
private void üyeListesiToolStripMenuItem1_Click(object sender, EventArgs e)
{
uyeListesi uyeListe = new uyeListesi();
uyeListe.MdiParent = this;
uyeListe.WindowState = FormWindowState.Maximized;
uyeListe.Show();
}
private void yayıneviListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
yayineviListesi yayineviListe = new yayineviListesi();
yayineviListe.MdiParent = this;
yayineviListe.WindowState = FormWindowState.Maximized;
yayineviListe.Show();
}
private void üyeEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
uyeEkle uyeEkle = new uyeEkle();
uyeEkle.MdiParent = this;
uyeEkle.WindowState = FormWindowState.Maximized;
uyeEkle.Show();
}
private void kategoriListesiToolStripMenuItem_Click(object sender, EventArgs e)
{
kategoriListe kategoriListe = new kategoriListe();
kategoriListe.MdiParent = this;
kategoriListe.WindowState = FormWindowState.Maximized;
kategoriListe.Show();
}
private void kategoriEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
kategoriEkle kategoriEkle = new kategoriEkle();
kategoriEkle.MdiParent = this;
kategoriEkle.WindowState = FormWindowState.Maximized;
kategoriEkle.Show();
}
private void kitapGüncelleToolStripMenuItem_Click(object sender, EventArgs e)
{
kitapIslemleri kitapIslemleri = new kitapIslemleri();
kitapIslemleri.MdiParent = this;
kitapIslemleri.WindowState = FormWindowState.Maximized;
kitapIslemleri.Show();
}
private void ödünçİşlemleriToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void üyeDüzenlemeToolStripMenuItem_Click(object sender, EventArgs e)
{
uyeIslemleri uyeIslemleri = new uyeIslemleri();
uyeIslemleri.MdiParent = this;
uyeIslemleri.WindowState = FormWindowState.Maximized;
uyeIslemleri.Show();
}
private void yazarİşlemleriToolStripMenuItem_Click(object sender, EventArgs e)
{
yazarIslemleri yazarIslemleri = new yazarIslemleri();
yazarIslemleri.MdiParent = this;
yazarIslemleri.WindowState = FormWindowState.Maximized;
yazarIslemleri.Show();
}
private void kategoriİşlemleriToolStripMenuItem_Click(object sender, EventArgs e)
{
katDuzenle katDuzenle = new katDuzenle();
katDuzenle.MdiParent = this;
katDuzenle.WindowState = FormWindowState.Maximized;
katDuzenle.Show();
}
private void yayıneviToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void yayıneviİslemleriToolStripMenuItem_Click(object sender, EventArgs e)
{
yayIslemleri yayIslemleri = new yayIslemleri();
yayIslemleri.MdiParent = this;
yayIslemleri.WindowState = FormWindowState.Maximized;
yayIslemleri.Show();
}
private void personelGüncelleToolStripMenuItem_Click(object sender, EventArgs e)
{
personelIslemleri personelIslemleri = new personelIslemleri();
personelIslemleri.MdiParent = this;
personelIslemleri.WindowState = FormWindowState.Maximized;
personelIslemleri.Show();
}
private void ödünçTablosunuGörüntüleToolStripMenuItem_Click(object sender, EventArgs e)
{
odunc odunc = new odunc();
odunc.MdiParent = this;
odunc.WindowState = FormWindowState.Maximized;
odunc.Show();
}
private void ödünçKitapVerToolStripMenuItem_Click(object sender, EventArgs e)
{
oduncEkle oduncEkle = new oduncEkle();
oduncEkle.MdiParent = this;
oduncEkle.WindowState = FormWindowState.Maximized;
oduncEkle.Show();
}
private void ödünçKitaplarıGüncelleVeyaSilToolStripMenuItem_Click(object sender, EventArgs e)
{
oduncIslemleri oduncIslemleri = new oduncIslemleri();
oduncIslemleri.MdiParent = this;
oduncIslemleri.WindowState = FormWindowState.Maximized;
oduncIslemleri.Show();
}
private void personelRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
perRapor perRpr = new perRapor();
perRpr.MdiParent = this;
perRpr.WindowState = FormWindowState.Maximized;
perRpr.Show();
}
private void kitapRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
kitapRpr kitRpr = new kitapRpr();
kitRpr.MdiParent = this;
kitRpr.WindowState = FormWindowState.Maximized;
kitRpr.Show();
}
private void yayıneviRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
yayinRpr yayinRpr = new yayinRpr();
yayinRpr.MdiParent = this;
yayinRpr.WindowState = FormWindowState.Maximized;
yayinRpr.Show();
}
private void aktiÜyeRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
auyeRpr auyeRpr = new auyeRpr();
auyeRpr.MdiParent = this;
auyeRpr.WindowState = FormWindowState.Maximized;
auyeRpr.Show();
}
private void pasifToolStripMenuItem_Click(object sender, EventArgs e)
{
puyeRpr puyeRpr = new puyeRpr();
puyeRpr.MdiParent = this;
puyeRpr.WindowState = FormWindowState.Maximized;
puyeRpr.Show();
}
private void üyeListesiRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
uyeRpr uyeRpr = new uyeRpr();
uyeRpr.MdiParent = this;
uyeRpr.WindowState = FormWindowState.Maximized;
uyeRpr.Show();
}
private void yazarRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
yazarRpr yazarRpr = new yazarRpr();
yazarRpr.MdiParent = this;
yazarRpr.WindowState = FormWindowState.Maximized;
yazarRpr.Show();
}
private void katagoriRaporToolStripMenuItem_Click(object sender, EventArgs e)
{
katRpr katRpr = new katRpr();
katRpr.MdiParent = this;
katRpr.WindowState = FormWindowState.Maximized;
katRpr.Show();
}
private void ödünçKitapİadeEtToolStripMenuItem_Click(object sender, EventArgs e)
{
odIade iade = new odIade();
iade.MdiParent = this;
iade.WindowState = FormWindowState.Maximized;
iade.Show();
}
private void iadeEdilmişKitaplarıGörüntüleToolStripMenuItem_Click(object sender, EventArgs e)
{
iadeEdilenKit iade = new iadeEdilenKit();
iade.MdiParent = this;
iade.WindowState = FormWindowState.Maximized;
iade.Show();
}
}
}
<file_sep>/OtomasyonKutuphane/oduncIslemleri.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class oduncIslemleri : Form
{
public oduncIslemleri()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void button2_Click(object sender, EventArgs e)
{
}
string odID;
private void oduncIslemleri_Load(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "SELECT odunc.odID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,odunc.alkitadedi, DATEDIFF(day,vtarih,getdate()) as fark from odunc,personel,uyeler,kitapAdedi,kitaplar,iade where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='H' and odunc.odID=iade.odID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
//------------------- KİTAP ID VE BİLGİLERİ COMBOBOX1'E ÇEKİLİYOR..
DataTable dt2 = new DataTable();
using (SqlDataAdapter da2 = new SqlDataAdapter(@"select kitaplar.kitapID,kitaplar.kitapAdi from kitaplar", baglanti))
da2.Fill(dt2);
comboBox1.DataSource = new BindingSource(dt2, null);
comboBox1.DisplayMember = "kitapAdi"; //kolon adi görüntülenecek
comboBox1.ValueMember = "kitapID"; //arkaplanda saklanacak veri
//-------------- Personel ID ve Ad Soyad Bilgileri Combobox2'ye Çekildi.
DataTable dt3 = new DataTable();
using (SqlDataAdapter da3 = new SqlDataAdapter(@"select personel.perNO,personel.perAdi from personel", baglanti))
da3.Fill(dt3);
comboBox2.DataSource = new BindingSource(dt3, null);
comboBox2.DisplayMember = "perAdi";
comboBox2.ValueMember = "perNO";
//--------------- Üye TC no ve bilgileri çekildi
DataTable dt4 = new DataTable();
using (SqlDataAdapter da4 = new SqlDataAdapter(@"select uyeler.uyeTC,uyeler.uyeAdi from uyeler", baglanti))
da4.Fill(dt4);
comboBox3.DataSource = new BindingSource(dt4, null);
comboBox3.DisplayMember = "uyeAdi";
comboBox3.ValueMember = "uyeTC";
}
private void button1_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DialogResult tus = MessageBox.Show("Seçili Alandaki Ödünç Bilgilerini Düzenlemek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
odID = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from odunc where odID=@odID";
sorgu.Parameters.AddWithValue("@odID", odID);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
comboBox1.SelectedItem = dr["kitapID"].ToString();
comboBox2.SelectedItem = dr["perNO"].ToString();
comboBox3.SelectedItem = dr["uyeTC"].ToString();
textBox2.Text = dr["vSure"].ToString();
textBox3.Text = dr["alKitAdedi"].ToString();
dateTimePicker1.Text = dr["vTarih"].ToString();
dr.Close();
baglanti.Close();
}
}
private void button2_Click_1(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update odunc set kitapID=@kitapID,perNO=@perNO,uyeTC=@uyeTC,vTarih=@vTarih,vSure=@vSure,alKitAdedi=@alKitAdedi where odID=@odID";
sorgu.Parameters.AddWithValue("@odID", odID);
sorgu.Parameters.AddWithValue("@kitapID", comboBox1.SelectedValue);
sorgu.Parameters.AddWithValue("@perNO", comboBox2.SelectedValue);
sorgu.Parameters.AddWithValue("@uyeTC", comboBox3.SelectedValue);
sorgu.Parameters.AddWithValue("@vTarih", dateTimePicker1.Value);
sorgu.Parameters.AddWithValue("@vSure", textBox2.Text);
sorgu.Parameters.AddWithValue("@alKitAdedi", textBox3.Text);
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
oduncIslemleri_Load(null, null);
}
}
}
<file_sep>/OtomasyonKutuphane/kitapIslemleri.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class kitapIslemleri : Form
{
public kitapIslemleri()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update kitaplar set kitapAdi=@adi,yazarID=@yazar,kitSayfasi=@sayfaSayisi,basimTarihi=@dtarih,yayinID=@yayinID,katID=@katID where kitapID=@kitapID";
sorgu.Parameters.AddWithValue("@kitapID", textBox1.Text);
sorgu.Parameters.AddWithValue("@adi", textBox2.Text);
sorgu.Parameters.AddWithValue("@yazar", comboBox2.SelectedValue);
sorgu.Parameters.AddWithValue("@sayfaSayisi", textBox4.Text);
sorgu.Parameters.AddWithValue("@yayinID", comboBox3.SelectedValue);
sorgu.Parameters.AddWithValue("@katID", comboBox4.SelectedValue);
sorgu.Parameters.AddWithValue("@dtarih", dateTimePicker1.Value);
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
kitapIslemleri_Load(null, null);
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void kitapIslemleri_Load(object sender, EventArgs e)
{
groupBox1.Hide();
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select kitaplar.kitapID,kitaplar.kitapAdi,yazar.yazarAdi+' '+yazar.yazarSoyadi,kitaplar.kitSayfasi,yayinevi.yayAdi,kitaplar.basimTarihi,kitapAdedi.kitAdedi from yazar,kitapAdedi,kitaplar,yayinevi where kitapAdedi.kitapID=kitaplar.kitapID and yazar.yazarID=kitaplar.yazarID and kitaplar.yayinID=yayinevi.yayinID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
string kitapno;
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (baglanti.State==ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "delete from kitaplar where kitapID=@kitapID";
sorgu.Parameters.AddWithValue("@kitapID", textBox1.Text);
//---------
SqlCommand kadedisil = new SqlCommand();
kadedisil.Connection = baglanti;
kadedisil.CommandText = "delete from kitapAdedi where kitapID=@kitapID";
kadedisil.Parameters.AddWithValue("@kitapID", textBox1.Text);
DialogResult tus = MessageBox.Show("Silme İşlemini Onaylıyor Musunuz ? ", " Silme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
kadedisil.ExecuteNonQuery();
sorgu.ExecuteNonQuery();
}
baglanti.Close();
kitapIslemleri_Load(null, null);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
groupBox1.Show();
}
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
//-------------------------------------------------------------------------------------------------------------
DataTable dt2 = new DataTable();
using (SqlDataAdapter da2 = new SqlDataAdapter(@"select yazar.yazarID,yazar.yazarAdi from yazar", baglanti))
da2.Fill(dt2);
comboBox2.DataSource = new BindingSource(dt2, null);
comboBox2.DisplayMember = "yazarAdi"; //kolon adi görüntülenecek
comboBox2.ValueMember = "yazarID"; //arkaplanda saklanacak veri
//---------------------------------------------------------------------------------------------------------------
DataTable dt3 = new DataTable();
using (SqlDataAdapter da3 = new SqlDataAdapter(@"SELECT yayinID, yayAdi FROM yayinevi", baglanti))
da3.Fill(dt3);
comboBox3.DataSource = new BindingSource(dt3, null);
comboBox3.DisplayMember = "yayAdi"; //kolon adi görüntülenecek
comboBox3.ValueMember = "yayinID"; //arkaplanda saklanacak veri
//-------------------------------------
DataTable dt4 = new DataTable();
using (SqlDataAdapter da4 = new SqlDataAdapter(@"select kategori.katID,kategori.cesit from kategori", baglanti))
da4.Fill(dt4);
comboBox4.DataSource = new BindingSource(dt4, null);
comboBox4.DisplayMember = "cesit"; //kolon adi görüntülenecek
comboBox4.ValueMember = "katID"; //arkaplanda saklanacak veri
//--------------------------------------------------
DialogResult tus = MessageBox.Show("Seçili Alandaki Kitap Bilgilerini Değiştirmek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
kitapno = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from kitaplar where kitapID=@kitapID";
sorgu.Parameters.AddWithValue("@kitapID", kitapno);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
textBox1.Text = dr["kitapID"].ToString();
textBox2.Text = dr["kitapAdi"].ToString();
comboBox2.SelectedItem = dr["yazarID"].ToString();
textBox4.Text = dr["kitSayfasi"].ToString();
dateTimePicker1.Text = dr["basimTarihi"].ToString();
comboBox3.SelectedItem = dr["yayinID"].ToString();
comboBox4.SelectedItem = dr["katID"].ToString();
dr.Close();
baglanti.Close();
}
}
}
}
<file_sep>/OtomasyonKutuphane/uyeEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace OtomasyonKutuphane
{
public partial class uyeEkle : Form
{
public uyeEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
if ((textBox1.Text != null) && (textBox2.Text != null) && (textBox3.Text != null) && (textBox4.Text != null))
{
string uyeTC = textBox1.Text;
DateTime dtarih = dateTimePicker1.Value;
SqlCommand sorgu = new SqlCommand();
sorgu.CommandText = "select * from uyeler where uyeTC=@uyeTC";
sorgu.Connection = baglanti;
sorgu.Parameters.AddWithValue("@uyeTC", uyeTC);
object sonuc = sorgu.ExecuteScalar();
if (sonuc != null)
{
MessageBox.Show(" Böyle Bir Üye Numarası Zaten Var!", "HATA !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into uyeler(uyeTC,uyeAdi,uyeSoyadi,Mail,Tel,kayitTarihi,aktifmi) values(" + textBox1.Text + ",'" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + dtarih.Date + "','" + comboBox1.SelectedItem +"')";
sorgu2.ExecuteNonQuery();
MessageBox.Show(" Kayıt Başarıyla Eklendi ! ");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
comboBox1.Text = "";
}
}
baglanti.Close();
}
private void uyeEkle_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("A");
comboBox1.Items.Add("P");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
comboBox1.Text = "";
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/yayineviEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class yayineviEkle : Form
{
public yayineviEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
if ((textBox1.Text != null) && (textBox2.Text != null) && (textBox3.Text != null) && (textBox4.Text != null))
{
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into yayinevi(yayAdi,adres,tel,mail) values(@yayAdi,@adres,@tel,@mail)";
sorgu2.Parameters.AddWithValue("@yayAdi",textBox1.Text);
sorgu2.Parameters.AddWithValue("@adres",textBox4.Text);
sorgu2.Parameters.AddWithValue("@tel",textBox2.Text);
sorgu2.Parameters.AddWithValue("@mail",textBox3.Text);
sorgu2.ExecuteNonQuery();
MessageBox.Show(" Kayıt Başarıyla Eklendi ! ");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
baglanti.Close();
}
catch (Exception Ex)
{
MessageBox.Show(" Bir Hata Oluştu ! ","Değerlerinizi Kontrol Ediniz !"+Ex.Message,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void yayineviEkle_Enter(object sender, EventArgs e)
{
//button1.Click+=button1_Click;
}
private void yayineviEkle_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/odunc.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace OtomasyonKutuphane
{
public partial class odunc : Form
{
public odunc()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void odunc_Load(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "SELECT odunc.odID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,odunc.alkitadedi, DATEDIFF(day,vtarih,getdate()) as fark from odunc,personel,uyeler,kitapAdedi,kitaplar,iade where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='H' and iade.odID=odunc.odID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
SqlCommand sorgu2 = new SqlCommand("SELECT odunc.odID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,odunc.alkitadedi, DATEDIFF(day,vtarih,getdate()) as fark from odunc,personel,uyeler,kitapAdedi,kitaplar,iade where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='H' and iade.odID=odunc.odID", baglanti);
SqlDataAdapter adp2 = new SqlDataAdapter(sorgu2);
DataTable dt2 = new DataTable();
adp2.Fill(dt2);
for (int i = 0; i < dt2.Rows.Count; i++)
{
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 0 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 14)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
}
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 15 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 30)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 31 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 60)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Orange;
}
if (Convert.ToInt32(dt2.Rows[i]["fark"]) >= 61 && Convert.ToInt32(dt2.Rows[i]["fark"]) <= 250)
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}
}
baglanti.Close();
}
private void button1_Click_1(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/katDuzenle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class katDuzenle : Form
{
public katDuzenle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;MultipleActiveResultSets=True;");
private void katDuzenle_Load(object sender, EventArgs e)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from kategori";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
string katno;
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update kategori set cesit=@cesit,icerik=@icerik where katID=@katID";
sorgu.Parameters.AddWithValue("@katID", katno);
sorgu.Parameters.AddWithValue("@cesit", textBox2.Text);
sorgu.Parameters.AddWithValue("@icerik", textBox3.Text);
sorgu.ExecuteNonQuery();
}
baglanti.Close();
katDuzenle_Load(null,null);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DialogResult tus = MessageBox.Show("Seçili Alandaki Kategori Bilgilerini Değiştirmek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
katno = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from kategori where katID=@katID";
sorgu.Parameters.AddWithValue("@katID", katno);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
textBox1.Text = dr["katID"].ToString();
textBox2.Text = dr["cesit"].ToString();
textBox3.Text = dr["icerik"].ToString();
katDuzenle_Load(null,null);
dr.Close();
baglanti.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "delete from kategori where katID=@katID";
sorgu.Parameters.AddWithValue("@katID",textBox1.Text);
//---------
DialogResult tus = MessageBox.Show("Silme İşlemini Onaylıyor Musunuz ? ", " Silme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
katDuzenle_Load(null, null);
}
}
}
<file_sep>/OtomasyonKutuphane/iadeEdilenKit.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class iadeEdilenKit : Form
{
public iadeEdilenKit()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=Administrator;initial catalog=kutuphaneDB;Integrated Security=True;MultipleActiveResultSets=True;");
private void iadeEdilenKit_Load(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "SELECT odunc.odID,kitaplar.kitapAdi,personel.perAdi+' '+personel.perSoyad,uyeler.uyeTC,odunc.vTarih,odunc.vSure,iade.iadeTarih,DATEDIFF(day,vtarih,getdate()) as fark from iade,odunc,personel,uyeler,kitapAdedi,kitaplar where odunc.perNO=personel.perNO and uyeler.uyeTC=odunc.uyeTC and kitaplar.kitapID=odunc.kitapID and kitaplar.kitapID=kitapAdedi.kitapID and iade.verdimi='E' and iade.odID=odunc.odID";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
}
}
<file_sep>/OtomasyonKutuphane/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
namespace OtomasyonKutuphane
{
public partial class Form1 : Form
{
public static string isim;
adminForm admin = new adminForm(); // admin arayüzü
anaForm form = new anaForm(); // kullanıcı arayüzü
public Form1()
{
InitializeComponent();
}
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;Initial Catalog=MTSK;User ID=sa;Password=<PASSWORD>");
// ana bilgisayar ile bağlantı sağlandı.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Yönetici");
comboBox1.Items.Add("Kullanıcı");
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void pictureBox2_Click(object sender, EventArgs e)
{
Application.Exit(); // uygulamayı kapat
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
textBox2.PasswordChar = '*';
checkBox1.Text = "Şifreyi Göster";
}
// Sifre gizleme kısmı
else
{
textBox2.PasswordChar = '\0';
checkBox1.Text = "Şifreyi Gizle";
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) // none formu hareket ettirme kısmı
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void pictureBox3_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized; // formu minimize ayara alma
}
private void button1_Click(object sender, EventArgs e)
{
string kadi = textBox1.Text;
string sifre = textBox2.Text;
SqlCommand sorgu = new SqlCommand(); // giriş paneli sorgusu kullanıcı
SqlCommand sorguYonetici = new SqlCommand(); // admin giriş sorgu
try
{
if (comboBox1.Text == "Yönetici")
{
sorgu.Connection = baglanti; // sorgumuzu bağlantıyla eşitledik
sorgu.CommandText = "Select * from GIRIS where yetki='1' and kullanici='" + kadi + "' and sifre='" + sifre + "'"; // veritabanından kullanıcı adı ve şifreyi sorguluyoruz.
object sonuc = sorgu.ExecuteScalar(); // sorgudan yanıt geliyor mu ?
SqlDataReader oku = sorgu.ExecuteReader();
if (sonuc == null)
{
MessageBox.Show("Kullanıcı Adınız veya Şifreniz Hatalı ! \n\n Yönetici Bölümünde Yetkiniz Yok ! ", "Hata ! ", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox1.Text = ""; // Eğer kullanıcı adı ve şifre doğru değilse, textboxları temizle.
textBox2.Text = "";
}
else
{
isim = kadi;
adminForm yoneticiArayuz = new adminForm();
this.Hide();
yoneticiArayuz.Show();
baglanti.Close(); // kullanıcı adı ve şifre doğruysa ve sayfaya yönlendirdiyse bağlantıyı kapat.*/
}
}
if (comboBox1.Text == "Kullanıcı")
{
sorguYonetici.Connection = baglanti; // sorgumuzu bağlantıyla eşitledik
sorguYonetici.CommandText = "Select * from personel where yetki='0' and perKadi='" + kadi + "' and perSifre='" + sifre + "'"; // veritabanından kullanıcı adı ve şifreyi sorguluyoruz.
object sonucYonetici = sorguYonetici.ExecuteScalar(); // admin yanıt geliyor mu ?
SqlDataReader okuYonetici = sorguYonetici.ExecuteReader();
if (sonucYonetici == null)
{
MessageBox.Show("Kullanıcı Adınız veya Şifreniz Hatalı ! \n\n Kullanıcı Yetkiniz Yok !", "Hata ! ", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox1.Text = ""; // Eğer kullanıcı adı ve şifre doğru değilse, textboxları temizle.
textBox2.Text = "";
}
else
{
isim = kadi;
this.Hide(); // şifre ve kullanıcı adı doğruysa ana sayfaya yönlendir.
form.Show();
baglanti.Close(); // kullanıcı adı ve şifre doğruysa ve sayfaya yönlendirdiyse bağlantıyı kapat.
}
}
}
catch (Exception)
{
throw;
}
}
private void label3_Click(object sender, EventArgs e)
{
}
}
}<file_sep>/OtomasyonKutuphane/kategoriEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class kategoriEkle : Form
{
public kategoriEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
if ((textBox2.Text != null) && (textBox3.Text != null))
{
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into kategori(cesit,icerik) values(@cesit,@icerik)";
sorgu2.Parameters.AddWithValue("@cesit",textBox2.Text);
sorgu2.Parameters.AddWithValue("@icerik",textBox3.Text);
sorgu2.ExecuteNonQuery();
MessageBox.Show(" Kayıt Başarıyla Eklendi ! ");
textBox2.Text = "";
textBox3.Text = "";
}
baglanti.Close();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void kategoriEkle_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/OtomasyonKutuphane/uyeIslemleri.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OtomasyonKutuphane
{
public partial class uyeIslemleri : Form
{
public uyeIslemleri()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void uyeIslemleri_Load(object sender, EventArgs e)
{
DataTable dt2 = new DataTable();
using (SqlDataAdapter da2 = new SqlDataAdapter(@"select uyeler.aktifmi from uyeler", baglanti))
da2.Fill(dt2);
comboBox1.DataSource = new BindingSource(dt2, null);
comboBox1.DisplayMember = "aktifmi"; //kolon adi görüntülenecek
comboBox1.ValueMember = "aktifmi"; //arkaplanda saklanacak veri
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from uyeler";
SqlDataAdapter adp = new SqlDataAdapter(sorgu);
DataTable dt = new DataTable();
adp.Fill(dt);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].DataPropertyName = dt.Columns[i].ToString();
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
baglanti.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "update uyeler set uyeAdi=@uyeAdi,uyeSoyadi=@uyeSoyadi,Mail=@Mail,Tel=@Tel,kayitTarihi=@kayitTarihi,aktifmi=@aktifmi where uyeTC=@uyeTC";
sorgu.Parameters.AddWithValue("@uyeTC", textBox1.Text);
sorgu.Parameters.AddWithValue("@uyeAdi", textBox2.Text);
sorgu.Parameters.AddWithValue("@uyeSoyadi", textBox3.Text);
sorgu.Parameters.AddWithValue("@Mail", textBox4.Text);
sorgu.Parameters.AddWithValue("@kayitTarihi",dateTimePicker1.Value);
sorgu.Parameters.AddWithValue("@Tel",textBox5.Text);
sorgu.Parameters.AddWithValue("@aktifmi", comboBox1.SelectedValue);
DialogResult tus = MessageBox.Show("Güncelleme İşlemini Onaylıyor Musunuz ? ", " Güncelleme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
uyeIslemleri_Load(null, null);
}
string uyeTCNO;
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//--------------------------------------------------
DialogResult tus = MessageBox.Show("Seçili Alandaki Üye Bilgilerini Değiştirmek İstiyor Musunuz ? ", " - Güncelleme ve Silme İşlemi - ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tus == DialogResult.Yes)
{
uyeTCNO = dataGridView1.SelectedCells[0].Value.ToString();
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "select * from uyeler where uyeTC=@uyeTC";
sorgu.Parameters.AddWithValue("@uyeTC", uyeTCNO);
SqlDataReader dr = sorgu.ExecuteReader();
dr.Read();
textBox1.Text = dr["uyeTC"].ToString();
textBox2.Text = dr["uyeAdi"].ToString();
textBox3.Text = dr["uyeSoyadi"].ToString();
textBox4.Text = dr["Mail"].ToString();
textBox5.Text = dr["Tel"].ToString();
dateTimePicker1.Text = dr["kayitTarihi"].ToString();
comboBox1.SelectedItem = dr["aktifmi"].ToString();
dr.Close();
baglanti.Close();
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
SqlCommand sorgu = new SqlCommand();
sorgu.Connection = baglanti;
sorgu.CommandText = "delete from uyeler where uyeTC=@uyeTC";
sorgu.Parameters.AddWithValue("@uyeTC", textBox1.Text);
DialogResult tus = MessageBox.Show("Silme İşlemini Onaylıyor Musunuz ? ", " Silme İşlemi ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (tus == DialogResult.Yes)
{
sorgu.ExecuteNonQuery();
}
baglanti.Close();
uyeIslemleri_Load(null, null);
}
}
}
<file_sep>/OtomasyonKutuphane/personelEkle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace OtomasyonKutuphane
{
public partial class personelEkle : Form
{
public personelEkle()
{
InitializeComponent();
}
SqlConnection baglanti = new SqlConnection("Data Source=ADMINISTRATOR;initial catalog=kutuphaneDB;Integrated Security=True;");
private void button1_Click(object sender, EventArgs e)
{
if (baglanti.State == ConnectionState.Closed)
{
baglanti.Open();
}
if ((textBox1.Text != null) && (textBox2.Text != null) && (textBox3.Text != null) && (textBox4.Text != null) && (textBox5.Text != null))
{
string perNO = textBox1.Text;
SqlCommand sorgu = new SqlCommand();
sorgu.CommandText = "select * from personel where perNO=@perNO";
sorgu.Connection = baglanti;
sorgu.Parameters.AddWithValue("@perNO", perNO);
object sonuc = sorgu.ExecuteScalar();
if (sonuc != null)
{
MessageBox.Show(" Böyle Bir Personel Numarası Zaten Var!", "HATA !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
SqlCommand sorgu2 = new SqlCommand();
sorgu2.Connection = baglanti;
sorgu2.CommandText = "insert into personel(perNO,perAdi,perSoyad,Tel,perSifre,perKadi,yetki,cinsiyet) values(" + textBox1.Text + ",'" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox6.Text + "','" + textBox5.Text + "','" + comboBox2.SelectedItem + "','" + comboBox1.SelectedItem + "')";
sorgu2.ExecuteNonQuery();
MessageBox.Show(" Kayıt Başarıyla Eklendi ! ");
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
comboBox1.Text = "";
comboBox2.Text = "";
int sayi = Convert.ToInt32(textBox1.Text) + 1;
textBox1.Text = Convert.ToString(sayi);
}
}
baglanti.Close();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void personelEkle_Load(object sender, EventArgs e)
{
comboBox2.Items.Add("1");
comboBox2.Items.Add("0");
comboBox1.Items.Add("K");
comboBox1.Items.Add("E");
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
comboBox1.Text = "";
comboBox2.Text = "";
}
}
}
|
7751c35493ae96e2661896b4d1a219ee27630d22
|
[
"C#"
] | 21
|
C#
|
emirhanakman/OtomasyonKutuphane
|
5665d5132ae3ee09c2508135a73203b6db3a11eb
|
e9716dd29fda6c8cda2e9532af9bb7f3262b035a
|
refs/heads/master
|
<file_sep>function initDiscussionEditing(discussion,target){
var original = discussion.text_field.replace(/\r/g,'');
var mouseDown, mouseUp, top, left, drag;
var range_txt;
var range = {};
var vision_text_history_count = discussion.vision_text_history.length;
var queryPaper = ".paper";
var paper = $(queryPaper);
$(target)
.on('mousedown', function (e) {
mouseDown = e;
$("#old_suggestion_popup").hide();
console.log(mouseDown);
})
.on('keydown', function (e) {
if(e.keyCode == 16){
mouseDown = e;
} else if ((e.shiftKey && (e.keyCode <= 40 && e.keyCode >= 37) || (e.ctrlKey && e.keyCode == 65))) {
drag = true;
} else if(!(e.keyCode <= 40 && e.keyCode >= 37)) {
e.preventDefault();
}
})
.on('keyup', function (e) {
if(e.keyCode == 16){
if(drag && paper.hasClass('passed_deadline')) {
popupProvider.showOkPopup({message:'עבר הזמן לעריכת המסמך'});
mouseDown = null;
} else {
if(!mouseDown || paper.hasClass('paper-closed'))
return;
e.stopPropagation();
mouseUp = e;
var err = false;
left = Math.ceil((mouseDown.clientX + mouseUp.clientX) / 2 - 97);
top = Math.min(mouseDown.clientY, mouseUp.clientY) - $("#new_suggestion_popup").height() - 40 + $(window).scrollTop() + 35;
range_txt = window.getSelection().toString();
// if we got here after flipping the discussion content to textarea get range easily
if ($(this).attr('id') === "discussion_content_textarea") {
range = $(this).getSelection();
range_txt = range.text;
}
if (range.length > 0 || range_txt.length > 0) {
if (!user._id) {
popupProvider.showLoginPopup({}, function (err, result) {
if (!err)
window.location = window.location;
});
return false;
}
// ie and accessibility work around
if (navigator.appName === "Microsoft Internet Explorer" || isNaN(top)) {
$("#pop_suggest_bt").click();
} else {
var offset = $('#discussion_edit_container').offset();
$("#old_suggestion_popup").hide();
$("#new_suggestion_popup")
.css({ top: top - offset.top - 50, left: (e.pageX - 97) - offset.left, opacity: 0 })
.show()
.animate({ top: '-=20px', opacity: 1 }, 100, 'linear');
setTimeout(function () {
mouseDown = null;
}, 500)
}
} else {
mouseDown = null;
}
}
}
})
.on('dragstart', function (e) {
e.preventDefault();
})
.on('mousemove', function(e){
if(mouseDown){
drag = true;
} else {
drag = false;
}
})
.on('mouseup', function (e) {
if(drag && paper.hasClass('passed_deadline')) {
popupProvider.showOkPopup({message:'עבר הזמן לעריכת המסמך'});
mouseDown = null;
} else {
if(!mouseDown || paper.hasClass('paper-closed'))
return;
e.stopPropagation();
mouseUp = e;
var err = false;
left = Math.ceil((mouseDown.clientX + mouseUp.clientX) / 2 - 97);
top = Math.min(mouseDown.clientY, mouseUp.clientY) - $("#new_suggestion_popup").height() - 40 + $(window).scrollTop() + 35;
range_txt = window.getSelection().toString();
// if we got here after flipping the discussion content to textarea get range easily
if ($(this).attr('id') === "discussion_content_textarea") {
range = $(this).getSelection();
range_txt = range.text;
} else {
var flag = discoverRange(range_txt);
if (range_txt.length == 0) {
mouseDown = null
return false;
}
if (flag === false || (range.start == 0 && range.end == 0)) {
var popupConfig = {};
popupConfig.message = "קרתה תקלה, נסה שנית";
popupConfig.removeCloseButton = true;
popupConfig.onOkCilcked = function (e) {
e.preventDefault();
clicked = 'ok';
// if (flag === false){
$('#discussion_content').hide();
$('#discussion_content_textarea').show();
$('#discussion_content_textarea').css('height', $("#discussion_content_textarea")[0].scrollHeight);
$('.read_less').click();
$('.read_more').click();
// }
$.colorbox.close();
},
popupProvider.showOkPopup(popupConfig);
return false;
}
}
if (range.length > 0 || range_txt.length > 0) {
if (!user._id) {
popupProvider.showLoginPopup({}, function (err, result) {
if (!err)
window.location = window.location
});
return false;
}
if (navigator.appName === "Microsoft Internet Explorer") {
$("#pop_suggest_bt").click();
} else {
var offset = $('#discussion_edit_container').offset();
$("#old_suggestion_popup").hide();
$("#new_suggestion_popup")
.css({ top: top - offset.top - 50, left: (e.pageX - 97) - offset.left, opacity: 0 })
.show()
.animate({ top: '-=20px', opacity: 1 }, 100, 'linear');
setTimeout(function () {
mouseDown = null;
}, 500)
}
} else {
mouseDown = null;
}
}
});
$('body').on('click', '.edit_content', function(){
var clicked = 'ok';
// if (flag === false){
$('#discussion_content').hide();
$('#discussion_content_textarea').show();
$('#discussion_content_textarea').css('height', $("#discussion_content_textarea")[0].scrollHeight);
$('.read_less').click();
$('.read_more').click();
$('#discussion_content_textarea').focus();
});
$('#pop_suggest_bt, .pop_suggest_bt').click(function (e) {
e.stopPropagation();
e.preventDefault();
$("#send_suggestion").data('executing', false);
$("#send_suggestion").removeClass('disable');
$('#discussion_content_txt').text('"' + range_txt + '"');
dust.render('request-change-dialog',{
orig_text: range_txt,
delete: $(this).hasClass('delete'),
add: $(this).hasClass('add')
},function(err,out){
$.colorbox({
html:out,
width:'910px',
height:'580px',
onComplete:function(){
$(".popup-window").hide();
$('.request-change-dialog textarea#discussion_suggest').focus();
if($('#discussion_suggest').attr('disabled')){
$('.request-change-dialog #discussion_explanation').focus();
$('.request-change-dialog textarea#discussion_suggest').val(" ");
}
}
});
});
});
function discoverRange(text) {
var t = text;
var occurences = original.split(text).length - 1;
if (occurences > 1) return false;
if (original.indexOf(text) != -1) {//no linebreaks
range.start = original.indexOf(text);
range.end = range.start + text.length;
} else {//chrome
t = text.replace(" \n", "\n");
if (original.indexOf(t) != -1) {
range.start = original.indexOf(t);
range.end = range.start + t.length;
} else {
t = text.replace(/\r/g, "");
if (original.indexOf(t) != -1) {
range.start = original.indexOf(t);
range.end = range.start + t.length;
} else {
range.start = 0;
range.end = 0;
console.log("error");
}
}
}
console.log("start=" + range.start + " | end=" + range.end);
}
$('body').on('click', "#cancelWriteCommentBT", function () {
$.colorbox.close();
});
$('body').mouseup(function (e) {
var target = $(e.target);
if (!target.is('.popup-window') || !target.parents('.popup-window').length) {
$(".popup-window").hide();
}
// var container = $(".arrow_box_container");
//
// if ((container.has(e.target).length === 0) && (!$(e.target).hasClass('grading_button'))) {
// container.hide();
// $('.slider-is-open').removeClass('slider-is-open');
// }
});
$('body').on('click', "#send_suggestion", function () {
var $this = $(this);
if ($this.data('executing')) {
return;
}
$this.data('executing', true);
$this.addClass('disable');
var part = {start: range.start, end: range.end, text: $(".request-change-dialog textarea#discussion_suggest").val()};
// todo i have replaced vision with original, see that it works
//arrange spaces
if (original[part.end - 1] == " " && part.text[part.text.length - 1] != " ")
part.text += " ";
// in case of editing existing suggestion
if ($('#send_suggestion').data('edit') === true) {
$('#send_suggestion').data('edit', false);
var sugg_id = $('#send_suggestion').data('suggestion-id');
db_functions.editSuggestion(sugg_id, part.text, function (err, data) {
if (!err) {
$this.data('executing', false);
$this.removeClass('disable');
// hide edit box
$('#write-comment').hide();
// change text of suggestion
$('#suggestions_wrapper').find('[data-id=' + sugg_id + ']').find('.alternative_part').text(part.text);
// edit button text back t what it used to be
$('#send_suggestion').text('הצע');
}
})
} else {
// create new suggestion
var explanation = $("#discussion_explanation").val();
var user_info = {
user_logged_in: user.first_name ? true : false,
action_done: (user.actions_done_by_user && user.actions_done_by_user.suggestion_on_object) ? true : false,
action_name: "suggestion_on_object",
tokens_owned: user.tokens ? user.tokens : 0,
price: gamification_price['suggestion_on_discussion']
}
db_functions.addSuggestionToDiscussion(discussion._id, vision_text_history_count, [part], explanation, user_info, function doWork(err, data) {
if (!err) {
activateMailNotifications();
// vision was updated while composing suggestion
if (data.cancel === true) {
updateVisionAndSuggestionText(data);
$this.data('executing', false);
$this.removeClass('disable');
return;
}
$this.data('executing', false);
$this.removeClass('disable');
if (data != 'canceled') {
$.colorbox.close();
/*
$("textarea#discussion_suggest").val('');
$("#user_tokens").text(data.updated_user_tokens);*/
render_suggestion(data, true);
scrollTo('#' + data.id);
$(".deals-box").show();
$('#suggestion_number').text(Number($('#suggestion_number').text()) + 1);
suggestions_list.push(data);
}
} else {
var err = err;
if (err.responseText == "a suggestion with this indexes already exist") {
popupProvider.showOkPopup({message: "????? ???? ??? ????? ?????? ?????"});
}
}
});
}
});
function displaySuggestionsRanges() {
var lines = [];
suggestions_list = suggestions_list.sort(function(a,b){
return a.parts[0].start - b.parts[0].start;
});
var lastIndex = 0;
var tab_counter = 0;
$.each(suggestions_list, function (index, suggestion) {
//var html = $('#discussion_content').html();
var text = original.substr(suggestion.parts[0].start, suggestion.parts[0].end - suggestion.parts[0].start);
// console.log(text);
if (suggestion.parts[0].start > original.length || suggestion.parts[0].start < lastIndex) {
console.log('range problem |' + suggestion.id);
return
}
text = text.replace(/(\r?\n)/g, '<br/>');
lines.push(original.substr(lastIndex,suggestion.parts[0].start - lastIndex).replace(/(\r?\n)/g, '<br/>'));
lines.push('<a href="javascript:;" data-tab="' + tab_counter + '" data-id="' + suggestion.id + '" class="marker_1 paper-mark">' + text + '</a>');
tab_counter++;
lastIndex = suggestion.parts[0].end;
});
lines.push(original.substr(lastIndex,original.length - lastIndex).replace(/(\r?\n)/g, '<br/>'));
$('#discussion_content').html(lines.join(''));
}
$("#discussion_content").on("click", ".marker_1", function () {
if (!mouseDown) {
$('#suggestionTab').click();
var id = $(this).data('id');
$('html, body').animate({
scrollTop: $("li.suggestion-item[data-id=" + id + "]").offset().top
}, 500);
}
});
$("body").on("keydown", ".marker_1", function (e) {
if (e.keyCode == 13) {
$('#suggestionTab').click();
var id = $(this).data('id');
$('html, body').animate({
scrollTop: $("li.suggestion-item[data-id=" + id + "]").offset().top
}, 500);
}
});
$("#old_suggestion_popup").click(function(){
$('#suggestionTab').click();
var id = $(this).data('suggestion');
$('html, body').animate({
scrollTop: $("li.suggestion-item[data-id=" + id + "]").offset().top
}, 500);
});
var fadeTO;
$("#discussion_content").on('mouseenter','.marker_1',function(e){
if ($("#discussion_content").parent().find(".icon-close").hasClass('hide')) return;
var position = $(e.target).offset();
var offset = $('#discussion_edit_container').offset();
left = Math.ceil((position.left + $(e.target).width() / 2) - 97);
if(fadeTO)
clearTimeout(fadeTO);
fadeTO = null;
$(this).unbind('mouseleave').one('mouseleave',function(){
fadeTO = setTimeout(function(){
$("#old_suggestion_popup").hide().data('suggestion','');
},500);
});
var suggestionId = $(this).data('id');
var $popup = $("#old_suggestion_popup");
if($popup.data('suggestion') == suggestionId)
return;
$popup
.css({ top: position.top - offset.top - 50, left: left - offset.left, opacity: 0 })
.show()
.animate({ opacity: 1 }, 100, 'linear').data('suggestion',suggestionId);
});
function updateVisionAndSuggestionText(data) {
// update vision
$('#discussion_content_textarea').val(data.text_field);
$('#discussion_content').html(data.text_field.replace(/\n/g, '<br />'));
original = $('#discussion_content_textarea').val();
// update original text
var original_text = original.substring(range.start, range.end);
$('#discussion_content_txt').text('"' + original_text + '"');
// update history
vision_text_history_count = data.discussion_vision_text_history.length;
var popupConfig = {};
popupConfig.popup_text =
"שים לב: מסמך החזון עודכן לאחרונה. בדוק שההצעה שלך עדיין בתוקף ושהטקסט שסימנת לא השתנה";
popupProvider.showOkPopup({message: popupConfig.popup_text});
}
function activateMailNotifications() {
db_functions.activateMailNotification(user._id, function (err, data) {});
};
var suggestions_list, approved_suggestions_list;
var suggestion_count, approved_count, post_count = 0;
var init = function(){
init_suggestions(function(){
init_approved(function(){
init_posts(function(){
go_to_hash();
});
});
});
};
var go_to_hash = function(){
//check if there is a hash, and if so find it and open it
if(window.location.hash){
var hash = window.location.hash,
hash_item = $(hash);
if(hash_item.hasClass('suggestion-item')){
scrollTo(hash, 1000);
} else if(hash_item.hasClass('discussion_suggestion_post')){
var suggestion = hash_item.closest('li.suggestion-item');
suggestion.find('.toggleComments').click();
scrollTo(hash, 1000);
} else if(hash_item.closest('#tab-3')) {
$('.tab a[href=#tab-3]').click();
if(hash_item.data('level') == 0){
scrollTo($(hash), 1000);
} else {
var main_msg = hash_item.closest('li[data-level=0]');
toggleMessage('message-' + main_msg.data('id'));
scrollTo($(hash), 1000);
}
}
}
};
var init_suggestions = function(callback){
// get change suggestions and render
db_functions.getSuggestionByDiscussion(discussion._id, 0, 0, function (err, data) {
if (err) return false;
$('#suggestion_number').text(data.meta.total_count);
suggestions_list = data.objects;
displaySuggestionsRanges();
suggestion_count = suggestions_list.length;
$.each(suggestions_list,function(i,suggestion){
render_suggestion(suggestion);
});
while(suggestion_count > 0){};
callback();
});
};
var init_approved = function(callback){
db_functions.getApprovedSuggestionsByDiscussion(discussion._id, 0, 0, function (err, data) {
approved_suggestions_list = data.objects || {};
approved_count = approved_suggestions_list.length;
$.each(approved_suggestions_list,function(i,suggestion){
render_suggestion(suggestion,false,true);
});
while(approved_count > 0){};
callback();
$('#approved_suggestion_number').text(data.meta.total_count);
});
};
var sub_post_count = 0;
//render a main post and responses if the post has any recursively
var render_post = function(type, data, level, callback){
sub_post_count++;
data.user_avatar = avatar;
dust.render('forum_post', data, function(err, out){
if(!err){
if(type == 'main')
$('.post-messages-container ul.main_container').append(out);
else {
console.log('reply');
$('ul.replies-' + data.parent_id).prepend(out);
}
}
//check if the post has any responses
if(post_groups[data._id] && post_groups[data._id].length > 0) {
var child_posts = post_groups[data._id];
$.each(child_posts, function(i, child_post){
var new_level = level + 1;
child_post.time = new Date(child_post.creation_date).format('dd.mm.yyyy');
child_post.date = new Date(child_post.creation_date).format('HH:MM');
child_post.level = level + 1;
child_post.reply_level = level + 2;
if(child_post.text.length > 140)
child_post.text_short = child_post.text.substring(0, 140) + '...';
child_post.last = level == 2 ? true : false;
child_post.replies = post_groups[child_post._id] && post_groups[child_post._id].length > 0 ? post_groups[child_post._id].length : 0;
render_post('child', child_post, new_level);
});
}
sub_post_count--;
if (sub_post_count == 0 && callback)
callback();
});
};
var init_posts = function(callback) {
var data = {
discussion_id: discussion._id,
limit: 0,
sorts: {'creation_date': -1},
offset: 0
};
db_functions.getDiscussionPosts(data, function(err, data){
page_posts = data.page_posts;
post_groups = data.post_groups;
count = data.count;
var post_count = page_posts.length;
$('#comments_number').html(count);
$.each(page_posts, function(i, post){
post.time = new Date(post.creation_date).format('dd.mm.yyyy');
post.date = new Date(post.creation_date).format('HH:MM');
post.level = 0;
post.reply_level = 1;
if(post.text.length > 140)
post.text_short = post.text.substring(0, 140) + '...';
post.hidden = true;
post.replies = post_groups[post._id] && post_groups[post._id].length > 0 ? post_groups[post._id].length : 0;
render_post('main', post, 0, function(){
post_count--;
if(post_count == 0) {
callback();
}
});
});
// check if we have passed teh deadline
if(new Date(discussion.deadline) < new Date()) {
passed_deadline = true;
$('.paper').addClass('passed_deadline');
$('.paper-edit-text').html('עבר הזמן לעריכת המסמך');
$('.paper-edit-title').hide();
$('#tab-3').addClass('hidden');
$('.message-reply').addClass('hidden');
}
});
};
init();
//render change suggestion
function render_suggestion(suggestion, use_animation, is_approved) {
// get original text and alternative text
if (suggestion.parts && suggestion.parts.length) {
if (is_approved){
suggestion.original_part = suggestion.replaced_text;
suggestion.alternative_part = suggestion.parts[0].text;
// set text for context popup
if (suggestion.context_before && suggestion.context_after && suggestion.context_before !== "undefined") {
suggestion.context_before = suggestion.context_before.substring(Math.max(suggestion.context_before.length - 400, 0), suggestion.context_before.length);
suggestion.context_after = suggestion.context_after.substring(0, Math.min(suggestion.context_after.length, 400));
}
}else{
suggestion.original_part = function () {
var from = suggestion.parts[0].start;
var end = suggestion.parts[0].end;
return original.substr(from, end - from);
};
// set text for context popup
suggestion.context_before = original.substring(Math.max(suggestion.parts[0].start - 400, 0), suggestion.parts[0].start, suggestion.parts[0].start);
suggestion.context_after = original.substring(suggestion.parts[0].end, Math.min(original.length, suggestion.parts[0].end + 400));
suggestion.alternative_part = function () {
return suggestion.parts[0].text;
};
}
suggestion.is_approved = !!is_approved;
suggestion.avatar = avatar;
suggestion.no_post = paper.hasClass('passed_deadline');
//suggestion = paper.hasClass('passed_deadline');
suggestion.to_delete = suggestion.parts.length && (suggestion.parts[0].text == " ");
dust.render('discussion_suggestion_new', suggestion, function (err, out) {
$(is_approved ? '#approved_suggestions_wrapper' : '#suggestions_wrapper').append(out);
image_autoscale($((is_approved ? '#approved_suggestions_wrapper' : '#suggestions_wrapper') +' .auto-scale img'));
// if (use_animation == true) {
// var bgc = $('.suggestion_holder').last().css('background-color');
// $('.suggestion_holder ').last().css('background-color', 'pink');
// $('.suggestion_holder ').last().animate({backgroundColor: bgc}, 3000);
// }
// check if got here after not logged user tryed to grade suggestion
var action = getURLParameter('action');
if (action !== "null") {
var id = window.location.hash;
action = ".button_" + action;
if (!id) return false;
$(id).find('.suggestion_bottom_segment ' + action + ' input').click();
}
db_functions.getCommentsBySuggestion(suggestion.id, function (err, data) {
suggestion.comments = data.objects;
dust.renderArray('discussion_suggestion_comment_new',suggestion.comments,null,function(err,out){
$('#' + suggestion._id).find('ul').html(out);
});
});
suggestion_count--;
approved_count--;
});
}
return null;
};
$('#approved_suggestions_wrapper,#suggestions_wrapper').on('click','.toggleComments',function(){
var $li = $(this).parents('.suggestion-item');
var suggestionId = $li.data('id');
var message = $li.find('.primary-message');
if (message.hasClass('message-closed')) {
message.removeClass('message-closed');
message.addClass('message-open');
$li.find('>ul,>.reply-to-message').removeClass("hide");
// Transform the button to a close button
$li.find(' button.review-respond').html('<i class="icon icon-small-pad-left icon-close-comments"></i>סגור');
var suggestion = $.grep(suggestions_list,function(suggestion){
return suggestion.id == suggestionId;
})[0];
if(!suggestion)
return;
}
else if (message.hasClass('message-open')) {
message.removeClass('message-open');
message.addClass('message-closed');
$li.find('>ul,>.reply-to-message').addClass("hide");
// Transform the button to a replies button
$li.find(' button.review-respond').html('תגובות');
}
});
$('#approved_suggestions_wrapper,#suggestions_wrapper').on('click', '.add_suggestion_comment', function (e) {
activateMailNotifications();
var $parent = $(this).parents('.reply-to-message');
var $suggestion = $parent.parents('.suggestion-item');
var $commentList = $parent.siblings('ul');
var post_or_suggestion_id = $suggestion.data('id');
var suggestion = $.grep(suggestions_list,function(suggestion){
return suggestion.id == post_or_suggestion_id;
})[0];
if(!suggestion)
return;
var text = $parent.find('textarea').val();
if (text.trim() == '') return false;
var add_comment = $(this).parent('.add_comment');
db_functions.addCommentToSuggestion(post_or_suggestion_id, discussion._id, text, function (err, comment) {
$parent.find('textarea').val('');
var file = $('#tab-1 .post-new-message-upload')[0].files[0];
if(!file)
return afterPost();
popupProvider.showLoading({message:'מעלה קובץ...'});
uploadAttachment(comment._id,file,afterPost);
function afterPost(error,attachment){
if(error)
return console.error(error);
if(attachment){
comment.attachment = attachment;
$.colorbox.close();
}
dust.render('discussion_suggestion_comment_new',comment,function(err,out){
$commentList.prepend(out);
});
$('.new_post .post-new-message-upload').val('');
$('.new_post .post-new-message-attachment').hide();
}
});
});
$('.container').on('change','.post-new-message-upload',function(e){
var file = this.files[0];
if(file){
var $parent = $(this).parents('.post-new-message-body');
$parent.find('.post-new-message-attachment label').text(file.name);
$parent.find('.post-new-message-attachment').show();
}
});
function uploadAttachment( id, file,cbk){
var client = new XMLHttpRequest();
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file);
client.open("put", "/api/post_suggestion_attachments/" + id + "?discussion_id=" + discussion._id, true);
//client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4){
if(client.status < 200 || client.status >= 300)
return cbk(client.status);
var attachment = JSON.parse(client.responseText);
cbk(null,attachment);
}
}
}
// toggle edit class to open/close contxt popup window or edit suggestion button
$('#approved_suggestions_wrapper, #suggestions_wrapper').on('mouseenter', '.change_proposal',function (e) {
var edit_window = $(this).parent().find('.edit_window');
var window_height = edit_window.height();
var window_padding = parseInt(edit_window.css("padding-top"));
var window_border = parseInt(edit_window.css("border-top-width"));
$(this).parents('.suggestion-item').toggleClass('show_context_popup');
// $(this).parents('.suggestion_wrapper').toggleClass('show_edit_button');
//set window top
edit_window.css('top', 10 - window_height - (window_padding * 2 + window_border * 2));
}).on('mouseleave', '.message-text', function () {
$('.suggestion-item').removeClass('show_context_popup');
});
$('#suggestions_wrapper').on('click', '.edit_window', function (e) {
$('.btn-read-more').click();
scrollTo('#discussion_edit_container');
})
}
function toggleComments(ui) {
}<file_sep>
var listCommon = (function(){
return {
reloadList: function (uiContainerId,original_type ,template_name,query,cbk ){
var jqueryContainer = $('#'+uiContainerId) ;
if(!query){
query={};
}
db_functions.getListItems(original_type, query, function(err,data){
jqueryContainer.css('height',jqueryContainer.height());
jqueryContainer.empty();
$.each(data.objects,function(index,elm)
{
elm._index = index;
elm.get_link = function()
{
return '/' + original_type + '/' + elm._id;
};
elm.get_link_uri = function()
{
return encodeURIComponent(elm.get_link());
}
if(template_name == "discussion_list_item_new") {
elm.deadline = new Date(elm.deadline) < new Date() ? null : elm.deadline;
}
});
dust.renderArray(template_name,data.objects,null,function(err,out)
{
jqueryContainer.append(out);
jqueryContainer.css('height','');
// $('#mainList img').autoscale();
});
if(cbk)
cbk();
});
}
}
})() ;<file_sep>
var common = require('./../common')
models = require('../../models'),
async = require('async');
var OpinionShaperResource = module.exports = common.BaseModelResource.extend(
{
init:function () {
this._super(models.OpinionShaper);
this.allowed_methods = ['get'];
this.fields = common.user_public_fields;
}
}
)
<file_sep>var config = {};
config.upload_dir = require('path').join(__dirname,'..','public','cdn');
config.sendgrid_user = '<EMAIL>';
config.sendgrid_key = 'a0oui08x';
config.systemEmail = '<EMAIL>'/*'<EMAIL>'*/;
config.systemEmailName = 'SHEATUFIM';
config.mailjet_user = process.env['SMTP-USER'] || '1ee0d830159fafb52746b375e1403294';
config.mailjet_pass = process.env['SENDGRID_KEY'] || '';
config.DB_URL = process.env['MONGOLAB_URI'] || 'mongodb://localhost/idemos';
config.ROOT_PATH = process.env.ROOT_PATH || 'http://dev.empeeric.com';
// facebook app params
config.fb_auth_params = {
appId : process.env['FACEBOOK_APPID'] || '',
appSecret: process.env['FACEBOOK_SECRET'] || '',
appName: process.env['FACEBOOK_APPNAME'] || '',
callback: config.ROOT_PATH + '/account/facebooklogin',
scope: 'email,publish_actions',
failedUri: '/noauth'
};
config.fb_general_params = {
fb_title: '',
fb_description: 'אתר "מעגלי השיח" מבית שיתופים נועד לתמוך בתהליכי שיח רבי משתתפים באמצעות סביבה אינטרנטית נגישה, המותאמת לכל תהליך ופתוחה למשתמשים מורשים בלבד.',
fb_image: ''
};
config.hosts = [
'www.sheatufim-roundtable.org.il',
'www.sheatufim-roundtable.org.il:8080',
'localhost:8080',
'dev.empeeric.com',
'172.16.31.10',
'172.16.31.10:8080',
'ubuntu.sheatufim.org.il'
];
/**
* Static fils configuration
*/
config.headConfigs = {
css_includes:{
type:'css',
name:'includes',
src:[
'/css/reset.css',
'/css/style.css',
'/css/feedback.css',
'/css/colorbox.css',
'/css/loginpop.css',
'/css/myuruproxy.css',
'/css/jquery.tooltip.css',
'/css/select2.css'
]
},
js_includes:{
type:'js',
name:'includes',
src:[
'/js/jquerypp/jquery-1.10.2.js',
'/js/jquerypp/jquery-ui-1.9.1.custom.min.js',
'/js/lib/dust-full-0.3.0.js',
// '/js/InfoBox.js',
'/js/lib/fileuploader.js',
'/js/upload.js',
'/js/imgscale.jquery.min.js',
'/js/jquerypp/jqtouch.min.js',
'/js/jquerypp/jquery-fieldselection.js',
'/js/jquerypp/jquery.autoellipsis-1.0.8.min.js',
'/js/jquerypp/jquery.colorbox-min.js',
'/js/jquerypp/jquery.cycle.all.js',
'/js/jquerypp/jquery.easing.1.3.js',
'/js/jquerypp/jquery.placeholder.min.js',
'/js/jquerypp/jquery.tools.min.js',
'/js/jquerypp/jquery.tooltip.min.js',
'/js/jquerypp/jquery.compare.js',
'/js/jquerypp/jquery.range.js',
'/js/jquerypp/jquery.selection.js',
'/js/jquerypp/jquery.truncate.js',
'/js/jquery.cookie.js',
'/js/lib/date.format.js',
'/js/select2.js',
/*'/plugins/ckeditor/ckeditor.js',
'/plugins/ckeditor/adapters/jquery.js',*/
'/js/common.js',
'/js/compiled_templates.js',
'/js/db.js',
'/js/fb.js',
'/js/lib/search.js',
'/js/timeline-min.js',
'/js/storyjs-embed.js',
'/js/tokensbar_model.js',
'/js/listCommon.js',
'/js/popupProvider.js',
'/js/proxy_common.js',
'/js/lib/maps.js',
'/js/jquerypp/jquery.movingboxes.js',
'/js/jquerypp/jquery.dotdotdot-1.5.6-packed.js',
'/js/timeline.js',
'/js/countdown.js',
'/js/custom/script.js',
'/js/custom/links_and_info_items.js',
'/js/lib/bootstrap.js',
'/js/accessibility.js'
/*'/js/jquerypp/jquery.dotdotdot-1.5.6-packed.js'*/
]
}
};
module.exports = config;
<file_sep>module.exports = function(req, res){
var models = require('../../models');
var doc = models.General.getGeneral();
var host = req.get('host');
var config = require('../../config.js');
var _ = require('underscore');
if(!_.find(config.hosts, function(hst){return hst == host; })){
console.log('hosting_subject');
console.log("req.get('host')", host);
models.Subject.findOne().where('host_details.host_address', 'http://' + req.get('host')).exec(function(err, subject){
if(err || !subject) throw new Error('Subject with this host was not found');
res.redirect('discussions/subject/' + subject._id);
});
} else {
console.log('index_new');
res.render('index_new.ejs', {
is_no_sheatufim: false,
subject: {},
welcome_pre_title:doc.welcome_pre_title || "ברוכים הבאים",
welcome_title: doc.welcome_title || "למעגלי השיח",
text: doc.text || "נולום ארווס סאפיאן - פוסיליס קוויס, אקווזמן קוואזי במר מודוף. אודיפו בלאסטיק מונופץ קליר, בנפת נפקט למסון וענוף להאמית קרהשק סכעיט דז מא, מנכם למטכין נשואי מנורך גולר מונפרר סוברט לורם שבצק יהול."
});
}
};<file_sep>
var resources = require('jest'),
og_action = require('../../og/og.js').doAction,
models = require('../../models'),
common = require('../common.js'),
async = require('async'),
_ = require('underscore'),
notifications = require('../notifications.js');
var PostOnSuggestionResource = module.exports = common.BaseModelResource.extend({
init:function () {
this._super(models.PostSuggestion);
this.allowed_methods = ['get', 'post', 'delete'];
this.filtering = {suggestion_id: null};
this.default_query = function (query) {
return query.sort({creation_date:'ascending'});
};
this.fields = {
creator_id : null,
username: null,
avatar: null,
text:null,
creation_date: null,
_id:null,
discussion_id:null,
suggestion_id: null,
is_my_comment: null,
attachment:null,
like_users: null,
likes: null,
user_liked: null
};
this.default_limit = 50;
},
run_query: function(req,query,callback)
{
query.populate('creator_id');
this._super(req,query,callback);
},
get_objects: function (req, filters, sorts, limit, offset, callback) {
// get user's avatar for each post
this._super(req, filters, sorts, limit, offset, function(err, results){
if(!err) {
async.forEach(results.objects, function(post, cbk){
post.like_users = "";
post.likes = 0;
post.user_liked = false;
post.avatar = post.creator_id.avatar_url();
post.username = post.creator_id.toString();
post.creator_id = post.creator_id.id;
//set is_my_comment flag
post.is_my_comment = req.user && (req.user.id + "" === (post.creator_id && post.creator_id + ""));
//get likes
models.LikePost.find().where('post_id', post._id).populate('user_id').exec(function(err, likes){
if(err) cbk(err);
else {
_.forEach(likes, function(like){
post.like_users += like.user_id.first_name + ' ' + like.user_id.last_name + ' ';
post.likes += 1;
if(like.user_id._id.toString() == req.user._id.toString()){
post.user_liked = true;
}
});
cbk(null);
}
});
}, function(err){
callback(err, results);
});
} else {
callback(err);
}
});
},
create_obj: function(req, fields, callback) {
var self = this;
var user = req.session.user,
discussion_id = req.body.discussion_id;
fields.creator_id = req.session.user.id;
fields.first_name = user.first_name;
fields.last_name = user.last_name;
fields.text = common.escapeHtml(fields.text);
async.parallel([
function(cbk) {
self._super(req, fields, function(err, post_suggestion){
post_suggestion.avatar = req.user.avatar_url();
post_suggestion.username = req.user + "";
post_suggestion.creator_id = req.user;
post_suggestion.like_users = "";
post_suggestion.likes = 0;
//add user that discussion participant_count to discussion
models.Discussion.update({_id: post_suggestion.discussion_id, "users.user_id": {$ne: fields.creator_id}},
{$addToSet: {users: {user_id: fields.creator_id, join_date: Date.now(), $set:{last_updated: Date.now()}}}}, function(err){
cbk(err, post_suggestion);
});
});
},
function(cbk) {
models.Suggestion.findById(req.body.suggestion_id).populate('discussion_id').exec(function(err, suggestion){
if(err) cbk(err);
notifications.create_user_notification("comment_on_change_suggestion_i_created", suggestion._id.toString(), suggestion.creator_id.toString(), user._id.toString(), discussion_id.toString(), '/discussions/' + discussion_id, suggestion.discussion_id.subject_id, function(err, result){
cbk(err, result);
});
});
}
], function(err, results){
var post_suggestion = results[0];
callback(err, post_suggestion);
});
},
delete_obj: function(req,object,callback){
if (object.creator_id && (req.user.id === object.creator_id.id)){
object.remove(function(err){
callback(err);
})
}else{
callback({err: 401, message :"user can't delete posts of others"});
}
}
});
<file_sep>var resources = require('jest'),
models = require('../models'),
common = require('./common.js'),
async = require('async'),
_ = require('underscore');
var VoteSuggestoinResource = module.exports = common.BaseModelResource.extend({
init:function () {
this._super(models.VoteSuggestion);
this.allowed_methods = ['post'];
this.fields = {
agrees:null,
not_agrees:null,
suggestion_id: null,
balance: null
};
this.update_fieilds = {
suggestion_id: null,
balance: null
}
},
//returns suggestion_
create_obj: function(req,fields,callback)
{
var self = this;
var base = self._super;
var user = req.user;
var suggestion_id = fields.suggestion_id;
var discussion_id = fields.discussion_id;
var vote_counts;
var _vote;
fields.user_id = user.id;
async.waterfall([
function(cbk){
models.VoteSuggestion.findOne({suggestion_id: suggestion_id, user_id: user.id}, function(err, vote_obj){
cbk(err, vote_obj);
})
},
function(vote, cbk){
// if no vote create new one
// if exist insert the new vote
if (!vote){
base.call(self, req, fields, cbk);
}else {
vote.balance = fields.balance;
vote.save(function(err, saved_vote){
cbk(err, saved_vote);
})
}
},
function(vote, cbk){
_vote = vote;
models.VoteSuggestion.find({suggestion_id: suggestion_id}, function(err, votes){
cbk(err, votes);
})
},
function(votes, cbk){
vote_counts = _.countBy(votes, function(vote) { return vote.balance == 1 ? 'agrees' : 'not_agrees' });
if(!vote_counts.agrees) vote_counts.agrees = 0;
if(!vote_counts.not_agrees) vote_counts.not_agrees = 0;
models.Suggestion.update({_id: suggestion_id}, {$set: {agrees: vote_counts.agrees, not_agrees: vote_counts.not_agrees}},function(err, suggestion){
cbk(err);
})
},
function(cbk){
//add user that discussion participant count to discussion
models.Discussion.update({_id: discussion_id, "users.user_id": {$ne: fields.user_id}},
{$addToSet: {users: {user_id: fields.user_id, join_date: Date.now(), $set:{last_updated: Date.now()}}}}, cbk);
}
], function(err){
callback(err, {
agrees: vote_counts.agrees,
not_agrees:vote_counts.not_agrees,
suggestion_id: suggestion_id,
balance: _vote.balance
}
)
});
/* models.VoteSuggestion.findOne({user_id: user.id, suggestion_id: suggestion_id}, function (err, vote_object) {
if (err) return
callback(err, null);
});
*/
}
});
function calculate_popularity(pos, n){
// var confidence = 1.96;
if (n == 0)
return 0;
//var norm = new jstat.NormalDistribution(0,1) // normal distribution
var z = 1.96;//norm.getQuantile(1-(1-confidence)/2);
// var z = Statistics2.pnormaldist(1-(1-confidence)/2);
var phat = 1.0*pos/n;
return (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)
}
<file_sep>/**
* Created by JetBrains WebStorm.
* User: saar
* Date: 23/02/12
* Time: 12:03
* To change this template use File | Settings | File Templates.
*/
var resources = require('jest'),
models = require('../../models'),
common = require('../common.js'),
discussionCommon = require('./common'),
async = require('async'),
fs = require('fs'),
_ = require('underscore'),
multiparty = require('multiparty');
var Authorization = common.BaseAuthorization.extend({
limit_object_list: function(req,query,cbk){
query.where('creator_id',req.user.id);
cbk(null,query);
},
limit_object:function(req,query,cbk){
return this.limit_object_list(req,query,cbk);
}
});
/**
*
* Resource for uploading attachment files to post or discussion
*
*/
var PostAttachmentResource = module.exports = common.MultipartFormResource.extend({
init:function () {
this._super(models.PostForum);
this.authorization = new Authorization();
},
onFile:function(req,object,file,callback){
req.queueStream = fs.createReadStream(file.path);
req.headers['x-file-name'] = file.originalFilename;
req.headers['x-file-type'] = file.headers['content-type'];
common.uploadHandler(req,function(err,picture){
if(err) return callback(err);
object.attachment = object.attachment || {};
object.attachment.path = picture.path;
object.attachment.name = file.originalFilename;
object.attachment.url = picture.url;
object.save(function(err){
callback(err,object.attachment);
});
});
}
});
<file_sep>/**
* Created by JetBrains WebStorm.
* User: saar
* Date: 13/05/12
* Time: 13:19
* To change this template use File | Settings | File Templates.
*/
var SEND_MAIL_NOTIFICATION = true;
var models = require('../models'),
async = require('async'),
notificationResource = require('./NotificationResource'),
templates = require('../lib/templates'),
mail = require('../lib/mail'),
config = require('../config'),
_ = require('underscore');
exports.create_user_notification = create_user_notification = function (notification_type, entity_id, user_id, notificatior_id, sub_entity, url, subject_id, no_mail, callback) {
if(typeof no_mail === 'function' && typeof callback !== 'function'){
callback = no_mail;
no_mail = null;
}
var single_notification_arr = [
"approved_change_suggestion_you_created",
"approved_change_suggestion_on_discussion_you_are_part_of",
"new_information_item_on_subject_you_are_part_of",
"new_discussion_in_subject_you_are_part_of",
"new_question_in_subject_you_are_part_of"
];
var multi_notification_arr = [
'comment_on_discussion_you_are_part_of',
"comment_on_discussion_you_created",
"comment_on_subject_you_are_part_of",
"comment_on_your_forum_post",
"comment_on_your_discussion_post",
"comment_on_change_suggestion_i_created",
"change_suggestion_on_discussion_you_are_part_of",
"comment_on_question_in_subject_you_are_part_of"
];
if (notificatior_id && _.indexOf(single_notification_arr, notification_type) == -1) {
async.waterfall([
//find existing notification
function (cbk) {
notification_type = notification_type + "";
if (_.contains(multi_notification_arr, notification_type) && sub_entity) {
models.Notification.findOne({type:notification_type, 'notificators.sub_entity_id':sub_entity, user_id:user_id, visited: false}, function (err, obj) {
cbk(err, obj);
});
}
else if (entity_id)
models.Notification.findOne({type:notification_type, entity_id:entity_id, user_id:user_id}, function (err, obj) {
cbk(err, obj);
});
else
models.Notification.findOne({type:notification_type, user_id:user_id}, function (err, obj) {
cbk(err, obj);
});
},
function(noti, cbk){
//check if mail needs to be sent
if(noti){
if(noti.visited)
cbk(null, noti, true);
else
cbk(null, noti, false);
} else {
cbk(null, noti, true);
}
},
function (noti, send_mail, cbk) {
if (noti) {
noti.seen = false;
noti.visited = false;
noti.update_date = Date.now();
var new_notificator = {
notificator_id:notificatior_id,
sub_entity_id:sub_entity
},
notificator_exists = _.any(noti.notificators, function (notificator) {
return notificator.notificator_id + "" == notificatior_id + ""
});
if(notificator_exists) {
if(_.contains(multi_notification_arr, notification_type)) {
noti.notificators.push(new_notificator);
}
} else {
noti.notificators.push(new_notificator);
}
noti.save(function(err, obj){
if(!err && send_mail) {
sendNotificationToUser(obj);
}
cbk(err, obj);
});
} else {
create_new_notification(notification_type, entity_id, user_id, notificatior_id, sub_entity, url, subject_id, !send_mail, function (err, obj) {
cbk(err, obj);
});
}
}
],
function (err, obj) {
callback(err, obj);
});
} else {
create_new_notification(notification_type, entity_id, user_id, notificatior_id, sub_entity, url, subject_id, no_mail,function (err, obj) {
callback(err, obj);
});
}
};
var create_new_notification = function (notification_type, entity_id, user_id, notificatior_id, sub_entity_id, url, subject_id, no_mail, callback) {
if(typeof no_mail === 'function' && typeof callback !== 'function'){
callback = no_mail;
no_mail = null;
}
var notification = new models.Notification();
var notificator = {
notificator_id:notificatior_id ? notificatior_id : null,
sub_entity_id:sub_entity_id
};
notification.user_id = user_id;
notification.notificators = notificator;
notification.type = notification_type;
notification.entity_id = entity_id;
notification.url = url;
notification.seen = false;
notification.update_date = new Date();
notification.visited = false;
notification.subject_id = subject_id;
console.log(subject_id);
notification.save(function (err, obj) {
if (err)
console.error(err);
callback(null, obj || notification);
if (!err && obj && !no_mail)
sendNotificationToUser(obj);
});
};
/***
* Send notification to user through mail or other external API
* Checks if user should receive notification according to settings
* @param notification
* Notification object
* @param last_update_date
* notification last update date, or null if the notification is new
* @param callback
* function(err)
*/
var sendNotificationToUser = function (notification) {
/**
* Waterfall:
* 1) Get user email
* 2) Check user mail configuration
* 3) create text message
* 4) send message
*/
var email, email_details;
var uru_group = [
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>'
];
if (SEND_MAIL_NOTIFICATION)
async.waterfall([
// 1) Get user email
function (cbk) {
models.User.findById(notification.user_id, cbk);
},
// 2) Check user mail configuration
function(user, cbk){
if(user && user.mail_notification_configuration['get_alert_of_' + notification.type] && user.mail_notification_configuration.get_mails){
cbk(null, user);
} else {
console.log('User should not receive mail because of his mail configuration');
cbk('break');
}
},
// 3.1) create text message
function(user, cbk){
// notification populate references by notification type
email = user.email;
/*
if (!_.find(uru_group, function(_mail){return _mail == email})){
console.error('not in uru group');
return cbk('not in uru group')
}
*/
notificationResource.populateNotifications({objects:[notification]}, user.id, function(err, result){
cbk(err, result);
});
},
// 3.2) create text message
function (results, cbk) {
var notification = results.objects[0],
main_subject = notification.main_subject,
email_details;
notification.host_title = "שיתופים";
notification.root_path = "http://www.sheatufim-roundtable.org.il";
if(main_subject.is_no_sheatufim && main_subject.host_details) {
notification.host_title = main_subject.host_details.title;
notification.root_path = main_subject.host_details.host_address;
email_details = {
title: notification.main_subject.host_details.title,
email: notification.main_subject.host_details.email
}
}
notification.entity_name = notification.name || '';
notification.description_of_notificators = notification.description_of_notificators || '';
notification.message_of_notificators = notification.message_of_notificators || '';
templates.renderTemplate('notifications/' + notification.type, notification, function(err, result){
cbk(err, result, email_details);
});
},
// 4) send message
function (message, email_details, cbk) {
mail.sendMailFromTemplate(email, message, email_details, cbk);
}
],
// Final
function (err) {
if (err) {
if (err != 'break') {
/*console.error('failed sending notification to user');
console.error(err);
console.trace();*/
}
}
else {
console.log('email ' + notification.type + ' sent to ' + email);
notification.visited = false;
notification.mail_was_sent = true;
notification.save(function (err) {
if (err) {
console.error('saving notification flag failed');
}
});
}
});
};
exports.update_user_notification = function (notification_type, obj_id, user, callback) {
};
exports.updateVisited = function (user, url) {
models.Notification.update({user_id:user._id, url:url}, {$set:{visited:true}}, {multi:true}, function (err, count) {
if (err) {
console.error('failed setting notification visited to true', err);
}
})
};
function updateNotificationToSendMail(noti){
models.Notification.update({_id: noti._id}, {$set: {mail_was_sent: false}}, function(err, num){
if(err){
console.error("could not set notification mail_was_sent flag to false");
console.error(err);
}
})
}
models.InformationItem.onPreSave(function(next){
var self = this;
if(self.isNew) {
async.each(self.subjects, function(subject_id, callback){
models.User.find().where('subjects', subject_id).exec(function(err, users){
if(err) next();
async.each(users, function(user, cbk){
create_user_notification("new_information_item_on_subject_you_are_part_of", self._id, user._id, user._id, subject_id, "/discussions/subject/" + subject_id, subject_id, function (err, results) {
cbk(err, results);
});
}, function(err){
callback(err);
});
});
} ,function(err){
next();
});
} else {
next();
}
});
models.Discussion.onPreSave(function(next){
var self = this;
if(self.isNew) {
models.User.find().where('subjects', self.subject_id).exec(function(err, users){
if(err) next();
async.each(users, function(user, cbk){
create_user_notification("new_discussion_in_subject_you_are_part_of", self._id, user._id, self.creator_id, self.subject_id, "/discussions/" + self._id.toString(), self.subject_id, function (err, results) {
cbk(err, results);
});
}, function(err){
next();
});
});
} else {
next();
}
});
models.Question.onPreSave(function(next){
var self = this;
if(self.isNew) {
models.User.find().where('subjects', self.subject_id).exec(function(err, users){
if(err) next();
async.each(users, function(user, cbk){
create_user_notification("new_question_in_subject_you_are_part_of", self._id, user._id, user._id, self.subject_id, "/discussions/subject/" + self.subject_id, self.subject_id, function (err, results) {
cbk(err, results);
});
}, function(err){
next();
});
});
} else {
next();
}
});
//approved_info_item_i_created
if (/notifications\.js/.test(process.argv[1])) {
var app = require('../app');
console.log('testing');
//function(notification_type, entity_id, user_id, notificatior_id, sub_entity_id, callback){
//4f90064e360b9b01000000ac --info item
//4fcdf7180a381201000005b3 --disc
//a_dicussion_created_with_info_item_that_you_created
// sub //4fce400ccdd0570100000216
//501fcef1e6ae520017000662 --הצעה לשינוי שהתקבלה
setTimeout(function () {
create_new_notification('comment_on_discussion_you_created',
'4fcdf7180a381201000005b3', '4ff1b29aabf64e440f00013a', '4f45145968766b0100000002', '501fcef1e6ae520017000662', function (err) {
console.log(err);
});
}, 1000);
}<file_sep>var mongoose = require("mongoose"),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId,
async = require('async');
var Subject = module.exports = new Schema({
name:{type:String,required:true},
tooltip:String,
description: {type:Schema.Types.Html},
text_field_preview:{type:Schema.Types.Text},
image_field: {type: Schema.Types.File, required: true},
cover_image_field:Schema.Types.File,
timeline_url: String,
tags:[String],
gui_order: {type:Number,'default':9999999, editable:false},
is_hot_object: {type:Boolean,'default':false},
is_uru:{type:Boolean,'default':false},
hidden_subject: {type:Boolean,'default':false},
is_no_sheatufim: {type:Boolean,'default':false},
host_details: {
title: String,
host_address: String,
email: String,
contact_details: Schema.Types.Html
}
}, {strict: true});
Subject.methods.toString = function(){
return this.name;
};
/**
* check if discussion subject is in user allowed subject ids
* @param user
* @returns {boolean}
* Is allowed
*/
Subject.methods.isUserAllowed = function(user){
if(!user || !user.subjects)
return false;
var subjectIds = user.subjects.map(function(subject) { return subject + '';});
var subjectId = this._id + '';
return subjectIds.indexOf(subjectId) != -1;
}
<file_sep>var models = require('../../models'),
async = require('async'),
common = require('../account/common'),
InformationItemResource = require('../../api/InformationItemResource.js'),
LinkResource = require('../../api/LinkResource.js'),
notifications = require('../../api/notifications.js'),
PostForumResource = require('../../api/forum/postForumResource.js');
module.exports = function(req,res) {
var post_resource = new PostForumResource();
var information_item_resource = new InformationItemResource();
var links_resource = new LinkResource();
var subject_id = req.params[0];
var page = req.query.page || 1,
limit = 10,
offset = (page - 1) * limit;
var user = req.user;
// quick getaway
if (!req.user) return res.redirect(common.DEFAULT_LOGIN_REDIRECT);
//get all the needed data for forum page
async.parallel([
function(cbk) {
models.Subject.findById(subject_id).exec(function(err, result){
cbk(null, result);
});
},
function(cbk){
post_resource.get_objects(req, {subject_id: subject_id}, {creation_date: -1}, limit, offset, function(err, posts){
cbk(err, posts);
});
},
function(cbk){
information_item_resource.get_objects(req, {subjects: subject_id}, {creation_date: -1}, 3, 0, function(err, information_items){
cbk(err, information_items);
});
},
function(cbk){
links_resource.get_objects(req, {subjects: subject_id}, {date: -1}, 6, 0, function(err, link_items){
cbk(err, link_items);
});
}
], function(err, results){
var subject = results[0],
count = results[1].count,
main_posts = results[1].page_posts,
post_groups = results[1].post_groups,
information_items = results[2].objects,
links = results[3].objects;
if (!subject.isUserAllowed(req.user))
return res.redirect('/');
res.render('forum.ejs', {
subject: subject,
logged: req.isAuthenticated(),
user: user && {_id: user._id, first_name: user.first_name, last_name: user.last_name, occupation: user.occupation},
avatar:req.session.avatar_url,
user_logged: req.isAuthenticated(),
url:req.url,
posts: main_posts || [],
post_groups: post_groups || [],
count: count,
page: page,
next: Number(page) + 1,
prev: Number(page) - 1,
information_items: information_items || [],
links: links || [],
is_no_sheatufim: subject.is_no_sheatufim
});
//update all notifications of user that connected to this object
if (req.user) {
var path = req.path.indexOf('#') == -1 ? req.path : req.path.substr(0, req.path.indexOf('#'));
notifications.updateVisited(user, req.path);
}
});
};
<file_sep>var resources = require('jest'),
util = require('util'),
models = require('../models'),
common = require('./common'),
async = require('async'),
sugar = require('sugar'),
_ = require('underscore');
var NotificationCategoryResource = module.exports = resources.MongooseResource.extend(
{
init:function () {
this._super(models.Notification);
this.allowed_methods = ['get'];
this.authentication = new common.SessionAuthentication();
this.update_fields = {name:null};
this.default_query = function (query) {
return query.sort({'update_date': 'descending'});
};
this.filtering = {visited: null};
this.fields = {
_id:null,
user_id:null,
main_subject: null,
notificators:{
sub_entity_id: null,
notificator_id: null,
ballance: null,
votes_for: null,
votes_against: null,
first_name:null,
last_name:null,
avatar_url:null
},
entity_id: null,
name: null,
update_date:null,
visited: null,
pic:null,
//text only
part_one: null,
//text with link
part_two: null,
link_two:null,
//text only
part_three: null,
//text with link
part_four: null,
link_four: null,
//text only
part_five: null,
//post text
text: null,
link_to_first_comment_user_didnt_see: null,
discussion_link: null,
//extra text is the text displayed before the button
extra_text: null,
main_link: null,
//for user part
user_link: null,
user: null,
//for "join" button
is_going: null,
check_going: null,
//for the share part
img_src: null,
title: null,
text_preview: null,
//for mail_settings part
mail_settings_link: null
}
},
get_objects:function (req, filters, sorts, limit, offset, callback) {
var user_id = req.query.user_id;
if (!user_id && req.user)
user_id = req.user.id;
if (user_id)
filters['user_id'] = user_id;
if(req.query.filters == 'visited'){
filters.visited = 'false';
}
this._super(req, filters, sorts, limit, offset, function (err, results) {
if(err)
callback(err);
else
populateNotifications(results, user_id, function(err, results){
callback(err, results);
});
});
}
});
var iterator = function (users_hash, discussions_hash, posts_hash, info_items_hash, subjects_hash, questions_hash, subjects_hash, user_id) {
return function (notification, itr_cbk) {
{
var user_obj = notification.notificators.length ?
users_hash[notification.notificators[0].notificator_id] : null;
var discussion = discussions_hash[notification.entity_id + ''] || discussions_hash[notification.notificators[0].sub_entity_id + ''];
var info_item = info_items_hash[notification.entity_id + ''] || info_items_hash[notification.notificators[0].sub_entity_id + ''];
var post = posts_hash[notification.entity_id + ''] || posts_hash[notification.notificators[0].sub_entity_id + ''];
var post_id = post ? post._id : "";
var post_text = post ? post.toObject().text : "";
var subject = subjects_hash[notification.entity_id + ''] || subjects_hash[notification.notificators[0].sub_entity_id + ''];
var question = questions_hash[notification.entity_id + ''] || questions_hash[notification.notificators[0].sub_entity_id + ''];
notification.main_subject = subjects_hash[notification.subject_id + ''];
switch (notification.type) {
case "change_suggestion_on_discussion_you_are_part_of":
var num_of_comments = notification.notificators.length;
if(discussion){
notification.main_link = notification.url + '#' + post_id.toString();
notification.part_two = discussion.title;
notification.link_two = "/discussions/" + discussion._id + "";
}
if (num_of_comments > 1) {
notification.part_one = "נוספו " + num_of_comments + " הצעות לשינוי למסמך ";
} else {
notification.part_one = "נוספה הצעה חדשה לשינוי למסמך ";
}
itr_cbk();
break;
case "comment_on_discussion_you_created" :
var num_of_comments = notification.notificators.length;
if(discussion){
notification.main_link = "/discussions/" + discussion._id + "#post" + post_id;
notification.pic = discussion.image_field_preview || discussion.image_field;
notification.part_two = discussion.title;
notification.link_two = "/discussions/" + discussion._id + "";
notification.img_src = notification.pic;
notification.title = discussion.title;
notification.text_preview = discussion.text_field_preview;
notification.mail_settings_link = "/mail_settings/discussion/" + discussion.id + '?force_login=1';
}
if (num_of_comments > 1) {
notification.user = num_of_comments + " " + "אנשים";
notification.part_one = " הגיבו על דיון שיצרת - ";
itr_cbk(null, 1);
} else {
if(user_obj){
notification.user = user_obj.first_name + " " + user_obj.last_name;
notification.user_link = "/myuru/" + user_obj._id + "";
notification.pic = user_obj.avatar_url();
}
notification.part_one = " הגיב על דיון שיצרת - ";
itr_cbk();
}
break;
case "approved_change_suggestion_you_created":
notification.main_link = notification.url;
notification.part_one = "התקבלה הצעה לשינוי שהעלת במסמך ";
if(discussion){
notification.part_two = discussion.title;
notification.link_two = "/discussions/" + discussion._id;
}
notification.part_three = " והטקסט בו עודכן";
itr_cbk();
break;
case "approved_change_suggestion_on_discussion_you_are_part_of":
notification.main_link = notification.url;
notification.part_one = "התקבלה הצעה לשינוי למסמך ";
if(discussion){
notification.part_two = discussion.title;
notification.link_two = "/discussions/" + discussion._id;
}
notification.part_three = " והטקסט בו עודכן";
itr_cbk();
break;
case "comment_on_subject_you_are_part_of":
var num_of_joined = notification.notificators.length;
if(num_of_joined > 1){
notification.part_one = "נוספו "
+ num_of_joined + " הודעות חדשות לפורום של "
} else {
if(user_obj){
notification.part_one = user_obj.first_name + ' ' + user_obj.last_name + ' ' + "פרסם/ה הודעה חדשה בפורום של ";
notification.user = user_obj.first_name + ' ' + user_obj.last_name;
}
}
if(subject){
notification.link_two = "/discussions/subject/" + subject._id;
notification.part_two = subject.name;
}
if(subject && post){
get_post_page(post._id, subject._id, function(page){
if(page == 0)
notification.main_link = notification.url + '#' + post._id;
else
notification.main_link = notification.url + '?page=' + page + '#' + post._id;
notification.extra_text = post_text;
itr_cbk();
});
}else {
itr_cbk();
}
break;
case "comment_on_discussion_you_are_part_of":
var num_of_joined = notification.notificators.length;
if(num_of_joined > 1){
notification.part_one = "נוספו "
+ num_of_joined + " הודעות חדשות למסמך "
} else {
if(user_obj){
notification.part_one = "הודעה חדשה בעמוד המסמך ";
}
}
if(discussion){
notification.link_two = "/discussions/" + discussion._id + '#' + post_id;
notification.part_two = discussion.title;
}
notification.extra_text = post_text;
notification.main_link = notification.url + '#' + post_id;
itr_cbk();
break;
case "comment_on_your_forum_post":
var num_of_joined = notification.notificators.length;
if(num_of_joined > 1){
notification.part_one = "נוספו " +
num_of_joined +
" תגובות חדשות להודעה שהעלית בפורום של "
} else {
if(user_obj){
notification.user = user_obj.first_name + " " + user_obj.last_name;
notification.part_one = " פרסם/ה תגובה חדשה להודעה שלך בפורום של ";
}
}
if(subject){
notification.link_two = "/discussions/subject/" + subject._id;
notification.part_two = subject.name;
}
get_post_page(post._id, subject._id, function(page){
if(page == 0)
notification.main_link = notification.url + '#' + post._id;
else
notification.main_link = notification.url + '?page=' + page + '#' + post._id;
notification.extra_text = post_text;
itr_cbk();
});
break;
case "comment_on_your_discussion_post":
var num_of_joined = notification.notificators.length;
if(num_of_joined > 1){
notification.part_one = "נוספו " +
num_of_joined +
" תגובות חדשות להודעה שלך בעמוד המסמך "
} else {
if(user_obj){
notification.part_one = "תגובה חדשה להודעה שלך בעמוד המסמך ";
}
}
if(discussion){
notification.link_two = "/discussions/" + discussion._id + '#' + post_id;
notification.part_two = discussion.title;
}
notification.main_link = notification.url;
itr_cbk();
break;
case "comment_on_change_suggestion_i_created":
var num_of_joined = notification.notificators.length;
if(num_of_joined > 1){
notification.part_one = "נוספו "
+ num_of_joined + " תגובות חדשות להצעה לשינוי שהעלית למסמך "
} else {
if(user_obj){
notification.part_one = "נוספה תגובה חדשה להצעה לשינוי שהעלית למסמך ";
}
}
if(discussion){
notification.link_two = "/discussions/" + discussion._id;
notification.part_two = discussion.title;
}
notification.main_link = notification.url + '#' + post_id;
itr_cbk();
break;
case "new_information_item_on_subject_you_are_part_of":
notification.part_one = "פריט מידע חדש נוסף למעגל השיח ";
if(subject){
notification.link_two = "/discussions/subject/" + subject._id;
notification.part_two = subject.name;
}
notification.part_three = ' : "' + info_item.title + '"';
notification.main_link = notification.url;
itr_cbk();
break;
case "new_discussion_in_subject_you_are_part_of":
if(subject){
notification.part_one = "מסמך חדש נפתח לעריכה במעגל השיח ";
notification.part_two = subject.name;
notification.link_two = "/discussions/subject/" + subject._id;
}
if(user_obj){
notification.extra_text = "המסמך הועלה על ידי " + user_obj.first_name + " " + user_obj.last_name;
}
if(discussion) {
notification.text = "המסמך פתוח לעריכה למשך: " + calc_time_until(discussion.deadline);
notification.part_three = ": ";
notification.part_four = '"' + discussion.title + '"';
notification.link_four = notification.url;
}
notification.main_link = notification.url;
itr_cbk();
break;
case "new_question_in_subject_you_are_part_of":
if(subject){
notification.part_one = "שאלה חדשה נפתחה לדיון במעגל השיח ";
notification.part_two = subject.name;
notification.link_two = "/discussions/subject/" + subject._id;
}
if(question){
notification.part_three = ' : "' + question.title + '"';
notification.text = '"' + question.title + '"';
}
notification.main_link = notification.url + '#' + question._id;
itr_cbk();
break;
case "comment_on_question_in_subject_you_are_part_of":
var num_of_joined = notification.notificators.length;
if(num_of_joined > 1){
notification.part_one = "נוספו "
+ num_of_joined + " הודעות חדשות לשאלה לדיון "
} else {
if(user_obj){
notification.part_one = user_obj.first_name + ' ' + user_obj.last_name + ' ' + " הגיב/ה על שאלה לדיון ";
notification.user = user_obj.first_name + ' ' + user_obj.last_name;
}
}
if(question){
notification.link_two = "/discussions/subject/" + question.subject_id;
notification.part_two = question.title;
}
notification.main_link = notification.url + '#' + question._id;
notification.extra_text = post_text;
itr_cbk();
break;
default:
itr_cbk({message: "there is no such notification type", code: 404});
}
}
};
};
var get_post_page = function(post_id, subject_id, callback){
var count = 0, id = post_id;
models.PostForum.find({'subject_id': subject_id}).exec(function(err, posts){
var main_posts = _.filter(posts, function(post){
return !post.parent_id;
});
var find_parent = function(post){
var temp = post;
while(temp && temp.parent_id){
var temp = _.find(posts, function(pst){
return pst._id.toString() == temp.parent_id.toString();
});
}
return temp;
};
var post = _.find(posts, function(pst){ return pst._id == post_id.toString(); });
var parent = find_parent(post);
var parent_idx = _.indexOf(main_posts, parent);
debugger
var page = Math.floor(main_posts.length / 10) - Math.floor(main_posts.length / parent_idx);
callback(page);
});
};
var calc_time_until = function(date_obj){
var date = Date.create(date_obj),
days = date.daysFromNow(),
hours = date.hoursFromNow() - (days * 24),
minutes = date.minutesFromNow() - (days * 1440) - (hours * 60);
return days + " ימים, " + hours + " שעות ו-" + minutes + " דקות ";
};
var populateNotifications = module.exports.populateNotifications = function(results, user_id, callback) {
//formulate notifications
var notificator_ids = _.chain(results.objects)
.map(function (notification) {
return notification.notificators.length ? notification.notificators[0].notificator_id : null;
})
.compact()
.uniq()
.value();
var post_or_suggestion_notification_types = [
"comment_on_change_suggestion_i_created",
"comment_on_question_in_subject_you_are_part_of",
"change_suggestion_on_discussion_you_are_part_of"
];
var post_notification_types = [
"comment_on_discussion_you_are_part_of",
"comment_on_discussion_you_created",
"change_suggestion_on_discussion_you_are_part_of",
"approved_change_suggestion_you_created",
"approved_change_suggestion_on_discussion_you_are_part_of",
"comment_on_subject_you_are_part_of",
"comment_on_your_forum_post",
"comment_on_your_discussion_post"
];
var discussion_notification_types = [
"new_discussion_in_subject_you_are_part_of",
"comment_on_discussion_you_are_part_of",
"comment_on_discussion_you_created"
];
var noti_subjects = _.chain(results.objects)
.map(function (notification) {
return notification.subject_id;
})
.compact()
.uniq()
.value();
var discussion_ids = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(discussion_notification_types, notification.type) > -1
? notification.entity_id : null;
})
.compact()
.uniq()
.value();
var discussion_notification_types_as_sub_entity = [
"comment_on_discussion_you_are_part_of",
"comment_on_discussion_you_created",
"change_suggestion_on_discussion_you_are_part_of",
"approved_change_suggestion_you_created",
"approved_change_suggestion_on_discussion_you_are_part_of",
"comment_on_your_discussion_post",
"comment_on_change_suggestion_i_created"
];
var discussion_ids_as_sub_entity = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(discussion_notification_types_as_sub_entity, notification.type) > -1
? notification.notificators[0].sub_entity_id : null;
})
.compact()
.uniq()
.value();
discussion_ids_as_sub_entity = _.chain(discussion_ids_as_sub_entity)
.compact()
.uniq()
.value();
discussion_ids = _.union(discussion_ids, discussion_ids_as_sub_entity);
discussion_ids = _.chain(discussion_ids).map(function(id) { return id + ''; })
.compact()
.uniq()
.value();
var subject_notification_types_as_sub_entity = [
"comment_on_subject_you_are_part_of",
"comment_on_your_forum_post",
"new_information_item_on_subject_you_are_part_of",
"new_discussion_in_subject_you_are_part_of",
"new_question_in_subject_you_are_part_of"
];
var subject_ids_as_sub_entity = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(subject_notification_types_as_sub_entity, notification.type) > -1
? notification.notificators[0].sub_entity_id : null;
})
.compact()
.uniq()
.value();
subject_ids_as_sub_entity = _.chain(subject_ids_as_sub_entity)
.compact()
.uniq()
.value();
var post_or_suggestion_ids = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(post_or_suggestion_notification_types, notification.type) > -1
? notification.entity_id : null;
})
.compact()
.uniq()
.value();
var post_ids = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(post_notification_types, notification.type) > -1
? notification.entity_id : null;
})
.compact()
.uniq()
.value();
post_ids = _.union(post_ids, post_or_suggestion_ids);
var question_notification_types = [
"new_question_in_subject_you_are_part_of"
];
var question_notification_types_as_sub_entity = [
"comment_on_question_in_subject_you_are_part_of"
];
var question_ids_as_sub_entity = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(question_notification_types_as_sub_entity, notification.type) > -1
? notification.notificators[0].sub_entity_id : null;
})
.compact()
.uniq()
.value();
var question_ids = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(question_notification_types, notification.type) > -1
? notification.entity_id : null;
})
.compact()
.uniq()
.value();
question_ids_as_sub_entity = _.chain(question_ids_as_sub_entity)
.compact()
.uniq()
.value();
question_ids = _.union(question_ids, question_ids_as_sub_entity);
var info_item_notification_types = [
"new_information_item_on_subject_you_are_part_of"
// "approved_info_item_i_liked"
];
var info_items_ids = _.chain(results.objects)
.map(function (notification) {
return _.indexOf(info_item_notification_types, notification.type) > -1
? notification.entity_id : null;
})
.compact()
.uniq()
.value();
async.parallel([
function(cbk){
if(notificator_ids.length)
models.User.find({}, {
'id':1,
'first_name':1,
'last_name':1,
'facebook_id':1,
'avatar':1})
.where('_id').in(notificator_ids)
.exec(function (err, users) {
if(!err){
var users_hash = {};
_.each(users, function (user) {
users_hash[user.id] = user;
});
}
cbk(err, users_hash);
});
else
cbk(null,{});
},
function(cbk){
if(discussion_ids.length)
models.Discussion.find()
.where('_id')
.in(discussion_ids)
.select({
'id':1,
'title':1,
'image_field_preview':1, 'image_field':1, 'text_field_preview':1,'vision_text_history':1,'text_field':1, 'subject_name':1, 'deadline':1})
.exec(function (err, discussions) {
var got_ids = _.pluck(discussions,'id');
var not_found_ids = _.without(discussion_ids,got_ids);
if(not_found_ids.length)
console.log(not_found_ids);
if(!err){
var discussions_hash = {};
_.each(discussions, function (discussion) {
discussions_hash[discussion.id] = discussion;
});
}
cbk(err, discussions_hash);
});
else
cbk(null,{});
},
function(cbk){
if(post_ids.length)
models.PostOrSuggestion.find({},{'id':1, 'text':1})
.where('_id').in(post_ids)
.exec(function (err, posts_items) {
if(!err){
var post_items_hash = {};
_.each(posts_items, function (post_item) {
post_items_hash[post_item.id] = post_item;
});
}
cbk(err, post_items_hash);
});
else
cbk(null,{});
},
function(cbk){
if(info_items_ids.length)
models.InformationItem.find({},
{'id':1,
'image_field_preview':1,
'image_field':1,
'title':1
})
.where('_id').in(info_items_ids)
.exec(function (err, info_items) {
if(!err){
var info_items_hash = {};
_.each(info_items, function (info_item) {
info_items_hash[info_item.id] = info_item;
});
}
cbk(err, info_items_hash);
});
else
cbk(null,{});
},
function(cbk){
if(subject_ids_as_sub_entity.length){
models.Subject.find()
.where('_id').in(subject_ids_as_sub_entity)
.select({'_id': 1, 'name': 1})
.exec(function(err, subjects){
if(!err){
var subjects_hash = {};
_.each(subjects, function(subject){
subjects_hash[subject._id] = subject;
});
}
cbk(err, subjects_hash);
})
}else
cbk(null,{});
},
function(cbk){
if(question_ids.length){
models.Question.find()
.where('_id').in(question_ids)
.select({'_id': 1, 'title': 1})
.exec(function(err, questions){
if(!err){
var questions_hash = {};
_.each(questions, function(question){
questions_hash[question._id] = question;
});
}
cbk(err, questions_hash);
})
}else
cbk(null,{});
}, function(cbk){
if(noti_subjects.length > 0){
models.Subject.find()
.where('_id').in(noti_subjects)
.exec(function(err, subjects){
if(!err){
var noti_subjects_hash = {};
_.each(subjects, function(subject){
noti_subjects_hash[subject._id] = subject;
});
}
cbk(err, noti_subjects_hash);
})
}
}
], function(err, args){
async.forEach(results.objects, iterator(args[0], args[1], args[2], args[3], args[4], args[5], args[6], user_id), function (err, obj) {
callback(err, results);
})
})
};
function getLatestNotificator(notificators_arr){
return _.max(notificators_arr, function(noti){ return noti.date; });
}
<file_sep>
//var SendGrid = require('sendgrid').SendGrid
// ,Email = require('sendgrid').Email;
var nodemailer = require('nodemailer')
,config = require('../config');
var from, fromName, smtpTransport;
exports.load = function(app)
{
from = config.systemEmail;
fromName = config.systemEmailName;
// create reusable transport method (opens pool of SMTP connections)
var mail_pass = process.env['SMTP-PASSWORD'] || '';
console.log("mail_pass", mail_pass);
smtpTransport = nodemailer.createTransport("SMTP",{
service: "Mailjet",
host:'in-v3.mailjet.com',
auth: {
// user:config.SMTPUsername,
// pass:config.SMTPPassword
user: config.mailjet_user,
pass: <PASSWORD>
}
});
};
var sendMail = exports.sendMail = function(to, body, subject, expFrom, callback) {
console.log('subject',subject);
if(typeof expFrom === "function" && typeof callback !== 'function') {
callback = expFrom;
expFrom = null;
}
if(!smtpTransport) {
console.log('email not sent because it\'s off in app.js. to turn mails on set app.set("send_mails",true); ');
return callback();
}
console.log('sending to ' + to + ' ' + subject);
// setup e-mail data with unicode symbols
var mailOptions = {
from: expFrom ? expFrom : fromName + " <" + from + ">", // sender address
// from: from,
to: to, // list of receivers
subject: subject, // Subject line
html: body // html body
};
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.error('mail was not sent',error);
console.error('config.mailjet_pass',config.mailjet_pass);
callback(response);
}
else{
console.log('mail was sent');
callback(null,response);
}
});
};
var sendMailFromTemplate = exports.sendMailFromTemplate = function(to, string, email_details,callback) {
if(typeof email_details === "function" && typeof callback !== 'function') {
callback = email_details;
email_details = null;
}
var parts = string.split('<!--body -->');
var subject = email_details && email_details.title ? 'עדכון ממעגל שיח - מסמך יסוד לחברה האזרחית' : 'עדכון מאתר מעגלי השיח של שיתופים';
var body = parts[1] || parts[0];
var email = email_details && email_details.title ? email_details.title + " <" + email_details.email + ">" : null;
sendMail(to,body,subject, email, callback);
};
function test(){
exports.load();
sendMail('<EMAIL>','Test','Testy',function(err){
console.error(err);
});
}
if(process.argv[1] == __filename)
test();<file_sep>
var common = require('../common')
,models = require('../../models');
/**
* Discussion related resources authorization:
*
* Makes sure user can only show discussion history of discussion is authorized to view
*/
exports.DiscussionAuthorization = common.BaseAuthorization.extend({
limit_object_list: function(req,query,cbk){
// get discussion id from query
var discussion_id = req.query.discussion_id || req.body.discussion_id;
if(!discussion_id || typeof(discussion_id) != 'string')
return cbk({code:401,message:'Must provide single discussion id filter'});
// get discussion object
models.Discussion.findById(discussion_id).select({subject_id:1}).exec(function(err,discussion){
if(err) return cbk(err);
if(!discussion) return cbk({code:404,message:'discussion not found'});
// check if discussion subject is in user allowed subject ids
if(!discussion.isUserAllowed(req.user))
return cbk({code:401,message:'no permission'});
query.where('discussion_id',discussion_id);
return cbk(null,query);
});
},
limit_object:function(req,query,cbk){
return this.limit_object_list(req,query,cbk);
}
});
<file_sep>/**
* Created by JetBrains WebStorm.
* User: saar
* Date: 23/02/12
* Time: 12:03
* To change this template use File | Settings | File Templates.
*/
var resources = require('jest'),
models = require('../../models'),
common = require('../common.js'),
discussionCommon = require('./common'),
async = require('async'),
fs = require('fs'),
_ = require('underscore'),
multiparty = require('multiparty');
/**
*
* Resource for uploading attachment files to post or discussion
*
*/
var PostSuggestionAttachmentResource = module.exports = common.MultipartFormResource.extend({
init:function () {
this._super(models.PostSuggestion);
this.authorization = new discussionCommon.DiscussionAuthorization();
},
onFile:function(req,object,val,callback){
var file = val;
req.queueStream = fs.createReadStream(file.path);
req.headers['x-file-name'] = val.originalFilename;
req.headers['x-file-type'] = val.headers['content-type'];
common.uploadHandler(req,function(err,file){
if(err) return callback(err);
object.attachment = object.attachment || {};
object.attachment.path = file.path;
object.attachment.name = val.originalFilename;
object.attachment.url = file.url;
object.save(function(err){
callback(err,object.attachment);
});
});
}
});
<file_sep>/**
* Created by JetBrains WebStorm.
* User: saar
* Date: 23/02/12
* Time: 12:03
* To change this template use File | Settings | File Templates.
*/
var resources = require('jest'),
og_action = require('../../og/og.js').doAction,
models = require('../../models'),
common = require('../common.js'),
discussionCommon = require('./common'),
async = require('async'),
_ = require('underscore'),
notifications = require('../notifications.js');
var EDIT_TEXT_LEGIT_TIME = 60 * 1000 * 15;
var PostResource = module.exports = common.BaseModelResource.extend({
init:function () {
this._super(models.Post);
this.allowed_methods = ['get', 'post', 'put', 'delete'];
this.filtering = {discussion_id:null, parent_id: null};
this.authorization = new discussionCommon.DiscussionAuthorization();
this.default_query = function (query) {
return query.sort({creation_date:'descending'});
};
this.fields = {
creator_id : common.user_public_fields,
voter_balance: null,
mandates_curr_user_gave_creator: null,
avatar: null,
user: null,
text:null,
popularity:null,
tokens:null,
creation_date: null,
total_votes:null,
votes_against:null,
votes_for:null,
_id:null,
ref_to_post_id: null,
quoted_by: null,
discussion_id:null,
is_user_follower: null,
is_editable: null,
is_my_comment: null,
parent_id: null,
user_occupation: null,
responses: null,
post_groups: null,
count: null,
page_posts: null,
attachment:null,
like_users: null,
likes: null,
user_liked: null
};
this.update_fields = {text: null, discussion_id: null, ref_to_post_id: null, attachment:null};
// this.validation = new resources.Validation();=
this.default_limit = 50;
},
run_query: function(req,query,callback)
{
query.populate('creator_id');
this._super(req,query,callback);
},
get_objects: function (req, filters, sorts, limit, offset, callback) {
var self = this;
self._super(req, filters, sorts, limit, offset, function(err, results){
var user_id;
if(req.user){
user_id = req.user._id + "";
async.waterfall([
function(cbk){
models.User.findById(user_id, cbk);
},
function(user_obj, cbk){
var proxies = user_obj.proxy;
// _.each(results.objects, function(post){
// var flag = false;
//
// var proxy = _.find(proxies, function(proxy){
// if(!post.creator_id)
// return null;
// else
// return proxy.user_id + "" == post.creator_id._id + ""});
// if(proxy)
// post.mandates_curr_user_gave_creator = proxy.number_of_tokens;
// if(post.creator_id)
// flag = _.any(post.creator_id.followers, function(follower){return follower.follower_id + "" == user_id + ""});
// post.is_user_follower = flag;
// })
async.forEach(results.objects, function(post, itr_cbk){
//set is_my_comment flag
post.is_my_comment = (user_id === (post.creator_id && post.creator_id.id));
// set is_editable flag
if (user_id === (post.creator_id && post.creator_id.id) && new Date() - post.creation_date <= EDIT_TEXT_LEGIT_TIME){
post.is_editable = true;
}
//update each post creator if he is a follower or not
var flag = false;
var proxy = _.find(proxies, function(proxy){
if(!post.creator_id)
return null;
else
return proxy.user_id + "" == post.creator_id._id + ""});
if(proxy)
post.mandates_curr_user_gave_creator = proxy.number_of_tokens;
if(post.creator_id)
flag = _.any(post.creator_id.followers, function(follower){return follower.follower_id + "" == user_id + ""});
post.is_user_follower = flag;
//update each post creator with his vote balance
models.Vote.findOne({user_id: user_id, post_id: post._id}, function(err, vote){
post.voter_balance = vote ? (vote.ballance || 0) : 0;
itr_cbk(err);
})
}, function(err, obj){
cbk(err, results);
});
}
], function(err, results){
if(err) {
callback(err);
} else {
self.sort_posts(req, limit, offset, results, function(rst){
callback(err, rst);
});
}
})
}else{
_.each(results.objects, function(post){ post.is_user_follower = false; });
self.sort_posts(req, limit, offset, results, function(rst){
callback(err, rst);
});
}
});
},
sort_posts: function(req, limit, offset, results, callback){
var new_posts = [];
//set avatar and user info for each posts
_.each(results.objects, function(post){
var new_post = post.toObject();
new_post.avatar = post.creator_id.avatar_url();
new_post.username = post.creator_id.toString();
new_post.creator_id = post.creator_id.id;
new_post.user_occupation = post.creator_id.occupation;
//set is_my_comment flag
new_post.is_my_comment = req.user && (req.user.id + "" === (post.creator_id && post.creator_id + ""));
new_posts.push(new_post);
});
//the posts with no parents are main posts
var main_posts = _.filter(new_posts, function(post){
return !post.parent_id;
});
//group sub_posts by their parents
var post_groups = _.groupBy(new_posts, function(post){
return post.parent_id;
});
//paginate
var page_posts = main_posts;
if(offset)
page_posts = _.rest(page_posts, offset);
if(limit)
page_posts = _.first(page_posts,limit);
var result = {
post_groups: post_groups || [],
count: main_posts.length,
page_posts: page_posts
};
callback(result);
},
create_obj:function (req, fields, callback) {
var user_id = req.user._id + "";
var self = this;
var post_object = new self.model();
var user = req.user;
// var notification_type = "comment_on_discussion_you_are_part_of"
var discussion_id = fields.discussion_id;
var discussion_creator_id;
var post_id;
var iterator = function(unique_user, itr_cbk){
if(unique_user){
if (unique_user + "" == user_id)
itr_cbk(null, 0);
else{
if (discussion_creator_id + "" == unique_user + ""){
notifications.create_user_notification("comment_on_discussion_you_created", post_id, unique_user, user_id, discussion_id, '/discussions/' + discussion_id, this.subject_id, function(err, results){
itr_cbk(err, results);
});
}else{
notifications.create_user_notification("comment_on_discussion_you_are_part_of", post_id, unique_user, user_id, discussion_id, '/discussions/' + discussion_id, this.subject_id, function(err, results){
itr_cbk(err, results);
});
}
}
}else{
console.log("in the following discussion - there is a user with no _id");
console.log(discussion_id);
itr_cbk()
}
};
console.log('debugging waterfall');
/**
* Waterfall:
* 1) set post object fields, send to authorization
* 2) save post object
* 3) send notifications
* 4) publish to facebook
* Final) return the object with the creator user object
*/
async.waterfall([
function(cbk){
models.Discussion.findById(discussion_id, cbk);
},
// 1) set post object fields, send to authorization
function(discussion_obj, cbk)
{
console.log('debugging waterfall 1');
fields.creator_id = user_id;
fields.parent_id = req.body.parent_id ? req.body.parent_id : null;
fields.first_name = user.first_name;
fields.last_name = user.last_name;
fields.avatar = user.avatar;
if(!fields.ref_to_post_id || fields.ref_to_post_id == "null" || fields.ref_to_post_id == "undefined"){
delete fields.ref_to_post_id;
}else{
setQuotedPost(post_object._id, fields.ref_to_post_id, req.user.toString());
}
fields.text = common.escapeHtml(fields.text);
// TODO add better sanitizer
// fields.text = sanitizer.sanitize(fields.text);
for (var field in fields) {
post_object.set(field, fields[field]);
}
self.authorization.edit_object(req, post_object, cbk);
},
// 2) save post object
function(_post_object, cbk){
post_id = _post_object._id;
post_object = _post_object;
console.log('debugging waterfall 2');
discussion_id = post_object.discussion_id + "";
post_object.creator_id + "";
post_object.save(function(err, result, num)
{
cbk(err,result);
});
},
// 3) send notifications
function (object,cbk) {
console.log('debugging waterfall 3');
//if post created successfuly, add user to discussion
// + add discussion to user
// + take tokens from the user
async.parallel([
function(cbk2)
{
//add user that connected somehow to discussion
models.Discussion.update({_id:object.discussion_id, "users.user_id": {$ne: user_id}},
{$addToSet: {users: {user_id: user_id, join_date: Date.now(), $set:{last_updated: Date.now()}}}}, cbk2);
},
//add user that connected somehow to discussion
function(cbk2)
{
models.User.update({_id: user_id, "discussions.discussion_id": {$ne: object.discussion_id}},
{$addToSet: {discussions: {discussion_id: object.discussion_id, join_date: Date.now()}}}, cbk2);
},
//add notification for the dicussion's connected people or creator
function(cbk2){
console.log('debugging waterfall 3 2');
models.Discussion.findById(object.discussion_id).populate('subject_id').exec(function(err, disc_obj){
if (err)
cbk2(err, null);
else{
var unique_users = [];
// be sure that there are no duplicated users in discussion.users
_.each(disc_obj.users, function(user){ unique_users.push(user.user_id + "")});
unique_users = _.uniq(unique_users);
discussion_creator_id = disc_obj.creator_id;
cbk2();
async.forEach(unique_users, iterator.bind({subject_id: disc_obj.subject_id}), function(err){
if (err) console.log(err);
});
}
})
},
//add notification for Qouted comment creator
function(cbk2){
console.log('debugging waterfall 3 3');
if(post_object.ref_to_post_id){
models.PostOrSuggestion.findById(post_object.ref_to_post_id, function(err, quoted_post){
if(err)
cbk2(err, null);
else{
if(quoted_post)
notifications.create_user_notification("been_quoted", post_object._id/*ref_to_post_id*/, quoted_post.creator_id, post_object.creator_id, discussion_id, '/discussions/' + discussion_id, function(err, result){
cbk2(err, result);
});
else
{
console.log("there is no post with post_object.ref_to_post_id id");
cbk2(err, 0);
}
}
})
}else{
cbk2(null, 0);
}
},
// update actions done by user
function(cbk2){
models.User.update({_id:user.id},{$set: {"actions_done_by_user.post_on_object": true}}, function(err){
cbk2(err);
});
}
],
cbk);
},
// 4) publish to facebook
function(args,cbk) {
og_action({
action: 'comment',
object_name:'discussion',
object_url : '/discussions/' + discussion_id,
callback_url:'/discussions/' + discussion_id + '/posts/' + post_id,
fid : user.facebook_id,
access_token:user.access_token,
user:user
});
cbk();
}
],function(err)
{
var rsp = {};
_.each(['text','popularity','creation_date','parent_id', 'votes_for','votes_against', '_id', 'ref_to_post_id', 'avatar'],function(field)
{
rsp[field] = post_object[field];
});
rsp.avatar = req.user.avatar_url();
rsp.creator_id = req.user;
rsp.user = req.user;
rsp.is_my_comment = true;
callback(err, rsp);
});
},
// user can update his post in the first 15 min after publish
update_obj: function(req, object, callback){
//first check if its in 15 min range after publish
if(new Date() - object.creation_date > EDIT_TEXT_LEGIT_TIME){
callback({message: 'to late to update comment', code: 404})
}else{
this._super(req, object, callback);
}
},
delete_obj: function(req,object,callback){
if (object.creator_id && (req.user.id === object.creator_id.id)){
object.remove(function(err){
callback(err);
})
}else{
callback({err: 401, message :"user can't delete others posts"});
}
}
});
function setQuotedPost(post_id, quoted_post_id, user_name){
var quoted_by = {
post_id: post_id,
user_name: user_name
}
models.Post.update({_id: quoted_post_id}, {$addToSet : {quoted_by : quoted_by}}, function(err, num){
if(err){
console.error(err);
}
});
}<file_sep>var models = require('../../models'),
SubjectResource = require('../../api/SubjectResource.js'),
notifications = require('../../api/notifications.js');
module.exports = function(req,res) {
var subject_id = req.params[0];
var subject_resource = new SubjectResource();
var user = req.user;
subject_resource.get_object(req, subject_id, function(err, result){
if(err) {
res.render('500.ejs',{error:err});
} else {
res.render('subject_new.ejs', {
subject: result,
logged: req.isAuthenticated(),
user: user && {_id: user._id, first_name: user.first_name, last_name: user.last_name, occupation: user.occupation},
avatar: req.session.avatar_url,
user_logged: req.isAuthenticated(),
url: req.url,
is_no_sheatufim: result.is_no_sheatufim
});
if (user){
var path = req.path.indexOf('#') == -1 ? req.path : req.path.substr(0, req.path.indexOf('#'));
notifications.updateVisited(user, req.path);
} }
});
};
// async.parallel([
// function(cbk) {
//
// },
//
// function(cbk){
// information_item_resource.get_objects(req, {subjects: subject_id}, {creation_date: -1}, 3, 0, function(err, information_items){
// console.log(information_items);
// cbk(err, information_items);
// });
// },
// function(cbk){
// links_resource.get_objects(req, {subjects: subject_id}, {creation_date: -1}, 6, 0, function(err, link_items){
// console.log(link_items);
// cbk(err, link_items);
// });
// }
// ], function(err, results){
// var subject = results[0],
// information_items = results[1].objects,
// links = results[2].objects;
// if(err)
// res.render('500.ejs',{error:err});
// else {
// if(!subject)
// res.redirect('/');
// else
// res.render('subject_new.ejs', {
// subject: subject,
// logged: req.isAuthenticated(),
// user: req.user,
// avatar:req.session.avatar_url,
// user_logged: req.isAuthenticated(),
// url:req.url,
// information_items: information_items || [],
// links: links || []
// });
// }
// });
<file_sep>
module.exports = function(router){
router.all('', require('./myuru'));
router.all(/\/([0-9a-f]+)\/?$/,require('./myuru'));
};
<file_sep>
var resources = require('jest'),
og_action = require('../../og/og.js').doAction,
models = require('../../models'),
common = require('../common.js'),
discussionCommon = require('./common'),
async = require('async'),
_ = require('underscore'),
notifications = require('../notifications.js');
var PostDiscussionResource = module.exports = common.BaseModelResource.extend({
init:function () {
this._super(models.PostDiscussion);
this.allowed_methods = ['get', 'post', 'put', 'delete'];
this.filtering = {discussion_id:null, parent_id: null};
this.authorization = new discussionCommon.DiscussionAuthorization();
this.default_query = function (query) {
return query.sort({creation_date:'descending'});
};
this.fields = {
creator_id : null,
user: null,
username: null,
avatar: null,
text:null,
creation_date: null,
_id:null,
discussion_id:null,
is_my_comment: null,
parent_id: null,
user_occupation: null,
responses: null,
post_groups: null,
count: null,
page_posts: null,
attachment:null,
like_users: null,
likes: null,
user_liked: null
};
this.default_limit = 50;
},
run_query: function(req,query,callback)
{
query.populate('creator_id');
this._super(req,query,callback);
},
get_objects:function (req, filters, sorts, limit, offset, callback) {
var self = this;
this._super(req, filters, sorts, 0, 0, function (err, results) {
var new_posts = [];
//set avatar and user info for each posts
_.each(results.objects, function(post){
var new_post = post.toObject();
new_post.avatar = post.creator_id. avatar_url();
new_post.username = post.creator_id.toString();
new_post.creator_id = post.creator_id.id;
new_post.user_occupation = post.creator_id.occupation;
//set is_my_comment flag
new_post.is_my_comment = req.user && (req.user.id + "" === (post.creator_id && post.creator_id + ""));
new_posts.push(new_post);
});
async.forEach(new_posts, function(post, cbk){
post.like_users = "";
post.likes = 0;
post.user_liked = false;
models.LikePost.find().where('post_id', post._id).populate('user_id').exec(function(err, likes){
if(err) cbk(err);
else {
_.forEach(likes, function(like){
post.like_users += like.user_id.first_name + ' ' + like.user_id.last_name + ' ';
post.likes += 1;
if(like.user_id._id.toString() == req.user._id.toString()){
post.user_liked = true;
}
});
cbk(null);
}
});
}, function(err){
//the posts with no parents are main posts
var main_posts = _.filter(new_posts, function(post){
return !post.parent_id;
});
//group sub_posts by their parents
var post_groups = _.groupBy(new_posts, function(post){
return post.parent_id;
});
//paginate
var page_posts = main_posts;
if(offset)
page_posts = _.rest(page_posts, offset);
if(limit)
page_posts = _.first(page_posts,limit);
var result = {
post_groups: post_groups,
count: main_posts.length,
page_posts: page_posts
};
callback(err, result);
});
});
},
create_obj: function(req, fields, callback) {
var self = this,
base = this._super,
user = req.session.user,
user_id = req.session.user._id;
fields.creator_id = req.session.user.id;
fields.text = common.escapeHtml(fields.text);
async.waterfall([
function(cbk) {
base.call(self, req, fields, function(err, post){
post.avatar = req.user.avatar_url();
post.user = req.user;
cbk(err, post);
});
},
function(post, cbk){
//find the discussion to get the subject_id
var discussion_id = post.discussion_id;
models
.Discussion
.findById(discussion_id, function(err, discussion){
cbk(err, post, discussion);
});
},
function(post, discussion, cbk){
var subject_id = discussion.subject_id;
models
.User
.find()
.where('subjects', subject_id)
.exec(function(err, users){
cbk(err, post, users, subject_id);
});
},
function(post, users, subject_id, cbk){
//find parent post user if exists
if(post.parent_id) {
models
.PostDiscussion
.findById(post.parent_id, function(err, parent_post){
cbk(err, post, users, subject_id, parent_post);
});
} else {
cbk(null, post, users, subject_id, null);
}
}
], function(err, post, users, subject_id, parent_post){
if(err){}
var post = post,
discussion_id = post.discussion_id.toString(),
users = users,
parent_post = parent_post,
subject_id = subject_id;
async.parallel([
function(clbk){
if(users) {
//send notification to all user that are part of the subject
async.each(users, function(user, c){
if(user._id.toString() == user_id.toString()){
c(null, 0);
} else {
notifications.create_user_notification("comment_on_discussion_you_are_part_of", post._id, user._id.toString(), user_id.toString(), discussion_id.toString(), '/discussions/' + discussion_id, subject_id, function(err, results){
c(err, results);
});
}
}, function(err, results){
clbk(err);
});
} else {
clbk(null);
}
},
function(clbk){
if (parent_post && parent_post.creator_id.toString() != user_id.toString()) {
//send notification to the parent post user if it exists
notifications.create_user_notification("comment_on_your_discussion_post", post._id.toString(), parent_post.creator_id.toString(), user_id.toString(), discussion_id.toString(), '/discussions/' + discussion_id, subject_id, function(err, results){
clbk(err, post);
});
} else {
clbk(null, post);
}
},
function(clbk)
{
//add user that discussion participant count to discussion
models.Discussion.update({_id: discussion_id, "users.user_id": {$ne: user_id}},
{$addToSet: {users: {user_id: user_id, join_date: Date.now(), $set:{last_updated: Date.now()}}}}, clbk);
},
], function(err, results){
var post_to_send = results[1];
post_to_send.avatar = req.user.avatar_url();
post_to_send.user = req.user;
callback(err, post_to_send);
});
});
},
delete_obj: function(req,object,callback){
if (object.creator_id && (req.user.id === object.creator_id.id)){
object.remove(function(err){
callback(err);
})
}else{
callback({err: 401, message :"user can't delete posts of others"});
}
}
});
<file_sep>var resources = require('jest'),
models = require('../../models'),
common = require('../common.js'),
async = require('async'),
og_action = require('../../og/og.js').doAction,
_ = require('underscore'),
notifications = require('../notifications.js');
/**
* Discussion Authorization
*/
var Authorization = common.BaseAuthorization.extend({
/**
* limits discussion query to published discussions that have a subjectId that the user is allowed to view
*/
limit_object_list: function (req, query, callback) {
var subjectIds = req.user.subjects ? req.user.subjects.map(function(subject) { return subject + '';}) : [];
query.where('subject_id').in(subjectIds);
if (req.method == "GET") {
query.where('is_published', true).populate('creator_id');
return callback(null, query);
}
callback(null, query);
},
limit_object:function (req, query, callback) {
return this.limit_object_list(req, query, callback);
}
});
var DiscussionResource = module.exports = common.BaseModelResource.extend({
init:function () {
this._super(models.Discussion);
this.allowed_methods = ['get', 'post', 'put', 'delete'];
this.filtering = {subject_id:null, users:null, is_published:null, is_private:null, tags:null,
'users.user_id':{
exact:true,
in:true
}
};
this.authorization = new Authorization();
this.default_query = function (query) {
return query.sort({creation_date:'descending'});
},
this.fields = {
title:null,
tooltip_or_title:null,
image_field:null,
image_field_preview:null,
subject_id:null,
subject_name:null,
creation_date:null,
creator_id:null,
first_name:null,
last_name:null,
text_field_preview:null,
text_field:null,
num_of_approved_change_suggestions:null,
is_cycle:null,
tags:null,
followers_count: null,
participants_count: null,
evaluate_counter: null,
_id:null,
is_follower: null,
grade: null,
last_updated: null,
grade_obj:{
grade_id:null,
value:null
},
deadline:null
};
this.update_fields = {
title:null,
image_field:null,
subject_id:null,
subject_name:null,
creation_date:null,
text_field:null,
tags:null
};
},
get_discussion:function (object, user, callback) {
if (object) {
object.is_follower = false;
object.participants_count = object.users ? object.users.length : 0;
if (user) {
if (_.find(user.discussions, function (user_discussion) {
return user_discussion.discussion_id + "" == object._id
})) {
object.is_follower = true;
}
models.Grade.findOne({user_id:user._id, discussion_id:object._id}, function (err, grade) {
if (err) {
callback(err, object);
}
else {
if (grade) {
object.grade_obj = {};
object.grade_obj["grade_id"] = grade._id;
object.grade_obj["value"] = grade.evaluation_grade;
}
}
callback(err, object);
});
} else {
callback(null, object);
}
} else {
callback({message:"internal error", code:500}, object);
}
},
get_object:function (req, id, callback) {
var self = this;
self._super(req, id, function (err, object) {
self.get_discussion(object, req.user, callback);
})
},
get_objects:function (req, filters, sorts, limit, offset, callback) {
if (req.query.get == "myUru") {
var user_id = req.query.user_id || req.user._id;
filters['users.user_id'] = user_id;
}
this._super(req, filters, sorts, limit, offset, function (err, results) {
if(err) return callback(err);
var user_discussions;
if (req.user)
user_discussions = req.user.discussions;
_.each(results.objects || [], function (discussion) {
discussion.participants_count = discussion.users ? discussion.users.length : 0;
discussion.is_follower = false;
if (user_discussions) {
if (_.find(user_discussions, function (user_discussion) {
return user_discussion.discussion_id + "" == discussion._id + "";
})) {
discussion.is_follower = true;
}
}
});
callback(err, results);
});
},
create_obj:function (req, fields, callback) {
var user_id = req.session.user_id;
var self = this;
var object = new self.model();
var user = req.user;
var created_discussion_id;
var info_items;
var number_of_taged_info_items;
if(fields.text_field)
fields.text_field_preivew = fields.text_field.substr(0,365);
if(!fields.image_field)
fields.image_field = { url:'/images/' + fields.subject_id + '.jpg',path:'/images/' + fields.subject_id + '.jpg'};
if(fields.image_field)
fields.image_field_preview = fields.image_field;
var iterator = function (info_item, itr_cbk) {
info_item.discussions.push(created_discussion_id);
for (var i = 0; i < info_item.users.length; i++) {
if (info_item.users[i] == req.session.user_id) {
info_item.users.splice(i, 1);
i--;
}
}
info_item.save(itr_cbk());
};
/**
* Waterfall:
* 1) get user shopping cart information items
* 2) check if has enough tokens, get subject
* 3) set fields, send to authorization
* 4) save the discussion object
* 5) remove information items from user shopping cart
* 6) add discussion to user discussions (as a follower)
* 7) set gamification details, create notifications
* 7.1) find all information items and set notifications for their owners
* 7.2) set notification for users that i'm their proxy
* 7.3) create new DiscussionHistory schema for this Discussion
* 8) publish to facebook
*
* Final) return discussion object (or error)
*/
async.waterfall([
// 1) get user shopping cart information items
function(cbk) {
models.InformationItem.find({users:req.user._id},cbk);
},
// 2) check if has enough tokens, get subject
function(_info_items,cbk) {
info_items = _info_items;
number_of_taged_info_items = info_items.length;
var user_cup = 9 + user.num_of_extra_tokens;
//conditions for creating a new discussion
var is_good_flag = true;
//vision cant be more than 800 words, title can't be more than 75 letters
var vision_splited_to_words = fields.text_field.split(" ");
var words_counter = 0;
var title_length = fields.title.length;
_.each(vision_splited_to_words, function (word) {
if (word != " " && word != "") words_counter++
});
if (words_counter >= 800) {
cbk({message: "vision can't be more than 800 words", code: 401}, null);
} else if (title_length > 75) {
cbk({message: "title can't be longer than 75 characters", code: 401}, null);
} else {
//get subject_name
models.Subject.findById(fields.subject_id, cbk);
}
},
// 3) set fields, send to authorization
function(subject,cbk) {
fields.subject_name = subject.name;
fields.creator_id = user_id;
fields.first_name = user.first_name;
fields.last_name = user.last_name;
fields.users = {
user_id:user_id,
join_date:Date.now()
};
fields.is_published = true; //TODO this is only for now
// create text_field_preview - 200 chars
if (fields.text_field.length >= 200)
fields.text_field_preview = fields.text_field.substr(0, 200);
else
fields.text_field_preview = fields.text_field;
for (var field in fields) {
object.set(field, fields[field]);
}
//set create_discussion_ price
// for each tagging of 2 information items the price is minus 1 tokens
// the max discount is 3;
self.authorization.edit_object(req, object, cbk);
},
// 4) save the discussion object
function(object,cbk) {
object.save(function (err, object) {
cbk(err,object)
});
},
// 5) remove information items from user shopping cart
function(obj,cbk) {
created_discussion_id = obj._id;
//add info items to discussion shopping cart and delete it from user's shopping cart
async.forEach(info_items, iterator, function (err) {
cbk(err);
});
},
// 6) add discussion to user discussions (as a follower)
function(cbk) {
var user_discussion = {
discussion_id:object._id,
join_date:Date.now()
};
if (object.is_published)
models.User.update({_id:user._id}, {$addToSet:{discussions:user_discussion}},function(err) {
cbk(err);
});
else
callback(null,object);
},
// 7) set gamification details, create notifications
function(cbk, arg) {
//set gamification
async.parallel([
//find all information items and set notifications for their owners
function(cbk1){
// first - continue
cbk1();
// second - create notifications and send mails
notifications_for_the_info_items_relvant(object._id, user_id, object.subject_id, function(err) {
if(err){
console.error(err);
}else{
console.log("notification of new discussion were created successfully")
}
});
},
// create new DiscussionHistory schema for this Discussion
function(cbk1){
var discussion_history = new models.DiscussionHistory();
discussion_history.discussion_id = object._id;
discussion_history.date = Date.now();
discussion_history.text_field = object.text_field;
discussion_history.save(cbk1);
},
// update actions done by user
function(cbk1){
models.User.update({_id:user._id},{$set: {"actions_done_by_user.create_object": true}}, function(err){
cbk1(err);
});
}
], function(err){
cbk(err);
})
},
// 8) publish to facebook
// function(cbk) {
// og_action({
// action: 'created',
// object_name:'discussion',
// object_url : '/discussions/' + object.id,
// fid : user.facebook_id,
// access_token:user.access_token,
// user:user
// });
// cbk();
// }
],
// Final) return discussion object
function(err) {
callback(err,object);
});
},
update_obj:function (req, object, callback) {
var user = req.user;
if (req.query.put == "follower") {
var disc = _.find(user.discussions, function (discussion) {
return discussion.discussion_id + '' == object._id + '';
});
if (!disc) {
async.parallel([
//add user to followers in users.discussions
function (cbk2) {
var user_discussion = {
discussion_id:object._id,
join_date:Date.now()
}
models.User.update({_id:user._id}, {$addToSet:{discussions:user_discussion}}, cbk2);
},
//increase discussion followers and add user to "people that connected somhow to discussion" if its a new user..
function (cbk2) {
var connected_somehow_user = _.find(object.users, function (user) {
return user.user_id + '' == user._id + '';
});
if (!connected_somehow_user) {
//if new user that "connected somehow to the discussion" so add to set it
var discussion_user = {
user_id: user._id,
join_date:Date.now()
}
models.Discussion.update({_id:object._id}, {$inc:{followers_count:1}, $addToSet:{users: discussion_user}}, cbk2);
}else{
//only increase num of followers
models.Discussion.update({_id:object._id}, {$inc:{followers_count:1}}, cbk2);
}
}
], function () {
object.followers_count++;
object.is_follower = true;
callback(null, object);
});
} else {
callback({message:"user is already a follower", code:401}, null);
}
} else {
if (req.query.put == "leave") {
async.waterfall([
function (cbk) {
var disc = _.find(user.discussions, function (discussion) {
return discussion.discussion_id + '' == object._id + '';
});
if (disc) {
//delete this discussion
user.discussions.splice(_.indexOf(user.discussions, disc));
user.save(cbk);
} else {
callback({message:"user is not a follower", code:401}, null);
}
},
function (obj, cbk) {
models.Discussion.update({_id:object._id}, {$inc:{followers_count:-1}}, function (err, num) {
object.followers_count--;
object.is_follower = false;
callback(err, object);
});
}
], function (err, result) {
callback(err, object);
})
} else {
if (object.is_published) {
callback("this discussion is already published", null);
} else {
object.is_published = true;
object.save(function (err, disc_obj) {
notifications_for_the_info_items_relvant(disc_obj._id, user._id, disc_obj.subject_id, function (err) {
if(err)
callback(err);
else {
// publish to facebook
if(!object.is_private) {
og_action({
action: 'created',
object_name:'discussion',
object_url : '/discussions/' + object.id,
fid : user.facebook_id,
access_token:user.access_token,
user:user
});
}
callback(err,object);
}
})
});
}
}
}
}
});
function notifications_for_the_info_items_relvant(discussion_id, notificator_id, subject_id, callback) {
var new_discussion_notification_itr = function (user, itr_cbk) {
// check if user is not the notificator and if user chosen to get this notification in mail configuration
if ( user._id + "" != notificator_id + "" && _.any(user.mail_notification_configuration.new_discussion, function(discussion){
return discussion.subject_id + "" == subject_id + "" && discussion.get_alert }))
{
notifications.create_user_notification("new_discussion",
discussion_id, user._id, notificator_id, null, '/discussions/' + discussion_id, subject_id, itr_cbk);
}else{
itr_cbk();
}
};
async.parallel([
// notifications about new discussion
function(par_cbk){
async.waterfall([
// find users that chosen to get notifications about new discussions of this subject
function (cbk) {
models.User.find({"mail_notification_configuration.get_mails": true, "mail_notification_configuration.new_discussion" : {$elemMatch : { subject_id : subject_id + "", get_alert : true}}}, cbk);
},
// create site notifications and mail notifications
function (users, cbk) {
async.forEach(users, new_discussion_notification_itr, cbk);
}
], function (err) {
par_cbk(err);
})
}
], function(err){
callback(err);
})
}
<file_sep>var mongoose = require("mongoose"),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId,
common = require('./common'),
utils = require('./../utils'),
async = require('async'),
_ = require('underscore');
var MinLengthValidator = function (min) {
return [function (value) {
return value && value.length >= min;
}, 'Name must contain at least ' + min + ' letters'];
};
var RegexValidator = function (regex) {
return [function (value) {
return value && regex.exec(value)
}, 'Value is not at the correct pattern'];
};
var User = module.exports = new Schema({
//this is for validation
is_activated: {type: Boolean, 'default': true},
has_reset_password: {type: Boolean, 'default': false},
is_suspended: {type: Boolean, 'default': false},
identity_provider:{type:String, "enum":['facebook', 'register'], 'default': 'register'},
facebook_id: {type: String, editable:false},
access_token: {type: String, editable:false},
first_name:{type:String, required:true, validate:MinLengthValidator(2)},
last_name:{type:String, required:false},
email:{type:String, required:true},//, match:/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/},
gender:{type:String, "enum":['male', 'female']},
age:{type:Number, min:0},
last_visit:{type:Date,'default':Date.now},
address: String,
occupation: String,
biography: String,
invitation_code: {type: String, editable:false},
//followers - in the redesign it is the same as discussion.users
discussions:[
new Schema({
discussion_id:{type:ObjectId, ref:'Discussion', limit: 1000},
join_date: {type:Date, 'default':Date.now},
time_of_alert: {type:String, "enum":['now', 'today', 'this_week'], 'default': 'now'},
})
],
// List of subject ref ids, that the user is authorized to view
subjects:[{type:ObjectId, ref:'Subject',query:common.SUBJECT_QUERY,help:'Add subject that this user is authorized to view'}],
password: {type: String, editable:false},
validation_code: {type: String, editable:false},
updates: {type:Schema.Types.Mixed,editable:false},
avatar : Schema.Types.File,
sent_mail: {type:Date,editable:false},
actions_done_by_user:{
create_object:false,
post_on_object:false,
suggestion_on_object:false,
grade_object:false,
vote_on_object:false,
join_to_object:false
},
no_mail_notifications: {type : Boolean, "default": true},
mail_notification_configuration: {
// general
get_mails: {type: Boolean, 'default': true},
get_alert_of_new_discussion_in_subject_you_are_part_of: {type: Boolean, 'default': true},
get_alert_of_new_information_item_on_subject_you_are_part_of: {type: Boolean, 'default': false},
get_alert_of_new_question_in_subject_you_are_part_of: {type: Boolean, 'default': true},
get_alert_of_comment_on_question_in_subject_you_are_part_of: {type: Boolean, 'default': false},
//general forum
get_alert_of_comment_on_subject_you_are_part_of: {type: Boolean, 'default': false},
get_alert_of_comment_on_your_forum_post: {type: Boolean, 'default': false},
//general discussions
get_alert_of_comment_on_discussion_you_are_part_of: {type: Boolean, 'default': false},
get_alert_of_comment_on_your_discussion_post: {type: Boolean, 'default': false},
get_alert_of_change_suggestion_on_discussion_you_are_part_of: {type: Boolean, 'default': false},
get_alert_of_comment_on_change_suggestion_i_created: {type: Boolean, 'default': false},
get_alert_of_approved_change_suggestion_on_discussion_you_are_part_of: {type: Boolean, 'default': false}
}
}, {strict:false});
User.methods.toString = function()
{
var parts = [];
if(this.first_name)
parts.push(this.first_name);
if(this.last_name)
parts.push(this.last_name);
return parts.join(' ');
};
User.methods.avatar_url = function()
{
if(this.avatar && this.avatar.url)
return this.avatar.url;
else
return this.facebook_id ? 'http://graph.facebook.com/' + this.facebook_id + '/picture/?type=large' : "/images/default_user_img.gif";
};
/**
* Post-init hook - save a copy of subject list
*/
User.post('init',function(){
this._lastSubjects = (this.subjects || []).map(function(subject) { return subject + ''; });
});
/**
* Pre-save hook - check is subject list was changed.
* If so, collect new subjects and notify user
*/
User.pre('save',function(next){
var is_new = this.isNew;
if(!this._lastSubjects && !is_new)
return next();
// get new subjects ids
var newSubjectList = (this.subjects || []).map(function(subject) { return subject + '';});
var newSubjects = _.difference(newSubjectList,this._lastSubjects || []);
delete this._lastSubjects;
// continue
next();
if(!newSubjects.length && !is_new)
return;
var self = this;
// get subject objects
mongoose.model('Subject').find()
.where('_id').in(newSubjects)
.exec(function(err,subjects){
if(err) return console.error('Error getting subjects from DB with ids ' + newSubjects,err);
if(!subjects.length) return;
var firstSubjectUrl = '/discussions/subject/' + subjects[0].id;
var redirect_to = require('../routes/account/common').DEFAULT_LOGIN_REDIRECT;
var host_title = "שיתופים",
root_path = "http://www.sheatufim-roundtable.org.il/",
email_details,
is_sheatufim_flag = true;
if(subjects[0].is_no_sheatufim){
host_title = subjects[0].host_details.title;
root_path = subjects[0].host_details.host_address + '/';
email_details = {
email: subjects[0].host_details.email,
title: subjects[0].host_details.title
};
is_sheatufim_flag = false;
}
if(is_new || !self.has_reset_password || !self.is_activated){
// if the user is new, need to send activation mail
require('../routes/account/activation').sendActivationMail(self, redirect_to/*firstSubjectUrl*/, 'inviteNewUserToSubject',{subjects:subjects, host_title: host_title, root_path: root_path, is_sheatufim_flag: is_sheatufim_flag}, email_details,function(err){
if(err)
console.error('Error sending mail to user ' + self,err);
});
}
else {
// if the user exists, send only activation mail
async.waterfall([
function(cbk){
require('../lib/templates').renderTemplate('inviteUserToSubject',{user:self, next:firstSubjectUrl,subjects:subjects, host_title: host_title, root_path: root_path, is_sheatufim_flag: is_sheatufim_flag},cbk);
},
function(string,cbk) {
require('../lib/mail').sendMailFromTemplate(self.email, string ,email_details, cbk);
}
],function(err){
if(err)
console.error('Error sending mail to user ' + self,err);
});
}
});
});<file_sep>
module.exports = function(router){
router.all('', require('./user'));
router.all(/\/([0-9a-f]+)\/?$/,require('./user'));
};
<file_sep>/**
* Created by JetBrains WebStorm.
* User: saar
* Date: 26/02/12
* Time: 19:26
* To change this template use File | Settings | File Templates.
*/
var resources = require('jest'),
util = require('util'),
models = require('../../models'),
common = require('../common.js'),
discussionCommon = require('./common');
var DiscussionShoppingCartResource = module.exports = common.BaseModelResource.extend({
init: function () {
this._super(models.InformationItem);
this.allowed_methods = ['get', 'post', 'put', 'delete'];
this.authorization = new discussionCommon.DiscussionAuthorization();
this.default_query = function (query) {
return query.where('is_visible', true).sort({creation_date: 'descending'});
};
},
update_obj: function (req, object, callback) {
console.log("inside DiscussionShoppingCartResource update.obj");
var discussion_id = req.body.discussion_id;
console.log(discussion_id);
var is_exist = false;
for (var i = 0; i < object.discussions.length; i++) {
if (object.discussions[i] == discussion_id) {
is_exist = true;
break;
}
}
if (is_exist) {
callback("information item is already in discussion shoping cart", null);
} else {
//add item to discussion's shopping cart
object.discussions.push(discussion_id);
//add notification for user
object.save(callback);
}
},
delete_obj: function (req, object, callback) {
console.log("inside DiscussionShoppingCartResource delete_obj");
var discussion_id = req.body.discussion_id;
var test = req.query.discussion_id;
for (var i = 0; i < object.discussions.length; i++) {
if (object.discussions[i] == test) {
object.discussions.splice(i, 1);
i--;
}
}
object.save(callback);
}
});
<file_sep>var models = require('../../models'),
config = require('../../config.js'),
_ = require('underscore')
, common = require('./common');
module.exports ={
get: function(req, res){
var host = req.get('host');
var data = {
next: req.query.next,
title: "רישום",
is_no_sheatufim : false,
subject : {}
};
if(!_.find(config.hosts, function(hst){return hst == host; })){
data.is_no_sheatufim = true;
models.Subject.findOne().where('host_details.host_address', 'http://' + host).exec(function(err, subject){
if(err || !subject) throw new Error('Subject with this host was not found');
data.subject = subject;
res.render('reset_password.ejs', data);
});
} else {
res.render('reset_password.ejs', data);
}
},
post: function(req, res){
var user_id = req.query.id;
var validation_code = req.query.code;
var password= <PASSWORD>;
if(user_id){
models.User.findById(user_id, function(err, user){
if(!err && user){
if(user.validation_code == validation_code){
user.password = <PASSWORD>.hash_password(<PASSWORD>);
user.is_activated = true;
user.has_reset_password = true;
user.save(function(err, user){
if(!err){
req.body.password = <PASSWORD>;
req.body.email = user.email;
req.authenticate('simple', function (err, is_authenticated) {
if (is_authenticated) {
var next = req.query.next || common.DEFAULT_LOGIN_REDIRECT;
if(next.indexOf('?') > -1)
next += '&is_new=reset';
else
next += '?is_new=reset';
res.redirect(next);
}
else {
res.render('500.ejs', {error:err});
}
});
}else{
console.error('cant save',err);
res.render('500.ejs', {error:err});
}
})
}else{
console.error('bad link');
res.render('500.ejs', {error:'לינק שגוי או מיושן, שלח מייל מחדש'});
}
}else{
console.error('no user',err);
res.render('500.ejs', {error:err});
}
})
} else{
console.error('bad link');
res.render('500.ejs', {error:'לינק שגוי'});
}
}
}
<file_sep>var _ = require('underscore'),
conf = require('./config');
module.exports = function (grunt) {
grunt.initConfig(createGruntConf());
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task.
grunt.registerTask('default', ['concat','uglify']);
};
function createGruntConf() {
var concat = {};
var min = {};
var mincss = {};
_.each(conf.headConfigs, function (value, key) {
var concatDest = __dirname + '/deliver/public' + ((value.min === false && value.final) || value.concat || '/dist/' + value.type + '/' + value.name + '.' + value.type);
var minDest = __dirname + '/deliver/public' + (value.final || '/dist/' + value.type + '/' + value.name + '.min.' + value.type);
concat[key] = {
src:_.map(value.src || [], function (src) {
return __dirname + '/deliver/public' + src;
}),
dest:concatDest,
options:{separator:value.type == 'js' ? ';\n' : '\n'}
};
if (value.min !== false) {
if (value.type == 'js')
min[key] = {
src:[concatDest],
dest:minDest
};
else {
mincss[key] = {};
mincss[key][concatDest] = minDest;
}
}
});
return {concat:concat, uglify:min};
};
<file_sep>(function ($) {
var allCounter = [];
$.fn.countdown = function (method) {
if (typeof method === 'object' || !method) {
return pictimeJQinit.apply(this, arguments);
} else {
return pictimeFunctions.apply(this, arguments)
}
};
$.fn.countdown.onEventBinding = function (id, eventname) {
pictimeFunctions.apply(document.getElementById(id), Array.prototype.slice.call(arguments).splice(1, arguments.length - 1));
};
function pictimeJQinit(options) {
options = $.extend(
{
deadline:null
}, options);
return this.each(function () {
var $this = $(this);
$this.data('countdown', options);
var data = $this.data('countdown');
pictimeFunctions.call(this, "initUC");
});
}
/////////////////////////////////////////////////////////////////////////////////////
function pictimeFunctions(method) {
var $this = $(this);
var data = $this.data('countdown') || {};
var id = $this.attr("id");
var mythis = this;
if (data.methods == null) {
data.methods = {
initUC:initUC,
updateTime:updateTime,
destroy:destroy
};
}
if (data.methods[method]) return data.methods[method].apply(this, Array.prototype.slice.call(arguments).splice(1, arguments.length - 1)); else throw "Method [" + method + "] was not found for photoStream, check data.methods";
function initUC() {
if(!data.deadline)
data.deadline = new Date($this.data('time'));
data.$seconds = $this.find('.seconds');
data.$minutes = $this.find('.minutes');
data.$hours = $this.find('.hours');
data.$days = $this.find('.days');
allCounter.push($this);
startGlobalTimer();
updateTime(new Date);
}
function updateTime(dateTime){
var span = data.deadline - dateTime;
if(span < 0)
return;
var seconds = span/1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var secondsLeft = Math.floor(seconds) - Math.floor(minutes) * 60;
if(data._seconds != secondsLeft) {
data.$seconds.text(secondsLeft < 10 ? '0' + secondsLeft : secondsLeft);
data._seconds = secondsLeft;
}
var minutesLeft = Math.floor(minutes) - Math.floor(hours) * 60;
if(minutesLeft != data._minutes) {
data.$minutes.text(minutesLeft);
data._minutes = minutesLeft;
}
var hoursLeft = Math.floor(hours) - Math.floor(days)*24;
if(data._hours != hoursLeft) {
data.$hours.text(hoursLeft);
data._hours = hoursLeft;
}
var daysLeft = Math.floor(days);
if(data._days != daysLeft) {
data.$days.text(daysLeft);
data._days = daysLeft;
}
}
function destroy(){
$this.removeData('countdown');
}
}
var globalInterval;
function startGlobalTimer(){
if(globalInterval)
return;
globalInterval = setInterval(function(){
var date = new Date();
$.each(allCounter,function(i,counter){
counter.countdown('updateTime',date);
});
},900);
}
})(jQuery);
<file_sep>var util = require('util');
var jest = require('jest'),
models = require('../models'),
fs = require('fs'),
path = require('path'),
async = require('async');
var formage = require('formage-admin').forms;
var knox;
try
{
knox = require('knox');
}
catch(e)
{
}
var ACTION_PRICE = 2;
var user_public_fields = exports.user_public_fields = {
id: null,
first_name: null,
last_name: null,
avatar_url: null,
score: null,
num_of_given_mandates: null,
num_of_proxies_i_represent: null,
has_voted: null,
no_mail_notifications: null ,
identity_provider:null,
occupation: null
};
var SessionAuthentication = exports.SessionAuthentication = jest.Authentication.extend({
init:function(allowAnonymous){
this._super();
this.allowAnonymous = allowAnonymous;
},
is_authenticated : function(req, callback){
//noinspection JSUnresolvedFunction
var is_auth = req.isAuthenticated();
if(is_auth)
{
var user_id = req.session.user_id;
if(!user_id){
callback({message: "no user id"}, null);
}else{
models.User.findById(user_id, function(err,user)
{
if(err)
callback(err);
else
{
if(!user) {
if(req.method != 'GET')
callback(null,false);
else
callback(null,true);
return;
}
req.user = user;
// save user last visit
// to avoid many updates to the db, don't save if the difference is less than 2 minutes
if( !user.last_visit || (new Date() - user.last_visit > 1000*60*2))
models.User.update({_id:user._id},{$set:{last_visit: new Date()}},function(err) {
if(err) {
console.error('failed setting last visit',err);
}
else
console.log('saved last visit');
});
var is_activated = user.is_activated;
var is_suspended = user.is_suspended;
if (req.method == 'GET' || (is_activated && !is_suspended))
callback(null, true);
else {
callback({code:401, message: is_suspended ? 'suspended' : 'not_activated'});
}
}
});
}
}
else
{
if(this.allowAnonymous && req.method == 'GET')
callback(null,true);
else
callback(null,false);
}
}
});
/**
* Base API Resources for model based resources
*/
exports.BaseModelResource = jest.MongooseResource.extend({
init:function(model){
this._super(model);
this.authentication = new SessionAuthentication();
}
});
var multiparty = require('multiparty');
exports.MultipartFormResource = exports.BaseModelResource.extend({
init:function(model){
this._super(model);
this.allowed_methods = ['put'];
this.fields = {
url:null,
name:null
};
this.update_fields = {};
},
deserialize:function(req,res,object,status){
if(!req._callback)
return this._super(req,res,object,status);
res.header('Content-Type','text/html');
if(status < 200 || status >= 300)
res.send('<html><head><script>window.parent["' + req._callback + '"](' + JSON.stringify(object) + ');</script></head><body></body></html>');
else
res.send('<html><head><script>window.parent["' + req._callback + '"](null,' + JSON.stringify(object) + ');</script></head><body></body></html>');
},
onFile:function(file,callback){
return callback('Not implemented');
},
update_obj: function(req, object, callback){
var form = new multiparty.Form({});
console.log(req.headers);
req.on('data',function(chunk) {
console.log(chunk.length);
});
form.on('field',function(name,val){
if(name == 'callback')
req._callback = val;
});
var self = this;
form.on('file', function(name, val){
self.onFile(req,object,val,callback);
callback = null;
});
form.on('error', function(err){
if(callback)
callback(err);
callback = null;
});
req.on('end', function(){
setTimeout(function(){
if(callback)
callback({code:400, message:'No file'});
callback = null;
},5000);
});
req.resume();
form.parse(req);
}
});
/**
* Base API Resources for bare resources
*/
exports.BaseResource = jest.Resource.extend({
init:function(){
this._super();
this.authentication = new SessionAuthentication();
}
});
/**
* Base class for authorization
*/
exports.BaseAuthorization = jest.Authorization;
var isArgIsInList = exports.isArgIsInList = function(arg_id, collection_list){
var flag = false;
for (var i = 0; i < collection_list.length; i++){
arg_id = arg_id || arg_id.id;
if (arg_id == collection_list[i].id){
flag = true;
break;
}
}
return flag;
};
var threshold_calc_variables = {};
function load_threshold_calc_variables(){
models.ThresholdCalcVariables.findOne({},function(err,doc)
{
if(doc)
threshold_calc_variables = doc._doc;
if(err)
console.error(err);
});
};
load_threshold_calc_variables();
models.ThresholdCalcVariables.schema.pre('save',function(next)
{
setTimeout(load_threshold_calc_variables, 1000);
next();
});
exports.getThresholdCalcVariables = function(type)
{
return threshold_calc_variables[type] || 0;
};
/**
* Upload file from http request.
* Content type is file
* @param req
* Http request with content-type as file, body is the file stream
* @param callback
* function(err, {url:'uploaded file url',path:'uploaded file path on server'})
*/
var uploadHandler = exports.uploadHandler = function(req,callback) {
var sanitize_filename = function(filename, is_dev) {
// This regex matches any character that's not alphanumeric, '_', '-' or '.', thus sanitizing the filename.
// Hebrew characters are not allowed because they would wreak havoc with the url in any case.
var regex = /[^-\w_\.]/g;
return decodeURIComponent(filename).replace(regex, '-');
},
filename_to_path = function (filename, is_dev) {
if(is_dev)
return path.join(__dirname,'..','public','cdn', filename);
else
return path.join(__dirname,'..', '..','public','cdn', filename);
},
create_file = function (filename, is_dev, callback) {
// This function attempts to create 0_filename, 1_filename, etc., until it finds a file that doesn't exist.
// Then it creates that and returns by calling callback(null, name, path, stream);
var attempt = function (index) {
var name = index + '_' + filename;
var path = filename_to_path(name, is_dev);
fs.exists(path, function (exists) {
if (exists) {
attempt(index + 1);
} else {
// File doesn't exist. We can create it
callback(null, name, path, fs.createWriteStream(path));
}
});
};
attempt(0);
},
writeToFile = function (is_dev, fName, stream, callback){
create_file(sanitize_filename(fName), is_dev, function (err, filename, fullPath, os) {
if (err) return callback(err);
// listen to stream data events
stream.on('data',function(data) {
os.write(data);
});
stream.on('end',function() {
// when stream ended, close the file
os.on('close', function () {
// when file is successuly closed
callback(null,{
url: '/cdn/' + filename,
path: fullPath
});
});
os.end();
});
// start receiving the stream
stream.resume();
});
};
var fName = req.header('x-file-name');
var fType = req.header('x-file-type');
if(!fName && !fType)
return callback({code:404,message:'bad file upload'});
var stream = req.queueStream || req;
var is_dev = req.app.get('is_developement');
writeToFile(is_dev, fName, stream,callback);
};
/**
* Ensure cdn folder exists, all file uploads will go to this folder
*/
if(!fs.existsSync(path.join(__dirname,'..','public','cdn'))){
console.log('create folder ' + path.join(__dirname,'..','public','cdn'));
fs.mkdirSync(path.join(__dirname,'..','public','cdn'));
}
var escapeHtml = exports.escapeHtml = function(text){
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return String(text).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
};
<file_sep>module.exports = function(router) {
router.get('/',require('./home'));
router.get('/about',require('./about'));
router.get('/about-en',require('./about-en'));
router.get('/contact',require('./contact'));
router.get('/team',require('./team'));
router.get('/terms-of-use',require('./terms_of_use'));
router.get('/qa',require('./qa'));
router.get('/founders',require('./founders'));
router.get('/page/:link',require('./page'));
};
<file_sep>var resources = require('jest'),
og_action = require('../../og/og.js').doAction,
models = require('../../models'),
common = require('../common.js'),
async = require('async'),
_ = require('underscore'),
notifications = require('../notifications.js');
var QuestionResource = module.exports = common.BaseModelResource.extend({
init:function () {
this._super(models.Question);
this.allowed_methods = ['get'];
this.filtering = {subject_id: null};
this.authorization = new common.BaseAuthorization();
this.default_query = function (query) {
return query.sort({creation_date:'descending'});
};
this.fields = {
_id : null,
subject_id : null,
title: null,
text: null,
creation_date: null,
deadline:null,
posts: null,
user_count: null
};
this.default_limit = 50;
},
run_query: function(req,query,callback)
{
this._super(req,query,callback);
},
get_objects:function (req, filters, sorts, limit, offset, callback) {
var self = this;
self._super(req, filters, sorts, 0, 0, function (err, results) {
if(results && results.objects.length > 0) {
async.each(results.objects, function(question, cbk){
models.PostOnQuestion
.find()
.where('question_id', question._id)
.sort({creation_date: -1})
.populate('creator_id')
.exec(function(err, posts){
if(!err){
var groups = _.unique(_.pluck(posts, 'creator_id'));
question.posts = JSON.parse(JSON.stringify(posts));
question.user_count = groups.length;
async.forEach(question.posts, function(post, cb){
post.like_users = "";
post.likes = 0;
post.user_liked = false;
//set is_my_comment flag
post.is_my_comment = req.user && (req.user.id + "" === (post.creator_id && post.creator_id + ""));
//get likes
models.LikePost.find().where('post_id', post._id).populate('user_id').exec(function(err, likes){
if(err) cb(err);
else {
_.forEach(likes, function(like){
post.like_users += like.user_id.first_name + ' ' + like.user_id.last_name + ' ';
post.likes += 1;
if(like.user_id._id.toString() == req.user._id.toString()){
post.user_liked = true;
}
});
cb(null);
}
});
}, function(err){
cbk(err, results);
});
} else {
cbk(err);
}
})
}, function(err){
callback(err, results);
});
}
});
}
});
<file_sep>var mongoose = require("mongoose"),
Schema = mongoose.Schema,
common = require('./common'),
ObjectId = Schema.ObjectId,
async = require('async'),
formage = require('formage-admin').forms,
utils = require('../utils');
var Question = module.exports = new Schema({
subject_id:{type:Schema.ObjectId, ref:'Subject', query:common.FIND_USER_QUERY,index:true, required:true, onDelete:'delete'},
title: {type: String},
text:{type:Schema.Types.Html},
creation_date:{type:Date, 'default':Date.now},
deadline:{type:Date,widget:formage.widgets.DateTimeWidget}
});
Question.statics.onPreSave = function(func){
Question.pre('save',func);
};<file_sep>var jest = require('jest')
,common = require('./common')
,models = require('../models')
,og_action = require('../og/og').doAction
,_ = require('underscore')
,config = require('../config.js')
,async = require('async')
,mail = require('../lib/mail');
var SendMailResource = module.exports = jest.Resource.extend({
init:function() {
this._super();
this.allowed_methods = ['post'];
// this.authentication = new common.SessionAuthentication();
this.fields = {};
this.update_fields = {
body : null
};
},
create_obj: function(req,fields,callback) {
var host = req.get('host');
async.waterfall([
function(callback){
if(!_.find(config.hosts, function(hst){return hst == host; })){
models.Subject.findOne().where('host_details.host_address', 'http://' + host).exec(function(err, subject){
if(err || !subject) throw new Error('Subject with this host was not found');
callback(null, subject.host_details.title);
});
} else {
callback(null, null);
}
}
], function (err, result) {
var user = req.user;
var from = result[0] ? result : config.systemEmail;
from += " <" + req.body.mail_config.email + ">";
var to = req.body.mail_config.to || '<EMAIL>';
var subject = req.body.mail_config.subject || 'NO MORE MAILS FOR ' + user.email;
var explanation = req.body.mail_config.explanation;
// var explanation = (req.body.mail_config.explanation ? req.body.mail_config.explanation + " " + user.email : 'The reason is:' + '<br>' + req.body.mail_config.body);
mail.sendMail(to, explanation, subject, from, function(err){
callback(err);
});
});
}
});
<file_sep>/**
* Created by JetBrains WebStorm.
* User: saar
* Date: 16/02/12
* Time: 11:00
* To change this template use File | Settings | File Templates.
*/
var resources = require('jest'),
models = require('../models'),
async = require('async'),
common = require('./common');
var SubjectResource = module.exports = common.BaseModelResource.extend({
init:function(){
this._super(models.Subject);
this.allowed_methods = ['get'];
this.filtering = {tags:null, is_no_sheatufim: null};
this.authentication = new common.SessionAuthentication(true);
this.max_limit = 8;
this.default_query = function(query){
return query.sort({'is_uru':-1,gui_order:1});
};
this.fields = ['name','tooltip','description','text_field_preview','image_field', 'cover_image_field',
'timeline_url','tags','is_hot_object','is_uru','isAllowed','_id'];
},
get_objects:function(req,filters,sorts,limit,offset,callback) {
this._super(req,filters,sorts,limit,offset,function(err,rsp) {
if(rsp && rsp.objects){
var userSubjects = req.user && req.user.subjects ? req.user.subjects.map(function(subject){
return subject + '';
}) : [];
rsp.objects.forEach(function(subject){
subject.isAllowed = userSubjects.indexOf(subject.id) > -1;
});
}
callback(err,rsp);
});
},
get_object:function (req, id, callback) {
models.Subject.findById(id).exec(function(err, result){
result.isAllowed = result.isUserAllowed(req.user);
callback(err, result);
});
}
});<file_sep>var models = require('../../models');
var async = require('async');
var config = require('../../config.js');
var _ = require('underscore');
module.exports = function (req, res) {
var host = req.get('host');
var data = {
layout: false,
title: "פרופיל שלי",
logged: req.isAuthenticated(),
user: req.user, // logged user
url: req.url,
avatar:req.session.avatar_url,
is_no_sheatufim : false,
subject : {}
};
if(!_.find(config.hosts, function(hst){return hst == host; })){
data.is_no_sheatufim = true;
models.Subject.findOne().where('host_details.host_address', 'http://' + host).exec(function(err, subject){
if(err || !subject) throw new Error('Subject with this host was not found');
data.subject = subject;
res.render('my_account.ejs', data);
});
} else {
res.render('my_account.ejs', data);
}
};
<file_sep>$(document).ready(function () {
var is_tabbing = false,
$popover = null;
$('body').keydown(function (e) {
console.log('keydown called');
var code = e.keyCode || e.which;
if (code == '9') { //tab
console.log('tabbing');
is_tabbing = true;
//workaround for marker navigation
// (explicitly focusing on next maker...)
if($(e.target).hasClass('marker_1')) {
var next_tab_id = $(e.target).data('tab') + 1,
$next_tab = $("#discussion_content a[data-tab=" + next_tab_id + "]");
if($next_tab.length)
$("#discussion_content a[data-tab=" + next_tab_id + "]").focus();
else
$('#suggestionTab').focus();
}
//workaround for textarea editor navigation...
if($(e.target).hasClass('discussion_content_textarea')) {
$('#suggestionTab').focus();
}
}
});
// bind a click event to the 'skip' link
$(".skip").click(function(event){
// strip the leading hash and declare
// the content we're skipping to
var skipTo="#"+this.href.split('#')[1];
// Setting 'tabindex' to -1 takes an element out of normal
// tab flow but allows it to be focused via javascript
$(skipTo).attr('tabindex', -1).on('blur focusout', function () {
// when focus leaves this element,
// remove the tabindex attribute
$(this).removeAttr('tabindex');
}).focus(); // focus on the content container
});
$('body').mouseup(function (e) {
is_tabbing = false;
$('body').find('.focused').removeClass('focused');
});
$('body').on('focus', "a, input, li, button", null, function (event) {
if (is_tabbing) {
console.log('focused added');
$(event.target).addClass("focused");
}
}).on('blur', "*", null, function (event) {
$(event.target).removeClass("focused");
});
$(document).on('focus', '.qq-uploader input', function(event){
if (is_tabbing) {
$(event.target).closest('.user_image').addClass("focused");
}
}).on('blur', ".qq-uploader input", null, function (event) {
$(event.target).closest('.user_image').removeClass("focused");
});
$(document).on('focus', '.email_settings input', function(event){
if (is_tabbing) {
$(event.target).next('label').addClass("focused");
}
}).on('blur', ".email_settings input", null, function (event) {
$(event.target).next('label').removeClass("focused");
});
$(document).on('focus', '.paper-mark', function(event){
if (is_tabbing) {
$(event.target).mouseenter();
}
});
});
<file_sep>'use strict';
console.log(process.env);
require('./lib/memory');
var express = require('express');
var util = require('util');
var utils = require('./utils');
var mongoose = require('mongoose');
var async = require('async');
var domain = require('domain');
var auth = require("connect-auth");
var formage_admin = require('formage-admin');
var config = require('./config');
formage_admin.forms.loadTypes(mongoose);
var app = module.exports = express();
app.set('show_only_published', process.env.SHOW_ONLY_PUBLISHED == '1');
utils.setShowOnlyPublished(app.settings.show_only_published);
console.log('Show only published',app.get('show_only_published'));
var logout_handler = require("connect-auth/lib/events").redirectOnLogout("/");
var account = require('./routes/account');
var fb_bot_middleware = require('./routes/fb_bot/middleware');
// ########### Static parameters ###########
var IS_ADMIN = false;
var IS_PROCESS_CRON = (process.argv[2] === 'cron');
var IS_PROCESS_WEB = !IS_PROCESS_CRON;
var auth_middleware = auth({
strategies: [
account.SimpleAuthentication(),
account.FbServerAuthentication(),
auth.Facebook(config.fb_auth_params)
],
trace: true,
logoutHandler: logout_handler
});
// ########### Static parameters ###########
// Run some compilations
// Run some compilations
require('./tools/compile_dust_templates');
// ######### connect to DB #########
if (!mongoose.connection.host) {
mongoose.connect(config.DB_URL, {safe: true}, function (db) { console.log("connected to db %s:%s/%s", mongoose.connection.host, mongoose.connection.port, mongoose.connection.name); });
mongoose.connection.on('error', function (err) { console.error('db connection error: ', err); });
mongoose.connection.on('disconnected', function (err) {
console.error('DB disconnected', err);
setTimeout(function () {mongoose.connect(config.DB_URL, function (err) { if (err) console.error(err); });}, 200);
});
}
// ######### end connect to DB #########
// ######### settings #########
app.settings['x-powered-by'] = 'Empeeric';
app.set('views', __dirname + '/views');
app.set('public_folder', __dirname + '/public');
app.set('port', process.env.PORT || 80);
app.set('facebook_app_id', config.fb_auth_params.appId);
app.set('facebook_secret', config.fb_auth_params.appSecret);
app.set('facebook_app_name', config.fb_auth_params.appName);
// TODO delete?
app.set('facebook_pages_admin_user', "<EMAIL>");
app.set('facebook_pages_admin_pass', "<PASSWORD>");
//
app.set('sendgrid_user', process.env.SENDGRID_USER || config.sendgrid_user);
app.set('sendgrid_key',process.env.SENDGRID_KEY || config.sendgrid_key);
app.set('root_path', config.ROOT_PATH);
// TODO delete?
app.set('url2png_api_key', process.env.url2png_api_key || 'P503113E58ED4A');
app.set('url2png_api_secret', process.env.url2png_api_key || 'SF1BFA95A57BE4');
//
app.set('is_developement', app.settings.env == 'development');
app.set('send_mails', true);
app.set('view engine', 'jade');
app.set('view options', { layout: false });
formage_admin.forms.setAmazonCredentials(config.s3_creds);
if(app.settings.env == 'staging' || app.settings.env == 'production'){
formage_admin.forms.setUploadDirectory(config.upload_dir);
}
var models = require('./models');
models.setDefaultPublish(app.settings.show_only_published);
// ######### settings #########
// ######### error handling #########
// ######### general middleware #########
app.use(function(req,res,next){
if(req.header('content-type') && req.header('content-type').indexOf('multipart') > -1){
console.log('Pausing req stream');
req.pause();
}
next();
});
app.use(express.compress());
app.use(express.static(app.get('public_folder')));
app.use(express.static(require('path').join(__dirname,'..','public')));
formage_admin.serve_static(app, express);
app.use(express.errorHandler());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.cookieSession({secret: '<KEY>', cookie: { path: '/', httpOnly: false/*, maxAge: 60 * 24 * 60 * 60 * 1000*/}}));
// ######### general middleware #########
// ########### Add request memory logger after 'static' folders ###########
express.logger.token('mem', function () { var p = process, r_mem = (p.memoryUsage().rss / 1048576).toFixed(0); if (r_mem > 400) p.nextTick(p.exit); return util.format('%dMb', r_mem); });
express.logger.format('default2', ':mem :response-time :res[content-length] :status ":method :url HTTP/:http-version" :res[body]');
app.use(express.logger('default2'));
// ########### setup memory logging ###########
// ######### specific middleware #########
app.use(fb_bot_middleware);
app.use(account.referred_by_middleware);
app.use(auth_middleware);
app.use(account.auth_middleware);
app.use(account.populate_user);
// ######### specific middleware #########
// ######### locals #########
app.use(function (req, res, next) {
if(req.query.overrideMethod)
req.method = req.query.overrideMethod;
//noinspection JSUnresolvedVariable
res.handle500 = function(err){
console.error(err);
res.render('500.ejs', {error: err});
};
res.locals({
tag_name: req.query.tag_name,
logged: req.isAuthenticated && req.isAuthenticated(),
user_logged: req.isAuthenticated && req.isAuthenticated(),
user: req.user,
avatar: (req.session && req.session.avatar_url) || "/images/default_user_img.gif",
url: req.url,
meta: {},
is_dev: app.settings.env == 'development' || app.settings.env == 'staging'
});
next();
});
app.locals({
footer_links: function (place) {
var links = mongoose.model('FooterLink').getFooterLinks();
var non_cms_pages = {'about': 1, 'team': 1, 'founders': 1, 'qa': 1};
var ret = links.filter(function (item) {return item[place];}).map(function (menu) {
var page_prefix = menu.tab in non_cms_pages ? '/' : '/page/';
var link = menu.link ? menu.link : (page_prefix + menu.tab);
return {link: link, name: menu.name};
});
return ret;
},
general_stuff: function(){
var general_shit = mongoose.model('General').getGeneral();
return general_shit.text;
},
cleanHtml: function (html) { return (html || '').replace(/<[^>]*?>/g, '').replace(/\[[^\]]*?]/g, '');},
fb_description: config.fb_general_params.fb_description,
fb_title: config.fb_general_params.fb_title,
fb_image: config.fb_general_params.fb_image,
get: function (attr) {
return app.get(attr);
}
});
app.locals({
writeHead: function(name) {
var isDev = true/*app.settings.env == 'development' || app.settings.env == 'staging'*/;
function headFromSrc(src, type) {
switch (type) {
case 'js':
return '<script src="' + src + '" type="text/javascript"></script>';
case 'css':
return '<link href="' + src + '" rel="stylesheet" type="text/css"/>';
default:
throw new Error('unknown type ' + type);
}
}
var conf = config.headConfigs[name];
var type = conf.type;
if (isDev)
return _.map(conf.src,
function (src) {
return headFromSrc(src, type);
}).join('\n');
else {
var final = conf.final || ( conf.min === false || type == 'css' ? '/dist/' + type + '/' + conf.name + '.' + type : '/dist/' + type + '/' + conf.name + '.min.' + type);
return headFromSrc(final, type);
}
}
});
// ######### locals #########
// ######### environment specific settings #########
app.configure('development', function(){
app.set('send_mails', true);
IS_ADMIN = true;
//app.set('listenHttps',true);
});
app.configure('staging',function(){
IS_ADMIN = true;
// ######### error handling #########
app.set('listenHttps',false);
process.on('uncaughtException', function(err) {
console.error('************************* unhandled exception !!!!! ********************************');
console.error(err);
console.error(err.stack);
});
});
app.configure('production',function(){
app.use(function (req, res, next) {
if(req.headers['host'] == 'sheatufim-roundtable.org.il')
return res.redirect('http://www.sheatufim-roundtable.org.il' + req.url);
next();
});
app.set('listenHttps',true);
// ######### error handling #########
process.on('uncaughtException', function(err) {
console.error('************************* unhandled exception !!!!! ********************************');
console.error(err);
console.error(err.stack);
});
});
if (IS_ADMIN) {
require('./admin')(app);
}
if (IS_PROCESS_WEB) {
require('./api')(app);
require('./og/config').load(app);
require('./lib/templates').load(app);
require('./routes')(app);
require('./api/common');
}
if (app.get('send_mails')) {
require('./lib/mail').load(app);
}
if (IS_PROCESS_CRON) {
var cron = require('./cron');
cron.run(app);
}
// ######### environment specific settings #########
// run web init
if (IS_PROCESS_WEB) {
async.waterfall([
function (cbk) {
mongoose.model('FooterLink').load(cbk);
},
function (cbk) {
mongoose.model('General').load(cbk);
}
], function (err, general) {
// app.set('general', general);
// Redirect http to https
var server;
if(app.get('listenHttps')){
// create HTTPS server, listen on 443
var fs = require('fs');
var privateKey = fs.readFileSync(__dirname + '/cert/key.pem').toString();
var certificate = fs.readFileSync(__dirname + '/cert/cert.cer').toString();
server = require('https').createServer({key: privateKey, cert: certificate},app).listen(443);
// create HTTP server that redirects to HTTPS
require('http').createServer(function(req,res){
var domain = req.headers['host'].toLowerCase();
if(domain == 'sheatufim-roundtable.org.il'){
res.writeHead(301, {
'Location': 'https://sheatufim-roundtable.org.il' + req.url
});
return res.end();
}
app(req,res);
}).listen(app.get('port'));
}
else {
console.log('listening on port ',app.get('port'));
server = app.listen(app.get('port'), function (err) {
if (err) {
console.error(err.stack || err);
process.exit(1);
}
console.log("Express server listening on port %d in %s mode", (server.address() || {}).port, app.get('env'));
});
}
server.on('error', function (err) {
console.error('********* Server Is NOT Working !!!! ***************\n %s', err);
});
});
}
// Redirect http to https
// require('http').createServer(function(req,res){
// var url = req.url;
// res.redirect('https://' + req.headers['host'] + req.url);
//}).listen(app.get('port'));
|
607755b29772edcbd22068cb45725b142328b865
|
[
"JavaScript"
] | 35
|
JavaScript
|
panstav/sheatufim
|
2164cb5b97d3ce47006df6e1b183ac7cd422f079
|
5de6ef94ded54c217f7fc7f020648fd66d96d558
|
refs/heads/main
|
<repo_name>Lomect/tide<file_sep>/src/response_builder.rs
use crate::http::headers::{HeaderName, ToHeaderValues};
use crate::http::{Body, Mime, StatusCode};
use crate::Response;
use std::convert::TryInto;
#[derive(Debug)]
/// Response Builder
///
/// Provides an ergonomic way to chain the creation of a response. This is generally accessed through [`Response::builder`](crate::Response::builder)
///
/// # Example
/// ```rust
/// # use tide::{StatusCode, Response, http::mime};
/// # async_std::task::block_on(async move {
/// let mut response = Response::builder(203)
/// .body("body")
/// .content_type(mime::HTML)
/// .header("custom-header", "value")
/// .build();
///
/// assert_eq!(response.take_body().into_string().await.unwrap(), "body");
/// assert_eq!(response.status(), StatusCode::NonAuthoritativeInformation);
/// assert_eq!(response["custom-header"], "value");
/// assert_eq!(response.content_type(), Some(mime::HTML));
/// # });
pub struct ResponseBuilder(Response);
impl ResponseBuilder {
pub(crate) fn new<S>(status: S) -> Self
where
S: TryInto<StatusCode>,
S::Error: std::fmt::Debug,
{
Self(Response::new(status))
}
/// Returns the inner Response
pub fn build(self) -> Response {
self.0
}
/// Sets a header on the response.
/// ```
/// # use tide::Response;
/// let response = Response::builder(200).header("header-name", "header-value").build();
/// assert_eq!(response["header-name"], "header-value");
/// ```
pub fn header(mut self, key: impl Into<HeaderName>, value: impl ToHeaderValues) -> Self {
self.0.insert_header(key, value);
self
}
/// Sets the Content-Type header on the response.
/// ```
/// # use tide::{http::mime, Response};
/// let response = Response::builder(200).content_type(mime::HTML).build();
/// assert_eq!(response["content-type"], "text/html;charset=utf-8");
/// ```
pub fn content_type(mut self, content_type: impl Into<Mime>) -> Self {
self.0.set_content_type(content_type);
self
}
/// Sets the body of the response.
/// ```
/// # async_std::task::block_on(async move {
/// # use tide::{Response, convert::json};
/// let mut response = Response::builder(200).body(json!({ "any": "Into<Body>"})).build();
/// assert_eq!(response.take_body().into_string().await.unwrap(), "{\"any\":\"Into<Body>\"}");
/// # });
/// ```
pub fn body(mut self, body: impl Into<Body>) -> Self {
self.0.set_body(body);
self
}
}
impl Into<Response> for ResponseBuilder {
fn into(self) -> Response {
self.build()
}
}
|
6ca935766ab55c7e937135feefd1451f22b1d6cc
|
[
"Rust"
] | 1
|
Rust
|
Lomect/tide
|
f9016ed166236f4a486bbabb2e5c79b058c62a32
|
6ccd9c0065692a3a8fb0613343532499fc7b0764
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Praktikum;
/**
*
* @author WINDOWS 10
*/
public class Bus {
public double penumpang;
public double maxPenumpang;
public double counter;
public double penumpangBaru;
public Bus(double maxPenumpang){
this.maxPenumpang=maxPenumpang;
penumpang=0;
}
public void addpenumpang (double penumpang)
{
double temp;
temp = this.penumpang+penumpang;
if(temp>maxPenumpang){
System.out.println("penumpang melebihi kuota");
}
else{
this.penumpang=temp;
}
}
public void getpenumpang(int password)
{
if (password==24) {
System.out.println("Password Benar");
}
else{
System.out.println("Password Salah");
}
}
public void getAverage(double counter){
double ratarata;
ratarata=maxPenumpang/counter;
System.out.println("Rata-rata penumpang adalah = "+ratarata);
}
public void cetak(){
System.out.println("Maksimal berat penumpang = " +maxPenumpang);
System.out.println("Jumlah berat Penumpang = " +penumpang);
}
//
}<file_sep># Enkapsulasi
Latihan 1

Latihan 2

Latihan 3

Latihan 4

Bola

Bus

Biodata

|
4e995e8785d2f985158286914d91d47560a9bcd4
|
[
"Markdown",
"Java"
] | 2
|
Java
|
RickyRahmadani10/Enkapsulasi
|
b464bbbd3d349a29f000650ebd67767790739df1
|
f278d760b99cbfae646ee4079b04d939edffaa46
|
refs/heads/master
|
<file_sep>wget -q -O — https://pkg.jenkins.io/debian/jenkins-ci.org.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt update
sudo apt install jenkins
sudo systemctl start jenkins
sudo systemctl status jenkins
sudo ufw allow 8080
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status
sudo cat /var/lib/jenkins/secrets/initialAdminPassword
|
6b849a597f5ad918d1b802d6922cd075d3080c9c
|
[
"Shell"
] | 1
|
Shell
|
utkusari/Jenkins-Installer-ShellFile
|
8c66f2cb500a697627081931719467d5bbfde874
|
717355e7cab2088cf75e9b97c377c5d0d23c5609
|
refs/heads/master
|
<repo_name>forty9unbeaten/recipeBox<file_sep>/recipes/views.py
from django.shortcuts import render
from recipes.models import Recipe, Chef
def index(request):
recipe_list = Recipe.objects.all()
return render(request,
'index.html',
{'recipe_list': recipe_list})
def chefs(request, chef_id=None):
selected_chef = Chef.objects.get(id=chef_id)
chef_recipes = Recipe.objects.filter(chef=selected_chef)
return render(request,
'chef.html',
{
'chef': selected_chef,
'recipes': chef_recipes
})
def recipes(request, recipe_id=None):
selected_recipe = Recipe.objects.get(id=recipe_id)
return render(request,
'recipe.html',
{'recipe': selected_recipe})
<file_sep>/recipes/urls.py
from django.urls import path
from recipes import views
urlpatterns = [
path('', views.index, name='index'),
path('chefs/<chef_id>', views.chefs, name='chefs'),
path('recipes/<recipe_id>', views.recipes, name='recipes')
]
<file_sep>/recipes/admin.py
from django.contrib import admin
from recipes.models import Chef, Recipe
# Register your models here.
admin.site.register(Chef)
admin.site.register(Recipe)
|
76c61500d12a65d4d5f40c94f4c7a7611123e86e
|
[
"Python"
] | 3
|
Python
|
forty9unbeaten/recipeBox
|
581cfa3bbc6aaf7fdfc99e15e5b88b4f2219f62b
|
bdb38cec8594c1c6a6a8de0253e16b86f25d9b98
|
refs/heads/master
|
<file_sep>package main
import (
"fmt"
"sync"
"time"
"github.com/sbiscigl/phonenumberperm/intstack"
"github.com/sbiscigl/phonenumberperm/permutations"
)
var wg sync.WaitGroup
func main() {
num := []int{2, 7, 1, 4, 5, 5, 2}
stack := intstack.New(num)
start := time.Now()
permutations.CalcWords(stack, "")
diff := time.Since(start).Nanoseconds()
fmt.Printf("time elapsed : %d\n", diff)
newStart := time.Now()
wg.Add(1)
go permutations.ThreadSafeCalcWords(stack, "", &wg)
wg.Wait()
newDiff := time.Since(newStart).Nanoseconds()
fmt.Printf("time elapsed : %d\n", newDiff)
}
<file_sep>package permutations
import (
"sync"
"github.com/sbiscigl/phonenumberperm/intstack"
)
var letterMap = map[int][]string{
2: []string{"a", "b", "c"},
3: []string{"d", "e", "f"},
4: []string{"g", "h", "i"},
5: []string{"j", "k", "l"},
6: []string{"m", "n", "o"},
7: []string{"p", "q", "r", "s"},
8: []string{"t", "u", "v"},
9: []string{"w", "x", "y", "z"},
}
/*CalcWords uses recursion to find posisble words*/
func CalcWords(s intstack.IntStack, word string) {
if s.IsEmpty() {
/* Commented out timing is pure calculation*/
//fmt.Println(word)
} else {
/*Check to see if the values are 1 or zero as they*/
/*have no letters associated with them*/
if s.Peek() == 1 || s.Peek() == 0 {
s.Pop()
CalcWords(s, word)
} else {
for _, letter := range letterMap[s.Pop()] {
CalcWords(s, word+letter)
}
}
}
}
/*ThreadSafeCalcWords uses recursion to find posisble words*/
/*Uses channels for multi threading*/
func ThreadSafeCalcWords(s intstack.IntStack, word string, wg *sync.WaitGroup) {
defer wg.Done()
if s.IsEmpty() {
/* Commented out timing is pure calculation*/
//fmt.Println(word)
} else {
/*Check to see if the values are 1 or zero as they*/
/*have no letters associated with them*/
if s.Peek() == 1 || s.Peek() == 0 {
s.Pop()
wg.Add(1)
go ThreadSafeCalcWords(s, word, wg)
} else {
for _, letter := range letterMap[s.Pop()] {
wg.Add(1)
go ThreadSafeCalcWords(s, word+letter, wg)
}
}
}
}
<file_sep>package intstack
import "fmt"
const (
maxSize = 100
)
/*IntStack implimentaiton of a stack for integers*/
type IntStack struct {
valueList []int
maxSize int
}
/*New returns bew instace of IntStack*/
func New(nums []int) IntStack {
return IntStack{
valueList: nums,
maxSize: maxSize,
}
}
/*Pop pops the top value off the stack*/
func (s *IntStack) Pop() int {
var val int
if !s.IsEmpty() {
val = s.valueList[0]
s.valueList = s.valueList[1:]
} else {
fmt.Println("stack is empty")
}
return val
}
/*Peek returns top value*/
func (s IntStack) Peek() int {
return s.valueList[0]
}
/*IsEmpty checks if the stack is empty*/
func (s IntStack) IsEmpty() bool {
if len(s.valueList) > 0 {
return false
}
return true
}
/*Print prints out the contents of the stack*/
func (s IntStack) Print() {
for _, element := range s.valueList {
fmt.Print(element)
}
fmt.Print("\n")
}
|
d34c02677ad012603e618036558afee11756721e
|
[
"Go"
] | 3
|
Go
|
sbiscigl/phonenumberperm
|
c5df2750b9af5bf30be0b3561f1b28517515c3ce
|
06d0fd70e5c557026811a6bd27126ee72e5f401e
|
refs/heads/master
|
<file_sep>'use strict';
var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwtconfig');
var jwtUtils = function() {
};
jwtUtils.prototype = {
encoder: function (payload) {
if (payload === null || payload == undefined || payload.length <= 0) {
throw {
name: 'JWT error',
level: 'Error',
message: 'Invalid payload to generate a JSON Web Token',
toString: function () {
return this.name + ' - ' + this.message
}
}
}
return jwt.sign(payload, jwtConfig.jwtsceret, jwtConfig.jwtoptions);
},
decoder: function(token) {
if (token === null || token == undefined || token.length <= 0) {
throw {
name: 'JWT error',
level: 'Warning',
message: 'JWT token is either null or an empty string.',
toString: function() {
return this.name + ' - ' + this.message
}
}
}
try {
return JWT.verify(token, MyJWTConfig.jwtsecret);
} catch(err) {
throw err;
}
}
};
module.exports = new jwtUtils();<file_sep>'use strict';
var express = require('express');
var http = require('http');
var configApp = require('./config/config');
var app = express();
app = configApp(app);
function httpHandler(err) {
if (err) {
console.log(new Date() + " - " + err);
} else {
var host = httpServer.address().address;
var port = httpServer.address().port;
console.log(new Date() + " - " + "Http Server started at https://%s:%s", host, port);
}
}
/*
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
*/
var httpServer = http.createServer(app).listen(9000, httpHandler);<file_sep># Auth Prototype using Node.JS
<file_sep>'use strict';
module.exports = {
jwtsceret: "may read from env. var",
jwtoptions: {
"algorithm": "HS256", // this is default
"expiresIn": "30d", // expires in 30 days
"issuer": "jc_ivyway"
}
};<file_sep>'use strict';
var memberDao = require('./memberDao');
function Member() {
this.getCompanyMembers = function(companyId, callback) {
memberDao.getCompanyMembers(companyId, function(err, result) {
if (err) {
callback(err);
} else {
callback(null, result);
}
});
};
this.authenticateMember = function (companyId, authInfo, callback) {
memberDao.getAuthenticatedMember(companyId, authInfo.email, authInfo.password, function (err, result) {
if (err) {
callback(err);
} else {
if (result.length <= 0) {
// TODO: construct an err object
var err = {
"status code": 1,
"message": "unable to authenticate the user by the email, " + authInfo.email
};
callback(err, result);
} else {
callback(null, result);
}
}
});
};
}
module.exports = new Member();<file_sep>'use strict';
var httpStatusCode = require('http-status-codes');
var member = require('../model/member');
var jwtUtils = require('../utils/jwtutils');
const ver = '/v1';
function authHandler() {
var config = function(app) {
app.post(ver + "/companies/:id/login", function(req, res) {
member.authenticateMember(req.params.id, req.body, function(err, result) {
if (err) {
res.send(err);
} else {
var payload = {
"memberId": req.body.email,
"companyId": req.params.id
};
var token = jwtUtils.encoder(payload);
res.status(httpStatusCode.CREATED);
res.json({"token": token});
}
});
});
};
return {
configure : config
};
}
module.exports = new authHandler();<file_sep>'use strict';
var dbConnection = require('../utils/mysqlDbConn');
function MemberDao() {
this.getCompanyMembers = function(companyId, callback) {
var SQL = "SELECT members.id, " +
"members.first_name, " +
"members.last_name, " +
"members.email " +
"FROM members " +
"WHERE members.company_id = ?";
dbConnection.acquire(function(err, dbConn) {
dbConn.query(SQL, [companyId], function(err, result) {
dbConn.release();
if (err) {
callback(err);
} else {
callback(null, result);
}
});
});
};
this.getAuthenticatedMember = function(companyId, email, password, callback) {
var SQL = "SELECT * FROM members WHERE email = ? AND password = ? AND company_id = ?";
dbConnection.acquire(function(err, dbConn) {
dbConn.query(SQL, [email, password, companyId], function (err, result) {
dbConn.release();
if (err) {
callback(err);
} else {
callback(null, result);
}
});
});
};
}
module.exports = new MemberDao();<file_sep>'use strict';
var httpStatusCode = require('http-status-codes');
var member = require('../model/member');
const ver = '/v1';
function memberHandler() {
var config = function(app) {
app.get(ver + "/companies/:id/members", function (req, res) {
member.getCompanyMembers(req.params.id, function (err, result) {
if (err) {
res.status(httpStatusCode.BAD_REQUEST);
res.send(result);
} else {
res.status(httpStatusCode.OK);
res.send(result);
}
})
});
};
return {
configure : config
};
}
module.exports = new memberHandler();
<file_sep>'use strict';
var mysql = require('mysql');
var devDb = {
connectionLimit: 10,
host: '192.168.99.100',
port: 32770,
user: 'devauth',
password: '<PASSWORD>',
database: 'cp4db_auth'
};
function Connection() {
var pool = null;
var init = (init)();
function init() {
pool = mysql.createPool(devDb);
}
return {
acquire : function(callback) {
pool.getConnection(function(err, connection) {
callback(err, connection);
});
}
};
}
module.exports = new Connection();
|
db927225673ea14231b68c087a1a648e659ec97d
|
[
"JavaScript",
"Markdown"
] | 9
|
JavaScript
|
justinchenusa/nodejsauthpoc
|
08de3b3b8539e1402cdf5e355013a6aa11987ea2
|
37af7eac0e08b2fb2711fc66d00213d0458ed861
|
refs/heads/master
|
<file_sep><?php
namespace Model;
use \Fuel\Core\Log;
use \Fuel\Core\Request;
class Articles extends Base {
/**
* 旅行誌ファイルアップロード(複数同時アップロードは可能)
*
*/
public static function receive_upload() {
try {
\DB::start_transaction();
$date_jst = self::get_date_jst();
// このアップロードのカスタム設定
$upload_config = array('path' => DOCROOT. '../fuel/app/tmp/upload/'. $date_jst,
'randomize' => true,
'max_size' => 5242880
);
self::upload_file($upload_config);
if(count(self::$uploaded_files_error) > 0) {
throw new \MarcoPandaException(5);
}
Log::warning('file uploaded: '. var_export(self::$uploaded_files, true));
$inserted_ids = array();
foreach(self::$uploaded_files as $key => $file) {
$insert_result = \DB::insert('multimedia')->set(array(
'media_type' => 1, // 画像
'mime_type' => $file['mimetype'],
'filename' => $file['name'],
'save_path' => $date_jst. DS. $file['saved_as'],
'created_at' => self::get_datetime_jst(),
))->execute();
$inserted_ids[] = $insert_result[0];
}
$inserted_save_path = \DB::select('multimedia_id', 'save_path')
->from('multimedia')
->where('multimedia_id', 'in', $inserted_ids)
->execute()
->as_array();
\DB::commit_transaction();
$received_files = array();
foreach($inserted_save_path as $key => $value) {
$received_files[] = array(
'multimedia_id' => $value['multimedia_id'],
'download_url' => '/multimedia/download?path='. $value['save_path'],
);
}
$return_data = array('files' => $received_files);
return $return_data;
} catch(\Exception $e) {
\DB::rollback_transaction();
throw $e;
}
}
/**
* 旅行誌投稿
*
*/
public static function regist($data)
{
try {
// 入力チェック
if(empty($data['spot_id'])) {
if(empty($data['longitude'])) {
throw new \MarcoPandaException(3);
}
if(empty($data['latitude'])) {
throw new \MarcoPandaException(4);
}
if(empty($data['category_id'])) {
throw new \MarcoPandaException(1);
}
if(empty($data['cost_id'])) {
throw new \MarcoPandaException(2);
}
}
if((!isset($data['multimedia_id']) || count($data['multimedia_id']) == 0) && empty($data['article_text'])) {
throw new \MarcoPandaException(6);
}
if(!empty($data['sex'])) {
if(!in_array($data['sex'], array(1, 2))) {
throw new \MarcoPandaException(12);
}
}
if(!empty($data['generation'])) {
if(!in_array($data['generation'], array(1, 9))) {
throw new \MarcoPandaException(13);
}
}
if(empty($data['spot_id'])) {
// Google APIを利用して地名取得
$GOOGLE_API_KEY = \Config::get('GOOGLE_API_KEY');
$google_api_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={$data['latitude']},{$data['longitude']}&key={$GOOGLE_API_KEY}";
// $curl = Request::forge($google_api_url, 'curl');
// $curl->set_option(CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//
// // assume some parameters and options were set, and execute
// $curl->execute();
//
// // fetch the resulting Response object
// $google_result = $curl->response();
$google_result = shell_exec("curl $google_api_url");
//\Log::warning("result: ". $google_result);
//$google_result = file_get_contents($google_api_url);
if($google_result != NULL && $google_result != '') {
$google_result_json = json_decode($google_result, true);
//\Log::warning(print_r($google_result_json, true));
if($google_result_json['status'] !== 'OK') {
\Log::error($google_api_url);
throw new \MarcoPandaException(9);
}
$address_components = $google_result_json['results'];
$location_name = '';
foreach($address_components as $key => $value) {
//\Log::warning(print_r($value, true));
$location_name = $value['formatted_address'];
break;
// 取得した複数件場所情報から、経度緯度一致して、住所名は一番長い物を取得する
// if($value['geometry']['location']['lat'] == $data['latitude'] &&
// $value['geometry']['location']['lng'] == $data['longitude']) {
// if(strlen($value['formatted_address']) > $location_name) {
// $location_name = $value['formatted_address'];
// }
// }
}
if($location_name == '') {
throw new \MarcoPandaException(10);
}
}
} else {
// TODO:スポット情報更新
}
// DB処理
\DB::start_transaction();
// スポット登録
if(empty($data['spot_id'])) {
$db_result = \DB::insert('spot')
->set(array(
'location_name' => $location_name,
'longitude' => $data['longitude'],
'latitude' => $data['latitude'],
'cost_id' => $data['cost_id'],
))->execute();
if($db_result[1] != 0) {
$spot_id = $db_result[0];
} else {
throw new \MarcoPandaException(11);
}
}
// ユーザ登録・情報更新
// TODO: move the code into user model
if(!empty($data['user_uuid'])) {
$user_update_result = \DB::update('user')
->set(array(
'come_from' => 0,
'nickname' => isset($data['nickname'])?$data['nickname']:null,
'sex' => isset($data['sex'])?$data['sex']:null,
'generation' => isset($data['generation'])?$data['generation']:null,
'country' => isset($data['text_language_code '])?$data['text_language_code ']:null,
'created_at' => self::get_datetime_jst(),
))->where('user_uuid', '=', $data['user_uuid'])
->execute();
if($user_update_result == 0) {
// 登録するべき
$user_insert_result = \DB::insert('user')
->set(array(
'user_uuid' => $data['user_uuid'],
'come_from' => 0,
'nickname' => isset($data['nickname'])?$data['nickname']:null,
'sex' => isset($data['sex'])?$data['sex']:null,
'generation' => isset($data['generation'])?$data['generation']:null,
'country' => isset($data['text_language_code '])?$data['text_language_code ']:null,
'created_at' => self::get_datetime_jst(),
))
->execute();
if($user_insert_result[1] == 0) {
throw new \MarcoPandaException(14); // 原因不明のユーザ登録失敗
}
}
}
// 旅行誌登録
$artice_insert_result = \DB::insert('article')
->set(array(
'user_uuid' => !empty($data['user_uuid'])?$data['user_uuid']:NULL,
'spot_id' => $spot_id,
'nick_name' => !empty($data['nick_name'])?$data['nick_name']:NULL,
'article_text' => !empty($data['article_text'])?$data['article_text']:NULL,
'text_language_code' => !empty($data['text_language_code'])?$data['text_language_code']:NULL,
'created_at' => self::get_datetime_jst(),
))->execute();
if($artice_insert_result[1] == 0) {
throw new \MarcoPandaException(15); // 原因不明のユーザ登録失敗
}
// 旅行誌とファイルに紐づく
if(isset($data['multimedia_id']) && count($data['multimedia_id']) > 0) {
$sort = 1;
foreach($data['multimedia_id'] as $key => $value) {
\DB::insert('article_multimedia')->set(array(
'multimedia_id' => $value,
'article_id' => $artice_insert_result[0],
'sort' => $sort++,
'created_at' => self::get_datetime_jst(),
))->execute();
}
}
// スポットの統計情報更新
$date1MonthAgo = date('Y-m-d H:i:s', strtotime(self::get_datetime_jst() . ' -1 month'));
$search_articles = \DB::select(\DB::expr('count(article_id) as cnt'))
->from('article')
->where('spot_id', '=', $spot_id)
->where('created_at', '>', $date1MonthAgo)
->execute()
->current();
$update_spot = \DB::update('spot')
->set(array(
'article_count_in_last_30_days' => $search_articles['cnt'],
'article_count' => \DB::expr('article_count + 1')
))->where('spot_id', '=', $spot_id)
->execute();
\DB::commit_transaction();
} catch(\Exception $e) {
\DB::rollback_transaction();
throw $e;
}
return array('article_id' => $artice_insert_result[0]);
}
public static function search_3_in_1($data) {
try {
if(!empty($data['longitude'])) {
return self::search_by_geocode($data);
}
} catch(\Exception $e) {
throw $e;
}
}
// 現在地から検索する
public static function search_by_geocode($data) {
if(empty($data['longitude']) || empty($data['latitude']) || empty($data['zoom'])) {
throw new \MarcoPandaException(18);
}
$query_cnt = \DB::select(\DB::expr('count(article_id) as cnt'))->from('article');
$query = \DB::select(\DB::expr('article.*, spot.category_id, spot.cost_id, spot.longitude, spot.latitude, spot.location_name'))
->from('article')
->join('spot', 'LEFT')
->on('article.spot_id', '=', 'spot.spot_id');
// limit and offset
if(isset($data['page'])) {
$query = $query->limit($data['page'])
->offset(($data['page'] - 1) * 20);
}
if(!isset($data['sort_by']) || $data['sort_by'] == 2) {
// デフォルトはいいね数でソート
$query = $query->order_by('article.like_number', 'desc');
} else if($data['sort_by'] == 3) {
// 星数
$query = $query->order_by('article.average_star', 'desc');
} else {
// 新しい順
$query = $query->order_by('article.created_at', 'desc');
}
$result_cnt = $query_cnt->execute()->current();
$result = $query->execute()->as_array();
\Log::warning(\DB::last_query());
$search_results = array();
foreach($result as $key => $value) {
$one_result = array();
$one_result['longitude'] = $value['longitude'];
$one_result['latitude'] = $value['latitude'];
$one_result['article_id'] = $value['article_id'];
$one_result['spot_id'] = $value['spot_id'];
$one_result['location_name'] = $value['location_name'];
$one_result['category_id'] = $value['category_id'];
$one_result['cost_id'] = $value['cost_id'];
$one_result['article_text'] = $value['article_text'];
$one_result['text_language_code'] = $value['text_language_code'];
$one_result['post_timestamp'] = $value['created_at'];
$one_result['star'] = (int)mt_rand(0, 5);// $value['average_star'];
$one_result['like_number'] = $value['like_number'];
$search_results[] = $one_result;
}
return array('search_result_count' => $result_cnt['cnt'],
'search_results' => $search_results,
);
}
/**
*
*
*/
public static function get_list($limit = 5, $offset = 0)
{
try {
//$result = array('key' => $_SERVER['FUEL_ENV']);
//return $result;
//
$result = \DB::select('*')->
from('article')->
order_by('created_at', 'desc')->
limit($limit)->
offset($offset)->
execute()->as_array();
} catch(\Exception $e) {
throw $e;
}
return $result;
}
}
<file_sep><?php
namespace Model;
use \Fuel\Core\Log;
class Maps extends Base {
public static function search_3_in_1($data)
{
try {
if(!empty($data['longitude'])) {
return self::search_by_geocode($data);
}
} catch(\Exception $e) {
throw $e;
}
}
// 現在地から検索する
public static function search_by_geocode($data) {
if(empty($data['longitude']) || empty($data['latitude']) || empty($data['zoom'])) {
throw new \MarcoPandaException(18);
}
$query_cnt = \DB::select(\DB::expr('count(spot_id) as cnt'))->from('spot');
$query = \DB::select('*')
->from('spot');
if(isset($data['page'])) {
$query = $query->limit($data['page'])
->offset(($data['page'] - 1) * 20);
}
if(!isset($data['sort_by'])) {
$query = $query->order_by('article_count', 'desc');
}
$result_cnt = $query_cnt->execute()->current();
$result = $query->execute()->as_array();
$search_results = array();
foreach($result as $key => $value) {
$one_result = array();
$one_result['longitude'] = $value['longitude'];
$one_result['latitude'] = $value['latitude'];
$one_result['spot_id'] = $value['spot_id'];
$one_result['location_name'] = $value['location_name'];
$one_result['category_id'] = $value['category_id'];
$one_result['cost_id'] = $value['cost_id'];
$x = 0;
if(!isset($data['sort_by'])) {
if($value['article_count'] >= 5) {
$x = 0;
} else {
$x = 100 - (int)($value['article_count'] * 20);
}
}
$one_result['color'] = array('rgb' => '#ff0000',
'r' => (int)((14 * 16 + 14 - 10 * 16 - 10) * (float)$x / (float)100 + 10 * 16 + 10),
'g' => (13 * 16 + 13 - 5 * 16 - 5) * $x / 100 + 5 * 16 + 5,
'b' => (13 * 16 + 13 - 5 * 16 - 5) * $x / 100 + 5 * 16 + 5,
'a' => 1,
);
// \Log::warning((int)((14 * 16 + 14 - 10 * 16 - 10) * (float)$x / (float)100 + 10 * 16 + 10));
// \Log::warning('article_count: '. $value['article_count']. ', x: '. $x. ', color: '. print_r($one_result['color'], true));
$one_result['star'] = (int)mt_rand(0, 5);// $value['average_star'];
$one_result['article_number'] = $value['article_count'];
$one_result['like_number'] = $value['like_sum'];
$one_result['score'] = 10 - $x;
$search_results[] = $one_result;
}
return array('search_results' => $search_results);
}
}
<file_sep># marcopanda
http://www.hackathon.io/marcopanda
# サーバー構築方法
[docs/setup/install.md](https://github.com/birdhxc/marcopanda/blob/master/docs/setup/install.md)に格納しています。
# API
## API定義書
http://api.marcopanda.dreamsfor.com/apidefine/
## APIリスト及びテスト方法(curlコマンド)
## 実装済みAPI
- ユーザ登録(プレゼンのためUUIDのみ登録)
`curl -X POST -d '{"user_uuid":"DsMjyOQu7JxMgQtksYMRoTtCCKMwBGw9CxETCB3Q"}' http://api.marcopanda.dreamsfor.com/user/uuid_regist.json`
- 旅行誌画像登録
`curl -F file1=@post01.jpg http://api.marcopanda.dreamsfor.com/article/fileupload.json`
- 旅行誌登録
`curl -X POST -d '{"longitude":"139.729249","latitude":"35.660464","category_id":"3","cost_id":"8","multimedia_id":[1,2],"article_text":"A happy day!"}' http://api.marcopanda.dreamsfor.com/article/post.json`
- 画像ダウンロード
http://api.marcopanda.dreamsfor.com/multimedia/download?path=2016-07-03/11b94aa158d38b270da53743e30a9cf8.png
- スポット検索(現在地検索)
`curl -X POST -d '{"longitude":"139.729249","latitude":"35.660464","zoom":"15"}' http://api.marcopanda.dreamsfor.com/map/search.json`
- 旅行誌検索(現在地検索)
`curl -X POST -d '{"longitude":"139.729249","latitude":"35.660464","zoom":"15"}' http://api.marcopanda.dreamsfor.com/article/search.json`
### API未実装
- スポット検索(地名検索)
- スポット検索(特定ユーザの投稿)
- スポット検索(私がいいねを付けた旅行誌)
- 旅行誌検索(地名検索)
- 旅行誌検索(特定スポット限定の投稿)
- 旅行誌検索(特定ユーザの投稿)
- いいねを付ける
- 星を付ける
- 旅行誌にコメントする
# アプリ
## 対応iOS
iOS9以上
## 環境構築、ビルド手順
+ Xcode 8をインストールしてください。
+ cd /marcopanda/ios/marcopandaios
+ pod install (pod 1.0.0が必要です)
+ xocde8でビルドする
## 実機で実行する方法
### デベロッパーアカウントを持っていない方
iPhoneをUSBでPCと繋いて、XCode経由でアプリにインストールする
### デベロッパーアカウントを持っている方
端末のUDIDを収集して、iOS developer centerに端末を登録して、
デベロッパー用プロビジョニングファイルを更新、或いは作成して、
それを使って、端末にインストールできるバイナリデータをビルドする。
ビルドしたら、iTunesでAdhoc版アプリをインストールするや、
OTA経由端末にインストールするやなど方法でインストールする。
# オープンソース
## サーバー
- fuelphp
http://fuelphp.com/
- phpMyAdmin
MySQL GUIツール
https://www.phpmyadmin.net/
- apidoc
RESTful API定義書作成ツール
http://apidocjs.com/
## アプリ
- Google Map Kit
https://developers.google.com/maps/ios/
- AFNetworking
https://github.com/AFNetworking/AFNetworking
- SDWebImage(現時点使っていない)
https://github.com/rs/SDWebImage
## 素材作成
- GIMP
https://www.gimp.org/
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.4.15.7
-- http://www.phpmyadmin.net
--
-- Host: rm-j6c2il7681qgjcw7o.mysql.rds.aliyuncs.com
-- Generation Time: 2016 年 7 月 03 日 12:27
-- サーバのバージョン: 5.5.18.1-log
-- PHP Version: 5.6.23
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!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 */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `marcopanda`
--
-- --------------------------------------------------------
--
-- テーブルの構造 `article`
--
DROP TABLE IF EXISTS `article`;
CREATE TABLE IF NOT EXISTS `article` (
`article_id` bigint(20) NOT NULL COMMENT '主キー',
`user_uuid` varchar(100) DEFAULT NULL COMMENT 'ユーザID。NULLの場合匿名',
`spot_id` bigint(20) NOT NULL COMMENT 'スポットID(FK)',
`nick_name` varchar(255) DEFAULT NULL COMMENT '匿名の場合付けられる',
`article_text` text COMMENT '投稿文書',
`text_language_code` varchar(100) DEFAULT NULL COMMENT '投稿文書言語(iso15924)',
`like_number` int(11) NOT NULL DEFAULT '0' COMMENT 'いいね数',
`average_star` float DEFAULT '0' COMMENT '平均星数(全体)',
`created_at` datetime NOT NULL COMMENT '作成日時',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='旅行誌';
-- --------------------------------------------------------
--
-- テーブルの構造 `article_like`
--
DROP TABLE IF EXISTS `article_like`;
CREATE TABLE IF NOT EXISTS `article_like` (
`article_id` bigint(20) NOT NULL COMMENT '旅行誌ID',
`user_uuid` varchar(100) NOT NULL COMMENT 'ユーザUUID',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '作成日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='旅行誌いいね履歴';
-- --------------------------------------------------------
--
-- テーブルの構造 `article_multimedia`
--
DROP TABLE IF EXISTS `article_multimedia`;
CREATE TABLE IF NOT EXISTS `article_multimedia` (
`multimedia_id` bigint(20) NOT NULL COMMENT '主キー',
`article_id` bigint(20) NOT NULL COMMENT '記事主キー(FK)',
`sort` tinyint(4) NOT NULL COMMENT 'ソート順。小さいのは頭',
`created_at` datetime NOT NULL COMMENT '作成日時',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='記事添付ファイル';
-- --------------------------------------------------------
--
-- テーブルの構造 `article_star`
--
DROP TABLE IF EXISTS `article_star`;
CREATE TABLE IF NOT EXISTS `article_star` (
`article_id` bigint(20) NOT NULL COMMENT '旅行誌ID',
`user_uuid` varchar(100) NOT NULL COMMENT 'ユーザUUID',
`star` tinyint(4) NOT NULL COMMENT '星数',
`created_at` datetime NOT NULL COMMENT '作成日時',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='旅行誌星付け履歴';
-- --------------------------------------------------------
--
-- テーブルの構造 `multimedia`
--
DROP TABLE IF EXISTS `multimedia`;
CREATE TABLE IF NOT EXISTS `multimedia` (
`multimedia_id` bigint(20) NOT NULL COMMENT '主キー',
`media_type` tinyint(4) NOT NULL COMMENT '1:画像 2:音声 3:動画',
`mime_type` varchar(30) DEFAULT NULL COMMENT 'MIME TYPE',
`filename` varchar(255) DEFAULT NULL COMMENT '元ファイル名',
`save_path` varchar(255) NOT NULL COMMENT '保存するパス',
`created_at` datetime NOT NULL COMMENT '作成日時',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='記事添付ファイル';
-- --------------------------------------------------------
--
-- テーブルの構造 `spot`
--
DROP TABLE IF EXISTS `spot`;
CREATE TABLE IF NOT EXISTS `spot` (
`spot_id` bigint(20) NOT NULL COMMENT '主キー',
`location_name` varchar(300) DEFAULT NULL COMMENT '地名',
`longitude` double(9,6) NOT NULL COMMENT '経度',
`latitude` double(8,6) NOT NULL COMMENT '緯度',
`location_name_jp` varchar(300) DEFAULT NULL COMMENT '日本語地名',
`category_id` smallint(6) NOT NULL DEFAULT '99' COMMENT 'カテゴリID。spot_idがNULLの場合必須。1:温泉 2:レストラン 3:ホテル 4:観光スポット 5:交通 6:ショッピング 7:イベント 8:公共施設 9:アミューズメント 10:病院 99:その他',
`cost_id` tinyint(4) NOT NULL DEFAULT '99' COMMENT 'コストID。spot_idがNULLの場合必須。1:¥0 2:¥1〜¥1,000 3:¥1,001〜¥2,000 4:¥2,001〜¥5,000 5:¥5,001〜¥10,000 6:¥10,001〜 99:不明',
`article_count` int(11) NOT NULL DEFAULT '0' COMMENT '該当スポットに投稿数',
`like_sum` bigint(20) NOT NULL DEFAULT '0' COMMENT '該当スポットに投稿のいいね数の合計',
`average_star` double(9,6) DEFAULT '0.000000' COMMENT '該当スポットに投稿の平均星数の平均',
`article_count_in_last_30_days` int(11) NOT NULL DEFAULT '0' COMMENT '直近30日に該当スポットに投稿の数',
`created_at` datetime NOT NULL COMMENT '作成日時',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='スポット';
-- --------------------------------------------------------
--
-- テーブルの構造 `user`
--
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
`user_uuid` varchar(100) NOT NULL COMMENT '主キー。ランダム文字列',
`come_from` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'どのSNSから来た。0:development 1:mail 2:facebook 3:google 4:wechat 5:twitter 6:linkedin',
`login_account` varchar(255) DEFAULT NULL COMMENT 'ログインアカウント。come_fromが1の場合メールアドレスになる。',
`nickname` varchar(255) DEFAULT NULL COMMENT 'ニックネーム',
`sex` tinyint(4) DEFAULT NULL COMMENT '性別。1:男性 2:女性',
`generation` tinyint(4) DEFAULT NULL COMMENT '年代。1:〜9 2:10〜19 3:20〜29 4:30〜39 5:40〜49 6:50〜59 7:60〜69 8:70〜79 9:80〜',
`country` varchar(100) DEFAULT NULL COMMENT '国名',
`image_file` varchar(255) DEFAULT NULL COMMENT 'ユーザアイコンURLパス',
`created_at` datetime NOT NULL COMMENT '作成日時',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日時'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ユーザ';
--
-- Indexes for dumped tables
--
--
-- Indexes for table `article`
--
ALTER TABLE `article`
ADD PRIMARY KEY (`article_id`);
--
-- Indexes for table `article_like`
--
ALTER TABLE `article_like`
ADD PRIMARY KEY (`article_id`,`user_uuid`);
--
-- Indexes for table `article_multimedia`
--
ALTER TABLE `article_multimedia`
ADD PRIMARY KEY (`multimedia_id`,`article_id`);
--
-- Indexes for table `multimedia`
--
ALTER TABLE `multimedia`
ADD PRIMARY KEY (`multimedia_id`),
ADD KEY `save_path` (`save_path`(191));
--
-- Indexes for table `spot`
--
ALTER TABLE `spot`
ADD PRIMARY KEY (`spot_id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`user_uuid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `article`
--
ALTER TABLE `article`
MODIFY `article_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主キー';
--
-- AUTO_INCREMENT for table `multimedia`
--
ALTER TABLE `multimedia`
MODIFY `multimedia_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主キー';
--
-- AUTO_INCREMENT for table `spot`
--
ALTER TABLE `spot`
MODIFY `spot_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主キー';
/*!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 */;
<file_sep><?php
return array(
'errors.0000' => array('code' => 'SystemError',
'message' => 'System error'),
'errors.0001' => array('code' => 'CategoryNotExis',
'message' => 'The category is not exist'),
'errors.0002' => array('code' => 'CostNotExist',
'message' => 'Cost is not exist'),
'errors.0003' => array('code' => 'LongitudeNotExist',
'message' => 'The longitude is neccesary'),
'errors.0004' => array('code' => 'LatitudeNotExist',
'message' => 'The Latitude is neccesary'),
'errors.0005' => array('code' => 'UploadFailed',
'message' => 'Some files upload failed'),
'errors.0006' => array('code' => 'NoContents',
'message' => 'No contents received'),
'errors.0007' => array('code' => 'UUIDNotExist',
'message' => 'UUID is neccesary'),
'errors.0008' => array('code' => 'UUIDExist',
'message' => 'UUID is already registed'),
'errors.0009' => array('code' => 'SearchServiceTemporarilyUnavailable',
'message' => 'Searching service is temporarily unavailable'),
'errors.0010' => array('code' => 'CanNotFoundAddress',
'message' => 'The address is not found by geocode searching service'),
'errors.0011' => array('code' => 'SpotRegistFailed',
'message' => 'The spot is failed to regist'),
'errors.0012' => array('code' => 'SexInavailable',
'message' => 'Sex is unavailable'),
'errors.0013' => array('code' => 'GenerationInavailable',
'message' => 'Generation is unavailable'),
'errors.0014' => array('code' => 'UserRegistFailed',
'message' => 'Failed to regist user'),
'errors.0015' => array('code' => 'ArticleRegistFailed',
'message' => 'Failed to regist article'),
'errors.0016' => array('code' => 'PathIsEmpty',
'message' => 'Path is necessary'),
'errors.0017' => array('code' => 'PathNotFoundInDB',
'message' => 'Path is not found'),
'errors.0018' => array('code' => 'ShortOfParameter',
'message' => 'Parameter is not enough'),
);
<file_sep>@api {Post} /user/uuid_regist ユーザUUID登録(プレゼン用)
@apiVersion 0.1.0
@apiName /user/uuid_regist
@apiGroup user
@apiSampleRequest off
@apiDescription ユーザUUID登録
@apiParam {String} user_uuid ユーザUUID
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {String} user_uuid ユーザUUID。もらったデータをそのまま返す
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"user_uuid": "5m0rjnZo7F2v3cx7GDj7WO5PmLcxSHSHlEtF0hNE"
}
@apiSuccessExample UserExist-Response:
HTTP/1.1 400 OK
{
"error": "UserExist",
"message": [
"ユーザが既に存在しました"
]
}
<file_sep><?php
namespace Model;
use \Fuel\Core\Log;
class Users extends Base {
public static function uuid_regist($data)
{
try {
if(empty($data['user_uuid'])) {
throw new \MarcoPandaException(7);
}
$insert_result = \DB::insert('user')->set(array(
'user_uuid' => $data['user_uuid'],
'come_from' => 0,
'created_at' => self::get_datetime_jst(),
))->execute();
if($insert_result[1] == 0) {
throw new \MarcoPandaException(8);
}
} catch(\Exception $e) {
throw new \MarcoPandaException(8);
}
return array('user_uuid' => $data['user_uuid']);
}
}
<file_sep>@api {Post} /article/search 旅行誌検索
@apiVersion 0.1.0
@apiName /article/search
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌検索。
@apiParam {String} [user_uuid] ユーザID(ログインしている場合必須)
@apiParam {Number} [longitude] 経度(現在地から検索する場合必須)
@apiParam {Number} [latitude] 緯度(現在地から検索する場合必須)
@apiParam {Number} [zoom] 拡大倍数(現在地から検索する場合必須)
@apiParam {Number} [spot_id] スポットID(スポットをタップして検索する場合必須)
@apiParam {String} [location_name] 地名(地名で検索する場合必須)
@apiParam {String} [text_language_code] 検索文字言語(iso15924、地名で検索する場合使う)
@apiParam {Object} [filtering] 絞り込む条件(ここ以降各種検索共通)
@apiParam {String} [filtering.freeword] フリーワード検索。投稿テキストから検索。
@apiParam {Number} [filtering.post_by_user_id] 投稿者ユーザID(特定の投稿者の投稿を探すとき使う。自分にも使える)
@apiParam {Number} [filtering.like_by_user_id] いいねを付けたユーザID(主に自分がいいねを付けた投稿を探すとき使う)
@apiParam {Number[]} [filtering.categorys] カテゴリ配列
@apiParam {Number} [filtering.categorys.category_id] カテゴリID
@apiParam {Number} [filtering.sex] 性別。1:男性 2:女性
@apiParam {String} [filtering.country] 国名
@apiParam {Number} [filtering.generation] 年代
@apiParam {Number} [filtering.cost_id_min] 最低コスト
@apiParam {Number} [filtering.cost_id_max] 最高コスト
@apiParam {Number} [filtering.star_min] 最低星数
@apiParam {Number} [filtering.star_max] 最高星数
@apiParam {Number} [sort_by] 並び替え。1:人数 2:いいね 3:星数 4:新しい順
@apiParam {Number} [page] 何ページ目指定。デフォルト1ページ目。
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Number} [zoom] 拡大倍数(現在地から検索する場合同じ値を返す。地名で検索する場合デフォルト値を返す。)
@apiSuccess {Object} google_map_results Google APIから返ってきた検索結果(status=OKの場合)
@apiSuccess {Number} search_result_count 検索結果件数
@apiSuccess {Object[]} [search_results] 検索結果
@apiSuccess {Number} [search_results.article_id] 投稿ID
@apiSuccess {Number} [search_results.spot_id] スポットID
@apiSuccess {String[]} [search_results.image_urls] 画像URL配列
@apiSuccess {String} [search_results.image_urls.url] 画像URL
@apiSuccess {String} [search_results.sound_url] 音声URL
@apiSuccess {Number} [search_results.longitude] 経度
@apiSuccess {Number} [search_results.latitude] 緯度
@apiSuccess {String} [search_results.location_name] 地名
@apiSuccess {String} [search_results.user_uuid] ユーザUUID。匿名の場合空欄
@apiSuccess {String} [search_results.nickname] ニックネーム
@apiSuccess {Number} [search_results.category_id] カテゴリID。1:温泉 2:レストラン 3:ホテル 4:観光スポット 5:交通 6:ショッピング 7:イベント 8:公共施設 9:アミューズメント 10:病院 99:その他
@apiSuccess {Number} [search_results.cost_id] コストID。1:¥0 2:¥1〜¥1,000 3:¥1,001〜¥2,000 4:¥2,001〜¥5,000 5:¥5,001〜¥10,000 6:¥10,001〜
@apiSuccess {String} [search_results.article_text] 投稿文書
@apiSuccess {String} [search_results.text_language_code] 投稿文書言語(iso15924)
@apiSuccess {Number} [search_results.post_timestamp] 投稿時タイムスタンプ
@apiSuccess {Number} [search_results.star] 星数
@apiSuccess {Number} [search_results.like_number] いいね数
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample NoResults-Response:
HTTP/1.1 400 OK
{
"error": "NoResults",
"message": [
"検索結果が見つかりません"
]
}
@apiSuccessExample SearchServiceTemporarilyUnavailable-Response:
HTTP/1.1 400 OK
{
"error": "SearchServiceTemporarilyUnavailable",
"message": [
"検索サービスが一時的に利用できません。時間を空けて再度ご利用ください。"
]
}
@apiSuccessExample AddressOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "AddressOverUpperLimit",
"message": [
"検索文字が文字数上限に超えました"
]
}
<file_sep>@api {Post} /map/search 地図検索
@apiVersion 0.1.0
@apiName /map/search
@apiGroup map
@apiSampleRequest off
@apiDescription 地図検索。
@apiParam {String} [user_uuid] ユーザID(ログインしている場合必須)
@apiParam {Number} [longitude] 経度(現在地から検索する場合必須)
@apiParam {Number} [latitude] 緯度(現在地から検索する場合必須)
@apiParam {Number} [zoom] 拡大倍数(現在地から検索する場合必須)
@apiParam {String} [location_name] 地名(地名で検索する場合必須)
@apiParam {String} [text_language_code] 検索文字言語(iso15924、地名で検索する場合使う)
@apiParam {Object} [filtering] 絞り込む条件(ここ以降各種検索共通)
@apiParam {String} [filtering.freeword] フリーワード検索。投稿テキストから検索。
@apiParam {Number} [filtering.post_by_user_id] 投稿者ユーザID(特定の投稿者の投稿を探すとき使う。自分にも使える)
@apiParam {Number} [filtering.like_by_user_id] いいねを付けたユーザID(主に自分がいいねを付けた投稿を探すとき使う)
@apiParam {Number[]} [filtering.categorys] カテゴリ配列
@apiParam {Number} [filtering.categorys.category_id] カテゴリID
@apiParam {Number} [filtering.sex] 性別。1:男性 2:女性
@apiParam {String} [filtering.country] 国名
@apiParam {Number} [filtering.generation] 年代
@apiParam {Number} [filtering.cost_id_min] 最低コスト
@apiParam {Number} [filtering.cost_id_max] 最高コスト
@apiParam {Number} [filtering.star_min] 最低星数
@apiParam {Number} [filtering.star_max] 最高星数
@apiParam {Number} [sort_by] 並び替え。1:人数 2:いいね 3:星数 4:新しい順(最近1ヶ月以内投稿多い順)
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Number} [zoom] 拡大倍数(現在地から検索する場合同じ値を返す。地名で検索する場合デフォルト値を返す。)
@apiSuccess {Object} [google_map_results] Google APIから返ってきた検索結果(status=OKの場合)
@apiSuccess {Object[]} search_results 検索結果
@apiSuccess {Number} [search_results.longitude] 経度
@apiSuccess {Number} [search_results.latitude] 緯度
@apiSuccess {Number} [search_results.spot_id] スポットID
@apiSuccess {String} [search_results.location_name] 地名
@apiSuccess {Number} [search_results.category_id] カテゴリID。1:温泉 2:レストラン 3:ホテル 4:観光スポット 5:交通 6:ショッピング 7:イベント 8:公共施設 9:アミューズメント 10:病院 99:その他
@apiSuccess {String[]} [search_results.color] スポット色
@apiSuccess {String} [search_results.color.rgb] スポット色のRGB形式。例:#99ee66
@apiSuccess {Number} [search_results.color.r] Red、範囲:0〜255。例:99
@apiSuccess {Number} [search_results.color.g] Green、範囲:0〜255。例:241
@apiSuccess {Number} [search_results.color.b] Blue、範囲:0〜255。例:150
@apiSuccess {Number} [search_results.color.a] Alpha、範囲:0〜1。例:0.5
@apiSuccess {Number} [search_results.cost_id] コストID。1:¥0 2:¥1〜¥1,000 3:¥1,001〜¥2,000 4:¥2,001〜¥5,000 5:¥5,001〜¥10,000 6:¥10,001〜
@apiSuccess {Number} [search_results.star] 星数
@apiSuccess {Number} [search_results.article_number] 投稿数
@apiSuccess {Number} [search_results.like_number] いいね数
@apiSuccess {Number} [search_results.score] スコア(並び順により算出お勧め度)
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample NoResults-Response:
HTTP/1.1 400 OK
{
"error": "NoResults",
"message": [
"検索結果が見つかりません"
]
}
@apiSuccessExample SearchServiceTemporarilyUnavailable-Response:
HTTP/1.1 400 OK
{
"error": "SearchServiceTemporarilyUnavailable",
"message": [
"検索サービスが一時的に利用できません。時間を空けて再度ご利用ください。"
]
}
@apiSuccessExample AddressOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "AddressOverUpperLimit",
"message": [
"検索文字が文字数上限に超えました"
]
}
<file_sep><?php
namespace Model;
use \Fuel\Core\Log;
class Multimedias extends Base {
public static function get_multimedia($data)
{
try {
if(empty($data['path'])) {
throw new \MarcoPandaException(16);
}
$multimedia_result = \DB::select('multimedia_id', 'save_path', 'mime_type', 'media_type', 'filename')
->from('multimedia')
->where('save_path', '=', $data['path'])
->execute()
->as_array();
if(count($multimedia_result) == 0) {
throw new \MarcoPandaException(17);
}
return $multimedia_result[0];
} catch(\Exception $e) {
throw new \MarcoPandaException(0);
}
}
}
<file_sep><?php
/**
* Fuel is a fast, lightweight, community driven PHP5 framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
use \Model\Maps;
/**
* The Article Controller.
*
* A basic controller example. Has examples of how to set the
* response body and status.
*
* @package app
* @extends Controller
*/
class Controller_Map extends Controller_Base
{
public function before()
{
parent::before();
}
public function after($response)
{
$response = parent::after($response);
return $response;
}
/**
* search in map
*
* @access public
* @return Response
*/
public function action_search()
{
try {
$results = Maps::search_3_in_1( self::$_JSON );
return $this->response($results, 200);
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
}
<file_sep>@api {Post} /multimedia/download ファイルダウンロード
@apiVersion 0.1.0
@apiName /multimedia/download
@apiGroup multimedia
@apiSampleRequest off
@apiDescription ファイルダウンロード
@apiParam {String} path パス
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Object} binary ファイルのバイナリデータ
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
@apiSuccessExample NoResults-Response:
HTTP/1.1 400 OK
{
"error": "PathNotFound",
"message": [
"パスが見つかりません"
]
}
<file_sep>../apidoc/api_data.js<file_sep>=begin
@api {Post} /user/regist ユーザ登録
@apiVersion 0.1.0
@apiName /user/regist
@apiGroup user
@apiSampleRequest off
@apiDescription ユーザ登録
@apiParam {Number} come_from どのSNSから来た。1:mail 2:facebook 3:google 4:wechat 5:twitter 6:linkedin
@apiParam {String} login_account ログインアカウント。come_fromが1の場合メールアドレスになる。
@apiParam {String} nickname ニックネーム
@apiParam {Number} [sex] 性別。1:男性 2:女性
@apiParam {Number} [generation] 年代。1:〜9 2:10〜19 3:20〜29 4:30〜39 5:40〜49 6:50〜59 7:60〜69 8:70〜79 9:80〜
@apiParam {String} [country] 国名
@apiParam {File} [image_file] ユーザアイコン
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {String} user_uuid ユーザUUID。40桁ランダム文字
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"user_uuid": "5m0rjnZo7F2v3cx7GDj7WO5PmLcxSHSHlEtF0hNE"
}
@apiSuccessExample ComeFromNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ComeFromNotExist",
"message": [
"SNSが存在しません"
]
}
@apiSuccessExample UserExist-Response:
HTTP/1.1 400 OK
{
"error": "UserExist",
"message": [
"ユーザが既に存在しました"
]
}
@apiSuccessExample GenerationNotExist-Response:
HTTP/1.1 400 OK
{
"error": "GenerationNotExist",
"message": [
"年代が存在しません"
]
}
=end
def /user/regist
end
=begin
@api {Post} /user/uuid_regist ユーザUUID登録(プレゼン用)
@apiVersion 0.1.0
@apiName /user/uuid_regist
@apiGroup user
@apiSampleRequest off
@apiDescription ユーザUUID登録
@apiParam {String} user_uuid ユーザUUID
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {String} user_uuid ユーザUUID。もらったデータをそのまま返す
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"user_uuid": "5m0rjnZo7F2v3cx7GDj7WO5PmLcxSHSHlEtF0hNE"
}
@apiSuccessExample UserExist-Response:
HTTP/1.1 400 OK
{
"error": "UserExist",
"message": [
"ユーザが既に存在しました"
]
}
=end
def /user/uuid_regist
end
<file_sep><?php
/**
* Fuel is a fast, lightweight, community driven PHP5 framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
use \Model\Multimedias;
use \Fule\Core\Log;
/**
* The Article Controller.
*
* A basic controller example. Has examples of how to set the
* response body and status.
*
* @package app
* @extends Controller
*/
class Controller_Multimedia extends Controller_Base
{
public function before()
{
parent::before();
}
public function after($response)
{
$response = parent::after($response);
return $response;
}
/**
* upload file
*
* @access public
* @return Response
*/
public function action_download()
{
try {
$result = Multimedias::get_multimedia(\Input::get());
//\Log::warning('input: '. var_export(\Input::get(), true). ', url: '. DOCROOT. '../fuel/app/tmp/upload/'. $result['path']);
header("Content-Type: ". $result['mime_type']);
echo file_get_contents(DOCROOT. '../fuel/app/tmp/upload/'. $result['save_path']);
exit();
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
}
<file_sep>../apidoc/api_project.js<file_sep>@api {Post} /article/ranking 旅行誌に星を付ける
@apiVersion 0.1.0
@apiName /article/ranking
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌に星を付ける
@apiParam {Number} article_id 旅行誌ID
@apiParam {String} user_uuid ユーザUUID。匿名の場合いいねを付けれない
@apiParam {Number} star 星数
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample ArticleNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ArticleNotExist",
"message": [
"旅行誌が存在しません"
]
}
@apiSuccessExample UserNotExist-Response:
HTTP/1.1 400 OK
{
"error": "UserNotExist",
"message": [
"ユーザが存在しません"
]
}
@apiSuccessExample StarOverLimit-Response:
HTTP/1.1 400 OK
{
"error": "StarOverLimit",
"message": [
"付けれない星数"
]
}
@apiSuccessExample RepeatRanking-Response:
HTTP/1.1 400 OK
{
"error": "RepeatLike",
"message": [
"ユーザが既に評価しました"
]
}
<file_sep><?php
namespace Model;
require_once(APPPATH.'vendor/marcopandaexception.php');
use \Fuel\Core\Log;
class Base extends \Model {
public static $uploaded_files = array();
public static $uploaded_files_error = array();
public static function upload_file($upload_config) {
try {
// $_FILES 内のアップロードされたファイルを処理する
\Upload::process($upload_config);
// 有効なファイルがある場合
if (\Upload::is_valid())
{
// バリデーションされた全てのファイルを別の場所に保存する
$arr = \Upload::get_files();
\Upload::save();
// $arr = Upload::get_files();
self::$uploaded_files = \Upload::get_files();
// Log::warning(var_export(self::$uploaded_files, true));
self::$uploaded_files_error = \Upload::get_errors();
// Log::warning(var_export(self::$uploaded_files_error, true));
} else {
// throw new \OneException(9009);
}
} catch(\Exception $e) {
throw $e;
}
}
/**
* システム日を日本時間で取得する
* @return type
*/
public static function get_datetime_jst() {
$jsdatetime = gmdate('Y-m-d H:i:s', strtotime('+9 hours'));
return $jsdatetime;
}
/**
* システム日を日本時間で取得する
* @return type
*/
public static function get_date_jst() {
$jsdate = gmdate('Y-m-d', strtotime('+9 hours'));
return $jsdate;
}
}
<file_sep>## 手順
1.Xcode 8をインストールしてください。
2.cd /marcopanda/ios/marcopandaios
3.pod install (pod 1.0.0が必要です)
4.xocde8でビルドする<file_sep>@api {Post} /article/like 旅行誌にいいねする
@apiVersion 0.1.0
@apiName /article/like
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌にいいねする
@apiParam {Number} article_id 旅行誌ID
@apiParam {String} user_uuid ユーザUUID。匿名の場合いいねを付けれない
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample ArticleNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ArticleNotExist",
"message": [
"旅行誌が存在しません"
]
}
@apiSuccessExample UserNotExist-Response:
HTTP/1.1 400 OK
{
"error": "UserNotExist",
"message": [
"ユーザが存在しません"
]
}
@apiSuccessExample RepeatLike-Response:
HTTP/1.1 400 OK
{
"error": "RepeatLike",
"message": [
"ユーザが既にいいねをしました"
]
}
<file_sep><?php
/**
* Fuel is a fast, lightweight, community driven PHP5 framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
use \Model\Users;
/**
* The Article Controller.
*
* A basic controller example. Has examples of how to set the
* response body and status.
*
* @package app
* @extends Controller
*/
class Controller_User extends Controller_Base
{
public function before()
{
parent::before();
}
public function after($response)
{
$response = parent::after($response);
return $response;
}
/**
* upload file
*
* @access public
* @return Response
*/
public function post_uuid_regist()
{
try {
$results = Users::uuid_regist( self::$_JSON );
return $this->response($results, 200);
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
/**
* The basic welcome message
*
* @access public
* @return Response
*/
public function post_post()
{
try {
$results = Articles::regist( self::$_JSON );
return $this->response($results, 200);
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
/**
* A typical "Hello, Bob!" type example. This uses a Presenter to
* show how to use them.
*
* @access public
* @return Response
*/
public function action_hello()
{
return Response::forge(Presenter::forge('welcome/hello'));
}
/**
* The 404 action for the application.
*
* @access public
* @return Response
*/
public function action_404()
{
return Response::forge(Presenter::forge('welcome/404'), 404);
}
}
<file_sep><?php
/**
* The development database settings. These get merged with the global settings.
*/
return array(
'default' => array(
'connection' => array(
'dsn' => 'mysql:host=rm-j6c2il7681qgjcw7o.mysql.rds.aliyuncs.com;dbname=marcopanda',
'username' => 'marcopandaecs',
'password' => '<PASSWORD>',
),
),
'read' => array(
'connection' => array(
'dsn' => 'mysql:host=rm-j6c2il7681qgjcw7o.mysql.rds.aliyuncs.com;dbname=marcopanda',
'username' => 'marcopandaread',
'password' => '<PASSWORD>',
),
),
);
<file_sep><?php
/**
* Fuel is a fast, lightweight, community driven PHP5 framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
use \Fuel\Core\Log;
/**
* The Article Controller.
*
* A basic controller example. Has examples of how to set the
* response body and status.
*
* @package app
* @extends Controller
*/
class Controller_Base extends Controller_Rest
{
public static $_JSON = NULL;
public function before()
{
parent::before();
// 認証処理などの共通処理を記述
\Lang::load('errors');
$php_input = file_get_contents('php://input');
//Log::warning(var_export($php_input, true));
self::$_JSON = json_decode($php_input, true);
}
public function after($response)
{
$response = parent::after($response);
// アクション実行後に行いたい共通処理を記述
return $response;
}
/**
* Exceptionが発生する場合エラーメッセージを返す
*/
public function error($exception) {
$response = array(
'error' => $exception->getMPErrorCode(),
'message' => $exception->getMessage(),
);
$this->response($response, 400);
}
}
<file_sep>@api {Post} /article/fileupload ファイルアップロード
@apiVersion 0.1.0
@apiName /article/fileupload
@apiGroup article
@apiSampleRequest off
@apiDescription ファイルアップロード
@apiParam {File[]} [file] ファイル投稿(複数ファイル可能)
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Object[]} files ファイル配列
@apiSuccess {Number} files.multimedia_id ファイルID
@apiSuccess {String} files.download_url ダウンロードURL
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"user_uuid": "5m0rjnZo7F2v3cx7GDj7WO5PmLcxSHSHlEtF0hNE"
}
@apiSuccessExample ComeFromNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ComeFromNotExist",
"message": [
"SNSが存在しません"
]
}
@apiSuccessExample UserExist-Response:
HTTP/1.1 400 OK
{
"error": "UserExist",
"message": [
"ユーザが既に存在しました"
]
}
@apiSuccessExample GenerationNotExist-Response:
HTTP/1.1 400 OK
{
"error": "GenerationNotExist",
"message": [
"年代が存在しません"
]
}
<file_sep>@api {Post} /article/post 旅行誌投稿
@apiVersion 0.1.0
@apiName /article/post
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌投稿
@apiParam {Number} [spot_id] スポットID(地図上スポットをタップして投稿する場合必須)
@apiParam {Number} [longitude] 経度(現在地から投稿する場合必須)
@apiParam {Number} [latitude] 緯度(現在地から投稿する場合必須)
@apiParam {String} [location_name] 地名(現在地から投稿する場合使う)
@apiParam {String} [user_uuid] ユーザUUID。匿名の場合省略可能
@apiParam {String} [nickname] ニックネーム
@apiParam {Number} [category_id] カテゴリID。spot_idがNULLの場合必須。1:温泉 2:レストラン 3:ホテル 4:観光スポット 5:交通 6:ショッピング 7:イベント 8:公共施設 9:アミューズメント 10:病院 99:その他
@apiParam {Number} [cost_id] コストID。spot_idがNULLの場合必須。1:¥0 2:¥1〜¥1,000 3:¥1,001〜¥2,000 4:¥2,001〜¥5,000 5:¥5,001〜¥10,000 6:¥10,001〜
@apiParam {Number[]} [multimedia_id] ファイルID(複数枚可能)
@apiParam {String} [article_text] 投稿文書
@apiParam {String} [text_language_code] 投稿文書言語(iso15924)
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Number} article_id ID
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"id": 2343
}
@apiSuccessExample LongitudeNotExist-Response:
HTTP/1.1 400 OK
{
"error": "LongitudeNotExist",
"message": [
"経度が存在しません"
]
}
@apiSuccessExample LatitudeNotExist-Response:
HTTP/1.1 400 OK
{
"error": "LatitudeNotExist",
"message": [
"経度が存在しません"
]
}
@apiSuccessExample UserNotExist-Response:
HTTP/1.1 400 OK
{
"error": "UserNotExist",
"message": [
"ユーザが存在しません"
]
}
@apiSuccessExample CategoryNotExist-Response:
HTTP/1.1 400 OK
{
"error": "CategoryNotExist",
"message": [
"カテゴリが存在しません"
]
}
@apiSuccessExample CostNotExist-Response:
HTTP/1.1 400 OK
{
"error": "CostNotExist",
"message": [
"コストが存在しません"
]
}
@apiSuccessExample ArticleTextOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "ArticleTextOverUpperLimit",
"message": [
"投稿テキストが文字数上限に超えました"
]
}
@apiSuccessExample NicknameOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "NicknameOverUpperLimit",
"message": [
"ニックネームは文字数上限に超えました"
]
}
<file_sep><?php
class MarcoPandaException extends Exception {
private $error_code = NULL;
public function __construct($code = NULL, $additional='', Exception $previous = null) {
$error_key = sprintf("errors.%04d", $code);
$lang_array = \Lang::get($error_key);
$this->error_code = $lang_array['code'];
$lang_msg = $lang_array['message'];
if($additional != "") {
$lang_msg = sprintf($lang_msg, $additional);
}
parent::__construct($lang_msg, $code, $previous);
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function getMPErrorCode() {
return $this->error_code;
}
}
<file_sep>#!/bin/bash
rm -f marcopanda/*.*
#<?php main(); ?>
php $0
apidoc -i marcopanda/ -o apidoc/ -t mytemplate/ --line-ending=CRLF
exit
<?php
function main() {
define("ROOT", dirname(__FILE__));
define("SOURCE_PATH", ROOT. "/source");
define("OUTPUT_PATH", ROOT. "/marcopanda");
//echo SOURCE_PATH, "\n";
$list = scandir(SOURCE_PATH);
foreach($list as $key => $value) {
$file_path = SOURCE_PATH. "/". $value;
$path_parts = pathinfo($file_path);
if($path_parts['extension'] == 'rb') {
$contents = file_get_contents($file_path);
//$contents = convert_to_rpc2($contents);
$apiGroup = "";
$apiName = "";
preg_match('/^@apiName\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[1])) {
$apiName = $matches[1];
}
preg_match('/^@apiGroup\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[1])) {
$apiGroup = $matches[1];
}
$output_file_path = OUTPUT_PATH. "/". $apiGroup. ".rb";
$handle = fopen($output_file_path, "a+");
fwrite($handle, "=begin\n");
fwrite($handle, $contents. "\n");
fwrite($handle, "=end\n");
fwrite($handle, "def ". $apiName. "\nend\n");
fclose($handle);
}
}
//print_r($list);
//echo "\n";
}
function convert_to_rpc2($contents) {
$contents = convert_http_method_and_url($contents);
$contents = convert_apiExample($contents);
//$contents = convertResponse($contents);
return $contents;
}
function convert_http_method_and_url($contents) {
$apiGroup = "";
$apiName = "";
preg_match('/^@apiName\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[1])) {
$apiName = $matches[1];
}
preg_match('/^@apiGroup\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[1])) {
$apiGroup = $matches[1];
}
//preg_match('/^@api\s(.*)[^\r\n]*/m', $contents, $matches);
preg_match('/^@api\s{(.*)}\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[2])) {
preg_match('/^(.*)\s(.*)$/m', $matches[2], $matches2);
if(isset($matches2[1])) {
$url = $matches2[1];
//$api_title = substr($matches[2], strpos($url, $matches[2]) + strlen($url));
$replace_to_row = "@api {post} ". $apiName;
$contents = str_replace($matches[0], $replace_to_row, $contents);
}
}
return $contents;
}
function convert_apiExample($contents) {
$apiGroup = "";
$apiName = "";
preg_match('/^@apiName\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[1])) {
$apiName = $matches[1];
}
preg_match('/^@apiGroup\s(.*)[^\r\n]*/m', $contents, $matches);
if(isset($matches[1])) {
$apiGroup = $matches[1];
}
preg_match_all('/^curl\s(.*)[^\r\n]*/m', $contents, $matches);
foreach($matches[0] as $key => $value) {
$array = preg_split("/[\s]+/", $value);
//echo "before\n";print_r($array);
$i_key = array_search('-i', $array);
if($i_key === false) {
$i_key = 0;
}
$d_key = array_search('-d', $array);
if($d_key !== false) {
$post_body = $array[$d_key + 1];
$post_body = substr($post_body, 1, strlen($post_body) - 2);
$post_body = '\'{"jsonrpc": "2.0", "method": "'. $apiName. '", "id": 1, "params": '. $post_body. '}\'';
$array[$d_key + 1] = $post_body;
} else if($apiName != '/opus/binary/post') {
$post_body = '\'{"jsonrpc": "2.0", "method": "'. $apiName. '", "id": 1, "params": ""}\'';
array_splice($array, $i_key + 1, 0, array('-d', $post_body));
//echo "after body\n";print_r($array);
}
$x_key = array_search('-X', $array);
if($x_key !== false) {
$array[$x_key + 1] = 'POST';
} else if($apiName != '/opus/binary/post') {
array_splice($array, $i_key + 1, 0, array('-X', 'POST'));
//echo "after post\n";print_r($array);
}
//echo "after\n";print_r($array);
if($apiName != '/opus/binary/post') {
$array[count($array) - 1] = 'http://api.otoba.dev.vc/v1/rpc';
$value_to_replace = implode(' ', $array);
$contents = str_replace($value, $value_to_replace, $contents);
}
}
return $contents;
}
function convertResponse($contents) {
preg_match_all('/^@apiSuccessExample\s(.*)[^\r\n]*/m', $contents, $matches);
//print_r($matches);
$rows = split("\n", $contents);
//print_r($rows);
for($i = count($matches[0]) - 1; $i >= 0; $i--) {
$start_line = array_search($matches[0][$i], $rows);
$end_line = count($rows);
if($i < count($matches[0]) - 1) {
$end_line = array_search($matches[0][$i + 1], $rows);
}
$replaces = array_slice($rows, $start_line + 2, $end_line - $start_line - 2);
for($j = 0; $j < $end_line - $start_line - 2 - 1; $j++) {
$replaces[$j] = " ". $replaces[$j];
}
//print_r($replaces);
$head_rows = array(
' {',
' "jsonrpc": "2.0",',
' "id": "1",',
' "result":');
$tail_rows = array(
' }');
array_splice($replaces, 0, 0, $head_rows);
array_splice($replaces, count($replaces), 0, $tail_rows);
//print_r($replaces);
array_splice($rows, $start_line + 2, $end_line - $start_line - 2, $replaces);
}
$contents = implode("\n", $rows);
return $contents;
}
?>
<file_sep>=begin
@api {Post} /address/search 住所検索
@apiVersion 0.1.0
@apiName /address/search
@apiGroup address
@apiSampleRequest off
@apiDescription 住所検索。直接に使わないかもしれません。
@apiParam {String} location_name 地名
@apiParam {String} [text_language_code] 検索文字言語(iso15924)
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Object} results Google APIから返ってきた検索結果(status=OKの場合)
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"results" : [
{
"address_components" : [
{
"long_name" : "Shibuya",
"short_name" : "Shibuya",
"types" : [ "political", "sublocality", "sublocality_level_1" ]
},
{
"long_name" : "Shibuya",
"short_name" : "Shibuya",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Tokyo",
"short_name" : "Tokyo",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Japan",
"short_name" : "JP",
"types" : [ "country", "political" ]
},
{
"long_name" : "150-0002",
"short_name" : "150-0002",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Shibuya, Tokyo 150-0002, Japan",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 35.6641549,
"lng" : 139.7139651
},
"southwest" : {
"lat" : 35.65347089999999,
"lng" : 139.7005457
}
},
"location" : {
"lat" : 35.6597803,
"lng" : 139.7017675
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 35.6641549,
"lng" : 139.7139651
},
"southwest" : {
"lat" : 35.65347089999999,
"lng" : 139.7005457
}
}
},
"place_id" : "ChIJGfSRvl6LGGAR5GDIDOVf4Bc",
"types" : [ "political", "sublocality", "sublocality_level_1" ]
}
],
}
@apiSuccessExample NoResults-Response:
HTTP/1.1 400 OK
{
"error": "NoResults",
"message": [
"検索結果が見つかりません"
]
}
@apiSuccessExample SearchServiceTemporarilyUnavailable-Response:
HTTP/1.1 400 OK
{
"error": "SearchServiceTemporarilyUnavailable",
"message": [
"検索サービスが一時的に利用できません。時間を空けて再度ご利用ください。"
]
}
@apiSuccessExample AddressOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "AddressOverUpperLimit",
"message": [
"検索文字が文字数上限に超えました"
]
}
=end
def /address/search
end
<file_sep>=begin
@api {Post} /article/fileupload ファイルアップロード
@apiVersion 0.1.0
@apiName /article/fileupload
@apiGroup article
@apiSampleRequest off
@apiDescription ファイルアップロード
@apiParam {File[]} [file] ファイル投稿(複数ファイル可能)
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Object[]} files ファイル配列
@apiSuccess {Number} files.multimedia_id ファイルID
@apiSuccess {String} files.download_url ダウンロードURL
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"user_uuid": "5m0rjnZo7F2v3cx7GDj7WO5PmLcxSHSHlEtF0hNE"
}
@apiSuccessExample ComeFromNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ComeFromNotExist",
"message": [
"SNSが存在しません"
]
}
@apiSuccessExample UserExist-Response:
HTTP/1.1 400 OK
{
"error": "UserExist",
"message": [
"ユーザが既に存在しました"
]
}
@apiSuccessExample GenerationNotExist-Response:
HTTP/1.1 400 OK
{
"error": "GenerationNotExist",
"message": [
"年代が存在しません"
]
}
=end
def /article/fileupload
end
=begin
@api {Post} /article/like 旅行誌にいいねする
@apiVersion 0.1.0
@apiName /article/like
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌にいいねする
@apiParam {Number} article_id 旅行誌ID
@apiParam {String} user_uuid ユーザUUID。匿名の場合いいねを付けれない
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample ArticleNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ArticleNotExist",
"message": [
"旅行誌が存在しません"
]
}
@apiSuccessExample UserNotExist-Response:
HTTP/1.1 400 OK
{
"error": "UserNotExist",
"message": [
"ユーザが存在しません"
]
}
@apiSuccessExample RepeatLike-Response:
HTTP/1.1 400 OK
{
"error": "RepeatLike",
"message": [
"ユーザが既にいいねをしました"
]
}
=end
def /article/like
end
=begin
@api {Post} /article/post 旅行誌投稿
@apiVersion 0.1.0
@apiName /article/post
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌投稿
@apiParam {Number} [spot_id] スポットID(地図上スポットをタップして投稿する場合必須)
@apiParam {Number} [longitude] 経度(現在地から投稿する場合必須)
@apiParam {Number} [latitude] 緯度(現在地から投稿する場合必須)
@apiParam {String} [location_name] 地名(現在地から投稿する場合使う)
@apiParam {String} [user_uuid] ユーザUUID。匿名の場合省略可能
@apiParam {String} [nickname] ニックネーム
@apiParam {Number} [category_id] カテゴリID。spot_idがNULLの場合必須。1:温泉 2:レストラン 3:ホテル 4:観光スポット 5:交通 6:ショッピング 7:イベント 8:公共施設 9:アミューズメント 10:病院 99:その他
@apiParam {Number} [cost_id] コストID。spot_idがNULLの場合必須。1:¥0 2:¥1〜¥1,000 3:¥1,001〜¥2,000 4:¥2,001〜¥5,000 5:¥5,001〜¥10,000 6:¥10,001〜
@apiParam {Number[]} [multimedia_id] ファイルID(複数枚可能)
@apiParam {String} [article_text] 投稿文書
@apiParam {String} [text_language_code] 投稿文書言語(iso15924)
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Number} article_id ID
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
"id": 2343
}
@apiSuccessExample LongitudeNotExist-Response:
HTTP/1.1 400 OK
{
"error": "LongitudeNotExist",
"message": [
"経度が存在しません"
]
}
@apiSuccessExample LatitudeNotExist-Response:
HTTP/1.1 400 OK
{
"error": "LatitudeNotExist",
"message": [
"経度が存在しません"
]
}
@apiSuccessExample UserNotExist-Response:
HTTP/1.1 400 OK
{
"error": "UserNotExist",
"message": [
"ユーザが存在しません"
]
}
@apiSuccessExample CategoryNotExist-Response:
HTTP/1.1 400 OK
{
"error": "CategoryNotExist",
"message": [
"カテゴリが存在しません"
]
}
@apiSuccessExample CostNotExist-Response:
HTTP/1.1 400 OK
{
"error": "CostNotExist",
"message": [
"コストが存在しません"
]
}
@apiSuccessExample ArticleTextOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "ArticleTextOverUpperLimit",
"message": [
"投稿テキストが文字数上限に超えました"
]
}
@apiSuccessExample NicknameOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "NicknameOverUpperLimit",
"message": [
"ニックネームは文字数上限に超えました"
]
}
=end
def /article/post
end
=begin
@api {Post} /article/ranking 旅行誌に星を付ける
@apiVersion 0.1.0
@apiName /article/ranking
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌に星を付ける
@apiParam {Number} article_id 旅行誌ID
@apiParam {String} user_uuid ユーザUUID。匿名の場合いいねを付けれない
@apiParam {Number} star 星数
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample ArticleNotExist-Response:
HTTP/1.1 400 OK
{
"error": "ArticleNotExist",
"message": [
"旅行誌が存在しません"
]
}
@apiSuccessExample UserNotExist-Response:
HTTP/1.1 400 OK
{
"error": "UserNotExist",
"message": [
"ユーザが存在しません"
]
}
@apiSuccessExample StarOverLimit-Response:
HTTP/1.1 400 OK
{
"error": "StarOverLimit",
"message": [
"付けれない星数"
]
}
@apiSuccessExample RepeatRanking-Response:
HTTP/1.1 400 OK
{
"error": "RepeatLike",
"message": [
"ユーザが既に評価しました"
]
}
=end
def /article/ranking
end
=begin
@api {Post} /article/search 旅行誌検索
@apiVersion 0.1.0
@apiName /article/search
@apiGroup article
@apiSampleRequest off
@apiDescription 旅行誌検索。
@apiParam {String} [user_uuid] ユーザID(ログインしている場合必須)
@apiParam {Number} [longitude] 経度(現在地から検索する場合必須)
@apiParam {Number} [latitude] 緯度(現在地から検索する場合必須)
@apiParam {Number} [zoom] 拡大倍数(現在地から検索する場合必須)
@apiParam {Number} [spot_id] スポットID(スポットをタップして検索する場合必須)
@apiParam {String} [location_name] 地名(地名で検索する場合必須)
@apiParam {String} [text_language_code] 検索文字言語(iso15924、地名で検索する場合使う)
@apiParam {Object} [filtering] 絞り込む条件(ここ以降各種検索共通)
@apiParam {String} [filtering.freeword] フリーワード検索。投稿テキストから検索。
@apiParam {Number} [filtering.post_by_user_id] 投稿者ユーザID(特定の投稿者の投稿を探すとき使う。自分にも使える)
@apiParam {Number} [filtering.like_by_user_id] いいねを付けたユーザID(主に自分がいいねを付けた投稿を探すとき使う)
@apiParam {Number[]} [filtering.categorys] カテゴリ配列
@apiParam {Number} [filtering.categorys.category_id] カテゴリID
@apiParam {Number} [filtering.sex] 性別。1:男性 2:女性
@apiParam {String} [filtering.country] 国名
@apiParam {Number} [filtering.generation] 年代
@apiParam {Number} [filtering.cost_id_min] 最低コスト
@apiParam {Number} [filtering.cost_id_max] 最高コスト
@apiParam {Number} [filtering.star_min] 最低星数
@apiParam {Number} [filtering.star_max] 最高星数
@apiParam {Number} [sort_by] 並び替え。1:人数 2:いいね 3:星数 4:新しい順
@apiParam {Number} [page] 何ページ目指定。デフォルト1ページ目。
@apiSuccess {String} [error] エラーコード
@apiSuccess {String[]} [message] エラーメッセージ
@apiSuccess {Number} [zoom] 拡大倍数(現在地から検索する場合同じ値を返す。地名で検索する場合デフォルト値を返す。)
@apiSuccess {Object} google_map_results Google APIから返ってきた検索結果(status=OKの場合)
@apiSuccess {Number} search_result_count 検索結果件数
@apiSuccess {Object[]} [search_results] 検索結果
@apiSuccess {Number} [search_results.article_id] 投稿ID
@apiSuccess {Number} [search_results.spot_id] スポットID
@apiSuccess {String[]} [search_results.image_urls] 画像URL配列
@apiSuccess {String} [search_results.image_urls.url] 画像URL
@apiSuccess {String} [search_results.sound_url] 音声URL
@apiSuccess {Number} [search_results.longitude] 経度
@apiSuccess {Number} [search_results.latitude] 緯度
@apiSuccess {String} [search_results.location_name] 地名
@apiSuccess {String} [search_results.user_uuid] ユーザUUID。匿名の場合空欄
@apiSuccess {String} [search_results.nickname] ニックネーム
@apiSuccess {Number} [search_results.category_id] カテゴリID。1:温泉 2:レストラン 3:ホテル 4:観光スポット 5:交通 6:ショッピング 7:イベント 8:公共施設 9:アミューズメント 10:病院 99:その他
@apiSuccess {Number} [search_results.cost_id] コストID。1:¥0 2:¥1〜¥1,000 3:¥1,001〜¥2,000 4:¥2,001〜¥5,000 5:¥5,001〜¥10,000 6:¥10,001〜
@apiSuccess {String} [search_results.article_text] 投稿文書
@apiSuccess {String} [search_results.text_language_code] 投稿文書言語(iso15924)
@apiSuccess {Number} [search_results.post_timestamp] 投稿時タイムスタンプ
@apiSuccess {Number} [search_results.star] 星数
@apiSuccess {Number} [search_results.like_number] いいね数
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
}
@apiSuccessExample NoResults-Response:
HTTP/1.1 400 OK
{
"error": "NoResults",
"message": [
"検索結果が見つかりません"
]
}
@apiSuccessExample SearchServiceTemporarilyUnavailable-Response:
HTTP/1.1 400 OK
{
"error": "SearchServiceTemporarilyUnavailable",
"message": [
"検索サービスが一時的に利用できません。時間を空けて再度ご利用ください。"
]
}
@apiSuccessExample AddressOverUpperLimit-Response:
HTTP/1.1 400 OK
{
"error": "AddressOverUpperLimit",
"message": [
"検索文字が文字数上限に超えました"
]
}
=end
def /article/search
end
<file_sep># サーバー構築手順
## 事前準備
aliyun ecsインスタンスを先に作成しました。
OSをCentos7.2に選択しています。
サーバーにSSHログインできるようにしました。
## yumを最新化
yum update
## php5.6、apache2.4インストール
下記サイトを参考している。
http://weblabo.oscasierra.net/centos7-php56-install/
実行コマンド
yum -y install epel-release
cd /etc/yum.repos.d
wget http://rpms.famillecollet.com/enterprise/remi.repo
yum -y --enablerepo=remi,remi-php56 install httpd php php-common
vi /etc/php.ini
;data.timezone =
を下記に変更
date.timezone = Asia/Tokyo
systemctl enable httpd.service
systemctl start httpd.service
vi /var/www/html/info.php
<?php
phpinfo();
?>
## ファイアウォール設定
デフォルトで22ポートしか空いていないので、httpとhttpsのポートを開放するように設定します。
許可するポートを確認する
firewall-cmd --list-all
httpとhttpsポートを開放する
firewall-cmd --permanent --add-service=http --add-service=https
firewall-cmd --reload
許可するポートを確認する
firewall-cmd --list-all
http://172.16.17.32
http://172.16.17.32/info.php
が見れることを確認する
## ドメイン設定
お名前.comで事前に取ったドメインにサブドメインを作って、
ecsサーバーのIPに指すようにDNSレコードを登録する。
DNSレコードの反映はすこし時間がかかりますが、
一定時間空いてから、下記URLが見れるようになります。
http://api.marcopanda.dreamsfor.com/info.php
## 必要なミドルウェアをインストール
yum install git
## RDS開設
- aliyunのコンソール画面にRDSのインスタンスを作る
- フル権限アカウント作成
- 読み込みのみアカウント作成
- データベース作成
ECSサーバーにmysqlクライアントインストール
yum -y --enablerepo=remi,remi-php56 install mysql
RDSにmysqlログインできるか確認
mysql -u [username] -p -h [host] [dbname]
ECSサーバーにphpmyadminインストール
yum -y --enablerepo=remi,remi-php56 install phpMyAdmin
IP確認君でグローバルIPを確認して、
そのIPアドレスをphpmyadmin.confの設定ファイルに追加する
vi /etc/httpd/conf.d/phpMyAdmin.conf
Require local
の後ろに下記を追加する(2箇所)。
Require ip [確認君で取得したグローバルIP]
systemctl restart httpd.service
vi /etc/phpMyAdmin/config.inc.php
$cfg['Servers'][$i]['host'] = 'localhost';
にlocalhostの部分を実際のRDSホストに変更する。
http://api.marcopanda.dreamsfor.com/phpmyadmin/
で確認する。
## fuelphpインストール
### ダウンロード
http://fuelphp.com/
から最新版fuelphpをダウンロードして、
gitに保管して、サーバーでに下記のコマンドでgit pullする(apache権限)。
su -s /bin/bash apache
cd /var/www/html
git pull
### httpd設定
vi /etc/httpd/conf/httpd.conf
DocumentRoot "/var/www/html"
を下記に変更
DocumentRoot "/var/www/html/server/public"
SetEnv FUEL_ENV production
また
<Directory "/var/www/html">
を下記に変更
<Directory "/var/www/html/server/public">
その配下の
AllowOverride None
を下記に変更
AllowOverride All
また下記を追加
<Directory "/var/www/html/docs/apiDefine/doc">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Alias /apidefine /var/www/html/docs/apiDefine/doc
systemctl start httpd.service
API定義書は下記のURLで見れる
http://api.marcopanda.dreamsfor.com/apidefine/index.html
### composer更新
cd /var/www/html/server/
php composer.phar self-update
php composer.phar update
# Google API KEY取得
- Google Maps APIs
https://developers.google.com/maps/documentation/
サーバーのIPアドレスをGoogle APIのコンソール画面に登録する
- Google Maps API呼び出しを試す
https://maps.googleapis.com/maps/api/geocode/json?address=roppongi&key=YOUR_API_KEY
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
上記APIをサーバー側で
curl [url]
で実行して、結果が返ってくることを確認する。
<file_sep>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
xcodeproj './marcopandaios'
target 'marcopandaios' do
pod 'AFNetworking', '~> 3.0'
pod 'GoogleMaps'
pod 'SDWebImage'
end<file_sep><?php
/**
* Fuel is a fast, lightweight, community driven PHP5 framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
use \Model\Articles;
/**
* The Article Controller.
*
* A basic controller example. Has examples of how to set the
* response body and status.
*
* @package app
* @extends Controller
*/
class Controller_Article extends Controller_Base
{
public function before()
{
parent::before();
}
public function after($response)
{
$response = parent::after($response);
return $response;
}
/**
* The basic welcome message
*
* @access public
* @return Response
*/
public function action_index()
{
$list = array(
'foo' => Input::get('foo'),
'baz' => array(
1, 50, 219
),
'empty' => null
);
$results = Articles::get_list( 10, 0);
//print_r($results);
return $this->response($results, 200);
}
/**
* upload file
*
* @access public
* @return Response
*/
public function post_fileupload()
{
try {
$results = Articles::receive_upload();
return $this->response($results, 200);
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
/**
* The basic welcome message
*
* @access public
* @return Response
*/
public function post_post()
{
try {
$results = Articles::regist( self::$_JSON );
//\Log::warning(print_r($results, true));
return $this->response($results, 200);
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
/**
* search articles
*
* @access public
* @return Response
*/
public function action_search()
{
try {
$results = Articles::search_3_in_1( self::$_JSON );
return $this->response($results, 200);
} catch (\MarcoPandaException $e) {
$this->error($e);
}
}
}
|
03ce1c51e98d7eb1e55cdbd9611865a79112496c
|
[
"SQL",
"Ruby",
"Markdown",
"JavaScript",
"PHP",
"Shell"
] | 32
|
PHP
|
TrungSpy/marcopanda
|
11452f633a5d4ca665e67fb94de0f709c6749a16
|
097465800b0c462f5284c3e75c7cfc78f76d11ec
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.