branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>MXCompFin/MXCompFin.github.io<file_sep>/google_finance/google_finance.Rmd
---
title: "Getting data from Google Finance"
author: "<NAME>"
output:
prettydoc::html_pretty:
theme: cayman
highlight: github
---
## Getting data from Google Finance
In this lecture we'll create a python code that can be used to download historical prices from [Google Finance](http://finance.google.com/finance).
The task is a simple one, we just need to find the symbol of the stock and the exchange, and our program will create the appropiate URL ;).
**Note**
Seems that you can't download historical data for currencies, this method works only for equity instruments.
Now let's get started!
### Requirements
For you to follow this lecture please make sure that you have the following python package installed:
* pandas (I used version 0.18.0 for this lecture).
### Explaining the URL (The theory)
The URL that we'll need, looks something like this:
http://finance.google.com/finance/historical?q=BMV:AMXL&startdate=Jan+3+2000&enddate=Nov+11+2017&output=csv
At first, this might be daunting but the only parts you have to worry about are:
* **q=BMV:AMXL** this part makes reference to the exchange where our stock is listed (in this case Bolsa Mexicana de Valores - Mexican Stock Exchange) and the symbol for identifying the company (in this case America Movil Serie L)
* **startdate=Jan+3+2000**
* **enddate=Nov+11+2017**
I think there is no need for me to explain you the last two parameters you're smart enough to figure out what they are ;).
The remaining parts of the URL are kept as they are, so basically our code only needs the above three parameters and no more.
### And finally the code (The practice)
```{python, engine.path='/home/david/anaconda2/bin/python',eval=FALSE}
import pandas as pd
def getGooglePrices(exchanges,symbols,startDate,endDate):
'''
Gets historical data from Google Finance
Parameters:
exchanges = list of the exchanges according to the nomenclature
used by Google Finance
symbols = list of stock symbols according to the symbols from
Google Finance (Same length) as exchanges
The correspondance must have the form Ex1:Sym1, Ex2:Sym2,...etc
startDate = Start date in format Mmm+dd+yyyy
endDate = End date in format Mmm+dd+yyyy
Output
No output, the data is stored in the current working directory
as CSV file.
'''
#Declare the static parts of the URL
urlStatic1="http://finance.google.com/finance/historical?q="
urlStatic2="&output=csv"
#Create the dynamic parts of the url and downloads a file
#per symbol
for i in range(0,len(exchanges)):
quote=exchanges[i] + ":" + symbols[i]
url=urlStatic1 + quote + "&startdate=" + startDate\
+ "&enddate=" + endDate + urlStatic2
#Read the data from the url
data=pd.read_csv(url)
#Save it in the current directory
#Removes the column index
fileName=exchanges[i] + "_" + symbols[i] + ".csv"
data.to_csv(fileName,index=False)
```
### Testing the code
Now let's test our code with the following examples
```{python,engine.path='/home/david/anaconda2/bin/python',eval=FALSE}
exchanges=["BMV","BMV","NYSEARCA"]
symbols=["AMXL","KOFL","SPY"]
startDate="Jan+01+2017"
endDate="Nov+10+2017"
getGooglePrices(exchanges,symbols,startDate,endDate)
```
The above lines should have created 3 CSV files each containing the historical prices from January 3rd 2017 (01 and 02 were not working days) up to and including November 10th 2017.
Try with your own symbols.
### Conclusion
As you can see, the code has not error handlers so make sure that the symbols and exchanges you enter are the correct ones.
Also you can implement a little function so you can read these variables from a csv file avoiding you having to type them manually, but I won't take all the fun from you :)
Hope you find the above useful
Thanks for reading!
[Home Page](https://mxcompfin.github.io/)
<file_sep>/Scoring/CreditScoring.Rmd
---
title: "Credit Scoring with R"
author: "<NAME>"
date: "January 2018"
output:
prettydoc::html_pretty:
theme: cayman
highlight: github
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(readr)
library(tidyverse)
library(ggplot2)
library(DescTools)
library(Hmisc)
library(purrr)
library(reshape2)
library(varhandle)
library(caret)
```
## Credit Scoring: an Introduction.
Credit scoring refers to an analysis made by lenders and banks to extended credit (or not) to customers. It has many applications within the financial industry as it automated the underwriting process substantially and allows to derive more sophisticated products to final customers (Risk based pricing is an example).
What I'm going to do is show the versatility of __R__ to deal with a dataset ready to perform analysis and model. Obviously, as it is the case with most applications, the real deal comes when you have to collect the data, define what is a __bad__ customers and so on.
This example also illustrated the ease to build your own functions to perform the computations required to obtain a model. __R__ has many functions built in different packages that help you process your functions through datasets with much control on the output and inputs.
## The Data
The dataset comes from the Kaggle Competition [Give me some credit](https://www.kaggle.com/c/GiveMeSomeCredit) which consists in a small dataset of 150,000 observations with 10 predictors. We proceed to read and inspect the data, and rename our columns to more suitable and understandable names of our liking.
```{r read, warning=FALSE, error=FALSE,message=FALSE}
data <- read_csv("C:/Users/galcala/Loan/cs-training.csv")
data.tbl <- as_tibble(data.frame(data))
typeof(data.tbl)
glimpse(data.tbl)
data.tbl$X1 <- NULL
colnames(data.tbl) <- c("bad","revUtilUnsec","age","n30_59dpd_nw","debtRatio","mIncome","nOpenTrades",
"n90dlate","nREstate","n60_89dpd_nw","nDependents")
```
Alright, seems like our data is well read. Let us split it into training and testing for modelling purposes and work our way through the data.
A very useful tool for inspecting variables (univariate) is the Desc function from the DescTools package, as it gives you many relevant statistics and information as well as useful plots to understand the distributions.
```{r describe, warning=FALSE, error=FALSE,message=FALSE}
set.seed(43)
inTrain <- createDataPartition(y=data.tbl$bad,p = .8, list = FALSE)
training <- data.tbl[inTrain,]
testing <- data.tbl[-inTrain,]
Desc(training)
#Income and Dependents have missing values (20% and 2.6%)
#6.7% delinquency rate
#Revolving highly skewed to the right. Needs trimming
#Age: We have a "0" age, 21 is our real minimum.
#n30_59dpd_nw: 84% zeros, skewed to the right
#debtRatio: 2.7% zeros. Highly skewed.
#mIncome: 1.3% zeros, highly skewed. 20% missing. Some negative.
#nOpenTrades: 1.3% zeros. slightly skewed. Integer variable.
#n90dlate: 94.4% zeros, highly skewed
#nREstate: 37.5% zeros, 33% 1s and 2+ the rest.
#n60_89dpd_nw: 94.9% zeros. skewed to the right.
#nDependents: 58% zeros. some missing (2.6%) outliers to the right.
```
Highly skewed data seems to be the norm, and such other undesired properties like censoring, missings and highly concentrated variables in only one of two attributes (mainly zero). But these are the norm for real world variables in credit scoring. What we are going to do next is to explore the relationship with our target variable, __bad__ and each characteristic. Let us do this visually through a plot.
We are going to plot our variable partitioned in 10 groups (or less, if the data doesn't allow for 10 groups) and plot the distribution of the data in bars and the rate of bads for each bin in a red line. These plots help us understand the relationship from our variables and our target.
```{r biplot,warning=FALSE, error=FALSE,message=FALSE,echo=FALSE,results='hide',fig.keep='all'}
graf_biv <- function(variable,datos=training,grupos=10,cortes=NULL){
if (is.null(cortes)){datos$nueva <- cut2(datos[[variable]],g=grupos)}
else{datos$nueva <- cut2(datos[[variable]],cuts = cortes)}
subset <- datos %>%
group_by(nueva) %>%
dplyr::summarise(casos = n(), media = round(mean(bad),3)) %>% ungroup()
escalay <- max(subset$media)
ajustey <- max(subset$casos)
media_global <- mean(datos$bad)
ggplot(subset) +
geom_bar(aes(x=nueva, y=casos),stat="identity", fill="grey", colour="grey")+
geom_point(aes(x=nueva, y=(ajustey/escalay)*media),stat="identity", color = "#D55E00")+
geom_path(aes(x=nueva, y=(ajustey/escalay)*media,group=1),stat="identity", color = "#D55E00")+
geom_text(aes(label=paste0((100*media),"%"), x=nueva, y=((ajustey/escalay)*media+ajustey/20)),
colour="black",size = 2.5)+
#geom_text(aes(label=Response, x=Year, y=0.95*Response), colour="black")+
scale_y_continuous(sec.axis = sec_axis(~./(ajustey/escalay),labels = scales::percent ,name ="Tasa de Incumplimento")) +
geom_hline(yintercept = (ajustey/escalay)*(media_global), col = "red") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
xlab(paste0(variable, " en ", grupos, " grupos")) +
ggtitle("Análisis Bivariado")
}
variables <- colnames(data.tbl)
variables <- variables[-1]
purrr::map(variables,safely(graf_biv),datos = training, grupos = 15)
#Conclusiones de bivariados
#Revolving Utilization has high discriminant power
#The age of the candidate has high discriminant power
#n30_59dpd_nw shows a strong relationship
#debtRatio has some counterintuitive results on the high end (related to mIncome missing, perhaps)
#mIncome is highly discriminant. beware of missings.
#nOpenTrades shows highly discriminant in the first group
#n90dlate concentrated but behaves correctly
#nREstate we can define 3 groups, 0, 1-2 and 3+ which profiles differently
#n60_89dpd concentrated but behaves correctly
#nDependents behaves correctly, NA and 0 are similar in risk.
```
In a credit scoring setting, it is most common to transform our characteristic into discrete variables through their Weight of Evidence (WoE) transformation, best explained [here](http://multithreaded.stitchfix.com/blog/2015/08/13/weight-of-evidence/). The advantage from these formulation is that it guarantees monotonic relationships and it is easily transformed into _points_ to add up in a _scorecard_ once the model is fitted.
To do that, let us first define __X__, our design matrix, with the variables grouped into our values of interest. We also deal with our NAs to obtain better results.
```{r designmatrix}
training$mIncome[training$mIncome<0] <- 0
X.tbl <- as_tibble(data.frame(list(bad=training$bad,
revUtilUnsec = cut2(training$revUtilUnsec,g=15),
age = cut2(training$age,g=13),
n30_59dpd_nw = cut2(training$n30_59dpd_nw,cuts=c(0,1,2,3)),
mIncome=cut2(training$mIncome,cuts=c(0,500,1250,1500,2000,3000,4000,5000,6000,7000,8000,9000)),
debtRatio = cut2(training$debtRatio,cuts=c(0,0.00001,.4,.6,.7,.8,.9,1)),
nOpenTrades = cut2(training$nOpenTrades,cuts=c(0,1,2,3,4,5)),
n90dlate = cut2(training$n90dlate,cuts=c(0,1,2,3)),
nREstate = cut2(training$nREstate,cuts=c(0,1,2,3)),
n60_89dpd_nw = cut2(training$n60_89dpd_nw,cuts=c(0,1,2,3)),
nDependents = cut2(training$nDependents,cuts=c(0,1,2,3,4))
)
))
#Transformamos los "NA" en "-1" para mantener dentro de los factores
X.tbl$nDependents<-factor(X.tbl$nDependents, levels = levels(addNA(X.tbl$nDependents)), labels = c(levels(X.tbl$nDependents), -1), exclude = NULL)
X.tbl$mIncome<-factor(X.tbl$mIncome, levels = levels(addNA(X.tbl$mIncome)), labels = c(levels(X.tbl$mIncome), -1), exclude = NULL)
```
Now we are ready to compute and transform our variables to their respective WoE. We are going to use two functions to do this (and show that it works with an example):
```{r transwoe}
computaWoE <- function(variable,datos=X.tbl,target = "bad"){
datos$variable <- datos[[variable]]
datos$target <- datos[[target]]
output <- datos %>% dplyr::mutate(totalB = sum(target), totalG = n() - totalB) %>%
group_by(variable) %>% dplyr::summarise(Bad = sum(target), Good = sum(1-target), Total = n(),
totalB = max(totalB), totalG = max(totalG)) %>%
ungroup() %>% dplyr::transmute(variable=variable,WoE = 100*log( (Good/totalG) / (Bad/totalB)))
columnas <- colnames(output)
columnas[1] <- c(variable)
colnames(output) <- columnas
output
}
transformaWoE <- function(variable,datos=X.tbl,target = "bad"){
fact <- datos[[variable]]
levels(fact)[computaWoE(variable)[[1]]] <- computaWoE(variable,datos=datos)$WoE
fact
}
computaWoE("age")
length(transformaWoE("debtRatio"))
```
It is always useful to explore the transformed variables WoE in the same scale, as it is an indication os predictability.
```{r woeplot,fig.width=9,fig.height=14}
#Visualicemos los WoE
varWoE <- list(variable = c(), indice = c(),WoE = c())
for (i in seq_along(variables)){
extrae <-computaWoE(variables[i])
varWoE$variable <- c(varWoE$variable,rep(variables[i],length(extrae$WoE)))
varWoE$indice <- c(varWoE$indice,1:length(extrae$WoE))
varWoE$WoE <- c(varWoE$WoE,extrae$WoE)
}
varWoE.tbl <- as_tibble(data.frame(varWoE))
ggplot(varWoE.tbl,aes(x=indice,y=WoE)) +
geom_col() + xlab("WoE de cada variable, misma escala") + theme(
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
facet_wrap(~variable,ncol=3,scales="free_x")
```
Let us construct our final dataset which contains the WoE for every variable to include in our model, this can be doe succinctly with the __purrr__ package in __R__ and the map function, as follows:
```{r finaldataset}
res <- purrr::map(variables,safely(transformaWoE)) %>% purrr::map("result")
str(res)
data.tbl <- as_tibble(as.data.frame(res))
colnames(data.tbl) <- variables
#remove factors and keep them as numeric
data.tbl <- purrr::map(data.tbl,varhandle::unfactor)
data.tbl<- as_tibble(as.data.frame(data.tbl))
data.tbl$bad <- X.tbl$bad
str(data.tbl)
```
Seems we are ready to build our model!. We are going to use a logistic regression to show results and different metrics of performance.
```{r model}
modFit <- train(as.factor(bad)~.,data=data.tbl,method="glm", family="binomial")
summary(modFit$finalModel)
```
Our model fitted well. Since we have transformed the variables to their WoE all Beta Coefficients have the same negative sign, as higher WoE leads to lower risk individuals. From the z-values of each coefficient we can derive the importance of the variable, but that is also shown with the varImp function:
```{r varimp}
varImp(modFit)
```
Same results as above. The statistics that describe our model are shown from a confusionMatrix output:
```{r confm}
pred <- predict(modFit,data.tbl)
score <-predict(modFit,data.tbl,type="prob")
colnames(score) <- c("pBueno","pMalo")
confusionMatrix(pred,data.tbl$bad)
```
As the sample is highly unbalanced in the target variable, our Accuracy leads us to believe we've fitted a very good model when in fact it is not as strong as it seems. Kappa is a better indicator of fitness for unbalanced samples and it is not very strong, but still useful.
Next in line is to visualize the fit of our model, we can use our previous function to plot the training sample:
```{r plotb}
data.tbl$pBueno <- score$pBueno
data.tbl$pMalo <- score$pMalo
graf_biv("pMalo",datos=data.tbl,grupos=30)
```
Not bad! Most Risk Managers are familiar with the Kolmogorov-Smirnov statistics, the ROC and it's Area Under the Curve (AUC). Let us obtain these statistics:
```{r statistics}
df.p <- data.tbl[order(data.tbl$pMalo),]
df.p$cumBad <- cumsum(df.p$bad) / sum(df.p$bad)
df.p$cumGood <- cumsum(1 - df.p$bad) / (dim(df.p)[1] - sum(df.p$bad))
ggplot(df.p,aes(cumBad,cumGood)) + geom_path(col="black") +
geom_segment(x = 0, xend = 1, y = 0, yend = 1, col="grey") + xlim(0,1) + ylim(0,1) +
xlab("Specificity") + ylab("Sensitivity") + ggtitle("Curva ROC")
#ROC con fórmula:
modFit$ROC <- 1-(sum(df.p$cumBad/length(df.p$cumBad)) - sum(df.p$cumGood/length(df.p$cumGood)) + 0.5)
print(paste0("AUC: ",round(modFit$ROC*100,2),"%"))
print(paste0("KS: ",round(max(abs(df.p$cumBad - df.p$cumGood))*100,2),"%"))
```
## Testing Data
An issue with the current code is that our transformation of the data into WoE is _dependent_ on the cuts and WoE of our training sample, thus we need to map there same groups in our testing dataset to the WoE calculated in our traning dataset (which can be quite cumbersome). To accomplish this first let us obtain the same groups (coded as factors in __R__).
```{r testing}
testing$mIncome[testing$mIncome<0] <- 0
XTest.tbl <- as_tibble(data.frame(list(bad=testing$bad,
revUtilUnsec = cut2(testing$revUtilUnsec,g=15),
age = cut2(testing$age,g=13),
n30_59dpd_nw = cut2(testing$n30_59dpd_nw,cuts=c(0,1,2,3)),
mIncome=cut2(testing$mIncome,cuts=c(0,500,1250,1500,2000,3000,4000,5000,6000,7000,8000,9000)),
debtRatio = cut2(testing$debtRatio,cuts=c(0,0.00001,.4,.6,.7,.8,.9,1)),
nOpenTrades = cut2(testing$nOpenTrades,cuts=c(0,1,2,3,4,5)),
n90dlate = cut2(testing$n90dlate,cuts=c(0,1,2,3)),
nREstate = cut2(testing$nREstate,cuts=c(0,1,2,3)),
n60_89dpd_nw = cut2(testing$n60_89dpd_nw,cuts=c(0,1,2,3)),
nDependents = cut2(testing$nDependents,cuts=c(0,1,2,3,4))
)
))
#Transformamos los "NA" en "-1" para mantener dentro de los factores
XTest.tbl$nDependents<-factor(XTest.tbl$nDependents, levels = levels(addNA(XTest.tbl$nDependents)), labels = c(levels(XTest.tbl$nDependents), -1), exclude = NULL)
XTest.tbl$mIncome<-factor(XTest.tbl$mIncome, levels = levels(addNA(XTest.tbl$mIncome)), labels = c(levels(XTest.tbl$mIncome), -1), exclude = NULL)
```
And from here we can _map_ the WoEs obtaining in our previous dataset:
```{r nuevotest,warning=FALSE, error=FALSE,message=FALSE,echo=FALSE,results='hide',fig.keep='all'}
cortaTest <- function(variable,datos=XTest.tbl,target = "bad"){
var <- data.frame(XTest.tbl[[variable]])
colnames(var) <- variable
var[,1] <- as.numeric(var[,1])
woes <- data.frame(computaWoE(variable))
woes[,1]<- as.numeric(woes[,1])
transformada <- left_join(var,woes)
colnames(transformada)<-c("x",variable)
transformada[[variable]]
}
previo <- purrr::map(variables,safely(cortaTest)) %>% purrr::map("result")
dataT.tbl <- as_tibble(data.frame(previo))
colnames(dataT.tbl) <-variables
str(dataT.tbl)
sum(is.na(dataT.tbl))
dataT.tbl$bad <- testing$bad
```
And it's all done. We can evaluate our model with our testing dataset to measure the effectiveness of our model.
```{r tconfm}
pred <- predict(modFit,dataT.tbl)
score <-predict(modFit,dataT.tbl,type="prob")
colnames(score) <- c("pBueno","pMalo")
confusionMatrix(pred,dataT.tbl$bad)
```
```{r tplotb}
dataT.tbl$pBueno <- score$pBueno
dataT.tbl$pMalo <- score$pMalo
graf_biv("pMalo",datos=dataT.tbl,grupos=30)
```
```{r tstatistics}
df.p <- dataT.tbl[order(dataT.tbl$pMalo),]
df.p$cumBad <- cumsum(df.p$bad) / sum(df.p$bad)
df.p$cumGood <- cumsum(1 - df.p$bad) / (dim(df.p)[1] - sum(df.p$bad))
ggplot(df.p,aes(cumBad,cumGood)) + geom_path(col="black") +
geom_segment(x = 0, xend = 1, y = 0, yend = 1, col="grey") + xlim(0,1) + ylim(0,1) +
xlab("Specificity") + ylab("Sensitivity") + ggtitle("Curva ROC")
#ROC con fórmula:
modFit$ROC <- 1-(sum(df.p$cumBad/length(df.p$cumBad)) - sum(df.p$cumGood/length(df.p$cumGood)) + 0.5)
print(paste0("AUC: ",round(modFit$ROC*100,2),"%"))
print(paste0("KS: ",round(max(abs(df.p$cumBad - df.p$cumGood))*100,2),"%"))
```
This can be done iteratively selection different partitions into testing and training to analyze the stability of the fit and coefficients.
## Scaling to a scorecard
To scale our results to obtain points to add up can be donde from a linear transformation of our results, but right now I'll leave that out of the scope of this entry. Obviously, if you're interested in this step of the process feel free to contact us to discuss the issue.<file_sep>/Regression/Stock Picking in R.Rmd
---
title: "Stock Picking in R"
author: "<NAME>"
date: "16 de noviembre de 2017"
output:
prettydoc::html_pretty:
theme: cayman
highlight: github
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(data.table)
library(readr)
library(dplyr)
library(lubridate)
library(tidyr)
library(reshape2)
library(stringr)
library(lazyeval)
library(knitr)
library(kernlab)
library(lazyeval)
library(ggplot2)
library(glue)
library(quadprog)
library(purrr)
library(caret)
library(quantmod)
library(ISLR)
library(forecast)
library(Hmisc)
library(gridExtra)
library(optimx)
library(glue)
library(purrr)
library(caret)
library(quantmod)
library(ISLR)
library(forecast)
library(rattle)
library(prettydoc)
library(DescTools)
library(DescToolsAddIns)
```
# Applying Regression to stock returns in R
### Introduction.
When faced with the challenge to outperform the market (that is, to obtain abnormal returns consistently through time, not explained by the systematic risk taken), the paths that can be taken are plenty and very diverse in nature. If the market we are exploring is the equities market in particular, outperforming the market could be simplified as _picking the companies that will generate the greater returns_. I'm a firm believer that an exhaustive fundamental analysis of each of these companies would provide the investor with the knowledge to better allocate her resources, effectively obtaining this abnormal returns (also known in the industry as __Alpha__).
Fundamental analysis requires a great amount of expertise, as you must understand the industry, the economic enviroment of both the country and the company under analysis, and of course the idiosyncratic business model of every player in the sector. As you might have guessed, this is time consuming and can't (yet) be automated, so assigning an analyst to focus on a particular company and thoroughly study an investment recommendation should be done efficiently, i.e., not analysing every single company but some that may promise achiving greater returns.
This work is a follow up of our previous [Markowitz Efficient Frontier](https://mxcompfin.github.io/Markowitz/Markowitz.html) and some of our insights shown there will continue to be used here, so i would recomend you to read it quickly before moving forward.
### The Data: Structure and manipulation.
Out data set comes from [kaggle: New York Stock Exchange dataset](https://www.kaggle.com/dgawlik/nyse) again, but we are going to explore the different tables that are available, in particular, the dataset containing variables from financial statements and data related to the securities. Let us load these tables.
```{r loading_data,eval=TRUE, results="hide", error=FALSE, message=FALSE,warning=FALSE}
fundamentales <- read_delim("fundamentals.csv",delim = ",")
securities <- read_delim("securities.csv",delim = ",")
names(securities) <-c("ticker","security","SECFilings","GICS","industry","address","firstAdded","CIK")
str(securities)
```
When working with data like these datasets it is important to get familiar with the information contained and the structure of it. The following lines of code is an example of the different tests and summary tables that i was creating along the way of finding what kind of data we had and if any relevant data was missing (in the particular case of the fundamentals, the variable __for Year__ was very important and had missings) and in case of finding missings, could they be filled with enough confidence as to maintain the integrity of the data (my analysis concluded that the answer was YES!). This last point is very important, as keeping a couple of extra registers can have relevant impacts when the datasets are small.
```{r data_manip, eval=TRUE, results="hide",error=FALSE, message=FALSE,warning=FALSE}
#Analizamos la informacion que disponemos para seleccionar empresas
str(fundamentales)
head(fundamentales,6)
nombres <- names(fundamentales)
nombres[c(1,2,3)] <- c("obs","ticker","period")
nombres
names(fundamentales)<-nombres
#Exploramos el dataset de EEFF y observamos que existen 448 tickers únicos
group_by(fundamentales,ticker) %>%
summarise(numero = n()) %>%
arrange(ticker)
#Las fechas únicas de los EEFF son 162
group_by(fundamentales,period) %>%
summarise(numero = n()) %>%
arrange(desc(period))
#Pero la variable que nos permite identificar el año de los EEFF es For Year
group_by(fundamentales,`For Year`) %>%
summarise(numero = n()) %>%
arrange(desc(`For Year`))
fundamentales <- mutate(fundamentales,forYear = `For Year`)
dup <- group_by(fundamentales,ticker,forYear) %>%
summarise(numero = n()) %>%
arrange(desc(ticker,forYear)) %>%
ungroup() %>%
filter(!is.na(forYear)) %>%
filter(numero >= max(numero))
#lo que hemos detectado es que son muy pocas las empresas que no tienen info financiera
#y son aún menos las que tienen años repetidos (en realidad son 6)
veamos_dup <- filter(fundamentales,ticker %in% c((dup$ticker))) %>%
arrange(ticker,forYear)
as.data.frame(veamos_dup[,c("ticker","period","forYear")])
#corregimos el error detectado
fundamentales[fundamentales$ticker %in% c((dup$ticker)),]$forYear <- year(fundamentales[fundamentales$ticker %in% c((dup$ticker)),]$period)
fundamentales[fundamentales$ticker %in% c((dup$ticker)),c("ticker","period","forYear")]
fundamentales <- mutate(fundamentales,year=year(period),month=month(period))
missing <- group_by(fundamentales,ticker,forYear) %>%
summarise(numero = n()) %>%
arrange(desc(ticker,forYear)) %>%
ungroup() %>%
filter(is.na(forYear))
veamos_missing <- filter(fundamentales,ticker %in% c((missing$ticker))) %>%
arrange(ticker,forYear)
as_tibble(as.data.frame(list(veamos_missing[,c("ticker","period","forYear")],year=year(veamos_missing$period)))) %>%
group_by(ticker,year) %>%
summarise(n=n()) %>%
ungroup() %>%
filter(n >= 2)
corregir <- veamos_missing[!(veamos_missing$ticker %in% c("CERN","HBI","SNA","SWK")),]$ticker
corregir <- unique(corregir)
#corregimos el error detectado
fundamentales[fundamentales$ticker %in% c((corregir)),]$forYear <- year(fundamentales[fundamentales$ticker %in% c((corregir)),]$period)
missing <- group_by(fundamentales,ticker,forYear) %>%
summarise(numero = n()) %>%
arrange(desc(ticker,forYear)) %>%
ungroup() %>%
filter(is.na(forYear))
veamos_missing <- filter(fundamentales,ticker %in% c((missing$ticker))) %>%
arrange(ticker,forYear)
veamos_missing[,c("ticker","period","forYear")]
#corregimos el error detectado
fundamentales[(fundamentales$ticker %in% c("CERN","HBI","SWK") & is.na(fundamentales$forYear)),]$forYear <-2016
fundamentales[fundamentales$ticker %in% c("SNA"),]$forYear <- c(2013,2014,2015,2016)
sum(is.na(fundamentales$forYear))
#Comenzamos el análisis
fund_2015 <- group_by(fundamentales,ticker,forYear)
names(fund_2015)
#2,3,10,11,13,14,15,19,23,25,26,31,32,33,34,38,39,40,41,42,47,49,59,59,61,62,64,67,69,70,71,72,73,74,75,77,78,79,80,81
fund_2015 <- fund_2015[,(c(2,3,10,11,13,14,15,19,23,25,26,31,32,33,34,38,39,40,41,42,47,49,59,61,62,64,67,69,70,71,72,73,74,75,77,78,79,80,81))]
names(fund_2015)
comp <- cbind(names(fund_2015),c("ticker","period","CashRatio","Cash","CommonStocks","CostOfRevenue","CurrentRatio","EBIT","FixedAssets","GrossMargin","GrossProfit",
"Investments","Liabilities","LongTermDebt","LongTermInvestments","NetCashFlow","NCFOperations", "NCFFinancing","NCFInvesting","NetIncome","NonRItems","OperatingMargin","PreTaxMargin","ProfitMargin",
"QuickRatio","RetainedEarnings","STBtoCPLTB","TotalAssets","CurrentAssets","CurrentLiabilities","Equity","TotalLiabilities","LiabPlusEquity","Revenue","oldFY","EPS","SharesOutstanding","forYear","year"))
comp
names(fund_2015) <- c("ticker","period","CashRatio","Cash","CommonStocks","CostOfRevenue","CurrentRatio","EBIT","FixedAssets","GrossMargin","GrossProfit",
"Investments","Liabilities","LongTermDebt","LongTermInvestments","NetCashFlow","NCFOperations", "NCFFinancing","NCFInvesting","NetIncome","NonRItems","OperatingMargin","PreTaxMargin","ProfitMargin",
"QuickRatio","RetainedEarnings","STBtoCPLTB","TotalAssets","CurrentAssets","CurrentLiabilities","Equity","TotalLiabilities","LiabPlusEquity","Revenue","oldFY","EPS","SharesOutstanding","forYear","year")
names(fund_2015)
info <- inner_join(fund_2015,securities,by="ticker")
print(info)
str(info)
info <- mutate(info,GICS = factor(GICS),industry = factor(industry),SECFilings = factor(SECFilings),CIK=factor(CIK))
str(info)
```
Another important step in our data preparation was the renaming of relevant variables. If you plan to continue the analysis of this datasets you can obtain very different results just by adding variables that i decided to remove. The reason I'm keeping these subset only is because my plan is to build ratios rather than input the raw data, as it is common in the investment industry to do so to relativize the size of the financial statement accounts this way.
The next lines of code are related to our prices dataset. We need to estimate returns from these prices on each ticker and different periods. The rationale that we are going to apply to do this is the following:
1. Our financial statements are for periods ending December year 20XX
+ If we would use this information to decide on what companies to invest, we would look at the following year's return, thus:
2. We will estimate our returns for periods of 1 year, starting January 1st and ending December 31st for every year at out disposal, as well as their respective risk (standard deviation).
3. When including these variables into our dataset, we will also add our _"leadReturn"_ which corresponds to the performance of a specific company on the year _following_ the financial statements, i.e, our __Independent Variable__.
```{r precios, results="hide"}
precios <- read_delim("prices-split-adjusted.csv",delim = ",")
str(precios)
head(precios)
names(precios)[2] <- "ticker"
precios <- arrange(precios,ticker,date)
precio_ant <- c(0,precios$close[1:(dim(precios)[1]-1)])
ticker_ant <- c("0",precios$ticker[1:(dim(precios)[1]-1)])
ticker_sig <- c(precios$ticker[2:(dim(precios)[1])],"0")
nuevos_datos <- as_tibble(list(precio_ant=precio_ant,ticker_ant=ticker_ant,ticker = precios$ticker, ticker_sig = ticker_sig))
nuevos_datos<- nuevos_datos %>%
mutate(marca = ifelse((ticker_ant==ticker & ticker == ticker_sig),0,ifelse(ticker_ant==ticker,1,-1))) %>%
select(precio_ant,marca)
precios_n <- cbind(precios,nuevos_datos)
precios_n <- mutate(precios_n,return = ifelse(marca >=0,log(close/precio_ant),0),year = year(date),
month=month(date),day=day(date))
index<-100
for (i in 1:(dim(precios_n)[1])){
if (precios_n$marca[i]==-1){
index[i] <- 100
}
else{index[i]<- index[i-1]*(1+precios_n$return[i])}
}
precios_n <- cbind(precios_n,index)
head(precios_n)
```
```{r preciosss, results="hide"}
precios_y <- group_by(precios_n,year,ticker) %>%
mutate(inicio = first(index),final = last(index)) %>%
summarise(stddev = sd(return)*sqrt(252),inicio = min(inicio), final = max(final)) %>%
mutate(return = log(final/inicio)) %>%
ungroup()
lead_return <- dplyr::select(precios_y,year,ticker,return) %>%
dplyr::rename(forYear=year, leadReturn=return) %>%
mutate(yearLeadReturn=forYear,forYear = forYear - 1)
dplyr::rename(precios_y,yearReturn = return,yearStdDev = stddev)
info <- mutate(info,year_eeff =forYear)
base <- inner_join(info,precios_y,by=(c("ticker"="ticker","forYear"="year")))
base <- inner_join(base,lead_return,by=(c("ticker"="ticker","forYear"="forYear")))
print(base)
table(base$year_eeff)
```
### The model: Generalized Linear Regression with a classification approach.
After all the hard work of processing the data, at last we have arrived at a stage of finding a good model for our data. This next section will focus on the design, analysis and visualization of the variables that we want to introduce in the model.
Specifically, everytime I say model I have something like this in mind:
$R_{j,year_{t+1}} = \hat{\beta_0} + \sum_i^n\hat{\beta_i}X_{i,j}$
Where each $R_{j,year_{t+1}}$ corresponds to the return next year for company $j$ and $X_{i,j}$ represents a _feature_ of company $j$ in year $t$, or previous year.
#### Exploring the features
There are many differents graphs and tests that should be made to explore the features to include in your model, I'm going to give a few examples here but this part of the modeling is more an art than science: it takes time and inspiration.
Our first step is splitting the sample in a __training sample__, from which we will obtain the parameters of our model through estimation; and a __testing sample__, on which we will test our model's performance. It is worth noting that, statistically speaking, our _features_ are not independent (because we are sampling from the _same companies_ over different years). This will be addressed on further submissions, but bear with me on this as the purpose of this exercise is to show steps to create a model.
Aditionally to sampling, we'll construct some features as ratios coming from the financial statements and we will _winsorize_ them, which is explained [here] (https://en.wikipedia.org/wiki/Winsorizing).
```{r gnrt_sample1, results="hide"}
training <- base[base$year_eeff %in% c(2012,2013),]
testing <- base[!(base$year_eeff %in% c(2012,2013)),]
```
```{r gnrt_sample}
#Vamos a ir iterando nuestro algoritmo sobre distintas ventanas de tiempo
#Para ver qué sucede con el modelo
training <- base[base$year_eeff %in% c(2012,2013),]
testing <- base[!(base$year_eeff %in% c(2012,2013)),]
colSums(is.na(training))/dim(training)[1]*100
#Tratemos de construir algunas variables que nos hagan sentido para explicar los retornos futuros, en particular,
#Buscaremos
training <- mutate(training,leverage= TotalAssets/TotalLiabilities,debtToEquity = TotalLiabilities/Equity,
EBITtoAssets = EBIT/TotalAssets, EBITtoEquity = EBIT/Equity, NCFtoEquity = NetCashFlow/Equity,
InvestToRetainedEarnings = Investments/RetainedEarnings)
names(training)
#Windsorize at 5%
training <- mutate(training,
leverage= max(min(quantile(training$leverage,.95),leverage),quantile(training$leverage,.05)),
debtToEquity= max(min(quantile(training$debtToEquity,.95),debtToEquity),quantile(training$debtToEquity,.05)),
EBITtoAssets= max(min(quantile(training$EBITtoAssets,.95),EBITtoAssets),quantile(training$EBITtoAssets,.05)),
EBITtoEquity= max(min(quantile(training$EBITtoEquity,.95),EBITtoEquity),quantile(training$EBITtoEquity,.05)),
NCFtoEquity= max(min(quantile(training$NCFtoEquity,.95),NCFtoEquity),quantile(training$NCFtoEquity,.05)),
InvestToRetainedEarnings= max(min(quantile(training$InvestToRetainedEarnings,.95),InvestToRetainedEarnings),quantile(training$InvestToRetainedEarnings,.05))
)
```
Different exploration tools are available in R to visualize data. What we are looking for are features that have any relationship with our independent variable and also have familiar shapes. To observe relationships between variables we can always use a _featurePlot_.
```{r feaplot}
featurePlot(x=training[,c("leverage","debtToEquity","EBITtoAssets","EBITtoEquity")],y=training$leadReturn,plot="pairs")
```
Another example is a scatterplot with fitted linear models in it. In this case I'm splitting the training sample per year to observe if the relationship is the same both periods.
```{r qqplot,error=FALSE, message=FALSE,warning=FALSE}
qq <- qplot(leverage,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
```
This has to be done for differents features, I will spare you the code but not the plots!
```{r qqplot2,echo=FALSE,error=FALSE, message=FALSE,warning=FALSE}
qq <- qplot(debtToEquity,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(EBITtoAssets,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(EBITtoEquity,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(NCFtoEquity,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(OperatingMargin,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(PreTaxMargin,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(ProfitMargin,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(return,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
qq <- qplot(stddev,leadReturn,color = factor(forYear),data=training)
qq + geom_smooth(method = 'lm', formula = y~x)
```
Next, we are going to explore our features standarized, as we will input them in the model this way:
```{r scaling,results="hide"}
escalas <- preProcess(as.data.frame(training[,c(10,22,23,24,54:59)]),method=c("center","scale"))
training_esc <- predict(escalas,as.data.frame(training[,c(10,22,23,24,54:59)]))
training_esc <- as_tibble(training_esc)
```
Another useful R function to explore data is _Desc_:
```{r desc}
DescTools::Desc(training_esc)
```
Clearly, Investment to Earnings has issues on the distribution, further testing shows that it can't be incorporated in the model (very little variability). These and other conclusions can be made from these plots to understand what we are doing in the modeling stage.
When analyzing a continous response variable, sometimes it is also useful to define groups of it to study different distributions of the features for levels of the dependent variable.
```{r cat}
class_return <- cut2(training$leadReturn,g=3)
training <- cbind(training,class_return=class_return)
featurePlot(x = training[, c(10,22,23,24)],
y = training$class_return,
plot = "density",
## Pass in options to xyplot() to
## make it prettier
scales = list(x = list(relation="free"),
y = list(relation="free")),
adjust = 1.5,
pch = "|",
layout = c(4, 1),
auto.key = list(columns = 3))
featurePlot(x = training[, c(54:57)],
y = training$class_return,
plot = "box",
## Pass in options to xyplot() to
## make it prettier
scales = list(x = list(relation="free"),
y = list(relation="free")),
adjust = 1.5,
pch = "|",
layout = c(4, 1),
auto.key = list(columns = 3))
featurePlot(x = training[, c(58:59)],
y = training$class_return,
plot = "box",
## Pass in options to xyplot() to
## make it prettier
scales = list(x = list(relation="free"),
y = list(relation="free")),
adjust = 1.5,
pch = "|",
layout = c(2, 1),
auto.key = list(columns = 3))
```
#### Calibrating the model
If you're still reading this, at last it's time to model!
We are modeling a linear relationship to the data, the features included in the model come from our exploratory analysis. Our first attempt will only include financial data and GICS classification. Let's see how it comes out:
```{r model}
modFit_glm <- train(leadReturn~GrossMargin+OperatingMargin+PreTaxMargin+ProfitMargin+
leverage+ debtToEquity+EBITtoAssets+EBITtoEquity+NCFtoEquity+GICS,method="glm",preProcess=c("center","scale"),data=training)
summary(modFit_glm)
```
Not bad in any way, as some variables are statistically significant. The sign of the coefficients is open to discussion and should be taken to experts to understand why some are counter-intuitive (we prefer companies with lower Operating Margins, for example) but it isn't all lost, as sometimes asset managers invest in companies that aren't performing well in the short-term to profit big long-term.
Let us think for a minute what kind of model we are trying to obtain: as I said before, we aren't really interested in fitting our data to predict future returns explicitly, but rather use this predicted return as a ranking, relative to the rest of the stocks considered in our analysis, to _filter_ the companies that our best analysts will focus on.
Either way, our next steps always should be to test if the model is fitting the data correctly. To do this, I will attach some code but i won't dig deeper into it, it's left to the reader to understand (you can ask me, of course).
```{r statis_anal, eval=FALSE}
#Revisamos el ajuste del modelo, primero analizamos los puntos de high leverage
lev <- hat(model.matrix(modFit_glm$finalModel))
#se detectan un par, pero no muchos
plot(lev)
#A continuación analizamos los residuos estandarizados
res_student <- rstudent(modFit_glm$finalModel)
cook = cooks.distance(modFit_glm$finalModel)
plot(cook,ylab="Cooks distances")
points(which(lev>.2),cook[which(lev>.2)],col='red')
par(mfrow=c(1,3))
plot(training$GrossMargin, res_student, xlab="Gross Margin", ylab="Studentized Residuals")
plot(training$OperatingMargin, res_student,xlab="Operating Margin", ylab="Studentized Residuals")
plot(modFit_glm$finalModel$fitted.values, res_student,xlab="Valores Ajustados", ylab="Studentized Residuals")
par(mfrow=c(1,2))
qqnorm(res_student)
qqline(res_student)
hist(res_student, freq=FALSE,
main="Distribution of Residuals")
xfit<-seq(min(res_student),max(res_student),length=40)
yfit<-dnorm(xfit)
lines(xfit, yfit)
spreadLevelPlot(modFit_glm$finalModel)
```
Being said that, what we really want is use this model to predict a subset of companies that outperform. Let us explore the effectiveness of this model to find companies that, on average, outperform the others.
```{r,testin1}
#Ahora probemos cómo funciona en el futuro:
testing <- mutate(testing,leverage= TotalAssets/TotalLiabilities,debtToEquity = TotalLiabilities/Equity,
EBITtoAssets = EBIT/TotalAssets, EBITtoEquity = EBIT/Equity, NCFtoEquity = NetCashFlow/Equity,
InvestToRetainedEarnings = Investments/RetainedEarnings)
names(testing)
dim(testing)
length(predict(modFit_glm,testing))
testing[is.na(testing$InvestToRetainedEarnings),]$InvestToRetainedEarnings <- c(0,0)
port_predict <- data.frame(list(testing,return_pred = predict(modFit_glm,testing)))
port_predict <- as.tbl(port_predict)
port_predict <- group_by(port_predict,forYear) %>%
mutate(ranking = rank(return_pred),class = ifelse(ranking <=170,0,ifelse(ranking<=340,1,2))) %>%
ungroup()
port_predict$class <- factor(port_predict$class,labels=c("LP","MP","HP"))
#No funciona muy bien, ya que en el 2014 sí nos consigue el mejor portafolio pero no en el 2015.
port_predict %>% group_by(forYear,class) %>%
summarise(return = mean(leadReturn),minimo=min(leadReturn),maximo=max(leadReturn), std=sd(leadReturn))
```
That last table summarises our findings: We have ordered the stocks using financial data for years 2014 and 2015, and we have estimated the returns of these stocks for 2015 and 2016 respectively. What the table shows is that, for 2014, we are able to predict the Highest performing subset of the three, but in 2015 we do quite poorly.
After a lot of hard work (not shown here) we can conclude that we are missing a very important feature to our model: the past return of the stock. This past return isn't strong to predict future returns (Efficient Market Hypothesis guys) but it can help discriminate among stocks.
```{r model_return}
modFit_glm2 <- train(leadReturn~return+GrossMargin+OperatingMargin+PreTaxMargin+ProfitMargin+
leverage+ debtToEquity+EBITtoAssets+EBITtoEquity+NCFtoEquity
+GICS,method="glm",preProcess=c("center","scale"),data=training)
summary(modFit_glm2)
```
Always analyze the fitted model.
```{r review, eval=FALSE}
#Revisamos el ajuste del modelo, primero analizamos los puntos de high leverage
lev <- hat(model.matrix(modFit_glm2$finalModel))
#se detectan un par, pero no muchos
plot(lev)
#A continuación analizamos los residuos estandarizados
res_student <- rstudent(modFit_glm2$finalModel)
cook = cooks.distance(modFit_glm2$finalModel)
plot(cook,ylab="Cooks distances")
points(which(lev>.2),cook[which(lev>.2)],col='red')
par(mfrow=c(1,3))
plot(training$GrossMargin, res_student, xlab="Gross Margin", ylab="Studentized Residuals")
plot(training$OperatingMargin, res_student,xlab="Operating Margin", ylab="Studentized Residuals")
plot(modFit_glm2$finalModel$fitted.values, res_student,xlab="Valores Ajustados", ylab="Studentized Residuals")
par(mfrow=c(1,2))
qqnorm(res_student)
qqline(res_student)
hist(res_student, freq=FALSE,
main="Distribution of Residuals")
xfit<-seq(min(res_student),max(res_student),length=40)
yfit<-dnorm(xfit)
lines(xfit, yfit)
ggplot(aes(x=return,y=predict(modFit_glm2,testing),color=year_eeff),data=testing)+
geom_point() +
geom_smooth(method="lm") +
geom_abline(slope=1,intercept=0)
```
```{r final_result}
port_predict2 <- data.frame(list(testing,return_pred = predict(modFit_glm2,testing)))
port_predict2 <- as.tbl(port_predict2)
port_predict2 <- group_by(port_predict2,forYear) %>%
mutate(ranking = rank(return_pred),class = ifelse(ranking <=170,0,ifelse(ranking<=340,1,2))) %>%
ungroup()
port_predict2$class <- factor(port_predict2$class,labels=c("LP","MP","HP"))
as.data.frame(port_predict2 %>% group_by(forYear,class) %>%
summarise(n=n(),return = mean(leadReturn),minimo=min(leadReturn),maximo=max(leadReturn), std=sd(leadReturn), pseudo_Sharpe= return/std))
```
Eureka! This model can filter some stocks nicely. In a sense, in 2014 we managed to find 94 stocks than, on average, had a sharpe that was twice and trice as big as the other 2 groups. For 2014 we didn't do as well yet we managed to double the worst performing group's pseudo Sharpe (no risk free included).
Hope you guys enjoyed this work, if any questions arise let me know.<file_sep>/BlackLitterman/Black Litterman.R
#BlackLitterman
rm(list=ls())
gc()
library(tidyverse)
library(tidyquant)
library(quadprog)
#Loadstidyquant,tidyverse,lubridate,quantmod,TTR,andxts
#library(quantmod)
#quantitativefinance
library(ggplot2)
library(igraph)
tickers <- c('AC.MX','ALFAA.MX','ALPEKA.MX','ALSEA.MX','AMXL.MX','ASURB.MX',
'BIMBOA.MX','BOLSAA.MX','CEMEXCPO.MX','ELEKTRA.MX','FEMSAUBD.MX','GAPB.MX',
'GCARSOA1.MX','GENTERA.MX','GFINBURO.MX','GFNORTEO.MX','GFREGIOO.MX','GMEXICOB.MX',
'GRUMAB.MX','IENOVA.MX','KIMBERA.MX','KOFL.MX','LABB.MX','LALAB.MX','LIVEPOLC-1.MX',
'MEXCHEM.MX','NEMAKA.MX','OHLMEX.MX','OMAB.MX','PE&OLES.MX','PINFRA.MX',
'SANMEXB.MX','TLEVISACPO.MX','VOLARA.MX','WALMEX.MX')
tickers_gf <- c('BMV:AC', 'BMV:ALFAA', 'BMV:ALPEKA', 'BMV:ALSEA', 'BMV:AMXL', 'BMV:ASURB', 'BMV:BIMBOA',
'BMV:BOLSAA', 'BMV:CEMEXCPO', 'BMV:ELEKTRA', 'BMV:FEMSAUBD', 'BMV:GAPB', 'BMV:GCARSOA1', 'BMV:GENTERA',
'BMV:GFINBURO', 'BMV:GFNORTEO', 'BMV:GFREGIOO', 'BMV:GMEXICOB', 'BMV:GRUMAB', 'BMV:IENOVA', 'BMV:KIMBERA',
'BMV:KOFL', 'BMV:LABB', 'BMV:LALAB', 'BMV:LIVEPOLC-1', 'BMV:MEXCHEM', 'BMV:NEMAKA', 'BMV:OHLMEX',
'BMV:OMAB', 'BMV:PE&OLES', 'BMV:PINFRA', 'BMV:SANMEXB', 'BMV:TLEVISACPO', 'BMV:VOLARA', 'BMV:WALMEX')
mapeo_tickers <- cbind(tickers,tickers_gf)
Precios<- tickers %>%
tq_get(get="stock.prices",from="2013-01-01")
mexbol <- tq_get(c("^MXX"),get="stock.prices",from="2000-01-01")
?tq_get
mexbol %>%
ggplot(aes(x = date, y = adjusted)) +
geom_line(col = "darkblue", size = 1) +
labs(title = "Daily Stock Prices",
x = "", y = "Adjusted Prices", color = "") +
scale_y_continuous(labels = scales::dollar) + theme_tq()
mexbol_rend <- mexbol %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic") %>%
summarise(xbar = mean(monthly.returns)*12, vol = sd(monthly.returns), sharpe = (xbar - 0.065)/(vol*sqrt(12)))
cetes <- read_delim("C:/Users/Gerardo/Documents/Repository/BlackLitterman/cetes.csv",delim = ",",skip=17,na = c("", "NA","N/E"))
cetes$date <- as.Date(cetes$Fecha,format="%d/%m/%Y")
cetes <- select(cetes,date,SF282) %>%
filter(date >= "2000-01-01") %>%
mutate(rf_mens = SF282*28/36000)
eom <- function(date){
mes = month(date)
ano = year(date)
if (mes == 12){
fecha = 1010000 + (ano + 1)
}
else{
fecha = (mes+1)*1000000+10000+ano
}
return(mdy(fecha)-1)
}
cetes$date<-as.Date(sapply(cetes$date,eom))
cetes %>%
ggplot(aes(x = date, y = rf_mens)) +
geom_line(col = "darkblue", size = 1) +
labs(title = "Daily Stock Prices",
x = "", y = "Adjusted Prices", color = "") +
scale_y_continuous(labels = scales::percent) + theme_tq()
mexbol_mens <- mexbol %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic")
mexbol_mens$date<-as.Date(sapply(mexbol_mens$date,eom))
mexbol_mens <- inner_join(mexbol_mens,cetes,by='date') %>%
mutate(mktER = monthly.returns - rf_mens)
mexbol_mens %>% summarise(mean = mean(mktER)*12)
ggplot(aes(x=date,y=cumprod(1+mexbol_mens$monthly.returns)),data=mexbol_mens) +
geom_line() +
labs(title = "Cumulative Returns on Mexbol", x = "Time", y = "Cum. Returns", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 0, hjust = 1))
(tail(cumprod(1+mexbol_mens[mexbol_mens$date >= "2010-01-01",]$monthly.returns),1))^(1/8)-1
market_cap <- tq_get(tickers_gf,get="financials") %>%
filter(type=="BS") %>%
select(-annual) %>%
unnest() %>% filter(date=="2017-09-30", category == "Total Common Shares Outstanding")
CommonStock <- tq_get(tickers_gf,get="financials") %>%
filter(type=="BS") %>%
select(-annual) %>%
unnest() %>% filter(date=="2017-09-30", category == "Common Stock, Total")
cap_mercado <- left_join(as.tibble(mapeo_tickers),market_cap, by=c("tickers_gf"="symbol"))
ult_precio <- Precios %>% filter(date==max(date)) %>% select(symbol,close)
cap_mercado <- left_join(cap_mercado,ult_precio,by=c("tickers"="symbol"))
#Hubo que incluir un par a mano porque no están en Google Finance, oh dear!
cap_mercado$value[cap_mercado$tickers=="VOLARA.MX"] <- 877.856219
cap_mercado$value[cap_mercado$tickers=="PE&OLES.MX"] <- 397.475747
cap_mercado$value[cap_mercado$tickers=="TLEVISACPO.MX"] <- 2557.893922
cap_mercado$value[cap_mercado$tickers=="FEMSAUBD.MX"] <- 3347.57
cap_mercado$value[cap_mercado$tickers=="CEMEXCPO.MX"] <- 14565.082738
cap_mercado$value[cap_mercado$tickers=="KOFL.MX"] <- 7233.29
cap_mercado <- cap_mercado %>% mutate(market.cap = value*close)
cap_mercado %>%
ggplot(aes(tickers,market.cap)) +
geom_col(fill="grey") +
labs(title = "BMV 35 compañías", x = "", y="Market Capitalization (Millions)",col = "") +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
scale_y_continuous(labels = scales::dollar)
rend_mensuales <- Precios %>% group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic")
rend_mensuales$date <- as.Date(sapply(rend_mensuales$date,eom))
rend_mensuales <- inner_join(rend_mensuales,cetes,by='date')
rend_mensuales %>%
ggplot(aes(x = symbol, y = monthly.returns)) +
geom_boxplot(fill="lightblue") +
labs(title = "Monthly returns by company", x = "", y = "", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 60, hjust = 1))
rend_mensuales %>% summarise(
mean=mean(monthly.returns,na.rm=T),
sd = sd(monthly.returns,na.rm=T),
min=min(monthly.returns,na.rm=T),
p1 = quantile(monthly.returns,.01,na.rm=T),
p99 = quantile(monthly.returns,.99,na.rm=T),
maxi = max(monthly.returns,na.rm=T)) %>% ungroup() %>%
arrange(desc(maxi))
Precios[Precios$symbol %in% c("AC.MX","SANMEXB.MX","GRUMAB.MX"),] %>%
ggplot(aes(x = date, y = adjusted)) +
geom_line(col = "darkblue", size = 1) +
labs(title = "Daily Stock Prices",
x = "", y = "Adjusted Prices", color = "") +
facet_wrap(~ symbol, ncol = 4, scales = "free_y") +
scale_y_continuous(labels = scales::dollar) + theme_tq()
#Winsorizamos los rendimientos
rend_mensuales <-rend_mensuales %>%
filter(!(is.na(monthly.returns))) %>% group_by(symbol) %>%
mutate(maxMR = quantile(monthly.returns,.98),
minMR = quantile(monthly.returns,.02),
adj.monthly.returns = ifelse(monthly.returns > maxMR,maxMR,ifelse(monthly.returns < minMR,minMR,monthly.returns))) %>%
select(-maxMR,-minMR,-monthly.returns)
rend_mensuales %>%
ggplot(aes(x = symbol, y = adj.monthly.returns)) +
geom_boxplot(fill="lightblue") +
labs(title = "Winsorized Monthly returns by company", x = "", y = "", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 60, hjust = 1))
rend_mensuales %>%
summarise(Total = n(), xbar=mean(adj.monthly.returns,na.rm=T), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol, y = xbar, label=symbol)) + geom_text(size=3) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "Mean return", x = "Volatility")
rend_mensuales<- rend_mensuales %>%
mutate(monthly.ER = adj.monthly.returns - rf_mens)
rend_mensuales %>%
summarise(Total = n(), xbar=mean(monthly.ER,na.rm=T), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol, y = xbar, label=symbol)) + geom_text(size=3) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "Mean return", x = "Volatility")
matrix_rend <- rend_mensuales %>% select(symbol,date,adj.monthly.returns) %>%
spread(key="symbol",value="adj.monthly.returns")
cov_mens <- cov(as.matrix(matrix_rend[,-1]),use="pairwise.complete.obs")
R_mens <- cor(as.matrix(matrix_rend[,-1]),use="pairwise.complete.obs")
cov_mens[is.na(cov_mens)] <- 0
R_mens[is.na(R_mens)] <- 0
mkt.cap.adjust <- cap_mercado$market.cap
names(mkt.cap.adjust) <- cap_mercado$tickers
pesos_mercado <- mkt.cap.adjust/sum(mkt.cap.adjust,na.rm=T)
pesos_mercado[is.na(pesos_mercado)] <- 0
sum(pesos_mercado)
aversion_riesgo = mean(mexbol_mens$mktER)/var(mexbol_mens$monthly.returns)
retornosEsperados = aversion_riesgo*(cov_mens) %*% pesos_mercado
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol*sqrt(12), y = retornosEsperados*12, label=symbol)) + geom_text(size=2.5) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk and Return", subtitle="Monthly frequency (annualized)", y = "Implied CAPM excess return", x = "Volatility")
rend_mensuales %>%
summarise(Total = n(), xbar=mean(monthly.ER,na.rm=T)*12) %>%
ggplot(aes(x = xbar, y = retornosEsperados*12, label=symbol)) + geom_text(size=2.5) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Implied (Excess) Returns vs Historical", subtitle="Monthly frequency (annualized)", y = "Implied CAPM excess return", x = "Historical Excess Returns") +
geom_vline(xintercept = c(.02))
equal <- seq(1,1,length.out = (dim(cov_mens)[1]))
equal <- matrix(equal,ncol=1)
b<-1
min_var <- quadprog::solve.QP(cov_mens,pesos_mercado,equal,b,meq=1,factorized=T)
w_min_var <- min_var$solution
sum(w_min_var)
ret_minvar <- t(w_min_var) %*% retornosEsperados
risk_minvar <- t(w_min_var) %*% cov_mens %*% w_min_var
port_min_var <- data.frame(list(retorno = ret_minvar,riesgo=risk_minvar,symbol=c("min var")))
frontera <- port_min_var
restricciones <- matrix(cbind(equal,retornosEsperados),ncol=2)
weights_portfolios <- matrix(w_min_var,nrow=1)
colnames(weights_portfolios) <- colnames(cov_mens)
for (ret in seq(as.numeric(frontera[1,c("retorno")])*1.01,max(retornosEsperados)*2.5,length.out=60)){
b <- c(1,ret)
optimiza_ret <- quadprog::solve.QP(cov_mens,pesos_mercado,restricciones,b,meq=2,factorized=T)
nuevo <- data.frame(list(retorno=matrix(optimiza_ret$solution,nrow=1) %*% matrix(retornosEsperados,ncol=1),
riesgo=matrix(optimiza_ret$solution,nrow=1) %*% cov_mens %*% t(matrix(optimiza_ret$solution,nrow=1)),symbol="algo"))
frontera <- rbind(frontera,nuevo)
weights_portfolios <- rbind(weights_portfolios,matrix(optimiza_ret$solution,nrow=1))
}
portafolios <- data.frame(list(tickers = colnames(weights_portfolios),t(weights_portfolios)))
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol, y = retornosEsperados, label=symbol)) + geom_text(size=2.5) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "Implied CAPM returns", x = "Volatility") +
geom_line(aes(x=riesgo,y=retorno, color="red"), data=frontera, show.legend=F)
pesos <- matrix(optimiza_ret$solution,nrow=1)
colnames(pesos) <- colnames(cov_mens)
barplot(pesos,horiz=T,cex.names=0.5,las=2)
portafolios %>%
ggplot(aes(tickers,X10)) +
geom_col(fill="grey") +
labs(title = "BMV 35 compañías", x = "", y="Portfolio Allocation",col = "") +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
scale_y_continuous(labels = scales::percent)
# visualizamos las correlaciones (ojo: usamos la relación inversa por para que rojo sea 1 y blanco sea 0)
heatmap(sqrt(2*(1-R_mens)), symm = TRUE)
#Incorporando Views del Mercado Mexicano
#1 Televisa va a tener un desempeño del -1% (Conf. 75%)
#2 Los aeropuertos tendrán un desempeño inferior a los grupos financieros de 2% (50%)
#3 AC sobrepasará a KOFL en un 1% (Conf. 65%)
Q = matrix(c(-0.01,0.02,0.01),ncol = 1)
#Vectores de Views por orden
View1 <- matrix(0,nrow=1,ncol = length(colnames(cov_mens)))
View2 <- matrix(0,nrow=1,ncol = length(colnames(cov_mens)))
View3 <- matrix(0,nrow=1,ncol = length(colnames(cov_mens)))
colnames(View1) <- colnames(cov_mens)
colnames(View2) <- colnames(cov_mens)
colnames(View3) <- colnames(cov_mens)
View1[1,"TLEVISACPO.MX"] <- 1
View2[1,c("GAPB.MX","OMAB.MX","ASURB.MX")] <- c(-1/3,-1/3,-1/3)
View2[1,c("GFREGIOO.MX","SANMEXB.MX","GFNORTEO.MX","GFINBURO.MX","GENTERA.MX")] <- c(1/5,1/5,1/5,1/5,1/5)
View3[1,"AC.MX"] <- 1
View3[1,"KOFL.MX"] <- -1
P <- rbind(View1,View2,View3)
P
#Calculamos la varianza de Omega proporcional a la de nuestra matriz "prior"
varView1 <- View1 %*% cov_mens %*% t(View1)
varView2 <- View2 %*% cov_mens %*% t(View2)
varView3 <- View3 %*% cov_mens %*% t(View3)
#Tao = 1 /(Muestras - Activos)
Tao <- 1
Omega <- diag(c(varView1,varView2,varView3)*Tao,nrow=3,ncol=3)
Omega
#BlackLitterman retornos esperados
BLExpectedReturns <- solve(solve(Tao*cov_mens) + t(P) %*% solve(Omega) %*% P) %*% (solve(Tao*cov_mens)%*%retornosEsperados + t(P) %*% solve(Omega) %*% Q)
CovBL <- cov_mens + solve(solve(Tao*cov_mens) + t(P) %*% solve(Omega) %*% P)
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol, y = BLExpectedReturns, label=symbol)) + geom_text(size=2.5) +
scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent, limits =c(-.01,.01)) +
theme_tq() +
labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "Mean return", x = "Volatility")
#BL
equal <- seq(1,1,length.out = (dim(CovBL)[1]))
equal <- matrix(equal,ncol=1)
b<-1
min_var <- quadprog::solve.QP(CovBL,pesos_mercado,equal,b,meq=1,factorized=T)
w_min_var <- min_var$solution
sum(w_min_var)
ret_minvar <- t(w_min_var) %*% BLExpectedReturns
risk_minvar <- t(w_min_var) %*% CovBL %*% w_min_var
port_min_var <- data.frame(list(retorno = ret_minvar,riesgo=risk_minvar,symbol=c("min var")))
frontera <- port_min_var
restricciones <- matrix(cbind(equal,BLExpectedReturns),ncol=2)
weights_portfolios <- matrix(w_min_var,nrow=1)
colnames(weights_portfolios) <- colnames(CovBL)
for (ret in seq(as.numeric(frontera[1,c("retorno")])*1.01,max(BLExpectedReturns)*3.5,length.out=60)){
b <- c(1,ret)
optimiza_ret <- quadprog::solve.QP(CovBL,pesos_mercado,restricciones,b,meq=2,factorized=T)
nuevo <- data.frame(list(retorno=matrix(optimiza_ret$solution,nrow=1) %*% matrix(BLExpectedReturns,ncol=1),
riesgo=matrix(optimiza_ret$solution,nrow=1) %*% CovBL %*% t(matrix(optimiza_ret$solution,nrow=1)),symbol="algo"))
frontera <- rbind(frontera,nuevo)
weights_portfolios <- rbind(weights_portfolios,matrix(optimiza_ret$solution,nrow=1))
}
portafolios <- data.frame(list(tickers = colnames(weights_portfolios),t(weights_portfolios)))
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol, y = BLExpectedReturns, label=symbol)) + geom_text(size=2.5) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "BL Expected Returns", x = "Volatility") +
geom_line(aes(x=riesgo,y=retorno, color="red"), data=frontera, show.legend=F)
pesos <- matrix(optimiza_ret$solution,nrow=1)
colnames(pesos) <- colnames(CovBL)
barplot(pesos,horiz=T,cex.names=0.5,las=2)
barplot(as.matrix(portafolios[,3:8]))
portafolios %>%
ggplot(aes(tickers,X10)) +
geom_col(fill="grey") +
labs(title = "BMV 35 compañías", x = "", y="Portfolio Allocation",col = "") +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
scale_y_continuous(labels = scales::percent)<file_sep>/home.Rmd
---
title: "MXCompFin Computational Finance"
output:
prettydoc::html_pretty:
theme: cayman
highlight: github
---
## **MXCompFin**
**MXCompFin** is a project born in 2017 with the collaboration between <NAME> and <NAME>.
The main purposes of the project are:
1. **Educational purposes:** We're not here to make you rich but give you some insights about financial topics we consider interesting and/or relevants.
2. **Fill the gap:** We're looking to fill the gap between mathematical theory and computational implementation of financial models.
## **Disclaimer**
Use the material at your own risk, as stated above everything is for **educational purposes only**.
If you have any comments, feel free to contact us at:
<EMAIL>
## **Contents**
* [Downloading historical prices from Google Finance (**Python**)](https://mxcompfin.github.io/google_finance)
* [Neat implementation of Markowitz Efficient Frontier (**R**)](https://mxcompfin.github.io/Markowitz/Markowitz.html)
* [Filtering Stocks using a Regression Model (**R**)](https://mxcompfin.github.io/Regression/Stock_Picking_in_R.html)
* [Black Litterman on Real Stock Data (**R**)](https://mxcompfin.github.io/BlackLitterman/BlackLitterman.html)
* [Portfolio's Conditional Value-at-Risk Optimization (**Python**)](https://mxcompfin.github.io/CVaROptimization/CVaROptimization.html)
* [Credit Scoring for Consumer Credit (**R**)](https://mxcompfin.github.io/Scoring/CreditScoring.html)
<file_sep>/Markowitz/Markowitz.Rmd
---
title: "Markowitz efficient frontier in R"
author: "<NAME>"
date: "14 de noviembre de 2017"
output:
prettydoc::html_pretty:
theme: cayman
highlight: github
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(data.table)
library(readr)
library(dplyr)
library(lubridate)
library(tidyr)
library(reshape2)
library(stringr)
library(lazyeval)
library(knitr)
library(kernlab)
library(lazyeval)
library(ggplot2)
library(glue)
library(quadprog)
library(purrr)
library(caret)
library(quantmod)
library(ISLR)
library(forecast)
library(Hmisc)
library(gridExtra)
library(optimx)
library(prettydoc)
```
# Solving Markowitz's efficient frontier in R.
### Introduction.
Anyone interested in Finance has come across literature related to Modern Portfolio Theory and the relationship between returns and risk, best explained by <NAME> in 1952 in his Article [Portfolio Selection](http://onlinelibrary.wiley.com/doi/10.1111/j.1540-6261.1952.tb01525.x/full). I'm a firm believer in the importance of theory to fully understand a model, both from implementation stage to the use in investment decisions applied to real world problems.
What i've found harder to find is an implementation of the model that describes different issues faced by finance professionals when they are required (or curious) to find the efficient frontier given a set of prices of different securities beyond the lousy examples found on the internet with two or three assets only or even worse: in Excel.
The following sections will describe an implementation based on data from the securities in the New York Stock Exchange dataset found in [kaggle](https://www.kaggle.com/dgawlik/nyse) as an illustrative example of the versatility of R to handle medium sized datasets of prices. Along the way, i will describe some issues faced with each of the steps in the implementation that should be taken into consideration, as well as my personal thoughts on certain issues. Please feel free to share your ideas to the issues raised during this exercise and i will try to address them fully in further updates.
### A little bit of theory.
I'm not going to bore any reader on the theory behind this, but some notation needs to be introduced.
We model our assets by their expected return, $E[R]$ and their risk, which is expressed by their standard deviation, $\sigma$. Our investment decisions are expressed by investing 100% of our wealth in assets, where each particular investment represents a proportion of our total wealth. That is, we invest $w_i$ in $asset_i$ for every $i$, and we always maintain $\sum_{i=1}^{n}w_i=1$ as a condition of being _fully invested_.
A portfolio is constructed by investing in different assets. We can express the return and risk of our portfolio by the following equations:
1) $E[R_p] = \sum_{i=1}^{n}w_iE[R_i]$
2) $\sigma^2(R_p) = \sum_{i=1}^{n}w_i^2\sigma^2(R_i)+\sum_i\sum_{j\neq i}w_iw_j\sigma(R_i)\sigma(R_j)\rho_{ij}$
An efficient portfolio is one that maximizes return for a given level of risk. The task at hand is to select the weights ($w_i$) adequately to accomplish this.
### The Data, structure and manipulation.
Our dataset is very simple, it comes from Kaggle as mentioned before and right now the quality of the data is not of our concern. That means that the results that we will show are relevant to understand the Markowitz Model but the model we obtain shouldn't be taken to make any investment decisions (yet!).
```{r load_prices}
precios <- read_delim("prices-split-adjusted.csv",delim = ",")
str(precios)
head(precios)
names(precios)[2] <- "ticker"
length(unique(precios$ticker))
min(precios$date)
max(precios$date)
```
Here i renamed the __Symbol__ column as __ticker__ because i feel more confortable working with that name. It is always best to modify column names for ones that are easier for you to understand. Our dataset consists of 501 different tickers over the last seven years.
Our first manipulations consist in the construction of auxiliary columns, which could be maintained as independent vectors (using the right indexing in R there is no need to merge into a DataFrame) but I prefer to have one dataset with all the relevant information.
We will lag our close price and use different lags of the ticker, after properly sorting the dataset, to calculate the daily returns in our data. A purist would have made some analysis on the data prior to this step, but i'm working on the assumption of data quality of acceptable levels. Our newer variables help us identify when a ticker starts, when it ends and it has returns for every day in our sample.
Additionally, we include a variable called __index__ which starts at the beggining of each ticker and _accumulates_ returns. This variable is very helpful when estimating Holding Period Returns (HPR) of different lengths, as you only need to divide the ending point over the beggining point (math of this is left to the reader to demonstrate).
```{r new_dataset}
precios <- arrange(precios,ticker,date)
precio_ant <- c(0,precios$close[1:(dim(precios)[1]-1)])
ticker_ant <- c("0",precios$ticker[1:(dim(precios)[1]-1)])
ticker_sig <- c(precios$ticker[2:(dim(precios)[1])],"0")
nuevos_datos <- as_tibble(list(precio_ant=precio_ant,ticker_ant=ticker_ant,ticker = precios$ticker, ticker_sig = ticker_sig))
nuevos_datos<- nuevos_datos %>%
mutate(marca = ifelse((ticker_ant==ticker & ticker == ticker_sig),0,ifelse(ticker_ant==ticker,1,-1))) %>%
select(precio_ant,marca)
precios_n <- cbind(precios,nuevos_datos)
precios_n <- mutate(precios_n,return = ifelse(marca >=0,log(close/precio_ant),0),year = year(date),
month=month(date),day=day(date))
index<-100
for (i in 1:(dim(precios_n)[1])){
if (precios_n$marca[i]==-1){
index[i] <- 100
}
else{index[i]<- index[i-1]*(1+precios_n$return[i])}
}
precios_n <- cbind(precios_n,index)
head(precios_n)
```
With our current dataset, it is possible to explore the performance of any particular ticker by plotting the index vs time.
```{r time_series, echo=FALSE}
precios_n[precios_n$ticker=="NFLX",] %>%
ggplot(aes(x=date,y=index)) +
geom_line()
```
Also, it might be interesting to analyze the distribution of returns:
```{r distribution}
precios_n[precios_n$ticker=="NFLX",] %>%
ggplot(aes(x=return)) +
geom_histogram(bins=70) +
xlab("Daily Returns Netflix") +
ylab("Count")+
theme_bw()
```
But what we really are interested in is not this but the efficient frontier, so let's move on.
### The Variance-Covariance Matrix
There are different approaches to solving for the efficient frontier. The Variance-Covariance Matrix of the returns could be estimated by different methods and for different lengths of time. It is important to notice that, for estimating this matrix for many assets, the amount of error increases as the number of parameters estimated is $\frac{n(n-1)}{2}$.
Here, we are going to stay away from all that and focus on the implementation. Using R cov function, we will estimate the daily returns VarCovar matrix. the _use_ parameter controls for missing values, as it will estimate the Covariance pairwise with all available data (pretty neat).
Another issue with Markowitz implementation comes from our _Expected Returns_, remember that _Expected_ means that they should incorporate our views. For this exercise, we will our our historical averages but trust me, this is not smart nor correct.
```{r covar}
matrixd <- select(precios_n,year,month,day,ticker,return) %>%
spread(key=ticker,value=return) %>%
arrange(year,month,day)
cov_matd <- cov(matrixd[,-c(1,2,3)],use="pairwise.complete.obs")
ret_mediasd <- colMeans(matrixd[,-c(1,2,3)],na.rm=T)
```
To find our portfolio of minimum variance, first we must establish our _fully invested_ constraint. This is incorporated in our model by a vector of $1's$ that should be exactly $1$ when finding our solution. Notice that, for the time being, we aren't imposing any restriction on short sales (if you're not familiar with this concept, google always has the answer).
Let's define our weights vector and constraints:
```{r parameters}
weights <- 0
weights[1:length(ret_mediasd)] <- 1/length(ret_mediasd)
equal <- seq(1,1,length.out = (dim(cov_matd)[1]))
weights <- matrix(weights,ncol=1)
equal <- matrix(equal,ncol=1)
b<-1
```
And we are all set up to start optimizing in search of our efficient frontier!.
### At last, the Efficient Frontier.
Let us begin introducing Quadratic Programming, which refers to solving a particular type of mathematical problems where we want to minimize (or maximize) a quadratic function subject to linear constraints. in particular, we look for solutions to the following problem:
minimize $\frac{1}{2}w^TQw+c^Tw$
subject to $Aw = b$
This is the particular case for our problem, as we haven't added many constraints nor we have any that isn't an equality.
To solve this, R has the following function:
```{r minvar}
min_var <- solve.QP(cov_matd,weights,equal,b,meq=1,factorized=T)
w_min_var <- min_var$solution
sum(w_min_var)
```
This is our first solution!
What we have done is: Find the weights $w_i$ for each $asset_i$ that minimize our portfolio variance, subject to being _fully invested_.
Now, let us use some visualization to understand what we have done.
If we plot our assets in a plane where return is a function of risk, we have:
```{r allassets}
inst_ret_riesgo <- data.frame(list(retorno =ret_mediasd*360,riesgo =sqrt(diag(cov_matd)*(252)) ))
retornos <- matrix(ret_mediasd*360, ncol=1)
restricciones <- matrix(cbind(equal,retornos),ncol=2)
frontera <- matrix(0,nrow=1,ncol=2)
frontera[1,c(1,2)] <- c(matrix(w_min_var,nrow=1) %*% matrix(ret_mediasd,ncol=1)*360,matrix(w_min_var,nrow=1) %*% cov_matd %*% t(matrix(w_min_var,nrow=1))*sqrt(252))
inst_ret_riesgo %>%
ggplot(aes(x=riesgo,y=retorno)) +
ylim(c(-.4,0.7)) +
xlim(c(0,1)) +
xlab("Annualized Standard Deviation") +
ylab("Expected Return") +
geom_point() +
geom_point(data=data.frame(list(riesgo=frontera[1,2],retorno=frontera[1,1])),aes(x=riesgo,y=retorno,color="red"),show.legend=F) +
geom_text(data = data.frame(list(riesgo=frontera[1,2],retorno=frontera[1,1])), aes(label = "Min. \n Var."),
vjust = "inward", hjust = "inward")
```
The next step is the most important one, as we are going to generate a couple of matrices to store optimization results from our model.
We will store our weights in a matrix called __p_weights__ which will also contain the risk and return of the portfolio. The risk and return will be stored in __frontera__ and our loop is an optimization that adds a constraint to the problem: we will increase the return that we want to achieve and the optimization will help us minimize the variance of the portfolio that achieves such return. Beware of the plot, as out returns axis range has changed.
```{r efficient_frontier}
frontera <- matrix(0,nrow=1,ncol=2)
frontera[1,c(1,2)] <- c(matrix(w_min_var,nrow=1) %*% matrix(ret_mediasd,ncol=1)*360,matrix(w_min_var,nrow=1) %*% cov_matd %*% t(matrix(w_min_var,nrow=1))*sqrt(252))
p_weights <- matrix(c(frontera,w_min_var),ncol=length(c(frontera,w_min_var)))
colnames(p_weights) <- c("retp","riesgop",colnames(cov_matd))
for (ret in seq(frontera[1,1]*1.01,5.8,length.out=60)){
b <- c(1,ret)
optimiza_ret <- solve.QP(cov_matd,weights,restricciones,b,meq=2,factorized=T)
frontera <- rbind(frontera,c(matrix(optimiza_ret$solution,nrow=1) %*% matrix(ret_mediasd,ncol=1)*360,matrix(optimiza_ret$solution,nrow=1) %*% cov_matd %*% t(matrix(optimiza_ret$solution,nrow=1))*sqrt(252)))
p_weights <- rbind(p_weights,c(c(matrix(optimiza_ret$solution,nrow=1) %*% matrix(ret_mediasd,ncol=1)*360,matrix(optimiza_ret$solution,nrow=1) %*% cov_matd %*% t(matrix(optimiza_ret$solution,nrow=1))*sqrt(252)),optimiza_ret$solution))
}
front_ef <- data.frame(list(retp = frontera[,1],riesgop = frontera[,2]))
#y graficamos la frontera eficiente con los instrumentos obtenidos
inst_ret_riesgo %>%
ggplot(aes(x=riesgo,y=retorno)) +
ylim(c(-.4,6)) +
xlab("Annualized Standard Deviation") +
ylab("Expected Return") +
ggtitle("Markowitz Efficient Frontier") +
geom_point() +
geom_point(data=data.frame(list(riesgo=frontera[1,2],retorno=frontera[1,1])),aes(x=riesgo,y=retorno,color="red"),show.legend=F) +
geom_text(data = data.frame(list(riesgo=frontera[1,2],retorno=frontera[1,1])), aes(label = "Min. \n Var."),
vjust = "inward", hjust = "inward") +
geom_path(data=front_ef,size=1,aes(x=riesgop,y=retp, color="red"),show.legend=F)
```
Hope you enjoyed the ride from the data to the Efficient Frontier. Next are some different implementations of the model using a variaty of constraints and approaches to estimating the Variance-Covariance Matrix. Stay tuned.<file_sep>/BlackLitterman/BlackLitterman.Rmd
---
title: "Black Litterman"
author: "<NAME>"
date: "December 2017"
output:
prettydoc::html_pretty:
theme: cayman
highlight: github
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(tidyquant)
library(quadprog)
library(ggplot2)
library(igraph)
library(reshape2)
eom <- function(date){
mes = month(date)
ano = year(date)
if (mes == 12){
fecha = 1010000 + (ano + 1)
}
else{
fecha = (mes+1)*1000000+10000+ano
}
return(mdy(fecha)-1)
}
```
## <NAME> - A Bayesian approach to asset allocation
Mean-variance optimization makes sense when explained conceptually, if you're confortable with the principles outlined by modern portfolio theory. The unsolvable questions arise when applying the precepts of this framework in real world application. Asset managers need to input Expected Returns into a model and, through a Variance-Covariance Matrix, obtain efficient portfolios. Variance-Covariance Matrix can be obtained from historical data, and assumptions of it's persistence through time is often made. Expected Returns, on the other hand, are extremely difficult tu estimate.
In real world settings, applying the Markowitz model to data tends to overweight a few stocks and short another small subset in really high proportions, which is very counterintuitive to the portfolio manager. Any asset with _negative_ expected returns is a shortable asset when solving for the efficient portfolio with no restrictions, and it is used to hedge a position for any other asset highly correlated to it with positive expected returns.
In the early 1990s, <NAME> and <NAME>, then working at Goldman Sachs, proposed a model from which an investor could derive the expected returns and modify them to take into account the investor's views on the returns on these assets. In an efficient market in equilibrium, the market capitalization of the assets represent the weights of the market portfolio and are closely related to their _expected excess returns_.
The following sections describe the application of the Black-Litterman Model to stocks in the Mexican Market, keeping the mathematics to a minimum, and focusing on the data manipulation and assumptions taken into consideration.
### Downloading price series for stocks in R.
To obtain financial data, R has a very neat package called _tidyquant_ which is the sum of the tidyverse packages and financial packages like _PerformanceAnalytics_ and _quantmod_. The following instructions are to define the tickers used in the extraction of the data:
```{r tickers}
tickers <- c('AC.MX','ALFAA.MX','ALPEKA.MX','ALSEA.MX','AMXL.MX','ASURB.MX',
'BIMBOA.MX','BOLSAA.MX','CEMEXCPO.MX','ELEKTRA.MX','FEMSAUBD.MX','GAPB.MX',
'GCARSOA1.MX','GENTERA.MX','GFINBURO.MX','GFNORTEO.MX','GFREGIOO.MX','GMEXICOB.MX',
'GRUMAB.MX','IENOVA.MX','KIMBERA.MX','KOFL.MX','LABB.MX','LALAB.MX','LIVEPOLC-1.MX',
'MEXCHEM.MX','NEMAKA.MX','OHLMEX.MX','OMAB.MX','PE&OLES.MX','PINFRA.MX',
'SANMEXB.MX','TLEVISACPO.MX','VOLARA.MX','WALMEX.MX')
tickers_gf <- c('BMV:AC', 'BMV:ALFAA', 'BMV:ALPEKA', 'BMV:ALSEA', 'BMV:AMXL', 'BMV:ASURB', 'BMV:BIMBOA','BMV:BOLSAA', 'BMV:CEMEXCPO', 'BMV:ELEKTRA', 'BMV:FEMSAUBD', 'BMV:GAPB', 'BMV:GCARSOA1','BMV:GENTERA','BMV:GFINBURO', 'BMV:GFNORTEO', 'BMV:GFREGIOO', 'BMV:GMEXICOB', 'BMV:GRUMAB', 'BMV:IENOVA', 'BMV:KIMBERA','BMV:KOFL', 'BMV:LABB', 'BMV:LALAB', 'BMV:LIVEPOLC-1', 'BMV:MEXCHEM', 'BMV:NEMAKA', 'BMV:OHLMEX','BMV:OMAB', 'BMV:PE&OLES', 'BMV:PINFRA', 'BMV:SANMEXB', 'BMV:TLEVISACPO', 'BMV:VOLARA','BMV:WALMEX')
mapeo_tickers <- cbind(tickers,tickers_gf)
Precios<- tickers %>%
tq_get(get="stock.prices",from="2007-01-01")
mexbol <- tq_get(c("^MXX"),get="stock.prices",from="2000-01-01")
```
From this data we can plot different visualizations of the market performance through time.
```{r IPC, echo=FALSE}
mexbol %>%
ggplot(aes(x = date, y = adjusted)) +
geom_line(col = "darkblue", size = 1) +
labs(title = "Mexbol historical level",
x = "Time", y = "Price", color = "") +
scale_y_continuous(labels = scales::dollar) + theme_tq()
```
Next in line is to estimate returns. We will work with monthly data to obtain our estimations for the Variance-Covariance Matrix and other interesting results. In Mexico, our Certificados de Tesorería are used as our Risk-Free asset.
```{r returns, message=FALSE, warning=FALSE}
mexbol_rend <- mexbol %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic") %>%
summarise(xbar = mean(monthly.returns)*12, vol = sd(monthly.returns), sharpe = (xbar - 0.065)/(vol*sqrt(12)))
cetes <- read_delim("C:/Users/Gerardo/Documents/Repository/BlackLitterman/cetes.csv",delim = ",",skip=17,na = c("", "NA","N/E"))
cetes$date <- as.Date(cetes$Fecha,format="%d/%m/%Y")
cetes <- select(cetes,date,SF282) %>%
filter(date >= "2000-01-01") %>%
mutate(rf_mens = SF282*28/36000)
cetes$date<-as.Date(sapply(cetes$date,eom))
cetes %>%
ggplot(aes(x = date, y = SF282/100)) +
geom_line(col = "darkblue", size = 1) +
labs(title = "CETES 28 Days Rate",
x = "", y = "Adjusted Prices", color = "") +
scale_y_continuous(labels = scales::percent) + theme_tq()
mexbol_mens <- mexbol %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic")
mexbol_mens$date<-as.Date(sapply(mexbol_mens$date,eom))
mexbol_mens <- inner_join(mexbol_mens,cetes,by='date') %>%
mutate(mktER = monthly.returns - rf_mens)
```
Now that we have our return series we can plot the cummulative returns on the mexbol from 2000 to date:
```{r cummexbol, message=FALSE, warning=FALSE}
ggplot(aes(x=date,y=cumprod(1+mexbol_mens$monthly.returns)),data=mexbol_mens) +
geom_line() +
labs(title = "Cumulative Returns on Mexbol", x = "Time", y = "Cum. Returns", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 0, hjust = 1))
```
Not bad for every peso invested since 2000, but what about 2010 to date? a Very poor performance as it can be shown.
```{r cummexbol2010, message=FALSE, warning=FALSE}
ggplot(aes(x=date,y=cumprod(1+monthly.returns)),data=mexbol_mens[mexbol_mens$date >= "2010-01-01",]) +
geom_line() +
labs(title = "Cumulative Returns on Mexbol", x = "Time", y = "Cum. Returns", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 0, hjust = 1))
print(paste0("CAGR:" ,round((tail(cumprod(1+mexbol_mens[mexbol_mens$date >= "2010-01-01",]$monthly.returns),1))^(1/8)-1,5)*100,"%"))
```
Next in line is to get our Market Capitalization for each company. To accomplish this, we will get our data from Google Finance and contrast it to the data in the BMV (Bolsa Mexicana de Valores). Some companies will have to be updated as the shares reported in Google Finance do not match the shares outstanding of the company.
```{r marketcap,message=FALSE, warning=FALSE}
market_cap <- tq_get(tickers_gf,get="financials") %>%
filter(type=="BS") %>%
select(-annual) %>%
unnest() %>% filter(date=="2017-09-30", category == "Total Common Shares Outstanding")
CommonStock <- tq_get(tickers_gf,get="financials") %>%
filter(type=="BS") %>%
select(-annual) %>%
unnest() %>% filter(date=="2017-09-30", category == "Common Stock, Total")
cap_mercado <- left_join(as.tibble(mapeo_tickers),market_cap, by=c("tickers_gf"="symbol"))
ult_precio <- Precios %>% filter(date==max(date)) %>% select(symbol,close)
cap_mercado <- left_join(cap_mercado,ult_precio,by=c("tickers"="symbol"))
#Hubo que incluir un par a mano porque no están en Google Finance, oh dear!
cap_mercado$value[cap_mercado$tickers=="VOLARA.MX"] <- 877.856219
cap_mercado$value[cap_mercado$tickers=="PE&OLES.MX"] <- 397.475747
cap_mercado$value[cap_mercado$tickers=="TLEVISACPO.MX"] <- 2557.893922
cap_mercado$value[cap_mercado$tickers=="FEMSAUBD.MX"] <- 3347.57
cap_mercado$value[cap_mercado$tickers=="CEMEXCPO.MX"] <- 14565.082738
cap_mercado$value[cap_mercado$tickers=="KOFL.MX"] <- 7233.29
cap_mercado <- cap_mercado %>% mutate(market.cap = value*close)
cap_mercado %>%
ggplot(aes(tickers,market.cap)) +
geom_col(fill="grey") +
labs(title = "BMV 35 compañías", x = "", y="Market Capitalization (Millions)",col = "") +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
scale_y_continuous(labels = scales::dollar)
mkt.cap.adjust <- cap_mercado$market.cap
names(mkt.cap.adjust) <- cap_mercado$tickers
pesos_mercado <- mkt.cap.adjust/sum(mkt.cap.adjust,na.rm=T)
pesos_mercado[is.na(pesos_mercado)] <- 0
sum(pesos_mercado)
```
We also need to manipulate our returns to explore if they make sense or not:
```{r returnos,message=FALSE, warning=FALSE}
rend_mensuales <- Precios %>% group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "arithmetic")
rend_mensuales$date <- as.Date(sapply(rend_mensuales$date,eom))
rend_mensuales <- inner_join(rend_mensuales,cetes,by='date')
rend_mensuales %>%
ggplot(aes(x = symbol, y = monthly.returns)) +
geom_boxplot(fill="lightblue") +
labs(title = "Monthly returns by company", x = "", y = "", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 60, hjust = 1))
rend_mensuales %>% summarise(
mean=round(mean(monthly.returns,na.rm=T),4),
sd = round(sd(monthly.returns,na.rm=T),4),
min=round(min(monthly.returns,na.rm=T),4),
p1 = round(quantile(monthly.returns,.01,na.rm=T),4),
p99 = round(quantile(monthly.returns,.99,na.rm=T),4),
maxi = round(max(monthly.returns,na.rm=T),4)) %>% ungroup() %>%
arrange(desc(maxi))
```
From our statistics we see that __AC.MX__ seems odd, further inspection would help detect errors:
```{r plotprices}
Precios[Precios$symbol %in% c("AC.MX","SANMEXB.MX","GRUMAB.MX"),] %>%
ggplot(aes(x = date, y = adjusted)) +
geom_line(col = "darkblue", size = 1) +
labs(title = "Daily Stock Prices",
x = "", y = "Adjusted Prices", color = "") +
facet_wrap(~ symbol, ncol = 4, scales = "free_y") +
scale_y_continuous(labels = scales::dollar) + theme_tq()+ theme(axis.text.x = element_text(angle = 0, hjust = 1))
```
Some of the prices are very odd, indeed. There are multiple ways of correcting this, but winsorizing is always helpful.
```{r windsorize}
#Winsorizamos los rendimientos
rend_mensuales <-rend_mensuales %>%
filter(!(is.na(monthly.returns))) %>% group_by(symbol) %>%
mutate(maxMR = quantile(monthly.returns,.98),
minMR = quantile(monthly.returns,.02),
adj.monthly.returns = ifelse(monthly.returns > maxMR,maxMR,ifelse(monthly.returns < minMR,minMR,monthly.returns))) %>%
select(-maxMR,-minMR,-monthly.returns)
rend_mensuales %>%
ggplot(aes(x = symbol, y = adj.monthly.returns)) +
geom_boxplot(fill="lightblue") +
labs(title = "Winsorized Monthly returns by company", x = "", y = "", col = "") +
scale_y_continuous(labels = scales::percent) + theme(axis.text.x = element_text(angle = 60, hjust = 1))
rend_mensuales %>%
summarise(Total = n(), xbar=mean(adj.monthly.returns,na.rm=T), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol, y = xbar, label=symbol)) + geom_text(size=3) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "Mean return", x = "Volatility")
rend_mensuales<- rend_mensuales %>%
mutate(monthly.ER = adj.monthly.returns - rf_mens)
```
There, problem fixed. Let us move forward to the black litterman implementation.
Our next step is to estimate our Variance-Covariance Matrix, as follows:
```{r varcovar}
matrix_rend <- rend_mensuales %>% select(symbol,date,adj.monthly.returns) %>%
spread(key="symbol",value="adj.monthly.returns")
cov_mens <- cov(as.matrix(matrix_rend[,-1]),use="pairwise.complete.obs")
cov_mens[is.na(cov_mens)] <- 0
```
And we are all set to allocate our resources using Black Litterman!.
### The parameters for Black Litterman.
I'm going to estimate the parameters for the BL model without much mathematics, but i will still outline the problem.
If we are an investor seeking to maximize our Utility from investing, we can formulate the following:
$$
U = w^t\Pi - (\frac{\lambda}{2})w^t\Sigma w
$$
where we have:
* $U$: is the Utility
* $w$: are the weights on each asset.
* $\Pi$: is a vector of Expected Returns.
* $\Sigma$: is the Variance-Covariance matrix.
* $\lambda$: is our risk-adversion factor.
It can be shown (I always wanted to do that) that our optimal solution must hold that:
$$
\Pi - \lambda\Sigma w = 0
$$
And thus, $\Pi = \lambda\Sigma w $.
Furthermore, we can derive our $\lambda$ and find that it is $\lambda = \frac{E[R_m]-R_f}{\sigma^2}$. We can estimate this from our historical data on the Mexbol and obtain the _Prior Returns_, $\Pi$.
```{r aversion_riesgo}
aversion_riesgo = mean(mexbol_mens$mktER)/var(mexbol_mens$monthly.returns)
print(paste0("Lambda is: " ,round(aversion_riesgo,2)))
retornosEsperados = aversion_riesgo*(cov_mens) %*% pesos_mercado
retornosEsperados[is.na(retornosEsperados)] <- 0
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = vol*sqrt(12), y = retornosEsperados*12, label=symbol)) + geom_text(size=2.5) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk and Return", subtitle="Monthly frequency (annualized)", y = "Implied CAPM excess return", x = "Volatility")
```
Our _Prior Excess Returns_ are the ones that, through Markowitz's optimization of Mean-Variance, would assign weights equal to Market Capitalization of each company. That is, these returns are derived from the current state of the Market.
We are going to use these returns to estimate our Posterior distribution of returns, based on our View of the Market. To do this, we employ Black Litterman's formula:
$$
E[R] = [(\tau\Sigma^{-1}) + P'\Omega^{-1}P]^{-1}[(\tau\Sigma^{-1})\Pi+P'\Omega^{-1}Q]
$$
A complex formula if you ask me, here we have:
* $E[R]$: is the posterior Expected Returns.
* $\tau$: is a scalar.
* $\Pi$: is a vector of Prior Expected Returns.
* $\Sigma$: is the Variance-Covariance matrix.
* $P$: Is a matrix with the assets involved in our Views.
* $\Omega$: is the uncertainty associated with our Views.
* $Q$: is the vector containing our Views.
So far, we have mentioned _Views_ quite a few times without explaining in detail what we mean by them: Views represent a conviction of the investor with a degree of confidence of certain events happening. To exemplify, we will have three particular Views in our model:
1. Televisa will underperform the market by 1% (75% Confidence).
2. The airports will underperform banks by 2% (50% Confidence).
3. In our bottlers industry, AC will outperform KOFL by 1% (65% Confidence).
This leads to expressing our Views through matrixes. To do this, we will first define our Matrices and fill the corresponding values.
```{r Views}
Q = matrix(c(-0.01,0.02,0.01),ncol = 1)
#Vectores de Views por orden
View1 <- matrix(0,nrow=1,ncol = length(colnames(cov_mens)))
View2 <- matrix(0,nrow=1,ncol = length(colnames(cov_mens)))
View3 <- matrix(0,nrow=1,ncol = length(colnames(cov_mens)))
colnames(View1) <- colnames(cov_mens)
colnames(View2) <- colnames(cov_mens)
colnames(View3) <- colnames(cov_mens)
View1[1,"TLEVISACPO.MX"] <- 1
View2[1,c("GAPB.MX","OMAB.MX","ASURB.MX")] <- c(-1/3,-1/3,-1/3)
View2[1,c("GFREGIOO.MX","SANMEXB.MX","GFNORTEO.MX","GFINBURO.MX","GENTERA.MX")] <- c(1/5,1/5,1/5,1/5,1/5)
View3[1,"AC.MX"] <- 1
View3[1,"KOFL.MX"] <- -1
P <- rbind(View1,View2,View3)
varView1 <- View1 %*% cov_mens %*% t(View1)
varView2 <- View2 %*% cov_mens %*% t(View2)
varView3 <- View3 %*% cov_mens %*% t(View3)
#Tao = 1 /(Muestras - Activos)
Tao <- (1/(59-35))
Omega <- diag(c(varView1,varView2,varView3)*Tao,nrow=3,ncol=3)
BLExpectedReturns <- solve(solve(Tao*cov_mens) + t(P) %*% solve(Omega) %*% P) %*% (solve(Tao*cov_mens)%*%retornosEsperados + t(P) %*% solve(Omega) %*% Q)
CovBL <- cov_mens + solve(solve(Tao*cov_mens) + t(P) %*% solve(Omega) %*% P)
```
With these results we have derived a different distribution for our Risk and Return space, shown in the following plot:
```{r graficasBL}
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = sqrt(diag(CovBL)*12), y = 12*BLExpectedReturns, label=symbol)) + geom_text(size=2.5) +
scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() +
labs(title = "Risk and Return", subtitle="monthly frequency (annualized)", y = "Black Litterman posterior Returns", x = "Volatility")
```
And now we can perform Mean-Variance optimization to find our optimal portfolios.
```{r FronteraBL}
equal <- seq(1,1,length.out = (dim(CovBL)[1]))
equal <- matrix(equal,ncol=1)
b<-1
min_var <- quadprog::solve.QP(CovBL,pesos_mercado,equal,b,meq=1,factorized=T)
w_min_var <- min_var$solution
ret_minvar <- t(w_min_var) %*% BLExpectedReturns
risk_minvar <- t(w_min_var) %*% CovBL %*% w_min_var
port_min_var <- data.frame(list(retorno = ret_minvar,riesgo=risk_minvar,symbol=c("Portafolio 1")))
frontera <- port_min_var
restricciones <- matrix(cbind(equal,BLExpectedReturns),ncol=2)
weights_portfolios <- matrix(w_min_var,nrow=1)
colnames(weights_portfolios) <- colnames(CovBL)
i <-2
for (ret in seq(as.numeric(frontera[1,c("retorno")])*1.01,max(BLExpectedReturns)*5.5,length.out=60)){
b <- c(1,ret)
optimiza_ret <- quadprog::solve.QP(CovBL,pesos_mercado,restricciones,b,meq=2,factorized=T)
nuevo <- data.frame(list(retorno=matrix(optimiza_ret$solution,nrow=1) %*% matrix(BLExpectedReturns,ncol=1),
riesgo=matrix(optimiza_ret$solution,nrow=1) %*% CovBL %*% t(matrix(optimiza_ret$solution,nrow=1)),symbol=paste0("Portafolio ",i)))
frontera <- rbind(frontera,nuevo)
weights_portfolios <- rbind(weights_portfolios,matrix(optimiza_ret$solution,nrow=1))
i <- i +1
}
portafolios <- data.frame(list(tickers = colnames(weights_portfolios),t(weights_portfolios)))
rend_mensuales %>%
summarise(Total = n(), vol=sd(adj.monthly.returns,na.rm=T)) %>%
ggplot(aes(x = sqrt(diag(CovBL)*12), y = BLExpectedReturns*12, label=symbol)) + geom_text(size=2.5) + scale_x_continuous(labels = scales::percent) + scale_y_continuous(labels = scales::percent) +
theme_tq() + labs(title = "Risk vs Return Tradeoff", subtitle="monthly frequency", y = "BL Expected Returns", x = "Volatility") +
geom_line(aes(x=riesgo*sqrt(12),y=retorno*12, color="red"), data=frontera, show.legend=F)
```
And that's how it's done! Let us compare some of the portfolios.
```{r allocation}
portafolios2 <- melt(portafolios[,c(1,2,5,10,20)], id.vars = "tickers")
portafolios2 %>%
ggplot(aes(x = tickers,y=value)) +
geom_col() +
facet_grid(variable ~ .) +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
scale_y_continuous(labels = scales::percent)
```
Here we are showing a couple portfolios, the minimum variance (X1), and higher-return ones.
There are a couple of points to make when analyzing these portfolios:
* First of all, we don't have _corner_ portfolios, that is, we have invested in almost every asset.
* When we want to achieve higher returns, we are consistently outweighting and underweighting different assets, but we keep our proportions.
* Our Views play a critical roll, but we aren't exactly following our Views without considering the relationship of all our assets. This is interesting when moving from a portfolio to a different allocation, as the change in asset weights seems continuous in a way.
Hope you enjoyed our exercise. Feel free to contact us if any questions arise!.
| 85f5eab0a38d5ffc741c4e0ea7bfb39c83349a3e | [
"R",
"RMarkdown"
] | 7 | RMarkdown | MXCompFin/MXCompFin.github.io | bd721240b7d31904de1a18fb1df48fec111dca31 | d7ef5fd598eed5e122e862ad98fef21299d0405e |
refs/heads/master | <repo_name>Viterbo/minecraft<file_sep>/README.md
sudo ln -s ${PWD}/minecraft.sh /usr/bin/minecraft
sudo apt-get install --no-install-recommends gnome-panel
gnome-desktop-item-edit ~/Escritorio/ --create-new
<file_sep>/minecraft.sh
#!/bin/bash
cd ~/Minecraft
java -jar Minecraft.jar | 5cd27f2dd4e68377ad420f56639e68c196bf1669 | [
"Markdown",
"Shell"
] | 2 | Markdown | Viterbo/minecraft | e5a77ed88f5d3e55ef64d0691e3d3c135fc34eb9 | f048f972977b1179b5374cc62b5fc342dbd01afd |
refs/heads/master | <repo_name>ugurozturk/SingleBeepSound<file_sep>/SingleBeep/Program.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using NAudio.Wave;
namespace SingleBeep
{
class Program
{
static async Task PlayBeepAsync(WaveOutEvent outputDevice)
{
await Task.Run(() =>
{
while (outputDevice.PlaybackState == PlaybackState.Playing)
{
}
});
}
static async Task RunSoundAsync()
{
var beeSoundLocalation = "D:\\beep.wav";
using (var audioFile = new AudioFileReader(beeSoundLocalation))
using (var outputDevice = new WaveOutEvent())
{
outputDevice.Init(audioFile);
outputDevice.Play();
await PlayBeepAsync(outputDevice);
}
}
static async Task Main(string[] args)
{
while (true)
{
System.Console.Write("Komut giriniz : ");
var commands = Console.ReadLine();
if (commands == "b")
{
await RunSoundAsync();
}
else if (commands == "exit")
{
break;
}
}
}
}
}
| 128baacf88dd8ad30eeadf2a71d6545bf433d1cd | [
"C#"
] | 1 | C# | ugurozturk/SingleBeepSound | ea68d9972b198c828ee4dda920e7c08738719bc9 | 456aa0560365a484bf24ed51c61b32b43201fee7 |
refs/heads/master | <repo_name>yashgurbani/hopfield-ws<file_sep>/graph-characterization.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import datetime
import matplotlib.pyplot as plt
import networkx as nx
n = 128
k = 20
p = 0
while (p <= 1):
filename = "_".join([str(n), str(k), str(p)])
name = filename + ".gexf"
g = nx.watts_strogatz_graph(128, 20, p)
nx.write_gexf(g, name)
p = p + 0.1
<file_sep>/phase-diagram/normal/visual/visual.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from random import choice
import datetime
import mpl_toolkits.axes_grid1 as axes_grid1
from tqdm import tqdm
import random
type = int(input('Enter network type: 1 for a fully connected network, 2 for a watts-strogatz network'))
n = int(input('Enter # of neurons'))
m = int(input('Enter # of memory states'))
if (type == 2):
k = int(input('Enter # of nearest neighbours k'))
p = float(input('Enter probability of rewiring p'))
MemoryMatrix = np.zeros((m, n))
W = np.zeros((n, n))
for a in range(0, m):
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
flip = round(0.25 * n)
Y = []
X = []
u = MemoryMatrix[1].copy() # copy target M to initial state
rs = random.sample(range(0, n), flip)
n_i = 10000
for z in list(rs): # randomly pick up 25 percent and flip them
u[z] = (MemoryMatrix[1][z] * -1)
if (type == 1):
g = nx.complete_graph(n)
if (type == 2):
g = nx.watts_strogatz_graph(n, k, p) # use for watts strogatz network
st = 0
for st in range(0, n):
g.nodes[st]['state'] = u[st]
alpha = (m/n)
# train the network with m memory states
for i, j in g.edges:
weight = 0
for zeta in range(0, m):
weight = weight + (MemoryMatrix[zeta][i] * MemoryMatrix[zeta][j])
g.edges[i, j]['weight'] = (weight / n)
W[i][j] = g.edges[i, j]['weight']
W[j][i] = W[i][j]
fig = plt.figure()
grid = axes_grid1.AxesGrid(
fig, 111, nrows_ncols=(1, 1), axes_pad = 0.5, cbar_location = "right",
cbar_mode="each", cbar_size="15%", cbar_pad="5%",)
im0 = grid[0].imshow(W, cmap='gray', interpolation='nearest')
grid.cbar_axes[0].colorbar(im0)
plt.savefig('/tmp/test.png', bbox_inches='tight', pad_inches=0.0, dpi=200,)
hamming_distance = np.zeros((n_i, m))
# evolve according to hopfield dynamics, n_i iterations
for z in range(0, n_i):
i = choice(list(g.nodes))
s = sum([g.edges[i, j]['weight'] * g.nodes[j]['state'] for j in g.neighbors(i)])
g.nodes[i]['state'] = 1 if s > 0 else -1 if s < 0 else g.nodes[i]['state']
for q in range(m):
for i in list(g.nodes):
hamming_distance [z, q] += (abs(g.nodes[i]['state'] - MemoryMatrix[q][i])/2)
z = z + 1
fig = plt.figure(figsize = (8, 8))
plt.plot(hamming_distance)
plt.xlabel('No of Iterations')
plt.ylabel('Hamming Distance')
plt.ylim([0, n])
plt.plot(hamming_distance)
#plt.legend(['pattern 0', 'pattern 1', 'pattern 2', 'pattern 3', 'pattern 4', 'pattern 5', 'pattern 6', 'pattern 7', 'pattern 8', 'pattern 9', 'pattern 10', 'pattern 11', 'pattern 12', 'pattern 13', 'pattern 14', 'pattern15', 'pattern16'], loc='best')
plt.show()
<file_sep>/excel.py
import numpy as np
import pandas as pd
df = pd.read_excel('Si2.xlsx')
numpy_matrix = df.as_matrix()
<file_sep>/phase-diagram/normal/visual/demo/demo.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from random import choice
from matplotlib import cm
import numpy as np
import networkx as nx
from random import choice
import datetime
from tqdm import tqdm
import random
type = int(input('Enter network type: 1 for a fully connected network, 2 for a watts-strogatz network'))
n = int(input('Enter # of neurons'))
m = int(input('Enter # of memory states'))
if (type == 2):
k = int(input('Enter # of nearest neighbours k'))
p = float(input('Enter probability of rewiring p'))
n_i = int(input('Enter # of iterations'))
MemoryMatrix = np.zeros((m, n))
W = np.zeros((n, n))
for a in range(0, m):
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
print(MemoryMatrix)
flip = round(0.25 * n)
Y = []
X = []
u = []
u = MemoryMatrix[1].copy() # copy target M to initial state
rs = random.sample(range(0, n), flip)
for z in list(rs): # randomly pick up 25 percent and flip them
u[z] = (MemoryMatrix[1][z] * -1)
if (type == 1):
g = nx.complete_graph(n)
if (type == 2):
g = nx.watts_strogatz_graph(n, k, p) # use for watts strogatz network
st = 0
for st in range(0, n):
g.nodes[st]['state'] = u[st]
alpha = (m/n)
if (n == 16):
g.pos = {}
for x in range(4):
for y in range(4):
g.pos[y * 4 + x] = (x, -y)
nx.draw(g, pos = g.pos, cmap = cm.jet, vmin = -1, vmax = 1, node_color = [g.nodes[i]['state'] for i in
g.nodes])
plt.show()
print ("Initial Graph")
# train the network with m memory states
for i, j in g.edges:
weight = 0
for zeta in range(0, m):
weight = weight + (MemoryMatrix[zeta][i] * MemoryMatrix[zeta][j])
g.edges[i, j]['weight'] = (weight / n)
W[i][j] = g.edges[i, j]['weight']
W[j][i] = W[i][j]
plt.imshow(W, cmap='gray')
plt.show()
hamming_distance = np.zeros((n_i, m))
# evolve according to hopfield dynamics, n_i iterations
for z in range(0, n_i):
i = choice(list(g.nodes))
s = sum([g.edges[i, j]['weight'] * g.nodes[j]['state'] for j in g.neighbors(i)])
g.nodes[i]['state'] = 1 if s > 0 else -1 if s < 0 else g.nodes[i]['state']
for q in range(m):
for i in list(g.nodes):
hamming_distance [z, q] += (abs(g.nodes[i]['state'] - MemoryMatrix[q][i])/2)
z = z + 1
if (n == 16):
nx.draw(g, pos = g.pos, cmap = cm.jet, vmin = -1, vmax = 1, node_color = [g.nodes[i]['state'] for i in g.nodes])
plt.show()
print ("Final Graph")
fig = plt.figure(figsize = (8, 8))
plt.plot(hamming_distance)
plt.xlabel('No of Iterations')
plt.ylabel('Hamming Distance')
plt.ylim([0, n])
plt.plot(hamming_distance)
plt.show()
<file_sep>/c-elegans/excel.py
import numpy as np
import pandas as pd
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from random import choice
import datetime
from tqdm import tqdm
import random
np.set_printoptions(threshold=sys.maxsize)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
df = pd.read_excel('s.xlsx', header=None, skiprows =1, usecols=range(1,515), sheet_name="male chem synapse adjacency")
c = df.to_numpy()
c[c > 0] = 1
n = 514
m_f = round(0.2 * n)
MemoryMatrix = np.zeros((m_f, n))
for a in range(0, m_f):
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
flip = round(0.3 * n)
n_i = 10000
W = np.zeros((n, n))
Y = []
X = []
u = []
u = MemoryMatrix[1].copy() # copy target M to initial state
rs = random.sample(range(0, n), flip)
ErrorMatrixn = np.zeros((1, round((m_f-1)/2))) # initiate quality matrix
steps = int(input('Enter # of steps in iteration of m (resolution)'))
for z in list(rs): # randomly pick up 25 percent and flip them
u[z] = (MemoryMatrix[1][z] * -1)
for m in tqdm(range (2, (m_f+1), steps)): # for this given random matrix, loop over different m values
alpha = (m/n)
# train the network with m memory states
for i in range(1, n):
for j in range(1, n):
weight = 0
for zeta in range(0, m):
weight = weight + (MemoryMatrix[zeta][i] * MemoryMatrix[zeta][j] * c[i][j])
W[i][j] = (weight / n)
W[j][i] = W[i][j]
# evolve according to hopfield dynamics, n_i iterations
for z in range(0, n_i):
i = random.randint(1, n-1)
for j in range (1, n):
s = sum([W[i][j] * u[j] * c[i][j]])
u[i] = 1 if s > 0 else -1 if s < 0 else u[i]
z = z + 1
# calculate hamming distances
overlaptemp = 0
for i in range(1, n):
overlaptemp += u[i] * MemoryMatrix[1][i]
X.append(alpha)
Y.append(overlaptemp)
col_totalsEavg = [(x / n) for x in Y]
# set up figure and axes
plt.plot(X, col_totalsEavg, color="red")
plt.ylabel("% of errors")
plt.xlabel("alpha")
png = ".png"
suffix = datetime.datetime.now().strftime("%m%d_%H%M%S")
filename = "_".join([str(n), suffix])
plt.autoscale()
plt.savefig(filename, dpi=200, bbox_inches = "tight")
plt.show()
np.savetxt(filename + "-s-Q.csv", np.column_stack((X, col_totalsEavg)), delimiter=",", fmt='%s')<file_sep>/efficacy/efficacy.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
# change
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import numpy as np
import networkx as nx
from random import choice
from matplotlib import cm
import datetime
from tqdm import tqdm
from random import randrange
import random
div = 10
n = int(input('Enter # of neurons'))
m = int(input('Enter # of memory states'))
k = int(input('Enter # of connected neighbours k'))
n_i = int(input('Enter # of iterations each run'))
ensembleCount = int(input('Enter # of realizations'))
EfficacyMatrix = np.zeros((ensembleCount, (div+1))) # initiate quality matrix
MemoryMatrix = np.zeros((m, n))
MemoryMatrixR = np.zeros((m, n))
for a in range(0, m): # random memory states
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
res = np.flipud(mem)
MemoryMatrix[a] = mem
MemoryMatrixR[a] = res
x = 0
for b in tqdm(range(ensembleCount)): #realizations
u = []
for a in range(0, n): #randomized init state
x = choice([1, -1])
u.append(x)
x = 0
Y = []
X = []
for rho in (range(0, div+1)): # for this given random matrix, loop over different p values
p = (rho / div)
g = nx.watts_strogatz_graph(n, k, p)
# set the initial state
for st in range(0, n):
g.nodes[st]['state'] = u[st]
# train the network
for i, j in g.edges:
weight = 0
for alpha in range(0, m):
weight = weight + (MemoryMatrix[alpha][i] * MemoryMatrix[alpha][j])
g.edges[i, j]['weight'] = (weight / n)
# evolve according to hopfield dynamics, n_i iterations
z = 0
for z in range(1, (n_i + 1)):
i = choice(list(g.nodes))
s = sum([g.edges[i, j]['weight'] * g.nodes[j]['state'] for j in g.neighbors(i)])
g.nodes[i]['state'] = 1 if s > 0 else -1 if s < 0 else g.nodes[i]['state']
# nx.draw(g, pos = g.pos, cmap = cm.jet, vmin = -1, vmax = 1, node_color = [g.nodes[i]['state'] for i in
# g.nodes]) plt.show()
z = z + 1
# calculate hamming distances and overlap for all the memory states
finalstate = []
for i in list(g.nodes):
x = g.nodes[i]['state']
finalstate.append(x)
eCount = 0
for a in range (0, m):
if (np.array_equal(finalstate, MemoryMatrix[a])):
eCount = eCount + 1
if (np.array_equal(finalstate, MemoryMatrixR[a])):
eCount = eCount + 1
X.append(p)
Y.append(eCount)
EfficacyMatrix[b] = Y
b = b + 1
col_totalsEff = np.sum(EfficacyMatrix, 0)
col_totalsEffavg = [(x / ensembleCount) for x in col_totalsEff]
# set up figure and axes
plt.plot(X, col_totalsEffavg, color="black")
plt.title("\n Variation of Network Performance with Rewiring Probability \n %s neurons with %s memory states \n "
"Iterations = %s | k = %s | Ensemble Count= ""%s \n \n" % (n, m, n_i, k, ensembleCount))
plt.ylabel("efficacy")
eff = "EFF"
suffix = datetime.datetime.now().strftime("%m%d_%H%M%S")
filename = "_".join([eff, str(n), str(m), str(k), str(n_i), str(ensembleCount), suffix])
plt.autoscale()
plt.savefig(filename, dpi=200, bbox_inches="tight")
plt.show()
np.savetxt(filename + "-r-Eff.csv", np.column_stack((X, col_totalsEffavg)), delimiter=",", fmt='%s')
<file_sep>/ran/overlap-random.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from random import choice
from matplotlib import cm
import datetime
from tqdm import tqdm
from random import randrange
import random
#yes it works
n = int(input('Enter # of neurons'))
m = int(input('Enter # of memory states'))
flip = round(0.25 * n)
MemoryMatrix = np.zeros((m, n))
for a in range(0, m):
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
k = int(input('Enter # of connected neighbours k'))
p = 0
n_i = int(input('Enter # of iterations each run'))
ensembleCount = int(input('Enter # of runs to average over'))
target = int(input('Select memory state which when added noise gives initial state'))
suffix = datetime.datetime.now().strftime("%m%d_%H%M%S")
filename = "_".join([str(n), str(m), str(k), str(n_i), str(ensembleCount), suffix])
np.savetxt(filename + "-ms-s.csv", np.column_stack((np.transpose(MemoryMatrix))), delimiter=",", fmt='%s')
OverlapMatrixn = np.zeros((ensembleCount, n)) # initiate overlap matrix
for b in tqdm(range(ensembleCount)):
u = []
u = MemoryMatrix[target].copy() # copy target M to initial state
Y = []
X = []
n_init = 0
n_fin = n_init + flip
for count in range(n_init, n_fin): # sequentially pick up 25% of bits and flip them
u[count] = (MemoryMatrix[target][count] * -1)
g = nx.watts_strogatz_graph(n, k, p)
st = 0
for st in range(0, n):
g.nodes[st]['state'] = u[st]
X.append(st)
# train the network
for i, j in g.edges:
weight = 0
alpha = 0
for alpha in range(0, m):
weight = weight + (MemoryMatrix[alpha][i] * MemoryMatrix[alpha][j])
g.edges[i, j]['weight'] = (weight / n)
# evolve according to hopfield dynamics, n_i iterations
for z in range(0, n_i):
i = choice(list(g.nodes))
s = sum([g.edges[i, j]['weight'] * g.nodes[j]['state'] for j in g.neighbors(i)])
g.nodes[i]['state'] = 1 if s > 0 else -1 if s < 0 else g.nodes[i]['state']
# nx.draw(g, pos = g.pos, cmap = cm.jet, vmin = -1, vmax = 1, node_color = [g.nodes[i]['state'] for i in
# g.nodes]) plt.show()
z = z + 1
# calculate hamming distances and overlap for all the memory states
for i in list(g.nodes):
isCorrect = 0
if (MemoryMatrix[target][i] == g.nodes[i]['state']):
isCorrect = 1
Y.append(isCorrect)
OverlapMatrixn[b] = Y
b = b + 1
totalCorrect = [sum(x) for x in zip(*OverlapMatrixn)]
tCorrect = [(x / ensembleCount) for x in totalCorrect]
# set up figure and axes
plt.plot(X, tCorrect, color="black")
plt.ylabel("probability of correctness")
plt.xlabel("neuron")
suffix = datetime.datetime.now().strftime("%m%d_%H%M%S")
filename = "_".join([str(n_i), str(ensembleCount), suffix])
plt.autoscale()
plt.savefig(filename, dpi=200, bbox_inches = "tight")
plt.show()
np.savetxt(filename + "-tcorrect.csv", np.column_stack((X, tCorrect)), delimiter=",", fmt='%s')
<file_sep>/ran/test.py
# libraries
import matplotlib.pyplot as plt
import numpy as np
# create data
x = np.random.normal(size=50000)
y = x * 3 + np.random.normal(size=50000)
# Big bins
plt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.jet)
# plt.show()
# Small bins
plt.hist2d(x, y, bins=(300, 300), cmap=plt.cm.jet)
# plt.show()
# If you do not set the same values for X and Y, the bins aren't square !
plt.hist2d(x, y, bins=(300, 30), cmap=plt.cm.jet)
# plt.show()
<file_sep>/ran/hist.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import numpy as np
import networkx as nx
from random import choice
from matplotlib import cm
import datetime
from tqdm import tqdm
from random import randrange
import random
n = int(input('Enter # of neurons'))
m = int(input('Enter # of memory states'))
flip = round(0.25 * n)
MemoryMatrix = np.zeros((m, n))
for a in range(0, m): #generate memory matrix
mem = []
for i in range(0, n): #each row is a configuration state for n neurons
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
k = int(input('Enter # of connected neighbours k'))
n_i = int(input('Enter # of iterations each run'))
ensembleCount = int(input('Enter # of runs to average over'))
target = int(input('Select memory state which when added noise gives initial state'))
suffix = datetime.datetime.now().strftime("%m%d_%H%M%S")
filename = "_".join([str(n), str(m), str(k), str(n_i), str(ensembleCount), suffix])
#np.savetxt(filename + "-ms-r.csv", np.column_stack((np.transpose(MemoryMatrix))), delimiter=",", fmt='%s')
div = 10 #resolution
OverlapMatrixn = np.zeros((ensembleCount, div)) # initiate overlap matrix
EtaMatrixn = np.zeros((ensembleCount, div)) # initiate quality matrix
for b in tqdm(range(ensembleCount)): #loop over various init configs
u = []
u = MemoryMatrix[target].copy() # copy target to initial test pattern
hammingtemp = overlaptemp = 0
hammingavg = overlapavg = 0
Y = []
Y2 = []
X = []
p = 0
rs = random.sample(range(0, n), flip)
for p in list(rs): # randomly pick up 25 percent and flip them
u[p] = (MemoryMatrix[target][p] * -1)
for rho in (range(0, 10)): # for this given random matrix, loop over different p values
p = (rho / div)
hammingtemp = overlaptemp = 0
hammingval = overlapval = 0
q = 0
g = nx.watts_strogatz_graph(n, k, p) #generate the graph
# g.pos = {}
# for x in range(4):
# for y in range(4):
# g.pos[y * 4 + x] = (x, -y)
# set the initial state
st = 0
for st in range(0, n):
g.nodes[st]['state'] = u[st]
# nx.draw(g, pos = g.pos, cmap = cm.jet, vmin = -1, vmax = 1, node_color = [g.nodes[i]['state'] for i in
# g.nodes]) plt.show() print ("Initial Graph")
# train the network
for i, j in g.edges:
weight = 0
alpha = 0
for alpha in range(0, m):
weight = weight + (MemoryMatrix[alpha][i] * MemoryMatrix[alpha][j])
g.edges[i, j]['weight'] = (weight / n)
# evolve according to hopfield dynamics, n_i iterations
z = 0
for z in range(1, (n_i + 1)):
i = choice(list(g.nodes)) #pick up a node randomly
s = sum([g.edges[i, j]['weight'] * g.nodes[j]['state'] for j in g.neighbors(i)])
g.nodes[i]['state'] = 1 if s > 0 else -1 if s < 0 else g.nodes[i]['state']
# nx.draw(g, pos = g.pos, cmap = cm.jet, vmin = -1, vmax = 1, node_color = [g.nodes[i]['state'] for i in
# g.nodes]) plt.show()
z = z + 1
# calculate hamming distances and overlap for all the memory states
weights_hist = []
binwidth = 0.001
for i, j in g.edges:
tempw = g.edges[i, j]['weight']
weights_hist.append(tempw)
hist = "HIST"
png = ".png"
filename = "_".join([hist, str(p), str(n), str(m), png])
plt.clf()
plt.hist(weights_hist, bins=np.arange(min(weights_hist), max(weights_hist) + binwidth, binwidth))
plt.savefig(filename, dpi=200, bbox_inches="tight")
for i in list(g.nodes):
overlaptemp += (MemoryMatrix[target][i] * g.nodes[i]['state'])
hammingtemp += abs(g.nodes[i]['state'] - MemoryMatrix[target][i])
hammingval = (hammingtemp / 2)
overlapval = (overlaptemp / n)
q = ((n - hammingval) / n)
X.append(p)
Y.append(q)
Y2.append(overlapval)
OverlapMatrixn[b] = Y2
EtaMatrixn[b] = Y
b = b + 1
col_totalsE = np.sum(EtaMatrixn, 0)
col_totalsO = np.sum(OverlapMatrixn, 0)
col_totalsEavg = [(x / ensembleCount) for x in col_totalsE]
col_totalsOavg = [(x / ensembleCount) for x in col_totalsO]
#np.savetxt(filename + "-r-Qu.csv", np.column_stack((X, col_totalsEavg)), delimiter=",", fmt='%s')
#np.savetxt(filename + "-r-Ov.csv", np.column_stack((X, col_totalsOavg)), delimiter=",", fmt='%s')
<file_sep>/phase-diagram/ws/hopfield.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from random import choice
import datetime
from tqdm import tqdm
import random
n = int(input('Enter # of neurons'))
m_f = round(0.2 * n)
MemoryMatrix = np.zeros((m_f, n))
for a in range(0, m_f):
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
flip = round(0.3 * n)
n_i = 10000
steps = int(input('Enter # of steps in iteration of m (resolution)'))
k = int(input('k'))
p = float(input('p'))
ErrorMatrixn = np.zeros((1, round((m_f-1)/2))) # initiate quality matrix
Y = []
X = []
u = []
u = MemoryMatrix[1].copy() # copy target M to initial state
rs = random.sample(range(0, n), flip)
for z in list(rs): # randomly pick up 25 percent and flip them
u[z] = (MemoryMatrix[1][z] * -1)
g = nx.watts_strogatz_graph(n, k, p)
st = 0
for st in range(0, n):
g.nodes[st]['state'] = u[st]
for m in tqdm(range (2, (m_f+1), steps)): # for this given random matrix, loop over different m values
alpha = (m/n)
# train the network with m memory states
for i, j in g.edges:
weight = 0
for zeta in range(0, m):
weight = weight + (MemoryMatrix[zeta][i] * MemoryMatrix[zeta][j])
g.edges[i, j]['weight'] = (weight / n)
# evolve according to hopfield dynamics, n_i iterations
for z in range(0, n_i):
i = choice(list(g.nodes))
s = sum([g.edges[i, j]['weight'] * g.nodes[j]['state'] for j in g.neighbors(i)])
g.nodes[i]['state'] = 1 if s > 0 else -1 if s < 0 else g.nodes[i]['state']
z = z + 1
# calculate hamming distances
hammingtemp = 0
for i in list(g.nodes):
hammingtemp += abs(g.nodes[i]['state'] - MemoryMatrix[1][i])
X.append(alpha)
Y.append(hammingtemp)
col_totalsEavg = [(x / (n * 2)) for x in Y]
# set up figure and axes
plt.plot(X, col_totalsEavg, color="magenta")
plt.ylabel("% of errors")
plt.xlabel("alpha")
png = ".png"
suffix = datetime.datetime.now().strftime("%m%d_%H%M%S")
filename = "_".join([str(n), str(p), str(k), suffix, png])
plt.autoscale()
plt.savefig(filename, dpi=200, bbox_inches = "tight")
plt.show()
np.savetxt(filename + "-s-Q.csv", np.column_stack((X, col_totalsEavg)), delimiter=",", fmt='%s')
<file_sep>/ran/ortho-test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yash
"""
import numpy as np
from random import choice
n = int(input('Enter # of neurons'))
m = int(input('Enter # of memory states'))
flip = round(0.25 * n)
MemoryMatrix = np.zeros((m, n))
for a in range(0, m):
mem = []
for i in range(0, n):
x = choice([1, -1])
mem.append(x)
MemoryMatrix[a] = mem
x = 0
print (MemoryMatrix)
Mt = MemoryMatrix.transpose()
print (Mt)
O = (1/n)*np.dot(MemoryMatrix,Mt)
print(O)
| ebfe4af13730ba8a575667c1386955ba5e556d51 | [
"Python"
] | 11 | Python | yashgurbani/hopfield-ws | 3821f02a87d204de21a7180464c23551fb51da67 | 1e9a947c70028b933d47f33af42349e53343bea8 |
refs/heads/master | <repo_name>looricardoso/NomeCompletoJs<file_sep>/index.js
let nome = prompt('Digite seu nome: ');
let sobrenome = prompt('Digite seu sobrenome: ');
alert(`Nome completo: ${nome} ${sobrenome}`);
sobrenome = sobrenome.toUpperCase();
alert(`Nome de catálogo: ${sobrenome}, ${nome}`); | 00f61f31d469188185d3fd1df9bbf9e1947f4d19 | [
"JavaScript"
] | 1 | JavaScript | looricardoso/NomeCompletoJs | 9eb28305a30f9843d13086a7d86adfcab7b63370 | f0e83844bd52393e7a59e67c8bdc35a2f552046c |
refs/heads/master | <repo_name>damiangene/UNISA-assignment-2<file_sep>/Makefile
default: compile run
compile:
g++ *.cpp -o main
run:
./main
clean:
@rm main<file_sep>/assignment 2.cpp
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//declaration of functions
string welcome();
void print_seats(string flight[]);
void populate_seats(string (&flight_arr)[5][52]);
bool validate_flight(string a);
bool validate_seat(string a, string (&flight_arr)[5][52], int b);
bool validate_book(string a);
void print_ticket(string passenger[], string (&flight_arr)[5][52], int &i);
//Const for economy class price
const int ECONOMY_CLASS = 1600;
int main(){
//Initialising all variables that are needed in the program
//2D array for storing seat numbers and passenger details
string flights [5][52];
string passengers [4][250];
string seat, flight, book = "y";
int int_flight, p = 0, j = 0;
int seat_number, seat_price;
populate_seats(flights);
//while loop that repeats the booking process while the user wants to continue booking.
while (book == "y" || book == "Y"){
passengers[p][0] = (welcome());
cout << "\nThe available travel times for flights are:" << endl;
cout << " Depart\tArrive" << endl;
//Checks whether all the flights are fully booked,
//If so, it ends the whole program.
for (int i = 0; i < 5; i++){
if (flights[i][51] != "50"){
cout << i + 1 << ". " << flights[i][0] << endl;
}
else if (j < 4){
j++;
}
else{
cout << "\nAll flights are booked" << endl;
return 0;
}
}
//Flight selection.
cout << "Choose the time by enetering the option number from the displayed list:" << endl;
do{
cin >> flight;
}
while(!validate_flight(flight));
//Converts the flight selection string to an int.
//So that the index can be selected when printing out the seats and flight time.
int_flight = stoi(flight) - 1;
//Prompts user to select seat number and accesses flight time from flights array
cout << "\nThe available seats for " << flights[int_flight][0].substr(0,5) << " are as follows:" << endl;
//Displays the seating layout for the chosen flight.
print_seats(flights[int_flight]);
cout << "Please key in a seat number to choose a seat (eg:A2)" << endl;
//Seat selection.
do{
cin >> seat;
}
while (!validate_seat(seat, flights, int_flight));
//Changes the booked seat number to **
for (int i = 0; i < 51; i++){
if (flights[int_flight][i] == seat){
flights[int_flight][i] = "**";
seat_number = i;
break;
}
}
//checks whether the seat was booked in first or economy class
//Sets the seat price for the passengers array
if (seat_number < 25){
seat_price = ECONOMY_CLASS*1.2;
passengers[p][4] = "First class";
}
else{
seat_price = ECONOMY_CLASS;
passengers[p][4] = "Economy class";
}
//Adds flight, seat and seat price information to passenger array
passengers[p][1] = flight;
passengers[p][2] = seat;
passengers[p][3] = to_string(seat_price);
//Keeps track of the number of seats booked on each flight
flights[int_flight][51] = to_string(stoi(flights[int_flight][51]) + 1);
print_ticket(passengers[p], flights, int_flight);
//Checks whether the user wants to book for another flight.
cout << "\nWould you like to book another seat? Y/N: " ;
do{
cin >> book;
cin.get();
}while(!validate_book(book));
//Keeps track of how many passengers have been booked.
//Allows the program to move to the next index in the passengers array.
p++;
cout << endl;
}
//Prints out the number of bookings for each flight
for (int i = 0; i < 5; i++){
cout << "Number of bookings made for " << flights[i][0].substr(0,5);
cout << ": " << flights[i][51] << endl;
}
return 0;
}
//Welcome message and passenger name capture
string welcome(){
string passenger;
cout << "Welcome to the COS1511 Flight Booking System\n" << endl;
cout << "Enter Full Name" << endl;
getline(cin,passenger);
return passenger;
}
//Prints out seats with the correct layout
void print_seats(string flight[]){
int k = 0;
cout << "First class(1920.00)" << endl;
for (int j = 0; j < 9; j++){
if (k == 24){
cout << "Economy class(1600.00)" << endl;
}
cout << "|";
for (int i = 0; i < 3; i++){
cout << flight[k+1] << "|";
k++;
if (k > 49){
cout << endl;
return;
}
}
cout << "----";
for (int i = 0; i < 3; i++){
cout << "|" << flight[k+1];
k++;
}
cout << "|" << endl;
}
}
//Seat generation for all 5 flights
void populate_seats(string (&flight_arr)[5][52]){
//Setting index 0 for all flights to the flights time
flight_arr[0][0] = "07:00\t09:30";
flight_arr[1][0] = "09:00\t11:30";
flight_arr[2][0] = "11:00\t13:30";
flight_arr[3][0] = "13:00\t15:30";
flight_arr[4][0] = "15:00\t17:30";
for (int a = 0; a < 5; a++){
int b = 0;
for (int i = 17; i < 26; i++){
for ( int j = 1; j < 7; j++){
if (i == 25 && j > 2){
break;
}
//Converting i into an ascii character to form the letters
string seat = char('0' + i) + to_string(j);
flight_arr[a][b+1] = seat;
b++;
}
flight_arr[a][b+1] = "0";
}
}
}
//Prints out the ticket for the passenger using setw for formatting
void print_ticket(string passenger[], string (&flight_arr)[5][52], int &i){
int name = passenger[0].length();
cout << "\n***************************" << endl;
cout << "Travel Ticket for Flight " << i + 1 << endl;
cout << "***************************" << endl;
cout << left << setw(15) << "Name " << ": " << passenger[0];
cout << setw(13) << "" << "Travel Ticket Class " << ": " << passenger[4] << endl;
cout << setw(31 + name) << "" << setw(20) << "Seat No." << ": " << passenger[2] << endl;
cout << setw(15) << "Departure" << ": " << setw(13 + name) << "Johannesburg";
cout << setw(20) << "Departure Time" << ": " << flight_arr[i][0].substr(0,5) << endl;
cout << setw(15) << "Destination" << ": " << setw(13 + name) << "Cape Town";
cout << setw(20) << "Arrival Time" << ": " << flight_arr[i][0].substr(6,10) << endl;
cout << "\n***************************" << endl;
cout << "Amount: R" << passenger[3] << endl;
cout << "Thank you for booking with COS 1511 Booking System." << endl;
cout << "Your travel agent is <NAME>" << endl;
cout << "***************************" << endl;
}
//Validates flight selection entry
bool validate_flight(string a){
for (int i = 1; i < 6; i++){
if (a == to_string(i)){
return true;
}
}
cout << "Incorrect option! Please choose from 1-5." << endl;
return false;
}
//Validates seat selection entry
bool validate_seat(string a, string (&flight_arr)[5][52], int b){
for (int i = 0; i < 51; i++){
if (flight_arr[b][i] == a){
return true;
}
}
cout << "Please select an available seat number." << endl;
return false ;
}
//validates whether the user would like to make another booking
bool validate_book(string a){
while(a != "y" && a != "n" & a != "Y" && a != "N"){
cout << "Enter a valid option: Y/N:";
return false;
}
return true;
} | ace7c2d71bd133ecdfbf1690d17f936891c4f45b | [
"Makefile",
"C++"
] | 2 | Makefile | damiangene/UNISA-assignment-2 | 97e005edb8336faded8d241c2a5a291eeb8c6ac6 | 1d3a3f555f583aa7b14e72b0a819f630a8277e5e |
refs/heads/master | <repo_name>alexanderwood/bioinformatics-algorithms<file_sep>/IndividualFunctions/GreedyMotifSearchWithPseudocounts.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
import itertools
import sys
import numpy
# Store as global variable since its values must be constant.
keys = 'ACGT'
# INPUT: Motif matrix
# OUTPUT: Count matrix
def Count(Motif):
Count_mat = []
# Initialize Count as a 4 x k matrix filled with zeros
for i in range(len(keys)):
temp_row = []
for j in range(len(Motif[0])):
temp_row.append(0)
Count_mat.append(temp_row)
# If the argument given is the file path name, call Motif() and
# generate its Motif matrix.
if type(Motif) == str:
Motif = Motifs(Motif)
for j in range(len(Motif[0])): # Vary over columns...
for i in range(len(Motif)): # Vary over rows...
for k in range(len(keys)): # Vary over nucleotides...
if Motif[i][j] == keys[k]:
Count_mat[k][j] += 1
return Count_mat
# INPUT: Profile matrix
# OUTPUT: Consensus vector where Consensus[j] yields the most common letter in column j.
def Consensus(Profile):
Consensus = []
for j in range(len(Profile[0])): #Column
temp = []
for i in range(len(Profile)): #Rows
temp.append(Profile[i][j])
letter_max = max(set(temp), key=temp.count)
index_max = keys.index(letter_max)
Consensus.append(keys[index_max])
return Consensus
# INPUT: Count matrix
# OUTPUT: Profile matrix
def Profile(Count_mat):
N = list(numpy.sum(Count_mat, 0))
N = N[0]
for i in range(len(Count_mat)):
for j in range(len(Count_mat[i])):
Count_mat[i][j] /= N
Profile_mat = Count_mat
return Profile_mat
## INPUT: A profile matrix Profile, a DNA pattern Pattern
## OUTPUT: The probability that Profile generates Pattern.
def ProbabilityGivenProfile(Profile, Pattern):
Probability = 1 # Initialize to 1
#print('pattern:', Pattern)
for j in range(len(Pattern)):
i = keys.index(Pattern[j])
Probability *= Profile[i][j]
return Probability
## Profile-most k-mer problem.
## INPUT: String Text, int k, 4xk matrix Profile
## OUTPUT: the k-mer that was most likely to have been generated by Profile among all k-mers in Text
def ProfileMost_kmer(Text, Profile, k):
for i in range(len(Text) - k + 1):
Pattern = Text[i:i+k]
Probability = ProbabilityGivenProfile(Profile, Pattern)
if i == 0:
PMK = Pattern
ProbPMK = Probability
elif Probability > ProbPMK:
PMK = Pattern
ProbPMK = Probability
return PMK
# INPUT: Motifs
## OUTPUT: Score(motifs), the total number of mismatches.
def Score(Motifs):
Consen = Consensus(Motifs)
Score = 0
for j in range(len(Motifs[0])): # Column
for i in range(len(Motifs)): # Rows
if Motifs[i][j] != Consen[j]:
Score += 1
return Score
## INPUT: Integers k, t and list of strings DNA
## OUTPUT: Collection of strings BestMotifs.
## This algorithm runs WITH pseudocounts
def GreedyMotifSearch(DNA, k, t):
BestMotifs = [] # BestMotifs will be a motif matrix constructed from the first kmer in each string in DNA
for dna in DNA:
BestMotifs.append(dna[:k])
FirstString = DNA[0]
for i in range(len(FirstString) - k + 1):
Motif = []
Motif.append(FirstString[i:i+k]) # So, for each k-mer in DNA[0]...
CountMatrix = Count(Motif) # ... apply LaPlace's rule to implement Pseudocounts....
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
ProfMatrix = Profile(CountMatrix) # ...Build profile from this k-mer
for l in range(1, t):
NextMotif = ProfileMost_kmer(DNA[l], ProfMatrix, k)
Motif.append(NextMotif)
CountMatrix = Count(Motif)
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
ProfMatrix = Profile(CountMatrix)
if Score(Motif) < Score(BestMotifs):
BestMotifs = Motif
return BestMotifs
<file_sep>/IndividualFunctions/ProfileMost_kmer.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
Temp = []
for i in range(2, len(tokens)):
Temp.append(float(tokens[i]))
n = len(Temp)//4
Profile = list(chunks(Temp,n))
# Store as global variable since its values must be constant.
keys = 'ACGT'
## INPUT: A profile matrix Profile, a DNA pattern Pattern
## OUTPUT: The probability that Profile generates Pattern.
def ProbabilityGivenProfile(Profile, Pattern):
Probability = 1 # Initialize to 1
#print('pattern:', Pattern)
for j in range(len(Pattern)):
i = keys.index(Pattern[j])
Probability *= Profile[i][j]
return Probability
## Profile-most k-mer problem.
## INPUT: String Text, int k, 4xk matrix Profile
## OUTPUT: the k-mer that was most likely to have been generated by Profile among all k-mers in Text
def ProfileMost_kmer(Text, Profile, k):
for i in range(len(Text) - k + 1):
Pattern = Text[i:i+k]
Probability = ProbabilityGivenProfile(Profile, Pattern)
if i == 0:
PMK = Pattern
ProbPMK = Probability
elif Probability >= ProbPMK:
PMK = Pattern
ProbPMK = Probability
return PMK
<file_sep>/2_PatternsAndFrequencies.py
'''
Module for algorithms from the week 2 work on the Bioinformatics course.
Solutions Copyright <NAME> 2016.
Includes:
Hamming Distance
Nearest d-Neighbors
Frequent Words
& more.
'''
# PatternCount algorithm from section 1.2 of
# Bioinformatics course.
# The input is a text string of DNA, along with
# some pattern you wish to count the number of
# occurences of within that string.
# The output is the number of occurences of the
# pattern within the string.
def PatternCount(Text, Pattern):
# Initialize count
count = 0
for i in range(len(Text) - len(Pattern) + 1):
if Pattern == Text[i:i+len(Pattern)]:
count += 1
# Return the number of times count appears in the text
return count
def ReverseComplement(Text):
ReverseText = '' # Initialize empty string
for i in range(len(Text)):
b = len(Text) - (i+1) # Backwards index!
if Text[b] == 'A':
ReverseText += 'T'
elif Text[b] == 'T':
ReverseText += 'A'
elif Text[b] == 'G':
ReverseText += 'C'
elif Text[b] == 'C':
ReverseText += 'G'
else:
return 'Error'
return ReverseText
# Converts single digit to single symbol.
def SymbolToNumber(Value):
if Value == 'A':
return 0
elif Value == 'C':
return 1
elif Value == 'G':
return 2
elif Value == 'T':
return 3
else:
return 'Error'
# Final, recursive, attempt:
def PatternToNumber(Pattern):
if Pattern == '':
return 0
LastSymbol = Pattern[len(Pattern) - 1]
Prefix = Pattern[0:len(Pattern)-1]
return 4*PatternToNumber(Prefix) + SymbolToNumber(LastSymbol)
# Converts single digit to single symbol.
def NumberToSymbol(Value):
if Value == 0:
return 'A'
elif Value == 1:
return 'C'
elif Value == 2:
return 'G'
elif Value == 3:
return 'T'
else:
return 'Error'
# Final defnition of function converting numbers to patterns.
# Uses recursion.
def NumberToPattern(Number, k):
if k == 1:
return NumberToSymbol(Number)
Prefix = Number // 4
Remainder = Number % 4
Pattern = NumberToSymbol(Remainder)
PrefixPattern = NumberToPattern(Prefix, k-1)
return PrefixPattern + Pattern
# Recall that skew(i, Genome) = # of occureences of G - # occurences of C
# on the first i nucleotides in the genome.
def skew(i, Genome):
# Store the values of skew in a list, Skew
# So, skew_list[j] is the value of skew at index j
# start with skew_list = [0] since the balance of G and C is initally zero.
skew_list = []
# To keep track of the skew values as we run through the string
count = 0
for nuc in range(i):
if (Genome[nuc] == 'A') or (Genome[nuc] == 'T'):
skew_list.append(count)
elif Genome[nuc] == 'G':
count += 1
skew_list.append(count)
elif Genome[nuc] == 'C':
count -= 1
skew_list.append(count)
elif Genome[nuc] == '\n':
continue
else:
print('An error occurred')
# for val in range(len(skew_list)):
# print(skew_list[val], end=' ')
return skew_list
'''
Minimum Skew Problem: Find a position in a genome where the skew diagram attains a minimum.
Input: A DNA string Genome.
Output: All integer(s) i minimizing Skewi (Genome) among all values of i (from 0 to |Genome|).
'''
# This algorithm returns a list of the indexes of minimum values in a list.
def MinListIndex(Some_List):
# Find the minimum
minimum = min(Some_List)
# Create a list to store the indexes.
min_index = []
for i in range(len(Some_List)):
if Some_List[i] == minimum:
min_index.append(i)
return min_index
def MinimumSkew(Genome):
# Get the list of skew funciton values
skew_list = skew(len(Genome), Genome)
# Get the list of indexes of occurences of min value.
min_index = MinListIndex(skew_list)
for val in range(len(min_index)):
print(min_index[val], end=' ')
#return min_index
'''
We say that position i in k-mers p1 … pk and q1 … qk is a mismatch if pi ≠ qi. For example, CGAAT and CGGAC have two mismatches.
The number of mismatches between strings p and q is called the Hamming distance between these strings and is denoted
HammingDistance(p, q).
Hamming Distance Problem: Compute the Hamming distance between two strings.
Input: Two strings of equal length.
Output: The Hamming distance between these strings.
'''
def HammingDistance(p, q):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] != q[i]:
hamming_dist += 1
#print hamming_dist
return hamming_dist
# The following is a variation on the HammingDistance function which quits running its calculations once a bound
# on the hamming distance has been reached. So for instance if the bound is d and p and q have a hamming distance of
# anything greater than d, it will simply return d+1.
def HammingDistance_bound(p, q, d):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] == q[i]:
continue
elif p[i] != q[i] and hamming_dist <= d:
hamming_dist += 1
continue
else:
break
return hamming_dist
'''
We say that a k-mer Pattern appears as a substring of Text with at most d mismatches if there is some k-mer substring Pattern'
of Text having d or fewer mismatches with Pattern, i.e., HammingDistance(Pattern, Pattern') ≤ d. Our observation that a DnaA
box may appear with slight variations leads to the following generalization of the Pattern Matching Problem.
Approximate Pattern Matching Problem: Find all approximate occurrences of a pattern in a string.
Input: Strings Pattern and Text along with an integer d.
Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.
Code Challenge: Solve the Approximate Pattern Matching Problem.
'''
def ApproximatePatternMatching(Pattern, Text, d):
# Create a list to store indexes of approximate matches.
approx_match = []
for i in range(len(Text) - len(Pattern) + 1):
temp = HammingDistance_bound(Pattern, Text[i: i+len(Pattern)], d)
if temp <= d:
approx_match.append(str(i))
return approx_match
'''
Our goal now is to modify our previous algorithm for the Frequent Words Problem in order to find DnaA boxes by identifying
frequent k-mers, possibly with mismatches. Given strings Text and Pattern as well as an integer d, we define
Countd(Text, Pattern) as the total number of occurrences of Pattern in Text with at most d mismatches. For example,
Count1(AACAAGCTGATAAACATTTAAAGAG, AAAAA) = 4 because AAAAA appears four times in this string with at most one mismatch:
AACAA, ATAAA, AAACA, and AAAGA. Note that two of these occurrences overlap.
'''
def Count(Pattern, Text, d):
total_count = len(ApproximatePatternMatching(Pattern, Text, d))
return total_count
'''
A most frequent k-mer with up to d mismatches in Text is simply a string Pattern maximizing Countd(Text, Pattern) among all k-mers.
Frequent Words with Mismatches Problem: Find the most frequent k-mers with mismatches in a string.
Input: A string Text as well as integers k and d. (You may assume k ≤ 12 and d ≤ 3.)
Output: All most frequent k-mers with up to d mismatches in Text.
One way to solve the above problem is to generate all 4k k-mers Pattern, compute ApproximatePatternCount(Text, Pattern, d)
for each k-mer Pattern, and then output k-mers with the maximum number of approximate occurrences. This is an inefficient
approach in practice, since many of the 4k k-mers that this method analyzes should not be considered because neither they
nor their mutated versions (with up to d mismatches) appear in Text. Check out Charging Station: Solving the Frequent Words
with Mismatches Problem to learn about a better approach that avoids analyzing such hopeless k-mers.
'''
# We need a method of analyzing the k-mers in the Text without having to test every possible k-mer as this would be massively
# ineffecient. Therefore, we first generate the d-neighborhood of a string, ie, all strings which have at most d mismatches with
# the string.
def ImmediateNeighbors(Pattern): # ie, differ by one char
nucs = ['A', 'C', 'G', 'T']
neighborhood = [Pattern] # Initialize a list
for i in range(len(Pattern)):
symbol = Pattern[i]
nucs.remove(symbol)
tempnucs = list(nucs)
nucs.append(symbol)
for nuc in tempnucs:
neighbor = Pattern[0:i] + nuc + Pattern[i+1:]
neighborhood.append(neighbor)
return neighborhood
# Is called recursively until it returns a list of all d-neighbors.
# i is current length of neighbor candidates.
def Neighbors_Test(Pattern, Neighbors, i, d):
neighbors = []
if d == 0:
return [Pattern]
nucs = ['A', 'C', 'G', 'T']
candidates = []
for Neighbor in Neighbors:
for nuc in nucs:
candidates.append(Neighbor + nuc)
new_candidates = []
for candidate in candidates:
if (HammingDistance(candidate, Pattern[:i+1]) < d) and (len(candidate) < len(Pattern)):
new_candidates.append(candidate)
elif (HammingDistance(candidate, Pattern[:i+1]) < d) and (len(candidate) == len(Pattern)):
neighbors.append(candidate)
elif HammingDistance(candidate, Pattern[:i+1]) == d:
neighbors.append(candidate + Pattern[i+1:])
else:
continue
if i < len(Pattern):
more_neighbors = Neighbors_Test(Pattern, new_candidates, i+1, d)
neighbors += more_neighbors
elif i == len(Pattern):
even_more = []
for cand in new_candidates:
for nuc in nucs:
even_more.append(cand + nuc)
neighbors += even_more
return neighbors
# This function initializes the call to Neighbors_Test, which will run recursively until
# all d-neighbors have been found.
def Neighbors(Pattern, d):
neighbors_init = ['A', 'G', 'C', 'T']
return Neighbors_Test(Pattern, neighbors_init, 1, d)
'''
A most frequent k-mer with up to d mismatches in Text is simply a string
Pattern maximizing Countd(Text, Pattern) among all k-mers. Note that
Pattern does not need to actually appear as a substring of Text; for
example, as we already saw, AAAAA is the most frequent 5-mer with 1 mismatch
in AACAAGCTGATAAACATTTAAAGAG, even though it does not appear exactly in this
string. Keep this in mind while solving the following problem.
Frequent Words with Mismatches Problem: Find the most frequent k-mers with mismatches in a string.
Input: A string Text as well as integers k and d. (You may assume k ≤ 12 and d ≤ 3.)
Output: All most frequent k-mers with up to d mismatches in Text.
'''
def FrequentWordsMismatch(Text, k, d):
FrequentPatterns = [] # Initialize an empty set to store the frequent patterns found
close = []
frequency_array = []
for i in range(4**k):
close.append(0)
frequency_array.append(0)
for i in range(len(Text) - k + 1):
neighborhood = Neighbors(Text[i:i+k], d)
for neighbor in neighborhood:
index = PatternToNumber(neighbor)
close[index] += 1
for i in range(4**k):
if close[i] > 0:
Pattern = NumberToPattern(i, k)
frequency_array[i] = len(ApproximatePatternMatching(Pattern, Text, d))
max_count = max(frequency_array)
for i in range(4**k):
if frequency_array[i] == max_count:
Pattern = NumberToPattern(i, k)
FrequentPatterns.append(Pattern)
return FrequentPatterns
'''
Now we wish to perform the same task as above, but with also the reverse complement.
We now redefine the Frequent Words Problem to account for both mismatches and reverse
complements. Recall that Patternrc refers to the reverse complement of Pattern.
Frequent Words with Mismatches and Reverse Complements Problem: Find the most frequent
k-mers (with mismatches and reverse complements) in a string.
Input: A DNA string Text as well as integers k and d.
Output: All k-mers Pattern maximizing the sum
Countd(Text, Pattern)+ Countd(Text, Pattern_rc)
over all possible k-mers.
'''
def FrequentWordsMismatch_ReverseComplement(Text, k, d):
FrequentPatterns = [] # Initialize an empty set to store the frequent patterns found
close = [] # zero array, where
frequency_array = [] #initialize array to store frequency of each k-word
for i in range(4**k):
close.append(0)
frequency_array.append(0)
# First, find all d-neighbors of Text[i:i+k]
for i in range(len(Text) - k + 1):
neighborhood = Neighbors(Text[i:i+k], d)
# Mark these k-mers in the array, so that you only test k-mers which appear at least once.
for neighbor in neighborhood:
index = PatternToNumber(neighbor)
close[index] += 1
for i in range(4**k): # ie, For each possible (forward) k-mer:
if close[i] > 0: # ie, If the k-mer appears in original Text at least once
Pattern = NumberToPattern(i, k) # Convert the index to a pattern.
Pattern_Reverse = ReverseComplement(Pattern) # Find the reverse complement of this pattern
# Set the frequency equal to the number of times an approximate match occurs for the original pattern
frequency_array[i] = len(ApproximatePatternMatching(Pattern, Text, d))
# Also add the number of times an approximate match for the reverse complement appears
frequency_array[i] += len(ApproximatePatternMatching(Pattern_Reverse, Text, d))
max_count = max(frequency_array)
for i in range(4**k):
if frequency_array[i] == max_count:
Pattern = NumberToPattern(i, k)
ReversePattern = ReverseComplement(Pattern)
FrequentPatterns.append(Pattern)
FrequentPatterns.append(ReversePattern)
FrequentPatterns = list(set(FrequentPatterns))
return FrequentPatterns
<file_sep>/IndividualFunctions/ApproximatePatternMatching.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
# The following is a variation on the HammingDistance function which quits running its calculations once a bound
# on the hamming distance has been reached. So for instance if the bound is d and p and q have a hamming distance of
# anything greater than d, it will simply return d+1.
def HammingDistance_bound(p, q, d):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] == q[i]:
continue
elif p[i] != q[i] and hamming_dist <= d:
hamming_dist += 1
continue
else:
break
#print hamming_dist
return hamming_dist
'''
We say that a k-mer Pattern appears as a substring of Text with at most d mismatches if there is some k-mer substring Pattern'
of Text having d or fewer mismatches with Pattern, i.e., HammingDistance(Pattern, Pattern') ≤ d. Our observation that a DnaA
box may appear with slight variations leads to the following generalization of the Pattern Matching Problem.
Approximate Pattern Matching Problem: Find all approximate occurrences of a pattern in a string.
Input: Strings Pattern and Text along with an integer d.
Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.
Code Challenge: Solve the Approximate Pattern Matching Problem.
'''
def ApproximatePatternMatching(Pattern, Text, d):
# Create a list to store indexes of approximate matches.
approx_match = []
for i in range(len(Text) - len(Pattern) + 1):
temp = HammingDistance_bound(Pattern, Text[i: i+len(Pattern)], d)
if temp <= d:
approx_match.append(str(i))
return approx_match
<file_sep>/IndividualFunctions/DistanceBetweenPatternAndStrings.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
import itertools
import sys
import numpy
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
def HammingDistance(p, q):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] != q[i]:
hamming_dist += 1
#print hamming_dist
return hamming_dist
## INPUT: string Pattern, list of strings DNA
## OUTPUT: d(DNA, Pattern)
def DistanceBetweenPatternAndStrings(DNA, Pattern):
k = len(Pattern)
distance = 0
for Text in DNA:
HammingDistanceMax = sys.maxsize
for i in range(len(Text) - k + 1):
test_string = Text[i:i+k]
condition = HammingDistance(Pattern, test_string)
if HammingDistanceMax > condition:
HammingDistanceMax = condition
distance = distance + HammingDistanceMax
return distance
<file_sep>/IndividualFunctions/MedianString.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
import itertools
import sys
# Store as global variable since its values must be constant.
keys = 'ACGT'
# Converts single digit to single symbol.
def NumberToSymbol(Value):
if Value == 0:
return 'A'
elif Value == 1:
return 'C'
elif Value == 2:
return 'G'
elif Value == 3:
return 'T'
else:
return 'Error'
# Final defnition of function converting numbers to patterns.
# Uses recursion.
def NumberToPattern(Number, k):
if k == 1:
return NumberToSymbol(Number)
Prefix = Number // 4
Remainder = Number % 4
Pattern = NumberToSymbol(Remainder)
PrefixPattern = NumberToPattern(Prefix, k-1)
return PrefixPattern + Pattern
'''
We say that position i in k-mers p1 … pk and q1 … qk is a mismatch if pi ≠ qi. For example, CGAAT and CGGAC have two mismatches.
The number of mismatches between strings p and q is called the Hamming distance between these strings and is denoted
HammingDistance(p, q).
Hamming Distance Problem: Compute the Hamming distance between two strings.
Input: Two strings of equal length.
Output: The Hamming distance between these strings.
'''
def HammingDistance(p, q):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] != q[i]:
hamming_dist += 1
#print hamming_dist
return hamming_dist
## Instead of generating all possible motifs in DNA we instead generate k-mers in each
## string in DNA. We then compute the minimum Hamming Distance between any k-mer
## and Text.
##
## We perform this computation for each string in DNA then add together the resulting
## minimums.
## INPUT: string Pattern, list of strings DNA
## OUTPUT: d(DNA, Pattern)
def DistanceBetweenPatternAndStrings(DNA, Pattern):
k = len(Pattern)
distance = 0
for Text in DNA:
HammingDistanceMax = sys.maxsize
for i in range(len(Text) - k + 1):
test_string = Text[i:i+k]
condition = HammingDistance(Pattern, test_string)
if HammingDistanceMax > condition:
HammingDistanceMax = condition
distance = distance + HammingDistanceMax
return distance
## INPUT: Int k, list of strings DNA.
## OUTPUT: k-mer Pattern that minimizes d(Pattern, DNA) among all k-mers Pattern.
## (Return the first one if there are multiple.)
##
def MedianString(DNA, k):
distance = sys.maxsize # Initialize distance to "infinity"
Median = ''
for val in range(4**k):
Pattern = NumberToPattern(val, k)
test = DistanceBetweenPatternAndStrings(DNA, Pattern)
if distance > test:
distance = test
Median = Pattern
return Median
<file_sep>/1_DNAReplication.py
## The following is a module containing functions which perform computations
## related to finding the origin of replication in DNA. Based on Week 1 of
## the Coursera Bioinformatics Specialization Course 1.
## Written by <NAME> October 2016
# ---------------------------------------------------------------------------------------- #
## PatternCount Algorithm
## INPUT: String DNA, string Pattern
## OUTPUT: The number of occurences of Pattern within DNA
def PatternCount(Text, Pattern):
# Initialize count
count = 0
for i in range(len(Text) - len(Pattern) + 1):
if Pattern == Text[i:i+len(Pattern)]:
count += 1
# Return the number of times count appears in the text
return count
# ---------------------------------------------------------------------------------------- #
## FrequentWords Algorithm: Inefficient Version
## INPUT: String DNA, int k
## OUTPUT: set of all k-words (subwords of DNA of length k) which appear most frequently
def FrequentWords(Text, k):
FrequentPatterns = set() # Empty set to store the frequent patterns in!
Count = [] # Empty list to store each count for subword i
for i in range(len(Text) - k + 1): # Create array of the # of occurences
Pattern = Text[i:i+k]
Count.append(PatternCount(Text, Pattern))
maxCount = max(Count)
for i in range(len(Count)):
if Count[i] == maxCount:
FrequentPatterns.add(Text[i:i+k])
return FrequentPatterns
# ---------------------------------------------------------------------------------------- #
## PatternToNumber Algorithm
## Input: Some DNA string Pattern
## Output: A numerical value in one-to-one corresp. with Pattern
## SymbolToNumber Algorithm
## Used in PatternToNumber
## INPUT: A, C, G, T
## OUTPUT: 0, 1, 2, 3
def SymbolToNumber(Value):
if Value == 'A':
return 0
elif Value == 'C':
return 1
elif Value == 'G':
return 2
elif Value == 'T':
return 3
else:
return 'Error'
def PatternToNumber(Pattern):
if Pattern == '':
return 0
LastSymbol = Pattern[len(Pattern) - 1]
Prefix = Pattern[0:len(Pattern)-1]
return 4*PatternToNumber(Prefix) + SymbolToNumber(LastSymbol)
# ---------------------------------------------------------------------------------------- #
## NumberToPattern Algorithm
## Input: Integer Number, integer k
## Output: The unique string Pattern of length k in one-to-one correspondence with Number
## NumberToSymbol Algorithm
## Used in NumberToPattern
## OUTPUT: 0, 1, 2, 3
## INPUT: A, C, G, T
def NumberToSymbol(Value):
if Value == 0:
return 'A'
elif Value == 1:
return 'C'
elif Value == 2:
return 'G'
elif Value == 3:
return 'T'
else:
return 'Error'
def NumberToPattern(Number, k):
if k == 1:
return NumberToSymbol(Number)
Prefix = Number // 4
Remainder = Number % 4
Pattern = NumberToSymbol(Remainder)
PrefixPattern = NumberToPattern(Prefix, k-1)
return PrefixPattern + Pattern
# ---------------------------------------------------------------------------------------- #
## ComputingFrequencies algorithm, Slow Version
## INPUT: String Text, integer k
## OUTPUT: Frequency array, which contains the number of times each possible pattern
## of lencth k appears in Text.
## We use the functions converting between number and lexicographic order
## of DNA sequences above in order to find frequent patterns.
def ComputingFrequencies(Text, k):
FrequencyArray = dict()
# Initialize a dictionary with 0 for the count for each word.
for i in range(4**k):
FrequencyArray[i] = 0
# Add one to the count each time you encounter a pattern.
for i in range(len(Text) - (k-1)):
Pattern = Text[i:i+k]
j = PatternToNumber(Pattern)
FrequencyArray[j] += 1
return FrequencyArray
# ---------------------------------------------------------------------------------------- #
## FasterFrequentWords Algorithm
## INPUT: String DNA, int k
## OUTPUT: set of all k-words (subwords of DNA of length k) which appear most frequently
def FasterFrequentWords(Text, k):
FrequentPatterns = set()
FrequencyArray = ComputingFrequencies(Text, k)
MaxIndex = max(FrequencyArray, key=FrequencyArray.get)
MaxCount = FrequencyArray[MaxIndex]
for i in range(4**k - 1):
if FrequencyArray[i] == MaxCount:
Pattern = NumberToPattern(i, k)
FrequentPatterns.add(Pattern)
return FrequentPatterns
# ---------------------------------------------------------------------------------------- #
## FasterFrequentWords Algorithm, lower bound variant
## INPUT: String DNA, int k, int t
## OUTPUT: set of all k-words (subwords of DNA of length k) which appear at least t times.
def FasterFrequentWords_t(Text, k, t):
FrequentPatterns = set()
FrequencyArray = ComputingFrequencies(Text, k)
for i in range(4**k - 1):
if FrequencyArray[i] >= t:
Pattern = NumberToPattern(i, k)
FrequentPatterns.add(Pattern)
return FrequentPatterns
# ---------------------------------------------------------------------------------------- #
## ReverseComplement algorithm
## INPUT: A DNA strand Text
## OUTPUT: The reverse complement of Text (recall that A<->T and G<->C.)
def ReverseComplement(Text):
ReverseText = '' # Initialize empty string
for i in range(len(Text)):
b = len(Text) - (i+1) # Backwards index!
if Text[b] == 'A':
ReverseText += 'T'
elif Text[b] == 'T':
ReverseText += 'A'
elif Text[b] == 'G':
ReverseText += 'C'
elif Text[b] == 'C':
ReverseText += 'G'
else:
return 'Error'
return ReverseText
# ---------------------------------------------------------------------------------------- #
## PatternMatching algorithm
## INPUT: DNA string Genome, substring Pattern
## OUTPUT: List of indexes in Geneome where Pattern begins
def PatternMatching(Genome, Pattern):
indexes = []
for i in range(len(Genome) - len(Pattern) + 1):
if Genome[i: i+len(Pattern)] == Pattern:
indexes.append(i)
return indexes
# ---------------------------------------------------------------------------------------- #
## ClumpFinding algorithm
## INPUT: String Genome, int k, int L, int t
## OUTPUT: All distinct k-mers forming (L,t)-clumps in Genome.
def ClumpFinding(Genome, k, L, t):
clumps = set()
for i in range(len(Genome) - L + 1):
L_Window = Genome[i:i+L]
words = FasterFrequentWords_t(L_Window, k, t)
for word in words:
clumps.add(word)
return clumps
# ---------------------------------------------------------------------------------------- #
## A faster ClumpFinding algorithm
## INPUT: String Genome, int k, int L, int t
## OUTPUT: All distinct k-mers forming (L,t)-clumps in Genome.
def BetterClumpFinding(Genome, k, L, t):
clumps = dict()
FrequentPatterns = set()
for i in range(4**k): # Inititalize all clump vals to zero
clumps[i] = 0
Text = Genome[0:L]
FrequencyArray = ComputingFrequencies(Text, k)
for i in range(4**k):
if FrequencyArray[i] >= t:
clumps[i] += 1
for i in range(1,len(Genome) - L+1):
FirstPattern = Genome[i-1:i-1+k]
index = PatternToNumber(FirstPattern)
FrequencyArray[index] = FrequencyArray[index] - 1
LastPattern = Genome[i+L-k:i+L]
index = PatternToNumber(LastPattern)
FrequencyArray[index] = FrequencyArray[index] + 1
if FrequencyArray[index] >= t:
clumps[index] += 1
for i in range(4**k):
if clumps[i] >= 1:
Pattern = NumberToPattern(i, k)
FrequentPatterns.add(Pattern)
return FrequentPatterns
<file_sep>/IndividualFunctions/minimumSkewProblem.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
'''
Minimum Skew Problem: Find a position in a genome where the skew diagram attains a minimum.
Input: A DNA string Genome.
Output: All integer(s) i minimizing Skewi (Genome) among all values of i (from 0 to |Genome|).
'''
# Recall that skew(i, Genome) = # of occureences of G - # occurences of C
# on the first i nucleotides in the genome.
def skew(i, Genome):
# Store the values of skew in a list, Skew
# So, skew_list[j] is the value of skew at index j
# start with skew_list = [0] since the balance of G and C is initally zero.
skew_list = [0]
# To keep track of the skew values as we run through the string
count = 0
for nuc in range(i):
if (Genome[nuc] == 'A') or (Genome[nuc] == 'T'):
skew_list.append(count)
elif Genome[nuc] == 'G':
count += 1
skew_list.append(count)
elif Genome[nuc] == 'C':
count -= 1
skew_list.append(count)
elif Genome[nuc] == '\n':
continue
else:
print('An error occurred')
# for val in range(len(skew_list)):
# print(skew_list[val], end=' ')
return skew_list
# This algorithm returns a list of the indexes of minimum values in a list.
def MinListIndex(Some_List):
# Find the minimum
minimum = min(Some_List)
# Create a list to store the indexes.
min_index = []
for i in range(len(Some_List)):
if Some_List[i] == minimum:
min_index.append(i)
return min_index
def MinimumSkew(Genome):
# Get the list of skew funciton values
skew_list = skew(len(Genome), Genome)
# Get the list of indexes of occurences of min value.
min_index = MinListIndex(skew_list)
for val in range(len(min_index)):
print(min_index[val], end=' ')
#return min_index
<file_sep>/IndividualFunctions/FrequentWordsMismatchesAndReverseComplements.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
# Converts single digit to single symbol.
def SymbolToNumber(Value):
if Value == 'A':
return 0
elif Value == 'C':
return 1
elif Value == 'G':
return 2
elif Value == 'T':
return 3
else:
return 'Error'
# Final, recursive, attempt:
def PatternToNumber(Pattern):
if Pattern == '':
return 0
LastSymbol = Pattern[len(Pattern) - 1]
Prefix = Pattern[0:len(Pattern)-1]
return 4*PatternToNumber(Prefix) + SymbolToNumber(LastSymbol)
# Converts single digit to single symbol.
def NumberToSymbol(Value):
if Value == 0:
return 'A'
elif Value == 1:
return 'C'
elif Value == 2:
return 'G'
elif Value == 3:
return 'T'
else:
return 'Error'
# Final defnition of function converting numbers to patterns.
# Uses recursion.
def NumberToPattern(Number, k):
if k == 1:
return NumberToSymbol(Number)
Prefix = Number // 4
Remainder = Number % 4
Pattern = NumberToSymbol(Remainder)
PrefixPattern = NumberToPattern(Prefix, k-1)
return PrefixPattern + Pattern
# We now write code for ReverseComplement. Given a DNA string
# we wish to print out its opposite strand. Due to directionality
# it must be printed backwards, with the complement of the DNA
# value. Recall that A<->T and G<->C.
def ReverseComplement(Text):
ReverseText = '' # Initialize empty string
for i in range(len(Text)):
b = len(Text) - (i+1) # Backwards index!
if Text[b] == 'A':
ReverseText += 'T'
elif Text[b] == 'T':
ReverseText += 'A'
elif Text[b] == 'G':
ReverseText += 'C'
elif Text[b] == 'C':
ReverseText += 'G'
else:
return 'Error'
return ReverseText
'''
We say that position i in k-mers p1 … pk and q1 … qk is a mismatch if pi ≠ qi. For example, CGAAT and CGGAC have two mismatches.
The number of mismatches between strings p and q is called the Hamming distance between these strings and is denoted
HammingDistance(p, q).
Hamming Distance Problem: Compute the Hamming distance between two strings.
Input: Two strings of equal length.
Output: The Hamming distance between these strings.
'''
def HammingDistance(p, q):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] != q[i]:
hamming_dist += 1
#print hamming_dist
return hamming_dist
# The following is a variation on the HammingDistance function which quits running its calculations once a bound
# on the hamming distance has been reached. So for instance if the bound is d and p and q have a hamming distance of
# anything greater than d, it will simply return d+1.
def HammingDistance_bound(p, q, d):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] == q[i]:
continue
elif p[i] != q[i] and hamming_dist <= d:
hamming_dist += 1
continue
else:
break
#print hamming_dist
return hamming_dist
'''
We say that a k-mer Pattern appears as a substring of Text with at most d mismatches if there is some k-mer substring Pattern'
of Text having d or fewer mismatches with Pattern, i.e., HammingDistance(Pattern, Pattern') ≤ d. Our observation that a DnaA
box may appear with slight variations leads to the following generalization of the Pattern Matching Problem.
Approximate Pattern Matching Problem: Find all approximate occurrences of a pattern in a string.
Input: Strings Pattern and Text along with an integer d.
Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.
Code Challenge: Solve the Approximate Pattern Matching Problem.
'''
def ApproximatePatternMatching(Pattern, Text, d):
# Create a list to store indexes of approximate matches.
approx_match = []
for i in range(len(Text) - len(Pattern) + 1):
temp = HammingDistance_bound(Pattern, Text[i: i+len(Pattern)], d)
if temp <= d:
approx_match.append(str(i))
return approx_match
# Is called recursively until it returns a list of all d-neighbors.
# i is current length of neighbor candidates.
def Neighbors_Test(Pattern, Neighbors, i, d):
neighbors = []
if d == 0:
return [Pattern]
nucs = ['A', 'C', 'G', 'T']
candidates = []
for Neighbor in Neighbors:
for nuc in nucs:
candidates.append(Neighbor + nuc)
new_candidates = []
for candidate in candidates:
if (HammingDistance(candidate, Pattern[:i+1]) < d) and (len(candidate) < len(Pattern)):
new_candidates.append(candidate)
elif (HammingDistance(candidate, Pattern[:i+1]) < d) and (len(candidate) == len(Pattern)):
neighbors.append(candidate)
elif HammingDistance(candidate, Pattern[:i+1]) == d:
neighbors.append(candidate + Pattern[i+1:])
else:
continue
if i < len(Pattern):
more_neighbors = Neighbors_Test(Pattern, new_candidates, i+1, d)
neighbors += more_neighbors
elif i == len(Pattern):
even_more = []
for cand in new_candidates:
for nuc in nucs:
even_more.append(cand + nuc)
neighbors += even_more
return neighbors
# This function initializes the call to Neighbors_Test, which will run recursively until
# all d-neighbors have been found.
def Neighbors(Pattern, d):
neighbors_init = ['A', 'G', 'C', 'T']
return Neighbors_Test(Pattern, neighbors_init, 1, d)
'''
A most frequent k-mer with up to d mismatches in Text is simply a string
Pattern maximizing Countd(Text, Pattern) among all k-mers. Note that
Pattern does not need to actually appear as a substring of Text; for
example, as we already saw, AAAAA is the most frequent 5-mer with 1 mismatch
in AACAAGCTGATAAACATTTAAAGAG, even though it does not appear exactly in this
string. Keep this in mind while solving the following problem.
Frequent Words with Mismatches Problem: Find the most frequent k-mers with mismatches in a string.
Input: A string Text as well as integers k and d. (You may assume k ≤ 12 and d ≤ 3.)
Output: All most frequent k-mers with up to d mismatches in Text.
'''
def FrequentWordsMismatch_ReverseComplement(Text, k, d):
FrequentPatterns = [] # Initialize an empty set to store the frequent patterns found
close = [] # zero array, where
frequency_array = [] #initialize array to store frequency of each k-word
for i in range(4**k):
close.append(0)
frequency_array.append(0)
# First, find all d-neighbors of Text[i:i+k]
for i in range(len(Text) - k + 1):
neighborhood = Neighbors(Text[i:i+k], d)
# Mark these k-mers in the array, so that you only test k-mers which appear at least once.
for neighbor in neighborhood:
index = PatternToNumber(neighbor)
close[index] += 1
for i in range(4**k): # ie, For each possible (forward) k-mer:
if close[i] > 0: # ie, If the k-mer appears in original Text at least once
Pattern = NumberToPattern(i, k) # Convert the index to a pattern.
Pattern_Reverse = ReverseComplement(Pattern) # Find the reverse complement of this pattern
# Set the frequency equal to the number of times an approximate match occurs for the original pattern
frequency_array[i] = len(ApproximatePatternMatching(Pattern, Text, d))
# Also add the number of times an approximate match for the reverse complement appears
frequency_array[i] += len(ApproximatePatternMatching(Pattern_Reverse, Text, d))
max_count = max(frequency_array)
for i in range(4**k):
if frequency_array[i] == max_count:
Pattern = NumberToPattern(i, k)
ReversePattern = ReverseComplement(Pattern)
FrequentPatterns.append(Pattern)
FrequentPatterns.append(ReversePattern)
return FrequentPatterns
<file_sep>/IndividualFunctions/RandomizedMotifSearch.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
import random
import sys
import numpy
# Store as global variable since its values must be constant.
keys = 'ACGT'
## INPUT: A profile matrix Profile, a DNA pattern Pattern
## OUTPUT: The probability that Profile generates Pattern.
def ProbabilityGivenProfile(Profile, Pattern):
Probability = 1 # Initialize to 1
for letter_index in range(len(Pattern)):
letter = Pattern[letter_index]
if letter != 'A' and letter != 'G' and letter != 'C' and letter != 'T':
print('letter:', letter)
i = keys.index(letter)
Probability *= Profile[i][letter_index]
return Probability
## Profile-most k-mer problem.
## INPUT: String Text, int k, 4xk matrix Profile
## OUTPUT: the k-mer that was most likely to have been generated by Profile among all k-mers in Text
def ProfileMost_kmer(Text, Profile, k):
for i in range(len(Text) - k + 1):
Pattern = Text[i:i+k]
Probability = ProbabilityGivenProfile(Profile, Pattern)
if i == 0:
PMK = Pattern
ProbPMK = Probability
elif Probability >= ProbPMK:
PMK = Pattern
ProbPMK = Probability
return PMK
# INPUT: Motif matrix
# OUTPUT: Count matrix
def Count(Motif):
Count = []
# Initialize Count as a 4 x k matrix filled with zeros
for i in range(len(keys)):
temp_row = []
for j in range(len(Motif[0])):
temp_row.append(0)
Count.append(temp_row)
for j in range(len(Motif[0])): # Vary over columns...
for i in range(len(Motif)): # Vary over rows...
for k in range(len(keys)): # Vary over nucleotides...
if Motif[i][j] == keys[k]:
Count[k][j] += 1
return Count
# INPUT: Count matrix
# OUTPUT: Profile matrix
def Profile(Count):
N = list(numpy.sum(Count, 0))
N = N[0]
for i in range(len(Count)):
for j in range(len(Count[i])):
Count[i][j] /= N
Profile = Count
return Profile
# INPUT: Profile matrix
# OUTPUT: Consensus vector where Consensus[j] yields the most common letter in column j.
def Consensus(Profile):
Consensus = []
for j in range(len(Profile[0])): #Column
temp = []
for i in range(len(Profile)): #Rows
temp.append(Profile[i][j])
letter_max = max(set(temp), key=temp.count)
index_max = keys.index(letter_max)
Consensus.append(keys[index_max])
return Consensus
# INPUT: Motifs
## OUTPUT: Score(motifs), the total number of mismatches.
def Score(Motifs):
Consen = Consensus(Motifs)
Score = 0
for j in range(len(Motifs[0])): # Column
for i in range(len(Motifs)): # Rows
if Motifs[i][j] != Consen[j]:
Score += 1
return Score
## INPUT: Collection of strings DNA, int k, int t
## OUTPUT: Collection of strings BestMotifs, with pseudocounts,
## Resulting from applying RandomizedMotifSearch 1000 times.
def RandomizedMotifSearch(DNA, k, t):
Motifs = [] # Initialize random motifs
# Randomly select a k-mer from each string & store it as Motifs.
for dna in DNA:
r = random.randint(0, len(DNA[0]) - k)
Motifs.append(dna[r:r+k])
BestMotifs = Motifs # Initialize the BestMotifs to the random Motifs.
while True:
# Apply Laplace's Rule of Succession to form Profile.
CountMatrix = Count(Motifs)
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
Prof_Matrix = Profile(CountMatrix)
# Now, construct the Motifs matrix to be the collection of
# profile-most probable k-mers under Prof_Matrix
Motifs = []
for dna in DNA:
PMK = ProfileMost_kmer(dna, Prof_Matrix, k)
Motifs.append(PMK)
if Score(Motifs) < Score(BestMotifs):
BestMotifs = Motifs
else:
return BestMotifs
def RandomizedMotifSearch_CallAndRepeat(DNA, k, t, N):
most_common_matrix = []
score = sys.maxsize
ent = sys.maxsize
for n in range(N):
answers = RandomizedMotifSearch(DNA, k, t)
score_temp = Score(answers)
if score_temp < score:
score = score_temp
final_score = answers
return final_score
<file_sep>/IndividualFunctions/ApproximatePatternCount.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
# The following is a variation on the HammingDistance function which quits running its calculations once a bound
# on the hamming distance has been reached. So for instance if the bound is d and p and q have a hamming distance of
# anything greater than d, it will simply return d+1.
def HammingDistance_bound(p, q, d):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] == q[i]:
continue
elif p[i] != q[i] and hamming_dist <= d:
hamming_dist += 1
continue
else:
break
#print hamming_dist
return hamming_dist
'''
We say that a k-mer Pattern appears as a substring of Text with at most d mismatches if there is some k-mer substring Pattern'
of Text having d or fewer mismatches with Pattern, i.e., HammingDistance(Pattern, Pattern') ≤ d. Our observation that a DnaA
box may appear with slight variations leads to the following generalization of the Pattern Matching Problem.
Approximate Pattern Matching Problem: Find all approximate occurrences of a pattern in a string.
Input: Strings Pattern and Text along with an integer d.
Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.
Code Challenge: Solve the Approximate Pattern Matching Problem.
'''
def ApproximatePatternMatching(Pattern, Text, d):
# Create a list to store indexes of approximate matches.
approx_match = []
for i in range(len(Text) - len(Pattern) + 1):
temp = HammingDistance_bound(Pattern, Text[i: i+len(Pattern)], d)
if temp <= d:
approx_match.append(str(i))
return approx_match
'''
Our goal now is to modify our previous algorithm for the Frequent Words Problem in order to find DnaA boxes by identifying
frequent k-mers, possibly with mismatches. Given strings Text and Pattern as well as an integer d, we define
Countd(Text, Pattern) as the total number of occurrences of Pattern in Text with at most d mismatches. For example,
Count1(AACAAGCTGATAAACATTTAAAGAG, AAAAA) = 4 because AAAAA appears four times in this string with at most one mismatch:
AACAA, ATAAA, AAACA, and AAAGA. Note that two of these occurrences overlap.
'''
def Count(Pattern, Text, d):
total_count = len(ApproximatePatternMatching(Pattern, Text, d))
return total_count
<file_sep>/IndividualFunctions/Neighbors.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
'''
We say that position i in k-mers p1 … pk and q1 … qk is a mismatch if pi ≠ qi. For example, CGAAT and CGGAC have two mismatches.
The number of mismatches between strings p and q is called the Hamming distance between these strings and is denoted
HammingDistance(p, q).
Hamming Distance Problem: Compute the Hamming distance between two strings.
Input: Two strings of equal length.
Output: The Hamming distance between these strings.
'''
def HammingDistance(p, q):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] != q[i]:
hamming_dist += 1
#print hamming_dist
return hamming_dist
#Is called recursively until it returns a list of all d-neighbors.
# i is current length of neighbor candidates.
def Neighbors_Test(Pattern, Neighbors, i, d):
neighbors = []
if d == 0:
return [Pattern]
nucs = ['A', 'C', 'G', 'T']
candidates = []
for Neighbor in Neighbors:
for nuc in nucs:
candidates.append(Neighbor + nuc)
new_candidates = []
for candidate in candidates:
if (HammingDistance(candidate, Pattern[:i+1]) < d) and (len(candidate) < len(Pattern)):
new_candidates.append(candidate)
elif (HammingDistance(candidate, Pattern[:i+1]) < d) and (len(candidate) == len(Pattern)):
neighbors.append(candidate)
elif HammingDistance(candidate, Pattern[:i+1]) == d:
neighbors.append(candidate + Pattern[i+1:])
else:
continue
if i < len(Pattern):
more_neighbors = Neighbors_Test(Pattern, new_candidates, i+1, d)
neighbors += more_neighbors
elif i == len(Pattern):
even_more = []
for cand in new_candidates:
for nuc in nucs:
even_more.append(cand + nuc)
neighbors += even_more
return neighbors
# This function initializes the call to Neighbors_Test, which will run recursively until
# all d-neighbors have been found.
def Neighbors(Pattern, d):
neighbors_init = ['A', 'G', 'C', 'T']
return Neighbors_Test(Pattern, neighbors_init, 1, d)
<file_sep>/IndividualFunctions/HammingDistance.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
'''
We say that position i in k-mers p1 … pk and q1 … qk is a mismatch if pi ≠ qi. For example, CGAAT and CGGAC have two mismatches.
The number of mismatches between strings p and q is called the Hamming distance between these strings and is denoted
HammingDistance(p, q).
Hamming Distance Problem: Compute the Hamming distance between two strings.
Input: Two strings of equal length.
Output: The Hamming distance between these strings.
'''
def HammingDistance(p, q):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] != q[i]:
hamming_dist += 1
print(hamming_dist)
#return hamming_dist
<file_sep>/IndividualFunctions/GibbsSampler.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
import random
import sys
import numpy
# Store as global variable since its values must be constant.
keys = 'ACGT'
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
## INPUT: A profile matrix Profile, a DNA pattern Pattern
## OUTPUT: The probability that Profile generates Pattern.
def ProbabilityGivenProfile(Profile, Pattern):
Probability = 1 # Initialize to 1
#print(Profile)
for letter_index in range(len(Pattern)):
letter = Pattern[letter_index]
i = keys.index(letter)
Probability *= Profile[i][letter_index]
return Probability
# INPUT: Motif matrix
# OUTPUT: Count matrix
def Count(Motif):
Count = []
# Initialize Count as a 4 x k matrix filled with zeros
for i in range(len(keys)):
temp_row = []
for j in range(len(Motif[0])):
temp_row.append(0)
Count.append(temp_row)
for j in range(len(Motif[0])): # Vary over columns...
for i in range(len(Motif)): # Vary over rows...
for k in range(len(keys)): # Vary over nucleotides...
if Motif[i][j] == keys[k]:
Count[k][j] += 1
return Count
## Now we wish to compute the Profile of the Motif matrix, which is
## just the count matrix converted to percentages. Thus we wish to divide
## each entry in the count matrix by the total number of rows. The element
## Profile[i][j] represents the percentage of nucleotides in column j which
## take on value keys[i].
## For instance:
## INPUT:
## 2 0 2
## 4 4 5
## 1 1 1
## 3 5 2
##
## OUTPUT:
## .2 0 .2
## .4 .4 .5
## .1 .1 .1
## .3 .5 .2
# INPUT: Count matrix
# OUTPUT: Profile matrix
def Profile(Count):
N = list(numpy.sum(Count, 0))
N = N[0]
for i in range(len(Count)):
for j in range(len(Count[i])):
Count[i][j] /= N
Profile = Count
return Profile
# INPUT: Profile matrix
# OUTPUT: Consensus vector where Consensus[j] yields the most common letter in column j.
def Consensus(Profile_Mat):
Consensus = []
for j in range(len(Profile_Mat[0])): #Column
temp = []
for i in range(len(Profile_Mat)): #Rows
temp.append(Profile_Mat[i][j])
letter_max = max(set(temp), key=temp.count)
index_max = keys.index(letter_max)
Consensus.append(keys[index_max])
return Consensus
# INPUT: Motifs
## OUTPUT: Score(motifs), the total number of mismatches.
def Score(Motifs):
Consen = Consensus(Motifs)
Score = 0
for j in range(len(Motifs[0])): # Column
for i in range(len(Motifs)): # Rows
if Motifs[i][j] != Consen[j]:
Score += 1
return Score
## INPUT: Profile matrix, and a DNA string
## OUTPUT: A profile-randomly generated k-mer in DNAString
def ProfileRandomlyGeneratedKmer(Prof_Matrix, DNAString, k):
Probabilities = []
Strings = []
for i in range(len(DNAString) - k + 1):
Strings.append(DNAString[i:i+k])
for string in Strings:
probability = ProbabilityGivenProfile(Prof_Matrix, string)
Probabilities.append(probability)
SUM = sum(Probabilities)
weight_matrix = []
for probability in Probabilities:
weight_matrix.append(probability/SUM)
VALUE = numpy.random.choice(Strings, p = weight_matrix)
return VALUE
def GibbsSampler(DNA, k, t, N):
Motifs = []
# Randomly select k-mers Motifs in each string from DNA
for dna in DNA:
n = random.randint(0, len(DNA[0]) - k)
Motifs.append(dna[n:n+k])
# Initialize BestMotifs to Motifs
BestMotifs = Motifs.copy()
for j in range(1, 50*N+1):
i = random.randint(0, t-1)
# Profile = profile matrix constructed from all strings
# in Motif EXCEPT Motif[i]
Motifs_Cut = Motifs[:i] + Motifs[i+1:]
# Apply Laplace's Rule of Succession to form Profile from Motifs_Cut.
CountMatrix = Count(Motifs_Cut)
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
Prof_Matrix = Profile(CountMatrix)
I = ProfileRandomlyGeneratedKmer(Prof_Matrix, DNA[i], k)
Motifs[i] = I
if Score(Motifs) < Score(BestMotifs):
BestMotifs = Motifs.copy()
SCORE = Score(BestMotifs)
return BestMotifs
<file_sep>/4_GibbsSampler.py
'''
My solutions for the coding exercises in week 4 of Coursera's Bioinformatics 1.
Copyright 2016 <NAME>.
Includes:
Randomized Motif Search
Gibbs Sampler
'''
import random
import 3_Regulatory_Motifs as m3
import sys
import 2_PatternsAndFrequencies as me
import numpy
## INPUT: Collection of strings DNA, int k, int t
## OUTPUT: Collection of strings BestMotifs, with pseudocounts,
## Resulting from applying RandomizedMotifSearch 1000 times.
def RandomizedMotifSearch(DNA, k, t):
Motifs = [] # Initialize random motifs
i = 1##REMOVE
# Randomly select a k-mer from each string & store it as Motifs.
for dna in DNA:
r = random.randint(0, len(DNA[0]) - k)
Motifs.append(dna[r:r+k])
BestMotifs = Motifs # Initialize the BestMotifs to the random Motifs.
BestMotifs = ['GTC', 'CCC', 'ATA', 'GCT'] ##REMOVE
while True:
# Apply Laplace's Rule of Succession to form Profile.
CountMatrix = m3.Count(Motifs)
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
Prof_Matrix = m3.Profile(CountMatrix)
# Now, construct the Motifs matrix to be the collection of
# profile-most probable k-mers under Prof_Matrix
Motifs = []
for dna in DNA:
PMK = m3.ProfileMost_kmer(dna, Prof_Matrix, k)
Motifs.append(PMK)
if m3.Score(Motifs) < m3.Score(BestMotifs):
BestMotifs = Motifs
else:
return BestMotifs
print(i, BestMotifs)##REMOVE
i += 1##REMOVE
def RandomizedMotifSearch_CallAndRepeat(DNA, k, t, N):
most_common_matrix = []
score = sys.maxsize
ent = sys.maxsize
for n in range(N):
answers = RandomizedMotifSearch(DNA, k, t)
score_temp = m3.Score(answers)
if score_temp < score:
score = score_temp
final_score = answers
return final_score
## INPUT: Profile matrix, and a DNA string
## OUTPUT: A profile-randomly generated k-mer in DNAString
def ProfileRandomlyGeneratedKmer(Prof_Matrix, DNAString, k):
Probabilities = []
Strings = []
for i in range(len(DNAString) - k + 1):
Strings.append(DNAString[i:i+k])
for string in Strings:
probability = m3.ProbabilityGivenProfile(Prof_Matrix, string)
Probabilities.append(probability)
SUM = sum(Probabilities)
weight_matrix = []
for probability in Probabilities:
weight_matrix.append(probability/SUM)
VALUE = numpy.random.choice(Strings, p = weight_matrix)
return VALUE
def GibbsSampler(DNA, k, t, N):
Motifs = []
# Randomly select k-mers Motifs in each string from DNA
for dna in DNA:
n = random.randint(0, len(DNA[0]) - k)
Motifs.append(dna[n:n+k])
# Initialize BestMotifs to Motifs
BestMotifs = Motifs.copy()
for j in range(1, 5*N+1):
i = random.randint(0, t-1)
# Profile = profile matrix constructed from all strings
# in Motif EXCEPT Motif[i]
Motifs_Cut = Motifs[:i] + Motifs[i+1:]
# Apply Laplace's Rule of Succession to form Profile from Motifs_Cut.
CountMatrix = m3.Count(Motifs_Cut)
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
Prof_Matrix = m3.Profile(CountMatrix)
I = ProfileRandomlyGeneratedKmer(Prof_Matrix, DNA[i], k)
Motifs[i] = I
if m3.Score(Motifs) < m3.Score(BestMotifs):
BestMotifs = Motifs.copy()
SCORE = m3.Score(BestMotifs)
return BestMotifs
<file_sep>/README.md
# BioinformaticsAlgorithms
Python modules for Bioinformatics. Topics include:
- Locating origin of replication in genome
- Finding Regulatory Motifs
Based off my experience with Coursera's Bioinformatics Specialization course.
<file_sep>/IndividualFunctions/MotifEnumeration.py
# Copyright <NAME> 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
import itertools
import sys
# The following is a variation on the HammingDistance function which quits running its calculations once a bound
# on the hamming distance has been reached. So for instance if the bound is d and p and q have a hamming distance of
# anything greater than d, it will simply return d+1.
def HammingDistance_bound(p, q, d):
if len(p) != len(q):
return 'Invalid input'
hamming_dist = 0 # Initialize to zero
for i in range(len(p)):
if p[i] == q[i]:
continue
elif p[i] != q[i] and hamming_dist <= d:
hamming_dist += 1
continue
else:
break
#print hamming_dist
return hamming_dist
'''
We say that a k-mer Pattern appears as a substring of Text with at most d mismatches if there is some k-mer substring Pattern'
of Text having d or fewer mismatches with Pattern, i.e., HammingDistance(Pattern, Pattern') ≤ d. Our observation that a DnaA
box may appear with slight variations leads to the following generalization of the Pattern Matching Problem.
Approximate Pattern Matching Problem: Find all approximate occurrences of a pattern in a string.
Input: Strings Pattern and Text along with an integer d.
Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.
Code Challenge: Solve the Approximate Pattern Matching Problem.
'''
def ApproximatePatternMatching(Pattern, Text, d):
# Create a list to store indexes of approximate matches.
approx_match = []
for i in range(len(Text) - len(Pattern) + 1):
temp = HammingDistance_bound(Pattern, Text[i: i+len(Pattern)], d)
if temp <= d:
approx_match.append(str(i))
return approx_match
'''
Code Challenge: Implement MotifEnumeration (reproduced below).
Input: Integers k and d, followed by a collection of strings Dna.
Output: All (k, d)-motifs in Dna.
'''
# A brute-force algorithm for finding regulatory motifs in DNA strands.
# Notes that a regulatory (k,d)-motif is a k-mer which appears in every
# string from some collection of strings with at most d mismatches.
# It appears in scattered regions within the DNA strand.
# A brute-force algorithm like the one which follows is highly
# unlikely to be of any real use but is an interesting learning exercise.
# First we create the following function:
# INPUT: A k-mer Text, integer d.
# OUTPUT: Every possible k-mer which is a d-mismatch of Text.
def GenerateMismatches(Text, d):
TEXT = list(Text)
for position in itertools.combinations(range(len(Text)), d): # Every way to pick d letters from Text
for key in itertools.product(keys, repeat=d): # Every way to pick d chars from keys
Flag = False # Escape flag
ans = dict(zip(position, key)) # Create a dictionary which associates the
# string position with the key you wish to overwrite.
#print(ans)
yield ''.join([TEXT[p] if p not in position else ans[p] for p in range(len(Text))])
#ans = GenerateMismatches('AAA', 2)
#for an in ans:
# print(an, end=' ')
# INPUT: Integers k,d; List of strings DNA
# OUTPUT: List Motifs of all (k,d)-motifs within DNA
def MotifEnumeration(DNA, k, d):
Patterns = [] # Initialize an empty list to store patterns.
for Strand in DNA: # For each strand....
for i in range(len(Strand) - k + 1): # For each k-mer in each strand...
Pattern = Strand[i:i+k]
Mismatches = list(set(GenerateMismatches(Pattern, d)))
for Mismatch in Mismatches: # For each d-mismatch....
FoundFlags = []
for i in range(len(DNA)):
FoundFlags.append(0)
for index in range(len(DNA)):
dna = DNA[index]
temp = ApproximatePatternMatching(Mismatch, dna, d)
if temp: # If it appears in the strand
FoundFlags[index] += 1
if 0 not in FoundFlags:
Patterns.append(Mismatch)
return list(set(Patterns))
<file_sep>/3_Regulatory_Motifs.py
'''
Following is my code from week 3 of Coursera's Bioinformatics 1 course.
Copyright 2016 <NAME>.
Includes the following functions:
Motif Count
Profile Matrix
Consensus Vector
Brute-Force Algorithm for Finding Regulatory motifs
Faster Methods for finding Regulatory Motifs
'''
# Uses modules from previous weeks.
import 2_PatternsAndFrequencies as m2 # Module from week 2
import itertools
import numpy
import sys
# Store as global variable since its values must be constant.
keys = 'ACGT'
##
## Next we create the Count matrix, a 4 x k matrix which
## stores the number of times a nucleotide appears in each column.
##
## For example, input:
## AAA
## ACG
## AGA
## ATG
##
## Yields:
## Count = [ [4, 1, 2], # of times A appears in each col
## [0, 1, 0], # of times C appears in each col
## [0, 1, 2], # of times G appears in each col
## [0, 1, 0] ] # of times T appears in each col
##
# INPUT: Motif matrix
# OUTPUT: Count matrix
def Count(Motif):
Count = []
# Initialize Count as a 4 x k matrix filled with zeros
for i in range(len(keys)):
temp_row = []
for j in range(len(Motif[0])):
temp_row.append(0)
Count.append(temp_row)
# If the argument given is the file path name, call Motif() and
# generate its Motif matrix.
if type(Motif) == str:
Motif = Motifs(Motif)
print(Motif)
for j in range(len(Motif[0])): # Vary over columns...
for i in range(len(Motif)): # Vary over rows...
for k in range(len(keys)): # Vary over nucleotides...
print('(i,j)', i, j)
if Motif[i][j] == keys[k]:
Count[k][j] += 1
return Count
## Now we wish to compute the Profile of the Motif matrix, which is
## just the count matrix converted to percentages. Thus we wish to divide
## each entry in the count matrix by the total number of rows. The element
## Profile[i][j] represents the percentage of nucleotides in column j which
## take on value keys[i].
## For instance:
## INPUT:
## 2 0 2
## 4 4 5
## 1 1 1
## 3 5 2
##
## OUTPUT:
## .2 0 .2
## .4 .4 .5
## .1 .1 .1
## .3 .5 .2
# INPUT: Count matrix
# OUTPUT: Profile matrix
def Profile(Count):
N = list(numpy.sum(Count, 0))
N = N[0]
for i in range(len(Count)):
for j in range(len(Count[i])):
Count[i][j] /= N
Profile = Count
return Profile
# INPUT: Profile matrix
# OUTPUT: Consensus vector where Consensus[j] yields the most common letter in column j.
def Consensus(Profile):
Consensus = []
print('Prof:', Profile)
for j in range(len(Profile[0])): #Column
temp = []
for i in range(len(Profile)): #Rows
print('(i,j)', i, j)
temp.append(Profile[i][j])
letter_max = max(set(temp), key=temp.count)
index_max = keys.index(letter_max)
Consensus.append(keys[index_max])
return Consensus
'''
Code Challenge: Implement MotifEnumeration (reproduced below).
Input: Integers k and d, followed by a collection of strings Dna.
Output: All (k, d)-motifs in Dna.
'''
# A brute-force algorithm for finding regulatory motifs in DNA strands.
# Notes that a regulatory (k,d)-motif is a k-mer which appears in every
# string from some collection of strings with at most d mismatches.
# It appears in scattered regions within the DNA strand.
# A brute-force algorithm like the one which follows is highly
# unlikely to be of any real use but is an interesting learning exercise.
# First we create the following function:
# INPUT: A k-mer Text, integer d.
# OUTPUT: Every possible k-mer which is a d-mismatch of Text.
def GenerateMismatches(Text, d):
TEXT = list(Text)
for position in itertools.combinations(range(len(Text)), d): # Every way to pick d letters from Text
for key in itertools.product(keys, repeat=d): # Every way to pick d chars from keys
Flag = False # Escape flag
ans = dict(zip(position, key)) # Create a dictionary which associates the
# string position with the key you wish to overwrite.
#print(ans)
yield ''.join([TEXT[p] if p not in position else ans[p] for p in range(len(Text))])
# INPUT: Integers k,d; List of strings DNA
# OUTPUT: List Motifs of all (k,d)-motifs within DNA
def MotifEnumeration(DNA, k, d):
Patterns = [] # Initialize an empty list to store patterns.
for Strand in DNA: # For each strand....
for i in range(len(Strand) - k + 1): # For each k-mer in each strand...
Pattern = Strand[i:i+k]
Mismatches = list(set(GenerateMismatches(Pattern, d)))
for Mismatch in Mismatches: # For each d-mismatch....
FoundFlags = []
for i in range(len(DNA)):
FoundFlags.append(0)
for index in range(len(DNA)):
dna = DNA[index]
temp = mod2.ApproximatePatternMatching(Mismatch, dna, d)
if temp: # If it appears in the strand
FoundFlags[index] += 1
if 0 not in FoundFlags:
Patterns.append(Mismatch)
return list(set(Patterns))
## Instead of generating all possible motifs in DNA we instead generate k-mers in each
## string in DNA. We then compute the minimum Hamming Distance between any k-mer
## and Text.
##
## We perform this computation for each string in DNA then add together the resulting
## minimums.
## INPUT: string Pattern, list of strings DNA
## OUTPUT: d(DNA, Pattern)
def DistanceBetweenPatternAndStrings(DNA, Pattern):
k = len(Pattern)
distance = 0
for Text in DNA:
HammingDistanceMax = sys.maxsize
for i in range(len(Text) - k + 1):
test_string = Text[i:i+k]
condition = m2.HammingDistance(Pattern, test_string)
if HammingDistanceMax > condition:
HammingDistanceMax = condition
distance = distance + HammingDistanceMax
return distance
##
## INPUT: Int k, list of strings DNA.
## OUTPUT: k-mer Pattern that minimizes d(Pattern, DNA) among all k-mers Pattern.
## (Return the first one if there are multiple.)
##
def MedianString(DNA, k):
distance = sys.maxsize # Initialize distance to "infinity"
Median = ''
for val in range(4**k):
Pattern = m2.NumberToPattern(val, k)
test = DistanceBetweenPatternAndStrings(DNA, Pattern)
if distance > test:
distance = test
Median = Pattern
return Median
## INPUT: A profile matrix Profile, a DNA pattern Pattern
## OUTPUT: The probability that Profile generates Pattern.
def ProbabilityGivenProfile(Profile, Pattern):
Probability = 1 # Initialize to 1
#print('pattern:', Pattern)
for j in range(len(Pattern)):
i = keys.index(Pattern[j])
Probability *= Profile[i][j]
return Probability
## Profile-most k-mer problem.
## INPUT: String Text, int k, 4xk matrix Profile
## OUTPUT: the k-mer that was most likely to have been generated by Profile among all k-mers in Text
def ProfileMost_kmer(Text, Profile, k):
for i in range(len(Text) - k + 1):
Pattern = Text[i:i+k]
Probability = ProbabilityGivenProfile(Profile, Pattern)
if i == 0:
PMK = Pattern
ProbPMK = Probability
elif Probability >= ProbPMK:
PMK = Pattern
ProbPMK = Probability
return PMK
# INPUT: Motifs
## OUTPUT: Score(motifs), the total number of mismatches.
def Score(Motifs):
Consen = Consensus(Motifs)
Score = 0
for j in range(len(Motifs[0])): # Column
for i in range(len(Motifs)): # Rows
if Motifs[i][j] != Consen[j]:
Score += 1
return Score
## INPUT: Integers k, t and list of strings DNA
## OUTPUT: Collection of strings BestMotifs.
## This algorithm runs WITHOUT pseudocounts, vastly damaging its reliability.
## We improve on this algorithm after.
def GreedyMotifSearch_noPC(DNA, k, t):
BestMotifs = [] # BestMotifs will be a motif matrix constructed from the first kmer in each string in DNA
for dna in DNA:
BestMotifs.append(dna[:k])
FirstString = DNA[0]
for i in range(len(FirstString) - k + 1):
Motif = []
Motif.append(FirstString[i:i+k]) # So, for each k-mer in DNA[0]...
ProfMatrix = Profile(Count(Motif)) # ...Build profile from this k-mer
for l in range(1, t):
NextMotif = ProfileMost_kmer(DNA[l], ProfMatrix, k)
Motif.append(NextMotif)
ProfMatrix = Profile(Count(Motif))
if Score(Motif) < Score(BestMotifs):
BestMotifs = Motif
return BestMotifs
## INPUT: Integers k, t and list of strings DNA
## OUTPUT: Collection of strings BestMotifs.
## This algorithm runs WITH pseudocounts
def GreedyMotifSearch(DNA, k, t):
BestMotifs = [] # BestMotifs will be a motif matrix constructed from the first kmer in each string in DNA
for dna in DNA:
BestMotifs.append(dna[:k])
FirstString = DNA[0]
for i in range(len(FirstString) - k + 1):
Motif = []
Motif.append(FirstString[i:i+k]) # So, for each k-mer in DNA[0]...
CountMatrix = Count(Motif) # ... apply LaPlace's rule to implement Pseudocounts....
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
ProfMatrix = Profile(CountMatrix) # ...Build profile from this k-mer
for l in range(1, t):
NextMotif = ProfileMost_kmer(DNA[l], ProfMatrix, k)
Motif.append(NextMotif)
CountMatrix = Count(Motif)
for row in range(len(CountMatrix)):
for col in range(len(CountMatrix[0])):
CountMatrix[row][col] += 1
ProfMatrix = Profile(CountMatrix)
if Score(Motif) < Score(BestMotifs):
BestMotifs = Motif
return BestMotifs
| f4db060f0ea93f8a8c0da29e66e782ac7d74d8ae | [
"Markdown",
"Python"
] | 18 | Python | alexanderwood/bioinformatics-algorithms | e22b50fc7235e63f095aa6756cef469776e3d362 | 97c33df2f5fc6264f880ef58620b65b720b03622 |
refs/heads/master | <repo_name>fastz123/4th_revolution<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/10_cust_rcpt_test.sql
CREATE TABLE RCPT_ACCT
(
SSN CHAR(13) NOT NULL,
ACCT_NO CHAR(10) PRIMARY KEY NOT NULL,
NEW_DT DATE,
CNCL_DT DATE,
RCPT_AMT DECIMAL(15,0)
);
INSERT INTO RCPT_ACCT VALUES ('5707121111000', '578221', '2012-03-26',null , 500000);
INSERT INTO RCPT_ACCT VALUES ('7706302222111', '687322', '2011-12-22', '2013-12-01', 0);
INSERT INTO RCPT_ACCT VALUES ('6508112222333', '658720', '2013-06-08',null , 41324);
INSERT INTO RCPT_ACCT VALUES ('8204073333111', '554520', '2013-09-28', null, 5678740);
INSERT INTO RCPT_ACCT VALUES ('5707121111000', '656421', '2009-11-17', null, 354210);
INSERT INTO RCPT_ACCT VALUES ('7706302222111', '668721', '2010-07-27', null, 547700);
INSERT INTO RCPT_ACCT VALUES ('8204073333111', '223620', '2010-09-11', null, 1000357);
INSERT INTO RCPT_ACCT VALUES ('8204073333111', '275123', '2013-11-26', null, 123000);
select * from rcpt_acct;
CREATE TABLE CUST_PARTY
(
SSN CHAR(13) PRIMARY KEY NOT NULL,
PARTY_NM CHAR(10) NOT NULL,
CUST_ID CHAR(10) NOT NULL,
TEL_NO CHAR(20) NOT NULL,
MOBILE_NO CHAR(20) NOT NULL
);
INSERT INTO CUST_PARTY VALUES ('5707121111000', 'AR KIM', '5670', '02-555-6678', '010-1111-1111');
INSERT INTO CUST_PARTY VALUES ('6912081111222', 'SH HONG', '2357', '031-4456-9887', '010-2222-2222');
INSERT INTO CUST_PARTY VALUES ('8311221111333', 'MK KANG', '3977', '051-999-8888', '010-3333-3333');
INSERT INTO CUST_PARTY VALUES ('7105252222000', 'JH KIM', '8988', '032-333-1111', '010-4444-4444');
INSERT INTO CUST_PARTY VALUES ('7706302222111', 'JH LEE', '7702', '033-111-3355', '010-5555-5555');
INSERT INTO CUST_PARTY VALUES ('6508112222333', 'JH RYU', '3574', '02-6666-4444', '010-6666-6666');
INSERT INTO CUST_PARTY VALUES ('8204073333111', '<NAME>', '5670', '02-2222-1111', '010-7777-7777');
INSERT INTO CUST_PARTY VALUES ('8911293333222', '<NAME>', '6989', '031-224-2222', '010-8888-8888');
INSERT INTO CUST_PARTY VALUES ('9011034444111', '<NAME>', '5570', '033-333-3333', '010-9999-9999');
select * from cust_party;
#1. 현재 살아있는 고객의 휴대폰 번호를 찾고, 살아있는 계좌수를 기준으로 오름차순 정렬하시오
select cust_party.SSN , MOBILE_NO,count(ACCT_NO)
from rcpt_acct,cust_party
where rcpt_acct.SSN=cust_party.ssn and CNCL_DT is null
group by rcpt_acct.ssn
order by count(Acct_no);
#2. 현재 살아있는 계좌수가 두 개 이상이고 수신잔액의 총합이 50만원 이상인 고객의
# 주민번호, 이름, 휴대전화,
# 계좌수, 수신잔액 총합을 주민번호기준으로 오름차순 정렬하시오.
select r.ssn,party_nm,MOBILE_NO,count(ACCT_NO),sum(RCPT_AMT)
from rcpt_acct as r,cust_party as c
where r.ssn=c.ssn and CNCL_DT is null
group by r.ssn
having count(ACCT_NO)>=2 and sum(RCPT_AMT)>=500000;
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/webdb.sql
create database webdb;
use webdb;
show databases;
show tables;
create table pet (
name varchar(20),
owner varchar(20),
species varchar(20),
sex char(1),
birth date,
death date);
show tables;
drop table pet;
insert ignore into pet values ('Claws', 'Gwen','cat', 'm', '1994-03-17', null);
insert ignore into pet values ('Buffy', 'Harold','dog', 'f', '1989-05-13', null);
insert ignore into pet values ('Fang', 'Benny','dog', 'm', '1990-08-27', null);
insert ignore into pet values ('Bowser', 'Diane','dog', 'm', '1979-08-31', '1995-17-29');
insert ignore into pet values ('Chirpy', 'Gwen','bird', 'f', '1998-09-11', null);
insert ignore into pet values ('Whistler', 'Gwen','bird','m' '1997-12-09', null);
insert ignore into pet values ('Slim', 'Benny','snake', 'm', '1996-04-29', null);
select * from pet;
load data local infile 'C:/Temp/pettb.txt' into table pet;
select * from pet;
select * from pet where name ='Bowser';
select * from pet where birth >= '1998-01-01';
select * from pet where species = 'dog' and sex = 'f';
select * from pet where species = 'snake' or species='bird';
select name, birth from pet;
select name, birth from pet order by birth;
select name, birth from pet order by birth desc;
select name from pet where death is not null;
select name from pet where death is null;
select * from pet where name like 'b%';
select * from pet where name like '%fy';
select * from pet where name like '%w%';
select * from pet where name like '_____';
select * from pet where name regexp '^b';
select * from pet where name regexp 'fy$';
select count(*) from pet;
select * from pet;
update pet set species='dog' where name='claws';
select * from pet;
set sql_safe_updates = 0;
update pet set species = 'pig' where birth < '1990-01-01';
select * from pet;
use sqldb;
select name, height from usertbl where name like '_종신';
select name, height from usertbl where height > 177;
-- 김경호 보다 키가 큰 사람들..
select name, height from usertbl
where height > (select height from usertbl
where name='김경호');
-- 주소가 경남인 사람의 키 보다 큰 사람들.. 이름, 키..
select name, height from usertbl
where height > (select height from usertbl
where addr='경남');
select name, height from usertbl
where height > all(select height from usertbl
where addr='경남');
select name, height from usertbl
where height > any(select height from usertbl
where addr='경남');
-- 경남에 거주하는 사람의 키와 동일한 사람들(키, 이름)..
select name, height from usertbl
where height in (select height from usertbl
where addr='경남');
select * from usertbl;
-- 이름과 가입일자 출력/ 가입일자 기준 오름차순정렬
select name, mdate from usertbl order by mdate;
select name, mdate from usertbl order by mdate desc;
select name, height from usertbl
order by name asc , height desc;
-- 주소가 중복되지 않는
use sqldb;
select distinct addr from usertbl;
/*
-- employee db에서 employee table의 emp_no,
-- hire_date를 출력하되 hire_date 오름차순으로 */
show databases;
use employees;
select emp_no, hire_date from employees
order by hire_date asc;
-- 입사시기가 가장 오래된 5명, emp_no, hire_date
select emp_no, hire_date from employees
order by hire_date asc limit 5;
select emp_no, hire_date from employees
order by hire_date asc limit 10, 10;
use sqldb;
create table buytbl2 (select * from buytbl);
select * from buytbl2;
show tables;
create table buytbl3 (select userid,
prodname from buytbl);
select * from buytbl3;
select * from buytbl;
select * from usertbl;
-- group by
select userid, sum(amount) from buytbl
group by userid;
-- 칼럼명을 아이디, 총구매개수
select userid 아이디, sum(amount) 총구매개수
from buytbl group by userid;
select userid 아이디, avg(amount) 평균구매개수
from buytbl group by userid;
select * from buytbl;
select userid 아이디, sum(amount*price) 총구매금액
from buytbl group by userid;
select userid 아이디, sum(amount*price) 총구매금액
from buytbl group by userid order by 총구매금액;
select max(height), min(height) from usertbl;
select name, height from usertbl where
height = (select max(height) from usertbl) or
height = (select min(height) from usertbl);
select name, height from usertbl where
height in ((select max(height) from usertbl),
(select min(height) from usertbl));
select count(*) from usertbl;
select count(*) as 전화번호등록자수 from usertbl
where mobile1 is not null;
select count(mobile1) as 전화번호등록자수
from usertbl;
select * from usertbl;
/*
1. 아이디별별 총구매금액
2. 아이디별 총구매금액이 1000 이상인 데이터*/
select * from buytbl;
select userid, sum(price*amount) as tm
from buytbl group by userid;
select userid, sum(price*amount) as tm
from buytbl
group by userid
having tm > 1000;
-- group by 시 조건은 having ( where는 안 됨)
select userid, sum(price*amount) as tm
from buytbl
group by userid
having tm > 1000
order by tm;
;
-- table 조작
-- testtbl1: id(int), username(char(3)), age(int)
use sqldb;
create table testtbl1 (id int, username char(3)
, age int);
insert into testtbl1 values (1, '홍길동', 25);
insert into testtbl1(id, username)
values (2, '설현');
insert into testtbl1(username, age, id)
values ('초아', 26, 3);
select * from testtbl1;
create table testtbl2(
id int auto_increment primary key,
username char(3),
age int);
insert into testtbl2 values (null, '지민', 25);
insert into testtbl2 values (null, '유나', 22);
insert into testtbl2 values (null, '유경', 21);
select * from testtbl2;
use sqldb;
-- 대량 데이터 테이블 생성
create table testtbl5
(select emp_no, first_name, last_name
from employees.employees);
create table testtbl4(
id int, fname varchar(50), lname varchar(50));
insert into testtbl4
select emp_no, first_name, last_name
from employees.employees;
-- 데이터 수정
select * from testtbl4 where fname='Parto';
update testtbl4
set lname = '없음'
where fname='Parto';
use sqldb;
select * from buytbl;
update buytbl set price = price*1.5;
select * from buytbl;
-- 데이터 삭제
select * from testtbl4 where fname='Aamer';
delete from testtbl4 where fname='Aamer';
select count(*) from testtbl4 where fname='Parto';
delete from testtbl4 where fname='Parto' limit 100;<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/08장_exercise.sql
-- Table & Constraints
DROP DATABASE IF EXISTS ShopDB;
DROP DATABASE IF EXISTS ModelDB;
DROP DATABASE IF EXISTS sqlDB;
DROP DATABASE IF EXISTS tableDB;
DROP DATABASE tableDB;
CREATE DATABASE tableDB;
USE tableDB;
DROP TABLE IF EXISTS buyTbl, userTbl;
CREATE TABLE userTbl -- 회원 테이블
( userID char(8) , -- 사용자 아이디 -- 컬럼명 데이터타입, - 반복
name nvarchar(10) , -- 이름
birthYear int, -- 출생년도
addr nchar(2), -- 지역(경기,서울,경남 등으로 글자만 입력) -- unicode(전세계 문자 표현 표준), utf-8
mobile1 char(3), -- 휴대폰의국번(011, 016, 017, 018, 019, 010 등) -- ascii - 영문 문자 인코딩 방식
mobile2 char(8), -- 휴대폰의 나머지 전화번호(하이픈 제외)
height smallint, -- 키
mDate date -- 회원 가입일
);
CREATE TABLE buyTbl -- 구매 테이블
( num int, -- 순번(PK)
userid char(8),-- 아이디(FK)
prodName nchar(6), -- 물품명
groupName nchar(4) , -- 분류
price int , -- 단가
amount smallint -- 수량
);
USE tableDB;
DROP TABLE IF EXISTS buyTbl, userTbl;
CREATE TABLE userTbl
( userID char(8) NOT NULL ,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
CREATE TABLE buyTbl
( num int NOT NULL ,
userid char(8) NOT NULL ,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL
);
-- 제약조건(constraints) -
/* 제약조건
primary key - unique, not null
foreign key -
unique
default
null, not null
*/
DROP TABLE IF EXISTS buyTbl, userTbl;
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY, -- 회원 아이디, 대부분 테이블에 설정, 하나 이상의 열에 가능
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
CREATE TABLE buyTbl
( num int NOT NULL PRIMARY KEY,
userid char(8) NOT NULL ,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL
);
use tabledb;
DROP TABLE IF EXISTS buyTbl;
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY, -- auto_increment - primary key or unique Key
userid char(8) NOT NULL ,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL
);
DROP TABLE IF EXISTS buyTbl;
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY ,
userid char(8) NOT NULL,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL
, FOREIGN KEY(userid) REFERENCES userTbl(userID) -- foreign key
);
INSERT INTO userTbl VALUES('LSG', '이승기', 1987, '서울', '011', '1111111', 182, '2008-8-8');
INSERT INTO userTbl VALUES('KBS', '김범수', 1979, '경남', '011', '2222222', 173, '2012-4-4');
INSERT INTO userTbl VALUES('KKH', '김경호', 1971, '전남', '019', '3333333', 177, '2007-7-7');
select * from usertbl;
INSERT INTO buyTbl VALUES(NULL, 'JYP', '모니터', '전자', 200, 1);
INSERT INTO buyTbl VALUES(NULL, 'KBS', '노트북', '전자', 1000, 1);
INSERT INTO buyTbl VALUES(NULL, 'KBS', '운동화', NULL, 30, 2); -- error
select * from buytbl;
INSERT ignore INTO buyTbl VALUES(NULL, 'JYP', '모니터', '전자', 200, 1);
INSERT ignore INTO buyTbl VALUES(NULL, 'KBS', '노트북', '전자', 1000, 1);
INSERT ignore INTO buyTbl VALUES(NULL, 'KBS', '운동화', NULL, 30, 2); -- error
select * from buytbl;
-- <Primary Key> -- 3가지 방법
drop table usertbl;
alter table buytbl drop foreign key buytbl_ibfk_1;
drop table usertbl;
-- 1
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
DESCRIBE userTBL;
DROP TABLE IF EXISTS userTbl;
-- 2
CREATE TABLE userTbl
( userID char(8) NOT NULL,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL,
constraint primary KEY PK_userTbl_userID (userID)
);
CREATE TABLE userTbl
( userID char(8) NOT NULL,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL,
PRIMARY KEY PK_userTbl_userID (userID)
);
DROP TABLE IF EXISTS userTbl;
CREATE TABLE userTbl
( userID char(8) NOT NULL,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL,
PRIMARY KEY (userID)
);
-- 3
CREATE TABLE userTbl
( userID char(8) NOT NULL,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
ALTER TABLE userTbl
ADD CONSTRAINT PK_userTbl_userID
PRIMARY KEY (userID);
ALTER TABLE userTbl
ADD CONSTRAINT PK_userTbl_userID
unique KEY (addr);
-- 2개의 칼럼을 묶어서 primary key지정
DROP TABLE IF EXISTS prodTbl;
CREATE TABLE prodTbl
( prodCode CHAR(3) NOT NULL,
prodID CHAR(4) NOT NULL,
prodDate DATETIME NOT NULL,
prodCur CHAR(10) NULL
);
ALTER TABLE prodTbl
ADD CONSTRAINT PK_prodTbl_proCode_prodID
PRIMARY KEY (prodCode, prodID) ;
DROP TABLE IF EXISTS prodTbl;
CREATE TABLE prodTbl
( prodCode CHAR(3) NOT NULL,
prodID CHAR(4) NOT NULL,
prodDate DATETIME NOT NULL,
prodCur CHAR(10) NULL,
CONSTRAINT PK_prodTbl_proCode_prodID
PRIMARY KEY (prodCode, prodID)
);
DROP TABLE IF EXISTS prodTbl;
CREATE TABLE prodTbl
( prodCode CHAR(3) NOT NULL,
prodID CHAR(4) NOT NULL,
prodDate DATETIME NOT NULL,
prodCur CHAR(10) NULL,
PRIMARY KEY (prodCode, prodID)
);
-- Foreign Key
-- 두 테이블의 관계 선언, 데이터의 무결성을 보장
-- 기준키 테이블, 외래 키 테이블
-- 외래키 테이블에 데이터를 입력 시, 기준키 테이블에 데이터가 존재해야
-- 기준키 테이블의 참조 열은 반드시 unique or primary key이어야
DROP TABLE IF EXISTS buyTbl, userTbl;
CREATE TABLE userTbl
( userID char(8) NOT NULL primary key,
name varchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
-- 1
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY ,
userid char(8) NOT NULL ,
FOREIGN KEY(userid) REFERENCES userTbl(userID),
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL
);
DROP TABLE IF EXISTS buyTbl;
-- 2
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY,
userid char(8) NOT NULL,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL,
CONSTRAINT FK_userTbl_buyTbl FOREIGN KEY(userid) REFERENCES userTbl(userID)
);
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY,
userid char(8) NOT NULL,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL,
FOREIGN KEY(userid) REFERENCES userTbl(userID)
);
-- 3
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY,
userid char(8) NOT NULL,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL,
FOREIGN KEY(userid) REFERENCES userTbl(userID)
);
DROP TABLE IF EXISTS buyTbl, userTbl ;
-- 4
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY,
name nvarchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
CREATE TABLE buyTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY,
userid char(8) NOT NULL,
prodName char(6) NOT NULL,
groupName char(4) NULL ,
price int NOT NULL,
amount smallint NOT NULL
);
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userid)
REFERENCES userTbl(userID);
show index from buytbl;
show index from usertbl;
-- on delete cascade, on update cascade
-- 기준 테이블의 데이터가 변경 시 외래키 테이블에도 자동 반영
ALTER TABLE buyTbl
DROP FOREIGN KEY FK_userTbl_buyTbl; -- 외래 키 제거
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userID)
REFERENCES userTbl (userID)
ON UPDATE CASCADE;
-- Unique
DROP TABLE IF EXISTS buyTbl, userTbl;
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY,
name nvarchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL,
email char(30) NULL UNIQUE
);
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY,
name nvarchar(10) NOT NULL,
birthYear int NOT NULL,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL,
email char(30) NULL ,
CONSTRAINT AK_email UNIQUE (email)
);
alter table usertbl
add constraint email_unique_key unique key (email);
-- Defualt
drop database testdb;
CREATE DATABASE IF NOT EXISTS testDB;
use testDB;
DROP TABLE IF EXISTS userTbl;
-- 1
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY,
name varchar(10) NOT NULL,
birthYear int NOT NULL DEFAULT -1,
addr char(2) NOT NULL DEFAULT '서울',
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL DEFAULT 170,
mDate date NULL
);
use testDB;
DROP TABLE IF EXISTS userTbl;
CREATE TABLE userTbl
( userID char(8) NOT NULL PRIMARY KEY,
name varchar(10) NOT NULL,
birthYear int NOT NULL ,
addr char(2) NOT NULL,
mobile1 char(3) NULL,
mobile2 char(8) NULL,
height smallint NULL,
mDate date NULL
);
-- 2
ALTER TABLE userTbl
ALTER COLUMN birthYear SET DEFAULT -1;
ALTER TABLE userTbl
ALTER COLUMN addr SET DEFAULT '서울';
ALTER TABLE userTbl
ALTER COLUMN height SET DEFAULT 170;
-- 값이 직접 명기되면 DEFAULT로 설정된 값은 무시된다.
INSERT INTO userTbl VALUES ('WB', '원빈', 1982, '대전', '019', '9876543', 176, '2017.5.5');
-- default 문은 DEFAULT로 설정된 값을 자동 입력한다.
INSERT INTO userTbl VALUES ('LHL', '이혜리', default, default, '011', '1234567', default, '2019.12.12');
-- 열이름이 명시되지 않으면 DEFAULT로 설정된 값을 자동 입력한다
INSERT INTO userTbl(userID, name) VALUES('KAY', '김아영');
SELECT * FROM userTbl;
-- <데이터 압축> --
-- 시스템변수 확인
SHOW VARIABLES LIKE 'innodb_file_format'; -- barracuda
SHOW VARIABLES LIKE 'innodb_large_prefix'; -- on
CREATE DATABASE IF NOT EXISTS compressDB;
USE compressDB;
CREATE TABLE normalTBL( emp_no int , first_name varchar(14));
CREATE TABLE compressTBL( emp_no int , first_name varchar(14))
ROW_FORMAT=COMPRESSED ;
INSERT INTO normalTbl
(SELECT emp_no, first_name FROM employees.employees);
INSERT INTO compressTBL
(SELECT emp_no, first_name FROM employees.employees);
SHOW TABLE STATUS FROM compressDB;
DROP DATABASE IF EXISTS compressDB;
-- 임시 테이블 - 잠시 사용하는 테이블
-- 세션 내에서만 사용, 생성한 클라이언트만 사용 가능
-- 임시테이블 삭제 - drop table, workbench 종료, mysql서비스 재시작
USE employees;
CREATE TEMPORARY TABLE IF NOT EXISTS tempTBL (id INT, name CHAR(5));
CREATE TEMPORARY TABLE IF NOT EXISTS employees (id INT, name CHAR(5));
DESCRIBE tempTBL;
DESCRIBE employees;
INSERT INTO tempTBL VALUES (1, 'This');
INSERT INTO employees VALUES (2, 'MySQL');
SELECT * FROM tempTBL;
SELECT * FROM employees;
USE employees;
SELECT * FROM tempTBL;
SELECT * FROM employees;
USE employees;
SELECT * FROM employees;
-- 테이블 삭제
-- drop table 테이블 이름
-- 외래키 제약 조건의 기준 테이블은 삭제할 수 없다
-- 먼저 외래키 테이블을 삭제해야 한다.
-- buytbl을 먼저 삭제 후 usertbl을 삭제해야
use tabledb;
show index from prodtbl;
show index from usertbl;
-- 테이블 수정--
-- cf. insert, delete, update
-- alter table table_name add column
-- alter table table_name change column
-- alter table table_name drop column/ primary key/ foreign key
USE tableDB;
ALTER TABLE userTbl
ADD homepage VARCHAR(30) -- 열추가
DEFAULT 'http://www.hanbit.co.kr' -- 디폴트값
NULL; -- Null 허용함
select * from usertbl;
ALTER TABLE userTbl
DROP COLUMN mobile1;
select * from usertbl;
ALTER TABLE userTbl
CHANGE COLUMN name uName VARCHAR(20) NULL ;
select * from usertbl;
show index from usertbl;
/*
ALTER TABLE userTbl
ADD CONSTRAINT PK_userTbl_userID
PRIMARY KEY (userID);
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userID)
REFERENCES userTbl (userID)
*/
ALTER TABLE userTbl
DROP PRIMARY KEY; -- error
show index from usertbl;
show index from buytbl;
ALTER TABLE buyTbl
DROP FOREIGN KEY fk_usertbl_buytbl;
ALTER TABLE userTbl
DROP PRIMARY KEY;
show index from usertbl;
drop database tabledb;
create database tabledb;
USE tableDB;
DROP TABLE IF EXISTS buyTbl, userTbl;
CREATE TABLE userTbl
( userID char(8),
name nvarchar(10),
birthYear int,
addr nchar(2),
mobile1 char(3),
mobile2 char(8),
height smallint,
mDate date
);
CREATE TABLE buyTbl
( num int AUTO_INCREMENT PRIMARY KEY,
userid char(8),
prodName nchar(6),
groupName nchar(4),
price int ,
amount smallint
);
INSERT INTO userTbl VALUES('LSG', '이승기', 1987, '서울', '011', '1111111', 182, '2008-8-8');
INSERT INTO userTbl VALUES('KBS', '김범수', NULL, '경남', '011', '2222222', 173, '2012-4-4');
INSERT INTO userTbl VALUES('KKH', '김경호', 1871, '전남', '019', '3333333', 177, '2007-7-7');
INSERT INTO userTbl VALUES('JYP', '조용필', 1950, '경기', '011', '4444444', 166, '2009-4-4');
INSERT INTO buyTbl VALUES(NULL, 'KBS', '운동화', NULL , 30, 2);
INSERT INTO buyTbl VALUES(NULL,'KBS', '노트북', '전자', 1000, 1);
INSERT INTO buyTbl VALUES(NULL,'JYP', '모니터', '전자', 200, 1);
INSERT INTO buyTbl VALUES(NULL,'BBK', '모니터', '전자', 200, 5);
select * from usertbl;
select * from buytbl;
ALTER TABLE userTbl
ADD CONSTRAINT PK_userTbl_userID
PRIMARY KEY (userID);
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userID)
REFERENCES userTbl (userID); -- error - BBK
DELETE FROM buyTbl WHERE userid = 'BBK';
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userID)
REFERENCES userTbl (userID);
INSERT INTO buyTbl VALUES(NULL,'BBK', '모니터', '전자', 200, 5); -- 오류
SET foreign_key_checks = 0; -- 외래키조건 해제
INSERT INTO buyTbl VALUES(NULL, 'BBK', '모니터', '전자', 200, 5);
INSERT INTO buyTbl VALUES(NULL, 'KBS', '청바지', '의류', 50, 3);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '메모리', '전자', 80, 10);
INSERT INTO buyTbl VALUES(NULL, 'SSK', '책' , '서적', 15, 5);
INSERT INTO buyTbl VALUES(NULL, 'EJW', '책' , '서적', 15, 2);
INSERT INTO buyTbl VALUES(NULL, 'EJW', '청바지', '의류', 50, 1);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '운동화', NULL , 30, 2);
INSERT INTO buyTbl VALUES(NULL, 'EJW', '책' , '서적', 15, 1);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '운동화', NULL , 30, 2);
SET foreign_key_checks = 1; -- 외래키조건 재설정
-- check - mysql에서 지원하지 않는다
select * from usertbl;
ALTER TABLE userTbl
ADD CONSTRAINT CK_birthYear
CHECK (birthYear >= 1900 AND birthYear <= YEAR(CURDATE())) ;
INSERT INTO userTbl VALUES('SSK', '성시경', 1979, '서울', NULL , NULL , 186, '2013-12-12');
INSERT INTO userTbl VALUES('LJB', '임재범', 1963, '서울', '016', '6666666', 182, '2009-9-9');
INSERT INTO userTbl VALUES('YJS', '윤종신', 1969, '경남', NULL , NULL , 170, '2005-5-5');
INSERT INTO userTbl VALUES('EJW', '은지원', 1972, '경북', '011', '8888888', 174, '2014-3-3');
INSERT INTO userTbl VALUES('JKW', '조관우', 1965, '경기', '018', '9999999', 172, '2010-10-10');
INSERT INTO userTbl VALUES('BBK', '바비킴', 1973, '서울', '010', '0000000', 176, '2013-5-5');
select * from usertbl;
-- update
UPDATE userTbl SET userID = 'VVK' WHERE userID='BBK'; -- error
select * from usertbl;
SET foreign_key_checks = 0;
UPDATE userTbl SET userID = 'VVK' WHERE userID='BBK';
SET foreign_key_checks = 1;
SELECT B.userid, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처' -- 4건 부족
FROM buyTbl B
INNER JOIN userTbl U
ON B.userid = U.userid ;
SELECT COUNT(*) FROM buyTbl;
select * from buytbl;
select * from usertbl;
SELECT B.userid, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처'
FROM buyTbl B
LEFT OUTER JOIN userTbl U
ON B.userid = U.userid
ORDER BY B.userid ;
SET foreign_key_checks = 0;
UPDATE userTbl SET userID = 'BBK' WHERE userID='VVK';
SET foreign_key_checks = 1;
ALTER TABLE buyTbl
DROP FOREIGN KEY FK_userTbl_buyTbl;
-- on update cascade
alter table usertbl
add constraint primary key (userid);
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userID)
REFERENCES userTbl (userID)
ON UPDATE CASCADE;
UPDATE userTbl SET userID = 'VVK' WHERE userID='BBK';
SELECT B.userid, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처' -- 함계 수정
FROM buyTbl B
INNER JOIN userTbl U
ON B.userid = U.userid
ORDER BY B.userid;
select * from buytbl;
DELETE FROM userTbl WHERE userID = 'VVK'; -- 삭제 안 딤
ALTER TABLE buyTbl
DROP FOREIGN KEY FK_userTbl_buyTbl;
ALTER TABLE buyTbl
ADD CONSTRAINT FK_userTbl_buyTbl
FOREIGN KEY (userID)
REFERENCES userTbl (userID)
ON UPDATE CASCADE
ON DELETE CASCADE;
DELETE FROM userTbl WHERE userID = 'VVK'; -- 함께 삭제됨
SELECT * FROM buyTbl ;
ALTER TABLE userTbl
DROP COLUMN birthYear ;
-- < view > --
--
USE tableDB;
CREATE VIEW v_userTbl
AS
SELECT userid, name, addr FROM userTbl;
SELECT * FROM v_userTbl; -- 뷰를 테이블이라고 생각해도 무방
/*
1. 보안에 도움
2. 복잡한 쿼리를 단순화
*/
SELECT U.userid, U.name, B.prodName, U.addr, CONCAT(U.mobile1, U.mobile2) AS '연락처'
FROM userTbl U
INNER JOIN buyTbl B
ON U.userid = B.userid ;
CREATE VIEW v_userbuyTbl
AS
SELECT U.userid, U.name, B.prodName, U.addr, CONCAT(U.mobile1, U.mobile2) AS '연락처'
FROM userTbl U
INNER JOIN buyTbl B
ON U.userid = B.userid ;
SELECT * FROM v_userbuyTbl WHERE name = '김범수';
show tables;
CREATE DATABASE sqlDB;
USE sqlDB;
drop table buytbl;
drop table usertbl;
CREATE TABLE userTbl -- 회원 테이블
( userID CHAR(8) NOT NULL PRIMARY KEY, -- 사용자아이디
name VARCHAR(10) NOT NULL, -- 이름
birthYear INT NOT NULL, -- 출생년도
addr CHAR(2) NOT NULL, -- 지역(경기,서울,경남 식으로 2글자만입력)
mobile1 CHAR(3), -- 휴대폰의 국번(011, 016, 017, 018, 019, 010 등)
mobile2 CHAR(8), -- 휴대폰의 나머지 전화번호(하이픈제외)
height SMALLINT, -- 키
mDate DATE -- 회원 가입일
);
CREATE TABLE buyTbl -- 회원 구매 테이블
( num INT AUTO_INCREMENT NOT NULL PRIMARY KEY, -- 순번(PK)
userID CHAR(8) NOT NULL, -- 아이디(FK)
prodName CHAR(6) NOT NULL, -- 물품명
groupName CHAR(4) , -- 분류
price INT NOT NULL, -- 단가
amount SMALLINT NOT NULL, -- 수량
FOREIGN KEY (userID) REFERENCES userTbl(userID)
);
INSERT INTO userTbl VALUES('LSG', '이승기', 1987, '서울', '011', '1111111', 182, '2008-8-8');
INSERT INTO userTbl VALUES('KBS', '김범수', 1979, '경남', '011', '2222222', 173, '2012-4-4');
INSERT INTO userTbl VALUES('KKH', '김경호', 1971, '전남', '019', '3333333', 177, '2007-7-7');
INSERT INTO userTbl VALUES('JYP', '조용필', 1950, '경기', '011', '4444444', 166, '2009-4-4');
INSERT INTO userTbl VALUES('SSK', '성시경', 1979, '서울', NULL , NULL , 186, '2013-12-12');
INSERT INTO userTbl VALUES('LJB', '임재범', 1963, '서울', '016', '6666666', 182, '2009-9-9');
INSERT INTO userTbl VALUES('YJS', '윤종신', 1969, '경남', NULL , NULL , 170, '2005-5-5');
INSERT INTO userTbl VALUES('EJW', '은지원', 1972, '경북', '011', '8888888', 174, '2014-3-3');
INSERT INTO userTbl VALUES('JKW', '조관우', 1965, '경기', '018', '9999999', 172, '2010-10-10');
INSERT INTO userTbl VALUES('BBK', '바비킴', 1973, '서울', '010', '0000000', 176, '2013-5-5');
INSERT INTO buyTbl VALUES(NULL, 'KBS', '운동화', NULL , 30, 2);
INSERT INTO buyTbl VALUES(NULL, 'KBS', '노트북', '전자', 1000, 1);
INSERT INTO buyTbl VALUES(NULL, 'JYP', '모니터', '전자', 200, 1);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '모니터', '전자', 200, 5);
INSERT INTO buyTbl VALUES(NULL, 'KBS', '청바지', '의류', 50, 3);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '메모리', '전자', 80, 10);
INSERT INTO buyTbl VALUES(NULL, 'SSK', '책' , '서적', 15, 5);
INSERT INTO buyTbl VALUES(NULL, 'EJW', '책' , '서적', 15, 2);
INSERT INTO buyTbl VALUES(NULL, 'EJW', '청바지', '의류', 50, 1);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '운동화', NULL , 30, 2);
INSERT INTO buyTbl VALUES(NULL, 'EJW', '책' , '서적', 15, 1);
INSERT INTO buyTbl VALUES(NULL, 'BBK', '운동화', NULL , 30, 2);
select * from buytbl;
select * from usertbl;
USE sqlDB;
CREATE VIEW v_userbuyTbl
AS
SELECT U.userid AS 'USER ID', U.name AS 'USER NAME', B.prodName AS 'PRODUCT NAME',
U.addr, CONCAT(U.mobile1, U.mobile2) AS 'MOBILE PHONE'
FROM userTbl U
INNER JOIN buyTbl B
ON U.userid = B.userid;
SELECT `USER ID`, `USER NAME` FROM v_userbuyTbl; -- 주의! 백틱을 사용한다.` `
# SELECT 'USER ID', 'USER NAME' FROM v_userbuyTbl;
ALTER VIEW v_userbuyTbl
AS
SELECT U.userid AS '사용자 아이디', U.name AS '이름', B.prodName AS '제품 이름',
U.addr, CONCAT(U.mobile1, U.mobile2) AS '전화 번호'
FROM userTbl U
INNER JOIN buyTbl B
ON U.userid = B.userid ;
SELECT `이름`,`전화 번호` FROM v_userbuyTbl;
DROP VIEW v_userbuyTbl;
/*
view를 사용하는 이유
1. 보안에 도움이 된다.
2. 복잡한 쿼리를 단순화한다.
*/
USE sqlDB;
CREATE OR REPLACE VIEW v_userTbl
AS
SELECT userid, name, addr FROM userTbl;
DESCRIBE v_userTbl;
# SHOW CREATE VIEW v_userTbl;
select * from v_usertbl;
UPDATE v_userTbl SET addr = '부산' WHERE userid='JKW' ;
INSERT INTO v_userTbl(userid, name, addr) VALUES('KBM','김병만','충북') ;
select * from usertbl;
CREATE VIEW v_sum
AS
SELECT userid AS 'userid', SUM(price*amount) AS 'total'
FROM buyTbl GROUP BY userid;
SELECT * FROM v_sum;
SELECT * FROM INFORMATION_SCHEMA.VIEWS -- 시스템에 저장된 모든 뷰
WHERE TABLE_SCHEMA = 'sqlDB' AND TABLE_NAME = 'v_sum';
CREATE VIEW v_height177
AS
SELECT * FROM userTbl WHERE height >= 177 ;
SELECT * FROM v_height177 ;
DELETE FROM v_height177 WHERE height < 177 ;
INSERT INTO v_height177 VALUES('KBM', '김병만', 1977 , '경기', '010', '5555555', 158, '2019-01-01') ;
INSERT INTO v_height177 VALUES('KBM', '김병만', 1977 , '경기', '010', '5555555', 158, '2019-01-01') ; -- 뷰에는 보이지 않지만 입력된다
select * from usertbl;
ALTER VIEW v_height177
AS
SELECT * FROM userTbl WHERE height >= 177
WITH CHECK OPTION ; -- 입력차단
INSERT INTO v_height177 VALUES('WDT', '서장훈', 2006 , '서울', '010', '3333333', 155, '2019-3-3') ;
CREATE VIEW v_userbuyTbl
AS
SELECT U.userid, U.name, B.prodName, U.addr, CONCAT(U.mobile1, U.mobile2) AS mobile
FROM userTbl U
INNER JOIN buyTbl B
ON U.userid = B.userid ;
INSERT INTO v_userbuyTbl VALUES('PKL','박경리','운동화','경기','00000000000','2020-2-2'); -- 두 개 이상의 테이블이 연결된 뷰는 업데이트할 수 없다
DROP TABLE IF EXISTS buyTbl, userTbl;
SELECT * FROM v_userbuyTbl;
CHECK TABLE v_userbuyTbl; -- 뷰의 상태 체크
-- </실습 6> --
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/2019.06.13sql.sql
SELECT * FROM shopdb.membertbl;
use employees;
show tables;
select * from dept_manager;
use shopdb;
select membername, memberaddress from membertbl;
select * from membertbl where membername='지운이';
show databases;
select * from membertbl;
create table test (id int);
show tables;
create table test1 ( id int, address char);
show tables;
select * from test1;
insert into test values (1);
select * from test;
insert into test (id) values (1);
insert into test1 (id, address) values (3, 's');
select * from test1;
use employees;
select * from shopdb.membertbl;
show tables;
select * from titles;
select first_name, last_name, gender -- 이름과 열을 가지고 옴.
from employees;
/*
select * from titles;
*/
show databases;
use employees;
show tables;
show table status;
describe employees;
select first_name, gender from employees;
select first_name as 이름, gender as 성별 from employees;
drop database if exists sqldb;
create database sqldb;
show databases;
use sqldb;
create table usertbl
( userid char(8) not null primary key,
name varchar(10) not null,
birthyear int not null,
addr char(2) not null,
mobile1 char(3),
mobile2 char(8),
height smallint,
mdate date);
show tables;
create table buytbl (
num int auto_increment not null primary key,
userid char(8) not null,
prodname char(6) not null,
groupname char(4),
price int not null,
amount smallint not null,
foreign key (userid) references usertbl(userid));
insert into usertbl values('LSG','이승기',1987,'서울','011','1111111',182,'2008-8-8');
insert into usertbl values('KBS','김범수',1979,'경남','011','2222222',173,'2012-4-4');
insert into usertbl values('KKH','김경호',1971,'전남','019','3333333',177,'2007-7-7');
insert into usertbl values('JYP','조용필',1950,'경기','011','4444444',166,'2009-4-4');
insert into usertbl values('SSK','성시경',1979,'서울',null,null,186,'2013-12-12');
insert into usertbl values('LJB','임재범',1963,'서울','016','6666666',182,'2009-9-9');
insert into usertbl values('YJS','윤종신',1969,'경남',null,null,170,'2005-5-5');
insert into usertbl values('EJW','은지원',1972,'경북','011','8888888',174,'2014-3-3');
insert into usertbl values('JKW','조관우',1965,'경기','018','9999999',172,'2010-10-10');
insert into usertbl values('BBK','바비킴',1973,'서울','010','0000000',176,'2013-5-5');
select * from usertbl;
insert into buytbl values(null, 'KBS', '운동화', null, 30, 2);
insert into buytbl values(null, 'KBS', '노트북', '전자', 1000, 1);
insert into buytbl values(null, 'JYP', '모니터', '전자', 200, 1);
insert into buytbl values(null, 'BBK', '모니터', '전자', 200, 5);
insert into buytbl values(null, 'KBS', '청바지', '의류', 50, 3);
insert into buytbl values(null, 'BBK', '메모리', '전자', 80, 10);
insert into buytbl values(null, 'SSK', '책', '서적', 15, 5);
insert into buytbl values(null, 'EJW', '책', '서적', 15, 2);
insert into buytbl values(null, 'EJW', '청바지', '의류', 30, 2);
insert into buytbl values(null, 'BBK', '운동화', null, 30, 2);
insert into buytbl values(null, 'EJW', '책', '서적', 15, 1);
insert into buytbl values(null, 'BBK', '운동화', null, 30, 2);
select * from buytbl;
select * from buytbl where price>50;
use sqldb;
show tables;
select * from usertbl where name='김경호';
select * from usertbl where birthyear>'1970' and height>=182;
select * from usertbl where height>=180 and height<=182;
select * from usertbl where addr='전남' or addr='경북' or addr='경남';
select name,height from usertbl where name like '김%';
select name,height from usertbl where name like '_종신';
select name,height from usertbl where height>177;
select name,height from usertbl where (height > (select height from usertbl where name='김경호'));
select name,height from usertbl where (height > all(select height from usertbl where addr='경남'));
select name,height from usertbl where (height > any(select height from usertbl where addr='경남'));
select * from usertbl where (height = any(select height from usertbl where addr='경남'));
select * from usertbl where (height in (select height from usertbl where addr='경남'));
select name,mdate from usertbl order by mdate;
select name,height from usertbl order by name,height desc;
select distinct addr from usertbl;
use employees;
select emp_no,hire_date from employees order by hire_date;
select emp_no from employees order by hire_date limit 5;
use sqldb;
create table buytbl2(
select * from buytbl
);
select * from buytbl2;
#group by
select userid,sum(amount) from buytbl group by userid;
select userid as 아이디, sum(amount) as 총구매개수 from buytbl group by userid;
select userid 아이디, avg(amount) 구매량평균 from buytbl group by userid;
select * from buytbl;
select userid 아이디, sum(amount*price) 총구매금액 from buytbl group by userid order by 총구매금액;
select max(height) 최대키 ,min(height) 최소키 from usertbl;
#가장키큰사람이름과 키 뽑기
select name,height from usertbl where height = (select max(height) from usertbl) or height = (select min(height) from usertbl);
select name,height from usertbl where height in ((select max(height) from usertbl),(select min(height) from usertbl));
select name,height from usertbl where height = (select max(height) from usertbl) or height = (select min(height) from usertbl);
select count(*) from usertbl;
select count(*) from usertbl where mobile1 is not null and mobile2 is not null;
select count(mobile1) from usertbl;
#아이디별 총 구매금액
select userid,sum(amount*price) as tm from buytbl group by userid;
#아이디별 총 구매금액이 1000 이상인 데이터 // group by시 조건은 having으로 해주어야함
select userid,sum(amount*price) as tm from buytbl group by userid having tm>1000;
create table testtbl1 (id int,username char(3), age int);
show tables;
drop table testtbl1;
insert into testtbl1 values(1, '홍길동', 25);
insert into testtbl1(id,username) values (2,'설현');
insert into testtbl1(username,age,id) values('초아',26,3);
select * from testtbl1;
create table testtbl2(
id int auto_increment primary key,
username char(3),
age int
);
insert into testtbl2 values(null,'지민',25);
insert into testtbl2 values(null,'유나',22);
insert into testtbl2 values(null,'유경',21);
select * from testtbl2;
use sqldb;
create table testtbl5(
select emp_no,first_name,last_name from employees.employees
);
select * from testtbl5;
create table testtbl4(
id int, fname varchar(50), lname varchar(50)
);
insert into testtbl4
select emp_no,first_name,last_name
from employees.employees;
#데이터 수정
select * from testtbl4 where fname='Parto';
update testtbl4 set lname='없음' where fname='Parto';
select * from buytbl;
update buytbl set price = price*1.5;
update buytbl set price = price*1/1.5;
#데이터 삭제
select * from testtbl4 where fname='Aamer';
delete from testtbl4 where fname='Aamer';
select count(*) from testtbl4 where fname='Parto';
delete from testtbl4 where fname='Parto' limit 100;
/*--------------------------------2019-06-13--------------------------------------------*/
create database webdb;
use webdb;
show databases;
create table pet(
name varchar(20),
owner varchar(20),
species varchar(20),
sex char(1),
birth date,
death date
);
show tables;
drop table pet;
insert into pet values('Fluffy','Harold','cat','f','1999-02-04',null);
load data local infile 'C:/Users/user/pet_table.txt' into table pet;
select * from pet;
select * from pet where name='Bowser';
select * from pet where birth >= '1998-01-01';
select * from pet where species='dog' and sex='f';
select * from pet where species='snake' or species='bird';
select name,birth from pet;
select name,birth from pet order by birth;
select name,birth from pet order by birth desc;
select name from pet where death is not null;
select name from pet where death is null;
set sql_safe_updates=0;
update pet set death=null where death='0000-00-00';
select * from pet where name like 'b%';
select * from pet where name like '%fy';
select * from pet where name like '%w%';
select * from pet where name like '_____';
select * from pet where name regexp '^b';
select * from pet where name regexp 'fy$';
select *from pet;
#drop table pet;
update pet set species='dog' where name='claws';
update pet set species='pig' where birth<'1990-01-01'
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/5_company_query_test.sql
create database company;
use company;
drop table cust_info;
CREATE TABLE CUST_INFO
(
RESIDENCE_ID CHAR(13) PRIMARY KEY NOT NULL,
FIRST_NM CHAR(10) NOT NULL,
LAST_NM CHAR(10) NOT NULL,
ANNL_PERF DECIMAL(15,2),
sex int
);
INSERT INTO CUST_INFO VALUES ('8301111999999', 'JIHUN', 'KIM', 330.08,1);
INSERT INTO CUST_INFO VALUES ('7012012888888', 'JINYOUNG', 'LEE', 857.61,2);
INSERT INTO CUST_INFO VALUES ('6705302777666', 'MIJA', 'HAN', -76.77,2);
INSERT INTO CUST_INFO VALUES ('8411011555666', 'YOUNGJUN', 'HA', 468.54,1);
INSERT INTO CUST_INFO VALUES ('7710092666777', 'DAYOUNG', 'SUNG', -890,2);
INSERT INTO CUST_INFO VALUES ('7911022444555', 'HYEJIN', 'SEO', 47.44,2);
select * from cust_info;
SET SQL_SAFE_UPDATES =0;
#1.남성은 man로 여성은 woman로 출력하시어
select (case when sex=1 then 'm' else 'f' end) from cust_info;
#2. 이메일을 보내기 위해 성과 이름을 결합하시오
select concat(first_nm,' ',last_nm) from cust_info;
#3. 고객의 수익을 소수점 첫 째자리에서 반올림하시오.
select round(annl_perf,1) from cust_info;
create table vendor_info(
id int,
name char(10),
country char(20));
insert into vendor_info values
(1, 'sue', 'germany'),
(2, 'david', 'switzerland'),
(3, 'sam', 'france'),
(4, 'jihoon', 'brazil'),
(5, 'sunwoo', 'france'),
(6, 'berney', 'italy'),
(7, 'sandy', 'germany'),
(8, 'young', 'korea') ;
select * from vendor_info;
#1. 이름을 소문자로 변환해서 출력하시오
select lower(name) from vendor_info;
#2. 이름을 대문자로 변환해서 출력하시오
select upper(name) from vendor_info;
#3. 이름의 길이를 name_len라는 별칭으로 출력하시오
select char_length(name) as name_len from vendor_info;
#4. 이름의 두 번째에서 네 번째 글자를 출력하고 name_str이라는 별칭으로 출력하시오
select substring(name,2,4) as name_str from vendor_info;
create table clerk (
id int,
staff_nm char(5),
def_nm char(10),
gender char(2),
birth_dt date,
emp_flag char(2) );
insert into clerk values
(135, '이민성', '마케팅부', 'm', '1984-02-11', 'y'),
(142, '김선명', '영업지원부', 'm', '1971-12-08', 'y'),
(121, '신지원', '리스크부', 'f', '1978-05-28','y'),
(334, '고현정', '전략기획부', 'f', '1965-01-12', 'y'),
(144, '이기동', '마케팅분석부', 'm', '1981-03-03', 'y'),
(703, '송지희', '검사부', 'f', '1985-05-14', 'f'),
(732, '연승환', '기업영업지원부', 'm', '1990-01-26', 'y'),
(911, '이명준', '여의도지점', 'm', '1988-06-11', 'n');
select * from clerk;
#1. 직원의 생일을 기준으로 내림차순으로 정렬하시오
select birth_dt from clerk order by birth_dt desc;
#2. 직원의 나이를 구하시오
select left(current_timestamp(),4)- left(birth_dt,4) from clerk;
#3. 직원의 생일에 1달을 더한 날짜를 구하시오
select birth_dt,adddate(birth_dt,30) from clerk;
#4. 남성의 평균 나이와 여성의 평균 나이를 구하시오
select avg(left(current_timestamp(),4)- left(birth_dt,4)) as average_age , gender from clerk group by gender;
#5. 평균 연령이 가장 낮은 부서는 어디인가
select def_nm,avg(left(current_timestamp(),4)- left(birth_dt,4)) as avg_age from clerk group by def_nm order by avg_age limit 1;
select * from cust_info;
/*
1. 고객이 남성이면 1, 여성이면 2를 출력하시오.
2. 남성의 평균 수익과 여성의 평균 수익을 구하시오
3. 수익이 가장 높은 고객의 이름을 출력하시오
*/
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/0_sql_test__BI.sql
# sales database 생성
# sales database 선택
# test table 생성
# test column 생성 - datatype - DECIMAL(5,3)
# 값 10.5 입력
# test테이블 출력
# 값 입력 - 12.55555
## 칼럼 추가 `test_fl` - FLOAT(5,3) NULL AFTER `test`
## 값 입력 - test_fl : 14.55555 / test : 16.55555
## test table 삭제
/*
sales 테이블 생성
purchase_number - INT ,
date_of_purchase - DATE NOT NULL,
customer_id - INT,
item_code - VARCHAR(10) NOT NULL
*/
create table sales (
purchase_number INT auto_increment primary key,
date_of_purchase DATE NOT NULL,
customer_id INT,
item_code VARCHAR(10) NOT NULL
);
/*
customers 테이블 생성
customer_id - INT,
first_name - varchar(255),
last_name - varchar(255),
email_address - varchar(255),
number_of_complaints - int
*/
create table customers (
customer_id INT,
first_name varchar(255),
last_name varchar(255),
email_address varchar(255),
number_of_complaints int
);
## sales 테이블의 purchase_number를 primary key로 지정 - 2가지 방범/ not null로 지정/ auto_increment로 지정
## customers 테이블의 customer_id를 primary key로 지정
create table customers (
customer_id INT primary key,
first_name varchar(255),
last_name varchar(255),
email_address varchar(255),
number_of_complaints int
);
create table customers (
customer_id int,
first_name varchar(255),
last_name varchar(255),
email_address varchar(255),
number_of_complaints int,
primary key(customer_id)
);
# customers table에 customer_id에 primary key 제약조건 추가
# sales 테이블에 purchase_number 칼럼에에 primary key 제약조건 추가
# customers, sales 테이블의 정보 확인
items 테이블 생성,
primary key - item_id
item_id - VARCHAR(255),
item - VARCHAR(255),
unit_price - NUMERIC(10 , 2 ),
company_id - VARCHAR(255),
create table items(
item_id VARCHAR(255) primary key,
item VARCHAR(255),
unit_price NUMERIC(10 , 2 ),
company_id VARCHAR(255)
);
companies 테이블 생성,
primary key - company_id
company_id - VARCHAR(255),
company_name - VARCHAR(255),
headquarters_phone_number - INT(12),
create table companies(
company_id VARCHAR(255),
company_name VARCHAR(255),
headquarters_phone_number INT(12),
primary key(company_id)
);
## alter - customers테이블 - email_address - unique key로 지정
## customers table에 외래키를 추가하고 삭제 시 자동 없데이트 옵션
## customers테이블 gender column를 추가 - enum('M', 'F')
## customers 테이블 값 추가 - '01', 'John', 'Mackinley', 'M', '<EMAIL>', 0
## customers 테이블 값 추가 - customer_id, first_name, last_name, gender, email_address -> 2, 'Peter', 'Figaro', 'M', '<EMAIL>'
## companies table의 company_name을 not null로 추가
/*
alter table companies add constraint not null(company_name);
alter table companies modify column company_name not null;
ALTER TABLE customers
CHANGE COLUMN number_of_complaints number_of_complaints INT DEFAULT 0;
*/
## company_name을 varchar(200), null로 변경
## employees database 선택
## first_name, last_name 출력
## first_name이 'Denis'인 데이터 출력
# 이름이 'Denis' 이고 남성인 데이터 출력
## 이름이 'Denis' 또는 'Elvis'인 데이터 출력
## 이름이 'Cathie' , 'Mark', 'Nathan'에 해당하는 row출력 - in 사용
## 이름이 'Cathie' , 'Mark', 'Nathan'에 해당하지 않는 row출력
## 이름이 Mar로 시작하는 row출력
## 이름이 ar로 끝나는 row출력
## 이름이 Mar로 시작하고 4글자인 row출력
# 이름에 jack을 포한하는 row를 출력
# hire_date이 '1990-01-01' 과 '2000-01-01' 사이인 row출력
# salary가 66000과 70000 사이인 row출력
# 이름이 null인 row출력
# 이름이 null이 아닌 row출력
# salary가 150000 이상인 데이터 출력
# 중복없는 title 데이터 출력
# 사원번호 갯수를 출력
# 중복없는 이름의 갯수 출력
# 연봉 100000이상인 사람의 총 수
# 메니저인 사람의 총 수 출력
# 성울 선순위, 이름을 차순위로 내림차순 정렬
# 연봉 상위 100명 출력
#중복 이름이 100 이상인 이름 목록 출력
# 평균 연봉이 120000 이상인 직원 번호와 평균 임금 출력
# 중복 이름이 200번 이상인 사람의 이름과 중복된 이름의 갯수 출력
## departments에서 dept_no가 'd010'인 데이터의 dept_name을 'data analysis'로 수정하시오
## employees 테이블에서 emp_no가 999903인 데이터를 삭제하시오
## departments에서 dept_no가 'd010'인 데이터를 삭제하시오
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/2019.06.14.sql
select cast('2020-10-19 12:35:29.123' AS date ) as 'Date';
select cast('2020-10-19 12:35:29.123' as time) as time;
select cast('2020-10-19 12:35:29.123' as datetime) as datetime;
use sqldb;
set @myVar1 = 5;
set @myVar2 = 3;
set @myVar3 = 4.25;
set @myVar4 = '가수 이름==>';
select @myVar1;
select @myVar2+@myVar3;
select @myVar4, Name from usertbl Where height>180;
set @myVar1 = 3;
prepare myquery from 'select name, height from usertbl order by height Limit ?';
Execute myquery using @myVar1;
use sqldb;
select avg(amount) as '평균 구매 개수' from buytbl;
select cast(avg(amount) as signed integer) as '평균구매개수' from buytbl;
select cast('2020$12$12' as date);
select cast('2020/12/12' as date);
select cast('2020%12%12' as date);
SELECT num, CONCAT(CAST(price AS CHAR(10)), 'X', CAST(amount AS CHAR(4)) ,'=' ) AS '단가X수
량',price*amount AS '구매액' FROM buyTbl ;
CREATE TABLE PERF
(
CUST_ID CHAR(5) PRIMARY KEY NOT NULL,
CUST_NM CHAR(10) NOT NULL,
CUST_BIRTH DATE,
VISIT_CNT DECIMAL(15,0),
SALES_AMT DECIMAL(15,0),
SALES_CNT DECIMAL(15,0)
);
INSERT INTO PERF VALUES ('56456', '모형건', '1982-01-24', 123, 3700000, 24);
INSERT INTO PERF VALUES ('65412', '이상훈', '1984-05-10', 23, 467200, 14);
INSERT INTO PERF VALUES ('23472', '이상희', '1978-02-27', 117, 2237065, 23);
INSERT INTO PERF VALUES ('27896', '모영길', '1982-05-11', 37, 123721, 2);
INSERT INTO PERF VALUES ('35478', '강주혁', '1983-09-10', 86, 830000, 30);
INSERT INTO PERF VALUES ('78693', '이선우', '1977-07-07', 103, 1789023, 7);
select * from perf;
#1. 고객 구매금액을 기준으로 내림차순으로 정렬해서 이름, 아이디, 생년월일, 총구매금액을 출력하시오
select cust_nm,cust_id,cust_birth,sales_amt from perf order by sales_amt;
#2. 고객 연령과 방문횟수를 비교하시오
#3. 방문횟수가 가장 많은 고객의 이름을 출력하시오
select cust_nm from perf where VISIT_CNT= (select max(visit_cnt) from perf);
#4. 1980년 이전 출생한 고객을 출력하시오.
select * from perf where cust_birth<'1980-01-01';
#5. 평균 방문횟수, 평균구입금액, 평균 구입상품 수를 구하시오
select avg(VISIT_CNT),avg(SALES_AMT),avg(SALES_CNT) from perf;
# 6. 방문 당 구매금액이 가장 큰 고객의 이름을 구하시오
select cust_nm from perf where (SALES_AMT/SALES_CNT) = (select max(sales_amt/SALES_CNT) from perf);
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/sqlDB.sql
SELECT * FROM shopdb.membertbl;
use employees;
show tables;
select * from dept_manager;
use shopdb;
select membername, memberaddress from membertbl;
select * from membertbl where membername='지운이';
show databases;
select * from membertbl;
create table test (id int);
show tables;
create table test1 ( id int, address char);
show tables;
select * from test1;
insert into test values (1);
select * from test;
insert into test (id) values (1);
insert into test1 (id, address) values (3, 's');
select * from test1;
use employees;
select * from shopdb.membertbl;
show tables;
select * from titles;
select first_name, last_name, gender -- 이름과 열을 가지고 옴.
from employees;
/*
select * from titles;
*/
show databases;
use employees;
show tables;
show table status;
describe employees;
select first_name, gender from employees;
select first_name as 이름, gender as 성별 from employees;
drop database if exists sqldb;
create database sqldb;
show databases;
use sqldb;
create table usertbl
( userid char(8) not null primary key,
name varchar(10) not null,
birthyear int not null,
addr char(2) not null,
mobile1 char(3),
mobile2 char(8),
height smallint,
mdate date);
show tables;
create table buytbl (
num int auto_increment not null primary key,
userid char(8) not null,
prodname char(6) not null,
groupname char(4),
price int not null,
amount smallint not null,
foreign key (userid) references usertbl(userid));
show tables;
insert into usertbl values('LSG', '이승기', 1987, '서울', '011', '1111111', 182, '2008-8-8');
insert into usertbl values('KBS', '김범수', 1979, '경남', '011', '2222222', 173, '2012-4-4');
insert into usertbl values('KKH', '김경호', 1971, '전남', '019', '3333333', 177, '2007-7-7');
insert into usertbl values('JYP', '조용필', 1950, '경기', '011', '4444444', 166, '2009-4-4');
insert into usertbl values('SSK', '성시경', 1979, '서울', null, null, 186, '2013-12-12');
insert into usertbl values('LJB', '임재범', 1963, '서울', '016', '6666666', 182, '2009-9-9');
insert into usertbl values('YJS', '윤종신', 1969, '경남', null, null, 170, '2005-5-5');
insert into usertbl values('EJW', '은지원', 1972, '경북', '011', '8888888', 174, '2014-3-3');
insert into usertbl values('JKW', '조관우', 1965, '경기', '018', '9999999', 172, '2010-10-10');
insert into usertbl values('BBK', '바비킴', 1973, '서울', '010', '0000000', 176, '2013-5-5');
insert into buytbl values(null, 'KBS', '운동화', null, 30, 2);
insert into buytbl values(null, 'KBS', '노트북', '전자', 1000, 1);
insert into buytbl values(null, 'JYP', '모니터', '전자', 200, 1);
insert into buytbl values(null, 'BBK', '모니터', '전자', 200, 5);
insert into buytbl values(null, 'KBS', '청바지', '의류', 50, 3);
insert into buytbl values(null, 'BBK', '메모리', '전자', 80, 10);
insert into buytbl values(null, 'SSK', '책', '서적', 15, 5);
insert into buytbl values(null, 'EJW', '책', '서적', 15, 2);
insert into buytbl values(null, 'EJW', '청바지', '의류', 30, 2);
insert into buytbl values(null, 'BBK', '운동화', null, 30, 2);
insert into buytbl values(null, 'EJW', '책', '서적', 15, 1);
insert into buytbl values(null, 'BBK', '운동화', null, 30, 2);
select * from buytbl;
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/perf_test.sql
CREATE TABLE PERF
(
CUST_ID CHAR(5) PRIMARY KEY NOT NULL,
CUST_NM CHAR(10) NOT NULL,
CUST_BIRTH DATE,
VISIT_CNT DECIMAL(15,0),
SALES_AMT DECIMAL(15,0),
SALES_CNT DECIMAL(15,0)
);
INSERT INTO PERF VALUES ('56456', '모형건', '1982-01-24', 123, 3700000, 24);
INSERT INTO PERF VALUES ('65412', '이상훈', '1984-05-10', 23, 467200, 14);
INSERT INTO PERF VALUES ('23472', '이상희', '1978-02-27', 117, 2237065, 23);
INSERT INTO PERF VALUES ('27896', '모영길', '1982-05-11', 37, 123721, 2);
INSERT INTO PERF VALUES ('35478', '강주혁', '1983-09-10', 86, 830000, 30);
INSERT INTO PERF VALUES ('78693', '이선우', '1977-07-07', 103, 1789023, 7);
select * from perf;
#1. 고객 구매금액을 기준으로 내림차순으로 정렬해서 이름, 아이디, 생년월일, 총구매금액을 출력하시오
select cust_id,cust_nm,cust_birth,sales_amt from perf order by sales_amt desc;
2. 고객 연령과 방문횟수를 비교하시오
3. 방문횟수가 가장 많은 고객의 이름을 출력하시오
4. 1980년 이전 출생한 고객을 출력하시오.
5. 평균 방문횟수, 평균구입금액, 평균 구입상품 수를 구하시오
6. 방문 당 구매금액이 가장 큰 고객의 이름을 구하시오<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/4_where_cardtran_purchastran_insoinfo_test.sql
CREATE TABLE CARD_TRAN_201311
(
CMF CHAR(4) PRIMARY KEY NOT NULL,
PARTY_NM CHAR(10) NOT NULL,
SEG CHAR(10) NOT NULL,
PIF_AMT DECIMAL(15,0),
INST_AMT DECIMAL(15,0),
OVRS_AMT DECIMAL(15,0),
CASH_AMT DECIMAL(15,0)
);
INSERT INTO CARD_TRAN_201311 VALUES ('2356', '김아름', 'PB', 1234041, , 1301710, );
INSERT INTO CARD_TRAN_201311 VALUES ('4570', '이선우', 'MASS', , , 524560, );
INSERT INTO CARD_TRAN_201311 VALUES ('4563', '홍지은', 'MASS', 213570, , , 3700000);
INSERT INTO CARD_TRAN_201311 VALUES ('3266', '윤일상', 'MASS', 89641, , , );
INSERT INTO CARD_TRAN_201311 VALUES ('8904', '이동건', 'PB', 1278960, 500000, , );
INSERT INTO CARD_TRAN_201311 VALUES ('4678', '최혜연', 'MASS', 4567780, , , );
INSERT INTO CARD_TRAN_201311 VALUES ('1746', '임하영', 'PB', 7836100, 3213400, , );
INSERT INTO CARD_TRAN_201311 VALUES ('3120', '김지철', 'PB', , , , );
INSERT INTO CARD_TRAN_201311 VALUES ('8974', '강성범', 'MASS', 655456, , , );
INSERT INTO CARD_TRAN_201311 VALUES ('3255', '김지연', 'MASS', 213, , , );
INSERT INTO CARD_TRAN_201311 VALUES ('8977', '김지현', 'PB', 1300, , 54000, 100000);
cmf - 고객번호, party_nm - 이름, seg - 고객등급, pif_amt - 일시불, inst_amt - 할부사용금액,
ovrs_amt - 해외사용금액, cash_amt - 현금서비스
coalesce함수 사용
1. cmd, 이름, 총 사용금액을 총 사용금액 기준 내림차순으로 출력하시오
2. 신규 무이자 할부 카드의 홍보대상 고객을 추출하시오
3. pb고객을 대상으로 일시불사용금액의 1%를 캐시백해주는 캠페인을 진행하면 누가 얼마의 금액을 받을 것인가
4. 고객 등급별 총사용 금액을 추출하고 총사용금액 기준 내림차순 정렬
5. 사용금액이 가장 많은 서비스는
6. 사용횟수가 가장 많은 서비스는
7. pb 고객이 가장 많이 사용한 서비스는
create table purchase_tran (
id int,
purchase_amt int,
purchase_cnt int,
last_amt int,
last_cnt int);
insert into purchase_tran values
(145, 2000000, 12, 1231000, 21),
(455, 1273100, 1, 2237230, 22),
(463, 111463, 3, 214047, 1),
(324, 154769, 3, 7474663, 13),
(568, 25786652, 47, 1000047, 3),
(662, 106868, 1, 277763, 1),
(871, 9694470, 123, 798874, 2),
(460, 65650000, 1200, 6557741, 320),
(277, 5766300, 470, 57663000, 444),
(309, 5579800, 415, 2333000, 135);
1. 올해 구매금액이 1백만원 이상인 고객의 고객번호와 올해 구매금액을 추출하시오.
2. 작년 구매금액이 1백만원 이상 5천만원 이하인 고객의 고객 번호와 작년 구매금액을 출력하시오.
3. 올해 구입건수가 작년 구입건수 보다 많은 고객들의 고객번호, 올해구입건수, 작년구입건수를 출력하고 올래구입건수를 기준으로 오름차순 정렬하시오.
4. 올해 건당 구입금액을 구하고 이름을 평균구매금액으로 출력하시오.
5. 올해와 작년의 구매건수 당 평균 구매금액을 구하시오
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/4_where_test.sql
CREATE TABLE CARD_TRAN_201311
(
CMF CHAR(4) PRIMARY KEY NOT NULL,
PARTY_NM CHAR(10) NOT NULL,
SEG CHAR(10) NOT NULL,
PIF_AMT DECIMAL(15,0),
INST_AMT DECIMAL(15,0),
OVRS_AMT DECIMAL(15,0),
CASH_AMT DECIMAL(15,0)
);
select coalesce(OVRS_AMT,0) from card_tran_201311 where party_nm='임하영';
INSERT INTO CARD_TRAN_201311 VALUES ('2356', '김아름', 'PB', 1234041,null , 1301710, null);
INSERT INTO CARD_TRAN_201311 VALUES ('4570', '이선우', 'MASS', null,null , 524560, null);
INSERT INTO CARD_TRAN_201311 VALUES ('4563', '홍지은', 'MASS', 213570, null,null , 3700000);
INSERT INTO CARD_TRAN_201311 VALUES ('3266', '윤일상', 'MASS', 89641, null,null ,null );
INSERT INTO CARD_TRAN_201311 VALUES ('8904', '이동건', 'PB', 1278960, 500000, null,null );
INSERT INTO CARD_TRAN_201311 VALUES ('4678', '최혜연', 'MASS', 4567780, null,null ,null );
INSERT INTO CARD_TRAN_201311 VALUES ('1746', '임하영', 'PB', 7836100, 3213400, null,null );
INSERT INTO CARD_TRAN_201311 VALUES ('3120', '김지철', 'PB', null,null ,null ,null );
INSERT INTO CARD_TRAN_201311 VALUES ('8974', '강성범', 'MASS', 655456, null,null ,null );
INSERT INTO CARD_TRAN_201311 VALUES ('3255', '김지연', 'MASS', 213, null,null ,null );
INSERT INTO CARD_TRAN_201311 VALUES ('8977', '김지현', 'PB', 1300,null , 54000, 100000);
select * from card_tran_201311;
#cmf - 고객번호, party_nm - 이름, seg - 고객등급, pif_amt - 일시불, inst_amt - 할부사용금액,
#ovrs_amt - 해외사용금액, cash_amt - 현금서비스
#coalesce함수 사용
#1. cmd, 이름, 총 사용금액을 총 사용금액 기준 내림차순으로 출력하시오
select cmf,party_nm,(coalesce(PIF_AMT,0)+coalesce(ovrs_amt,0)+coalesce(PIF_AMT,0))as 총사용금액 from card_tran_201311 order by 총사용금액 desc;
#2. 신규 무이자 할부 카드의 홍보대상 고객을 추출하시오
select party_nm from card_tran_201311 where INST_AMT is not null;
#3. pb고객을 대상으로 일시불사용금액의 1%를 캐시백해주는 캠페인을 진행하면 누가 얼마의 금액을 받을 것인가
select Party_nm, pif_amt*0.01 as 일시불사용금액 from card_tran_201311 where SEG='PB';
#4. 고객 등급별 총사용 금액을 추출하고 총사용금액 기준 내림차순 정렬
select SEG,sum(coalesce(PIF_AMT,0)+coalesce(ovrs_amt,0)+coalesce(PIF_AMT,0))as 총사용금액 from card_tran_201311 group by SEG;
#5. 사용금액이 가장 많은 서비스는
select sum(PIF_AMT),sum(INST_AMT),sum(OVRS_AMT),sum(CASH_AMT) from card_tran_201311;
#6. 사용횟수가 가장 많은 서비스는
select count(PIF_AMT),count(INST_AMT),count(OVRS_AMT),count(CASH_AMT) from card_tran_201311;
#7. pb 고객이 가장 많이 사용한 서비스는
select count(PIF_AMT),count(INST_AMT),count(OVRS_AMT),count(CASH_AMT) from card_tran_201311 where SEG='PB';
create table purchase_tran (
id int,
purchase_amt int,
purchase_cnt int,
last_amt int,
last_cnt int);
insert into purchase_tran values
(145, 2000000, 12, 1231000, 21),
(455, 1273100, 1, 2237230, 22),
(463, 111463, 3, 214047, 1),
(324, 154769, 3, 7474663, 13),
(568, 25786652, 47, 1000047, 3),
(662, 106868, 1, 277763, 1),
(871, 9694470, 123, 798874, 2),
(460, 65650000, 1200, 6557741, 320),
(277, 5766300, 470, 57663000, 444),
(309, 5579800, 415, 2333000, 135);
select * from purchase_tran;
#1. 올해 구매금액이 1백만원 이상인 고객의 고객번호와 올해 구매금액을 추출하시오.
select id,purchase_amt from purchase_tran where purchase_amt>1000000;
#2. 작년 구매금액이 1백만원 이상 5천만원 이하인 고객의 고객 번호와 작년 구매금액을 출력하시오.
select id,last_amt from purchase_tran where last_amt>1000000 and last_amt<50000000;
#3. 올해 구입건수가 작년 구입건수 보다 많은 고객들의 고객번호, 올해구입건수, 작년구입건수를 출력하고 올래구입건수를 기준으로 오름차순 정렬하시오.
select id, purchase_cnt,last_cnt from purchase_tran where purchase_cnt>last_cnt order by purchase_cnt;
#4. 올해 건당 구입금액을 구하고 이름을 평균구매금액으로 출력하시오.
select id, (purchase_amt/purchase_cnt) as 평균구매금액 from purchase_tran;
#5. 올해와 작년의 구매건수 당 평균 구매금액을 구하시오
select id, (purchase_amt/purchase_cnt) as 평균구매금액, (last_amt/last_cnt) as 작년구매금액평균 from purchase_tran;
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/9_ppc_mast_test.sql
CREATE TABLE PPC_MAST_201312
(
SSN CHAR(13) NOT NULL,
ACCT_NO CHAR(10) NOT NULL,
ACCT_CD DECIMAL(10) NOT NULL,
PRFT DECIMAL(15,0),
BALANCE_AMT DECIMAL(15,0)
) ;
drop table PPC_MAST_201312;
INSERT INTO PPC_MAST_201312 VALUES ('7802221111111', '22033', 130, 504, 56746);
INSERT INTO PPC_MAST_201312 VALUES ('8307153333444', '54412', 110, 585, 23540);
INSERT INTO PPC_MAST_201312 VALUES ('5605099999222', '65433', 340, 213, 987800);
INSERT INTO PPC_MAST_201312 VALUES ('8012301111333', '58721', 320, 780, 310000);
INSERT INTO PPC_MAST_201312 VALUES ('6711032222111', '23422', 120, 5679, 3);
INSERT INTO PPC_MAST_201312 VALUES ('8910103333222', '89811', 310, 240, 40011);
INSERT INTO PPC_MAST_201312 VALUES ('7802221111111', '78022', 100, 899, 4565000);
INSERT INTO PPC_MAST_201312 VALUES ('6711032222111', '35714', 300, 3780, 2545640);
INSERT INTO PPC_MAST_201312 VALUES ('8910103333222', '68740', 310, 233, 522312);
INSERT INTO PPC_MAST_201312 VALUES ('5605099999222', '96870', 330, 7000, 2158);
INSERT INTO PPC_MAST_201312 VALUES ('7802221111111', '89770', 140, 1000, 566600);
INSERT INTO PPC_MAST_201312 VALUES ('6711032222111', '33270', 130, 5600, 68770);
INSERT INTO PPC_MAST_201312 VALUES ('7802221111111', '87890', 340, 1270, 5500000);
select * from ppc_mast_201312;
/*
고객계좌별 수익
SSN CHAR(13) - 주민번호
ACCT_NO - 계좌번호
ACCT_CD - 종별 코드 (수신 : 100, 110, 120, 130, 140/ 여신 - 300, 310, 320, 330, 340 )
PRFT - 수익
BALANCE_AMT - 잔액
*/
#1. 수신액은 1, 여신은 0으로 구분하고 각각 총액을 구하시오
alter table ppc_mast_201312 add ACCT int not null;
update ppc_mast_201312 set ACCT=1 where ACCT_CD=100 or ACCT_CD=110 or ACCT_CD=120 or ACCT_CD=130 or ACCT_CD=140;
update ppc_mast_201312 set ACCT=0 where ACCT_CD=300 or ACCT_CD=310 or ACCT_CD=320 or ACCT_CD=330 or ACCT_CD=340;
select sum(Balance_AMT),ACCT from PPC_MAST_201312 group by ACCT;
select sum(BALANCE_AMT),case when ACCT_CD in (100,110,120,130,140) then '1' when ACCT_CD in (300,310,320,330,340) then '0' end as pop
from ppc_mast_201312 group by pop;
#2. 고객 당 금융상품 가입수를 구하시오
select SSN,count(acct_cd) from PPC_MAST_201312 group by SSN;
#3. 고객당 잔액 합계가 200만원 이상인 고객을 구하시오
select SSN from PPC_MAST_201312 group by SSN having sum(BALANCE_AMT)>2000000;
#4. 고객당 금융상품 가입자수가 3개 이상인 고객을 구하시오
select SSN from PPC_MAST_201312 group by SsN having count(*)>3;<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/0_sql_test_BI.sql
sales database 생성
sales database 선택
test table 생성
test column 생성 - datatype - DECIMAL(5,3)
값 10.5 입력
test테이블 출력
값 입력 - 12.55555
칼럼 추가 `test_fl` - FLOAT(5,3) NULL after test
값 입력 - test_fl : 14.55555 / test : 16.55555
test table 삭제
###########
-- LECTURE: Creating a Table
sales 테이블 생성
purchase_number - INT ,
date_of_purchase - DATE NOT NULL,
customer_id - INT,
item_code - VARCHAR(10) NOT NULL
-- EXERCISE 1: Creating a Table
customers 테이블 생성
customer_id - INT,
first_name - varchar(255),
last_name - varchar(255),
email_address - varchar(255),
number_of_complaints - int
sales 테이블의 purchase_number를 primary key로 지정 - 2가지 방범/ not null로 지정/ auto_increment로 지정
customers 테이블의 customer_id를 primary key로 지정
-- EXERCISE 1: PRIMARY KEY Constraint
items 테이블 생성, primary key - item_id
item_id - VARCHAR(255),
item - VARCHAR(255),
unit_price - NUMERIC(10 , 2 ),
company_id - VARCHAR(255),
companies 테이블 생성, primary key - company_id
company_id - VARCHAR(255),
company_name - VARCHAR(255),
headquarters_phone_number - INT(12),
customers 테이블 값 추가 - 'John', 'Mackinley', 'M', '<EMAIL>', 0
customers 테이블 값 추가 - first_name, last_name, gender -> 'Peter', 'Figaro', 'M'
###########
-- LECTURE: SELECT - FROM
employees database 선택
first_name, last_name 출력
###########
-- LECTURE: WHERE
이름이 'Denis'인 데이터 출력
###########
-- LECTURE: AND
이름이 'Denis' 이고 남성인 데이터 출력
###########
-- LECTURE: OR
이름이 'Denis' 또는 'Elvis'인 데이터 출력
###########
-- LECTURE: IN / NOT IN
이름이 'Cathie' , 'Mark', 'Nathan'에 해당하는 row출력
이름이 'Cathie' , 'Mark', 'Nathan'에 해당하지 않는 row출력
###########
-- LECTURE: LIKE / NOT LIKE
이름이 Mar로 시작하는 row출력
이름이 ar로 끝나는 row출력
이름이 Mar로 시작하고 4글자인 row출력
이름에 jack을 포한하는 row를 출력
fire_date이 '1990-01-01' 과 '2000-01-01' 사이인 row출력
salary가 66000과 70000 사이인 row출력
이름이 null인 row출력
이름이 null이 아닌 row출력
이름이 'Mark'가 아닌 row를 출력
hire_date이 '2000-01-01' 이후인 데이터 출력
hire_date이 '1985-02-01'이전인 데이터 출력
hire_date이 '1985-02-01'이전이고 남성인인 데이터 출력
salary가 150000 이상인 데이터 출력
중복없는 입사일자 데이터 출력
중복없는 이름 출력
###########
-- LECTURE: Introduction to Aggregate Functions
사원번호 갯수를 출력
이름 칼럼 값의 총 합 출력
중복없는 이름의 갯수 출력
-- EXERCISE 1: Introduction to Aggregate Functions
연봉 100000이상인 사람의 총 수
메니저인 사람의 총 수 출력
이름으로 오름차순 정렬 후 하위 10개 이름 출력
이름으로 내림차순 정렬 후 하위 10개 이름 출력
성울 선순위, 이름을 차순위로 내림차순 정렬
연봉 상위 100명 이름 출력
중복 이름이 100 이상인 이름 목록 출력
평균 연봉이 120000 이상인 직원 번호와 평균 임금 출력
###########
-- LECTURE: WHERE vs HAVING - Part I
중복 이름이 200번 이상이면서 1999-01-01 이후에 입사한 사람의 이름과 중복된 이름의 갯수 출력
use employees;
employees에 데이터 삽입
emp_no,
birth_date,
first_name,
last_name,
gender,
hire_date
999901,
'1986-04-21',
'John',
'Smith',
'M',
'2011-01-01'
'1973-3-26',
999902,
'Patricia',
'Lawrence',
'F',
'2005-01-01'
999903,
'1977-09-14',
'Johnathan',
'Creek',
'M',
'1999-01-01'
employees 내림차순 상위 10개 출력
titles에 데이터 입력
emp_no,
title,
from_date
999903,
'Senior Engineer',
'1997-10-01'
employees 내림차순 상위 10개 출력
dept_emp에 데이터 입력
emp_no,
dept_no,
from_date,
to_date
999903,
'd005',
'1997-10-01',
'9999-01-01'
###########
-- LECTURE: Inserting Data INTO a New Table
use employees;
CREATE TABLE departments_dup
(
dept_no CHAR(4) NOT NULL,
dept_name VARCHAR(40) NOT NULL
);
departments의 데이터를 departments-dup에 삽입하시오
-- LECTURE: The UPDATE Statement - Part I
USE employees;
emp_no = 999901e데이터를 수정하시오
update employees set (
first_name = 'Stella',
last_name = 'Parkinson',
birth_date = '1990-12-31',
gender = 'F') where emp_no = 999901;
emp_no 기준 내림차순으로 상위 10개를 출력하시오
###########
-- EXERCISE 1: The UPDATE Statement - Part II
departments에서 dept_no가 'd010'인 데이터의 dept_name을 'data analysis'로 수정하시오
-- LECTURE: The DELETE Statement - Part I
USE employees;
SELECT
*
FROM
titles
WHERE
emp_no = 999903;
employees 테이블에서 emp_no가 999903인 데이터를 삭제하시오
SELECT
*
FROM
employees
WHERE
emp_no = 999903;
###########
-- LECTURE: The DELETE Statement - Part II
SELECT
*
FROM
departments_dup
ORDER BY dept_no;
departments_dup의 모든 데이터를 삭제하시오
departments에서 dept_no가 'd010'인 데이터를 삭제하시오
###########
-- LECTURE: COUNT()
SELECT
*
FROM
salaries
ORDER BY salary DESC
LIMIT 10;
SELECT
COUNT(salary)
FROM
salaries;
salaries테이블에서 입사일자 총 갯수합합을 산출하시오
salaries테이블에서 중복없는 입사일자 총 합을 산출하시오
salaries 테이블의 총데이터 갯수를 구하시오
dept_emp에서 중복없는 dept_no의 갯수를 구하시오
salaries에서 salary의 총 합을 구하시오.
'1997-01-01'일 이후의 salary의 총합을 구하시오.
###########
-- LECTURE: MIN() and MAX()
salaries에서 salary최대값을 구하시오.
salaries에서 salary최소값을 구하시오
salaries에서 salary 평균값을 구하시오
salaries에서 salary 반올림한 평균값을 구하시오.
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/3_emp_insa_test.sql
CREATE TABLE EMP
(
ID CHAR(3) PRIMARY KEY NOT NULL,
“POSITION” CHAR(10) NOT NULL,
PARTY_NM CHAR(10) NOT NULL,
MANAGER_ID CHAR(10) NOT NULL,
TEAM_NM CHAR(10) NOT NULL,
GRADE CHAR(10) NOT NULL
);
INSERT INTO EMP VALUES ('650', '대리', '이재훈', '1270', '마케팅부', '1');
INSERT INTO EMP VALUES ('540', '과장', '장성수', '3221', '리스크부', '2');
INSERT INTO EMP VALUES ('210', '차장', '문보미', '3914', '인사팀', '3');
INSERT INTO EMP VALUES ('347', '차장', '정호천', '3942', '기획팀', '3');
INSERT INTO EMP VALUES ('970', '부장', '김영성', '3221', '리스크부', '2');
INSERT INTO EMP VALUES ('345', '대리', '오윤경', '1270', '마케팅부', '2');
INSERT INTO EMP VALUES ('711', '과장', '이재중', '3914', '인사팀', '2');
select * from emp;
#1. 어떤 직급이 있는지?
select distinct “POSITION” from emp;
#2. 직급에 따라 어떤 고과를 받았는가
select distinct(“POSITION”),GRADE from emp;
#3. 인사고과 주는 사람 구하기
select distinct manager_id from emp;
#4. 인사고과를 몇명이 주고 있는가
select count(distinct(MANAGER_ID)) from emp;
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/SQL 쿼리 선재.sql
SELECT * FROM shopdb.membertbl;
-- shopdb를 불러오기
use employees;
-- employees DB 활성화
show tables;
-- 큰 범위의 data 종류를 보여주는 명령어(show)
select * from dept_manager;
-- dept_manager 불러오기
use shopdb;
-- shopdb 활성화(작업중인 DB를 이동시 입력)
select membername, memberaddress from membertbl;
-- membertbl의 membername, memberaddress column을 가져오기
select * from membertbl where membername = '지운이';
-- membertbl 에서 membername = '지운이' 인 raw 출력
show databases;
-- database 종류 출력
select * from membertbl;
-- membertbl 출력
create table test(id int);
-- 이름이 test이고 column이 int인 table을 만들기
show tables;
-- test table 확인
create table test1 (id int, address char);
show tables;
select * from test1;
show test1;
-- show는 특정 table 출력 불가능
insert into test values(1);
insert into test (id) values(2);
insert into test1 (id, address) values (3, 's');
-- test table에 values 값 추가(default = values 값 안의 순차대로 입력)
select * from test;
select * from test1;
use employees;
select * from shopdb.membertbl;
-- employees를 사용하고 있지만 다른 DB의 정보에 접근하기
show tables;
select * from titles;
select first_name, last_name, gender from employees;
/*
select * from titles;
블록 주석 만들기
*/
show databases;
use employees;
show tables;
show table status;
-- table data 확인 like info()
describe employees;
-- 특정 table 에 대한 구조 확인
select first_name, gender from employees;
select first_name 이름, gender 성별 from employees;
-- employees table의 first_name과 gender column의 이름을 변경
select * from employees.employees;
drop database if exists sqldb;
create database sqldb;
show databases;
-- 새로운 DB 만들기
use sqldb;
create table usertbl
( userid char(8) not null primary key,
usename varchar(10) not null,
birthyear int not null,
addr char(2) not null,
mobile1 char(3),
mobile2 char(8),
height smallint,
mdate date);
show tables;
select * from usertbl;
create table buytbl
( num int auto_increment not null primary key,
userid char(8) not null,
prodname char(6) not null,
groupname char(4),
price int not null,
amount smallint not null,
foreign key (userid) refErences usertbl(userid));
-- DB안에 usertbl 이라는 table을 만들고 column들의 성질을 결정
-- foreign key 다른 table의 column을 가져와서 auto_increment 에 대입
-- refErences = foreign key를 가져올 table 경로를 지정
insert into usertbl values('LSG', '이승기', 1987, '서울', '011', '1111111', 182, '2008-8-8');
insert into usertbl values('KBS', '김범수', 1979, '경남', '011', '2222222', 173, '2012-4-4');
insert into usertbl values('KKH', '김경호', 1971, '전남', '019', '3333333', 177, '2007-7-7');
insert into usertbl values('JYP', '조용필', 1950, '경기', '011', '4444444', 166, '2009-4-4');
insert into usertbl values('SSK', '성시경', 1979, '서울', NULL, NULL, 186, '2013-12-12');
insert into usertbl values('LJB', '임재범', 1963, '서울', '016', '6666666', 182, '2009-9-9');
insert into usertbl values('YJS', '윤종신', 1969, '경남', NULL, NULL, 170, '2005-5-5');
insert into usertbl values('EJW', '은지원', 1972, '경북', '011', '8888888', 174, '2014-3-3');
insert into usertbl values('JKW', '조관우', 1965, '경기', '018', '9999999', 172, '2010-10-10');
insert into usertbl values('BBK', '바비킴', 1973, '서울', '010', '0000000', 176, '2013-5-5');
select * from usertbl;
-- DELETE FROM `sqldb`.`usertbl` WHERE (`userid` = 'EJW');
insert into buytbl values(null, 'KBS', '운동화', null, 30, 2);
insert into buytbl values(null, 'KBS', '노트북', '전자', 1000, 1);
insert into buytbl values(null, 'JYP', '모니터', '전자', 200, 1);
insert into buytbl values(null, 'BBK', '모니터', '전자', 200, 5);
insert into buytbl values(null, 'KBS', '청바지', '의류', 50, 3);
insert into buytbl values(null, 'BBK', '메모리', '전자', 80, 10);
insert into buytbl values(null, 'SSK', '책', '서적', 15, 5);
insert into buytbl values(null, 'EJW', '책', '서적', 15, 2);
insert into buytbl values(null, 'EJW', '청바지', '의류', 30, 2);
insert into buytbl values(null, 'BBK', '운동화', null, 30, 2);
insert into buytbl values(null, 'EJW', '책', '서적', 15, 1);
insert into buytbl values(null, 'BBK', '운동화', null, 30, 2);
select * from buytbl;<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_test/6_case_when_query_test.sql
CREATE TABLE CASA_201312
(
CUST_ID CHAR(13) PRIMARY KEY NOT NULL,
CUST_SEG CHAR(10) NOT NULL,
BALANCE_201311 DECIMAL(15,0),
BALANCE_201312 DECIMAL(15,0)
);
INSERT INTO CASA_201312 VALUES ('54560', 'SILVER', 1000000, 2000000);
INSERT INTO CASA_201312 VALUES ('68477', 'GOLD', 112000, 3500);
INSERT INTO CASA_201312 VALUES ('96147', 'SILVER', 300000, 1000010);
INSERT INTO CASA_201312 VALUES ('32134', 'GOLD', 2354000, 3200000);
INSERT INTO CASA_201312 VALUES ('12478', 'DIAMOND', 6015000, 5800000);
INSERT INTO CASA_201312 VALUES ('54789', 'SILVER', 200000, 300000);
INSERT INTO CASA_201312 VALUES ('34181', 'GOLD', 4200000, 4100000);
INSERT INTO CASA_201312 VALUES ('23458', 'DIAMOND', 5000000, 6200000);
INSERT INTO CASA_201312 VALUES ('12344', 'SILVER', 210000, 200000);
select * from casa_201312;
#11월과 12월의 고객별 수신잔고 평균
select cust_id ,BALANCE_201311+BALANCE_201312/2 from casa_201312;
#1. 11월 캠페인결과 잔고증가율이 10%이상인 고객은 1, 아니면 0으로
#캠페인 성공 여부를 새로운 칼럼으로 표시하시오
select (case when((balance_201312-balance_201311)/balance_201311 > 0.1) then 1 else 0 end) from casa_201312 ;
#2. 캠페인 성공률을 계산하시오
select avg(case when((balance_201312-balance_201311)/balance_201311 > 0.1) then 1 else 0 end) from casa_201312 ;
#3. 캠페인의 결과로 증가된 수신고 순 증가분을 구하시오
select sum(balance_201312) - sum(balance_201311) as 증가분 from casa_201312;
#4. 캠페인 결과 수신고 증가율을 구하시오
select ( sum(balance_201312) - sum(balance_201311) )/(sum(balance_201311)) as 증가율 from casa_201312;
create table stud_score (
student_id int,
math_score int,
eng_score int,
phil_score int,
music_score int);
insert into stud_score values
(123511,89,78,45,90),
(255475,88,90,null,87),
(9921100,87,null, null, 98),
(9732453,69,98,78,78),
(578981,59,90,89,null),
(768789,94,80,87,99),
(565789,58,64,72,null);
select * from stud_score;
#1. null값을 포함해서 행의 개수를 구하시오
select count(*) from stud_score;
#1-1. null값을 포함한 행들만의 갯수..
select count(*) from stud_score where math_score is null or eng_score is null or phil_score is null or music_score is null;
#2. null값을 제외한 음악점수 보유자의 숫자를 구하시오
select count(music_score) from stud_score;
#3. null값 및 중복값을 제외한 영어점수 보유자의 수자를 구하시오
select count(distinct(math_score)) from stud_score where eng_score is not null;
#4. 수학점수의 총합을 구하시오
select sum(math_score) from stud_score;
#5. 음악 점수의 평균을 구하시오
select avg(music_score) from stud_score;
#6. 전과목 최고득점자의 학번을 구하시오
select student_id,coalesce(math_Score,0)+coalesce(eng_score,0)+coalesce(phil_score,0)+coalesce(music_score,0) as 총점수 from stud_Score order by 총점수 desc limit 1;
#7. 수학점수의 최고점수와 최저점수를 구하시오
select max(math_score),min(math_score) from stud_score;
#8. 평균점수가 가장 높은 과목은 무엇인가
select avg(math_score),avg(eng_score),avg(phil_score),avg(music_score) from stud_Score;
#9. 과목 당 표준편차가 가장 작은 학생의 학번을 구하시오
select stddev(math_score),stddev(music_score),stddev(phil_Score),stddev(eng_score) from stud_score;
#10. 분산이 가장 작은 과목은 무엇인가
create table staff_sal (
id int,
job char(10),
current_sal int,
eng_score int);
insert into staff_sal value
(2148,'officer',40000,90),
(5780,'clerk',32000,98),
(6870, 'manager', 100000,80),
(4565, 'clerk', 30000,79),
(9687,'clerk', 33000,66),
(7337, 'manager', 100000,95),
(1321,'officer', 43000,80),
(9595, 'clerk', 30000, 50);
select * from staff_sal;
#1. 직위 별 연봉 평균을 구하시오
select job,avg(current_sal) from staff_Sal group by job;
#2. clerk은 7%, officer는 5%, manager는 3% 연봉을 인상하기로 하였다. 직원별 인상된 연봉을 현재연봉과 함께 계산하시오
select current_sal, (case when job='clerk' then current_sal*1.07 when job='officer' then current_sal*1.05 else current_sal*1.03 end) from staff_sal;
/*3. 연봉인상 기준이 직급과 영어점수에 따라 다음과 같다면 사원별 인상되는 연봉금액을 계산하시오.
90점 이상 -> 5%
90점 미만 -> 0%
clerk
officer
manager
*/
select current_sal,(case when job='clerk' and eng_score>=90 then 1.12*current_sal
when job='clerk' and eng_score<90 then 1.07*current_sal
when job='officer' and eng_score>=90 then 1.1*current_sal
when job='officer' and eng_score<90 then 1.05*current_sal
when job='manager' and eng_score>=90 then 1.08*current_sal
when job='manager' and eng_score<90 then 1.03*current_sal end
) from staff_sal;
#4. 위와 같이 연봉이 인상된다면 추가되는 임금비용은 얼마인가?
select sum(case when job='clerk' and eng_score>=90 then 1.12*current_sal
when job='clerk' and eng_score<90 then 1.07*current_sal
when job='officer' and eng_score>=90 then 1.1*current_sal
when job='officer' and eng_score<90 then 1.05*current_sal
when job='manager' and eng_score>=90 then 1.08*current_sal
when job='manager' and eng_score<90 then 1.03*current_sal end
)-sum(current_sal) as 총추가임금 from staff_sal;
<file_sep>/4th_revolution-master/4th_revolution-master/bigdata/bigdata/home.selection/bigdata/sql/sql_code/ch7.sql
/* 07장 */
SELECT CAST('2020-10-19 12:35:29.123' AS DATE) AS 'DATE' ;
SELECT CAST('2020-10-19 12:35:29.123' AS TIME) AS 'TIME' ;
SELECT CAST('2020-10-19 12:35:29.123' AS DATETIME) AS 'DATETIME' ;
-- <실습 1> --
USE sqlDB;
SET @myVar1 = 5 ;
SET @myVar2 = 3 ;
SET @myVar3 = 4.25 ;
SET @myVar4 = '가수 이름==> ' ;
SELECT @myVar1 ;
SELECT @myVar2 + @myVar3 ;
SELECT @myVar4 , Name FROM userTbl WHERE height > 180 ;
SET @myVar1 = 3 ;
PREPARE myQuery
FROM 'SELECT Name, height FROM userTbl ORDER BY height LIMIT ?';
EXECUTE myQuery USING @myVar1 ;
-- </실습 1> --
USE sqlDB ;
SELECT AVG(amount) AS '평균 구매 개수' FROM buyTbl ;
SELECT CAST(AVG(amount) AS SIGNED INTEGER) AS '평균 구매 개수' FROM buyTbl ;
-- 또는
SELECT CONVERT(AVG(amount) , SIGNED INTEGER) AS '평균 구매 개수' FROM buyTbl ;
SELECT CAST('2020$12$12' AS DATE);
SELECT CAST('2020/12/12' AS DATE);
SELECT CAST('2020%12%12' AS DATE);
SELECT CAST('2020@12@12' AS DATE);
SELECT num, CONCAT(CAST(price AS CHAR(10)), 'X', CAST(amount AS CHAR(4)) ,'=' ) AS '단가X수
량',
price*amount AS '구매액'
FROM buyTbl ;
SELECT '100' + '200' ; -- 문자와 문자를 더함 (정수로 변환되서 연산됨)
SELECT CONCAT('100', '200'); -- 문자와 문자를 연결 (문자로 처리)
SELECT CONCAT(100, '200'); -- 정수와 문자를 연결 (정수가 문자로 변환되서 처리)
SELECT IF (100>200, '참이다', '거짓이다');
SELECT IFNULL(NULL, '널이군요'), IFNULL(100, '널이군요');
SELECT NULLIF(100,100), IFNULL(200,100);
SELECT CASE 10
WHEN 1 THEN '일'
WHEN 5 THEN '오'
WHEN 10 THEN '십'
ELSE '모름'
END;
SELECT BIT_LENGTH('abc'), CHAR_LENGTH('abc'), LENGTH('abc'); -- length : byte 길이
SELECT BIT_LENGTH('가나다'), CHAR_LENGTH('가나다'), LENGTH('가나다');
SELECT CONCAT_WS('/', '2020', '01', '01'); -- 구분자로 문자열을 이어준다.
SELECT ELT(2, '하나', '둘', '셋'), FIELD('둘', '하나', '둘', '셋'), FIND_IN_SET('둘', '하나,둘,셋'), INSTR('하나
둘셋', '둘'), LOCATE('둘', '하나둘셋');
SELECT FORMAT(123456.123456, 4);
SELECT INSERT('abcdefghi', 3, 4, '@@@@'), INSERT('abcdefghi', 3, 2, '@@@@');
SELECT LEFT('abcdefghi', 3), RIGHT('abcdefghi', 3);
SELECT LOWER('abcdEFGH'), UPPER('abcdEFGH');
SELECT LPAD('이것이', 5, '##'), RPAD('이것이', 5, '##');
SELECT LTRIM(' 이것이'), RTRIM('이것이 ');
SELECT REPEAT('이것이', 3);
SELECT REPLACE ('이것이 MySQL이다', '이것이' , 'This is');
SELECT REVERSE ('MySQL');
SELECT CONCAT('이것이', SPACE(10), 'MySQL이다');
SELECT SUBSTRING('대한민국만세', 3, 2);
SELECT SUBSTRING_INDEX('cafe.naver.com', '.', 2), SUBSTRING_INDEX('cafe.naver.com', '.', -2);
SELECT ABS(-100);
SELECT CEILING(4.7), FLOOR(4.7), ROUND(4.7);
SELECT CONV('AA', 16, 2), CONV(100, 10, 8);
SELECT MOD(157, 10), 157 % 10, 157 MOD 10;
SELECT POW(2,3), SQRT(9);
SELECT SIGN(100), SIGN(0), SIGN(-100.123);
SELECT TRUNCATE(12345.12345, 2), TRUNCATE(12345.12345, -2);
-- <실습 2> --
USE sqlDB;
CREATE TABLE maxTbl ( col1 LONGTEXT, col2 LONGTEXT);
INSERT INTO maxTbl VALUES (REPEAT('A', 1000000), REPEAT('가',1000000));
SELECT LENGTH(col1), LENGTH(col2) FROM maxTBL;
INSERT INTO maxTbl VALUES (REPEAT('A', 10000000), REPEAT('가',10000000));
/*
CD %PROGRAMDATA%
CD MySQL
CD "MySQL Server 5.7"
DIR
NOTEPAD my.ini
max_allowed_packet=4M --> 1000M
NET STOP MySQL
NET START MySQL
*/
use sqldb;
INSERT INTO maxTbl VALUES (REPEAT('A', 10000000), REPEAT('가',10000000));
SELECT LENGTH(col1), LENGTH(col2) FROM maxTBL;
SHOW variables LIKE 'max%';
/*
secure-file-priv=C:/TEMP
*/
USE sqlDB;
SELECT * INTO OUTFILE 'C:/TEMP/userTBL.txt' FROM userTBL;
CREATE TABLE memberTBL LIKE userTBL; -- 테이블 구조만 복사
LOAD DATA LOCAL INFILE 'C:/TEMP/userTBL.txt' INTO TABLE memberTBL;
select * from membertbl;
-- </실습 2> --
select * from buytbl;
select * from usertbl;
USE sqlDB; -- 구매자 주소 확인
SELECT *
FROM buyTbl
INNER JOIN userTbl
ON buyTbl.userID = userTbl.userID
WHERE buyTbl.userID = 'JYP';
SELECT userID, name, prodName, addr, mobile1 + mobile2 AS '연락처' -- 필요한 열만 추출 - error
FROM buyTbl
INNER JOIN userTbl
ON buyTbl.userID = userTbl.userID ;
SELECT buyTbl.userID, name, prodName, addr, mobile1 + mobile2 AS '연락처' -- buytbl 기준
FROM buyTbl
INNER JOIN userTbl
ON buyTbl.userID = userTbl.userID;
SELECT buyTbl.userID, name, prodName, addr, mobile1 + mobile2 -- where문 활용
FROM buyTbl, userTbl
WHERE buyTbl.userID = userTbl.userID ;
SELECT buyTbl.userID, userTbl.name, buyTbl.prodName, userTbl.addr, -- 모두 테이블명
userTbl.mobile1 + userTbl.mobile2 AS '연락처'
FROM buyTbl
INNER JOIN userTbl
ON buyTbl.userID = userTbl.userID;
SELECT B.userID, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처' -- 별칭
FROM buyTbl B
INNER JOIN userTbl U
ON B.userID = U.userID;
SELECT B.userID, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처'
FROM buyTbl B
INNER JOIN userTbl U
ON B.userID = U.userID
WHERE B.userID = 'JYP';
SELECT U.userID, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처' -- 회원테이블 기준
FROM userTbl U
INNER JOIN buyTbl B
ON U.userID = B.userID
WHERE B.userID = 'JYP';
SELECT U.userID, U.name, B.prodName, U.addr, U.mobile1 + U.mobile2 AS '연락처'
FROM userTbl U
INNER JOIN buyTbl B
ON U.userID = B.userID
ORDER BY U.userID;
SELECT DISTINCT U.userID, U.name, U.addr
FROM userTbl U
INNER JOIN buyTbl B
ON U.userID = B.userID
ORDER BY U.userID ;
-- <실습 4> --
USE sqlDB;
CREATE TABLE stdTbl
( stdName VARCHAR(10) NOT NULL PRIMARY KEY,
addr CHAR(4) NOT NULL
);
CREATE TABLE clubTbl
( clubName VARCHAR(10) NOT NULL PRIMARY KEY,
roomNo CHAR(4) NOT NULL
);
CREATE TABLE stdclubTbl
( num int AUTO_INCREMENT NOT NULL PRIMARY KEY,
stdName VARCHAR(10) NOT NULL,
clubName VARCHAR(10) NOT NULL,
FOREIGN KEY(stdName) REFERENCES stdTbl(stdName),
FOREIGN KEY(clubName) REFERENCES clubTbl(clubName)
);
INSERT INTO stdTbl VALUES ('김범수','경남'), ('성시경','서울'), ('조용필','경기'), ('은지원','경북'),('바비
킴','서울');
INSERT INTO clubTbl VALUES ('수영','101호'), ('바둑','102호'), ('축구','103호'), ('봉사','104호');
INSERT INTO stdclubTbl VALUES (NULL, '김범수','바둑'), (NULL,'김범수','축구'), (NULL,'조용필','축구'),
(NULL,'은지원','축구'), (NULL,'은지원','봉사'), (NULL,'바비킴','봉사');
select * from stdtbl;
select * from clubtbl;
select * from stdclubtbl;
SELECT S.stdName, S.addr, C.clubName, C.roomNo
FROM stdTbl S
INNER JOIN stdclubTbl SC
ON S.stdName = SC.stdName
INNER JOIN clubTbl C
ON SC.clubName = C.clubName
ORDER BY S.stdName;
SELECT C.clubName, C.roomNo, S.stdName, S.addr
FROM stdTbl S
INNER JOIN stdclubTbl SC
ON SC.stdName = S.stdName
INNER JOIN clubTbl C
ON SC.clubName = C.clubName
ORDER BY C.clubName;
-- </실습 4> --
USE sqlDB;
SELECT U.userID, U.name, B.prodName, U.addr, CONCAT(U.mobile1, U.mobile2) AS '연락처'
FROM userTbl U
LEFT OUTER JOIN buyTbl B
ON U.userID = B.userID
ORDER BY U.userID;
SELECT U.userID, U.name, B.prodName, U.addr, CONCAT(U.mobile1, U.mobile2) AS '연락처'
FROM buyTbl B
RIGHT OUTER JOIN userTbl U
ON U.userID = B.userID
ORDER BY U.userID;
SELECT U.userID, U.name, B.prodName, U.addr, CONCAT(U.mobile1, U.mobile2) AS '연락처'
FROM userTbl U
LEFT OUTER JOIN buyTbl B
ON U.userID = B.userID
WHERE B.prodName IS NULL
ORDER BY U.userID;
-- <실습 5> --
USE sqlDB;
SELECT S.stdName, S.addr, C.clubName, C.roomNo
FROM stdTbl S
LEFT OUTER JOIN stdclubTbl SC
ON S.stdName = SC.stdName
LEFT OUTER JOIN clubTbl C
ON SC.clubName = C.clubName
ORDER BY S.stdName;
SELECT C.clubName, C.roomNo, S.stdName, S.addr
FROM stdTbl S
LEFT OUTER JOIN stdclubTbl SC
ON SC.stdName = S.stdName
RIGHT OUTER JOIN clubTbl C
ON SC.clubName = C.clubName
ORDER BY C.clubName ;
SELECT S.stdName, S.addr, C.clubName, C.roomNo
FROM stdTbl S
LEFT OUTER JOIN stdclubTbl SC
ON S.stdName = SC.stdName
LEFT OUTER JOIN clubTbl C
ON SC.clubName = C.clubName
UNION
SELECT S.stdName, S.addr, C.clubName, C.roomNo
FROM stdTbl S
LEFT OUTER JOIN stdclubTbl SC
ON SC.stdName = S.stdName
RIGHT OUTER JOIN clubTbl C
ON SC.clubName = C.clubName;
USE sqlDB;
SELECT stdName, addr FROM stdTbl -- 중복된 열 포함/ union - 중복된 열 제거
UNION ALL
SELECT clubName, roomNo FROM clubTbl;
SELECT name, CONCAT(mobile1, mobile2) AS '전화번호' FROM userTbl -- 전화 없는 사람 제거
WHERE name NOT IN ( SELECT name FROM userTbl WHERE mobile1 IS NULL) ;
SELECT name, CONCAT(mobile1, mobile2) AS '전화번호' FROM userTbl -- 전화 없는 사람 조회
WHERE name IN ( SELECT name FROM userTbl WHERE mobile1 IS NULL) ;
DROP PROCEDURE IF EXISTS ifProc; -- 기존에 만든적이 있다면 삭제
DELIMITER $$
CREATE PROCEDURE ifProc()
BEGIN
DECLARE var1 INT; -- var1 변수선언
SET var1 = 100; -- 변수에 값 대입
IF var1 = 100 THEN -- 만약 @var1이 100이라면,
SELECT '100입니다.';
ELSE
SELECT '100이 아닙니다.';
END IF;
END $$
DELIMITER ;
CALL ifProc();
DROP PROCEDURE IF EXISTS ifProc3;
DELIMITER $$
CREATE PROCEDURE ifProc3()
BEGIN
DECLARE point INT ;
DECLARE credit CHAR(1);
SET point = 77 ;
IF point >= 90 THEN
SET credit = 'A';
ELSEIF point >= 80 THEN
SET credit = 'B';
ELSEIF point >= 70 THEN
SET credit = 'C';
ELSEIF point >= 60 THEN
SET credit = 'D';
ELSE
SET credit = 'F';
END IF;
SELECT CONCAT('취득점수==>', point), CONCAT('학점==>', credit);
END $$
DELIMITER ;
CALL ifProc3();
DROP PROCEDURE IF EXISTS caseProc;
DELIMITER $$
CREATE PROCEDURE caseProc()
BEGIN
DECLARE point INT ;
DECLARE credit CHAR(1);
SET point = 77 ;
CASE
WHEN point >= 90 THEN
SET credit = 'A';
WHEN point >= 80 THEN
SET credit = 'B';
WHEN point >= 70 THEN
SET credit = 'C';
WHEN point >= 60 THEN
SET credit = 'D';
ELSE
SET credit = 'F';
END CASE;
SELECT CONCAT('취득점수==>', point), CONCAT('학점==>', credit);
END $$
DELIMITER ;
CALL caseProc();
use sqldb;
SELECT U.userID, U.name, SUM(price*amount) AS '총구매액',
CASE
WHEN (SUM(price*amount) >= 1500) THEN '최우수고객'
WHEN (SUM(price*amount) >= 1000) THEN '우수고객'
WHEN (SUM(price*amount) >= 1 ) THEN '일반고객'
ELSE '유령고객'
END AS '고객등급'
FROM buyTbl B
RIGHT OUTER JOIN userTbl U
ON B.userID = U.userID
GROUP BY U.userID, U.name
ORDER BY sum(price*amount) DESC ;
-- </실습 7> --
DROP PROCEDURE IF EXISTS whileProc;
DELIMITER $$
CREATE PROCEDURE whileProc()
BEGIN
DECLARE i INT; -- 1에서 100까지 증가할 변수
DECLARE hap INT; -- 더한 값을 누적할 변수
SET i = 1;
SET hap = 0;
WHILE (i <= 100) DO
SET hap = hap + i; -- hap의 원래의 값에 i를 더해서 다시 hap에 넣으라는 의미
SET i = i + 1; -- i의 원래의 값에 1을 더해서 다시 i에 넣으라는 의미
END WHILE;
SELECT hap;
END $$
DELIMITER ;
CALL whileProc(); | 890db22bdf8ad2cea556325e51c94dd0fd63e4f3 | [
"SQL"
] | 17 | SQL | fastz123/4th_revolution | fd667fadfe952c45a0631c8b7f42172c34f6b833 | d2173211bfcd7e55806c5ec12f04549893b5e67d |
refs/heads/master | <repo_name>meadoch1/bin<file_sep>/pingcmme3
#!/bin/bash
curl https://env3-$1.integration.covermymeds.com/_ping
printf "\n"
<file_sep>/tmux-onlife-kill
#! /bin/bash
tmux -S /var/tmux/liveon send-keys -t liveon:3.1 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:3.2 C-c
tmux -S /var/tmux/liveon send-keys -t entity:3.1 C-c
tmux -S /var/tmux/liveon send-keys -t entity:3.2 C-c
tmux -S /var/tmux/liveon kill-server<file_sep>/tshare-start
#!/bin/bash
ln -sf "$SSH_AUTH_SOCK" "$HOME/.ssh/ssh-auth-sock"
# windows="orch epa pv ex_cmm_messages rb_cmm_messages protobuf_definitions"
# directories="orch examplepluginapp pipeline_verifier ex_cmm_messages rb_cmm_messages protobuf_definitions"
windows="fs fb bash"
directories="fhir-starter fhir_bridge fhir_bridge"
ports="3000"
window_a=(${windows// / })
directory_a=(${directories// / })
length=${#window_a[@]}
session="work"
$TCMD -S /tmp/work new-session -s $session -n console -d
$TCMD -S /tmp/work send-keys -t $session "cd ~/Dropbox/org/active.org" C-m
$TCMD -S /tmp/work send-keys -t $session "e" C-m
# $TCMD -S /tmp/work split-window -h -t $session
# $TCMD -S /tmp/work send-keys -t $session "cd ~/git/cmm/fhir_bridge/" C-m
# $TCMD -S /tmp/work send-keys -t $session "clear" C-m
# $TCMD -S /tmp/work split-window -v -t $session
for ((i==0;i<=$length-1;i++)); do
window="${window_a[$i]}"
directory="${directory_a[$i]}"
$TCMD -S /tmp/work new-window -n $window -t $session
$TCMD -S /tmp/work send-keys -t $session "cd ~/git/cmm/$directory/" C-m
$TCMD -S /tmp/work send-keys -t $session "e" C-m
# $TCMD -S /tmp/work new-window -t $session
# $TCMD -S /tmp/work send-keys -t $session "cd ~/git/cmm/$directory/" C-m
# $TCMD -S /tmp/work send-keys -t $session "clear" C-m
# $TCMD -S /tmp/work split-window -h -t $session
# $TCMD -S /tmp/work send-keys -t $session "cd ~/git/cmm/$directory/" C-m
# $TCMD -S /tmp/work send-keys -t $session "clear" C-m
done
$TCMD -S /tmp/work select-window -t $session:2
$TCMD -S /tmp/work -2 attach -t work
# $TCMD -S /tmp/work new-session -s work -n emacs -d
# for name in spec bash console vagrant watch; do
# $TCMD -S /tmp/work new-window -n $name -t work
# done
# for window in 1 2 3 4 5 6; do
# # cd to current directory to jostle rvm's fragile mind
# $TCMD -S /tmp/work send-keys -t work:$window 'cd .' C-m
# # clear screens of profile startup trash
# $TCMD -S /tmp/work send-keys -t work:$window 'clear' C-m
# done
# # get this party started
# $TCMD -S /tmp/work send-keys -t work:1 'cd ~/git/cmm/epamotron' C-m
# $TCMD -S /tmp/work send-keys -t work:1 'emacs' C-m
# $TCMD -S /tmp/work send-keys -t work:2 'time bundle exec rspec' C-m
# $TCMD -S /tmp/work send-keys -t work:4 'bundle exec rails console' C-m
# $TCMD -S /tmp/work send-keys -t work:5 'cd ~/cmm/vagrant' C-m
# $TCMD -S /tmp/work send-keys -t work:5 'vagrant ssh' C-m
# $TCMD -S /tmp/work send-keys -t work:6 'cd ~/cmm/vagrant/code' C-m
# # Select window 1 and attach to it
# $TCMD -S /tmp/work select-window -t work:1
# $TCMD -S /tmp/work -2 attach -t work
# # NOTES
# How to rename a window after you've created it
# $TCMD -S /tmp/work rename-window -t work:1 newname
<file_sep>/addpair
#! /bin/bash
gh-auth add --users=$1 --command="/usr/local/bin/tmux -S /var/tmp/cmm -2 attach -t epamotron"
sudo cp ~/.ssh/authorized_keys /Users/tmuxguest/.ssh/<file_sep>/hcl_alias.sh
#! /bin/bash
hcl alias admin 22492028 2152678
hcl alias break 22492028 12993302
hcl alias dev 22492028 2213734
hcl alias mtg 22492028 2213737
hcl alias pr 22492028 12993290
hcl alias groom 22492028 2213733
<file_sep>/pgr
#! /bin/bash
for x in spring rails phantomjs zeus; do
pgrep -fl $x;
done
<file_sep>/tm-start
#!/bin/bash
TCMD=tmate tshare-start
<file_sep>/envaws
#! /bin/bash
set -e
while [ "$1" != "" ]; do
case $1 in
*) profile="$1";;
esac
shift
done
if [[ -z "$profile" ]] ; then
echo 'Please supply the profile you wish to load into env'
echo ' example: envaws cb-dap-auth-nonprod-dev-cli'
exit 0
fi
mykey=`aws configure --profile $profile get aws_access_key_id`
mysecret_key=`aws configure --profile $profile get aws_secret_access_key`
mytoken=`aws configure --profile $profile get aws_session_token`
export AWS_ACCESS_KEY_ID=$mykey
export AWS_SECRET_ACCESS_KEY=$mysecret_key
export AWS_SESSION_TOKEN=$mytoken
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
<file_sep>/t-attach
#!/bin/bash
TCMD=tmux tshare-attach<file_sep>/tmux-cmm-kill
#! /bin/bash
#tmux -S /var/tmux/cmm send-keys -t liveon:3.1 C-c
#tmux -S /var/tmux/cmm send-keys -t liveon:3.2 C-c
#tmux -S /var/tmux/cmm send-keys -t entity:3.1 C-c
#tmux -S /var/tmux/cmm send-keys -t entity:3.2 C-c
tmux -S /var/tmp/cb kill-server
<file_sep>/tm-end
#!/bin/bash
TCMD=tmux tshare-end
<file_sep>/tmux-simple-start
#! /bin/bash --login
session="new"
directory="cb"
#port="3000"
tmux -v -S /var/tmux/cb new-session -s $session -n editor -d
tmux -v -S /var/tmux/cb send-keys -t $session "cd ~/git/cb/tpa/tpa" C-m
tmux -S /var/tmux/cb split-window -h -t $session
tmux -S /var/tmux/cb send-keys -t $session "v" C-m
tmux -S /var/tmux/cb new-window -n console -t $session
tmux -v -S /var/tmux/cb send-keys -t $session "cd ~/git/cb/tpa/tpa/" C-m
tmux -S /var/tmux/cb split-window -h -t $session
tmux -S /var/tmux/cb send-keys -t $session:2.1 "yarn start" C-m
# tmux -S /var/tmux/cb send-keys -t $session "v" C-m
# tmux -S /var/tmux/cb new-window -n docker -t $session
# tmux -v -S /var/tmux/cb send-keys -t $session "cd ~/git/cb/crane-docker/" C-m
# tmux -S /var/tmux/cb send-keys -t $session "v" C-m
# tmux -S /var/tmux/cb split-window -h -t $session
# tmux -S /var/tmux/cb new-window -n app -t $session
# tmux -S /var/tmux/cb split-window -h -t $session
# tmux -S /var/tmux/cb send-keys -t $session:2.1 "cd ~/git/$directory" C-m
# tmux -S /var/tmux/cb send-keys -t $session:2.2 "cd ~/git/$directory/" C-m
# tmux -S /var/tmux/cb send-keys -t $session:3.1 "cd ~/git/$directory" c-m
# tmux -S /var/tmux/cb send-keys -t $session:3.1 "bundle exec rails s -p $port" c-m
# tmux -S /var/tmux/cb send-keys -t $session:3.2 "cd ~/git/$directory" C-m
# tmux -S /var/tmux/cb send-keys -t $session:3.2 "bundle exec rails c" C-m
# tmux -S /var/tmux/cb rename-window -t $session:2 rspec
# tmux -S /var/tmux/cb rename-window -t $session:3 app
# tmux -S /var/tmux/cb select-window -t $session:1
# tmux -S /var/tmux/cb new-session -s ngrok -n console -d
# chgrp tmuxers /var/tmux/cb
tmux -v -S /var/tmux/cb -2 attach -t new
<file_sep>/tmux-simple-kill
#! /bin/bash
tmux -S /var/tmux/cb send-keys -t new:3.1 C-c
tmux -S /var/tmux/cb send-keys -t new:3.2 C-c
tmux -S /var/tmux/cb kill-server
<file_sep>/agf
#!/bin/bash
find . | ag "/.*$1[^/]*$"
<file_sep>/cinint
#!/bin/bash
cin admini "Participated in a candidate interview"
<file_sep>/renew_mfa
#! /bin/bash
~/bin/mfap
# aws ecr get-login-password --profile cb-pivot-nonprod-dev-cli --region us-east-1 | docker login --username AWS --password-stdin 7<PASSWORD>.dkr.ecr.us-east-1.amazonaws.com
acp cb-pivot-nonprod-dev-cli
# ~/bin/mfada
# ~/bin/mfadr
# ~/bin/mfats
# ~/bin/mfaita
# ~/bin/mfacat
# ~/bin/mfatpa
# ~/bin/mfasrp
# ~/bin/mfadev
# ~/bin/mfastage
# ~/bin/mfablue
<file_sep>/mfaita
#! /bin/bash
~/git/cb/bp/utility-scripts/setMfaSessionToken.sh -p cb-esattestassurance-nonprod-dev
<file_sep>/make_hcl_aliases
#!/bin/bash
hcl alias admin 4731947 2152678
hcl alias mtg 4731947 2213737
hcl alias pm 4731947 2152679
hcl alias dev 4731947 2213734
<file_sep>/tmate-liveon2
#! /bin/bash
rvm use ruby-1.9.3-p448
tmate send-keys -t liveon 'cd ~/git/onlife' C-m
tmate send-keys -t liveon 'e' C-m
tmate new-window -n rspec -t liveon
tmate new-window -n apps -t liveon
tmate split-window -h
tmate split-window -v
tmate select-pane -L
tmate split-window -v -p 66
tmate split-window -v
tmate new-window -n irb -t liveon
tmate split-window -h
tmate split-window -v
tmate select-pane -L
tmate split-window -v -p 66
tmate split-window -v
tmate new-window -n services -t liveon
tmate split-window -h
tmate new-window -n console -t liveon
tmate send-keys -t liveon:5.1 'rabbitmq-server' C-m
tmate send-keys -t liveon:5.2 'mongod' C-m
tmate send-keys -t liveon:2 'cd ~/git/onlife/liveon' C-m
tmate send-keys -t liveon:3.1 'cd ~/git/onlife/entity_service' C-m
tmate send-keys -t liveon:3.1 'bundle exec rails s -p 3002' C-m
tmate send-keys -t liveon:3.2 'cd ~/git/onlife/assessment_service' C-m
tmate send-keys -t liveon:3.2 'bundle exec rails s -p 3003' C-m
tmate send-keys -t liveon:3.3 'cd ~/git/onlife/platform_configuration' C-m
tmate send-keys -t liveon:3.3 'bundle exec rails s -p 3001' C-m
tmate send-keys -t liveon:3.4 'cd ~/git/onlife/liveon' C-m
tmate send-keys -t liveon:3.4 'bundle exec rails s' C-m
tmate send-keys -t liveon:3.5 'cd ~/git/onlife/onlife_health' C-m
tmate send-keys -t liveon:3.5 'bundle exec rails s -p 9494' C-m
tmate send-keys -t liveon:4.1 'cd ~/git/onlife/entity_service' C-m
tmate send-keys -t liveon:4.1 'bundle exec rails c' C-m
tmate send-keys -t liveon:4.2 'cd ~/git/onlife/assessment_service' C-m
tmate send-keys -t liveon:4.2 'bundle exec rails c' C-m
tmate send-keys -t liveon:4.3 'cd ~/git/onlife/platform_configuration' C-m
tmate send-keys -t liveon:4.3 'bundle exec rails c' C-m
tmate send-keys -t liveon:4.4 'cd ~/git/onlife/liveon' C-m
tmate send-keys -t liveon:4.4 'bundle exec rails c' C-m
tmate send-keys -t liveon:4.5 'cd ~/git/onlife/onlife_health' C-m
tmate send-keys -t liveon:4.5 'bundle exec rails c' C-m
tmate send-keys -t liveon:6 'cd ~/git' C-m
tmate rename-window -t liveon:2 rspec
tmate rename-window -t liveon:3 apps
tmate rename-window -t liveon:4 irb
tmate rename-window -t liveon:5 services
tmate select-window -t liveon:1
tmate attach -t liveon
<file_sep>/pingcmme3all
#!/bin/bash
pingcmme3 epamotron
pingcmme3 epa
pingcmme3 pbmproxy
pingcmme3 central
pingcmme3 eligibility
<file_sep>/tmux-cmm-start
#! /bin/bash
ln -sf "$SSH_AUTH_SOCK" "$HOME/.ssh/ssh-auth-sock"
rvm use ruby-2.0.0
sessions="epamotron dashboard"
directories="epamotron dashboard"
ports="3000"
session_a=(${sessions// / })
directory_a=(${directories// / })
port_a=(${ports// / })
length=${#session_a[@]}
for ((i==0;i<=$length-1;i++)); do
session="${session_a[$i]}"
directory="${directory_a[$i]}"
port="${port_a[$i]}"
tmux -S /var/tmp/cmm new-session -s $session -n editor -d
tmux -S /var/tmp/cmm send-keys -t $session "cd ~/git/cmm/$directory/" C-m
tmux -S /var/tmp/cmm send-keys -t $session "v" C-m
tmux -S /var/tmp/cmm new-window -n rspec -t $session
tmux -S /var/tmp/cmm split-window -h -t $session
tmux -S /var/tmp/cmm new-window -n app -t $session
tmux -S /var/tmp/cmm split-window -h -t $session
tmux -S /var/tmp/cmm send-keys -t $session:2.1 "cd ~/git/cmm/$directory" C-m
tmux -S /var/tmp/cmm send-keys -t $session:2.2 "cd ~/git/cmm/$directory/" C-m
tmux -S /var/tmp/cmm send-keys -t $session:3.1 "cd ~/git/cmm/$directory" c-m
tmux -S /var/tmp/cmm send-keys -t $session:3.1 "bundle exec rails s -p $port" c-m
tmux -S /var/tmp/cmm send-keys -t $session:3.2 "cd ~/git/cmm/$directory" C-m
tmux -S /var/tmp/cmm send-keys -t $session:3.2 "bundle exec rails c" C-m
tmux -S /var/tmp/cmm rename-window -t $session:2 rspec
tmux -S /var/tmp/cmm rename-window -t $session:3 app
tmux -S /var/tmp/cmm select-window -t $session:1
done
tmux -S /var/tmp/cmm new-session -s ngrok -n console -d
chgrp tmuxers /var/tmp/cmm
tmux -S /var/tmp/cmm -2 attach -t epamotron
<file_sep>/pgk
#! /bin/bash
for x in spring rails phantomjs zeus; do
pkill -fl $x;
done<file_sep>/tmux-simple-attach
#! /bin/bash
tmux -S /var/tmp/cb -2 attach -t new
<file_sep>/cinso
#!/bin/bash
cin mtg "Participated in the LiveOn daily standup"
<file_sep>/zslog
#!/bin/bash
tail -n200 /Library/Application\ Support/Zscaler/ZSAT*.log
ls /Library/Application\ Support/Zscaler/ZSAT*.log
<file_sep>/start-kafka
#! /bin/bash
zookeeper-server-start /usr/local/etc/kafka/zookeeper.properties & kafka-server-start /usr/local/etc/kafka/server.properties
<file_sep>/cout
#!/bin/bash
hcl stop
<file_sep>/tmate-liveon
#! /bin/bash
rvm use ruby-1.9.3-p448
tmate -S /var/tmux/liveon new-session -s liveon -n editor -d
tmate -S /var/tmux/liveon send-keys -t liveon 'cd ~/git/onlife' C-m
tmate -S /var/tmux/liveon send-keys -t liveon 'e' C-m
tmate -S /var/tmux/liveon new-window -n rspec -t liveon
tmate -S /var/tmux/liveon new-window -n apps -t liveon
tmate -S /var/tmux/liveon split-window -h
tmate -S /var/tmux/liveon split-window -v
tmate -S /var/tmux/liveon select-pane -L
tmate -S /var/tmux/liveon split-window -v -p 66
tmate -S /var/tmux/liveon split-window -v
tmate -S /var/tmux/liveon new-window -n irb -t liveon
tmate -S /var/tmux/liveon split-window -h
tmate -S /var/tmux/liveon split-window -v
tmate -S /var/tmux/liveon select-pane -L
tmate -S /var/tmux/liveon split-window -v -p 66
tmate -S /var/tmux/liveon split-window -v
tmate -S /var/tmux/liveon new-window -n services -t liveon
tmate -S /var/tmux/liveon split-window -h
tmate -S /var/tmux/liveon new-window -n console -t liveon
tmate -S /var/tmux/liveon send-keys -t liveon:5.1 'rabbitmq-server' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:5.2 'mongod' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:2 'cd ~/git/onlife/liveon' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.1 'cd ~/git/onlife/entity_service' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.1 'bundle exec rails s -p 3002' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.2 'cd ~/git/onlife/assessment_service' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.2 'bundle exec rails s -p 3003' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.3 'cd ~/git/onlife/platform_configuration' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.3 'bundle exec rails s -p 3001' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.4 'cd ~/git/onlife/liveon' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.4 'bundle exec rails s' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.5 'cd ~/git/onlife/onlife_health' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:3.5 'bundle exec rails s -p 9494' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.1 'cd ~/git/onlife/entity_service' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.1 'bundle exec rails c' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.2 'cd ~/git/onlife/assessment_service' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.2 'bundle exec rails c' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.3 'cd ~/git/onlife/platform_configuration' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.3 'bundle exec rails c' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.4 'cd ~/git/onlife/liveon' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.4 'bundle exec rails c' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.5 'cd ~/git/onlife/onlife_health' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:4.5 'bundle exec rails c' C-m
tmate -S /var/tmux/liveon send-keys -t liveon:6 'cd ~/git' C-m
tmate -S /var/tmux/liveon rename-window -t liveon:2 rspec
tmate -S /var/tmux/liveon rename-window -t liveon:3 apps
tmate -S /var/tmux/liveon rename-window -t liveon:4 irb
tmate -S /var/tmux/liveon rename-window -t liveon:5 services
tmate -S /var/tmux/liveon select-window -t liveon:1
chgrp tmuxers /var/tmux/liveon
tmate -S /var/tmux/liveon -2 attach -t liveon
<file_sep>/tmux-onlife-start
#! /bin/bash
rvm use ruby-1.9.3-p448
sessions="liveon entity assessment config ondemand plyushkin eligibility dl"
directories="liveon entity_service assessment_service platform_configuration onlife_health plyushkin-service eligibility_service direct_login"
ports="3000 3002 3003 3001 9494 3004 3005 nil"
session_a=(${sessions// / })
directory_a=(${directories// / })
port_a=(${ports// / })
length=${#session_a[@]}
for ((i==0;i<=$length-1;i++)); do
session="${session_a[$i]}"
directory="${directory_a[$i]}"
port="${port_a[$i]}"
tmux -S /var/tmux/liveon new-session -s $session -n editor -d
tmux -S /var/tmux/liveon send-keys -t $session "cd ~/git/onlife/$directory/" C-m
tmux -S /var/tmux/liveon send-keys -t $session "v" C-m
tmux -S /var/tmux/liveon new-window -n rspec -t $session
tmux -S /var/tmux/liveon split-window -h -t $session
tmux -S /var/tmux/liveon new-window -n app -t $session
tmux -S /var/tmux/liveon split-window -h -t $session
tmux -S /var/tmux/liveon send-keys -t $session:2.1 "cd ~/git/onlife/$directory" C-m
tmux -S /var/tmux/liveon send-keys -t $session:2.2 "cd ~/git/onlife/$directory/" C-m
tmux -S /var/tmux/liveon send-keys -t $session:3.1 "cd ~/git/onlife/$directory" c-m
tmux -S /var/tmux/liveon send-keys -t $session:3.1 "bundle exec rails s -p $port" c-m
tmux -S /var/tmux/liveon send-keys -t $session:3.2 "cd ~/git/onlife/$directory" C-m
tmux -S /var/tmux/liveon send-keys -t $session:3.2 "bundle exec rails c" C-m
tmux -S /var/tmux/liveon rename-window -t $session:2 rspec
tmux -S /var/tmux/liveon rename-window -t $session:3 app
tmux -S /var/tmux/liveon select-window -t $session:1
done
tmux -S /var/tmux/liveon new-session -s ngrok -n console -d
chgrp tmuxers /var/tmux/liveon
tmux -S /var/tmux/liveon -2 attach -t liveon
<file_sep>/cin
#!/bin/bash
cout
hcl @$1 $2
<file_sep>/tmux-onlife-attach
#! /bin/bash
tmux -S /var/tmux/liveon -2 attach -t liveon
<file_sep>/tmux-liveon-kill
#! /bin/bash
tmux -S /var/tmux/liveon send-keys -t liveon:5.2 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:5.2 'rabbitmqctl stop' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.1 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:3.2 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:3.3 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:3.4 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:3.5 C-c
tmux -S /var/tmux/liveon send-keys -t liveon:4.5 'exit' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.4 'exit' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.3 'exit' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.2 'exit' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.1 'exit' C-m
tmux -S /var/tmux/liveon kill-server<file_sep>/mfaitaprod
#! /bin/bash
~/git/cb/bp/utility-scripts/setMfaSessionToken.sh -p cb-esattestassurance-prod-dev
~/git/cb/bp/utility-scripts/setMfaSessionToken.sh -p cb-esattestassurance-prod-admin
<file_sep>/tmux-liveon-start
#! /bin/bash
rvm use ruby-1.9.3-p448
tmux -S /var/tmux/liveon new-session -s liveon -n editor -d
tmux -S /var/tmux/liveon send-keys -t liveon 'cd ~/git/onlife' C-m
tmux -S /var/tmux/liveon send-keys -t liveon 'e' C-m
tmux -S /var/tmux/liveon new-window -n rspec -t liveon
tmux -S /var/tmux/liveon new-window -n apps -t liveon
tmux -S /var/tmux/liveon split-window -h
tmux -S /var/tmux/liveon split-window -v
tmux -S /var/tmux/liveon select-pane -L
tmux -S /var/tmux/liveon split-window -v -p 66
tmux -S /var/tmux/liveon split-window -v
tmux -S /var/tmux/liveon new-window -n irb -t liveon
tmux -S /var/tmux/liveon split-window -h
tmux -S /var/tmux/liveon split-window -v
tmux -S /var/tmux/liveon select-pane -L
tmux -S /var/tmux/liveon split-window -v -p 66
tmux -S /var/tmux/liveon split-window -v
tmux -S /var/tmux/liveon new-window -n services -t liveon
tmux -S /var/tmux/liveon split-window -h
tmux -S /var/tmux/liveon new-window -n console -t liveon
tmux -S /var/tmux/liveon send-keys -t liveon:5.1 'rabbitmq-server' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:5.2 'mongod' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:2 'cd ~/git/onlife/liveon' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.1 'cd ~/git/onlife/entity_service' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.1 'bundle exec rails s -p 3002' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.2 'cd ~/git/onlife/assessment_service' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.2 'bundle exec rails s -p 3003' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.3 'cd ~/git/onlife/platform_configuration' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.3 'bundle exec rails s -p 3001' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.4 'cd ~/git/onlife/liveon' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.4 'bundle exec rails s' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.5 'cd ~/git/onlife/onlife_health' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:3.5 'bundle exec rails s -p 9494' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.1 'cd ~/git/onlife/entity_service' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.1 'bundle exec rails c' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.2 'cd ~/git/onlife/assessment_service' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.2 'bundle exec rails c' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.3 'cd ~/git/onlife/platform_configuration' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.3 'bundle exec rails c' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.4 'cd ~/git/onlife/liveon' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.4 'bundle exec rails c' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.5 'cd ~/git/onlife/onlife_health' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:4.5 'bundle exec rails c' C-m
tmux -S /var/tmux/liveon send-keys -t liveon:6 'cd ~/git' C-m
tmux -S /var/tmux/liveon rename-window -t liveon:2 rspec
tmux -S /var/tmux/liveon rename-window -t liveon:3 apps
tmux -S /var/tmux/liveon rename-window -t liveon:4 irb
tmux -S /var/tmux/liveon rename-window -t liveon:5 services
tmux -S /var/tmux/liveon select-window -t liveon:1
chgrp tmuxers /var/tmux/liveon
tmux -S /var/tmux/liveon -2 attach -t liveon
<file_sep>/cinmc
#!/bin/bash
cin admin "Morning communication catch-up"
<file_sep>/publish_int_key
#!/bin/bash
servers=( int-portweb01 int-portweb02 int-adminweb01 int-linbe01 )
for server in "${servers[@]}"
do
scp ~/.ssh/id_olh_qa.pub $server:~/
ssh $server "mkdir .ssh; mv id_olh_qa.pub .ssh/authorized_keys; chmod 700 .ssh; chmod 600 .ssh/authorized_keys"
ssh $server
done
<file_sep>/cintrouble
#!/bin/bash
cin devi "Supported Production issues"
<file_sep>/publish_qa_key
#!/bin/bash
servers=( QA-MDB01 QA-RMQ01 QA-SOLR01 QA-DAEMON01 QA-PORTWEB01 QA-PORTWEB02 QA-ASSESSWEB01 QA-ASSESSWEB02 QA-WEBSERV01 QA-WEBSERV02 QA-ADMINWEB01 )
for server in "${servers[@]}"
do
scp ~/.ssh/id_olh_qa.pub $server:~/
ssh $server "mkdir .ssh; mv id_olh_qa.pub .ssh/authorized_keys; chmod 700 .ssh; chmod 600 .ssh/authorized_keys"
ssh $server
done
<file_sep>/tm-attach
#!/bin/bash
TCMD=tmate tshare-attach
<file_sep>/tm-link
#!/bin/bash
tmate display -p '#{tmate_ssh}'
<file_sep>/tshare-end
#!/bin/sh
$TCMD -S /tmp/work kill-server<file_sep>/t-start
#!/bin/bash
TCMD=tmux tshare-start
<file_sep>/tshare-attach
#!/bin/bash
$TCMD -S /tmp/work -2 attach -t work<file_sep>/cinpr
#!/bin/bash
cin dev "Reviewed PRs"
<file_sep>/cres
#!/bin/bash
hcl resume @$1
| 7d9ed6da84d9cb0f5cb62886ec4b264909795b27 | [
"Shell"
] | 45 | Shell | meadoch1/bin | fda2bcbec539c3a01b959272e157eee314ce8375 | 114e5f9c841f50c50ecbe2f2072d05a5e7dd51d4 |
refs/heads/master | <repo_name>cybertron/openstack-virtual-baremetal<file_sep>/doc/source/host-cloud/patches.rst
Patching the Host Cloud
=======================
The changes described in this section apply to compute nodes in the
host cloud.
Apply the Nova pxe boot patch file in the ``patches`` directory to the host
cloud Nova. ``nova-pxe-boot.patch`` can be used with all releases prior to
Pike, ``nova-pxe-boot-pike.patch`` must be used with Pike and later.
Examples:
TripleO/RDO::
sudo patch -p1 -d /usr/lib/python2.7/site-packages < patches/nova/nova-pxe-boot.patch
or
::
sudo patch -p1 -d /usr/lib/python2.7/site-packages < patches/nova/nova-pxe-boot-pike.patch
Devstack:
.. note:: You probably don't want to try to run this with devstack anymore.
Devstack no longer supports rejoining an existing stack, so if you
have to reboot your host cloud you will have to rebuild from
scratch.
.. note:: The patch may not apply cleanly against master Nova
code. If/when that happens, the patch will need to
be applied manually.
::
cp patches/nova/nova-pxe-boot.patch /opt/stack/nova
cd /opt/stack/nova
patch -p1 < nova-pxe-boot.patch
or
::
cp patches/nova/nova-pxe-boot-pike.patch /opt/stack/nova
cd /opt/stack/nova
patch -p1 < nova-pxe-boot-pike.patch
<file_sep>/doc/source/introduction.rst
Introduction
============
OpenStack Virtual Baremetal is a way to use OpenStack instances to do
simulated baremetal deployments. This project is a collection of tools
and documentation that make it much easier to do so. It primarily consists
of the following pieces:
- Patches and documentation for setting up a host cloud.
- A deployment CLI that leverages the OpenStack Heat project to deploy the
VMs, networks, and other resources needed.
- An OpenStack BMC that can be used to control OpenStack instances via IPMI
commands.
- A tool to collect details from the "baremetal" VMs so they can be added as
nodes in the OpenStack Ironic baremetal deployment project.
A basic OVB environment is just a BMC VM configured to control a number
of "baremetal" VMs. This allows them to be treated largely the same
way a real baremetal system with a BMC would. A number of additional
features can also be enabled to add more to the environment.
OVB was initially conceived as an improved method to deploy environments for
OpenStack TripleO development and testing. As such, much of the terminology
is specific to TripleO. However, it should be possible to use it for any
non-TripleO scenarios where a baremetal-style deployment is desired.
Benefits and Drawbacks
----------------------
As noted above, OVB started as part of the OpenStack TripleO project.
Previous methods for deploying virtual environments for TripleO focused on
setting up all the vms for a given environment on a single box. This had a
number of drawbacks:
- Each developer needed to have their own system. Sharing was possible, but
more complex and generally not done. Multi-tenancy is a basic design
tenet of OpenStack so this is not a problem when using it to provision the
VMs. A large number of developers can make use of a much smaller number of
physical systems.
- If a deployment called for more VMs than could fit on a single system, it
was a complex manual process to scale out to multiple systems. An OVB
environment is only limited by the number of instances the host cloud can
support.
- Pre-OVB test environments were generally static because there was not an API
for dynamic provisioning. By using the OpenStack API to create all of the
resources, test environments can be easily tailored to their intended use
case.
One drawback to OVB at this time is that it does have hard requirements on a
few OpenStack features (Heat, Neutron port-security, private image uploads,
for example) that are not all widely available in public clouds. Fortunately,
as they move to newer and newer versions of OpenStack that situation should
improve.
It should also be noted that without the Nova PXE boot patch, OVB is not
compatible with any workflows that write to the root disk before deployment.
This includes Ironic node cleaning.
<file_sep>/doc/source/deploy/heterogeneous.rst
Deploying Heterogeneous Environments
====================================
It is possible to deploy an OVB environment with multiple "baremetal"
node types. The :doc:`QuintupleO <quintupleo>` deployment method must be used, so it
would be best to start with a working configuration for that before
moving on to heterogeneous deployments.
Each node type will be identified as a ``role``. A simple QuintupleO
deployment can be thought of as a single-role deployment. To deploy
multiple roles, additional environment files describing the extra roles
are required. These environments are simplified versions of the
standard environment file. See ``environments/base-role.yaml``
for a starting point when writing these role files.
.. note:: Each extra role consists of exactly one environment file. This
means that the standalone option environments cannot be used with
roles. To override the options specified for the primary role in
a secondary role, the parameter_defaults and resource_registry
entries from the option environment must be copied into the role
environment.
However, note that most resource_registry entries are filtered out
of role environments anyway since they are not relevant for a
secondary stack.
Steps for deploying the environment:
#. Customize the environment files. Make sure all environments have a ``role``
key in the ``parameter_defaults`` section. When building nodes.json, this
role will be automatically assigned to the node, so it is simplest to use
one of the default TripleO roles (control, compute, cephstorage, etc.).
#. Deploy with both roles::
bin/deploy.py --quintupleo --env env-control.yaml --role env-compute.yaml
#. One Heat stack will be created for each role being deployed. Wait for them
all to complete before proceeding.
.. note:: Be aware that the extra role stacks will be connected to networks
in the primary role stack, so the extra stacks must be deleted
before the primary one or the neutron subnets will not delete cleanly.
#. Build a nodes.json file that can be imported into Ironic::
bin/build-nodes-json --env env-control.yaml
.. note:: Only the primary environment file needs to be passed here. The
resources deployed as part of the secondary roles will be named
such that they appear to be part of the primary environment.
.. note:: If ``--id`` was used when deploying, remember to pass the generated
environment file to this command instead of the original.
<file_sep>/openstack_virtual_baremetal/tests/test_auth.py
# Copyright 2017 Red Hat Inc.
#
# 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.
import fixtures
import json
import mock
import testtools
from openstack_virtual_baremetal import auth
class TestCreateAuthParameters(testtools.TestCase):
@mock.patch('openstack_virtual_baremetal.auth.OS_CLOUD', 'foo')
@mock.patch('os_client_config.OpenStackConfig')
def test_create_auth_parameters_os_cloud(self, mock_osc):
mock_data = mock.Mock()
mock_data.config = {'auth': {'username': 'admin',
'password': '<PASSWORD>',
'project_name': 'admin',
'auth_url': 'http://host:5000',
}}
mock_instance = mock.Mock()
mock_instance.get_one_cloud.return_value = mock_data
mock_osc.return_value = mock_instance
result = auth._create_auth_parameters()
expected = {'os_user': 'admin',
'os_password': '<PASSWORD>',
'os_tenant': 'admin',
'os_auth_url': 'http://host:5000',
'os_project': 'admin',
'os_user_domain': '',
'os_project_domain': '',
}
self.assertEqual(expected, result)
@mock.patch('openstack_virtual_baremetal.auth.OS_CLOUD', 'foo')
@mock.patch('os_client_config.OpenStackConfig')
def test_create_auth_parameters_os_cloud_v3_id(self, mock_osc):
mock_data = mock.Mock()
mock_data.config = {'auth': {'username': 'admin',
'password': '<PASSWORD>',
'project_name': 'admin',
'auth_url': 'http://host:5000',
'user_domain_id': 'default',
'project_domain_id': 'default',
}}
mock_instance = mock.Mock()
mock_instance.get_one_cloud.return_value = mock_data
mock_osc.return_value = mock_instance
result = auth._create_auth_parameters()
expected = {'os_user': 'admin',
'os_password': '<PASSWORD>',
'os_tenant': 'admin',
'os_auth_url': 'http://host:5000',
'os_project': 'admin',
'os_user_domain': 'default',
'os_project_domain': 'default',
}
self.assertEqual(expected, result)
@mock.patch('openstack_virtual_baremetal.auth.OS_CLOUD', 'foo')
@mock.patch('os_client_config.OpenStackConfig')
def test_create_auth_parameters_os_cloud_v3_name(self, mock_osc):
mock_data = mock.Mock()
mock_data.config = {'auth': {'username': 'admin',
'password': '<PASSWORD>',
'project_name': 'admin',
'auth_url': 'http://host:5000',
'user_domain_name': 'default',
'project_domain_name': 'default',
}}
mock_instance = mock.Mock()
mock_instance.get_one_cloud.return_value = mock_data
mock_osc.return_value = mock_instance
result = auth._create_auth_parameters()
expected = {'os_user': 'admin',
'os_password': '<PASSWORD>',
'os_tenant': 'admin',
'os_auth_url': 'http://host:5000',
'os_project': 'admin',
'os_user_domain': 'default',
'os_project_domain': 'default',
}
self.assertEqual(expected, result)
def test_create_auth_parameters_env_v3(self):
self.useFixture(fixtures.EnvironmentVariable('OS_USERNAME', 'admin'))
self.useFixture(fixtures.EnvironmentVariable('OS_PASSWORD', 'pw'))
self.useFixture(fixtures.EnvironmentVariable('OS_TENANT_NAME',
'admin'))
self.useFixture(fixtures.EnvironmentVariable('OS_AUTH_URL', 'auth/v3'))
self.useFixture(fixtures.EnvironmentVariable('OS_PROJECT_NAME',
'admin'))
self.useFixture(fixtures.EnvironmentVariable('OS_USER_DOMAIN_ID',
'default'))
self.useFixture(fixtures.EnvironmentVariable('OS_PROJECT_DOMAIN_ID',
'default'))
result = auth._create_auth_parameters()
expected = {'os_user': 'admin',
'os_password': 'pw',
'os_tenant': 'admin',
'os_auth_url': 'auth/v3',
'os_project': 'admin',
'os_user_domain': 'default',
'os_project_domain': 'default',
}
self.assertEqual(expected, result)
def test_create_auth_parameters_env_name(self):
self.useFixture(fixtures.EnvironmentVariable('OS_USERNAME', 'admin'))
self.useFixture(fixtures.EnvironmentVariable('OS_PASSWORD', 'pw'))
self.useFixture(fixtures.EnvironmentVariable('OS_TENANT_NAME',
None))
self.useFixture(fixtures.EnvironmentVariable('OS_AUTH_URL', 'auth/v3'))
self.useFixture(fixtures.EnvironmentVariable('OS_PROJECT_NAME',
'admin'))
self.useFixture(fixtures.EnvironmentVariable('OS_USER_DOMAIN_NAME',
'default'))
self.useFixture(fixtures.EnvironmentVariable('OS_PROJECT_DOMAIN_NAME',
'default'))
result = auth._create_auth_parameters()
expected = {'os_user': 'admin',
'os_password': 'pw',
'os_tenant': 'admin',
'os_auth_url': 'auth/v3',
'os_project': 'admin',
'os_user_domain': 'default',
'os_project_domain': 'default',
}
self.assertEqual(expected, result)
class TestCloudJSON(testtools.TestCase):
@mock.patch('openstack_virtual_baremetal.auth.OS_CLOUD', 'foo')
@mock.patch('os_client_config.OpenStackConfig')
def test_cloud_json(self, mock_osc):
mock_data = mock.Mock()
mock_data.config = {'auth': {'username': 'admin',
'password': '<PASSWORD>',
'project_name': 'admin',
'auth_url': 'http://host:5000',
'user_domain_name': 'default',
'project_domain_name': 'default',
}}
mock_instance = mock.Mock()
mock_instance.get_one_cloud.return_value = mock_data
mock_osc.return_value = mock_instance
result = auth._cloud_json()
expected = json.dumps(mock_data.config)
self.assertEqual(expected, result)
<file_sep>/bin/test-job-v2
#!/bin/bash
# Edit these to match your environment
BMC_IMAGE=bmc-base
BMC_FLAVOR=bmc
KEY_NAME=default
UNDERCLOUD_IMAGE=centos7-base
UNDERCLOUD_FLAVOR=undercloud-16
BAREMETAL_FLAVOR=baremetal
EXTERNAL_NET=external
# Set to 0 if you're not running in bnemec's private cloud
LOCAL=1
set -ex
date
start_seconds=$(date +%s)
BIN_DIR=$(cd $(dirname $0); pwd -P)
MY_ID=$1
BMC_PREFIX=bmc-$MY_ID
BAREMETAL_PREFIX=baremetal-$MY_ID
UNDERCLOUD_NAME=undercloud-$MY_ID
PUBLIC_NET=public-$MY_ID
PROVISION_NET=provision-$MY_ID
PRIVATE_NET=private-$MY_ID
# NOTE(bnemec): I'm intentionally not adding a trap to clean this up because
# if something fails it may be helpful to look at the contents of the tempdir.
TEMPDIR=$(mktemp -d)
echo "Working in $TEMPDIR"
cd $TEMPDIR
cp -r $BIN_DIR/../templates .
cp -r $BIN_DIR/../environments .
cp -r $BIN_DIR/../overcloud-templates .
cp environments/base.yaml ./env.yaml
sed -i "s/bmc_image: .*/bmc_image: $BMC_IMAGE/" env.yaml
sed -i "s/bmc_flavor: .*/bmc_flavor: $BMC_FLAVOR/" env.yaml
sed -i "s/key_name: .*/key_name: $KEY_NAME/" env.yaml
sed -i "s/baremetal_flavor: .*/baremetal_flavor: $BAREMETAL_FLAVOR/" env.yaml
sed -i "s/undercloud_image: .*/undercloud_image: $UNDERCLOUD_IMAGE/" env.yaml
sed -i "s/undercloud_flavor: .*/undercloud_flavor: $UNDERCLOUD_FLAVOR/" env.yaml
sed -i "s|external_net: .*|external_net: $EXTERNAL_NET|" env.yaml
sed -i "s/private_net: .*/private_net: $PRIVATE_NET/" env.yaml
if [ $LOCAL -eq 1 ]
then
sed -i "s/dns_nameservers: .*/dns_nameservers: 172.16.31.10/" environments/create-private-network.yaml
fi
cp -r $BIN_DIR ./bin
cp -r $BIN_DIR/../openstack_virtual_baremetal .
STACK_NAME=$MY_ID
$BIN_DIR/deploy.py --quintupleo --id $MY_ID --name $STACK_NAME --poll -e env.yaml -e environments/create-private-network.yaml -e environments/all-networks.yaml
UNDERCLOUD_IP=$(heat output-show $STACK_NAME undercloud_host_floating_ip | sed -e 's/"//g')
bin/build-nodes-json --env env-$MY_ID.yaml --driver ipmi
SSH_OPTS="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=Verbose -o PasswordAuthentication=no -o ConnectionAttempts=32 "
# Canary command to make sure the undercloud is ready
until ssh -t -t $SSH_OPTS centos@$UNDERCLOUD_IP ls; do sleep 1; done
scp $SSH_OPTS bin/ovb-instack centos@$UNDERCLOUD_IP:/tmp
scp $SSH_OPTS nodes.json centos@$UNDERCLOUD_IP:~/instackenv.json
scp $SSH_OPTS -r overcloud-templates centos@$UNDERCLOUD_IP:~
ssh -t -t $SSH_OPTS centos@$UNDERCLOUD_IP LOCAL=$LOCAL VERSION=2 /tmp/ovb-instack
heat stack-delete -y $STACK_NAME
date
end_seconds=$(date +%s)
elapsed_seconds=$(($end_seconds - $start_seconds))
echo "Finished in $elapsed_seconds seconds"
rm -rf $TEMPDIR
<file_sep>/requirements.txt
os-client-config
pyghmi
PyYAML
python-glanceclient
python-heatclient
python-keystoneclient
python-neutronclient
python-novaclient
<file_sep>/bin/start-env
#!/bin/bash
# Usage: start-env <ID>
# Example: start-env test
# This will start the undercloud-test and bmc-test instances
nova start bmc-$1 undercloud-$1
<file_sep>/openstack_virtual_baremetal/tests/test_openstackbmc.py
# Copyright 2016 Red Hat Inc.
#
# 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.
import sys
import unittest
import fixtures
import mock
from novaclient import exceptions
import testtools
from openstack_virtual_baremetal import openstackbmc
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'log')
@mock.patch('pyghmi.ipmi.bmc.Bmc.__init__')
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_find_instance')
@mock.patch('os_client_config.make_client')
class TestOpenStackBmcInit(testtools.TestCase):
def test_init_os_cloud(self, mock_make_client, mock_find_instance,
mock_bmc_init, mock_log):
mock_client = mock.Mock()
mock_server = mock.Mock()
mock_server.name = 'foo-instance'
mock_client.servers.get.return_value = mock_server
mock_make_client.return_value = mock_client
mock_find_instance.return_value = 'abc-123'
bmc = openstackbmc.OpenStackBmc(authdata={'admin': '<PASSWORD>'},
port=623,
address='::ffff:127.0.0.1',
instance='foo',
cache_status=False,
os_cloud='bar'
)
mock_make_client.assert_called_once_with('compute', cloud='bar')
mock_find_instance.assert_called_once_with('foo')
self.assertEqual('abc-123', bmc.instance)
mock_client.servers.get.assert_called_once_with('abc-123')
mock_log.assert_called_once_with('Managing instance: %s UUID: %s' %
('foo-instance', 'abc-123'))
@mock.patch('time.sleep')
def test_init_retry(self, _, mock_make_client, mock_find_instance,
mock_bmc_init, mock_log):
self.useFixture(fixtures.EnvironmentVariable('OS_CLOUD', None))
mock_client = mock.Mock()
mock_server = mock.Mock()
mock_server.name = 'foo-instance'
mock_client.servers.get.return_value = mock_server
mock_make_client.return_value = mock_client
mock_find_instance.side_effect = (Exception, 'abc-123')
bmc = openstackbmc.OpenStackBmc(authdata={'<PASSWORD>': '<PASSWORD>'},
port=623,
address='::ffff:127.0.0.1',
instance='foo',
cache_status=False,
os_cloud='foo'
)
mock_make_client.assert_called_once_with('compute', cloud='foo')
find_calls = [mock.call('foo'), mock.call('foo')]
self.assertEqual(find_calls, mock_find_instance.mock_calls)
self.assertEqual('abc-123', bmc.instance)
mock_client.servers.get.assert_called_once_with('abc-123')
log_calls = [mock.call('Exception finding instance "%s": %s' %
('foo', '')),
mock.call('Managing instance: %s UUID: %s' %
('foo-instance', 'abc-123'))
]
self.assertEqual(log_calls, mock_log.mock_calls)
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'__init__', return_value=None)
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'log')
@mock.patch('novaclient.client.Client')
class TestOpenStackBmc(unittest.TestCase):
def _create_bmc(self, mock_nova):
self.mock_client = mock.Mock()
mock_nova.return_value = self.mock_client
self.bmc = openstackbmc.OpenStackBmc(authdata={'<PASSWORD>': '<PASSWORD>'},
port=623,
address='::ffff:127.0.0.1',
instance='foo',
cache_status=False,
os_cloud='bar'
)
self.bmc.novaclient = self.mock_client
self.bmc.instance = 'abc-123'
self.bmc.cached_status = None
self.bmc.target_status = None
self.bmc.cache_status = False
def test_find_instance(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
self.mock_client.servers.get.return_value = mock_server
instance = self.bmc._find_instance('abc-123')
self.assertEqual('abc-123', instance)
def test_find_instance_by_name(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
mock_server.id = 'abc-123'
self.mock_client.servers.get.side_effect = exceptions.NotFound('foo')
self.mock_client.servers.list.return_value = [mock_server]
instance = self.bmc._find_instance('abc-123')
self.assertEqual('abc-123', instance)
@mock.patch('sys.exit')
def test_find_instance_multiple(self, mock_exit, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
self.mock_client.servers.get.side_effect = exceptions.NotFound('foo')
self.mock_client.servers.list.return_value = [mock_server, mock_server]
self.bmc._find_instance('abc-123')
mock_exit.assert_called_once_with(1)
@mock.patch('sys.exit')
def test_find_instance_not_found(self, mock_exit, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
self.mock_client.servers.get.side_effect = exceptions.NotFound('foo')
self.mock_client.servers.list.return_value = []
self.bmc._find_instance('abc-123')
mock_exit.assert_called_once_with(1)
def test_get_boot_device(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
mock_server.metadata.get.return_value = None
self.mock_client.servers.get.return_value = mock_server
device = self.bmc.get_boot_device()
self.assertEqual('hd', device)
def test_get_boot_device_network(self, mock_nova, mock_log, mock_init):
def fake_get(key):
if key == 'libvirt:pxe-first':
return '1'
return ''
self._create_bmc(mock_nova)
mock_server = mock.Mock()
mock_server.metadata.get.side_effect = fake_get
self.mock_client.servers.get.return_value = mock_server
device = self.bmc.get_boot_device()
self.assertEqual('network', device)
def test_set_boot_device_hd(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
self.mock_client.servers.get.return_value = mock_server
self.bmc.set_boot_device('hd')
self.mock_client.servers.set_meta_item.assert_called_once_with(
mock_server,
'libvirt:pxe-first',
'')
def test_set_boot_device_net(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
self.mock_client.servers.get.return_value = mock_server
self.bmc.set_boot_device('network')
self.mock_client.servers.set_meta_item.assert_called_once_with(
mock_server,
'libvirt:pxe-first',
'1')
def test_instance_active(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
mock_server.status = 'ACTIVE'
self.mock_client.servers.get.return_value = mock_server
self.assertTrue(self.bmc._instance_active())
def test_instance_inactive(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
mock_server.status = 'SHUTOFF'
self.mock_client.servers.get.return_value = mock_server
self.assertFalse(self.bmc._instance_active())
def test_instance_active_mismatch(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_server = mock.Mock()
mock_server.status = 'ACTIVE'
self.mock_client.servers.get.return_value = mock_server
self.bmc.target_status = 'ACTIVE'
self.bmc.cached_status = 'SHUTOFF'
self.bmc.cache_status = True
self.assertTrue(self.bmc._instance_active())
def test_instance_active_cached(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
self.bmc.target_status = 'ACTIVE'
self.bmc.cached_status = 'ACTIVE'
self.bmc.cache_status = True
self.assertTrue(self.bmc._instance_active())
self.assertFalse(self.mock_client.servers.get.called)
def test_cache_disabled(self, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
self.bmc.target_status = 'ACTIVE'
self.bmc.cached_status = 'ACTIVE'
mock_server = mock.Mock()
mock_server.status = 'SHUTOFF'
self.mock_client.servers.get.return_value = mock_server
self.assertFalse(self.bmc._instance_active())
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_get_power_state(self, mock_active, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = True
self.assertTrue(self.bmc.get_power_state())
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_power_off(self, mock_active, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = True
self.bmc.power_off()
self.mock_client.servers.stop.assert_called_once_with('abc-123')
self.assertEqual('SHUTOFF', self.bmc.target_status)
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_power_off_conflict(self, mock_active, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = True
self.mock_client.servers.stop.side_effect = exceptions.Conflict('a')
self.bmc.power_off()
self.mock_client.servers.stop.assert_called_once_with('abc-123')
mock_log.assert_called_once_with('Ignoring exception: '
'"Conflict (HTTP a)"')
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_power_off_already_off(self, mock_active, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = False
val = self.bmc.power_off()
self.assertIsNone(val)
mock_log.assert_called_once_with('abc-123 is already off.')
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_power_on(self, mock_active, mock_nova, mock_log, mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = False
self.bmc.power_on()
self.mock_client.servers.start.assert_called_once_with('abc-123')
self.assertEqual('ACTIVE', self.bmc.target_status)
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_power_on_conflict(self, mock_active, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = False
self.mock_client.servers.start.side_effect = exceptions.Conflict('a')
self.bmc.power_on()
self.mock_client.servers.start.assert_called_once_with('abc-123')
mock_log.assert_called_once_with('Ignoring exception: '
'"Conflict (HTTP a)"')
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc.'
'_instance_active')
def test_power_on_already_on(self, mock_active, mock_nova, mock_log,
mock_init):
self._create_bmc(mock_nova)
mock_active.return_value = True
val = self.bmc.power_on()
self.assertIsNone(val)
mock_log.assert_called_once_with('abc-123 is already on.')
class TestMain(unittest.TestCase):
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc')
def test_main(self, mock_bmc):
mock_instance = mock.Mock()
mock_bmc.return_value = mock_instance
mock_argv = ['openstackbmc', '--port', '111', '--address', '1.2.3.4',
'--instance', 'foobar', '--os-cloud', 'foo']
with mock.patch.object(sys, 'argv', mock_argv):
openstackbmc.main()
mock_bmc.assert_called_once_with({'admin': '<PASSWORD>'},
port=111,
address='::ffff:1.2.3.4',
instance='foobar',
cache_status=False,
os_cloud='foo'
)
mock_instance.listen.assert_called_once_with()
@mock.patch('openstack_virtual_baremetal.openstackbmc.OpenStackBmc')
def test_main_default_addr(self, mock_bmc):
mock_instance = mock.Mock()
mock_bmc.return_value = mock_instance
mock_argv = ['openstackbmc', '--port', '111',
'--instance', 'foobar', '--os-cloud', 'bar']
with mock.patch.object(sys, 'argv', mock_argv):
openstackbmc.main()
mock_bmc.assert_called_once_with({'admin': '<PASSWORD>'},
port=111,
address='::',
instance='foobar',
cache_status=False,
os_cloud='bar'
)
mock_instance.listen.assert_called_once_with()
<file_sep>/doc/source/deploy/baremetal.rst
Deploying a Standalone Baremetal Stack
======================================
The process described here will create a very minimal OVB environment, and the
user will be responsible for creating most of the resources manually. In most
cases it will be easier to use the :doc:`QuintupleO <quintupleo>` deployment
method, which creates most of the resources needed automatically.
#. Create private network.
If your cloud provider has already created a private network for your use
then you can skip this step and reference the existing network in your
OVB environment file.
::
neutron net-create private
neutron subnet-create --name private private 10.0.1.0/24 --dns-nameserver 8.8.8.8
You will also need to create a router so traffic from your private network
can get to the external network. The external network should have been
created by the cloud provider::
neutron router-create router
neutron router-gateway-set router [external network name or id]
neutron router-interface-add router private
#. Create provisioning network.
.. note:: The CIDR used for the subnet does not matter.
Standard tenant and external networks are also needed to
provide floating ip access to the undercloud and bmc instances
.. warning:: Do not enable DHCP on this network. Addresses will be
assigned by the undercloud Neutron.
::
neutron net-create provision
neutron subnet-create --name provision --no-gateway --disable-dhcp provision 192.168.24.0/24
#. Create "public" network.
.. note:: The CIDR used for the subnet does not matter.
This can be used as the network for the public API endpoints
on the overcloud, but it does not have to be accessible
externally. Only the undercloud VM will need to have access
to this network.
.. warning:: Do not enable DHCP on this network. Doing so may cause
conflicts between the host cloud metadata service and the
undercloud metadata service. Overcloud nodes will be
assigned addresses on this network by the undercloud Neutron.
::
neutron net-create public
neutron subnet-create --name public --no-gateway --disable-dhcp public 10.0.0.0/24
#. Copy the example env file and edit it to reflect the host environment:
.. note:: Some of the parameters in the base environment file are only
used for QuintupleO deployments. Their values will be ignored
in a plain virtual-baremetal deployment.
::
cp environments/base.yaml env.yaml
vi env.yaml
#. Deploy the stack::
bin/deploy.py
#. Wait for Heat stack to complete:
.. note:: The BMC instance does post-deployment configuration that can
take a while to complete, so the Heat stack completing does
not necessarily mean the environment is entirely ready for
use. To determine whether the BMC is finished starting up,
run ``nova console-log bmc``. The BMC service outputs a
message like "Managing instance [uuid]" when it is fully
configured. There should be one of these messages for each
baremetal instance.
::
heat stack-show baremetal
#. Boot a VM to serve as the undercloud::
nova boot undercloud --flavor m1.xlarge --image centos7 --nic net-id=[tenant net uuid] --nic net-id=[provisioning net uuid]
neutron floatingip-create [external net uuid]
neutron port-list
neutron floatingip-associate [floatingip uuid] [undercloud instance port id]
#. Turn off port-security on the undercloud provisioning port::
neutron port-update [UUID of undercloud port on the provision network] --no-security-groups --port-security-enabled=False
#. Build a nodes.json file that can be imported into Ironic::
bin/build-nodes-json
scp nodes.json centos@[undercloud floating ip]:~/instackenv.json
.. note:: ``build-nodes-json`` also outputs a file named ``bmc_bm_pairs``
that lists which BMC address corresponds to a given baremetal
instance.
#. The undercloud vm can now be used with something like TripleO
to do a baremetal-style deployment to the virtual baremetal instances
deployed previously.
Deleting an OVB Environment
---------------------------
All of the OpenStack resources created by OVB are part of the Heat stack, so
to delete the environment just delete the Heat stack. There are a few local
files that may also have been created as part of the deployment, such as
nodes.json files and bmc_bm_pairs. Once the stack is deleted these can be
removed safely as well.
<file_sep>/doc/source/host-cloud/configuration.rst
Configuring the Host Cloud
==========================
Some of the configuration recommended below is optional, but applying
all of it will provide the optimal experience.
The changes described in this document apply to compute nodes in the
host cloud.
#. The Nova option ``force_config_drive`` must _not_ be set. If you have to
change this option, restart ``nova-compute`` to apply it.
#. Ideally, jumbo frames should be enabled on the host cloud. This
avoids MTU problems when deploying to instances over tunneled
Neutron networks with VXLAN or GRE.
For TripleO-based host clouds, this can be done by setting ``mtu``
on all interfaces and vlans in the network isolation nic-configs.
A value of at least 1550 should be sufficient to avoid problems.
If this cannot be done (perhaps because you don't have access to make
such a change on the host cloud), it will likely be necessary to
configure a smaller MTU on the deployed virtual instances. Details
on doing so can be found on the :doc:`../usage/usage` page.
<file_sep>/doc/source/deploy/deploy.rst
Deploying the Heat stack
========================
There are two options for deploying the Heat stack.
.. toctree::
quintupleo
baremetal
heterogeneous
environment-index
<file_sep>/ipxe/elements/ipxe-boot-image/README.rst
===============
ipxe-boot-image
===============
Builds an image which contains *only* a grub2 based boot configured to run a
custom built ipxe.lkrn image.
While this element depends on centos7, all remnants of the OS are removed apart
from the /boot grub configuration and modules.
Optional parameters:
* IPXE_GIT_REF a git reference to checkout from the iPXE git repository before
building the iPXE image. If not specified then current master will be built.
<file_sep>/bin/ovb-instack
#!/bin/bash
function timer
{
name=${1:-}
seconds=$(date +%s)
if [ -n "$name" ]
then
echo "${name}: $((seconds - start_time))" >> ~/timer-results
else
start_time=$seconds
fi
}
set -ex
timer
# When not running my local cloud we don't want these set
if [ ${LOCAL:-1} -eq 1 ]
then
export http_proxy=http://roxy:3128
curl -O http://openstack/CentOS-7-x86_64-GenericCloud-1802.qcow2
export DIB_LOCAL_IMAGE=CentOS-7-x86_64-GenericCloud-1802.qcow2
export DIB_DISTRIBUTION_MIRROR=http://mirror.centos.org/centos
export no_proxy=192.168.24.1,192.168.24.2,192.168.24.3
fi
# Set up the undercloud in preparation for running the deployment
sudo yum install -y git wget
rm -rf git-tripleo-ci
git clone https://git.openstack.org/openstack-infra/tripleo-ci git-tripleo-ci
echo '#!/bin/bash' > tripleo.sh
echo 'git-tripleo-ci/scripts/tripleo.sh $@' >> tripleo.sh
chmod +x tripleo.sh
if [ ! -d overcloud-templates ]
then
git clone https://github.com/cybertron/openstack-virtual-baremetal
cp -r openstack-virtual-baremetal/overcloud-templates .
fi
export OVERCLOUD_PINGTEST_OLD_HEATCLIENT=0
export TRIPLEOSH=/home/centos/tripleo.sh
# Do the tripleo deployment
# Repo setup
wget -r --no-parent -nd -e robots=off -l 1 -A 'python2-tripleo-repos-*' https://trunk.rdoproject.org/centos7/current/
sudo yum install -y python2-tripleo-repos-*
sudo tripleo-repos current-tripleo-dev --rdo-mirror http://mirror.regionone.rdo-cloud.rdoproject.org:8080/rdo --centos-mirror http://mirror.regionone.rdo-cloud.rdoproject.org
timer 'system setup'
timer
# Undercloud install
cat << EOF > undercloud.conf
[DEFAULT]
undercloud_hostname=undercloud.localdomain
enable_telemetry = false
enable_legacy_ceilometer_api = false
enable_ui = false
enable_validations = false
enable_tempest = false
local_mtu = 1450
[ctlplane-subnet]
masquerade = true
EOF
sudo yum install -y python-tripleoclient
openstack undercloud install
. stackrc
# Undercloud networking
cat >> /tmp/eth2.cfg <<EOF_CAT
network_config:
- type: interface
name: eth2
use_dhcp: false
mtu: 1450
addresses:
- ip_netmask: 10.0.0.1/24
- ip_netmask: 2001:db8:fd00:1000::1/64
EOF_CAT
sudo os-net-config -c /tmp/eth2.cfg -v
sudo iptables -A POSTROUTING -s 10.0.0.0/24 ! -d 10.0.0.0/24 -j MASQUERADE -t nat
sudo iptables -I FORWARD -s 10.0.0.0/24 -j ACCEPT
sudo iptables -I FORWARD -d 10.0.0.0/24 -j ACCEPT
timer 'undercloud install'
timer
# Image creation
export DIB_YUM_REPO_CONF="/etc/yum.repos.d/delorean*"
openstack overcloud image build
openstack overcloud image upload --update-existing
timer 'image build'
timer
# Node registration and introspection
openstack overcloud node import --introspect --provide instackenv.json
timer 'node introspection'
sleep 60
timer
# Overcloud deploy
export OVERCLOUD_DEPLOY_ARGS="--libvirt-type qemu -e /usr/share/openstack-tripleo-heat-templates/environments/disable-telemetry.yaml"
if [ ${VERSION:-1} -eq 2 ]
then
OVERCLOUD_DEPLOY_ARGS="$OVERCLOUD_DEPLOY_ARGS -e /home/centos/overcloud-templates/network-templates-v2/network-isolation-absolute.yaml -e /home/centos/overcloud-templates/network-templates-v2/network-environment.yaml"
fi
openstack overcloud deploy --templates $OVERCLOUD_DEPLOY_ARGS
timer 'overcloud deploy'
timer
# Overcloud validation
if [ ${VERSION:-1} -eq 2 ]
then
export FLOATING_IP_CIDR=10.0.0.0/24
export FLOATING_IP_START=10.0.0.50
export FLOATING_IP_END=10.0.0.70
export EXTERNAL_NETWORK_GATEWAY=10.0.0.1
fi
$TRIPLEOSH --overcloud-pingtest --skip-pingtest-cleanup
timer 'ping test'
cat ~/timer-results
<file_sep>/ipxe/Makefile
# git ref to checkout from the iPXE git repository
IPXE_GIT_REF=6366fa7a
ipxe-boot.qcow2:
ELEMENTS_PATH=./elements IPXE_GIT_REF=$(IPXE_GIT_REF) disk-image-create -x -o ipxe-boot ipxe-boot-image
clean:
rm -f ipxe-boot.qcow2
<file_sep>/doc/source/api.rst
Python API
==========
build_nodes_json
----------------
.. automodule:: build_nodes_json
:members:
:private-members:
deploy
------
.. automodule:: deploy
:members:
:private-members:
openstackbmc
------------
.. autoclass:: openstackbmc.OpenStackBmc
:members:
auth
------
.. automodule:: auth
:members:
:private-members:
<file_sep>/README.rst
DEPRECATED - OpenStack Virtual Baremetal
========================================
**IMPORTANT:** This repository is deprecated. The new location for OVB is
`<https://git.openstack.org/cgit/openstack/openstack-virtual-baremetal>`_
OpenStack Virtual Baremetal is a way to use OpenStack instances to do
simulated baremetal deployments. For more details, see the `full
documentation
<http://openstack-virtual-baremetal.readthedocs.io/en/latest/index.html>`_.
<file_sep>/doc/source/host-cloud/setup.rst
Host Cloud Setup
================
Instructions for setting up the host cloud[1].
1: The host cloud is any OpenStack cloud providing the necessary functionality
to run OVB. The host cloud must be running on real baremetal.
.. toctree::
patches
configuration
prepare
<file_sep>/doc/source/host-cloud/prepare.rst
Preparing the Host Cloud Environment
====================================
#. Source an rc file that will provide admin credentials for the host cloud.
#. Upload an ipxe-boot image for the baremetal instances::
glance image-create --name ipxe-boot --disk-format qcow2 --property os_shutdown_timeout=5 --container-format bare < ipxe/ipxe-boot.qcow2
.. note:: The path provided to ipxe-boot.qcow2 is relative to the root of
the OVB repo. If the command is run from a different working
directory, the path will need to be adjusted accordingly.
.. note:: os_shutdown_timeout=5 is to avoid server shutdown delays since
since these servers won't respond to graceful shutdown requests.
.. note:: On a UEFI enabled openstack cloud, to boot the baremetal instances
with uefi (instead of the default bios firmware) the image should
be created with the parameters --property="hw_firmware_type=uefi".
#. Upload a CentOS 7 image for use as the base image::
wget http://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2
glance image-create --name CentOS-7-x86_64-GenericCloud --disk-format qcow2 --container-format bare < CentOS-7-x86_64-GenericCloud.qcow2
#. (Optional) Create a pre-populated base BMC image. This is a CentOS 7 image
with the required packages for the BMC pre-installed. This eliminates one
potential point of failure during the deployment of an OVB environment
because the BMC will not require any external network resources::
wget https://repos.fedorapeople.org/repos/openstack-m/ovb/bmc-base.qcow2
glance image-create --name bmc-base --disk-format qcow2 --container-format bare < bmc-base.qcow2
To use this image, configure ``bmc_image`` in env.yaml to be ``bmc-base`` instead
of the generic CentOS 7 image.
#. Create recommended flavors::
nova flavor-create baremetal auto 8192 50 2
nova flavor-create bmc auto 512 20 1
These flavors can be customized if desired. For large environments
with many baremetal instances it may be wise to give the bmc flavor
more memory. A 512 MB BMC will run out of memory around 20 baremetal
instances.
#. Source an rc file that will provide user credentials for the host cloud.
#. Add a Nova keypair to be injected into instances::
nova keypair-add --pub-key ~/.ssh/id_rsa.pub default
#. (Optional) Configure quotas. When running in a dedicated OVB cloud, it may
be helpful to set some quotas to very large/unlimited values to avoid
running out of quota when deploying multiple or large environments::
neutron quota-update --security_group 1000
neutron quota-update --port -1
neutron quota-update --network -1
neutron quota-update --subnet -1
nova quota-update --instances -1 --cores -1 --ram -1 [tenant uuid]
<file_sep>/doc/source/index.rst
OpenStack Virtual Baremetal
===========================
OpenStack Virtual Baremetal is a tool for using OpenStack instances to test
baremetal-style deployments.
Table of Contents
-----------------
.. toctree::
:maxdepth: 2
introduction
host-cloud/setup
deploy/deploy
usage/usage
troubleshooting
api
Search
------
* :ref:`search`
Index
-----
* :ref:`genindex`
* :ref:`modindex`
<file_sep>/templates/overcloud-env/README.rst
Deploying an Overcloud for Virtual Baremetal
============================================
The files in this directory can be used to deploy an overcloud
using TripleO that is suitable for use as a virtual
baremetal host. The following are instructions on how to do so.
Custom Environment
------------------
.. note::
This template applies a patch to Nova that may not be suitable
for production deployments. Use at your own risk.
Copy the yaml files to the undercloud so they can be referenced by
the overcloud deploy call. The ``ovb.yaml`` file must be passed
as an additional ``-e`` parameter. See `Overcloud Deployment`_ for
an example deploy call.
Hieradata Changes
-----------------
Make a copy of the tripleo-heat-templates directory::
cp -r /usr/share/openstack-tripleo-heat-templates/ custom
Add the necessary hieradata configuration::
echo "neutron::agents::ml2::ovs::firewall_driver: neutron.agent.firewall.NoopFirewallDriver" >> custom/puppet/hieradata/common.yaml
Overcloud Deployment
--------------------
Pass both the custom environment and templates to the deploy call::
openstack overcloud deploy --libvirt-type kvm --templates custom -e ovb.yaml
<file_sep>/bin/load-test
#!/bin/bash
set -ex
JOBS=${1:-1}
DELAY=${2:-60}
BIN_DIR=$(cd $(dirname $0); pwd -P)
for i in $(seq $JOBS)
do
jobid=$(uuidgen | md5sum)
jobid=${jobid:1:8}
date
echo "Starting job $jobid, logging to /tmp/$jobid.log"
$BIN_DIR/test-job $jobid > /tmp/$jobid.log 2>&1 &
sleep $DELAY
done
<file_sep>/doc/source/deploy/environment-index.rst
Sample Environment Index
========================
Deploy with All Networks Enabled and Two Public Interfaces
----------------------------------------------------------
**File:** environments/all-networks-public-bond.yaml
**Description:** Deploy an OVB stack that adds interfaces for all the standard TripleO
network isolation networks. This version will deploy duplicate
public network interfaces on the baremetal instances so that the
public network can be configured as a bond.
Deploy with All Networks Enabled
--------------------------------
**File:** environments/all-networks.yaml
**Description:** Deploy an OVB stack that adds interfaces for all the standard TripleO
network isolation networks.
Base Configuration Options for Extra Nodes
------------------------------------------
**File:** environments/base-extra-node.yaml
**Description:** Configuration options that need to be set when deploying an OVB
environment with extra undercloud-like nodes. This environment
should be used like a role file, but will deploy an undercloud-like
node instead of more baremetal nodes.
Base Configuration Options for Secondary Roles
----------------------------------------------
**File:** environments/base-role.yaml
**Description:** Configuration options that need to be set when deploying an OVB
environment that has multiple roles.
Base Configuration Options
--------------------------
**File:** environments/base.yaml
**Description:** Basic configuration options needed for all OVB environments
Enable Instance Status Caching in BMC
-------------------------------------
**File:** environments/bmc-use-cache.yaml
**Description:** Enable caching of instance status in the BMC. This should reduce load on
the host cloud, but at the cost of potential inconsistency if the state
of a baremetal instance is changed without using the BMC.
Boot Baremetal Instances from Volume
------------------------------------
**File:** environments/boot-baremetal-from-volume.yaml
**Description:** Boot the baremetal instances from Cinder volumes instead of
ephemeral storage.
Boot Undercloud and Baremetal Instances from Volume
---------------------------------------------------
**File:** environments/boot-from-volume.yaml
**Description:** Boot the undercloud and baremetal instances from Cinder volumes instead of
ephemeral storage.
Boot Undercloud Instance from Volume
------------------------------------
**File:** environments/boot-undercloud-from-volume.yaml
**Description:** Boot the undercloud instance from a Cinder volume instead of
ephemeral storage.
Create a Private Network
------------------------
**File:** environments/create-private-network.yaml
**Description:** Create the private network as part of the OVB stack instead of using an
existing one.
Public Network External Router
------------------------------
**File:** environments/public-router.yaml
**Description:** Deploy a router that connects the public and external networks. This
allows the public network to be used as a gateway instead of routing all
traffic through the undercloud.
Disable the Undercloud in a QuintupleO Stack
--------------------------------------------
**File:** environments/quintupleo-no-undercloud.yaml
**Description:** Deploy a QuintupleO environment, but do not create the undercloud
instance.
Configuration for Routed Networks
---------------------------------
**File:** environments/routed-networks-configuration.yaml
**Description:** Contains the available parameters that need to be configured when using
a routed networks environment. Requires the routed-networks.yaml
environment.
Base Role Configuration for Routed Networks
-------------------------------------------
**File:** environments/routed-networks-role.yaml
**Description:** A base role environment that contains the necessary parameters for
deploying with routed networks.
Enable Routed Networks
----------------------
**File:** environments/routed-networks.yaml
**Description:** Enable use of routed networks, where there may be multiple separate
networks connected with a router and DHCP relay. Do not pass any other
network configuration environments after this one or they may override
the changes made by this environment. When this environment is in use,
the routed-networks-configuration environment should usually be
included as well.
Assign the Undercloud an Existing Floating IP
---------------------------------------------
**File:** environments/undercloud-floating-existing.yaml
**Description:** When deploying the undercloud, assign it an existing floating IP instead
of creating a new one.
Do Not Assign a Floating IP to the Undercloud
---------------------------------------------
**File:** environments/undercloud-floating-none.yaml
**Description:** When deploying the undercloud, do not assign a floating ip to it.
<file_sep>/ipxe/elements/ipxe-boot-image/install.d/50-grub2-boot-ipxe
#!/bin/bash
# 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.
if [ ${DIB_DEBUG_TRACE:-1} -gt 0 ]; then
set -x
fi
set -eu
set -o pipefail
SCRIPTDIR=$(dirname $0)
cd /root
git clone git://git.ipxe.org/ipxe.git
cd ipxe/src
if [ -n "${IPXE_GIT_REF:-}" ]; then
git checkout ${IPXE_GIT_REF}
fi
IPXE_GIT_REF_CURRENT=$(git rev-parse --short HEAD)
make bin/ipxe.lkrn
cp bin/ipxe.lkrn /boot/
cat << EOF >>/etc/grub.d/40_custom
menuentry "iPXE boot ${IPXE_GIT_REF_CURRENT}" {
linux16 /boot/ipxe.lkrn
}
EOF
if [ -s /etc/default/grub ]; then
sed -i -e 's/^GRUB_TIMEOUT.*/GRUB_TIMEOUT=5/' /etc/default/grub
sed -i -e 's/^GRUB_DEFAULT.*/GRUB_DEFAULT="iPXE boot"/' /etc/default/grub
fi
# remove all unneeded /boot files
rm -f /boot/vmlinuz*
rm -f /boot/initramfs*
rm -f /boot/initrd.*
rm -f /boot/System.map*
rm -f /boot/config-*
rm -f /boot/symvers-*
rm -rf /boot/grub2/locale
<file_sep>/doc/source/usage/usage.rst
Using a Deployed OVB Environment
================================
After an OVB environment has been deployed, there are a few things to know.
#. The undercloud vm can be used with something like TripleO
to do a baremetal-style deployment to the virtual baremetal instances
deployed previously.
#. To reset the environment, usually it is sufficient to do a ``nova rebuild``
on the undercloud to return it to the original image. To ensure that
no traces of the old environment remain, the baremetal vms can be rebuilt
to the ipxe-boot image as well.
.. note:: If you are relying on the ipxe-boot image to provide PXE boot
support in your cloud because Nova does not know how to PXE boot
natively, the baremetal instances must always be rebuilt before
subsequent deployments.
.. note:: **Do not** rebuild the bmc. It is unnecessary and not guaranteed
to work.
#. If the host cloud's tenant network MTU is 1500 or less, it will be necessary
to configure the deployed interfaces with a smaller MTU. The tenant network
MTU minus 50 is usually a safe value. For the undercloud this can be done
by setting ``local_mtu`` in ``undercloud.conf``.
.. note::
In Mitaka and older versions of TripleO it will be necessary to do the
MTU configuration manually. That can be done with the following
commands (as root)::
# Replace 'eth1' with the actual device to be used for the
# provisioning network
ip link set eth1 mtu 1350
echo -e "\ndhcp-option-force=26,1350" >> /etc/dnsmasq-ironic.conf
systemctl restart 'neutron-*'
#. If using the full network isolation provided by one of the
``all-networks*.yaml`` environments then a TripleO overcloud can be deployed
in the OVB environment by using the network templates in the
``overcloud-templates`` directory. The names are fairly descriptive, but
this is a brief explanation of each:
- **network-templates:** IPv4 multi-nic. Usable with the network layout
deployed by the ``all-networks.yaml`` environment.
- **ipv6-network-templates:** IPv6 multi-nic. Usable with the network layout
deployed by the ``all-networks.yaml`` environment.
- **bond-network-templates:** IPv4 multi-nic, with duplicate `public`
interfaces for testing bonded nics. Usable with the network layout
deployed by the ``all-networks-public-bond.yaml`` environment.
The undercloud's ``public`` interface should be configured with the address
of the default route from the templates in use. Firewall rules for
forwarding the traffic from that interface should also be added. The
following commands will make the necessary configuration::
cat >> /tmp/eth2.cfg <<EOF_CAT
network_config:
- type: interface
name: eth2
use_dhcp: false
addresses:
- ip_netmask: 10.0.0.1/24
- ip_netmask: 2001:db8:fd00:1000::1/64
EOF_CAT
sudo os-net-config -c /tmp/eth2.cfg -v
sudo iptables -A POSTROUTING -s 10.0.0.0/24 ! -d 10.0.0.0/24 -j MASQUERADE -t nat
<file_sep>/openstack_virtual_baremetal/tests/test_build_nodes_json.py
# Copyright 2016 Red Hat Inc.
#
# 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.
import copy
import json
import sys
import fixtures
import mock
import testtools
from openstack_virtual_baremetal import build_nodes_json
TEST_NODES = [{'arch': 'x86_64',
'capabilities': 'boot_option:local',
'cpu': 128,
'disk': 1024,
'mac': ['aa:aa:aa:aa:aa:aa'],
'memory': 145055,
'name': 'bm-0',
'pm_addr': '1.1.1.1',
'pm_password': '<PASSWORD>',
'pm_type': 'pxe_ipmitool',
'pm_user': 'admin'},
{'arch': 'x86_64',
'capabilities': 'boot_option:local',
'cpu': 128,
'disk': 1024,
'mac': ['aa:aa:aa:aa:aa:ab'],
'memory': 145055,
'name': 'bm-1',
'pm_addr': '1.1.1.2',
'pm_password': '<PASSWORD>',
'pm_type': 'pxe_ipmitool',
'pm_user': 'admin'}]
class TestBuildNodesJson(testtools.TestCase):
def test_parse_args(self):
mock_argv = ['build-nodes-json', '--env', 'foo.yaml', '--bmc_prefix',
'bmc-foo', '--baremetal_prefix', 'baremetal-foo',
'--provision_net', 'provision-foo', '--nodes_json',
'nodes-foo.json', '--driver', 'ipmi',
'--physical_network',
]
with mock.patch.object(sys, 'argv', mock_argv):
args = build_nodes_json._parse_args()
self.assertEqual('foo.yaml', args.env)
self.assertEqual('bmc-foo', args.bmc_prefix)
self.assertEqual('baremetal-foo', args.baremetal_prefix)
self.assertEqual('provision-foo', args.provision_net)
self.assertEqual('nodes-foo.json', args.nodes_json)
self.assertEqual('ipmi', args.driver)
self.assertTrue(args.physical_network)
def test_get_names_no_env(self):
args = mock.Mock()
args.env = None
args.bmc_prefix = 'bmc-foo'
args.baremetal_prefix = 'baremetal-foo'
args.add_undercloud = False
bmc_base, baremetal_base, undercloud_name = (
build_nodes_json._get_names(args))
self.assertEqual('bmc-foo', bmc_base)
self.assertEqual('baremetal-foo', baremetal_base)
self.assertEqual('undercloud', undercloud_name)
def test_get_names_no_env_w_undercloud(self):
args = mock.Mock()
args.env = None
args.bmc_prefix = 'bmc-foo'
args.baremetal_prefix = 'baremetal-foo'
args.add_undercloud = True
bmc_base, baremetal_base, undercloud_name = (
build_nodes_json._get_names(args))
self.assertEqual('bmc-foo', bmc_base)
self.assertEqual('baremetal-foo', baremetal_base)
self.assertEqual('undercloud', undercloud_name)
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
@mock.patch('yaml.safe_load')
def test_get_names_env(self, mock_load, mock_open):
args = mock.Mock()
args.env = 'foo.yaml'
args.add_undercloud = False
mock_env = {
'parameter_defaults': {
'bmc_prefix': 'bmc-foo',
'baremetal_prefix': 'baremetal-foo',
},
}
mock_load.return_value = mock_env
bmc_base, baremetal_base, undercloud_name = (
build_nodes_json._get_names(args))
self.assertEqual('bmc-foo', bmc_base)
self.assertEqual('baremetal-foo', baremetal_base)
self.assertIsNone(undercloud_name)
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
@mock.patch('yaml.safe_load')
def test_get_names_env_no_role(self, mock_load, mock_open):
args = mock.Mock()
args.env = 'foo.yaml'
args.add_undercloud = False
mock_env = {
'parameter_defaults': {
'bmc_prefix': 'bmc',
'baremetal_prefix': 'baremetal',
'role': 'foo',
},
}
mock_load.return_value = mock_env
bmc_base, baremetal_base, undercloud_name = (
build_nodes_json._get_names(args))
self.assertEqual('bmc', bmc_base)
self.assertEqual('baremetal', baremetal_base)
self.assertIsNone(undercloud_name)
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
@mock.patch('yaml.safe_load')
def test_get_names_env_strip_role(self, mock_load, mock_open):
args = mock.Mock()
args.env = 'foo.yaml'
args.add_undercloud = False
mock_env = {
'parameter_defaults': {
'bmc_prefix': 'bmc-foo',
'baremetal_prefix': 'baremetal-foo-bar',
'role': 'bar',
},
}
mock_load.return_value = mock_env
bmc_base, baremetal_base, undercloud_name = (
build_nodes_json._get_names(args))
self.assertEqual('bmc-foo', bmc_base)
self.assertEqual('baremetal-foo', baremetal_base)
self.assertIsNone(undercloud_name)
@mock.patch('os_client_config.make_client')
def test_get_clients_os_cloud(self, mock_make_client):
self.useFixture(fixtures.EnvironmentVariable('OS_CLOUD', 'foo'))
build_nodes_json._get_clients()
calls = [mock.call('compute', cloud='foo'),
mock.call('network', cloud='foo'),
mock.call('image', cloud='foo')]
self.assertEqual(calls, mock_make_client.mock_calls)
@mock.patch('os_client_config.make_client')
def test_get_clients_os_cloud_unset(self, mock_make_client):
self.useFixture(fixtures.EnvironmentVariable('OS_CLOUD', None))
build_nodes_json._get_clients()
calls = [mock.call('compute', cloud=None),
mock.call('network', cloud=None),
mock.call('image', cloud=None)]
self.assertEqual(calls, mock_make_client.mock_calls)
def test_get_ports(self):
neutron = mock.Mock()
fake_fixed_ips = [{'subnet_id': 'provision_id'}]
fake_ports = {
'ports': [
{'name': 'random',
'id': 'random_id',
'fixed_ips': fake_fixed_ips},
{'name': 'bmc_1',
'id': 'bmc_1_id',
'fixed_ips': fake_fixed_ips},
{'name': 'bmc_0',
'id': 'bmc_0_id',
'fixed_ips': fake_fixed_ips},
{'name': 'baremetal_1',
'id': 'baremetal_1_id',
'fixed_ips': fake_fixed_ips},
{'name': 'baremetal_0',
'id': 'baremetal_0_id',
'fixed_ips': fake_fixed_ips},
]
}
fake_subnets = {
'subnets': [
{'name': 'provision',
'id': 'provision_id'}
]
}
neutron.list_ports.return_value = fake_ports
neutron.list_subnets.return_value = fake_subnets
bmc_ports, bm_ports, provision_net_map = build_nodes_json._get_ports(
neutron, 'bmc', 'baremetal')
self.assertEqual([fake_ports['ports'][2], fake_ports['ports'][1]],
bmc_ports)
self.assertEqual([fake_ports['ports'][4], fake_ports['ports'][3]],
bm_ports)
self.assertEqual({'baremetal_0_id': 'provision',
'baremetal_1_id': 'provision'}, provision_net_map)
def test_get_ports_mismatch(self):
neutron = mock.Mock()
fake_ports = {'ports': [{'name': 'bmc_0'}]}
neutron.list_ports.return_value = fake_ports
self.assertRaises(RuntimeError, build_nodes_json._get_ports, neutron,
'bmc', 'baremetal')
def test_get_ports_multiple(self):
neutron = mock.Mock()
fake_fixed_ips = [{'subnet_id': 'provision_id'}]
fake_ports = {
'ports': [
{'name': 'random',
'id': 'random_id',
'fixed_ips': fake_fixed_ips},
{'name': 'bmc-foo_0',
'id': 'bmc_foo_0_id',
'fixed_ips': fake_fixed_ips},
{'name': 'bmc-bar_0',
'id': 'bmc_bar_0_id',
'fixed_ips': fake_fixed_ips},
{'name': 'baremetal-foo_0',
'id': 'baremetal_foo_0_id',
'fixed_ips': fake_fixed_ips},
{'name': 'baremetal-bar_0',
'id': 'baremetal_bar_0_id',
'fixed_ips': fake_fixed_ips},
]
}
fake_subnets = {
'subnets': [
{'name': 'provision',
'id': 'provision_id'}
]
}
neutron.list_ports.return_value = fake_ports
neutron.list_subnets.return_value = fake_subnets
bmc_ports, bm_ports, provision_net_map = build_nodes_json._get_ports(
neutron, 'bmc-foo', 'baremetal-foo')
self.assertEqual([fake_ports['ports'][1]], bmc_ports)
self.assertEqual([fake_ports['ports'][3]], bm_ports)
def _fake_port(self, device_id, ip, mac):
return {'device_id': device_id,
'fixed_ips': [{'ip_address': ip}],
}
def _create_build_nodes_mocks(self, nova, servers):
nova.servers.get.side_effect = servers
servers[0].name = 'bm_0'
servers[0].flavor = {'id': '1'}
servers[0].addresses = {'provision': [{'OS-EXT-IPS-MAC:mac_addr':
'aa:aa:aa:aa:aa:aa',
'addr': '172.16.17.32'}]}
servers[0].image = {'id': 'f00'}
servers[0].id = '123abc'
servers[1].name = 'bm_1'
servers[1].flavor = {'id': '1'}
servers[1].addresses = {'provision': [{'OS-EXT-IPS-MAC:mac_addr':
'aa:aa:aa:aa:aa:ab',
'addr': '192.168.3.11'}]}
servers[1].image = {'id': 'f00'}
servers[1].id = '456def'
mock_flavor = mock.Mock()
mock_flavor.vcpus = 128
mock_flavor.ram = 145055
mock_flavor.disk = 1024
nova.flavors.get.return_value = mock_flavor
@mock.patch('os_client_config.make_client')
def test_build_nodes(self, mock_make_client):
bmc_ports = [{'fixed_ips': [{'ip_address': '1.1.1.1'}]},
{'fixed_ips': [{'ip_address': '192.168.127.12'}]}
]
bm_ports = [{'device_id': '1', 'id': 'port_id_server1'},
{'device_id': '2', 'id': 'port_id_server2'}]
provision_net_map = {'port_id_server1': 'provision',
'port_id_server2': 'provision',
'port_id_server3': 'provision', }
physical_network = False
nova = mock.Mock()
servers = [mock.Mock(), mock.Mock(), mock.Mock()]
self._create_build_nodes_mocks(nova, servers)
servers[1].image = None
mock_to_dict = {'os-extended-volumes:volumes_attached':
[{'id': 'v0lume'}]}
servers[1].to_dict.return_value = mock_to_dict
mock_cinder = mock.Mock()
mock_make_client.return_value = mock_cinder
mock_vol = mock.Mock()
mock_vol.size = 100
mock_cinder.volumes.get.return_value = mock_vol
servers[2].name = 'undercloud'
servers[2].flavor = {'id': '1'}
servers[2].addresses = {'provision': [{'OS-EXT-IPS-MAC:mac_addr':
'aa:aa:aa:aa:aa:ac'}]}
servers[2].image = {'id': 'f00'}
nova.servers.list.return_value = [servers[2]]
ips_return_val = 'ips call value'
nova.servers.ips.return_value = ips_return_val
glance = mock.Mock()
(nodes,
extra_nodes,
network_details) = build_nodes_json._build_nodes(
nova, glance, bmc_ports, bm_ports, provision_net_map, 'bm',
'undercloud', 'pxe_ipmitool', physical_network)
expected_nodes = copy.deepcopy(TEST_NODES)
expected_nodes[1]['disk'] = 100
self.assertEqual(expected_nodes, nodes)
self.assertEqual(1, len(extra_nodes))
self.assertEqual('undercloud', extra_nodes[0]['name'])
self.assertEqual(
'172.16.17.32', network_details['bm_0']['ips']['provision'][0]['addr'])
self.assertEqual(
'192.168.3.11', network_details['bm_1']['ips']['provision'][0]['addr'])
@mock.patch('os_client_config.make_client')
def test_build_nodes_with_driver(self, mock_make_client):
bmc_ports = [{'fixed_ips': [{'ip_address': '1.1.1.1'}]},
{'fixed_ips': [{'ip_address': '192.168.127.12'}]}
]
bm_ports = [{'device_id': '1', 'id': 'port_id_server1'},
{'device_id': '2', 'id': 'port_id_server2'}]
provision_net_map = {'port_id_server1': 'provision',
'port_id_server2': 'provision',
'port_id_server3': 'provision', }
physical_network = False
nova = mock.Mock()
servers = [mock.Mock(), mock.Mock(), mock.Mock()]
self._create_build_nodes_mocks(nova, servers)
servers[1].image = None
mock_to_dict = {'os-extended-volumes:volumes_attached':
[{'id': 'v0lume'}]}
servers[1].to_dict.return_value = mock_to_dict
mock_cinder = mock.Mock()
mock_make_client.return_value = mock_cinder
mock_vol = mock.Mock()
mock_vol.size = 100
mock_cinder.volumes.get.return_value = mock_vol
servers[2].name = 'undercloud'
servers[2].flavor = {'id': '1'}
servers[2].addresses = {'provision': [{'OS-EXT-IPS-MAC:mac_addr':
'aa:aa:aa:aa:aa:ac'}]}
servers[2].image = {'id': 'f00'}
nova.servers.list.return_value = [servers[2]]
ips_return_val = 'ips call value'
nova.servers.ips.return_value = ips_return_val
glance = mock.Mock()
(nodes,
extra_nodes,
network_details) = build_nodes_json._build_nodes(
nova, glance, bmc_ports, bm_ports, provision_net_map, 'bm',
'undercloud', 'ipmi', physical_network)
expected_nodes = copy.deepcopy(TEST_NODES)
expected_nodes[1]['disk'] = 100
for node in expected_nodes:
node['pm_type'] = 'ipmi'
self.assertEqual(expected_nodes, nodes)
self.assertEqual(1, len(extra_nodes))
self.assertEqual('undercloud', extra_nodes[0]['name'])
self.assertEqual(
'172.16.17.32', network_details['bm_0']['ips']['provision'][0]['addr'])
self.assertEqual(
'192.168.3.11', network_details['bm_1']['ips']['provision'][0]['addr'])
def test_build_nodes_role_uefi(self):
bmc_ports = [{'fixed_ips': [{'ip_address': '1.1.1.1'}]},
{'fixed_ips': [{'ip_address': '192.168.127.12'}]}
]
bm_ports = [{'device_id': '1', 'id': 'port_id_server1'},
{'device_id': '2', 'id': 'port_id_server2'}]
provision_net_map = {'port_id_server1': 'provision',
'port_id_server2': 'provision',
'port_id_server3': 'provision', }
physical_network = False
nova = mock.Mock()
servers = [mock.Mock(), mock.Mock(), mock.Mock()]
self._create_build_nodes_mocks(nova, servers)
servers[0].name = 'bm-foo-control_0'
servers[1].name = 'bm-foo-control_1'
ips_return_val = 'ips call value'
nova.servers.ips.return_value = ips_return_val
glance = mock.Mock()
mock_image_get = mock.Mock()
mock_image_get.get.return_value = 'uefi'
glance.images.get.return_value = mock_image_get
nodes, extra_nodes, _ = build_nodes_json._build_nodes(
nova, glance, bmc_ports, bm_ports, provision_net_map, 'bm-foo',
None, 'pxe_ipmitool', physical_network)
expected_nodes = copy.deepcopy(TEST_NODES)
expected_nodes[0]['name'] = 'bm-foo-control-0'
expected_nodes[0]['capabilities'] = ('boot_option:local,'
'boot_mode:uefi,'
'profile:control')
expected_nodes[1]['name'] = 'bm-foo-control-1'
expected_nodes[1]['capabilities'] = ('boot_option:local,'
'boot_mode:uefi,'
'profile:control')
self.assertEqual(expected_nodes, nodes)
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
def test_write_nodes(self, mock_open):
args = mock.Mock()
mock_open.return_value = mock.MagicMock()
args.nodes_json = 'test.json'
args.network_details = False
extra_nodes = []
build_nodes_json._write_nodes(TEST_NODES, extra_nodes, {}, args)
data = json.dumps({'nodes': TEST_NODES}, indent=2)
f = mock_open.return_value.__enter__.return_value
f.write.assert_called_once_with(data)
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
def test_write_nodes_extra_node(self, mock_open):
args = mock.Mock()
mock_open.return_value = mock.MagicMock()
args.nodes_json = 'test.json'
args.network_details = True
extra_nodes = [{'foo': 'bar'}]
network_details = {'bar': 'baz'}
build_nodes_json._write_nodes(TEST_NODES, extra_nodes,
network_details, args)
data = json.dumps({'nodes': TEST_NODES,
'extra_nodes': extra_nodes,
'network_details': network_details}, indent=2)
f = mock_open.return_value.__enter__.return_value
f.write.assert_called_once_with(data)
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
def test_write_role_nodes(self, mock_open):
test_nodes = copy.deepcopy(TEST_NODES)
args = mock.Mock()
args.nodes_json = 'test.json'
build_nodes_json._write_role_nodes(test_nodes, args)
mock_open.assert_not_called()
@mock.patch('openstack_virtual_baremetal.build_nodes_json.open',
create=True)
def test_write_role_nodes_profile(self, mock_open):
test_nodes = copy.deepcopy(TEST_NODES)
test_nodes[1]['capabilities'] = ('boot_option:local,'
'boot_mode:uefi,'
'profile:extra')
args = mock.Mock()
args.nodes_json = 'test.json'
build_nodes_json._write_role_nodes(test_nodes, args)
self.assertIn(mock.call('test-no-profile.json', 'w'),
mock_open.mock_calls)
self.assertIn(mock.call('test-extra.json', 'w'),
mock_open.mock_calls)
f = mock_open.return_value.__enter__.return_value
f.write.assert_any_call(json.dumps({'nodes': [test_nodes[0]]},
indent=2))
f.write.assert_any_call(json.dumps({'nodes': [test_nodes[1]]},
indent=2))
@mock.patch('openstack_virtual_baremetal.build_nodes_json.'
'_write_role_nodes')
@mock.patch('openstack_virtual_baremetal.build_nodes_json._write_nodes')
@mock.patch('openstack_virtual_baremetal.build_nodes_json._build_nodes')
@mock.patch('openstack_virtual_baremetal.build_nodes_json._get_ports')
@mock.patch('openstack_virtual_baremetal.build_nodes_json._get_clients')
@mock.patch('openstack_virtual_baremetal.build_nodes_json._get_names')
@mock.patch('openstack_virtual_baremetal.build_nodes_json._parse_args')
def test_main(self, mock_parse_args, mock_get_names, mock_get_clients,
mock_get_ports, mock_build_nodes, mock_write_nodes,
mock_write_role_nodes):
args = mock.Mock()
mock_parse_args.return_value = args
bmc_base = mock.Mock()
baremetal_base = mock.Mock()
provision_net_map = mock.Mock()
undercloud_name = 'undercloud'
mock_get_names.return_value = (bmc_base, baremetal_base,
undercloud_name)
nova = mock.Mock()
neutron = mock.Mock()
glance = mock.Mock()
mock_get_clients.return_value = (nova, neutron, glance)
bmc_ports = mock.Mock()
bm_ports = mock.Mock()
mock_get_ports.return_value = (bmc_ports, bm_ports, provision_net_map)
nodes = mock.Mock()
extra_nodes = mock.Mock()
network_details = mock.Mock()
mock_build_nodes.return_value = (nodes, extra_nodes,
network_details)
build_nodes_json.main()
mock_parse_args.assert_called_once_with()
mock_get_names.assert_called_once_with(args)
mock_get_clients.assert_called_once_with()
mock_get_ports.assert_called_once_with(neutron, bmc_base,
baremetal_base)
mock_build_nodes.assert_called_once_with(nova, glance, bmc_ports,
bm_ports, provision_net_map,
baremetal_base,
undercloud_name,
args.driver,
args.physical_network)
mock_write_nodes.assert_called_once_with(nodes, extra_nodes,
network_details, args)
mock_write_role_nodes.assert_called_once_with(nodes, args)
<file_sep>/doc/source/deploy/quintupleo.rst
Deploying with QuintupleO
=========================
QuintupleO is short for OpenStack on OpenStack on OpenStack. It was the
original name for OVB, and has been repurposed to indicate that this
deployment method is able to deploy a full TripleO development environment
in one command. It should be useful for non-TripleO users of OVB as well,
however.
#. Copy the example env file and edit it to reflect the host environment::
cp environments/base.yaml env.yaml
vi env.yaml
#. Deploy a QuintupleO stack. The example command includes a number of
environment files intended to simplify the deployment process or make
it compatible with a broader set of host clouds. However, these
environments are not necessary in every situation and may not even work
with some older clouds. See below for details on customizing an OVB
deployment for your particular situation::
bin/deploy.py --quintupleo -e env.yaml -e environments/all-networks.yaml -e environments/create-private-network.yaml
.. note:: There is a quintupleo-specific option ``--id`` in deploy.py.
It appends the value passed in to the name of all resources
in the stack. For example, if ``undercloud_name`` is set to
'undercloud' and ``--id foo`` is passed to deploy.py, the
resulting undercloud VM will be named 'undercloud-foo'. It is
recommended that this be used any time multiple environments are
being deployed in the same cloud/tenant to avoid name collisions.
Be aware that when ``--id`` is used, a new environment file will
be generated that reflects the new names. The name of the new
file will be ``env-${id}.yaml``. This new file should be passed
to build-nodes-json instead of the original.
.. note:: See :ref:`advanced-options` for other ways to customize an OVB
deployment.
#. Wait for Heat stack to complete. To make this easier, the ``--poll``
option can be passed to ``deploy.py``.
.. note:: The BMC instance does post-deployment configuration that can
take a while to complete, so the Heat stack completing does
not necessarily mean the environment is entirely ready for
use. To determine whether the BMC is finished starting up,
run ``nova console-log bmc``. The BMC service outputs a
message like "Managing instance [uuid]" when it is fully
configured. There should be one of these messages for each
baremetal instance.
::
heat stack-show quintupleo
#. Build a nodes.json file that can be imported into Ironic::
bin/build-nodes-json
scp nodes.json centos@[undercloud floating ip]:~/instackenv.json
.. note:: Only the base environment file needs to be passed to this command.
Additional option environments that may have been passed to the
deploy command should *not* be included here.
.. note:: If ``--id`` was used to deploy the stack, make sure to pass the
generated ``env-${id}.yaml`` file to build-nodes-json using the
``--env`` parameter. Example::
bin/build-nodes-json --env env-foo.yaml
.. note:: If roles were used for the deployment, separate node files named
``nodes-<profile>.json`` will also be output that list only the
nodes for that particular profile. Nodes with no profile
specified will go in ``nodes-no-profile.json``. The base
``nodes.json`` will still contain all of the nodes in the
deployment, regardless of profile.
.. note:: ``build-nodes-json`` also outputs a file named ``bmc_bm_pairs``
that lists which BMC address corresponds to a given baremetal
instance.
Deleting an OVB Environment
---------------------------
All of the OpenStack resources created by OVB are part of the Heat stack, so
to delete the environment just delete the Heat stack. There are a few local
files that may also have been created as part of the deployment, such as
ID environment files, nodes.json files, and bmc_bm_pairs. Once the stack is
deleted these can be removed safely as well.
.. _advanced-options:
Advanced Options
----------------
There are also a number of advanced options that can be enabled for a
QuintupleO deployment. For each such option there is a sample environment
to be passed to the deploy command.
For example, to deploy all networks needed for TripleO network isolation, the
following command could be used::
bin/deploy.py --quintupleo -e env.yaml -e environments/all-networks.yaml
.. important:: When deploying with multiple environment files, ``env.yaml``
*must* be explicitly passed to the deploy command.
``deploy.py`` will only default to using ``env.yaml`` if no
environments are specified.
Some options may have additional configuration parameters. These parameters
will be listed in the environment file.
A full list of the environments available can be found at
:doc:`environment-index`.
Network Isolation
-----------------
There are a number of environments related to enabling the network isolation
functionality in OVB. These environments are named ``all-networks*.yaml``
and cause OVB to deploy additional network interfaces on the baremetal
instances that allow the use of TripleO's network isolation.
.. note:: There are templates suitable for doing a TripleO overcloud deployment
with network isolation in the ``overcloud-templates`` directory. See
the readme files in those directories for details on how to use them.
The v2 versions of the templates are suitable for use with the
TripleO Ocata release and later. The others can be used in Newton
and earlier.
Three primary networking layouts are included:
* Basic. This is the default and will only deploy a provisioning interface to
the baremetal nodes. It is not suitable for use with network isolation.
* All Networks. This will deploy an interface per isolated network to the
baremetal instances. It is suitable for use with any of the overcloud
network isolation templates not starting with 'bond'.
* All Networks, Public Bond. This will also deploy an interface per isolated
network to the baremetal instances, but it will additionally deploy a second
interface for the 'public' network that can be used to test bonding in an
OVB environment. The ``bond-*`` overcloud templates must be used with this
type of environment.
QuintupleO and routed networks
------------------------------
TripleO supports deploying OpenStack with nodes on multiple network segments
which is connected via L3 routing. OVB can set up a full development
environment with routers and DHCP-relay service. This environment is targeted
for TripleO development, however it should be useful for non-TripleO users of
OVB as well.
#. When deploying QuintupleO with routed networks environment files to enable
routed networks must be included, as well as one or more role environment
files. See :ref:`Enable Routed Networks`,
:ref:`Configuration for Routed Networks`, and
:ref:`Base Role Configuration for Routed Networks` in the
:doc:`environment-index` for details.
#. Copy the example env file and edit it to reflect the host environment::
cp environments/base.yaml env.yaml
vi env.yaml
#. Copy the ``routed-networks-configuration.yaml`` sample environment file and
edit it to reflect the host environment::
cp environments/routed-networks-configuration.yaml env-routed-networks.yaml
vi env-routed-networks.yaml
#. For each desired role, copy the ``routed-networks-role.yaml`` sample
environment file and edit it to reflect the host environment::
cp environments/routed-networks-role.yaml env-leaf1.yaml
vi env-leaf1.yaml
#. Deploy the QuintupleO routed networks environment by running the deploy.py
command. For example::
./bin/deploy.py --env env.yaml \
--quintupleo \
--env environments/all-networks.yaml \
--env environments/routed-networks.yaml \
--env env-routed-networks.yaml \
--role env-leaf1.yaml
#. When generating the ``nodes.json`` file for TripleO undercloud node import,
the environment ``env-routed.yaml`` should be specified. Also, to include
physical network attributes of the node ports in ``nodes.json`` specify the
``--physical_network`` option when running ``build-nodes-json``. For
example::
bin/build-nodes-json --physical_network
The following is an example node definition produced when using the
``--physical_network`` options. Notice that ports are defined with both
``address`` and ``physical_network`` attributes.
::
{
"pm_password": "<PASSWORD>",
"name": "baremetal-leaf1-0",
"memory": 8192,
"pm_addr": "10.0.1.13",
"ports": [
{
"physical_network": "provision2",
"address": "fa:16:3e:2f:a1:cf"
}
],
"capabilities": "boot_option:local,profile:leaf1",
"pm_type": "pxe_ipmitool",
"disk": 80,
"arch": "x86_64",
"cpu": 4,
"pm_user": "admin"
}
.. NOTE:: Due to technical debet (backward compatibility) the TripleO
Undercloud uses ``ctlplane`` as the physical network name for the
subnet that is local to the Undercloud itself. Either override
the name of the provision network in the ovb environment by
setting: ``provision_net: ctlplane`` in the
``parameters_defaults`` section or edit the generated nodes.json
file, replacing:
``"physical_network": "<name-used-for-provision_net>"`` with
``"physical_network": "ctlplane"``.
#. For convenience router addresses are made available via the
``network_environment_data`` key in the stack output of the quintupleo heat
stack. To retrieve this data run the ``openstack stack show`` command. For
example::
$ openstack stack show quintupleo -c outputs -f yaml
outputs:
- description: floating ip of the undercloud instance
output_key: undercloud_host_floating_ip
output_value: 192.168.127.12
- description: Network environment data, router addresses etc.
output_key: network_environment_data
output_value:
internal2_router: 172.17.1.204
internal_router_address: 172.17.0.201
provision2_router: 192.168.25.254
provision3_router: 192.168.26.254
provision_router: 192.168.24.254
storage2_router_address: 172.18.1.254
storage_mgmt2_router_address: 172.19.1.254
storage_mgmt_router_address: 172.19.0.254
storage_router_address: 172.18.0.254
tenant2_router_address: 172.16.1.254
tenant_router_address: 172.16.0.254
- description: ip of the undercloud instance on the private network
output_key: undercloud_host_private_ip
output_value: 10.0.1.14
#. Below is an example TripleO Undercloud configuration (``undercloud.conf``)
with routed networks support enabled and the three provisioning networks
defined.
::
[DEFAULT]
enable_routed_networks = true
enable_ui = false
overcloud_domain_name = localdomain
scheduler_max_attempts = 2
undercloud_ntp_servers = pool.ntp.org
undercloud_hostname = undercloud.rdocloud
local_interface = eth1
local_mtu = 1450
local_ip = 192.168.24.1/24
undercloud_public_host = 192.168.24.2
undercloud_admin_host = 192.168.24.3
undercloud_nameservers = 8.8.8.8,8.8.4.4
local_subnet = provision
subnets = provision,provision2,provision3
[provision]
cidr = 192.168.24.0/24
dhcp_start = 192.168.24.10
dhcp_end = 192.168.24.30
gateway = 192.168.24.254
inspection_iprange = 192.168.24.100,192.168.24.120
masquerade = true
[provision2]
cidr = 192.168.25.0/24
dhcp_start = 192.168.25.10
dhcp_end = 192.168.25.30
gateway = 192.168.25.254
inspection_iprange = 192.168.25.100,192.168.25.120
masquerade = true
[provision3]
cidr = 192.168.26.0/24
dhcp_start = 192.168.26.10
dhcp_end = 192.168.26.30
gateway = 192.168.26.254
inspection_iprange = 192.168.26.100,192.168.26.120
masquerade = true
<file_sep>/openstack_virtual_baremetal/deploy.py
#!/usr/bin/env python
# Copyright 2016 Red Hat Inc.
#
# 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.
from __future__ import print_function
import argparse
import sys
import time
import yaml
from heatclient.common import template_utils
import os_client_config
import auth
def _parse_args():
parser = argparse.ArgumentParser(description='Deploy an OVB environment')
parser.add_argument(
'--env', '-e',
help='Path to Heat environment file describing the OVB '
'environment to be deployed. Default: %(default)s',
action='append',
default=[])
parser.add_argument(
'--id',
help='Identifier to add to all resource names. The '
'resulting names will look like undercloud-ID or '
'baremetal-ID. By default no changes will be made to '
'the resource names. If an id is specified, a new '
'environment file will be written to env-ID.yaml. ')
parser.add_argument(
'--name',
help='Name for the Heat stack to be created. Defaults '
'to "baremetal" in a standard deployment. If '
'--quintupleo is specified then the default is '
'"quintupleo".')
parser.add_argument(
'--quintupleo',
help='Deploy a full environment suitable for TripleO '
'development.',
action='store_true',
default=False)
parser.add_argument(
'--role',
help='Additional environment file describing a '
'secondary role to be deployed alongside the '
'primary one described in the main environment.',
action='append',
default=[])
parser.add_argument(
'--poll',
help='Poll until the Heat stack(s) are complete. '
'Automatically enabled when multiple roles are '
'deployed.',
action='store_true',
default=False)
return parser.parse_args()
def _process_args(args):
if args.id:
if not args.quintupleo:
raise RuntimeError('--id requires --quintupleo')
id_env = 'env-%s.yaml' % args.id
if id_env in args.env:
raise ValueError('Input env file "%s" would be overwritten by ID '
'env file. Either rename the input file or '
'change the deploy ID.' % id_env)
if args.role and not args.quintupleo:
raise RuntimeError('--role requires --quintupleo')
# NOTE(bnemec): We changed the way the --env parameter works such that the
# default is no longer 'env.yaml' but instead an empty list. However, for
# compatibility we need to maintain the ability to default to env.yaml
# if --env is not explicitly specified.
if not args.env:
args.env = ['env.yaml']
if args.name:
stack_name = args.name
else:
stack_name = 'baremetal'
if args.quintupleo:
stack_name = 'quintupleo'
if not args.quintupleo:
stack_template = 'templates/virtual-baremetal.yaml'
else:
stack_template = 'templates/quintupleo.yaml'
return stack_name, stack_template
def _add_identifier(env_data, name, identifier, default=None):
"""Append identifier to the end of parameter name in env_data
Look for ``name`` in the ``parameter_defaults`` key of ``env_data`` and
append '-``identifier``' to it.
"""
value = env_data['parameter_defaults'].get(name)
if value is None:
value = default
if value is None:
raise RuntimeError('No base value found when adding id')
if identifier:
value = '%s-%s' % (value, identifier)
env_data['parameter_defaults'][name] = value
def _build_env_data(env_paths):
"""Merge env data from the provided paths
Given a list of files in env_paths, merge the contents of all those
environment files and return the results.
:param env_paths: A list of env files to operate on.
:returns: A dict containing the merged contents of the provided files.
"""
_, env_data = template_utils.process_multiple_environments_and_files(
env_paths)
return env_data
def _generate_id_env(args):
env_data = _build_env_data(args.env)
_add_identifier(env_data, 'provision_net', args.id, default='provision')
_add_identifier(env_data, 'provision_net2', args.id, default='provision2')
_add_identifier(env_data, 'provision_net3', args.id, default='provision3')
_add_identifier(env_data, 'public_net', args.id, default='public')
_add_identifier(env_data,
'baremetal_prefix',
args.id,
default='baremetal')
role = env_data['parameter_defaults'].get('role')
if role:
_add_identifier(env_data, 'baremetal_prefix', role)
_add_identifier(env_data, 'bmc_prefix', args.id, default='bmc')
_add_identifier(env_data,
'undercloud_name',
args.id,
default='undercloud')
_add_identifier(env_data, 'overcloud_internal_net', args.id,
default='internal')
_add_identifier(env_data, 'overcloud_storage_net', args.id,
default='storage')
_add_identifier(env_data, 'overcloud_storage_mgmt_net', args.id,
default='storage_mgmt')
_add_identifier(env_data, 'overcloud_tenant_net', args.id,
default='tenant')
# TODO(bnemec): Network names should be parameterized so we don't have to
# hardcode them into deploy.py like this.
_add_identifier(env_data, 'overcloud_internal_net2', args.id,
default='overcloud_internal2')
_add_identifier(env_data, 'overcloud_storage_net2', args.id,
default='overcloud_storage2')
_add_identifier(env_data, 'overcloud_storage_mgmt_net2', args.id,
default='overcloud_storage_mgmt2')
_add_identifier(env_data, 'overcloud_tenant_net2', args.id,
default='overcloud_tenant2')
# We don't modify any resource_registry entries, and because we may be
# writing the new env file to a different path it can break relative paths
# in the resource_registry.
env_data.pop('resource_registry', None)
env_path = 'env-%s.yaml' % args.id
with open(env_path, 'w') as f:
yaml.safe_dump(env_data, f, default_flow_style=False)
return args.env + [env_path]
def _validate_env(args, env_paths):
"""Check for invalid environment configurations
:param args: Argparse args.
:param env_paths: Path(s) of the environment file(s) to validate.
"""
if not args.id:
env_data = _build_env_data(env_paths)
role = env_data.get('parameter_defaults', {}).get('role')
prefix = env_data['parameter_defaults']['baremetal_prefix']
if role and prefix.endswith('-' + role):
raise RuntimeError('baremetal_prefix ends with role name. This '
'will break build-nodes-json. Please choose '
'a different baremetal_prefix or role name.')
for path in env_paths:
if 'port-security.yaml' in path:
print('WARNING: port-security environment file detected. '
'port-security is now the default. The existing '
'port-security environment files are deprecated and may be '
'removed in the future. Please use the environment files '
'without "port-security" in their filename instead.'
)
def _get_heat_client():
return os_client_config.make_client('orchestration',
cloud=auth.OS_CLOUD)
def _deploy(stack_name, stack_template, env_paths, poll):
hclient = _get_heat_client()
template_files, template = template_utils.get_template_contents(
stack_template)
env_files, env = template_utils.process_multiple_environments_and_files(
['templates/resource-registry.yaml'] + env_paths)
all_files = {}
all_files.update(template_files)
all_files.update(env_files)
parameters = {'cloud_data': auth._cloud_json()}
hclient.stacks.create(stack_name=stack_name,
template=template,
environment=env,
files=all_files,
parameters=parameters)
print('Deployment of stack "%s" started.' % stack_name)
if poll:
_poll_stack(stack_name, hclient)
def _poll_stack(stack_name, hclient):
"""Poll status for stack_name until it completes or fails"""
print('Waiting for stack to complete', end="")
done = False
while not done:
print('.', end="")
# By the time we get here we know Heat was up at one point because
# we were able to start the stack create. Therefore, we can
# reasonably guess that any errors from this call are going to be
# transient.
try:
stack = hclient.stacks.get(stack_name, resolve_outputs=False)
except Exception as e:
# Print the error so the user can determine whether they need
# to cancel the deployment, but keep trying otherwise.
print('WARNING: Exception occurred while polling stack: %s' % e)
time.sleep(10)
continue
sys.stdout.flush()
if stack.status == 'COMPLETE':
print('Stack %s created successfully' % stack_name)
done = True
elif stack.status == 'FAILED':
print(stack.to_dict().get('stack_status_reason'))
raise RuntimeError('Failed to create stack %s' % stack_name)
else:
time.sleep(10)
# Abstract out the role file interactions for easier unit testing
def _load_role_data(base_envs, role_file, args):
base_data = _build_env_data(base_envs)
with open(role_file) as f:
role_data = yaml.safe_load(f)
orig_data = _build_env_data(args.env)
return base_data, role_data, orig_data
def _write_role_file(role_env, role_file):
with open(role_file, 'w') as f:
yaml.safe_dump(role_env, f, default_flow_style=False)
def _process_role(role_file, base_envs, stack_name, args):
"""Merge a partial role env with the base env
:param role: Filename of an environment file containing the definition
of the role.
:param base_envs: Filename(s) of the environment file(s) used to deploy the
stack containing shared resources such as the undercloud and
networks.
:param stack_name: Name of the stack deployed using base_envs.
:param args: The command-line arguments object from argparse.
"""
base_data, role_data, orig_data = _load_role_data(base_envs, role_file,
args)
inherited_keys = ['baremetal_image', '<KEY>', 'bmc_image',
'external_net', 'key_name', 'os_auth_url',
'os_password', 'os_tenant', 'os_user',
'private_net', 'provision_net', 'public_net',
'overcloud_internal_net', 'overcloud_storage_mgmt_net',
'overcloud_storage_net', 'overcloud_tenant_net',
]
# Parameters that are inherited but can be overridden by the role
allowed_parameter_keys = ['baremetal_image', '<KEY>', 'key_name',
'provision_net', 'overcloud_internal_net',
'overcloud_storage_net',
'overcloud_storage_mgmt_net',
'overcloud_tenant_net',
]
allowed_registry_keys = ['OS::OVB::BaremetalPorts', '<KEY>',
'OS::OVB::UndercloudNetworks',
]
# NOTE(bnemec): Not sure what purpose this serves. Can probably be removed.
role_env = role_data
# resource_registry is intentionally omitted as it should not be inherited
role_env.setdefault('parameter_defaults', {}).update({
k: v for k, v in base_data.get('parameter_defaults', {}).items()
if k in inherited_keys and
(k not in role_env.get('parameter_defaults', {}) or
k not in allowed_parameter_keys)
})
# Most of the resource_registry should not be included in role envs.
# Only allow specific entries that may be needed.
role_env.setdefault('resource_registry', {})
role_env['resource_registry'] = {
k: v for k, v in role_env['resource_registry'].items()
if k in allowed_registry_keys}
role_reg = role_env['resource_registry']
base_reg = base_data['resource_registry']
for k in allowed_registry_keys:
if k not in role_reg and k in base_reg:
role_reg[k] = base_reg[k]
# We need to start with the unmodified prefix
base_prefix = orig_data['parameter_defaults']['baremetal_prefix']
# But we do need to add the id if one is in use
if args.id:
base_prefix += '-%s' % args.id
bmc_prefix = base_data['parameter_defaults']['bmc_prefix']
role = role_data['parameter_defaults']['role']
if '_' in role:
raise RuntimeError('_ character not allowed in role name "%s".' % role)
role_env['parameter_defaults']['baremetal_prefix'] = ('%s-%s' %
(base_prefix, role))
role_env['parameter_defaults']['bmc_prefix'] = '%s-%s' % (bmc_prefix, role)
# At this time roles are only attached to a single set of networks, so
# we use just the primary network parameters.
def maybe_add_id(role_env, name, args):
"""Add id only if one is not already present
When we inherit network names, they will already have the id present.
However, if the user overrides the network name (for example, when
using multiple routed networks) then it should not have the id.
We can detect which is the case by looking at whether the name already
ends with -id.
"""
if (args.id and
not role_env['parameter_defaults'].get(name, '')
.endswith('-' + args.id)):
_add_identifier(role_env, name, args.id)
maybe_add_id(role_env, 'provision_net', args)
maybe_add_id(role_env, 'overcloud_internal_net', args)
maybe_add_id(role_env, 'overcloud_storage_net', args)
maybe_add_id(role_env, 'overcloud_storage_mgmt_net', args)
maybe_add_id(role_env, 'overcloud_tenant_net', args)
role_env['parameter_defaults']['networks'] = {
'private': role_env['parameter_defaults']['private_net'],
'provision': role_env['parameter_defaults']['provision_net'],
'public': role_env['parameter_defaults']['public_net'],
}
role_file = 'env-%s-%s.yaml' % (stack_name, role)
_write_role_file(role_env, role_file)
return role_file, role
def _deploy_roles(stack_name, args, env_paths):
for r in args.role:
role_env, role_name = _process_role(r, env_paths, stack_name, args)
_deploy(stack_name + '-%s' % role_name,
'templates/virtual-baremetal.yaml',
[role_env], poll=True)
if __name__ == '__main__':
args = _parse_args()
stack_name, stack_template = _process_args(args)
env_paths = args.env
if args.id:
env_paths = _generate_id_env(args)
_validate_env(args, env_paths)
poll = args.poll
if args.role:
poll = True
_deploy(stack_name, stack_template, env_paths, poll=poll)
_deploy_roles(stack_name, args, env_paths)
<file_sep>/openstack_virtual_baremetal/tests/test_deploy.py
#!/usr/bin/env python
# Copyright 2016 Red Hat Inc.
#
# 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.
import copy
import unittest
import yaml
import mock
import testtools
from openstack_virtual_baremetal import deploy
class TestProcessArgs(unittest.TestCase):
def _basic_mock_args(self):
"""Return a mock with basic args set"""
mock_args = mock.Mock()
mock_args.name = None
mock_args.quintupleo = False
mock_args.id = None
mock_args.env = []
mock_args.role = []
return mock_args
def test_basic(self):
mock_args = self._basic_mock_args()
name, template = deploy._process_args(mock_args)
self.assertEqual('baremetal', name)
self.assertEqual('templates/virtual-baremetal.yaml', template)
def test_name(self):
mock_args = self._basic_mock_args()
mock_args.name = 'foo'
name, template = deploy._process_args(mock_args)
self.assertEqual('foo', name)
self.assertEqual('templates/virtual-baremetal.yaml', template)
def test_quintupleo(self):
mock_args = self._basic_mock_args()
mock_args.quintupleo = True
name, template = deploy._process_args(mock_args)
self.assertEqual('quintupleo', name)
self.assertEqual('templates/quintupleo.yaml', template)
def test_quintupleo_name(self):
mock_args = self._basic_mock_args()
mock_args.name = 'foo'
mock_args.quintupleo = True
name, template = deploy._process_args(mock_args)
self.assertEqual('foo', name)
self.assertEqual('templates/quintupleo.yaml', template)
def test_id_quintupleo(self):
mock_args = self._basic_mock_args()
mock_args.id = 'foo'
self.assertRaises(RuntimeError, deploy._process_args, mock_args)
def test_role_quintupleo(self):
mock_args = self._basic_mock_args()
mock_args.role = 'foo.yaml'
self.assertRaises(RuntimeError, deploy._process_args, mock_args)
def test_maintain_old_default(self):
mock_args = self._basic_mock_args()
mock_args.name = 'foo'
mock_args.quintupleo = True
name, template = deploy._process_args(mock_args)
self.assertEqual('foo', name)
self.assertEqual('templates/quintupleo.yaml', template)
self.assertEqual(['env.yaml'], mock_args.env)
def test_no_overwrite(self):
mock_args = self._basic_mock_args()
mock_args.quintupleo = True
mock_args.id = 'foo'
mock_args.env = ['env-foo.yaml']
self.assertRaises(ValueError, deploy._process_args, mock_args)
test_env = u"""parameter_defaults:
provision_net: provision
public_net: public
baremetal_prefix: baremetal
bmc_prefix: bmc
"""
test_env_extra = u"""
overcloud_internal_net: internalapi
role: ''
"""
test_env_output = {
'baremetal_prefix': 'baremetal-foo',
'undercloud_name': 'undercloud-foo',
'provision_net': 'provision-foo',
'public_net': 'public-foo',
'bmc_prefix': 'bmc-foo',
'overcloud_internal_net': 'internal-foo',
'overcloud_storage_net': 'storage-foo',
'overcloud_storage_mgmt_net': 'storage_mgmt-foo',
'overcloud_tenant_net': 'tenant-foo'
}
class TestIdEnv(unittest.TestCase):
def test_add_identifier(self):
env_data = {'parameter_defaults': {'foo': 'bar'}}
deploy._add_identifier(env_data, 'foo', 'baz')
self.assertEqual('bar-baz', env_data['parameter_defaults']['foo'])
def test_add_identifier_different_section(self):
env_data = {'parameter_defaults': {'foo': 'bar'}}
deploy._add_identifier(env_data, 'foo', 'baz')
self.assertEqual('bar-baz', env_data['parameter_defaults']['foo'])
@mock.patch('openstack_virtual_baremetal.deploy._build_env_data')
@mock.patch('yaml.safe_dump')
def test_generate(self, mock_safe_dump, mock_bed):
mock_args = mock.Mock()
mock_args.id = 'foo'
mock_args.env = ['foo.yaml']
mock_bed.return_value = yaml.safe_load(test_env)
path = deploy._generate_id_env(mock_args)
self.assertEqual(['foo.yaml', 'env-foo.yaml'], path)
dumped_dict = mock_safe_dump.call_args_list[0][0][0]
for k, v in test_env_output.items():
self.assertEqual(v, dumped_dict['parameter_defaults'][k])
@mock.patch('openstack_virtual_baremetal.deploy._build_env_data')
@mock.patch('yaml.safe_dump')
def test_generate_undercloud_name(self, mock_safe_dump, mock_bed):
mock_args = mock.Mock()
mock_args.id = 'foo'
mock_args.env = ['foo.yaml']
env = (test_env + test_env_extra +
' undercloud_name: test-undercloud\n')
mock_bed.return_value = yaml.safe_load(env)
env_output = dict(test_env_output)
env_output['undercloud_name'] = 'test-undercloud-foo'
env_output['overcloud_internal_net'] = 'internalapi-foo'
path = deploy._generate_id_env(mock_args)
self.assertEqual(['foo.yaml', 'env-foo.yaml'], path)
dumped_dict = mock_safe_dump.call_args_list[0][0][0]
for k, v in env_output.items():
self.assertEqual(v, dumped_dict['parameter_defaults'][k])
@mock.patch('openstack_virtual_baremetal.deploy._build_env_data')
@mock.patch('yaml.safe_dump')
def test_generate_with_role(self, mock_safe_dump, mock_bed):
mock_args = mock.Mock()
mock_args.id = 'foo'
mock_args.env = ['foo.yaml']
env = (test_env + test_env_extra)
mock_bed.return_value = yaml.safe_load(env)
mock_bed.return_value['parameter_defaults']['role'] = 'compute'
env_output = dict(test_env_output)
env_output['overcloud_internal_net'] = 'internalapi-foo'
env_output['baremetal_prefix'] = 'baremetal-foo-compute'
path = deploy._generate_id_env(mock_args)
self.assertEqual(['foo.yaml', 'env-foo.yaml'], path)
dumped_dict = mock_safe_dump.call_args_list[0][0][0]
for k, v in env_output.items():
self.assertEqual(v, dumped_dict['parameter_defaults'][k])
# _process_role test data
role_base_data = {
'parameter_defaults': {
'overcloud_storage_mgmt_net': 'storage_mgmt-foo',
'overcloud_internal_net': 'internal-foo',
'overcloud_storage_net': 'storage-foo',
'overcloud_tenant_net': 'tenant-foo',
'provision_net': 'provision-foo',
'public_net': 'public-foo',
'private_net': 'private',
'role': 'control',
'os_user': 'admin',
'key_name': 'default',
'undercloud_name': 'undercloud-foo',
'bmc_image': 'bmc-base',
'baremetal_flavor': 'baremetal',
'os_auth_url': 'http://1.1.1.1:5000/v2.0',
'os_password': '<PASSWORD>',
'os_tenant': 'admin',
'bmc_prefix': 'bmc-foo',
'undercloud_image': 'centos7-base',
'baremetal_image': 'ipxe-boot',
'external_net': 'external',
'baremetal_prefix': 'baremetal-foo-control',
'undercloud_flavor': 'undercloud-16',
'node_count': 3,
'bmc_flavor': 'bmc'
},
'resource_registry': {
'OS::OVB::BaremetalNetworks': 'templates/baremetal-networks-all.yaml',
'OS::OVB::BaremetalPorts':
'templates/baremetal-ports-public-bond.yaml',
'OS::OVB::BMCPort': 'templates/bmc-port.yaml'
}
}
role_specific_data = {
'parameter_defaults': {
'role': 'compute',
'key_name': 'default',
'baremetal_flavor': 'baremetal',
'baremetal_image': 'centos',
'bmc_image': 'bmc-base',
'bmc_prefix': 'bmc',
'node_count': 2,
'bmc_flavor': 'bmc'
},
'resource_registry': {
'OS::OVB::BaremetalNetworks': 'templates/baremetal-networks-all.yaml',
'OS::OVB::BaremetalPorts': 'templates/baremetal-ports-all.yaml'
}
}
role_original_data = {
'parameter_defaults': {
'role': 'control',
'baremetal_prefix': 'baremetal',
'public_net': 'public',
'private_net': 'private',
'provision_net': 'provision',
'os_user': 'admin',
'key_name': 'default',
'undercloud_name': 'undercloud',
'baremetal_flavor': 'baremetal',
'os_auth_url': 'http://1.1.1.1:5000/v2.0',
'bmc_image': 'bmc-base',
'os_tenant': 'admin',
'bmc_prefix': 'bmc',
'undercloud_image': 'centos7-base',
'baremetal_image': 'ipxe-boot',
'external_net': 'external',
'os_password': '<PASSWORD>',
'undercloud_flavor': 'undercloud-16',
'node_count': 3,
'bmc_flavor': 'bmc'
},
'resource_registry': {
'OS::OVB::BaremetalNetworks': 'templates/baremetal-networks-all.yaml',
'OS::OVB::BaremetalPorts':
'templates/baremetal-ports-public-bond.yaml',
'OS::OVB::BMCPort': 'templates/bmc-port.yaml'
}
}
# end _process_role test data
class TestDeploy(testtools.TestCase):
def _test_deploy(self, mock_ghc, mock_tu, mock_poll, mock_cj, poll=False):
mock_client = mock.Mock()
mock_ghc.return_value = mock_client
template_files = {'template.yaml': {'foo': 'bar'}}
template = {'foo': 'bar'}
mock_tu.get_template_contents.return_value = (
template_files, template
)
env_files = {'templates/resource_registry.yaml': {'bar': 'baz'},
'env.yaml': {'parameter_defaults': {}}}
env = {'parameter_defaults': {}}
mock_tu.process_multiple_environments_and_files.return_value = (
env_files, env
)
all_files = {}
all_files.update(template_files)
all_files.update(env_files)
auth = {'os_user': 'admin',
'os_password': '<PASSWORD>',
'os_tenant': 'admin',
'os_auth_url': 'http://1.1.1.1:5000/v2.0',
}
params = {'auth': auth}
expected_params = {'cloud_data': params}
mock_cj.return_value = params
deploy._deploy('test', 'template.yaml', ['env.yaml', 'test.yaml'],
poll)
mock_tu.get_template_contents.assert_called_once_with('template.yaml')
process = mock_tu.process_multiple_environments_and_files
process.assert_called_once_with(['templates/resource-registry.yaml',
'env.yaml', 'test.yaml'])
mock_client.stacks.create.assert_called_once_with(
stack_name='test',
template=template,
environment=env,
files=all_files,
parameters=expected_params)
if not poll:
mock_poll.assert_not_called()
else:
mock_poll.assert_called_once_with('test', mock_client)
@mock.patch('openstack_virtual_baremetal.auth._cloud_json')
@mock.patch('openstack_virtual_baremetal.deploy._poll_stack')
@mock.patch('openstack_virtual_baremetal.deploy.template_utils')
@mock.patch('openstack_virtual_baremetal.deploy._get_heat_client')
def test_deploy(self, mock_ghc, mock_tu, mock_poll, mock_cj):
self._test_deploy(mock_ghc, mock_tu, mock_poll, mock_cj)
@mock.patch('openstack_virtual_baremetal.auth._cloud_json')
@mock.patch('openstack_virtual_baremetal.deploy._poll_stack')
@mock.patch('openstack_virtual_baremetal.deploy.template_utils')
@mock.patch('openstack_virtual_baremetal.deploy._get_heat_client')
def test_deploy_poll(self, mock_ghc, mock_tu, mock_poll, mock_cj):
self._test_deploy(mock_ghc, mock_tu, mock_poll, mock_cj, True)
@mock.patch('time.sleep')
def test_poll(self, mock_sleep):
hclient = mock.Mock()
stacks = [mock.Mock(), mock.Mock()]
stacks[0].status = 'IN_PROGRESS'
stacks[1].status = 'COMPLETE'
hclient.stacks.get.side_effect = stacks
deploy._poll_stack('foo', hclient)
self.assertEqual(
[
mock.call('foo', resolve_outputs=False),
mock.call('foo', resolve_outputs=False)
], hclient.stacks.get.mock_calls)
@mock.patch('time.sleep')
def test_poll_fail(self, mock_sleep):
hclient = mock.Mock()
stacks = [mock.Mock(), mock.Mock()]
stacks[0].status = 'IN_PROGRESS'
stacks[1].status = 'FAILED'
hclient.stacks.get.side_effect = stacks
self.assertRaises(RuntimeError, deploy._poll_stack, 'foo', hclient)
self.assertEqual(
[
mock.call('foo', resolve_outputs=False),
mock.call('foo', resolve_outputs=False)
], hclient.stacks.get.mock_calls)
@mock.patch('time.sleep')
def test_poll_retry(self, mock_sleep):
hclient = mock.Mock()
stacks = [mock.Mock(), Exception, mock.Mock()]
stacks[0].status = 'IN_PROGRESS'
stacks[2].status = 'COMPLETE'
hclient.stacks.get.side_effect = stacks
deploy._poll_stack('foo', hclient)
self.assertEqual(
[
mock.call('foo', resolve_outputs=False),
mock.call('foo', resolve_outputs=False),
mock.call('foo', resolve_outputs=False)
], hclient.stacks.get.mock_calls)
@mock.patch('openstack_virtual_baremetal.deploy._write_role_file')
@mock.patch('openstack_virtual_baremetal.deploy._load_role_data')
def test_process_role(self, mock_load, mock_write):
mock_load.return_value = (role_base_data, role_specific_data,
role_original_data)
args = mock.Mock()
args.id = 'foo'
role_file, role = deploy._process_role('foo-compute.yaml', 'foo.yaml',
'foo', args)
mock_load.assert_called_once_with('foo.yaml', 'foo-compute.yaml', args)
self.assertEqual('env-foo-compute.yaml', role_file)
self.assertEqual('compute', role)
output = mock_write.call_args[0][0]
# These values are computed in _process_role
self.assertEqual('baremetal-foo-compute',
output['parameter_defaults']['baremetal_prefix'])
self.assertEqual('bmc-foo-compute',
output['parameter_defaults']['bmc_prefix'])
# These should be inherited
self.assertEqual('tenant-' + args.id,
output['parameter_defaults']['overcloud_tenant_net'])
self.assertEqual('internal-' + args.id,
output['parameter_defaults']['overcloud_internal_net']
)
self.assertEqual('storage-' + args.id,
output['parameter_defaults']['overcloud_storage_net'])
self.assertEqual('storage_mgmt-' + args.id,
output['parameter_defaults'][
'overcloud_storage_mgmt_net'])
# This parameter should be overrideable
self.assertEqual('centos',
output['parameter_defaults']['baremetal_image'])
# This should not be present in a role env, even if set in the file
self.assertNotIn('OS::OVB::BaremetalNetworks',
output['resource_registry'])
# This should be the value set in the role env, not the base one
self.assertEqual(
'templates/baremetal-ports-all.yaml',
output['resource_registry']['OS::OVB::BaremetalPorts'])
# This should be inherited from the base env
self.assertEqual('templates/bmc-port.yaml',
output['resource_registry']['OS::OVB::BMCPort'])
@mock.patch('openstack_virtual_baremetal.deploy._load_role_data')
def test_process_role_invalid_name(self, mock_load):
bad_role_specific_data = copy.deepcopy(role_specific_data)
bad_role_specific_data['parameter_defaults']['role'] = 'foo_bar'
mock_load.return_value = (role_base_data, bad_role_specific_data,
role_original_data)
args = mock.Mock()
args.id = 'foo'
self.assertRaises(RuntimeError, deploy._process_role,
'foo-foo_bar.yaml', 'foo.yaml', 'foo', args)
@mock.patch('openstack_virtual_baremetal.deploy._deploy')
@mock.patch('openstack_virtual_baremetal.deploy._process_role')
def test_deploy_roles(self, mock_process, mock_deploy):
args = mock.Mock()
args.role = ['foo-compute.yaml']
mock_process.return_value = ('env-foo-compute.yaml', 'compute')
deploy._deploy_roles('foo', args, 'foo.yaml')
mock_process.assert_called_once_with('foo-compute.yaml', 'foo.yaml',
'foo', args)
mock_deploy.assert_called_once_with('foo-compute',
'templates/virtual-baremetal.yaml',
['env-foo-compute.yaml'],
poll=True)
@mock.patch('openstack_virtual_baremetal.deploy._process_role')
def test_deploy_roles_empty(self, mock_process):
args = mock.Mock()
args.role = []
deploy._deploy_roles('foo', args, 'foo.yaml')
mock_process.assert_not_called()
def _test_validate_env_ends_with_profile(self, mock_id, mock_bed):
test_env = dict(role_original_data)
test_env['parameter_defaults']['baremetal_prefix'] = (
'baremetal-control')
mock_bed.return_value = test_env
args = mock.Mock()
args.id = mock_id
if not mock_id:
self.assertRaises(RuntimeError, deploy._validate_env,
args, ['foo.yaml'])
else:
deploy._validate_env(args, ['foo.yaml'])
@mock.patch('openstack_virtual_baremetal.deploy._build_env_data')
def test_validate_env_fails(self, mock_bed):
self._test_validate_env_ends_with_profile(None, mock_bed)
@mock.patch('openstack_virtual_baremetal.deploy._build_env_data')
def test_validate_env_with_id(self, mock_bed):
self._test_validate_env_ends_with_profile('foo', mock_bed)
@mock.patch('openstack_virtual_baremetal.deploy._build_env_data')
def test_validate_env(self, mock_bed):
mock_bed.return_value = role_original_data
args = mock.Mock()
args.id = None
deploy._validate_env(args, ['foo.yaml'])
class TestGetHeatClient(testtools.TestCase):
@mock.patch('openstack_virtual_baremetal.auth.OS_CLOUD', 'foo')
@mock.patch('os_client_config.make_client')
def test_os_cloud(self, mock_make_client):
deploy._get_heat_client()
mock_make_client.assert_called_once_with('orchestration', cloud='foo')
if __name__ == '__main__':
unittest.main()
<file_sep>/bin/rebuild-baremetal
#!/bin/bash
# Script to rebuild baremetal instances to the ipxe-boot image.
# When using OVB without the Nova PXE boot patch, this is required after
# each deployment to ensure the nodes can PXE boot for the next one.
# Usage: rebuild-baremetal <number of nodes> [baremetal_base] [environment ID]
# Examples: rebuild-baremetal 2
# rebuild-baremetal 5 my-baremetal-name
# rebuild-baremetal 5 baremetal test
node_num=$1
baremetal_base=${2:-'baremetal'}
env_id=${3:-}
name_base="$baremetal_base"
if [ -n "$env_id" ]
then
name_base="$baremetal_base-$env_id"
fi
for i in `seq 0 $((node_num - 1))`
do
echo nova rebuild "${instance_list}${name_base}_$i" ipxe-boot
nova rebuild "${instance_list}${name_base}_$i" ipxe-boot
done
<file_sep>/bin/stop-env
#!/bin/bash
# Usage: stop-env <ID>
# Example: stop-env test
# This will stop the undercloud and bmc, as well as up to 5 baremetal instances
# TODO: Make this smarter so it will handle an arbitrary number of baremetal instances
nova stop undercloud-$1 bmc-$1 baremetal-$1_0 baremetal-$1_1 baremetal-$1_2 baremetal-$1_3 baremetal-$1_4
<file_sep>/bin/deploy.py
../openstack_virtual_baremetal/deploy.py<file_sep>/openstack_virtual_baremetal/auth.py
# Copyright 2017 Red Hat Inc.
#
# 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.
import json
import os
import os_client_config
# Older versions of os-client-config pop this from the environment when
# make_client is called. Cache it on import so we know what the original
# value was, regardless of any funny business that happens later.
OS_CLOUD = os.environ.get('OS_CLOUD')
def _create_auth_parameters():
"""Read keystone auth parameters from appropriate source
If the environment variable OS_CLOUD is set, read the auth information
from os_client_config. Otherwise, read it from environment variables.
When reading from the environment, also validate that all of the required
values are set.
:returns: A dict containing the following keys: os_user, os_password,
os_tenant, os_auth_url, os_project, os_user_domain,
os_project_domain.
"""
config = os_client_config.OpenStackConfig().get_one_cloud(OS_CLOUD)
auth = config.config['auth']
username = auth['username']
password = auth['<PASSWORD>']
# os_client_config seems to always call this project_name
tenant = auth['project_name']
auth_url = auth['auth_url']
project = auth['project_name']
user_domain = (auth.get('user_domain_name') or
auth.get('user_domain_id', ''))
project_domain = (auth.get('project_domain_name') or
auth.get('project_domain_id', ''))
return {'os_user': username,
'os_password': <PASSWORD>,
'os_tenant': tenant,
'os_auth_url': auth_url,
'os_project': project,
'os_user_domain': user_domain,
'os_project_domain': project_domain,
}
def _cloud_json():
"""Return the current cloud's data in JSON
Retrieves the cloud from os-client-config and serializes it to JSON.
"""
config = os_client_config.OpenStackConfig().get_one_cloud(OS_CLOUD)
return json.dumps(config.config)
<file_sep>/doc/source/troubleshooting.rst
Troubleshooting
===============
A list of common problems and their solutions.
Nodes hang while downloading the deploy ramdisk or kernel
---------------------------------------------------------
**Cause**: Improper MTU settings on deployment interfaces.
**Solution**: Set the MTU on the deployment interfaces to allow PXE booting to
work correctly. For TripleO-based deployments, see the readme
for details on how to do this. For others, make sure that the
deployment nic on the undercloud vm has the MTU set appropriately
and that the DHCP server responding to PXE requests advertises the
same MTU. Note that this MTU should be 50 bytes smaller than the
physical MTU of the host cloud.
Nodes are deployed, but cannot talk to each other
-------------------------------------------------
In OpenStack deployments, this often presents as rabbitmq connectivity issues
from compute nodes.
**Cause**: Improper MTU settings on deployed instances.
**Solution**: Essentially the same as the previous problem. Ensure that the MTU
being used on the deployed instances is 50 bytes smaller than the
physical MTU of the host cloud. Again, for TripleO-based
deployments the readme has details on how to do this.
Nodes fail to PXE boot
----------------------
**Cause**: The nodes are not configured to PXE boot properly.
**Solution**: This depends on the method being used to PXE boot. If the Nova
patch is being used to provide this functionality, then ensure
that it has been applied on all compute nodes and those nodes'
nova-compute service has been restarted. If the ipxe-boot image
is being used without the Nova patch, the baremetal instances must
be rebuilt to the ipxe-boot image before subsequent deployments.
Nodes fail to PXE boot 2
------------------------
DHCP requests are seen on the undercloud
VM, but responses never get to the baremetal instances.
**Cause**: Neutron port security blocking DHCP from the undercloud.
**Solution**: Ensure that the Neutron port-security extension is present in
the host cloud. It is required for OVB to function properly.
The BMC does not respond to IPMI requests
-----------------------------------------
**Cause**: Several. Neutron may not be configured to allow the BMC to listen
on arbitrary addresses. The BMC deployment may have failed for some
reason.
**Solution**: Neutron must be configured to allow the BMC to listen on
arbitrary addresses. This requires the port-security extension as in the
previous solution. If this is already configured correctly, then the BMC may
have failed to deploy properly. This can usually be determined by looking at
the nova console-log of the BMC instance. A correctly working BMC will
display 'Managing instance [uuid]' for each baremetal node in the
environment. If those messages are not found, then the BMC has
failed to start properly. The relevant error messages should be
found in the console-log of the BMC. If that is not sufficient to
troubleshoot the problem, the BMC can be accessed using the
ssh key configured in the OVB environment yaml as the 'centos'
user.
| 3cd681227ef57f47b2729c1c8d83b933d3bdc3f6 | [
"reStructuredText",
"Makefile",
"Python",
"Text",
"Shell"
] | 33 | reStructuredText | cybertron/openstack-virtual-baremetal | dcd546609c5362610b885eae02ae1055343e11ab | f001c66930362d9643eba5330907ff34a789421b |
refs/heads/master | <file_sep>#define SNAKE_SYMBOL '@' /* snake body and food symbol */
#define FOOD_SYMBOL '*'
#define MAX_NODE 30 /* maximum snake nodes */
#define DFL_SPEED 50 /* snake default speed */
#define TOP_ROW 5 /* top_row */
#define BOT_ROW LINES - 1
#define LEFT_EDGE 0
#define RIGHT_EDGE COLS - 1
typedef struct node /* Snake_node structure */
{
int x_pos;
int y_pos;
struct node *prev;
struct node *next;
} Snake_Node;
struct position /* food position structure */
{
int x_pos;
int y_pos;
} ;
void Init_Disp(); /* init and display the interface */
void Food_Disp(); /* display the food position */
void Wrap_Up(); /* turn off the curses */
void Key_Ctrl(); /* using keyboard to control snake */
int set_ticker(int n_msecs);/* ticker */
void DLL_Snake_Create(); /* create double linked list*/
void DLL_Snake_Insert(int x, int y); /* insert node */
void DLL_Snake_Delete_Node(); /* delete a node */
void DLL_Snake_Delete(); /* delete all the linked list */
void Snake_Move(); /* control the snake move and judge */
void gameover(int n); /* different n means different state */
<file_sep># Информация о проекте
Игрок управляет длинным, тонким существом, напоминающим змею , которое ползает по плоскости (как правило, ограниченной стенками), собирая еду , избегая столкновения с собственным хвостом и краями игрового поля. Каждый раз, когда змея съедает кусок пищи, она становится длиннее. Игрок управляет направлением движения головы змеи (обычно 4 направления: вверх, вниз, влево, вправо), а хвост змеи движется следом.
# Интерфейс
Это возможности управления персонажем, взаимодействия персонажей друг с другом, общения игроков между собой и т.д. Интерфейс игры состоит из игрового поля. С помощью клавиатуры игроки могут контролировать змею. Главная задача игрока помогать змею кушать больше еды.
## Игровое поле

# Структура директория
Код организован следующим образом:
Каталог | Описание
---------------- |--------------------------
src/ | файлы исходного кода
doc/ | документация
doc/res/ | ресурсы для документации
# Авторы
* **<NAME>** -<EMAIL>
* **<NAME>**-<EMAIL>
* **<NAME>** -<EMAIL>
# Лицензия
Этот проект лицензирован под MIT License - смотри LICENSE файл для подробностей
| 1bdd10ff97c6b0e17599519de9244b7dd9728fa3 | [
"Markdown",
"C"
] | 2 | C | TianYJ1/Snake | c561d1e172074c6ec8845fd66802326dfd167525 | b4e3b8a036153073e49157f23e39ee9fdbdf3390 |
refs/heads/master | <repo_name>pinyinc/pinyinc.github.io<file_sep>/pinyin.py
import sys
import string
"""
Create a data structure that can be globaly used and holds each vowel of every tone
"""
# Now you understand what is a promgramming 'chores'
vowels = {'a': ['a', 'ā', 'á', 'ǎ', 'à'],
'e': ['e', 'ē', 'é', 'ě', 'è'],
'i': ['i', 'ī', 'í', 'ǐ', 'ì'],
'o': ['o', 'ō', 'ó', 'ǒ', 'ò'],
'u': ['u', 'ū', 'ú', 'ǔ', 'ù'],
'ü': ['ü', 'ǖ', 'ǘ', 'ǚ', 'ǜ']}
def pinyin(word, punc):
"""
Parameters:
str: a string of word with number of tone at the end
Return:
str: a string of pinyin without the number at the end
Usage Examples:
>>> pinyin('hao3')
'hǎo'
"""
word = word.replace('v', 'ü')
punctuation = ''
while word[-1] in string.punctuation:
punctuation += word[-1]
word = word[:-1]
if word[-1].isdigit():
tone = int(word[-1])
word = word[:-1]
else:
return word + punctuation
vowel_to_change = ''
if 'a' in word:
vowel_to_change = 'a'
elif 'e' in word:
vowel_to_change = 'e'
elif 'i' in word:
vowel_to_change = 'i'
elif 'o' in word:
vowel_to_change = 'o'
elif 'u' in word:
vowel_to_change = 'u'
elif 'ü' in word:
vowel_to_change = 'ü'
else:
vowel_to_change = ''
if vowel_to_change:
new_word = word.replace(vowel_to_change, vowels[vowel_to_change][tone])
return new_word + punctuation
def convert(sentence):
"""
Takes in an input of sentence with words with tone number at each end.
Calls convert function to convert each word.
Then return the complete sentence of pinyin.
Parameters:
str: a string of sentence with multiple words
Return:
str: a string of sentence with multiple pinyin
Usage Examples:
>>> convert('ni3 hao3 ma1')
'nǐ hǎo mā'
"""
result = []
for word in sentence.split():
result.append(pinyin(word, ''))
return ' '.join(result)
def main():
if len(sys.argv) == 1:
"""
If runs with no argument, it asks for user input and print answer back
"""
sentence = input('Input: ')
result = convert(sentence)
print(result)
elif len(sys.argv) == 2:
"""
If runs with one argument, it expects a txt file to convert it and
output into another txt file named 'output.txt'
"""
print('1 arg')
else:
"""
If runs with more than one argument, that is an error
Or we can implement multiple file features but still
output into one file 'output.txt' separate by new line
"""
print('many args')
if __name__ == '__main__':
main()
<file_sep>/README.md
# A realtime PinYin Converter
##### Easy to use. Changes in realtime.
#### Just type the format: [word][number]
#### For example: ni2 hao3, This will print ní hǎo on the right.
#### Just keep typing!
| 8aa66d89e37e4eedf7f1fde915d92eb33b878fdc | [
"Markdown",
"Python"
] | 2 | Python | pinyinc/pinyinc.github.io | 141a9a2086e6463369e9904dd9168fa62e823e04 | 87e00cdeaa859992f77b9d4f78cfb23f4079c770 |
refs/heads/master | <repo_name>lukesilvia/zsh-peco-history<file_sep>/zsh-peco-history.zsh
# zsh-peco-history
# Search shell history with peco when pressing ctrl+r.
# https://github.com/jimeh/zsh-peco-history
#
# Based on: https://github.com/mooz/percol#zsh-history-search
# Get peco from: https://github.com/peco/peco
#
if which peco &> /dev/null; then
function peco_select_history() {
if which tac >/dev/null; then
BUFFER=`history -n 1 | tac | awk '!a[$0]++' | peco`
else
BUFFER=`history -n 1 | tail -r | awk '!a[$0]++' | peco`
fi
CURSOR=$#BUFFER # move cursor
zle -R -c # refresh
}
zle -N peco_select_history
bindkey '^R' peco_select_history
fi
| a740d7dcd29a41bd21f89e126af5c27f957cdf24 | [
"Shell"
] | 1 | Shell | lukesilvia/zsh-peco-history | 5e81b474a193220b6a3332b22f0c57151228b734 | ad67808e77536f6fec7ed89e63cb62432ccb604b |
refs/heads/master | <repo_name>sondh0127/doclabel<file_sep>/frontend/src/pages/project/task/service.js
import request from '@/utils/request';
import { PAGE_SIZE } from '@/pages/constants';
export async function fetchTask({ projectId, params, data }) {
return request(`/api/projects/${projectId}/docs/`, {
method: 'GET',
params: {
...params,
limit: PAGE_SIZE,
...data,
},
});
}
export async function removeTask({ projectId, taskId }) {
return request(`/api/projects/${projectId}/docs/${taskId}/`, {
method: 'DELETE',
});
}
export async function updateTask({ projectId, taskId, data }) {
return request(`/api/projects/${projectId}/docs/${taskId}`, {
method: 'PATCH',
data,
});
}
<file_sep>/doclabel/core/migrations/0013_auto_20191127_0835.py
# Generated by Django 2.2.6 on 2019-11-27 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_project_annotator_per_example'),
]
operations = [
migrations.AddField(
model_name='documentannotation',
name='finished',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='pdfannotation',
name='finished',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='seq2seqannotation',
name='finished',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='sequenceannotation',
name='finished',
field=models.BooleanField(default=False),
),
]
<file_sep>/frontend/src/pages/project/task/model.js
import { fetchTask, removeTask, updateTask } from './service';
import { getPageQuery, arrayToObject } from '@/utils/utils';
const Model = {
namespace: 'task',
state: {
list: {},
pagination: {},
},
effects: {
*fetch({ payload }, { call, put, take, select }) {
let projectId = yield select(state => state.project.currentProject.id);
if (!projectId) {
const action = yield take('project/saveCurrentProject');
projectId = action.payload.id;
}
const { params, data } = payload;
const response = yield call(fetchTask, { projectId, params, data });
const ret = {
list: arrayToObject(response.results, 'id'),
pagination: {
total: response.count,
next: response.next && getPageQuery(response.next),
previous: response.previous && getPageQuery(response.previous),
},
};
yield put({
type: 'save',
payload: ret,
});
return ret;
},
*remove({ payload }, { call, put, select, take }) {
let projectId = yield select(state => state.project.currentProject.id);
if (!projectId) {
const action = yield take('project/saveCurrentProject');
projectId = action.payload.id;
}
yield call(removeTask, { projectId, ...payload });
},
*update({ payload }, { call, put }) {
const response = yield call(updateTask, payload);
yield put({
type: 'save',
payload: response,
});
},
*reset(_, { put }) {
yield put({
type: 'save',
payload: {
list: {},
pagination: {},
},
});
},
},
reducers: {
save(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/models/project.js
import pathToRegexp from 'path-to-regexp';
import { queryCurrent, createProject } from '@/services/project';
import { arrayToObject } from '@/utils/utils';
import { setAuthority } from '@/utils/authority';
const UserModel = {
namespace: 'project',
state: {
currentProject: {},
list: [],
pagination: {},
},
effects: {
*fetchProject({ payload }, { call, put }) {
// payload ~ params
const response = yield call(queryCurrent, payload);
// console.log('TCL: *fetchProject -> response', response);
yield put({ type: 'saveCurrentProject', payload: response });
return response;
},
*createProject({ payload }, { call, put }) {
const res = yield call(createProject, payload);
const ret = res;
yield put({
type: 'changeProjectState',
payload: ret,
});
return ret;
},
*cleanProject({ payload }, { put }) {
yield put({
type: 'saveCurrentProject',
payload: {},
});
},
},
reducers: {
saveCurrentProject(state, { payload }) {
const authority =
Object.keys(payload).length > 0
? Object.keys(payload.current_users_role).filter(item => payload.current_users_role[item])
: '';
setAuthority(authority);
return { ...state, currentProject: payload || {} };
},
changeProjectState(state, action) {
return { ...state, ...action.payload };
},
},
// subscriptions: {
// setup({ dispatch, history }) {
// return history.listen(({ pathname, query }) => {
// const match = pathToRegexp('/projects/:id/(.*)').exec(pathname);
// if (match && history.action === 'POP') {
// dispatch({
// type: 'fetchProject',
// payload: match[1],
// });
// }
// });
// },
// },
};
export default UserModel;
<file_sep>/frontend/src/pages/Home/components/TopBanner.jsx
import React from 'react';
import { GithubOutlined } from '@ant-design/icons';
import { Button, Row, Col, Typography } from 'antd';
import { Parallax } from 'react-parallax';
import { Link } from 'umi';
import styles from './index.less';
import logo from '@/assets/logo.svg';
function TopBanner(props) {
const image = 'https://zos.alipayobjects.com/rmsportal/hzPBTkqtFpLlWCi.jpg';
return (
<div className={styles.topBanner}>
<Parallax bgImage={image} strength={500}>
<div className={styles.wrapper}>
<Row
type="flex"
gutter={[0, 24]}
align="middle"
justify="center"
className={styles.content}
>
<Col xs={24} md={10} className={styles.logo}>
<img src={logo} alt="logo" />
</Col>
<Col xs={24} md={14}>
<Row type="flex" gutter={16} className={styles.text} justify="center">
<Col xs={24}>
<Typography.Title className={styles.title}>
The Text Annotation <br />
For Your Teams
</Typography.Title>
</Col>
<Col className={styles.btnExplore}>
<Button size="large" type="primary">
<Link to="/explore">Explore</Link>
</Button>
</Col>
<Col className={styles.btnGithub}>
<a href="https://github.com/sonstephendo/doclabel">
<Button size="large" type="default" icon={<GithubOutlined />}>
Github
</Button>
</a>
</Col>
</Row>
</Col>
</Row>
</div>
</Parallax>
</div>
);
}
export default React.memo(TopBanner);
<file_sep>/frontend/src/pages/project/dashboard/locales/en-US.js
export default {
'dashboard.progress': 'Project progress',
'dashboard.user': 'Contributors',
'dashboard.user-title': 'Annotations/User',
'dashboard.labels': 'Labels',
'dashboard.labels-title': 'Annotations/Label',
'dashboard.tasks': 'Tasks',
};
<file_sep>/frontend/src/layouts/SecurityLayout.jsx
import { connect } from 'dva';
import { stringify } from 'querystring';
import React from 'react';
import { Redirect } from 'umi';
import { PageLoading } from '@ant-design/pro-layout';
const SecurityLayout = props => {
const [isReady, setIsReady] = React.useState(false);
const { dispatch, children, loading, currentUser, location } = props;
const isHome = ['/home', '/explore', '/'].includes(location.pathname);
React.useEffect(() => {
const fetchCurrentUser = async () => {
try {
await dispatch({
type: 'user/fetchCurrent',
});
} catch (err) {
console.log('[DEBUG]: fetchCurrentUser -> err', err);
}
};
if (dispatch) {
fetchCurrentUser();
}
dispatch({
type: 'settings/changeTheme',
});
setIsReady(true);
}, []);
// You can replace it to your authentication rule (such as check token exists)
// const isLogin = getAuthorization() !== 'undefined' && getAuthorization() !== null;
const isLogin = currentUser && currentUser.id;
const queryString = stringify({
redirect: window.location.href,
});
if ((!isLogin && loading) || !isReady) {
return <PageLoading />;
}
if (!isLogin && !isHome) {
return <Redirect to={`/user/login?${queryString}`} />;
}
return children;
};
export default connect(({ user, loading, settings }) => ({
currentUser: user.currentUser,
loading: loading.models.user,
theme: settings.themeName,
}))(SecurityLayout);
<file_sep>/frontend/src/pages/user/permission/components/UserModal.jsx
import React, { Component } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, Select } from 'antd';
const FormItem = Form.Item;
const { Option } = Select;
@connect(stores => ({
usersDetail: stores.usersDetail,
}))
@Form.create()
class UserModal extends Component {
render() {
const {
dispatch,
form: { getFieldDecorator, validateFields },
onCancel = () => {},
visible,
recordData = {},
} = this.props;
const formItemLayout = {
// 表单的栅格行配置
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
return (
<Modal
title="编辑用户信息"
visible={visible}
onOk={() => {
validateFields((errors, values) => {
if (errors) {
return;
}
const params = {
userId: recordData.userId,
role: values.role,
};
dispatch({ type: 'usersDetail/assignRole', payload: params }).then(errCode => {
if (!errCode) {
dispatch({ type: 'usersDetail/queryUsersList' });
onCancel();
}
});
});
}}
onCancel={onCancel}
destroyOnClose
>
<FormItem label="账号" {...formItemLayout}>
{getFieldDecorator('username', {
initialValue: recordData.userName,
})(<Input disabled />)}
</FormItem>
<FormItem label="角色" {...formItemLayout}>
{getFieldDecorator('role', {
rules: [{ required: true, message: '请选择角色!' }],
initialValue: recordData.role,
})(
<Select style={{ width: 120 }}>
<Option value="admin">超级管理员</Option>
<Option value="user">普通用户</Option>
<Option value="guest">游客</Option>
</Select>,
)}
</FormItem>
</Modal>
);
}
}
export default UserModal;
<file_sep>/frontend/src/layouts/ProjectLayout.jsx
/**
* Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
* You can view component api by:
* https://github.com/ant-design/ant-design-pro-layout
*/
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect } from 'react';
import { Link, router } from 'umi';
import { connect } from 'dva';
import { ArrowLeftOutlined, GithubOutlined } from '@ant-design/icons';
import { Result, Button, Spin, List, Typography } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import Authorized, { reloadAuthorized } from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { isAntDesignPro, getAuthorityFromRouter } from '@/utils/utils';
import logo from '../assets/logo.svg';
import LayoutFooter from './components/LayoutFooter';
/**
* use Authorized check all menu item
*/
const noMatch = (
<Result
status="403"
title="403"
subTitle="Sorry, you are not authorized to access this page."
extra={
<Button type="primary">
<Link to="/user/login">Go Login</Link>
</Button>
}
/>
);
const menuDataRender = menuList =>
menuList.map(item => {
const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
return Authorized.check(item.authority, localItem, null);
});
const ProjectLayout = connect(({ global, settings, loading }) => ({
collapsed: global.collapsed,
settings,
loading: loading.effects['project/fetchProject'],
}))(props => {
const {
dispatch,
children,
settings,
match,
location = {
pathname: '/app',
},
loading,
} = props;
/**
* constructor
*/
const [isReady, setIsReady] = React.useState(false);
const fetchCurrentProject = async () => {
const res = await dispatch({
type: 'project/fetchProject',
payload: match.params.id,
});
reloadAuthorized();
setIsReady(true);
// if (!res.current_users_role.is_project_admin) {
// router.push('/exception/403');
// }
};
useEffect(() => {
if (dispatch) {
fetchCurrentProject();
dispatch({
type: 'settings/getSetting',
});
}
}, []);
/**
* init variables
*/
const handleMenuCollapse = payload => {
if (dispatch) {
dispatch({
type: 'global/changeLayoutCollapsed',
payload,
});
}
};
// get children authority
const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
authority: undefined,
};
const isLoading = loading || !isReady;
return (
<ProLayout
logo={logo}
onCollapse={handleMenuCollapse}
links={[
<Link to="/account/center">
<ArrowLeftOutlined /> Center
</Link>,
]}
menuDataRender={menuDataRender}
menuItemRender={(menuItemProps, defaultDom) => {
if (menuItemProps.isUrl || menuItemProps.children) {
return defaultDom;
}
let { path } = menuItemProps;
if (match.path !== match.url) {
// Compute the right path
Object.keys(match.params).forEach(key => {
path = path.replace(`:${key}`, match.params[key]);
});
}
return <Link to={path}>{defaultDom}</Link>;
}}
breadcrumbRender={(routers = []) => [...routers]}
// Antd Breadcrumb
itemRender={(route, params, routes, paths) => {
const first = routes.indexOf(route) === 0;
return first ? (
<Link to={paths.join('/')}>{route.breadcrumbName}</Link>
) : (
<span>{route.breadcrumbName}</span>
);
}}
footerRender={<LayoutFooter />}
formatMessage={formatMessage}
rightContentRender={rightProps => <RightContent {...rightProps} />}
{...props}
{...settings}
layout="sidemenu"
fixedHeader={false}
>
{!isLoading && (
<Authorized authority={authorized.authority} noMatch={noMatch}>
{children}
</Authorized>
)}
</ProLayout>
);
});
export default ProjectLayout;
<file_sep>/frontend/config/routes.ts
import { IRoute } from 'umi-types';
export default [
{
path: '/user',
component: '../layouts/UserLayout',
routes: [
{
name: 'permission',
path: '/user/permission',
component: './user/permission',
},
{
name: 'login',
path: '/user/login',
component: './user/login',
},
{
name: 'register',
path: '/user/register',
component: './user/register',
},
{
name: 'register-result',
path: '/user/register-result',
component: './user/register-result',
},
{
name: 'activation',
path: '/user/activation/:uid/:token',
component: './user/auth/Activation',
},
{
name: 'resend-activation',
path: '/user/resend-activation',
component: './user/auth/ResendActivation',
},
{
name: 'oauth',
path: '/user/oauth/:provider',
component: './user/auth/OAuthLogin',
},
{
name: 'reset-password',
path: '/user/reset-password',
component: './user/auth/ResetPassword',
},
{
name: 'reset-password-confirm',
path: '/user/reset-password/confirm/:uid/:token',
component: './user/auth/ResetPasswordConfirm',
},
{
component: './exception/404',
},
],
},
{
path: '/exception',
routes: [
{
name: '403',
path: '/exception/403',
component: './exception/403',
},
{
name: '404',
path: '/exception/404',
component: './exception/404',
},
{
name: '500',
path: '/exception/500',
component: './exception/500',
},
],
},
{
path: '/',
component: '../layouts/SecurityLayout',
routes: [
{
path: '/projects/:id',
component: '../layouts/ProjectLayout',
routes: [
{
path: '/projects/:id',
redirect: '/projects/:id/dashboard',
},
{
name: 'dashboard',
icon: 'project',
path: '/projects/:id/dashboard',
component: './project/dashboard',
authority: ['is_project_admin'],
},
{
name: 'task',
icon: 'database',
path: '/projects/:id/task',
component: './project/task',
authority: ['is_project_admin'],
},
{
name: 'label',
icon: 'flag',
path: '/projects/:id/label',
component: './project/label',
authority: ['is_project_admin'],
},
{
name: 'contributor',
icon: 'team',
path: '/projects/:id/contributor',
component: './project/contributor',
authority: ['is_project_admin'],
},
{
name: 'export',
icon: 'cloud-download',
path: '/projects/:id/export',
component: './project/export',
authority: ['is_project_admin'],
},
{
name: 'guide',
icon: 'deployment-unit',
path: '/projects/:id/guide',
component: './project/guide',
authority: ['is_project_admin'],
},
{
name: 'setting',
icon: 'setting',
path: '/projects/:id/setting',
component: './project/setting',
authority: ['is_project_admin'],
},
],
},
{
path: '/annotation/:id',
component: '../layouts/AnnotationLayout',
routes: [
{
name: 'annotation',
hideInMenu: true,
path: '/annotation/:id',
component: './annotation',
authority: ['is_project_admin', 'is_annotator', 'is_annotation_approver'],
},
],
},
{
path: '/',
component: '../layouts/BasicLayout',
routes: [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'home',
icon: 'home',
component: './Home',
},
{
name: 'explore',
icon: 'monitor',
path: '/explore',
component: './explore',
},
{
name: 'account-center',
path: '/account/center',
icon: 'smile',
component: './account/center',
},
{
name: 'account-settings',
hideInMenu: true,
path: '/account/settings',
component: './account/settings',
},
],
},
{
component: './exception/404',
},
],
},
{
component: './exception/404',
},
] as IRoute[];
<file_sep>/frontend/src/pages/project/dashboard/components/TaskInfo/index.jsx
import { Col, Row, Typography } from 'antd';
import classNames from 'classnames';
import React from 'react';
import Pie from '../Pie';
import styles from './index.less';
const TaskInfo = ({ task, theme }) => {
const { text, total, remaining } = task;
const percent = Math.min(Math.floor(((total - remaining) / total) * 100), 100);
const suffix = '%';
return (
<Row
gutter={8}
className={classNames(styles.numberInfo, {
[styles[`numberInfo${theme}`]]: theme,
})}
style={{
width: 138,
}}
type="flex"
>
<Col
span={24}
className={styles.numberInfoTitle}
title={typeof text === 'string' ? text : ''}
>
<Typography.Paragraph ellipsis>{text}</Typography.Paragraph>
</Col>
<Col span={12} className={styles.numberInfoValue}>
<span>
{percent}
{suffix && <em className={styles.suffix}>{suffix}</em>}
</span>
</Col>
<Col span={12} className={styles.numberInfoChart}>
<Pie
animate={false}
inner={0.55}
tooltip={false}
margin={[0, 0, 0, 0]}
percent={percent}
height={64}
/>
</Col>
</Row>
);
};
export default TaskInfo;
<file_sep>/Makefile
.DEFAULT_GOAL := help
### QUICK
# ¯¯¯¯¯¯¯
start: server.start
include makefiles/server.mk
include makefiles/database.mk
include makefiles/help.mk
<file_sep>/frontend/src/pages/account/settings/data.d.ts
export interface TagType {
key: string;
label: string;
}
export interface GeographicItemType {
name: string;
id: string;
}
export interface NoticeType {
id: string;
title: string;
logo: string;
description: string;
updatedAt: string;
member: string;
href: string;
memberLink: string;
}
export interface CurrentUser {
id: number;
email: string;
full_name: string;
avatar: string;
username: string;
//
notice: NoticeType[];
tags: TagType[];
notifyCount: number;
unreadCount: number;
}
<file_sep>/frontend/src/models/setting.js
import { message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import defaultSettings from '../../config/defaultSettings';
const updateColorWeak = colorWeak => {
const root = document.getElementById('root');
if (root) {
root.className = colorWeak ? 'colorWeak' : '';
}
};
const SettingModel = {
namespace: 'settings',
state: defaultSettings,
reducers: {
getSetting(state = defaultSettings) {
const setting = {};
const urlParams = new URL(window.location.href);
Object.keys(state).forEach(key => {
if (urlParams.searchParams.has(key)) {
const value = urlParams.searchParams.get(key);
setting[key] = value;
}
});
const { colorWeak } = setting;
updateColorWeak(!!colorWeak);
return { ...state, ...setting };
},
changeSetting(state = defaultSettings, { payload }) {
const { colorWeak, contentWidth } = payload;
if (state.contentWidth !== contentWidth && window.dispatchEvent) {
window.dispatchEvent(new Event('resize'));
}
updateColorWeak(!!colorWeak);
return { ...state, ...payload };
},
changeTheme(state = defaultSettings, { payload }) {
let newTheme;
if (payload && Object.keys(payload)) {
newTheme = payload;
} else {
const themeCache = localStorage.getItem('site-theme');
newTheme = themeCache || state.navTheme;
}
const dark = newTheme === 'dark';
if (typeof window === 'undefined') {
return { ...state };
}
// message.loading(
// formatMessage({
// id: 'app.setting.loading',
// defaultMessage: 'Loading theme.',
// }),
// 0.5,
// );
const href = dark ? '/theme/dark' : '/theme/';
const dom = document.getElementById('theme-style');
if (!href) {
if (dom) {
dom.remove();
localStorage.removeItem('site-theme');
}
return { ...state };
}
const url = `${href}.css`;
if (dom) {
dom.onload = () => {
window.setTimeout(() => {});
};
dom.href = url;
} else {
const style = document.createElement('link');
style.type = 'text/css';
style.rel = 'stylesheet';
style.id = 'theme-style';
style.onload = () => {
window.setTimeout(() => {
// hide();
});
};
style.href = url;
document.body.append(style);
}
localStorage.setItem('site-theme', dark ? 'dark' : 'light');
return { ...state, navTheme: dark ? 'dark' : 'light' };
},
},
};
export default SettingModel;
<file_sep>/frontend/src/pages/project/guide/model.js
import { updateGuideline } from './service';
const Model = {
namespace: 'guide',
state: {},
effects: {
*updateGuideline({ payload }, { call, put, select, take }) {
let projectId = yield select(state => state.project.currentProject.id);
if (!projectId) {
const action = yield take('project/saveCurrentProject');
projectId = action.payload.id;
}
const response = yield call(updateGuideline, { projectId, data: payload });
yield put({
type: 'project/saveCurrentProject',
payload: response,
});
return response;
},
},
reducers: {
changeGuide(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/utils/utils.ts
import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { Route } from '@/models/connect';
import { FieldData } from 'rc-field-form/lib/interface';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path: string) => reg.test(path);
export const isAntDesignPro = (): boolean => {
if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
return true;
}
return window.location.hostname === 'preview.pro.ant.design';
};
/**
* Used for official demo sites to turn off features that are not needed in real-world
* development environments
*/
export const isAntDesignProOrDev = (): boolean => {
const { NODE_ENV } = process.env;
if (NODE_ENV === 'development') {
return true;
}
return isAntDesignPro();
};
export const getPageQuery = (href?: string) => {
let url = href;
if (!url) {
url = window.location.href;
}
return parse(url.split('?')[1]);
};
/**
* props.route.routes
* @param router [{}]
* @param pathname string
*/
export const getAuthorityFromRouter = <T extends Route>(
router: T[] = [],
pathname: string,
): T | undefined => {
const authority = router.find(
({ routes, path = '/' }) =>
(path && pathRegexp(path).exec(pathname)) ||
(routes && getAuthorityFromRouter(routes, pathname)),
);
if (authority) return authority;
return undefined;
};
export const arrayToObject = <T>(array: T[], keyField: string) =>
array.reduce((obj, item) => {
const newObj = { ...obj };
newObj[item[keyField]] = item;
return newObj;
}, {});
export const getFieldsFromErrorData: (
err: {
data: Record<string, Array<string>>;
},
values: {
[name: string]: any;
},
) => FieldData[] = ({ data }, values) => {
const valueWithError: FieldData[] = [];
Object.entries(data).forEach(([key, val]) => {
valueWithError.push({
name: key,
value: values[key],
errors: val,
});
});
return valueWithError;
};
<file_sep>/frontend/src/pages/user/auth/locales/en-US.ts
export default {
'user-activation.verify-email': 'Activate account',
'user-activation.result.msg': 'Please click confirm to activate your account!',
'user-activation.confirm': 'Confirm',
'user-resend-activation.email.sent': 'Activation email has been sent to your email!',
'user-resend-activation.email.required': 'Please enter your email!',
'user-resend-activation.email.wrong-format': 'The email address is in the wrong format!',
'user-resend-activation.email.placeholder': 'Your email',
'user-reset-password.email.sent': 'Reset password link has been sent to',
'user-reset-password.email.success': 'Your password has been changed successfully!',
'user-reset-password.go-login': 'Go to login',
'user-reset-password.go-home': 'Go home',
'user-reset-password.password.twice': 'The new passwords entered twice do not match!',
'user-reset-password.password.new-password': '<PASSWORD>',
'user-reset-password.password.re-new-password': '<PASSWORD>',
};
<file_sep>/makefiles/database.mk
# ### DATABASE
# # ¯¯¯¯¯¯¯¯
database.migrate: ## Create alembic migration file
docker-compose -f local.yml run django python manage.py migrate
database.createsuperuser:
docker-compose -f local.yml run django python manage.py createsuperuser
<file_sep>/doclabel/core/views.py
from django.conf import settings
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404, redirect
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Count, F, Q
from libcloud.base import DriverType, get_driver
from libcloud.storage.types import ContainerDoesNotExistError, ObjectDoesNotExistError
from django.core.files.storage import FileSystemStorage
from rest_framework import generics, filters, status, viewsets
from rest_framework.exceptions import ParseError, ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework_csv.renderers import CSVRenderer
from rest_framework import serializers
from notifications.models import Notification
from notifications.signals import notify
from .filters import DocumentFilter, ProjectFilter
from .models import Project, Label, Document, RoleMapping, Role, SEQ2SEQ
from .permissions import (
IsProjectAdmin,
IsAnnotatorAndReadOnly,
IsAnnotator,
IsAnnotationApproverAndReadOnly,
IsOwnAnnotation,
IsAnnotationApprover,
)
from .serializers import (
ProjectSerializer,
LabelSerializer,
DocumentSerializer,
# UserSerializer,
NotificationSerializer,
)
from .serializers import (
ProjectPolymorphicSerializer,
RoleMappingSerializer,
RoleSerializer,
)
from .utils import (
CSVParser,
ExcelParser,
JSONParser,
PlainTextParser,
CoNLLParser,
iterable_to_io,
to_file,
)
from .utils import JSONLRenderer
from .utils import JSONPainter, CSVPainter
User = get_user_model()
IsInProjectReadOnlyOrAdmin = (
IsAnnotatorAndReadOnly | IsAnnotationApproverAndReadOnly | IsProjectAdmin
)
IsInProjectOrAdmin = IsAnnotator | IsAnnotationApprover | IsProjectAdmin
IsInProjectReadOnlyOrAdmin2 = (
IsAnnotator | IsAnnotationApproverAndReadOnly | IsProjectAdmin
)
class Features(APIView):
def get(self, request, *args, **kwargs):
return Response(
{"cloud_upload": bool(settings.CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER)}
)
class ProjectList(generics.ListCreateAPIView):
serializer_class = ProjectPolymorphicSerializer
permission_classes = [IsInProjectReadOnlyOrAdmin]
filter_backends = (
DjangoFilterBackend, # importance
filters.SearchFilter,
filters.OrderingFilter,
)
search_fields = (
"name",
"description",
)
# ordering_fields = (
# "created_at",
# "updated_at",
# "doc_annotations__updated_at",
# "seq_annotations__updated_at",
# "seq2seq_annotations__updated_at",
# )
filter_class = ProjectFilter
def get_queryset(self):
# Filter public only (published project)
queryset = Project.objects.filter(public=True)
return queryset
def perform_create(self, serializer):
# perform addition method, this will add a user to users list
serializer.save(users=[self.request.user])
class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
lookup_url_kwarg = "project_id"
permission_classes = [IsInProjectReadOnlyOrAdmin]
def update(self, request, *args, **kwargs):
instance = self.get_object()
# Unable to publish project if missing data
if request.data.get("public"):
labels = instance.labels.count()
documents = instance.documents.count()
project_type = instance.project_type
if not documents:
return Response(
data={"public": "Unable to publish project! Missing dataset!"},
status=status.HTTP_400_BAD_REQUEST,
)
if not labels and project_type != SEQ2SEQ:
return Response(
data={"public": "Unable to publish project! Missing label!"},
status=status.HTTP_400_BAD_REQUEST,
)
# Unable to change project type
if request.data.get("project_type"):
return Response(
data={"project_type": "Unable to change the project category"},
status=status.HTTP_400_BAD_REQUEST,
)
return super().update(request, *args, **kwargs)
class StatisticsAPI(APIView):
pagination_class = None
permission_classes = [IsInProjectReadOnlyOrAdmin]
def get(self, request, *args, **kwargs):
p = get_object_or_404(Project, pk=self.kwargs["project_id"])
include = set(request.GET.getlist("include"))
user = request.GET.get("user")
response = {}
if "user_progress" in include:
user = user if user else self.request.user
user_progress = self.annotator_progress(project=p, user=user)
response.update(user_progress)
if not include or "label" in include or "user" in include:
label_count, user_count = self.label_per_data(p)
response["label"] = label_count
response["user"] = user_count
if not include or "project_proggress" in include:
project_proggress = self.project_proggress(project=p)
response.update(project_proggress)
# if include:
# response = {
# key: value for (key, value) in response.items() if key in include
# }
return Response(response)
def annotator_progress(self, project, user):
docs = project.documents
annotation_class = project.get_annotation_class()
total = docs.count()
done = annotation_class.objects.filter(
document_id__in=docs.all(), user_id=user
).aggregate(Count("document", distinct=True))["document__count"]
remaining = total - done
return {"total": total, "remaining": remaining}
def project_proggress(self, project):
docs = project.documents
annotator_per_example = project.annotator_per_example
annotation_class = project.get_annotation_class()
aggregatation = {}
for val in docs.all().values_list("id", flat=True):
aggregatation[str(val)] = Count(
"user", distinct=True, filter=Q(document_id=val)
)
annotation_docs = annotation_class.objects.filter(
document_id__in=docs.all()
).aggregate(**aggregatation)
total = docs.count() * annotator_per_example
done = sum(annotation_docs.values())
remaining = total - done
docs_stat = {}
for doc in docs.all():
docs_stat[doc.id] = {
"id": doc.id,
"text": doc.text,
"total": annotator_per_example,
"remaining": annotator_per_example - annotation_docs[str(doc.id)],
}
return {"total": total, "remaining": remaining, "docs_stat": docs_stat}
def label_per_data(self, project):
annotation_class = project.get_annotation_class()
return annotation_class.objects.get_label_per_data(project=project)
class ApproveLabelsAPI(APIView):
permission_classes = [IsAnnotationApprover | IsProjectAdmin]
def post(self, request, *args, **kwargs):
prob = self.request.data.get("prob", 1)
user = self.request.data.get("user")
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
annotation_class = project.get_annotation_class()
annotation_serializer = project.get_annotation_serializer()
query = annotation_class.objects.filter(
document_id=self.kwargs["doc_id"], user_id=user
)
query.update(prob=prob)
for anno in query:
anno.save()
data = annotation_serializer(
query, many=True, context={"request": request}
).data
return Response(data)
class LabelList(generics.ListCreateAPIView):
serializer_class = LabelSerializer
pagination_class = None
permission_classes = [IsInProjectReadOnlyOrAdmin]
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
return project.labels
# TODO: check working or not
def create(self, request, *args, **kwargs):
request.data["project"] = self.kwargs["project_id"]
return super().create(request, args, kwargs)
def perform_create(self, serializer):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
serializer.save(project=project)
class LabelDetail(generics.RetrieveUpdateDestroyAPIView):
# queryset = Label.objects.all()
serializer_class = LabelSerializer
lookup_url_kwarg = "label_id"
permission_classes = [IsInProjectReadOnlyOrAdmin]
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
return project.labels
class DocumentList(generics.ListCreateAPIView):
serializer_class = DocumentSerializer
filter_backends = (
DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
)
search_fields = ("text",)
ordering_fields = (
"created_at",
"updated_at",
"doc_annotations__updated_at",
"seq_annotations__updated_at",
"seq2seq_annotations__updated_at",
)
filter_class = DocumentFilter
permission_classes = [IsInProjectReadOnlyOrAdmin]
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
queryset = project.documents
# TODO: Dont make random order if admin request
# if project.randomize_document_order:
# queryset = queryset.annotate(
# sort_id=F("id") % self.request.user.id
# ).order_by("sort_id")
return queryset
def perform_create(self, serializer):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
serializer.save(project=project)
class DocumentDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Document.objects.all()
serializer_class = DocumentSerializer
lookup_url_kwarg = "doc_id"
permission_classes = [IsInProjectReadOnlyOrAdmin]
class AnnotationList(generics.ListCreateAPIView):
pagination_class = None
permission_classes = [IsInProjectReadOnlyOrAdmin2]
def get_serializer_class(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
self.serializer_class = project.get_annotation_serializer()
return self.serializer_class
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
model = project.get_annotation_class()
queryset = model.objects.filter(document=self.kwargs["doc_id"])
role = RoleMapping.objects.get(user=self.request.user, project=project).role
# If approver
if role.name == settings.ROLE_ANNOTATION_APPROVER:
user = get_object_or_404(User, pk=self.request.data["user"])
queryset = queryset.filter(user=user)
else:
# if not project.collaborative_annotation:
queryset = queryset.filter(user=self.request.user)
return queryset
def create(self, request, *args, **kwargs):
project = get_object_or_404(Project, pk=kwargs["project_id"])
annotation_class = project.get_annotation_class()
queryset = annotation_class.objects.filter(
document_id__in=project.documents.all(),
user_id=self.request.user,
finished=True,
)
if queryset:
return Response(
"Cant not change finished annotation!",
status=status.HTTP_400_BAD_REQUEST,
)
request.data["document"] = self.kwargs["doc_id"]
# pdf case
if request.data.get("content"):
content = request.data["content"]
if content.get("image"):
image = to_file(content["image"])
fs = FileSystemStorage(
location=settings.MEDIA_ROOT
+ "/pdf_annotations/doc_"
+ str(self.kwargs["doc_id"])
+ "/",
)
filename = fs.save(image.name, image)
content["image"] = filename
request.data["content"] = content
return super().create(request, args, kwargs)
def perform_create(self, serializer):
serializer.save(document_id=self.kwargs["doc_id"], user=self.request.user)
class AnnotationCompleted(APIView):
def patch(self, request, *args, **kwargs):
project = get_object_or_404(Project, pk=kwargs["project_id"])
docs = project.documents
annotation_class = project.get_annotation_class()
annotation_serializer = project.get_annotation_serializer()
total = docs.count()
query = annotation_class.objects.filter(
document_id__in=docs.all(), user_id=self.request.user
)
done = query.aggregate(Count("document", distinct=True))["document__count"]
if total != done:
return Response(
"The taskset is not completed.", status=status.HTTP_400_BAD_REQUEST
)
query.update(finished=True)
for anno in query:
anno.save()
data = annotation_serializer(
query, many=True, context={"request": request}
).data
return Response(data=data, status=status.HTTP_201_CREATED)
class AnnotationDetail(generics.RetrieveUpdateDestroyAPIView):
lookup_url_kwarg = "annotation_id"
permission_classes = [
((IsAnnotator | IsAnnotationApprover) & IsOwnAnnotation) | IsProjectAdmin
]
def get_serializer_class(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
self.serializer_class = project.get_annotation_serializer()
return self.serializer_class
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
model = project.get_annotation_class()
self.queryset = model.objects.all()
return self.queryset
def update(self, request, *args, **kwargs):
instance = self.get_object()
if instance.finished:
return Response(
"Cant not change finished annotation!",
status=status.HTTP_400_BAD_REQUEST,
)
return super().update(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
if instance.finished:
return Response(
"Cant not change finished annotation!",
status=status.HTTP_400_BAD_REQUEST,
)
return super().destroy(request, *args, **kwargs)
class TextUploadAPI(APIView):
parser_classes = (MultiPartParser,)
permission_classes = [IsProjectAdmin]
def post(self, request, *args, **kwargs):
if "file" not in request.data:
raise ParseError("Empty content")
file_format = request.data["format"]
if file_format == "pdf":
file = request.data["file"]
fs = FileSystemStorage(location=settings.MEDIA_ROOT + "/pdf_documents/",)
filename = fs.save(file.name, file)
# save document
data = {
"text": filename,
}
serializer = DocumentSerializer(data=data)
serializer.is_valid(raise_exception=True)
project = get_object_or_404(Project, pk=kwargs["project_id"])
doc = serializer.save(project=project)
ret_data = DocumentSerializer(doc, context={"request": request}).data
return Response(data=ret_data, status=status.HTTP_201_CREATED)
else:
# save doccument + create existence label
self.save_file(
user=request.user,
file=request.data["file"],
file_format=file_format,
project_id=kwargs["project_id"],
)
return Response(status=status.HTTP_201_CREATED)
@classmethod
def save_file(cls, user, file, file_format, project_id):
project = get_object_or_404(Project, pk=project_id)
parser = cls.select_parser(file_format)
data = parser.parse(file)
storage = project.get_storage(data)
storage.save(user)
@classmethod
def select_parser(cls, file_format):
if file_format == "plain":
return PlainTextParser()
elif file_format == "csv":
return CSVParser()
elif file_format == "json":
return JSONParser()
elif file_format == "conll":
return CoNLLParser()
elif file_format == "excel":
return ExcelParser()
else:
raise ValidationError("format {} is invalid.".format(file_format))
class CloudUploadAPI(APIView):
permission_classes = TextUploadAPI.permission_classes
def get(self, request, *args, **kwargs):
try:
project_id = request.query_params["project_id"]
file_format = request.query_params["upload_format"]
cloud_container = request.query_params["container"]
cloud_object = request.query_params["object"]
except KeyError as ex:
raise ValidationError("query parameter {} is missing".format(ex))
try:
cloud_file = self.get_cloud_object_as_io(cloud_container, cloud_object)
except ContainerDoesNotExistError:
raise ValidationError(
"cloud container {} does not exist".format(cloud_container)
)
except ObjectDoesNotExistError:
raise ValidationError("cloud object {} does not exist".format(cloud_object))
TextUploadAPI.save_file(
user=request.user,
file=cloud_file,
file_format=file_format,
project_id=project_id,
)
next_url = request.query_params.get("next")
if next_url == "about:blank":
return Response(
data="", content_type="text/plain", status=status.HTTP_201_CREATED
)
if next_url:
return redirect(next_url)
return Response(status=status.HTTP_201_CREATED)
@classmethod
def get_cloud_object_as_io(cls, container_name, object_name):
provider = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER.lower()
account = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_ACCOUNT
key = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_SECRET_KEY
driver = get_driver(DriverType.STORAGE, provider)
client = driver(account, key)
cloud_container = client.get_container(container_name)
cloud_object = cloud_container.get_object(object_name)
return iterable_to_io(cloud_object.as_stream())
class TextDownloadAPI(APIView):
permission_classes = TextUploadAPI.permission_classes
renderer_classes = (CSVRenderer, JSONLRenderer)
def get(self, request, *args, **kwargs):
format = request.query_params.get("q")
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
documents = project.documents.all()
serializer_data = DocumentSerializer(
documents, many=True, context={"request": request}
).data
# Label filter
labels = project.labels.all()
label_serializer_data = LabelSerializer(
labels, many=True, context={"request": request}
).data
painter = self.select_painter(format)
# json1 format prints text labels while json format prints annotations with label ids
# json1 format - "labels": [[0, 15, "PERSON"], ..]
# json format-"annotations":[{"label": 5,"start_offset": 0, "end_offset": 2, "user": 1},..]
data = painter.paint(serializer_data, label_serializer_data)
return Response(data)
def select_painter(self, format):
if format == "csv":
return CSVPainter()
elif format == "json" or format == "json1":
return JSONPainter()
else:
raise ValidationError("format {} is invalid.".format(format))
class Roles(generics.ListCreateAPIView):
serializer_class = RoleSerializer
pagination_class = None
permission_classes = [IsProjectAdmin]
queryset = Role.objects.all()
class RoleMappingList(generics.ListCreateAPIView):
serializer_class = RoleMappingSerializer
pagination_class = None
permission_classes = [IsProjectAdmin]
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
return project.role_mappings
def perform_create(self, serializer):
project = get_object_or_404(Project, pk=self.kwargs["project_id"])
# Perform unique role per user in one project
serializer.save(project=project)
class RoleMappingDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = RoleMapping.objects.all()
serializer_class = RoleMappingSerializer
lookup_url_kwarg = "rolemapping_id"
permission_classes = [IsProjectAdmin]
class NotificationList(APIView):
permission_classes = [IsProjectAdmin]
def get(self, request, *args, **kwargs):
queryset = request.user.notifications.unread().filter(
target_object_id=kwargs["project_id"]
)
serializer = NotificationSerializer(
queryset, many=True, context={"request": request}
)
return Response(serializer.data)
class RequestJoinProject(APIView):
def post(self, request, *args, **kwargs):
# If user in project then throw exception 400
request_user = request.user
project = Project.objects.get(pk=kwargs["project_id"])
try:
RoleMapping.objects.get(user=request_user, project=project)
return Response(
data={"You are already joined in this project."},
status=status.HTTP_400_BAD_REQUEST,
)
except RoleMapping.DoesNotExist:
qs = Notification.objects.filter(
actor_object_id=request_user.id,
target_object_id=project.id,
unread=True,
)
if qs.count() != 0:
return Response(
data={"You are already requested to join this project."},
status=status.HTTP_400_BAD_REQUEST,
)
else:
role_admin = Role.objects.get(name=settings.ROLE_PROJECT_ADMIN)
project_admins = User.objects.filter(
role_mappings__project=kwargs["project_id"],
role_mappings__role=role_admin,
)
requestRole = Role.objects.get(name=request.data["role"])
notify.send(
request_user,
recipient=project_admins,
verb="request to join project as",
action_object=requestRole,
target=project,
public=False,
)
return Response(status=status.HTTP_201_CREATED)
class NotificationDetail(APIView):
permission_classes = [IsProjectAdmin]
def delete(self, request, *args, **kwargs):
# mark all "notify" sent by "actor" user to target "project" related to notification id
notify = get_object_or_404(Notification, pk=kwargs["notify_id"])
qs = Notification.objects.filter(
actor_object_id=notify.actor.id, target_object_id=kwargs["project_id"]
)
qs.mark_all_as_read()
return Response(status=status.HTTP_204_NO_CONTENT)
class UserNotifications(APIView):
# authenticated user
def get(self, request, *args, **kwargs):
request_user = request.user
queryset = request_user.notifications.all()
return Response(
data=NotificationSerializer(
queryset, many=True, context={"request": request}
).data
)
class NotificationViewSet(viewsets.ViewSet):
serializer_class = NotificationSerializer
def list(self, request):
queryset = Notification.objects.unread()
return Response(
NotificationSerializer(
queryset, many=True, context={"request": request}
).data
)
<file_sep>/frontend/src/pages/project/export/index.jsx
import { DownloadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Modal, Radio, Spin, Card, Popconfirm, Select } from 'antd';
import { connect } from 'dva';
import React, { useState, useEffect, useMemo } from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { darcula } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './index.less';
import StandardTable from './components/StandardTable';
const CodeBlock = ({ language, value }) => (
<SyntaxHighlighter language={language} style={darcula}>
{value}
</SyntaxHighlighter>
);
const FormItem = Form.Item;
const { Option } = Select;
const Extract = ({ dispatch, loading, currentProject, location: { query } }) => {
// Form Data
const [format, setFormat] = useState('json');
const [userId, setUserId] = useState(null); // all users
//
const [modalVisible, setModalVisible] = useState(false);
const [selectedRows, setSelectedRows] = useState([]);
const handleDownload = async () => {
try {
const payload = userId ? { format, userId } : { format };
const res = await dispatch({
type: 'extract/download',
payload,
});
const url = window.URL.createObjectURL(new Blob([res]));
const link = document.createElement('a');
link.href = url;
link.setAttribute(
'download',
`${currentProject.name}-${userId ? `${userId}` : 'all'}.${
format === 'json' ? 'jsonl' : format
}`,
);
document.body.appendChild(link);
link.click();
} catch (err) {
console.log('[DEBUG]: handleDownload -> err', err);
}
};
const fetchTasks = async () => {
try {
const params = {};
const data = {};
const res = await dispatch({
type: 'task/fetch',
payload: { params, data },
});
console.log('[DEBUG]: fetchTasks -> res', res);
} catch (err) {
console.log('[DEBUG]: fetchTasks -> err', err);
}
};
useEffect(() => {
// effect
fetchTasks();
return () => {
// cleanup
};
}, []);
// useEffect(() => {
// if (currentProject && currentProject.id) {
// setUserId(currentProject.users[0]);
// }
// return () => {};
// }, [currentProject]);
const handleRemoveTask = () => {};
const columns = [
{
title: '#',
dataIndex: 'id',
},
{
title: 'Text',
dataIndex: 'text',
},
{
title: 'Contributor',
render: () => <div>Contributor</div>,
},
// {
// title: 'Annotation approver',
// dataIndex: 'annotation_approver',
// render: (text, record) => {},
// },
{
title: 'Operation',
render: (text, record) => (
<React.Fragment>
{/* <Divider type="vertical" /> */}
<Popconfirm
title="Are you sure delete this task?"
onConfirm={() => handleRemoveTask(record)}
okText="Yes"
cancelText="No"
>
<a href="#">Delete</a>
</Popconfirm>
</React.Fragment>
),
},
];
const handleStandardTableChange = () => {};
const taskTransform = () => {};
const handleSelectRows = () => {};
const hasData =
currentProject && Array.isArray(currentProject.users) && currentProject.users.length > 0;
return (
<div className={styles.main}>
<PageHeaderWrapper
title="Export data"
content={
<Button icon={<DownloadOutlined />} type="primary" onClick={() => setModalVisible(true)}>
Download
</Button>
}
>
<Card bordered={false} title="Feature export individual task data: TODO">
<div className={styles.tableList}>
{/* <div className={styles.tableListForm}>{renderForm()}</div> */}
<div className={styles.tableListOperator}>
{/* {selectedRows.length > 0 && (
<span>
<Dropdown overlay={menu}>
<Button>
More operations <Icon type="down" />
</Button>
</Dropdown>
</span>
)} */}
</div>
<StandardTable
rowKey={record => record.id}
selectedRows={selectedRows}
loading={loading}
data={taskTransform}
columns={columns}
onSelectRow={handleSelectRows}
onChange={handleStandardTableChange}
defaultCurrent={Number(query.page)}
/>
</div>
</Card>
<Modal
destroyOnClose
title="Download Annotation Data"
visible={modalVisible}
footer={null}
width={600}
onCancel={() => setModalVisible(false)}
>
<Spin spinning={!!loading}>
<Form layout="horizontal">
<FormItem
labelCol={{
span: 3,
}}
wrapperCol={{
span: 17,
}}
label="Format"
>
<Radio.Group
buttonStyle="solid"
value={format}
onChange={e => setFormat(e.target.value)}
>
<Radio.Button value="json">JSON</Radio.Button>
<Radio.Button value="csv">CSV</Radio.Button>
</Radio.Group>
</FormItem>
<FormItem
labelCol={{
span: 3,
}}
wrapperCol={{
span: 17,
}}
label="User"
>
<Select
defaultValue={null}
style={{ width: 130 }}
onChange={value => {
setUserId(value);
}}
>
<Option value={null}>All</Option>
{hasData &&
currentProject.users.map(({ id, username }) => (
<Option key={id} value={id}>
{username}
</Option>
))}
</Select>
</FormItem>
{/* <div style={{ margin: '24px 0' }}>
{format && <CodeBlock value={format} language={format} />}
</div> */}
<FormItem
wrapperCol={{
span: 17,
offset: 3,
}}
>
<Button type="primary" onClick={handleDownload}>
<DownloadOutlined /> Download
</Button>
</FormItem>
</Form>
</Spin>
</Modal>
</PageHeaderWrapper>
</div>
);
};
export default connect(({ project, loading }) => ({
currentProject: project.currentProject,
loading: loading.models.extract,
}))(Extract);
<file_sep>/doclabel/core/filters.py
from django.db.models import Count, Q
from django_filters import rest_framework as filters
from django.conf import settings
from .models import Document, PROJECT_CHOICES, Project, Role, RoleMapping
class DocumentFilter(filters.FilterSet):
seq_annotations__isnull = filters.BooleanFilter(
field_name="seq_annotations", method="filter_annotations"
)
doc_annotations__isnull = filters.BooleanFilter(
field_name="doc_annotations", method="filter_annotations"
)
seq2seq_annotations__isnull = filters.BooleanFilter(
field_name="seq2seq_annotations", method="filter_annotations"
)
def filter_annotations(self, queryset, field_name, value):
queryset = queryset.annotate(
num_annotations=Count(
field_name, filter=Q(**{f"{field_name}__user": self.request.user})
)
)
should_have_annotations = not value
if should_have_annotations:
queryset = queryset.filter(num_annotations__gte=1)
else:
queryset = queryset.filter(num_annotations__lte=0)
return queryset
class Meta:
model = Document
fields = (
"project",
"text",
"meta",
"created_at",
"updated_at",
"doc_annotations__label__id",
"seq_annotations__label__id",
"doc_annotations__isnull",
"seq_annotations__isnull",
"seq2seq_annotations__isnull",
)
class ProjectFilter(filters.FilterSet):
project_type = filters.MultipleChoiceFilter(choices=PROJECT_CHOICES)
role_project = filters.CharFilter(method="get_role_project")
def get_role_project(self, queryset, field_name, value):
role_abstractor = {
"admin": settings.ROLE_PROJECT_ADMIN,
"annotator": settings.ROLE_ANNOTATOR,
"approver": settings.ROLE_ANNOTATION_APPROVER,
}
role = Role.objects.filter(name=role_abstractor[value]).first()
project_list = RoleMapping.objects.filter(
role_id=role.id, user=self.request.user
).values_list("project_id", flat=True)
queryset = Project.objects.filter(id__in=project_list)
return queryset
class Meta:
model = Project
fields = ("project_type", "role_project")
<file_sep>/doclabel/users/admin.py
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from .forms import UserChangeForm, UserCreationForm
@admin.register(get_user_model())
class UserAdmin(auth_admin.UserAdmin):
old_fieldsets = auth_admin.UserAdmin.fieldsets
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (
(old_fieldsets[0],)
+ ((_("Personal info"), {"fields": ("email", "avatar")}),)
+ (old_fieldsets[2:])
)
list_display = ["username", "is_active", "is_superuser"]
search_fields = ["username"]
<file_sep>/frontend/src/pages/explore/model.js
import { queryProjectList, requestJoinProject } from './service';
import { arrayToObject, getPageQuery } from '@/utils/utils';
const Model = {
namespace: 'projects',
state: {
list: {},
pagination: {},
},
effects: {
*fetch({ payload }, { call, put }) {
const res = yield call(queryProjectList, payload);
const ret = {
list: arrayToObject(res.results, 'id'),
pagination: {
count: res.count,
next: res.next && getPageQuery(res.next),
previous: res.previous && getPageQuery(res.previous),
},
};
yield put({
type: 'changeState',
payload: ret,
});
return ret;
},
*requestJoinProject({ payload }, { call }) {
const res = yield call(requestJoinProject, payload);
return res;
},
},
reducers: {
changeState(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/pages/project/task/index.jsx
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Card, Dropdown, Menu, Popconfirm, message } from 'antd';
import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { router } from 'umi';
import CreateForm from './components/CreateForm';
import StandardTable from './components/StandardTable';
import styles from './index.less';
import { PAGE_SIZE } from '@/pages/constants';
const getValue = obj =>
Object.keys(obj)
.map(key => obj[key])
.join(',');
const ProjectTask = connect(({ project, task, loading }) => ({
project,
task,
loading: loading.models.task,
}))(props => {
const {
dispatch,
project,
task,
loading,
form,
location: { query },
} = props;
const { currentProject } = project;
const [modalVisible, setModalVisible] = React.useState(false);
const [selectedRows, setSelectedRows] = React.useState([]);
const [formValues, setFormValues] = React.useState({});
const taskTransform = React.useMemo(() => {
const list = task.list ? Object.entries(task.list).map(([key, val]) => val) : [];
return {
...task,
list,
};
}, [task]);
const fetchTask = async params => {
try {
await dispatch({
type: 'task/fetch',
payload: { params },
});
} catch (error) {
message.error('Something wrong! Try agian');
}
};
const fetchTaskDefault = async () => {
await fetchTask({ offset: query.page ? (query.page - 1) * PAGE_SIZE : 0 });
};
const handleRemoveTask = async record => {
try {
await dispatch({
type: 'task/remove',
payload: {
taskId: record.id,
},
});
await fetchTaskDefault();
message.success('Successfully deleted task!');
} catch (error) {
message.error('Something wrong! Try again');
}
};
React.useEffect(() => {
fetchTaskDefault();
}, []);
const columns = [
{
title: '#',
dataIndex: 'id',
},
{
title: 'Text',
dataIndex: 'text',
},
// {
// title: 'Annotation approver',
// dataIndex: 'annotation_approver',
// render: (text, record) => {},
// },
{
title: 'Operation',
render: (text, record) => (
<React.Fragment>
{/* <Divider type="vertical" /> */}
<Popconfirm
title="Are you sure delete this task?"
onConfirm={() => handleRemoveTask(record)}
okText="Yes"
cancelText="No"
>
<a href="#">Delete</a>
</Popconfirm>
</React.Fragment>
),
},
];
const handleStandardTableChange = (pagination, filtersArg, sorter) => {
const filters = Object.keys(filtersArg).reduce((obj, key) => {
const newObj = { ...obj };
newObj[key] = getValue(filtersArg[key]);
return newObj;
}, {});
const params = {
offset: (pagination.current - 1) * PAGE_SIZE,
...formValues,
...filters,
};
if (sorter.field) {
params.sorter = `${sorter.field}_${sorter.order}`;
}
fetchTask(params);
router.push({
query: pagination.current !== 1 ? { page: pagination.current } : {},
});
};
const handleFormReset = () => {
form.resetFields();
setFormValues({});
fetchTask();
};
// const toggleForm = () => {
// const { expandForm } = this.state;
// this.setState({
// expandForm: !expandForm,
// });
// };
const handleMenuClick = e => {
if (!selectedRows) return;
switch (e.key) {
case 'remove':
// TODO: Api not support yet ?
// dispatch({
// type: 'task/remove',
// payload: {
// key: selectedRows.map(row => row.key),
// },
// callback: () => {
// setSelectedRows([]);
// },
// });
break;
default:
break;
}
};
const handleSelectRows = rows => {
setSelectedRows(rows);
};
const handleSearch = e => {
e.preventDefault();
form.validateFields((err, fieldsValue) => {
if (err) return;
const values = {
...fieldsValue,
updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
};
setFormValues(values);
fetchTask(values);
});
};
const menu = (
<Menu onClick={handleMenuClick} selectedKeys={[]}>
<Menu.Item key="remove">Delete</Menu.Item>
</Menu>
);
return (
<PageHeaderWrapper
content={
<Button icon={<PlusOutlined />} type="primary" onClick={() => setModalVisible(true)}>
Add task
</Button>
}
>
<Card bordered={false}>
<div className={styles.tableList}>
{/* <div className={styles.tableListForm}>{renderForm()}</div> */}
<div className={styles.tableListOperator}>
{selectedRows.length > 0 && (
<span>
<Dropdown overlay={menu}>
<Button>
More operations <DownOutlined />
</Button>
</Dropdown>
</span>
)}
</div>
<StandardTable
rowKey={record => record.id}
selectedRows={selectedRows}
loading={loading}
data={taskTransform}
columns={columns}
onSelectRow={handleSelectRows}
onChange={handleStandardTableChange}
defaultCurrent={Number(query.page)}
/>
</div>
</Card>
<CreateForm
modalVisible={modalVisible}
setModalVisible={setModalVisible}
currentProject={currentProject}
onAddCompleted={fetchTask}
/>
</PageHeaderWrapper>
);
});
export default Form.create()(ProjectTask);
<file_sep>/doclabel/core/migrations/0012_project_annotator_per_example.py
# Generated by Django 2.2.6 on 2019-11-26 12:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_auto_20191121_1547'),
]
operations = [
migrations.AddField(
model_name='project',
name='annotator_per_example',
field=models.IntegerField(default=3),
),
]
<file_sep>/doclabel/core/migrations/0005_auto_20191025_0815.py
# Generated by Django 2.2.6 on 2019-10-25 08:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0004_project_owner'),
]
operations = [
migrations.AlterField(
model_name='project',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='projects', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='project',
name='users',
field=models.ManyToManyField(related_name='contribute_projects', to=settings.AUTH_USER_MODEL),
),
]
<file_sep>/frontend/src/pages/user/permission/Permission.jsx
import React, { Component } from 'react';
import { connect } from 'dva';
import { Table } from 'antd';
import UserModal from './components/UserModal';
import styles from './Permission.less';
@connect(stores => ({
usersDetail: stores.usersDetail,
}))
class Permission extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
recordData: {},
};
this.columns = [
{
title: '用户编号',
dataIndex: 'userId',
},
{
title: '名称',
dataIndex: 'userName',
},
{
title: '角色',
dataIndex: 'role',
render: text => {
switch (text) {
case 'admin':
return '超级管理员';
case 'user':
return '普通用户';
case 'guest':
return '游客';
default:
return 'Unknown';
}
},
},
{
title: '操作',
key: 'action',
width: 120,
render: (text, record) => (
<span>
<a
onClick={() => {
this.setState({
visible: true,
recordData: record,
});
}}
>
编辑
</a>
</span>
),
},
];
}
componentDidMount() {
const { dispatch } = this.props;
dispatch({ type: 'usersDetail/queryUsersList' });
}
render() {
const { usersDetail: { usersList = [] } = {} } = this.props;
const { visible, recordData } = this.state;
return (
<div className={styles.root}>
用户列表
<Table
className={styles.table}
columns={this.columns}
dataSource={usersList}
rowKey={record => record.userId}
/>
<UserModal
visible={visible}
recordData={recordData}
onCancel={() => {
this.setState({ visible: false, recordData: {} });
}}
/>
</div>
);
}
}
export default Permission;
<file_sep>/frontend/src/pages/account/center/components/Projects/CreateModalForm/index.jsx
import React from 'react';
import { useModalForm } from 'sunflower-antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Button, Spin, message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import { router } from 'umi';
import { FormContext } from './FormContext';
import NameInput from './FormItem/NameInput';
import DescriptionInput from './FormItem/DescriptionInput';
import Guideline from './FormItem/Guideline';
import ProjectTypeSelect from './FormItem/ProjectTypeSelect';
import OptionsCheckBox from './FormItem/OptionsCheckBox';
const messageID = {
'project with this name already exists.': 'projects-list.name.unique',
};
const CreateModalForm = connect(({ loading }) => ({
loading: loading.effects['project/createProject'],
}))(props => {
const { form, dispatch, errors } = props;
const { buttonText } = props;
const { modalProps, formProps, show, close, formLoading } = useModalForm({
defaultVisible: false,
autoSubmitClose: true,
autoResetForm: true,
submit: async formValues => {
const payload = { ...formValues };
const { options } = formValues;
delete payload.options;
options.forEach(val => {
payload[val] = true;
});
payload.resourcetype = payload.project_type;
console.log('[DEBUG]: payload', payload);
try {
const res = await dispatch({
type: 'project/createProject',
payload,
});
message.success(`Successfully created!${res.name}`);
router.push(`/projects/${res.id}/dashboard`);
form.resetFields();
close();
} catch (error) {
const valueWithError = {};
if (error.data) {
Object.entries(error.data).forEach(([key, val]) => {
const msg = formatMessage({
id: messageID[val[0]],
});
valueWithError[key] = {
value: form.getFieldValue(key),
errors: [new Error(msg)],
};
});
}
form.setFields({ ...valueWithError });
message.error('Something wrong! Try again');
}
},
form,
});
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
return (
<FormContext.Provider value={form}>
<Modal {...modalProps} title="Create new project" footer={null} width={740}>
<Spin spinning={formLoading}>
<Form {...formItemLayout} {...formProps} layout="horizontal">
<NameInput />
<DescriptionInput />
<Guideline />
<ProjectTypeSelect />
<OptionsCheckBox />
<Form.Item wrapperCol={{ span: 12, offset: 6 }}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</Spin>
</Modal>
<div className={props.className}>
<Button onClick={show} size="large">
{buttonText}
</Button>
</div>
</FormContext.Provider>
);
});
export default Form.create()(CreateModalForm);
<file_sep>/frontend/src/layouts/AnnotationLayout.jsx
import Authorized, { reloadAuthorized } from '@/utils/Authorized';
import { getAuthorityFromRouter } from '@/utils/utils';
import { Button, message, Result } from 'antd';
import { connect } from 'dva';
import React from 'react';
import { router, Link } from 'umi';
const noMatch = (
<Result
status="403"
title="403"
subTitle="Sorry, you are not authorized to access this page."
extra={
<Button type="primary">
<Link to="/user/login">Go Login</Link>
</Button>
}
/>
);
const AnnotationLayout = connect(({ loading }) => ({
loading: loading.effects['project/fetchProject'],
}))(props => {
const {
dispatch,
children,
match,
location = {
pathname: '/app',
},
loading,
} = props;
/**
* constructor
*/
const [isReady, setIsReady] = React.useState(false);
const { id: projectId } = match.params;
const fetchProject = async () => {
if (projectId) {
const res = await dispatch({
type: 'project/fetchProject',
payload: projectId,
});
if (res && !res.public) {
router.push('/home');
message.warn('Project is not ready!');
} else {
reloadAuthorized();
}
setIsReady(true);
}
};
React.useEffect(() => {
if (dispatch) {
fetchProject();
}
return () => {
dispatch({
type: 'project/cleanProject',
});
};
}, [projectId]);
React.useEffect(() => {
dispatch({
type: 'settings/getSetting',
});
}, []);
/**
* init variables
*/
// get children authority
const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
authority: undefined,
};
const isLoading = loading || !isReady;
return (
<>
{!isLoading && (
<Authorized authority={authorized.authority} noMatch={noMatch}>
{children}
</Authorized>
)}
</>
);
});
export default AnnotationLayout;
<file_sep>/doclabel/users/backends.py
from social_core.backends.gitlab import GitLabOAuth2
from social_core.backends.google import GoogleOAuth2
from social_core.backends.github import GithubOAuth2
class GitLabOAuth2Override(GitLabOAuth2):
REDIRECT_STATE = False
class GoogleOAuth2Override(GoogleOAuth2):
REDIRECT_STATE = False
class GithubOAuth2Override(GithubOAuth2):
REDIRECT_STATE = False
<file_sep>/frontend/src/models/connect.d.ts
import { AnyAction } from 'redux';
import { MenuDataItem } from '@ant-design/pro-layout';
import { RouterTypes } from 'umi';
import { GlobalModelState } from './global';
import { DefaultSettings as SettingModelState } from '../../config/defaultSettings';
import { UserModelState, UserModelType } from './user';
import { AuthModelState } from './auth';
export { GlobalModelState, SettingModelState, UserModelState };
export interface Loading {
global: boolean;
effects: { [key: string]: boolean | undefined };
models: {
global?: boolean;
menu?: boolean;
setting?: boolean;
user?: boolean;
login?: boolean;
accountCenter: boolean;
project: boolean;
label: boolean;
task: boolean;
dashboard: boolean;
};
}
export interface OAuthModelState {
opened: boolean;
}
export interface ConnectState {
global: GlobalModelState;
loading: Loading;
settings: SettingModelState;
user: UserModelState;
auth: AuthModelState;
oauth: OAuthModelState;
}
export interface Route extends MenuDataItem {
routes?: Route[];
}
/**
* @type T: Params matched in dynamic routing
*/
export interface ConnectProps<T = {}> extends Partial<RouterTypes<Route, T>> {
dispatch?: Dispatch<AnyAction>;
}
// Models
export interface Pagination {
count: number;
next: {
limit: string;
offset: string;
};
previous: {
limit: string;
offset: string;
};
}
export interface Project {
id: number;
name: string;
description: string;
guideline: string;
randomize_document_order: boolean;
collaborative_annotation: boolean;
annotator_per_example: number;
public: boolean;
image: string;
updated_at: string;
users: UserModelType[];
project_type: string;
current_users_role: {
is_project_admin: boolean;
is_annotator: boolean;
is_annotation_approver: boolean;
is_guest: boolean;
};
project_stat: {
total: number;
remaining: number;
docs_stat: {
count: number;
};
};
resourcetype: string;
}
export interface Label {
id: number;
text: string;
prefix_key?: string;
project: number;
suffix_key: string;
background_color: string;
text_color: string;
}
export interface Task {
id: number;
text: string;
annotations: Annotation[];
meta: string;
annotation_approver?: number;
file_url?: string;
}
export interface Annotation {
id: number;
prob: number;
user: number;
document: number;
finished: boolean;
label: number;
}
<file_sep>/frontend/src/pages/account/center/components/Projects/CreateModalForm/FormItem/Guideline.jsx
import React from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Typography } from 'antd';
import { useFormContext } from '../FormContext';
export default () => {
const { getFieldDecorator } = useFormContext();
return (
<Form.Item
label={formatMessage({
id: 'projects-list.guideline.placeholder',
})}
>
{getFieldDecorator('guideline', {
initialValue: formatMessage({
id: 'projects-list.guideline.code',
}),
})(
<Typography.Text code>
<FormattedMessage id="projects-list.guideline.code" />
</Typography.Text>,
)}
</Form.Item>
);
};
<file_sep>/frontend/src/pages/user/register-result/locales/en-US.ts
export default {
'userandregister-result.register-result.msg': 'Sign up with email',
'userandregister-result.register-result.activation-email':
'Please log in to the email click on the link in the email to verify your account.',
'userandregister-result.register-result.amazing': 'Check some of the amazing projects',
'userandregister-result.register-result.back': 'Back',
'userandregister-result.register-result.view-projects': 'Explore Projects',
'userandregister-result.navBar.lang': 'Languages',
};
<file_sep>/frontend/src/pages/Home/index.jsx
import React from 'react';
import { Button } from 'antd';
import styles from './index.less';
import TopBanner from './components/TopBanner';
import FeatureCards from './components/FeatureCards';
import ProjectsBanner from './components/ProjectsBanner';
function Home(props) {
const [state, setState] = React.useState();
return (
<div className={styles.main}>
<TopBanner />
<FeatureCards />
<ProjectsBanner />
</div>
);
}
export default React.memo(Home);
<file_sep>/doclabel/core/models.py
import string
import os
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save, pre_delete, post_delete
from django.db import models
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
from django.core.files.storage import FileSystemStorage
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.exceptions import ValidationError
from polymorphic.models import PolymorphicModel
from .managers import AnnotationManager, Seq2seqAnnotationManager
User = get_user_model()
DOCUMENT_CLASSIFICATION = "TextClassificationProject"
SEQUENCE_LABELING = "SequenceLabelingProject"
SEQ2SEQ = "Seq2seqProject"
PDF_LABELING = "PdfLabelingProject"
PROJECT_CHOICES = (
(DOCUMENT_CLASSIFICATION, "Document Classification"),
(SEQUENCE_LABELING, "Sequence Labeling"),
(SEQ2SEQ, "Sequence to Sequence"),
(PDF_LABELING, "PDF Labeling Project"),
)
# Project
class Project(PolymorphicModel):
name = models.CharField(max_length=100, unique=True)
description = models.TextField(default="")
guideline = models.TextField(default="")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
users = models.ManyToManyField(User, related_name="projects")
project_type = models.CharField(max_length=30, choices=PROJECT_CHOICES, null=False)
annotator_per_example = models.IntegerField(default=3)
randomize_document_order = models.BooleanField(default=False)
# Allow see annotation from other user
collaborative_annotation = models.BooleanField(default=False)
public = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse("upload", args=[self.id])
@property
def image(self):
raise NotImplementedError()
def get_annotation_serializer(self):
raise NotImplementedError()
def get_annotation_class(self):
raise NotImplementedError()
def get_storage(self, data):
raise NotImplementedError()
def __str__(self):
return self.name
class TextClassificationProject(Project):
@property
def image(self):
return staticfiles_storage.url("images/cats/text_classification.jpg")
def get_annotation_serializer(self):
from doclabel.core.serializers import DocumentAnnotationSerializer
return DocumentAnnotationSerializer
def get_annotation_class(self):
return DocumentAnnotation
def get_storage(self, data):
from .utils import ClassificationStorage
return ClassificationStorage(data, self)
class SequenceLabelingProject(Project):
@property
def image(self):
return staticfiles_storage.url("images/cats/sequence_labeling.jpg")
def get_annotation_serializer(self):
from .serializers import SequenceAnnotationSerializer
return SequenceAnnotationSerializer
def get_annotation_class(self):
return SequenceAnnotation
def get_storage(self, data):
from .utils import SequenceLabelingStorage
return SequenceLabelingStorage(data, self)
class Seq2seqProject(Project):
@property
def image(self):
return staticfiles_storage.url("images/cats/seq2seq.jpg")
def get_annotation_serializer(self):
from .serializers import Seq2seqAnnotationSerializer
return Seq2seqAnnotationSerializer
def get_annotation_class(self):
return Seq2seqAnnotation
def get_storage(self, data):
from .utils import Seq2seqStorage
return Seq2seqStorage(data, self)
class PdfLabelingProject(Project):
@property
def image(self):
return staticfiles_storage.url("images/cats/pdf_labeling.jpg")
def get_annotation_serializer(self):
from .serializers import PdfAnnotationSerializer
return PdfAnnotationSerializer
def get_annotation_class(self):
return PdfAnnotation
def get_storage(self, data):
from .utils import PdfLabelingStorage
return PdfLabelingStorage(data, self)
# Label
class Label(models.Model):
PREFIX_KEYS = (("ctrl", "ctrl"), ("shift", "shift"), ("ctrl shift", "ctrl shift"))
SUFFIX_KEYS = tuple((c, c) for c in string.ascii_lowercase)
text = models.CharField(max_length=100)
prefix_key = models.CharField(
max_length=10, blank=True, null=True, choices=PREFIX_KEYS
)
suffix_key = models.CharField(
max_length=1, blank=True, null=True, choices=SUFFIX_KEYS
)
project = models.ForeignKey(
Project, related_name="labels", on_delete=models.CASCADE
)
background_color = models.CharField(max_length=7, default="#209cee")
text_color = models.CharField(max_length=7, default="#ffffff")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.text
def clean(self):
# Don't allow shortcut key not to have a suffix key.
if self.prefix_key and not self.suffix_key:
raise ValidationError("Shortcut key may not have a suffix key.")
# each shortcut (prefix key + suffix key) can only be assigned to one label
if self.suffix_key or self.prefix_key:
other_labels = self.project.labels.exclude(id=self.id)
if other_labels.filter(
suffix_key=self.suffix_key, prefix_key=self.prefix_key
).exists():
raise ValidationError(
"A label with this shortcut already exists in the project"
)
super().clean()
class Meta:
unique_together = (("project", "text"),)
# Dataset
class Document(models.Model):
# text content or pdf content
text = models.TextField()
project = models.ForeignKey(
Project, related_name="documents", on_delete=models.CASCADE
)
meta = models.TextField(default="{}")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
annotations_approved_by = models.ForeignKey(
User, on_delete=models.SET_NULL, null=True
)
def __str__(self):
return self.text[:50]
# Annotation
class Annotation(models.Model):
objects = AnnotationManager()
prob = models.FloatField(default=0.0)
manual = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# user confirm finish task set
finished = models.BooleanField(default=False)
class Meta:
abstract = True
class DocumentAnnotation(Annotation):
document = models.ForeignKey(
Document, related_name="doc_annotations", on_delete=models.CASCADE
)
label = models.ForeignKey(Label, on_delete=models.CASCADE)
class Meta:
unique_together = (("document", "user", "label"),)
class SequenceAnnotation(Annotation):
document = models.ForeignKey(
Document, related_name="seq_annotations", on_delete=models.CASCADE
)
label = models.ForeignKey(Label, on_delete=models.CASCADE)
start_offset = models.IntegerField()
end_offset = models.IntegerField()
tokens = JSONField()
def clean(self):
if self.start_offset >= self.end_offset:
raise ValidationError("start_offset is after end_offset")
class Meta:
unique_together = (("document", "user", "label", "start_offset", "end_offset"),)
class Seq2seqAnnotation(Annotation):
# Override AnnotationManager for custom functionality
objects = Seq2seqAnnotationManager()
document = models.ForeignKey(
Document, related_name="seq2seq_annotations", on_delete=models.CASCADE
)
text = models.CharField(max_length=500)
class Meta:
unique_together = (("document", "user", "text"),)
class PdfAnnotation(Annotation):
document = models.ForeignKey(
Document, related_name="pdf_annotations", on_delete=models.CASCADE
)
label = models.ForeignKey(Label, on_delete=models.CASCADE)
content = JSONField()
position = JSONField()
class Meta:
unique_together = (("document", "user", "label", "content", "position"),)
class Role(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.TextField(default="")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class RoleMapping(models.Model):
user = models.ForeignKey(
User, related_name="role_mappings", on_delete=models.CASCADE
)
project = models.ForeignKey(
Project, related_name="role_mappings", on_delete=models.CASCADE
)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def clean(self):
other_rolemappings = self.project.role_mappings.exclude(id=self.id)
if other_rolemappings.filter(user=self.user, project=self.project).exists():
raise ValidationError(
"This user is already assigned to a role in this project."
)
class Meta:
unique_together = ("user", "project", "role")
@receiver(post_save, sender=RoleMapping)
def add_linked_project(sender, instance, created, **kwargs):
if not created:
return
userInstance = instance.user
projectInstance = instance.project
isAnnotator = instance.role.name == settings.ROLE_ANNOTATOR
if userInstance and projectInstance and isAnnotator:
user = User.objects.get(pk=userInstance.pk)
project = Project.objects.get(pk=projectInstance.pk)
user.projects.add(project)
user.save()
@receiver(post_save)
def add_superusers_to_project(sender, instance, created, **kwargs):
if not created:
return
if sender not in Project.__subclasses__():
return
superusers = User.objects.filter(is_superuser=True)
admin_role = Role.objects.filter(name=settings.ROLE_PROJECT_ADMIN).first()
if superusers and admin_role:
RoleMapping.objects.bulk_create(
[
RoleMapping(
role_id=admin_role.id, user_id=superuser.id, project_id=instance.id
)
for superuser in superusers
]
)
@receiver(post_save, sender=User)
def add_new_superuser_to_projects(sender, instance, created, **kwargs):
if created and instance.is_superuser:
admin_role = Role.objects.filter(name=settings.ROLE_PROJECT_ADMIN).first()
projects = Project.objects.all()
if admin_role and projects:
RoleMapping.objects.bulk_create(
[
RoleMapping(
role_id=admin_role.id,
user_id=instance.id,
project_id=project.id,
)
for project in projects
]
)
@receiver(pre_delete, sender=RoleMapping)
def delete_linked_project(sender, instance, using, **kwargs):
userInstance = instance.user
projectInstance = instance.project
isAnnotator = instance.role.name == settings.ROLE_ANNOTATOR
if userInstance and projectInstance and isAnnotator:
user = User.objects.get(pk=userInstance.pk)
project = Project.objects.get(pk=projectInstance.pk)
user.projects.remove(project)
user.save()
@receiver(post_delete, sender=Document)
def delete_file_on_remove(sender, instance, **kwargs):
file = instance.text
fs = FileSystemStorage(location=settings.MEDIA_ROOT + "/pdf_documents/")
if fs.exists(file):
fs.delete(file)
@receiver(post_delete, sender=PdfAnnotation)
def delete_anno_on_remove(sender, instance, **kwargs):
content = instance.content
if "image" in content:
doc = instance.document
fs = FileSystemStorage(
location=settings.MEDIA_ROOT + "/pdf_annotations/doc_" + str(doc.id) + "/"
)
if fs.exists(content["image"]):
fs.delete(content["image"])
<file_sep>/frontend/src/pages/explore/index.jsx
import { connect } from 'dva';
import React from 'react';
import FilterForm from './components/FilterForm';
import Projects from './components/Projects';
import styles from './style.less';
function Explore(props) {
const { location } = props;
return (
<div className={styles.coverCardList}>
<FilterForm location={location} />
<div className={styles.cardList}>
<Projects location={location} />
</div>
</div>
);
}
export default connect(({ projects, loading }) => ({
projects,
loading: loading.models.projects,
}))(Explore);
<file_sep>/frontend/src/utils/request.js
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
* request Network request tool
* More specifically api document: https://github.com/umijs/umi-request
*/
import { extend } from 'umi-request';
import { message } from 'antd';
import { router } from 'umi';
import { getAuthorization, setAuthorization } from '@/utils/authority';
/**
* Exception handler
*/
const errorHandler = error => {
const { response } = error;
if (response && response.status) {
const { status } = response;
// if (status === 401) {
// setAuthorization();
// // eslint-disable-next-line no-underscore-dangle
// window.g_app._store.dispatch({
// type: 'auth/logout',
// });
// }
if (status === 403) {
router.push('/exception/403');
}
if (status <= 504 && status >= 500) {
router.push('/exception/500');
}
if (status >= 404 && status < 422) {
router.push('/exception/404');
}
} else if (!response) {
message.error('Your network is abnormal and cannot connect to the server');
}
throw error;
};
/**
* Default parameters when configuring request
*/
const request = extend({
errorHandler,
// Default error handling
credentials: 'include', // Whether the default request is taken cookie
headers: {
Authorization: `Token ${getAuthorization()}`,
},
});
request.interceptors.request.use((url, options) => {
const token = getAuthorization();
const { headers } = options;
let newHeader;
if (token === 'undefined' || token === null) {
delete headers.Authorization;
} else {
newHeader = {
...headers,
Authorization: `Token ${token}`,
};
}
return {
options: {
...options,
headers: { ...newHeader },
},
};
});
// const reloadAuthorizationInterceptors = () => {
// request.interceptors.request.use((url, options) => ({
// options: {
// ...options,
// headers: {
// ...options.headers,
// Authorization: `Bearer ${getAuthorization()}`,
// },
// },
// }));
// };
// export { reloadAuthorizationInterceptors };
export default request;
<file_sep>/frontend/src/pages/explore/service.js
import request from '@/utils/request';
export async function queryProjectList(params) {
return request('/api/projects/', {
method: 'GET',
params,
});
}
export async function requestJoinProject({ projectId, role }) {
return request(`/api/projects/${projectId}/join/`, {
method: 'POST',
data: { role },
});
}
<file_sep>/frontend/src/pages/project/guide/components/Editor/index.jsx
import React from 'react';
import { UnControlled as CodeMirror } from 'react-codemirror2';
import styles from './index.less';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/dracula.css';
import 'codemirror/mode/markdown/markdown';
function Editor({ value, onChange, dark }) {
return (
<CodeMirror
autoCursor={false}
className={styles.main}
value={value}
options={{
mode: 'markdown',
theme: dark ? 'dracula' : '',
lineNumbers: true,
}}
onChange={(editor, data, newValue) => {
onChange(newValue);
}}
/>
);
}
export default Editor;
<file_sep>/frontend/src/pages/explore/locales/en-US.js
export default {
'projects-list.name.required': 'Please enter the project name',
'projects-list.name.unique': 'Project with this name already exists.',
'projects-list.name.toolong': 'The project name too long! (< 100)',
'projects-list.name.placeholder': 'Name',
// Description
'projects-list.description.required': 'Please enter the project description',
'projects-list.description.placeholder': 'Description',
// Guideline
'projects-list.guideline.code': 'Please add guide-line later',
'projects-list.guideline.placeholder': 'Annatation guide',
// Project type
'projects-list.project_type.required': 'Please select the project type',
'projects-list.project_type.placeholder': 'Select a project type',
'projects-list.project_type.label': 'Project type',
'projects-list.options.label': 'Options',
// randomize_document_order
'projects-list.randomize_document_order.placeholder': 'Randomize document order',
// collaborative_annotation
'projects-list.collaborative_annotation.placeholder': 'Collaborative annotation',
};
<file_sep>/frontend/src/pages/account/settings/service.js
import request from '@/utils/request';
export async function updateAccount({ data }) {
return request('/api/user/', {
method: 'PATCH',
data,
});
}
export async function changeAvatar({ data }) {
return request('/api/user/', {
method: 'PATCH',
headers: {
'Content-Type': 'multipart/form-data',
},
data,
});
}
export async function changePassword({ data }) {
return request('/api/password/change/', {
method: 'POST',
data,
});
}
<file_sep>/frontend/src/pages/annotation/components/AnnotationArea/PdfLabelingProject/Sidebar.jsx
import { DeleteOutlined } from '@ant-design/icons';
import { Button, Col, Collapse, Layout, List, Popconfirm, Row, Typography } from 'antd';
import React, { useState } from 'react';
import LabelPreview from '../../LabelPreview';
import styles from './style.less';
function Sidebar({
annoList = [],
labelList,
handleRemoveLabel,
setActiveKey,
activeKey,
setCurrentAnno,
dark,
isDisabled,
}) {
const handleDeleteAnno = annoId => {
if (annoId) {
handleRemoveLabel(annoId);
}
};
const [collapsed, setCollapsed] = useState(true);
const dataObjectList = {
...labelList,
};
Object.keys(labelList).forEach(key => {
dataObjectList[key] = {
...dataObjectList[key],
array: annoList.filter(val => val.label === Number(key)),
};
});
const loading = !labelList;
return (
<Layout.Sider
width={320}
className={styles.sidebar}
theme={dark ? 'dark' : 'light'}
breakpoint="xxl"
collapsedWidth="0"
onBreakpoint={broken => {
// console.log(broken);
}}
reverseArrow
// collapsed={collapsed}
// onCollapse={$collapsed => setCollapsed($collapsed)}
>
<div className={styles.title}>
<Typography.Title level={4}>Annotation Label</Typography.Title>
</div>
<Collapse
accordion
activeKey={[`${activeKey}`]}
onChange={key => {
setActiveKey(key);
}}
expandIconPosition="right"
>
{!!Object.keys(dataObjectList).length &&
Object.values(dataObjectList).map((val, idx) => (
<Collapse.Panel
header={
<Row type="flex" gutter={48}>
<Col>
<Typography.Text strong style={{ lineHeight: '32px' }}>
Label:
</Typography.Text>
</Col>
<Col>
<LabelPreview label={val} />
</Col>
</Row>
}
// eslint-disable-next-line react/no-array-index-key
key={val.id}
>
<List
loading={loading}
dataSource={val.array}
bordered={false}
renderItem={({ content, position, label, id, image_url: url }) => (
<List.Item
onClick={() => {
setCurrentAnno(id);
}}
className={styles.sidebarItem}
>
<Row
gutter={[12, 24]}
type="flex"
style={{ flex: 1, padding: '0 12px' }}
align="middle"
justify="space-between"
>
<Col span={24}>
{content.text && (
<Typography.Text mark strong className={styles.contentMark}>
{content.text.length > 90
? `${content.text.slice(0, 90).trim()}…`
: `${content.text}`}
</Typography.Text>
)}
{content.image && (
<div className={styles.dataImage}>
<img src={url} alt="Screenshot" />
</div>
)}
</Col>
{content.comment ? (
<Col span={24}>
<Typography.Paragraph ellipsis style={{ marginBottom: 0 }}>
{content.comment}
</Typography.Paragraph>
</Col>
) : null}
{/* */}
<Col>
<Typography.Text code className={styles.labelPage}>
Page {position.pageNumber}
</Typography.Text>
</Col>
<Col>
{!isDisabled && (
<Popconfirm
title="Are you sure delete this annotation?"
onConfirm={() => handleDeleteAnno(id)}
placement="topRight"
>
<Button icon={<DeleteOutlined />} shape="circle-outline" type="dashed" />
</Popconfirm>
)}
</Col>
</Row>
</List.Item>
)}
/>
</Collapse.Panel>
))}
</Collapse>
</Layout.Sider>
);
}
export default React.memo(Sidebar);
<file_sep>/frontend/src/pages/account/center/components/Approvals/index.jsx
import { SafetyCertificateTwoTone, ShareAltOutlined } from '@ant-design/icons';
import { Avatar, Card, List, Tooltip, Row, Col, Typography } from 'antd';
import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { router } from 'umi';
import styles from './index.less';
import { PROJECT_TYPE, PAGE_SIZE } from '@/pages/constants';
const Approvals = connect(({ user, accountCenter, loading }) => ({
currentUser: user.currentUser,
myApprovals: accountCenter.myApprovals,
loading: loading.effects['accountCenter/fetchMyApproval'],
}))(props => {
const {
currentUser,
myApprovals: { list, pagination },
loading,
location: {
query: { pc = 1, ...rest },
},
fetchMyApproval,
} = props;
const dataLoading = loading || loading === undefined;
/** Handler */
const handleOnChange = newPage => {
router.push({
query: { ...rest, pc: newPage },
});
fetchMyApproval(newPage);
};
return (
<React.Fragment>
<List
rowKey="id"
className={styles.filterCardList}
grid={{
gutter: 24,
xxl: 2,
xl: 2,
lg: 2,
md: 2,
sm: 2,
xs: 1,
}}
loading={dataLoading}
dataSource={list}
pagination={{
onChange: handleOnChange,
defaultPageSize: PAGE_SIZE,
total: pagination.count,
current: pc ? Number(pc) : 1,
}}
renderItem={item => {
const stat = item.project_stat;
const taskNumber = stat && stat.docs_stat && `${stat.docs_stat.count}`;
const completeStatus = `${stat.total - stat.remaining}/${stat.total}`;
const contributors = item && item.users && Object.keys(item.users).length;
return (
<List.Item key={item.id}>
<Card
hoverable
bodyStyle={{
paddingBottom: 20,
}}
actions={[
<Tooltip title="Approval" key="approval">
<SafetyCertificateTwoTone onClick={() => router.push(`/annotation/${item.id}`)} />
</Tooltip>,
<Tooltip title="Share" key="share">
<ShareAltOutlined />
</Tooltip>,
]}
>
<Card.Meta
avatar={<Avatar src={item.image} />}
title={item.name}
description={
<Row gutter={16} type="flex" justify="space-between">
<Col>
<Typography.Text strong>
{PROJECT_TYPE[item.project_type].tag}
</Typography.Text>
</Col>
{/* <Col>{item.public ? 'Published' : 'Unpublished'}</Col> */}
</Row>
}
/>
<div className={styles.cardInfo}>
<div className={styles.paragraph}>
<Typography.Paragraph ellipsis={{ rows: 3 }}>
{item.description}
</Typography.Paragraph>
</div>
<Row type="flex" gutter={16} justify="end">
<Col>{moment(item.updated_at).fromNow()}</Col>
</Row>
<Row type="flex" gutter={16}>
<Col span={8}>
{taskNumber} {taskNumber === 1 ? ' task' : ' tasks'}
</Col>
<Col span={8}>{completeStatus} done</Col>
<Col span={8}>{contributors} contributors</Col>
</Row>
</div>
</Card>
</List.Item>
);
}}
/>
</React.Fragment>
);
});
export default Approvals;
<file_sep>/frontend/src/pages/annotation/components/LabelList.jsx
import React from 'react';
import { Row, Col } from 'antd';
import { GlobalHotKeys } from 'react-hotkeys';
import LabelPreview from './LabelPreview';
const shortcutKey = shortcut => {
let ret = shortcut.suffix_key;
if (shortcut.prefix_key) {
ret = `${shortcut.prefix_key}+${shortcut.suffix_key}`;
}
return ret;
};
function LabelList({ labelList, handleChooseLabel }) {
const memoHotkey = React.useMemo(() => {
const keyMap = { ...labelList };
const handlers = { ...labelList };
Object.keys(labelList).forEach(key => {
keyMap[key] = shortcutKey(labelList[key]);
handlers[key] = () => handleChooseLabel(key);
});
return { keyMap, handlers };
}, [labelList, handleChooseLabel]);
return (
<GlobalHotKeys allowChanges keyMap={memoHotkey.keyMap} handlers={memoHotkey.handlers}>
<Row type="flex" gutter={[24, 16]} justify="center">
{labelList &&
Object.keys(labelList).map(key => (
<Col key={key}>
<LabelPreview
key={key}
label={labelList[key]}
onClick={() => handleChooseLabel(key)}
/>
</Col>
))}
</Row>
</GlobalHotKeys>
);
}
export default LabelList;
<file_sep>/frontend/src/pages/project/dashboard/components/ContributionCard.jsx
import { Card, Col, Row, Tabs } from 'antd';
import React from 'react';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Bar from './Bar';
import styles from './ContributionCard.less';
import TaskInfo from './TaskInfo';
const ContributionCard = ({ loading, userData, labelData, docStat }) => {
const isReady = !loading && docStat && Object.keys(docStat).length;
return (
<Card
loading={loading}
bordered={false}
bodyStyle={{
padding: 0,
}}
>
<div className={styles.contributionCard}>
<Tabs
size="large"
tabBarStyle={{
marginBottom: 24,
}}
>
<Tabs.TabPane
tab={<FormattedMessage id="dashboard.user" defaultMessage="Contributors" />}
key="users"
>
<Row type="flex" style={{ padding: '16px' }}>
<Col xl={24} lg={24} md={24} sm={24} xs={24}>
<div className={styles.userBar}>
<Bar
height={295}
title={
<FormattedMessage
id="dashboard.user-title"
defaultMessage="Annotations/User"
/>
}
data={userData}
/>
</div>
</Col>
</Row>
</Tabs.TabPane>
<Tabs.TabPane
tab={<FormattedMessage id="dashboard.labels" defaultMessage="Labels" />}
key="labels"
>
<Row
type="flex"
style={{
padding: '16px',
}}
>
<Col xl={24} lg={24} md={24} sm={24} xs={24}>
<div className={styles.labelBar}>
<Bar
height={295}
color="rgba(255, 135, 24, 0.85)"
title={
<FormattedMessage
id="dashboard.labels-title"
defaultMessage="Annotations/Label"
/>
}
data={labelData}
/>
</div>
</Col>
</Row>
</Tabs.TabPane>
<Tabs.TabPane
tab={<FormattedMessage id="dashboard.tasks" defaultMessage="Task Progress" />}
key="tasks"
>
<Row gutter={[8, 8]} type="flex" style={{ padding: '0 24px' }}>
{isReady &&
Object.entries(docStat).map(([key, val]) => (
<Col key={key} xs={12} sm={8} xxl={6}>
<TaskInfo task={val} />
</Col>
))}
</Row>
</Tabs.TabPane>
</Tabs>
</div>
</Card>
);
};
export default ContributionCard;
<file_sep>/frontend/src/pages/annotation/components/AnnotationArea/SequenceLabelingProject.jsx
import { Card, Col, Row, Spin, Tag, Typography } from 'antd';
import classNames from 'classnames';
import React from 'react';
import { TokenAnnotator } from 'react-text-annotate';
import { useAnnotaionContext } from '../AnnotationContext';
import LabelList from '../LabelList';
import LabelPreview from '../LabelPreview';
import styles from './SequenceLabelingProject.less';
function SequenceLabelingProject(prs) {
const {
isDisabled,
annoList = [],
labelList = [],
handleRemoveLabel,
handleAddLabel,
task,
annoLoading: loading,
} = useAnnotaionContext();
const [tag, setTag] = React.useState(null);
const handleChange = newVal => {
const isAdd = annoList.length < newVal.length;
if (isAdd) {
const [difference] = newVal.filter(val => !val.id);
handleAddLabel({
start_offset: difference.start,
end_offset: difference.end,
label: difference.tag.id,
tokens: difference.tokens,
});
} else {
const annoListTemp = annoList.map(item => item.id);
const newValTemp = newVal.map(item => item.id);
const [id] = annoListTemp.filter(val => !newValTemp.includes(val));
handleRemoveLabel(id);
}
};
const handleChooseLabel = labelKey => {
if (tag.id !== labelKey) {
setTag(labelList[labelKey]);
}
};
React.useEffect(() => {
setTag(Object.values(labelList)[0]);
}, [labelList]);
const getTokenValue = () => {
const list = [...annoList];
return list.map(val => ({
start: val.start_offset,
end: val.end_offset,
tokens: val.tokens,
tag: labelList[val.label],
id: val.id,
}));
};
return (
<React.Fragment>
<Card>
<Row gutter={[0, 16]}>
<Col>
<Typography.Text strong>Labels</Typography.Text>
</Col>
<Col>
<LabelList labelList={labelList} handleChooseLabel={handleChooseLabel} />
</Col>
</Row>
</Card>
<Card>
<Row gutter={[0, 16]}>
<Col>
<Typography.Text strong>Choosen label</Typography.Text>
</Col>
<Col>
<Row type="flex" justify="center">
<Col>
<LabelPreview label={tag} />
</Col>
</Row>
</Col>
</Row>
</Card>
<Card>
<Spin spinning={!!loading} size="large">
{task && (
<Row
type="flex"
justify="center"
align="middle"
style={{ minHeight: '165px' }}
className={classNames({
[styles.disabled]: isDisabled,
})}
>
<Col className={styles.tokenText}>
<TokenAnnotator
tokens={task.text.split(' ')}
value={getTokenValue()}
onChange={handleChange}
getSpan={span => ({
...span,
tag,
})}
renderMark={props => (
<React.Fragment key={props.key}>
<div className={styles.labelText} title="Click to remove">
<Tag
className={styles.text}
style={{ color: props.tag.text_color }}
color={props.tag.background_color}
closable
onClose={e => {
e.preventDefault();
props.onClick({ start: props.start, end: props.end });
}}
>
{props.tag.text}
</Tag>
<div
className={styles.content}
style={{ borderColor: props.tag.background_color }}
>
<div className={styles.textContent}>{props.content}</div>
</div>
</div>{' '}
</React.Fragment>
)}
/>
</Col>
</Row>
)}
</Spin>
</Card>
</React.Fragment>
);
}
export default React.memo(SequenceLabelingProject);
<file_sep>/frontend/src/components/GlobalHeader/RightContent.jsx
import { BulbFilled, BulbOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';
import React from 'react';
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import Avatar from './AvatarDropdown';
import HeaderSearch from '../HeaderSearch';
import SelectLang from '../SelectLang';
import styles from './index.less';
const GlobalHeaderRight = props => {
const { theme, layout, dispatch } = props;
let className = styles.right;
if (theme === 'dark' && layout === 'topmenu') {
className = `${styles.right} ${styles.dark}`;
}
const handleSwitchTheme = () => {
dispatch({
type: 'settings/changeTheme',
payload: theme === 'dark' ? 'light' : 'dark',
});
};
return (
<div className={className}>
<HeaderSearch
className={`${styles.action} ${styles.search}`}
placeholder={formatMessage({
id: 'component.globalHeader.search',
})}
defaultValue="umi ui"
dataSource={[
formatMessage({
id: 'component.globalHeader.search.example1',
}),
formatMessage({
id: 'component.globalHeader.search.example2',
}),
formatMessage({
id: 'component.globalHeader.search.example3',
}),
]}
onSearch={value => {
console.log('input', value);
}}
onPressEnter={value => {
console.log('enter', value);
}}
/>
<Tooltip
title={formatMessage({
id: 'component.globalHeader.theme',
})}
>
<a href="#" className={styles.action} onClick={handleSwitchTheme}>
{theme === 'dark' ? <BulbFilled /> : <BulbOutlined />}
</a>
</Tooltip>
<Avatar menu />
<SelectLang className={styles.action} />
</div>
);
};
export default connect(({ settings }) => ({
theme: settings.navTheme,
layout: settings.layout,
}))(GlobalHeaderRight);
<file_sep>/frontend/src/pages/account/center/components/Projects/index.jsx
import { DownloadOutlined, EditOutlined, ShareAltOutlined } from '@ant-design/icons';
import { Avatar, Card, List, Tooltip, Row, Col, Typography } from 'antd';
import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { router } from 'umi';
import styles from './index.less';
import CreateModalForm from './CreateModalForm';
import { PROJECT_TYPE, PAGE_SIZE } from '@/pages/constants';
const Projects = connect(({ user, accountCenter, loading }) => ({
currentUser: user.currentUser,
myProjects: accountCenter.myProjects,
loading: loading.effects['accountCenter/fetchMyProject'],
}))(props => {
const {
currentUser,
myProjects: { list, pagination },
loading,
location: {
query: { pp = 1, ...rest },
},
fetchMyProject,
} = props;
const dataLoading = loading || !list;
const isSuperUser = currentUser && Object.keys(currentUser).length && currentUser.is_superuser;
/** Handler */
const handleOnChange = newPage => {
router.push({
query: { ...rest, pp: newPage },
});
fetchMyProject(newPage);
};
return (
<React.Fragment>
{isSuperUser && <CreateModalForm buttonText="New Project" className={styles.createModal} />}
<List
rowKey="id"
className={styles.filterCardList}
grid={{
gutter: 24,
xxl: 2,
xl: 2,
lg: 2,
md: 2,
sm: 2,
xs: 1,
}}
loading={dataLoading}
dataSource={list}
pagination={{
onChange: handleOnChange,
defaultPageSize: PAGE_SIZE,
total: pagination.count,
current: pp ? Number(pp) : 1,
}}
renderItem={item => {
const stat = item.project_stat;
const taskNumber = stat && stat.docs_stat && `${stat.docs_stat.count}`;
const completeStatus = `${stat.total - stat.remaining}/${stat.total}`;
const contributors = item && item.users && Object.keys(item.users).length;
return (
<List.Item key={item.id}>
<Card
hoverable
bodyStyle={{
paddingBottom: 20,
}}
actions={[
<Tooltip title="Edit" key="edit">
<EditOutlined onClick={() => router.push(`/projects/${item.id}/dashboard`)} />
</Tooltip>,
<Tooltip title="Download" key="download">
<DownloadOutlined />
</Tooltip>,
<Tooltip title="Share" key="share">
<ShareAltOutlined />
</Tooltip>,
]}
>
<Card.Meta
avatar={<Avatar src={item.image} />}
title={item.name}
description={
<Row gutter={16} type="flex" justify="space-between">
<Col>
<Typography.Text strong>
{PROJECT_TYPE[item.project_type].tag}
</Typography.Text>
</Col>
<Col>{item.public ? 'Published' : 'Unpublished'}</Col>
</Row>
}
/>
<div className={styles.cardInfo}>
<div className={styles.paragraph}>
<Typography.Paragraph ellipsis={{ rows: 3 }}>
{item.description}
</Typography.Paragraph>
</div>
<Row type="flex" gutter={16} justify="end">
<Col>{moment(item.updated_at).fromNow()}</Col>
</Row>
<Row type="flex" gutter={16}>
<Col span={8}>
{taskNumber} {taskNumber === 1 ? ' task' : ' tasks'}
</Col>
<Col span={8}>{completeStatus} done</Col>
<Col span={8}>{contributors} contributors</Col>
</Row>
</div>
</Card>
</List.Item>
);
}}
/>
</React.Fragment>
);
});
export default Projects;
<file_sep>/config/api_router.py
from django.conf import settings
from django.urls import include, path, re_path
from rest_framework.routers import DefaultRouter, SimpleRouter
# Extend this router with your own routes
# E.g.: router.registry.extend(your_router.registry)
if settings.DEBUG:
router = DefaultRouter()
else:
router = SimpleRouter()
# API URL configuration
app_urls = [
# API
path("", include(router.urls)),
path("", include("doclabel.core.urls")),
# API Authentication
path("auth/", include("djoser.urls")),
path("auth/", include("djoser.urls.authtoken")),
path("auth/", include("djoser.social.urls")),
]
# Schema URL configuration
# schema_urls = [
# # Swagger
# re_path(
# r"swagger(?P<format>\.json|\.yaml)$",
# schema_view.without_ui(cache_timeout=0),
# name="schema-json",
# ),
# path("swagger/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui",),
# path("redoc/", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),
# ]
# Final URL configuration
app_name = "api"
urlpatterns = app_urls
<file_sep>/frontend/src/pages/annotation/model.js
import { queryAnno, addAnno, removeAnno, editAnno, markCompleted, markApproved } from './service';
export default {
namespace: 'annotation',
state: {
annotation: {},
},
effects: {
*queryAnno({ payload }, { call, put, select }) {
const { projectId, docId, data } = payload;
const res = yield call(addAnno, { projectId, docId, data });
return res;
},
*addAnno({ payload }, { call, put, select }) {
const projectId = yield select(state => state.project.currentProject.id);
const { taskId, data } = payload;
const res = yield call(addAnno, { projectId, taskId, data });
return res;
},
*editAnno({ payload }, { call, put, select }) {
const projectId = yield select(state => state.project.currentProject.id);
const { taskId, annotationId, data } = payload;
try {
const res = yield call(editAnno, { projectId, taskId, annotationId, data });
return res;
} catch (error) {
return error.data;
}
},
*removeAnno({ payload }, { call, put, select }) {
const projectId = yield select(state => state.project.currentProject.id);
const { taskId, annotationId } = payload;
const res = yield call(removeAnno, { projectId, taskId, annotationId });
},
*markCompleted(_, { call, put, select }) {
const projectId = yield select(state => state.project.currentProject.id);
const res = yield call(markCompleted, { projectId });
return res;
},
*markApproved({ payload }, { call, put, select }) {
const projectId = yield select(state => state.project.currentProject.id);
const { taskId, user, prob } = payload;
const res = yield call(markApproved, { projectId, taskId, data: { prob, user } });
return res;
},
},
reducers: {
saveAnnotation: (state, { payload = {} }) => ({
...state,
...payload,
}),
},
};
<file_sep>/frontend/src/pages/annotation/components/AnnotationArea/TextClassificationProject.jsx
import { Card, Col, Empty, Row, Spin, Tag, Typography } from 'antd';
import classNames from 'classnames';
import React from 'react';
import { useAnnotaionContext } from '../AnnotationContext';
import LabelList from '../LabelList';
import styles from './TextClassificationProject.less';
function TextClassificationProject(props) {
const {
isDisabled,
annoList = [],
labelList = [],
handleRemoveLabel,
handleAddLabel,
task,
annoLoading: loading,
} = useAnnotaionContext();
const handleChooseLabel = labelKey => {
const currentAnno = annoList;
const anno = currentAnno.find(val => val.label === Number(labelKey));
if (anno) {
handleRemoveLabel(anno.id);
} else {
// data form for request
handleAddLabel({ label: labelKey });
}
};
return (
<React.Fragment>
<Card>
<Row gutter={[0, 16]}>
<Col>
<Typography.Text strong>Labels</Typography.Text>
</Col>
<Col className={classNames({ [styles.disabled]: isDisabled })}>
<LabelList labelList={labelList} handleChooseLabel={handleChooseLabel} />
</Col>
</Row>
</Card>
<Card>
<Row gutter={[0, 16]}>
<Col>
<Typography.Text strong>Classification</Typography.Text>
</Col>
<Col>
<Spin spinning={!!loading}>
<Row
type="flex"
gutter={[16, 16]}
justify="center"
className={classNames(styles.annoList, { [styles.disabled]: isDisabled })}
>
{annoList.length > 0 &&
Object.values(annoList).map(({ label, id }) => (
<Col key={id}>
{labelList[label] && (
<Tag
style={{ color: labelList[label].text_color }}
key={id}
color={labelList[label].background_color}
closable
onClose={() => handleRemoveLabel(id)}
>
<span>{labelList[label].text}</span>
</Tag>
)}
</Col>
))}
{!(annoList.length > 0) && (
<Col>
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={false}
imageStyle={{
height: 24,
}}
/>
</Col>
)}
</Row>
</Spin>
</Col>
</Row>
</Card>
<Card>
<Row type="flex" justify="center">
<Col>{task && <div className={styles.textContent}>{task.text}</div>}</Col>
</Row>
</Card>
</React.Fragment>
);
}
export default TextClassificationProject;
<file_sep>/frontend/src/pages/account/settings/components/SecurityView.jsx
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, message, Typography } from 'antd';
import { connect } from 'dva';
import React, { useRef, useState } from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import styles from './SecurityView.less';
const FormItem = Form.Item;
function SecurityView({ dispatch, currentUser, form, loading }) {
const viewRef = useRef(undefined);
const [confirmDirty, setConfirmDirty] = useState(false);
const validateToNextPassword = (rule, value, callback) => {
if (value && confirmDirty) {
form.validateFields(['new_password2'], { force: true });
}
callback();
};
const compareToFirstPassword = (rule, value, callback) => {
if (value && value !== form.getFieldValue('new_password1')) {
callback(
formatMessage({
id: 'user-register.password.twice',
}),
);
}
callback();
};
// eslint-disable-next-line @typescript-eslint/camelcase
const requestConfirmPassword = async ({ <PASSWORD>, <PASSWORD> }) => {
try {
const res = await dispatch({
type: 'accountSettings/changePassword',
payload: {
new_password1,
new_password2,
},
});
message.success(res.detail);
} catch (err) {
const valueWithError = {};
if (err.data) {
Object.entries(err.data).forEach(([key, val]) => {
valueWithError[key] = {
value: form.getFieldValue(key),
errors: [new Error(val[0])],
};
});
}
form.setFields({ ...valueWithError });
message.error('Something wrong! Try again');
}
};
const { getFieldDecorator, getFieldsError, validateFields } = form;
const hasErrors = fieldsError => Object.keys(fieldsError).some(field => fieldsError[field]);
return (
<div className={styles.baseView} ref={viewRef}>
<div className={styles.form}>
<div style={{ marginBottom: 16 }}>
<Typography.Text strong>Change password</Typography.Text>
</div>
<Form
layout="vertical"
hideRequiredMark
onSubmit={e => {
e.preventDefault();
validateFields((err, values) => {
if (!err) {
requestConfirmPassword(values);
}
});
}}
>
<FormItem label="New password" hasFeedback>
{getFieldDecorator('new_password1', {
rules: [
{
required: true,
message: 'Please enter your new password!',
},
{
min: 6,
message: 'Please enter at least 6 characters!',
},
{
validator: validateToNextPassword,
},
],
})(<Input type="password" placeholder="<PASSWORD>" />)}
</FormItem>
<FormItem label="Confirm new password" hasFeedback>
{getFieldDecorator('new_password2', {
rules: [
{
required: true,
message: 'Please confirm your new password!',
},
{
validator: compareToFirstPassword,
},
],
})(
<Input
type="password"
placeholder="<PASSWORD> password"
onBlur={e => setConfirmDirty(confirmDirty || !!e.target.value)}
/>,
)}
</FormItem>
<FormItem>
<Button
htmlType="submit"
type="primary"
disabled={hasErrors(getFieldsError())}
loading={loading}
>
Submit
</Button>
</FormItem>
</Form>
</div>
</div>
);
}
export default Form.create()(
connect(({ user, loading }) => ({
currentUser: user.currentUser,
loading: loading.effects['accountSettings/changePassword'],
}))(SecurityView),
);
<file_sep>/frontend/src/components/Markdown/index.jsx
import React from 'react';
import ReactMarkdown from 'react-markdown/with-html';
import SyntaxHighlighter from 'react-syntax-highlighter/';
import { darcula } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import styles from './index.less';
const CodeBlock = ({ language = null, value }) => (
<SyntaxHighlighter language={language} style={darcula}>
{value}
</SyntaxHighlighter>
);
function Markdown({ markdownSrc }) {
return (
<div className={styles.main}>
<ReactMarkdown
className="result"
source={markdownSrc}
renderers={{ code: CodeBlock }}
escapeHtml={false}
/>
</div>
);
}
export default Markdown;
<file_sep>/frontend/src/pages/account/settings/model.js
import { updateAccount, changeAvatar, changePassword } from './service';
const Model = {
namespace: 'accountSettings',
state: {},
effects: {
*updateAccount({ payload }, { call, put }) {
const res = yield call(updateAccount, { data: payload });
const ret = {
...res,
};
yield put({
type: 'user/saveCurrentUser',
payload: ret,
});
return ret;
},
*changeAvatar({ payload }, { call, put }) {
const res = yield call(changeAvatar, { data: payload });
yield put({
type: 'user/saveCurrentUser',
payload: res,
});
return res;
},
*changePassword({ payload }, { call }) {
const res = yield call(changePassword, { data: payload });
return res;
},
},
reducers: {
changeLoading(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/pages/annotation/service.js
import request from '@/utils/request';
/**
* Annotation services
*/
export async function queryAnno({ projectId, docId, data }) {
return request(`/api/projects/${projectId}/docs/${docId}/`, {
data,
});
}
export async function addAnno({ projectId, taskId, data }) {
return request(`/api/projects/${projectId}/docs/${taskId}/annotations/`, {
method: 'POST',
data,
});
}
export async function removeAnno({ projectId, taskId, annotationId }) {
return request(`/api/projects/${projectId}/docs/${taskId}/annotations/${annotationId}/`, {
method: 'DELETE',
});
}
export async function editAnno({ projectId, taskId, annotationId, data }) {
return request(`/api/projects/${projectId}/docs/${taskId}/annotations/${annotationId}/`, {
method: 'PATCH',
data,
});
}
export async function markCompleted({ projectId }) {
return request(`/api/projects/${projectId}/annotations/completed/`, {
method: 'PATCH',
});
}
export async function markApproved({ projectId, taskId, data }) {
return request(`/api/projects/${projectId}/docs/${taskId}/approve-labels/`, {
method: 'POST',
data,
});
}
<file_sep>/makefiles/server.mk
### SERVER
# ¯¯¯¯¯¯¯¯¯¯¯
server.start: ## Start server in its docker container
docker-compose -f local.yml up django
server.stop: ## Start server in its docker container
docker-compose -f local.yml stop
server.shell:
docker-compose -f local.yml run django python manage.py shell
<file_sep>/frontend/src/pages/account/center/model.js
import { fetchMyProject } from './service';
import { getPageQuery } from '@/utils/utils';
const getConversionObject = res => ({
list: Array.isArray(res.results) ? res.results : [],
pagination: {
count: res.count,
next: res.next ? getPageQuery(res.next) : null,
prev: res.previous ? getPageQuery(res.previous) : null,
},
});
const Model = {
namespace: 'accountCenter',
state: {
myProjects: {
list: [],
pagination: {},
},
myContributions: {
list: [],
listStat: [],
pagination: {},
},
myApprovals: {
list: [],
listStat: [],
pagination: {},
},
},
effects: {
*fetchMyProject({ payload }, { put, call }) {
const res = yield call(fetchMyProject, { ...payload, role_project: 'admin' });
const ret = getConversionObject(res);
yield put({
type: 'changeState',
payload: {
myProjects: ret,
},
});
return ret;
},
*fetchMyContribution({ payload }, { put, call }) {
const res = yield call(fetchMyProject, { ...payload, role_project: 'annotator' });
const ret = getConversionObject(res);
yield put({
type: 'changeState',
payload: {
myContributions: ret,
},
});
return ret;
},
*fetchMyApproval({ payload }, { put, call }) {
const res = yield call(fetchMyProject, { ...payload, role_project: 'approver' });
const ret = getConversionObject(res);
yield put({
type: 'changeState',
payload: {
myApprovals: ret,
},
});
return ret;
},
},
reducers: {
changeState(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/pages/annotation/components/ProgressBar.jsx
import React from 'react';
import { DeploymentUnitOutlined } from '@ant-design/icons';
import { Icon as LegacyIcon } from '@ant-design/compatible';
import { Button, Card, Row, Col, Progress, Modal, Typography, Tooltip, Popconfirm } from 'antd';
import Markdown from '@/components/Markdown';
import { useAnnotaionContext } from './AnnotationContext';
function ProgressBar({ totalTask, remaining, currentProject, onClickApproved, task }) {
const { annoList = [] } = useAnnotaionContext();
// Modal
const [visible, setVisible] = React.useState(false);
const hasData = currentProject && !!Object.keys(currentProject).length;
const isAnnotationApprover =
hasData &&
(currentProject.current_users_role.is_annotation_approver ||
currentProject.current_users_role.is_project_admin);
const isApproved = annoList[0] && annoList[0].prob !== 0;
return (
<Card>
<Row type="flex" gutter={[0, 24]} justify="space-between" align="middle">
<Col md={{ span: 12 }} xs={{ span: 24 }}>
<Row type="flex" gutter={24}>
<Col>
<Tooltip title="Guide line">
<Button icon={<DeploymentUnitOutlined />} size="large" onClick={() => setVisible(true)} />
</Tooltip>
<Modal
width={700}
title={<Typography.Title level={4}>Annotation Guideline</Typography.Title>}
visible={visible}
footer={null}
onCancel={() => setVisible(false)}
centered
>
<div style={{ margin: '0 24px', overflow: 'auto' }}>
<Markdown markdownSrc={currentProject.guideline} />
</div>
</Modal>
</Col>
{/* <Col>
<Tooltip title="Document Meta">
<Button icon="inbox" size="large" />
</Tooltip>
</Col> */}
{isAnnotationApprover && (
<Col>
<Tooltip title={isApproved ? 'Approved' : 'Unapproved'}>
<Button
icon={<LegacyIcon type={isApproved ? 'check-circle' : 'question-circle'} />}
size="large"
style={isApproved ? { color: '#00a854' } : {}}
type={isApproved ? 'primary' : 'warning'}
disabled={isApproved}
onClick={() =>
Modal.confirm({
title: 'Are you want to approve this task?',
content: 'After approved, you could not change the result.',
onOk: onClickApproved,
centered: true,
okText: 'Confirm',
})
}
/>
</Tooltip>
</Col>
)}
</Row>
</Col>
<Col md={{ span: 12 }} xs={{ span: 24 }}>
<div style={{ maxWidth: '350px', margin: 'auto' }}>
<Tooltip title="Progress" placement="topRight">
<Progress
percent={Math.floor(((totalTask - remaining) / totalTask) * 100)}
format={() => `${totalTask - remaining}/${totalTask}`}
status="normal"
strokeColor="#00a854"
strokeWidth={15}
/>
</Tooltip>
</div>
</Col>
</Row>
</Card>
);
}
export default ProgressBar;
<file_sep>/frontend/src/pages/project/contributor/service.js
import request from '@/utils/request';
export async function fetchProjectRoles(projectId) {
return request(`/api/projects/${projectId}/roles/`, {
method: 'GET',
});
}
export async function fetchRoles() {
return request('/api/roles/', {
method: 'GET',
});
}
export async function fetchUsers() {
return request('/api/users', {
method: 'GET',
});
}
export async function fetchProjectNotification({ projectId }) {
return request(`/api/projects/${projectId}/notifications/`, {
method: 'GET',
});
}
export async function addRole({ projectId, data }) {
return request(`/api/projects/${projectId}/roles/`, {
method: 'POST',
data,
});
}
export async function deleteRole({ projectId, roleId }) {
return request(`/api/projects/${projectId}/roles/${roleId}`, {
method: 'DELETE',
});
}
export async function switchRole({ projectId, roleId, data }) {
return request(`/api/projects/${projectId}/roles/${roleId}/`, {
method: 'PATCH',
data,
});
}
export async function markAsReadNotification({ projectId, notifyId }) {
return request(`/api/projects/${projectId}/notifications/${notifyId}/`, {
method: 'DELETE',
});
}
<file_sep>/frontend/src/pages/explore/components/FilterForm/index.jsx
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Row, Col, Select, Input } from 'antd';
import { router } from 'umi';
import { connect } from 'dva';
import { PROJECT_TYPE } from '@/pages/constants';
import StandardFormRow from '../StandardFormRow';
import TagSelect from '../TagSelect';
import styles from './index.less';
// TODO: Search by project name
const FilterForm = connect(({ projects, loading }) => ({
projects,
loadingProject: loading.models.projects,
}))(props => {
const {
dispatch,
form,
location: { query },
} = props;
const formItemLayout = {
wrapperCol: {
xs: {
span: 24,
},
sm: {
span: 16,
},
},
};
const fetchProjects = async () => {
await dispatch({
type: 'projects/fetch',
payload: query,
});
};
React.useEffect(() => {
fetchProjects();
}, [query]);
const handleSearch = q => {
router.push({
query: { ...query, q },
});
};
return (
<Card bordered={false}>
<div className={styles.searchBox}>
<Input.Search
placeholder="Input project name or description"
enterButton="Search"
size="large"
onSearch={handleSearch}
style={{
maxWidth: 522,
width: '100%',
}}
/>
</div>
<Form layout="inline">
<StandardFormRow
title="Category"
block
style={{
paddingBottom: 11,
}}
>
<Form.Item>
{form.getFieldDecorator('type', {
initialValue: Object.keys(PROJECT_TYPE),
})(
<TagSelect>
{Object.keys(PROJECT_TYPE).map(key => (
<TagSelect.Option value={key} key={key}>
{PROJECT_TYPE[key].label}
</TagSelect.Option>
))}
</TagSelect>,
)}
</Form.Item>
</StandardFormRow>
{/* <StandardFormRow
title="Other options"
grid
last
style={{
paddingBottom: 11,
}}
>
<Row gutter={16}>
<Col lg={8} md={10} sm={10} xs={24}>
<Form.Item {...formItemLayout} label="Author">
{form.getFieldDecorator(
'author',
{},
)(
<Select
placeholder="Unlimited"
style={{
maxWidth: 200,
width: '100%',
}}
>
<Select.Option value="lisa"><NAME></Select.Option>
</Select>,
)}
</Form.Item>
</Col>
<Col lg={8} md={10} sm={10} xs={24}>
<Form.Item {...formItemLayout} label="Popularity">
{form.getFieldDecorator(
'rate',
{},
)(
<Select
placeholder="Unlimited"
style={{
maxWidth: 200,
width: '100%',
}}
>
<Select.Option value="good">Excellent</Select.Option>
<Select.Option value="normal">Ordinary</Select.Option>
</Select>,
)}
</Form.Item>
</Col>
</Row>
</StandardFormRow> */}
</Form>
</Card>
);
});
export default Form.create({
onValuesChange(props, changedValues, allValue) {
router.push({
query: { project_type: changedValues.type },
});
},
})(React.memo(FilterForm));
<file_sep>/frontend/src/pages/Home/components/FeatureCards.jsx
import format from '@/assets/features/format.svg';
import group from '@/assets/features/group.svg';
import languages from '@/assets/features/languages.svg';
import text from '@/assets/features/text.svg';
import { Card, Col, Row, Typography } from 'antd';
import Meta from 'antd/lib/card/Meta';
import React from 'react';
import styles from './index.less';
function FeatureCards(props) {
const data = [
{
key: '#1',
image: group,
title: 'Team Collaboration',
description: 'Define guidelines and invite others to join your project',
},
{
key: '#2',
image: text,
title: 'Text Annotation Tool',
description: 'Variety in the type annotation tool',
},
{
key: '#3',
image: format,
title: 'Multiple formats',
description: 'Annotation with team collaboration',
},
{
key: '#4',
image: languages,
title: 'Multilingual support',
description: 'English, Vietnamese, etc',
},
];
return (
<div className={styles.featureCards}>
<Typography.Title className={styles.featureTitle} level={2}>
Features
</Typography.Title>
<Row type="flex" align="stretch" justify="center" gutter={[24, 24]}>
{data.map(item => (
<Col xs={24} md={6} key={item.key}>
<Card
style={{ height: '100%' }}
hoverable
cover={
<div className={styles.cardCover}>
<img alt={item.key} src={item.image} />
</div>
}
>
<Meta
title={
<Typography.Title level={4} strong>
{item.title}
</Typography.Title>
}
description={
<Typography.Paragraph ellipsis={{ rows: 2 }}>
{item.description}
</Typography.Paragraph>
}
/>
</Card>
</Col>
))}
</Row>
</div>
);
}
export default React.memo(FeatureCards);
<file_sep>/doclabel/users/serializers.py
from djoser.serializers import UserSerializer as DjoserUserSerializer
from rest_framework import serializers
class UserSerializer(DjoserUserSerializer):
avatar = serializers.ImageField(use_url=True)
class Meta(DjoserUserSerializer.Meta):
fields = DjoserUserSerializer.Meta.fields + ("avatar", "is_superuser",)
<file_sep>/frontend/src/pages/project/task/components/constants.js
// import uploadTextClassificationTxt from '@/assets/examples/upload_text_classification.txt';
// import uploadTextClassificationCsv from '@/assets/examples/upload_text_classification.csv';
// import uploadTextClassificationJsonl from '@/assets/examples/upload_text_classification.jsonl';
// import uploadTextClassificationXlsx from '@/assets/examples/upload_text_classification.xlsx';
// import uploadSeq2seqTxt from '@/assets/examples/upload_seq2seq.txt';
// import uploadSeq2seqJsonl from '@/assets/examples/upload_seq2seq.jsonl';
// import uploadSeq2seqCsv from '@/assets/examples/upload_seq2seq.csv';
// import uploadSeq2seqXlsx from '@/assets/examples/upload_seq2seq.xlsx';
// import uploadSequenceLabelingTxt from '@/assets/examples/upload_sequence_labeling.txt';
// import uploadSequenceLabelingJsonl from '@/assets/examples/upload_sequence_labeling.jsonl';
// import uploadSequenceLabelingConll from '@/assets/examples/upload_sequence_labeling.conll';
// import uploadPdfLabelingJsonl from '@/assets/examples/upload_pdf_labeling.jsonl';
export const TextClassificationProject = {
json: {
label: 'JSONL',
format: 'uploadTextClassificationJsonl',
},
csv: { label: 'CSV', format: 'uploadTextClassificationCsv' },
excel: {
label: 'Excel',
format: 'uploadTextClassificationXlsx',
},
plain: {
label: 'Plain',
format: 'uploadTextClassificationTxt',
},
};
export const SequenceLabelingProject = {
json: {
label: 'JSONL',
format: 'uploadSequenceLabelingJsonl',
},
// conll: {
// label: 'Conll',
// format: uploadSequenceLabelingConll,
// },
plain: {
label: 'Plain',
format: 'uploadSequenceLabelingTxt',
},
};
export const Seq2seqProject = {
json: {
label: 'JSONL',
format: 'uploadSeq2seqJsonl',
},
csv: {
label: 'CSV',
format: 'uploadSeq2seqCsv',
},
excel: {
label: 'Excel',
format: 'uploadSeq2seqXlsx',
},
plain: {
label: 'Plain',
format: 'uploadSeq2seqTxt',
},
};
export const PdfLabelingProject = {
json: {
label: 'JSONL',
format: 'uploadPdfLabelingJsonl',
},
pdf: {
label: 'PDF',
format: 'Upload new PDF file',
},
};
<file_sep>/frontend/src/pages/project/label/index.jsx
import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Card, Divider, Table, Popconfirm, Typography } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import styles from './index.less';
import CreateForm from './components/CreateForm';
import { PROJECT_TYPE } from '@/pages/constants';
// TODO: make color random
function LabelPage({ dispatch, updateLoading, createLoading, loading, label, currentProject }) {
const { list: dataSource } = label;
const projectId = currentProject.id;
// States
const [modalVisible, setModalVisible] = React.useState(false);
const [modalUpdateVisible, setModalUpdateVisible] = React.useState(false);
const formRef = React.useRef(null);
// Effects
React.useEffect(() => {
dispatch({
type: 'label/fetch',
});
}, []);
// Functions
const callBackFormError = errors => {
if (errors) {
const [key, errorMsg] = errors.non_field_errors[0].split(':');
console.log(key, errorMsg);
formRef.current.setFields({
[key]: {
value: formRef.current.getFieldValue(key),
errors: [new Error(errorMsg)],
},
});
message.error('Something wrong!');
} else {
message.success('Label added successfully!');
dispatch({
type: 'label/fetch',
payload: projectId,
});
}
};
const handleAddLabel = values => {
dispatch({
type: 'label/add',
payload: {
projectId,
data: values,
},
callback: callBackFormError,
});
};
const handleUpdateLabel = values => {
console.log('TCL: values', values);
dispatch({
type: 'label/update',
payload: {
projectId,
labelId: values.id,
data: values,
},
callback: errors => {
if (errors) {
const [key, errorMsg] = errors.non_field_errors[0].split(':');
console.log(key, errorMsg);
formRef.current.setFields({
[key]: {
value: formRef.current.getFieldValue(key),
errors: [new Error(errorMsg)],
},
});
message.error('Something wrong!');
} else {
message.success('Updated successfully!');
dispatch({
type: 'label/fetch',
payload: projectId,
});
}
},
});
};
const handleRemoveLabel = record => {
dispatch({
type: 'label/remove',
payload: {
projectId,
labelId: record.id,
},
callback: errors => {
if (errors) {
message.error('Something wrong!');
} else {
message.success('Deleted successfully!');
dispatch({
type: 'label/fetch',
payload: projectId,
});
}
},
});
};
const handleUpdateModalVisible = record => {
setModalUpdateVisible(true);
formRef.current.setFieldsValue({
...record,
});
};
// Variables
const columns = [
{
title: '#',
dataIndex: 'id',
},
{
title: 'Text',
dataIndex: 'text',
// mark to display a total number
// needTotal: true,
},
{
title: 'Prefix',
dataIndex: 'prefix_key',
align: 'right',
render: text => text && text.toUpperCase(),
},
{
title: 'Key',
dataIndex: 'suffix_key',
render: text => text.toUpperCase(),
},
{
title: 'Preview',
dataIndex: 'background_color',
render: (text, record) => (
<Button style={{ backgroundColor: text, color: record.text_color }}>{record.text}</Button>
),
},
// {
// title: 'text_color',
// dataIndex: 'text_color',
// },
{
title: 'Operation',
render: (text, record) => (
<React.Fragment>
<a onClick={() => handleUpdateModalVisible(record)}>Update</a>
<Divider type="vertical" />
<Popconfirm
title="Are you sure delete this label?"
onConfirm={() => handleRemoveLabel(record)}
okText="Yes"
cancelText="No"
>
<a href="#">Delete</a>
</Popconfirm>
</React.Fragment>
),
},
];
const dataSourceTranform = React.useMemo(() => {
const list = dataSource ? Object.entries(dataSource).map(([key, val]) => val) : [];
return list;
}, [dataSource]);
const isShow = currentProject.project_type !== 'Seq2seqProject';
return (
<PageHeaderWrapper
content={
<React.Fragment>
{isShow && (
<Button icon={<PlusOutlined />} type="primary" onClick={() => setModalVisible(true)}>
Add label
</Button>
)}
{!isShow && (
<Typography.Text type="warning" style={{ fontSize: '16px' }}>
{currentProject.project_type && PROJECT_TYPE[currentProject.project_type].label}{' '}
project does not use labels for annotation !
</Typography.Text>
)}
</React.Fragment>
}
>
{isShow && (
<React.Fragment>
<Card bordered={false}>
<div className={styles.tableList}></div>
<Table
rowKey={record => record.id}
loading={loading}
dataSource={dataSourceTranform}
columns={columns}
/>
</Card>
<CreateForm
onCreate={form => {
formRef.current = form;
}}
modalVisible={modalVisible}
setModalVisible={setModalVisible}
loading={createLoading}
handleSubmit={handleAddLabel}
/>
<CreateForm
onCreate={form => {
formRef.current = form;
}}
modalVisible={modalUpdateVisible}
setModalVisible={setModalUpdateVisible}
loading={updateLoading}
handleSubmit={handleUpdateLabel}
/>
</React.Fragment>
)}
</PageHeaderWrapper>
);
}
export default connect(({ project, label, loading }) => ({
currentProject: project.currentProject,
label,
loading: loading.effects['label/fetch'],
createLoading: loading.effects['label/add'],
updateLoading: loading.effects['label/update'],
}))(LabelPage);
<file_sep>/frontend/src/pages/user/register/locales/en-US.ts
export const APP_NAME = 'doclabel';
export const FIRST_NAME_MAX_LENGTH = 30;
export const LAST_NAME_MAX_LENGTH = 150;
export const USER_NAME_MAX_LENGTH = 150;
export const NOT_VALID_CHARS = '$#&\\/| ';
export default {
'user-register.register.register': 'Sign up an account',
'user-register.register.sign-up': 'Sign up',
'user-register.first_name.required': 'Please enter your first name!',
'user-register.first_name.length': `First name must be ${FIRST_NAME_MAX_LENGTH} characters long or fewer`,
'user-register.first_name.placeholder': 'First name',
'user-register.last_name.required': 'Please enter your last name!',
'user-register.last_name.length': `Last name must be ${LAST_NAME_MAX_LENGTH} characters long or fewer`,
'user-register.last_name.placeholder': 'Last name',
'user-register.username.required': 'Please enter your user name!',
'user-register.username.length': `User name must be between 3 and ${USER_NAME_MAX_LENGTH} characters long`,
'user-register.username.wrong-format': 'Special characters and space are forbidden',
'user-register.username.placeholder': 'Username',
'user-register.email.required': 'Please enter your email!',
'user-register.email.wrong-format': 'The email address is in the wrong format!',
'user-register.email.placeholder': 'Email',
'user-register.password.required': 'Please enter your password!',
'user-register.password.length': 'Password too short!',
'user-register.password.placeholder': 'Password',
'user-register.password.twice': 'The passwords entered twice do not match!',
'user-register.strength.msg':
"Please enter at least 6 characters and don't use passwords that are easy to guess.",
'user-register.strength.strong': 'Strength: strong',
'user-register.strength.medium': 'Strength: medium',
'user-register.strength.short': 'Strength: too short',
'user-register.confirm-password.required': 'Please confirm your password!',
'user-register.confirm-password.placeholder': '<PASSWORD>',
'user-register.register.sign-in': 'Already have an account?',
'user-register.register.resend-activation': 'Resend activation email',
'user-register.consent.content': `I accept receiving emails from ${APP_NAME}`,
};
<file_sep>/frontend/src/pages/project/label/model.ts
import { addLabel, queryLabel, removeRule, updateLabel } from './service';
import { arrayToObject } from '@/utils/utils';
const Model = {
namespace: 'label',
state: {
list: [],
},
effects: {
*fetch({ payload }, { call, put, select, take }) {
let projectId = yield select(state => state.project.currentProject.id);
if (!projectId) {
const action = yield take('project/saveCurrentProject');
projectId = action.payload.id;
}
const response = yield call(queryLabel, { projectId, ...payload });
const ret = arrayToObject(response, 'id');
yield put({
type: 'save',
payload: ret,
});
return ret;
},
*add({ payload, callback }, { call, put }) {
const response = yield call(addLabel, payload);
const { statusCode } = response;
if (statusCode) {
delete response.statusCode;
if (callback) callback(response);
} else {
// TODO: Re fetching ?
console.log('TCL: *add -> response', response);
if (callback) callback();
}
},
*update({ payload, callback }, { call }) {
const response = yield call(updateLabel, payload);
const { statusCode: error } = response;
if (error) {
delete response.statusCode;
if (callback) callback(response);
} else {
// TODO: Re fetching ?
console.log('TCL: *add -> response', response);
if (callback) callback();
}
},
*remove({ payload, callback }, { call, put }) {
const response = yield call(removeRule, payload);
if (callback) callback();
},
*reset(_, { put }) {
yield put({
type: 'save',
payload: [],
});
},
},
reducers: {
save(state, action) {
return { ...state, list: action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/models/auth.ts
import {
activation,
getOAuth,
login,
loginOAuth,
logout,
register,
resendActivation,
resetPassword,
resetPasswordConfirm,
} from '@/services/auth';
import { setAuthority, setAuthorization } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';
import { getPageQuery } from '@/utils/utils';
import { Effect } from 'dva';
import { Reducer } from 'redux';
import { router } from 'umi';
export interface AuthModelState {
token?: string;
}
export interface AuthModelType {
namespace: 'auth';
state: AuthModelState;
effects: {
register: Effect;
activation: Effect;
resendActivation: Effect;
login: Effect;
logout: Effect;
resetPassword: Effect;
resetPasswordConfirm: Effect;
getOAuth: Effect;
loginOAuth: Effect;
};
reducers: {
changeAuth: Reducer<AuthModelState>;
};
}
const Model: AuthModelType = {
namespace: 'auth',
state: {
token: undefined,
},
effects: {
*register({ payload }, { call }) {
const res = yield call(register, payload);
return res;
},
*activation({ payload }, { call }) {
const res = yield call(activation, payload);
return res;
},
*resendActivation({ payload }, { call }) {
const res = yield call(resendActivation, payload);
return res;
},
*login({ payload }, { call, put }) {
const res = yield call(login, payload);
yield put({
type: 'changeAuth',
payload: {
token: res.auth_token,
},
});
// /**
// * Redirect
// */
const urlParams = new URL(window.location.href);
const params = getPageQuery();
let { redirect } = params as { redirect: string };
if (redirect) {
const redirectUrlParams = new URL(redirect);
if (redirectUrlParams.origin === urlParams.origin) {
redirect = redirect.substr(urlParams.origin.length + 4);
if (redirect.match(/^\/.*#/)) {
redirect = redirect.substr(redirect.indexOf('#') + 1);
}
} else {
window.location.href = redirect;
return;
}
}
router.replace(redirect || '/');
},
*logout(_, { call, put }) {
const res = yield call(logout);
yield put({
type: 'changeAuth',
payload: {
key: undefined,
},
});
yield put({
type: 'user/saveCurrentUser',
payload: {},
});
setAuthority();
reloadAuthorized();
return res;
},
*resetPassword({ payload }, { call }) {
yield call(resetPassword, payload);
},
*resetPasswordConfirm({ payload }, { call, put }) {
const res = yield call(resetPasswordConfirm, payload);
yield put({
type: 'changeAuth',
payload: res,
});
return res;
},
*getOAuth({ payload }, { call }) {
const res = yield call(getOAuth, payload);
return res;
},
*loginOAuth({ payload }, { call, put }) {
const res = yield call(loginOAuth, payload);
yield put({
type: 'changeAuth',
payload: {
token: res.access,
},
});
return res;
},
},
reducers: {
changeAuth(state, { payload }) {
setAuthorization(payload.token);
return { ...state, ...payload };
},
},
};
export default Model;
<file_sep>/frontend/src/pages/user/permission/services/usersService.js
import request from '@/utils/request';
/**
* User查询
*/
export const queryUsersList = () => request('/api/queryUsersList');
/**
* User分配角色
*/
export const assignRole = ({ userId, role }) =>
request('/api/assignRole', { method: 'POST', data: { userId, role } });
<file_sep>/doclabel/core/migrations/0015_auto_20191216_1857.py
# Generated by Django 2.2.6 on 2019-12-16 18:57
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0014_sequenceannotation_text'),
]
operations = [
migrations.RemoveField(
model_name='sequenceannotation',
name='text',
),
migrations.AddField(
model_name='sequenceannotation',
name='tokens',
field=django.contrib.postgres.fields.jsonb.JSONField(default=''),
preserve_default=False,
),
]
<file_sep>/frontend/src/pages/project/export/model.js
import { download } from './service';
const Model = {
namespace: 'extract',
state: {},
effects: {
*download({ payload }, { call, select, take }) {
let projectId = yield select(state => state.project.currentProject.id);
if (!projectId) {
const action = yield take('project/saveCurrentProject');
projectId = action.payload.id;
}
const { format, userId } = payload;
const res = yield call(download, { projectId, format, userId });
return res;
},
},
reducers: {
changeState(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/pages/annotation/components/SiderList/index.jsx
import { PROJECT_TYPE } from '@/pages/constants';
import { CheckOutlined } from '@ant-design/icons';
import { Button, Col, Descriptions, Modal, Row, Select, Typography, Spin } from 'antd';
import React, { useContext } from 'react';
import { Link } from 'umi';
import { useAnnotaionContext } from '../AnnotationContext';
import styles from './index.less';
function SiderList({ itemProps, onSubmit }) {
const {
currentProject,
annotations,
annoList,
taskList,
isApprover,
isNotApprover,
annotationValue,
setAnnotationValue,
pagination,
sidebarTotal,
sidebarPage,
submitLoading,
remaining,
projectLoading,
isProjectAdmin,
} = useAnnotaionContext();
const { name } = itemProps;
const isSubmitDisabled = Number(remaining) !== 0;
const isFinished = annoList && annoList[0] && annoList[0].finished;
const hasData = currentProject && Object.keys(currentProject).length;
const dataLoading = projectLoading || !hasData;
const getAnnotators = () => {
if (Object.keys(currentProject).length) {
return currentProject.users;
}
return [];
};
const showConfirm = () => {
Modal.confirm({
title: 'Are you sure to submit this task ?',
content: 'You can not change the answers after submit.',
onOk: onSubmit,
centered: true,
okText: 'Submit',
});
};
if (name === 'menu') {
return (
<Spin spinning={dataLoading} size="small">
{hasData && (
<div style={{}}>
<Descriptions title="Project Info" size="middle" column={1}>
<Descriptions.Item label="Name">{currentProject.name}</Descriptions.Item>
<Descriptions.Item label="Type">
{PROJECT_TYPE[currentProject.project_type].tag}
</Descriptions.Item>
{isProjectAdmin && (
<Descriptions.Item label="Settings">
<Link to={`/projects/${currentProject.id}/dashboard`}>Edit</Link>
</Descriptions.Item>
)}
</Descriptions>
</div>
)}
</Spin>
);
}
if (name === 'about') {
return (
<div style={{ textAlign: 'center', cursor: '' }}>
{`About ${pagination.total} tasks. (page ${sidebarPage} of ${sidebarTotal})`}
</div>
);
}
if (name === 'loading') {
return (
<div style={{ textAlign: 'center' }}>
<Spin type="small" />
</div>
);
}
if (name === 'info') {
return (
<Spin spinning={dataLoading} size="small">
{hasData && (
<div style={{}}>
<Descriptions title="Project Info" size="middle" column={1}>
<Descriptions.Item label="Name">{currentProject.name}</Descriptions.Item>
<Descriptions.Item label="Type">
{PROJECT_TYPE[currentProject.project_type].tag}
</Descriptions.Item>
{isProjectAdmin && (
<Descriptions.Item label="Settings">
<Link to={`/projects/${currentProject.id}/dashboard`}>Edit</Link>
</Descriptions.Item>
)}
</Descriptions>
</div>
)}
</Spin>
);
}
if (name === 'field' && isNotApprover) {
return (
<Button
type="primary"
size="large"
block
onClick={showConfirm}
disabled={isSubmitDisabled || isFinished}
loading={submitLoading}
>
{isFinished ? 'Finished' : 'Submit'}
</Button>
);
}
if (name === 'field' && isApprover) {
return (
<Select
showSearch
placeholder="Select a annotation"
onChange={value => {
setAnnotationValue(value);
}}
value={annotationValue}
// onFocus={onFocus}
// onBlur={onBlur}
// onSearch={onSearch}
size="large"
style={{ width: '100%' }}
>
{getAnnotators().map(item => (
<Select.Option value={item.id} key={item.id}>
<span style={{ fontWeight: 500 }}>{item.username}</span>
<span> - {item.full_name}</span>
</Select.Option>
))}
</Select>
);
}
return (
<Row gutter={16} type="flex">
<Col span={2}>
{annotations[name] && annotations[name].length !== 0 && <CheckOutlined />}
</Col>
<Col span={22}>
<Typography.Paragraph ellipsis>{taskList[name].text}</Typography.Paragraph>
</Col>
</Row>
);
}
export default React.memo(SiderList);
<file_sep>/frontend/src/pages/account/center/components/Projects/CreateModalForm/FormContext.jsx
import React from 'react';
// Context
export const FormContext = React.createContext({});
// Hook
export const useFormContext = () => {
const form = React.useContext(FormContext);
if (!form) {
throw new Error('Missing FormContextProvider in it parent.');
}
return form;
};
<file_sep>/frontend/src/pages/project/guide/service.js
import request from '@/utils/request';
export async function updateGuideline({ projectId, data }) {
return request(`/api/projects/${projectId}/`, {
method: 'PATCH',
data,
});
}
<file_sep>/frontend/src/pages/project/setting/components/TaskSettings/index.jsx
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Card, Typography, Select, InputNumber, message, Spin } from 'antd';
import { connect } from 'dva';
import styles from './index.less';
const TaskSettings = connect(({ loading, project }) => ({
currentProject: project.currentProject,
loading: loading.effects['setting/updateProject'],
}))(props => {
const { dispatch, form, currentProject, loading } = props;
/**
* Handler
*/
const handleSubmit = async e => {
e.preventDefault();
const values = form.getFieldsValue();
try {
await dispatch({
type: 'setting/updateProject',
payload: values,
});
message.success('Successfully updated!');
} catch ({ data }) {
const valueWithError = {};
if (data) {
Object.entries(data).forEach(([key, val]) => {
// const msg = formatMessage({
// id: messageID[val[0]],
// });
valueWithError[key] = {
value: form.getFieldValue(key),
errors: [new Error(val[0])],
};
});
}
form.setFields({ ...valueWithError });
message.error('Something wrong! Try again!');
}
};
/**
* Effects
*/
React.useEffect(() => {
if (currentProject) {
form.setFieldsValue({
annotator_per_example: currentProject.annotator_per_example,
});
}
}, [currentProject]);
/**
* Variables
*/
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 20,
offset: 4,
},
},
};
const hasErrors = fieldsError => Object.keys(fieldsError).some(field => fieldsError[field]);
const isTouched = Object.keys(form.getFieldsValue()).some(field => form.isFieldTouched(field));
return (
<div className={styles.taskSettings}>
<Card title={<Typography.Title level={4}>Task settings</Typography.Title>}>
<Spin spinning={!!loading}>
<Form {...formItemLayout} layout="vertical" onSubmit={handleSubmit} hideRequiredMark>
<Form.Item label="Task redundancy">
{form.getFieldDecorator('annotator_per_example')(
<InputNumber min={1} max={100} style={{ width: 150 }} />,
)}
</Form.Item>
<Form.Item label="Task scheduler">
{form.getFieldDecorator('task_scheduler')(
<Select style={{ width: 150 }}>
<Select.Option value="">1</Select.Option>
<Select.Option value="">2</Select.Option>
</Select>,
)}
</Form.Item>
<Form.Item {...tailFormItemLayout}>
<Button
htmlType="submit"
type="primary"
disabled={hasErrors(form.getFieldsError()) || !isTouched}
>
Update
</Button>
</Form.Item>
</Form>
</Spin>
</Card>
</div>
);
});
export default Form.create()(React.memo(TaskSettings));
<file_sep>/doclabel/core/serializers.py
from django.contrib.auth import get_user_model
from django.conf import settings
from rest_framework import serializers
from rest_polymorphic.serializers import PolymorphicSerializer
from rest_framework.exceptions import ValidationError
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError as ValidationErrorCore
from rest_framework.validators import UniqueTogetherValidator
from django.core.files.storage import FileSystemStorage
from doclabel.users.serializers import UserSerializer
from notifications.models import Notification
from django.db.models import Count, Q
from .models import Label, Project, Document, RoleMapping, Role
from .models import (
TextClassificationProject,
SequenceLabelingProject,
Seq2seqProject,
PdfLabelingProject,
)
from .models import (
DocumentAnnotation,
SequenceAnnotation,
Seq2seqAnnotation,
PdfAnnotation,
)
UserModel = get_user_model()
class LabelSerializer(serializers.ModelSerializer):
def validate(self, attrs):
prefix_key = attrs["prefix_key"] if ("prefix_key" in attrs) else None
suffix_key = attrs["suffix_key"] if ("suffix_key" in attrs) else None
# In the case of user don't set any shortcut key.
if prefix_key is None and suffix_key is None:
return super().validate(attrs)
# Don't allow shortcut key not to have a suffix key.
if prefix_key and not suffix_key:
raise ValidationError("suffix_key:Shortcut key may not have a suffix key.")
# Don't allow to save same shortcut key when prefix_key is null.
try:
context = self.context["request"].parser_context
project_id = context["kwargs"]["project_id"]
label_id = context["kwargs"]["label_id"]
except (AttributeError, KeyError):
pass # unit tests don't always have the correct context set up
else:
if (
Label.objects.exclude(id=label_id)
.filter(
suffix_key=suffix_key, prefix_key=prefix_key, project=project_id
)
.exists()
):
raise ValidationError("suffix_key:Duplicate shortcut key.")
return super().validate(attrs)
class Meta:
model = Label
fields = (
"id",
"text",
"prefix_key",
"project",
"suffix_key",
"background_color",
"text_color",
)
validators = [
UniqueTogetherValidator(
queryset=Label.objects.all(),
fields=["text", "project"],
message="text:Duplicate text label for this project",
)
]
class DocumentSerializer(serializers.ModelSerializer):
annotations = serializers.SerializerMethodField()
annotation_approver = serializers.SerializerMethodField()
file_url = serializers.SerializerMethodField()
def get_file_url(self, instance):
request = self.context.get("request")
fs = FileSystemStorage(location=settings.MEDIA_ROOT + "/pdf_documents/")
if fs.exists(instance.text):
return request.build_absolute_uri("/media/pdf_documents/" + instance.text)
val = URLValidator()
try:
val(instance.text)
return instance.text
except ValidationErrorCore:
return None
return None
def get_annotations(self, instance):
request = self.context.get("request")
project = instance.project
model = project.get_annotation_class()
serializer = project.get_annotation_serializer()
annotations = model.objects.filter(document=instance.id)
role = RoleMapping.objects.get(user=request.user, project=project).role
if role.name == settings.ROLE_ANNOTATION_APPROVER:
try:
user = UserModel.objects.get(pk=request.GET.get("user", None))
annotations = annotations.filter(user=user)
except UserModel.DoesNotExist:
raise serializers.ValidationError("Request data missing!")
elif role.name == settings.ROLE_ANNOTATOR:
# if not project.collaborative_annotation:
annotations = annotations.filter(user=request.user)
elif role.name == settings.ROLE_PROJECT_ADMIN:
user_id = request.GET.get("user", None)
if user_id:
user = UserModel.objects.get(pk=request.GET.get("user", None))
annotations = annotations.filter(user=user)
else:
annotations = annotations.filter(user=request.user)
serializer = serializer(annotations, many=True, context={"request": request})
return serializer.data
@classmethod
def get_annotation_approver(cls, instance):
approver = instance.annotations_approved_by
return approver.username if approver else None
class Meta:
model = Document
fields = (
"id",
"text",
"annotations",
"meta",
"annotation_approver",
"file_url",
)
class ProjectSerializer(serializers.ModelSerializer):
current_users_role = serializers.SerializerMethodField()
users = UserSerializer(read_only=True, many=True)
project_stat = serializers.SerializerMethodField()
def get_project_stat(self, instance):
docs = instance.documents
annotator_per_example = instance.annotator_per_example
annotation_class = instance.get_annotation_class()
docs_stat = {}
remaining = 0
total = 0
# General case
aggregatation = {}
for val in instance.users.values_list("id", flat=True):
aggregatation["count_" + str(val)] = Count(
"document", distinct=True, filter=Q(user_id=val)
)
total = docs.count() * annotator_per_example
done = sum(
annotation_class.objects.filter(document_id__in=docs.all())
.aggregate(**aggregatation)
.values()
)
remaining = total - done
docs_stat["count"] = docs.count() * instance.users.count()
request = self.context["request"]
role_project = request.GET.get("role_project")
if role_project == "annotator":
total = docs.count()
done = annotation_class.objects.filter(
document_id__in=docs.all(), user_id=request.user.id
).aggregate(Count("document", distinct=True))["document__count"]
remaining = total - done
return {"total": total, "remaining": remaining, "docs_stat": docs_stat}
def get_current_users_role(self, instance):
role_abstractor = {
"is_project_admin": settings.ROLE_PROJECT_ADMIN,
"is_annotator": settings.ROLE_ANNOTATOR,
"is_annotation_approver": settings.ROLE_ANNOTATION_APPROVER,
"is_guest": settings.ROLE_GUEST,
}
queryset = RoleMapping.objects.values("role_id__name")
if queryset:
try:
users_role = queryset.get(
project=instance.id, user=self.context.get("request").user.id
)
for key, val in role_abstractor.items():
role_abstractor[key] = users_role["role_id__name"] == val
except RoleMapping.DoesNotExist:
for key, val in role_abstractor.items():
role_abstractor[key] = False
role_abstractor["is_guest"] = True
return role_abstractor
class Meta:
model = Project
fields = (
"id",
"name",
"description",
"guideline",
"randomize_document_order",
"collaborative_annotation",
"annotator_per_example",
"public",
"image",
"updated_at",
"users",
"project_type",
"current_users_role",
"project_stat",
)
read_only_fields = (
"image",
"updated_at",
"users",
"current_users_role",
)
class TextClassificationProjectSerializer(ProjectSerializer):
class Meta(ProjectSerializer.Meta):
model = TextClassificationProject
class SequenceLabelingProjectSerializer(ProjectSerializer):
class Meta(ProjectSerializer.Meta):
model = SequenceLabelingProject
class Seq2seqProjectSerializer(ProjectSerializer):
class Meta(ProjectSerializer.Meta):
model = Seq2seqProject
class PdfLabelingProjectSerializer(ProjectSerializer):
class Meta(ProjectSerializer.Meta):
model = PdfLabelingProject
class ProjectPolymorphicSerializer(PolymorphicSerializer):
model_serializer_mapping = {
Project: ProjectSerializer,
TextClassificationProject: TextClassificationProjectSerializer,
SequenceLabelingProject: SequenceLabelingProjectSerializer,
Seq2seqProject: Seq2seqProjectSerializer,
PdfLabelingProject: PdfLabelingProjectSerializer,
}
class ProjectFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
view = self.context.get("view", None)
request = self.context.get("request", None)
queryset = super(ProjectFilteredPrimaryKeyRelatedField, self).get_queryset()
if not request or not queryset or not view:
return None
return queryset.filter(project=view.kwargs["project_id"])
class AnnotationSerializer(serializers.ModelSerializer):
label = serializers.PrimaryKeyRelatedField(queryset=Label.objects.all())
document = serializers.PrimaryKeyRelatedField(queryset=Document.objects.all())
class Meta:
abstract = True
fields = ("id", "prob", "user", "document", "finished")
read_only_fields = ("user",)
class DocumentAnnotationSerializer(AnnotationSerializer):
class Meta(AnnotationSerializer.Meta):
model = DocumentAnnotation
fields = AnnotationSerializer.Meta.fields + ("label",)
class SequenceAnnotationSerializer(AnnotationSerializer):
# label = ProjectFilteredPrimaryKeyRelatedField(queryset=Label.objects.all())
tokens = serializers.JSONField()
class Meta(AnnotationSerializer.Meta):
model = SequenceAnnotation
fields = AnnotationSerializer.Meta.fields + (
"label",
"start_offset",
"end_offset",
"tokens",
)
class Seq2seqAnnotationSerializer(AnnotationSerializer):
class Meta(AnnotationSerializer.Meta):
model = Seq2seqAnnotation
fields = AnnotationSerializer.Meta.fields + ("text",)
class PdfAnnotationSerializer(AnnotationSerializer):
content = serializers.JSONField()
position = serializers.JSONField()
image_url = serializers.SerializerMethodField()
def get_image_url(self, instance):
request = self.context.get("request")
content = instance.content
if "image" in content:
doc = instance.document
directory = "/pdf_annotations/doc_" + str(doc.id) + "/"
fs = FileSystemStorage(location=settings.MEDIA_ROOT + directory)
if fs.exists(content["image"]):
return request.build_absolute_uri(
"/media" + directory + content["image"]
)
return None
class Meta(AnnotationSerializer.Meta):
model = PdfAnnotation
fields = AnnotationSerializer.Meta.fields + (
"label",
"content",
"image_url",
"position",
)
class RoleSerializer(serializers.ModelSerializer):
class Meta:
model = Role
fields = ("id", "name")
class RoleMappingSerializer(serializers.ModelSerializer):
username = serializers.SerializerMethodField()
rolename = serializers.SerializerMethodField()
@classmethod
def get_username(cls, instance):
user = instance.user
return user.username if user else None
@classmethod
def get_rolename(cls, instance):
role = instance.role
return role.name if role else None
def validate(self, attrs):
project_id = self.context["request"].parser_context["kwargs"]["project_id"]
user = attrs.get("user")
# Check user role is admin
if (
self.instance
and self.instance.role.name == settings.ROLE_PROJECT_ADMIN
and self.instance.user.is_superuser
):
raise serializers.ValidationError(
"Can not change role of super project admin."
)
# Check exists user
try:
RoleMapping.objects.get(user=user, project=project_id)
raise serializers.ValidationError(
"This user is already assigned to a role in this project."
)
except RoleMapping.DoesNotExist:
return attrs
class Meta:
model = RoleMapping
fields = ("id", "user", "role", "username", "rolename")
class GenericNotificationRelatedField(serializers.RelatedField):
def to_representation(self, value):
request = self.context.get("request")
serializer = ProjectPolymorphicSerializer(value, context={"request": request})
if isinstance(value, Project):
serializer = ProjectPolymorphicSerializer(
value, context={"request": request}
)
if isinstance(value, Role):
serializer = RoleSerializer(value, context={"request": request})
return serializer.data
class NotificationSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
actor = UserSerializer(read_only=True)
recipient = UserSerializer(read_only=True)
unread = serializers.BooleanField(read_only=True)
target = GenericNotificationRelatedField(read_only=True)
verb = serializers.CharField()
action_object = GenericNotificationRelatedField(read_only=True)
<file_sep>/doclabel/users/token.py
class TokenStrategy:
@classmethod
def obtain(cls, user):
from rest_framework.authtoken.models import Token
token, _ = Token.objects.get_or_create(user=user)
return {"access": token.key}
<file_sep>/frontend/src/pages/project/dashboard/service.js
import request from '@/utils/request';
export async function fetchStatistics({ projectId, params }) {
return request(`/api/projects/${projectId}/statistics/`, {
method: 'GET',
params,
});
}
<file_sep>/frontend/src/pages/user/permission/models/usersModel.js
import { queryUsersList, assignRole } from '../services/usersService';
export default {
namespace: 'usersDetail',
state: {
usersList: [],
},
effects: {
*queryUsersList({ payload }, { call, put }) {
const { data = [] } = yield call(queryUsersList, payload);
yield put({ type: 'saveUsersList', payload: data });
},
*assignRole({ payload }, { call }) {
const { errCode } = yield call(assignRole, payload);
return errCode;
},
},
reducers: {
saveUsersList: (state, { payload = [] }) => ({
...state,
usersList: payload,
}),
},
};
<file_sep>/frontend/src/services/user.ts
import request from '@/utils/request';
export async function queryCurrent() {
return request('/api//auth/users/me/');
}
export async function queryNotices() {
return request('/api/notices/');
}
<file_sep>/frontend/src/pages/explore/components/Projects/index.jsx
import { HighlightTwoTone, NotificationTwoTone, ShareAltOutlined } from '@ant-design/icons';
import { Avatar, Card, List, Tooltip, Row, Col, Typography, Modal, Select, message } from 'antd';
import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { router } from 'umi';
import { stringify } from 'querystring';
import styles from './index.less';
import { PROJECT_TYPE, ROLE_LABELS, PAGE_SIZE } from '@/pages/constants';
function Projects({
dispatch,
projects: { list, pagination },
loading,
location: { query },
currentUser,
}) {
const [visible, setVisible] = React.useState(false);
const [selectedRole, setSelectedRole] = React.useState('annotator');
const [selectedProject, setSelectedProject] = React.useState({});
const handleSentRequest = async projectId => {
try {
await dispatch({
type: 'projects/requestJoinProject',
payload: {
projectId,
role: selectedRole,
},
});
message.success('Successfully sent request!');
setVisible(false);
} catch ({ data }) {
console.log('[DEBUG]: data', data);
message.error(data[0]);
}
};
const isProjectGuest = project => project.current_users_role.is_guest;
const isLogin = currentUser && currentUser.id;
return (
<Card title="Explore">
<Modal
title={`Request to join project "${selectedProject.name}"`}
visible={visible}
onOk={() => handleSentRequest(selectedProject.id)}
onCancel={() => setVisible(false)}
centered
>
<Row gutter={16} type="flex" justify="space-between">
<Col span={4} style={{ lineHeight: '38px', fontSize: '16px' }}>
Role:
</Col>
<Col span={20}>
<Select
size="large"
style={{ width: '240px' }}
value={selectedRole}
onChange={value => setSelectedRole(value)}
>
<Select.Option value="annotator">{ROLE_LABELS.annotator}</Select.Option>
<Select.Option value="annotation_approver">
{ROLE_LABELS.annotation_approver}
</Select.Option>
</Select>
</Col>
</Row>
</Modal>
<List
rowKey="id"
className={styles.filterCardList}
grid={{
gutter: 24,
xxl: 3,
xl: 3,
lg: 3,
md: 2,
sm: 2,
xs: 1,
}}
loading={loading}
dataSource={Object.values(list)}
pagination={{
onChange: newPage => {
router.push({
query: {
...query,
page: newPage,
},
});
// refetchProject(newPage);
},
defaultPageSize: PAGE_SIZE,
total: pagination.count,
current: query.page ? Number(query.page) : 1,
showQuickJumper: true,
showTotal: total => `Total ${total} projects`,
}}
renderItem={item => {
const stat = item.project_stat;
const taskNumber = stat && stat.docs_stat && `${stat.docs_stat.count}`;
const completeStatus = `${stat.total - stat.remaining}/${stat.total}`;
const contributors = item && item.users && Object.keys(item.users).length;
return (
<List.Item key={item.id}>
<Card
hoverable
bodyStyle={{
paddingBottom: 20,
}}
actions={[
<React.Fragment>
{!isProjectGuest(item) ? (
<Tooltip title="Contribute" key="contribute">
<HighlightTwoTone onClick={() => router.push(`/annotation/${item.id}`)} />
</Tooltip>
) : (
<Tooltip title="Contribute" key="contribute">
<NotificationTwoTone
onClick={() => {
if (isLogin) {
setVisible(true);
setSelectedProject(item);
} else {
const queryString = stringify({
redirect: window.location.href,
});
router.replace(`/user/login?${queryString}`);
}
}} />
</Tooltip>
)}
</React.Fragment>,
<Tooltip title="Share" key="share">
<ShareAltOutlined />
</Tooltip>,
]}
>
<Card.Meta
avatar={<Avatar src={item.image} size="large" />}
title={item.name}
description={
<Row gutter={16} type="flex" justify="space-between">
<Col>
<Typography.Text strong>
{PROJECT_TYPE[item.project_type].tag}
</Typography.Text>
</Col>
</Row>
}
/>
<div className={styles.cardInfo}>
<div className={styles.paragraph}>
<Typography.Paragraph ellipsis={{ rows: 3 }}>
{item.description}
</Typography.Paragraph>
</div>
<Row type="flex" gutter={16} justify="end" className={styles.day}>
<Col>{moment(item.updated_at).fromNow()}</Col>
</Row>
<Row type="flex" gutter={16}>
<Col span={8}>
{taskNumber} {taskNumber === 1 ? ' task' : ' tasks'}
</Col>
<Col span={8}>{completeStatus} done</Col>
<Col span={8}>{contributors} contributors</Col>
</Row>
</div>
</Card>
</List.Item>
);
}}
/>
</Card>
);
}
export default connect(({ loading, projects, user }) => ({
projects,
loading: loading.models.projects,
currentUser: user.currentUser,
}))(Projects);
<file_sep>/frontend/src/pages/project/label/service.ts
import request from '@/utils/request';
export async function queryLabel({ projectId, params }) {
return request(`/api/projects/${projectId}/labels/`, {
params,
});
}
export async function addLabel({ projectId, data }) {
return request(`/api/projects/${projectId}/labels/`, {
method: 'POST',
data,
});
}
export async function updateLabel({ projectId, labelId, data }) {
return request(`/api/projects/${projectId}/labels/${labelId}/`, {
method: 'PATCH',
data,
});
}
export async function removeRule({ projectId, labelId }) {
return request(`/api/projects/${projectId}/labels/${labelId}/`, {
method: 'DELETE',
});
}
<file_sep>/doclabel/core/migrations/0006_auto_20191025_0838.py
# Generated by Django 2.2.6 on 2019-10-25 08:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0005_auto_20191025_0815'),
]
operations = [
migrations.AlterField(
model_name='project',
name='project_type',
field=models.CharField(choices=[('textclassificationproject', 'Document Classification'), ('sequencelabelingproject', 'Sequence Labeling'), ('seq2seqproject', 'Sequence to Sequence')], max_length=30),
),
]
<file_sep>/doclabel/core/migrations/0002_auto_20191024_1802.py
# Generated by Django 2.2.6 on 2019-10-24 18:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='project',
name='project_type',
field=models.CharField(choices=[('document_classification', 'Document Classification'), ('sequence_labeling', 'Sequence Labeling'), ('seq2seq', 'Sequence to Sequence')], max_length=30),
),
]
<file_sep>/frontend/src/app.js
export const dva = {
config: {
onError(e) {},
},
};
<file_sep>/frontend/src/pages/project/contributor/model.js
import {
fetchProjectRoles,
fetchRoles,
fetchUsers,
switchRole,
addRole,
deleteRole,
fetchProjectNotification,
markAsReadNotification,
} from './service';
const Model = {
namespace: 'contributor',
state: {
roles: [],
users: [],
projectRoles: [],
notifications: [],
},
effects: {
*fetchContributor(_, { call, put, select, all, take }) {
let projectId = yield select(state => state.project.currentProject.id);
if (!projectId) {
const action = yield take('project/saveCurrentProject');
projectId = action.payload.id;
}
const { roles, users, projectRoles, notifications } = yield all({
roles: call(fetchRoles),
users: call(fetchUsers),
projectRoles: call(fetchProjectRoles, projectId),
notifications: yield call(fetchProjectNotification, { projectId }),
});
const ret = { roles, users, projectRoles, notifications };
yield put({
type: 'changeState',
payload: {
...ret,
},
});
return ret;
},
*switchRole({ payload }, { call, put, select }) {
// switch to object List => to get better performance
const projectId = yield select(state => state.project.currentProject.id);
const res = yield call(switchRole, { projectId, roleId: payload.roleId, data: payload.data });
const projectRoles = yield select(state => state.contributor.projectRoles);
const labelIndex = projectRoles.findIndex(val => val.id === res.id);
projectRoles[labelIndex] = res;
yield put({
type: 'changeState',
payload: {
projectRoles,
},
});
return projectRoles;
},
*addRole({ payload }, { call, put, select, take }) {
const projectId = yield select(state => state.project.currentProject.id);
const res = yield call(addRole, { projectId, data: payload });
const projectRoles = yield select(state => state.contributor.projectRoles);
yield put({
type: 'changeState',
payload: {
projectRoles: [...projectRoles, res],
},
});
return res;
},
*deleteRole({ payload }, { call, put, select, take }) {
const projectId = yield select(state => state.project.currentProject.id);
yield call(deleteRole, { projectId, roleId: payload });
const projectRoles = yield select(state => state.contributor.projectRoles);
yield put({
type: 'changeState',
payload: {
projectRoles: projectRoles.filter(item => item.id !== payload),
},
});
},
*markAsReadNotification({ payload }, { call, put, select }) {
const projectId = yield select(state => state.project.currentProject.id);
yield call(markAsReadNotification, { projectId, notifyId: payload });
const notifications = yield select(state => state.contributor.notifications);
yield put({
type: 'changeState',
payload: {
notifications: notifications.filter(item => item.id !== payload),
},
});
},
},
reducers: {
changeState(state, action) {
return { ...state, ...action.payload };
},
},
};
export default Model;
<file_sep>/frontend/src/pages/account/center/index.jsx
import { MailTwoTone, SmileTwoTone } from '@ant-design/icons';
import { Card, Col, Divider, Row, Button } from 'antd';
import React from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { router } from 'umi';
import Contributions from './components/Contributions';
import Approvals from './components/Approvals';
import Projects from './components/Projects';
import styles from './Center.less';
import { PAGE_SIZE } from '@/pages/constants';
const Center = connect(({ loading, user, accountCenter }) => ({
currentUser: user.currentUser,
myProjects: accountCenter.myProjects,
myContributions: accountCenter.myContributions,
myApprovals: accountCenter.myApprovals,
currentUserLoading: loading.effects['user/fetchCurrent'],
}))(props => {
const {
dispatch,
currentUser,
currentUserLoading,
location,
myProjects,
myContributions,
myApprovals,
} = props;
const { pagination } = myProjects;
const { pagination: cPagination } = myContributions;
const { pagination: aPagination } = myApprovals;
const dataLoading = currentUserLoading || !(currentUser && Object.keys(currentUser).length);
const isSuperUser = currentUser && Object.keys(currentUser).length && currentUser.is_superuser;
const dataReady = currentUser
? !!Object.keys(pagination).length
: !!(Object.keys(cPagination).length && Object.keys(aPagination).length);
const [tabKey, setTabKey] = React.useState(isSuperUser ? 'projects' : 'contributions');
const url = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
const fetchMyProject = async page => {
const offset = page ? (page - 1) * PAGE_SIZE : 0;
if (dispatch) {
await dispatch({
type: 'accountCenter/fetchMyProject',
payload: {
offset,
},
});
}
};
const fetchMyContribution = async page => {
const offset = page ? (page - 1) * PAGE_SIZE : 0;
if (dispatch) {
await dispatch({
type: 'accountCenter/fetchMyContribution',
payload: {
offset,
},
});
}
};
const fetchMyApproval = async page => {
const offset = page ? (page - 1) * PAGE_SIZE : 0;
if (dispatch) {
await dispatch({
type: 'accountCenter/fetchMyApproval',
payload: {
offset,
},
});
}
};
const fetchData = async tab => {
const arr = [
...(isSuperUser
? [
{
key: 'projects',
func: fetchMyProject,
page: location.query.pp,
},
]
: [
{
key: 'contributions',
func: fetchMyContribution,
page: location.query.pc,
},
{
key: 'approvals',
func: fetchMyApproval,
page: location.query.pa,
},
]),
].sort((a, b) => {
if (a.key === tab) return -1;
if (b.key === tab) return 1;
return 0;
});
if (isSuperUser) {
await arr[0].func(arr[0].page);
} else {
await arr[0].func(arr[0].page);
await arr[1].func(arr[1].page);
}
};
React.useEffect(() => {
if (location.query.tab) {
setTabKey(location.query.tab);
fetchData(location.query.tab);
} else fetchData();
}, []);
const onTabChange = key => {
// If you need to sync state to url
const { match } = props;
router.push({
query: { ...location.query, tab: key },
});
setTabKey(key);
};
const renderChildrenByTabKey = () => {
if (tabKey === 'projects') {
return <Projects location={location} fetchMyProject={fetchMyProject} />;
}
if (tabKey === 'contributions') {
return <Contributions location={location} fetchMyContribution={fetchMyContribution} />;
}
if (tabKey === 'approvals') {
return <Approvals location={location} fetchMyApproval={fetchMyApproval} />;
}
return null;
};
const operationTabList = [
...(isSuperUser
? [
{
key: 'projects',
tab: (
<span>
Projects{' '}
<span
style={{
fontSize: 14,
}}
>
{dataReady && `(${pagination.count})`}
</span>
</span>
),
},
]
: [
{
key: 'contributions',
tab: (
<span>
Contributions{' '}
<span
style={{
fontSize: 14,
}}
>
{dataReady && `(${cPagination.count})`}
</span>
</span>
),
},
{
key: 'approvals',
tab: (
<span>
Approval{' '}
<span
style={{
fontSize: 14,
}}
>
{dataReady && `(${aPagination.count})`}
</span>
</span>
),
},
]),
];
return (
<GridContent>
<Row gutter={24}>
<Col lg={7} md={24}>
<Card
bordered={false}
style={{
marginBottom: 24,
}}
loading={dataLoading}
>
{!dataLoading ? (
<div>
<div className={styles.avatarHolder}>
<img alt="avatar" src={currentUser.avatar || url} />
<div className={styles.name}>{currentUser.full_name}</div>
{/* <div>signature</div> */}
</div>
<div className={styles.detail}>
<p>
<MailTwoTone />
{currentUser.email}
</p>
<p>
<SmileTwoTone />
{currentUser.username}
</p>
</div>
<div className={styles.buttonEdit}>
<Button onClick={() => router.push('/account/settings')} type="primary" block>
Edit profile
</Button>
</div>
<Divider dashed />
<div className={styles.tags}>
<div className={styles.tagsTitle}>Other info</div>
{/* */}
</div>
<Divider
style={{
marginTop: 16,
}}
dashed
/>
<div className={styles.team}>
<div className={styles.teamTitle}>Notice</div>
<Row gutter={36}>{/* */}</Row>
</div>
</div>
) : null}
</Card>
</Col>
<Col lg={17} md={24}>
<Card
className={styles.tabsCard}
bordered={false}
tabList={operationTabList}
activeTabKey={tabKey}
onTabChange={onTabChange}
>
{renderChildrenByTabKey()}
</Card>
</Col>
</Row>
</GridContent>
);
});
export default React.memo(Center);
<file_sep>/frontend/src/pages/project/contributor/components/UserRequestList/index.jsx
import React from 'react';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Card, List, Button, Row, Col, Typography, Tag, Popconfirm } from 'antd';
import styles from './index.less';
import { ROLE_LABELS } from '@/pages/constants';
function UserRequestList({ list = [], onResolve, onReject, loading }) {
const [hoverItem, setHoverItem] = React.useState(null);
return (
<div className={styles.main}>
<Card bordered={false}>
<List
header={<Typography.Title level={4}>Contribution requests</Typography.Title>}
bordered={false}
dataSource={list}
loading={loading}
renderItem={(item, idx) => (
<List.Item
onMouseEnter={() => setHoverItem(idx)}
onMouseLeave={() => setHoverItem(null)}
>
<Row type="flex" justify="space-between" style={{ flex: 1 }}>
<Col span={20}>
<div
style={{
lineHeight: '32px',
}}
>
<Typography.Paragraph>
<Typography.Text>User</Typography.Text>{' '}
<Typography.Text code strong>
{item.actor.username}
</Typography.Text>{' '}
<Typography.Text>{item.verb}</Typography.Text>{' '}
{item.action_object && (
<Typography.Text code strong>
{ROLE_LABELS[item.action_object.name]}
</Typography.Text>
)}{' '}
<Typography.Text>on</Typography.Text>{' '}
<Typography.Text code strong>
{item.target.name}.
</Typography.Text>
</Typography.Paragraph>
</div>
</Col>
<Col span={4}>
{hoverItem === idx && (
<Row gutter={[0, 16]} type="flex" justify="space-around">
<Col>
<Popconfirm
title="Are you sure resole this user request?"
onConfirm={() => onResolve(item)}
>
<Button type="dashed" icon={<CheckOutlined />}>
Resolve
</Button>
</Popconfirm>
</Col>
<Col>
<Popconfirm
title="Are you sure reject this user request?"
onConfirm={() => onReject(item)}
>
<Button type="danger" icon={<CloseOutlined />}>
Reject
</Button>
</Popconfirm>
</Col>
</Row>
)}
</Col>
</Row>
</List.Item>
)}
/>
</Card>
</div>
);
}
export default React.memo(UserRequestList);
<file_sep>/doclabel/users/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
class User(AbstractUser):
email = models.EmailField(_("email address"), unique=True)
avatar = models.ImageField(upload_to="user_avatar/", blank=True)
first_name = models.CharField(_("first name"), max_length=30, blank=False)
last_name = models.CharField(_("last name"), max_length=150, blank=False)
REQUIRED_FIELDS = ["first_name", "last_name", "email"]
<file_sep>/frontend/src/services/auth.ts
import request from '@/utils/request';
import umiRequest from 'umi-request';
import { REDIRECT_URI, ProviderTypes } from '@/pages/constants';
export interface RegisterValues {
first_name: string;
last_name: string;
email: string;
username: string;
password: string;
re_password: string;
}
export interface ActivationValues {
uid: string;
token: string;
}
export interface ResendActivationValues {
email: string;
}
export interface LoginValues {
username: string;
password: string;
}
export type ResetPasswordValues = ResendActivationValues;
export interface ResetPasswordConfirmValues {
uid: string;
token: string;
new_password: string;
re_new_password: string;
}
export interface LoginOAuthValues {
code: string;
state: string;
provider: ProviderTypes;
}
export async function register(params: RegisterValues) {
return request('/api/auth/users/', {
method: 'POST',
data: params,
});
}
export async function activation(params: ActivationValues) {
return request('/api/auth/users/activation/', {
method: 'POST',
data: params,
});
}
export async function resendActivation(params: ResendActivationValues) {
return request('/api/auth/users/resend_activation/', {
method: 'POST',
data: params,
});
}
export async function login(params: LoginValues) {
return request('/api/auth/token/login/', {
method: 'POST',
data: params,
});
}
export async function logout() {
return request('/api/auth/token/logout/', {
method: 'POST',
});
}
export async function resetPassword(params: ResetPasswordValues) {
return request('/api/auth/users/reset_password/', {
method: 'POST',
data: params,
});
}
export async function resetPasswordConfirm(params: ResetPasswordConfirmValues) {
return request('/api/auth/users/reset_password_confirm/ ', {
method: 'POST',
data: params,
});
}
export async function getOAuth(provider: ProviderTypes) {
return request(`/api/auth/o/${provider}/`, {
method: 'GET',
params: {
redirect_uri: REDIRECT_URI + provider,
},
});
}
export async function loginOAuth({ provider, code, state }: LoginOAuthValues) {
return umiRequest.post(`/api/auth/o/${provider}/`, {
credentials: 'include',
requestType: 'form',
data: {
code,
state,
},
});
}
| ddd797595216a3694bd64d02ef7858fc95aeecd1 | [
"JavaScript",
"Python",
"Makefile",
"TypeScript"
] | 89 | JavaScript | sondh0127/doclabel | 2cadea9fc925435aea49ac0b56c29474664ade4e | 062c1a349b24e3d8683209e4348340fcf4491969 |
refs/heads/master | <repo_name>HonQii/Darkroom<file_sep>/Darkroom/Crafts/ResizeCraft.swift
//
// ResizeCraft.swift
// Darkroom
//
// Created by HonQi on 2020/5/31.
// Copyright © 2020 HonQi. All rights reserved.
//
#if os(macOS)
import AppKit
#else
import UIKit
#endif
public struct ResizeCraft: DarkroomCraft {
public enum FitMode {
case exact
case scaleToMin
case scaleToMax
}
private let size: CGSize
private let mode: FitMode
init(target size: CGSize, mode: FitMode = .exact) {
self.size = size
self.mode = mode
}
public func process(_ image: DarkroomImage) -> DarkroomImage? {
guard let imgRef = image.orientationCGImage else { return nil }
let originalWidth = CGFloat(imgRef.width)
let originalHeight = CGFloat(imgRef.height)
let widthRatio = size.width / originalWidth
let heightRatio = size.height / originalHeight
let scaleRatio = mode == .scaleToMin ? min(heightRatio, widthRatio) : max(heightRatio, widthRatio)
let resizedImageBounds = CGRect(x: 0, y: 0, width: round(originalWidth * scaleRatio), height: round(originalHeight * scaleRatio))
image.draw(in: resizedImageBounds)
defer { UIGraphicsEndImageContext() }
guard let resizedImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
switch (mode) {
case .scaleToMin:
return resizedImage
case .scaleToMax:
let croppedRect = CGRect(x: (resizedImage!.size.width - size.width) / 2,
y: (resizedImage!.size.height - size.height) / 2,
width: size.width, height: size.height)
return Util.croppedImageWithRect(resizedImage!, rect: croppedRect)
case .scale:
return Util.drawImageInBounds(resizedImage!, bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
}
}
<file_sep>/README.md
# Darkroom
Image Process tools
<file_sep>/Darkroom/Extensions/ImageExtensions.swift
//
// ImageExtensions.swift
// Darkroom
//
// Created by HonQi on 2020/5/31.
// Copyright © 2020 HonQi. All rights reserved.
//
import CoreGraphics
internal extension DarkroomImage {
var orientationCGImage: CGImage? {
guard let contextImage = cgImage else { return nil }
if imageOrientation == .up {
return cgImage
}
var transform : CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: .pi / -2.0)
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: .pi / 2.0)
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: .pi)
default:
break
}
switch imageOrientation {
case .rightMirrored, .leftMirrored:
transform = transform.translatedBy(x: size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .downMirrored, .upMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
break
}
let contextWidth: Int
let contextHeight: Int
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
contextWidth = contextImage.height
contextHeight = contextImage.width
break
default:
contextWidth = contextImage.width
contextHeight = contextImage.height
break
}
guard let context = CGContext(data: nil,
width: contextWidth,
height: contextHeight,
bitsPerComponent: contextImage.bitsPerComponent,
bytesPerRow: 0,
space: contextImage.colorSpace!,
bitmapInfo: contextImage.bitmapInfo.rawValue) else { return nil }
context.concatenate(transform)
context.draw(contextImage, in: CGRect(x: 0, y: 0, width: CGFloat(contextWidth), height: CGFloat(contextHeight)))
return context.makeImage()
}
}
<file_sep>/Darkroom/Darkroom.swift
//
// Darkroom.swift
// Darkroom
//
// Created by HonQi on 2020/5/31.
// Copyright © 2020 HonQi. All rights reserved.
//
#if os(macOS)
import AppKit
public typealias DarkroomImage = NSImage
public typealias DarkroomColor = NSColor
#else
import UIKit
public typealias DarkroomImage = UIImage
public typealias DarkroomColor = UIColor
#endif
public protocol DarkroomProtocol {
associatedtype WrapperType
var dr: WrapperType { get }
}
extension DarkroomImage: DarkroomProtocol {
public typealias WrapperType = DarkroomEngine
public var dr: DarkroomEngine {
return DarkroomEngine(self)
}
}
// https://medium.com/greedygame-engineering/ios-a-haiku-on-image-processing-using-swift-f2fe0131d476
// https://www.cnblogs.com/kenshincui/p/12181735.html
<file_sep>/Darkroom/Crafts/MaskColorCraft.swift
//
// MaskColorCraft.swift
// Darkroom
//
// Created by HonQi on 2020/5/31.
// Copyright © 2020 HonQi. All rights reserved.
//
import Foundation
import CoreGraphics
public struct MaskColorCraft: DarkroomCraft {
let color: DarkroomColor
init(_ color: DarkroomColor) {
self.color = color
}
public func process(_ image: DarkroomImage) -> DarkroomImage? {
return image
}
}
<file_sep>/Darkroom/DarkroomEngine.swift
//
// DarkroomEngine.swift
// Darkroom
//
// Created by HonQi on 2020/5/31.
// Copyright © 2020 HonQi. All rights reserved.
//
import Foundation
open class DarkroomEngine {
private var image: DarkroomImage?
init(_ image: DarkroomImage) {
self.image = image
}
public func process(_ crafts: DarkroomCraft) -> DarkroomImage? {
return image
}
}
<file_sep>/Darkroom/DarkroomCraft.swift
//
// DarkroomCraft.swift
// Darkroom
//
// Created by HonQi on 2020/5/31.
// Copyright © 2020 HonQi. All rights reserved.
//
import Foundation
public protocol DarkroomCraft {
func process(_ image: DarkroomImage) -> DarkroomImage?
}
public enum DarkroomCrafts {
case maskColor(DarkroomColor)
// var craft: DarkroomCraft {
//
// }
}
| bd22316c5b13917e1ca89ae5d64af62f85aea03c | [
"Swift",
"Markdown"
] | 7 | Swift | HonQii/Darkroom | 3d5d7e20fcb3ca6108ab1f416db98f662efd8eae | e52a3c79c64341306b1485ec73a198a0253e78b2 |
refs/heads/master | <repo_name>Glindorf/Flinter<file_sep>/Profile.cs
namespace Flinter
{
/// <summary>
/// This class represents a person profile,
/// for instance for a dating website
/// </summary>
public class Profile
{
#region Instance fields
private Gender _gender;
private EyeColor _eyeColor;
private HairColor _hairColor;
private HeightCategory _heightCategory;
#endregion
public enum HairColor { Brown, Blond, Black, Blue, White, Pink, Grey }
public enum EyeColor { Brown, Grey, Black, Blue, Green }
public enum Gender { Male, Female, Other }
public enum HeightCategory { Short, Medium, Tall }
#region Constructor
public Profile(Gender Gender, EyeColor EyeColor, HairColor HairColor, HeightCategory HeightCategory)
{
_gender = Gender;
_eyeColor = EyeColor;
_hairColor = HairColor;
_heightCategory = HeightCategory;
}
#endregion
#region Properties
public string Description
{
get
{
return $"You got a {_gender} with {_eyeColor} eyes and {_hairColor} hair, who is {_heightCategory}";
}
}
#endregion
}
} | e15aef24e89d0c6db9baaeefc00faef066b640e8 | [
"C#"
] | 1 | C# | Glindorf/Flinter | f1cfd980903137ec575737b5702a171b2f08e5b8 | ca62e3b5591c281680b693ce6a91451bc1b5377d |
refs/heads/master | <file_sep>
# two-phase classifier
# two-phase classifier
# two-phase classifier
# This classifier treat with 5 classes excluding Others
# Non-profit organization, for-profit organization and Medias are treated as one classes in first phase
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import copy
import pickle
import datetime
class TwoPhaseTwitterClassifier4:
def __init__(self):
pass
def loadClassifierFromFile(self,class1,class2):
self.clf1=pickle.load(open(class1))
self.clf2=pickle.load(open(class2))
pass
def trainset(self,data):
self.trainset=data
pass
def savemodel(self):
file1=datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")+"_two_phase_phase1.pkl"
file2=datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")+"_two_phase_phase2.pkl"
with open(file1, 'wb') as f:
pickle.dump(self.clf1, f)
with open(file2, 'wb') as f:
pickle.dump(self.clf2, f)
pass
def train(self,class1,class2):
xy=self.trainset
clf,clf2=DecisionTreeClassifier(),DecisionTreeClassifier()
if class1=='svm':
clf=SVC(kernel="linear",probability=True,max_iter=500)
elif class1=='log':
clf=LogisticRegression(penalty='l2', C=1,max_iter=500,solver='newton-cg')
elif class1=='decisiontree':
clf=DecisionTreeClassifier()
elif class1=='knn':
clf=KNeighborsClassifier()
if class2=='svm':
clf2=SVC(kernel="linear",probability=True,max_iter=500)
elif class2=='log':
clf2=LogisticRegression(penalty='l2', C=1,max_iter=500,solver='newton-cg')
elif class2=='decisiontree':
clf2=DecisionTreeClassifier()
elif class2=='knn':
clf2=KNeighborsClassifier()
xy2=copy.deepcopy(xy)
for i in range(len(xy)):
if xy[i][11]==2 or xy[i][11]==1:
xy2[i][11]=0
numberoftrain=len(xy)
trainx,trainy=xy[:,:11],xy[:,11]
trainx2,trainy2=xy2[:,:11],xy2[:,11]
if class1=='svm':
sc=StandardScaler()
sc.fit(trainx2)
trainx2=sc.fit_transform(trainx2)
clf.fit(trainx2,trainy2)
rtrainx,rtrainy=[],[]
if class2=='svm':
sc=StandardScaler()
sc.fit(trainx2)
trainx2=sc.fit_transform(trainx2)
for i in range(len(trainx2)):
if trainy[i]==0 or trainy[i]==2:
rtrainx.append(trainx2[i])
rtrainy.append(trainy[i])
else:
for i in range(len(trainx2)):
if trainy[i]==0 or trainy[i]==2:
rtrainx.append(trainx2[i])
rtrainy.append(trainy[i])
rtrainx=np.asarray(rtrainx)
rtrainy=np.asarray(rtrainy)
clf2.fit(rtrainx,rtrainy)
self.clf1=clf
self.clf2=clf2
pass
def test(self,xy):
if self.clf1 is None:
print "Have not trained any classifier"
return
xy2=copy.deepcopy(xy)
for i in range(len(xy)):
if xy[i][11]==2 or xy[i][11]==1:
xy2[i][11]=0
testx,testy=xy[:,:11],xy[:,11]
testx2,testy2=xy2[:,:11],xy2[:,11]
predpro=self.clf1.predict_proba(testx)
predy1=self.clf1.predict(testx)
print predy1.shape
testx2phase=[]
for i in range(len(predy1)):
if predy1[i]==0:
testx2phase.append(testx2[i])
testx2phase=np.asarray(testx2phase)
predy2=self.clf2.predict(testx2phase)
predpro2=self.clf2.predict_proba(testx2phase)
j=0
predytotal=copy.deepcopy(predy1)
notest=len(predy1)
preprototal=np.zeros((notest,5))
for i in range(len(predy1)):
preprototal[i][3]=predpro[i][1]
preprototal[i][4]=predpro[i][2]
if predy1[i]==0:
preprototal[i][int(predy2[j])]=predpro[i][0]
predytotal[i]=predy2[j]
j=j+1
print "Recall:"
print recall_score(testy,predytotal,average=None)
print "Precision:"
print precision_score(testy,predytotal,average=None)
print "F1:"
print f1_score(testy,predytotal,average=None)
print "AUC:"
for i in range(5):
scorei=preprototal[:,i]
fpr, tpr, thresholds =roc_curve(testy,scorei,pos_label=i)
print auc(fpr,tpr)
cm=confusion_matrix(testy,predytotal)
print "confusion matrix:"
print cm
aa=0.0
for i in range(5):
aa+=cm[i][i]
print "accuracy:",aa/notest
pass
<file_sep>'''
Created on Aug 30, 2017
@author: dongxinyu
'''
import os
import numpy as np
import pickle
import datetime
import json
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from Classifier import TwoPhaseTwitterClassifier,TwoPhaseTwitterClassifier2,TwoPhaseTwitterClassifier3,TwoPhaseTwitterClassifier4
#os.chdir('Desktop/Twitter_User_types')
f=pickle.load(open('Features/allfeatures.txt'))
features=f['features']
label=f['label']
for i in range(len(features)):
features[i].append(label[i])
xy=np.asarray(features)
print xy.shape
np.random.shuffle(xy)
f=pickle.load(open('Features/opioid_features.txt'))
features=f['feature']
label=f['label']
for i in range(len(features)):
features[i].append(label[i])
xyf=np.asarray(features)
xyf=filter(lambda x:x[-1]<5,xyf)
xyf=np.asarray(xyf)
print "Classifier2:"
tptc2=TwoPhaseTwitterClassifier2.TwoPhaseTwitterClassifier2()
tptc2.trainset(xy)
tptc2.train("decisiontree","decisiontree")
tptc2.test(xyf)
tptc2.savemodel()
<file_sep>import tweepy
import datetime
import pickle
files=['For_profit_organizations','media','Non_profit_organizations','Personalities','ordinary']
allfeatures,alllabels=[],[]
for i in range(5):
a=open('../Data/'+files[i]+'.csv')
b=a.readlines()
screennames=b[0].split('\r')
screennames=map(lambda x:x.strip(),screennames)
a.close()
CONSUMER_KEY = "UfKQzmcJDqHRJQiC2Ipo4gKL8"
CONSUMER_SECRET = "<KEY>"
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth,wait_on_rate_limit=True)
features,label=[],[]
for sn in screennames:
try:
userid=api.get_user(sn).id
tweets = api.user_timeline(id = userid, count = 1000)
indegree=tweets[0]._json['user']['followers_count']
outdegree=tweets[0]._json['user']['friends_count']
user_favourite_count=tweets[0]._json['user']['favourites_count']
user_listed_count=tweets[0]._json['user']['listed_count']
retweet_count=0
favourite_count=0
verified=0
if tweets[0]._json['user']['verified']==True:
verified=1
urls=0.0
mentions=0.0
retweeted=0.0
for tweet in tweets:
retweet_count+=(tweet._json['retweet_count'])
favourite_count+=(tweet._json['favorite_count'])
if len(tweet._json['entities']['urls'])>0:
urls+=1
if len(tweet._json['entities']['user_mentions'])>0:
mentions+=1
if tweet._json['retweeted']:
retweeted+=1
retweeted_frac=retweeted/len(tweets)
mentions_frac=mentions/len(tweets)
urls_frac=urls/len(tweets)
postin3month=0
date0=tweets[0]._json['created_at']
date=datetime.datetime.strptime(date0,'%a %b %d %H:%M:%S +0000 %Y')
for line in range(1,len(tweets)):
date1=tweets[line]._json['created_at']
date1=datetime.datetime.strptime(date1,'%a %b %d %H:%M:%S +0000 %Y')
d3=date-date1
if d3.days<=90:
postin3month+=1
feature=[indegree,outdegree,postin3month,user_favourite_count,retweeted_frac,mentions_frac,urls_frac,favourite_count,user_listed_count,retweet_count,verified]
features.append(feature)
label.append(i)
except BaseException:
print sn
f={"features":features,'label':label}
print files[i]
print len(features),len(label)
allfeatures=allfeatures+features
alllabels=alllabels+label
pickle.dump(f,open(files[i]+".txt",'wb'))
allf={"features":allfeatures,'label':alllabels}
print len(allfeatures),len(alllabels)
pickle.dump(allf,open("allfeatures.txt",'wb'))
<file_sep>import tweepy
import datetime
label_number=1
a=open('../Data/screen_names.txt')
b=a.readlines()
screennames=b[0].split('\r')
screennames=map(lambda x:x.strip(),screennames)
a.close()
CONSUMER_KEY = "CONSUMER_KEY"
CONSUMER_SECRET = "ECONSUMER_SECRET"
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth,wait_on_rate_limit=True)
features,label=[],[]
for sn in screennames:
try:
userid=api.get_user(sn).id
tweets = api.user_timeline(id = userid, count = 1000)
indegree=tweets[0]._json['user']['followers_count']
outdegree=tweets[0]._json['user']['friends_count']
user_favourite_count=tweets[0]._json['user']['favourites_count']
user_listed_count=tweets[0]._json['user']['listed_count']
retweet_count=0
favourite_count=0
verified=0
if tweets[0]._json['user']['verified']==True:
verified=1
urls=0.0
mentions=0.0
retweeted=0.0
for tweet in tweets:
retweet_count+=(tweet._json['retweet_count'])
favourite_count+=(tweet._json['favorite_count'])
if len(tweet._json['entities']['urls'])>0:
urls+=1
if len(tweet._json['entities']['user_mentions'])>0:
mentions+=1
if tweet._json['retweeted']:
retweeted+=1
retweeted_frac=retweeted/len(tweets)
mentions_frac=mentions/len(tweets)
urls_frac=urls/len(tweets)
postin3month=0
date0=tweets[0]._json['created_at']
date=datetime.datetime.strptime(date0,'%a %b %d %H:%M:%S +0000 %Y')
for line in range(1,len(tweets)):
date1=tweets[line]._json['created_at']
date1=datetime.datetime.strptime(date1,'%a %b %d %H:%M:%S +0000 %Y')
d3=date-date1
if d3.days<=90:
postin3month+=1
feature=[indegree,outdegree,postin3month,user_favourite_count,retweeted_frac,mentions_frac,urls_frac,favourite_count,user_listed_count,retweet_count,verified]
features.append(feature)
label.append(label_number)
except BaseException:
print sn
<file_sep>import json
import datetime
import pickle
import numpy as np
result='Data/opioid_result.csv'
rf=open(result,'r')
lines=rf.readlines()
lines=lines[0].split('\r')
map2={'For-profit organizations':0,'Journalists/Media/News':1,'Non-profit organizations':2,'Personalities':3,'Ordinary Individuals':4,'Other':5}
aa,features,labels,yyy=[],[],[],[]
for line in lines:
filename=line.split(',')[0].split('/')[1]
aa.append(filename)
filename=line.split(',')[1]
labels.append(filename)
for label in labels:
yyy.append(map2[label])
for a in aa:
filen="To_Tag/"+a+".txt"
file1=open(filen)
lines=file1.readlines()
file1.close()
indegree=json.loads(lines[0])['user']['followers_count']
outdegree=json.loads(lines[0])['user']['friends_count']
user_favourite_count=json.loads(lines[0])['user']['favourites_count']
user_listed_count=json.loads(lines[0])['user']['listed_count']
retweet_count=0
favourite_count=0
verified=0
if json.loads(lines[0])['user']['verified']==True:
verified=1
urls=0.0
mentions=0.0
retweeted=0.0
for line in range(0,len(lines)):
retweet_count+=(json.loads(lines[line])['retweet_count'])
favourite_count+=(json.loads(lines[line])['favorite_count'])
if len(json.loads(lines[line])['entities']['urls'])>0:
urls+=1
if len(json.loads(lines[line])['entities']['user_mentions'])>0:
mentions+=1
if json.loads(lines[line])['retweeted']:
retweeted+=1
retweeted_frac=retweeted/len(lines)
mentions_frac=mentions/len(lines)
urls_frac=urls/len(lines)
postin3month=0
date0=json.loads(lines[0])['created_at']
date=datetime.datetime.strptime(date0,'%a %b %d %H:%M:%S +0000 %Y')
for line in range(1,len(lines)):
date1=json.loads(lines[line])['created_at']
date1=datetime.datetime.strptime(date1,'%a %b %d %H:%M:%S +0000 %Y')
d3=date-date1
if d3.days<=90:
postin3month+=1
feature=[indegree,outdegree,postin3month,user_favourite_count,retweeted_frac,mentions_frac,urls,favourite_count,user_listed_count,retweet_count,verified]
features.append(feature)
for i in range(len(features)):
features[i].append(yyy[i])
features=np.asarray(features)
f={'feature':features,'label':yyy}
pickle.dump(f,open('offline_opioid_features.txt','wb'))
<file_sep>import os
import numpy as np
import pickle
import datetime
import json
import tweepy
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
result='../Data/opioid_result.csv'
rf=open(result,'r')
lines=rf.readlines()
lines=lines[0].split('\r')
map2={'For-profit organizations':0,'Journalists/Media/News':1,'Non-profit organizations':2,'Personalities':3,'Ordinary Individuals':4,'Other':5}
screen_names,features,labels,yyy=[],[],[],[]
CONSUMER_KEY = "UfKQzmcJDqHRJQiC2Ipo4gKL8"
CONSUMER_SECRET = "<KEY>"
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth,wait_on_rate_limit=True)
for line in lines:
filename=line.split(',')[0].split('/')[1]
screen_names.append(filename)
filename=line.split(',')[1]
labels.append(filename)
for label in labels:
yyy.append(map2[label])
for i in range(len(screen_names)):
sn=screen_names[i]
try:
userid=api.get_user(sn).id
tweets = api.user_timeline(id = userid, count = 1000)
indegree=tweets[0]._json['user']['followers_count']
outdegree=tweets[0]._json['user']['friends_count']
user_favourite_count=tweets[0]._json['user']['favourites_count']
user_listed_count=tweets[0]._json['user']['listed_count']
retweet_count=0
favourite_count=0
verified=0
if tweets[0]._json['user']['verified']==True:
verified=1
urls=0.0
mentions=0.0
retweeted=0.0
for tweet in tweets:
retweet_count+=(tweet._json['retweet_count'])
favourite_count+=(tweet._json['favorite_count'])
if len(tweet._json['entities']['urls'])>0:
urls+=1
if len(tweet._json['entities']['user_mentions'])>0:
mentions+=1
if tweet._json['retweeted']:
retweeted+=1
retweeted_frac=retweeted/len(tweets)
mentions_frac=mentions/len(tweets)
urls_frac=urls/len(tweets)
postin3month=0
date0=tweets[0]._json['created_at']
date=datetime.datetime.strptime(date0,'%a %b %d %H:%M:%S +0000 %Y')
for line in range(1,len(tweets)):
date1=tweets[line]._json['created_at']
date1=datetime.datetime.strptime(date1,'%a %b %d %H:%M:%S +0000 %Y')
d3=date-date1
if d3.days<=90:
postin3month+=1
feature=[indegree,outdegree,postin3month,user_favourite_count,retweeted_frac,mentions_frac,urls_frac,favourite_count,user_listed_count,retweet_count,verified]
features.append(feature)
yyy.append(map2[labels[i]])
except BaseException:
print sn
print len(features),len(yyy)
f={'feature':features,"label":yyy}
pickle.dump(f,open('opioid_features.txt','w'))
#for i in range(len(features)):
# features[i].append(yyy[i])
#features=np.asarray(features)
#f=pickle.load(open('features2.txt'))
#ffeatures=f['feature']
#newfeatures=np.concatenate((ffeatures,features))
#newf={'feature':newfeatures}
#pickle.dump(newf,open('features4.txt','w'))
<file_sep>
import os
import numpy as np
import pickle
import datetime
import json
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
#os.chdir('Desktop/Twitter_User_types')
f=pickle.load(open('Features/opioid_features.txt'))
features=f['feature']
label=f['label']
for i in range(len(features)):
features[i].append(label[i])
xy=np.asarray(features)
print xy.shape
np.random.shuffle(xy)
numberoftrain=len(xy)*2/3
trainx,trainy,testx,testy=xy[:numberoftrain,:11],xy[:numberoftrain,11],xy[numberoftrain:,:11],xy[numberoftrain:,11]
#st=StandardScaler()
#st.fit(trainx)
#trainx=st.fit_transform(trainx)
#testx=st.fit_transform(testx)
clf=DecisionTreeClassifier()
#clf=LogisticRegression(penalty='l2', C=1,max_iter=500,solver='newton-cg')
#clf=SVC(kernel="linear",probability=True,max_iter=500)
#clf=KNeighborsClassifier()
#train
clf.fit(trainx,trainy)
#accuracy
print clf.score(testx,testy)
predy=clf.predict(testx)
predpro=clf.predict_proba(testx)
#recall, precision, f1
print recall_score(testy,predy,average=None)
print precision_score(testy,predy,average=None)
print f1_score(testy,predy,average=None)
#auc
for i in range(5):
scorei=predpro[:,i]
fpr, tpr, thresholds =roc_curve(testy,scorei,pos_label=i)
print auc(fpr,tpr)
#confusion matrix
confusion_matrix(testy,predy)
<file_sep>'''
Created on Aug 29, 2017
@author: dongxinyu
'''
import os
import numpy as np
import pickle
import datetime
import json
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from Classifier import TwoPhaseTwitterClassifier,TwoPhaseTwitterClassifier2,TwoPhaseTwitterClassifier3,TwoPhaseTwitterClassifier4
#os.chdir('Desktop/Twitter_User_types')
f=pickle.load(open('Features/allfeatures.txt'))
features=f['features']
label=f['label']
for i in range(len(features)):
features[i].append(label[i])
xy=np.asarray(features)
print xy.shape
np.random.shuffle(xy)
numberoftrain=len(xy)*2/3
trainxy,testxy=xy[:numberoftrain,:],xy[numberoftrain:,:]
print "Classifier2:"
tptc2=TwoPhaseTwitterClassifier2.TwoPhaseTwitterClassifier2()
tptc2.trainset(trainxy)
tptc2.train("decisiontree","log")
tptc2.test(testxy)
tptc2.savemodel()
print "Classifier4:"
tptc4=TwoPhaseTwitterClassifier4.TwoPhaseTwitterClassifier4()
tptc4.trainset(trainxy)
tptc4.train("decisiontree","log")
tptc4.test(testxy)
tptc4.savemodel()
f=pickle.load(open('Features/opioid_features.txt'))
features=f['feature']
label=f['label']
for i in range(len(features)):
features[i].append(label[i])
xyf=np.asarray(features)
print xyf.shape
np.random.shuffle(xyf)
numberoftrain=len(xyf)*2/3
trainxy,testxy=xyf[:numberoftrain,:],xyf[numberoftrain:,:]
print "Classifier1:"
tptc1=TwoPhaseTwitterClassifier.TwoPhaseTwitterClassifier()
tptc1.trainset(trainxy)
tptc1.train("decisiontree","decisiontree")
tptc1.test(testxy)
tptc1.savemodel()
print "Classifier3:"
tptc3=TwoPhaseTwitterClassifier3.TwoPhaseTwitterClassifier3()
tptc3.trainset(trainxy)
tptc3.train("decisiontree","decisiontree")
tptc3.test(testxy)
tptc3.savemodel()
<file_sep>
#extract features directly from downloaded tweets data.
import os
import json
import datetime
classes=['For_profit_organisations','Media_Outlets','Non_profit_organizations','Personalities','User_Data']
#map2=['For_profit_organisations':0,'Media_Outlets':1,'Non_profit_organizations':2,'Personalities':3,'Ordinary Individuals':4,'Other':5]
features=[]
label=[]
for j in range(5):
type2=os.listdir(classes[j])
for i in range(len(type2)):
typei=type2[i]
filename=classes[j]+"/"+typei
file1=open(filename)
lines=file1.readlines()
file1.close()
try:
indegree=json.loads(lines[0])['user']['followers_count']
outdegree=json.loads(lines[0])['user']['friends_count']
user_favourite_count=json.loads(lines[0])['user']['favourites_count']
user_listed_count=json.loads(lines[0])['user']['listed_count']
retweet_count=0
favourite_count=0
verified=0
if json.loads(lines[0])['user']['verified']==True:
verified=1
urls=0.0
mentions=0.0
retweeted=0.0
for line in range(0,len(lines)):
retweet_count+=(json.loads(lines[line])['retweet_count'])
favourite_count+=(json.loads(lines[line])['favorite_count'])
if len(json.loads(lines[line])['entities']['urls'])>0:
urls+=1
if len(json.loads(lines[line])['entities']['user_mentions'])>0:
mentions+=1
if json.loads(lines[line])['retweeted']:
retweeted+=1
retweeted_frac=retweeted/len(lines)
mentions_frac=mentions/len(lines)
urls_frac=urls/len(lines)
postin3month=0
date0=json.loads(lines[0])['created_at']
date=datetime.datetime.strptime(date0,'%a %b %d %H:%M:%S +0000 %Y')
for line in range(1,len(lines)):
date1=json.loads(lines[line])['created_at']
date1=datetime.datetime.strptime(date1,'%a %b %d %H:%M:%S +0000 %Y')
d3=date-date1
if d3.days<=90:
postin3month+=1
feature=[indegree,outdegree,postin3month,user_favourite_count,retweeted_frac,mentions_frac,urls_frac,favourite_count,user_listed_count,retweet_count,verified]
features.append(feature)
label.append(j)
except BaseException:
print classes[j],typei
continue
<file_sep>'''
Created on Aug 29, 2017
@author: dongxinyu
'''
| d093ed26153075347e325369935d9050728fcede | [
"Python"
] | 10 | Python | CodeBreakPP/TwitterUserType | 0e3703e89fb4418357be953f82b044050ca2bf17 | 3267e2dc0dd7a61af317d5f955ad0d8d14b38dcf |
refs/heads/main | <file_sep>//
// ImageSingleton.swift
// homeDepotChallenge
//
// Created by RaveBizz on 2/8/21.
//
import UIKit
class ImageSingleton {
static let shared = ImageSingleton()
private var internalCache = NSCache<NSString, UIImage>()
private init() {}
func getImage(with url: URL, updateImageClosure: @escaping (UIImage) -> () ) {
if let cachedImage = internalCache.object(forKey: url.absoluteString as NSString) {
// print("getting image from cache")
DispatchQueue.main.async {
updateImageClosure(cachedImage)
}
} else {
// print("getting image from API")
DispatchQueue.global(qos: .userInitiated).async {
guard let data = try? Data(contentsOf: url) else {return}
let image = UIImage(data: data) ?? UIImage(named: "leaf.png")!
DispatchQueue.main.async {
updateImageClosure(image)
self.internalCache.setObject(image, forKey: url.absoluteString as NSString)
}
}
}
}
}
<file_sep>//
// CellViewModel.swift
// homeDepotChallenge
//
// Created by RaveBizz on 2/7/21.
//
import Foundation
class CellViewModel {
private var album: Album
init(album: Album) {
self.album = album
}
func getArtistName() -> String {
return album.artistName
}
func getAlbumName() -> String {
return album.name
}
func getReleaseDate() -> String {
return album.releaseDate
}
func getImageURL() -> URL {
guard let url = URL(string: album.artworkUrl100) else {
return URL(string: "https://www.google.com")!
}
return url
}
}
<file_sep>//
// Album.swift
// homeDepotChallenge
//
// Created by RaveBizz on 2/7/21.
//
import Foundation
struct AlbumTopLevel: Decodable {
var feed: Feed
}
struct Feed: Decodable {
var results: [Album]
}
struct Album: Decodable {
let artistName: String
let releaseDate: String
let name: String
let artworkUrl100: String
var dateFromString: Date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: self.releaseDate ?? "") ?? Date()
print(date)
return date
}
}
<file_sep>//
// AlbumDetailCell.swift
// homeDepotChallenge
//
// Created by RaveBizz on 2/7/21.
//
import UIKit
class AlbumDetailCell: UICollectionViewCell {
static let identifier = String(describing: AlbumDetailCell.self)
@IBOutlet weak var albumImageView: UIImageView!
@IBOutlet weak var albumLabel: UILabel!
@IBOutlet weak var artistLabel: UILabel!
@IBOutlet weak var releaseDateLabel: UILabel!
var viewModel: CellViewModel? {
didSet {
albumLabel.text = viewModel?.getAlbumName()
artistLabel.text = viewModel?.getArtistName()
releaseDateLabel.text = viewModel?.getReleaseDate()
getImage()
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
func bind(viewModel: CellViewModel?){
self.viewModel = viewModel
}
func getImage() {
guard let url = viewModel?.getImageURL() else {return}
ImageSingleton.shared.getImage(with: url) { image in
self.albumImageView.image = image
}
}
}
<file_sep>//
// ViewController.swift
// animations
//
// Created by RaveBizz on 2/2/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var greenSquare: UIView!
lazy var redSquare: UIView = createView()
var cyanSquare: UIView = {
let square = UIView(frame: CGRect(x: 0, y: 700, width: 100, height: 100))
square.backgroundColor = .cyan
return square
}()
override func viewDidLoad() {
super.viewDidLoad()
greenSquare.backgroundColor = .green
redSquare.backgroundColor = .red
view.addSubview(cyanSquare)
ani1()
ani2()
basicAni()
rotate()
topConstraintAni()
}
func basicAni() {
let ani = CABasicAnimation(keyPath: "position.y")
ani.fromValue = 0
ani.toValue = 100
ani.duration = 1
redSquare.layer.add(ani, forKey: "aniID")
}
func ani1() {
UIView.animate(withDuration: 2, animations: {
self.greenSquare.backgroundColor = .purple
})
}
func rotate(){
redSquare.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3)
}
func ani2() {
UIView.animate(withDuration: 4) {
self.greenSquare.center = self.view.center
} completion: { (finished) in
print("finished")
UIView.animate(withDuration: 1) {
self.transition1()
}
}
}
func transition1(){
UIView.transition(with: greenSquare, duration: 2, options: .transitionCurlUp) {
self.view.layoutIfNeeded()
}
}
func createView() -> UIView {
let square = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
square.backgroundColor = .cyan
view.addSubview(square)
return square
}
func topConstraintAni() {
topConstraint.constant = 400
UIView.animate(withDuration: 1){
self.view.layoutIfNeeded()
} completion: { (finished) in
if finished {
UIView.animate(withDuration: 1){
self.greenSquare.alpha = 0.5
self.heightConstraint.constant = 20
self.view.layoutIfNeeded()
}
}
}
}
}
<file_sep>//
// ViewModel.swift
// homeDepotChallenge
//
// Created by RaveBizz on 2/7/21.
//
import Foundation
class ViewModel {
var numItems: Int? {
dataVM?.count
}
var dataVM: [CellViewModel]? {
didSet {
DispatchQueue.main.async {
self.updateViewClosure?()
}
}
}
// private func sortTrackList() {
// let sorted = model?.results?.sorted(by: {$0.dateFromString.compare($1.dateFromString) == .orderedDescending})
// model?.results = sorted
// }
var linkString = "https://rss.itunes.apple.com/api/v1/us/apple-music/coming-soon/all/50/explicit.json"
var updateViewClosure: (() -> Void)?
func downloadAlbums(){
print("downloading albums")
guard let url = URL(string: linkString) else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
print("error request not successful")
return
}
let decoder = JSONDecoder()
do {
var decodedAlbums = try decoder.decode(AlbumTopLevel.self, from: data)
print("decodedAlbums", decodedAlbums.feed.results)
let sorted = decodedAlbums.feed.results.sorted(by: {$0.dateFromString.compare($1.dateFromString) == .orderedAscending})
decodedAlbums.feed.results = sorted
self.updateDataVM(decodedModel: decodedAlbums)
} catch let error {
print("decoding unsuccessful", error)
}
}
task.resume()
}
func updateDataVM(decodedModel: AlbumTopLevel) {
dataVM = decodedModel.feed.results.map { album in
// print("album", album)
let cellVM = CellViewModel(album: album)
return cellVM
}
}
}
| 2d3093327fda506617a5d7cf006a1a11311efef8 | [
"Swift"
] | 6 | Swift | ganymede30/Swift_Examples | f12a1453b3cc966beb8305189e3c479cfd9f3e29 | 70f013654839e7e21b2004c21a35b41c2f0e8b6e |
refs/heads/master | <file_sep>/*\
* 7seg - v0.1
* Web: http://home.kal9001.co.uk Email: <EMAIL>
*
* Copyright (C) 2015 Kal9001
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* called GPLv3.txt in the root directory where this source file is located.
* If not, see <http://www.gnu.org/licenses/>.
\*/
/*\
* Counts in hex from 0x000 to 0xfff and displays each step on a 3x7segment display.
*
* Pinout:
*
* ATtiny84A
* ╔═══╦═══╗
* 5v VCC -║1 14║- GND 0v
* 1 (O)PB0 -║2 13║- PA0(O) A
* 2 (O)PB1 -║3 12║- PA1(O) B
* RESET -║4 11║- PA2(O) C
* 3 (O)PB2 -║5 10║- PA3(O) D
* P (O)PA7 -║6 9║- PA4(O) E
* G (O)PA6 -║7 8║- PA5(O) F
* ╚═══════╝
*
\*/
#define F_CPU 8000000
#include <avr/io.h>
#include <util/delay.h>
void displayLoop(uint8_t counter1, uint8_t counter2, uint8_t counter3, uint8_t *charMap);
int main(void)
{
// 0 // 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8 // 9 // a // b // c // d // e // f
uint8_t charMap[16] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71 };
uint8_t counter1, counter2, counter3;
DDRA = 0xff;
DDRB = 0x07;
PORTA = 0xff;
PORTB = 0x00;
while(1)
{
for(counter1 = 0; counter1 < 16; counter1++)
{
for(counter2 = 0; counter2 < 16; counter2++)
{
for(counter3 = 0; counterThree < 16; counter3++)
{
displayLoop(counter1, counter2, counter3, charMap);
}
}
}
}
}
void displayLoop(uint8_t counter1, uint8_t counter2, uint8_t counter3, uint8_t *charMap)
{
uint8_t counter;
for(counter = 0; counter < 66; counter++)
{
PORTA = ~(charMap[counter1]);
PORTB = 0x01;
_delay_ms(1);
PORTA = ~(charMap[counter2]);
PORTB = 0x02;
_delay_ms(1);
PORTA = ~(charMap[counter3]);
PORTB = 0x04;
_delay_ms(1);
}
}
<file_sep>/*\
* ADC counter - v1.0
* Web: http://home.kal9001.co.uk Email: <EMAIL>
*
* Copyright (C) 2015 Kal9001
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* called GPLv3.txt in the root directory where this source file is located.
* If not, see <http://www.gnu.org/licenses/>.
\*/
/*\
*
* The program simply samples the two pots (ADC2 and 3) and passes the data into a function to shift
* shift out using the USI with a manual clock.
*
* ATtiny 85P
* ╔═══╦═══╗
* RESET -║1 28║- 5V VCC
* pot 1 (ADC3)(A)PB3 -║2 27║- PB2(O)(USCK) clock pin
* pot 2 (ADC2)(A)PB4 -║3 26║- PB1(O)(DO) data output
* GND 0V -║4 25║- PB0(O)(DI) SS chip select
* ╚═══════╝
*
\*/
#define F_CPU 8000000
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
void init_hardware_ADC(void);
void init_hardware_USI(void);
uint8_t getAnalogResult(uint8_t whichOne);
void displayData(uint8_t data[2], uint8_t numberOfBytes);
int main(void)
{
uint8_t ADCresult[2] = { 0x00 };
uint8_t whichOne = 0;
DDRB = 0x07;
PORTB = 0x01;
init_hardware_ADC();//sets up the ADC
init_hardware_USI();//sets up the USI
while(1)
{
for(whichOne = 2; whichOne <= 3; whichOne++)
{
ADCresult[(whichOne - 2)] = getAnalogResult(whichOne);
}
displayData(ADCresult, 2);
_delay_ms(500);
}
return 0;//we will never get here
}
void init_hardware_ADC(void)
{
ADMUX = 0x22;//0010 0010//using AVCC, ADLAR 1 and ADC2 preselected.
DIDR0 = 0x18;//Disable digital input for ACD2 and 3
ADCSRA = 0x87;//ADC enable with 128 clock division
return;
}
void init_hardware_USI(void)
{
USICR = 0x5a;//sets USI to three wire mode with software clock set to USITC
return;
}
uint8_t getAnalogResult(uint8_t whichOne)
{
ADMUX = 0x20 + whichOne;//select input
ADCSRA |= 0x40;//start conversion.
while(ADCSRA & 0x40);//wait for conversion to finish
return ADCH;
}
void displayData(uint8_t data[2], uint8_t numberOfBytes)
{
uint8_t counter_a, counter_b;
PORTB &= 0xfe;//PB0 (SS) low
USICR = 0x5a;//sets USI to three wire mode with software clock
for(counter_a = 0; counter_a < numberOfBytes; counter_a++)
{
USIDR = data[counter_a];//loads data to send
for(counter_b = 0; counter_b < 8; counter_b++)
{
USICR = 0x11;//toggle the USI clock
USICR = 0x13;//toggle the USE clock and the USI data register
}
}
USICR = 0x00;//Turns USI off to resume normal port operation.
PORTB |= 0x01;//PB0 (SS) high
return;
}
<file_sep>/*\
* multiple_output_clock - v1.0
* Web: http://home.kal9001.co.uk Email: <EMAIL>
*
* Copyright (C) 2014 Kal9001
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* called GPLv3.txt in the root directory where this source file is located.
* If not, see <http://www.gnu.org/licenses/>.
\*/
/*\
* Turns on and then off pins PB0 through PB4 at a set interval and duty cycle.
* All outputs are independent.
*
* Pinout:
*
* ATtiny85
* ╔═══╦═══╗
* RESET -║1 8║- VCC 5V5
* (o) PB3 -║2 7║- PB2 (O)
* (o) PB4 -║3 6║- PB1 (O)
* GND 0V -║4 5║- PB0 (O)
* ╚═══════╝
*
\*/
#define F_CPU 8000000
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{ //_PB0, _PB1, _PB2, _PB3, _PB4
int pinOn[] = { 250, 75, 1000, 100, 50}; // Select each pins 'on' time in miliseconds.
int pinOff[] = { 250, 75, 100, 1111, 500}; // Select each pins 'off' time in miliseconds.
int pinState[] = {0, 0, 0, 0, 0};
int pinTime[] = {0, 0, 0, 0, 0};
int i = 0;
DDRB = 0x1f;
while(1)
{
for(i = 0; i < 5; i++)
{
if(pinTime[i] > 0)
{
pinTime[i] = (pinTime[i] - 1);
}
else
{
if(pinState[i])
{
PORTB &= ~(1<<i);
pinState[i] = 0;
pinTime[i] = pinOff[i];
}
else
{
PORTB |= (1<<i);
pinState[i] = 1;
pinTime[i] = pinOn[i];
}
}
_delay_us(930); //wait 1 milisecond minus apx 70 microseconds to execute the loop
}
}
return(0);
}
<file_sep>ATtiny projects page.
This page contains various examples and experiments with the ATtiny Microcontrollers.
Summery:-
single_output_clock - A simple clocked output.
multiple_output_clock - Each pin can be turned on and off independantly (hard coded at compile time).
stepper - Able to move a stepper motor forwards or backwards and change between full and half step mode.
single_7seg_serial - A simple 3 digit hex counter using a seven segment display.
multiple_7seg_serial - Upto eight digit output using two shift registers.
<file_sep>/*\
* stepper - v0.2
* Web: http://home.kal9001.co.uk Email: <EMAIL>
*
* Copyright (C) 2015 Kal9001
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* called GPLv3.txt in the root directory where this source file is located.
* If not, see <http://www.gnu.org/licenses/>.
\*/
/*\
* Control of a stepper motor using a L293D or SN754410 chip.
*
* Pinout:
*
* ATtiny84A
* ╔═══╦═══╗
* 5v VCC -║1 14║- VCC 5V5
* Motor enable (O)PB0 -║2 13║- PA0(O) Coil 1A
* Unused (X)PB1 -║3 12║- PA1(O) Coil 1B
* RESET -║4 11║- PA2(O) Coil 2A
* Unused (X)PB2 -║5 10║- PA3(O) Coil 2B
* half step (I)PA7 -║6 9║- PA4(I) step forward
* step clock (I)PA6 -║7 8║- PA5(I) step backward
* ╚═══════╝
*
\*/
//includes
#include <avr/io.h>
//Function prototypes
uint8_t executeStep(uint8_t newStepValue, uint8_t *stepPositions);
//executes the current step values when step clock is high
uint8_t stepValues(uint8_t direction, uint8_t currentPosition, int8_t *stepRounding);
//Generates new step values based on current position and intended direction
void getDirection(uint8_t *direction);
//decodes the step direction pins
void correction(uint8_t *currentValue);
//does the currentValue / stepPositions wrap around
int main(void)
{
uint8_t direction = 0x00;
//which direction are we going
//0x00 = free running
//0x01 = forwards
//0x02 = backwards
//0x03 = brake
uint8_t newPosition = 0x00;
//The new value that will be used.
uint8_t currentPosition = 0x02;
//the last value executed
int8_t stepRounding = 0x00;
uint8_t stepPositions[14] = {0x03, 0x01, 0x09, 0x08, 0x0c, 0x04, 0x06, 0x02, 0x03, 0x01, 0x09, 0x08, 0x0c, 0x04};
//stepPositions holds the current step phases for the motor
// 0000 0011 = 0x03 - Half
// 0000 0001 = 0x01 - Full
// 0000 1001 = 0x09 - Half
// 0000 1000 = 0x08 - Full
// 0000 1100 = 0x0c - Half
// 0000 0100 = 0x04 - Full
// 0000 0110 = 0x06 - Half
// 0000 0010 = 0x02 - Full
// 0000 0011 = 0x03 - Half
// 0000 0001 = 0x01 - Full
// 0000 1001 = 0x09 - Half
// 0000 1000 = 0x08 - Full
// 0000 1100 = 0x0c - Half
// 0000 0100 = 0x04 - Full
DDRB = 0x01;//b00000001
DDRA = 0x0f;//b00001111
while(1)
{
getDirection(&direction);
newPosition = stepValues(direction, currentPosition, &stepRounding);
if(PINA & 0x40)
{
currentPosition = executeStep(newPosition, stepPositions);
}
correction(¤tPosition);
}
}
uint8_t executeStep(uint8_t newPosition, uint8_t *stepPositions)
{
PORTA = stepPositions[newPosition];//sets motor pins
PORTB = 0x01;
while(PINA & 0x40){}//wait until the step clock pin goes back low.
return newPosition;
}
void getDirection(uint8_t *direction)
{
*direction = ((PINA & 0x30) >> 4); //b00110000
}
uint8_t stepValues(uint8_t direction, uint8_t currentPosition, int8_t *stepRounding)
{
uint8_t step;
uint8_t newPosition = 0x00;
if(PINA & 0x80)
{
step = 1;
}
else
{
step = 2;
if(currentPosition % 2)
{
if(*stepRounding == 1)
{
step -= 1;
*stepRounding = 0;
}
else
{
step += 1;
*stepRounding = 1;
}
}
}
switch(direction)
{
case 0x00://free running
break;
case 0x01://forwards
newPosition = currentPosition + step;
break;
case 0x02://backwards
newPosition = currentPosition - step;
break;
case 0x03://brake
break;
}
return newPosition;
}
void correction(uint8_t *currentValue)
{
uint8_t correctedValue = *currentValue;
if(*currentValue < 3)
{
correctedValue = *currentValue + 8;
}
if(*currentValue > 11)
{
correctedValue = *currentValue - 8;
}
*currentValue = correctedValue;
}
<file_sep>/*\
* multiple_7seg_serial - v0.1
* Web: http://home.kal9001.co.uk Email: <EMAIL>
*
* Copyright (C) 2016 Kal9001
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* called GPLv3.txt in the root directory where this source file is located.
* If not, see <http://www.gnu.org/licenses/>.
\*/
/*\
* Displays a given number on a 7-segment LED display with upto 8 digits.
* Number is input over serial interface by methods not yet currently implemented.
*
* Pinout:
*
* ATtiny84A
* ╔═══╦═══╗
* 5v VCC -║1 14║- GND 0v
* (O)PB0 -║2 13║- PA0(O)
* (O)PB1 -║3 12║- PA1(O)
* RESET -║4 11║- PA2(O)
* (O)PB2 -║5 10║- PA3(O)
* (O)PA7 -║6 9║- PA4(O)
* (O)PA6 -║7 8║- PA5(O)
* ╚═══════╝
*
\*/
//includes
//function prototypes
| d1a9c20d198144e3ce8d0ed34055fcac17f69b5c | [
"C",
"Text"
] | 6 | C | kal9001/AVR-small | 2e4b6a1846cdd4676dcd16efa38728c1098ccde3 | 482c3a946f08e569739ed6b0acae7dc19ad2a9c4 |
refs/heads/master | <file_sep>// import { DynamoDB, EC2 } from 'aws-sdk';
// import { APIGatewayEvent, Callback, Context, Handler } from 'aws-lambda';
// // import AWS from 'aws-sdk';
// // Set the region
// const tempKacper: Handler = (event: APIGatewayEvent, context: Context, cb: Callback) => {
// const params = {
// TableName : "Projects",
// KeySchema: [
// {
// AttributeName: "_id",
// KeyType: "HASH", //Partition key
// },
// ],
// AttributeDefinitions: [
// {
// AttributeName: "Artist",
// AttributeType: "S"
// },
// {
// AttributeName: "SongTitle",
// AttributeType: "S"
// }
// ],
// ProvisionedThroughput: {
// ReadCapacityUnits: 1,
// WriteCapacityUnits: 1
// }
// }
// const request = new DynamoDB();
// const ddb = new DynamoDB().promise()
// const tep = new EC2({apiVersion: '2014-10-01'}).promise()
// console.log('DUPA')
// const response = {
// statusCode: 200,
// body: JSON.stringify({
// message: 'Kacper\'s msg',
// input: event,
// }),
// };
// cb(null, response);
// };
// export default tempKacper;
<file_sep>import { DynamoDB } from 'aws-sdk';
import {Config, TesterType} from '../types';
import {APIGatewayEvent, Callback, Context} from 'aws-lambda';
const doubleFunction = async () => {
const ddb = new DynamoDB();
const params = {
TableName: 'Services'
}
const dynamoObject = await ddb.scan(params).promise()
console.log(dynamoObject)
return dynamoObject.Items.map(x => DynamoDB.Converter.unmarshall(x));
};
export const getConfig = async (): Promise<Config> => {
return {
services: [
{
name: 'Example API',
notificators: [
{
type: 'email',
},
],
testers: [
{
type: TesterType.curl,
url: 'http://example.com',
},
],
},
],
};
};
export default async (event: APIGatewayEvent, context: Context, cb: Callback) => {
try {
const res = await doubleFunction();
console.log(res)
cb(null, {
body: JSON.stringify({
message: JSON.stringify(res)
}),
statusCode: 200,
});
} catch (err) {
console.error(err);
cb(null, {
body: JSON.stringify(err),
statusCode: 500,
});
}
};<file_sep>export type Config = {
services: ServiceConfig[];
}
export type ServiceConfig = {
name: string;
testers: TesterConfig[];
notificators: NotificatorConfig[];
}
export type NotificatorConfig = {
type: string;
}
export type TesterConfig = CurlTesterConfig;
export const enum TesterType {
curl = 'curl',
// ddp,
// puppeteer,
}
type CommonTesterConfig = {
type: TesterType;
}
export type CurlTesterConfig = CommonTesterConfig & {
url: string;
};
export type TestResults = {
isOK: boolean;
services: ServiceTestResult[];
}
export type ServiceTestResult = {
isOK: boolean;
name: string;
error?: TestResultError;
}
export type TestResultError = {
message: string;
}
export type TesterAdapter<Config = CommonTesterConfig> = (Config) => Promise<ServiceTestResult>
<file_sep>import {curl} from './curl';
export default {
curl
}<file_sep>import React, { Component } from 'react';
import Fetch from '../components/Fetch.js'
import fetchMessages from '../utils/fetchMessages'
import MessageInformation from '../components/Components/MessageInformation'
import {
ScrollView,
StyleSheet,
View,
} from 'react-native';
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: null,
};
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
<Fetch
source={fetchMessages}
>
{props =>
<MessageInformation {...props} />
}
</Fetch>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
contentContainer: {
paddingTop: 30,
},
});
<file_sep>import React, { Component } from 'react';
import Fetch from '../Fetch.js'
import fetchMessages from '../utils/fetchMessages'
import MessageInformation from './MessageInformation'
export default class MessageListing extends Component {
render() {
return (
<div>
<Fetch
source={fetchMessages}
>
{props =>
<MessageInformation {...props} />
}
</Fetch>
</div>
);
}
}
<file_sep>{
"compilerOptions": {
"baseUrl": ".",
"sourceMap": true,
"lib": [
"es5",
"es2015",
"es2016",
"es2017",
"es2018",
"esnext"
]
}
}
<file_sep>import {TesterAdapter, CurlTesterConfig} from 'types';
export const curl: TesterAdapter<CurlTesterConfig> = async config => {
return {
isOK: true,
name: config.name,
};
};
<file_sep><h1 align="center">
<a href="https://github.com/vazco">vazco</a>/Livescan
</h1>
Live apps health scanner
### License
<img src="https://vazco.eu/banner.png" align="right">
**Like every package maintained by [Vazco](https://vazco.eu/), Livescan is [MIT licensed](https://github.com/vazco/uniforms/blob/master/LICENSE).**
<file_sep>import { DynamoDB } from 'aws-sdk';
import { Config } from '../types';
import { APIGatewayEvent, Callback, Context } from 'aws-lambda';
import { notify } from '../notificators';
import { runTesters } from '../testers';
const mockupData = {
services: [
{
_id: '1',
name: '<NAME>',
notificators: [
{
type: 'email',
},
],
testers: [
{
type: 'curl',
url: 'http://example.com',
},
],
},
]
}
export default async (event: APIGatewayEvent, context: Context, cb: Callback) => {
try {
const ddb = new DynamoDB();
mockupData.services.forEach(async (item, index) => {
const params = {
TableName: "Services",
Item: DynamoDB.Converter.marshall(item)
}
await ddb.putItem(params).promise()
});
cb(null, {
body: JSON.stringify({
// message: JSON.stringify()
}),
statusCode: 200,
});
} catch (err) {
console.error(err);
cb(null, {
body: JSON.stringify(err),
statusCode: 500,
});
}
};<file_sep>import {Config} from '../types';
export const notify = async (config: Config, testResults) => {
return {};
};
<file_sep>import PropTypes from 'prop-types'
import React, { Fragment } from 'react'
import { Card, Header, Text, Title } from 'native-base';
import {
View,
} from 'react-native';
export default function MessageInformation(props) {
return (
<View style={{flex: 1, flexDirection: 'column'}}>
{props.data && props.data.results.map(message =>
<Card key={message.name}>
{message.isOk &&
<Fragment>
<Header>
<Title>
{message.name}
</Title>
</Header>
<Text style={{ textAlign: 'center', marginTop: 10, marginBottom: 10}}>
{message.type}
</Text>
<Text style={{ textAlign: 'center', marginBottom: 10}}>
{message.url}
</Text>
</Fragment>
}
</Card>
)}
</View>
);
}
MessageInformation.propTypes = {
data: PropTypes.object
}
<file_sep>import {APIGatewayEvent, Callback, Context} from 'aws-lambda';
import {getConfig} from 'api';
import {notify} from 'notificators';
import {runTesters} from 'testers';
import {Config, TestResults} from 'types';
export default async (event: APIGatewayEvent, context: Context, cb: Callback) => {
try {
// Get configuration data
const config: Config = await getConfig();
// Execute configured tests
const testResults: TestResults = await runTesters(config);
// Notify about executed tests
const notifyResults = await notify(config, testResults);
cb(null, {
body: JSON.stringify({
message: 'Execution complete',
notifyResults,
testResults,
}),
statusCode: 200,
});
} catch (err) {
console.error(err);
cb(null, {
body: JSON.stringify(err),
statusCode: 500,
});
}
};
<file_sep>import PropTypes from 'prop-types'
import React, { Fragment } from 'react'
import { Header , Segment } from 'semantic-ui-react'
export default function MessageInformation(props) {
return (
<div className="centered_container">
{props.data && props.data.results.map(message =>
<Segment key={message.name} className="item" textAlign='center'>
{message.isOk &&
<Fragment>
<Header as='h3' block>
{message.name}
</Header>
<Header as='h4'>
{message.type}
</Header>
<Header as='h4'>
{message.url}
</Header>
</Fragment>
}
</Segment>
)}
</div>
);
}
MessageInformation.propTypes = {
data: PropTypes.object
}
<file_sep>import {Config, TesterConfig, TestResults, ServiceTestResult} from 'types';
import adapters from './adapters';
export const runTesters = async (config: Config): Promise<TestResults> => {
const results = config.services.map((serviceConfig): Promise<ServiceTestResult> => Promise.all(
serviceConfig.testers.map((testerConfig: TesterConfig) => adapters[testerConfig.type](config))
).then(results =>
results.reduce((result, curr) => Object.assign(result, {isOK: result.isOK && curr.isOK}), {isOK: true, name: serviceConfig.name})
));
return {
isOK: true,
services: await Promise.all(results)
};
};
| eb93ce1764ebd12a671c629ae46493e1625c4682 | [
"JavaScript",
"TypeScript",
"JSON with Comments",
"Markdown"
] | 15 | TypeScript | vazco/livescan | 8f17b8ef3caf84401f3e98ae7073552e5ead2f65 | 12db6ecdc259d0d7b383712a24a295aa73a21738 |
refs/heads/main | <repo_name>jack-nonnie/CPE593DataAnalysis<file_sep>/README.md
# CPE593DataAnalysis
In this project I create a automated data analysis driver.
Given a set of input and output data it tries to fit the data to a constant value, linear function, quadratic function, exponential function and a sine wave.
It works for both Integer[] and double[] datasets.
It also works for 2 Dimensional data as well.
## Running the project
There are two different ways to run the project.
The first is by creating an array of data and utilizing the DataAnalysis object on your array.
I have already done an example of this for each of the possible functions and I added normally distributed noise to each of the functions so that the data is more realistic.
To run my sample data go to CPE593DataAnalysis in your terminal. Than do the following commands:
```bash
cd demo
mvn clean install
mvn compile exec:java -Dexec.mainClass="jack.App"
```
The second way to run the project is by creating a binary file for both your input and output variable.
If you do not wish to create your own I have provided 1 binary input file "input.dat" and 3 binary output files "lin.dat" "quad.dat" and "sin.dat"
When running the project this way the project will give you some instructions and than ask you for the name of your input file and your output file.
Make sure that both of these files are in the repository and exist/spelled correctly otherwise it will cause an error.
It will ask you some other questions like do you want to add a second input and is the binary file a file of double[] or Integer[]. Answer honestly.
To run the project this way go to CPE593DataAnalysis in your terminal. Than do the following commands:
```bash
cd demo
mvn clean install
mvn compile exec:java -Dexec.mainClass="jack.Input"
```
<file_sep>/demo/src/main/java/jack/Input.java
package jack;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Input {
private Input() {
}
public static void main(String[] args) throws IOException {
// This is the code I used to create the binary files that I used to test the
// project
// double[] x = { 1.0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19, 20 };
// double[] lin = new double[20];
// double[] quad = new double[20];
// double[] sin = new double[20];
// Random rand = new Random();
// for (int i = 0; i < 20; i++) {
// lin[i] = x[i] * 2.5 + 7 + rand.nextGaussian();
// quad[i] = x[i] * x[i] * .5 + x[i] * 4 - 12 + rand.nextGaussian();
// sin[i] = 12 * Math.sin(x[i] / Math.PI + .5) + rand.nextGaussian();
// }
// FileOutputStream outX = new FileOutputStream("input.dat");
// DataOutputStream doutX = new DataOutputStream(outX);
// for (double d : x) {
// doutX.writeDouble(d);
// }
// doutX.close();
// FileOutputStream outLin = new FileOutputStream("lin.dat");
// DataOutputStream doutLin = new DataOutputStream(outLin);
// for (double d : lin) {
// doutLin.writeDouble(d);
// }
// doutLin.close();
// FileOutputStream outQuad = new FileOutputStream("quad.dat");
// DataOutputStream doutQuad = new DataOutputStream(outQuad);
// for (double d : quad) {
// doutQuad.writeDouble(d);
// }
// doutQuad.close();
// FileOutputStream outSin = new FileOutputStream("sin.dat");
// DataOutputStream doutSin = new DataOutputStream(outSin);
// for (double d : sin) {
// doutSin.writeDouble(d);
// }
// doutSin.close();
// DataInputStream in = new DataInputStream(new FileInputStream("input.dat"));
// ArrayList<Double> doub = new ArrayList<Double>();
// while (in.available() > 0) {
// doub.add(in.readDouble());
// }
// double[] x1 = new double[doub.size()];
// in.close();
// for (int i = 0; i < doub.size(); i++) {
// x1[i] = doub.get(i);
// }
// DataInputStream in2 = new DataInputStream(new FileInputStream("lin.dat"));
// ArrayList<Double> doub2 = new ArrayList<Double>();
// while (in2.available() > 0) {
// doub2.add(in2.readDouble());
// }
// double[] linear = new double[doub2.size()];
// in2.close();
// for (int i = 0; i < doub2.size(); i++) {
// linear[i] = doub2.get(i);
// }
// DataInputStream in3 = new DataInputStream(new FileInputStream("quad.dat"));
// ArrayList<Double> doub3 = new ArrayList<Double>();
// while (in3.available() > 0) {
// doub3.add(in3.readDouble());
// }
// double[] quadratic = new double[doub3.size()];
// in3.close();
// for (int i = 0; i < doub3.size(); i++) {
// quadratic[i] = doub3.get(i);
// }
// DataInputStream in4 = new DataInputStream(new FileInputStream("sin.dat"));
// ArrayList<Double> doub4 = new ArrayList<Double>();
// while (in4.available() > 0) {
// doub4.add(in4.readDouble());
// }
// double[] sine = new double[doub4.size()];
// in4.close();
// for (int i = 0; i < doub4.size(); i++) {
// sine[i] = doub4.get(i);
// }
// DataAnalysis a = new DataAnalysis(x1, linear);
// System.out.println(a.analyse());
// DataAnalysis b = new DataAnalysis(x1, quad);
// System.out.println(b.analyse()[2]);
// DataAnalysis c = new DataAnalysis(x1, sine);
// System.out.println(c.analyse()[3]);
// Introductory statements
System.out.println(
"The program is going to ask you for the name of the binary file that is the input variable, the output variable, if its a double and if there are two input variables. ");
System.out.println(
"From your answer the data will automatically be analysed and tell you the result that most closely matches your data");
System.out.println(
"Make sure the binary file was already added to the repository prior to running the program and that you spell the name of the file correctly. Failure to do so will cause an error.");
System.out.println("Enter the input variable binary file name: ");
// Asking the user for the names of the binary files that they added to the
// repository in order to run the program on and taking in those file names
Scanner sc = new Scanner(System.in);
String x1Name = sc.nextLine();
System.out.println(
"If you would like to add a second input file type 'Y' type anything else for 1 input variable");
String x2Name = "";
String Var2D = sc.nextLine();
if (Var2D.equals("Y")) {
System.out.println("Enter the second input variable binary file name: ");
x2Name = sc.nextLine();
}
System.out.println("Enter the output variable binary file name: ");
String yName = sc.nextLine();
System.out.println(
"If the binary data you uploaded is a int[] type 'Y' if it is a double[] type in anything else");
String isInt = sc.nextLine();
// Checking to see if the data is Integer[] or double[]
if (isInt.equals("Y")) {
// Scanning the binary file and turing it into an ArrayList than converting the
// ArrayList to an Integer[]
// The reason for using an ArrayList first is because ArrayLists are Arbitrary
// size and I need to convert it to an Integer[] to get it to work with the
// program
DataInputStream inx = new DataInputStream(new FileInputStream(x1Name));
ArrayList<Integer> doubx = new ArrayList<Integer>();
while (inx.available() > 0) {
doubx.add(inx.readInt());
}
Integer[] X1 = new Integer[doubx.size()];
inx.close();
for (int i = 0; i < doubx.size(); i++) {
X1[i] = doubx.get(i);
}
// Same Thing but for the Y var
DataInputStream iny = new DataInputStream(new FileInputStream(yName));
ArrayList<Integer> douby = new ArrayList<Integer>();
while (iny.available() > 0) {
douby.add(iny.readInt());
}
Integer[] Y = new Integer[douby.size()];
iny.close();
for (int i = 0; i < douby.size(); i++) {
Y[i] = douby.get(i);
}
// Checks to see if the User wanted 2 input variables
if (Var2D.equals("Y")) {
DataInputStream inx2 = new DataInputStream(new FileInputStream(x2Name));
ArrayList<Integer> doubx2 = new ArrayList<Integer>();
while (inx2.available() > 0) {
doubx2.add(inx2.readInt());
}
Integer[] X2 = new Integer[doubx2.size()];
inx2.close();
for (int i = 0; i < doubx2.size(); i++) {
X2[i] = doubx2.get(i);
}
// Analyses the data
DataAnalysis2D a = new DataAnalysis2D(X1, X2, Y);
a.analyse();
} else {
// Analyses the data
DataAnalysis a = new DataAnalysis(X1, Y);
a.analyse();
}
sc.close();
} else {
// Scanning the binary file and turing it into an ArrayList than converting the
// ArrayList to a Double[]
// The reason for using an ArrayList first is because ArrayLists are Arbitrary
// size and I need to convert it to an Double[] to get it to work with the
// program
DataInputStream inx = new DataInputStream(new FileInputStream(x1Name));
ArrayList<Double> doubx = new ArrayList<Double>();
while (inx.available() > 0) {
doubx.add(inx.readDouble());
}
double[] X1 = new double[doubx.size()];
inx.close();
for (int i = 0; i < doubx.size(); i++) {
X1[i] = doubx.get(i);
}
// Same Thing but for the Y var
DataInputStream iny = new DataInputStream(new FileInputStream(yName));
ArrayList<Double> douby = new ArrayList<Double>();
while (iny.available() > 0) {
douby.add(iny.readDouble());
}
double[] Y = new double[douby.size()];
iny.close();
for (int i = 0; i < douby.size(); i++) {
Y[i] = douby.get(i);
}
// Checks to see if the user wanted 2 input vars
if (Var2D.equals("Y")) {
// Same thing as above but for the second input var
DataInputStream inx2 = new DataInputStream(new FileInputStream(x2Name));
ArrayList<Double> doubx2 = new ArrayList<Double>();
while (inx2.available() > 0) {
doubx2.add(inx2.readDouble());
}
double[] X2 = new double[doubx2.size()];
inx2.close();
for (int i = 0; i < doubx2.size(); i++) {
X2[i] = doubx2.get(i);
}
// Analyses the data
DataAnalysis2D a = new DataAnalysis2D(X1, X2, Y);
a.analyse();
} else {
// Analyses the data
DataAnalysis a = new DataAnalysis(X1, Y);
a.analyse();
}
sc.close();
}
}
}<file_sep>/Documents/README.md
For this project I will be working on my own to come up with an automated exploratory data analysis algorithm. I will do this by creating multiple different algorithms to fit a variety of different curves to a given dataset. I will utilize MSE to judge the overall fitness of a curve. I will come up with an algorithm to match a constant value, a linear sequence, a quadratic sequence, a 2D linear sequence, a 2D quadratic sequence, an exponential curve, a sine wave, a cubic spline, and a PCHIP to a given dataset. I will come up with the algorithm for determining the best parameters for each curve to match the data by utilizing stochastic gradient descent over the entire dataset. Once I have the parameters for a curve fitted I will take the MSE for the whole data set for each curve. I will then compare all of the errors for all of the curves and return the curve that best fits the data along with the error associated with this curve. This whole process will be completely automated.
| fb3b548a950385bd0973425588101b04fee7f2fa | [
"Markdown",
"Java"
] | 3 | Markdown | jack-nonnie/CPE593DataAnalysis | c0c092cb742b776a7af307ca5c2cbb47f4f3b315 | d0e5f398cf678317c563f6742a29786cd124f3b3 |
refs/heads/master | <file_sep>import ast
import sys
import pytest
from pyp import find_names
def test_basic():
assert (set(), set("x")) == find_names(ast.parse("x[:3]"))
assert ({"x"}, set()) == find_names(ast.parse("x = 1"))
assert ({"x", "y"}, set()) == find_names(ast.parse("x = 1; y = x + 1"))
def test_builtins():
assert (set(), {"print"}) == find_names(ast.parse("print(5)"))
assert ({"print"}, set()) == find_names(ast.parse("print = 5; print(5)"))
def test_loops():
assert ({"x"}, {"y", "print"}) == find_names(ast.parse("for x in y: print(x)"))
assert (set(), {"x"}) == find_names(ast.parse("while x: pass"))
def test_weird_assignments():
assert ({"x"}, {"x"}) == find_names(ast.parse("x += 1"))
assert ({"x"}, {"x"}) == find_names(ast.parse("for x in x: pass"))
assert ({"x", "y"}, {"x", "y"}) == find_names(ast.parse("x, y = x, y"))
if sys.version_info >= (3, 8):
assert ({"x"}, {"x"}) == find_names(ast.parse("(x := x)"))
def test_comprehensions():
assert ({"x"}, {"y"}) == find_names(ast.parse("(x for x in y)"))
assert ({"x"}, {"x"}) == find_names(ast.parse("(x for x in x)"))
assert ({"x", "xx"}, {"xxx"}) == find_names(ast.parse("(x for xx in xxx for x in xx)"))
assert ({"x", "xx"}, {"xx", "xxx"}) == find_names(ast.parse("(x for x in xx for xx in xxx)"))
assert ({"x"}, {"xx"}) == find_names(ast.parse("(x for x in xx if x == 'foo')"))
def test_args():
assert ({"f"}, {"x"}) == find_names(ast.parse("f = lambda: x"))
assert ({"f", "x"}, set()) == find_names(ast.parse("f = lambda x: x"))
assert ({"f", "x"}, {"y"}) == find_names(ast.parse("f = lambda x: y"))
assert ({"a", "b", "c", "x", "y", "z"}, set()) == find_names(
ast.parse("def f(x, y = 0, *z, a, b = 0, **c): ...")
)
@pytest.mark.xfail(reason="do not currently support scopes")
def test_args_bad():
assert ({"f", "x"}, {"x"}) == find_names(ast.parse("f = lambda x: x; x"))
@pytest.mark.xfail(reason="do not currently support deletes")
def test_del():
assert ({"x"}, {"x"}) == find_names(ast.parse("x = 3; del x; x"))
| b5b58dd11e4107f232973bba189c982e549d7c8f | [
"Python"
] | 1 | Python | sailfish009/pyp | b06421dcccbc57f118e166fd683053715257695b | ad7374c25d8adb1e52c8b19ee8b627ad6a29aa29 |
refs/heads/master | <file_sep>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;
namespace Ramy_Shop.PL
{
public partial class FRM_MAIN : Form
{
//Instance from frm class
private static FRM_MAIN frm;
static void frm_Formclosed(object sender, FormClosedEventArgs e)
{
frm = null;
}
public static FRM_MAIN getMainForm
{
get
{
if(frm == null)
{
frm = new FRM_MAIN();
frm.FormClosed+=new FormClosedEventHandler(frm_Formclosed);
}
return frm;
}
}
public FRM_MAIN()
{
InitializeComponent();
if (frm == null)
frm = this;
this.المنتجاتToolStripMenuItem.Enabled = false;
this.العملاءToolStripMenuItem.Enabled = false;
this.المستخدمونToolStripMenuItem.Enabled = false;
this.إنشاءنسخةإحتياطيةToolStripMenuItem.Enabled = false;
this.إستعادةToolStripMenuItem.Enabled = false;
}
private void تسجيلالدخولToolStripMenuItem_Click(object sender, EventArgs e)
{
FRM_LOGIN frm = new FRM_LOGIN();
frm.ShowDialog();
}
private void FRM_MAIN_Load(object sender, EventArgs e)
{
}
private void تسجيلالخروجToolStripMenuItem_Click(object sender, EventArgs e)
{
frm.Close();
}
private void إضافةToolStripMenuItem_Click(object sender, EventArgs e)
{
FRM_ADD_PRODUCT frm = new FRM_ADD_PRODUCT();
frm.ShowDialog();
}
}
}
<file_sep>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;
namespace Ramy_Shop.PL
{
public partial class FRM_ADD_PRODUCT : Form
{
public FRM_ADD_PRODUCT()
{
InitializeComponent();
}
private void FRM_ADD_PRODUCT_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "ملفات الصور | *.PNG; *.GIF;*.BMP";
if(ofd.ShowDialog() ==DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
}
}
<file_sep>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;
namespace Ramy_Shop.PL
{
public partial class FRM_LOGIN : Form
{
BL.CLA_LOGIN log = new BL.CLA_LOGIN();
public FRM_LOGIN()
{
InitializeComponent();
}
private void FRM_LOGIN_Load(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = log.Login(txtID.Text, txtPWD.Text);
if(dt.Rows.Count > 0)
{
FRM_MAIN.getMainForm.المنتجاتToolStripMenuItem.Enabled = true;
FRM_MAIN.getMainForm.العملاءToolStripMenuItem.Enabled = true;
FRM_MAIN.getMainForm.المستخدمونToolStripMenuItem.Enabled = true;
FRM_MAIN.getMainForm.إنشاءنسخةإحتياطيةToolStripMenuItem.Enabled = true;
FRM_MAIN.getMainForm.إستعادةToolStripMenuItem.Enabled = true;
this.Close();
}
else
{
MessageBox.Show("أعد المحالة مرة اخري");
}
}
}
}
| e1991e4af712417b69ed63497f792da56f3c1016 | [
"C#"
] | 3 | C# | mahmoudFaragallah/Sales-Management | 5c017fe46178058637ba996616545c371bfc64f7 | d389c0c2aac4a71ee0cd536c22a7e15d7ea2c9da |
refs/heads/master | <file_sep>import csv
import pygal
from scipy.interpolate import interp1d
import numpy as np
""" This project attempts to evaluate whether advancement on different
portions of the football field is more valuable. It quanifies the values
from a team's own goal line up to the opposing teams. It does this by
looking at the average next score from data provided by nflscrapR in
csv format. Further, this project attempts to uncover whether this method
of valuing yards correlates with the outcome of a game over the standard
comparision of total yards"""
# Initiate list of list to store data for each down
yard_scores = [[0 for i in range(1,100)] for i in range(4)]
num_plays = [[0 for i in range(1,100)] for i in range(4)]
yard_values = [[0 for i in range(1,100)] for i in range(4)]
# Initiate lists to store counter for score type
off_td = [[0 for i in range(1,100)] for i in range(4)]
def_td = [[0 for i in range(1,100)] for i in range(4)]
off_fg = [[0 for i in range(1,100)] for i in range(4)]
def_fg = [[0 for i in range(1,100)] for i in range(4)]
off_safety = [[0 for i in range(1,100)] for i in range(4)]
def_safety = [[0 for i in range(1,100)] for i in range(4)]
# Loop to navigate thru available seasons
for year in range(2009, 2019):
# Initiate filename that iterates thru every year
filename = str(year) + '_reg_season_pbp.csv'
# Load data
with open(filename) as f:
data = csv.reader(f)
header_row = next(data)
# Store data in list of lists to access w/ file closed
pbp = []
for row in data:
pbp.append(row)
# Start loop through given year & intialize index counter
index = -1
for p in pbp:
index += 1
# Remove kickoffs, no plays, end of quarters,
# extra points, and two point conversions
if (p[25] == 'kickoff' or p[25] == 'no_play'
or p[25] == 'NA' or p[25] == 'qb_kneel'
or p[25] == 'extra_point' or p[42] != 'NA'):
continue
# Specify down for given play
if p[18] == '1':
down = 1
elif p[18] == '2':
down = 2
elif p[18] == '3':
down = 3
elif p[18] == '4':
down = 4
else:
print('Error')
print(index)
# Establish what side of field team in possession has the ball
yardline = p[21].split()
# If on own side of field, yardline is number that follows side
if p[4] == p[7]:
yardline = 100 - int(yardline[1])
elif p[6] == p[7]:
yardline = int(yardline[1])
elif p[7] == 'MID':
yardline = 50
# Attribute score on scoring play from the yard it originated
# Identify whether home or away team had the ball
if int(p[16]) == 1:
if p[2] == p[4]:
off_score_index = 50
def_score_index = 51
elif p[3] == p[4]:
off_score_index = 51
def_score_index = 50
# Establish initial offensive and defensive scores
orig_off_score = int(pbp[index-1][off_score_index])
orig_def_score = int(pbp[index-1][def_score_index])
# Identify new offensive and defensive scores on a scoring play,
# calculate score change and attribute it to yardline
new_off_score = int(p[off_score_index])
new_def_score = int(p[def_score_index])
score_diff = (new_off_score - orig_off_score) - (new_def_score - orig_def_score)
# Identify score type on scoring plays and attribute to yardline
if int(score_diff) == 6:
off_td[down-1][yardline-1] += 1
elif int(score_diff) == 3:
off_fg[down-1][yardline-1] += 1
elif int(score_diff) == -6:
def_td[down-1][yardline-1] += 1
elif int(score_diff) == -3:
def_fg[down-1][yardline-1] += 1
elif int(score_diff) == 2:
off_safety[down-1][yardline-1] += 1
elif int(score_diff) == -2:
def_safety[down-1][yardline-1] += 1
# Add points for extra points and two point conversion
if int(score_diff) == 6:
stop = 0
for pat in pbp[index:]:
stop += 1
if pat[16] == '1' and pat[25] == 'extra_point':
score_diff += 1
break
if play[16] == '1' and play[42] == 'success':
score_diff += 2
break
if stop > 3:
break
yard_scores[down-1][yardline-1] += score_diff
num_plays[down-1][yardline-1] += 1
# No need to look for later scores
continue
# Search for next score from a given non-scoring play
# Identify whether home or away team had the ball
if p[2] == p[4]:
off_score_index = 50
def_score_index = 51
elif p[3] == p[4]:
off_score_index = 51
def_score_index = 50
# Establish initial offensive and defensive scores
orig_off_score = int(p[off_score_index])
orig_def_score = int(p[def_score_index])
game_id = int(p[1])
# Search for next score
for play in pbp[index:]:
# Identify play where score changes
if int(play[off_score_index]) != orig_off_score or int(play[def_score_index]) != orig_def_score:
# Attribute no score if half ends or game ends
if play[24] == 'END QUARTER 2' or play[24] == 'END GAME':
break
# Calculate how much score changed
else:
new_off_score = int(play[off_score_index])
new_def_score = int(play[def_score_index])
score_diff = (new_off_score - orig_off_score) - (new_def_score - orig_def_score)
# Identify score type on scoring plays and attribute to yardline
if int(score_diff) == 6:
off_td[down-1][yardline-1] += 1
elif int(score_diff) == 3:
off_fg[down-1][yardline-1] += 1
elif int(score_diff) == -6:
def_td[down-1][yardline-1] += 1
elif int(score_diff) == -3:
def_fg[down-1][yardline-1] += 1
elif int(score_diff) == 2:
off_safety[down-1][yardline-1] += 1
elif int(score_diff) == -2:
def_safety[down-1][yardline-1] += 1
# Add points for extra points and two point conversion
if int(score_diff) == 6:
stop = 0
for pat in pbp[index:]:
stop += 1
if pat[16] == '1' and pat[25] == 'extra_point':
score_diff += 1
break
if play[16] == '1' and play[42] == 'success':
score_diff += 2
break
if stop > 3:
break
yard_scores[down-1][yardline-1] += score_diff
num_plays[down-1][yardline-1] += 1
break
for down in range(4):
for yard in range(99):
yard_values[down][yard] = yard_scores[down][yard] / num_plays[down][yard]
off_td[down][yard] = off_td[down][yard] / num_plays[down][yard] * 100
off_fg[down][yard] = off_fg[down][yard] / num_plays[down][yard] * 100
def_td[down][yard] = def_td[down][yard] / num_plays[down][yard] * 100
def_fg[down][yard] = def_fg[down][yard] / num_plays[down][yard] * 100
off_safety[down][yard] = off_safety[down][yard] / num_plays[down][yard] * 100
def_safety[down][yard] = def_safety[down][yard] / num_plays[down][yard] * 100
# Graph final
x_label = [num for num in range(1,100)]
x_labels_maj = [num for num in range(5, 100, 5)]
# Write data to csv
with open("expected_points_data.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(yard_values)
exp_value = pygal.Line(show_minor_x_labels=False, truncate_label=-1, x_title = 'Yards from Opponents Endzone', y_title = 'Expected Points', label_font_size=3)
exp_value.title = 'Expected Points From Each Yardline in the NFL'
exp_value.x_labels = x_label
exp_value.x_labels_major = x_labels_maj
exp_value.add( 'First Down', yard_values[0])
exp_value.add( 'Second Down', yard_values[1])
exp_value.add( 'Third Down', yard_values[2])
exp_value.add( 'Fourth Down', yard_values[3])
exp_value.render_to_file('value_of_yards_nfl.svg')
score_type_first = pygal.Line(legend_at_bottom=True, show_minor_x_labels=False, truncate_label=-1, x_title = 'Yards from Opponents Endzone', y_title = 'Probability in %', label_font_size=3)
score_type_first.title = 'Probabilities of Type of Next Score From First Down'
score_type_first.x_labels = x_label
score_type_first.x_labels_major = x_labels_maj
score_type_first.add('Offense Scores TD', off_td[0])
score_type_first.add('Defense Scores TD', def_td[0])
score_type_first.add('Offense Scores FG', off_fg[0])
score_type_first.add('Defense Scores FG', def_fg[0])
score_type_first.add('Safety Against Defense', off_safety[0])
score_type_first.add('Safety Against Offense', def_safety[0])
score_type_first.render_to_file('next_score_type_first_nfl.svg')
score_type_second = pygal.Line(legend_at_bottom=True, show_minor_x_labels=False, truncate_label=-1, x_title = 'Yards from Opponents Endzone', y_title = 'Probability in %', label_font_size=3)
score_type_second.title = 'Probabilities of Type of Next Score From Second Down'
score_type_second.x_labels = x_label
score_type_second.x_labels_major = x_labels_maj
score_type_second.add('Offense Scores TD', off_td[1])
score_type_second.add('Defense Scores TD', def_td[1])
score_type_second.add('Offense Scores FG', off_fg[1])
score_type_second.add('Defense Scores FG', def_fg[1])
score_type_second.add('Safety Against Defense', off_safety[1])
score_type_second.add('Safety Against Offense', def_safety[1])
score_type_second.render_to_file('next_score_type_second_nfl.svg')
score_type_third = pygal.Line(legend_at_bottom=True, show_minor_x_labels=False, truncate_label=-1, x_title = 'Yards from Opponents Endzone', y_title = 'Probability in %', label_font_size=3)
score_type_third.title = 'Probabilities of Type of Next Score From Third Down'
score_type_third.x_labels = x_label
score_type_third.x_labels_major = x_labels_maj
score_type_third.add('Offense Scores TD', off_td[2])
score_type_third.add('Defense Scores TD', def_td[2])
score_type_third.add('Offense Scores FG', off_fg[2])
score_type_third.add('Defense Scores FG', def_fg[2])
score_type_third.add('Safety Against Defense', off_safety[2])
score_type_third.add('Safety Against Offense', def_safety[2])
score_type_third.render_to_file('next_score_type_third_nfl.svg')
score_type_fourth = pygal.Line(legend_at_bottom=True, show_minor_x_labels=False, truncate_label=-1, x_title = 'Yards from Opponents Endzone', y_title = 'Probability in %', label_font_size=3)
score_type_fourth.title = 'Probabilities of Type of Next Score From Fourth Down'
score_type_fourth.x_labels = x_label
score_type_fourth.x_labels_major = x_labels_maj
score_type_fourth.add('Offense Scores TD', off_td[3])
score_type_fourth.add('Defense Scores TD', def_td[3])
score_type_fourth.add('Offense Scores FG', off_fg[3])
score_type_fourth.add('Defense Scores FG', def_fg[3])
score_type_fourth.add('Safety Against Defense', off_safety[3])
score_type_fourth.add('Safety Against Offense', def_safety[3])
score_type_fourth.render_to_file('next_score_type_fourth_nfl.svg')
# DOES EXPECTED POINTS FROM YARDS GAINED CORRELATE BETTER TO RESULTS THAN SIMPLY TOTAL YARDS
# WHERE IS WORSE SPOT TO TURN THE BALL OVER (ORIG EXP POINTS - NEW EXP POINTS)
| a7647f9fc42bada00cebc99a1b77e933071b6937 | [
"Python"
] | 1 | Python | mrmcmullan/expected_points | 98f2bd9362d8003871ee07ae2de6e2393b6e907b | 436f6d47a351ecc4e1a08fdd6386dcadb48844eb |
refs/heads/master | <file_sep>package io.aggreg.app.provider.publishercategory;
import java.util.Date;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import io.aggreg.app.provider.base.AbstractSelection;
import io.aggreg.app.provider.publisher.*;
import io.aggreg.app.provider.category.*;
/**
* Selection for the {@code publisher_category} table.
*/
public class PublisherCategorySelection extends AbstractSelection<PublisherCategorySelection> {
@Override
protected Uri baseUri() {
return PublisherCategoryColumns.CONTENT_URI;
}
/**
* Query the given content resolver using this selection.
*
* @param contentResolver The content resolver to query.
* @param projection A list of which columns to return. Passing null will return all columns, which is inefficient.
* @param sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort
* order, which may be unordered.
* @return A {@code PublisherCategoryCursor} object, which is positioned before the first entry, or null.
*/
public PublisherCategoryCursor query(ContentResolver contentResolver, String[] projection, String sortOrder) {
Cursor cursor = contentResolver.query(uri(), projection, sel(), args(), sortOrder);
if (cursor == null) return null;
return new PublisherCategoryCursor(cursor);
}
/**
* Equivalent of calling {@code query(contentResolver, projection, null)}.
*/
public PublisherCategoryCursor query(ContentResolver contentResolver, String[] projection) {
return query(contentResolver, projection, null);
}
/**
* Equivalent of calling {@code query(contentResolver, projection, null, null)}.
*/
public PublisherCategoryCursor query(ContentResolver contentResolver) {
return query(contentResolver, null, null);
}
public PublisherCategorySelection id(long... value) {
addEquals("publisher_category." + PublisherCategoryColumns._ID, toObjectArray(value));
return this;
}
public PublisherCategorySelection publisherId(long... value) {
addEquals(PublisherCategoryColumns.PUBLISHER_ID, toObjectArray(value));
return this;
}
public PublisherCategorySelection publisherIdNot(long... value) {
addNotEquals(PublisherCategoryColumns.PUBLISHER_ID, toObjectArray(value));
return this;
}
public PublisherCategorySelection publisherIdGt(long value) {
addGreaterThan(PublisherCategoryColumns.PUBLISHER_ID, value);
return this;
}
public PublisherCategorySelection publisherIdGtEq(long value) {
addGreaterThanOrEquals(PublisherCategoryColumns.PUBLISHER_ID, value);
return this;
}
public PublisherCategorySelection publisherIdLt(long value) {
addLessThan(PublisherCategoryColumns.PUBLISHER_ID, value);
return this;
}
public PublisherCategorySelection publisherIdLtEq(long value) {
addLessThanOrEquals(PublisherCategoryColumns.PUBLISHER_ID, value);
return this;
}
public PublisherCategorySelection publisherImageUrl(String... value) {
addEquals(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection publisherImageUrlNot(String... value) {
addNotEquals(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection publisherImageUrlLike(String... value) {
addLike(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection publisherImageUrlContains(String... value) {
addContains(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection publisherImageUrlStartsWith(String... value) {
addStartsWith(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection publisherImageUrlEndsWith(String... value) {
addEndsWith(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection publisherWebsite(String... value) {
addEquals(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherCategorySelection publisherWebsiteNot(String... value) {
addNotEquals(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherCategorySelection publisherWebsiteLike(String... value) {
addLike(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherCategorySelection publisherWebsiteContains(String... value) {
addContains(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherCategorySelection publisherWebsiteStartsWith(String... value) {
addStartsWith(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherCategorySelection publisherWebsiteEndsWith(String... value) {
addEndsWith(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherCategorySelection publisherName(String... value) {
addEquals(PublisherColumns.NAME, value);
return this;
}
public PublisherCategorySelection publisherNameNot(String... value) {
addNotEquals(PublisherColumns.NAME, value);
return this;
}
public PublisherCategorySelection publisherNameLike(String... value) {
addLike(PublisherColumns.NAME, value);
return this;
}
public PublisherCategorySelection publisherNameContains(String... value) {
addContains(PublisherColumns.NAME, value);
return this;
}
public PublisherCategorySelection publisherNameStartsWith(String... value) {
addStartsWith(PublisherColumns.NAME, value);
return this;
}
public PublisherCategorySelection publisherNameEndsWith(String... value) {
addEndsWith(PublisherColumns.NAME, value);
return this;
}
public PublisherCategorySelection publisherCountry(String... value) {
addEquals(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherCategorySelection publisherCountryNot(String... value) {
addNotEquals(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherCategorySelection publisherCountryLike(String... value) {
addLike(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherCategorySelection publisherCountryContains(String... value) {
addContains(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherCategorySelection publisherCountryStartsWith(String... value) {
addStartsWith(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherCategorySelection publisherCountryEndsWith(String... value) {
addEndsWith(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherCategorySelection publisherTagLine(String... value) {
addEquals(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherCategorySelection publisherTagLineNot(String... value) {
addNotEquals(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherCategorySelection publisherTagLineLike(String... value) {
addLike(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherCategorySelection publisherTagLineContains(String... value) {
addContains(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherCategorySelection publisherTagLineStartsWith(String... value) {
addStartsWith(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherCategorySelection publisherTagLineEndsWith(String... value) {
addEndsWith(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherCategorySelection publisherFollowing(boolean value) {
addEquals(PublisherColumns.FOLLOWING, toObjectArray(value));
return this;
}
public PublisherCategorySelection publisherOrder(Integer... value) {
addEquals(PublisherColumns.ORDER, value);
return this;
}
public PublisherCategorySelection publisherOrderNot(Integer... value) {
addNotEquals(PublisherColumns.ORDER, value);
return this;
}
public PublisherCategorySelection publisherOrderGt(int value) {
addGreaterThan(PublisherColumns.ORDER, value);
return this;
}
public PublisherCategorySelection publisherOrderGtEq(int value) {
addGreaterThanOrEquals(PublisherColumns.ORDER, value);
return this;
}
public PublisherCategorySelection publisherOrderLt(int value) {
addLessThan(PublisherColumns.ORDER, value);
return this;
}
public PublisherCategorySelection publisherOrderLtEq(int value) {
addLessThanOrEquals(PublisherColumns.ORDER, value);
return this;
}
public PublisherCategorySelection categoryId(long... value) {
addEquals(PublisherCategoryColumns.CATEGORY_ID, toObjectArray(value));
return this;
}
public PublisherCategorySelection categoryIdNot(long... value) {
addNotEquals(PublisherCategoryColumns.CATEGORY_ID, toObjectArray(value));
return this;
}
public PublisherCategorySelection categoryIdGt(long value) {
addGreaterThan(PublisherCategoryColumns.CATEGORY_ID, value);
return this;
}
public PublisherCategorySelection categoryIdGtEq(long value) {
addGreaterThanOrEquals(PublisherCategoryColumns.CATEGORY_ID, value);
return this;
}
public PublisherCategorySelection categoryIdLt(long value) {
addLessThan(PublisherCategoryColumns.CATEGORY_ID, value);
return this;
}
public PublisherCategorySelection categoryIdLtEq(long value) {
addLessThanOrEquals(PublisherCategoryColumns.CATEGORY_ID, value);
return this;
}
public PublisherCategorySelection categoryName(String... value) {
addEquals(CategoryColumns.NAME, value);
return this;
}
public PublisherCategorySelection categoryNameNot(String... value) {
addNotEquals(CategoryColumns.NAME, value);
return this;
}
public PublisherCategorySelection categoryNameLike(String... value) {
addLike(CategoryColumns.NAME, value);
return this;
}
public PublisherCategorySelection categoryNameContains(String... value) {
addContains(CategoryColumns.NAME, value);
return this;
}
public PublisherCategorySelection categoryNameStartsWith(String... value) {
addStartsWith(CategoryColumns.NAME, value);
return this;
}
public PublisherCategorySelection categoryNameEndsWith(String... value) {
addEndsWith(CategoryColumns.NAME, value);
return this;
}
public PublisherCategorySelection categoryImageUrl(String... value) {
addEquals(CategoryColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection categoryImageUrlNot(String... value) {
addNotEquals(CategoryColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection categoryImageUrlLike(String... value) {
addLike(CategoryColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection categoryImageUrlContains(String... value) {
addContains(CategoryColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection categoryImageUrlStartsWith(String... value) {
addStartsWith(CategoryColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection categoryImageUrlEndsWith(String... value) {
addEndsWith(CategoryColumns.IMAGE_URL, value);
return this;
}
public PublisherCategorySelection categoryOrder(Integer... value) {
addEquals(CategoryColumns.ORDER, value);
return this;
}
public PublisherCategorySelection categoryOrderNot(Integer... value) {
addNotEquals(CategoryColumns.ORDER, value);
return this;
}
public PublisherCategorySelection categoryOrderGt(int value) {
addGreaterThan(CategoryColumns.ORDER, value);
return this;
}
public PublisherCategorySelection categoryOrderGtEq(int value) {
addGreaterThanOrEquals(CategoryColumns.ORDER, value);
return this;
}
public PublisherCategorySelection categoryOrderLt(int value) {
addLessThan(CategoryColumns.ORDER, value);
return this;
}
public PublisherCategorySelection categoryOrderLtEq(int value) {
addLessThanOrEquals(CategoryColumns.ORDER, value);
return this;
}
}
<file_sep>package io.aggreg.app.ui;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import io.aggreg.app.R;
import io.aggreg.app.ui.fragment.PublishersFragment;
import io.aggreg.app.utils.GeneralUtils;
import io.aggreg.app.utils.References;
public class ManagePublishersActivity extends AppCompatActivity implements PublishersFragment.OnFragmentInteractionListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_publisher);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, PublishersFragment.newInstance())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_publisher, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}else if(id == R.id.action_refresh){
new GeneralUtils(this).SyncRefreshPublisherCategories();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFabClicked() {
finish();
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
<file_sep>package io.aggreg.app.provider.article;
import java.util.Date;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import io.aggreg.app.provider.base.AbstractSelection;
import io.aggreg.app.provider.category.*;
import io.aggreg.app.provider.publisher.*;
/**
* Selection for the {@code article} table.
*/
public class ArticleSelection extends AbstractSelection<ArticleSelection> {
@Override
protected Uri baseUri() {
return ArticleColumns.CONTENT_URI;
}
/**
* Query the given content resolver using this selection.
*
* @param contentResolver The content resolver to query.
* @param projection A list of which columns to return. Passing null will return all columns, which is inefficient.
* @param sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort
* order, which may be unordered.
* @return A {@code ArticleCursor} object, which is positioned before the first entry, or null.
*/
public ArticleCursor query(ContentResolver contentResolver, String[] projection, String sortOrder) {
Cursor cursor = contentResolver.query(uri(), projection, sel(), args(), sortOrder);
if (cursor == null) return null;
return new ArticleCursor(cursor);
}
/**
* Equivalent of calling {@code query(contentResolver, projection, null)}.
*/
public ArticleCursor query(ContentResolver contentResolver, String[] projection) {
return query(contentResolver, projection, null);
}
/**
* Equivalent of calling {@code query(contentResolver, projection, null, null)}.
*/
public ArticleCursor query(ContentResolver contentResolver) {
return query(contentResolver, null, null);
}
public ArticleSelection id(long... value) {
addEquals("article." + ArticleColumns._ID, toObjectArray(value));
return this;
}
public ArticleSelection title(String... value) {
addEquals(ArticleColumns.TITLE, value);
return this;
}
public ArticleSelection titleNot(String... value) {
addNotEquals(ArticleColumns.TITLE, value);
return this;
}
public ArticleSelection titleLike(String... value) {
addLike(ArticleColumns.TITLE, value);
return this;
}
public ArticleSelection titleContains(String... value) {
addContains(ArticleColumns.TITLE, value);
return this;
}
public ArticleSelection titleStartsWith(String... value) {
addStartsWith(ArticleColumns.TITLE, value);
return this;
}
public ArticleSelection titleEndsWith(String... value) {
addEndsWith(ArticleColumns.TITLE, value);
return this;
}
public ArticleSelection link(String... value) {
addEquals(ArticleColumns.LINK, value);
return this;
}
public ArticleSelection linkNot(String... value) {
addNotEquals(ArticleColumns.LINK, value);
return this;
}
public ArticleSelection linkLike(String... value) {
addLike(ArticleColumns.LINK, value);
return this;
}
public ArticleSelection linkContains(String... value) {
addContains(ArticleColumns.LINK, value);
return this;
}
public ArticleSelection linkStartsWith(String... value) {
addStartsWith(ArticleColumns.LINK, value);
return this;
}
public ArticleSelection linkEndsWith(String... value) {
addEndsWith(ArticleColumns.LINK, value);
return this;
}
public ArticleSelection image(String... value) {
addEquals(ArticleColumns.IMAGE, value);
return this;
}
public ArticleSelection imageNot(String... value) {
addNotEquals(ArticleColumns.IMAGE, value);
return this;
}
public ArticleSelection imageLike(String... value) {
addLike(ArticleColumns.IMAGE, value);
return this;
}
public ArticleSelection imageContains(String... value) {
addContains(ArticleColumns.IMAGE, value);
return this;
}
public ArticleSelection imageStartsWith(String... value) {
addStartsWith(ArticleColumns.IMAGE, value);
return this;
}
public ArticleSelection imageEndsWith(String... value) {
addEndsWith(ArticleColumns.IMAGE, value);
return this;
}
public ArticleSelection pubDate(Date... value) {
addEquals(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection pubDateNot(Date... value) {
addNotEquals(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection pubDate(Long... value) {
addEquals(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection pubDateAfter(Date value) {
addGreaterThan(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection pubDateAfterEq(Date value) {
addGreaterThanOrEquals(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection pubDateBefore(Date value) {
addLessThan(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection pubDateBeforeEq(Date value) {
addLessThanOrEquals(ArticleColumns.PUB_DATE, value);
return this;
}
public ArticleSelection text(String... value) {
addEquals(ArticleColumns.TEXT, value);
return this;
}
public ArticleSelection textNot(String... value) {
addNotEquals(ArticleColumns.TEXT, value);
return this;
}
public ArticleSelection textLike(String... value) {
addLike(ArticleColumns.TEXT, value);
return this;
}
public ArticleSelection textContains(String... value) {
addContains(ArticleColumns.TEXT, value);
return this;
}
public ArticleSelection textStartsWith(String... value) {
addStartsWith(ArticleColumns.TEXT, value);
return this;
}
public ArticleSelection textEndsWith(String... value) {
addEndsWith(ArticleColumns.TEXT, value);
return this;
}
public ArticleSelection bookMarked(Boolean value) {
addEquals(ArticleColumns.BOOK_MARKED, toObjectArray(value));
return this;
}
public ArticleSelection isRead(Boolean value) {
addEquals(ArticleColumns.IS_READ, toObjectArray(value));
return this;
}
public ArticleSelection categoryId(long... value) {
addEquals(ArticleColumns.CATEGORY_ID, toObjectArray(value));
return this;
}
public ArticleSelection categoryIdNot(long... value) {
addNotEquals(ArticleColumns.CATEGORY_ID, toObjectArray(value));
return this;
}
public ArticleSelection categoryIdGt(long value) {
addGreaterThan(ArticleColumns.CATEGORY_ID, value);
return this;
}
public ArticleSelection categoryIdGtEq(long value) {
addGreaterThanOrEquals(ArticleColumns.CATEGORY_ID, value);
return this;
}
public ArticleSelection categoryIdLt(long value) {
addLessThan(ArticleColumns.CATEGORY_ID, value);
return this;
}
public ArticleSelection categoryIdLtEq(long value) {
addLessThanOrEquals(ArticleColumns.CATEGORY_ID, value);
return this;
}
public ArticleSelection categoryName(String... value) {
addEquals(CategoryColumns.NAME, value);
return this;
}
public ArticleSelection categoryNameNot(String... value) {
addNotEquals(CategoryColumns.NAME, value);
return this;
}
public ArticleSelection categoryNameLike(String... value) {
addLike(CategoryColumns.NAME, value);
return this;
}
public ArticleSelection categoryNameContains(String... value) {
addContains(CategoryColumns.NAME, value);
return this;
}
public ArticleSelection categoryNameStartsWith(String... value) {
addStartsWith(CategoryColumns.NAME, value);
return this;
}
public ArticleSelection categoryNameEndsWith(String... value) {
addEndsWith(CategoryColumns.NAME, value);
return this;
}
public ArticleSelection categoryImageUrl(String... value) {
addEquals(CategoryColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection categoryImageUrlNot(String... value) {
addNotEquals(CategoryColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection categoryImageUrlLike(String... value) {
addLike(CategoryColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection categoryImageUrlContains(String... value) {
addContains(CategoryColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection categoryImageUrlStartsWith(String... value) {
addStartsWith(CategoryColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection categoryImageUrlEndsWith(String... value) {
addEndsWith(CategoryColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection categoryOrder(Integer... value) {
addEquals(CategoryColumns.ORDER, value);
return this;
}
public ArticleSelection categoryOrderNot(Integer... value) {
addNotEquals(CategoryColumns.ORDER, value);
return this;
}
public ArticleSelection categoryOrderGt(int value) {
addGreaterThan(CategoryColumns.ORDER, value);
return this;
}
public ArticleSelection categoryOrderGtEq(int value) {
addGreaterThanOrEquals(CategoryColumns.ORDER, value);
return this;
}
public ArticleSelection categoryOrderLt(int value) {
addLessThan(CategoryColumns.ORDER, value);
return this;
}
public ArticleSelection categoryOrderLtEq(int value) {
addLessThanOrEquals(CategoryColumns.ORDER, value);
return this;
}
public ArticleSelection publisherId(long... value) {
addEquals(ArticleColumns.PUBLISHER_ID, toObjectArray(value));
return this;
}
public ArticleSelection publisherIdNot(long... value) {
addNotEquals(ArticleColumns.PUBLISHER_ID, toObjectArray(value));
return this;
}
public ArticleSelection publisherIdGt(long value) {
addGreaterThan(ArticleColumns.PUBLISHER_ID, value);
return this;
}
public ArticleSelection publisherIdGtEq(long value) {
addGreaterThanOrEquals(ArticleColumns.PUBLISHER_ID, value);
return this;
}
public ArticleSelection publisherIdLt(long value) {
addLessThan(ArticleColumns.PUBLISHER_ID, value);
return this;
}
public ArticleSelection publisherIdLtEq(long value) {
addLessThanOrEquals(ArticleColumns.PUBLISHER_ID, value);
return this;
}
public ArticleSelection publisherImageUrl(String... value) {
addEquals(PublisherColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection publisherImageUrlNot(String... value) {
addNotEquals(PublisherColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection publisherImageUrlLike(String... value) {
addLike(PublisherColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection publisherImageUrlContains(String... value) {
addContains(PublisherColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection publisherImageUrlStartsWith(String... value) {
addStartsWith(PublisherColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection publisherImageUrlEndsWith(String... value) {
addEndsWith(PublisherColumns.IMAGE_URL, value);
return this;
}
public ArticleSelection publisherWebsite(String... value) {
addEquals(PublisherColumns.WEBSITE, value);
return this;
}
public ArticleSelection publisherWebsiteNot(String... value) {
addNotEquals(PublisherColumns.WEBSITE, value);
return this;
}
public ArticleSelection publisherWebsiteLike(String... value) {
addLike(PublisherColumns.WEBSITE, value);
return this;
}
public ArticleSelection publisherWebsiteContains(String... value) {
addContains(PublisherColumns.WEBSITE, value);
return this;
}
public ArticleSelection publisherWebsiteStartsWith(String... value) {
addStartsWith(PublisherColumns.WEBSITE, value);
return this;
}
public ArticleSelection publisherWebsiteEndsWith(String... value) {
addEndsWith(PublisherColumns.WEBSITE, value);
return this;
}
public ArticleSelection publisherName(String... value) {
addEquals(PublisherColumns.NAME, value);
return this;
}
public ArticleSelection publisherNameNot(String... value) {
addNotEquals(PublisherColumns.NAME, value);
return this;
}
public ArticleSelection publisherNameLike(String... value) {
addLike(PublisherColumns.NAME, value);
return this;
}
public ArticleSelection publisherNameContains(String... value) {
addContains(PublisherColumns.NAME, value);
return this;
}
public ArticleSelection publisherNameStartsWith(String... value) {
addStartsWith(PublisherColumns.NAME, value);
return this;
}
public ArticleSelection publisherNameEndsWith(String... value) {
addEndsWith(PublisherColumns.NAME, value);
return this;
}
public ArticleSelection publisherCountry(String... value) {
addEquals(PublisherColumns.COUNTRY, value);
return this;
}
public ArticleSelection publisherCountryNot(String... value) {
addNotEquals(PublisherColumns.COUNTRY, value);
return this;
}
public ArticleSelection publisherCountryLike(String... value) {
addLike(PublisherColumns.COUNTRY, value);
return this;
}
public ArticleSelection publisherCountryContains(String... value) {
addContains(PublisherColumns.COUNTRY, value);
return this;
}
public ArticleSelection publisherCountryStartsWith(String... value) {
addStartsWith(PublisherColumns.COUNTRY, value);
return this;
}
public ArticleSelection publisherCountryEndsWith(String... value) {
addEndsWith(PublisherColumns.COUNTRY, value);
return this;
}
public ArticleSelection publisherTagLine(String... value) {
addEquals(PublisherColumns.TAG_LINE, value);
return this;
}
public ArticleSelection publisherTagLineNot(String... value) {
addNotEquals(PublisherColumns.TAG_LINE, value);
return this;
}
public ArticleSelection publisherTagLineLike(String... value) {
addLike(PublisherColumns.TAG_LINE, value);
return this;
}
public ArticleSelection publisherTagLineContains(String... value) {
addContains(PublisherColumns.TAG_LINE, value);
return this;
}
public ArticleSelection publisherTagLineStartsWith(String... value) {
addStartsWith(PublisherColumns.TAG_LINE, value);
return this;
}
public ArticleSelection publisherTagLineEndsWith(String... value) {
addEndsWith(PublisherColumns.TAG_LINE, value);
return this;
}
public ArticleSelection publisherFollowing(boolean value) {
addEquals(PublisherColumns.FOLLOWING, toObjectArray(value));
return this;
}
public ArticleSelection publisherOrder(Integer... value) {
addEquals(PublisherColumns.ORDER, value);
return this;
}
public ArticleSelection publisherOrderNot(Integer... value) {
addNotEquals(PublisherColumns.ORDER, value);
return this;
}
public ArticleSelection publisherOrderGt(int value) {
addGreaterThan(PublisherColumns.ORDER, value);
return this;
}
public ArticleSelection publisherOrderGtEq(int value) {
addGreaterThanOrEquals(PublisherColumns.ORDER, value);
return this;
}
public ArticleSelection publisherOrderLt(int value) {
addLessThan(PublisherColumns.ORDER, value);
return this;
}
public ArticleSelection publisherOrderLtEq(int value) {
addLessThanOrEquals(PublisherColumns.ORDER, value);
return this;
}
}
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "io.aggreg.app"
minSdkVersion 9
targetSdkVersion 22
versionCode 4
versionName "1.3.1"
resValue "bool", "ga_dry_run", "true"
}
signingConfigs {
release {
storeFile file("../keystore/aggregiokeystore.jks")
storePassword "<PASSWORD>"
keyAlias "Midas"
keyPassword "sadim0779685241"
}
}
productFlavors {
// kenya {
// applicationId "io.aggreg.app.kenya"
// resValue "string", "app_name", "Aggregio KE News"
// resValue "string", "app_version", "Version 1.1"
// resValue "string", "app_country", "Kenya"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.kenya"
// resValue "string", "analytics_tracker_id", "UA-63988121-3"
// resValue "string", "feedback_api_key", "<KEY>"
// resValue "string", "facebook_placement_id", "1615604058689016_1619135521669203"
//
// }
// uganda {
// applicationId "io.aggreg.app.uganda"
// resValue "string", "app_name", "Aggregio UG News"
// resValue "string", "app_version", "Version 1.1"
// resValue "string", "app_country", "Uganda"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.uganda"
// resValue "string", "analytics_tracker_id", "UA-63988121-4"
// resValue "string", "feedback_api_key", "AF-DAFBA7E454D4-01"
// resValue "string", "facebook_placement_id", "1621484961451837_1621525618114438"
// }
// tanzania {
// applicationId "io.aggreg.app.tanzania"
// resValue "string", "app_name", "Aggregio TZ"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Tanzania"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.tanzania"
// }
nigeria {
applicationId "io.aggreg.app.nigeria"
resValue "string", "app_name", "Aggregio NG News"
resValue "string", "app_version", "Version 1.3.1"
resValue "string", "app_country", "Nigeria"
resValue "string", "authorities", applicationId + '.provider'
resValue "string", "account_type", "io.aggreg.nigeria"
resValue "string", "analytics_tracker_id", "UA-63988121-5"
resValue "string", "feedback_api_key", "<KEY>"
resValue "string", "facebook_placement_id", "1621484961451837_1621525618114438"
}
// southafrica {
// applicationId "io.aggreg.app.southafrica"
// resValue "string", "app_name", "Aggregio ZA"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "South Africa"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.southafrica"
// }
// ghana {
// applicationId "io.aggreg.app.ghana"
// resValue "string", "app_name", "Aggregio GH"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Ghana"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.ghana"
// }
// rwanda {
// applicationId "io.aggreg.app.rwanda"
// resValue "string", "app_name", "Aggregio RW"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Rwanda"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.rwanda"
// }
// malawi {
// applicationId "io.aggreg.app.malawi"
// resValue "string", "app_name", "<NAME>"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Malawi"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.malawi"
// }
// zambia {
// applicationId "io.aggreg.app.zambia"
// resValue "string", "app_name", "<NAME>"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Zambia"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.zambia"
// }
// zimbabwe {
// applicationId "io.aggreg.app.zimbabwe"
// resValue "string", "app_name", "<NAME>"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Zimbabwe"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.zimbabwe"
// }
// swaziland {
// applicationId "io.aggreg.app.swaziland"
// resValue "string", "app_name", "<NAME>"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Swaziland"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.swaziland"
// }
// lesotho {
// applicationId "io.aggreg.app.lesotho"
// resValue "string", "app_name", "<NAME>"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Lesotho"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.lesotho"
// }
// southsudan {
// applicationId "io.aggreg.app.southsudan"
// resValue "string", "app_name", "<NAME>"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "SouthSudan"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.southsudan"
// }
// botswana {
// applicationId "io.aggreg.app.botswana"
// resValue "string", "app_name", "Aggregio Botswana"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Botswana"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.botswana"
// }
// somalia {
// applicationId "io.aggreg.app.somalia"
// resValue "string", "app_name", "Aggregio Somalia"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Somalia"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.somalia"
// }
// namibia {
// applicationId "io.aggreg.app.namibia"
// resValue "string", "app_name", "Aggregio Namibia"
// resValue "string", "app_version", "Version 1.0-BETA"
// resValue "string", "app_country", "Namibia"
// resValue "string", "authorities", applicationId + '.provider'
// resValue "string", "account_type", "io.aggreg.namibia"
// }
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'proguard-fresco.pro', 'proguard-google-api-client.pro'
signingConfig signingConfigs.release
resValue "bool", "ga_dry_run", "false"
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile files('libs/feedback_v6.jar')
compile([group: 'com.appspot.aggregio_web_service', name: 'aggregio', version: 'v1.0-1.20.0-SNAPSHOT'])
compile ([group: 'com.google.api-client', name: 'google-api-client-android', version: '1.20.0'])
compile ([group: 'com.google.api-client', name: 'google-api-client-gson', version: '1.20.0'])
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:cardview-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.github.curioustechizen.android-ago:library:1.2.0'
compile 'org.apache.commons:commons-lang3:3.0'
compile 'com.github.paolorotolo:appintro:3.1.0'
compile 'com.github.codechimp-org.apprater:library:1.0.29'
compile 'de.psdev.licensesdialog:licensesdialog:1.7.0'
compile 'com.android.support:support-v4:22.2.0'
compile 'com.google.android.gms:play-services-analytics:7.5.0'
compile 'com.google.android.gms:play-services-gcm:7.5.0'
compile 'com.github.castorflex.smoothprogressbar:library:1.1.0'
compile 'com.android.support:support-v4:22.2.0'
compile files('libs/AudienceNetwork.jar')
compile 'com.facebook.fresco:fresco:0.6.0'
}
<file_sep>package io.aggreg.app.provider.article;
import java.util.Date;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.aggreg.app.provider.base.AbstractCursor;
import io.aggreg.app.provider.category.*;
import io.aggreg.app.provider.publisher.*;
/**
* Cursor wrapper for the {@code article} table.
*/
public class ArticleCursor extends AbstractCursor implements ArticleModel {
public ArticleCursor(Cursor cursor) {
super(cursor);
}
/**
* Primary key.
*/
public long getId() {
Long res = getLongOrNull(ArticleColumns._ID);
if (res == null)
throw new NullPointerException("The value of '_id' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code title} value.
* Cannot be {@code null}.
*/
@NonNull
public String getTitle() {
String res = getStringOrNull(ArticleColumns.TITLE);
if (res == null)
throw new NullPointerException("The value of 'title' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code link} value.
* Cannot be {@code null}.
*/
@NonNull
public String getLink() {
String res = getStringOrNull(ArticleColumns.LINK);
if (res == null)
throw new NullPointerException("The value of 'link' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code image} value.
* Can be {@code null}.
*/
@Nullable
public String getImage() {
String res = getStringOrNull(ArticleColumns.IMAGE);
return res;
}
/**
* Get the {@code pub_date} value.
* Can be {@code null}.
*/
@Nullable
public Date getPubDate() {
Date res = getDateOrNull(ArticleColumns.PUB_DATE);
return res;
}
/**
* Get the {@code text} value.
* Can be {@code null}.
*/
@Nullable
public String getText() {
String res = getStringOrNull(ArticleColumns.TEXT);
return res;
}
/**
* Get the {@code book_marked} value.
* Can be {@code null}.
*/
@Nullable
public Boolean getBookMarked() {
Boolean res = getBooleanOrNull(ArticleColumns.BOOK_MARKED);
return res;
}
/**
* Get the {@code is_read} value.
* Can be {@code null}.
*/
@Nullable
public Boolean getIsRead() {
Boolean res = getBooleanOrNull(ArticleColumns.IS_READ);
return res;
}
/**
* Get the {@code category_id} value.
*/
public long getCategoryId() {
Long res = getLongOrNull(ArticleColumns.CATEGORY_ID);
if (res == null)
throw new NullPointerException("The value of 'category_id' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code name} value.
* Can be {@code null}.
*/
@Nullable
public String getCategoryName() {
String res = getStringOrNull(CategoryColumns.NAME);
return res;
}
/**
* Get the {@code image_url} value.
* Can be {@code null}.
*/
@Nullable
public String getCategoryImageUrl() {
String res = getStringOrNull(CategoryColumns.IMAGE_URL);
return res;
}
/**
* Get the {@code order} value.
* Can be {@code null}.
*/
@Nullable
public Integer getCategoryOrder() {
Integer res = getIntegerOrNull(CategoryColumns.ORDER);
return res;
}
/**
* Get the {@code publisher_id} value.
*/
public long getPublisherId() {
Long res = getLongOrNull(ArticleColumns.PUBLISHER_ID);
if (res == null)
throw new NullPointerException("The value of 'publisher_id' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code image_url} value.
* Can be {@code null}.
*/
@Nullable
public String getPublisherImageUrl() {
String res = getStringOrNull(PublisherColumns.IMAGE_URL);
return res;
}
/**
* Get the {@code website} value.
* Can be {@code null}.
*/
@Nullable
public String getPublisherWebsite() {
String res = getStringOrNull(PublisherColumns.WEBSITE);
return res;
}
/**
* Get the {@code name} value.
* Can be {@code null}.
*/
@Nullable
public String getPublisherName() {
String res = getStringOrNull(PublisherColumns.NAME);
return res;
}
/**
* Get the {@code country} value.
* Can be {@code null}.
*/
@Nullable
public String getPublisherCountry() {
String res = getStringOrNull(PublisherColumns.COUNTRY);
return res;
}
/**
* Get the {@code tag_line} value.
* Can be {@code null}.
*/
@Nullable
public String getPublisherTagLine() {
String res = getStringOrNull(PublisherColumns.TAG_LINE);
return res;
}
/**
* Get the {@code following} value.
*/
public boolean getPublisherFollowing() {
Boolean res = getBooleanOrNull(PublisherColumns.FOLLOWING);
if (res == null)
throw new NullPointerException("The value of 'following' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code order} value.
* Can be {@code null}.
*/
@Nullable
public Integer getPublisherOrder() {
Integer res = getIntegerOrNull(PublisherColumns.ORDER);
return res;
}
}
<file_sep>package io.aggreg.app.sync;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.Date;
import io.aggreg.app.R;
import io.aggreg.app.provider.article.ArticleSelection;
import io.aggreg.app.utils.References;
/**
* Created by Timo on 6/29/15.
*/
public class ArticleDeleteService extends IntentService{
private String LOG_TAG = ArticleDeleteService.class.getSimpleName();
public ArticleDeleteService(String name) {
super(name);
}
public ArticleDeleteService(){
super(ArticleDeleteService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String deleteDaysString = prefs.getString(getApplicationContext().getString(R.string.pref_key_delete_stale_articles), "14");
Log.d(LOG_TAG, "article delete service started!");
Integer deleteDays = Integer.valueOf(deleteDaysString);
if(deleteDays != -1) {
ArticleSelection articleSelection = new ArticleSelection();
long DAY_IN_MS = 1000 * 60 * 60 * 24;
articleSelection.pubDateBeforeEq(new Date(System.currentTimeMillis() - (deleteDays * DAY_IN_MS)));
articleSelection.delete(getContentResolver());
Log.d(LOG_TAG, "articles deleting");
}
}
}
<file_sep>package io.aggreg.app.provider.publisher;
import java.util.Date;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.aggreg.app.provider.base.AbstractCursor;
/**
* Cursor wrapper for the {@code publisher} table.
*/
public class PublisherCursor extends AbstractCursor implements PublisherModel {
public PublisherCursor(Cursor cursor) {
super(cursor);
}
/**
* Primary key.
*/
public long getId() {
Long res = getLongOrNull(PublisherColumns._ID);
if (res == null)
throw new NullPointerException("The value of '_id' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code image_url} value.
* Can be {@code null}.
*/
@Nullable
public String getImageUrl() {
String res = getStringOrNull(PublisherColumns.IMAGE_URL);
return res;
}
/**
* Get the {@code website} value.
* Can be {@code null}.
*/
@Nullable
public String getWebsite() {
String res = getStringOrNull(PublisherColumns.WEBSITE);
return res;
}
/**
* Get the {@code name} value.
* Can be {@code null}.
*/
@Nullable
public String getName() {
String res = getStringOrNull(PublisherColumns.NAME);
return res;
}
/**
* Get the {@code country} value.
* Can be {@code null}.
*/
@Nullable
public String getCountry() {
String res = getStringOrNull(PublisherColumns.COUNTRY);
return res;
}
/**
* Get the {@code tag_line} value.
* Can be {@code null}.
*/
@Nullable
public String getTagLine() {
String res = getStringOrNull(PublisherColumns.TAG_LINE);
return res;
}
/**
* Get the {@code following} value.
*/
public boolean getFollowing() {
Boolean res = getBooleanOrNull(PublisherColumns.FOLLOWING);
if (res == null)
throw new NullPointerException("The value of 'following' in the database was null, which is not allowed according to the model definition");
return res;
}
/**
* Get the {@code order} value.
* Can be {@code null}.
*/
@Nullable
public Integer getOrder() {
Integer res = getIntegerOrNull(PublisherColumns.ORDER);
return res;
}
}
<file_sep>package io.aggreg.app.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.InetAddress;
/**
* Created by Timo on 6/6/15.
*/
public class NetworkUtils {
private Context mContext;
private static final String LOG_TAG = NetworkUtils.class.getSimpleName();
public NetworkUtils(Context context) {
this.mContext = context;
}
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public boolean isWIFIAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
return true;
} else {
return false;
}
}
public boolean isInternetAvailable() {
Boolean isNetworkAvailable = isNetworkAvailable();
if(isNetworkAvailable) {
return isOnline();
}else {
Log.d(LOG_TAG, "network off");
return false;
}
}
private boolean isOnline() {
// Runtime runtime = Runtime.getRuntime();
// try {
//
// Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
// int exitValue = ipProcess.waitFor();
// return (exitValue == 0);
//
// } catch (IOException e) { e.printStackTrace(); }
// catch (InterruptedException e) { e.printStackTrace(); }
//
// return false;
try {
InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
Log.d(LOG_TAG, "ip address "+ipAddr);
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
<file_sep>package io.aggreg.app.provider.category;
import java.util.Date;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import io.aggreg.app.provider.base.AbstractSelection;
/**
* Selection for the {@code category} table.
*/
public class CategorySelection extends AbstractSelection<CategorySelection> {
@Override
protected Uri baseUri() {
return CategoryColumns.CONTENT_URI;
}
/**
* Query the given content resolver using this selection.
*
* @param contentResolver The content resolver to query.
* @param projection A list of which columns to return. Passing null will return all columns, which is inefficient.
* @param sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort
* order, which may be unordered.
* @return A {@code CategoryCursor} object, which is positioned before the first entry, or null.
*/
public CategoryCursor query(ContentResolver contentResolver, String[] projection, String sortOrder) {
Cursor cursor = contentResolver.query(uri(), projection, sel(), args(), sortOrder);
if (cursor == null) return null;
return new CategoryCursor(cursor);
}
/**
* Equivalent of calling {@code query(contentResolver, projection, null)}.
*/
public CategoryCursor query(ContentResolver contentResolver, String[] projection) {
return query(contentResolver, projection, null);
}
/**
* Equivalent of calling {@code query(contentResolver, projection, null, null)}.
*/
public CategoryCursor query(ContentResolver contentResolver) {
return query(contentResolver, null, null);
}
public CategorySelection id(long... value) {
addEquals("category." + CategoryColumns._ID, toObjectArray(value));
return this;
}
public CategorySelection name(String... value) {
addEquals(CategoryColumns.NAME, value);
return this;
}
public CategorySelection nameNot(String... value) {
addNotEquals(CategoryColumns.NAME, value);
return this;
}
public CategorySelection nameLike(String... value) {
addLike(CategoryColumns.NAME, value);
return this;
}
public CategorySelection nameContains(String... value) {
addContains(CategoryColumns.NAME, value);
return this;
}
public CategorySelection nameStartsWith(String... value) {
addStartsWith(CategoryColumns.NAME, value);
return this;
}
public CategorySelection nameEndsWith(String... value) {
addEndsWith(CategoryColumns.NAME, value);
return this;
}
public CategorySelection imageUrl(String... value) {
addEquals(CategoryColumns.IMAGE_URL, value);
return this;
}
public CategorySelection imageUrlNot(String... value) {
addNotEquals(CategoryColumns.IMAGE_URL, value);
return this;
}
public CategorySelection imageUrlLike(String... value) {
addLike(CategoryColumns.IMAGE_URL, value);
return this;
}
public CategorySelection imageUrlContains(String... value) {
addContains(CategoryColumns.IMAGE_URL, value);
return this;
}
public CategorySelection imageUrlStartsWith(String... value) {
addStartsWith(CategoryColumns.IMAGE_URL, value);
return this;
}
public CategorySelection imageUrlEndsWith(String... value) {
addEndsWith(CategoryColumns.IMAGE_URL, value);
return this;
}
public CategorySelection order(Integer... value) {
addEquals(CategoryColumns.ORDER, value);
return this;
}
public CategorySelection orderNot(Integer... value) {
addNotEquals(CategoryColumns.ORDER, value);
return this;
}
public CategorySelection orderGt(int value) {
addGreaterThan(CategoryColumns.ORDER, value);
return this;
}
public CategorySelection orderGtEq(int value) {
addGreaterThanOrEquals(CategoryColumns.ORDER, value);
return this;
}
public CategorySelection orderLt(int value) {
addLessThan(CategoryColumns.ORDER, value);
return this;
}
public CategorySelection orderLtEq(int value) {
addLessThanOrEquals(CategoryColumns.ORDER, value);
return this;
}
}
<file_sep>package io.aggreg.app.provider.article;
import android.net.Uri;
import android.provider.BaseColumns;
import io.aggreg.app.provider.AggregioProvider;
import io.aggreg.app.provider.article.ArticleColumns;
import io.aggreg.app.provider.articleimage.ArticleImageColumns;
import io.aggreg.app.provider.category.CategoryColumns;
import io.aggreg.app.provider.publisher.PublisherColumns;
import io.aggreg.app.provider.publishercategory.PublisherCategoryColumns;
/**
* Columns for the {@code article} table.
*/
public class ArticleColumns implements BaseColumns {
public static final String TABLE_NAME = "article";
public static final Uri CONTENT_URI = Uri.parse(AggregioProvider.CONTENT_URI_BASE + "/" + TABLE_NAME);
/**
* Primary key.
*/
public static final String _ID = BaseColumns._ID;
public static final String TITLE = "title";
public static final String LINK = "link";
public static final String IMAGE = "image";
public static final String PUB_DATE = "pub_date";
public static final String TEXT = "text";
public static final String BOOK_MARKED = "book_marked";
public static final String IS_READ = "is_read";
public static final String CATEGORY_ID = "category_id";
public static final String PUBLISHER_ID = "publisher_id";
public static final String DEFAULT_ORDER = TABLE_NAME + "." +_ID;
// @formatter:off
public static final String[] ALL_COLUMNS = new String[] {
_ID,
TITLE,
LINK,
IMAGE,
PUB_DATE,
TEXT,
BOOK_MARKED,
IS_READ,
CATEGORY_ID,
PUBLISHER_ID
};
// @formatter:on
public static boolean hasColumns(String[] projection) {
if (projection == null) return true;
for (String c : projection) {
if (c.equals(TITLE) || c.contains("." + TITLE)) return true;
if (c.equals(LINK) || c.contains("." + LINK)) return true;
if (c.equals(IMAGE) || c.contains("." + IMAGE)) return true;
if (c.equals(PUB_DATE) || c.contains("." + PUB_DATE)) return true;
if (c.equals(TEXT) || c.contains("." + TEXT)) return true;
if (c.equals(BOOK_MARKED) || c.contains("." + BOOK_MARKED)) return true;
if (c.equals(IS_READ) || c.contains("." + IS_READ)) return true;
if (c.equals(CATEGORY_ID) || c.contains("." + CATEGORY_ID)) return true;
if (c.equals(PUBLISHER_ID) || c.contains("." + PUBLISHER_ID)) return true;
}
return false;
}
public static final String PREFIX_CATEGORY = TABLE_NAME + "__" + CategoryColumns.TABLE_NAME;
public static final String PREFIX_PUBLISHER = TABLE_NAME + "__" + PublisherColumns.TABLE_NAME;
}
<file_sep>package io.aggreg.app.ui.adapter;
/**
* Created by Timo on 6/3/15.
*/
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.facebook.ads.MediaView;
import com.facebook.ads.NativeAd;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.curioustechizen.ago.RelativeTimeTextView;
import io.aggreg.app.R;
import io.aggreg.app.provider.article.ArticleColumns;
import io.aggreg.app.provider.article.ArticleContentValues;
import io.aggreg.app.provider.article.ArticleSelection;
import io.aggreg.app.ui.ArticleDetailActivity;
import io.aggreg.app.ui.MainActivity;
import io.aggreg.app.ui.fragment.ArticleDetailFragment;
import io.aggreg.app.utils.NetworkUtils;
import io.aggreg.app.utils.References;
public class ArticleListCursorAdapter extends CursorRecyclerViewAdapter {
private static final int ARTICLE_VIEW_TYPE = 0;
private static final int AD_VIEW_TYPE = 1;
private Context mContext;
private static String LOG_TAG = ArticleListCursorAdapter.class.getSimpleName();
private int imageWidth;
private boolean isTablet;
private boolean isTwoPane;
private boolean isBookmarks;
public ArticleListCursorAdapter(Context context, Cursor cursor, @Nullable Boolean isTwoPane, @Nullable Boolean isBookmarks) {
super(context, cursor);
this.mContext = context;
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
this.imageWidth = (int) (displayMetrics.widthPixels);
this.isTablet = mContext.getResources().getBoolean(R.bool.isTablet);
if (isTablet) {
int spanCount = mContext.getResources().getInteger(R.integer.span_count);
this.imageWidth = (int) ((displayMetrics.widthPixels) / spanCount);
}
if (isTwoPane != null) {
this.isTwoPane = isTwoPane;
} else {
this.isTwoPane = false;
}
if (isBookmarks != null) {
this.isBookmarks = isBookmarks;
} else {
this.isBookmarks = false;
}
}
@Override
public int getItemCount() {
int originalCount = super.getItemCount();
int adInterval = mContext.getResources().getInteger(R.integer.ad_interval_count);
int adViewCount = originalCount / adInterval;
return originalCount + adViewCount;
}
@Override
public int getItemViewType(int position) {
position = position + 1;
int adInterval = mContext.getResources().getInteger(R.integer.ad_interval_count);
if (position > 1 && position % adInterval == 0) {
return AD_VIEW_TYPE;
} else {
return ARTICLE_VIEW_TYPE;
}
}
public static class AdViewHolder extends RecyclerView.ViewHolder {
public CardView cardView;
public TextView adTitle;
public TextView adBody;
public MediaView adMedia;
public RatingBar adRatingBar;
public Button adCallToAction;
public AdViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cardview);
adTitle = (TextView) itemView.findViewById(R.id.nativeAdTitle);
adBody = (TextView) itemView.findViewById(R.id.nativeAdBody);
adMedia = (MediaView) itemView.findViewById(R.id.nativeAdMedia);
adCallToAction = (Button) itemView.findViewById(R.id.nativeAdCallToAction);
adRatingBar = (RatingBar) itemView.findViewById(R.id.nativeAdStarRating);
}
}
public static class ArticleViewHolder extends RecyclerView.ViewHolder {
public TextView articleTitle;
public TextView publisherName;
public RelativeTimeTextView timeAgo;
public SimpleDraweeView articleImage;
private CardView cardView;
private ImageView bookmarkIconView;
public ArticleViewHolder(View view) {
super(view);
articleTitle = (TextView) view.findViewById(R.id.article_item_title);
publisherName = (TextView) view.findViewById(R.id.article_item_publisher_name);
timeAgo = (RelativeTimeTextView) view.findViewById(R.id.article_item_time_ago);
articleImage = (SimpleDraweeView) view.findViewById(R.id.article_item_image);
cardView = (CardView) view.findViewById(R.id.cardview);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
View itemView;
if (viewType == ARTICLE_VIEW_TYPE) {
if (isTwoPane) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.article_item_mini, parent, false);
} else if (isTablet) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.article_item_grid, parent, false);
} else {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.article_item, parent, false);
}
ArticleViewHolder vh = new ArticleViewHolder(itemView);
return vh;
} else if (viewType == AD_VIEW_TYPE) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.ad_unit, parent, false);
AdViewHolder vh = new AdViewHolder(itemView);
return vh;
}
return null;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder1, final Cursor cursor) {
int viewType = viewHolder1.getItemViewType();
if (viewType == ARTICLE_VIEW_TYPE) {
final ArticleViewHolder viewHolder = (ArticleViewHolder) viewHolder1;
int adInterval = mContext.getResources().getInteger(R.integer.ad_interval_count);
int oldPosition = viewHolder.getLayoutPosition();
final int position = oldPosition - ((oldPosition + 1) / adInterval);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cursor.moveToPosition(position);
Intent i = new Intent(mContext, ArticleDetailActivity.class);
String imageUrl = cursor.getString(cursor.getColumnIndex(ArticleColumns.IMAGE));
boolean hasImage = false;
if (imageUrl != null) {
hasImage = true;
}
i.putExtra(References.ARG_KEY_ARTICLE_ID, cursor.getLong(cursor.getColumnIndex(ArticleColumns._ID)));
i.putExtra(References.ARG_KEY_CATEGORY_ID, cursor.getLong(cursor.getColumnIndex(ArticleColumns.CATEGORY_ID)));
i.putExtra(References.ARG_KEY_ARTICLE_LINK, cursor.getString(cursor.getColumnIndex(ArticleColumns.LINK)));
i.putExtra(References.ARG_KEY_ARTICLE_HAS_IMAGE, hasImage);
i.putExtra(References.ARG_KEY_CURSOR_POSITION, viewHolder.getLayoutPosition());
i.putExtra(References.ARG_KEY_IS_BOOKMARKS, isBookmarks);
if (isTwoPane) {
((AppCompatActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.article_detail_container, ArticleDetailFragment.newInstance(i.getExtras())).commit();
} else {
mContext.startActivity(i);
}
}
});
ArticleItem articleItem = ArticleItem.fromCursor(cursor);
viewHolder.articleTitle.setText(articleItem.getTitle());
if (cursor.getInt(cursor.getColumnIndex(ArticleColumns.IS_READ)) == 0) {
viewHolder.articleTitle.setTextColor(mContext.getResources().getColor(R.color.primary_text_default_material_light));
} else if (cursor.getInt(cursor.getColumnIndex(ArticleColumns.IS_READ)) == 1) {
viewHolder.articleTitle.setTextColor(mContext.getResources().getColor(R.color.secondary_text_default_material_light));
}
viewHolder.publisherName.setText(articleItem.getPublisherName());
viewHolder.timeAgo.setReferenceTime(articleItem.getTimeAgo());
if (articleItem.getImage() != null) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
Boolean shouldShowImageOnlyOnWifi = settings.getBoolean(mContext.getString(R.string.key_images_on_wifi_only), false);
Boolean isOnWifi = new NetworkUtils(mContext).isWIFIAvailable();
if (shouldShowImageOnlyOnWifi) {
if (isOnWifi) {
viewHolder.articleImage.setVisibility(View.VISIBLE);
Uri uri = Uri.parse(articleItem.getImage() + "=s" + imageWidth);
viewHolder.articleImage.setImageURI(uri);
} else {
viewHolder.articleImage.setVisibility(View.GONE);
}
} else {
viewHolder.articleImage.setVisibility(View.VISIBLE);
Uri uri = Uri.parse(articleItem.getImage() + "=s" + imageWidth);
viewHolder.articleImage.setImageURI(uri);
}
} else {
viewHolder.articleImage.setVisibility(View.GONE);
}
viewHolder.cardView.setPreventCornerOverlap(false);
} else if (viewType == AD_VIEW_TYPE) {
final AdViewHolder viewHolder = (AdViewHolder) viewHolder1;
try {
NativeAd nativeAd = ((MainActivity) mContext).getNativeAd();
viewHolder.adTitle.setText(nativeAd.getAdTitle());
viewHolder.adBody.setText(nativeAd.getAdBody());
viewHolder.adCallToAction.setText(nativeAd.getAdCallToAction());
viewHolder.adCallToAction.setVisibility(View.VISIBLE);
NativeAd.Image adCoverImage = nativeAd.getAdCoverImage();
int bannerWidth = adCoverImage.getWidth();
int bannerHeight = adCoverImage.getHeight();
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
viewHolder.adMedia.setLayoutParams(new LinearLayout.LayoutParams(
screenWidth,
Math.min((int) (((double) screenWidth / (double) bannerWidth) * bannerHeight), screenHeight / 3)
));
NativeAd.Rating rating = nativeAd.getAdStarRating();
if (rating != null) {
viewHolder.adRatingBar.setVisibility(View.VISIBLE);
viewHolder.adRatingBar.setNumStars((int) rating.getScale());
viewHolder.adRatingBar.setRating((float) rating.getValue());
} else {
viewHolder.adRatingBar.setVisibility(View.GONE);
}
viewHolder.adMedia.setNativeAd(nativeAd);
viewHolder.cardView.setVisibility(View.VISIBLE);
nativeAd.registerViewForInteraction(viewHolder.itemView);
} catch (Exception e) {
e.printStackTrace();
viewHolder.cardView.setVisibility(View.GONE);
}
}
}
}<file_sep>//package io.aggreg.app.gcm;
//
//import android.app.IntentService;
//import android.app.NotificationManager;
//import android.app.PendingIntent;
//import android.content.ContentResolver;
//import android.content.Context;
//import android.content.Intent;
//import android.media.RingtoneManager;
//import android.net.Uri;
//import android.os.Bundle;
//import android.os.Handler;
//import android.os.Looper;
//import android.support.v4.app.NotificationCompat;
//import android.support.v4.app.TaskStackBuilder;
//import android.util.Log;
//import android.widget.Toast;
//
//import com.google.android.gms.gcm.GoogleCloudMessaging;
//
//import java.util.logging.Level;
//import java.util.logging.Logger;
//
//import io.aggreg.app.R;
//import io.aggreg.app.provider.AggregioProvider;
//import io.aggreg.app.ui.ArticleDetailActivity;
//import io.aggreg.app.utils.AccountUtils;
//import io.aggreg.app.utils.References;
//
///**
// * Created by Timo on 12/22/14.
// */
//public class GcmIntentService extends IntentService {
//
// public static final int NOTIFICATION_ID = 1;
// private static final String TAG = GcmIntentService.class.getSimpleName();
//
// private NotificationManager mNotificationManager;
//
//
// public GcmIntentService() {
// super("GcmIntentService");
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// Bundle extras = intent.getExtras();
// GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// String messageType = gcm.getMessageType(intent);
//
// if (extras != null && !extras.isEmpty()) {
//
// if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Logger.getLogger("GCM_RECEIVED").log(Level.INFO, extras.toString());
//
// Log.d(TAG, "Request sync called via GCM");
// if(extras.containsKey(References.GCM_KEY_TYPE) && extras.getString(References.GCM_KEY_TYPE).equalsIgnoreCase(References.GCM_TYPE_NOTIFICATION)){
// extras.putLong(References.ARG_GCM_ID_KEY, Long.valueOf(extras.getString(References.ARG_GCM_ID_KEY)));
// sendNotification(extras);
// Log.d(TAG, "send notification called");
//
// }else if(extras.containsKey(References.GCM_KEY_TYPE) && extras.getString(References.GCM_KEY_TYPE).equalsIgnoreCase(References.GCM_TYPE_TICKLE)){
// extras.putLong(References.ARG_GCM_ID_KEY, Long.valueOf(extras.getString(References.ARG_GCM_ID_KEY)));
// ContentResolver.requestSync(new AccountUtils(getApplicationContext()).getSyncAccount(), AggregioProvider.AUTHORITY, extras);
// }
// }
// }
// GcmBroadcastReceiver.completeWakefulIntent(intent);
// }
//
// private void sendNotification(Bundle extras) {
// mNotificationManager = (NotificationManager)
// this.getSystemService(Context.NOTIFICATION_SERVICE);
// Intent resultIntent = new Intent(getApplicationContext(), ArticleDetailActivity.class);
// resultIntent.putExtra(References.ARG_KEY_ARTICLE_LINK, extras.getLong(References.ARG_KEY_ARTICLE_LINK));
// TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
// stackBuilder.addNextIntent(resultIntent);
// PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//
// NotificationCompat.Builder mBuilder =
// new NotificationCompat.Builder(getApplicationContext())
// .setSmallIcon(R.drawable.ic_launcher)
// .setContentTitle(extras.getString(References.ARG_KEY_NOTIFICATION_TITLE))
// .setStyle(new NotificationCompat.BigTextStyle()
// .bigText(extras.getString(References.ARG_KEY_NOTIFICATION_TITLE)))
// .setAutoCancel(true)
// .setSound(uri)
// .setContentText(extras.getString(References.ARG_KEY_NOTIFICATION_TITLE));
//
// mBuilder.setContentIntent(resultPendingIntent);
// mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
// }
//
//
// protected void showToast(final String message) {
// new Handler(Looper.getMainLooper()).post(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
// }
// });
// }
//}
<file_sep>package io.aggreg.app.provider.publisher;
import java.util.Date;
import android.content.ContentResolver;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.aggreg.app.provider.base.AbstractContentValues;
/**
* Content values wrapper for the {@code publisher} table.
*/
public class PublisherContentValues extends AbstractContentValues {
@Override
public Uri uri() {
return PublisherColumns.CONTENT_URI;
}
/**
* Update row(s) using the values stored by this object and the given selection.
*
* @param contentResolver The content resolver to use.
* @param where The selection to use (can be {@code null}).
*/
public int update(ContentResolver contentResolver, @Nullable PublisherSelection where) {
return contentResolver.update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args());
}
public PublisherContentValues putImageUrl(@Nullable String value) {
mContentValues.put(PublisherColumns.IMAGE_URL, value);
return this;
}
public PublisherContentValues putImageUrlNull() {
mContentValues.putNull(PublisherColumns.IMAGE_URL);
return this;
}
public PublisherContentValues putWebsite(@Nullable String value) {
mContentValues.put(PublisherColumns.WEBSITE, value);
return this;
}
public PublisherContentValues putWebsiteNull() {
mContentValues.putNull(PublisherColumns.WEBSITE);
return this;
}
public PublisherContentValues putName(@Nullable String value) {
mContentValues.put(PublisherColumns.NAME, value);
return this;
}
public PublisherContentValues putNameNull() {
mContentValues.putNull(PublisherColumns.NAME);
return this;
}
public PublisherContentValues putCountry(@Nullable String value) {
mContentValues.put(PublisherColumns.COUNTRY, value);
return this;
}
public PublisherContentValues putCountryNull() {
mContentValues.putNull(PublisherColumns.COUNTRY);
return this;
}
public PublisherContentValues putTagLine(@Nullable String value) {
mContentValues.put(PublisherColumns.TAG_LINE, value);
return this;
}
public PublisherContentValues putTagLineNull() {
mContentValues.putNull(PublisherColumns.TAG_LINE);
return this;
}
public PublisherContentValues putFollowing(boolean value) {
mContentValues.put(PublisherColumns.FOLLOWING, value);
return this;
}
public PublisherContentValues putOrder(@Nullable Integer value) {
mContentValues.put(PublisherColumns.ORDER, value);
return this;
}
public PublisherContentValues putOrderNull() {
mContentValues.putNull(PublisherColumns.ORDER);
return this;
}
}
<file_sep>package io.aggreg.app.provider.publisher;
import io.aggreg.app.provider.base.BaseModel;
import java.util.Date;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* Data model for the {@code publisher} table.
*/
public interface PublisherModel extends BaseModel {
/**
* Get the {@code image_url} value.
* Can be {@code null}.
*/
@Nullable
String getImageUrl();
/**
* Get the {@code website} value.
* Can be {@code null}.
*/
@Nullable
String getWebsite();
/**
* Get the {@code name} value.
* Can be {@code null}.
*/
@Nullable
String getName();
/**
* Get the {@code country} value.
* Can be {@code null}.
*/
@Nullable
String getCountry();
/**
* Get the {@code tag_line} value.
* Can be {@code null}.
*/
@Nullable
String getTagLine();
/**
* Get the {@code following} value.
*/
boolean getFollowing();
/**
* Get the {@code order} value.
* Can be {@code null}.
*/
@Nullable
Integer getOrder();
}
<file_sep>package io.aggreg.app.provider.publishercategory;
import android.net.Uri;
import android.provider.BaseColumns;
import io.aggreg.app.provider.AggregioProvider;
import io.aggreg.app.provider.article.ArticleColumns;
import io.aggreg.app.provider.articleimage.ArticleImageColumns;
import io.aggreg.app.provider.category.CategoryColumns;
import io.aggreg.app.provider.publisher.PublisherColumns;
import io.aggreg.app.provider.publishercategory.PublisherCategoryColumns;
/**
* Columns for the {@code publisher_category} table.
*/
public class PublisherCategoryColumns implements BaseColumns {
public static final String TABLE_NAME = "publisher_category";
public static final Uri CONTENT_URI = Uri.parse(AggregioProvider.CONTENT_URI_BASE + "/" + TABLE_NAME);
/**
* Primary key.
*/
public static final String _ID = BaseColumns._ID;
public static final String PUBLISHER_ID = "publisher_id";
public static final String CATEGORY_ID = "category_id";
public static final String DEFAULT_ORDER = TABLE_NAME + "." +_ID;
// @formatter:off
public static final String[] ALL_COLUMNS = new String[] {
_ID,
PUBLISHER_ID,
CATEGORY_ID
};
// @formatter:on
public static boolean hasColumns(String[] projection) {
if (projection == null) return true;
for (String c : projection) {
if (c.equals(PUBLISHER_ID) || c.contains("." + PUBLISHER_ID)) return true;
if (c.equals(CATEGORY_ID) || c.contains("." + CATEGORY_ID)) return true;
}
return false;
}
public static final String PREFIX_PUBLISHER = TABLE_NAME + "__" + PublisherColumns.TABLE_NAME;
public static final String PREFIX_CATEGORY = TABLE_NAME + "__" + CategoryColumns.TABLE_NAME;
}
<file_sep>package io.aggreg.app.ui.fragment;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import io.aggreg.app.R;
import io.aggreg.app.provider.publisher.PublisherColumns;
import io.aggreg.app.ui.adapter.SelectPublishersAdapter;
import io.aggreg.app.utils.References;
public class PublishersFragment extends Fragment implements LoaderManager.LoaderCallbacks{
private OnFragmentInteractionListener mListener;
private static String LOG_TAG = PublishersFragment.class.getSimpleName();
RecyclerView recyclerView;
private FloatingActionButton doneFab;
private Cursor mCursor;
View headerView;
private GridLayoutManager layoutManager;
private Parcelable mListState;
public static PublishersFragment newInstance() {
PublishersFragment publishersFragment = new PublishersFragment();
Bundle args = new Bundle();
publishersFragment.setArguments(args);
return publishersFragment;
}
public PublishersFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(References.PUBLISHER_LOADER, getArguments(), this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_publishers, container, false);
doneFab = (FloatingActionButton)rootView.findViewById(R.id.done_fab);
doneFab.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.ic_done_white_24dp));
doneFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.onFabClicked();
}
});
recyclerView = (RecyclerView)rootView.findViewById(android.R.id.list);
final int publisherSpanCount = getActivity().getResources().getInteger(R.integer.publisher_span_count);
layoutManager = new GridLayoutManager(getActivity(), publisherSpanCount, GridLayoutManager.VERTICAL, false);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return position == 0 ? publisherSpanCount : 1;
}
});
recyclerView.setLayoutManager(layoutManager);
headerView = inflater.inflate(R.layout.publisher_grid_header, null);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public Loader onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), PublisherColumns.CONTENT_URI, null, null, null, PublisherColumns.ORDER+" ASC");
}
@Override
public void onLoadFinished(Loader loader, Object data) {
if(data!=null) {
mCursor = (Cursor) data;
SelectPublishersAdapter adapter = new SelectPublishersAdapter(getActivity(), mCursor);
adapter.addHeader(headerView);
mListState = layoutManager.onSaveInstanceState();
recyclerView.setAdapter(adapter);
layoutManager.onRestoreInstanceState(mListState);
}
}
@Override
public void onLoaderReset(Loader loader) {
}
public interface OnFragmentInteractionListener {
void onFabClicked();
}
@Override
public void onResume() {
super.onResume();
if (recyclerView != null) {
if(mListState!=null) {
layoutManager.onRestoreInstanceState(mListState);
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(recyclerView != null) {
mListState = layoutManager.onSaveInstanceState();
outState.putParcelable(References.ARG_KEY_PARCEL, mListState);
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null) {
mListState = savedInstanceState.getParcelable(References.ARG_KEY_PARCEL);
}
}
}
<file_sep>package io.aggreg.app.provider.article;
import io.aggreg.app.provider.base.BaseModel;
import java.util.Date;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* Data model for the {@code article} table.
*/
public interface ArticleModel extends BaseModel {
/**
* Get the {@code title} value.
* Cannot be {@code null}.
*/
@NonNull
String getTitle();
/**
* Get the {@code link} value.
* Cannot be {@code null}.
*/
@NonNull
String getLink();
/**
* Get the {@code image} value.
* Can be {@code null}.
*/
@Nullable
String getImage();
/**
* Get the {@code pub_date} value.
* Can be {@code null}.
*/
@Nullable
Date getPubDate();
/**
* Get the {@code text} value.
* Can be {@code null}.
*/
@Nullable
String getText();
/**
* Get the {@code book_marked} value.
* Can be {@code null}.
*/
@Nullable
Boolean getBookMarked();
/**
* Get the {@code is_read} value.
* Can be {@code null}.
*/
@Nullable
Boolean getIsRead();
/**
* Get the {@code category_id} value.
*/
long getCategoryId();
/**
* Get the {@code publisher_id} value.
*/
long getPublisherId();
}
<file_sep>package io.aggreg.app.ui;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.view.Window;
import io.aggreg.app.R;
import io.aggreg.app.ui.fragment.ArticleDetailFragment;
import io.aggreg.app.ui.fragment.ArticlesFragment;
import io.aggreg.app.utils.References;
public class ArticleDetailActivity extends AppCompatActivity implements ArticleDetailFragment.OnFragmentInteractionListener, ArticlesFragment.OnFragmentInteractionListener{
Boolean isTablet;
Toolbar mainToolbar;
FloatingActionButton bookmarkFab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article_detail);
isTablet = getResources().getBoolean(R.bool.isTablet);
if(isTablet){
mainToolbar = (Toolbar)findViewById(R.id.main_toolbar);
mainToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
mainToolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mainToolbar.setSubtitle(getResources().getString(R.string.app_country));
bookmarkFab = (FloatingActionButton)findViewById(R.id.bookmark_fab);
if (savedInstanceState == null) {
Bundle articlesBundle = getIntent().getExtras();
articlesBundle.putBoolean(References.ARG_KEY_IS_TAB_TWO_PANE, true);
getSupportFragmentManager().beginTransaction()
.add(R.id.article_list_container, ArticlesFragment.newInstance(articlesBundle))
.add(R.id.article_detail_container, ArticleDetailFragment.newInstance(getIntent().getExtras()))
.commit();
}
}else {
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, ArticleDetailFragment.newInstance(getIntent().getExtras()))
.commit();
}
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void updateTitle(String title){
if(isTablet) {
if(mainToolbar != null) {
mainToolbar.setTitle(title);
}
}
}
@Override
public FloatingActionButton getBookmarkFab() {
return bookmarkFab;
}
@Override
public Boolean checkSyncStatus() {
return false;
}
}
<file_sep>package io.aggreg.app.ui.fragment;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import io.aggreg.app.R;
import io.aggreg.app.provider.article.ArticleColumns;
import io.aggreg.app.provider.article.ArticleSelection;
import io.aggreg.app.provider.publisher.PublisherColumns;
import io.aggreg.app.ui.adapter.ArticleListCursorAdapter;
import io.aggreg.app.utils.References;
public class ArticlesFragment extends Fragment implements LoaderManager.LoaderCallbacks{
private static String LOG_TAG = ArticlesFragment.class.getSimpleName();
private RecyclerView recyclerView;
private ViewSwitcher viewSwitcher;
private Boolean isTablet;
private Parcelable mListState;
private RecyclerView.LayoutManager layoutManager;
private TextView noArticlesMessage;
private OnFragmentInteractionListener mListener;
private Boolean switched;
ArticleListCursorAdapter adapter;
public ArticlesFragment() {
}
public static ArticlesFragment newInstance(Bundle bundle) {
ArticlesFragment fragment = new ArticlesFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.isTablet = getResources().getBoolean(R.bool.isTablet);
this.switched = false;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(References.ARTICLES_LOADER, getArguments(), this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_article_list, container, false);
recyclerView = (RecyclerView) view.findViewById(android.R.id.list);
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
if(getArguments().getBoolean(References.ARG_KEY_IS_TAB_TWO_PANE)){
layoutManager = new LinearLayoutManager(getActivity());
}
else if (isTablet) {
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(getActivity().getResources().getInteger(R.integer.span_count), StaggeredGridLayoutManager.VERTICAL);
staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
layoutManager = staggeredGridLayoutManager;
}else {
layoutManager = new LinearLayoutManager(getActivity());
}
recyclerView.setLayoutManager(layoutManager);
viewSwitcher = (ViewSwitcher)view.findViewById(R.id.article_list_view_switcher);
noArticlesMessage = (TextView)view.findViewById(R.id.text_view_no_article_message);
if(getArguments().getBoolean(References.ARG_KEY_IS_BOOKMARKS)){
noArticlesMessage.setText("You haven't yet bookmarked any articles!");
}else {
noArticlesMessage.setText("No articles to show! Hit the refresh button at the top to get the latest news");
}
adapter = new ArticleListCursorAdapter(getActivity(),
null, getArguments().getBoolean(References.ARG_KEY_IS_TAB_TWO_PANE, false),
getArguments().getBoolean(References.ARG_KEY_IS_BOOKMARKS, false));
recyclerView.setAdapter(adapter);
return view;
}
@Override
public Loader onCreateLoader(int id, Bundle args) {
String[] COLUMNS = {ArticleColumns._ID, ArticleColumns.IS_READ, ArticleColumns.TITLE, ArticleColumns.IMAGE, ArticleColumns.CATEGORY_ID,ArticleColumns.PUB_DATE, ArticleColumns.LINK, ArticleColumns.TEXT, PublisherColumns.NAME, PublisherColumns.IMAGE_URL, PublisherColumns.FOLLOWING};
ArticleSelection selection = new ArticleSelection();
if(getArguments().getBoolean(References.ARG_KEY_IS_BOOKMARKS)){
selection.bookMarked(true);
}else {
selection.categoryId(args.getLong(References.ARG_KEY_CATEGORY_ID));
selection.and();
selection.publisherFollowing(true);
}
return new CursorLoader(getActivity(), ArticleColumns.CONTENT_URI, COLUMNS, selection.sel(), selection.args(), ArticleColumns.TABLE_NAME+"."+ArticleColumns.PUB_DATE+" DESC");
}
@Override
public void onLoadFinished(Loader loader, Object data) {
//switching logic
Cursor c = (Cursor) data;
if(c!= null){
if(c.getCount() != 0){
recyclerView.setVisibility(View.VISIBLE);
noArticlesMessage.setVisibility(View.GONE);
if (switched==false) {
viewSwitcher.showNext();
switched = true;
}
}else {
if (getArguments().getBoolean(References.ARG_KEY_IS_BOOKMARKS, false)) {
if (switched==false) {
viewSwitcher.showNext();
switched = true;
}
recyclerView.setVisibility(View.GONE);
noArticlesMessage.setVisibility(View.VISIBLE);
}else {
if(mListener.checkSyncStatus()){
//leave progress
Log.d(LOG_TAG, "is syncing");
}else {
Log.d(LOG_TAG, "is not syncing");
if (switched==false) {
viewSwitcher.showNext();
switched = true;
}
recyclerView.setVisibility(View.GONE);
noArticlesMessage.setVisibility(View.VISIBLE);
}
}
}
}
if(getArguments().getBoolean(References.ARG_KEY_IS_TAB_TWO_PANE)){
mListState = ((LinearLayoutManager)layoutManager).onSaveInstanceState();
}
else if (isTablet) {
mListState = ((StaggeredGridLayoutManager)layoutManager).onSaveInstanceState();
}else {
mListState = ((LinearLayoutManager)layoutManager).onSaveInstanceState();
}
adapter.swapCursor((Cursor)data);
layoutManager.onRestoreInstanceState(mListState);
if(getArguments().getBoolean(References.ARG_KEY_IS_TAB_TWO_PANE)){
try {
recyclerView.scrollToPosition(getArguments().getInt(References.ARG_KEY_CURSOR_POSITION));
}catch (Exception e){
e.printStackTrace();
}
}
Log.d(LOG_TAG, "load finished");
}
@Override
public void onLoaderReset(Loader loader) {
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(recyclerView != null) {
if(getArguments().getBoolean(References.ARG_KEY_IS_TAB_TWO_PANE)){
mListState = ((LinearLayoutManager)layoutManager).onSaveInstanceState();
}
else if (isTablet) {
mListState = ((StaggeredGridLayoutManager)layoutManager).onSaveInstanceState();
}else {
mListState = ((LinearLayoutManager)layoutManager).onSaveInstanceState();
}
outState.putParcelable(References.ARG_KEY_PARCEL, mListState);
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null) {
mListState = savedInstanceState.getParcelable(References.ARG_KEY_PARCEL);
}
}
@Override
public void onResume() {
super.onResume();
if (recyclerView != null) {
if(mListState!=null) {
layoutManager.onRestoreInstanceState(mListState);
}
}
}
public interface OnFragmentInteractionListener {
Boolean checkSyncStatus();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
<file_sep>package io.aggreg.app.ui;
import android.accounts.Account;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.AdSettings;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdsManager;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.suredigit.inappfeedback.FeedbackDialog;
import org.codechimp.apprater.AppRater;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
import io.aggreg.app.R;
import io.aggreg.app.provider.category.CategoryColumns;
import io.aggreg.app.provider.publishercategory.PublisherCategoryColumns;
import io.aggreg.app.provider.publishercategory.PublisherCategorySelection;
import io.aggreg.app.sync.ArticleDeleteService;
import io.aggreg.app.sync.PeriodicalSyncService;
import io.aggreg.app.ui.fragment.ArticlesFragment;
import io.aggreg.app.utils.GeneralUtils;
import io.aggreg.app.utils.NetworkUtils;
import io.aggreg.app.utils.References;
public class MainActivity extends SyncActivity implements LoaderManager.LoaderCallbacks, ArticlesFragment.OnFragmentInteractionListener,
NativeAdsManager.Listener, AdListener {
private DrawerLayout mDrawerLayout;
private Cursor publisherCategoriesCursor;
private SectionsPagerAdapter mSectionsPagerAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private SmoothProgressBar progressBar;
private Tracker tracker;
private Boolean isSyncing;
private NativeAdsManager listNativeAdsManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
// Log.d(LOG_TAG, "device width is "+dpWidth+"dp");
// Log.d(LOG_TAG, "device height is "+dpHeight+"dp");
viewPager = (ViewPager) findViewById(R.id.viewpager);
progressBar = (SmoothProgressBar)findViewById(R.id.progress);
publisherCategoriesCursor = null;
getSupportLoaderManager().initLoader(References.PUBLISHER_LOADER, null, this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setTitle(getResources().getString(R.string.app_name_general));
ab.setSubtitle(getResources().getString(R.string.app_country));
ab.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
ab.setDisplayHomeAsUpEnabled(true);
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
TextView textView = (TextView)findViewById(R.id.nav_header_text);
textView.setText(getGreeting());
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
if (viewPager != null) {
viewPager.setAdapter(mSectionsPagerAdapter);
}
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
AppRater.app_launched(this);
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
tracker = analytics.newTracker(getString(R.string.analytics_tracker_id));
tracker.setScreenName("home screen");
setUpPeriodicSyncService();
setUpArticleDeleteService();
new CheckInternetTask().execute();
AdSettings.addTestDevice("73f8ce4641689c3367382c249e2e2979");
listNativeAdsManager = new NativeAdsManager(this, getResources().getString(R.string.facebook_placement_id), 10);
listNativeAdsManager.setListener(this);
listNativeAdsManager.loadAds();
}
@Override
protected Account getAccount() {
Account account = new GeneralUtils(getApplicationContext()).getSyncAccount();
return account;
}
@Override
protected void updateState(boolean isSynchronizing) {
isSyncing = isSynchronizing;
if(isSynchronizing){
showProgress();
}
else{
hideProgress();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_refresh:
refreshArticles();
return true;
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
if (menuItem.getItemId() == R.id.nav_manage_sources) {
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("manage sources nav action")
.build());
startActivity(new Intent(MainActivity.this, ManagePublishersActivity.class));
} else if (menuItem.getItemId() == R.id.nav_settings) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
} else if (menuItem.getItemId() == R.id.nav_bookmarks) {
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("bookmarks nav action")
.build());
startActivity(new Intent(MainActivity.this, BookmarksActivity.class));
} else if (menuItem.getItemId() == R.id.nav_help) {
FeedbackDialog feedBackDialog = new FeedbackDialog(MainActivity.this, getResources().getString(R.string.feedback_api_key));
feedBackDialog.show();
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("feedback action")
.build());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
@Override
public void onAdClicked(Ad ad) {
//Toast.makeText(MainActivity.this, "Ad Clicked", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdLoaded(Ad ad) { }
@Override
public void onAdsLoaded() {
}
public NativeAd getNativeAd(){
NativeAd ad = this.listNativeAdsManager.nextNativeAd();
ad.setAdListener(this);
return ad;
}
@Override
public void onAdError(AdError error) {
// Toast.makeText(this, "Native ads manager failed to load: " + error.getErrorMessage(),
// Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Ad ad, AdError error) {
// Toast.makeText(this, "Ad failed to load: " + error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
publisherCategoriesCursor.moveToPosition(position);
Bundle bundle = new Bundle();
bundle.putLong(References.ARG_KEY_CATEGORY_ID, (publisherCategoriesCursor.getLong(publisherCategoriesCursor.getColumnIndex(PublisherCategoryColumns.CATEGORY_ID))));
return ArticlesFragment.newInstance(bundle);
}
@Override
public int getCount() {
if(publisherCategoriesCursor!=null) {
return publisherCategoriesCursor.getCount();
}else {
return 0;
}
}
@Override
public CharSequence getPageTitle(int position) {
publisherCategoriesCursor.moveToPosition(position);
return publisherCategoriesCursor.getString(publisherCategoriesCursor.getColumnIndex(CategoryColumns.NAME));
}
}
@Override
public Loader onCreateLoader(int i, Bundle bundle) {
PublisherCategorySelection publisherCategorySelection = new PublisherCategorySelection();
publisherCategorySelection.publisherFollowing(true);
String COLUMNS[] = {"DISTINCT "+PublisherCategoryColumns.CATEGORY_ID, CategoryColumns.NAME, CategoryColumns.ORDER};
return new CursorLoader(this, PublisherCategoryColumns.CONTENT_URI, COLUMNS, null, null, CategoryColumns.ORDER);
}
@Override
public void onLoadFinished(Loader loader, Object data) {
Bundle savedState = new Bundle();
if(viewPager!=null) {
savedState.putParcelable(References.ARG_KEY_PARCEL, viewPager.onSaveInstanceState());
}
publisherCategoriesCursor = (Cursor) data;
mSectionsPagerAdapter.notifyDataSetChanged();
tabLayout.setupWithViewPager(viewPager);
onRestoreInstanceState(savedState);
}
@Override
public void onLoaderReset(Loader loader) {
}
public void refreshArticles(){
showProgress();
new GeneralUtils(this).SyncRefreshArticles();
}
public void hideProgress(){
progressBar.setVisibility(View.GONE);
}
public void showProgress() {
progressBar.setVisibility(View.VISIBLE);
new CheckInternetTask().execute();
}
private String getGreeting() {
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay >= 0 && timeOfDay < 12) {
return "Good Morning!";
} else if (timeOfDay >= 12 && timeOfDay < 16) {
return "Good Afternoon!";
} else if (timeOfDay >= 16 && timeOfDay < 21) {
return "Good Evening!";
} else if (timeOfDay >= 21 && timeOfDay < 24) {
return "Good Night!";
}
return "";
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Parcelable state = viewPager.onSaveInstanceState();
outState.putParcelable(References.ARG_KEY_PARCEL, state);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
try {
viewPager.onRestoreInstanceState(savedInstanceState.getParcelable(References.ARG_KEY_PARCEL));
super.onRestoreInstanceState(savedInstanceState);
}catch (Exception e){
e.printStackTrace();
}
}
private void setUpPeriodicSyncService(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String periodicSyncHoursString = settings.getString(getString(R.string.pref_key_refresh_interval), "720");
Integer periodicSyncHours = Integer.valueOf(periodicSyncHoursString);
//Log.d(LOG_TAG, "refresh interval is " + periodicSyncHoursString);
if(periodicSyncHours != -1) {
Intent periodicSyncIntent = new Intent(this, PeriodicalSyncService.class);
PendingIntent periodicSyncPendingIntent = PendingIntent.getService(this, References.REQUEST_CODE,
periodicSyncIntent, 0);
int periodicSyncAlarmType = AlarmManager.ELAPSED_REALTIME;
final long PERIODIC_SYNC_MILLIS = TimeUnit.HOURS.toMillis(periodicSyncHours);
AlarmManager periodicSyncAlarmManager = (AlarmManager)
this.getSystemService(ALARM_SERVICE);
periodicSyncAlarmManager.setRepeating(periodicSyncAlarmType, SystemClock.elapsedRealtime() + PERIODIC_SYNC_MILLIS,
PERIODIC_SYNC_MILLIS, periodicSyncPendingIntent);
}
}
private void setUpArticleDeleteService(){
Intent deleteArticlesIntent = new Intent(this, ArticleDeleteService.class);
PendingIntent deleteArticlesPendingIntent = PendingIntent.getService(this, References.REQUEST_CODE,
deleteArticlesIntent, 0);
int deleteArticlesAlarmType = AlarmManager.ELAPSED_REALTIME;
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final long MILLIS = TimeUnit.HOURS.toMillis(12);
AlarmManager alarmManager = (AlarmManager)
this.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(deleteArticlesAlarmType, SystemClock.elapsedRealtime() + MILLIS,
MILLIS, deleteArticlesPendingIntent);
}
class CheckInternetTask extends AsyncTask<String, String, Boolean>{
@Override
protected Boolean doInBackground(String... strings) {
return new NetworkUtils(MainActivity.this).isInternetAvailable();
}
@Override
protected void onPostExecute(Boolean aBoolean) {
if(aBoolean){
progressBar.setVisibility(View.VISIBLE);
}
else {
progressBar.setVisibility(View.GONE);
Snackbar.make(viewPager, "No internet connection", Snackbar.LENGTH_LONG).show();
}
}
}
@Override
public Boolean checkSyncStatus() {
if(isSyncing != null) {
return isSyncing;
}else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}
<file_sep>package io.aggreg.app.ui;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import com.facebook.drawee.backends.pipeline.Fresco;
import io.aggreg.app.R;
import io.aggreg.app.utils.GeneralUtils;
import io.aggreg.app.utils.References;
public class SplashscreenActivity extends AppCompatActivity {
protected int splashTime = 2000;
private final String LOG_TAG = SplashscreenActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(getApplicationContext());
setContentView(R.layout.activity_splashscreen);
ImageView logo = (ImageView)findViewById(R.id.text_logo);
Drawable normalDrawable = logo.getDrawable();
Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable);
DrawableCompat.setTint(wrapDrawable, Color.parseColor("#ffffff"));
logo.setImageDrawable(wrapDrawable);
SharedPreferences prefs = this.getSharedPreferences(References.KEY_PREFERENCES, MODE_PRIVATE);
Boolean isFirstTime = prefs.getBoolean(References.KEY_HAS_INTRO_BEEN_SHOWN, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Boolean shouldSyncFirstTime = settings.getBoolean(getString(R.string.pref_key_refresh_on_start), true);
if(shouldSyncFirstTime) {
new GeneralUtils(this).SyncRefreshArticles();
}
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(References.KEY_HAS_INTRO_BEEN_SHOWN, true);
editor.commit();
Log.d(LOG_TAG, "has intro been shown "+isFirstTime);
if (!isFirstTime) {
Thread splashTread = new Thread() {
@Override
public void run() {
try {
synchronized(this){
wait(splashTime);
}
} catch(InterruptedException e) {}
finally {
finish();
Intent i = new Intent();
i.setClass(SplashscreenActivity.this, IntroActivity.class);
startActivity(i);
}
}
};
splashTread.start();
}
else{
Intent i = new Intent();
i.setClass(SplashscreenActivity.this, MainActivity.class);
startActivity(i);
}
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
<file_sep>package io.aggreg.app.ui.adapter;
import android.database.Cursor;
import android.text.Html;
import io.aggreg.app.provider.article.ArticleColumns;
import io.aggreg.app.provider.publisher.PublisherColumns;
/**
* Created by Timo on 6/3/15.
*/
public class ArticleItem {
private String title;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String text;
private Long timeAgo;
private String publisherName;
private String image;
private String publisherLogo;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getTimeAgo() {
return timeAgo;
}
public void setTimeAgo(Long timeAgo) {
this.timeAgo = timeAgo;
}
public String getPublisherName() {
return publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPublisherLogo() {
return publisherLogo;
}
public void setPublisherLogo(String publisherLogo) {
this.publisherLogo = publisherLogo;
}
public static ArticleItem fromCursor(Cursor cursor) {
ArticleItem item = new ArticleItem();
item.setTitle(cursor.getString(cursor.getColumnIndex(ArticleColumns.TITLE)));
item.setText(cursor.getString(cursor.getColumnIndex(ArticleColumns.TEXT)));
item.setPublisherName(cursor.getString(cursor.getColumnIndex(PublisherColumns.NAME)));
item.setImage(cursor.getString(cursor.getColumnIndex(ArticleColumns.IMAGE)));
item.setPublisherLogo(cursor.getString(cursor.getColumnIndex(PublisherColumns.IMAGE_URL)));
item.setTimeAgo(cursor.getLong(cursor.getColumnIndex(ArticleColumns.PUB_DATE)));
return item;
}
}
<file_sep>package io.aggreg.app.ui.fragment;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.curioustechizen.ago.RelativeTimeTextView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import io.aggreg.app.R;
import io.aggreg.app.provider.AggregioProvider;
import io.aggreg.app.provider.article.ArticleColumns;
import io.aggreg.app.provider.article.ArticleContentValues;
import io.aggreg.app.provider.article.ArticleCursor;
import io.aggreg.app.provider.article.ArticleSelection;
import io.aggreg.app.provider.category.CategoryColumns;
import io.aggreg.app.provider.publisher.PublisherColumns;
import io.aggreg.app.ui.ArticleDetailActivity;
import io.aggreg.app.ui.SettingsActivity;
import io.aggreg.app.utils.NetworkUtils;
import io.aggreg.app.utils.References;
public class ArticleDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks, View.OnClickListener {
private TextView articleText;
private TextView articleTitle;
private TextView publisherName;
private RelativeTimeTextView timeAgo;
private SimpleDraweeView articleImage;
private SimpleDraweeView publisherLogo;
private FloatingActionButton bookmarkFab;
private static String LOG_TAG = ArticleDetailFragment.class.getSimpleName();
private Cursor articleCursor;
private Cursor relatedCursor;
private Button viewOnWeb;
private Button bookmarkButton;
Tracker tracker;
private SimpleDraweeView related1Image;
private SimpleDraweeView related2Image;
private SimpleDraweeView related3Image;
private TextView related1Title;
private TextView related2Title;
private TextView related3Title;
private CardView articleRelated1;
private CardView articleRelated2;
private CardView articleRelated3;
private RelativeTimeTextView timeAgoRelated1;
private RelativeTimeTextView timeAgoRelated2;
private RelativeTimeTextView timeAgoRelated3;
private ShareActionProvider mShareActionProvider;
private String mShareString;
private int imageWidth;
private ViewSwitcher viewSwitcher;
private boolean isTablet;
private ProgressBar progressBar;
private FrameLayout articleImageFrame;
private Boolean hasNextBeenShown;
private OnFragmentInteractionListener mListener;
public static ArticleDetailFragment newInstance(Bundle bundle) {
ArticleDetailFragment fragment = new ArticleDetailFragment();
fragment.setArguments(bundle);
fragment.setHasOptionsMenu(true);
return fragment;
}
public ArticleDetailFragment() {
this.hasNextBeenShown = false;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(References.ARTICLE_DETAIL_LOADER, getArguments(), this);
if(!isTablet) {
getLoaderManager().initLoader(References.ARTICLE_RELATED_LOADER, getArguments(), this);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.isTablet = getActivity().getResources().getBoolean(R.bool.isTablet);
DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
imageWidth = (int) (displayMetrics.widthPixels);
if(isTablet){
imageWidth = (int) (displayMetrics.widthPixels);
}
GoogleAnalytics analytics = GoogleAnalytics.getInstance(getActivity());
tracker = analytics.newTracker(getString(R.string.analytics_tracker_id));
tracker.setScreenName("detail screen");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
if(isTablet){
view = inflater.inflate(R.layout.fragment_article_detail, container, false);
}else {
if(getArguments().getBoolean(References.ARG_KEY_ARTICLE_HAS_IMAGE, false)){
view = inflater.inflate(R.layout.fragment_article_detail, container, false);
}else{
view = inflater.inflate(R.layout.no_image_fragment_article_detail, container, false);
}
}
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
if(toolbar != null){
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).setTitle(null);
try {
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}else {
}
articleText = (TextView) view.findViewById(R.id.article_detail_text);
publisherName = (TextView) view.findViewById(R.id.article_detail_publisher_name);
timeAgo = (RelativeTimeTextView) view.findViewById(R.id.article_detail_time_ago);
articleTitle = (TextView) view.findViewById(R.id.article_detail_title);
articleImage = (SimpleDraweeView) view.findViewById(R.id.article_detail_image);
publisherLogo = (SimpleDraweeView) view.findViewById(R.id.article_item_publisher_logo);
viewOnWeb = (Button) view.findViewById(R.id.btn_view_on_web);
if(isTablet) {
bookmarkFab = mListener.getBookmarkFab();
bookmarkButton = (Button) view.findViewById(R.id.btn_bookmark);
if (bookmarkButton != null) {
bookmarkButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggleBookmark();
}
});
}
}else {
bookmarkFab = (FloatingActionButton) view.findViewById(R.id.bookmark_fab);
}
if(bookmarkFab != null) {
bookmarkFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggleBookmark();
}
});
}
viewOnWeb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("open in browser button")
.build());
openInBrowser();
}
});
if(!isTablet) {
related1Title = (TextView) view.findViewById(R.id.article_related1_title);
related2Title = (TextView) view.findViewById(R.id.article_related2_title);
related3Title = (TextView) view.findViewById(R.id.article_related3_title);
related1Image = (SimpleDraweeView) view.findViewById(R.id.article_related1_image);
related2Image = (SimpleDraweeView) view.findViewById(R.id.article_related2_image);
related3Image = (SimpleDraweeView) view.findViewById(R.id.article_related3_image);
articleRelated1 = (CardView) view.findViewById(R.id.article_related1);
articleRelated2 = (CardView) view.findViewById(R.id.article_related2);
articleRelated3 = (CardView) view.findViewById(R.id.article_related3);
timeAgoRelated1 = (RelativeTimeTextView) view.findViewById(R.id.article_related1_timeago);
timeAgoRelated2 = (RelativeTimeTextView) view.findViewById(R.id.article_related2_timeago);
timeAgoRelated3 = (RelativeTimeTextView) view.findViewById(R.id.article_related3_timeago);
}
viewSwitcher = (ViewSwitcher)view.findViewById(R.id.detail_view_switcher);
progressBar = (ProgressBar)view.findViewById(R.id.progress);
if(isTablet){
Toolbar toolbar2 = (Toolbar)view.findViewById(R.id.toolbar2);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar2);
articleImageFrame = (FrameLayout)view.findViewById(R.id.article_detail_image_frame);
}
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public Loader onCreateLoader(int i, Bundle bundle) {
if (i == References.ARTICLE_DETAIL_LOADER) {
Uri contentUri = Uri.parse(AggregioProvider.CONTENT_URI_BASE + "/" + ArticleColumns.TABLE_NAME + "/" + bundle.getLong(References.ARG_KEY_ARTICLE_ID, 0));
return new CursorLoader(getActivity(), contentUri, null, null, null, null);
} else if (i == References.ARTICLE_RELATED_LOADER) {
ArticleSelection articleSelection = new ArticleSelection();
String[] COLUMNS = {ArticleColumns._ID, ArticleColumns.TITLE, ArticleColumns.IMAGE, ArticleColumns.CATEGORY_ID, ArticleColumns.PUB_DATE, ArticleColumns.LINK, PublisherColumns.NAME, PublisherColumns.IMAGE_URL};
articleSelection.categoryId(bundle.getLong(References.ARG_KEY_CATEGORY_ID));
articleSelection.and();
articleSelection.linkNot(bundle.getString(References.ARG_KEY_ARTICLE_LINK));
articleSelection.and();
articleSelection.publisherFollowing(true);
return new CursorLoader(getActivity(), ArticleColumns.CONTENT_URI, COLUMNS, articleSelection.sel(), articleSelection.args(), "RANDOM() LIMIT 3");
}
return null;
}
@Override
public void onLoadFinished(Loader loader, Object data) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
Boolean shouldShowImageOnlyOnWifi = settings.getBoolean(getActivity().getString(R.string.key_images_on_wifi_only), false);
Boolean isOnWifi = new NetworkUtils(getActivity()).isWIFIAvailable();
if (loader.getId() == References.ARTICLE_DETAIL_LOADER) {
articleCursor = (Cursor) data;
if (articleCursor.getCount() != 0) {
articleCursor.moveToFirst();
articleText.setText(Html.fromHtml(articleCursor.getString(articleCursor.getColumnIndex(ArticleColumns.TEXT))));
articleText.setMovementMethod(LinkMovementMethod.getInstance());
final String title = articleCursor.getString(articleCursor.getColumnIndex(ArticleColumns.TITLE));
articleTitle.setText(title);
if(isTablet) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(null);
String mainToolbarTitle;
if(getArguments().getBoolean(References.ARG_KEY_IS_BOOKMARKS)){
mainToolbarTitle = "Bookmarks";
}else {
mainToolbarTitle = articleCursor.getString(articleCursor.getColumnIndex(CategoryColumns.NAME));
}
mListener.updateTitle(mainToolbarTitle);
}
String imageUrl = articleCursor.getString(articleCursor.getColumnIndex(ArticleColumns.IMAGE));
if (imageUrl != null) {
if(shouldShowImageOnlyOnWifi){
if(isOnWifi){
Uri uri = Uri.parse(imageUrl + "=s" + imageWidth);
articleImage.setImageURI(uri);
}
else {
if(articleImageFrame != null){
articleImageFrame.setVisibility(View.GONE);
}
}
}
else {
Uri uri = Uri.parse(imageUrl + "=s" + imageWidth);
articleImage.setImageURI(uri);
}
} else {
if(articleImageFrame != null){
articleImageFrame.setVisibility(View.GONE);
}
}
String publisherImageUrl = articleCursor.getString(articleCursor.getColumnIndex(PublisherColumns.IMAGE_URL));
if(publisherImageUrl!=null) {
Uri uri = Uri.parse(articleCursor.getString(articleCursor.getColumnIndex(PublisherColumns.IMAGE_URL)));
publisherLogo.setImageURI(uri);
}
publisherName.setText(articleCursor.getString(articleCursor.getColumnIndex(PublisherColumns.NAME)));
timeAgo.setReferenceTime(articleCursor.getLong(articleCursor.getColumnIndex(ArticleColumns.PUB_DATE)));
int bookmarked = articleCursor.getInt(articleCursor.getColumnIndex(ArticleColumns.BOOK_MARKED));
Drawable drawable;
Drawable wrapDrawable;
if(bookmarked == 0){
drawable = getResources().getDrawable(R.drawable.ic_bookmark_outline_white_24dp);
wrapDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(wrapDrawable, Color.parseColor("#ffffff"));
}else {
drawable = getResources().getDrawable(R.drawable.ic_bookmark_black_24dp);
wrapDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(wrapDrawable, Color.parseColor("#ffffff"));
}
bookmarkFab.setImageDrawable(wrapDrawable);
mShareString = articleCursor.getString(articleCursor.getColumnIndex(ArticleColumns.TITLE))
+ " "
+ articleCursor.getString(articleCursor.getColumnIndex(ArticleColumns.LINK));
setShareIntent(createShareIntent());
int isRead = articleCursor.getInt(articleCursor.getColumnIndex(ArticleColumns.IS_READ));
if (isRead == 0) {
ArticleSelection articleSelection = new ArticleSelection();
articleSelection.link(articleCursor.getString(articleCursor.getColumnIndex(ArticleColumns.LINK)));
ArticleContentValues articleContentValues = new ArticleContentValues();
articleContentValues.putIsRead(true);
articleContentValues.update(getActivity().getContentResolver(), articleSelection);
}
}
if(!hasNextBeenShown) {
if (viewSwitcher.getNextView() != progressBar) {
hasNextBeenShown = true;
viewSwitcher.showNext();
}
}
} else if (loader.getId() == References.ARTICLE_RELATED_LOADER) {
relatedCursor = (Cursor) data;
if (relatedCursor != null) {
if (relatedCursor.getCount() != 0) {
relatedCursor.moveToFirst();
int i = 0;
CardView[] articleRelatedViews = {articleRelated1, articleRelated2, articleRelated3};
TextView[] relatedTextViews = {related1Title, related2Title, related3Title};
SimpleDraweeView[] relatedImageViews = {related1Image, related2Image, related3Image};
RelativeTimeTextView[] timeAgoRelatedViews = {timeAgoRelated1, timeAgoRelated2, timeAgoRelated3};
do {
articleRelatedViews[i].setVisibility(View.VISIBLE);
relatedTextViews[i].setText(relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.TITLE)));
String imageUrl = relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.IMAGE));
if (imageUrl != null) {
Uri uri = Uri.parse(imageUrl);
if(shouldShowImageOnlyOnWifi){
if(isOnWifi){
relatedImageViews[i].setVisibility(View.VISIBLE);
relatedImageViews[i].setImageURI(uri);
}else {
relatedImageViews[i].setVisibility(View.GONE);
}
}else {
relatedImageViews[i].setVisibility(View.VISIBLE);
relatedImageViews[i].setImageURI(uri);
}
}
else {
relatedImageViews[i].setVisibility(View.GONE);
}
articleRelatedViews[i].setOnClickListener(this);
articleRelatedViews[i].setPreventCornerOverlap(false);
timeAgoRelatedViews[i].setReferenceTime(relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns.PUB_DATE)));
i++;
if (i > 2) {
break;
}
} while (relatedCursor.moveToNext());
}
}
}
}
@Override
public void onLoaderReset(Loader loader) {
}
@Override
public void onClick(View view) {
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("related")
.build());
Intent i = new Intent(getActivity(), ArticleDetailActivity.class);
String imageUrl = null;
boolean hasImage = false;
switch (view.getId()) {
case R.id.article_related1:
relatedCursor.moveToPosition(0);
imageUrl = relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.IMAGE));
hasImage = false;
if(imageUrl != null){
hasImage = true;
}
i.putExtra(References.ARG_KEY_ARTICLE_LINK, relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.LINK)));
i.putExtra(References.ARG_KEY_ARTICLE_ID, relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns._ID)));
i.putExtra(References.ARG_KEY_CATEGORY_ID, relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns.CATEGORY_ID)));
i.putExtra(References.ARG_KEY_ARTICLE_HAS_IMAGE, hasImage);
getActivity().startActivity(i);
break;
case R.id.article_related2:
relatedCursor.moveToPosition(1);
imageUrl = relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.IMAGE));
hasImage = false;
if(imageUrl != null){
hasImage = true;
}
i.putExtra(References.ARG_KEY_ARTICLE_ID, relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns._ID)));
i.putExtra(References.ARG_KEY_ARTICLE_LINK, relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.LINK)));
i.putExtra(References.ARG_KEY_CATEGORY_ID, relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns.CATEGORY_ID)));
i.putExtra(References.ARG_KEY_ARTICLE_HAS_IMAGE, hasImage);
getActivity().startActivity(i);
break;
case R.id.article_related3:
relatedCursor.moveToPosition(2);
imageUrl = relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.IMAGE));
hasImage = false;
if(imageUrl != null){
hasImage = true;
}
i.putExtra(References.ARG_KEY_ARTICLE_ID, relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns._ID)));
i.putExtra(References.ARG_KEY_ARTICLE_LINK, relatedCursor.getString(relatedCursor.getColumnIndex(ArticleColumns.LINK)));
i.putExtra(References.ARG_KEY_CATEGORY_ID, relatedCursor.getLong(relatedCursor.getColumnIndex(ArticleColumns.CATEGORY_ID)));
i.putExtra(References.ARG_KEY_ARTICLE_HAS_IMAGE, hasImage);
getActivity().startActivity(i);
break;
default:
break;
}
}
public interface OnFragmentInteractionListener {
void updateTitle(String title);
FloatingActionButton getBookmarkFab();
}
private void toggleBookmark() {
ArticleSelection articleSelection = new ArticleSelection();
articleSelection.link(getArguments().getString(References.ARG_KEY_ARTICLE_LINK));
ArticleCursor articleCursor = articleSelection.query(getActivity().getContentResolver());
articleCursor.moveToFirst();
Boolean bookMarked = articleCursor.getBookMarked();
if (bookMarked == null) {
bookMark();
} else if (bookMarked) {
unBookMark();
} else {
bookMark();
}
}
private void bookMark() {
ArticleSelection articleSelection = new ArticleSelection();
articleSelection.link(getArguments().getString(References.ARG_KEY_ARTICLE_LINK));
ArticleContentValues articleContentValues = new ArticleContentValues();
articleContentValues.putBookMarked(true);
articleContentValues.update(getActivity().getContentResolver(), articleSelection);
Toast.makeText(getActivity(), "The article was bookmarked", Toast.LENGTH_SHORT).show();
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("bookmark")
.build());
}
private void unBookMark() {
ArticleSelection articleSelection = new ArticleSelection();
articleSelection.link(getArguments().getString(References.ARG_KEY_ARTICLE_LINK));
ArticleContentValues articleContentValues = new ArticleContentValues();
articleContentValues = new ArticleContentValues();
articleContentValues.putBookMarked(false);
articleContentValues.update(getActivity().getContentResolver(), articleSelection);
Toast.makeText(getActivity(), "The bookmark was removed", Toast.LENGTH_SHORT).show();
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("unbookmark")
.build());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_article_detail, menu);
MenuItem item = menu.findItem(R.id.action_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
setShareIntent(createShareIntent());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("settings action")
.build());
return true;
} else if (id == R.id.action_open_in_browser) {
openInBrowser();
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("open in browser action")
.build());
return true;
} else if (id == R.id.action_share) {
tracker.send(new HitBuilders.EventBuilder()
.setCategory("UX")
.setAction("click")
.setLabel("share action")
.build());
return true;
} else if (id == R.id.action_settings) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
else if(id == android.R.id.home){
getActivity().finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openInBrowser() {
String link = getArguments().getString(References.ARG_KEY_ARTICLE_LINK);
Uri uri = Uri.parse(link);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}else {
}
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mShareString);
return shareIntent;
}
@Override
public void onPause() {
super.onPause();
}
}
<file_sep># aggregio
News aggregator
Aggregio aggregates news from multiple sources in Uganda, Kenya and Nigeria.
Full documentation coming soon.
Its available on [Google Play](https://play.google.com/store/apps/details?id=io.aggreg.app.uganda)
<file_sep>package io.aggreg.app.provider.articleimage;
import java.util.Date;
import android.content.ContentResolver;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.aggreg.app.provider.base.AbstractContentValues;
/**
* Content values wrapper for the {@code article_image} table.
*/
public class ArticleImageContentValues extends AbstractContentValues {
@Override
public Uri uri() {
return ArticleImageColumns.CONTENT_URI;
}
/**
* Update row(s) using the values stored by this object and the given selection.
*
* @param contentResolver The content resolver to use.
* @param where The selection to use (can be {@code null}).
*/
public int update(ContentResolver contentResolver, @Nullable ArticleImageSelection where) {
return contentResolver.update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args());
}
public ArticleImageContentValues putImageUrl(@NonNull String value) {
if (value == null) throw new IllegalArgumentException("imageUrl must not be null");
mContentValues.put(ArticleImageColumns.IMAGE_URL, value);
return this;
}
public ArticleImageContentValues putArticleId(@Nullable Long value) {
mContentValues.put(ArticleImageColumns.ARTICLE_ID, value);
return this;
}
public ArticleImageContentValues putArticleIdNull() {
mContentValues.putNull(ArticleImageColumns.ARTICLE_ID);
return this;
}
}
| 5ceff2be11f6e1012f6df9fe0da18207f3d131fe | [
"Markdown",
"Java",
"Gradle"
] | 25 | Java | jokamjohn/aggregio | 6e8bd9f3fcc49773d84f7ea6d402525c2feeffb1 | 5f9a87860782cd340f6ffebaad7664329928c30d |
refs/heads/master | <file_sep><?php
echo 'ooops!! i did it again';
?> | bef3e736c025309a88677a06fb7a089bce6de629 | [
"PHP"
] | 1 | PHP | ralphskie/test1 | 2b71a649be71e06545519278ecc67d5f10f01329 | c7364e2cb63aec4e8845256dcbc3ac56434a095a |
refs/heads/master | <file_sep>type MessageNode = { [segment: string]: string[] };
type MessageWithFieldNode = {
[segment: string]: {
[field: string]: string | string[];
};
};
export type FieldComponent = {
[component: string]:
| string
| {
[sub: string]: string;
};
};
export type MessageWithFieldAndComponentNode = {
[segment: string]: {
[field: string]: string | FieldComponent[] | FieldComponent;
};
};
export class HL7v2Message {
private readonly fieldDelimiter: string;
private readonly componentDelimiter: string;
private readonly repeatingFieldDelimiter: string;
private readonly escapeCharacter: string;
private readonly subComponentDelimiter: string;
private readonly MSH_SEGMENT: string;
private readonly DATA_SEGMENTS: string[];
private _message: MessageWithFieldAndComponentNode;
private _raw: string;
get message() {
return this._message;
}
get raw() {
return this._raw;
}
constructor(raw: string) {
this._raw = raw;
this._message = {};
let segments = raw.split("\r");
let MSH_SEGMENT = segments.shift();
if (!MSH_SEGMENT) throw new Error("MSH Segment is Empty");
if (!MSH_SEGMENT.match(/^MSH/))
throw new Error(
"Invalid MSH Segment - Ensure that the first segment is a MSH Segment"
);
this.MSH_SEGMENT = MSH_SEGMENT;
this.DATA_SEGMENTS = segments;
this.fieldDelimiter = MSH_SEGMENT[3];
this.componentDelimiter = MSH_SEGMENT[4];
this.repeatingFieldDelimiter = MSH_SEGMENT[5];
this.escapeCharacter = MSH_SEGMENT[6];
this.subComponentDelimiter = MSH_SEGMENT[7];
this.parse();
}
private parse() {
const MSH_SEGMENT = this.parseMSH();
const parsedSegments = this.parseSegments(this.DATA_SEGMENTS);
//this.segmentsParsed = parsedSegments;
const parsedRepeatedField = this.parseRepeatingFields(parsedSegments);
//this.repeatedParsed = parsedRepeatedField;
const parsedComponents = this.parseComponents(parsedRepeatedField);
let parsedMessage: MessageWithFieldAndComponentNode = {
MSH: MSH_SEGMENT["MSH"],
...parsedComponents,
};
this._message = parsedMessage;
return this._message;
}
private parseMSH() {
const segments = this.parseSegments([this.MSH_SEGMENT]);
const parseRepeatedField = this.parseRepeatingFields(segments);
let components = this.parseComponents(parseRepeatedField);
let mshSegment: { MSH: { [field: number]: any } } = { MSH: {} };
// re-write keys field because the parsing will be incorrect;
for (let [key, field] of Object.entries(components["MSH"])) {
let fieldKey = parseInt(key, 10);
// the Encoding characters and Field separator don't map correctly with the parsing logic so we will
// manually correct those;
if (fieldKey < 2) continue;
// increment key value by 1 since HL7 fields are 1-based
mshSegment.MSH[fieldKey + 1] = field;
}
// set the first field in MSH to the field delimiter
mshSegment.MSH[1] = this.fieldDelimiter;
// this contains the escape characters
mshSegment.MSH[2] = this.MSH_SEGMENT.substring(4, 8);
return mshSegment;
}
private replaceEscape(str: string): string {
return str
.replace(`${this.escapeCharacter}F`, "|")
.replace(`${this.escapeCharacter}R`, "~")
.replace(`${this.escapeCharacter}S`, "^")
.replace(`${this.escapeCharacter}T`, "&")
.replace(`${this.escapeCharacter}E`, "\\");
}
/**
*
* @param segments Array of Segments
* @returns an object with headers as keys and values of fields
*/
private parseSegments(segments: string[]): MessageNode {
let obj: MessageNode = {};
for (let ind in segments) {
let segment = segments[ind];
let fields = segment
.split(this.fieldDelimiter)
// remove any line feed
.map((v) => v.replace(/\n/, ""));
let header = fields.shift();
if (!header) throw new Error("Empty Segment Header");
// some segments can appear multiple times so we append the Sequence Field
// PV1.1 when parsing into a JSON object
switch (header) {
case "AIG":
case "AIL":
case "AIP":
case "AIS":
case "AL1":
case "CM0":
case "CM1":
case "CM2":
case "DB1":
case "DG1":
case "DSP":
case "FT1":
case "GT1":
case "IN1":
case "IN3":
case "NK1":
case "NTE":
case "OBR":
case "OBX":
case "PID":
case "PR1":
case "PV1":
case "RGS":
case "RQD":
case "TXA":
case "UB1":
case "UB2": {
let seq: string = fields[0];
if (seq === "" || seq === undefined || seq === null) seq = "1";
// set based on sequence field or if omitted set to 1;
header = `${header}.${seq}`;
break;
}
default:
break;
}
// in the event the header already already exists will append [index] 1-based
if (obj[header]) {
let incrementingHeader = header;
let index = 1;
while (true) {
incrementingHeader = `${header}[${index}]`;
if (
!Object.entries(obj)
.map((v) => v[0])
.includes(incrementingHeader)
)
break;
index = index + 1;
}
header = incrementingHeader;
}
obj[header] = fields;
continue;
}
return obj;
}
/**
* Parses over messages that have repeating fields and
* @param messageNode The message node to parse over it's keys
* @returns
*/
private parseRepeatingFields(messageNode: MessageNode): MessageWithFieldNode {
let obj: MessageWithFieldNode = {};
fields: for (let [segment, fields] of Object.entries(messageNode)) {
field: for (let fieldInd in fields) {
let fieldIndex = parseInt(fieldInd, 10) + 1;
let field = fields[fieldInd];
if (!obj[segment]) {
obj[segment] = {};
}
let repeatedFields = field.split(this.repeatingFieldDelimiter);
if (repeatedFields.length <= 1) {
// No repeating fields
obj[segment][fieldIndex] = repeatedFields[0];
continue;
}
obj[segment][fieldIndex] = repeatedFields;
}
}
return obj;
}
private parseComponents(
fieldNode: MessageWithFieldNode
): MessageWithFieldAndComponentNode {
let componentNode: MessageWithFieldAndComponentNode = {};
// * iterate through the segments
segment: for (let [segment, fields] of Object.entries(fieldNode)) {
componentNode[segment] = {};
// * iterate through the fields
fields: for (let [outerInd, field] of Object.entries(fields)) {
if (typeof field !== "string") {
// * field is an array, which should be a repeated field
repeat: for (let [_ind, repeat] of Object.entries(field)) {
let components = repeat.split(this.componentDelimiter);
if (!Array.isArray(componentNode[segment][outerInd]))
componentNode[segment][outerInd] = [];
this.initializeFieldObject(componentNode, segment, outerInd);
if (components.length <= 1) {
// There is only 1 item so we create the string and index the property based on the repeated field
(
componentNode[segment][outerInd] as (FieldComponent | string)[]
).push(this.replaceEscape(components[0]));
continue;
}
let componentObject = this.toComplexComponentObject(components);
(componentNode[segment][outerInd] as FieldComponent[]).push(
componentObject
);
continue;
}
continue fields;
}
// field is a string
let components = field.split(this.componentDelimiter);
this.initializeFieldObject(componentNode, segment, outerInd);
if (components.length <= 1) {
componentNode[segment][outerInd] = this.replaceEscape(components[0]);
continue;
}
let componentObject = this.toComplexComponentObject(components);
componentNode[segment][outerInd] = componentObject;
}
}
return componentNode;
}
private initializeFieldObject(
componentNode: MessageWithFieldAndComponentNode,
segment: string,
outerInd: string
) {
if (!componentNode[segment][outerInd]) {
componentNode[segment][outerInd] = {};
}
}
private toComplexComponentObject(components: string[]) {
let componentObject: any = {};
components: for (let compInd in components) {
let index = parseInt(compInd, 10) + 1;
let component = components[compInd];
let subComponents = component.split(this.subComponentDelimiter);
if (subComponents.length <= 1) {
componentObject[index] = this.replaceEscape(subComponents[0]);
continue components;
}
subComponents: for (let subInd in subComponents) {
let subComponent = subComponents[subInd];
let subIndex = parseInt(subInd, 10) + 1;
if (!componentObject[index]) componentObject[index] = {};
componentObject[index][subIndex] = this.replaceEscape(subComponent);
continue subComponents;
}
}
return componentObject;
}
}
<file_sep>export type Node = {
[node: string]: string | Node;
};
export type Message = {
msg: Node;
raw: string;
};
| 19cc6b6d5695b4b4a9dcba186aea9e4ac970812b | [
"TypeScript"
] | 2 | TypeScript | campfhir/hl7-mapper | 0bae50ee18a79deca30f74ad5657c8aa2549def6 | 9852f65921663571003f6ea63202c2680fd24c63 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Direccion;
use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
class RedireccionController extends Controller
{
public function abrir ($short) {
$direccion = Direccion::select('url')->where('short', $short)->first();
return redirect($direccion->url);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class DireccionesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('direcciones')->insert([
'url' => 'https://github.com/FelipeUFRO15',
'short' => 'gthbf',
'id_usuario' => '1',
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Direccion;
use App\Http\Controllers\AuthController;
use DB;
class DireccionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
try {
$user = \JWTAuth::parseToken()->authenticate();
$direcciones = Direccion::where('id_usuario', $user->id)->get();
foreach ($direcciones as $dir) {
$dir->short = 'http://localhost:8000/'.$dir->short;
}
return $direcciones;
} catch (\Exception $e) {
\Log::info("Error {$e->getCode()}, {$e->getLine()}, {$e->getMessage()}");
return \Response::json('Error: $e', 500);
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request, AuthController $auth)
{
$user = \JWTAuth::parseToken()->authenticate();
$direc = new Direccion();
$direc->url = $request->url;
$direc->short = substr(md5(time().$direc->url), 0, 5);
$direc->id_usuario = $user->id;
$direc->save();
return ['created' => true, 'short' => 'http://localhost:8000/'. $direc->short];
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($short)
{
$url = '';
$user = \JWTAuth::parseToken()->authenticate();
$direcciones = Direccion::where('id_usuario', $user->id)->get();
foreach ($direcciones as $dir) {
if ($dir->short == $short) {
$url = $dir->url;
break;
}
}
return redirect($url);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$direccion = Direccion::find($id);
$direccion->update($request->all());
return ['update' => true];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Direccion::destroy($id);
return ['deleted' => true];
}
}
| ce7a182093630950e0b5849faec905f1d4855e95 | [
"PHP"
] | 3 | PHP | FelipeUFRO15/Taller-1-startup | f8f82bee2d77c4cebb8acca62d0c566a8d63c0c9 | 01341527b20e7714a1e12f98483222b64acfa1df |
refs/heads/master | <file_sep>package website.marcioheleno.twitterreativo.model;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Document( collection = "twitter")
public class Twitter {
@Id
@Generated
private String id;
@NotBlank
@Size(max = 140)
private String titulo;
@NonNull
private String texto;
@NotNull
private Date dataCriacao;
@NonNull
private String usuario;
@NonNull
private Boolean status;
}
| b1edd63cd79c154222b9630959d363341e1062df | [
"Java"
] | 1 | Java | marcio012/twitter-unifor-back | 52c60222107b7985d6357a3056dae0af912d8d76 | 066ff3b4ad6b8ff974ec5e3d4d17a9ec7926c1fa |
refs/heads/master | <repo_name>EnzoCodes/AuthTests<file_sep>/assets/javascript/loginPage.js
$(document).ready(function() {
console.log("JavaScript Up!");
var config = {
apiKey: "<KEY>",
authDomain: "imagewordmatch.firebaseapp.com",
databaseURL: "https://imagewordmatch.firebaseio.com",
projectId: "imagewordmatch",
storageBucket: "imagewordmatch.appspot.com",
messagingSenderId: "621229379920"
};
firebase.initializeApp(config);
var database = firebase.database();
var user = firebase.auth().currentUser;
// var provider = new firebase.auth.GoogleAuthProvider(); Logging NULL!
// console.log(provider); Logging NULL!
var displayName;
var email;
var emailVerified;
var photoURL;
var uid;
var providerData;
var userRef = firebase.database().ref('users/user');
var userScoreRef = firebase.database().ref('users/user/score');
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
uid = user.uid;
console.log(user);
console.log(user.displayName);
} else {
console.log("YUCKIE");
}
});
$('#addPoint').on('click' function() {
userScoreRef.transaction(function(currentScore) {
return currentScore + 1;
})
});
userRef.transaction(function(currentData) {
if (currentData === null) {
return { userIdentity: uid };
} else {
console.log('User #' + uid + 'already exists!');
return; // ABORT
}
});
});
// firebase.auth().onAuthStateChanged(function(user) {
// if (user) {
// // User is signed in.
// var displayName = user.displayName;
// var email = user.email;
// var emailVerified = user.emailVerified;
// var photoURL = user.photoURL;
// var isAnonymous = user.isAnonymous;
// var uid = user.uid;
// var providerData = user.providerData;
// // ...
// } else {
// console.log("UUUUUHHHHHHH")
// }
// });
// var userId = firebase.auth().currentUser.uid;
// var userIdentity = profile.uid;
// if (user != null) {
// user.providerData.forEach(function () {
// console.log("Sign-in provider: " + provider.providerId);
// console.log(" Provider-specific UID: " + provider.uid);
// console.log(" Name: " + provider.displayName);
// console.log(" Email: " + provider.email);
// console.log(" Photo URL: " + provider.photoURL);
// });
// };
// function scorePlus(uid, score, username) {
//
// var postData = {
// author: username,
// uid: uid,
// score: 0
// };
//
// // Get a new Key for new score?
// var moreScore = firebase.database().ref().child('score').push(1).key;
//
// var updates = {};
// updates['/score/' + newScoreKey] = scoreData;
//
// return firebase.database().ref().update(updates);
// }
// OR
// When score++, make post = true, to activate this codeblock!
// function toggleScore(scoreRef, uid) {
// scoreRef.transaction(function(post) {
// if (post) {
// if (post.score && post.score[uid]){
// post.scoreCount++;
// }
// post.stars[uid] = false;
// }
// });
// return post;
// }
// When a user registers for the game we want to save a 'score' object
// to their dedicated node in our database.
// To do this we:
// Create a node for each user under their account's uid property
// sice it's garunteed to be a unique identifier.
// While we will continue to save 'score' under a unique push ID
// we'll also capture this ID and save it as an attribute in a main
// 'SCORES' object...
// @Override
// public void onMatch_In_Guess_Array(View score)
// transction - update score
// firebase.database().ref('/users/' + userId)
//
// var userId = firebase.auth().currentUser.uid;
//
// fbUsers.child(userId + "/points")
//
// fbUsers = new Firebase("https://enzocodes.github.io/AuthTests/loggedIn.html");
//Users
//UID
//score.
// Sign out codeblock
//
// firebase.auth().signOut().then(function() {
// // Sign-out successful.
// }).catch(function(error) {
// // An error happened.
// });
| f129d1d8d04e9b221e830cafdbf9beb5897d63da | [
"JavaScript"
] | 1 | JavaScript | EnzoCodes/AuthTests | e2491e8f8231697c14a49e7c75ebc7d8a7e72643 | 209ade2ecd573c7eed2b80fd102b81163e5458b7 |
refs/heads/master | <repo_name>dtjm/webworker-demos<file_sep>/README.markdown
Web Worker Demos
================
Just messing around with Web Workers.
This one starts up a bunch of Web Workers who each emit the value of
`Math.random()`
The master page then takes the average of all values that it has ever
seen for each worker. I was hoping to see the value converge to 0.5.
<file_sep>/worker.js
// Do some work!
var id;
var go = false;
var work = function() {
postMessage({id: id, value: Math.random()});
if(go) {
setTimeout(work, 0);
}
}
onmessage = function(event){
var msg = event.data;
if(typeof msg.id !== "undefined") {
id = msg.id;
}
if(msg.start) {
go = true;
work();
} else if (msg.stop) {
go = false;
}
}
| fbbab696ddb831f9d728dfd2c15c5893e86f02f7 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dtjm/webworker-demos | 812ce155ce808bdf886f3eb5d5058294b895cfe8 | 16cab9cf27d65213f790c3f87de3706e4e6ac75a |
refs/heads/master | <file_sep>#!/bin/bash
#install ruby
curl -o rubystack-2.3.0-0-dev.run https://downloads.bitnami.com/files/stacks/rubystack/2.3.0-0/bitnami-rubystack-2.3.0-0-dev-linux-x64-installer.run
chmod +x rubystack-2.3.0-0-dev.run
./rubystack-2.3.0-0-dev.run --mode unattended --disable-components varnish,phpmyadmin,rvm
#install ruby dev headers
apt-get install -y g++ ruby-dev zlib1g-dev
#install wagon
gem install locomotivecms_wagon<file_sep>define(['jquery'], function(){
var dfd = $.Deferred();
window.handleClientLoad = function(){
gapi.client.setApiKey('<KEY>');
dfd.resolve(gapi);
}
$.getScript('https://apis.google.com/js/client.js?onload=handleClientLoad');
return dfd.promise();
});
<file_sep>window.jsHome = cfgUrl.replace(/config.js$/, "");
require.config({
baseUrl: jsHome,
paths: {
async: 'plugins/async',
googleapi: 'lib/googleapi',
propertyParser: 'plugins/propertyParser',
"bootstrap": "lib/bootstrap.min",
"skrollr": "lib/skrollr.min",
"jquery": ["//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min", "lib/jquery-1.11.1.min"],
"modernizr": "//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min",
"respond": "https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min"
},
shim: {
'bootstrap' : {
deps: ['jquery']
}
}
});
require(['bootstrap', 'modernizr', 'respond', window.page], function(){
});
<file_sep>Vagrant.require_version ">= 1.3.5"
Vagrant.configure(2) do |config|
config.vm.provider "virtualbox" do |v|
v.memory = 2048
v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate//vagrant", "1"]
end
config.vm.box = "ubuntu/vivid64"
config.vm.network "forwarded_port", guest: 3333, host: 3333
config.vm.network "forwarded_port", guest: 35729, host: 35729
config.vm.provision "file", source: "~/.gitconfig", destination: "~/.gitconfig"
config.vm.provision "shell", path: "./provision.sh"
end<file_sep>require(['jquery', 'skrollr', 'modules/gcal', 'bootstrap'], function( $, skrollr, GCal ) {
if(!(/Android|iPhone|iPad|iPod|BlackBerry|Windows Phone/i).test(navigator.userAgent || navigator.vendor || window.opera)){
skrollr.init({
forceHeight: false
});
}
$('[data-toggle="popover"]').popover();
var cal = new GCal("<EMAIL>");
cal.load().done(function(result) {
console.log('rss', result.items);
if(result.items.length > 0){
var entry;
var dt;
var formatted;
$.each(result.items, function(idx, e){
if(e.start.dateTime){
dt = new Date(e.start.dateTime)
formatted = dt.toLocaleString();
}
else if(e.start.date){
dt = new Date(e.start.date)
formatted = new Date(dt.getTime() + (dt.getTimezoneOffset() * 60000)).toLocaleDateString();
}
if(dt > new Date()){
entry = e;
return false;
}
});
if(!entry)
return;
var $title = $("<span>").text(entry.summary);
$("#nextEvent .evtTitle").append($title);
if(dt){
$("#nextEvent .evtDate").text(formatted);
}
$("#nextEvent .evtDesc").html(entry.description);
}
});
});
<file_sep>require(['jquery'], function($){
var otherText = "";
function cbOther_OnChange() {
if($("#cbOther").is(":checked")) {
$("#inputOther").removeAttr("disabled").attr("placeholder", "Tell us what you're interested in!").focus();
if(otherText && otherText != ""){
$("#inputOther").val(otherText);
otherText = "";
}
}
else{
$("#inputOther").attr("disabled", true).removeAttr("placeholder");
otherText = $("#inputOther").val();
$("#inputOther").val("");
}
}
$("#cbOther").change(cbOther_OnChange);
cbOther_OnChange();
});
| 96598e44815c471d60732ecc35597001edae8932 | [
"JavaScript",
"Ruby",
"Shell"
] | 6 | Shell | gburgett/reclaimed_site | 23f8ab9351067d28b71b65ea02a2b33f97149881 | a5ec95ed69849e8a1ede443f3fd178033c8bd6b4 |
refs/heads/master | <file_sep>#pragma once
// listbox 对话框
class listbox : public CDialogEx
{
DECLARE_DYNAMIC(listbox)
public:
listbox(CWnd* pParent = NULL); // 标准构造函数
virtual ~listbox();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_MFCAPPLICATION1_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
};
<file_sep>
// MFCApplication1Dlg.h : 头文件
//
#pragma once
#include "afxwin.h"
// CMFCApplication1Dlg 对话框
class CMFCApplication1Dlg : public CDHtmlDialog
{
// 构造
public:
CMFCApplication1Dlg(CWnd* pParent = NULL); // 标准构造函数
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_MFCAPPLICATION1_DIALOG, IDH = IDR_HTML_MFCAPPLICATION1_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
HRESULT OnButtonOK(IHTMLElement *pElement);
HRESULT OnButtonCancel(IHTMLElement *pElement);
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
DECLARE_DHTML_EVENT_MAP()
public:
afx_msg void OnLbnSelchangeList1();
afx_msg void OnDropFiles(HDROP hDropInfo);
CListBox listbox;
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton2();
CListBox listbox2;
afx_msg void OnLbnSelchangeList2();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnBnClickedButton3();
afx_msg void OnBnClickedButton4();
afx_msg void OnBnClickedButton5();
};
<file_sep>
// MFCApplication1Dlg.cpp : 实现文件
//
#include "stdafx.h"
#include "MFCApplication1.h"
#include "MFCApplication1Dlg.h"
#include "afxdialogex.h"
#include "md5.h"
//#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCApplication1Dlg 对话框
BEGIN_DHTML_EVENT_MAP(CMFCApplication1Dlg)
DHTML_EVENT_ONCLICK(_T("ButtonOK"), OnButtonOK)
DHTML_EVENT_ONCLICK(_T("ButtonCancel"), OnButtonCancel)
END_DHTML_EVENT_MAP()
CMFCApplication1Dlg::CMFCApplication1Dlg(CWnd* pParent /*=NULL*/)
: CDHtmlDialog(IDD_MFCAPPLICATION1_DIALOG, IDR_HTML_MFCAPPLICATION1_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCApplication1Dlg::DoDataExchange(CDataExchange* pDX)
{
CDHtmlDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, listbox);
DDX_Control(pDX, IDC_LIST2, listbox2);
}
BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDHtmlDialog)
ON_WM_SYSCOMMAND()
ON_LBN_SELCHANGE(IDC_LIST1, &CMFCApplication1Dlg::OnLbnSelchangeList1)
ON_WM_DROPFILES()
ON_BN_CLICKED(IDC_BUTTON1, &CMFCApplication1Dlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &CMFCApplication1Dlg::OnBnClickedButton2)
ON_LBN_SELCHANGE(IDC_LIST2, &CMFCApplication1Dlg::OnLbnSelchangeList2)
ON_WM_SIZE()
ON_BN_CLICKED(IDC_BUTTON3, &CMFCApplication1Dlg::OnBnClickedButton3)
ON_BN_CLICKED(IDC_BUTTON4, &CMFCApplication1Dlg::OnBnClickedButton4)
ON_BN_CLICKED(IDC_BUTTON5, &CMFCApplication1Dlg::OnBnClickedButton5)
END_MESSAGE_MAP()
// CMFCApplication1Dlg 消息处理程序
BOOL CMFCApplication1Dlg::OnInitDialog()
{
CDHtmlDialog::OnInitDialog();
listbox.SetHorizontalExtent(500);
listbox2.SetHorizontalExtent(200);
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CMFCApplication1Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDHtmlDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CMFCApplication1Dlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDHtmlDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CMFCApplication1Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
HRESULT CMFCApplication1Dlg::OnButtonOK(IHTMLElement* /*pElement*/)
{
OnOK();
return S_OK;
}
HRESULT CMFCApplication1Dlg::OnButtonCancel(IHTMLElement* /*pElement*/)
{
OnCancel();
return S_OK;
}
void CMFCApplication1Dlg::OnLbnSelchangeList1()
{
for (int i = listbox.GetCount() - 1;i >= 0;i--)
{
if (listbox.GetSel(i))
{
listbox2.SetCurSel(i);
}
}
}
void CMFCApplication1Dlg::OnDropFiles(HDROP hDropInfo)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
char szFilePathName[_MAX_PATH + 1] = { 0 };
//得到文件个数
UINT nNumOfFiles = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
for (UINT nIndex = 0; nIndex< nNumOfFiles; ++nIndex) {
// 得到文件名
DragQueryFile(hDropInfo, nIndex, (LPTSTR)szFilePathName, _MAX_PATH);
CString str2 = (_tcsrchr(szFilePathName, '\\'));
str2.Remove('\\'); //截取得到文件全名。如abc.avi
CString str4 = ",";
CString str8;
//CString str5 = "字节";
WIN32_FILE_ATTRIBUTE_DATA FindFileData;
GetFileAttributesEx(szFilePathName, GetFileExInfoStandard, &FindFileData);
//通过GetFileAttributesEx取的文件字节数
ULONGLONG FileSize = (FindFileData.nFileSizeHigh * 4294967296) + FindFileData.nFileSizeLow;
str8.Format("%I64u", FileSize);
str2 =str2 + str4 +str8;//文件全名+,+字节数 readme.txt,137
CString strmd5;
MD5 md5; //定义MD5的类
md5.update(str2.GetBuffer()); //因为update函数只接收string类型,所以使用getbuffer()函数转换CString为string
//md5.update(ifstream("E:\TDDownload\jre-8u66-windows-x64.exe)"));
strmd5 = md5.toString().c_str() + str4; //toString()函数获得加密字符串,c_str();函数重新转换成CString类型
listbox.AddString(str2);
listbox2.AddString(strmd5); //32位小写md5 (文件名.拓展名,字节数)
md5.reset();//每次计算后重置
}
DragFinish(hDropInfo);
CDHtmlDialog::OnDropFiles(hDropInfo);
}
void CMFCApplication1Dlg::OnBnClickedButton1()
{
CStdioFile file;
if (file.Open("info.txt", CFile::modeWrite | CFile::modeCreate))
{
int total = (int)listbox2.GetCount();
for (int ii = 0; ii< total; ii++)
{
char str[MAX_PATH] = { 0 };
listbox2.GetText(ii, str);
file.WriteString(str);
}
}
HMODULE module = GetModuleHandle(0);
char pFileName[MAX_PATH];
GetModuleFileName(module, pFileName, MAX_PATH);
CString csFullPath(pFileName);
int nPos = csFullPath.ReverseFind(_T('\\'));
if (nPos < 0) {
csFullPath = CString("");
}
else {
csFullPath = csFullPath.Left(nPos);
}
file.Close();
MessageBox("生成成功!生成路径为:" + csFullPath);
}
void CMFCApplication1Dlg::OnBnClickedButton2()
{
listbox.ResetContent();
listbox2.ResetContent();
}
void CMFCApplication1Dlg::OnLbnSelchangeList2()
{
for (int i = listbox2.GetCount() - 1;i >= 0;i--)
{
if (listbox2.GetSel(i))
{
listbox.SetCurSel(i);
}
}
}
void CMFCApplication1Dlg::OnSize(UINT nType, int cx, int cy)
{
CDHtmlDialog::OnSize(nType, cx, cy);
CWnd* pWnd = GetDlgItem(IDC_LIST1);
if (pWnd->GetSafeHwnd())
pWnd->MoveWindow(15, 15, 210, cy - 30);
CWnd* pWnd2 = GetDlgItem(IDC_LIST2);
if (pWnd2->GetSafeHwnd())
pWnd2->MoveWindow(220, 15, 210, cy - 30);
// CWnd* pWnd3 = GetDlgItem(IDC_BUTTON2);
// if (pWnd3->GetSafeHwnd())
//// pWnd3->MoveWindow(cx - 50, cy-200, cx - 10, cy - 100);
// TODO: 在此处添加消息处理程序代码
//CWnd *pWnd3;
// pWnd3 = GetDlgItem(IDC_BUTTON2); //获取控件指针,IDC_BUTTON1为控件ID号
//pWnd3->SetWindowPos(NULL, 50, 80, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
}
void CMFCApplication1Dlg::OnBnClickedButton3()
{
// TODO: Add your control notification handler code here
// 设置过滤器
TCHAR szFilter[] = _T("所有文件(*.*)|*.*||");
// 构造打开文件对话框
CFileDialog fileDlg(TRUE, _T("txt"), NULL, 0, szFilter, this);
CString szFilePathName;
// 显示打开文件对话框
if (IDOK == fileDlg.DoModal())
{
// 如果点击了文件对话框上的“打开”按钮,则将选择的文件路径显示到编辑框里
szFilePathName = fileDlg.GetPathName();
//SetDlgItemText(IDC_OPEN_EDIT, strFilePath);
CString str2 = (_tcsrchr(szFilePathName, '\\'));
str2.Remove('\\'); //截取得到文件全名。如abc.avi
CString str4 = ",";
CString str8;
//CString str5 = "字节";
WIN32_FILE_ATTRIBUTE_DATA FindFileData;
GetFileAttributesEx(szFilePathName, GetFileExInfoStandard, &FindFileData);
//通过GetFileAttributesEx取的文件字节数
ULONGLONG FileSize = (FindFileData.nFileSizeHigh * 4294967296) + FindFileData.nFileSizeLow;
str8.Format("%I64u", FileSize);
str2 = str2 + str4 + str8;//文件全名+,+字节数 readme.txt,137
CString strmd5;
MD5 md5; //定义MD5的类
md5.update(str2.GetBuffer()); //因为update函数只接收string类型,所以使用getbuffer()函数转换CString为string
//md5.update(ifstream("E:\TDDownload\jre-8u66-windows-x64.exe)"));
strmd5 = md5.toString().c_str() + str4; //toString()函数获得加密字符串,c_str();函数重新转换成CString类型
listbox.AddString(str2);
listbox2.AddString(strmd5); //32位小写md5 (文件名.拓展名,字节数)
}
}
void CMFCApplication1Dlg::OnBnClickedButton4()
{
//CString str;
for (int i = listbox.GetCount() - 1;i >= 0;i--)
{
if (listbox.GetSel(i))
{
//listbox.GetText(i, str);
//m_ToBeAdded.AddString(str);
listbox.DeleteString(i);
listbox2.DeleteString(i);
}
}
for (int i = listbox2.GetCount() - 1;i >= 0;i--)
{
if (listbox2.GetSel(i))
{
//listbox.GetText(i, str);
//m_ToBeAdded.AddString(str);
listbox.DeleteString(i);
listbox2.DeleteString(i);
}
}
}
void CMFCApplication1Dlg::OnBnClickedButton5()
{
char szPath[MAX_PATH]; //存放选择的目录路径
CString str;
ZeroMemory(szPath, sizeof(szPath));
BROWSEINFO bi;
bi.hwndOwner = m_hWnd;
bi.pidlRoot = NULL;
bi.pszDisplayName = szPath;
bi.lpszTitle = "请选择需要存放加密文件的目录:";
bi.ulFlags = 0;
bi.lpfn = NULL;
bi.lParam = 0;
bi.iImage = 0;
//弹出选择目录对话框
LPITEMIDLIST lp = SHBrowseForFolder(&bi);
if (lp && SHGetPathFromIDList(lp, szPath))
{
CStdioFile file;
CString info = "\\info.txt";
info = szPath + info;
if (file.Open(info, CFile::modeWrite | CFile::modeCreate))
{
int total = (int)listbox2.GetCount();
for (int ii = 0; ii< total; ii++)
{
char str[MAX_PATH] = { 0 };
listbox2.GetText(ii, str);
file.WriteString(str);
}
}
file.Close();
MessageBox("生成成功!生成路径为:" + info);
}
else
AfxMessageBox("无效的目录,请重新选择");
}
<file_sep>
// MFCApplication1.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "MFCApplication1.h"
#include "MFCApplication1Dlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFCApplication1App
BEGIN_MESSAGE_MAP(CMFCApplication1App, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CMFCApplication1App 构造
CMFCApplication1App::CMFCApplication1App()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CMFCApplication1App 对象
CMFCApplication1App theApp;
// CMFCApplication1App 初始化
BOOL CMFCApplication1App::InitInstance()
{
//HKEY Key;
//CString sKeyPath;
//sKeyPath = "Software\\mingrisoft";
//if (RegOpenKey(HKEY_CURRENT_USER, sKeyPath, &Key) != 0 && RegOpenKey(HKEY_CURRENT_USER, sKeyPath, &Key) != ERROR_SUCCESS)
//{
// //在注册表中记录已试用的次数
// ::RegCreateKey(HKEY_CURRENT_USER, sKeyPath, &Key);
// ::RegSetValueEx(Key, "TryTime", 0, REG_SZ, (unsigned char*)"20", 2);
// ::RegCloseKey(Key);
// MessageBox(NULL, "您还可以试用20次!", "系统提示", MB_OK | MB_ICONEXCLAMATION);
//}
//else //已经存在注册信息
//{
// CString sTryTime;
// int nTryTime;
// LPBYTE Data = new BYTE[80];
// DWORD TYPE = REG_SZ;
// DWORD cbData = 80;
// //取出已记载的数量
// ::RegQueryValueEx(Key, "TryTime", 0, &TYPE, Data, &cbData);
// sTryTime.Format("%s", Data);
// nTryTime = atoi(sTryTime);
// if (nTryTime<1)
// {
// MessageBox(NULL, "您的最大试用次数已过,只有注册后才允许继续使用!", "系统提示", MB_OK | MB_ICONSTOP);
// return FALSE;
// }
// nTryTime--;
// sTryTime.Format("%d", nTryTime);
// ::RegSetValueEx(Key, "TryTime", 0, REG_SZ, (unsigned char*)sTryTime.GetBuffer(sTryTime.GetLength()), 2);
// ::RegCloseKey(Key);
// MessageBox(NULL, "您还可以试用" + sTryTime + "次!", "系统提示", MB_OK | MB_ICONEXCLAMATION);
//}
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。 否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// 创建 shell 管理器,以防对话框包含
// 任何 shell 树视图控件或 shell 列表视图控件。
CShellManager *pShellManager = new CShellManager;
// 激活“Windows Native”视觉管理器,以便在 MFC 控件中启用主题
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
CMFCApplication1Dlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此放置处理何时用
// “确定”来关闭对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用
// “取消”来关闭对话框的代码
}
else if (nResponse == -1)
{
TRACE(traceAppMsg, 0, "警告: 对话框创建失败,应用程序将意外终止。\n");
TRACE(traceAppMsg, 0, "警告: 如果您在对话框上使用 MFC 控件,则无法 #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS。\n");
}
// 删除上面创建的 shell 管理器。
if (pShellManager != NULL)
{
delete pShellManager;
}
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
<file_sep>// listbox.cpp : 实现文件
//
#include "stdafx.h"
#include "MFCApplication1.h"
#include "listbox.h"
#include "afxdialogex.h"
// listbox 对话框
IMPLEMENT_DYNAMIC(listbox, CDialogEx)
listbox::listbox(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_MFCAPPLICATION1_DIALOG, pParent)
{
}
listbox::~listbox()
{
}
void listbox::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(listbox, CDialogEx)
END_MESSAGE_MAP()
// listbox 消息处理程序
| c4dce258bf8ece98f685fbe98ad5dbbe702d45e7 | [
"C++"
] | 5 | C++ | lu-kuan/FileName2MD5 | 360ee8ab5fef1f358111b02adb700b48438988a3 | 9e2efdc498fd522109eb26f33bb2de0d3d486d96 |
refs/heads/master | <repo_name>NizarHafizulllah/aplikasi_pu<file_sep>/application/modules/coba_map/views/coba_map_view.php
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
.gm-style-iw {
overflow-y: auto !important;
overflow-x: hidden !important;
}
.gm-style-iw > div {
overflow: visible !important;
}
.infoWindow {
overflow: hidden !important;
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.map-control {
background-color: #fff;
border: 1px solid #ccc;
box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
font-family: 'Roboto','sans-serif';
margin: 10px;
/* Hide the control initially, to prevent it from appearing
before the map loads. */
display: none;
}
/* Display the control once it is inside the map. */
#map .map-control { display: block; }
.selector-control {
font-size: 14px;
line-height: 30px;
padding-left: 5px;
padding-right: 5px;
}
</style>
</head>
<body>
<div id="style-selector-control" class="map-control">
<select id="style-selector" class="selector-control">
<option value="default">Bawaan</option>
<option value="silver">Putih</option>
<option value="night">Mode Malam</option>
<option value="retro" selected="selected">Retro</option>
<option value="hiding">Bersih</option>
</select>
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
var map;
alert('<NAME>');
var lokasi = [];
var base_urlimg = '<?php echo base_url("assets/img/") ?>'
var icons = {
jembatan: {
icon: '<?php echo base_url('assets/icon/jembatan.png') ?>'
},
gedung: {
icon: '<?php echo base_url('assets/icon/gedung.png') ?>'
},
}
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -8.489765, lng: 117.419735},
zoom: 12,
mapTypeControl: false,
zoomControlOptions: {
position : google.maps.ControlPosition.RIGHT_TOP
},
});
// Add a style-selector control to the map.
var styleControl = document.getElementById('style-selector-control');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(styleControl);
// Set the map's style to the initial value of the selector.
var styleSelector = document.getElementById('style-selector');
map.setOptions({styles: styles[styleSelector.value]});
// Apply new JSON when the user selects a different style.
styleSelector.addEventListener('change', function() {
map.setOptions({styles: styles[styleSelector.value]});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
var styles = {
default: null,
silver: [
{
elementType: 'geometry',
stylers: [{color: '#f5f5f5'}]
},
{
elementType: 'labels.icon',
stylers: [{visibility: 'off'}]
},
{
elementType: 'labels.text.fill',
stylers: [{color: '#616161'}]
},
{
elementType: 'labels.text.stroke',
stylers: [{color: '#f5f5f5'}]
},
{
featureType: 'administrative.land_parcel',
elementType: 'labels.text.fill',
stylers: [{color: '#bdbdbd'}]
},
{
featureType: 'poi',
elementType: 'geometry',
stylers: [{color: '#eeeeee'}]
},
{
featureType: 'poi',
elementType: 'labels.text.fill',
stylers: [{color: '#757575'}]
},
{
featureType: 'poi.park',
elementType: 'geometry',
stylers: [{color: '#e5e5e5'}]
},
{
featureType: 'poi.park',
elementType: 'labels.text.fill',
stylers: [{color: '#9e9e9e'}]
},
{
featureType: 'road',
elementType: 'geometry',
stylers: [{color: '#ffffff'}]
},
{
featureType: 'road.arterial',
elementType: 'labels.text.fill',
stylers: [{color: '#757575'}]
},
{
featureType: 'road.highway',
elementType: 'geometry',
stylers: [{color: '#dadada'}]
},
{
featureType: 'road.highway',
elementType: 'labels.text.fill',
stylers: [{color: '#616161'}]
},
{
featureType: 'road.local',
elementType: 'labels.text.fill',
stylers: [{color: '#9e9e9e'}]
},
{
featureType: 'transit.line',
elementType: 'geometry',
stylers: [{color: '#e5e5e5'}]
},
{
featureType: 'transit.station',
elementType: 'geometry',
stylers: [{color: '#eeeeee'}]
},
{
featureType: 'water',
elementType: 'geometry',
stylers: [{color: '#c9c9c9'}]
},
{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [{color: '#9e9e9e'}]
}
],
night: [
{elementType: 'geometry', stylers: [{color: '#242f3e'}]},
{elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
{elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
{
featureType: 'administrative.locality',
elementType: 'labels.text.fill',
stylers: [{color: '#d59563'}]
},
{
featureType: 'poi',
elementType: 'labels.text.fill',
stylers: [{color: '#d59563'}]
},
{
featureType: 'poi.park',
elementType: 'geometry',
stylers: [{color: '#263c3f'}]
},
{
featureType: 'poi.park',
elementType: 'labels.text.fill',
stylers: [{color: '#6b9a76'}]
},
{
featureType: 'road',
elementType: 'geometry',
stylers: [{color: '#38414e'}]
},
{
featureType: 'road',
elementType: 'geometry.stroke',
stylers: [{color: '#212a37'}]
},
{
featureType: 'road',
elementType: 'labels.text.fill',
stylers: [{color: '#9ca5b3'}]
},
{
featureType: 'road.highway',
elementType: 'geometry',
stylers: [{color: '#746855'}]
},
{
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [{color: '#1f2835'}]
},
{
featureType: 'road.highway',
elementType: 'labels.text.fill',
stylers: [{color: '#f3d19c'}]
},
{
featureType: 'transit',
elementType: 'geometry',
stylers: [{color: '#2f3948'}]
},
{
featureType: 'transit.station',
elementType: 'labels.text.fill',
stylers: [{color: '#d59563'}]
},
{
featureType: 'water',
elementType: 'geometry',
stylers: [{color: '#17263c'}]
},
{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [{color: '#515c6d'}]
},
{
featureType: 'water',
elementType: 'labels.text.stroke',
stylers: [{color: '#17263c'}]
}
],
retro: [
{elementType: 'geometry', stylers: [{color: '#ebe3cd'}]},
{elementType: 'labels.text.fill', stylers: [{color: '#523735'}]},
{elementType: 'labels.text.stroke', stylers: [{color: '#f5f1e6'}]},
{
featureType: 'administrative',
elementType: 'geometry.stroke',
stylers: [{color: '#c9b2a6'}]
},
{
featureType: 'administrative.land_parcel',
elementType: 'geometry.stroke',
stylers: [{color: '#dcd2be'}]
},
{
featureType: 'administrative.land_parcel',
elementType: 'labels.text.fill',
stylers: [{color: '#ae9e90'}]
},
{
featureType: 'landscape.natural',
elementType: 'geometry',
stylers: [{color: '#dfd2ae'}]
},
{
featureType: 'poi',
elementType: 'geometry',
stylers: [{color: '#dfd2ae'}]
},
{
featureType: 'poi',
elementType: 'labels.text.fill',
stylers: [{color: '#93817c'}]
},
{
featureType: 'poi.park',
elementType: 'geometry.fill',
stylers: [{color: '#a5b076'}]
},
{
featureType: 'poi.park',
elementType: 'labels.text.fill',
stylers: [{color: '#447530'}]
},
{
featureType: 'road',
elementType: 'geometry',
stylers: [{color: '#f5f1e6'}]
},
{
featureType: 'road.arterial',
elementType: 'geometry',
stylers: [{color: '#fdfcf8'}]
},
{
featureType: 'road.highway',
elementType: 'geometry',
stylers: [{color: '#f8c967'}]
},
{
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [{color: '#e9bc62'}]
},
{
featureType: 'road.highway.controlled_access',
elementType: 'geometry',
stylers: [{color: '#e98d58'}]
},
{
featureType: 'road.highway.controlled_access',
elementType: 'geometry.stroke',
stylers: [{color: '#db8555'}]
},
{
featureType: 'road.local',
elementType: 'labels.text.fill',
stylers: [{color: '#806b63'}]
},
{
featureType: 'transit.line',
elementType: 'geometry',
stylers: [{color: '#dfd2ae'}]
},
{
featureType: 'transit.line',
elementType: 'labels.text.fill',
stylers: [{color: '#8f7d77'}]
},
{
featureType: 'transit.line',
elementType: 'labels.text.stroke',
stylers: [{color: '#ebe3cd'}]
},
{
featureType: 'transit.station',
elementType: 'geometry',
stylers: [{color: '#dfd2ae'}]
},
{
featureType: 'water',
elementType: 'geometry.fill',
stylers: [{color: '#b9d3c2'}]
},
{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [{color: '#92998d'}]
}
],
hiding: [
{
featureType: 'poi.business',
stylers: [{visibility: 'off'}]
},
{
featureType: 'transit',
elementType: 'labels.icon',
stylers: [{visibility: 'off'}]
}
]
};
function findLokasi() {
$.ajax({
type: "GET",
url: "<?php echo site_url('coba_map/get_data') ?>",
dataType: "json",
success: function(data){
var d = new google.maps.InfoWindow();
var e;
$.each(data, function(i, b) {
// membuat maker dari lat, lng
e = new google.maps.Marker({
position: new google.maps.LatLng(b.lat, b.lng),
icon: b.icon,
map: map
});
lokasi.push(e);
// membuat info window alamat
google.maps.event.addListener(e, 'click', (function(a, i) {
return function() {
// alert(a.position.lat());
d.setContent('<div><img src="' + b.image + '" alt="Smiley face" height="300" width="300"></div><div class="row"><table width="100%"><tr><td width="30%"><b>Nama </b></td><td width="70%"><b>' + b.nama + '</b></td></tr><tr><td width="30%"><b>Jenis</b> </td><td width="70%"><b>' + b.jenis + '</b></td></tr><tr><td width="30%"><b>Lat</b> </td><td width="70%"><b>' + b.lat + '</b></td></tr><tr><td width="30%"><b>Lng</b> </td><td width="70%"><b>' + b.lng + '</b></td></tr></table>');
google.maps.event.addListener(d, 'domready', fixInfoWindowScrollbars);
d.open(map, a)
}
})(e, i))
});
}
});
}
function fixInfoWindowScrollbars() {
if (this.hasFixApplied) return;
// Find the DOM node for this infoWindow
var InfoWindowWrapper = $((this.B || this.D).contentNode.parentElement);
// We disable scrollbars temporarily
// Then increase .infoWindow's natural dimensions by 2px in width and height
InfoWindowWrapper.children().css('overflow', 'visible');
var InfoWindowElement = InfoWindowWrapper.find('.infoWindow');
InfoWindowElement
.width(function(i, oldWidth) { return oldWidth + 3 })
// Will this content need scrollbars? If so, add another 20px padding on right
if (InfoWindowElement.height() > InfoWindowWrapper.height()) {
InfoWindowElement
.css({'padding-right': '20px'})
.width(function(i, oldWidth) { return oldWidth - 20 })
}
InfoWindowElement
.height(function(i, oldHeight) { return oldHeight + 3 })
// Replace infoWindow content with our new DOM nodes
this.hasFixApplied = true;
this.setContent(InfoWindowElement.get(0))
}
$(function(){
findLokasi();
});
</script>
</body>
</html><file_sep>/application/views/admin/index_view.php
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
.gm-style-iw {
overflow-y: auto !important;
overflow-x: hidden !important;
}
.gm-style-iw > div {
overflow: visible !important;
}
.infoWindow {
overflow: hidden !important;
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var lokasi = [];
var base_urlimg = '<?php echo base_url("assets/img/") ?>'
var icons = {
jembatan: {
icon: '<?php echo base_url('assets/icon/jembatan.png') ?>'
},
gedung: {
icon: '<?php echo base_url('assets/icon/gedung.png') ?>'
},
}
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -8.489765, lng: 117.419735},
zoom: 12,
zoomControlOptions: {
position : google.maps.ControlPosition.RIGHT_TOP
},
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function findLokasi() {
$.ajax({
type: "GET",
url: "<?php echo site_url('admin/get_data') ?>",
dataType: "json",
success: function(data){
var d = new google.maps.InfoWindow();
var e;
$.each(data, function(i, b) {
// membuat maker dari lat, lng
e = new google.maps.Marker({
position: new google.maps.LatLng(b.lat, b.lng),
icon: icons[b.jenis].icon,
map: map
});
lokasi.push(e);
// membuat info window alamat
google.maps.event.addListener(e, 'click', (function(a, i) {
return function() {
// alert(a.position.lat());
d.setContent('<div><img src="' + base_urlimg + '/' + b.image + '" alt="Smiley face" height="300" width="300"></div><div class="row"><table width="100%"><tr><td width="30%"><b>Nama </b></td><td width="70%"><b>' + b.nama + '</b></td></tr><tr><td width="30%"><b>Jenis</b> </td><td width="70%"><b>' + b.jenis + '</b></td></tr><tr><td width="30%"><b>Lat</b> </td><td width="70%"><b>' + b.lat + '</b></td></tr><tr><td width="30%"><b>Lng</b> </td><td width="70%"><b>' + b.lng + '</b></td></tr></table>');
google.maps.event.addListener(d, 'domready', fixInfoWindowScrollbars);
d.open(map, a)
}
})(e, i))
});
}
});
}
function fixInfoWindowScrollbars() {
if (this.hasFixApplied) return;
// Find the DOM node for this infoWindow
var InfoWindowWrapper = $((this.B || this.D).contentNode.parentElement);
// We disable scrollbars temporarily
// Then increase .infoWindow's natural dimensions by 2px in width and height
InfoWindowWrapper.children().css('overflow', 'visible');
var InfoWindowElement = InfoWindowWrapper.find('.infoWindow');
InfoWindowElement
.width(function(i, oldWidth) { return oldWidth + 3 })
// Will this content need scrollbars? If so, add another 20px padding on right
if (InfoWindowElement.height() > InfoWindowWrapper.height()) {
InfoWindowElement
.css({'padding-right': '20px'})
.width(function(i, oldWidth) { return oldWidth - 20 })
}
InfoWindowElement
.height(function(i, oldHeight) { return oldHeight + 3 })
// Replace infoWindow content with our new DOM nodes
this.hasFixApplied = true;
this.setContent(InfoWindowElement.get(0))
}
$(function(){
findLokasi();
});
</script>
</body>
</html><file_sep>/application/modules/coba_map/controllers/coba_map.php
<?php
class coba_map extends CI_Controller {
function __construct(){
parent::__construct();
$this->controller = get_class($this);
$this->load->helper("tanggal");
$this->load->helper("url");
$this->load->helper("kirimemail");
//$this->load->helper("serviceurl");
}
function index(){
$this->load->view("coba_map_view");
}
function get_data() {
$result = $this->db->get('properti')->result_array();
$this->db->select("p.*, j.jenis as jenis, j.icon as icon")->from("properti p");
$this->db->join('jenis j','j.id=p.jenis');
$result = $this->db->get()->result_array();
$data = array();
foreach($result as $row) :
$icon = base_url("upload_file/icon/".$row["icon"]);
$image = base_url("upload_file/image/".$row["image"]);
$data[] = array(
"lat" => $row['lat'],
"lng" => $row['lng'],
"icon" => $icon,
"jenis" => $row['jenis'],
"nama" => $row['nama'],
"image" => $image,
);
endforeach;
echo json_encode($data);
}
}
?>
<file_sep>/application/modules/jenis/views/jenis_view.php
<link href="<?php echo base_url("assets") ?>/css/datepicker.css" rel="stylesheet">
<script src="<?php echo base_url("assets") ?>/js/bootstrap-datepicker.js"></script>
<script src="<?php echo base_url("assets") ?>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery.dataTables.min.css">
<!-- Content Header (Page header) -->
<!-- Default box -->
<form role="form" action="" id="btn-cari" >
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label for="Tanggal">Jenis</label>
<input name="jenis" id="jenis" type="text" class="form-control" placeholder="Jenis" ></input>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label> </label>
<button type="submit" class="btn btn-primary form-control" id="btn_submit"><i class="fa fa-search"></i> Cari</button>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label> </label>
<button type="reset" class="btn btn-danger form-control" id="btn_reset"><i class="fa fa-ban"></i> Reset</button>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label> </label>
<a href="<?php echo site_url($this->controller.'/baru'); ?>" class="btn btn-success form-control" ><i class="fa fa-user-plus"></i> Tambah Data</a>
</div>
</div>
</div>
</form>
<table width="100%" border="0" id="biro_jasa" class="table table-striped
table-bordered table-hover dataTable no-footer" role="grid">
<thead>
<tr >
<th>ID</th>
<th>Jenis</th>
<th>Icon</th>
<th>Action</th>
</tr>
</thead>
</table>
<?php
$this->load->view($this->controller."_view_js");
?><file_sep>/application/controllers/admin.php
<?php
class admin extends admin_controller {
var $controller;
public function __construct(){
parent::__construct();
$this->controller = get_class($this);
}
function index(){
$data_array=array();
$content = $this->load->view("admin/index_view",$data_array,true);
$this->set_subtitle("Desa Labuhan Ijuk");
$this->set_title("BERANDA");
$this->set_content($content);
$this->cetak();
}
function get_data() {
$this->db->select("p.*, j.jenis as jenis, j.icon as icon")->from("properti p");
$this->db->join('jenis j','j.id=p.jenis');
$result = $this->db->get()->result_array();
$data = array();
foreach($result as $row) :
$icon = base_url("upload_file/icon/".$row["icon"]);
$image = base_url("upload_file/image/".$row["image"]);
$data[] = array(
"lat" => $row['lat'],
"lng" => $row['lng'],
"icon" => $icon,
"jenis" => $row['jenis'],
"nama" => $row['nama'],
"image" => $image,
);
endforeach;
// show_array($data);
// exit();
echo json_encode($data);
}
}
?><file_sep>/pudb.sql
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 18 Okt 2017 pada 12.33
-- Versi Server: 5.6.20
-- PHP Version: 5.5.15
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 utf8 */;
--
-- Database: `pudb`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `jenis`
--
CREATE TABLE IF NOT EXISTS `jenis` (
`id` int(11) NOT NULL,
`jenis` varchar(50) NOT NULL,
`icon` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data untuk tabel `jenis`
--
INSERT INTO `jenis` (`id`, `jenis`, `icon`) VALUES
(1, 'Jembatan', '00182392839.png'),
(2, 'Kantor Pemerintahan', '324234234234.png'),
(3, 'Masjid', 'b981d4e680336002b0d508accac69b01.png'),
(4, 'Gereja', '492845f46e95971632d89f7f486b0749.png');
-- --------------------------------------------------------
--
-- Struktur dari tabel `pengguna`
--
CREATE TABLE IF NOT EXISTS `pengguna` (
`id` int(11) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`nama` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data untuk tabel `pengguna`
--
INSERT INTO `pengguna` (`id`, `email`, `password`, `nama`) VALUES
(1, 'admin', '<PASSWORD>', 'Bustanil');
-- --------------------------------------------------------
--
-- Struktur dari tabel `properti`
--
CREATE TABLE IF NOT EXISTS `properti` (
`id` int(11) NOT NULL,
`lat` varchar(30) NOT NULL,
`lng` varchar(30) NOT NULL,
`jenis` varchar(25) NOT NULL,
`nama` varchar(100) NOT NULL,
`image` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data untuk tabel `properti`
--
INSERT INTO `properti` (`id`, `lat`, `lng`, `jenis`, `nama`, `image`) VALUES
(1, '-8.497025', '117.420246', '1', 'Kerangka Baja', 'krangkabaja.jpg'),
(2, '-8.488960', '117.416642', '1', 'Brang Biji', 'brangbiji.jpg'),
(3, '-8.476924', '117.410605', '1', 'Lempeh', 'lempeh.jpg'),
(4, '-8.551390', '117.487409', '1', 'Jembatan Serading', 'serading.jpg'),
(5, '-8.505734', '117.424155', '1', 'Jembatan Baru', '1543dc4381bf589a6d5bfbe3e8c19252.jpg'),
(6, '-8.504475', '117.426344', '3', 'Masjid Jami', '9d705b46dc5afc83115f93a2b0f78a62.jpg'),
(7, '-8.487409', '117.424871', '4', 'GKT Ebenhaezer', 'dffaf54c3cc27e600c275ec5131af6a0.jpg');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `jenis`
--
ALTER TABLE `jenis`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `pengguna`
--
ALTER TABLE `pengguna`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `properti`
--
ALTER TABLE `properti`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `jenis`
--
ALTER TABLE `jenis`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `pengguna`
--
ALTER TABLE `pengguna`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `properti`
--
ALTER TABLE `properti`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
/*!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>/application/modules/properti/views/properti_form_view.php
<link href="<?php echo base_url("assets") ?>/css/datepicker.css" rel="stylesheet">
<script src="<?php echo base_url("assets") ?>/js/bootstrap-datepicker.js"></script>
<script src="<?php echo base_url("assets"); ?>/vendors/fileinput/js/fileinput.min.js"></script>
<link href="<?php echo base_url("assets"); ?>/vendors/fileinput/css/fileinput.min.css" rel="stylesheet">
<script src="<?php echo base_url("assets"); ?>/ckeditor/ckeditor.js"></script>
<form id="form_data" class="form-horizontal" method="post" action="<?php echo site_url("$this->controller/$action"); ?>" role="form" enctype="multipart/form-data">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Data Properti</h3>
</div>
<div class="box-body">
<div class="form-group">
<label class="col-sm-3 control-label">Nama</label>
<div class="col-sm-9">
<input type="text" name="nama" id="nama" class="form-control input-style" placeholder="Nama" value="<?php echo isset($nama)?$nama:""; ?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Jenis Properti</label>
<div class="col-sm-9">
<?php echo form_dropdown("jenis",$arr_jenis,isset($jenis)?$jenis:'','id="jenis" class="form-control input-style"'); ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Lat</label>
<div class="col-sm-4">
<input type="text" name="lat" id="lat" class="form-control input-style" placeholder="Lat" value="<?php echo isset($lat)?$lat:""; ?>">
</div>
<label class="col-sm-1 control-label">Lng</label>
<div class="col-sm-4">
<input type="text" name="lng" id="lng" class="form-control input-style" placeholder="Lng" value="<?php echo isset($lng)?$lng:""; ?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="image" id="image" class="file form-control" data-show-preview="true" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Keterangan</label>
<div class="col-sm-9">
<textarea name="keterangan" id="keterangan" class="ckeditor"></textarea>
</div>
</div>
<div class="form-group pull-center">
<div class="col-md-3"></div>
<div class="col-sm-4">
<?php
if ($action=='simpan') { ?>
<button id="tombolsubmitsimpan" style="border-radius: 4;" type="submit" class="btn btn-primary" >Simpan</button>
<?php }else{ ?>
<button id="tombolsubmitupdate" style="border-radius: 4;" type="submit" class="btn btn-primary" >Update</button>
<?php
}
?>
<a href="<?php echo site_url('properti'); ?>"><button style="border-radius: 4;" id="reset" type="button" class="btn btn-danger">Kembali</button></a>
</div>
</div>
</div><!-- /.box-body -->
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'keterangan' );
</script>
</div>
</form>
<?php
$this->load->view($this->controller."_form_view_js");
?><file_sep>/application/modules/jenis/models/jenis_model.php
<?php
class jenis_model extends CI_Model {
function __construct(){
parent::__construct();
}
function data($param)
{
// show_array($param);
// exit;
extract($param);
$kolom = array(0=>"id",
"jenis"
);
if(!empty($jenis)) {
$this->db->like("jenis",$jenis);
}
($param['limit'] != null ? $this->db->limit($param['limit']['end'], $param['limit']['start']) : '');
//$this->db->limit($param['limit']['end'], $param['limit']['start']) ;
($param['sort_by'] != null) ? $this->db->order_by($kolom[$param['sort_by']], $param['sort_direction']) :'';
$res = $this->db->get('jenis');
// echo $this->db->last_query(); exit;
return $res;
}
}
?> | c886aec23e09aaa1a7a236837808a431eb4db931 | [
"SQL",
"PHP"
] | 8 | PHP | NizarHafizulllah/aplikasi_pu | 41b4c0d2e469a995b6e31ee076d329230f5562d8 | 433669259cd52f7745df8cbdbfd6f0d8d97d7c18 |
refs/heads/master | <repo_name>vjayathilaka/springDemo<file_sep>/src/main/java/com/demo/demo/jdbc/PersonJDBCDao.java
package com.demo.demo.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.demo.demo.entity.Person;
@Repository
public class PersonJDBCDao {
@Autowired
JdbcTemplate jdbcTemplate;
public PersonJDBCDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Person> findAll() {
return jdbcTemplate.query("select * from person", new BeanPropertyRowMapper<Person>(Person.class));
}
public List<Person> findAllWithRowMapper() {
return jdbcTemplate.query("select * from person", new RowMapper<Person>() {
@Override
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Person(
rs.getInt("id"),
rs.getString("name"),
rs.getDate("birth_day")
);
}
});
}
public List<Person> findAllWithLambda() {
return jdbcTemplate.query("select * from person", (rs, index) -> {
return new Person(
rs.getInt("id"),
rs.getString("name"),
rs.getDate("birth_day")
);
});
}
}
<file_sep>/src/main/resources/data.sql
--create table person (
--id integer not null,
--name varchar(255) not null,
--birth_day timestamp,
--primary key(id)
--);
insert into person(id, name, birth_day) values(10001, 'vijitha', sysdate());
insert into person(id, name, birth_day) values(10002, 'hiranthi', sysdate());
insert into person(id, name, birth_day) values(10003, 'sameera', sysdate());
insert into person(id, name, birth_day) values(10004, 'nalaka', sysdate());<file_sep>/src/main/resources/application.properties
spring.h2.console.enabled=true
server.port=9092
security.basic.enabled=false
spring.jpa.generate-ddl=true | 76f6c65621299d00955a1f00c8149cba04b37bd5 | [
"Java",
"SQL",
"INI"
] | 3 | Java | vjayathilaka/springDemo | 3e5cf98f064dbd05cfd87175f01605bacf7ae926 | fe9b274c8bea97bdb63c8816d81ae163c1944ccf |
refs/heads/master | <file_sep># Generated by Django 3.0.3 on 2020-03-01 12:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='MainPersonData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=15)),
('sex', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=6)),
('age', models.PositiveSmallIntegerField()),
('height', models.PositiveSmallIntegerField()),
('weight', models.PositiveSmallIntegerField()),
('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'main_data',
},
),
migrations.CreateModel(
name='BodyMassIndex',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', models.DecimalField(decimal_places=2, max_digits=5)),
('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'body_mass_index',
},
),
]
<file_sep>=====
BodyMassIndexCalculator
=====
BodyMassIndexCalculator is a Django app to conduct body mass index calculation
logic.
Quick start
-----------
1. Add "calculator" to your INSTALLED_APPS setting like this::
INSTALLED_APPS = [
...
'body_mass_calculator',
]
2. Run `python manage.py migrate` to create the polls models.<file_sep>default_app_config = 'body_mass_calculator.apps.CalculatorConfig'
<file_sep>from django.forms import ModelForm
from .models import MainPersonData
class MainDataForm(ModelForm):
class Meta:
model = MainPersonData
fields = ['name', 'age', 'sex', 'height', 'weight', 'smoking']
def clean(self):
cleaned_data = super().clean()
name = cleaned_data.get('name')
age = cleaned_data.get('age')
height = cleaned_data.get('height')
weight = cleaned_data.get('weight')
if len(name) < 1:
self.add_error('name', 'Имя не может состоять из одной буквы')
if age < 21:
self.add_error('age', 'Возраст должен быть больше 20')
if height <= 0:
self.add_error('height', 'Рост не может быть равен нулю')
if weight <= 0:
self.add_error('weight', 'Вес не может быть равен нулю')
return cleaned_data
<file_sep>from math import pow
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class MainPersonData(models.Model):
class Meta:
db_table = 'main_data'
constraints = (
models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
)
verbose_name = 'Основные данные пользователя'
verbose_name_plural = 'Основные данные пользователей'
MALE = 'M'
FEMALE = 'F'
SEX_TYPES = (
(MALE, 'Муж.'),
(FEMALE, 'Жен.'),
)
person = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, verbose_name='Пользователь')
name = models.CharField(max_length=15, verbose_name='Имя')
sex = models.CharField(max_length=6, choices=SEX_TYPES, verbose_name='Пол')
age = models.PositiveSmallIntegerField(verbose_name='Возраст')
height = models.PositiveSmallIntegerField(verbose_name='Рост')
weight = models.PositiveSmallIntegerField(verbose_name='Вес')
smoking = models.BooleanField(verbose_name='Курение', default=False)
def __str__(self):
return self.person.username
class BodyMassIndex(models.Model):
class Meta:
db_table = 'body_mass_index'
constraints = (
models.CheckConstraint(check=models.Q(value__gte=0), name='value_gte_0'),
)
verbose_name = 'Индекс массы тела'
verbose_name_plural = 'Индекс масс тел'
value = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='Индекс массы тела')
person = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Пользователь')
def __str__(self):
return self.person.name
@receiver(post_save, sender=MainPersonData, dispatch_uid='calculate_body_mass_index_value')
def calculate_body_mass_index(sender, instance, **kwargs) -> None:
user = instance.person
value = instance.weight / pow((instance.height / 100), 2)
previous_data = BodyMassIndex.objects.filter(person=user)
if previous_data.exists():
previous_data.update(value=value)
else:
body_mass_index = BodyMassIndex(value=value, person=user)
body_mass_index.save()
<file_sep># Generated by Django 3.0.3 on 2020-03-01 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('body_mass_calculator', '0001_initial'),
]
operations = [
migrations.AddConstraint(
model_name='bodymassindex',
constraint=models.CheckConstraint(check=models.Q(value__gte=0), name='value_gte_0'),
),
migrations.AddConstraint(
model_name='mainpersondata',
constraint=models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
),
]
<file_sep># Generated by Django 3.0.3 on 2020-03-13 10:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('body_mass_calculator', '0004_auto_20200305_1046'),
]
operations = [
migrations.AlterModelOptions(
name='bodymassindex',
options={'verbose_name': 'Индекс массы тела', 'verbose_name_plural': 'Индекс масс тел'},
),
migrations.AlterModelOptions(
name='mainpersondata',
options={'verbose_name': 'Основные данные пользователя', 'verbose_name_plural': 'Основные данные пользователей'},
),
migrations.AddField(
model_name='mainpersondata',
name='smoking',
field=models.BooleanField(default=False, verbose_name='Курение'),
),
migrations.AlterField(
model_name='bodymassindex',
name='person',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Пользователь'),
),
migrations.AlterField(
model_name='bodymassindex',
name='value',
field=models.DecimalField(decimal_places=2, max_digits=5, verbose_name='Индекс массы тела'),
),
migrations.AlterField(
model_name='mainpersondata',
name='age',
field=models.PositiveSmallIntegerField(verbose_name='Возраст'),
),
migrations.AlterField(
model_name='mainpersondata',
name='height',
field=models.PositiveSmallIntegerField(verbose_name='Рост'),
),
migrations.AlterField(
model_name='mainpersondata',
name='name',
field=models.CharField(max_length=15, verbose_name='Имя'),
),
migrations.AlterField(
model_name='mainpersondata',
name='person',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Пользователь'),
),
migrations.AlterField(
model_name='mainpersondata',
name='sex',
field=models.CharField(choices=[('M', 'Муж.'), ('F', 'Жен.')], max_length=6, verbose_name='Пол'),
),
migrations.AlterField(
model_name='mainpersondata',
name='weight',
field=models.PositiveSmallIntegerField(verbose_name='Вес'),
),
]
<file_sep>from django.contrib import admin
from .models import MainPersonData
@admin.register(MainPersonData)
class MainPersonDataAdmin(admin.ModelAdmin):
fields = (
'person',
'name',
'sex',
'age',
'height',
'weight',
'smoking'
)
list_display = (
'person',
'name',
'sex',
'age',
'height',
'weight',
)
readonly_fields = (
'person',
)
<file_sep>from decimal import Decimal
from django.test import TestCase, TransactionTestCase
from django.db.utils import IntegrityError
from .models import MainPersonData, BodyMassIndex, User
TEST_USER_NAME = 'test_user'
TEST_EMAIL = '<EMAIL>'
TEST_PASSWORD = '<PASSWORD>'
TEST_AGE = 22
TEST_HEIGHT = 180
TEST_WEIGHT = 180
TEST_SEX = MainPersonData.MALE
TEST_RESULT = Decimal('55.56')
TEST_WRONG_AGE = 13
TEST_UPDATE_HEIGHT = 100
TEST_UPDATE_WEIGHT = 40
TEST_UPDATE_RESULT = 40
def save_test_user(name, email, password) -> User:
user = User.objects.create_user(username=name, email=email, password=password)
return user
def save_test_data(name, sex, age, height, weight) -> User:
user = save_test_user(TEST_USER_NAME, TEST_EMAIL, TEST_PASSWORD)
MainPersonData.objects.create(
person=user,
name=name,
sex=sex,
age=age,
height=height,
weight=weight
)
return user
class BodyMassIndexTest(TestCase):
def setUp(self) -> None:
save_test_data(TEST_USER_NAME, TEST_SEX,
TEST_AGE, TEST_HEIGHT, TEST_WEIGHT)
def test_calculate_body_mass_index(self) -> None:
user = User.objects.get_by_natural_key(TEST_USER_NAME)
body_mass_index = BodyMassIndex.objects.get(person=user)
self.assertEqual(body_mass_index.value, TEST_RESULT)
class MainPersonDataTest(TransactionTestCase):
def test_constraint(self) -> None:
with self.assertRaises(IntegrityError):
save_test_data(TEST_USER_NAME, TEST_SEX,
TEST_WRONG_AGE, TEST_HEIGHT,
TEST_WEIGHT)
class BodyMassIndexUpdateTest(TransactionTestCase):
def setUp(self) -> None:
save_test_data(TEST_USER_NAME, TEST_SEX,
TEST_AGE, TEST_HEIGHT, TEST_WEIGHT)
def update_test(self) -> None:
user = User.objects.get_by_natural_key(TEST_USER_NAME)
MainPersonData.objects.filter(user=user).update(
height=TEST_UPDATE_HEIGHT,
weight=TEST_UPDATE_WEIGHT
)
body_mass_index = BodyMassIndex.objects.get(person=user)
self.assertEqual(body_mass_index.value, TEST_UPDATE_RESULT)
<file_sep>from django.apps import AppConfig
class CalculatorConfig(AppConfig):
name = 'body_mass_calculator'
verbose_name = 'Калькулятор массы тела'
| f0aa47199c5f58c916718400ee18e4a8efd543a8 | [
"Python",
"reStructuredText"
] | 10 | Python | AlexanderUstinovv/body_mass_calculator | 0cefb6e0d0785d9045959493b4553390a6c58dc7 | 1aaa7a327e48c347771bc7b83ae4a9da75d4e94d |
refs/heads/master | <file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Behaviours;
use Spiral\Stempler\BehaviourInterface;
use Spiral\Stempler\HtmlTokenizer;
use Spiral\Stempler\Node;
use Spiral\Stempler\Supervisor;
/**
* Replaces specified block (including tag) with external node, automatically uses inner tag
* content as "context" block and all other tag attributes as additional node child.
*/
class IncludeBehaviour implements BehaviourInterface
{
/**
* Name of block used to represent import context.
*/
const CONTEXT_BLOCK = 'context';
/**
* Path to be included (see Supervisor createNode).
*
* @var string
*/
protected $path = '';
/**
* Import context includes everything between opening and closing tag.
*
* @var array
*/
protected $context = [];
/**
* Context token.
*
* @var array
*/
protected $token = [];
/**
* @var Supervisor
*/
protected $supervisor = null;
/**
* @param Supervisor $supervisor
* @param string $path
* @param array $context
* @param array $token
*/
public function __construct(Supervisor $supervisor, $path, array $context, array $token = [])
{
$this->supervisor = $supervisor;
$this->path = $path;
$this->context = $context;
$this->token = $token;
}
/**
* Create node to be injected into template at place of tag caused import.
*
* @return Node
*/
public function createNode()
{
//Content of node to be imported
$node = $this->supervisor->createNode($this->path, $this->token);
//Let's register user defined blocks (context and attributes) as placeholders
$node->mountBlock(
self::CONTEXT_BLOCK,
[],
[$this->createPlaceholder(self::CONTEXT_BLOCK, $contextID)],
true
);
foreach ($this->token[HtmlTokenizer::TOKEN_ATTRIBUTES] as $attribute => $value) {
//Attributes counted as blocks to replace elements in included node
$node->mountBlock($attribute, [], [$value], true);
}
//We now have to compile node content to pass it's body to parent node
$content = $node->compile($dynamic);
//Outer blocks (usually user attributes) can be exported to template using non default
//rendering technique, for example every "extra" attribute can be passed to specific
//template location. Stempler to decide.
foreach ($this->supervisor->syntax()->blockExporters() as $exporter) {
$content = $exporter->mountBlocks($content, $dynamic);
}
//Let's parse complied content without any imports (to prevent collision)
$supervisor = clone $this->supervisor;
$supervisor->flushImporters();
//Outer content must be protected using unique names
$rebuilt = new Node($supervisor, $supervisor->uniquePlaceholder(), $content);
if (!empty($contextBlock = $rebuilt->findNode($contextID))) {
//Now we can mount our content block
$contextBlock->mountNode($this->contextNode());
}
return $rebuilt;
}
/**
* Pack node context (everything between open and close tag).
*
* @return Node
*/
protected function contextNode()
{
$context = '';
foreach ($this->context as $token) {
$context .= $token[HtmlTokenizer::TOKEN_CONTENT];
}
return new Node($this->supervisor, $this->supervisor->uniquePlaceholder(), $context);
}
/**
* Create placeholder block (to be injected with inner blocks defined in context).
*
* @param string $name
* @param string $blockID
* @return string
*/
protected function createPlaceholder($name, &$blockID)
{
$blockID = $name . '-' . $this->supervisor->uniquePlaceholder();
//Short block declaration syntax
return '${' . $blockID . '}';
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Tokenizer\Reflections\ReflectionInvocation;
/**
* Analog of LocatorInterface for method/function invocations. Can only work with simple invocations
* such as $this->method, self::method, static::method, or ClassName::method.
*
* @todo use AST
*/
interface InvocationLocatorInterface
{
/**
* Find all possible invocations of given function or method. Make sure you know about location
* limitations.
*
* @param \ReflectionFunctionAbstract $function
* @return ReflectionInvocation[]
*/
public function getInvocations(\ReflectionFunctionAbstract $function);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres;
use Spiral\Core\FactoryInterface;
use Spiral\Core\HippocampusInterface;
use Spiral\Database\DatabaseInterface;
use Spiral\Database\Drivers\Postgres\Schemas\Commander;
use Spiral\Database\Drivers\Postgres\Schemas\TableSchema;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Exceptions\DriverException;
/**
* Talks to postgres databases.
*/
class PostgresDriver extends Driver
{
/**
* Driver type.
*/
const TYPE = DatabaseInterface::POSTGRES;
/**
* Driver schemas.
*/
const SCHEMA_TABLE = TableSchema::class;
/**
* Commander used to execute commands. :)
*/
const COMMANDER = Commander::class;
/**
* Query compiler class.
*/
const QUERY_COMPILER = QueryCompiler::class;
/**
* Default timestamp expression.
*/
const TIMESTAMP_NOW = 'now()';
/**
* Cached list of primary keys associated with their table names. Used by InsertBuilder to
* emulate last insert id.
*
* @var array
*/
private $primaryKeys = [];
/**
* Needed to remember table primary keys.
*
* @invisible
* @var HippocampusInterface
*/
protected $memory = null;
/**
* {@inheritdoc}
* @param string $name
* @param array $config
* @param FactoryInterface $factory
* @param HippocampusInterface $memory
*/
public function __construct(
$name,
array $config,
FactoryInterface $factory = null,
HippocampusInterface $memory = null
) {
parent::__construct($name, $config, $factory);
$this->memory = $memory;
}
/**
* {@inheritdoc}
*/
public function hasTable($name)
{
$query = 'SELECT "table_name" FROM "information_schema"."tables" '
. 'WHERE "table_schema" = \'public\' AND "table_type" = \'BASE TABLE\' AND "table_name" = ?';
return (bool)$this->query($query, [$name])->fetchColumn();
}
/**
* {@inheritdoc}
*/
public function tableNames()
{
$query = 'SELECT "table_name" FROM "information_schema"."tables" '
. 'WHERE "table_schema" = \'public\' AND "table_type" = \'BASE TABLE\'';
$tables = [];
foreach ($this->query($query) as $row) {
$tables[] = $row['table_name'];
}
return $tables;
}
/**
* Get singular primary key associated with desired table. Used to emulate last insert id.
*
* @param string $table Fully specified table name, including postfix.
* @return string
* @throws DriverException
*/
public function getPrimary($table)
{
if (!empty($this->memory) && empty($this->primaryKeys)) {
$this->primaryKeys = (array)$this->memory->loadData($this->getSource() . '-primary');
}
if (!empty($this->primaryKeys) && array_key_exists($table, $this->primaryKeys)) {
return $this->primaryKeys[$table];
}
if (!$this->hasTable($table)) {
throw new DriverException(
"Unable to fetch table primary key, no such table '{$table}' exists."
);
}
$this->primaryKeys[$table] = $this->tableSchema($table)->getPrimaryKeys();
if (count($this->primaryKeys[$table]) === 1) {
//We do support only single primary key
$this->primaryKeys[$table] = $this->primaryKeys[$table][0];
} else {
$this->primaryKeys[$table] = null;
}
//Caching
if (!empty($this->memory)) {
$this->memory->saveData($this->getSource() . '-primary', $this->primaryKeys);
}
return $this->primaryKeys[$table];
}
/**
* {@inheritdoc}
*/
public function insertBuilder(Database $database, array $parameters = [])
{
return $this->factory->make(InsertQuery::class, [
'database' => $database,
'compiler' => $this->queryCompiler($database->getPrefix())
] + $parameters);
}
/**
* {@inheritdoc}
*/
protected function createPDO()
{
//Spiral is purely UTF-8
$pdo = parent::createPDO();
$pdo->exec("SET NAMES 'UTF-8'");
return $pdo;
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
use Spiral\Models\Exceptions\AccessorExceptionInterface;
/**
* Generic ODM accessor exception.
*/
class AccessorException extends DocumentException implements AccessorExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core\Container;
/**
* Must define constant INJECTOR pointing to associated injector class or binding.
*/
interface InjectableInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database;
/**
* Must represent single query result. Has to decorate or extend methods of PDOStatement.
*/
interface ResultInterface extends \Countable, \Iterator
{
/**
* The number of columns in the result set.
*
* @return int
*/
public function countColumns();
/**
* Fetch one result row as array or return false.
*
* @return array|bool
*/
public function fetch();
/**
* Returns a single column value from the next row of a result set.
*
* @param int $columnID Column number (0 - first column)
* @return mixed
*/
public function fetchColumn($columnID = 0);
/**
* Bind a column value to a PHP variable.
*
* @param integer|string $columnID Column number (0 - first column)
* @param mixed $variable
*/
public function bind($columnID, &$variable);
/**
* Returns an array containing all of the result set rows, do not use this method on big
* datasets.
*
* @return array
*/
public function fetchAll();
/**
* Close result iterator. Must free as much memory as it can.
*/
public function close();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache;
use Spiral\Cache\Configs\CacheConfig;
use Spiral\Cache\Exceptions\CacheException;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\FactoryInterface;
use Spiral\Debug\Traits\BenchmarkTrait;
/**
* Default implementation of CacheInterface. Better fit for spiral.
*/
class CacheManager extends Component implements SingletonInterface, CacheInterface, InjectorInterface
{
/**
* Some operations can be slow.
*/
use BenchmarkTrait;
/**
* Declares to Spiral IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* Already constructed cache adapters.
*
* @var StoreInterface[]
*/
private $stores = false;
/**
* @var CacheConfig
*/
protected $config = null;
/**
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param CacheConfig $config
* @param FactoryInterface $factory
*/
public function __construct(CacheConfig $config, FactoryInterface $factory)
{
$this->config = $config;
$this->factory = $factory;
}
/**
* {@inheritdoc}
*/
public function store($store = null)
{
//Default store class
//todo: default store like in db manager
$store = !empty($store) ? $store : $this->config['store'];
$store = $this->config->resolveAlias($store);
if (isset($this->stores[$store])) {
return $this->stores[$store];
}
$benchmark = $this->benchmark('store', $store);
try {
//Constructing cache instance
$this->stores[$store] = $this->factory->make(
$this->config->storeClass($store),
$this->config->storeOptions($store)
);
} finally {
$this->benchmark($benchmark);
}
if ($store == $this->config['store'] && !$this->stores[$store]->isAvailable()) {
throw new CacheException(
"Unable to use default store '{$store}', driver is unavailable."
);
}
return $this->stores[$store];
}
/**
* {@inheritdoc}
*
* @throws CacheException
*/
public function createInjection(\ReflectionClass $class, $context = null)
{
if (isset($this->stores[$class->getName()])) {
return $this->stores[$class->getName()];
}
if (!$class->isInstantiable()) {
//Default store
return $this->store();
}
if (!$this->config->hasStore($class->getName())) {
throw new CacheException(
"Unable construct cache store '{$class}', no options found."
);
}
return $this->store($class->getName());
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core\Exceptions;
/**
* General spiral Exception.
*/
interface ExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
/**
* Raised what document class can not be resolved based on set of provided fields or using logic
* method.
*
* @see Document::defineClass();
*/
class DefinitionException extends DocumentException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders\Traits;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Exceptions\BuilderException;
use Spiral\Database\Injections\Expression;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Injections\Parameter;
use Spiral\Database\Injections\ParameterInterface;
/**
* Provides ability to generate QueryCompiler JOIN tokens including ON conditions and table/column
* aliases.
*
* Simple joins (ON userID = users.id):
* $select->join('LEFT', 'info', 'userID', 'users.id');
* $select->leftJoin('info', 'userID', '=', 'users.id');
* $select->rightJoin('info', ['userID' => 'users.id']);
*
* More complex ON conditions:
* $select->leftJoin('info', function($select) {
* $select->on('userID', 'users.id')->orOn('userID', 'users.masterID');
* });
*
* To specify on conditions outside join method use "on" methods.
* $select->leftJoin('info')->on('userID', '=', 'users.id');
*
* On methods will only support conditions based on outer table columns. You can not use parametric
* values here, use "on where" conditions instead.
* $select->leftJoin('info')->on('userID', '=', 'users.id')->onWhere('value', 100);
*
* Arguments and syntax in "on" and "onWhere" conditions is identical to "where" method defined in
* AbstractWhere.
* Attention, "on" and "onWhere" conditions will be applied to last registered join only!
*
* You can also use table aliases and use them in conditions after:
* $select->join('LEFT', 'info as i')->on('i.userID', 'users.id');
* $select->join('LEFT', 'info as i', function($select) {
* $select->on('i.userID', 'users.id')->orOn('i.userID', 'users.masterID');
* });
*
* @see AbstractWhere
*/
trait JoinsTrait
{
/**
* Name/id of last join, every ON and ON WHERE call will be associated with this join.
*
* @var string
*/
private $activeJoin = null;
/**
* Set of join tokens with on and on where conditions associated, must be supported by
* QueryCompilers.
*
* @var array
*/
protected $joinTokens = [];
/**
* Parameters collected while generating ON WHERE tokens, must be in a same order as parameters
* in resulted query. Parameters declared in ON methods will be converted into expressions and
* will not be aggregated.
*
* @see AbstractWhere
* @var array
*/
protected $onParameters = [];
/**
* Register new JOIN with specified type with set of on conditions (linking one table to
* another, no parametric on conditions allowed here).
*
* @param string $type Join type. Allowed values, LEFT, RIGHT, INNER and etc.
* @param string $table Joined table name (without prefix), may include AS statement.
* @param mixed $on Simplified on definition linking table names (no parameters allowed) or
* closure.
* @return $this
* @throws BuilderException
*/
public function join($type, $table, $on = null)
{
$this->joinTokens[$this->activeJoin = $table] = ['type' => strtoupper($type), 'on' => []];
return call_user_func_array([$this, 'on'], array_slice(func_get_args(), 2));
}
/**
* Register new INNER JOIN with set of on conditions (linking one table to another, no
* parametric on conditions allowed here).
*
* @link http://www.w3schools.com/sql/sql_join_inner.asp
* @see join()
* @param string $table Joined table name (without prefix), may include AS statement.
* @param mixed $on Simplified on definition linking table names (no parameters allowed) or
* closure.
* @return $this
* @throws BuilderException
*/
public function innerJoin($table, $on = null)
{
$this->joinTokens[$this->activeJoin = $table] = ['type' => 'INNER', 'on' => []];
return call_user_func_array([$this, 'on'], array_slice(func_get_args(), 1));
}
/**
* Register new RIGHT JOIN with set of on conditions (linking one table to another, no
* parametric on conditions allowed here).
*
* @link http://www.w3schools.com/sql/sql_join_right.asp
* @see join()
* @param string $table Joined table name (without prefix), may include AS statement.
* @param mixed $on Simplified on definition linking table names (no parameters allowed) or
* closure.
* @return $this
* @throws BuilderException
*/
public function rightJoin($table, $on = null)
{
$this->joinTokens[$this->activeJoin = $table] = ['type' => 'RIGHT', 'on' => []];
return call_user_func_array([$this, 'on'], array_slice(func_get_args(), 1));
}
/**
* Register new LEFT JOIN with set of on conditions (linking one table to another, no parametric
* on conditions allowed here).
*
* @link http://www.w3schools.com/sql/sql_join_left.asp
* @see join()
* @param string $table Joined table name (without prefix), may include AS statement.
* @param mixed $on Simplified on definition linking table names (no parameters allowed) or
* closure.
* @return $this
* @throws BuilderException
*/
public function leftJoin($table, $on = null)
{
$this->joinTokens[$this->activeJoin = $table] = ['type' => 'LEFT', 'on' => []];
return call_user_func_array([$this, 'on'], array_slice(func_get_args(), 1));
}
/**
* Register new FULL JOIN with set of on conditions (linking one table to another, no parametric
* on conditions allowed here).
*
* @link http://www.w3schools.com/sql/sql_join_full.asp
* @see join()
* @param string $table Joined table name (without prefix), may include AS statement.
* @param mixed $on Simplified on definition linking table names (no parameters allowed) or
* closure.
* @return $this
* @throws BuilderException
*/
public function fullJoin($table, $on = null)
{
$this->joinTokens[$this->activeJoin = $table] = ['type' => 'FULL', 'on' => []];
return call_user_func_array([$this, 'on'], array_slice(func_get_args(), 1));
}
/**
* Simple ON condition with various set of arguments. Can only be used to link column values
* together, no parametric values allowed.
*
* @param mixed $joined Joined column name or expression.
* @param mixed $operator Foreign column name, if operator specified.
* @param mixed $outer Foreign column name.
* @return $this
* @throws BuilderException
*/
public function on($joined = null, $operator = null, $outer = null)
{
$this->whereToken(
'AND', func_get_args(), $this->joinTokens[$this->activeJoin]['on'],
$this->onWrapper()
);
return $this;
}
/**
* Simple AND ON condition with various set of arguments. Can only be used to link column values
* together, no parametric values allowed.
*
* @param mixed $joined Joined column name or expression.
* @param mixed $operator Foreign column name, if operator specified.
* @param mixed $outer Foreign column name.
* @return $this
* @throws BuilderException
*/
public function andOn($joined = null, $operator = null, $outer = null)
{
$this->whereToken(
'AND', func_get_args(), $this->joinTokens[$this->activeJoin]['on'],
$this->onWrapper()
);
return $this;
}
/**
* Simple OR ON condition with various set of arguments. Can only be used to link column values
* together, no parametric values allowed.
*
* @param mixed $joined Joined column name or expression.
* @param mixed $operator Foreign column name, if operator specified.
* @param mixed $outer Foreign column name.
* @return $this
* @throws BuilderException
*/
public function orOn($joined = null, $operator = null, $outer = null)
{
$this->whereToken(
'AND', func_get_args(), $this->joinTokens[$this->activeJoin]['on'], $this->onWrapper()
);
return $this;
}
/**
* Simple ON WHERE condition with various set of arguments. You can use parametric values in
* such methods.
*
* @see AbstractWhere
* @param string|mixed $joined Joined column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function onWhere($joined, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken(
'AND', func_get_args(), $this->joinTokens[$this->activeJoin]['on'],
$this->whereWrapper()
);
return $this;
}
/**
* Simple AND ON WHERE condition with various set of arguments. You can use parametric values in
* such methods.
*
* @see AbstractWhere
* @param string|mixed $joined Joined column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function andOnWhere($joined, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken(
'AND', func_get_args(), $this->joinTokens[$this->activeJoin]['on'],
$this->whereWrapper()
);
return $this;
}
/**
* Simple OR ON WHERE condition with various set of arguments. You can use parametric values in
* such methods.
*
* @see AbstractWhere
* @param string|mixed $joined Joined column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function orOnWhere($joined, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken(
'AND', func_get_args(), $this->joinTokens[$this->activeJoin]['on'],
$this->whereWrapper()
);
return $this;
}
/**
* Convert various amount of where function arguments into valid where token.
*
* @see AbstractWhere
* @param string $joiner Boolean joiner (AND | OR).
* @param array $parameters Set of parameters collected from where functions.
* @param array $tokens Array to aggregate compiled tokens. Reference.
* @param \Closure|null $wrapper Callback or closure used to wrap/collect every potential
* parameter.
* @throws BuilderException
*/
abstract protected function whereToken(
$joiner,
array $parameters,
&$tokens = [],
callable $wrapper
);
/**
* Convert parameters used in JOIN ON statements into sql expressions.
*
* @return \Closure
*/
private function onWrapper()
{
return function ($parameter) {
if ($parameter instanceof FragmentInterface) {
return $parameter;
}
return new Expression($parameter);
};
}
/**
* Applied to every potential parameter while ON WHERE tokens generation.
*
* @return \Closure
*/
private function whereWrapper()
{
return function ($parameter) {
if ($parameter instanceof FragmentInterface) {
//We are only not creating bindings for plan fragments
if (!$parameter instanceof ParameterInterface && !$parameter instanceof QueryBuilder) {
return $parameter;
}
return $parameter;
}
if (is_array($parameter)) {
throw new BuilderException("Arrays must be wrapped with Parameter instance.");
}
//Wrapping all values with ParameterInterface
if (!$parameter instanceof ParameterInterface) {
$parameter = new Parameter($parameter, Parameter::DETECT_TYPE);
};
//Let's store to sent to driver when needed
$this->onParameters[] = $parameter;
return $parameter;
};
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer;
/**
* SQLServer specific result reader, required due server need additional column for sorting in some
* cases.
*/
class QueryResult extends \Spiral\Database\Query\QueryResult
{
/**
* Helper column used to create limit, offset statements in older versions of sql server.
*/
const ROW_NUMBER_COLUMN = 'spiral_row_number';
/**
* Indication that result includes row number column which should be excluded from results.
*
* @var bool
*/
protected $helperRow = false;
/**
* {@inheritdoc}
*/
public function __construct(\PDOStatement $statement, array $parameters = [])
{
parent::__construct($statement, $parameters);
if ($this->statement->getColumnMeta($this->countColumns() - 1)['name'] == self::ROW_NUMBER_COLUMN) {
$this->helperRow = true;
}
}
/**
* {@inheritdoc}
*/
public function countColumns()
{
return $this->statement->columnCount() + ($this->helperRow ? -1 : 0);
}
/**
* {@inheritdoc}
*/
public function fetch($mode = null)
{
$result = parent::fetch($mode);
!empty($result) && $this->helperRow && array_pop($result);
return $result;
}
/**
* {@inheritdoc}
*/
public function fetchAll($mode = null)
{
if (!$this->helperRow) {
return parent::fetchAll($mode);
}
$result = [];
while ($rowset = $this->fetch($mode)) {
$result[] = $rowset;
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Relations;
use Spiral\Database\Entities\Table;
use Spiral\Database\Exceptions\QueryException;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\Models\EntityInterface;
use Spiral\ORM\Entities\Loaders\ManyToManyLoader;
use Spiral\ORM\Entities\Relation;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* Provides ability to load records related using pivot table, link, unlink and check such records.
* Relation support WHERE_PIVOT conditions.
*/
class ManyToMany extends Relation
{
/**
* Connection errors.
*/
use LoggerTrait;
/**
* Relation type, required to fetch record class from relation definition.
*/
const RELATION_TYPE = RecordEntity::MANY_TO_MANY;
/**
* Indication that relation represent multiple records (HAS_MANY relations).
*/
const MULTIPLE = true;
/**
* Forced value of parent role, used by morphed many to many.
*
* @var string
*/
private $parentRole = '';
/**
* Force parent role name (for morphed relations only).
*
* @param string $role
*/
public function setRole($role)
{
$this->parentRole = $role;
}
/**
* Check if Record(s) associated with this relation. Method can accept one id, array of ids,
* or instance of ActiveRecord. In case of multiple ids provided method will return true only
* if every record is linked to relation.
*
* Attention, WHERE conditions are not involved in has, link and other methods!
*
* Examples:
* $user->tags()->has($tag);
* $user->tags()->has([$tagA, $tagB]);
* $user->tags()->has(1);
* $user->tags()->has([1, 2, 3, 4]);
*
* @param mixed $outer
* @return bool
*/
public function has($outer)
{
$selectQuery = $this->pivotTable()->select()->where($this->wherePivot(
$this->parentKey(),
$this->prepareRecords($outer)
));
//We can use hasEach methods there, but this is more optimal way
return $selectQuery->count() == count($outer);
}
/**
* Link one of multiple related records. You can pass pivotData as additional argument or
* associate it with record id. Connections will only be created not updated, check sync()
* method. Do not forget to pre-populate pivot columns if you using WHERE_PIVOT conditions.
*
* Examples:
* $user->tags()->link(1);
* $user->tags()->link($tag);
* $user->tags()->link([1, 2], ['approved' => true]);
* $user->tags()->link([
* 1 => ['approved' => true],
* 2 => ['approved' => false]
* ]);
*
* Method will not affect state of pre-loaded data! Use reset() method to do that.
*
* @see sync()
* @param mixed $outer
* @param array $pivotData
*/
public function link($outer, array $pivotData = [])
{
//I need different method here
$pivotRows = $this->prepareRecords($outer, $pivotData);
$linkedIDs = $this->linkedIDs(array_keys($pivotRows));
foreach ($pivotRows as $recordID => $pivotRow) {
if (!in_array($recordID, $linkedIDs)) {
/**
* In future this statement should be optimized to use batchInsert in cases when
* set of columns for every record is the same.
*/
try {
$this->pivotTable()->insert($pivotRow);
} catch (QueryException $exception) {
$this->logger()->error($exception->getMessage());
}
}
}
}
/**
* Method is similar to link() except will update pivot columns of alread exists records and
* unlink records not specified in argument. Do not forget to pre-populate pivot columns if you
* using WHERE_PIVOT conditions.
*
* Examples:
* $user->tags()->sync(1);
* $user->tags()->sync($tag);
* $user->tags()->sync([1, 2], ['approved' => true]);
* $user->tags()->sync([
* 1 => ['approved' => true],
* 2 => ['approved' => false]
* ]);
*
* Method will not affect state of pre-loaded data! Use reset() method to do that.
*
* @see link()
* @param mixed $outer
* @param array $pivotData
*/
public function sync($outer, array $pivotData = [])
{
$pivotRows = $this->prepareRecords($outer, $pivotData);
$linkedIDs = $this->linkedIDs([]);
foreach ($pivotRows as $recordID => $pivotRow) {
if (!in_array($recordID, $linkedIDs)) {
try {
$this->pivotTable()->insert($pivotRow);
} catch (QueryException $exception) {
$this->logger()->error($exception->getMessage());
}
} else {
//Updating connection
$this->pivotTable()->update(
$pivotRow,
$this->wherePivot($this->parentKey(), $recordID)
)->run();
}
}
foreach ($linkedIDs as $linkedID) {
if (!isset($pivotRows[$linkedID])) {
//Unlink
$this->unlink($linkedID);
}
}
}
/**
* Method used to unlink one of multiple associated ActiveRecords, method can accept id, list of
* ids or instance of ActiveRecord. Method will return count of affected rows.
*
* Examples:
* $user->tags()->unlink($tag);
* $user->tags()->unlink([$tagA, $tagB]);
* $user->tags()->unlink(1);
* $user->tags()->unlink([1, 2, 3, 4]);
*
* Method will not affect state of pre-loaded data! Use reset() method to do that.
*
* @param mixed $recordID
* @return int
*/
public function unlink($recordID)
{
return $this->pivotTable()->delete($this->wherePivot(
$this->parentKey(),
array_keys($this->prepareRecords($recordID))
))->run();
}
/**
* Unlink every associated record, method will return amount of affected rows. Method will not
* affect state of pre-loaded data! Use reset() method to do that.
*
* @return int
*/
public function unlinkAll()
{
return $this->pivotTable()->delete($this->wherePivot($this->parentKey(), null))->run();
}
/**
* {@inheritdoc}
*/
protected function createSelector()
{
//For Many-to-Many relation we have to use custom loader to parse data, this is ONLY for
//this type of relation
$loader = new ManyToManyLoader($this->orm, '', $this->definition);
$selector = $loader->createSelector($this->parentRole())->where(
$loader->pivotAlias() . '.' . $this->definition[RecordEntity::THOUGHT_INNER_KEY],
$this->parentKey()
);
//Conditions
if (!empty($this->definition[RecordEntity::WHERE_PIVOT])) {
//Custom where pivot conditions
$selector->onWhere($this->mountAlias(
$loader->pivotAlias(),
$this->definition[RecordEntity::WHERE_PIVOT]
));
}
if (!empty($this->definition[RecordEntity::WHERE])) {
//Custom where pivot conditions
$selector->where($this->mountAlias(
$loader->getAlias(),
$this->definition[RecordEntity::WHERE]
));
}
return $selector;
}
/**
* {@inheritdoc}
*/
protected function mountRelation(EntityInterface $record)
{
//Nothing to do, every fetched record should be already linked
return $record;
}
/**
* Helper method used to create valid WHERE query for deletes and updates in pivot table.
*
* @param mixed|array $innerKey
* @param mixed|array $outerKey
* @return array
*/
protected function wherePivot($innerKey, $outerKey)
{
$query = [];
if (!empty($this->definition[RecordEntity::MORPH_KEY])) {
$query[$this->definition[RecordEntity::MORPH_KEY]] = $this->parentRole();
}
if (!empty($innerKey)) {
$query[$this->definition[RecordEntity::THOUGHT_INNER_KEY]] = $innerKey;
}
if (!empty($this->definition[RecordEntity::WHERE_PIVOT])) {
//Custom where pivot conditions
$query = $query + $this->mountAlias(
$this->definition[RecordEntity::PIVOT_TABLE],
$this->definition[RecordEntity::WHERE_PIVOT]
);
}
if (!empty($outerKey)) {
$query[$this->definition[RecordEntity::THOUGHT_OUTER_KEY]] = is_array($outerKey)
? ['IN' => $outerKey]
: $outerKey;
}
return $query;
}
/**
* Return array of record ids associated with pivot columns.
*
* @param mixed $records
* @param array $pivotData
* @return array
* @throws RelationException
*/
protected function prepareRecords($records, array $pivotData = [])
{
if (is_scalar($records)) {
return [
$records => $this->pivotRow($records, $pivotData)
];
}
if (is_array($records)) {
$result = [];
foreach ($records as $key => $value) {
if (is_scalar($value)) {
$result[$value] = $this->pivotRow($value, $pivotData);
} else {
//Specified in key => pivotData format.
$result[$key] = $this->pivotRow($key, $value + $pivotData);
}
}
return $result;
}
if (is_object($records) && get_class($records) != $this->getClass()) {
throw new RelationException(
"Relation can work only with instances of '{$this->getClass()}' record."
);
}
$records = $records->getField($this->definition[RecordEntity::OUTER_KEY]);
return [
$records => $this->pivotRow($records, $pivotData)
];
}
/**
* Create data set to be inserted/updated into pivot table.
*
* @param mixed $outerKey
* @param array $pivotData
* @return array
*/
protected function pivotRow($outerKey, array $pivotData = [])
{
$data = [
$this->definition[RecordEntity::THOUGHT_INNER_KEY] => $this->parentKey(),
$this->definition[RecordEntity::THOUGHT_OUTER_KEY] => $outerKey
];
if (!empty($this->definition[RecordEntity::MORPH_KEY])) {
$data[$this->definition[RecordEntity::MORPH_KEY]] = $this->parentRole();
}
return $data + $pivotData;
}
/**
* Get parent role. Role can be redefined by setRole method.
*
* @return string
*/
protected function parentRole()
{
return !empty($this->parentRole) ? $this->parentRole : $this->parent->recordRole();
}
/**
* Parent record inner key value.
*
* @return mixed
*/
protected function parentKey()
{
return $this->parent->getField($this->definition[RecordEntity::INNER_KEY]);
}
/**
* Instance of DBAL\Table associated with relation pivot table.
*
* @return Table
*/
protected function pivotTable()
{
return $this->orm->database($this->definition[ORM::R_DATABASE])->table(
$this->definition[RecordEntity::PIVOT_TABLE]
);
}
/**
* Fetch keys of linked records.
*
* @param array $outerIDs
* @return array
*/
protected function linkedIDs(array $outerIDs)
{
$selectQuery = $this->pivotTable()->where(
$this->wherePivot($this->parentKey(), $outerIDs)
);
$selectQuery->columns($this->definition[RecordEntity::THOUGHT_OUTER_KEY]);
$result = [];
foreach ($selectQuery->run() as $row) {
//Let's return outer key value as result
$result[] = $row[$this->definition[RecordEntity::THOUGHT_OUTER_KEY]];
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Database;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\Driver;
use Spiral\Database\TableInterface;
class DatabaseTest extends \PHPUnit_Framework_TestCase
{
public function testDatabase()
{
/**
* @var Driver|\PHPUnit_Framework_MockObject_MockObject $driver
*/
$driver = $this->getMockBuilder(Driver::class)
->disableOriginalConstructor()
->getMock();
$driver->method('getType')->will($this->returnValue('test-driver'));
$database = new Database($driver, 'test', 'prefix_');
$this->assertEquals('test', $database->getName());
$this->assertEquals($driver, $database->driver());
$this->assertEquals('prefix_', $database->getPrefix());
$this->assertEquals('test-driver', $database->getType());
}
public function testQuery()
{
/**
* @var Driver|\PHPUnit_Framework_MockObject_MockObject $driver
*/
$driver = $this->getMockBuilder(Driver::class)
->disableOriginalConstructor()
->getMock();
$driver->expects($this->once())->method('query')->with('test query');
$database = new Database($driver, 'test', 'prefix_');
$database->query('test query');
}
public function testStatement()
{
/**
* @var Driver|\PHPUnit_Framework_MockObject_MockObject $driver
*/
$driver = $this->getMockBuilder(Driver::class)
->disableOriginalConstructor()
->getMock();
$driver->expects($this->once())->method('statement')->with('test statement', [1, 2, 3]);
$database = new Database($driver, 'test', 'prefix_');
$database->statement('test statement', [1, 2, 3]);
}
public function testHasTable()
{
/**
* @var Driver|\PHPUnit_Framework_MockObject_MockObject $driver
*/
$driver = $this->getMockBuilder(Driver::class)
->disableOriginalConstructor()
->getMock();
$driver->expects($this->once())->method('hasTable')->with('prefix_table')->will(
$this->returnValue(true)
);
$database = new Database($driver, 'test', 'prefix_');
$this->assertTrue($database->hasTable('table'));
}
public function testTable()
{
/**
* @var Driver|\PHPUnit_Framework_MockObject_MockObject $driver
*/
$driver = $this->getMockBuilder(Driver::class)
->disableOriginalConstructor()
->getMock();
$database = new Database($driver, 'test', 'prefix_');
$driver->expects($this->once())->method('hasTable')->with('prefix_table')->will(
$this->returnValue(true)
);
$this->assertInstanceOf(TableInterface::class, $table = $database->table('table'));
$this->assertEquals('table', $table->getName());
$this->assertEquals('prefix_table', $table->realName());
$this->assertTrue($table->exists());
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Validation\Checker;
/**
* Validate different addresses: email, url and etc.
*/
class AddressChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"email" => "[[Must be a valid email address.]]",
"url" => "[[Must be a valid URL address.]]",
];
/**
* Check if email is valid.
*
* @link http://www.ietf.org/rfc/rfc2822.txt
* @param string
* @return bool
*/
public function email($email)
{
return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
}
/**
* Check if URL is valid.
*
* @link http://www.faqs.org/rfcs/rfc2396.html
* @param string $url
* @param bool $requireScheme If true, this will require having a protocol definition.
* @return bool
*/
public function url($url, $requireScheme = true)
{
if (
!$requireScheme
&& stripos($url, 'http://') === false && stripos($url, 'https://') === false
) {
//Forcing scheme (not super great idea)
$url = 'http://' . $url;
}
return (bool)filter_var($url, FILTER_VALIDATE_URL);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Validation\Checker;
/**
* Variable type checks.
*/
class TypeChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"notEmpty" => "[[This field is required.]]",
"boolean" => "[[Not a valid boolean.]]",
"datetime" => "[[Not a valid datetime.]]",
"timezone" => "[[Not a valid timezone.]]"
];
/**
* Value should not be empty.
*
* @param mixed $value
* @param bool $trim
* @return bool
*/
public function notEmpty($value, $trim = true)
{
if ($trim && is_string($value) && strlen(trim($value)) == 0) {
return false;
}
return !empty($value);
}
/**
* Value has to be boolean or integer[0,1].
*
* @param mixed $value
* @return bool
*/
public function boolean($value)
{
return is_bool($value) || (is_numeric($value) && ($value === 0 || $value === 1));
}
/**
* Value has to be valid datetime definition including numeric timestamp.
*
* @param mixed $value
* @return bool
*/
public function datetime($value)
{
if (!is_scalar($value)) {
return false;
}
if (is_numeric($value)) {
return true;
}
return (int)strtotime($value) != 0;
}
/**
* Value has to be valid timezone.
*
* @param mixed $value
* @return bool
*/
public function timezone($value)
{
return in_array($value, \DateTimeZone::listIdentifiers());
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\HippocampusInterface;
use Spiral\Debug\Traits\BenchmarkTrait;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\Files\FilesInterface;
use Spiral\Tokenizer\Configs\TokenizerConfig;
use Spiral\Tokenizer\Reflections\ReflectionFile;
use Spiral\Tokenizer\Traits\TokensTrait;
use Symfony\Component\Finder\Finder;
/**
* Default implementation of spiral tokenizer support while and blacklisted directories and etc.
*/
class Tokenizer extends Component implements SingletonInterface, TokenizerInterface, InjectorInterface
{
/**
* Required traits.
*/
use LoggerTrait, BenchmarkTrait, TokensTrait;
/**
* Declares to IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* Memory section.
*/
const MEMORY_LOCATION = 'tokenizer';
/**
* @var TokenizerConfig
*/
protected $config = null;
/**
* @invisible
* @var FilesInterface
*/
protected $files = null;
/**
* @invisible
* @var HippocampusInterface
*/
protected $memory = null;
/**
* Tokenizer constructor.
*
* @param FilesInterface $files
* @param TokenizerConfig $config
* @param HippocampusInterface $runtime
*/
public function __construct(
FilesInterface $files,
TokenizerConfig $config,
HippocampusInterface $runtime
) {
$this->files = $files;
$this->config = $config;
$this->memory = $runtime;
}
/**
* {@inheritdoc}
*
* @deprecated this method creates looped dependencies, drop it
*/
public function fetchTokens($filename)
{
return $this->normalizeTokens(token_get_all($this->files->read($filename)));
}
/**
* {@inheritdoc}
*/
public function fileReflection($filename)
{
$fileMD5 = $this->files->md5($filename = $this->files->normalizePath($filename));
$reflection = new ReflectionFile(
$this->fetchTokens($filename),
(array)$this->memory->loadData($fileMD5, self::MEMORY_LOCATION)
);
//Let's save to cache
$this->memory->saveData($fileMD5, $reflection->exportSchema(), static::MEMORY_LOCATION);
return $reflection;
}
/**
* Get pre-configured class locator.
*
* @param array $directories
* @param array $exclude
* @param Finder $finder
* @return ClassLocator
*/
public function classLocator(
array $directories = [],
array $exclude = [],
Finder $finder = null
) {
$finder = !empty($finder) ?: new Finder();
if (empty($directories)) {
$directories = $this->config->getDirectories();
}
if (empty($exclude)) {
$exclude = $this->config->getExcludes();
}
//Configuring finder
return new ClassLocator(
$this,
$finder->files()->in($directories)->exclude($exclude)->name('*.php')
);
}
/**
* Get pre-configured invocation locator.
*
* @param array $directories
* @param array $exclude
* @param Finder $finder
* @return ClassLocator
*/
public function invocationLocator(
array $directories = [],
array $exclude = [],
Finder $finder = null
) {
$finder = !empty($finder) ?: new Finder();
if (empty($directories)) {
$directories = $this->config->getDirectories();
}
if (empty($exclude)) {
$exclude = $this->config->getExcludes();
}
//Configuring finder
return new InvocationLocator(
$this,
$finder->files()->in($directories)->exclude($exclude)->name('*.php')
);
}
/**
* {@inheritdoc}
*/
public function createInjection(\ReflectionClass $class, $context = null)
{
if ($class->isSubclassOf(ClassLocatorInterface::class)) {
return $this->classLocator();
} else {
return $this->invocationLocator();
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas;
use Spiral\Core\Component;
/**
* Compares two table states.
*/
class Comparator extends Component
{
/**
* @var TableState
*/
private $initial = null;
/**
* @var TableState
*/
private $current = null;
/**
* @param TableState $initial
* @param TableState $current
*/
public function __construct(TableState $initial, TableState $current)
{
$this->initial = $initial;
$this->current = $current;
}
/**
* @return bool
*/
public function hasChanges()
{
if ($this->current->getName() != $this->initial->getName()) {
return true;
}
if ($this->current->getPrimaryKeys() != $this->initial->getPrimaryKeys()) {
return true;
}
$difference = [
count($this->addedColumns()),
count($this->droppedColumns()),
count($this->alteredColumns()),
count($this->addedIndexes()),
count($this->droppedIndexes()),
count($this->alteredIndexes()),
count($this->addedForeigns()),
count($this->droppedForeigns()),
count($this->alteredForeigns())
];
return array_sum($difference) != 0;
}
/**
* @return AbstractColumn[]
*/
public function addedColumns()
{
$difference = [];
foreach ($this->current->getColumns() as $name => $column) {
if (!$this->initial->knowsColumn($name)) {
$difference[] = $column;
}
}
return $difference;
}
/**
* @return AbstractColumn[]
*/
public function droppedColumns()
{
$difference = [];
foreach ($this->initial->getColumns() as $name => $column) {
if (!$this->current->knowsColumn($name)) {
$difference[] = $column;
}
}
return $difference;
}
/**
* Returns array where each value contain current and initial element state.
*
* @return array
*/
public function alteredColumns()
{
$difference = [];
$initialColumns = $this->initial->getColumns();
foreach ($this->current->getColumns() as $name => $column) {
if (!$this->initial->knowsColumn($name)) {
//Added into schema
continue;
}
if (!$column->compare($initialColumns[$name])) {
$difference[] = [$column, $initialColumns[$name]];
}
}
return $difference;
}
/**
* @return AbstractIndex[]
*/
public function addedIndexes()
{
$difference = [];
foreach ($this->current->getIndexes() as $name => $index) {
if (!$this->initial->knowsIndex($name)) {
$difference[] = $index;
}
}
return $difference;
}
/**
* @return AbstractIndex[]
*/
public function droppedIndexes()
{
$difference = [];
foreach ($this->initial->getIndexes() as $name => $index) {
if (!$this->current->knowsIndex($name)) {
$difference[] = $index;
}
}
return $difference;
}
/**
* Returns array where each value contain current and initial element state.
*
* @return array
*/
public function alteredIndexes()
{
$difference = [];
$initialIndexes = $this->initial->getIndexes();
foreach ($this->current->getIndexes() as $name => $index) {
if (!$this->initial->knowsIndex($name)) {
//Added into schema
continue;
}
if (!$index->compare($initialIndexes[$name])) {
$difference[] = [$index, $initialIndexes[$name]];
}
}
return $difference;
}
/**
* @return AbstractReference[]
*/
public function addedForeigns()
{
$difference = [];
foreach ($this->current->getForeigns() as $name => $foreign) {
if (!$this->initial->knowsForeign($name)) {
$difference[] = $foreign;
}
}
return $difference;
}
/**
* @return AbstractReference[]
*/
public function droppedForeigns()
{
$difference = [];
foreach ($this->initial->getForeigns() as $name => $foreign) {
if (!$this->current->knowsForeign($name)) {
$difference[] = $foreign;
}
}
return $difference;
}
/**
* Returns array where each value contain current and initial element state.
*
* @return array
*/
public function alteredForeigns()
{
$difference = [];
$initialForeigns = $this->initial->getForeigns();
foreach ($this->current->getForeigns() as $name => $foreign) {
if (!$this->initial->knowsForeign($name)) {
//Added into schema
continue;
}
if (!$foreign->compare($initialForeigns[$name])) {
$difference[] = [$foreign, $initialForeigns[$name]];
}
}
return $difference;
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'name' => [
'initial' => $this->initial->getName(),
'current' => $this->current->getName()
],
'columns' => [
'added' => $this->addedColumns(),
'dropped' => $this->droppedColumns(),
'altered' => $this->alteredColumns(),
],
'indexes' => [
'added' => $this->addedIndexes(),
'dropped' => $this->droppedIndexes(),
'altered' => $this->alteredIndexes(),
],
'foreignKeys' => [
'added' => $this->addedForeigns(),
'dropped' => $this->droppedForeigns(),
'altered' => $this->alteredForeigns()
]
];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders\Prototypes;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Exceptions\BuilderException;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Injections\Parameter;
use Spiral\Database\Injections\ParameterInterface;
/**
* Abstract query with WHERE conditions generation support. Provides simplified way to generate
* WHERE tokens using set of where methods. Class support different where conditions, simplified
* definitions
* (using arrays) and closures to describe nested conditions:
*
* 1) Simple token/nested query or expression
* $select->where(new SQLFragment('(SELECT count(*) from `table`)'));
*
* 2) Simple assessment
* $select->where('column', $value);
* $select->where('column', new SQLFragment('CONCAT(columnA, columnB)'));
*
* 3) Assessment with specified operator (operator will be converted to uppercase automatically)
* $select->where('column', '=', $value);
* $select->where('column', 'IN', [1, 2, 3]);
* $select->where('column', 'LIKE', $string);
* $select->where('column', 'IN', new SQLFragment('(SELECT id from `table` limit 1)'));
*
* 4) Between and not between statements
* $select->where('column', 'between', 1, 10);
* $select->where('column', 'not between', 1, 10);
* $select->where('column', 'not between', new SQLFragment('MIN(price)'), $maximum);
*
* 5) Closure with nested conditions
* $this->where(function(AbstractWhere $select){
* $select->where("name", "Wolfy-J")->orWhere("balance", ">", 100)
* });
*
* 6) Simplified array based condition definition
* $select->where(["column" => 1]);
* $select->where(["column" => [
* ">" => 1,
* "<" => 10
* ]]);
*
* Tokens "@or" and "@and" used to aggregate nested conditions.
* $select->where([
* "@or" => [
* ["id" => 1],
* ["column" => ["like" => "name"]]
* ]
* ]);
*
* $select->where([
* "@or" => [
* ["id" => 1], ["id" => 2], ["id" => 3], ["id" => 4], ["id" => 5]
* ],
* "column" => [
* "like" => "name"
* ],
* "x" => [
* ">" => 1,
* "<" => 10
* ]
* ]);
*
* To describe between or not between condition use array with two arguments.
* $select->where([
* "column" => [
* "between" => [1, 100]
* ]
* ]);
*/
abstract class AbstractWhere extends QueryBuilder
{
/**
* Tokens for nested OR and AND conditions.
*/
const TOKEN_AND = "@AND";
const TOKEN_OR = "@OR";
/**
* Set of generated where tokens, format must be supported by QueryCompilers.
*
* @var array
*/
protected $whereTokens = [];
/**
* Parameters collected while generating WHERE tokens, must be in a same order as parameters
* in resulted query.
*
* @var array
*/
protected $whereParameters = [];
/**
* Simple WHERE condition with various set of arguments.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function where($identifier, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken('AND', func_get_args(), $this->whereTokens, $this->whereWrapper());
return $this;
}
/**
* Simple AND WHERE condition with various set of arguments.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function andWhere($identifier, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken('AND', func_get_args(), $this->whereTokens, $this->whereWrapper());
return $this;
}
/**
* Simple OR WHERE condition with various set of arguments.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function orWhere($identifier, $variousA = [], $variousB = null, $variousC = null)
{
$this->whereToken('OR', func_get_args(), $this->whereTokens, $this->whereWrapper());
return $this;
}
/**
* Convert various amount of where function arguments into valid where token.
*
* @see AbstractWhere
* @param string $joiner Boolean joiner (AND | OR).
* @param array $parameters Set of parameters collected from where functions.
* @param array $tokens Array to aggregate compiled tokens. Reference.
* @param callable $wrapper Callback or closure used to wrap/collect every potential
* parameter.
* @throws BuilderException
*/
protected function whereToken($joiner, array $parameters, &$tokens = [], callable $wrapper)
{
list($identifier, $valueA, $valueB, $valueC) = $parameters + array_fill(0, 5, null);
if (empty($identifier)) {
//Nothing to do
return;
}
//Where conditions specified in array form
if (is_array($identifier)) {
if (count($identifier) == 1) {
$this->arrayWhere(
$joiner == 'AND' ? self::TOKEN_AND : self::TOKEN_OR,
$identifier,
$tokens,
$wrapper
);
return;
}
$tokens[] = [$joiner, '('];
$this->arrayWhere(self::TOKEN_AND, $identifier, $tokens, $wrapper);
$tokens[] = ['', ')'];
return;
}
if ($identifier instanceof \Closure) {
$tokens[] = [$joiner, '('];
call_user_func($identifier, $this, $joiner, $wrapper);
$tokens[] = ['', ')'];
return;
}
if ($identifier instanceof QueryBuilder) {
//Will copy every parameter from QueryBuilder
$wrapper($identifier);
}
switch (count($parameters)) {
case 1:
//AND|OR [identifier: sub-query]
$tokens[] = [$joiner, $identifier];
break;
case 2:
//AND|OR [identifier] = [valueA]
$tokens[] = [$joiner, [$identifier, '=', $wrapper($valueA)]];
break;
case 3:
//AND|OR [identifier] [valueA: OPERATION] [valueA]
$tokens[] = [$joiner, [$identifier, strtoupper($valueA), $wrapper($valueB)]];
break;
case 4:
//BETWEEN or NOT BETWEEN
$valueA = strtoupper($valueA);
if (!in_array($valueA, ['BETWEEN', 'NOT BETWEEN'])) {
throw new BuilderException(
'Only "BETWEEN" or "NOT BETWEEN" can define second comparasions value.'
);
}
//AND|OR [identifier] [valueA: BETWEEN|NOT BETWEEN] [valueB] [valueC]
$tokens[] = [$joiner, [$identifier, $valueA, $wrapper($valueB), $wrapper($valueC)]];
}
}
/**
* Convert simplified where definition into valid set of where tokens.
*
* @see AbstractWhere
* @param string $grouper Grouper type (see self::TOKEN_AND, self::TOKEN_OR).
* @param array $where Simplified where definition.
* @param array $tokens Array to aggregate compiled tokens. Reference.
* @param callable $wrapper Callback or closure used to wrap/collect every potential
* parameter.
* @throws BuilderException
*/
private function arrayWhere($grouper, array $where, &$tokens, callable $wrapper)
{
$joiner = ($grouper == self::TOKEN_AND ? 'AND' : 'OR');
foreach ($where as $key => $value) {
$token = strtoupper($key);
//Grouping identifier (@OR, @AND), MongoDB like style
if ($token == self::TOKEN_AND || $token == self::TOKEN_OR) {
$tokens[] = [$joiner, '('];
foreach ($value as $nested) {
if (count($nested) == 1) {
$this->arrayWhere($token, $nested, $tokens, $wrapper);
continue;
}
$tokens[] = [$token == self::TOKEN_AND ? 'AND' : 'OR', '('];
$this->arrayWhere(self::TOKEN_AND, $nested, $tokens, $wrapper);
$tokens[] = ['', ')'];
}
$tokens[] = ['', ')'];
continue;
}
//AND|OR [name] = [value]
if (!is_array($value)) {
$tokens[] = [$joiner, [$key, '=', $wrapper($value)]];
continue;
}
if (count($value) > 1) {
//Multiple values to be joined by AND condition (x = 1, x != 5)
$tokens[] = [$joiner, '('];
$this->builtConditions('AND', $key, $value, $tokens, $wrapper);
$tokens[] = ['', ')'];
} else {
$this->builtConditions($joiner, $key, $value, $tokens, $wrapper);
}
}
return;
}
/**
* Build set of conditions for specified identifier.
*
* @param string $innerJoiner Inner boolean joiner.
* @param string $key Column identifier.
* @param array $where Operations associated with identifier.
* @param array $tokens Array to aggregate compiled tokens. Reference.
* @param callable $wrapper Callback or closure used to wrap/collect every potential
* parameter.
* @return array
*/
private function builtConditions($innerJoiner, $key, $where, &$tokens, callable $wrapper)
{
foreach ($where as $operation => $value) {
if (is_numeric($operation)) {
throw new BuilderException("Nested conditions should have defined operator.");
}
$operation = strtoupper($operation);
if (!in_array($operation, ['BETWEEN', 'NOT BETWEEN'])) {
//AND|OR [name] [OPERATION] [nestedValue]
$tokens[] = [$innerJoiner, [$key, $operation, $wrapper($value)]];
continue;
}
/**
* Between and not between condition described using array of [left, right] syntax.
*/
if (!is_array($value) || count($value) != 2) {
throw new BuilderException(
"Exactly 2 array values are required for between statement."
);
}
$tokens[] = [
//AND|OR [name] [BETWEEN|NOT BETWEEN] [value 1] [value 2]
$innerJoiner,
[$key, $operation, $wrapper($value[0]), $wrapper($value[1])]
];
}
return $tokens;
}
/**
* Applied to every potential parameter while where tokens generation. Used to prepare and
* collect where parameters.
*
* @return \Closure
*/
private function whereWrapper()
{
return function ($parameter) {
if ($parameter instanceof FragmentInterface) {
//We are only not creating bindings for plan fragments
if (!$parameter instanceof ParameterInterface && !$parameter instanceof QueryBuilder) {
return $parameter;
}
}
if (is_array($parameter)) {
throw new BuilderException("Arrays must be wrapped with Parameter instance.");
}
//Wrapping all values with ParameterInterface
if (!$parameter instanceof ParameterInterface) {
$parameter = new Parameter($parameter, Parameter::DETECT_TYPE);
};
//Let's store to sent to driver when needed
$this->whereParameters[] = $parameter;
return $parameter;
};
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
use Spiral\Models\Exceptions\EntityExceptionInterface;
/**
* Represents generic "ActiveRecord" like patten.
*/
interface ActiveEntityInterface extends IdentifiedInterface
{
/**
* Save entity content into it's primary storage and return true if operation went successfully.
*
* @param bool $validate
* @return bool
* @throws EntityExceptionInterface
*/
public function save($validate = null);
/**
* Delete entity from it's primary storage, entity object must not be used anymore after that
* operation.
*/
public function delete();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage\Configs;
use Spiral\Core\InjectableConfig;
use Spiral\Core\Traits\Config\AliasTrait;
/**
* Storage manager configuration.
*/
class StorageConfig extends InjectableConfig
{
use AliasTrait;
/**
* Configuration section.
*/
const CONFIG = 'storage';
/**
* @var array
*/
protected $config = [
'servers' => [],
'buckets' => []
];
/**
* @param string $server
* @return bool
*/
public function hasServer($server)
{
return isset($this->config['servers'][$server]);
}
/**
* @param string $server
* @return string
*/
public function serverClass($server)
{
return $this->config['servers'][$server]['class'];
}
/**
* @param string $server
* @return array
*/
public function serverOptions($server)
{
return $this->config['servers'][$server];
}
/**
* @return array
*/
public function getBuckets()
{
return $this->config['buckets'];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Syntaxes;
use Spiral\Stempler\Exceptions\SyntaxException;
use Spiral\Stempler\Exporters\AttributesExporter;
use Spiral\Stempler\HtmlTokenizer;
use Spiral\Stempler\Importers\Aliaser;
use Spiral\Stempler\Importers\Bundler;
use Spiral\Stempler\Importers\Prefixer;
use Spiral\Stempler\Importers\Stopper;
use Spiral\Stempler\Supervisor;
use Spiral\Stempler\SyntaxInterface;
/**
* Default Stempler syntax - Woo. Provides ability to define blocks, extends and includes.
*/
class DarkSyntax implements SyntaxInterface
{
/**
* Path attribute in extends and other nodes.
*/
const PATH_ATTRIBUTE = 'path';
/**
* @var bool
*/
private $strict = true;
/**
* Stempler syntax options, syntax and names. Every option is required.
*
* @todo Something with DTD? Seems compatible.
* @var array
*/
protected $constructions = [
self::TYPE_BLOCK => ['block:', 'section:', 'yield:', 'define:'],
self::TYPE_EXTENDS => [
'extends:',
'extends',
'dark:extends',
'layout:extends'
],
self::TYPE_IMPORTER => ['dark:use', 'use', 'node:use', 'stempler:use']
];
/**
* @param bool $strict
*/
public function __construct($strict = true)
{
$this->strict = $strict;
}
/**
* {@inheritdoc}
*/
public function tokenType(array $token, &$name = null)
{
$name = $token[HtmlTokenizer::TOKEN_NAME];
foreach ($this->constructions as $type => $prefixes) {
foreach ($prefixes as $prefix) {
if (strpos($name, $prefix) === 0) {
//We found prefix pointing to needed behaviour
$name = substr($name, strlen($prefix));
return $type;
}
}
}
return self::TYPE_NONE;
}
/**
* {@inheritdoc}
*/
public function resolvePath(array $token)
{
$type = $this->tokenType($token, $name);
if (isset($token[HtmlTokenizer::TOKEN_ATTRIBUTES][static::PATH_ATTRIBUTE])) {
return $token[HtmlTokenizer::TOKEN_ATTRIBUTES][static::PATH_ATTRIBUTE];
}
if ($type == self::TYPE_EXTENDS && isset($token[HtmlTokenizer::TOKEN_ATTRIBUTES]['layout'])) {
return $token[HtmlTokenizer::TOKEN_ATTRIBUTES]['layout'];
}
return $name;
}
/**
* {@inheritdoc}
*/
public function isStrict()
{
return $this->strict;
}
/**
* {@inheritdoc}
*/
public function createImporter(array $token, Supervisor $supervisor)
{
//Fetching path
$path = $this->resolvePath($token);
if (empty($attributes = $token[HtmlTokenizer::TOKEN_ATTRIBUTES])) {
throw new SyntaxException("Invalid import element syntax, attributes missing.", $token);
}
/**
* <dark:use bundle="path-to-bundle"/>
*/
if (isset($attributes['bundle'])) {
$path = $attributes['bundle'];
return new Bundler($supervisor, $path, $token);
}
/**
* <dark:use path="path-to-element" as="tag"/>
* <dark:use path="path-to-element" element="tag"/>
*/
if (isset($attributes['element']) || isset($attributes['as'])) {
$alias = isset($attributes['element']) ? $attributes['element'] : $attributes['as'];
return new Aliaser($alias, $path);
}
//Now we have to decide what importer to use
if (isset($attributes['namespace']) || isset($attributes['prefix'])) {
if (strpos($path, '*') === false) {
throw new SyntaxException(
"Path in namespace/prefix import must include start symbol.", $token
);
}
$prefix = isset($attributes['namespace'])
? $attributes['namespace'] . ':'
: $attributes['prefix'];
return new Prefixer($prefix, $path);
}
if (isset($attributes['stop'])) {
return new Stopper($attributes['stop']);
}
throw new SyntaxException("Undefined use element.", $token);
}
/**
* {@inheritdoc}
*/
public function blockExporters()
{
return [
new AttributesExporter()
];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Exceptions;
use Spiral\Core\Exceptions\RuntimeException;
/**
* Error while performing migration.
*/
class MigrationException extends RuntimeException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Database;
use Spiral\Database\Drivers\MySQL\MySQLDriver;
use Spiral\Database\Drivers\SQLServer\SQLServerDriver;
use Spiral\Database\Entities\PDODriver;
use Spiral\Database\Entities\Quoter;
class QuoterTest extends \PHPUnit_Framework_TestCase
{
public function testPrefixless()
{
$quoter = $this->quoter();
$this->assertEquals('*', $quoter->quote('*'));
$quoter->reset();
$this->assertEquals('"column"', $quoter->quote('column'));
$quoter->reset();
$this->assertEquals('"table"."column"', $quoter->quote('table.column'));
$quoter->reset();
$this->assertEquals('"table".*', $quoter->quote('table.*'));
$quoter->reset();
$this->assertEquals('"table_name"', $quoter->quote('table_name', true));
$quoter->reset();
$this->assertEquals(
'"table"."column" AS "column_alias"',
$quoter->quote('table.column AS column_alias')
);
$quoter->reset();
$this->assertEquals(
'"table_name" AS "table_name"',
$quoter->quote('table_name AS table_name', true)
);
}
public function testPrefixlessAggregations()
{
$quoter = $this->quoter();
$this->assertEquals('COUNT(*)', $quoter->quote('COUNT(*)'));
$quoter->reset();
$this->assertEquals('SUM("column")', $quoter->quote('SUM(column)'));
$quoter->reset();
$this->assertEquals('MIN("table"."column")', $quoter->quote('MIN(table.column)'));
$quoter->reset();
$this->assertEquals(
'AVG("table"."column") AS "column_alias"',
$quoter->quote('AVG(table.column) AS column_alias')
);
}
public function testPrefixlessOperations()
{
$quoter = $this->quoter();
$this->assertEquals('"column_a" + "column_b"', $quoter->quote('column_a + column_b'));
$quoter->reset();
$this->assertEquals('"table"."column" * 10', $quoter->quote('table.column * 10'));
$quoter->reset();
$this->assertEquals(
'("table"."column" + "some_column") / "other_table"."column_b"',
$quoter->quote('(table.column + some_column) / other_table.column_b')
);
}
public function testPrefixes()
{
$quoter = $this->quoter('p_');
$this->assertEquals('*', $quoter->quote('*'));
$quoter->reset();
$this->assertEquals('"column"', $quoter->quote('column'));
$quoter->reset();
$this->assertEquals('"p_table"."column"', $quoter->quote('table.column'));
$quoter->reset();
$this->assertEquals('"p_table".*', $quoter->quote('table.*'));
$quoter->reset();
$this->assertEquals('"p_table_name"', $quoter->quote('table_name', true));
$quoter->reset();
$this->assertEquals(
'"p_table"."column" AS "column_alias"',
$quoter->quote('table.column AS column_alias')
);
$quoter->reset();
$this->assertEquals(
'"p_table_name" AS "table_name"',
$quoter->quote('table_name AS table_name', true)
);
}
public function testPrefixesAggregations()
{
$quoter = $this->quoter('p_');
$this->assertEquals('COUNT(*)', $quoter->quote('COUNT(*)'));
$quoter->reset();
$this->assertEquals('SUM("column")', $quoter->quote('SUM(column)'));
$quoter->reset();
$this->assertEquals('MIN("p_table"."column")', $quoter->quote('MIN(table.column)'));
$quoter->reset();
$this->assertEquals(
'AVG("p_table"."column") AS "column_alias"',
$quoter->quote('AVG(table.column) AS column_alias')
);
}
public function testPrefixesOperations()
{
$quoter = $this->quoter('p_');
$this->assertEquals('"column_a" + "column_b"', $quoter->quote('column_a + column_b'));
$quoter->reset();
$this->assertEquals('"p_table"."column" * 10', $quoter->quote('table.column * 10'));
$quoter->reset();
$this->assertEquals(
'("p_table"."column" + "some_column") / "p_other_table"."column_b" AS "xxx"',
$quoter->quote('(table.column + some_column) / other_table.column_b AS xxx')
);
}
public function testAliases()
{
$quoter = $this->quoter('p_');
$this->assertEquals('"p_table"."column"', $quoter->quote('table.column'));
$this->assertEquals('"p_table_name"', $quoter->quote('table_name', true));
$this->assertEquals(
'"p_table_name" AS "bubble"',
$quoter->quote('table_name AS bubble', true));
$this->assertEquals(
'"bubble"."column" AS "column_alias"',
$quoter->quote('bubble.column AS column_alias')
);
$this->assertEquals(
'"p_table_name" AS "table_name"',
$quoter->quote('table_name AS table_name', true)
);
$this->assertEquals('"table_name"."column"', $quoter->quote('table_name.column'));
$quoter->reset();
$this->assertEquals('"p_table_name"."column"', $quoter->quote('table_name.column'));
$this->assertEquals(
'"p_bubble"."column" AS "column_alias"',
$quoter->quote('bubble.column AS column_alias')
);
}
public function testAliasesAggregations()
{
$quoter = $this->quoter('p_');
$this->assertEquals(
'"p_table_name" AS "bubble"',
$quoter->quote('table_name AS bubble', true)
);
$this->assertEquals(
'MIN("bubble"."column")',
$quoter->quote('MIN(bubble.column)')
);
$this->assertEquals(
'AVG("bubble"."column") AS "column_alias"',
$quoter->quote('AVG(bubble.column) AS column_alias')
);
}
public function testAliasesOperations()
{
$quoter = $this->quoter('p_');
$this->assertEquals(
'"p_table_name" AS "bubble"',
$quoter->quote('table_name AS bubble', true)
);
$this->assertEquals(
'"bubble"."column" * 10 + "p_other_table"."column_x"',
$quoter->quote('bubble.column * 10 + other_table.column_x')
);
$this->assertEquals(
'("p_table"."column" + "some_column") / "p_yolo"."column_b"',
$quoter->quote('(table.column + some_column) / yolo.column_b')
);
$this->assertEquals(
'("p_table"."column" + "some_column") / "bubble"."column_b" AS "xxx"',
$quoter->quote('(table.column + some_column) / bubble.column_b AS xxx')
);
}
public function testCollisions()
{
$quoter = $this->quoter('p_');
$this->assertEquals(
'"p_table"."column" AS "bubble"',
$quoter->quote('table.column AS bubble')
);
$this->assertEquals('"bubble"', $quoter->quote('bubble', false));
$this->assertEquals('"p_bubble"', $quoter->quote('bubble', true));
$this->assertEquals(
'"p_bubble"."column" AS "new_bubble"',
$quoter->quote('bubble.column AS new_bubble')
);
$this->assertEquals(
'"p_new_bubble" AS "x_bubble"',
$quoter->quote('new_bubble AS x_bubble', true)
);
$this->assertEquals('"p_new_bubble"', $quoter->quote('new_bubble', true));
$this->assertEquals('"x_bubble"', $quoter->quote('x_bubble', true));
}
public function testMySQLlPrefixes()
{
$quoter = $this->quoter('p_', MySQLDriver::class);
$this->assertEquals(
'*',
$quoter->quote('*')
);
$quoter->reset();
$this->assertEquals(
'`column`',
$quoter->quote('column')
);
$quoter->reset();
$this->assertEquals(
'`p_table`.`column`',
$quoter->quote('table.column')
);
$quoter->reset();
$this->assertEquals(
'`p_table`.*',
$quoter->quote('table.*')
);
$quoter->reset();
$this->assertEquals(
'`p_table_name`',
$quoter->quote('table_name', true)
);
$quoter->reset();
$this->assertEquals(
'`p_table`.`column` AS `column_alias`',
$quoter->quote('table.column AS column_alias')
);
$quoter->reset();
$this->assertEquals(
'`p_table_name` AS `table_name`',
$quoter->quote('table_name AS table_name', true)
);
}
public function testSQLServerPrefixes()
{
$quoter = $this->quoter('p_', SQLServerDriver::class);
$this->assertEquals(
'*',
$quoter->quote('*')
);
$quoter->reset();
$this->assertEquals(
'[column]',
$quoter->quote('column')
);
$quoter->reset();
$this->assertEquals(
'[p_table].[column]',
$quoter->quote('table.column')
);
$quoter->reset();
$this->assertEquals(
'[p_table].*',
$quoter->quote('table.*')
);
$quoter->reset();
$this->assertEquals(
'[p_table_name]',
$quoter->quote('table_name', true)
);
$quoter->reset();
$this->assertEquals(
'[p_table].[column] AS [column_alias]',
$quoter->quote('table.column AS column_alias')
);
$quoter->reset();
$this->assertEquals(
'[p_table_name] AS [table_name]',
$quoter->quote('table_name AS table_name', true)
);
}
/**
* Get instance of quoter.
*
* @param string $prefix
* @param string $driver Driver class.
* @return Quoter
*/
protected function quoter($prefix = '', $driver = PDODriver::class)
{
/**
* @var PDODriver $driver
*/
$driver = $this->getMockBuilder($driver)
->disableOriginalConstructor()
->setMethods(null)
->getMock();
return new Quoter($driver, $prefix);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\RecordEntity;
/**
* {@inheritdoc}
*
* Provides common set of functionality for polymorphic relations. Polymorphic relations declare
* their relation to interfaces not to record classes. Record role names will be used to resolve
* outer records.
*
* @see RecordSchema::getRole()
*/
abstract class MorphedSchema extends RelationSchema
{
/**
* {@inheritdoc}
*/
public function isInversable()
{
//Morphed relations must control unique relations on lower level
return !empty($this->definition[RecordEntity::INVERSE]) && $this->isReasonable();
}
/**
* {@inheritdoc}
*/
public function isReasonable()
{
return !empty($this->outerRecords());
}
/**
* {@inheritdoc}
*/
public function isSameDatabase()
{
foreach ($this->outerRecords() as $record) {
if ($this->record->getDatabase() != $record->getDatabase()) {
return false;
}
}
return true;
}
/**
* {@inheritdoc}
*
* Method will ensure that all related records has same key type.
*
* @throws RelationSchemaException
*/
public function getOuterKeyType()
{
$outerKeyType = null;
foreach ($this->outerRecords() as $record) {
if (!$record->tableSchema()->hasColumn($this->getOuterKey())) {
throw new RelationSchemaException(
"Morphed relation ($this) requires outer key exists in every record ({$record})."
);
}
$recordKeyType = $this->resolveAbstract(
$record->tableSchema()->column($this->getOuterKey())
);
if (is_null($outerKeyType)) {
$outerKeyType = $recordKeyType;
}
//Consistency of outer keys is strictly required
if ($outerKeyType != $recordKeyType) {
throw new RelationSchemaException(
"Morphed relation ({$this}) requires consistent outer key type ({$record}), "
. "expected '{$outerKeyType}' got '{$recordKeyType}'."
);
}
}
return $outerKeyType;
}
/**
* Get every related outer record.
*
* @return RecordSchema[]
*/
public function outerRecords()
{
$records = [];
foreach ($this->builder->getRecords() as $record) {
if ($record->isSubclassOf($this->getTarget()) && !$record->isAbstract()) {
$records[] = $record;
}
}
return $records;
}
/**
* {@inheritdoc}
*/
protected function clarifyDefinition()
{
parent::clarifyDefinition();
if (!$this->isSameDatabase()) {
throw new RelationSchemaException(
"Morphed relations ({$this}) can only link entities from the same database."
);
}
}
/**
* {@inheritdoc}
*/
protected function normalizeDefinition()
{
$definition = parent::normalizeDefinition();
$definition[static::RELATION_TYPE] = [];
foreach ($this->outerRecords() as $record) {
//We must remember how to relate morphed key value to outer record
$definition[static::RELATION_TYPE][$record->getRole()] = $record->getName();
}
return $definition;
}
/**
* {@inheritdoc}
*/
protected function proposedDefinitions()
{
$options = parent::proposedDefinitions();
foreach ($this->outerRecords() as $record) {
//We can use first found record primary key to populate default value
$options['outer:primaryKey'] = $record->getPrimaryKey();
break;
}
return $options;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Stores\Memcache;
/**
* Two brothers.
*/
class MemcacheDriver extends AbstractDriver
{
/**
* @var \Memcache
*/
protected $driver = null;
/**
* {@inheritdoc}
*/
public function __construct(array $servers)
{
$this->servers = $servers;
$this->driver = new \Memcache();
}
/**
* {@inheritdoc}
*/
public function connect()
{
foreach ($this->servers as $server) {
$server = $server + $this->defaultServer;
$this->driver->addServer(
$server['host'],
$server['port'],
$server['persistent'],
$server['weight']
);
}
}
/**
* {@inheritdoc}
*/
public function has($name)
{
return $this->driver->get($name) !== false;
}
/**
* {@inheritdoc}
*/
public function get($name)
{
return $this->driver->get($name);
}
/**
* {@inheritdoc}
*
* @throws \MemcachedException
*/
public function set($name, $data, $lifetime)
{
return $this->driver->set($name, $data, 0, $lifetime);
}
/**
* {@inheritdoc}
*/
public function forever($name, $data)
{
$this->driver->set($name, $data);
}
/**
* {@inheritdoc}
*/
public function delete($name)
{
$this->driver->delete($name);
}
/**
* {@inheritdoc}
*/
public function inc($name, $delta = 1)
{
if (!$this->has($name)) {
$this->forever($name, $delta);
return $delta;
}
return $this->driver->increment($name, $delta);
}
/**
* {@inheritdoc}
*/
public function dec($name, $delta = 1)
{
return $this->driver->decrement($name, $delta);
}
/**
* {@inheritdoc}
*/
public function flush()
{
$this->driver->flush();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas\Prototypes;
use Spiral\Core\Component;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Exceptions\SchemaException;
/**
* Aggregates common functionality for columns, indexes and foreign key schemas.
*/
abstract class AbstractElement extends Component
{
/**
* Declaration flag used to create full table diff.
*
* @var bool
*/
protected $declared = false;
/**
* Element name.
*
* @var string
*/
protected $name = '';
/**
* @invisible
* @var AbstractTable
*/
protected $table = null;
/**
* @param AbstractTable $table
* @param string $name
* @param mixed $schema Driver specific schema information.
*/
public function __construct(AbstractTable $table, $name, $schema = null)
{
$this->name = $name;
$this->table = $table;
if (!empty($schema)) {
$this->resolveSchema($schema);
}
}
/**
* Associated table.
*
* @return AbstractTable
*/
public function table()
{
return $this->table;
}
/**
* Set element name.
*
* @param string $name
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get element name. Can automatically quote such name.
*
* @param bool $quoted
* @return string
*/
public function getName($quoted = false)
{
if ($quoted) {
return $this->table->driver()->identifier($this->name);
}
return $this->name;
}
/**
* @return bool
*/
public function isDeclared()
{
return $this->declared;
}
/**
* Mark schema entity as declared, it will be kept in final diff.
*
* @param bool $declared
* @return $this
*/
public function declared($declared = true)
{
$this->declared = $declared;
return $this;
}
/**
* Element creation/definition syntax.
*
* @return string
*/
abstract public function sqlStatement();
/**
* @return string
*/
public function __toString()
{
return $this->sqlStatement();
}
/**
* Parse driver specific schema information and populate element data.
*
* @param mixed $schema
* @throws SchemaException
*/
abstract protected function resolveSchema($schema);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage\Entities;
use Spiral\Core\Component;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Storage\BucketInterface;
use Spiral\Storage\Exceptions\ObjectException;
use Spiral\Storage\ObjectInterface;
use Spiral\Storage\StorageInterface;
/**
* Default implementation of storage object.
*/
class StorageObject extends Component implements ObjectInterface
{
/**
* We all love sugar.
*/
use SaturateTrait;
/**
* @var BucketInterface
*/
private $bucket = null;
/**
* @var string
*/
private $address = false;
/**
* @var string
*/
private $name = false;
/**
* @invisible
* @var StorageInterface
*/
protected $storage = null;
/**
* @param string $address
* @param StorageInterface|null $storage
* @throws SugarException
*/
public function __construct($address, StorageInterface $storage = null)
{
$this->storage = $this->saturate($storage, StorageInterface::class);
//Trying to find bucket using address
if (empty($address)) {
throw new ObjectException("Unable to create StorageObject with empty address.");
}
$this->address = $address;
$this->bucket = $this->storage->locateBucket($address, $this->name);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function getAddress()
{
return $this->address;
}
/**
* {@inheritdoc}
*/
public function getBucket()
{
return $this->bucket;
}
/**
* {@inheritdoc}
*/
public function exists()
{
if (empty($this->name)) {
return false;
}
return $this->bucket->exists($this->name);
}
/**
* {@inheritdoc}
*/
public function getSize()
{
if (empty($this->name)) {
return false;
}
return $this->bucket->size($this->name);
}
/**
* {@inheritdoc}
*/
public function localFilename()
{
if (empty($this->name)) {
throw new ObjectException("Unable to allocate filename for unassigned storage object.");
}
return $this->bucket->allocateFilename($this->name);
}
/**
* {@inheritdoc}
*/
public function getStream()
{
if (empty($this->name)) {
throw new ObjectException("Unable to get stream for unassigned storage object.");
}
return $this->bucket->allocateStream($this->name);
}
/**
* {@inheritdoc}
*/
public function delete()
{
if (empty($this->name)) {
return;
}
$this->bucket->delete($this->name);
$this->address = $this->name = '';
$this->bucket = null;
}
/**
* {@inheritdoc}
*/
public function rename($newname)
{
if (empty($this->name)) {
throw new ObjectException("Unable to rename unassigned storage object.");
}
$this->address = $this->bucket->rename($this->name, $newname);
$this->name = $newname;
return $this;
}
/**
* {@inheritdoc}
*/
public function copy($destination)
{
if (empty($this->name)) {
throw new ObjectException("Unable to copy unassigned storage object.");
}
if (is_string($destination)) {
$destination = $this->storage->bucket($destination);
}
return $this->storage->open($this->bucket->copy($destination, $this->name));
}
/**
* {@inheritdoc}
*/
public function replace($destination)
{
if (empty($this->name)) {
throw new ObjectException("Unable to replace unassigned storage object.");
}
if (is_string($destination)) {
$destination = $this->storage->bucket($destination);
}
$this->address = $this->bucket->replace($destination, $this->name);
$this->bucket = $destination;
return $this;
}
/**
* @return string
*/
public function __toString()
{
return $this->address;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Models;
use Spiral\Models\DataEntity;
class DataEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetter()
{
$entity = new DataEntity();
$entity->setField('abc', 123);
$this->assertEquals(123, $entity->getField('abc'));
$this->assertTrue($entity->hasField('abc'));
$this->assertFalse($entity->hasField('bce'));
}
public function testMagicProperties()
{
$entity = new DataEntity();
$entity->abc = 123;
$this->assertEquals(123, $entity->abc);
$this->assertTrue(isset($entity->abc));
}
public function testMagicMethods()
{
$entity = new DataEntity();
$entity->setAbc('123');
$this->assertEquals(123, $entity->getAbc());
$this->assertEquals($entity->getField('abc'), $entity->getAbc());
$this->assertTrue($entity->hasField('abc'));
}
public function testSerialize()
{
$data = ['a' => 123, 'b' => null, 'c' => 'test'];
$entity = new DataEntity($data);
$this->assertEquals($data, $entity->serializeData());
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Spiral\Core\Component;
use Spiral\Models\ActiveEntityInterface;
use Spiral\Models\EntityInterface;
use Spiral\Models\IdentifiedInterface;
use Spiral\ORM\Entities\Traits\AliasTrait;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\RecordInterface;
use Spiral\ORM\RelationInterface;
/**
* Abstract implementation of ORM Relations, provides access to associated instances, use ORM entity
* cache and record iterators. In additional, relation can be serialized into json, or iterated when
* needed.
*
* This abstract implement built to work with ORM Record classes.
*/
abstract class Relation extends Component implements
RelationInterface,
\Countable,
\IteratorAggregate,
\JsonSerializable
{
/**
* {@} table aliases.
*/
use AliasTrait;
/**
* Relation type, required to fetch record class from relation definition.
*/
const RELATION_TYPE = null;
/**
* Indication that relation represent multiple records (HAS_MANY relations).
*/
const MULTIPLE = false;
/**
* Indication that relation data has been loaded from databases.
*
* @var bool
*/
protected $loaded = false;
/**
* Pre-loaded relation data, can be loaded while parent record, or later. Real data instance
* will be constructed on demand and will keep it pre-loaded context between calls.
*
* @see Record::setContext()
* @var array|null
*/
protected $data = [];
/**
* Instance of constructed EntityInterface of RecordIterator.
*
* @invisible
* @var mixed|EntityInterface|RecordIterator
*/
protected $instance = null;
/**
* Parent Record caused relation to be created.
*
* @var RecordInterface
*/
protected $parent = null;
/**
* Relation definition fetched from ORM schema. Must already be normalized by RelationSchema.
*
* @invisible
* @var array
*/
protected $definition = [];
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* @param ORM $orm
* @param RecordInterface $parent
* @param array $definition Relation definition, must be normalized by relation
* schema.
* @param mixed $data Pre-loaded relation data.
* @param bool $loaded Indication that relation data has been loaded.
*/
public function __construct(
ORM $orm,
RecordInterface $parent,
array $definition,
$data = null,
$loaded = false
) {
$this->orm = $orm;
$this->parent = $parent;
$this->definition = $definition;
$this->data = $data;
$this->loaded = $loaded;
}
/**
* {@inheritdoc}
*/
public function isLoaded()
{
return $this->loaded;
}
/**
* {@inheritdoc}
*
* Relation will automatically create related record if relation is not nullable. Usually
* applied for has one relations ($user->profile).
*/
public function getRelated()
{
if (!empty($this->instance)) {
//RecordIterator will update context automatically
return $this->instance;
}
if (!$this->isLoaded()) {
//Loading data if not already loaded
$this->loadData();
}
if (empty($this->data)) {
if (
array_key_exists(RecordEntity::NULLABLE, $this->definition)
&& !$this->definition[RecordEntity::NULLABLE]
&& !static::MULTIPLE
) {
//Not nullable relations must always return requested instance
return $this->instance = $this->emptyRecord();
}
//Can not be loaded, let's use empty iterator
return static::MULTIPLE ? $this->createIterator() : null;
}
if (static::MULTIPLE) {
$instance = $this->createIterator();
} else {
$instance = $this->createRecord();
}
return $this->instance = $instance;
}
/**
* {@inheritdoc}
*/
public function associate(EntityInterface $related = null)
{
if (static::MULTIPLE) {
throw new RelationException(
"Unable to associate relation data (relation represent multiple records)."
);
}
//Simplification for morphed relations
if (!is_array($allowed = $this->definition[static::RELATION_TYPE])) {
$allowed = [$allowed];
}
if (!is_object($related) || !in_array(get_class($related), $allowed)) {
$allowed = join("', '", $allowed);
throw new RelationException(
"Only instances of '{$allowed}' can be assigned to this relation."
);
}
//Entity caching
$this->instance = $related;
$this->loaded = true;
$this->data = [];
}
/**
* {@inheritdoc}
*/
public function saveAssociation($validate = true)
{
if (empty($instance = $this->getRelated())) {
//Nothing to save
return true;
}
if (static::MULTIPLE) {
/**
* @var RecordIterator|EntityInterface[] $instance
*/
foreach ($instance as $record) {
if (!$this->saveEntity($record, $validate)) {
return false;
}
}
return true;
}
return $this->saveEntity($instance, $validate);
}
/**
* {@inheritdoc}
*/
public function reset(array $data = [], $loaded = false)
{
if ($loaded && !empty($this->data) && $this->data == $data) {
//Nothing to do, context is the same
return;
}
if (!$loaded || !($this->instance instanceof EntityInterface)) {
//Flushing instance
$this->instance = null;
}
$this->data = $data;
$this->loaded = $loaded;
}
/**
* {@inheritdoc}
*/
public function isValid()
{
$related = $this->getRelated();
if (!static::MULTIPLE) {
if ($related instanceof EntityInterface) {
return $related->isValid();
}
return true;
}
/**
* @var RecordIterator|EntityInterface[] $data
*/
$hasErrors = false;
foreach ($related as $entity) {
if (!$entity->isValid()) {
$hasErrors = true;
}
}
return !$hasErrors;
}
/**
* {@inheritdoc}
*/
public function hasErrors()
{
return !$this->isValid();
}
/**
* List of errors associated with parent field, every field must have only one error assigned.
*
* @param bool $reset Clean errors after receiving every message.
* @return array
*/
public function getErrors($reset = false)
{
$related = $this->getRelated();
if (!static::MULTIPLE) {
if ($related instanceof EntityInterface) {
return $related->getErrors($reset);
}
return [];
}
/**
* @var RecordIterator|EntityInterface[] $data
*/
$errors = [];
foreach ($related as $position => $record) {
if (!$record->isValid()) {
$errors[$position] = $record->getErrors($reset);
}
}
return !empty($errors);
}
/**
* Get selector associated with relation.
*
* @param array $where
* @return RecordSelector
*/
public function find(array $where = [])
{
return $this->createSelector()->where($where);
}
/**
* {@inheritdoc}
*
* Use getRelation() method to count pre-loaded data.
*
* @return int
*/
public function count()
{
return $this->createSelector()->count();
}
/**
* Perform iterator on pre-loaded data. Use relation selector to iterate thought custom relation
* query.
*
* @return RecordEntity|RecordEntity[]|RecordIterator
*/
public function getIterator()
{
return $this->getRelated();
}
/**
* Bypassing call to created selector.
*
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call($method, array $arguments)
{
return call_user_func_array([$this->createSelector(), $method], $arguments);
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->getRelated();
}
/**
* {@inheritdoc}
*/
protected function container()
{
return $this->orm->container();
}
/**
* Class name of outer record.
*
* @return string
*/
protected function getClass()
{
return $this->definition[static::RELATION_TYPE];
}
/**
* Mount relation keys to parent or children records to ensure their connection. Method called
* when record requests relation save.
*
* @param EntityInterface $record
* @return EntityInterface
*/
abstract protected function mountRelation(EntityInterface $record);
/**
* Convert pre-loaded relation data to record iterator record.
*
* @return RecordIterator
*/
protected function createIterator()
{
return new RecordIterator($this->orm, $this->getClass(), (array)$this->data);
}
/**
* Convert pre-loaded relation data to active record record.
*
* @return RecordEntity
*/
protected function createRecord()
{
return $this->orm->record($this->getClass(), (array)$this->data);
}
/**
* Create empty record to be associated with non nullable relation.
*
* @return RecordEntity
*/
protected function emptyRecord()
{
$record = $this->orm->record($this->getClass(), []);
$this->associate($record);
return $record;
}
/**
* Load relation data based on created selector.
*
* @return array|null
*/
protected function loadData()
{
if (!$this->parent->isLoaded()) {
//Nothing to load for unloaded parents
return null;
}
$this->loaded = true;
if (static::MULTIPLE) {
return $this->data = $this->createSelector()->fetchData();
}
$data = $this->createSelector()->fetchData();
if (isset($data[0])) {
return $this->data = $data[0];
}
return null;
}
/**
* Internal ORM relation method used to create valid selector used to pre-load relation data or
* create custom query based on relation options.
*
* Must be redeclarated in child implementations.
*
* @return RecordSelector
*/
protected function createSelector()
{
return $this->orm->selector($this->getClass());
}
/**
* Save simple related entity.
*
* @param EntityInterface $entity
* @param bool $validate
* @return bool|void
*/
private function saveEntity(EntityInterface $entity, $validate)
{
if ($entity instanceof RecordInterface && $entity->isDeleted()) {
return true;
}
if (!$entity instanceof ActiveEntityInterface) {
throw new RelationException("Unable to save non active entity.");
}
$this->mountRelation($entity);
if (!$entity->save($validate)) {
return false;
}
if ($entity instanceof IdentifiedInterface) {
$this->orm->cache()->remember($entity);
}
return true;
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Core\Component;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\FactoryInterface;
use Spiral\Core\HippocampusInterface;
use Spiral\Database\DatabaseManager;
use Spiral\Database\Entities\Database;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\Models\DataEntity;
use Spiral\Models\SchematicEntity;
use Spiral\ORM\Configs\ORMConfig;
use Spiral\ORM\Entities\Loader;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\Entities\RecordSource;
use Spiral\ORM\Entities\SchemaBuilder;
use Spiral\ORM\Entities\Schemas\RecordSchema;
use Spiral\ORM\Exceptions\ORMException;
use Spiral\Tokenizer\ClassLocatorInterface;
/**
* ORM component used to manage state of cached Record's schema, record creation and schema
* analysis.
*
* Attention, do not forget to reset cache between requests.
*
* @todo Think about using views for complex queries? Using views for entities? ViewRecord?
* @todo ability to merge multiple tables into one entity - like SearchEntity? Partial entities?
*
* @todo think about entity cache and potential use cases when model can be accessed from outside
*/
class ORM extends Component implements SingletonInterface
{
use LoggerTrait;
/**
* Declares to IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* Memory section to store ORM schema.
*/
const MEMORY = 'orm.schema';
/**
* Normalized record constants.
*/
const M_ROLE_NAME = 0;
const M_SOURCE = 1;
const M_TABLE = 2;
const M_DB = 3;
const M_HIDDEN = SchematicEntity::SH_HIDDEN;
const M_SECURED = SchematicEntity::SH_SECURED;
const M_FILLABLE = SchematicEntity::SH_FILLABLE;
const M_MUTATORS = SchematicEntity::SH_MUTATORS;
const M_VALIDATES = SchematicEntity::SH_VALIDATES;
const M_COLUMNS = 9;
const M_NULLABLE = 10;
const M_RELATIONS = 11;
const M_PRIMARY_KEY = 12;
/**
* Normalized relation options.
*/
const R_TYPE = 0;
const R_TABLE = 1;
const R_DEFINITION = 2;
const R_DATABASE = 3;
/**
* Pivot table data location in Record fields. Pivot data only provided when record is loaded
* using many-to-many relation.
*/
const PIVOT_DATA = '@pivot';
/**
* @var EntityCache
*/
private $cache = null;
/**
* @var ORMConfig
*/
protected $config = null;
/**
* Cached records schema.
*
* @var array|null
*/
protected $schema = null;
/**
* @invisible
* @var DatabaseManager
*/
protected $databases = null;
/**
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @invisible
* @var HippocampusInterface
*/
protected $memory = null;
/**
* @param ORMConfig $config
* @param EntityCache $cache
* @param HippocampusInterface $memory
* @param DatabaseManager $databases
* @param FactoryInterface $factory
*/
public function __construct(
ORMConfig $config,
EntityCache $cache,
HippocampusInterface $memory,
DatabaseManager $databases,
FactoryInterface $factory
) {
$this->config = $config;
$this->memory = $memory;
$this->cache = $cache;
$this->schema = (array)$memory->loadData(static::MEMORY);
$this->databases = $databases;
$this->factory = $factory;
}
/**
* @param EntityCache $cache
* @return $this
*/
public function setCache(EntityCache $cache)
{
$this->cache = $cache;
return $this;
}
/**
* @return EntityCache
*/
public function cache()
{
return $this->cache;
}
/**
* When ORM is cloned we are automatically flushing it's cache and creating new isolated area.
* Basically we have cache enabled per selection.
*
* @see RecordSelector::getIterator()
*/
public function __clone()
{
$this->cache = clone $this->cache;
if (!$this->cache->isEnabled()) {
$this->logger()->warning("ORM are cloned with disabled state.");
}
}
/**
* Get database by it's name from DatabaseManager associated with ORM component.
*
* @param string $database
* @return Database
*/
public function database($database)
{
return $this->databases->database($database);
}
/**
* Construct instance of Record or receive it from cache (if enabled). Only records with
* declared primary key can be cached.
*
* @param string $class Record class name.
* @param array $data
* @param bool $cache Add record to entity cache if enabled.
* @return RecordInterface
*/
public function record($class, array $data = [], $cache = true)
{
$schema = $this->schema($class);
if (!$this->cache->isEnabled() || !$cache) {
//Entity cache is disabled, we can create record right now
return new $class($data, !empty($data), $this, $schema);
}
//We have to find unique object criteria (will work for objects with primary key only)
$primaryKey = null;
if (
!empty($schema[self::M_PRIMARY_KEY])
&& !empty($data[$schema[self::M_PRIMARY_KEY]])
) {
$primaryKey = $data[$schema[self::M_PRIMARY_KEY]];
}
if ($this->cache->has($class, $primaryKey)) {
/**
* @var RecordInterface $entity
*/
return $this->cache->get($class, $primaryKey);
}
return $this->cache->remember(
new $class($data, !empty($data), $this, $schema)
);
}
/**
* Get ORM source for given class.
*
* @param string $class
* @return RecordSource
* @throws ORMException
*/
public function source($class)
{
$schema = $this->schema($class);
if (empty($source = $schema[self::M_SOURCE])) {
//Default source
$source = RecordSource::class;
}
return new $source($class, $this);
}
/**
* Get ORM selector for given class.
*
* @param string $class
* @param Loader $loader
* @return RecordSelector
*/
public function selector($class, Loader $loader = null)
{
return new RecordSelector($class, $this, $loader);
}
/**
* Get cached schema for specified record by it's name.
*
* @param string $record
* @return array
* @throws ORMException
*/
public function schema($record)
{
if (!isset($this->schema[$record])) {
$this->updateSchema();
}
if (!isset($this->schema[$record])) {
throw new ORMException("Undefined ORM schema item, unknown record '{$record}'.");
}
return $this->schema[$record];
}
/**
* Create record relation instance by given relation type, parent and definition (options).
*
* @param int $type
* @param RecordInterface $parent
* @param array $definition Relation definition.
* @param array $data
* @param bool $loaded
* @return RelationInterface
* @throws ORMException
*/
public function relation(
$type,
RecordInterface $parent,
$definition,
$data = null,
$loaded = false
) {
if (!$this->config->hasRelation($type, 'class')) {
throw new ORMException("Undefined relation type '{$type}'.");
}
$class = $this->config->relationClass($type, 'class');
//For performance reasons class constructed without container
return new $class($this, $parent, $definition, $data, $loaded);
}
/**
* Get instance of relation/selection loader based on relation type and definition.
*
* @param int $type Relation type.
* @param string $container Container related to parent loader.
* @param array $definition Relation definition.
* @param Loader $parent Parent loader (if presented).
* @return LoaderInterface
* @throws ORMException
*/
public function loader($type, $container, array $definition, Loader $parent = null)
{
if (!$this->config->hasRelation($type, 'loader')) {
throw new ORMException("Undefined relation loader '{$type}'.");
}
$class = $this->config->relationClass($type, 'loader');
//For performance reasons class constructed without container
return new $class($this, $container, $definition, $parent);
}
/**
* Update ORM records schema, synchronize declared and database schemas and return instance of
* SchemaBuilder.
*
* @param SchemaBuilder $builder User specified schema builder.
* @param bool $syncronize Create all required tables and columns
* @return SchemaBuilder
*/
public function updateSchema(SchemaBuilder $builder = null, $syncronize = false)
{
if (empty($builder)) {
$builder = $this->schemaBuilder();
}
//Create all required tables and columns
if ($syncronize) {
$builder->synchronizeSchema();
}
//Getting normalized (cached) version of schema
$this->schema = $builder->normalizeSchema();
//Saving
$this->memory->saveData(static::MEMORY, $this->schema);
//Let's reinitialize records
DataEntity::resetInitiated();
return $builder;
}
/**
* Get instance of ORM SchemaBuilder.
*
* @param ClassLocatorInterface $locator
* @return SchemaBuilder
*/
public function schemaBuilder(ClassLocatorInterface $locator = null)
{
return $this->factory->make(SchemaBuilder::class, [
'config' => $this->config,
'orm' => $this,
'locator' => $locator
]);
}
/**
* Create instance of relation schema based on relation type and given definition (declared in
* record). Resolve using container to support any possible relation type. You can create your
* own relations, loaders and schemas by altering ORM config.
*
* @param mixed $type
* @param SchemaBuilder $builder
* @param RecordSchema $record
* @param string $name
* @param array $definition
* @return Schemas\RelationInterface
*/
public function relationSchema(
$type,
SchemaBuilder $builder,
RecordSchema $record,
$name,
array $definition
) {
if (!$this->config->hasRelation($type, 'schema')) {
throw new ORMException("Undefined relation schema '{$type}'.");
}
//Getting needed relation schema builder
return $this->factory->make(
$this->config->relationClass($type, 'schema'),
compact('builder', 'record', 'name', 'definition')
);
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\ORM\Exceptions\LoaderException;
/**
* ORM loaders responsible for loading nested and related data inside parent Selector. Every loader
* must have defined container to describe where loaded data should be mounted in it's parent.
*
* Some loader implementations (see Loader) allows not only data loading, but manipulations with
* parent Selector to create filters and joins.
*
* @see Selector
* @see Loader
* @see LoaderInterface::mount()
*/
interface LoaderInterface
{
/**
* @param ORM $orm
* @param string $container
* @param array $definition
* @param LoaderInterface|null $parent
* @throws LoaderException
*/
public function __construct(
ORM $orm,
$container,
array $definition = [],
LoaderInterface $parent = null
);
/**
* Is loader represent multiple records or one.
*
* @return bool
*/
public function isMultiple();
/**
* Reference key (from parent object) required to speed up data normalization. In most of cases
* this is primary key of parent record. Method must return name of field which parent will
* pre-aggregate.
*
* @return string
* @throws LoaderException
*/
public function getReferenceKey();
/**
* Must return array of unique values of specified column by it's name (key). In order to
* optimize loadings, LoaderInterface must declare such column name in getReferenceKey to it's
* parent before requesting for aggregation. Keys like that can be used in IN statements for
* post loaders.
*
* @see getReferenceKey()
* @param string $referenceKey
* @return array
* @throws LoaderException
*/
public function aggregatedKeys($referenceKey);
/**
* Load data. Internal loader logic must mount every loader chunk of data into parent loader
* using mount method, container name and data key.
*
* @see mount()
* @throws LoaderException
*/
public function loadData();
/**
* Mount record data into internal data storage under specified container using reference key
* (inner key) and reference criteria (outer key value).
*
* Example (default ORM Loaders):
* $this->parent->mount('profile', 'id', 1, [
* 'id' => 100,
* 'user_id' => 1,
* ...
* ]);
*
* In this example "id" argument is inner key of "user" record and it's linked to outer key
* "user_id" in "profile" record, which defines reference criteria as 1.
*
* @param string $container
* @param string $key
* @param mixed $criteria
* @param array $data Data must be referenced to existed set if it was registered
* previously.
* @param bool $multiple If true all mounted records will added to array.
* @throws LoaderException
*/
public function mount($container, $key, $criteria, array &$data, $multiple = false);
/**
* Clean loader data.
*
* @throws LoaderException
*/
public function clean();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas;
use Doctrine\Common\Inflector\Inflector;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\ORM\Entities\SchemaBuilder;
use Spiral\ORM\Exceptions\RecordSchemaException;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\Exceptions\SchemaException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\Schemas\RelationInterface;
/**
* Generic (abstract) implementation of relation schema. Used for basic ORM relations.
*/
abstract class RelationSchema implements RelationInterface
{
/**
* Must contain relation type, this constant is required to fetch outer record(s) class name
* from relation definition.
*/
const RELATION_TYPE = null;
/**
* Relation represent multiple records.
*/
const MULTIPLE = false;
/**
* Some relations may declare that polymorphic must be used instead, polymorphic relation type
* must be stated here.
*/
const EQUIVALENT_RELATION = null;
/**
* Size of string column dedicated to store outer role name. Used in polymorphic relations.
* Even simple relations might include morph key (usually such relations created via inversion
* of polymorphic relation).
*
* @see RecordSchema::getRole()
*/
const MORPH_COLUMN_SIZE = 32;
/**
* @var string
*/
private $name = '';
/**
* Name of target record or interface. Must be fetched from definition.
*
* @var string
*/
private $target = '';
/**
* Definition specified by record schema or another definition.
*
* @var array
*/
protected $definition = [];
/**
* Most of relations provides ability to specify many different configuration options, such
* as key names, pivot table schemas, foreign key request, ability to be nullabe and etc.
*
* To simple schema definition in real projects we can fill some of this values automatically
* based on some "environment" values such as parent/outer record table, role name, primary key
* and etc.
*
* Example:
* ActiveRecord::INNER_KEY => '{outer:role}_{outer:primaryKey}'
*
* Result:
* Outer Record is User with primary key "id" => "user_id"
*
* @invisible
* @var array
*/
protected $defaultDefinition = [];
/**
* @invisible
* @var SchemaBuilder
*/
protected $builder = null;
/**
* @invisible
* @var RecordSchema
*/
protected $record = null;
/**
* {@inheritdoc}
*/
public function __construct(
SchemaBuilder $builder,
RecordSchema $record,
$name,
array $definition
) {
$this->builder = $builder;
$this->record = $record;
$this->name = $name;
//We can use definition type to fetch target outer record or interface
$this->target = $definition[static::RELATION_TYPE];
$this->definition = $definition;
if ($this->hasEquivalent()) {
return;
}
if (!class_exists($this->target) && !interface_exists($this->target)) {
throw new RelationSchemaException(
"Unable to build relation from '{$this->record}' to undefined target '{$this->target}'."
);
}
$this->clarifyDefinition();
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function getType()
{
return static::RELATION_TYPE;
}
/**
* Get name or target to be related to.
*
* @return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Relation represent multiple records.
*
* @return bool
*/
public function isMultiple()
{
return static::MULTIPLE;
}
/**
* {@inheritdoc}
*/
public function hasEquivalent()
{
if (empty(static::EQUIVALENT_RELATION)) {
//No equivalents
return false;
}
//Let's switch to polymorphic relation
return (new \ReflectionClass($this->target))->isInterface();
}
/**
* {@inheritdoc}
*/
public function createEquivalent()
{
if (!$this->hasEquivalent()) {
throw new RelationSchemaException(
"Relation '{$this->record}'.'{$this}' does not have equivalents."
);
}
//Let's convert to polymorphic
$definition = [
static::EQUIVALENT_RELATION => $this->target
] + $this->definition;
unset($definition[static::RELATION_TYPE]);
//Usually when relation declared as polymorphic
return $this->builder->relationSchema($this->record, $this->name, $definition);
}
/**
* {@inheritdoc}
*/
public function isInversable()
{
if (empty($this->definition[RecordEntity::INVERSE]) || !$this->isReasonable()) {
return false;
}
$inversed = $this->definition[RecordEntity::INVERSE];
if (is_array($inversed)) {
//Some relations requires not only inversed relation name but also type
$inversed = $inversed[1];
}
//We must prevent duplicate relations
return !$this->outerRecord()->hasRelation($inversed);
}
/**
* {@inheritdoc}
*/
public function isReasonable()
{
//Relation is only reasonable when outer record is not abstract and does not have relation
//under same name
return !$this->outerRecord()->isAbstract();
}
/**
* Some relations may not have any associated record, which means that inner/outer key must
* support nullable values. Records must allow setting fields like that to null.
*
* @return bool
*/
public function isNullable()
{
if (array_key_exists(RecordEntity::NULLABLE, $this->definition)) {
return $this->definition[RecordEntity::NULLABLE];
}
return false;
}
/**
* Indication that relation has declared morph key. This means that request to outer data must
* not only include inner key, but it must state value of morph key (usually record role name).
*
* Most of relations like that created automatically as inversion of polymorphic relation to
* it's related record(s).
*
* @return bool
*/
public function hasMorphKey()
{
return !empty($this->definition[RecordEntity::MORPH_KEY]);
}
/**
* Name of declared morph key.
*
* @return string
*/
public function getMorphKey()
{
if (isset($this->definition[RecordEntity::MORPH_KEY])) {
return $this->definition[RecordEntity::MORPH_KEY];
}
return null;
}
/**
* Indication that relation allowed to create indexes in outer or inner tables.
*
* @return bool
*/
public function isIndexed()
{
return !empty($this->definition[RecordEntity::CREATE_INDEXES]);
}
/**
* Check if relation requests foreign key constraints to be created.
*
* @return bool
*/
public function isConstrained()
{
if (!$this->isSameDatabase()) {
//Unable to create constraint when relation points to another database
return false;
}
if (array_key_exists(RecordEntity::CONSTRAINT, $this->definition)) {
return $this->definition[RecordEntity::CONSTRAINT];
}
return false;
}
/**
* Some relations allows user to specify what type of delete/update behaviour must be applied to
* created foreign keys.
*
* @return string|null
*/
public function getConstraintAction()
{
if (array_key_exists(RecordEntity::CONSTRAINT_ACTION, $this->definition)) {
return $this->definition[RecordEntity::CONSTRAINT_ACTION];
}
return null;
}
/**
* Check if parent and related records belongs to same database, it will allow ORM to use joins
* to preload or filter by related data.
*
* @return bool
* @throws SchemaException
*/
public function isSameDatabase()
{
if (!$this->builder->hasRecord($this->target)) {
//Usually it tells us that relation relates to many different records (polymorphic)
//We can't clearly say
return false;
}
//Databases must be the same
return $this->record->getDatabase() == $this->outerRecord()->getDatabase();
}
/**
* Declared inner key. Must return null if no key defined or required.
*
* @return null|string
*/
public function getInnerKey()
{
if (isset($this->definition[RecordEntity::INNER_KEY])) {
return $this->definition[RecordEntity::INNER_KEY];
}
return null;
}
/**
* Declared outer key. Must return null if no key defined or required.
*
* @return null|string
*/
public function getOuterKey()
{
if (isset($this->definition[RecordEntity::OUTER_KEY])) {
return $this->definition[RecordEntity::OUTER_KEY];
}
return null;
}
/**
* Calculates abstract type of inner key. Must return null if no key defined or required.
* Primary types will be converted to appropriate sized integers.
*
* @return null|string
* @throws SchemaException
*/
public function getInnerKeyType()
{
if (empty($innerKey = $this->getInnerKey())) {
return null;
}
return $this->resolveAbstract(
$this->record->tableSchema()->column($innerKey)
);
}
/**
* Calculates abstract type of outer key. Must return null if no key defined or required.
* Primary types will be converted to appropriate sized integers.
*
* @return null|string
* @throws SchemaException
*/
public function getOuterKeyType()
{
if (empty($outerKey = $this->getOuterKey())) {
return null;
}
return $this->resolveAbstract(
$this->outerRecord()->tableSchema()->column($outerKey)
);
}
/**
* {@inheritdoc}
*/
public function normalizeSchema()
{
return [
ORM::R_TYPE => static::RELATION_TYPE,
ORM::R_DEFINITION => $this->normalizeDefinition()
];
}
/**
* @return string
*/
public function __toString()
{
return $this->getName();
}
/**
* Normalize schema definition into light cachable form.
*
* @return array
*/
protected function normalizeDefinition()
{
$definition = $this->definition;
//Unnecessary fields.
unset(
$definition[RecordEntity::CONSTRAINT],
$definition[RecordEntity::CONSTRAINT_ACTION],
$definition[RecordEntity::CREATE_PIVOT],
$definition[RecordEntity::INVERSE],
$definition[RecordEntity::CREATE_INDEXES]
);
return $definition;
}
/**
* Will specify missing fields in relation definition using default definition options. Such
* options are dynamic and populated based on values fetched from related records.
*/
protected function clarifyDefinition()
{
foreach ($this->defaultDefinition as $property => $pattern) {
if (isset($this->definition[$property])) {
//Specified by user
continue;
}
if (!is_string($pattern)) {
//Some options are actually array of options
$this->definition[$property] = $pattern;
continue;
}
//Let's create option value using default proposer values
$this->definition[$property] = \Spiral\interpolate(
$pattern,
$this->proposedDefinitions()
);
}
}
/**
* Create set of options to specify missing relation definition fields.
*
* @return array
*/
protected function proposedDefinitions()
{
$options = [
//Relation name
'name' => $this->name,
//Relation name in plural form
'name:plural' => Inflector::pluralize($this->name),
//Relation name in singular form
'name:singular' => Inflector::singularize($this->name),
//Parent record role name
'record:role' => $this->record->getRole(),
//Parent record table name
'record:table' => $this->record->getTable(),
//Parent record primary key
'record:primaryKey' => $this->record->getPrimaryKey()
];
//Some options may use values declared in other definition fields
$proposed = [
RecordEntity::OUTER_KEY => 'outerKey',
RecordEntity::INNER_KEY => 'innerKey',
RecordEntity::PIVOT_TABLE => 'pivotTable'
];
foreach ($proposed as $property => $alias) {
if (isset($this->definition[$property])) {
//Let's create some default options based on user specified values
$options['definition:' . $alias] = $this->definition[$property];
}
}
if ($this->builder->hasRecord($this->target)) {
$options = $options + [
//Outer role name
'outer:role' => $this->outerRecord()->getRole(),
//Outer record table
'outer:table' => $this->outerRecord()->getTable(),
//Outer record primary key
'outer:primaryKey' => $this->outerRecord()->getPrimaryKey()
];
}
return $options;
}
/**
* Get RecordSchema to be associated with, method must throw an exception if outer record not
* found.
*
* @return RecordSchema
* @throws RelationSchemaException
* @throws SchemaException
* @throws RecordSchemaException
*/
protected function outerRecord()
{
if (!$this->builder->hasRecord($this->target)) {
throw new RelationSchemaException(
"Undefined outer record '{$this->target}' in relation '{$this->record}'.'{$this}'."
);
}
return $this->builder->record($this->target);
}
/**
* Resolve correct abstract type to represent inner or outer key. Primary types will be
* converted to appropriate sized integers.
*
* @param AbstractColumn $column
* @return string
*/
protected function resolveAbstract(AbstractColumn $column)
{
switch ($column->abstractType()) {
case 'bigPrimary':
return 'bigInteger';
case 'primary':
return 'integer';
default:
//Not primary key
return $column->abstractType();
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer\Highlighter;
/**
* Highlight code tokens. Attention, you have to specify container and container colors manually.
*/
class Style
{
/**
* Style templates.
*
* @var array
*/
protected $templates = [
'token' => "<span style=\"{style}\">{code}</span>",
'line' => "<div><span class=\"number\">{number}</span>{code}</div>\n",
'highlighted' => "<div class=\"highlighted\"><span class=\"number\">{number}</span>{code}</div>\n"
];
/**
* Styles associated with token types.
*
* @var array
*/
protected $styles = [
'color: blue; font-weight: bold;' => [
T_STATIC,
T_PUBLIC,
T_PRIVATE,
T_PROTECTED,
T_CLASS,
T_NEW,
T_FINAL,
T_ABSTRACT,
T_IMPLEMENTS,
T_CONST,
T_ECHO,
T_CASE,
T_FUNCTION,
T_GOTO,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
T_VAR,
T_INSTANCEOF,
T_INTERFACE,
T_THROW,
T_ARRAY,
T_IF,
T_ELSE,
T_ELSEIF,
T_TRY,
T_CATCH,
T_CLONE,
T_WHILE,
T_FOR,
T_DO,
T_UNSET,
T_FOREACH,
T_RETURN,
T_EXIT
],
'color: blue' => [
T_DNUMBER,
T_LNUMBER
],
'color: black; font: weight: bold;' => [
T_OPEN_TAG,
T_CLOSE_TAG,
T_OPEN_TAG_WITH_ECHO
],
'color: gray;' => [
T_COMMENT,
T_DOC_COMMENT
],
'color: green; font-weight: bold;' => [
T_CONSTANT_ENCAPSED_STRING,
T_ENCAPSED_AND_WHITESPACE
],
'color: #660000;' => [
T_VARIABLE
]
];
/**
* Highlight given token.
*
* @param int $tokenType
* @param string $code
* @return string
*/
public function highlightToken($tokenType, $code)
{
foreach ($this->styles as $style => $tokens) {
if (!in_array($tokenType, $tokens)) {
//Nothing to highlight
continue;
}
if (strpos($code, "\n") === false) {
return \Spiral\interpolate($this->templates['token'], compact('style', 'code'));
}
$lines = [];
foreach (explode("\n", $code) as $line) {
$lines[] = \Spiral\interpolate($this->templates['token'], [
'style' => $style,
'code' => $line
]);
}
return join("\n", $lines);
}
return $code;
}
/**
* Highlight one line.
*
* @param int $number
* @param string $code
* @param bool $highlighted
* @return string
*/
public function line($number, $code, $highlighted = false)
{
return \Spiral\interpolate(
$this->templates[$highlighted ? 'highlighted' : 'line'],
compact('number', 'code')
);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres\Schemas;
use Spiral\Database\Entities\Schemas\AbstractIndex;
/**
* Postgres index schema.
*/
class IndexSchema extends AbstractIndex
{
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->type = strpos($schema, ' UNIQUE ') ? self::UNIQUE : self::NORMAL;
if (preg_match('/\(([^)]+)\)/', $schema, $matches)) {
$this->columns = explode(',', $matches[1]);
foreach ($this->columns as &$column) {
//Postgres with add quotes to all columns with uppercase letters
$column = trim($column, ' "\'');
unset($column);
}
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage\Servers;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerAwareInterface;
use Spiral\Cache\StoreInterface;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\Files\FilesInterface;
use Spiral\Storage\BucketInterface;
use Spiral\Storage\Exceptions\ServerException;
use Spiral\Storage\StorageServer;
/**
* Provides abstraction level to work with data located in Rackspace cloud.
*/
class RackspaceServer extends StorageServer implements LoggerAwareInterface
{
/**
* There is few warning messages.
*/
use LoggerTrait;
/**
* @var string
*/
private $authToken = [];
/**
* Some operations can be performed only inside one region.
*
* @var array
*/
private $regions = [];
/**
* @var array
*/
protected $options = [
'server' => 'https://auth.api.rackspacecloud.com/v1.0',
'authServer' => 'https://identity.api.rackspacecloud.com/v2.0/tokens',
'username' => '',
'apiKey' => '',
'cache' => true,
'lifetime' => 86400
];
/**
* Cache store to remember connection.
*
* @invisible
* @var StoreInterface
*/
protected $store = null;
/**
* @var Client
*/
protected $client = null;
/**
* @param FilesInterface $files
* @param StoreInterface $store
* @param array $options
*/
public function __construct(FilesInterface $files, StoreInterface $store, array $options)
{
parent::__construct($files, $options);
$this->store = $store;
if ($this->options['cache']) {
$this->authToken = $this->store->get(
$this->options['username'] . '@rackspace-token'
);
$this->regions = (array)$this->store->get(
$this->options['username'] . '@rackspace-regions'
);
}
//This code is going to use additional abstraction layer to connect storage and guzzle
$this->client = new Client($this->options);
$this->connect();
}
/**
* {@inheritdoc}
*
* @return bool|ResponseInterface
*/
public function exists(BucketInterface $bucket, $name)
{
try {
$response = $this->client->send($this->buildRequest('HEAD', $bucket, $name));
} catch (ClientException $exception) {
if ($exception->getCode() == 404) {
return false;
}
if ($exception->getCode() == 401) {
$this->reconnect();
return $this->exists($bucket, $name);
}
//Some unexpected error
throw new ServerException($exception->getMessage(), $exception->getCode(), $exception);
}
if ($response->getStatusCode() !== 200) {
return false;
}
return $response;
}
/**
* {@inheritdoc}
*/
public function size(BucketInterface $bucket, $name)
{
if (empty($response = $this->exists($bucket, $name))) {
return false;
}
return (int)$response->getHeaderLine('Content-Length');
}
/**
* {@inheritdoc}
*/
public function put(BucketInterface $bucket, $name, $source)
{
if (empty($mimetype = \GuzzleHttp\Psr7\mimetype_from_filename($name))) {
$mimetype = self::DEFAULT_MIMETYPE;
}
try {
$request = $this->buildRequest('PUT', $bucket, $name, [
'Content-Type' => $mimetype,
'Etag' => md5_file($this->castFilename($source))
]);
$this->client->send($request->withBody($this->castStream($source)));
} catch (ClientException $exception) {
if ($exception->getCode() == 401) {
$this->reconnect();
return $this->put($bucket, $name, $source);
}
//Some unexpected error
throw new ServerException($exception->getMessage(), $exception->getCode(), $exception);
}
return true;
}
/**
* {@inheritdoc}
*/
public function allocateStream(BucketInterface $bucket, $name)
{
try {
$response = $this->client->send($this->buildRequest('GET', $bucket, $name));
} catch (ClientException $exception) {
if ($exception->getCode() == 401) {
$this->reconnect();
return $this->allocateStream($bucket, $name);
}
throw new ServerException($exception->getMessage(), $exception->getCode(), $exception);
}
return $response->getBody();
}
/**
* {@inheritdoc}
*/
public function delete(BucketInterface $bucket, $name)
{
try {
$this->client->send($this->buildRequest('DELETE', $bucket, $name));
} catch (ClientException $exception) {
if ($exception->getCode() == 401) {
$this->reconnect();
$this->delete($bucket, $name);
} elseif ($exception->getCode() != 404) {
throw new ServerException($exception->getMessage(), $exception->getCode(),
$exception);
}
}
}
/**
* {@inheritdoc}
*/
public function rename(BucketInterface $bucket, $oldname, $newname)
{
try {
$request = $this->buildRequest('PUT', $bucket, $newname, [
'X-Copy-From' => '/' . $bucket->getOption('container') . '/' . rawurlencode($oldname),
'Content-Length' => 0
]);
$this->client->send($request);
} catch (ClientException $exception) {
if ($exception->getCode() == 401) {
$this->reconnect();
return $this->rename($bucket, $oldname, $newname);
}
throw new ServerException($exception->getMessage(), $exception->getCode(), $exception);
}
//Deleting old file
$this->delete($bucket, $oldname);
return true;
}
/**
* {@inheritdoc}
*/
public function copy(BucketInterface $bucket, BucketInterface $destination, $name)
{
if ($bucket->getOption('region') != $destination->getOption('region')) {
$this->logger()->warning(
"Copying between regions are not allowed by Rackspace and performed using local buffer."
);
//Using local memory/disk as buffer
return parent::copy($bucket, $destination, $name);
}
try {
$request = $this->buildRequest('PUT', $destination, $name, [
'X-Copy-From' => '/' . $bucket->getOPtion('container') . '/' . rawurlencode($name),
'Content-Length' => 0
]);
$this->client->send($request);
} catch (ClientException $exception) {
if ($exception->getCode() == 401) {
$this->reconnect();
return $this->copy($bucket, $destination, $name);
}
throw new ServerException($exception->getMessage(), $exception->getCode(), $exception);
}
return true;
}
/**
* Connect to rackspace servers using new or cached token.
*
* @throws ServerException
*/
protected function connect()
{
if (!empty($this->authToken)) {
//Already got credentials from cache
return;
}
//Credentials request
$request = new Request(
'POST',
$this->options['authServer'],
['Content-Type' => 'application/json'],
json_encode([
'auth' => [
'RAX-KSKEY:apiKeyCredentials' => [
'username' => $this->options['username'],
'apiKey' => $this->options['apiKey']
]
]
])
);
try {
/**
* @var ResponseInterface $response
*/
$response = $this->client->send($request);
} catch (ClientException $exception) {
if ($exception->getCode() == 401) {
throw new ServerException(
"Unable to perform Rackspace authorization using given credentials."
);
}
throw new ServerException($exception->getMessage(), $exception->getCode(), $exception);
}
$response = json_decode((string)$response->getBody(), 1);
foreach ($response['access']['serviceCatalog'] as $location) {
if ($location['name'] == 'cloudFiles') {
foreach ($location['endpoints'] as $server) {
$this->regions[$server['region']] = $server['publicURL'];
}
}
}
if (!isset($response['access']['token']['id'])) {
throw new ServerException("Unable to fetch rackspace auth token.");
}
$this->authToken = $response['access']['token']['id'];
if ($this->options['cache']) {
$this->store->set(
$this->options['username'] . '@rackspace-token',
$this->authToken,
$this->options['lifetime']
);
$this->store->set(
$this->options['username'] . '@rackspace-regions',
$this->regions,
$this->options['lifetime']
);
}
}
/**
* Reconnect.
*
* @throws ServerException
*/
protected function reconnect()
{
$this->authToken = null;
$this->connect();
}
/**
* Create instance of UriInterface based on provided bucket options and storage object name.
*
* @param BucketInterface $bucket
* @param string $name
* @return UriInterface
* @throws ServerException
*/
protected function buildUri(BucketInterface $bucket, $name)
{
if (empty($bucket->getOption('region'))) {
throw new ServerException("Every rackspace container should have specified region.");
}
$region = $bucket->getOption('region');
if (!isset($this->regions[$region])) {
throw new ServerException("'{$region}' region is not supported by Rackspace.");
}
return new Uri(
$this->regions[$region] . '/' . $bucket->getOption('container') . '/' . rawurlencode($name)
);
}
/**
* Create pre-configured object request.
*
* @param string $method
* @param BucketInterface $bucket
* @param string $name
* @param array $headers
* @return RequestInterface
*/
protected function buildRequest($method, BucketInterface $bucket, $name, array $headers = [])
{
//Adding auth headers
$headers += [
'X-Auth-Token' => $this->authToken,
'Date' => gmdate('D, d M Y H:i:s T')
];
return new Request($method, $this->buildUri($bucket, $name), $headers);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Schemas;
/**
* Represent table schema with it's all columns, indexes and foreign keys.
*/
interface TableInterface
{
/**
* Check if table exists in database.
*
* @return bool
*/
public function exists();
/**
* Store specific table name (may include prefix).
*
* @return string
*/
public function getName();
/**
* Array of columns dedicated to primary index. Attention, this methods will ALWAYS return
* array, even if there is only one primary key.
*
* @return array
*/
public function getPrimaryKeys();
/**
* Check if table have specified column.
*
* @param string $name Column name.
* @return bool
*/
public function hasColumn($name);
/**
* Get all declared columns.
*
* @return ColumnInterface[]
*/
public function getColumns();
/**
* Check if table has index related to set of provided columns. Columns order does matter!
*
* @param array $columns
* @return bool
*/
public function hasIndex(array $columns = []);
/**
* Get all table indexes.
*
* @return IndexInterface[]
*/
public function getIndexes();
/**
* Check if table has foreign key related to table column.
*
* @param string $column Column name.
* @return bool
*/
public function hasForeign($column);
/**
* Get all table foreign keys.
*
* @return ReferenceInterface[]
*/
public function getForeigns();
/**
* Get list of table names current schema depends on, must include every table linked using
* foreign key or other constraint. Table names MUST include prefixes.
*
* @return array
*/
public function getDependencies();
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Models\EntityInterface;
use Spiral\ORM\Exceptions\ORMException;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\Validation\ValidatesInterface;
/**
* Relations used to represent data related to parent record. Every relation must be embedded into
* record, be callable and provide related data by record request. In addition, relations must know
* how to associate data/entity provided by user.
*
* @see Record
*/
interface RelationInterface extends ValidatesInterface
{
/**
* @param ORM $orm ORM component.
* @param null|RecordInterface $parent Parent RecordEntity.
* @param array $definition Relation definition, crated by RelationSchema.
* @param mixed $data Pre-loaded relation data.
* @param bool $loaded Indication that relation data has been loaded from
* database.
*/
public function __construct(
ORM $orm,
RecordInterface $parent,
array $definition,
$data = null,
$loaded = false
);
/**
* Check if relation data was loaded (even if no data presented).
*
* @return bool
*/
public function isLoaded();
/**
* Return data, object or instances handled by relation, resulted type depends of relation
* implementation and might be: Record, RecordIterator, itself (ManyToMorphed), Document and
* etc. Related data must be loaded if relation was not pre-loaded with record.
*
* Example:
* echo $user->profile->facebookUID;
*
* @see Record::__get()
* @return null|EntityInterface
* @throws EntityInterface
*/
public function getRelated();
/**
* Associate relation to new object data. Method will be called by parent record when field
* with name = relation name set with some value. Relation must update inner and outer keys
* in parent and related records.
*
* Example:
* $user->profile = new Profile();
*
* You should be able to disassociate some relations by providing null as value, but only if
* relation was configured as nullable.
*
* Example:
* $post->picture = null;
*
* @see Record::__set()
* @param EntityInterface|null $related
* @throws RelationException
* @throws ORMException
*/
public function associate(EntityInterface $related = null);
/**
* Must save related data into database by parent Record request.
*
* @see Record::save()
* @param bool $validate
* @return bool
* @throws RelationException
*/
public function saveAssociation($validate = true);
/**
* Reset relation state. By default it must flush all relation data. Method used by Record when
* context were changed.
*
* @see Record::setContext()
* @param array $data Set relation data in array form.
* @param bool $loaded Indication that relation data has been loaded.
* @throws RelationException
*/
public function reset(array $data = [], $loaded = false);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler;
/**
* Provides ability to compose multiple html files together.
*/
class Stempler
{
/**
* @var LoaderInterface
*/
protected $loader = null;
/**
* @var SyntaxInterface
*/
protected $syntax = null;
/**
* @var array
*/
protected $options = [];
/**
* @param LoaderInterface $loader
* @param SyntaxInterface $syntax
* @param array $options
*/
public function __construct($loader, SyntaxInterface $syntax, array $options = [])
{
$this->loader = $loader;
$this->syntax = $syntax;
$this->options = $options;
}
/**
* Compile path.
*
* @param string $path
* @return string
*/
public function compile($path)
{
return $this->supervisor()->createNode($path);
}
/**
* Compile string template.
*
* @param string $source
* @return string
*/
public function compileString($source)
{
$node = new Node($this->supervisor(), 'root', $source);
return $node->compile();
}
/**
* Create new instance of supervisor.
*
* @return Supervisor
*/
protected function supervisor()
{
return new Supervisor($this->loader, $this->syntax);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Configs;
use Spiral\Core\InjectableConfig;
/**
* Translation component configuration.
*/
class ORMConfig extends InjectableConfig
{
/**
* Configuration section.
*/
const CONFIG = 'orm';
/**
* @var array
*/
protected $config = [
'mutators' => [],
'mutatorAliases' => [],
'relations' => []
];
/**
* @param string $type
* @param string $target
* @return bool
*/
public function hasRelation($type, $target = 'class')
{
return isset($this->config['relations'][$type][$target]);
}
/**
* @param string $type
* @param string $target
* @return string
*/
public function relationClass($type, $target)
{
return $this->config['relations'][$type][$target];
}
/**
* Resolve mutator alias.
*
* @param string $mutator
* @return string
*/
public function mutatorAlias($mutator)
{
if (!is_string($mutator) || !isset($this->config['mutatorAliases'][$mutator])) {
return $mutator;
}
return $this->config['mutatorAliases'][$mutator];
}
/**
* Get list of mutators associated with given type.
*
* @param string $type
* @return array
*/
public function getMutators($type)
{
return isset($this->config['mutators'][$type]) ? $this->config['mutators'][$type] : [];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache;
use Spiral\Cache\Exceptions\StoreException;
/**
* Represents single cache store.
*/
interface StoreInterface
{
/**
* Check if store is working properly. Please check if the store drives exists, files are
* writable, etc.
*
* @return bool
*/
public function isAvailable();
/**
* Check if value is present in cache.
*
* @param string $name Stored value name.
* @return bool
* @throws StoreException
*/
public function has($name);
/**
* Get value stored in cache.
*
* @param string $name Stored value name.
* @return mixed
* @throws StoreException
*/
public function get($name);
/**
* Save data in cache. Method will replace values created before.
*
* @param string $name
* @param mixed $data
* @param int $lifetime Duration in seconds until the value will expire.
* @return mixed
* @throws StoreException
*/
public function set($name, $data, $lifetime);
/**
* Store value in cache with infinite lifetime. Value will only expire when the cache is
* flushed.
*
* @param string $name
* @param mixed $data
* @return mixed
* @throws StoreException
*/
public function forever($name, $data);
/**
* Delete data from cache.
*
* @param string $name Stored value name.
* @throws StoreException
*/
public function delete($name);
/**
* Increment numeric value stored in cache. Must return incremented value.
*
* @param string $name
* @param int $delta How much to increment by. Set to 1 by default.
* @return int
* @throws StoreException
*/
public function inc($name, $delta = 1);
/**
* Decrement numeric value stored in cache. Must return decremented value.
*
* @param string $name
* @param int $delta How much to decrement by. Set to 1 by default.
* @return int
* @throws StoreException
*/
public function dec($name, $delta = 1);
/**
* Read item from cache and delete it afterwards.
*
* @param string $name Stored value name.
* @return mixed
* @throws StoreException
*/
public function pull($name);
/**
* Get the item from cache and if the item is missing, set a default value using Closure.
*
* @param string $name
* @param int $lifetime
* @param callback $callback Callback should be called if a value doesn't exist in cache.
* @return mixed
* @throws StoreException
*/
public function remember($name, $lifetime, $callback);
/**
* Flush all values stored in cache.
*
* @throws StoreException
*/
public function flush();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite\Schemas;
use Spiral\Database\Entities\Schemas\AbstractReference;
/**
* SQLite foreign key schema.
*/
class ReferenceSchema extends AbstractReference
{
/**
* {@inheritdoc}
*/
public function sqlStatement()
{
$statement = [];
$statement[] = 'FOREIGN KEY';
$statement[] = '(' . $this->table->driver()->identifier($this->column) . ')';
$statement[] = 'REFERENCES ' . $this->table->driver()->identifier($this->foreignTable);
$statement[] = '(' . $this->table->driver()->identifier($this->foreignKey) . ')';
$statement[] = "ON DELETE {$this->deleteRule}";
$statement[] = "ON UPDATE {$this->updateRule}";
return join(' ', $statement);
}
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->column = $schema['from'];
$this->foreignTable = $schema['table'];
$this->foreignKey = $schema['to'];
$this->deleteRule = $schema['on_delete'];
$this->updateRule = $schema['on_update'];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite\Schemas;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Entities\Schemas\AbstractCommander;
use Spiral\Database\Entities\Schemas\AbstractReference;
use Spiral\Database\Entities\Schemas\AbstractTable;
/**
* SQLite commander.
*/
class Commander extends AbstractCommander
{
/**
* {@inheritdoc}
*/
public function addColumn(AbstractTable $table, AbstractColumn $column)
{
//Not supported
}
/**
* {@inheritdoc}
*/
public function dropColumn(AbstractTable $table, AbstractColumn $column)
{
//Not supported
}
/**
* {@inheritdoc}
*/
public function alterColumn(
AbstractTable $table,
AbstractColumn $initial,
AbstractColumn $column
) {
//Not supported
}
/**
* {@inheritdoc}
*/
public function addForeign(AbstractTable $table, AbstractReference $foreign)
{
//Not supported
}
/**
* {@inheritdoc}
*/
public function dropForeign(AbstractTable $table, AbstractReference $foreign)
{
//Not supported
}
/**
* {@inheritdoc}
*/
public function alterForeign(
AbstractTable $table,
AbstractReference $initial,
AbstractReference $foreign
) {
//Not supported
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer;
use PDO;
use Spiral\Database\DatabaseInterface;
use Spiral\Database\Drivers\SQLServer\Schemas\Commander;
use Spiral\Database\Drivers\SQLServer\Schemas\TableSchema;
use Spiral\Database\Entities\Driver;
/**
* Talk to microsoft sql server databases.
*
* @todo UTF8?
*/
class SQLServerDriver extends Driver
{
/**
* Driver type.
*/
const TYPE = DatabaseInterface::SQL_SERVER;
/**
* Driver schemas.
*/
const SCHEMA_TABLE = TableSchema::class;
/**
* Commander used to execute commands. :)
*/
const COMMANDER = Commander::class;
/**
* Query result class.
*/
const QUERY_RESULT = QueryResult::class;
/**
* Query compiler class.
*/
const QUERY_COMPILER = QueryCompiler::class;
/**
* DateTime format to be used to perform automatic conversion of DateTime objects.
*
* @var string
*/
const DATETIME = 'Y-m-d\TH:i:s.000';
/**
* Default datetime value.
*/
const DEFAULT_DATETIME = '1970-01-01T00:00:00';
/**
* Default timestamp expression.
*/
const TIMESTAMP_NOW = 'getdate()';
/**
* @var array
*/
protected $options = [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_STRINGIFY_FETCHES => false
];
/**
* SQLServer version. Required for better LIMIT/OFFSET syntax.
*
* @link http://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server
* @var int
*/
protected $serverVersion = 0;
/**
* {@inheritdoc}
*/
public function identifier($identifier)
{
return $identifier == '*' ? '*' : '[' . str_replace('[', '[[', $identifier) . ']';
}
/**
* {@inheritdoc}
*/
public function hasTable($name)
{
$query = "SELECT COUNT(*) FROM information_schema.tables "
. "WHERE table_type = 'BASE TABLE' AND table_name = ?";
return (bool)$this->query($query, [$name])->fetchColumn();
}
/**
* {@inheritdoc}
*/
public function tableNames()
{
$query = "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE'";
$tables = [];
foreach ($this->query($query)->fetchMode(PDO::FETCH_NUM) as $row) {
$tables[] = $row[0];
}
return $tables;
}
/**
* SQLServer version.
*
* @link http://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server
* @return int
*/
public function serverVersion()
{
if (empty($this->serverVersion)) {
$this->serverVersion = (int)$this->getPDO()->getAttribute(\PDO::ATTR_SERVER_VERSION);
}
return $this->serverVersion;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Schemas;
/**
* Represents table schema column abstraction.
*/
interface ColumnInterface
{
/**
* Column name.
*
* @return string
*/
public function getName();
/**
* Internal database type, can vary based on database driver.
*
* @return string
*/
public function getType();
/**
* Must return PHP type column value can be better mapped into: int, bool, string or float.
*
* @return string
*/
public function phpType();
/**
* Column size.
*
* @return int
*/
public function getSize();
/**
* Column precision.
*
* @return int
*/
public function getPrecision();
/**
* Column scale value.
*
* @return int
*/
public function getScale();
/**
* Can column store null value?
*
* @return bool
*/
public function isNullable();
/**
* Indication that column has default value.
*
* @return bool
*/
public function hasDefaultValue();
/**
* Get column default value, value must be automatically converted to appropriate internal type.
*
* @return mixed
*/
public function getDefaultValue();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Validation\Checker;
/**
* String validations.
*/
class StringChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"regexp" => "[[Your value does not match required pattern.]]",
"shorter" => "[[Enter text shorter or equal to {0}.]]",
"longer" => "[[Your text must be longer or equal to {0}.]]",
"length" => "[[Your text length must be exactly equal to {0}.]]",
"range" => "[[Text length should be in range of {0}-{1}.]]"
];
/**
* Check string using regexp.
*
* @param string $string
* @param string $expression
* @return bool
*/
public function regexp($string, $expression)
{
return is_string($string) && preg_match($expression, $string);
}
/**
* Check if string length is shorter or equal that specified value.
*
* @param string $string
* @param int $length
* @return bool
*/
public function shorter($string, $length)
{
return mb_strlen($string) <= $length;
}
/**
* Check if string length is longer or equal that specified value.
*
* @param string $string
* @param int $length
* @return bool
*/
public function longer($string, $length)
{
return mb_strlen($string) >= $length;
}
/**
* Check if string length are equal to specified value.
*
* @param string $string
* @param int $length
* @return bool
*/
public function length($string, $length)
{
return mb_strlen($string) == $length;
}
/**
* Check if string length are fits in specified range.
*
* @param string $string
* @param int $lengthA
* @param int $lengthB
* @return bool
*/
public function range($string, $lengthA, $lengthB)
{
return (mb_strlen($string) >= $lengthA) && (mb_strlen($string) <= $lengthB);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Core\Component;
/**
* Isolators used to find and replace php blocks in given source. Can be used by view processors,
* or to remove php code from some string.
*/
class Isolator extends Component
{
/**
* Unique block id, required to generate unique placeholders.
*
* @var int
*/
private static $blockID = 0;
/**
* Found PHP blocks to be replaced.
*
* @var array
*/
private $phpBlocks = [];
/**
* Isolation prefix. Use any values that will not corrupt HTML or other source.
*
* @var string
*/
private $prefix = '';
/**
* Isolation postfix. Use any values that will not corrupt HTML or other source.
*
* @var string
*/
private $postfix = '';
/**
* Set of patterns to convert "disabled" php blocks into catchable (in terms of token_get_all)
* code. Will fix short tags using regular expressions. Legacy.
*
* @var array
*/
private $patterns = [];
/**
* Temporary block replaces. Used to "enable" php blocks.
*
* @var array
*/
private $replaces = [];
/**
* @param string $prefix Replaced block prefix, -php by default.
* @param string $postfix Replaced block postfix, block- by default.
* @param bool $shortTags Handle short tags. This is not required if short_tags are enabled.
*/
public function __construct($prefix = '-php-', $postfix = '-block-', $shortTags = true)
{
$this->prefix = $prefix;
$this->postfix = $postfix;
if ($shortTags) {
$this->addPattern('<?=', false, "<?php /*%s*/ echo ");
$this->addPattern('<?', '/<\?(?!php)/is');
}
}
/**
* Isolates all returned PHP blocks with a defined pattern. Method uses token_get_all function.
* Returned source have all php blocks replaces with non executable placeholder.
*
* @param string $source
* @return string
*/
public function isolatePHP($source)
{
//Replacing all
$source = $this->replaceTags($source);
$tokens = token_get_all($source);
$this->phpBlocks = [];
$phpBlock = false;
$blockID = 0;
$source = '';
foreach ($tokens as $token) {
if ($token[0] == T_OPEN_TAG || $token[0] == T_OPEN_TAG_WITH_ECHO) {
$phpBlock = $token[1];
continue;
}
if ($token[0] == T_CLOSE_TAG) {
$phpBlock .= $token[1];
$this->phpBlocks[$blockID] = $phpBlock;
$phpBlock = '';
$source .= $this->prefix . ($blockID++) . $this->postfix;
continue;
}
if (!empty($phpBlock)) {
$phpBlock .= is_array($token) ? $token[1] : $token;
} else {
$source .= is_array($token) ? $token[1] : $token;
}
}
foreach ($this->phpBlocks as &$phpBlock) {
//Will repair php source with correct (original) tags
$phpBlock = $this->restoreTags($phpBlock);
unset($phpBlock);
}
//Will restore tags which were replaced but weren't handled by php (for example string
//contents)
return $this->restoreTags($source);
}
/**
* Restore PHP blocks position in isolated source (isolatePHP() must be already called).
*
* @param string $source
* @return string
*/
public function repairPHP($source)
{
return preg_replace_callback(
'/' . preg_quote($this->prefix) . '(?P<id>[0-9]+)' . preg_quote($this->postfix) . '/',
[$this, 'getBlock'],
$source
);
}
/**
* Remove PHP blocks from isolated source (isolatePHP() must be already called).
*
* @param string $isolatedSource
* @return string
*/
public function removePHP($isolatedSource)
{
return preg_replace(
'/' . preg_quote($this->prefix) . '(?P<id>[0-9]+)' . preg_quote($this->postfix) . '/',
'',
$isolatedSource
);
}
/**
* Update isolator php blocks.
*
* @param array $phpBlocks
* @return $this
*/
public function setBlocks($phpBlocks)
{
$this->phpBlocks = $phpBlocks;
return $this;
}
/**
* List of all found and replaced php blocks.
*
* @return array
*/
public function getBlocks()
{
return $this->phpBlocks;
}
/**
* Reset isolator state.
*/
public function reset()
{
$this->phpBlocks = $this->replaces = [];
}
/**
* New pattern to fix untrackable blocks.
*
* @param string $name
* @param string $regexp
* @param string $replace
*/
protected function addPattern($name, $regexp = null, $replace = "<?php /*%s*/")
{
$this->patterns[$name] = [
'regexp' => $regexp,
'replace' => $replace
];
}
/**
* Get PHP block by it's ID.
*
* @param int $blockID
* @return mixed
*/
protected function getBlock($blockID)
{
if (!isset($this->phpBlocks[$blockID['id']])) {
return $blockID[0];
}
return $this->phpBlocks[$blockID['id']];
}
/**
* Replace all matched tags with their <?php equivalent. These tags will be detected and parsed
* by token_get_all() function even if there isn't a directive in php.ini file.
*
* @param string $source
* @return string
*/
private function replaceTags($source)
{
$replaces = &$this->replaces;
foreach ($this->patterns as $tag => $pattern) {
if (empty($pattern['regexp'])) {
if ($replace = array_search($tag, $replaces)) {
$source = str_replace($tag, $replace, $source);
continue;
}
$replace = sprintf($pattern['replace'], $this->getPlaceholder());
$replaces[$replace] = $tag;
//Replacing
$source = str_replace($tag, $replace, $source);
continue;
}
$source = preg_replace_callback(
$pattern['regexp'],
function ($tag) use (&$replaces, $pattern) {
$tag = $tag[0];
if ($key = array_search($tag, $replaces)) {
return $key;
}
$replace = sprintf($pattern['replace'], $this->getPlaceholder());
$replaces[$replace] = $tag;
return $replace;
},
$source
);
}
return $source;
}
/**
* Fix blocks altered by replaceTags() method.
*
* @see replaceTags()
* @param string $source
* @return string
*/
private function restoreTags($source)
{
return strtr($source, $this->replaces);
}
/**
* Get unique block placeholder for replacement.
*
* @return string
*/
private function getPlaceholder()
{
return md5(self::$blockID++ . '-' . uniqid('', true));
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Behaviours;
use Spiral\Stempler\BehaviourInterface;
/**
* Defines new block.
*/
class BlockBehaviour implements BehaviourInterface
{
/**
* @var string
*/
private $name = '';
/**
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* Created block name.
*
* @return string
*/
public function blockName()
{
return $this->name;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations\Traits;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\ORM\Exceptions\DefinitionException;
/**
* Trait provides ability for relation to cast columns in specified table using format identical to
* format used in record schema. Used by relations with pivot tables.
*/
trait ColumnsTrait
{
/**
* Cast table using set of columns and their default values.
*
* @param AbstractTable $table
* @param array $columns
* @param array $defaults
*/
protected function castTable(AbstractTable $table, array $columns, array $defaults)
{
foreach ($columns as $column => $definition) {
//Addition pivot columns must be defined same way as in Record schema
$column = $this->castColumn($table, $table->column($column), $definition);
if (!empty($defaults[$column->getName()])) {
$column->defaultValue($defaults[$column->getName()]);
}
}
}
/**
* Cast (specify) column schema based on provided column definition. Column definition are
* compatible with database Migrations, AbstractColumn types and Record schema.
*
* @param AbstractTable $table
* @param AbstractColumn $column
* @param string $definition
* @return AbstractColumn
* @throws DefinitionException
* @throws \Spiral\Database\Exceptions\SchemaException
*/
private function castColumn(AbstractTable $table, AbstractColumn $column, $definition)
{
//Expression used to declare column type, easy to read
$pattern = '/(?P<type>[a-z]+)(?: *\((?P<options>[^\)]+)\))?(?: *, *(?P<nullable>null(?:able)?))?/i';
if (!preg_match($pattern, $definition, $type)) {
throw new DefinitionException(
"Invalid column type definition in '{$this}'.'{$column->getName()}'."
);
}
if (!empty($type['options'])) {
//Exporting and trimming
$type['options'] = array_map('trim', explode(',', $type['options']));
}
//We are forcing every column to be NOT NULL by default, DEFAULT value should fix potential
//problems, nullable flag must be applied before type was set (some types do not want
//null values to be allowed)
$column->nullable(!empty($type['nullable']));
//Bypassing call to AbstractColumn->__call method (or specialized column method)
call_user_func_array(
[$column, $type['type']],
!empty($type['options']) ? $type['options'] : []
);
//Default value
if (!$column->hasDefaultValue() && !$column->isNullable()) {
//Ouch, columns like that can break synchronization!
$column->defaultValue($this->castDefault($table, $column));
}
return $column;
}
/**
* Cast default value based on column type. Required to prevent conflicts when not nullable
* column added to existed table with data in.
*
* @param AbstractTable $table
* @param AbstractColumn $column
* @return bool|float|int|mixed|string
*/
private function castDefault(AbstractTable $table, AbstractColumn $column)
{
if ($column->abstractType() == 'timestamp' || $column->abstractType() == 'datetime') {
$driver = $table->driver();
return $driver::DEFAULT_DATETIME;
}
if ($column->abstractType() == 'enum') {
//We can use first enum value as default
return $column->getEnumValues()[0];
}
switch ($column->phpType()) {
case 'int':
return 0;
break;
case 'float':
return 0.0;
break;
case 'bool':
return false;
break;
}
return '';
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer\Schemas;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Entities\Schemas\AbstractColumn;
/**
* SQL Server specific column schema.
*/
class ColumnSchema extends AbstractColumn
{
/**
* {@inheritdoc}
*/
protected $mapping = [
//Primary sequences
'primary' => [
'type' => 'int',
'identity' => true,
'nullable' => false
],
'bigPrimary' => [
'type' => 'bigint',
'identity' => true,
'nullable' => false
],
//Enum type (mapped via method)
'enum' => 'enum',
//Logical types
'boolean' => 'bit',
//Integer types (size can always be changed with size method), longInteger has method alias
//bigInteger
'integer' => 'int',
'tinyInteger' => 'tinyint',
'bigInteger' => 'bigint',
//String with specified length (mapped via method)
'string' => 'varchar',
//Generic types
'text' => ['type' => 'varchar', 'size' => 0],
'tinyText' => ['type' => 'varchar', 'size' => 0],
'longText' => ['type' => 'varchar', 'size' => 0],
//Real types
'double' => 'float',
'float' => 'real',
//Decimal type (mapped via method)
'decimal' => 'decimal',
//Date and Time types
'datetime' => 'datetime',
'date' => 'date',
'time' => 'time',
'timestamp' => 'datetime',
//Binary types
'binary' => ['type' => 'varbinary', 'size' => 0],
'tinyBinary' => ['type' => 'varbinary', 'size' => 0],
'longBinary' => ['type' => 'varbinary', 'size' => 0],
//Additional types
'json' => ['type' => 'varchar', 'size' => 0]
];
/**
* {@inheritdoc}
*/
protected $reverseMapping = [
'primary' => [['type' => 'int', 'identity' => true]],
'bigPrimary' => [['type' => 'bigint', 'identity' => true]],
'enum' => ['enum'],
'boolean' => ['bit'],
'integer' => ['int'],
'tinyInteger' => ['tinyint', 'smallint'],
'bigInteger' => ['bigint'],
'text' => [['type' => 'varchar', 'size' => 0]],
'string' => ['varchar', 'char'],
'double' => ['float'],
'float' => ['real'],
'decimal' => ['decimal'],
'timestamp' => ['datetime'],
'date' => ['date'],
'time' => ['time'],
'binary' => ['varbinary'],
];
/**
* Field is table identity.
*
* @var bool
*/
protected $identity = false;
/**
* Name of default constraint.
*
* @var string
*/
protected $defaultConstraint = '';
/**
* Name of enum constraint.
*
* @var string
*/
protected $enumConstraint = '';
/**
* {@inheritdoc}
*/
public function getConstraints()
{
$constraints = parent::getConstraints();
if (!empty($this->defaultConstraint)) {
$constraints[] = $this->defaultConstraint;
}
if (!empty($this->enumConstraint)) {
$constraints[] = $this->enumConstraint;
}
return $constraints;
}
/**
* {@inheritdoc}
*/
public function abstractType()
{
if (!empty($this->enumValues)) {
return 'enum';
}
return parent::abstractType();
}
/**
* {@inheritdoc}
*/
public function enum($values)
{
$this->enumValues = array_map('strval', is_array($values) ? $values : func_get_args());
sort($this->enumValues);
$this->type = 'varchar';
foreach ($this->enumValues as $value) {
$this->size = max((int)$this->size, strlen($value));
}
return $this;
}
/**
* {@inheritdoc}
*
* @param bool $ignoreEnum If true ENUM declaration statement will be returned only. Internal
* helper.
*/
public function sqlStatement($ignoreEnum = false)
{
if (!$ignoreEnum && $this->abstractType() == 'enum') {
return "{$this->sqlStatement(true)} {$this->enumStatement()}";
}
$statement = [$this->getName(true), $this->type];
if (!empty($this->precision)) {
$statement[] = "({$this->precision}, {$this->scale})";
} elseif (!empty($this->size)) {
$statement[] = "({$this->size})";
} elseif ($this->type == 'varchar' || $this->type == 'varbinary') {
$statement[] = "(max)";
}
if ($this->identity) {
$statement[] = 'IDENTITY(1,1)';
}
$statement[] = $this->nullable ? 'NULL' : 'NOT NULL';
if ($this->hasDefaultValue()) {
$statement[] = "DEFAULT {$this->prepareDefault()}";
}
return join(' ', $statement);
}
/**
* Generate set of altering operations should be applied to column to change it's type, size,
* default value or null flag.
*
* @param ColumnSchema $initial
* @return array
*/
public function alteringOperations(ColumnSchema $initial)
{
$operations = [];
$currentDefinition = [
$this->type,
$this->size,
$this->precision,
$this->scale,
$this->nullable
];
$initialDefinition = [
$initial->type,
$initial->size,
$initial->precision,
$initial->scale,
$initial->nullable
];
if ($currentDefinition != $initialDefinition) {
if ($this->abstractType() == 'enum') {
//Getting longest value
$enumSize = $this->size;
foreach ($this->enumValues as $value) {
$enumSize = max($enumSize, strlen($value));
}
$type = "ALTER COLUMN {$this->getName(true)} varchar($enumSize)";
$operations[] = $type . ' ' . ($this->nullable ? 'NULL' : 'NOT NULL');
} else {
$type = "ALTER COLUMN {$this->getName(true)} {$this->type}";
if (!empty($this->size)) {
$type .= "($this->size)";
} elseif ($this->type == 'varchar' || $this->type == 'varbinary') {
$type .= "(max)";
} elseif (!empty($this->precision)) {
$type .= "($this->precision, $this->scale)";
}
$operations[] = $type . ' ' . ($this->nullable ? 'NULL' : 'NOT NULL');
}
}
//Constraint should be already removed it this moment (see doColumnChange in TableSchema)
if ($this->hasDefaultValue()) {
$operations[] = \Spiral\interpolate(
"ADD CONSTRAINT {constraint} DEFAULT {default} FOR {column}",
[
'constraint' => $this->defaultConstrain(true),
'column' => $this->getName(true),
'default' => $this->prepareDefault()
]
);
}
//Constraint should be already removed it this moment (see doColumnChange in TableSchema)
if ($this->abstractType() == 'enum') {
$operations[] = "ADD {$this->enumStatement()}";
}
return $operations;
}
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->type = $schema['DATA_TYPE'];
$this->nullable = strtoupper($schema['IS_NULLABLE']) == 'YES';
$this->defaultValue = $schema['COLUMN_DEFAULT'];
$this->identity = (bool)$schema['is_identity'];
$this->size = (int)$schema['CHARACTER_MAXIMUM_LENGTH'];
if ($this->size == -1) {
$this->size = 0;
}
if ($this->type == 'decimal') {
$this->precision = (int)$schema['NUMERIC_PRECISION'];
$this->scale = (int)$schema['NUMERIC_SCALE'];
}
//Normalizing default value
$this->normalizeDefault();
/**
* We have to fetch all column constrains cos default and enum check will be included into
* them, plus column drop is not possible without removing all constraints.
*/
$tableDriver = $this->table->driver();
if (!empty($schema['default_object_id'])) {
//Looking for default constrain id
$this->defaultConstraint = $tableDriver->query(
"SELECT name FROM sys.default_constraints WHERE object_id = ?", [
$schema['default_object_id']
])->fetchColumn();
}
//Potential enum
if ($this->type == 'varchar' && !empty($this->size)) {
$this->resolveEnum($schema, $tableDriver);
}
}
/**
* {@inheritdoc}
*/
protected function prepareDefault()
{
$defaultValue = parent::prepareDefault();
if ($this->abstractType() == 'boolean') {
$defaultValue = (int)$this->defaultValue;
}
return $defaultValue;
}
/**
* Get name of enum constraint.
*
* @param bool $quoted True to quote identifier.
* @return string
*/
protected function enumConstraint($quoted = false)
{
if (empty($this->enumConstraint)) {
$this->enumConstraint = $this->generateName('enum');
}
return $quoted
? $this->table->driver()->identifier($this->enumConstraint)
: $this->enumConstraint;
}
/**
* Default constrain name.
*
* @param bool $quoted
* @return string
*/
protected function defaultConstrain($quoted = false)
{
if (empty($this->defaultConstraint)) {
$this->defaultConstraint = $this->generateName('default');
}
return $quoted
? $this->table->driver()->identifier($this->defaultConstraint)
: $this->defaultConstraint;
}
/**
* Enum constrain statement.
*
* @return string
*/
private function enumStatement()
{
$enumValues = [];
foreach ($this->enumValues as $value) {
$enumValues[] = $this->table->driver()->getPDO()->quote($value);
}
$enumConstrain = $this->enumConstraint(true);
$enumValues = join(', ', $enumValues);
return "CONSTRAINT {$enumConstrain} CHECK ({$this->getName(true)} IN ({$enumValues}))";
}
/**
* Normalizing default value.
*/
private function normalizeDefault()
{
if (
$this->defaultValue[0] == '('
&& $this->defaultValue[strlen($this->defaultValue) - 1] == ')'
) {
//Cut braces
$this->defaultValue = substr($this->defaultValue, 1, -1);
}
if (preg_match('/^[\'""].*?[\'"]$/', $this->defaultValue)) {
$this->defaultValue = substr($this->defaultValue, 1, -1);
}
if (
$this->phpType() != 'string'
&& (
$this->defaultValue[0] == '('
&& $this->defaultValue[strlen($this->defaultValue) - 1] == ')'
)
) {
//Cut another braces
$this->defaultValue = substr($this->defaultValue, 1, -1);
}
}
/**
* Check if column is enum.
*
* @param array $schema
* @param Driver $tableDriver
*/
private function resolveEnum(array $schema, $tableDriver)
{
$query = "SELECT object_definition(o.object_id) AS [definition], "
. "OBJECT_NAME(o.OBJECT_ID) AS [name]\nFROM sys.objects AS o\n"
. "JOIN sys.sysconstraints AS [c] ON o.object_id = [c].constid\n"
. "WHERE type_desc = 'CHECK_CONSTRAINT' AND parent_object_id = ? AND [c].colid = ?";
$constraints = $tableDriver->query($query, [$schema['object_id'], $schema['column_id']]);
foreach ($constraints as $checkConstraint) {
$this->enumConstraint = $checkConstraint['name'];
$name = preg_quote($this->getName(true));
//We made some assumptions here...
if (preg_match_all(
'/' . $name . '=[\']?([^\']+)[\']?/i',
$checkConstraint['definition'],
$matches
)) {
//Fetching enum values
$this->enumValues = $matches[1];
sort($this->enumValues);
}
}
}
/**
* Generate constrain name.
*
* @param string $type
* @return string
*/
private function generateName($type)
{
return $this->table->getName() . '_' . $this->getName() . "_{$type}_" . uniqid();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core\Container;
/**
* Class treated as singleton MAY be saved as reference in IoC bindings - this is spiral Container
* specific class. Must declare SINGLETON constant.
*
* @todo potentially deprecated
*/
interface SingletonInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer\Schemas;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Entities\Schemas\AbstractCommander;
use Spiral\Database\Entities\Schemas\AbstractIndex;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Exceptions\SchemaException;
/**
* SQLServer commander.
*/
class Commander extends AbstractCommander
{
/**
* Rename table from one name to another.
*
* @param string $table
* @param string $name
* @return self
*/
public function renameTable($table, $name)
{
$this->run("sp_rename @objname = ?, @newname = ?", [$table, $name]);
return $this;
}
/**
* Driver specific column add command.
*
* @param AbstractTable $table
* @param AbstractColumn $column
* @return self
*/
public function addColumn(AbstractTable $table, AbstractColumn $column)
{
$this->run("ALTER TABLE {$table->getName(true)} ADD {$column->sqlStatement()}");
return $this;
}
/**
* Driver specific column alter command.
*
* @param AbstractTable $table
* @param AbstractColumn $initial
* @param AbstractColumn $column
* @return self
*/
public function alterColumn(
AbstractTable $table,
AbstractColumn $initial,
AbstractColumn $column
) {
if (!$initial instanceof ColumnSchema || !$column instanceof ColumnSchema) {
throw new SchemaException("SQlServer commander can work only with Postgres columns.");
}
if ($column->getName() != $initial->getName()) {
//Renaming is separate operation
$this->run("sp_rename ?, ?, 'COLUMN'", [
$table->getName() . '.' . $initial->getName(),
$column->getName()
]);
}
//In SQLServer we have to drop ALL related indexes and foreign keys while
//applying type change... yeah...
$indexesBackup = [];
$foreignBackup = [];
foreach ($table->getIndexes() as $index) {
if (in_array($column->getName(), $index->getColumns())) {
$indexesBackup[] = $index;
$this->dropIndex($table, $index);
}
}
foreach ($table->getForeigns() as $foreign) {
if ($foreign->getColumn() == $column->getName()) {
$foreignBackup[] = $foreign;
$this->dropForeign($table, $foreign);
}
}
//Column will recreate needed constraints
foreach ($column->getConstraints() as $constraint) {
$this->dropConstrain($table, $constraint);
}
foreach ($column->alteringOperations($initial) as $operation) {
$this->run("ALTER TABLE {$table->getName(true)} {$operation}");
}
//Restoring indexes and foreign keys
foreach ($indexesBackup as $index) {
$this->addIndex($table, $index);
}
foreach ($foreignBackup as $foreign) {
$this->addForeign($table, $foreign);
}
return $this;
}
/**
* Driver specific index remove (drop) command.
*
* @param AbstractTable $table
* @param AbstractIndex $index
* @return self
*/
public function dropIndex(AbstractTable $table, AbstractIndex $index)
{
$this->run("DROP INDEX {$index->getName(true)} ON {$table->getName(true)}");
return $this;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite\Schemas;
use Spiral\Database\Entities\Schemas\AbstractIndex;
/**
* SQLite index schema.
*/
class IndexSchema extends AbstractIndex
{
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->name = $schema['name'];
$this->type = $schema['unique'] ? self::UNIQUE : self::NORMAL;
$indexColumns = $this->table->driver()->query("PRAGMA INDEX_INFO({$this->getName(true)})");
foreach ($indexColumns as $column) {
$this->columns[] = $column['name'];
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Exceptions;
use Spiral\Core\Exceptions\ExceptionInterface;
/**
* Exception related to error while working with DataEntity.
*/
interface EntityExceptionInterface extends ExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Schemas;
use Spiral\ORM\Entities\SchemaBuilder;
use Spiral\ORM\Entities\Schemas\RecordSchema;
use Spiral\ORM\Exceptions\RecordSchemaException;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\Exceptions\SchemaException;
/**
* RelationSchema is responsible for clarification of inner and outer record schemas (for example it
* might declare required columns, indexes and foreign keys). In addition every RelationSchema must
* pack it's definition it cachable form which will be later feeded to record Relation and will be
* used as set of instructions
*/
interface RelationInterface
{
/**
* @param SchemaBuilder $builder
* @param RecordSchema $record
* @param string $name
* @param array $definition
* @throws RelationSchemaException
*/
public function __construct(
SchemaBuilder $builder,
RecordSchema $record,
$name,
array $definition
);
/**
* Relation name.
*
* @return string
*/
public function getName();
/**
* Relation type. Check ORM config to see where relation types declared.
*
* @return int
*/
public function getType();
/**
* Check if relation has it's equivalent. For example if relation associated to a specific
* record
* (or, like in case with polymorphic relations to interface) it can declare alternative
* relation definition with different relation type.
*
* @return bool
*/
public function hasEquivalent();
/**
* Get definition for equivalent (usually polymorphic relationship) relation. For example this
* method can route to ODM relations if outer record is instance of Document.
*
* @return RelationInterface
* @throws RelationSchemaException
* @throws RecordSchemaException
*/
public function createEquivalent();
/**
* Check if relation definition contains request to be reverted. Inversion used in cases when
* inner and outer records wants to have relations to each other.
*
* @return bool
*/
public function isInversable();
/**
* Check if it's reasonable to create relation, creation must be skipped if outer record is
* abstract or relation under such name already exists.
*
* @return bool
*/
public function isReasonable();
/**
* Must declare inversed (reverted) relation in outer record schema. Relation must not be
* created if it's name already taken.
*
* @throws RelationSchemaException
* @throws SchemaException
* @throws RelationSchemaException
*/
public function inverseRelation();
/**
* Create all required relation columns, indexes and constraints.
*
* @throws RelationSchemaException
* @throws \Spiral\Database\Exceptions\SchemaException
*/
public function buildSchema();
/**
* Pack relation data into normalized structured to be used in cached ORM schema.
*
* @return array
*/
public function normalizeSchema();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Relations;
use Spiral\ORM\RecordEntity;
/**
* Represents simple HAS_MANY relation with pre-defined WHERE query for generated selector.
*
* You have to pre-populate WHERE conditional field in associated records manually, create() method
* not filling them.
*/
class HasMany extends HasOne
{
/**
* Relation type, required to fetch record class from relation definition.
*/
const RELATION_TYPE = RecordEntity::HAS_MANY;
/**
* Indication that relation represent multiple records (HAS_MANY relations).
*/
const MULTIPLE = true;
/**
* {@inheritdoc}
*/
protected function createSelector()
{
$selector = parent::createSelector();
if (isset($this->definition[RecordEntity::WHERE])) {
$selector->where(
$this->mountAlias($selector->primaryAlias(), $this->definition[RecordEntity::WHERE])
);
}
return $selector;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Models\AccessorInterface;
use Spiral\Models\ActiveEntityInterface;
use Spiral\Models\EntityInterface;
use Spiral\Models\Events\EntityEvent;
use Spiral\ODM\Entities\DocumentSelector;
use Spiral\ODM\Entities\DocumentSource;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\DocumentException;
use Spiral\ODM\Exceptions\ODMException;
use Spiral\ODM\Traits\FindTrait;
/**
* DocumentEntity with added ActiveRecord methods and ability to connect to associated source.
*
* Document also provides an ability to specify aggregations using it's schema:
*
* protected $schema = [
* ...,
* 'outer' => [self::ONE => Outer::class, [ //Reference to outer document using internal
* '_id' => 'self::outerID' //outerID value
* ]],
* 'many' => [self::MANY => Outer::class, [ //Reference to many outer document using
* 'innerID' => 'self::_id' //document primary key
* ]]
* ];
*
* Note: self::{name} construction will be replaced with document value in resulted query, even
* in case of arrays ;) You can also use dot notation to get value from nested document.
*
* @var array
*/
class Document extends DocumentEntity implements ActiveEntityInterface
{
/**
* Static find method.
*/
use FindTrait;
/**
* Indication that save methods must be validated by default, can be altered by calling save
* method with user arguments.
*/
const VALIDATE_SAVE = true;
/**
* Collection name where document should be stored into.
*
* @var string
*/
protected $collection = null;
/**
* Database name/id where document related collection located in.
*
* @var string|null
*/
protected $database = null;
/**
* Set of indexes to be created for associated collection. Use self::INDEX_OPTIONS or "@options"
* for additional parameters.
*
* Example:
* protected $indexes = [
* ['email' => 1, '@options' => ['unique' => true]],
* ['name' => 1]
* ];
*
* @link http://php.net/manual/en/mongocollection.ensureindex.php
* @var array
*/
protected $indexes = [];
/**
* @see Component::staticContainer()
* @param array $fields
* @param EntityInterface $parent
* @param ODM $odm
* @param array $odmSchema
*/
public function __construct(
$fields = [],
EntityInterface $parent = null,
ODM $odm = null,
$odmSchema = null
) {
parent::__construct($fields, $parent, $odm, $odmSchema);
if ((!$this->isLoaded() && !$this->isEmbedded())) {
//Document is newly created instance
$this->solidState(true)->invalidate();
}
}
/**
* {@inheritdoc}
*
* @return \MongoId|null
*/
public function primaryKey()
{
return isset($this->fields['_id']) ? $this->fields['_id'] : null;
}
/**
* {@inheritdoc}
*/
public function isLoaded()
{
return (bool)$this->primaryKey();
}
/**
* {@inheritdoc}
*
* Create or update document data in database.
*
* @param bool|null $validate Overwrite default option declared in VALIDATE_SAVE to force or
* disable validation before saving.
* @throws DocumentException
* @event saving()
* @event saved()
* @event updating()
* @event updated()
*/
public function save($validate = null)
{
$validate = !is_null($validate) ? $validate : static::VALIDATE_SAVE;
if ($validate && !$this->isValid()) {
//Using default model behaviour
return false;
}
if ($this->isEmbedded()) {
throw new DocumentException(
"Embedded document '" . get_class($this) . "' can not be saved into collection."
);
}
//Associated collection
$collection = $this->mongoCollection();
if (!$this->isLoaded()) {
$this->dispatch('saving', new EntityEvent($this));
unset($this->fields['_id']);
//Create new document
$collection->insert($this->fields = $this->serializeData());
$this->dispatch('saved', new EntityEvent($this));
} elseif ($this->isSolid() || $this->hasUpdates()) {
$this->dispatch('updating', new EntityEvent($this));
//Update existed document
$collection->update(['_id' => $this->primaryKey()], $this->buildAtomics());
$this->dispatch('updated', new EntityEvent($this));
}
$this->flushUpdates();
return true;
}
/**
* {@inheritdoc}
*
* @throws DocumentException
* @event deleting()
* @event deleted()
*/
public function delete()
{
if ($this->isEmbedded()) {
throw new DocumentException(
"Embedded document '" . get_class($this) . "' can not be deleted from collection."
);
}
$this->dispatch('deleting', new EntityEvent($this));
if ($this->isLoaded()) {
$this->mongoCollection()->remove(['_id' => $this->primaryKey()]);
}
$this->fields = $this->odmSchema()[ODM::D_DEFAULTS];
$this->dispatch('deleted', new EntityEvent($this));
}
/**
* {@inheritdoc} See DataEntity class.
*
* ODM: Get instance of Collection or Document associated with described aggregation.
*
* Example:
* $parentGroup = $user->group();
* echo $user->posts()->where(['published' => true])->count();
*
* @return mixed|AccessorInterface|DocumentSelector|Document[]|Document
* @throws DocumentException
*/
public function __call($offset, array $arguments)
{
if (!isset($this->odmSchema()[ODM::D_AGGREGATIONS][$offset])) {
//Field getter/setter
return parent::__call($offset, $arguments);
}
return $this->aggregate($offset);
}
/**
* Get document aggregation.
*
* @param string $aggregation
* @return DocumentSelector|Document
*/
public function aggregate($aggregation)
{
if (!isset($this->odmSchema()[ODM::D_AGGREGATIONS][$aggregation])) {
throw new DocumentException("Undefined aggregation '{$aggregation}'.");
}
$aggregation = $this->odmSchema()[ODM::D_AGGREGATIONS][$aggregation];
//Query preparations
$query = $this->interpolateQuery($aggregation[ODM::AGR_QUERY]);
//Every aggregation works thought ODM collection
$selector = $this->odm->selector($aggregation[ODM::ARG_CLASS], $query);
//In future i might need separate class to represent aggregation
if ($aggregation[ODM::AGR_TYPE] == self::ONE) {
return $selector->findOne();
}
return $selector;
}
/**
* @return array
*/
public function __debugInfo()
{
if (empty($this->collection)) {
return [
'fields' => $this->getFields(),
'atomics' => $this->hasUpdates() ? $this->buildAtomics() : [],
'errors' => $this->getErrors()
];
}
return [
'collection' => $this->odmSchema()[ODM::D_DB] . '/' . $this->collection,
'fields' => $this->getFields(),
'atomics' => $this->hasUpdates() ? $this->buildAtomics() : [],
'errors' => $this->getErrors()
];
}
/**
* Instance of ODM Selector associated with specific document.
*
* @see Component::staticContainer()
* @param ODM $odm ODM component, global container will be called if not instance provided.
* @return DocumentSource
* @throws ODMException
* @throws SugarException
*/
public static function source(ODM $odm = null)
{
if (empty($odm)) {
if (empty(self::staticContainer())) {
throw new SugarException("Unable to get document source, no shared container found.");
}
//Using global container as fallback
$odm = self::staticContainer()->get(ODM::class);
}
return $odm->source(static::class);
}
/**
* {@inheritdoc}
*
* Accessor options include field type resolved by DocumentSchema.
*
* @throws ODMException
* @throws DefinitionException
*/
protected function createAccessor($accessor, $value)
{
$accessor = parent::createAccessor($accessor, $value);
if (
$accessor instanceof CompositableInterface
&& !$this->isLoaded()
&& !$this->isEmbedded()
) {
//Newly created object
$accessor->invalidate();
}
return $accessor;
}
/**
* Interpolate aggregation query with document values.
*
* @param array $query
* @return array
*/
protected function interpolateQuery(array $query)
{
$fields = $this->fields;
array_walk_recursive($query, function (&$value) use ($fields) {
if (strpos($value, 'self::') === 0) {
$value = $this->dotGet(substr($value, 6));
}
});
return $query;
}
/**
* Get field value using dot notation.
*
* @param string $name
* @return mixed|null
*/
private function dotGet($name)
{
/**
* @var EntityInterface|AccessorInterface|array $source
*/
$source = $this;
$path = explode('.', $name);
foreach ($path as $step) {
if ($source instanceof EntityInterface) {
if (!$source->hasField($step)) {
return null;
}
//Sub entity
$source = $source->getField($step);
continue;
}
if ($source instanceof AccessorInterface) {
$source = $source->serializeData();
continue;
}
if (is_array($source) && array_key_exists($step, $source)) {
$source = &$source[$step];
continue;
}
//Unable to resolve value, an exception required here
return null;
}
return $source;
}
/**
* Associated mongo collection.
*
* @return \MongoCollection
*/
private function mongoCollection()
{
return $this->odm->mongoCollection(static::class);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL\Schemas;
use Spiral\Database\Entities\Schemas\AbstractReference;
/**
* MySQL foreign key schema.
*/
class ReferenceSchema extends AbstractReference
{
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->column = $schema['COLUMN_NAME'];
$this->foreignTable = $schema['REFERENCED_TABLE_NAME'];
$this->foreignKey = $schema['REFERENCED_COLUMN_NAME'];
$this->deleteRule = $schema['DELETE_RULE'];
$this->updateRule = $schema['UPDATE_RULE'];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Models\AccessorInterface;
use Spiral\Models\EntityInterface;
use Spiral\Models\Events\EntityEvent;
use Spiral\Models\SchematicEntity;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\DocumentException;
use Spiral\ODM\Exceptions\FieldException;
use Spiral\ODM\Exceptions\ODMException;
/**
* DocumentEntity is base data model for ODM component, it describes it's own schema,
* compositions, validations and etc. ODM component will automatically analyze existed
* Documents and create cached version of their schema.
*
* Can create set of mongo atomic operations and be embedded into other documents.
*/
abstract class DocumentEntity extends SchematicEntity implements CompositableInterface
{
/**
* Optional constructor arguments.
*/
use SaturateTrait;
/**
* We are going to inherit parent validation rules, this will let spiral translator know about
* it and merge i18n messages.
*
* @see TranslatorTrait
*/
const I18N_INHERIT_MESSAGES = true;
/**
* Helper constant to identify atomic SET operations.
*/
const ATOMIC_SET = '$set';
/**
* Tells ODM component that Document class must be resolved using document fields. ODM must
* match fields to every child of this documents and find best match. This is default definition
* behaviour.
*
* Example:
* > Class A: _id, name, address
* > Class B extends A: _id, name, address, email
* < Class B will be used to represent all documents with existed email field.
*
* @see DocumentSchema
*/
const DEFINITION_FIELDS = 1;
/**
* Tells ODM that logical method (defineClass) must be used to define document class. Method
* will receive document fields as input and must return document class name.
*
* Example:
* > Class A: _id, name, type (a)
* > Class B extends A: _id, name, type (b)
* > Class C extends B: _id, name, type (c)
* < Static method in class A (parent) should return A, B or C based on type field value (as
* example).
*
* Attention, ODM will always ask TOP PARENT (in collection) to define class when you loading
* documents from collections.
*
* @see defineClass($fields)
* @see DocumentSchema
*/
const DEFINITION_LOGICAL = 2;
/**
* Indication to ODM component of method to resolve Document class using it's fieldset. This
* constant is required due Document can inherit another Document.
*/
const DEFINITION = self::DEFINITION_FIELDS;
/**
* Automatically convert "_id" to "id" in publicFields() method.
*/
const REMOVE_ID_UNDERSCORE = true;
/**
* Additional index options must be located under this key.
*/
const INDEX_OPTIONS = '@options';
/**
* Constants used to describe aggregation relations.
*
* Example:
* 'items' => [self::MANY => 'Models\Database\Item', [
* 'parentID' => 'key::_id'
* ]]
*
* @see Document::$schema
*/
const MANY = 778;
const ONE = 899;
/**
* Errors in nested documents and acessors.
*
* @var array
*/
private $nestedErrors = [];
/**
* Model schema provided by ODM compoent.
*
* @var array
*/
private $odmSchema = [];
/**
* SolidState will force document to be saved as one big data set without any atomic operations
* (dirty fields).
*
* @var bool
*/
private $solidState = false;
/**
* Document field updates (changed values).
*
* @var array
*/
private $updates = [];
/**
* User specified set of atomic operation to be applied to document on save() call.
*
* @var array
*/
private $atomics = [];
/**
* Document fields, accessors and relations. ODM will generate setters and getters for some
* fields based on their types.
*
* Example, fields:
* protected $schema = [
* '_id' => 'MongoId', //Primary key field
* 'value' => 'string', //Default string field
* 'values' => ['string'] //ScalarArray accessor will be applied for fields like that
* ];
*
* Compositions:
* protected $schema = [
* ...,
* 'child' => Child::class, //One document are composited, for example user Profile
* 'many' => [Child::class] //Compositor accessor will be applied, allows to
* composite
* //many document instances
* ];
*
* Documents can extend each other, in this case schema will also be inherited.
*
* @var array
*/
protected $schema = [];
/**
* Default field values.
*
* @var array
*/
protected $defaults = [];
/**
* @invisible
* @var EntityInterface
*/
protected $parent = null;
/**
* @invisible
* @var ODM
*/
protected $odm = null;
/**
* @param array $fields
* @param EntityInterface $parent
* @param ODM $odm
* @param array $odmSchema
* @throws SugarException
*/
public function __construct(
$fields = [],
EntityInterface $parent = null,
ODM $odm = null,
$odmSchema = null
) {
$this->parent = $parent;
//We can use global container as fallback if no default values were provided
$this->odm = $this->saturate($odm, ODM::class);
$this->odmSchema = !empty($odmSchema)
? $odmSchema
: $this->odm->schema(static::class);
if (empty($fields)) {
$this->invalidate();
}
$fields = is_array($fields) ? $fields : [];
if (!empty($this->odmSchema[ODM::D_DEFAULTS])) {
//Merging with default values
$fields = array_replace_recursive($this->odmSchema[ODM::D_DEFAULTS], $fields);
}
parent::__construct($fields, $this->odmSchema);
}
/**
* Change document solid state. SolidState will force document to be saved as one big data set
* without any atomic operations (dirty fields).
*
* @param bool $solidState
* @param bool $forceUpdate Mark all fields as changed to force update later.
* @return $this
*/
public function solidState($solidState, $forceUpdate = false)
{
$this->solidState = $solidState;
if ($forceUpdate) {
$this->updates = $this->odmSchema[ODM::D_DEFAULTS];
}
return $this;
}
/**
* Is document is solid state?
*
* @see solidState()
* @return bool
*/
public function isSolid()
{
return $this->solidState;
}
/**
* Check if document has parent.
*
* @return bool
*/
public function isEmbedded()
{
return !empty($this->parent);
}
/**
* {@inheritdoc}
*/
public function embed(EntityInterface $parent)
{
if (empty($this->parent)) {
$this->parent = $parent;
//Moving under new parent
return $this->solidState(true, true);
}
if ($parent === $this->parent) {
return $this;
}
/**
* @var Document $document
*/
$document = new static($this->serializeData(), $parent, $this->odm, $this->odmSchema);
return $document->solidState(true, true);
}
/**
* {@inheritdoc}
*/
public function setValue($data)
{
return $this->setFields($data);
}
/**
* {@inheritdoc}
*
* Must track field updates.
*/
public function setField($name, $value, $filter = true)
{
if (!array_key_exists($name, $this->fields)) {
throw new FieldException("Undefined field '{$name}' in '" . static::class . "'.");
}
$original = isset($this->fields[$name]) ? $this->fields[$name] : null;
parent::setField($name, $value, $filter);
if (!array_key_exists($name, $this->updates)) {
$this->updates[$name] = $original instanceof AccessorInterface
? $original->serializeData()
: $original;
}
}
/**
* {@inheritdoc}
*
* Will restore default value if presented.
*/
public function __unset($offset)
{
if (!array_key_exists($offset, $this->updates)) {
//Let document know that field value changed, but without overwriting previous change
$this->updates[$offset] = isset($this->odmSchema[ODM::D_DEFAULTS][$offset])
? $this->odmSchema[ODM::D_DEFAULTS][$offset]
: null;
}
$this->fields[$offset] = null;
if (isset($this->odmSchema[ODM::D_DEFAULTS][$offset])) {
//Restoring default value if presented (required for typecasting)
$this->fields[$offset] = $this->odmSchema[ODM::D_DEFAULTS][$offset];
}
}
/**
* Alias for atomic operation $set. Attention, this operation is not identical to setField()
* method, it performs low level operation and can be used only on simple fields. No filters
* will be applied to field!
*
* @param string $field
* @param mixed $value
* @return $this
* @throws DocumentException
*/
public function set($field, $value)
{
if ($this->hasUpdates($field, true)) {
throw new FieldException(
"Unable to apply multiple atomic operation to field '{$field}'."
);
}
$this->atomics[self::ATOMIC_SET][$field] = $value;
$this->fields[$field] = $value;
return $this;
}
/**
* Alias for atomic operation $inc.
*
* @param string $field
* @param string $value
* @return $this
* @throws DocumentException
*/
public function inc($field, $value)
{
if ($this->hasUpdates($field, true) && !isset($this->atomics['$inc'][$field])) {
throw new FieldException(
"Unable to apply multiple atomic operation to field '{$field}'."
);
}
if (!isset($this->atomics['$inc'][$field])) {
$this->atomics['$inc'][$field] = 0;
}
$this->atomics['$inc'][$field] += $value;
$this->fields[$field] += $value;
return $this;
}
/**
* {@inheritdoc}
*
* Include every composition public data into result.
*/
public function publicFields()
{
$result = [];
foreach ($this->fields as $field => $value) {
if (in_array($field, $this->odmSchema[ODM::D_HIDDEN])) {
//We might need to use isset in future, for performance
continue;
}
/**
* @var mixed|array|DocumentAccessorInterface|CompositableInterface
*/
$value = $this->getField($field);
if ($value instanceof CompositableInterface) {
$result[$field] = $value->publicFields();
continue;
}
if ($value instanceof \MongoId) {
$value = (string)$value;
}
if (is_array($value)) {
array_walk_recursive($value, function (&$value) {
if ($value instanceof \MongoId) {
$value = (string)$value;
}
});
}
if (static::REMOVE_ID_UNDERSCORE && $field == '_id') {
$field = 'id';
}
$result[$field] = $value;
}
return $result;
}
/**
* {@inheritdoc}
*
* @param string $field Specific field name to check for updates.
* @param bool $atomicsOnly Check if field has any atomic operation associated with.
*/
public function hasUpdates($field = null, $atomicsOnly = false)
{
if (empty($field)) {
if (!empty($this->updates) || !empty($this->atomics)) {
return true;
}
foreach ($this->fields as $field => $value) {
if ($value instanceof DocumentAccessorInterface && $value->hasUpdates()) {
return true;
}
}
return false;
}
foreach ($this->atomics as $operations) {
if (array_key_exists($field, $operations)) {
//Property already changed by atomic operation
return true;
}
}
if ($atomicsOnly) {
return false;
}
if (array_key_exists($field, $this->updates)) {
return true;
}
$value = $this->getField($field);
if ($value instanceof DocumentAccessorInterface && $value->hasUpdates()) {
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function flushUpdates()
{
$this->updates = $this->atomics = [];
foreach ($this->fields as $value) {
if ($value instanceof DocumentAccessorInterface) {
$value->flushUpdates();
}
}
}
/**
* {@inheritdoc}
*/
public function buildAtomics($container = '')
{
if (!$this->hasUpdates() && !$this->isSolid()) {
return [];
}
if ($this->isSolid()) {
if (!empty($container)) {
//Simple nested document in solid state
return [self::ATOMIC_SET => [$container => $this->serializeData()]];
}
//Direct document save
$atomics = [self::ATOMIC_SET => $this->serializeData()];
unset($atomics[self::ATOMIC_SET]['_id']);
return $atomics;
}
if (empty($container)) {
$atomics = $this->atomics;
} else {
$atomics = [];
foreach ($this->atomics as $atomic => $fields) {
foreach ($fields as $field => $value) {
$atomics[$atomic][$container . '.' . $field] = $value;
}
}
}
foreach ($this->fields as $field => $value) {
if ($field == '_id') {
continue;
}
if ($value instanceof DocumentAccessorInterface) {
$atomics = array_merge_recursive(
$atomics,
$value->buildAtomics(($container ? $container . '.' : '') . $field)
);
continue;
}
foreach ($atomics as $atomic => $operations) {
if (array_key_exists($field, $operations) && $atomic != self::ATOMIC_SET) {
//Property already changed by atomic operation
continue;
}
}
if (array_key_exists($field, $this->updates)) {
//Generating set operation for changed field
$atomics[self::ATOMIC_SET][($container ? $container . '.' : '') . $field] = $value;
}
}
return $atomics;
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'fields' => $this->getFields(),
'atomics' => $this->hasUpdates() ? $this->buildAtomics() : [],
'errors' => $this->getErrors()
];
}
/**
* {@inheritdoc}
*/
public function defaultValue()
{
return $this->odmSchema[ODM::D_DEFAULTS];
}
/**
* {@inheritdoc}
*/
public function isValid()
{
$this->validate();
return empty($this->errors) && empty($this->nestedErrors);
}
/**
* {@inheritdoc}
*/
public function getErrors($reset = false)
{
return parent::getErrors($reset) + $this->nestedErrors;
}
/**
* {@inheritdoc}
*/
protected function container()
{
if (empty($this->odm)) {
return parent::container();
}
return $this->odm->container();
}
/**
* Related and cached ODM schema.
*
* @return array
*/
protected function odmSchema()
{
return $this->odmSchema;
}
/**
* {@inheritdoc}
*
* Will validate every CompositableInterface instance.
*
* @param bool $reset
* @throws DocumentException
*/
protected function validate($reset = false)
{
$this->nestedErrors = [];
//Validating all compositions
foreach ($this->odmSchema[ODM::D_COMPOSITIONS] as $field) {
$composition = $this->getField($field);
if (!$composition instanceof CompositableInterface) {
//Something weird.
continue;
}
if (!$composition->isValid()) {
$this->nestedErrors[$field] = $composition->getErrors($reset);
}
}
parent::validate($reset);
return empty($this->errors + $this->nestedErrors);
}
/**
* {@inheritdoc}
*
* Accessor options include field type resolved by DocumentSchema.
*
* @throws ODMException
* @throws DefinitionException
*/
protected function createAccessor($accessor, $value)
{
$options = null;
if (is_array($accessor)) {
list($accessor, $options) = $accessor;
}
if ($accessor == ODM::CMP_ONE) {
//Pointing to document instance
$accessor = $this->odm->document($options, $value, $this);
} else {
//Additional options are supplied for CompositableInterface
$accessor = new $accessor($value, $this, $this->odm, $options);
}
return $accessor;
}
/**
* {@inheritdoc}
*
* @see Component::staticContainer()
* @param array $fields Model fields to set, will be passed thought filters.
* @param ODM $odm ODM component, global container will be called if not instance provided.
* @event created()
*/
public static function create($fields = [], ODM $odm = null)
{
/**
* @var DocumentEntity $document
*/
$document = new static([], null, $odm);
//Forcing validation (empty set of fields is not valid set of fields)
$document->setFields($fields)->dispatch('created', new EntityEvent($document));
return $document;
}
/**
* Called by ODM with set of loaded fields. Must return name of appropriate class.
*
* @param array $fields
* @param ODM $odm
* @return string
* @throws DefinitionException
*/
public static function defineClass(array $fields, ODM $odm)
{
throw new DefinitionException("Class definition methods was not implemented.");
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Behaviours;
use Spiral\Stempler\BehaviourInterface;
use Spiral\Stempler\HtmlTokenizer;
use Spiral\Stempler\ImporterInterface;
use Spiral\Stempler\Node;
use Spiral\Stempler\Supervisor;
/**
* Points node to it's parent.
*/
class ExtendsBehaviour implements BehaviourInterface
{
/**
* Parent (extended) node, treat it as page or element layout.
*
* @var Node
*/
private $parent = null;
/**
* Attributes defined using extends tag.
*
* @var array
*/
private $attributes = [];
/**
* @var array
*/
private $token = [];
/**
* @param Node $parent
* @param array $token
*/
public function __construct(Node $parent, array $token)
{
$this->parent = $parent;
$this->token = $token;
$this->attributes = $token[HtmlTokenizer::TOKEN_ATTRIBUTES];
}
/**
* Node which are getting extended.
*
* @return Node
*/
public function extendedNode()
{
return $this->parent;
}
/**
* Every import defined in parent (extended node).
*
* @return ImporterInterface[]
*/
public function parentImports()
{
$supervisor = $this->parent->supervisor();
if (!$supervisor instanceof Supervisor) {
return [];
}
return $supervisor->getImporters();
}
/**
* Set of blocks defined at moment of extend definition.
*
* @return array
*/
public function dynamicBlocks()
{
return $this->attributes;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations;
use Doctrine\Common\Inflector\Inflector;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\ORM\Entities\Schemas\MorphedSchema;
use Spiral\ORM\Entities\Schemas\Relations\Traits\ColumnsTrait;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* ManyToMorphed relation declares relation between parent record and set of outer records joined by
* common interface. Relation allow to specify inner key (key in parent record), outer key (key in
* outer records), morph key, pivot table name, names of pivot columns to store inner and outer key
* values and set of additional columns. Relation DOES NOT to specify WHERE statement for outer
* records. However you can specify where conditions for PIVOT table.
*
* You can declare this relation using same syntax as for ManyToMany except your target class
* must be an interface.
*
* Attention, be very careful using morphing relations, you must know what you doing!
* Attention #2, relation like that can not be preloaded!
*
* Example [Tag related to many TaggableInterface], relation name "tagged", relation requested to be
* inversed using name "tags":
* - relation will walk should every record implementing TaggableInterface to collect name and
* type of outer keys, if outer key is not consistent across records implementing this interface
* an exception will be raised, let's say that outer key is "id" in every record
* - relation will create pivot table named "tagged_map" (if allowed), where table name generated
* based on relation name (you can change name)
* - relation will create pivot key named "tag_ud" related to Tag primary key
* - relation will create pivot key named "tagged_id" related to primary key of outer records,
* singular relation name used to generate key like that
* - relation will create pivot key named "tagged_type" to store role of outer record
* - relation will create unique index on "tag_id", "tagged_id" and "tagged_type" columns if allowed
* - relation will create additional columns in pivot table if any requested
*
* Using in records:
* You can use inversed relation as usual ManyToMany, however in Tag record relation access will be
* little bit more complex - every linked record will create inner ManyToMany relation:
* $tag->tagged->users->count(); //Where "users" is plural form of one outer records
*
* You can defined your own inner relation names by using MORPHED_ALIASES option when defining
* relation.
*
* @see BelongsToMorhedSchema
* @see ManyToManySchema
*/
class ManyToMorphedSchema extends MorphedSchema
{
/**
* Relation may create custom columns in pivot table using Record schema format.
*/
use ColumnsTrait;
/**
* {@inheritdoc}
*/
const RELATION_TYPE = RecordEntity::MANY_TO_MORPHED;
/**
* Relation represent multiple records.
*/
const MULTIPLE = true;
/**
* {@inheritdoc}
*
* @invisible
*/
protected $defaultDefinition = [
//Association list between tables and roles, internal
RecordEntity::MORPHED_ALIASES => [],
//Pivot table name will be generated based on singular relation name and _map postfix
RecordEntity::PIVOT_TABLE => '{name:singular}_map',
//Inner key points to primary key of parent record by default
RecordEntity::INNER_KEY => '{record:primaryKey}',
//By default, we are looking for primary key in our outer records, outer key must present
//in every outer record and be consistent
RecordEntity::OUTER_KEY => '{outer:primaryKey}',
//Linking pivot table and parent record
RecordEntity::THOUGHT_INNER_KEY => '{record:role}_{definition:innerKey}',
//Linking pivot table and outer records
RecordEntity::THOUGHT_OUTER_KEY => '{name:singular}_{definition:outerKey}',
//Declares what specific record pivot record linking to
RecordEntity::MORPH_KEY => '{name:singular}_type',
//Set constraints in pivot table (foreign keys)
RecordEntity::CONSTRAINT => true,
//@link https://en.wikipedia.org/wiki/Foreign_key
RecordEntity::CONSTRAINT_ACTION => 'CASCADE',
//Relation allowed to create indexes in pivot table
RecordEntity::CREATE_INDEXES => true,
//Relation allowed to create pivot table
RecordEntity::CREATE_PIVOT => true,
//Additional set of columns to be added into pivot table, you can use same column definition
//type as you using for your records
RecordEntity::PIVOT_COLUMNS => [],
//Set of default values to be used for pivot table
RecordEntity::PIVOT_DEFAULTS => [],
//WHERE statement in a form of simplified array definition to be applied to pivot table
//data
RecordEntity::WHERE_PIVOT => []
];
/**
* {@inheritdoc}
*
* Relation will be inversed to every associated record.
*/
public function inverseRelation()
{
//WHERE conditions can not be inversed
foreach ($this->outerRecords() as $record) {
if (!$record->hasRelation($this->definition[RecordEntity::INVERSE])) {
$record->addRelation($this->definition[RecordEntity::INVERSE], [
RecordEntity::MANY_TO_MANY => $this->record->getName(),
RecordEntity::PIVOT_TABLE => $this->definition[RecordEntity::PIVOT_TABLE],
RecordEntity::OUTER_KEY => $this->definition[RecordEntity::INNER_KEY],
RecordEntity::INNER_KEY => $this->definition[RecordEntity::OUTER_KEY],
RecordEntity::THOUGHT_INNER_KEY => $this->definition[RecordEntity::THOUGHT_OUTER_KEY],
RecordEntity::THOUGHT_OUTER_KEY => $this->definition[RecordEntity::THOUGHT_INNER_KEY],
RecordEntity::MORPH_KEY => $this->definition[RecordEntity::MORPH_KEY],
RecordEntity::CREATE_INDEXES => $this->definition[RecordEntity::CREATE_INDEXES],
RecordEntity::CREATE_PIVOT => $this->definition[RecordEntity::CREATE_PIVOT],
RecordEntity::PIVOT_COLUMNS => $this->definition[RecordEntity::PIVOT_COLUMNS],
RecordEntity::WHERE_PIVOT => $this->definition[RecordEntity::WHERE_PIVOT]
]);
}
}
}
/**
* Generate name of pivot table or fetch if from schema.
*
* @return string
*/
public function getPivotTable()
{
return $this->definition[RecordEntity::PIVOT_TABLE];
}
/**
* Instance of AbstractTable associated with relation pivot table.
*
* @return AbstractTable
*/
public function pivotSchema()
{
return $this->builder->declareTable(
$this->record->getDatabase(),
$this->getPivotTable()
);
}
/**
* {@inheritdoc}
*/
public function buildSchema()
{
if (!$this->definition[RecordEntity::CREATE_PIVOT]) {
//No pivot table creation were requested, noting really to do
return;
}
$pivotTable = $this->pivotSchema();
//Inner key points to our parent record
$innerKey = $pivotTable->column($this->definition[RecordEntity::THOUGHT_INNER_KEY]);
$innerKey->setType($this->getInnerKeyType());
if ($this->isIndexed()) {
$innerKey->index();
}
//Morph key will store role name of outer records
$morphKey = $pivotTable->column($this->getMorphKey());
$morphKey->string(static::MORPH_COLUMN_SIZE);
//Points to inner key of our outer records (outer key)
$outerKey = $pivotTable->column($this->definition[RecordEntity::THOUGHT_OUTER_KEY]);
$outerKey->setType($this->getOuterKeyType());
//Casting pivot table columns
$this->castTable(
$this->pivotSchema(),
$this->definition[RecordEntity::PIVOT_COLUMNS],
$this->definition[RecordEntity::PIVOT_DEFAULTS]
);
//Complex index
if ($this->isIndexed()) {
//Complex index including 3 columns from pivot table
$pivotTable->unique(
$this->definition[RecordEntity::THOUGHT_INNER_KEY],
$this->definition[RecordEntity::MORPH_KEY],
$this->definition[RecordEntity::THOUGHT_OUTER_KEY]
);
}
if ($this->isConstrained()) {
$foreignKey = $innerKey->references(
$this->record->getTable(),
$this->record->getPrimaryKey()
);
$foreignKey->onDelete($this->getConstraintAction());
$foreignKey->onUpdate($this->getConstraintAction());
}
}
/**
* {@inheritdoc}
*/
protected function normalizeDefinition()
{
$definition = parent::normalizeDefinition();
foreach ($this->outerRecords() as $record) {
if (!in_array($record->getRole(), $definition[RecordEntity::MORPHED_ALIASES])) {
//Let's remember associations between tables and roles
$plural = Inflector::pluralize($record->getRole());
$definition[RecordEntity::MORPHED_ALIASES][$plural] = $record->getRole();
}
//We must include pivot table database into data for easier access
$definition[ORM::R_DATABASE] = $record->getDatabase();
}
//Let's include pivot table columns
$definition[RecordEntity::PIVOT_COLUMNS] = [];
foreach ($this->pivotSchema()->getColumns() as $column) {
$definition[RecordEntity::PIVOT_COLUMNS][] = $column->getName();
}
return $definition;
}
/**
* {@inheritdoc}
*/
protected function clarifyDefinition()
{
parent::clarifyDefinition();
if (!$this->isSameDatabase()) {
throw new RelationSchemaException(
"Many-to-Many morphed relation can create relations ({$this}) "
. "only to entities from same database."
);
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer\Highlighter;
/**
* Dark highlighter.
*/
class InversedStyle extends Style
{
/**
* Styles associated with token types.
*
* @var array
*/
protected $styles = [
'color: #C26230; font-weight: bold;' => [
T_STATIC,
T_PUBLIC,
T_PRIVATE,
T_PROTECTED,
T_CLASS,
T_NEW,
T_FINAL,
T_ABSTRACT,
T_IMPLEMENTS,
T_CONST,
T_ECHO,
T_CASE,
T_FUNCTION,
T_GOTO,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
T_VAR,
T_INSTANCEOF,
T_INTERFACE,
T_THROW,
T_ARRAY,
T_IF,
T_ELSE,
T_ELSEIF,
T_TRY,
T_CATCH,
T_CLONE,
T_WHILE,
T_FOR,
T_DO,
T_UNSET,
T_FOREACH,
T_RETURN,
T_EXIT,
T_EXTENDS
],
'color: black; font: weight: bold;' => [
T_OPEN_TAG,
T_CLOSE_TAG,
T_OPEN_TAG_WITH_ECHO
],
'color: #BC9458;' => [
T_COMMENT,
T_DOC_COMMENT
],
'color: #A5C261;' => [
T_CONSTANT_ENCAPSED_STRING,
T_ENCAPSED_AND_WHITESPACE,
T_DNUMBER,
T_LNUMBER
],
'color: #D0D0FF;' => [
T_VARIABLE
]
];
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Relations;
use Spiral\Models\EntityInterface;
use Spiral\ORM\Entities\Relation;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\ORM\RecordEntity;
/**
* Represent simple HAS_ONE relation with ability to associate and de-associate records.
*/
class HasOne extends Relation
{
/**
* Relation type, required to fetch record class from relation definition.
*/
const RELATION_TYPE = RecordEntity::HAS_ONE;
/**
* {@inheritdoc}
*
* Attention, you have to drop association with old instance manually!
*/
public function associate(EntityInterface $related = null)
{
//Removing association
if ($related === null) {
throw new RelationException(
"Unable to associate null to HAS_ONE relation."
);
}
parent::associate($this->mountRelation($related));
}
/**
* Create record and configure it's fields with relation data. Attention, you have to validate
* and save record by your own. Newly created entity will not be associated automatically!
* Pre-loaded data will not be altered, unless reset() method are called.
*
* @param mixed $fields
* @return RecordEntity
*/
public function create($fields = [])
{
$record = call_user_func([$this->getClass(), 'create'], $fields, $this->orm);
return $this->mountRelation($record);
}
/**
* {@inheritdoc}
*/
protected function mountRelation(EntityInterface $record)
{
//Key in child record
$outerKey = $this->definition[RecordEntity::OUTER_KEY];
//Key in parent record
$innerKey = $this->definition[RecordEntity::INNER_KEY];
if ($record->getField($outerKey, false) != $this->parent->getField($innerKey, false)) {
$record->setField($outerKey, $this->parent->getField($innerKey, false));
}
if (!isset($this->definition[RecordEntity::MORPH_KEY])) {
//No morph key presented
return $record;
}
$morphKey = $this->definition[RecordEntity::MORPH_KEY];
if ($record->getField($morphKey) != $this->parent->recordRole()) {
$record->setField($morphKey, $this->parent->recordRole());
}
return $record;
}
/**
* {@inheritdoc}
*/
protected function createSelector()
{
$selector = parent::createSelector();
//We are going to clarify selector manually (without loaders), that's easy relation
if (isset($this->definition[RecordEntity::MORPH_KEY])) {
$selector->where(
$selector->primaryAlias() . '.' . $this->definition[RecordEntity::MORPH_KEY],
$this->parent->recordRole()
);
}
$selector->where(
$selector->primaryAlias() . '.' . $this->definition[RecordEntity::OUTER_KEY],
$this->parent->getField($this->definition[RecordEntity::INNER_KEY], false)
);
return $selector;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Exporters;
use Spiral\Stempler\ConditionalExporter;
/**
* Export user defined (outer) blocks as tag attributes.
*
* Use following pattern: node:attributes[="condition"]
*/
class AttributesExporter extends ConditionalExporter
{
/**
* {@inheritdoc}
*/
public function mountBlocks($content, array $blocks)
{
if (preg_match_all('/ node:attributes(?:=\"([^\'"]+)\")?/i', $content, $matches)) {
//We have to sort from longest to shortest
uasort($matches[0], function ($replaceA, $replaceB) {
return strlen($replaceB) - strlen($replaceA);
});
foreach ($matches[0] as $id => $replace) {
$inject = [];
//That's why we need longest first (prefix mode)
foreach ($this->filterBlocks($matches[1][$id], $blocks) as $name => $value) {
if ($value === null) {
$inject[$name] = $name;
continue;
}
$inject[$name] = $name . '="' . $value . '"';
}
//Injecting
$content = str_replace($replace, $inject ? ' ' . join(' ', $inject) : '', $content);
}
}
return $content;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
use Spiral\Core\Exceptions\LogicException;
/**
* Generic ODM exception.
*/
class ODMException extends LogicException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Exceptions;
/**
* Errors raised by data entity accessors.
*/
interface AccessorExceptionInterface extends EntityExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
/**
* Image based validations.
*/
class ImageChecker extends FileChecker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* Getimagesize constants.
*/
const WIDTH = 0;
const HEIGHT = 1;
const IMAGE_TYPE = 2;
/**
* {@inheritdoc}
*/
protected $messages = [
"type" => "[[Image does not supported.]]",
"valid" => "[[Image does not supported (allowed JPEG, PNG or GIF).]]",
"smaller" => "[[Image size should not exceed {0}x{1}px.]]",
"bigger" => "[[The image dimensions should be at least {0}x{1}px.]]"
];
/**
* Known image types.
*
* @var array
*/
protected $imageTypes = [
'null',
'gif',
'jpeg',
'png',
'swf',
'psd',
'bmp',
'tiff',
'tiff',
'jpc',
'jp2',
'jpx',
'jb2',
'swc',
'iff',
'wbmp',
'xbm'
];
/**
* Check if image in a list of allowed image types.
*
* @param mixed $filename
* @param array|mixed $types
* @return bool
*/
public function type($filename, $types)
{
if (empty($image = $this->imageData($filename))) {
return false;
}
if (!is_array($types)) {
$types = array_slice(func_get_args(), 1);
}
return in_array($this->imageTypes[$image[self::IMAGE_TYPE]], $types);
}
/**
* Shortcut to check if image has valid type (JPEG, PNG and GIF are allowed).
*
* @param mixed $filename
* @return bool
*/
public function valid($filename)
{
return $this->type($filename, ['jpeg', 'png', 'gif']);
}
/**
* Check if image smaller that specified rectangle (height check if optional).
*
* @param mixed $filename
* @param int $width
* @param int $height Optional.
* @return bool
*/
public function smaller($filename, $width, $height = null)
{
if (empty($image = $this->imageData($filename))) {
return false;
}
if ($image[self::WIDTH] >= $width) {
return false;
}
if (!empty($height) && $image[self::HEIGHT] >= $height) {
return false;
}
return true;
}
/**
* Check if image is bigger that specified rectangle (height check is optional).
*
* @param mixed $filename
* @param int $width
* @param int $height Optional.
* @return bool
*/
public function bigger($filename, $width, $height = null)
{
if (empty($image = $this->imageData($filename))) {
return false;
}
if ($image[self::WIDTH] < $width) {
return false;
}
if (!empty($height) && $image[self::HEIGHT] < $height) {
return false;
}
return true;
}
/**
* Internal method, return image details fetched by getimagesize() or false.
*
* @see getimagesize()
* @param string $filename
* @return array|bool
*/
protected function imageData($filename)
{
try {
return getimagesize($this->filename($filename));
} catch (\Exception $exception) {
//We can simply invalidate image if system can't read it
}
return false;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage;
use Psr\Http\Message\StreamInterface;
use Spiral\Files\Streams\StreamableInterface;
use Spiral\Storage\Exceptions\BucketException;
use Spiral\Storage\Exceptions\ObjectException;
use Spiral\Storage\Exceptions\ServerException;
use Spiral\Storage\Exceptions\StorageException;
/**
* Abstraction level to work with local and remote files represented using storage objects and
* buckets.
*/
interface StorageInterface
{
/**
* Register new bucket using it's options, server and prefix.
*
* @param string $name
* @param string $prefix
* @param array $options
* @param ServerInterface $server
* @return BucketInterface
* @throws StorageException
*/
public function registerBucket($name, $prefix, array $options = [], ServerInterface $server);
/**
* Get bucket by it's name.
*
* @param string $bucket
* @return BucketInterface
* @throws StorageException
*/
public function bucket($bucket);
/**
* Find bucket instance using object address.
*
* @param string $address
* @param string $name Name stripped from address.
* @return BucketInterface
* @throws StorageException
*/
public function locateBucket($address, &$name = null);
/**
* Get or create instance of storage server.
*
* @param string $server
* @return ServerInterface
* @throws StorageException
*/
public function server($server);
/**
* Put object data into specified bucket under provided name. Should support filenames, PSR7
* streams and streamable objects. Must create empty object if source empty.
*
* @param string|BucketInterface $bucket
* @param string $name
* @param mixed|StreamInterface|StreamableInterface $source
* @return ObjectInterface|bool
* @throws StorageException
* @throws BucketException
* @throws ServerException
*/
public function put($bucket, $name, $source = '');
/**
* Create instance of storage object using it's address.
*
* @param string $address
* @return ObjectInterface
* @throws StorageException
* @throws ObjectException
*/
public function open($address);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Stores\Memcache;
use Spiral\Cache\StoreInterface;
/**
* User by MemcacheStore to abstract drivers.
*/
interface DriverInterface extends StoreInterface
{
/**
* New driver using user options. Driver should ignore prefix from config.
*
* @param array $servers
*/
public function __construct(array $servers);
/**
* Connect driver.
*/
public function connect();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Exceptions;
/**
* Something happen with/in store.
*/
class StoreException extends CacheException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations;
use Spiral\ORM\Entities\Schemas\MorphedSchema;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* BelongsToMorphed are almost identical to BelongsTo except it parent Record defined by role value
* stored in [morph key] and parent key in [inner key].
*
* You can define BelongsToMorphed relation using syntax for BelongsTo but declaring outer class
* as interface, meaning you should not only declare inversed relation name, but also it's type -
* HAS_ONE or HAS_MANY.
*
* Example: 'parent' => [self::BELONGS_TO => 'Records\CommentableInterface']
*
* Attention, be very careful using morphing relations, you must know what you doing!
* Attention #2, relation like that can not be preloaded!
*
* Example, [Comment can belong to any CommentableInterface record], relation name "parent",
* relation requested to be inversed into HAS_MANY "comments":
* - relation will walk should every record implementing CommentableInterface to collect name and
* type of outer keys, if outer key is not consistent across records implementing this interface
* an exception will be raised, let's say that outer key is "id" in every record
* - relation will create inner key "parent_id" in "comments" table (or other table name), nullable
* by default
* - relation will create "parent_type" morph key in "comments" table, nullable by default
* - relation will create complex index index on columns "parent_id" and "parent_type" in
* "comments"
* table if allowed
* - due relation is inversable every record implementing CommentableInterface will receive
* HAS_MANY
* relation "comments" pointing to Comment record using record role value
*
* @see BelongsToSchema
*/
class BelongsToMorphedSchema extends MorphedSchema
{
/**
* {@inheritdoc}
*/
const RELATION_TYPE = RecordEntity::BELONGS_TO_MORPHED;
/**
* {@inheritdoc}
*
* @invisible
*/
protected $defaultDefinition = [
//By default, we are looking for primary key in our outer records, outer key must present
//in every outer record and be consistent
RecordEntity::OUTER_KEY => '{outer:primaryKey}',
//Inner key name will be created based on singular relation name and outer key name
RecordEntity::INNER_KEY => '{name:singular}_{definition:outerKey}',
//Morph key created based on singular relation name and postfix _type
RecordEntity::MORPH_KEY => '{name:singular}_type',
//Relation allowed to create indexes in pivot table
RecordEntity::CREATE_INDEXES => true,
//Relation is nullable by default
RecordEntity::NULLABLE => true
];
/**
* {@inheritdoc}
*
* Relation will be inversed to every associated record.
*/
public function inverseRelation()
{
//Same logic as in BelongsTo
if (
!is_array($this->definition[RecordEntity::INVERSE])
|| !isset($this->definition[RecordEntity::INVERSE][1])
) {
throw new RelationSchemaException(
"Unable to revert BELONG_TO_MORPHED relation '{$this->record}'.'{$this}', " .
"backward relation type is missing or invalid."
);
}
//We are going to inverse relation to every outer record
$inversed = $this->definition[RecordEntity::INVERSE];
foreach ($this->outerRecords() as $record) {
if (!$record->hasRelation($inversed[1])) {
$record->addRelation($inversed[1], [
$inversed[0] => $this->record->getName(),
RecordEntity::OUTER_KEY => $this->definition[RecordEntity::INNER_KEY],
RecordEntity::INNER_KEY => $this->definition[RecordEntity::OUTER_KEY],
RecordEntity::MORPH_KEY => $this->definition[RecordEntity::MORPH_KEY],
RecordEntity::NULLABLE => $this->definition[RecordEntity::NULLABLE]
]);
}
}
}
/**
* {@inheritdoc}
*/
public function buildSchema()
{
//Inner (parent) record table
$innerSchema = $this->record->tableSchema();
//Morph key contains parent role name
$morphKey = $innerSchema->column($this->getMorphKey());
//We have predefined morphed key size
$morphKey->string(static::MORPH_COLUMN_SIZE);
$morphKey->nullable($morphKey->isNullable() || $this->isNullable());
//Points to inner key of outer records (outer key)
$innerKey = $innerSchema->column($this->getInnerKey());
$innerKey->setType($this->getOuterKeyType());
$innerKey->nullable($innerKey->isNullable() || $this->isNullable());
if ($this->isIndexed()) {
//Compound index may help with performance
$innerSchema->index($this->getMorphKey(), $this->getInnerKey());
}
}
/**
* Normalize schema definition into light cachable form.
*
* @return array
*/
protected function normalizeDefinition()
{
$definition = parent::normalizeDefinition();
if (empty($this->outerRecords())) {
return $definition;
}
//We should only check first record since they all must follow same key
if ($this->getOuterKey() == $this->outerRecords()[0]->getPrimaryKey()) {
//Linked using primary key
$definition[ORM::M_PRIMARY_KEY] = $this->getOuterKey();
}
return $definition;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Events;
use Spiral\Validation\ValidatorInterface;
use Symfony\Component\EventDispatcher\Event;
/**
* Raised at moment of validator creation.
*/
class ValidatorEvent extends Event
{
/**
* @var ValidatorInterface
*/
private $validator = null;
/**
* @param ValidatorInterface $validator
*/
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
/**
* Change validation.
*
* @param ValidatorInterface $validator
*/
public function setValidator(ValidatorInterface $validator)
{
$this->$validator = $validator;
}
/**
* @return ValidatorInterface
*/
public function validator()
{
return $this->validator;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Stores\Memcache;
use Spiral\Cache\CacheStore;
/**
* Common functionality for Memcache and Memcached drivers.
*/
abstract class AbstractDriver extends CacheStore implements DriverInterface
{
/**
* @var array
*/
protected $servers = [];
/**
* Default server options.
*
* @invisible
* @var array
*/
protected $defaultServer = [
'host' => 'localhost',
'port' => 11211,
'persistent' => true,
'weight' => 1
];
/**
* @var \Memcached|\Memcache
*/
protected $driver = null;
/**
* {@inheritdoc}
*/
public function connect()
{
foreach ($this->servers as $server) {
//Merging default options
$server = $server + $this->defaultServer;
$this->driver->addServer(
$server['host'],
$server['port'],
$server['weight']
);
}
}
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return true;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Pagination;
/**
* Provides ability to associate paginator and execute pagination when needed.
*/
interface PaginatorAwareInterface extends PaginableInterface
{
/**
* Manually set paginator instance for specific object.
*
* @param PaginatorInterface $paginator
* @return $this
*/
public function setPaginator(PaginatorInterface $paginator);
/**
* Get paginator for the current selection. Paginate method should be already called.
*
* @see paginate()
* @return PaginatorInterface
*/
public function paginator();
/**
* Indication that object was paginated.
*
* @return bool
*/
public function isPaginated();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Debug;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\HandlerInterface;
use Monolog\Logger;
use Spiral\Core\Component;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\FactoryInterface;
use Spiral\Debug\Configs\DebuggerConfig;
use Spiral\Debug\Exceptions\BenchmarkException;
use Spiral\Debug\Exceptions\DebuggerException;
use Spiral\Debug\Logger\SharedHandler;
/**
* Debugger is responsible for global log, benchmarking and configuring Monolog loggers.
*/
class Debugger extends Component implements BenchmarkerInterface, LogsInterface, SingletonInterface
{
/**
* Declares to IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* @invisible
* @var array
*/
private $benchmarks = [];
/**
* @todo array of handlers?
* @var HandlerInterface
*/
protected $sharedHandler = null;
/**
* @var DebuggerConfig
*/
protected $config = null;
/**
* Container is needed to construct log handlers.
*
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param DebuggerConfig $config
* @param FactoryInterface $factory
*/
public function __construct(DebuggerConfig $config, FactoryInterface $factory)
{
$this->config = $config;
$this->factory = $factory;
}
/**
* {@inheritdoc}
*/
public function getLogger($name)
{
//Monolog by default
return $this->factory->make(Logger::class, [
'name' => $name,
'handlers' => $this->logHandlers($name)
]);
}
/**
* Get handlers associated with specified log.
*
* @param string $name
* @return HandlerInterface[]
*/
public function logHandlers($name)
{
$handlers = [];
if (!empty($this->sharedHandler)) {
//Shared handler applied to every Logger
$handlers[] = $this->sharedHandler;
}
if (!$this->config->hasHandlers($name)) {
return $handlers;
}
foreach ($this->config->logHandlers($name) as $handler) {
/**
* @var HandlerInterface $instance
*/
$handlers[] = $instance = $this->factory->make(
$handler['handler'],
$handler['options']
);
if (!empty($handler['format'])) {
//Let's use custom line formatter
$instance->setFormatter(new LineFormatter($handler['format']));
}
}
return $handlers;
}
/**
* Set instance of shared HandlerInterface, such handler will be passed to every created log.
* To remove existed handler set it argument as null.
*
* @param HandlerInterface $handler
* @return SharedHandler|null Returns previously set handler.
*/
public function shareHandler(HandlerInterface $handler = null)
{
$previous = $this->sharedHandler;
$this->sharedHandler = $handler;
return $previous;
}
/**
* @return bool
*/
public function hasSharedHandler()
{
return !empty($this->sharedHandler);
}
/**
* Get currently associated shared handler.
*
* @return HandlerInterface
* @throws DebuggerException When no handler being set.
*/
public function getSharedHandler()
{
if (empty($this->sharedHandler)) {
throw new DebuggerException("Unable to receive shared handler.");
}
return $this->sharedHandler;
}
/**
* {@inheritdoc}
*
* @throws BenchmarkException
*/
public function benchmark($caller, $record, $context = '')
{
$benchmarkID = count($this->benchmarks);
if (is_array($record)) {
$benchmarkID = $record[0];
} elseif (!isset($this->benchmarks[$benchmarkID])) {
$this->benchmarks[$benchmarkID] = [$caller, $record, $context, microtime(true)];
//Payload
return [$benchmarkID];
}
if (!isset($this->benchmarks[$benchmarkID])) {
throw new BenchmarkException("Unpaired benchmark record '{$benchmarkID}'.");
}
$this->benchmarks[$benchmarkID][4] = microtime(true);
return $this->benchmarks[$benchmarkID][4] - $this->benchmarks[$benchmarkID][3];
}
/**
* Retrieve all active and finished benchmark records.
*
* @return array|null
*/
public function getBenchmarks()
{
return $this->benchmarks;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Psr\Http\Message\UploadedFileInterface;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Files\FilesInterface;
use Spiral\Files\Streams\StreamableInterface;
use Spiral\Files\Streams\StreamWrapper;
use Spiral\Validation\Checker;
class FileChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"exists" => "[[File does not exists.]]",
"uploaded" => "[[File not received, please try again.]]",
"size" => "[[File exceeds the maximum file size of {1}KB.]]",
"extension" => "[[File has an invalid file format.]]"
];
/**
* @var FilesInterface
*/
protected $files = null;
/**
* @param FilesInterface $files
*/
public function __construct(FilesInterface $files)
{
$this->files = $files;
}
/**
* Check if file exist.
*
* @param mixed $filename
* @return bool
*/
public function exists($filename)
{
return (bool)$this->filename($filename, false);
}
/**
* Will check if local file exists or just uploaded.
*
* @param mixed $file Local file or uploaded file array.
* @return bool
*/
public function uploaded($file)
{
return (bool)$this->filename($file, true);
}
/**
* Check if file size less that specified value in KB.
*
* @param mixed $filename Local file or uploaded file array.
* @param int $size Size in KBytes.
* @return bool
*/
public function size($filename, $size)
{
if (empty($filename = $this->filename($filename, false))) {
return false;
}
return $this->files->size($filename) < $size * 1024;
}
/**
* Check if file extension in whitelist. Client name of uploaded file will be used!
*
* @param mixed $filename
* @param array $extensions
* @return bool
*/
public function extension($filename, $extensions)
{
if (!is_array($extensions)) {
$extensions = array_slice(func_get_args(), 1);
}
if ($filename instanceof UploadedFileInterface) {
return in_array(
$this->files->extension($filename->getClientFilename()),
$extensions
);
}
return in_array($this->files->extension($filename), $extensions);
}
/**
* Internal method to fetch filename using multiple input formats.
*
* @param mixed|UploadedFileInterface $filename
* @param bool $onlyUploaded Check if file uploaded.
* @return string|bool
*/
protected function filename($filename, $onlyUploaded = true)
{
if (empty($filename) || ($onlyUploaded && !$this->isUploaded($filename))) {
return false;
}
if (
$filename instanceof UploadedFileInterface
|| $filename instanceof StreamableInterface
) {
return StreamWrapper::getUri($filename->getStream());
}
if (is_array($filename)) {
$filename = $filename['tmp_name'];
}
return $this->files->exists($filename) ? $filename : false;
}
/**
* Check if file being uploaded.
*
* @param mixed|UploadedFileInterface $filename Filename or file array.
* @return bool
*/
private function isUploaded($filename)
{
if (is_string($filename)) {
//We can use native method
return is_uploaded_file($filename);
}
if (is_array($filename)) {
return isset($filename['tmp_name']) && is_uploaded_file($filename['tmp_name']);
}
if ($filename instanceof UploadedFileInterface) {
return empty($filename->getError());
}
return false;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
* @copyright �2009-2015
*/
namespace Spiral\ODM\Accessors;
use Spiral\Models\EntityInterface;
use Spiral\ODM\DocumentAccessorInterface;
use Spiral\ODM\DocumentEntity;
use Spiral\ODM\Exceptions\AccessorException;
use Spiral\ODM\ODM;
/**
* Simple ODM accessor with ability to mock access to array field. ScalarArray support atomic
* operations and performs type normalization.
*/
class ScalarArray implements DocumentAccessorInterface, \IteratorAggregate, \Countable, \ArrayAccess
{
/**
* No typecasting will be performed if primary array type defined as "mixed".
*/
const MIXED_TYPE = 'mixed';
/**
* Scalar array type name.
*
* @var string
*/
private $type = '';
/**
* Array data.
*
* @var array
*/
protected $data = [];
/**
* When solid state is enabled no atomic operations will be pushed to databases and array will
* be saved as one big set. Enabled by default.
*
* @var bool
*/
protected $solidState = true;
/**
* Indication that were updated.
*
* @var bool
*/
protected $updated = false;
/**
* Low level atomic operations.
*
* @var array
*/
protected $atomics = [];
/**
* @invisible
* @var EntityInterface
*/
protected $parent = null;
/**
* Supported type filters. No boolean include, cos who the hell need array of booleans.
*
* @var array
*/
protected $filters = [
'int' => 'intval',
'float' => 'floatval',
'string' => 'strval',
'MongoId' => [ODM::class, 'mongoID'],
'\MongoId' => [ODM::class, 'mongoID']
];
/**
* {@inheritdoc}
*
* @param mixed $type Type to be filtered by. Set to null or mixed to allow any type.
*/
public function __construct(
$value,
EntityInterface $parent = null,
ODM $odm = null,
$type = self::MIXED_TYPE
) {
$this->parent = $parent;
if (!is_array($value) && $value !== null) {
throw new AccessorException("ScalarArray support only scalar arrays."); //:)
}
$this->data = is_array($value) ? $value : [];
$this->type = !empty($type) ? $type : self::MIXED_TYPE;
if ($this->type != self::MIXED_TYPE && !isset($this->filters[$this->type])) {
throw new AccessorException("Unknown/unsupported ScalarArray value type '{$type}'.");
}
}
/**
* {@inheritdoc}
*/
public function defaultValue()
{
$result = [];
foreach ($this->data as $value) {
$value = $this->filter($value);
if ($value !== null) {
$result[] = $value;
}
}
return $result;
}
/**
* ScalarArray values type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* When solid state is enabled no atomic operations will be pushed to databases and array will
* be saved as one big set request.
*
* @param bool $solidState
* @return $this
*/
public function solidState($solidState)
{
$this->solidState = $solidState;
return $this;
}
/**
* {@inheritdoc}
*/
public function embed(EntityInterface $parent)
{
if ($parent === $this->parent) {
return $this;
}
$accessor = clone $this;
$accessor->parent = $parent;
$accessor->solidState = $accessor->updated = true;
return $accessor;
}
/**
* {@inheritdoc}
*
* @return $this
*/
public function setValue($data)
{
$this->updated = $this->solidState = true;
if (!is_array($data)) {
//Ignoring this set
return $this;
}
$this->data = [];
foreach ($data as $value) {
$value = $this->filter($value);
if (!is_null($value) || $this->type == self::MIXED_TYPE) {
$this->data[] = $value;
}
}
return $this;
}
/**
* {@inheritdoc}
*/
public function serializeData()
{
return $this->data;
}
/**
* {@inheritdoc}
*/
public function hasUpdates()
{
return $this->updated || !empty($this->atomics);
}
/**
* {@inheritdoc}
*/
public function flushUpdates()
{
$this->updated = false;
$this->atomics = [];
}
/**
* {@inheritdoc}
*/
public function buildAtomics($container = '')
{
if (!$this->hasUpdates()) {
return [];
}
if ($this->solidState) {
//We don't care about atomics in solid state
return [DocumentEntity::ATOMIC_SET => [$container => $this->serializeData()]];
}
$atomics = [];
foreach ($this->atomics as $operation => $value) {
$atomics = [$operation => [$container => $value]];
}
return $atomics;
}
/**
* {@inheritdoc}
*/
public function count()
{
return count($this->data);
}
/**
* {@inheritdoc}
*/
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
/**
* {@inheritdoc}
* @throws AccessorException
*/
public function offsetGet($offset)
{
if (!isset($this->data[$offset])) {
throw new AccessorException("Undefined offset '{$offset}'.");
}
return $this->data[$offset];
}
/**
* {@inheritdoc}
* @throws AccessorException
*/
public function offsetSet($offset, $value)
{
if (!$this->solidState) {
throw new AccessorException(
"Direct offset operations can not be performed for ScalarArray in non solid state."
);
}
$value = $this->filter($value);
if (is_null($value) && $this->type != self::MIXED_TYPE) {
//Invalid value
return;
}
$this->updated = true;
if (is_null($offset)) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
/**
* {@inheritdoc}
* @throws AccessorException
*/
public function offsetUnset($offset)
{
if (!$this->solidState) {
throw new AccessorException(
"Direct offset operations can not be performed for ScalarArray in non solid state."
);
}
$this->updated = true;
unset($this->data[$offset]);
}
/**
* {@inheritdoc}
*/
public function getIterator()
{
return new \ArrayIterator($this->data);
}
/**
* Clear all values.
*
* @return $this
*/
public function clear()
{
$this->solidState = $this->updated = true;
$this->data = [];
return $this;
}
/**
* Alias for atomic operation $push. Only values passed type filter will be added.
*
* @param mixed $value
* @return $this
*/
public function push($value)
{
if (($value = $this->filter($value)) === null) {
return $this;
}
array_push($this->data, $value);
$this->atomics['$push']['$each'][] = $value;
return $this;
}
/**
* Alias for atomic operation $addToSet. Only values passed type filter will be added.
*
* @param mixed $value
* @return $this
*/
public function addToSet($value)
{
if (($value = $this->filter($value)) === null) {
return $this;
}
!in_array($value, $this->data) && array_push($this->data, $value);
$this->atomics['$addToSet']['$each'] = $value;
return $this;
}
/**
* Alias for atomic operation $pull. Only values passed type filter will be added.
*
* @param mixed $value
* @return $this
*/
public function pull($value)
{
if (($value = $this->filter($value)) === null) {
return $this;
}
$this->data = array_filter($this->data, function ($item) use ($value) {
return $item != $value;
});
$this->atomics['$pull'] = $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->serializeData();
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'data' => $this->serializeData(),
'type' => $this->getType(),
'atomics' => $this->buildAtomics('@scalarArray')
];
}
/**
* Filter value before embedding into array.
*
* @param mixed $value
* @return mixed
*/
protected function filter($value)
{
if ($this->type == self::MIXED_TYPE) {
return $value;
}
if (!is_scalar($value)) {
//This is ScalarArray
return null;
}
try {
return call_user_func($this->filters[$this->type], $value);
} catch (\Exception $exception) {
return null;
}
}
}<file_sep><?php
/**
* Spiral Framework, SpiralScout LLC.
*
* @package spiralFramework
* @author <NAME> (Wolfy-J)
* @copyright ©2009-2011
*/
namespace Spiral\Storage;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
use Spiral\Core\Component;
use Spiral\Files\FilesInterface;
use Spiral\Files\Streams\StreamableInterface;
use Spiral\Files\Streams\StreamWrapper;
use Spiral\Storage\Exceptions\ServerException;
/**
* AbstractServer implementation with different naming.
*/
abstract class StorageServer extends Component implements ServerInterface
{
/**
* Default mimetype to be used when nothing else can be applied.
*/
const DEFAULT_MIMETYPE = 'application/octet-stream';
/**
* @var array
*/
protected $options = [];
/**
* @var FilesInterface
*/
protected $files = null;
/**
* @param FilesInterface $files Required for local filesystem operations.
* @param array $options Server specific options.
*/
public function __construct(FilesInterface $files, array $options)
{
$this->options = $options + $this->options;
$this->files = $files;
}
/**
* {@inheritdoc}
*/
public function allocateFilename(BucketInterface $bucket, $name)
{
if (empty($stream = $this->allocateStream($bucket, $name))) {
throw new ServerException("Unable to allocate local filename for '{$name}'.");
}
//Default implementation will use stream to create temporary filename, such filename
//can't be used outside php scope
return StreamWrapper::getUri($stream);
}
/**
* {@inheritdoc}
*/
public function copy(BucketInterface $bucket, BucketInterface $destination, $name)
{
return $this->put($destination, $name, $this->allocateStream($bucket, $name));
}
/**
* {@inheritdoc}
*/
public function replace(BucketInterface $bucket, BucketInterface $destination, $name)
{
if ($this->copy($bucket, $destination, $name)) {
$this->delete($bucket, $name);
return true;
}
throw new ServerException("Unable to copy '{$name}' to new bucket.");
}
/**
* Cast local filename to be used in file based methods and etc.
*
* @param string|StreamInterface $source
* @return string
*/
protected function castFilename($source)
{
if (empty($source) || is_string($source)) {
if (!$this->files->exists($source)) {
//This code is going to use additional abstraction layer to connect storage and guzzle
return StreamWrapper::getUri(\GuzzleHttp\Psr7\stream_for(''));
}
return $source;
}
if ($source instanceof UploadedFileInterface || $source instanceof StreamableInterface) {
$source = $source->getStream();
}
if ($source instanceof StreamInterface) {
return StreamWrapper::getUri($source);
}
throw new ServerException("Unable to get filename for non Stream instance.");
}
/**
* Cast stream associated with origin data.
*
* @param string|StreamInterface $source
* @return StreamInterface
*/
protected function castStream($source)
{
if ($source instanceof UploadedFileInterface || $source instanceof StreamableInterface) {
$source = $source->getStream();
}
if ($source instanceof StreamInterface) {
return $source;
}
if (empty($source)) {
//This code is going to use additional abstraction layer to connect storage and guzzle
return \GuzzleHttp\Psr7\stream_for('');
}
return \GuzzleHttp\Psr7\stream_for($source);
}
} <file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Views\Exceptions;
/**
* Exception while rendering.
*/
class RenderException extends ViewsException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Spiral\Core\Component;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Debug\Traits\LoggerTrait;
/**
* Saves multiple linked tables at once but treating their cross dependency.
*/
class SynchronizationBus extends Component
{
/**
* Logging.
*/
use LoggerTrait;
/**
* @var AbstractTable[]
*/
protected $tables = [];
/**
* @var Driver[]
*/
protected $drivers = [];
/**
* @param AbstractTable[] $tables
*/
public function __construct(array $tables)
{
$this->tables = $tables;
$this->collectDrivers();
}
/**
* @return AbstractTable[]
*/
public function getTables()
{
return $this->tables;
}
/**
* List of tables sorted in order of cross dependency.
*
* @return AbstractTable[]
*/
public function sortedTables()
{
$tables = $this->tables;
uasort($tables, function (AbstractTable $tableA, AbstractTable $tableB) {
if (in_array($tableA->getName(), $tableB->getDependencies())) {
return true;
}
return count($tableB->getDependencies()) > count($tableA->getDependencies());
});
return array_reverse($tables);
}
/**
* Syncronize table schemas.
*
* @throws \Exception
*/
public function syncronize()
{
$this->beginTransaction();
try {
//Dropping non declared foreign keys
$this->saveTables(false, false, true);
//Dropping non declared indexes
$this->saveTables(false, true, true);
//Dropping non declared columns
$this->saveTables(true, true, true);
} catch (\Exception $exception) {
$this->rollbackTransaction();
throw $exception;
}
$this->commitTransaction();
}
/**
* @param bool $forgetColumns
* @param bool $forgetIndexes
* @param bool $forgetForeigns
*/
protected function saveTables($forgetColumns, $forgetIndexes, $forgetForeigns)
{
foreach ($this->sortedTables() as $table) {
$table->save($forgetColumns, $forgetIndexes, $forgetForeigns);
}
}
/**
* Collecting all involved drivers.
*/
protected function collectDrivers()
{
foreach ($this->tables as $table) {
if (!in_array($table->driver(), $this->drivers, true)) {
$this->drivers[] = $table->driver();
}
}
}
/**
* Begin mass transaction.
*/
protected function beginTransaction()
{
$this->logger()->debug("Begin transaction");
foreach ($this->drivers as $driver) {
$driver->beginTransaction();
}
}
/**
* Commit mass transaction.
*/
protected function commitTransaction()
{
$this->logger()->debug("Commit transaction");
foreach ($this->drivers as $driver) {
$driver->commitTransaction();
}
}
/**
* Roll back mass transaction.
*/
protected function rollbackTransaction()
{
$this->logger()->warning("Roll back transaction");
foreach ($this->drivers as $driver) {
$driver->rollbackTransaction();
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Configs;
use Spiral\Core\InjectableConfig;
use Spiral\Core\Traits\Config\AliasTrait;
/**
* Translation component configuration.
*/
class ODMConfig extends InjectableConfig
{
use AliasTrait;
/**
* Configuration section.
*/
const CONFIG = 'odm';
/**
* @var array
*/
protected $config = [
'default' => '',
'aliases' => [],
'databases' => [],
'schemas' => [
'mutators' => [],
'mutatorAliases' => []
]
];
/**
* @return string
*/
public function defaultDatabase()
{
return $this->config['default'];
}
/**
* @param string $database
* @return bool
*/
public function hasDatabase($database)
{
return isset($this->config['databases'][$database]);
}
/**
* Database connection configuration.
*
* @param string $database
* @return array
*/
public function databaseConfig($database)
{
return $this->config['databases'][$database];
}
/**
* Resolve mutator alias.
*
* @param string $mutator
* @return string
*/
public function mutatorAlias($mutator)
{
if (!is_string($mutator) || !isset($this->config['schemas']['mutatorAliases'][$mutator])) {
return $mutator;
}
return $this->config['schemas']['mutatorAliases'][$mutator];
}
/**
* Get list of mutators associated with given type.
*
* @param string $type
* @return array
*/
public function getMutators($type)
{
return isset($this->config['schemas']['mutators'][$type])
? $this->config['schemas']['mutators'][$type]
: [];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres\Schemas;
use Spiral\Database\Entities\Schemas\AbstractTable;
/**
* Postgres table schema.
*/
class TableSchema extends AbstractTable
{
/**
* Found table sequences.
*
* @var array
*/
private $sequences = [];
/**
* Sequence object name usually defined only for primary keys and required by ORM to correctly
* resolve inserted row id.
*
* @var string|null
*/
private $primarySequence = null;
/**
* Sequence object name usually defined only for primary keys and required by ORM to correctly
* resolve inserted row id.
*
* @return string|null
*/
public function getSequence()
{
return $this->primarySequence;
}
/**
* {@inheritdoc}
*/
protected function loadColumns()
{
//Required for constraints fetch
$tableOID = $this->driver->query("SELECT oid FROM pg_class WHERE relname = ?", [
$this->getName()
])->fetchColumn();
//Collecting all candidates
$query = "SELECT * FROM information_schema.columns "
. "JOIN pg_type ON (pg_type.typname = columns.udt_name) WHERE table_name = ?";
$columnsQuery = $this->driver->query($query, [$this->getName()]);
foreach ($columnsQuery->bind('column_name', $columnName) as $column) {
if (preg_match(
'/^nextval\([\'"]([a-z0-9_"]+)[\'"](?:::regclass)?\)$/i',
$column['column_default'],
$matches
)) {
$this->sequences[$columnName] = $matches[1];
}
$this->registerColumn(
$this->columnSchema($columnName, $column + ['tableOID' => $tableOID])
);
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadIndexes()
{
$query = "SELECT * FROM pg_indexes WHERE schemaname = 'public' AND tablename = ?";
foreach ($this->driver->query($query, [$this->getName()]) as $index) {
$index = $this->registerIndex(
$this->indexSchema($index['indexname'], $index['indexdef'])
);
$conType = $this->driver->query(
"SELECT contype FROM pg_constraint WHERE conname = ?", [$index->getName()]
)->fetchColumn();
if ($conType == 'p') {
$this->setPrimaryKeys($index->getColumns());
//We don't need primary index in this form
$this->forgetIndex($index);
if (is_array($this->primarySequence) && count($index->getColumns()) === 1) {
$column = $index->getColumns()[0];
if (isset($this->sequences[$column])) {
//We found our primary sequence
$this->primarySequence = $this->sequences[$column];
}
}
}
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadReferences()
{
//Mindblowing
$query = "SELECT tc.constraint_name, tc.table_name, kcu.column_name, rc.update_rule, "
. "rc.delete_rule, ccu.table_name AS foreign_table_name, "
. "ccu.column_name AS foreign_column_name\n"
. "FROM information_schema.table_constraints AS tc\n"
. "JOIN information_schema.key_column_usage AS kcu\n"
. " ON tc.constraint_name = kcu.constraint_name\n"
. "JOIN information_schema.constraint_column_usage AS ccu\n"
. " ON ccu.constraint_name = tc.constraint_name\n"
. "JOIN information_schema.referential_constraints AS rc\n"
. " ON rc.constraint_name = tc.constraint_name\n"
. "WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name=?";
foreach ($this->driver->query($query, [$this->getName()]) as $reference) {
$this->registerReference(
$this->referenceSchema($reference['constraint_name'], $reference)
);
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function columnSchema($name, $schema = null)
{
return new ColumnSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function indexSchema($name, $schema = null)
{
return new IndexSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function referenceSchema($name, $schema = null)
{
return new ReferenceSchema($this, $name, $schema);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Tokenizer\Reflections\ReflectionInvocation;
/**
* Must provide generic information about given filename.
*/
interface ReflectionFileInterface
{
/**
* List of declared function names.
*
* @return array
*/
public function getFunctions();
/**
* List of declared classe names.
*
* @return array
*/
public function getClasses();
/**
* List of declared trait names.
*
* @return array
*/
public function getTraits();
/**
* List of declared interface names.
*
* @return array
*/
public function getInterfaces();
/**
* Indication that file contains require/include statements.
*
* @return bool
*/
public function hasIncludes();
/**
* Locate and return list of every method or function call in specified file. Only static class
* methods will be indexed.
*
* @return ReflectionInvocation[]
*/
public function getInvocations();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas;
use Psr\Log\LoggerAwareInterface;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Schemas\ColumnInterface;
use Spiral\Database\Schemas\TableInterface;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\ODM\Exceptions\SchemaException;
/**
* AbstractTable class used to describe and manage state of specified table. It provides ability to
* get table introspection, update table schema and automatically generate set of diff operations.
*
* Most of table operation like column, index or foreign key creation/altering will be applied when
* save() method will be called.
*
* Column configuration shortcuts:
* @method AbstractColumn primary($column)
* @method AbstractColumn bigPrimary($column)
* @method AbstractColumn enum($column, array $values)
* @method AbstractColumn string($column, $length = 255)
* @method AbstractColumn decimal($column, $precision, $scale)
* @method AbstractColumn boolean($column)
* @method AbstractColumn integer($column)
* @method AbstractColumn tinyInteger($column)
* @method AbstractColumn bigInteger($column)
* @method AbstractColumn text($column)
* @method AbstractColumn tinyText($column)
* @method AbstractColumn longText($column)
* @method AbstractColumn double($column)
* @method AbstractColumn float($column)
* @method AbstractColumn datetime($column)
* @method AbstractColumn date($column)
* @method AbstractColumn time($column)
* @method AbstractColumn timestamp($column)
* @method AbstractColumn binary($column)
* @method AbstractColumn tinyBinary($column)
* @method AbstractColumn longBinary($column)
*/
abstract class AbstractTable extends TableState implements TableInterface, LoggerAwareInterface
{
/**
* Some operation better to be logged.
*/
use LoggerTrait;
/**
* Indication that table is exists and current schema is fetched from database.
*
* @var bool
*/
private $exists = false;
/**
* Database specific tablePrefix. Required for table renames.
*
* @var string
*/
private $prefix = '';
/**
* We have to remember original schema state to create set of diff based commands.
*
* @invisible
* @var TableState
*/
protected $initial = null;
/**
* Compares current and original states.
*
* @invisible
* @var Comparator
*/
protected $comparator = null;
/**
* @invisible
* @var Driver
*/
protected $driver = null;
/**
* Executes table operations.
*
* @var AbstractCommander
*/
protected $commander = null;
/**
* @param Driver $driver Parent driver.
* @param AbstractCommander $commander
* @param string $name Table name, must include table prefix.
* @param string $prefix Database specific table prefix.
*/
public function __construct(Driver $driver, AbstractCommander $commander, $name, $prefix)
{
parent::__construct($name);
$this->driver = $driver;
$this->commander = $commander;
$this->prefix = $prefix;
//Locking down initial table state
$this->initial = new TableState($name);
//Needed to compare schemas
$this->comparator = new Comparator($this->initial, $this);
if (!$this->driver->hasTable($this->getName())) {
//There is no need to load table schema when table does not exist
return;
}
//Loading table information
$this->loadColumns()->loadIndexes()->loadReferences();
//Syncing schemas
$this->initial->syncSchema($this);
$this->exists = true;
}
/**
* Get associated table driver.
*
* @return Driver
*/
public function driver()
{
return $this->driver;
}
/**
* Get table comparator.
*
* @return Comparator
*/
public function comparator()
{
return $this->comparator;
}
/**
* {@inheritdoc}
*/
public function exists()
{
return $this->exists;
}
/**
* {@inheritdoc}
*
* Automatically forces prefix value.
*/
public function setName($name)
{
parent::setName($this->prefix . $name);
}
/**
* {@inheritdoc}
*
* @param bool $quoted Quote name.
*/
public function getName($quoted = false)
{
if (!$quoted) {
return parent::getName();
}
return $this->driver->identifier(parent::getName());
}
/**
* Return database specific table prefix.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* {@inheritdoc}
*/
public function getDependencies()
{
$tables = [];
foreach ($this->getForeigns() as $foreign) {
$tables[] = $foreign->getForeignTable();
}
return $tables;
}
/**
* Set table primary keys. Operation can only be applied for newly created tables. Now every
* database might support compound indexes.
*
* @param array $columns
* @return $this
* @throws SchemaException
*/
public function setPrimaryKeys(array $columns)
{
if ($this->exists() && $this->getPrimaryKeys() != $columns) {
throw new SchemaException("Unable to change primary keys for already exists table.");
}
parent::setPrimaryKeys($columns);
return $this;
}
/**
* Get/create instance of AbstractColumn associated with current table.
*
* Examples:
* $table->column('name')->string();
*
* @param string $name
* @return AbstractColumn
*/
public function column($name)
{
if (!empty($column = $this->findColumn($name))) {
return $column->declared(true);
}
$column = $this->columnSchema($name)->declared(true);
//Registering (without adding to initial schema)
return $this->registerColumn($column);
}
/**
* Get/create instance of AbstractIndex associated with current table based on list of forming
* column names.
*
* Example:
* $table->index('key');
* $table->index('key', 'key2');
* $table->index(['key', 'key2']);
*
* @param mixed $columns Column name, or array of columns.
* @return AbstractIndex
*/
public function index($columns)
{
$columns = is_array($columns) ? $columns : func_get_args();
if (!empty($index = $this->findIndex($columns))) {
return $index->declared(true);
}
$index = $this->indexSchema(null)->declared(true);
$index->columns($columns)->unique(false);
return $this->registerIndex($index);
}
/**
* Get/create instance of AbstractIndex associated with current table based on list of forming
* column names. Index type must be forced as UNIQUE.
*
* Example:
* $table->unique('key');
* $table->unique('key', 'key2');
* $table->unique(['key', 'key2']);
*
* @param mixed $columns Column name, or array of columns.
* @return AbstractColumn|null
*/
public function unique($columns)
{
$columns = is_array($columns) ? $columns : func_get_args();
return $this->index($columns)->unique(true);
}
/**
* Get/create instance of AbstractReference associated with current table based on local column
* name.
*
* @param string $column Column name.
* @return AbstractReference|null
*/
public function foreign($column)
{
if (!empty($foreign = $this->findForeign($column))) {
return $foreign->declared(true);
}
$foreign = $this->referenceSchema(null)->declared(true);
$foreign->column($column);
return $this->registerReference($foreign);
}
/**
* Rename column (only if column exists).
*
* @param string $column
* @param string $name New column name.
* @return $this
*/
public function renameColumn($column, $name)
{
if (empty($column = $this->findColumn($column))) {
return $this;
}
//Renaming automatically declares column
$column->declared(true)->setName($name);
return $this;
}
/**
* Rename index (only if index exists).
*
* @param array $columns Index forming columns.
* @param string $name New index name.
* @return $this
*/
public function renameIndex(array $columns, $name)
{
if (empty($index = $this->findIndex($columns))) {
return $this;
}
//Renaming automatically declares index
$index->declared(true)->setName($name);
return $this;
}
/**
* Drop column by it's name.
*
* @param string $column
* @return $this
*/
public function dropColumn($column)
{
if (!empty($column = $this->findColumn($column))) {
$this->forgetColumn($column);
$this->removeDependent($column);
}
return $this;
}
/**
* Drop index by it's forming columns.
*
* @param array $columns
* @return $this
*/
public function dropIndex(array $columns)
{
if (!empty($index = $this->findIndex($columns))) {
$this->forgetIndex($index);
}
return $this;
}
/**
* Drop foreign key by it's name.
*
* @param string $column
* @return $this
*/
public function dropForeign($column)
{
if (!empty($foreign = $this->findForeign($column))) {
$this->forgetForeign($foreign);
}
return $this;
}
/**
* Shortcut for column() method.
*
* @param string $column
* @return AbstractColumn
*/
public function __get($column)
{
return $this->column($column);
}
/**
* Column creation/altering shortcut, call chain is identical to:
* AbstractTable->column($name)->$type($arguments)
*
* Example:
* $table->string("name");
* $table->text("some_column");
*
* @param string $type
* @param array $arguments Type specific parameters.
* @return AbstractColumn
*/
public function __call($type, array $arguments)
{
return call_user_func_array(
[$this->column($arguments[0]), $type],
array_slice($arguments, 1)
);
}
/**
* Declare every existed element. Method has to be called if table modification applied to
* existed table to prevent dropping of existed elements.
*
* @return $this
*/
public function declareExisted()
{
foreach ($this->getColumns() as $column) {
$column->declared(true);
}
foreach ($this->getIndexes() as $index) {
$index->declared(true);
}
foreach ($this->getForeigns() as $foreign) {
$foreign->declared(true);
}
return $this;
}
/**
* Save table schema including every column, index, foreign key creation/altering. If table does
* not exist it must be created.
*
* @param bool $forgetColumns Drop all non declared columns.
* @param bool $forgetIndexes Drop all non declared indexes.
* @param bool $forgetForeigns Drop all non declared foreign keys.
*/
public function save($forgetColumns = true, $forgetIndexes = true, $forgetForeigns = true)
{
if (!$this->exists()) {
$this->createSchema();
} else {
//Let's remove from schema elements which wasn't declared
$this->forgetUndeclared($forgetColumns, $forgetIndexes, $forgetForeigns);
if ($this->hasChanges()) {
$this->synchroniseSchema();
}
}
//Syncing internal states
$this->initial->syncSchema($this);
$this->exists = true;
}
/**
* Drop table schema in database. This operation must be applied immediately.
*/
public function drop()
{
$this->forgetElements();
//Re-syncing initial state
$this->initial->syncSchema($this->forgetElements());
if ($this->exists()) {
$this->commander->dropTable($this->getName());
}
$this->exists = false;
}
/**
* @return AbstractColumn|string
*/
public function __toString()
{
return $this->getName();
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'name' => $this->getName(),
'primaryKeys' => $this->getPrimaryKeys(),
'columns' => array_values($this->getColumns()),
'indexes' => array_values($this->getIndexes()),
'references' => array_values($this->getForeigns())
];
}
/**
* Create table.
*/
protected function createSchema()
{
$this->logger()->debug("Creating new table {table}.", ['table' => $this->getName(true)]);
$this->commander->createTable($this);
}
/**
* Execute schema update.
*/
protected function synchroniseSchema()
{
if ($this->getName() != $this->initial->getName()) {
//Executing renaming
$this->commander->renameTable($this->initial->getName(), $this->getName());
}
//Some data has to be dropped before column updates
$this->dropForeigns()->dropIndexes();
//Generate update flow
$this->synchroniseColumns()->synchroniseIndexes()->synchroniseForeigns();
}
/**
* Synchronise columns.
*
* @return $this
*/
protected function synchroniseColumns()
{
foreach ($this->comparator->droppedColumns() as $column) {
$this->logger()->debug("Dropping column [{statement}] from table {table}.", [
'statement' => $column->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->dropColumn($this, $column);
}
foreach ($this->comparator->addedColumns() as $column) {
$this->logger()->debug("Adding column [{statement}] into table {table}.", [
'statement' => $column->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->addColumn($this, $column);
}
foreach ($this->comparator->alteredColumns() as $pair) {
/**
* @var AbstractColumn $initial
* @var AbstractColumn $current
*/
list($current, $initial) = $pair;
$this->logger()->debug("Altering column [{statement}] to [{new}] in table {table}.", [
'statement' => $initial->sqlStatement(),
'new' => $current->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->alterColumn($this, $initial, $current);
}
return $this;
}
/**
* Drop needed indexes.
*
* @return $this
*/
protected function dropIndexes()
{
foreach ($this->comparator->droppedIndexes() as $index) {
$this->logger()->debug("Dropping index [{statement}] from table {table}.", [
'statement' => $index->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->dropIndex($this, $index);
}
return $this;
}
/**
* Synchronise indexes.
*
* @return $this
*/
protected function synchroniseIndexes()
{
foreach ($this->comparator->addedIndexes() as $index) {
$this->logger()->debug("Adding index [{statement}] into table {table}.", [
'statement' => $index->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->addIndex($this, $index);
}
foreach ($this->comparator->alteredIndexes() as $pair) {
/**
* @var AbstractIndex $initial
* @var AbstractIndex $current
*/
list($current, $initial) = $pair;
$this->logger()->debug("Altering index [{statement}] to [{new}] in table {table}.", [
'statement' => $initial->sqlStatement(),
'new' => $current->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->alterIndex($this, $initial, $current);
}
return $this;
}
/**
* Drop needed foreign keys.
*
* @return $this
*/
protected function dropForeigns()
{
foreach ($this->comparator->droppedForeigns() as $foreign) {
$this->logger()->debug("Dropping foreign key [{statement}] from table {table}.", [
'statement' => $foreign->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->dropForeign($this, $foreign);
}
return $this;
}
/**
* Synchronise foreign keys.
*
* @return $this
*/
protected function synchroniseForeigns()
{
foreach ($this->comparator->addedForeigns() as $foreign) {
$this->logger()->debug("Adding foreign key [{statement}] into table {table}.", [
'statement' => $foreign->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->addForeign($this, $foreign);
}
foreach ($this->comparator->alteredForeigns() as $pair) {
/**
* @var AbstractReference $initial
* @var AbstractReference $current
*/
list($current, $initial) = $pair;
$this->logger()->debug("Altering foreign key [{statement}] to [{new}] in {table}.", [
'statement' => $initial->sqlStatement(),
'table' => $this->getName(true)
]);
$this->commander->alterForeign($this, $initial, $current);
}
return $this;
}
/**
* Driver specific column schema.
*
* @param string $name
* @param mixed $schema
* @return AbstractColumn
*/
abstract protected function columnSchema($name, $schema = null);
/**
* Driver specific index schema.
*
* @param string $name
* @param mixed $schema
* @return AbstractIndex
*/
abstract protected function indexSchema($name, $schema = null);
/**
* Driver specific reference schema.
*
* @param string $name
* @param mixed $schema
* @return AbstractReference
*/
abstract protected function referenceSchema($name, $schema = null);
/**
* Must load table columns.
*
* @see registerColumn()
* @return self
*/
abstract protected function loadColumns();
/**
* Must load table indexes.
*
* @see registerIndex()
* @return self
*/
abstract protected function loadIndexes();
/**
* Must load table references.
*
* @see registerReference()
* @return self
*/
abstract protected function loadReferences();
/**
* Check if table schema has been modified. Attention, you have to execute dropUndeclared first
* to get valid results.
*
* @return bool
*/
protected function hasChanges()
{
return $this->comparator->hasChanges();
}
/**
* Calculate difference (removed columns, indexes and foreign keys).
*
* @param bool $forgetColumns
* @param bool $forgetIndexes
* @param bool $forgetForeigns
*/
protected function forgetUndeclared($forgetColumns, $forgetIndexes, $forgetForeigns)
{
//We don't need to worry about changed or created columns, indexes and foreign keys here
//as it already handled, we only have to drop columns which were not listed in schema
foreach ($this->getColumns() as $column) {
if ($forgetColumns && !$column->isDeclared()) {
$this->forgetColumn($column);
$this->removeDependent($column);
}
}
foreach ($this->getIndexes() as $index) {
if ($forgetIndexes && !$index->isDeclared()) {
$this->forgetIndex($index);
}
}
foreach ($this->getForeigns() as $foreign) {
if ($forgetForeigns && !$foreign->isDeclared()) {
$this->forgetForeign($foreign);
}
}
}
/**
* Remove dependent indexes and foreign keys.
*
* @param ColumnInterface $column
*/
private function removeDependent(ColumnInterface $column)
{
if ($this->hasForeign($column->getName())) {
$this->forgetForeign($this->foreign($column->getName()));
}
foreach ($this->getIndexes() as $index) {
if (in_array($column->getName(), $index->getColumns())) {
//Dropping related indexes
$this->forgetIndex($index);
}
}
}
/**
* Forget all elements.
*
* @return $this
*/
private function forgetElements()
{
foreach ($this->getColumns() as $column) {
$this->forgetColumn($column);
}
foreach ($this->getIndexes() as $index) {
$this->forgetIndex($index);
}
foreach ($this->getForeigns() as $foreign) {
$this->forgetForeign($foreign);
}
return $this;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\ORM\Entities\Schemas\Relations\Traits\ColumnsTrait;
use Spiral\ORM\Entities\Schemas\RelationSchema;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* ManyToMany relation declares that two records related to each other using pivot table data.
* Relation allow to specify inner key (key in parent record), outer key (key in outer record),
* pivot table name, names of pivot columns to store inner and outer key values and set of
* additional columns. Relation allow specifying default WHERE statement for outer records and
* pivot table separately.
*
* Example (User related to many Tag records):
* - relation will create pivot table named "tag_user_map" (if allowed), where table name generated
* based on roles of inner and outer tables sorted in ABC order (you can change name)
* - relation will create pivot key named "user_id" related to User primary key
* - relation will create pivot key named "tag_id" related to Tag primary key
* - relation will create unique index on "user_id" and "tag_id" columns if allowed
* - relation will create foreign key "tag_user_map"."user_id" => "users"."id" if allowed
* - relation will create foreign key "tag_user_map"."tag_id" => "tags"."id" if allowed
* - relation will create additional columns in pivot table if any requested
*/
class ManyToManySchema extends RelationSchema
{
/**
* Relation may create custom columns in pivot table using Record schema format.
*/
use ColumnsTrait;
/**
* {@inheritdoc}
*/
const RELATION_TYPE = RecordEntity::MANY_TO_MANY;
/**
* Relation represent multiple records.
*/
const MULTIPLE = true;
/**
* {@inheritdoc}
*
* When relation states that relation defines connection to interface relation will be switched
* to ManyToManyMorphed.
*/
const EQUIVALENT_RELATION = RecordEntity::MANY_TO_MORPHED;
/**
* Default postfix for pivot tables.
*/
const PIVOT_POSTFIX = '_map';
/**
* {@inheritdoc}
*
* @invisible
*/
protected $defaultDefinition = [
//Inner key of parent record will be used to fill "THOUGHT_INNER_KEY" in pivot table
RecordEntity::INNER_KEY => '{record:primaryKey}',
//We are going to use primary key of outer table to fill "THOUGHT_OUTER_KEY" in pivot table
//This is technically "inner" key of outer record, we will name it "outer key" for simplicity
RecordEntity::OUTER_KEY => '{outer:primaryKey}',
//Name field where parent record inner key will be stored in pivot table, role + innerKey
//by default
RecordEntity::THOUGHT_INNER_KEY => '{record:role}_{definition:innerKey}',
//Name field where inner key of outer record (outer key) will be stored in pivot table,
//role + outerKey by default
RecordEntity::THOUGHT_OUTER_KEY => '{outer:role}_{definition:outerKey}',
//Set constraints in pivot table (foreign keys)
RecordEntity::CONSTRAINT => true,
//@link https://en.wikipedia.org/wiki/Foreign_key
RecordEntity::CONSTRAINT_ACTION => 'CASCADE',
//Relation allowed to create indexes in pivot table
RecordEntity::CREATE_INDEXES => true,
//Name of pivot table to be declared, default value is not stated as it will be generated
//based on roles of inner and outer records
RecordEntity::PIVOT_TABLE => null,
//Relation allowed to create pivot table
RecordEntity::CREATE_PIVOT => true,
//Additional set of columns to be added into pivot table, you can use same column definition
//type as you using for your records
RecordEntity::PIVOT_COLUMNS => [],
//Set of default values to be used for pivot table
RecordEntity::PIVOT_DEFAULTS => [],
//WHERE statement in a form of simplified array definition to be applied to pivot table
//data.
RecordEntity::WHERE_PIVOT => [],
//WHERE statement to be applied for data in outer data while loading relation data
//can not be inversed. Attention, WHERE conditions not used in has(), link() and sync()
//methods.
RecordEntity::WHERE => []
];
/**
* {@inheritdoc}
*/
public function inverseRelation()
{
//Many to many relation can be inversed pretty easily, we only have to swap inner keys
//with outer keys, however WHERE conditions can not be inversed
$this->outerRecord()->addRelation($this->definition[RecordEntity::INVERSE], [
RecordEntity::MANY_TO_MANY => $this->record->getName(),
RecordEntity::PIVOT_TABLE => $this->definition[RecordEntity::PIVOT_TABLE],
RecordEntity::OUTER_KEY => $this->definition[RecordEntity::INNER_KEY],
RecordEntity::INNER_KEY => $this->definition[RecordEntity::OUTER_KEY],
RecordEntity::THOUGHT_INNER_KEY => $this->definition[RecordEntity::THOUGHT_OUTER_KEY],
RecordEntity::THOUGHT_OUTER_KEY => $this->definition[RecordEntity::THOUGHT_INNER_KEY],
RecordEntity::CONSTRAINT => $this->definition[RecordEntity::CONSTRAINT],
RecordEntity::CONSTRAINT_ACTION => $this->definition[RecordEntity::CONSTRAINT_ACTION],
RecordEntity::CREATE_INDEXES => $this->definition[RecordEntity::CREATE_INDEXES],
RecordEntity::CREATE_PIVOT => $this->definition[RecordEntity::CREATE_PIVOT],
RecordEntity::PIVOT_COLUMNS => $this->definition[RecordEntity::PIVOT_COLUMNS],
RecordEntity::WHERE_PIVOT => $this->definition[RecordEntity::WHERE_PIVOT]
]);
}
/**
* Generate name of pivot table or fetch if from schema.
*
* @return string
*/
public function getPivotTable()
{
if (isset($this->definition[RecordEntity::PIVOT_TABLE])) {
return $this->definition[RecordEntity::PIVOT_TABLE];
}
//Generating pivot table name
$names = [$this->record->getRole(), $this->outerRecord()->getRole()];
asort($names);
return join('_', $names) . static::PIVOT_POSTFIX;
}
/**
* Instance of AbstractTable associated with relation pivot table.
*
* @return AbstractTable
*/
public function pivotSchema()
{
return $this->builder->declareTable(
$this->record->getDatabase(),
$this->getPivotTable()
);
}
/**
* {@inheritdoc}
*/
public function buildSchema()
{
if (!$this->definition[RecordEntity::CREATE_PIVOT]) {
//No pivot table creation were requested, noting really to do
return;
}
$pivotTable = $this->pivotSchema();
//Thought outer key points to inner key in outer record (outer key)
$outerKey = $pivotTable->column($this->definition[RecordEntity::THOUGHT_OUTER_KEY]);
$outerKey->setType($this->getOuterKeyType());
if ($this->hasMorphKey()) {
//ManyToManyMorphed relation will cause creation set of ManyToMany relations
//linking every possible morphed record with parent record
$morphKey = $pivotTable->column($this->getMorphKey());
$morphKey->string(static::MORPH_COLUMN_SIZE);
}
//Thought inner key points to inner key in parent record
$innerKey = $pivotTable->column($this->definition[RecordEntity::THOUGHT_INNER_KEY]);
$innerKey->setType($this->getInnerKeyType());
//Casting pivot table columns
$this->castTable(
$this->pivotSchema(),
$this->definition[RecordEntity::PIVOT_COLUMNS],
$this->definition[RecordEntity::PIVOT_DEFAULTS]
);
if (!$this->isConstrained() || $this->hasMorphKey()) {
//Either not need to create constraint or it relation is polymorphic, we also
//can't create indexes in this case
return;
}
if ($this->isIndexed()) {
//Unique index are added to pivot table keys, you can't link records multiple times
//If you DO want to do that, please create necessary tables and indexes using migrations
$pivotTable->unique(
$this->definition[RecordEntity::THOUGHT_INNER_KEY],
$this->definition[RecordEntity::THOUGHT_OUTER_KEY]
);
}
//Inner pivot key = parent record inner key
$foreignKey = $innerKey->references(
$this->record->getTable(),
$this->record->getPrimaryKey()
);
$foreignKey->onDelete($this->getConstraintAction());
$foreignKey->onUpdate($this->getConstraintAction());
//Outer pivot key = outer record inner key (outer key)
$foreignKey = $outerKey->references(
$this->outerRecord()->getTable(),
$this->outerRecord()->getPrimaryKey()
);
$foreignKey->onDelete($this->getConstraintAction());
$foreignKey->onUpdate($this->getConstraintAction());
}
/**
* {@inheritdoc}
*/
protected function normalizeDefinition()
{
$definition = parent::normalizeDefinition();
$definition[RecordEntity::PIVOT_COLUMNS] = [];
foreach ($this->pivotSchema()->getColumns() as $column) {
//Let's include pivot table columns, it will help many to many loaded to map data correctly
$definition[RecordEntity::PIVOT_COLUMNS][] = $column->getName();
}
//We must include pivot table database into data for easier access
$definition[ORM::R_DATABASE] = $this->outerRecord()->getDatabase();
return $definition;
}
/**
* {@inheritdoc}
*/
protected function clarifyDefinition()
{
parent::clarifyDefinition();
if (empty($this->definition[RecordEntity::PIVOT_TABLE])) {
$this->definition[RecordEntity::PIVOT_TABLE] = $this->getPivotTable();
}
if (!$this->isSameDatabase()) {
throw new RelationSchemaException(
"Many-to-Many relation can create relations ({$this}) only to entities from same database."
);
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
/**
* Errors inside ODM document compositor.
*/
class CompositorException extends AccessorException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Exceptions;
use Spiral\Models\Exceptions\FieldExceptionInterface;
/**
* When field can not be set or get.
*/
class FieldException extends RecordException implements FieldExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas;
use Doctrine\Common\Inflector\Inflector;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Entities\Schemas\AbstractIndex;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Models\Reflections\ReflectionEntity;
use Spiral\ORM\Entities\SchemaBuilder;
use Spiral\ORM\Exceptions\DefinitionException;
use Spiral\ORM\Exceptions\RecordSchemaException;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\Exceptions\SchemaException;
use Spiral\ORM\RecordAccessorInterface;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\Schemas\RelationInterface;
/**
* Performs analysis, schema building and table declaration for one specific Record class.
*
* You have to call
*/
class RecordSchema extends ReflectionEntity
{
/**
* Required to validly merge parent and children attributes.
*/
const BASE_CLASS = RecordEntity::class;
/**
* Related source class.
*
* @var string
*/
private $source = null;
/**
* Every ORM Record must have associated database table, table will be used to read column
* names, default values and write declared record changes.
*
* @var AbstractTable
*/
private $tableSchema = null;
/**
* Declared and requested record relationships.
*
* @var RelationInterface[]
*/
protected $relations = [];
/**
* @invisible
* @var SchemaBuilder
*/
protected $builder = null;
/**
* @param SchemaBuilder $builder Parent ORM schema (all other documents).
* @param string $class Class name.
* @throws \ReflectionException
* @throws DefinitionException
* @throws RecordSchemaException
*/
public function __construct(SchemaBuilder $builder, $class)
{
parent::__construct($class);
$this->builder = $builder;
//Associated table
$this->tableSchema = $this->builder->declareTable($this->getDatabase(), $this->getTable());
/**
* Use record schema (property) to declare table indexes, columns and default values.
* No relations has to be declared at this point.
*/
$this->castSchema();
}
/**
* Associate source class.
*
* @param string $class
*/
public function setSource($class)
{
$this->source = $class;
}
/**
* Related source class.
*
* @return string|null
*/
public function getSource()
{
return $this->source;
}
/**
* @return AbstractTable
*/
public function tableSchema()
{
return $this->tableSchema;
}
/**
* Returns true if Record states that related table can be altered by ORM. To allow schema
* altering set record constant ACTIVE_SCHEMA to true.
*
* Tables associated to records with ACTIVE_SCHEMA = false counted as "passive".
*
* @see Record::ACTIVE_SCHEMA
* @return bool
*/
public function isActive()
{
return !empty($this->getConstant('ACTIVE_SCHEMA'));
}
/**
* Record role named used widely in relations to generate inner and outer keys, define related
* class and table in morphed relations and etc. You can defined your own role name by defining
* record constant MODEL_ROLE.
*
* Example:
* Record: Records\Post with primary key "id"
* Relation: HAS_ONE
* Outer key: post_id
*
* @return string
*/
public function getRole()
{
if ($this->hasConstant('MODEL_ROLE') && !empty($this->getConstant('MODEL_ROLE'))) {
return $this->getConstant('MODEL_ROLE');
}
return lcfirst($this->getShortName());
}
/**
* Source table. In cases where table name was not specified, RecordSchema will generate need
* value using class name and Doctrine inflector.
*
* @see Record::$table
* @return mixed
*/
public function getTable()
{
if (empty($table = $this->property('table'))) {
//We can guess table name
$table = Inflector::tableize($this->getShortName());
//Table names are plural by default
return Inflector::pluralize($table);
}
return $table;
}
/**
* Get database where record data should be stored in. Database alias must be resolved.
*
* @see Record::$database
* @return mixed
*/
public function getDatabase()
{
return $this->builder->resolveDatabase($this->property('database'));
}
/**
* SourceID must fully describe record source table and database in context of application.
*
* @return string
*/
public function getTableID()
{
return $this->getDatabase() . '.' . $this->getTable();
}
/**
* Name of first primary key (usually sequence). Might return null for records with no primary
* key.
*
* @return string|null
*/
public function getPrimaryKey()
{
if (empty($this->tableSchema->getPrimaryKeys())) {
return null;
}
//Spiral ORM can work only with singular primary keys for now... for now.
return array_slice($this->tableSchema->getPrimaryKeys(), 0, 1)[0];
}
/**
* Get declared indexes. This may not be the same set of indexes as in associated table schema,
* use RecordSchema->tableSchema()->getIndexes() method to get real table indexes.
*
* @see Record::$indexes
* @see tableSchema()
* @return array
*/
public function getIndexes()
{
return $this->property('indexes', true);
}
/**
* {@inheritdoc}
*/
public function getFields()
{
$result = [];
foreach ($this->tableSchema->getColumns() as $column) {
//Yep, so simple
$result[$column->getName()] = $column->phpType();
}
return $result;
}
/**
* Get column names associated with their default values. Default values will be fetched from
* values declared by record and values declared in associated table schema. Every default value
* will be normalized in a cachable form (no objects allowed here).
*
* @return array
*/
public function getDefaults()
{
//We have to reiterate columns as schema can be altered while relation creation,
//plus we always have to keep original columns order (this is very important)
$defaults = [];
$recordDefaults = $this->property('defaults', true);
//We must pass all default values thought set of setters and accessor to ensure their value
$setters = $this->getSetters();
$accessors = $this->getAccessors();
foreach ($this->tableSchema->getColumns() as $column) {
//Let's use default value fetched from column first
$default = $this->exportDefault($column);
if (isset($recordDefaults[$column->getName()])) {
//Let's use value declared in record schema
$default = $recordDefaults[$column->getName()];
}
if (is_null($default) && in_array($column->getName(), $this->getNullable())) {
//We must keep null values
$defaults[$column->getName()] = $default;
continue;
}
if (isset($accessors[$column->getName()])) {
$accessor = $accessors[$column->getName()];
$accessor = new $accessor($default, null);
if ($accessor instanceof RecordAccessorInterface) {
$default = $accessor->defaultValue($this->tableSchema->driver());
}
}
if (isset($setters[$column->getName()])) {
try {
$setter = $setters[$column->getName()];
//Applying filter to default value
$default = call_user_func($setter, $default);
} catch (\ErrorException $exception) {
//Ignoring
}
}
$defaults[$column->getName()] = $default;
}
return $defaults;
}
/**
* Get array of fields which can be set with null value. Record schema must allow setting this
* values to null and bypass filters.
*
* @return array
*/
public function getNullable()
{
$result = [];
foreach ($this->tableSchema->getColumns() as $column) {
if ($column->isNullable()) {
$result[] = $column->getName();
}
}
//Let's include primary keys to nullable fields
return array_unique(array_merge($result, $this->tableSchema->getPrimaryKeys()));
}
/**
* Record will utilize it's schema definition to create set of relations to other records and
* entities (for example ODM).
*
* @throws SchemaException
* @throws RelationSchemaException
*/
public function castRelations()
{
foreach ($this->property('schema', true) as $name => $definition) {
if (is_scalar($definition)) {
//Column definition or something else
continue;
}
if (!$this->hasRelation($name)) {
$this->addRelation($name, $definition);
}
}
}
/**
* Check if RecordSchema already have declared relation by it's name.
*
* @param string $name
* @return bool
*/
public function hasRelation($name)
{
return isset($this->relations[$name]);
}
/**
* Declare new record relation by it's name and definition. Only unique relations can be added.
*
* @see SchemaBuilder::relationSchema()
* @param string $name
* @param array $definition
* @throws RecordSchemaException
*/
public function addRelation($name, array $definition)
{
if (isset($this->relations[$name])) {
throw new RecordSchemaException(
"Unable to create relation '{$this}'.'{$name}', relation already exists."
);
}
$relation = $this->builder->relationSchema($this, $name, $definition);
//We can cast relation only if it's parent class has active schema
if ($this->isActive() && $relation->isReasonable()) {
//Initiating required columns, foreign keys and indexes
$relation->buildSchema();
}
$this->relations[$name] = $relation;
}
/**
* Get all declared or requested record relation schemas.
*
* @return RelationInterface[]
*/
public function getRelations()
{
return $this->relations;
}
/**
* {@inheritdoc}
*
* Schema can generate accessors and filters based on field type.
*/
public function getMutators()
{
$mutators = parent::getMutators();
//Trying to resolve mutators based on field type
foreach ($this->tableSchema->getColumns() as $column) {
//Resolved filters
$resolved = [];
if (!empty($filter = $this->builder->getMutators($column->abstractType()))) {
//Mutator associated with type directly
$resolved += $filter;
} elseif (!empty($filter = $this->builder->getMutators('php:' . $column->phpType()))) {
//Mutator associated with php type
$resolved += $filter;
}
//Merging mutators and default mutators
foreach ($resolved as $mutator => $filter) {
if (!array_key_exists($column->getName(), $mutators[$mutator])) {
$mutators[$mutator][$column->getName()] = $filter;
}
}
}
foreach ($mutators as $mutator => &$filters) {
foreach ($filters as $field => $filter) {
//Some mutators may be described using aliases (for shortness)
$filters[$field] = $this->builder->mutatorAlias($filter);
}
unset($filters);
}
return $mutators;
}
/**
* Method utilizes value of record schema property to generate table columns. Property "indexes"
* going to feed table indexes.
*
* @see Record::$schema
* @throws DefinitionException
* @throws \Spiral\Database\Exceptions\SchemaException
*/
protected function castSchema()
{
//Default values fetched from record, system will try to use this values as default
//values for associated table column
$defaults = $this->property('defaults', true);
foreach ($this->property('schema', true) as $name => $definition) {
if (is_array($definition)) {
//Relation or something else
continue;
}
//Let's cast table column using it's name, declared definition and default value (if any)
$this->castColumn(
$this->tableSchema->column($name),
$definition,
isset($defaults[$name]) ? $defaults[$name] : null
);
}
//Casting declared record indexes
foreach ($this->getIndexes() as $definition) {
$this->castIndex($definition);
}
}
/**
* {@inheritdoc}
*/
protected function parentSchema()
{
if (!$this->builder->hasRecord($this->getParentClass()->getName())) {
return null;
}
return $this->builder->record($this->getParentClass()->getName());
}
/**
* Cast (specify) column schema based on provided column definition and default value.
* Spiral will force default values (internally) for every NOT NULL column except primary keys!
*
* Column definition are compatible with database Migrations and AbstractColumn types.
*
* Column definition examples (by default all columns has flag NOT NULL):
* protected $schema = [
* 'id' => 'primary',
* 'name' => 'string', //Default length is 255 characters.
* 'email' => 'string(255), nullable', //Can be NULL
* 'status' => 'enum(active, pending, disabled)', //Enum values, trimmed
* 'balance' => 'decimal(10, 2)',
* 'message' => 'text, null', //Alias for nullable
* 'time_expired' => 'timestamp'
* ];
*
* @see AbstractColumn
* @param AbstractColumn $column
* @param string $definition
* @param mixed $default Default value declared by record schema.
* @return mixed
* @throws DefinitionException
* @throws \Spiral\Database\Exceptions\SchemaException
*/
private function castColumn(AbstractColumn $column, $definition, $default = null)
{
//Expression used to declare column type, easy to read
$pattern = '/(?P<type>[a-z]+)(?: *\((?P<options>[^\)]+)\))?(?: *, *(?P<nullable>null(?:able)?))?/i';
if (!preg_match($pattern, $definition, $type)) {
throw new DefinitionException(
"Invalid column type definition in '{$this}'.'{$column->getName()}'."
);
}
if (!empty($type['options'])) {
//Exporting and trimming
$type['options'] = array_map('trim', explode(',', $type['options']));
}
//We are forcing every column to be NOT NULL by default, DEFAULT value should fix potential
//problems, nullable flag must be applied before type was set (some types do not want
//null values to be allowed)
$column->nullable(!empty($type['nullable']));
//Bypassing call to AbstractColumn->__call method (or specialized column method)
call_user_func_array(
[$column, $type['type']],
!empty($type['options']) ? $type['options'] : []
);
if (in_array($column->getName(), $this->tableSchema->getPrimaryKeys())) {
//No default value can be set of primary keys
return $column;
}
if (!is_null($default)) {
//We have default value stated my record schema
$column->defaultValue($default);
}
if (!$column->hasDefaultValue() && !$column->isNullable()) {
//Ouch, columns like that can break synchronization!
$column->defaultValue($this->castDefault($column));
}
return $column;
}
/**
* Cast (specify) index shema in associated table based on Record index property definition.
* Only normal or unique indexes can be casted at this moment.
*
* Example:
* protected $indexes = array(
* [self::UNIQUE, 'email'],
* [self::INDEX, 'status', 'balance'],
* [self::INDEX, 'public_id']
* );
*
* @param array $definition
* @return AbstractIndex
* @throws DefinitionException
* @throws \Spiral\Database\Exceptions\SchemaException
*/
protected function castIndex(array $definition)
{
//Index type (UNIQUE or INDEX)
$type = null;
//Columns index associated too
$columns = [];
foreach ($definition as $chunk) {
if ($chunk == RecordEntity::INDEX || $chunk == RecordEntity::UNIQUE) {
$type = $chunk;
continue;
}
if (!$this->tableSchema->hasColumn($chunk)) {
throw new DefinitionException(
"Record '{$this}' has index definition with undefined local column."
);
}
$columns[] = $chunk;
}
if (empty($type)) {
throw new DefinitionException(
"Record '{$this}' has index definition with unspecified index type."
);
}
if (empty($columns)) {
throw new DefinitionException(
"Record '{$this}' has index definition without any column associated to."
);
}
//Casting schema
return $this->tableSchema->index($columns)->unique($type == RecordEntity::UNIQUE);
}
/**
* Export default value from column schema into scalar form (which we can store in cache).
*
* @param AbstractColumn $column
* @return mixed|null
*/
private function exportDefault(AbstractColumn $column)
{
if (in_array($column->getName(), $this->tableSchema->getPrimaryKeys())) {
//Column declared as primary key, nothing to do with default values
return null;
}
$defaultValue = $column->getDefaultValue();
if ($defaultValue instanceof FragmentInterface) {
//We can't cache values like that
return null;
}
if (is_null($defaultValue) && !$column->isNullable()) {
return $this->castDefault($column);
}
return $defaultValue;
}
/**
* Cast default value based on column type. Required to prevent conflicts when not nullable
* column added to existed table with data in.
*
* @param AbstractColumn $column
* @return bool|float|int|mixed|string
*/
private function castDefault(AbstractColumn $column)
{
if ($column->abstractType() == 'timestamp' || $column->abstractType() == 'datetime') {
$driver = $this->tableSchema->driver();
return $driver::DEFAULT_DATETIME;
}
if ($column->abstractType() == 'enum') {
//We can use first enum value as default
return $column->getEnumValues()[0];
}
if ($column->abstractType() == 'json') {
return '{}';
}
switch ($column->phpType()) {
case 'int':
return 0;
break;
case 'float':
return 0.0;
break;
case 'bool':
return false;
break;
}
return '';
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
* @copyright �2009-2015
*/
namespace Spiral\ODM\Entities\Schemas;
use Doctrine\Common\Inflector\Inflector;
use Spiral\Models\Reflections\ReflectionEntity;
use Spiral\ODM\Document;
use Spiral\ODM\DocumentAccessorInterface;
use Spiral\ODM\DocumentEntity;
use Spiral\ODM\Entities\Compositor;
use Spiral\ODM\Entities\SchemaBuilder;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\SchemaException;
use Spiral\ODM\ODM;
/**
* Performs analysis and schema building for one specific Document class.
*/
class DocumentSchema extends ReflectionEntity
{
/**
* Required to validly merge parent and children attributes.
*/
const BASE_CLASS = DocumentEntity::class;
/**
* Related source class.
*
* @var string
*/
private $source = null;
/**
* @invisible
* @var SchemaBuilder
*/
protected $builder = null;
/**
* @param SchemaBuilder $builder Parent ODM schema (all other documents).
* @param string $class Class name.
* @throws \ReflectionException
*/
public function __construct(SchemaBuilder $builder, $class)
{
$this->builder = $builder;
parent::__construct($class);
}
/**
* Associate source class.
*
* @param string $class
*/
public function setSource($class)
{
$this->source = $class;
}
/**
* Related source class.
*
* @return string|null
*/
public function getSource()
{
return $this->source;
}
/**
* Document has not collection and only be embedded.
*
* @return bool
*/
public function isEmbeddable()
{
return !$this->isSubclassOf(Document::class);
}
/**
* Collection name associated with document model. Can automatically generate collection name
* based on model class.
*
* @return mixed
*/
public function getCollection()
{
if ($this->isEmbeddable()) {
return null;
}
$collection = $this->property('collection');
if (empty($collection)) {
if ($this->parentSchema()) {
//Using parent collection
return $this->parentSchema()->getCollection();
}
$collection = Inflector::camelize($this->getShortName());
$collection = Inflector::pluralize($collection);
}
return $collection;
}
/**
* Database document data should be stored in. Database alias will be resolved.
*
* @return mixed
*/
public function getDatabase()
{
if ($this->isEmbeddable()) {
return null;
}
return $this->builder->databaseAlias($this->property('database'));
}
/**
* {@inheritdoc}
*
* @throws SchemaException
*/
public function getFields()
{
//We should select only embedded fields, no aggregations
$fields = [];
foreach ($this->getSchema() as $field => $type) {
if ($this->isAggregation($type)) {
//Aggregation
continue;
}
if (is_array($type) && empty($type[0])) {
throw new SchemaException("Type definition of {$this}.{$field} is invalid.");
}
$fields[$field] = $type;
}
return $fields;
}
/**
* Document default values type-casted with model accessors, setters and compositors.
*
* @return array
* @throws SchemaException
*/
public function getDefaults()
{
//Default values described in defaults property, inherited
$defaults = $this->property('defaults', true);
$setters = $this->getSetters();
$accessors = $this->getAccessors();
foreach ($this->getFields() as $field => $type) {
$default = is_array($type) ? [] : null;
if (array_key_exists($field, $defaults)) {
//Default value declared in model schema
$default = $defaults[$field];
}
if (isset($setters[$field])) {
try {
$setter = $setters[$field];
//Applying filter to default value
$default = call_user_func($setter, $default);
} catch (\ErrorException $exception) {
//Ignoring
}
}
if (isset($accessors[$field])) {
$default = $this->accessorDefaults($accessors[$field], $type, $default);
}
//Using composition to resolve default value
if (!empty($this->getCompositions()[$field])) {
$default = $this->compositionDefaults($field, $default);
}
$defaults[$field] = $default;
}
return $defaults;
}
/**
* Get indexes requested by document and it's children from the same collection.
*
* @return array
*/
public function getIndexes()
{
if ($this->isEmbeddable()) {
return [];
}
$indexes = $this->property('indexes', true);
foreach ($this->getChildren(true) as $children) {
$indexes = array_merge($indexes, $children->getIndexes());
}
return $indexes;
}
/**
* Declared document compositions.
*
* @return array
* @throws SchemaException
*/
public function getCompositions()
{
$compositions = [];
foreach ($this->getFields() as $field => $type) {
if (is_scalar($type)) {
if ($this->builder->hasDocument($type)) {
$compositions[$field] = [
'type' => ODM::CMP_ONE,
'class' => $type
];
}
continue;
}
$type = $type[0];
if ($this->builder->hasDocument($type)) {
$compositions[$field] = [
'type' => ODM::CMP_MANY,
'class' => $type
];
}
}
return $compositions;
}
/**
* Declared document aggregations.
*
* @return array
* @throws SchemaException
*/
public function getAggregations()
{
$aggregations = [];
foreach ($this->getSchema() as $field => $options) {
if (!$this->isAggregation($options)) {
//Not aggregation
continue;
}
//Class to be aggregated
$class = isset($options[DocumentEntity::MANY])
? $options[DocumentEntity::MANY]
: $options[DocumentEntity::ONE];
if (!$this->builder->hasDocument($class)) {
throw new SchemaException(
"Unable to build aggregation {$this}.{$field}, no such document '{$class}'."
);
}
$document = $this->builder->document($class);
if ($document->isEmbeddable()) {
throw new SchemaException(
"Unable to build aggregation {$this}.{$field}, "
. "document '{$class}' does not have any collection."
);
}
if (!empty($options[DocumentEntity::MANY])) {
//Aggregation may select parent document
$class = $document->getParent(true)->getName();
}
$aggregations[$field] = [
'type' => isset($options[DocumentEntity::ONE]) ? DocumentEntity::ONE : DocumentEntity::MANY,
'class' => $class,
'collection' => $document->getCollection(),
'database' => $document->getDatabase(),
'query' => array_pop($options)
];
}
return $aggregations;
}
/**
* {@inheritdoc}
*
* Schema can generate accessors and filters based on field type.
*/
public function getMutators()
{
$mutators = parent::getMutators();
//Trying to resolve mutators based on field type
foreach ($this->getFields() as $field => $type) {
//Resolved filters
$resolved = [];
if (
is_array($type)
&& is_scalar($type[0])
&& $filter = $this->builder->getMutators('array::' . $type[0])
) {
//Mutator associated to array with specified type
$resolved += $filter;
} elseif (is_array($type) && $filter = $this->builder->getMutators('array')) {
//Default array mutator
$resolved += $filter;
} elseif (!is_array($type) && $filter = $this->builder->getMutators($type)) {
//Mutator associated with type directly
$resolved += $filter;
}
if (isset($resolved[self::MUTATOR_ACCESSOR])) {
//Accessor options include field type, this is ODM specific behaviour
$resolved[self::MUTATOR_ACCESSOR] = [
$resolved[self::MUTATOR_ACCESSOR],
is_array($type) ? $type[0] : $type
];
}
//Merging mutators and default mutators
foreach ($resolved as $mutator => $filter) {
if (!array_key_exists($field, $mutators[$mutator])) {
$mutators[$mutator][$field] = $filter;
}
}
}
//Some mutators may be described using aliases (for shortness)
$mutators = $this->normalizeMutators($mutators);
//Every composition is counted as field accessor :)
foreach ($this->getCompositions() as $field => $composition) {
$mutators[self::MUTATOR_ACCESSOR][$field] = [
$composition['type'] == ODM::CMP_MANY ? Compositor::class : ODM::CMP_ONE,
$composition['class']
];
}
return $mutators;
}
/**
* Get Document child classes.
*
* Example:
* Class A
* Class B extends A
* Class D extends A
* Class E extends D
*
* Result: B, D, E
*
* @see getPrimary()
* @param bool $sameCollection Find only children related to same collection as parent.
* @param bool $firstOrder Only child extended directly from current document.
* @return DocumentSchema[]
*/
public function getChildren($sameCollection = false, $firstOrder = false)
{
$result = [];
foreach ($this->builder->getDocuments() as $document) {
if ($document->isSubclassOf($this)) {
if ($sameCollection && !$this->compareCollection($document)) {
//Child changed collection or database
continue;
}
if ($firstOrder && $document->getParentClass()->getName() != $this->getName()) {
//Grandson
continue;
}
$result[] = $document;
}
}
return $result;
}
/**
* Get schema of top parent of current document or document schema itself. This method is
* reverse implementation of getChildren().
*
* @see getChindren()
* @param bool $sameCollection Only document with same collection.
* @return DocumentSchema
*/
public function getParent($sameCollection = false)
{
$result = $this;
foreach ($this->builder->getDocuments() as $document) {
if (!$result->isSubclassOf($document)) {
//I'm not your father!
continue;
}
if ($sameCollection && !$result->compareCollection($document)) {
//Different collection
continue;
}
//Level down
$result = $document;
}
return $result;
}
/**
* Parent document schema or null. Similar to getParentClass().
*
* @see parentSchema()
* @return DocumentSchema|null
*/
public function getParentDocument()
{
return $this->parentSchema();
}
/**
* Compile information required to resolve class instance using given set of fields. Fields
* based definition will analyze unique fields in every child model to create association
* between model class and required set of fields. Only document from same collection will be
* involved in definition creation. Definition built only for child of first order.
*
* @return array|string
* @throws SchemaException
* @throws DefinitionException
*/
public function classDefinition()
{
if (empty($children = $this->getChildren(true, true))) {
//No children
return $this->getName();
}
if ($this->getConstant('DEFINITION') == DocumentEntity::DEFINITION_LOGICAL) {
//Class definition will be performed using method with custom logic
return [
'type' => DocumentEntity::DEFINITION_LOGICAL,
'options' => [$this->getName(), 'defineClass']
];
}
//Definition will be performed using field = class association
$definition = [
'type' => DocumentEntity::DEFINITION_FIELDS,
'options' => []
];
//We must sort child in order or unique fields
uasort($children, [$this, 'sortChildren']);
//Fields which are common for parent and child models
$commonFields = $this->getFields();
foreach ($children as $document) {
//Child document fields
if (empty($fields = $document->getFields())) {
throw new DefinitionException(
"Child document {$document} of {$this} does not have any fields."
);
}
$uniqueField = null;
if (empty($commonFields)) {
//Parent did not declare any fields, happen sometimes
$commonFields = $fields;
$uniqueField = key($fields);
} else {
foreach ($fields as $field => $type) {
if (!isset($commonFields[$field])) {
if (empty($uniqueField)) {
$uniqueField = $field;
}
//New non unique field (must be excluded from analysis)
$commonFields[$field] = true;
}
}
}
if (empty($uniqueField)) {
throw new DefinitionException(
"Child document {$document} of {$this} does not have any unique field."
);
}
$definition['options'][$uniqueField] = $document->getName();
}
return $definition;
}
/**
* Get declared document schema (merged with parent entity(s) values).
*
* @return array
*/
protected function getSchema()
{
//Reading schema as property to inherit all values
return $this->property('schema', true);
}
/**
* {@inheritdoc}
*/
protected function parentSchema()
{
if (!$this->builder->hasDocument($this->getParentClass()->getName())) {
return null;
}
return $this->builder->document($this->getParentClass()->getName());
}
/**
* Check if both documents belongs to same collection. Documents without declared collection
* must be counted as documents from same collection.
*
* @param DocumentSchema $document
* @return bool
*/
protected function compareCollection(DocumentSchema $document)
{
return $document->getCollection() == $this->getCollection()
&& $document->getDatabase() == $this->getDatabase();
}
/**
* Check if type definition describes aggregation.
*
* @param mixed $type
* @return bool
*/
private function isAggregation($type)
{
return is_array($type) && (
array_key_exists(DocumentEntity::MANY, $type)
|| array_key_exists(DocumentEntity::ONE, $type)
);
}
/**
* Sort child documents in order or declared fields.
*
* @param DocumentSchema $childA
* @param DocumentSchema $childB
* @return int
*/
private function sortChildren(DocumentSchema $childA, DocumentSchema $childB)
{
return count($childA->getFields()) > count($childB->getFields());
}
/**
* Cast default value using accessor.
*
* @param string $accessor
* @param mixed $type
* @param mixed $default
* @return mixed
*/
private function accessorDefaults($accessor, $type, $default)
{
$options = is_array($type) ? $type[0] : $type;
if (is_array($accessor)) {
list($accessor, $options) = $accessor;
}
if ($accessor != ODM::CMP_ONE) {
//Not an accessor but composited class
$accessor = new $accessor($default, null, $this->builder->odm(), $options);
if ($accessor instanceof DocumentAccessorInterface) {
return $accessor->defaultValue();
}
}
return $default;
}
/**
* Get default value for composition.
*
* @param string $field
* @param mixed $default Casted default value.
* @return mixed
*/
private function compositionDefaults($field, $default)
{
$composition = $this->getCompositions()[$field];
if ($composition['type'] == ODM::CMP_MANY) {
if (!empty($default) && $default !== []) {
throw new SchemaException(
"Default value of {$this}.{$field} is not compatible with document composition."
);
}
return [];
}
if (empty($default)) {
return $this->builder->document($composition['class'])->getDefaults();
}
return $default;
}
/**
* Resolve mutator aliases and normalize accessor definitions.
*
* @param array $mutators
* @return array
*/
private function normalizeMutators(array $mutators)
{
foreach ($mutators as $mutator => &$filters) {
foreach ($filters as $field => $filter) {
$filters[$field] = $this->builder->mutatorAlias($filter);
if ($mutator == self::MUTATOR_ACCESSOR && is_string($filters[$field])) {
$type = null;
if (!empty($this->getFields()[$field])) {
$type = $this->getFields()[$field];
}
$filters[$field] = [$filters[$field], is_array($type) ? $type[0] : $type];
}
}
unset($filters);
}
return $mutators;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Loaders;
use Spiral\ORM\Entities\Loader;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\LoaderInterface;
use Spiral\ORM\ORM;
class RootLoader extends Loader
{
/**
* RootLoader always work via INLOAD.
*/
const LOAD_METHOD = self::INLOAD;
/**
* {@inheritdoc}
*
* We don't need to initiate parent constructor as root loader is pretty simple and used only
* for primary record parsing without any conditions.
*/
public function __construct(
ORM $orm,
$container,
array $definition = [],
LoaderInterface $parent = null
) {
$this->orm = $orm;
$this->schema = $definition;
//No need for aliases
$this->options['method'] = self::INLOAD;
//Primary table will be named under it's declared table name by default (without prefix)
$this->options['alias'] = $this->schema[ORM::M_ROLE_NAME];
$this->dataColumns = array_keys($this->schema[ORM::M_COLUMNS]);
//No need to call parent constructor
}
/**
* {@inheritdoc}
*/
public function configureSelector(RecordSelector $selector)
{
if (empty($this->loaders) && empty($this->joiners)) {
//No need to create any column aliases
return;
}
parent::configureSelector($selector);
}
/**
* {@inheritdoc}
*/
protected function clarifySelector(RecordSelector $selector)
{
//Nothing to do for root loader, no conditions required
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Core\Component;
use Spiral\Tokenizer\Highlighter\Style;
use Spiral\Tokenizer\Traits\TokensTrait;
/**
* Highlights php file using specified style.
*/
class Highlighter extends Component
{
use TokensTrait;
/**
* @invisible
* @var Style
*/
private $style = null;
/**
* @invisible
* @var array
*/
private $tokens = [];
/**
* Highlighted source.
*
* @var string
*/
private $highlighted = '';
/**
* @param string $source
* @param Style|null $style
*/
public function __construct($source, Style $style = null)
{
$this->style = !empty($style) ? $style : new Style();
$this->tokens = $this->normalizeTokens(token_get_all($source));
}
/**
* Set highlighter styler.
*
* @param Style $style
* @return $this
*/
public function setStyle(Style $style)
{
$this->style = $style;
return $this;
}
/**
* Get highlighted source.
*
* @return string
*/
public function highlight()
{
if (!empty($this->highlighted)) {
//Nothing to do
return $this->highlighted;
}
$this->highlighted = '';
foreach ($this->tokens as $tokenID => $token) {
$this->highlighted .= $this->style->highlightToken(
$token[TokenizerInterface::TYPE],
htmlentities($token[TokenizerInterface::CODE])
);
}
return $this->highlighted;
}
/**
* Get only part of php file around specified line.
*
* @param int|null $line Set as null to avoid line highlighting.
* @param int|null $around Set as null to return every line.
* @return string
*/
public function lines($line = null, $around = null)
{
//Chinking by lines
$lines = explode("\n", str_replace("\r\n", "\n", $this->highlight()));
$result = "";
foreach ($lines as $number => $code) {
$human = $number + 1;
if (
!empty($around)
&& ($human <= $line - $around || $human >= $line + $around)
) {
//Not included in a range
continue;
}
$result .= $this->style->line(
$human,
mb_convert_encoding($code, 'utf-8'),
$human === $line
);
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage\Entities;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerAwareInterface;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Debug\Traits\BenchmarkTrait;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\Files\FilesInterface;
use Spiral\Files\Streams\StreamableInterface;
use Spiral\Storage\BucketInterface;
use Spiral\Storage\ServerInterface;
use Spiral\Storage\StorageInterface;
use Spiral\Storage\StorageManager;
/**
* Default implementation of storage bucket.
*/
class StorageBucket extends Component implements
BucketInterface,
LoggerAwareInterface,
InjectableInterface
{
/**
* Most of storage operations are pretty slow, we might record and explain all of them.
*/
use BenchmarkTrait, LoggerTrait;
/**
* This is magick constant used by Spiral Constant, it helps system to resolve controllable
* injections, once set - Container will ask specific binding for injection.
*/
const INJECTOR = StorageManager::class;
/**
* @var string
*/
private $name = '';
/**
* @var string
*/
private $prefix = '';
/**
* @var ServerInterface
*/
private $server = null;
/**
* @var array
*/
private $options = [];
/**
* @invisible
* @var StorageInterface
*/
protected $storage = null;
/**
* @invisible
* @var FilesInterface
*/
protected $files = null;
/**
* {@inheritdoc}
*/
public function __construct(
$name,
$prefix,
array $options,
ServerInterface $server,
StorageInterface $storage,
FilesInterface $files
) {
$this->name = $name;
$this->prefix = $prefix;
$this->options = $options;
$this->server = $server;
$this->storage = $storage;
$this->files = $files;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function server()
{
return $this->server;
}
/**
* {@inheritdoc}
*/
public function getOption($name, $default = null)
{
return isset($this->options[$name]) ? $this->options[$name] : $default;
}
/**
* {@inheritdoc}
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* {@inheritdoc}
*/
public function hasAddress($address)
{
if (strpos($address, $this->prefix) === 0) {
return strlen($this->prefix);
}
return false;
}
/**
* {@inheritdoc}
*/
public function buildAddress($name)
{
return $this->prefix . $name;
}
/**
* {@inheritdoc}
*/
public function exists($name)
{
$this->logger()->info(
"Check existence of '{$this->buildAddress($name)}' at '{$this->getName()}'."
);
$benchmark = $this->benchmark($this->getName(), "exists::{$this->buildAddress($name)}");
try {
return (bool)$this->server->exists($this, $name);
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function size($name)
{
$this->logger()->info(
"Get size of '{$this->buildAddress($name)}' at '{$this->getName()}'."
);
$benchmark = $this->benchmark($this->getName(), "size::{$this->buildAddress($name)}");
try {
return $this->server->size($this, $name);
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function put($name, $source)
{
$this->logger()->info(
"Put '{$this->buildAddress($name)}' at '{$this->getName()}' server."
);
if ($source instanceof UploadedFileInterface || $source instanceof StreamableInterface) {
//Known simplification for UploadedFile
$source = $source->getStream();
}
if (is_resource($source)) {
$source = \GuzzleHttp\Psr7\stream_for($source);
}
$benchmark = $this->benchmark($this->getName(), "put::{$this->buildAddress($name)}");
try {
$this->server->put($this, $name, $source);
//Reopening
return $this->storage->open($this->buildAddress($name));
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function allocateFilename($name)
{
$this->logger()->info(
"Allocate filename of '{$this->buildAddress($name)}' at '{$this->getName()}' server."
);
$benchmark = $this->benchmark(
$this->getName(), "filename::{$this->buildAddress($name)}"
);
try {
return $this->server()->allocateFilename($this, $name);
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function allocateStream($name)
{
$this->logger()->info(
"Get stream for '{$this->buildAddress($name)}' at '{$this->server}' server."
);
$benchmark = $this->benchmark(
$this->getName(), "stream::{$this->buildAddress($name)}"
);
try {
return $this->server()->allocateStream($this, $name);
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function delete($name)
{
$this->logger()->info(
"Delete '{$this->buildAddress($name)}' at '{$this->server}' server."
);
$benchmark = $this->benchmark(
$this->getName(), "delete::{$this->buildAddress($name)}"
);
try {
$this->server->delete($this, $name);
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function rename($oldname, $newname)
{
if ($oldname == $newname) {
return true;
}
$this->logger()->info(
"Rename '{$this->buildAddress($oldname)}' to '{$this->buildAddress($newname)}' "
. "at '{$this->server}' server."
);
$benchmark = $this->benchmark(
$this->getName(), "rename::{$this->buildAddress($oldname)}"
);
try {
$this->server->rename($this, $oldname, $newname);
return $this->buildAddress($newname);
} finally {
$this->benchmark($benchmark);
}
}
/**
* {@inheritdoc}
*/
public function copy(BucketInterface $destination, $name)
{
if ($destination == $this) {
return $this->buildAddress($name);
}
//Internal copying
if ($this->server() === $destination->server()) {
$this->logger()->info(
"Internal copy of '{$this->buildAddress($name)}' "
. "to '{$destination->buildAddress($name)}' at '{$this->server}' server."
);
$benchmark = $this->benchmark(
$this->getName(), "copy::{$this->buildAddress($name)}"
);
try {
$this->server()->copy($this, $destination, $name);
} finally {
$this->benchmark($benchmark);
}
} else {
$this->logger()->info(
"External copy of '{$this->getName()}'.'{$this->buildAddress($name)}' "
. "to '{$destination->getName()}'.'{$destination->buildAddress($name)}'."
);
$destination->put($name, $this->allocateStream($name));
}
return $destination->buildAddress($name);
}
/**
* {@inheritdoc}
*/
public function replace(BucketInterface $destination, $name)
{
if ($destination == $this) {
return $this->buildAddress($name);
}
//Internal copying
if ($this->getName() == $destination->getName()) {
$this->logger()->info(
"Internal move '{$this->buildAddress($name)}' "
. "to '{$destination->buildAddress($name)}' at '{$this->getName()}' server."
);
$benchmark = $this->benchmark(
$this->getName(), "replace::{$this->buildAddress($name)}"
);
try {
$this->server()->replace($this, $destination, $name);
} finally {
$this->benchmark($benchmark);
}
} else {
$this->logger()->info(
"External move '{$this->getName()}'.'{$this->buildAddress($name)}'"
. " to '{$destination->getName()}'.'{$destination->buildAddress($name)}'."
);
//Copying using temporary stream (buffer)
$destination->put($name, $stream = $this->allocateStream($name));
if ($stream->detach()) {
//Dropping temporary stream
$this->delete($name);
}
}
return $destination->buildAddress($name);
}
}<file_sep>Purely based on Symfony Events. Only helper trait left. :/
Potentially to be reworked to use one global dispatcher and even prefixes (namespaces), bad design desigion has been made but no BC expected.
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Exceptions;
use Spiral\Models\Exceptions\EntityException;
/**
* Record related exception.
*/
class RecordException extends EntityException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Spiral\ORM\Exceptions\IteratorException;
use Spiral\ORM\Exceptions\ORMException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\RecordInterface;
/**
* Provides iteration over set of specified records data using internal instances cache. In
* addition, allows to decorate set of callbacks with association by their name (@see __call()).
* Keeps record context.
*/
class RecordIterator implements \Iterator, \Countable, \JsonSerializable
{
/**
* Current iterator position.
*
* @var int
*/
private $position = 0;
/**
* Set of "methods" to be decorated.
*
* @var callable[]
*/
private $callbacks = [];
/**
* @var string
*/
protected $class = '';
/**
* Indication that entity cache must be used.
*
* @var bool
*/
protected $cache = true;
/**
* Data to be iterated.
*
* @var array
*/
protected $data = [];
/**
* Constructed record instances. Cache.
*
* @var RecordEntity[]
*/
protected $instances = [];
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* @param ORM $orm
* @param string $class
* @param array $data
* @param bool $cache
* @param callable[] $callbacks
*/
public function __construct(ORM $orm, $class, array $data, $cache = true, array $callbacks = [])
{
$this->class = $class;
$this->cache = $cache;
$this->orm = $orm;
$this->data = $data;
//Magic functionality provided by outer parent
$this->callbacks = $callbacks;
}
/**
* {@inheritdoc}
*/
public function count()
{
return count($this->data);
}
/**
* Get all Records as array.
*
* @return RecordInterface[]
*/
public function all()
{
$result = [];
/**
* @var self|RecordInterface[] $iterator
*/
$iterator = clone $this;
foreach ($iterator as $nested) {
$result[] = $nested;
}
//Copying instances just in case
$this->instances = $iterator->instances;
return $result;
}
/**
* {@inheritdoc}
*
* @return RecordInterface
* @see ORM::record()
* @see Record::setContext()
* @throws ORMException
*/
public function current()
{
if (isset($this->instances[$this->position])) {
//Due record was pre-constructed we must update it's context to force values for relations
//and pivot fields
return $this->instances[$this->position];
}
//Let's ask ORM to create needed record
return $this->instances[$this->position] = $this->orm->record(
$this->class,
$this->data[$this->position],
$this->cache
);
}
/**
* {@inheritdoc}
*/
public function next()
{
$this->position++;
}
/**
* {@inheritdoc}
*/
public function key()
{
return $this->position;
}
/**
* {@inheritdoc}
*/
public function valid()
{
return isset($this->data[$this->position]);
}
/**
* {@inheritdoc}
*/
public function rewind()
{
$this->position = 0;
}
/**
* Check if record or record with specified id presents in iteration.
*
* @param RecordEntity|string|int $record
* @return true
*/
public function has($record)
{
/**
* @var self|RecordEntity[] $iterator
*/
$iterator = clone $this;
foreach ($iterator as $nested) {
$found = false;
if (is_array($record)) {
if (array_intersect_assoc($nested->getFields(), $record) == $record) {
//Comparing fields intersection
$found = true;
}
} elseif (!$record instanceof RecordEntity) {
if (!empty($record) && $nested->primaryKey() == $record) {
//Comparing using primary keys
$found = true;
}
} elseif ($nested == $record || $nested->getFields() == $record->getFields()) {
//Comparing as class
$found = true;
}
if ($found) {
//They all must be iterated already
$this->instances = $iterator->instances;
return true;
}
}
//They all must be iterated already
$this->instances = $iterator->instances;
return false;
}
/**
* Executes decorated method providing itself as function argument.
*
* @param string $method
* @param array $arguments
* @return mixed
* @throws IteratorException
*/
public function __call($method, array $arguments)
{
if (!isset($this->callbacks[$method])) {
throw new IteratorException("Undefined method or callback.");
}
return call_user_func($this->callbacks[$method], $this);
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->all();
}
/**
* @return RecordEntity[]
*/
public function __debugInfo()
{
return $this->all();
}
/**
* Flushing references.
*/
public function __destruct()
{
$this->data = [];
$this->instances = [];
$this->orm = null;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer\Exceptions;
use Spiral\Core\Exceptions\RuntimeException;
/**
* Generic tokenizer exception.
*/
class TokenizerException extends RuntimeException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Entities\Schemas;
/**
* Describes one ODM collection with it's primary class, indexes and etc.
*/
class CollectionSchema
{
/**
* Primary collection document.
*
* @var DocumentSchema
*/
protected $parent = null;
/**
* @param DocumentSchema $parent
*/
public function __construct(DocumentSchema $parent)
{
$this->parent = $parent;
}
/**
* Parent collection document.
*
* @return DocumentSchema
*/
public function getParent()
{
return $this->parent;
}
/**
* Every document can be fetched from collection.
*
* @return DocumentSchema[]
*/
public function getDocuments()
{
return array_merge([$this->parent], $this->parent->getChildren(true));
}
/**
* @return string
*/
public function getName()
{
return $this->parent->getCollection();
}
/**
* @return string
*/
public function getDatabase()
{
return $this->parent->getDatabase();
}
/**
* Requested collection indexes. May not be identical to existed collection indexes.
*
* @return array
*/
public function getIndexes()
{
return $this->parent->getIndexes();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Query;
use PDO;
use Spiral\Cache\StoreInterface;
use Spiral\Database\Entities\QueryInterpolator;
use Spiral\Database\Exceptions\ResultException;
/**
* CacheResult is almost identical to QueryResult by it's functionality, but used to represent query
* result stored in cache storage.
*/
class CachedResult extends QueryResult
{
/**
* @var StoreInterface
*/
protected $store = null;
/**
* @var string
*/
protected $key = '';
/**
* Query string (not interpolated).
*
* @var string
*/
protected $queryString = '';
/**
* Cache data.
*
* @var array
*/
protected $data = [];
/**
* FetchMode to be emulated.
*
* @var int
*/
protected $fetchMode = PDO::FETCH_ASSOC;
/**
* Column bindings has to be validated also.
*
* @var array
*/
protected $bindings = [];
/**
* @param StoreInterface $store
* @param string $cacheID
* @param string $queryString
* @param array $parameters
* @param array $data
*/
public function __construct(
StoreInterface $store,
$cacheID,
$queryString,
array $parameters = [],
array $data = []
) {
$this->store = $store;
$this->key = $cacheID;
$this->queryString = $queryString;
$this->parameters = $parameters;
$this->data = $data;
$this->count = count($data);
$this->cursor = 0;
//No need to call parent constructor
}
/**
* {@inheritdoc}
*/
public function queryString()
{
return QueryInterpolator::interpolate($this->queryString, $this->parameters);
}
/**
* {@inheritdoc}
*/
public function countColumns()
{
return $this->data ? count($this->data[0]) : 0;
}
/**
* {@inheritdoc}
*
* @throws ResultException
*/
public function fetchMode($mode)
{
if ($mode != PDO::FETCH_ASSOC && $mode != PDO::FETCH_NUM) {
throw new ResultException(
'Cached query supports only FETCH_ASSOC and FETCH_NUM fetching modes.'
);
}
$this->fetchMode = $mode;
return $this;
}
/**
* {@inheritdoc}
*/
public function fetch($mode = null)
{
if (!empty($mode)) {
$this->fetchMode($mode);
}
if (!isset($this->data[$this->cursor])) {
return false;
}
if ($data = $this->data[$this->cursor++]) {
foreach ($this->bindings as $columnID => &$variable) {
$variable = $data[$columnID];
}
}
if ($this->fetchMode == PDO::FETCH_NUM) {
return $data ? array_values($data) : false;
}
return $data;
}
/**
* {@inheritdoc}
*/
public function fetchColumn($columnID = 0)
{
return $this->fetch(PDO::FETCH_NUM)[$columnID];
}
/**
* {@inheritdoc}
*
* @throws ResultException
*/
public function bind($columnID, &$variable)
{
if (empty($this->data)) {
return $this;
}
if (is_numeric($columnID)) {
//Getting column number
foreach (array_keys($this->data[0]) as $index => $name) {
if ($index == $columnID - 1) {
$this->bindings[$name] = &$variable;
return $this;
}
}
throw new ResultException("No such index '{$columnID}' in the result columns.");
} else {
if (!isset($this->data[0][$columnID])) {
throw new ResultException(
"No such column name '{$columnID}' in the result columns."
);
}
$this->bindings[$columnID] = &$variable;
}
return $this;
}
/**
* {@inheritdoc}
*/
public function fetchAll($mode = null)
{
$mode && $this->fetchMode($mode);
//So we can properly emulate bindings and etc.
$result = [];
foreach ($this as $row) {
$result[] = $row;
}
return $result;
}
/**
* {@inheritdoc}
*/
public function next()
{
$this->rowData = $this->fetch();
return $this->rowData;
}
/**
* {@inheritdoc}
*/
public function rewind()
{
$this->cursor = 0;
$this->rowData = $this->fetch();
}
/**
* {@inheritdoc}
*/
public function close()
{
return true;
}
/**
* Flush results stored in CacheStore and CachedResult.
*/
public function flush()
{
$this->data = [];
$this->count = 0;
$this->store->delete($this->key);
$this->key = null;
}
/**
* @return object
*/
public function __debugInfo()
{
return (object)[
'store' => get_class($this->store),
'cacheKey' => $this->key,
'statement' => $this->queryString(),
'count' => $this->count,
'rows' => $this->count > static::DUMP_LIMIT
? '[TOO MANY RECORDS TO DISPLAY]'
: $this->fetchAll(\PDO::FETCH_ASSOC)
];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Relations;
use Spiral\Models\EntityInterface;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* Represents simple BELONGS_TO relation with ability to associate and de-associate parent.
*/
class BelongsTo extends HasOne
{
/**
* Relation type, required to fetch record class from relation definition.
*/
const RELATION_TYPE = RecordEntity::BELONGS_TO;
/**
* {@inheritdoc}
*/
public function isLoaded()
{
$this->fromCache();
if (empty($this->parent->getField($this->definition[RecordEntity::INNER_KEY], false))) {
return true;
}
return $this->loaded;
}
/**
* {@inheritdoc}
*/
public function getRelated()
{
$this->fromCache();
return parent::getRelated();
}
/**
* {@inheritdoc}
*
* Parent record MUST be saved in order to preserve parent association.
*/
public function associate(EntityInterface $related = null)
{
if ($related === null) {
$this->deassociate();
return;
}
/**
* @var RecordEntity $related
*/
if (!$related->isLoaded()) {
throw new RelationException(
"Unable to set 'belongs to' parent, parent has be fetched from database."
);
}
parent::associate($related);
//Key in parent record
$outerKey = $this->definition[RecordEntity::OUTER_KEY];
//Key in child record
$innerKey = $this->definition[RecordEntity::INNER_KEY];
if ($this->parent->getField($innerKey, false) != $related->getField($outerKey, false)) {
//We are going to set relation keys right on assertion
$this->parent->setField($innerKey, $related->getField($outerKey, false));
}
}
/**
* {@inheritdoc}
*/
protected function mountRelation(EntityInterface $record)
{
//Nothing to do, children can not update parent relation
return $record;
}
/**
* {@inheritdoc}
*
* @throws RelationException
*/
protected function createSelector()
{
if (empty($this->parent->getField($this->definition[RecordEntity::INNER_KEY], false))) {
throw new RelationException(
"Belongs-to selector can not be constructed when inner key ("
. $this->definition[RecordEntity::INNER_KEY]
. ") is null."
);
}
return parent::createSelector();
}
/**
* {@inheritdoc}
*
* Belongs-to can not automatically create parent.
*/
protected function emptyRecord()
{
return null;
}
/**
* De associate related record.
*/
protected function deassociate()
{
if (!$this->definition[RecordEntity::NULLABLE]) {
throw new RelationException(
"Unable to de-associate relation data, relation is not nullable."
);
}
$innerKey = $this->definition[RecordEntity::INNER_KEY];
$this->parent->setField($innerKey, null);
$this->loaded = true;
$this->instance = null;
$this->data = [];
}
/**
* Try to fetch outer model using entity cache.
*/
private function fromCache()
{
if ($this->loaded) {
return;
}
$innerKey = $this->parent->getField($this->definition[RecordEntity::INNER_KEY], false);
if (empty($innerKey)) {
return;
}
if (empty($this->definition[ORM::M_PRIMARY_KEY])) {
//Linked not by primary key
return;
}
if (empty($entity = $this->orm->cache()->get($this->getClass(), $innerKey))) {
return;
}
$this->loaded = true;
$this->instance = $entity;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Injections;
/**
* Declares ability to be converted into sql statement.
*/
interface FragmentInterface
{
/**
* @return string
*/
public function sqlStatement();
/**
* @return string
*/
public function __toString();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Files;
use Spiral\Files\Exceptions\FileNotFoundException;
use Spiral\Files\Exceptions\WriteErrorException;
/**
* Access to hard drive or local store. Does not provide full filesystem abstractions.
*
* @todo more methods needed? access to finder?
*/
interface FilesInterface
{
/**
* Permission mode: fully writable and readable files.
*/
const RUNTIME = 0777;
/**
* Permission mode: only locked to parent (one environment).
*/
const READONLY = 0666;
/**
* Few size constants for better size manipulations.
*/
const KB = 1024;
const MB = 1048576;
const GB = 1073741824;
/**
* Default location (directory) separator.
*/
const SEPARATOR = '/';
/**
* Ensure location (directory) existence with specified mode.
*
* @param string $directory
* @param int $mode
* @return bool
*/
public function ensureDirectory($directory, $mode = self::RUNTIME);
/**
* Read file content into string.
*
* @param string $filename
* @return string
* @throws FileNotFoundException
*/
public function read($filename);
/**
* Write file data with specified mode. Ensure location option should be used only if desired
* location may not exist to ensure such location/directory (slow operation).
*
* @param string $filename
* @param string $data
* @param int $mode One of mode constants.
* @param bool $ensureDirectory Ensure final destination!
* @return bool
* @throws WriteErrorException
*/
public function write($filename, $data, $mode = null, $ensureDirectory = false);
/**
* Same as write method with will append data at the end of existed file without replacing it.
*
* @see write()
* @param string $filename
* @param string $data
* @param int $mode
* @param bool $ensureDirectory
* @return bool
* @throws WriteErrorException
*/
public function append($filename, $data, $mode = null, $ensureDirectory = false);
/**
* Method has to return local uri which can be used in require and include statements.
* Implementation is allowed to use virtual stream uris if it's not local.
*
* @param string $filename
* @return string
*/
public function localUri($filename);
/**
* Delete local file if possible. No error should be raised if file does not exists.
*
* @param string $filename
*/
public function delete($filename);
/**
* Delete directory all content in it.
*
* @param string $directory
* @param bool $contentOnly
*/
public function deleteDirectory($directory, $contentOnly = false);
/**
* Move file from one location to another. Location must exist.
*
* @param string $filename
* @param string $destination
* @return bool
* @throws FileNotFoundException
*/
public function move($filename, $destination);
/**
* Copy file at new location. Location must exist.
*
* @param string $filename
* @param string $destination
* @return bool
* @throws FileNotFoundException
*/
public function copy($filename, $destination);
/**
* Touch file to update it's timeUpdated value or create new file. Location must exist.
*
* @param string $filename
* @param int $mode
*/
public function touch($filename, $mode = null);
/**
* Check if file exists.
*
* @param string $filename
* @return bool
*/
public function exists($filename);
/**
* Get filesize in bytes if file does exists.
*
* @param string $filename
* @return int
* @throws FileNotFoundException
*/
public function size($filename);
/**
* Get file extension using it's name. Simple but pretty common method.
*
* @param string $filename
* @return string
*/
public function extension($filename);
/**
* Get file MD5 hash.
*
* @param string $filename
* @return string
* @throws FileNotFoundException
*/
public function md5($filename);
/**
* Timestamp when file being updated/created.
*
* @param string $filename
* @return int
* @throws FileNotFoundException
*/
public function time($filename);
/**
* @param string $filename
* @return bool
*/
public function isDirectory($filename);
/**
* @param string $filename
* @return bool
*/
public function isFile($filename);
/**
* Current file permissions (if exists).
*
* @param string $filename
* @return int|bool
* @throws FileNotFoundException
*/
public function getPermissions($filename);
/**
* Update file permissions.
*
* @param string $filename
* @param int $mode
* @throws FileNotFoundException
*/
public function setPermissions($filename, $mode);
/**
* Flat list of every file in every sub location. Locations must be normalized.
*
* Note: not a generator yet, waiting for PHP7.
*
* @param string $location Location for search.
* @param string $pattern Extension pattern.
* @return array
*/
public function getFiles($location, $pattern = null);
/**
* Return unique name of temporary (should be removed when interface implementation destructed)
* file in desired location.
*
* @param string $extension Desired file extension.
* @param string $location
* @return string
*/
public function tempFilename($extension = '', $location = null);
/**
* Create the most normalized version for path to file or location.
*
* @param string $path File or location path.
* @param bool $directory Path points to directory.
* @return string
*/
public function normalizePath($path, $directory = false);
/**
* Get relative location based on absolute path.
*
* @param string $path Original file or directory location (to).
* @param string $from Path will be converted to be relative to this directory (from).
* @return string
*/
public function relativePath($path, $from);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Importers;
use Spiral\Stempler\ImporterInterface;
/**
* Namespace importer provides ability to include multiple elements using common namespace prefix.
*
* Example: namespace:folder/* => namespace:folder/name
*/
class Prefixer implements ImporterInterface
{
/**
* @var string
*/
private $prefix = '';
/**
* @var string
*/
private $target = '';
/**
* @param string $prefix
* @param string $target
*/
public function __construct($prefix, $target)
{
$this->prefix = $prefix;
$this->target = $target;
}
/**
* {@inheritdoc}
*/
public function importable($element, array $token)
{
$element = strtolower($element);
return strpos($element, $this->prefix) === 0;
}
/**
* {@inheritdoc}
*/
public function resolvePath($element, array $token)
{
$element = substr($element, strlen($this->prefix));
return str_replace('*', str_replace('.', '/', $element), $this->target);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Importers;
use Spiral\Stempler\ImporterInterface;
use Spiral\Stempler\Supervisor;
/**
* Share all template importers with given supervisor.
*/
class Bundler implements ImporterInterface
{
/**
* Importers fetched from bundle file.
*
* @var ImporterInterface[]
*/
protected $importers = [];
/**
* @param Supervisor $supervisor
* @param string $path
* @param array $token
*/
public function __construct(Supervisor $supervisor, $path, array $token = [])
{
$node = $supervisor->createNode($path, $token);
$supervisor = $node->supervisor();
if ($supervisor instanceof Supervisor) {
$this->importers = $supervisor->getImporters();
}
}
/**
* {@inheritdoc}
*/
public function importable($element, array $token)
{
foreach ($this->importers as $importer) {
if ($importer->importable($element, $token)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function resolvePath($element, array $token)
{
foreach ($this->importers as $importer) {
if ($importer->importable($element, $token)) {
return $importer->resolvePath($element, $token);
}
}
return null;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL\Schemas;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Entities\Schemas\AbstractCommander;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Exceptions\SchemaException;
/**
* MySQL table schema.
*/
class TableSchema extends AbstractTable
{
/**
* List of most common MySQL table engines.
*/
const ENGINE_INNODB = 'InnoDB';
const ENGINE_MYISAM = 'MyISAM';
const ENGINE_MEMORY = 'Memory';
/**
* MySQL table engine.
*
* @var string
*/
private $engine = self::ENGINE_INNODB;
/**
* @param Driver $driver Parent driver.
* @param AbstractCommander $commander
* @param string $name Table name, must include table prefix.
* @param string $prefix Database specific table prefix.
*/
public function __construct(Driver $driver, AbstractCommander $commander, $name, $prefix)
{
parent::__construct($driver, $commander, $name, $prefix);
//Let's load table type, just for fun
if ($this->exists()) {
$query = $driver->query('SHOW TABLE STATUS WHERE Name = ?', [$name]);
$this->engine = $query->fetch()['Engine'];
}
}
/**
* Change table engine. Such operation will be applied only at moment of table creation.
*
* @param string $engine
* @return $this
*/
public function setEngine($engine)
{
if ($this->exists()) {
throw new SchemaException("Table engine can be set only at moment of creation.");
}
$this->engine = $engine;
return $this;
}
/**
* @return string
*/
public function getEngine()
{
return $this->engine;
}
/**
* {@inheritdoc}
*/
protected function loadColumns()
{
$query = "SHOW FULL COLUMNS FROM {$this->getName(true)}";
foreach ($this->driver->query($query)->bind(0, $name) as $column) {
$this->registerColumn($this->columnSchema($name, $column));
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadIndexes()
{
$query = "SHOW INDEXES FROM {$this->getName(true)}";
$indexes = [];
$primaryKeys = [];
foreach ($this->driver->query($query) as $index) {
if ($index['Key_name'] == 'PRIMARY') {
$primaryKeys[] = $index['Column_name'];
continue;
}
$indexes[$index['Key_name']][] = $index;
}
$this->setPrimaryKeys($primaryKeys);
foreach ($indexes as $name => $schema) {
$this->registerIndex($this->indexSchema($name, $schema));
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadReferences()
{
$query = "SELECT * FROM information_schema.referential_constraints "
. "WHERE constraint_schema = ? AND table_name = ?";
$references = $this->driver->query($query, [$this->driver->getSource(), $this->getName()]);
foreach ($references->all() as $reference) {
$query = "SELECT * FROM information_schema.key_column_usage "
. "WHERE constraint_name = ? AND table_schema = ? AND table_name = ?";
$column = $this->driver->query(
$query,
[$reference['CONSTRAINT_NAME'], $this->driver->getSource(), $this->getName()]
)->fetch();
$this->registerReference(
$this->referenceSchema($reference['CONSTRAINT_NAME'], $reference + $column)
);
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function columnSchema($name, $schema = null)
{
return new ColumnSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function indexSchema($name, $schema = null)
{
return new IndexSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function referenceSchema($name, $schema = null)
{
return new ReferenceSchema($this, $name, $schema);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
use Spiral\Models\Exceptions\EntityException;
/**
* Exceptions raised by document.
*/
class DocumentException extends EntityException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use PDO;
use Psr\Log\LoggerAwareInterface;
use Spiral\Core\Component;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Core\FactoryInterface;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Database\DatabaseManager;
use Spiral\Database\Exceptions\ConstrainException;
use Spiral\Database\Exceptions\DriverException;
use Spiral\Database\Exceptions\QueryException;
use Spiral\Database\Injections\Parameter;
use Spiral\Database\Injections\ParameterInterface;
use Spiral\Database\Query\QueryResult;
use Spiral\Debug\Traits\BenchmarkTrait;
use Spiral\Debug\Traits\LoggerTrait;
/**
* Basic implementation of DBAL Driver, can talk to PDO, send queries and etc.
*/
abstract class PDODriver extends Component implements LoggerAwareInterface
{
/**
* There is few points can raise warning message or take long time to execute, we better profile
* them.
*/
use LoggerTrait, BenchmarkTrait, SaturateTrait;
/**
* One of DatabaseInterface types.
*/
const TYPE = '';
/**
* Driver schemas.
*/
const SCHEMA_TABLE = '';
const SCHEMA_COLUMN = '';
const SCHEMA_INDEX = '';
const SCHEMA_REFERENCE = '';
/**
* Query result class.
*/
const QUERY_RESULT = QueryResult::class;
/**
* Query compiler class.
*/
const QUERY_COMPILER = QueryCompiler::class;
/**
* DateTime format to be used to perform automatic conversion of DateTime objects.
*
* @var string
*/
const DATETIME = 'Y-m-d H:i:s';
/**
* @var PDO|null
*/
private $pdo = null;
/**
* Transaction level (count of nested transactions). Not all drives can support nested
* transactions.
*
* @var int
*/
private $transactionLevel = 0;
/**
* Driver name.
*
* @var string
*/
private $name = '';
/**
* Connection configuration described in DBAL config file. Any driver can be used as data source
* for multiple databases as table prefix and quotation defined on Database instance level.
*
* @var array
*/
protected $config = [
'profiling' => false,
'connection' => '',
'username' => '',
'password' => '',
'options' => []
];
/**
* PDO connection options set.
*
* @var array
*/
protected $options = [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_STRINGIFY_FETCHES => true
];
/**
* Container is needed to construct instances of QueryCompiler.
*
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param string $name
* @param array $config
* @param FactoryInterface $factory Factory is needed to construct instances of QueryCompiler.
* Sugared using static container.
* @throws SugarException
*/
public function __construct($name, array $config, FactoryInterface $factory = null)
{
$this->name = $name;
$this->config = $config + $this->config;
//PDO connection options has to be stored under key "options" of config
$this->options = $config['options'] + $this->options;
$this->factory = $this->saturate($factory, FactoryInterface::class);
}
/**
* Source name, can include database name or database file.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get driver source database or file name.
*
* @return string
* @throws DriverException
*/
public function getSource()
{
if (preg_match('/(?:dbname|database)=([^;]+)/i', $this->config['connection'], $matches)) {
return $matches[1];
}
throw new DriverException("Unable to locate source name.");
}
/**
* Database type driver linked to.
*
* @return string
*/
public function getType()
{
return static::TYPE;
}
/**
* Enabled profiling will raise set of log messages and benchmarks associated with PDO queries.
*
* @param bool $enabled Enable or disable driver profiling.
* @return $this
*/
public function setProfiling($enabled = true)
{
$this->config['profiling'] = $enabled;
return $this;
}
/**
* Check if profiling mode is enabled.
*
* @return bool
*/
public function isProfiling()
{
return $this->config['profiling'];
}
/**
* Force driver to connect.
*
* @return PDO
*/
public function connect()
{
$benchmark = $this->benchmark('connect', $this->config['connection']);
try {
$this->pdo = $this->createPDO();
} finally {
$this->benchmark($benchmark);
}
return $this->pdo;
}
/**
* Disconnect driver.
*
* @return $this
*/
public function disconnect()
{
$this->pdo = null;
return $this;
}
/**
* Check if driver already connected.
*
* @return bool
*/
public function isConnected()
{
return (bool)$this->pdo;
}
/**
* Change PDO instance associated with driver.
*
* @param PDO $pdo
* @return $this
*/
public function setPDO(PDO $pdo)
{
$this->pdo = $pdo;
return $this;
}
/**
* Get associated PDO connection. Will automatically connect if such connection does not exists.
*
* @return PDO
*/
public function getPDO()
{
if (!$this->isConnected()) {
$this->connect();
}
return $this->pdo;
}
/**
* Driver specific database/table identifier quotation.
*
* @param string $identifier
* @return string
*/
public function identifier($identifier)
{
return $identifier == '*' ? '*' : '"' . str_replace('"', '""', $identifier) . '"';
}
/**
* Execute sql statement and wrap resulted rows using driver specific or default instance of
* QueryResult.
*
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @return QueryResult
* @throws QueryException
*/
public function query($query, array $parameters = [])
{
return $this->factory->make(static::QUERY_RESULT, [
'statement' => $this->statement($query, $parameters),
'parameters' => $parameters
]);
}
/**
* Create instance of PDOStatement using provided SQL query and set of parameters.
*
* @todo more exceptions to be thrown
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @return \PDOStatement
* @throws QueryException
*/
public function statement($query, array $parameters = [])
{
try {
if ($this->isProfiling()) {
$queryString = QueryInterpolator::interpolate($query, $parameters);
$benchmark = $this->benchmark($this->name, $queryString);
}
/**
* This code requires minor improvements to support prepared statements on user level.
*/
//Prepared statement
$pdoStatement = $this->prepare($query);
foreach ($this->flattenParameters($parameters) as $index => $parameter) {
//Let's mount statement parameters
$pdoStatement->bindValue($index + 1, $parameter->getValue(), $parameter->getType());
}
try {
$pdoStatement->execute();
} finally {
if (!empty($benchmark)) {
$this->benchmark($benchmark);
}
}
//Only exists if profiling on
if (!empty($queryString)) {
$this->logger()->info($queryString, compact('query', 'parameters'));
}
} catch (\PDOException $exception) {
if (empty($queryString)) {
$queryString = QueryInterpolator::interpolate($query, $parameters);
}
$this->logger()->error($queryString, compact('query', 'parameters'));
//Converting exception into query or integrity exception
throw $this->clarifyException($exception);
}
return $pdoStatement;
}
/**
* Get prepared PDO statement.
*
* @param string $statement
* @return \PDOStatement
*/
public function prepare($statement)
{
//todo: what about caching prepared statements?
return $this->getPDO()->prepare($statement);
}
/**
* Get id of last inserted row, this method must be called after insert query. Attention,
* such functionality may not work in some DBMS property (Postgres).
*
* @param string|null $sequence Name of the sequence object from which the ID should be
* returned.
* @return mixed
*/
public function lastInsertID($sequence = null)
{
return $sequence
? (int)$this->getPDO()->lastInsertId($sequence)
: (int)$this->getPDO()->lastInsertId();
}
/**
* Prepare set of query builder/user parameters to be send to PDO. Must convert DateTime
* instances into valid database timestamps and resolve values of ParameterInterface.
*
* Every value has to wrapped with parameter interface.
*
* @param array $parameters
* @return ParameterInterface[]
*/
public function flattenParameters(array $parameters)
{
$flatten = [];
foreach ($parameters as $parameter) {
if (!$parameter instanceof ParameterInterface) {
//Let's wrap value
$parameter = new Parameter($parameter, Parameter::DETECT_TYPE);
}
//Converting into flat array
$flattenParameter = $parameter->flatten();
/**
* @var ParameterInterface $value
*/
foreach ($flattenParameter as $value) {
if ($value->getValue() instanceof \DateTime) {
//Converting datetime object into string representation
$value->setValue($this->prepareDateTime($value->getValue()));
}
}
//We have to flatten all parameters as some of them can be provided in array form
$flatten = array_merge($flatten, $flattenParameter);
}
return $flatten;
}
/**
* Start SQL transaction with specified isolation level (not all DBMS support it). Nested
* transactions are processed using savepoints.
*
* @link http://en.wikipedia.org/wiki/Database_transaction
* @link http://en.wikipedia.org/wiki/Isolation_(database_systems)
* @param string $isolationLevel
* @return bool
*/
public function beginTransaction($isolationLevel = null)
{
$this->transactionLevel++;
if ($this->transactionLevel == 1) {
if (!empty($isolationLevel)) {
$this->isolationLevel($isolationLevel);
}
$this->logger()->info('Begin transaction');
return $this->getPDO()->beginTransaction();
}
$this->savepointCreate($this->transactionLevel);
return true;
}
/**
* Commit the active database transaction.
*
* @return bool
*/
public function commitTransaction()
{
$this->transactionLevel--;
if ($this->transactionLevel == 0) {
$this->logger()->info('Commit transaction');
return $this->getPDO()->commit();
}
$this->savepointRelease($this->transactionLevel + 1);
return true;
}
/**
* Rollback the active database transaction.
*
* @return bool
*/
public function rollbackTransaction()
{
$this->transactionLevel--;
if ($this->transactionLevel == 0) {
$this->logger()->info('Rollback transaction');
return $this->getPDO()->rollBack();
}
$this->savepointRollback($this->transactionLevel + 1);
return true;
}
/**
* Clean (truncate) specified driver table.
*
* @param string $table Table name with prefix included.
*/
public function truncate($table)
{
$this->statement("TRUNCATE TABLE {$this->identifier($table)}");
}
/**
* Get instance of Driver specific QueryCompiler.
*
* @param string $prefix Database specific table prefix, used to quote table names and build
* aliases.
* @return QueryCompiler
*/
public function queryCompiler($prefix = '')
{
return $this->factory->make(static::QUERY_COMPILER, [
'driver' => $this,
'quoter' => new Quoter($this, $prefix)
]);
}
/**
* @return object
*/
public function __debugInfo()
{
return (object)[
'connection' => $this->config['connection'],
'connected' => $this->isConnected(),
'profiling' => $this->isProfiling(),
'database' => $this->getSource(),
'options' => $this->options
];
}
/**
* Create instance of configured PDO class.
*
* @return PDO
*/
protected function createPDO()
{
return new PDO(
$this->config['connection'],
$this->config['username'],
$this->config['password'],
$this->options
);
}
/**
* Convert PDO exception into query or integrity exception.
*
* @param \PDOException $exception
* @return QueryException|ConstrainException
*/
protected function clarifyException(\PDOException $exception)
{
return new QueryException($exception);
}
/**
* Set transaction isolation level, this feature may not be supported by specific database
* driver.
*
* @param string $level
*/
protected function isolationLevel($level)
{
$this->logger()->info("Set transaction isolation level to '{$level}'.");
if (!empty($level)) {
$this->statement("SET TRANSACTION ISOLATION LEVEL {$level}");
}
}
/**
* Create nested transaction save point.
*
* @link http://en.wikipedia.org/wiki/Savepoint
* @param string $name Savepoint name/id, must not contain spaces and be valid database
* identifier.
*/
protected function savepointCreate($name)
{
$this->logger()->info("Creating savepoint '{$name}'.");
$this->statement("SAVEPOINT " . $this->identifier("SVP{$name}"));
}
/**
* Commit/release savepoint.
*
* @link http://en.wikipedia.org/wiki/Savepoint
* @param string $name Savepoint name/id, must not contain spaces and be valid database
* identifier.
*/
protected function savepointRelease($name)
{
$this->logger()->info("Releasing savepoint '{$name}'.");
$this->statement("RELEASE SAVEPOINT " . $this->identifier("SVP{$name}"));
}
/**
* Rollback savepoint.
*
* @link http://en.wikipedia.org/wiki/Savepoint
* @param string $name Savepoint name/id, must not contain spaces and be valid database
* identifier.
*/
protected function savepointRollback($name)
{
$this->logger()->info("Rolling back savepoint '{$name}'.");
$this->statement("ROLLBACK TO SAVEPOINT " . $this->identifier("SVP{$name}"));
}
/**
* Convert DateTime object into local database representation. Driver will automatically force
* needed timezone.
*
* @param \DateTime $dateTime
* @return string
*/
protected function prepareDateTime(\DateTime $dateTime)
{
return $dateTime->setTimezone($this->getTimezone())->format(static::DATETIME);
}
/**
* Connection specific timezone, at this moment locked to UTC.
*
* @todo Support connection specific timezones.
* @return \DateTimeZone
*/
protected function getTimezone()
{
return new \DateTimeZone(DatabaseManager::DEFAULT_TIMEZONE);
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Events;
use Spiral\Models\EntityInterface;
use Symfony\Component\EventDispatcher\Event;
/**
* Entity specific event.
*/
class EntityEvent extends Event
{
/**
* @var null|EntityInterface
*/
private $entity = null;
/**
* @param EntityInterface $entity
*/
public function __construct(EntityInterface $entity)
{
$this->entity = $entity;
}
/**
* @return null|EntityInterface
*/
public function entity()
{
return $this->entity;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL\Schemas;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Entities\Schemas\AbstractCommander;
use Spiral\Database\Entities\Schemas\AbstractIndex;
use Spiral\Database\Entities\Schemas\AbstractReference;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Exceptions\SchemaException;
/**
* MySQL commander.
*/
class Commander extends AbstractCommander
{
/**
* {@inheritdoc}
*/
public function alterColumn(
AbstractTable $table,
AbstractColumn $initial,
AbstractColumn $column
) {
$query = "ALTER TABLE {table} CHANGE {column} {statement}";
$query = \Spiral\interpolate($query, [
'table' => $table->getName(true),
'column' => $initial->getName(true),
'statement' => $column->sqlStatement()
]);
$this->run($query);
return $this;
}
/**
* {@inheritdoc}
*/
public function dropIndex(AbstractTable $table, AbstractIndex $index)
{
$this->run("DROP INDEX {$index->getName(true)} ON {$table->getName(true)}");
return $this;
}
/**
* {@inheritdoc}
*/
public function alterIndex(AbstractTable $table, AbstractIndex $initial, AbstractIndex $index)
{
$query = \Spiral\interpolate("ALTER TABLE {table} DROP INDEX {index}, ADD {statement}", [
'table' => $table->getName(true),
'index' => $initial->getName(true),
'statement' => $index->sqlStatement(false)
]);
$this->run($query);
return $this;
}
/**
* {@inheritdoc}
*/
public function dropForeign(AbstractTable $table, AbstractReference $foreign)
{
$this->run("ALTER TABLE {$table->getName(true)} DROP FOREIGN KEY {$foreign->getName(true)}");
return $this;
}
/**
* Get statement needed to create table.
*
* @param AbstractTable $table
* @return string
*/
protected function createStatement(AbstractTable $table)
{
if (!$table instanceof TableSchema) {
throw new SchemaException("MySQL commander can process only MySQL tables.");
}
return parent::createStatement($table) . " ENGINE {$table->getEngine()}";
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core\Exceptions;
/**
* Exceptions raised by spiral Core Application.
*/
class CoreException extends RuntimeException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations;
use Spiral\ORM\RecordEntity;
/**
* Declares simple has many relation. Relations like that used when parent record has many child
* with
* [outer] key linked to value of [inner] key of parent mode. Relation allow specifying default
* WHERE statement. Attention, WHERE statement will not be used in populating newly created record
* fields.
*
* Example, [User has many Comments], user primary key is "id":
* - relation will create outer key "user_id" in "comments" table (or other table name), nullable
* by default
* - relation will create index on column "user_id" in "comments" table if allowed
* - relation will create foreign key "comments"."user_id" => "users"."id" if allowed
*/
class HasManySchema extends HasOneSchema
{
/**
* {@inheritdoc}
*/
const RELATION_TYPE = RecordEntity::HAS_MANY;
/**
* Relation represent multiple records.
*/
const MULTIPLE = true;
/**
* {@inheritdoc}
*
* @invisible
*/
protected $defaultDefinition = [
//Let's use parent record primary key as default inner key
RecordEntity::INNER_KEY => '{record:primaryKey}',
//Outer key will be based on parent record role and inner key name
RecordEntity::OUTER_KEY => '{record:role}_{definition:innerKey}',
//Set constraints (foreign keys) by default
RecordEntity::CONSTRAINT => true,
//@link https://en.wikipedia.org/wiki/Foreign_key
RecordEntity::CONSTRAINT_ACTION => 'CASCADE',
//We are going to make all relations nullable by default, so we can add fields to existed
//tables without raising an exceptions
RecordEntity::NULLABLE => true,
//Relation allowed to create indexes in outer table
RecordEntity::CREATE_INDEXES => true,
//HasMany allow us to define default WHERE statement for relation in a simplified array form
RecordEntity::WHERE => []
];
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Entities\QueryCompiler;
use Spiral\Database\Injections\Parameter;
/**
* Insert statement query builder, support singular and batch inserts.
*/
class InsertQuery extends QueryBuilder
{
/**
* @var string
*/
protected $table = '';
/**
* Column names associated with insert.
*
* @var array
*/
protected $columns = [];
/**
* Rowsets to be inserted.
*
* @var array
*/
protected $rowsets = [];
/**
* @param Database $database Parent database.
* @param QueryCompiler $compiler Driver specific QueryGrammar instance (one per builder).
* @param string $table Associated table name.
*/
public function __construct(Database $database, QueryCompiler $compiler, $table = '')
{
parent::__construct($database, $compiler);
$this->table = $table;
}
/**
* Set target insertion table.
*
* @param string $into
* @return $this
*/
public function into($into)
{
$this->table = $into;
return $this;
}
/**
* Set insertion column names. Names can be provided as array, set of parameters or comma
* separated string.
*
* Examples:
* $insert->columns(["name", "email"]);
* $insert->columns("name", "email");
* $insert->columns("name, email");
*
* @param array|string $columns
* @return $this
*/
public function columns($columns)
{
$this->columns = $this->fetchIdentifiers(func_get_args());
return $this;
}
/**
* Set insertion rowset values or multiple rowsets. Values can be provided in multiple forms
* (method parameters, array of values, array or rowsets). Columns names will be automatically
* fetched (if not already specified) from first provided rowset based on rowset keys.
*
* Examples:
* $insert->columns("name", "balance")->values("Wolfy-J", 10);
* $insert->values([
* "name" => "Wolfy-J",
* "balance" => 10
* ]);
* $insert->values([
* [
* "name" => "Wolfy-J",
* "balance" => 10
* ],
* [
* "name" => "Ben",
* "balance" => 20
* ]
* ]);
*
* @param mixed $rowsets
* @return $this
*/
public function values($rowsets)
{
if (!is_array($rowsets)) {
return $this->values(func_get_args());
}
//Checking if provided set is array of multiple
reset($rowsets);
if (!is_array($rowsets[key($rowsets)])) {
if (empty($this->columns)) {
$this->columns = array_keys($rowsets);
}
$this->rowsets[] = new Parameter(array_values($rowsets));
} else {
foreach ($rowsets as $rowset) {
$this->rowsets[] = new Parameter(array_values($rowset));
}
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getParameters(QueryCompiler $compiler = null)
{
$compiler = !empty($compiler) ? $compiler : $this->compiler;
return $this->flattenParameters($compiler->orderParameters(
QueryCompiler::INSERT_QUERY, [], [], [], $this->rowsets
));
}
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler->resetQuoter();
}
return $compiler->compileInsert($this->table, $this->columns, $this->rowsets);
}
/**
* {@inheritdoc}
*/
public function run()
{
//This must execute our query
$this->pdoStatement();
return $this->database->driver()->lastInsertID();
}
/**
* Reset all insertion rowsets to make builder reusable (columns still set).
*/
public function flushValues()
{
$this->rowsets = [];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\Schemas\Prototypes\AbstractElement;
use Spiral\Database\Exceptions\InvalidArgumentException;
use Spiral\Database\Exceptions\SchemaException;
use Spiral\Database\Injections\Fragment;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Schemas\ColumnInterface;
/**
* Abstract column schema with read (see ColumnInterface) and write abilities. Must be implemented
* by driver to support DBMS specific syntax and creation rules.
*
* Shortcuts for various column types:
* @method AbstractColumn|$this boolean()
*
* @method AbstractColumn|$this integer()
* @method AbstractColumn|$this tinyInteger()
* @method AbstractColumn|$this bigInteger()
*
* @method AbstractColumn|$this text()
* @method AbstractColumn|$this tinyText()
* @method AbstractColumn|$this longText()
*
* @method AbstractColumn|$this double()
* @method AbstractColumn|$this float()
*
* @method AbstractColumn|$this datetime()
* @method AbstractColumn|$this date()
* @method AbstractColumn|$this time()
* @method AbstractColumn|$this timestamp()
*
* @method AbstractColumn|$this binary()
* @method AbstractColumn|$this tinyBinary()
* @method AbstractColumn|$this longBinary()
*
* @method AbstractColumn|$this json()
*/
abstract class AbstractColumn extends AbstractElement implements ColumnInterface
{
/**
* PHP types for phpType() method.
*/
const INT = 'int';
const BOOL = 'bool';
const STRING = 'string';
const FLOAT = 'float';
/**
* Abstract type aliases (for consistency).
*
* @var array
*/
private $aliases = [
'int' => 'integer',
'bigint' => 'bigInteger',
'incremental' => 'primary',
'bigIncremental' => 'bigPrimary',
'bool' => 'boolean',
'blob' => 'binary'
];
/**
* Association list between abstract types and native PHP types. Every non listed type will be
* converted into string.
*
* @invisible
* @var array
*/
private $phpMapping = [
self::INT => ['primary', 'bigPrimary', 'integer', 'tinyInteger', 'bigInteger'],
self::BOOL => ['boolean'],
self::FLOAT => ['double', 'float', 'decimal']
];
/**
* Mapping between abstract type and internal database type with it's options. Multiple abstract
* types can map into one database type, this implementation allows us to equalize two columns
* if they have different abstract types but same database one. Must be declared by DBMS
* specific implementation.
*
* Example:
* integer => array('type' => 'int', 'size' => 1),
* boolean => array('type' => 'tinyint', 'size' => 1)
*
* @invisible
* @var array
*/
protected $mapping = [
//Primary sequences
'primary' => null,
'bigPrimary' => null,
//Enum type (mapped via method)
'enum' => null,
//Logical types
'boolean' => null,
//Integer types (size can always be changed with size method), longInteger has method alias
//bigInteger
'integer' => null,
'tinyInteger' => null,
'bigInteger' => null,
//String with specified length (mapped via method)
'string' => null,
//Generic types
'text' => null,
'tinyText' => null,
'longText' => null,
//Real types
'double' => null,
'float' => null,
//Decimal type (mapped via method)
'decimal' => null,
//Date and Time types
'datetime' => null,
'date' => null,
'time' => null,
'timestamp' => null,
//Binary types
'binary' => null,
'tinyBinary' => null,
'longBinary' => null,
//Additional types
'json' => null
];
/**
* Reverse mapping is responsible for generating abstact type based on database type and it's
* options. Multiple database types can be mapped into one abstract type.
*
* @invisible
* @var array
*/
protected $reverseMapping = [
'primary' => [],
'bigPrimary' => [],
'enum' => [],
'boolean' => [],
'integer' => [],
'tinyInteger' => [],
'bigInteger' => [],
'string' => [],
'text' => [],
'tinyText' => [],
'longText' => [],
'double' => [],
'float' => [],
'decimal' => [],
'datetime' => [],
'date' => [],
'time' => [],
'timestamp' => [],
'binary' => [],
'tinyBinary' => [],
'longBinary' => [],
'json' => []
];
/**
* DBMS specific column type.
*
* @var string
*/
protected $type = '';
/**
* Indicates that column can contain null values.
*
* @var bool
*/
protected $nullable = true;
/**
* Default column value, may not be applied to some datatypes (for example to primary keys),
* should follow type size and other options.
*
* @var mixed
*/
protected $defaultValue = null;
/**
* Column type size, can have different meanings for different datatypes.
*
* @var int
*/
protected $size = 0;
/**
* Precision of column, applied only for "decimal" type.
*
* @var int
*/
protected $precision = 0;
/**
* Scale of column, applied only for "decimal" type.
*
* @var int
*/
protected $scale = 0;
/**
* List of allowed enum values.
*
* @var array
*/
protected $enumValues = [];
/**
* {@inheritdoc}
*/
public function getType()
{
return $this->type;
}
/**
* {@inheritdoc}
*/
public function phpType()
{
$schemaType = $this->abstractType();
foreach ($this->phpMapping as $phpType => $candidates) {
if (in_array($schemaType, $candidates)) {
return $phpType;
}
}
return self::STRING;
}
/**
* {@inheritdoc}
*/
public function getSize()
{
return $this->size;
}
/**
* {@inheritdoc}
*/
public function getPrecision()
{
return $this->precision;
}
/**
* {@inheritdoc}
*/
public function getScale()
{
return $this->scale;
}
/**
* {@inheritdoc}
*/
public function isNullable()
{
return $this->nullable;
}
/**
* {@inheritdoc}
*/
public function hasDefaultValue()
{
return !is_null($this->defaultValue);
}
/**
* {@inheritdoc}
*/
public function getDefaultValue()
{
if (!$this->hasDefaultValue()) {
return null;
}
if ($this->defaultValue instanceof FragmentInterface) {
return $this->defaultValue;
}
if (in_array($this->abstractType(), ['time', 'date', 'datetime', 'timestamp'])) {
if (
strtolower($this->defaultValue) == strtolower($this->table->driver()->nowExpression())
) {
return new Fragment($this->defaultValue);
}
}
switch ($this->phpType()) {
case 'int':
return (int)$this->defaultValue;
case 'float':
return (float)$this->defaultValue;
case 'bool':
if (strtolower($this->defaultValue) == 'false') {
return false;
}
return (bool)$this->defaultValue;
}
return (string)$this->defaultValue;
}
/**
* Get every associated column constraint names.
*
* @return array
*/
public function getConstraints()
{
return [];
}
/**
* Get allowed enum values.
*
* @return array
*/
public function getEnumValues()
{
return $this->enumValues;
}
/**
* DBMS specific reverse mapping must map database specific type into limited set of abstract
* types.
*
* @return string
*/
public function abstractType()
{
foreach ($this->reverseMapping as $type => $candidates) {
foreach ($candidates as $candidate) {
if (is_string($candidate)) {
if (strtolower($candidate) == strtolower($this->type)) {
return $type;
}
continue;
}
if (strtolower($candidate['type']) != strtolower($this->type)) {
continue;
}
foreach ($candidate as $option => $required) {
if ($option == 'type') {
continue;
}
if ($this->$option != $required) {
continue 2;
}
}
return $type;
}
}
return 'unknown';
}
/**
* Give column new abstract type. DBMS specific implementation must map provided type into one
* of internal database values.
*
* Attention, changing type of existed columns in some databases has a lot of restrictions like
* cross type conversions and etc. Try do not change column type without a reason.
*
* @param string $abstract Abstract or virtual type declared in mapping.
* @return $this
* @throws SchemaException
*/
public function setType($abstract)
{
if (isset($this->aliases[$abstract])) {
$abstract = $this->aliases[$abstract];
}
if (!isset($this->mapping[$abstract])) {
throw new SchemaException("Undefined abstract/virtual type '{$abstract}'.");
}
//Resetting all values to default state.
$this->size = $this->precision = $this->scale = 0;
$this->enumValues = [];
if (is_string($this->mapping[$abstract])) {
$this->type = $this->mapping[$abstract];
return $this;
}
//Additional type options
foreach ($this->mapping[$abstract] as $property => $value) {
$this->$property = $value;
}
return $this;
}
/**
* Set column nullable/not nullable.
*
* @param bool $nullable
* @return $this
*/
public function nullable($nullable = true)
{
$this->nullable = $nullable;
return $this;
}
/**
* Change column default value (can be forbidden for some column types).
* Use Database::TIMESTAMP_NOW to use driver specific NOW() function.
*
* @param mixed $value
* @return $this
*/
public function defaultValue($value)
{
$this->defaultValue = $value;
if (
$this->abstractType() == 'timestamp'
&& strtolower($value) == strtolower(Database::TIMESTAMP_NOW)
) {
$this->defaultValue = $this->table->driver()->nowExpression();
}
return $this;
}
/**
* Set column as primary key and register it in parent table primary key list.
*
* @see TableSchema::setPrimaryKeys()
* @return $this
*/
public function primary()
{
if (!in_array($this->name, $this->table->getPrimaryKeys())) {
$this->table->setPrimaryKeys([$this->name]);
}
return $this->setType('primary');
}
/**
* Set column as big primary key and register it in parent table primary key list.
*
* @see TableSchema::setPrimaryKeys()
* @return $this
*/
public function bigPrimary()
{
if (!in_array($this->name, $this->table->getPrimaryKeys())) {
$this->table->setPrimaryKeys([$this->name]);
}
return $this->setType('bigPrimary');
}
/**
* Set column as enum type and specify set of allowed values. Most of drivers will emulate enums
* using column constraints.
*
* Examples:
* $table->status->enum(['active', 'disabled']);
* $table->status->enum('active', 'disabled');
*
* @param string|array $values Enum values (array or comma separated). String values only.
* @return $this
*/
public function enum($values)
{
$this->setType('enum');
$this->enumValues = array_map('strval', is_array($values) ? $values : func_get_args());
return $this;
}
/**
* Set column type as string with limited size. Maximum allowed size is 255 bytes, use "text"
* abstract types for longer strings.
*
* Strings are perfect type to store email addresses as it big enough to store valid address
* and
* can be covered with unique index.
*
* @link http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
* @param int $size Max string length.
* @return $this
* @throws InvalidArgumentException
*/
public function string($size = 255)
{
$this->setType('string');
if ($size > 255) {
throw new InvalidArgumentException(
"String size can't exceed 255 characters. Use text instead."
);
}
if ($size < 0) {
throw new InvalidArgumentException("Invalid string length value.");
}
$this->size = (int)$size;
return $this;
}
/**
* Set column type as decimal with specific precision and scale.
*
* @param int $precision
* @param int $scale
* @return $this
* @throws InvalidArgumentException
*/
public function decimal($precision, $scale = 0)
{
$this->setType('decimal');
if (empty($precision)) {
throw new InvalidArgumentException("Invalid precision value.");
}
$this->precision = (int)$precision;
$this->scale = (int)$scale;
return $this;
}
/**
* Create/get table index associated with this column.
*
* @return AbstractIndex
* @throws SchemaException
*/
public function index()
{
return $this->table->index($this->name);
}
/**
* Create/get table index associated with this column. Index type will be forced as UNIQUE.
*
* @return AbstractIndex
* @throws SchemaException
*/
public function unique()
{
return $this->table->unique($this->name);
}
/**
* Create/get foreign key schema associated with column and referenced foreign table and column.
* Make sure local and outer column types are identical.
*
* @param string $table Foreign table name.
* @param string $column Foreign column name (id by default).
* @return AbstractReference
* @throws SchemaException
*/
public function references($table, $column = 'id')
{
if ($this->phpType() != self::INT) {
throw new SchemaException(
"Only numeric types can be defined with foreign key constraint."
);
}
return $this->table->foreign($this->name)->references($table, $column);
}
/**
* Compile column create statement.
*
* @return string
*/
public function sqlStatement()
{
$statement = [$this->getName(true), $this->type];
if ($this->abstractType() == 'enum') {
//Enum specific column options
if (!empty($enumDefinition = $this->prepareEnum())) {
$statement[] = $enumDefinition;
}
} elseif (!empty($this->precision)) {
$statement[] = "({$this->precision}, {$this->scale})";
} elseif (!empty($this->size)) {
$statement[] = "({$this->size})";
}
$statement[] = $this->nullable ? 'NULL' : 'NOT NULL';
if ($this->defaultValue !== null) {
$statement[] = "DEFAULT {$this->prepareDefault()}";
}
return join(' ', $statement);
}
/**
* Must compare two instances of AbstractColumn.
*
* @param self $initial
* @return bool
*/
public function compare(self $initial)
{
$normalized = clone $initial;
$normalized->declared = $this->declared;
if ($this == $normalized) {
return true;
}
$columnVars = get_object_vars($this);
$dbColumnVars = get_object_vars($normalized);
$difference = [];
foreach ($columnVars as $name => $value) {
if ($name == 'defaultValue') {
//Default values has to compared using type-casted value
if ($this->getDefaultValue() != $initial->getDefaultValue()) {
$difference[] = $name;
}
continue;
}
if ($value != $dbColumnVars[$name]) {
$difference[] = $name;
}
}
return empty($difference);
}
/**
* Shortcut for AbstractColumn->type() method.
*
* @param string $type Abstract type.
* @param array $arguments Not used.
* @return $this
*/
public function __call($type, array $arguments = [])
{
return $this->setType($type);
}
/**
* Simplified way to dump information.
*
* @return array
*/
public function __debugInfo()
{
$column = [
'name' => $this->name,
'declared' => $this->declared,
'type' => [
'database' => $this->type,
'schema' => $this->abstractType(),
'php' => $this->phpType()
]
];
if (!empty($this->size)) {
$column['size'] = $this->size;
}
if ($this->nullable) {
$column['nullable'] = true;
}
if ($this->defaultValue !== null) {
$column['defaultValue'] = $this->getDefaultValue();
}
if ($this->abstractType() == 'enum') {
$column['enumValues'] = $this->enumValues;
}
if ($this->abstractType() == 'decimal') {
$column['precision'] = $this->precision;
$column['scale'] = $this->scale;
}
return $column;
}
/**
* Get database specific enum type definition options.
*
* @return string.
*/
protected function prepareEnum()
{
$enumValues = [];
foreach ($this->enumValues as $value) {
$enumValues[] = $this->table->driver()->getPDO()->quote($value);
}
if (!empty($enumValues)) {
return '(' . join(', ', $enumValues) . ')';
}
return '';
}
/**
* Must return driver specific default value.
*
* @return string
*/
protected function prepareDefault()
{
if (($defaultValue = $this->getDefaultValue()) === null) {
return 'NULL';
}
if ($defaultValue instanceof FragmentInterface) {
return $defaultValue->sqlStatement();
}
if ($this->phpType() == 'bool') {
return $defaultValue ? 'TRUE' : 'FALSE';
}
if ($this->phpType() == 'float') {
return sprintf('%F', $defaultValue);
}
if ($this->phpType() == 'int') {
return $defaultValue;
}
return $this->table->driver()->getPDO()->quote($defaultValue);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Pagination;
/**
* Declares ability to be paginated and store associated paginator.
*/
interface PaginableInterface extends \Countable
{
/**
* Set selection limit.
*
* @param int $limit
* @return mixed
*/
public function limit($limit = 0);
/**
* @return int
*/
public function getLimit();
/**
* Set selection offset.
*
* @param int $offset
* @return mixed
*/
public function offset($offset = 0);
/**
* @return int
*/
public function getOffset();
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Spiral\Database\Builders\DeleteQuery;
use Spiral\Database\Builders\InsertQuery;
use Spiral\Database\Builders\SelectQuery;
use Spiral\Database\Builders\UpdateQuery;
use Spiral\Database\Entities\Schemas\AbstractTable;
/**
* Driver abstraction is responsible for DBMS specific set of functions and used by Databases to
* hide implementation specific functionality. Extends PDODriver and adds ability to create driver
* specific query builders and schemas (basically operates like a factory).
*/
abstract class Driver extends PDODriver
{
/**
* Driver schemas.
*/
const SCHEMA_TABLE = '';
/**
* Commander used to execute commands. :)
*/
const COMMANDER = '';
/**
* Default datetime value.
*/
const DEFAULT_DATETIME = '1970-01-01 00:00:00';
/**
* Default timestamp expression.
*/
const TIMESTAMP_NOW = 'DRIVER_SPECIFIC_NOW_EXPRESSION';
/**
* Current timestamp expression value.
*
* @return string
*/
public function nowExpression()
{
return static::TIMESTAMP_NOW;
}
/**
* Clean (truncate) specified driver table.
*
* @param string $table Table name with prefix included.
*/
public function truncate($table)
{
$this->statement("TRUNCATE TABLE {$this->identifier($table)}");
}
/**
* Check if table exists.
*
* @param string $name
* @return bool
*/
abstract public function hasTable($name);
/**
* Get every available table name as array.
*
* @return array
*/
abstract public function tableNames();
/**
* Get Driver specific AbstractTable implementation.
*
* @param string $table Table name without prefix included.
* @param string $prefix Database specific table prefix, this parameter is not required,
* but if provided all
* foreign keys will be created using it.
* @return AbstractTable
*/
public function tableSchema($table, $prefix = '')
{
return $this->factory->make(static::SCHEMA_TABLE, [
'driver' => $this,
'name' => $table,
'prefix' => $prefix,
'commander' => $this->factory->make(static::COMMANDER, ['driver' => $this])
]);
}
/**
* Get InsertQuery builder with driver specific query compiler.
*
* @param Database $database Database instance builder should be associated to.
* @param array $parameters Initial builder parameters.
* @return InsertQuery
*/
public function insertBuilder(Database $database, array $parameters = [])
{
return $this->factory->make(InsertQuery::class, [
'database' => $database,
'compiler' => $this->queryCompiler($database->getPrefix())
] + $parameters);
}
/**
* Get SelectQuery builder with driver specific query compiler.
*
* @param Database $database Database instance builder should be associated to.
* @param array $parameters Initial builder parameters.
* @return SelectQuery
*/
public function selectBuilder(Database $database, array $parameters = [])
{
return $this->factory->make(SelectQuery::class, [
'database' => $database,
'compiler' => $this->queryCompiler($database->getPrefix())
] + $parameters);
}
/**
* Get DeleteQuery builder with driver specific query compiler.
*
* @param Database $database Database instance builder should be associated to.
* @param array $parameters Initial builder parameters.
* @return DeleteQuery
*/
public function deleteBuilder(Database $database, array $parameters = [])
{
return $this->factory->make(DeleteQuery::class, [
'database' => $database,
'compiler' => $this->queryCompiler($database->getPrefix())
] + $parameters);
}
/**
* Get UpdateQuery builder with driver specific query compiler.
*
* @param Database $database Database instance builder should be associated to.
* @param array $parameters Initial builder parameters.
* @return UpdateQuery
*/
public function updateBuilder(Database $database, array $parameters = [])
{
return $this->factory->make(UpdateQuery::class, [
'database' => $database,
'compiler' => $this->queryCompiler($database->getPrefix())
] + $parameters);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Loaders;
use Spiral\Database\Injections\Parameter;
use Spiral\ORM\Entities\Loader;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* Dedicated to load HAS_ONE relations, by default loader will prefer to join data into query.
* Loader support MORPH_KEY.
*/
class HasOneLoader extends Loader
{
/**
* Relation type is required to correctly resolve foreign record class based on relation
* definition.
*/
const RELATION_TYPE = RecordEntity::HAS_ONE;
/**
* Default load method (inload or postload).
*/
const LOAD_METHOD = self::INLOAD;
/**
* Internal loader constant used to decide how to aggregate data tree, true for relations like
* MANY TO MANY or HAS MANY.
*/
const MULTIPLE = false;
/**
* {@inheritdoc}
*/
public function createSelector()
{
if (empty($selector = parent::createSelector())) {
return null;
}
if (empty($this->parent)) {
//No need for where conditions
return $selector;
}
//Mounting where conditions
$this->mountConditions($selector);
//Aggregated keys (example: all parent ids)
if (empty($aggregatedKeys = $this->parent->aggregatedKeys($this->getReferenceKey()))) {
//Nothing to postload, no parents
return null;
}
//Adding condition
$selector->where(
$this->getKey(RecordEntity::OUTER_KEY),
'IN',
new Parameter($aggregatedKeys)
);
return $selector;
}
/**
* {@inheritdoc}
*/
protected function clarifySelector(RecordSelector $selector)
{
$selector->join($this->joinType(), $this->getTable() . ' AS ' . $this->getAlias(), [
$this->getKey(RecordEntity::OUTER_KEY) => $this->getParentKey()
]);
$this->mountConditions($selector);
}
/**
* Mount additional (not related to parent key) conditions, extended by child loaders
* (HAS_MANY, BELONGS_TO).
*
* @param RecordSelector $selector
* @return RecordSelector
*/
protected function mountConditions(RecordSelector $selector)
{
//We only going to mount morph key as additional condition
if (!empty($morphKey = $this->getKey(RecordEntity::MORPH_KEY))) {
if ($this->isJoinable()) {
$selector->onWhere($morphKey, $this->parent->schema[ORM::M_ROLE_NAME]);
} else {
$selector->where($morphKey, $this->parent->schema[ORM::M_ROLE_NAME]);
}
}
return $selector;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache;
use Spiral\Cache\Exceptions\CacheException;
/**
* StoreInterface provider.
*/
interface CacheInterface
{
/**
* Create specified or default cache store. This function will load cache adapter if it
* was not initiated, or fetch it from memory.
*
* @param string $store Keep null, empty or not specified to get default cache adapter.
* @return StoreInterface
* @throws CacheException
*/
public function store($store = null);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Models\AccessorInterface;
/**
* Declares requirement for every ORM field accessor to declare it's driver depended value and
* control it's updates.
*
* ORM accessors are much more simple by initiation that ODM accessors.
*/
interface RecordAccessorInterface extends AccessorInterface
{
/**
* Check if object has any update.
*
* @return bool
*/
public function hasUpdates();
/**
* Mark object as successfully updated and flush all existed atomic operations and updates.
*/
public function flushUpdates();
/**
* Create update value or statement to be used in DBAL update builder. May return SQLFragments
* and expressions.
*
* @param string $field Name of field where accessor associated to.
* @return mixed|FragmentInterface
*/
public function compileUpdates($field = '');
/**
* Accessor default value (must be specific to driver).
*
* @param Driver $driver
* @return mixed
*/
public function defaultValue(Driver $driver);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Exceptions;
use Spiral\Core\Exceptions\RuntimeException;
/**
* Query specific exception (bad parameters, database failure).
*
* @todo change hierarchy?
* @todo add ConstrainException
*/
class QueryException extends RuntimeException
{
/**
* {@inheritdoc}
*
* @param \PDOException $exception
*/
public function __construct(\PDOException $exception)
{
parent::__construct($exception->getMessage(), (int)$exception->getCode(), $exception);
}
/**
* @return \PDOException
*/
public function pdoException()
{
return $this->getPrevious();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Accessors;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Injections\Expression;
use Spiral\Models\EntityInterface;
use Spiral\ORM\RecordAccessorInterface;
/**
* Atomic number accessor provides ability to change numeric record field using delta values, this
* accessor is very similar by idea to Document->inc() method.
*
* Accessor will declare expression to sent to update statement in compileUpdate() method. If parent
* record is solid (solid state) dynamic expression will be ignored and accessor will return it's
* internal numeric value (altered by inc/dec operations and based on original record value).
*/
class AtomicNumber implements RecordAccessorInterface
{
/**
* Current numeric value.
*
* @var float|int
*/
private $value = null;
/**
* @var float|int
*/
private $original = null;
/**
* Difference between original and current values.
*
* @var float|int
*/
protected $delta = 0;
/**
* @var EntityInterface
*/
protected $parent = null;
/**
* {@inheritdoc}
*/
public function __construct($number, EntityInterface $parent = null)
{
$this->original = $this->value = $number;
$this->parent = $parent;
}
/**
* {@inheritdoc}
*/
public function embed(EntityInterface $parent)
{
$accessor = clone $this;
$accessor->parent = $parent;
return $accessor;
}
/**
* {@inheritdoc}
*/
public function setValue($data)
{
$this->original = $this->value = $data;
$this->delta = 0;
}
/**
* {@inheritdoc}
*/
public function serializeData()
{
return $this->value;
}
/**
* {@inheritdoc}
*/
public function hasUpdates()
{
return $this->value !== $this->original;
}
/**
* {@inheritdoc}
*/
public function flushUpdates()
{
$this->original = $this->value;
$this->delta = 0;
}
/**
* {@inheritdoc}
*/
public function compileUpdates($field = '')
{
if ($this->delta === 0) {
//Nothing were changed
return $this->value;
}
$sign = $this->delta > 0 ? '+' : '-';
//"field" = "field" + delta
return new Expression("{$field} {$sign} " . abs($this->delta));
}
/**
* Increment numeric value (alias for inc) by given delta.
*
* @param float|int $delta
* @return $this
*/
public function inc($delta = 1)
{
$this->value += $delta;
$this->delta += $delta;
return $this;
}
/**
* Increment numeric value (alias for inc) by given delta.
*
* @param float|int $delta
* @return $this
*/
public function add($delta = 1)
{
$this->value += $delta;
$this->delta += $delta;
return $this;
}
/**
* Decrement numeric value by given delta.
*
* @param float|int $delta Delta must be positive to deduct value.
* @return $this
*/
public function dec($delta = 1)
{
$this->value -= $delta;
$this->delta -= $delta;
return $this;
}
/**
* {@inheritdoc}
*/
public function defaultValue(Driver $driver)
{
return $this->serializeData();
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->serializeData();
}
/**
* @return string
*/
public function __toString()
{
return (string)$this->value;
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'value' => $this->value,
'delta' => $this->delta
];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core\Container;
/**
* Provided to method or constructor which declares such dependency.
*/
final class Context
{
/**
* @var \ReflectionFunctionAbstract
*/
private $function = null;
/**
* @var \ReflectionParameter|null
*/
private $parameter = null;
/**
* @param \ReflectionFunctionAbstract $function
* @param \ReflectionParameter|null $parameter
*/
public function __construct(
\ReflectionFunctionAbstract $function,
\ReflectionParameter $parameter = null
) {
$this->function = $function;
$this->parameter = $parameter;
}
/**
* Function or method or constructor.
*
* @return \ReflectionFunctionAbstract
*/
public function getFunction()
{
return $this->function;
}
/**
* Can be empty.
*
* @return null|\ReflectionParameter
*/
public function getParameter()
{
return $this->parameter;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Spiral\Database\Builders\DeleteQuery;
use Spiral\Database\Builders\SelectQuery;
use Spiral\Database\Builders\UpdateQuery;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Query\QueryResult;
use Spiral\Database\TableInterface;
/**
* Represent table level abstraction with simplified access to SelectQuery associated with such
* table.
*
* @method int avg($identifier) Perform aggregation (AVG) based on column or expression value.
* @method int min($identifier) Perform aggregation (MIN) based on column or expression value.
* @method int max($identifier) Perform aggregation (MAX) based on column or expression value.
* @method int sum($identifier) Perform aggregation (SUM) based on column or expression value.
*/
class Table implements \JsonSerializable, \IteratorAggregate, TableInterface
{
/**
* @var string
*/
private $name = '';
/**
* @var Database
*/
protected $database = null;
/**
* @param Database $database Parent DBAL database.
* @param string $name Table name without prefix.
*/
public function __construct(Database $database, $name)
{
$this->name = $name;
$this->database = $database;
}
/**
* {@inheritdoc}
*
* @return AbstractTable
*/
public function schema()
{
return $this->database->driver()->tableSchema(
$this->realName(),
$this->database->getPrefix()
);
}
/**
* Check if table exists.
*
* @return bool
*/
public function exists()
{
return $this->database->hasTable($this->name);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* Real table name, will include database prefix.
*
* @return string
*/
public function realName()
{
return $this->database->getPrefix() . $this->name;
}
/**
* Get list of column names associated with their abstract types.
*
* @return array
*/
public function getColumns()
{
$columns = [];
foreach ($this->schema()->getColumns() as $column) {
$columns[$column->getName()] = $column->abstractType();
}
return $columns;
}
/**
* {@inheritdoc}
*/
public function truncate()
{
$this->database->driver()->truncate($this->realName());
}
/**
* {@inheritdoc}
*/
public function insert(array $rowset = [])
{
return $this->database->insert($this->name)->values($rowset)->run();
}
/**
* Perform batch insert into table, every rowset should have identical amount of values matched
* with column names provided in first argument. Method will return lastInsertID on success.
*
* Example:
* $table->insert(["name", "balance"], array(["Bob", 10], ["Jack", 20]))
*
* @param array $columns Array of columns.
* @param array $rowsets Array of rowsets.
* @return mixed
*/
public function batchInsert(array $columns = [], array $rowsets = [])
{
return $this->database->insert($this->name)->columns($columns)->values($rowsets)->run();
}
/**
* Get SelectQuery builder with pre-populated from tables.
*
* @param string $columns
* @return SelectQuery
*/
public function select($columns = '*')
{
return $this->database->select(func_num_args() ? func_get_args() : '*')->from($this->name);
}
/**
* Get DeleteQuery builder with pre-populated table name. This is NOT table delete method, use
* schema()->drop() for this purposes. If you want to remove all records from table use
* Table->truncate() method. Call ->run() to perform query.
*
* @param array $where Initial set of where rules specified as array.
* @return DeleteQuery
*/
public function delete(array $where = [])
{
return $this->database->delete($this->name, $where);
}
/**
* Get UpdateQuery builder with pre-populated table name and set of columns to update. Columns
* can be scalar values, Parameter objects or even SQLFragments. Call ->run() to perform query.
*
* @param array $values Initial set of columns associated with values.
* @param array $where Initial set of where rules specified as array.
* @return UpdateQuery
*/
public function update(array $values = [], array $where = [])
{
return $this->database->update($this->name, $values, $where);
}
/**
* Count number of records in table.
*
* @return int
*/
public function count()
{
return $this->select()->count();
}
/**
* Retrieve an external iterator, SelectBuilder will return QueryResult as iterator.
*
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return SelectQuery
*/
public function getIterator()
{
return $this->select();
}
/**
* A simple alias for table query without condition.
*
* @return QueryResult
*/
public function all()
{
return $this->select()->all();
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->select()->jsonSerialize();
}
/**
* Bypass call to SelectQuery builder.
*
* @param string $method
* @param array $arguments
* @return SelectQuery
*/
public function __call($method, array $arguments)
{
return call_user_func_array([$this->select(), $method], $arguments);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Spiral\Core\Component;
use Spiral\Database\Exceptions\CompilerException;
use Spiral\Database\Injections\ExpressionInterface;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Injections\ParameterInterface;
/**
* Responsible for conversion of set of query parameters (where tokens, table names and etc) into
* sql to be send into specific Driver.
*
* Source of Compiler must be optimized in nearest future.
*/
class QueryCompiler extends Component
{
/**
* Query types for parameter ordering.
*/
const SELECT_QUERY = 'select';
const UPDATE_QUERY = 'update';
const DELETE_QUERY = 'delete';
const INSERT_QUERY = 'insert';
/**
* Associated driver instance, may be required for some data assumptions.
*
* @var PDODriver
*/
protected $driver = null;
/**
* Quotes names and expressions.
*
* @var Quoter
*/
protected $quoter = null;
/**
* QueryCompiler constructor.
*
* @param PDODriver $driver
* @param Quoter $quoter
*/
public function __construct(PDODriver $driver, Quoter $quoter)
{
$this->driver = $driver;
$this->quoter = $quoter;
}
/**
* Reset table aliases cache, required if same compiler used twice.
*
* @return $this
*/
public function resetQuoter()
{
$this->quoter->reset();
return $this;
}
/**
* Query query identifier, if identified stated as table - table prefix must be added.
*
* @param string $identifier Identifier can include simple column operations and functions,
* having "." in it will automatically force table prefix to first
* value.
* @param bool $table Set to true to let quote method know that identified is related
* to table name.
* @return mixed|string
*/
public function quote($identifier, $table = false)
{
if ($identifier instanceof FragmentInterface) {
return $this->prepareFragment($identifier);
}
return $this->quoter->quote($identifier, $table);
}
/**
* Sort list of parameters in dbms query specific order, query type must be provided. This
* method was used at times when delete and update queries supported joins, i might need to
* drop it now.
*
* @param int $queryType
* @param array $whereParameters
* @param array $onParameters
* @param array $havingParameters
* @param array $columnIdentifiers Column names (if any).
* @return array
*/
public function orderParameters(
$queryType,
array $whereParameters = [],
array $onParameters = [],
array $havingParameters = [],
array $columnIdentifiers = []
) {
return array_merge($columnIdentifiers, $onParameters, $whereParameters, $havingParameters);
}
/**
* Create insert query using table names, columns and rowsets. Must support both - single and
* batch inserts.
*
* @param string $table
* @param array $columns
* @param FragmentInterface[] $rowsets Every rowset has to be convertable into string. Raw data
* not allowed!
* @return string
* @throws CompilerException
*/
public function compileInsert($table, array $columns, array $rowsets)
{
if (empty($columns)) {
throw new CompilerException("Unable to build insert statement, columns must be set.");
}
if (empty($rowsets)) {
throw new CompilerException(
"Unable to build insert statement, at least one value set must be provided."
);
}
//To add needed prefixes (if any)
$table = $this->quote($table, true);
//Compiling list of columns
$columns = $this->prepareColumns($columns);
//Simply joining every rowset
$rowsets = join(",\n", $rowsets);
return "INSERT INTO {$table} ({$columns})\nVALUES {$rowsets}";
}
/**
* Create update statement.
*
* @param string $table
* @param array $updates
* @param array $whereTokens
* @return string
* @throws CompilerException
*/
public function compileUpdate($table, array $updates, array $whereTokens = [])
{
$table = $this->quote($table, true);
//Preparing update column statement
$updates = $this->prepareUpdates($updates);
//Where statement is optional for update queries
$whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens));
return rtrim("UPDATE {$table}\nSET {$updates} {$whereStatement}");
}
/**
* Create delete statement.
*
* @param string $table
* @param array $whereTokens
* @return string
* @throws CompilerException
*/
public function compileDelete($table, array $whereTokens = [])
{
$table = $this->quote($table, true);
//Where statement is optional for delete query (which is weird)
$whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens));
return rtrim("DELETE FROM {$table} {$whereStatement}");
}
/**
* Create select statement. Compiler must validly resolve table and column aliases used in
* conditions and joins.
*
* @param array $fromTables
* @param boolean|string $distinct String only for PostgresSQL.
* @param array $columns
* @param array $joinTokens
* @param array $whereTokens
* @param array $havingTokens
* @param array $grouping
* @param array $ordering
* @param int $limit
* @param int $offset
* @param array $unionTokens
* @return string
* @throws CompilerException
*/
public function compileSelect(
array $fromTables,
$distinct,
array $columns,
array $joinTokens = [],
array $whereTokens = [],
array $havingTokens = [],
array $grouping = [],
array $ordering = [],
$limit = 0,
$offset = 0,
array $unionTokens = []
) {
//This statement parts should be processed first to define set of table and column aliases
$fromTables = $this->compileTables($fromTables);
$joinsStatement = $this->optional(' ', $this->compileJoins($joinTokens), ' ');
//Distinct flag (if any)
$distinct = $this->optional(' ', $this->compileDistinct($distinct));
//Columns are compiled after table names and joins to enshure aliases and prefixes
$columns = $this->prepareColumns($columns);
//A lot of constrain and other statements
$whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens));
$havingStatement = $this->optional("\nHAVING", $this->compileWhere($havingTokens));
$groupingStatement = $this->optional("\nGROUP BY", $this->compileGrouping($grouping), ' ');
//Union statement has new line at beginning of every union
$unionsStatement = $this->optional("\n", $this->compileUnions($unionTokens));
$orderingStatement = $this->optional("\nORDER BY ", $this->compileOrdering($ordering));
$limingStatement = $this->optional("\n", $this->compileLimit($limit, $offset));
//Initial statement have predictable order
$statement = "SELECT{$distinct}\n{$columns}\nFROM {$fromTables}";
$statement .= "{$joinsStatement}{$whereStatement}{$groupingStatement}{$havingStatement}";
$statement .= "{$unionsStatement}{$orderingStatement}{$limingStatement}";
return rtrim($statement);
}
/**
* Quote and wrap column identifiers (used in insert statement compilation).
*
* @param array $columnIdentifiers
* @param int $maxLength Automatically wrap columns.
* @return string
*/
protected function prepareColumns(array $columnIdentifiers, $maxLength = 180)
{
//Let's quote every identifier
$columnIdentifiers = array_map([$this, 'quote'], $columnIdentifiers);
return wordwrap(join(', ', $columnIdentifiers), $maxLength);
}
/**
* Prepare column values to be used in UPDATE statement.
*
* @param array $updates
* @return array
*/
protected function prepareUpdates(array $updates)
{
foreach ($updates as $column => &$value) {
if ($value instanceof FragmentInterface) {
$value = $this->prepareFragment($value);
} else {
//Simple value (such condition should never be met since every value has to be
//wrapped using parameter interface)
$value = '?';
}
$value = "{$this->quote($column)} = {$value}";
unset($value);
}
return trim(join(",", $updates));
}
/**
* Compile DISTINCT statement.
*
* @param mixed $distinct Not every DBMS support distinct expression, only Postgres does.
* @return string
*/
protected function compileDistinct($distinct)
{
if (empty($distinct)) {
return '';
}
return "DISTINCT";
}
/**
* Compile table names statement.
*
* @param array $tables
* @return string
*/
protected function compileTables(array $tables)
{
foreach ($tables as &$table) {
$table = $this->quote($table, true);
unset($table);
}
return join(', ', $tables);
}
/**
* Compiler joins statement.
*
* @param array $joinTokens
* @return string
*/
protected function compileJoins(array $joinTokens)
{
$statement = '';
foreach ($joinTokens as $table => $join) {
$statement .= "\n" . $join['type'] . ' JOIN ' . $this->quote($table, true);
$statement .= $this->optional("\n ON", $this->compileWhere($join['on']));
}
return $statement;
}
/**
* Compile union statement chunk. Keywords UNION and ALL will be included, this methods will
* automatically move every union on new line.
*
* @param array $unionTokens
* @return string
*/
protected function compileUnions(array $unionTokens)
{
if (empty($unionTokens)) {
return '';
}
$statement = '';
foreach ($unionTokens as $union) {
//First key is union type, second united query (no need to share compiler)
$statement .= "\nUNION {$union[1]}\n({$union[0]})";
}
return ltrim($statement, "\n");
}
/**
* Compile ORDER BY statement.
*
* @param array $ordering
* @return string
*/
protected function compileOrdering(array $ordering)
{
$result = [];
foreach ($ordering as $order) {
$result[] = $this->quote($order[0]) . ' ' . strtoupper($order[1]);
}
return join(', ', $result);
}
/**
* Compiler GROUP BY statement.
*
* @param array $grouping
* @return string
*/
protected function compileGrouping(array $grouping)
{
$statement = '';
foreach ($grouping as $identifier) {
$statement .= $this->quote($identifier);
}
return $statement;
}
/**
* Compile limit statement.
*
* @param int $limit
* @param int $offset
* @return string
*/
protected function compileLimit($limit, $offset)
{
if (empty($limit) && empty($offset)) {
return '';
}
$statement = '';
if (!empty($limit)) {
$statement = "LIMIT {$limit} ";
}
if (!empty($offset)) {
$statement .= "OFFSET {$offset}";
}
return trim($statement);
}
/**
* Compile where statement.
*
* @param array $tokens
* @return string
* @throws CompilerException
*/
protected function compileWhere(array $tokens)
{
if (empty($tokens)) {
return '';
}
$statement = '';
$activeGroup = true;
foreach ($tokens as $condition) {
//OR/AND keyword
$boolean = $condition[0];
//See AbstractWhere
$context = $condition[1];
//First condition in group/query, no any AND, OR required
if ($activeGroup) {
//Kill AND, OR and etc.
$boolean = '';
//Next conditions require AND or OR
$activeGroup = false;
}
/**
* When context is string it usually represent control keyword/syntax such as opening
* or closing braces.
*/
if (is_string($context)) {
if ($context == '(') {
//New where group.
$activeGroup = true;
}
$postfix = ' ';
if ($context == '(') {
//We don't need space after opening brace
$postfix = '';
}
$statement .= ltrim("{$boolean} {$context}{$postfix}");
continue;
}
if ($context instanceof FragmentInterface) {
//Fragments has to be compiled separately
$statement .= "{$boolean} {$this->prepareFragment($context)} ";
continue;
}
if (!is_array($context)) {
throw new CompilerException(
"Invalid where token, context expected to be an array."
);
}
/**
* This is "normal" where token which includes identifier, operator and value.
*/
list($identifier, $operator, $value) = $context;
//Identifier can be column name, expression or even query builder
$identifier = $this->quote($identifier);
//Value has to be prepared as well
$placeholder = $this->prepareValue($value);
if ($operator == 'BETWEEN' || $operator == 'NOT BETWEEN') {
//Between statement has additional parameter
$right = $this->prepareValue($context[3]);
$statement .= "{$boolean} {$identifier} {$operator} {$placeholder} AND {$right} ";
continue;
}
//Compiler can switch equal to IN if value points to array
$operator = $this->prepareOperator($value, $operator);
$statement .= "{$boolean} {$identifier} {$operator} {$placeholder} ";
}
if ($activeGroup) {
throw new CompilerException("Unable to build where statement, unclosed where group.");
}
return trim($statement);
}
/**
* Combine expression with prefix/postfix (usually SQL keyword) but only if expression is not
* empty.
*
* @param string $prefix
* @param string $expression
* @param string $postfix
* @return string
*/
protected function optional($prefix, $expression, $postfix = '')
{
if (empty($expression)) {
return '';
}
if ($prefix != "\n") {
$prefix .= ' ';
}
return $prefix . $expression . $postfix;
}
/**
* Resolve operator value based on value value. ;)
*
* @param mixed $parameter
* @param string $operator
* @return string
*/
protected function prepareOperator($parameter, $operator)
{
if (!$parameter instanceof ParameterInterface) {
//Probably fragment
return $operator;
}
if ($operator != '=' || is_scalar($parameter->getValue())) {
//Doing nothing for non equal operators
return $operator;
}
if (is_array($parameter->getValue())) {
//Automatically switching between equal and IN
return 'IN';
}
return $operator;
}
/**
* Prepare value to be replaced into query (replace ?).
*
* @param string $value
* @return string
*/
protected function prepareValue($value)
{
if ($value instanceof FragmentInterface) {
return $this->prepareFragment($value);
}
//Technically should never happen (but i prefer to keep this legacy code)
return '?';
}
/**
* Prepare where fragment to be injected into statement.
*
* @param FragmentInterface $context
* @return string
*/
protected function prepareFragment(FragmentInterface $context)
{
if ($context instanceof QueryBuilder) {
//Nested queries has to be wrapped with braces
return '(' . $context->sqlStatement($this) . ')';
}
if ($context instanceof ExpressionInterface) {
//Fragments does not need braces around them
return $context->sqlStatement($this);
}
return $context->sqlStatement();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Entities;
use Spiral\ODM\Document;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\ODMException;
use Spiral\ODM\ODM;
/**
* Walks thought query result and creates instances of Document on demand. Class decorates methods
* of MongoCursor.
*
* @see MongoCursor
*
* Wrapped methods.
* @method bool hasNext()
* @method static limit($number)
* @method static batchSize($number)
* @method static skip($number)
* @method static addOption($key, $value)
* @method static snapshot()
* @method static sort($fields)
* @method static hint($keyPattern)
* @method array explain()
* @method static setFlag($bit, $set)
* @method static slaveOkay($okay)
* @method static tailable($tail)
* @method static immortal($liveForever)
* @method static awaitData($wait)
* @method static partial($okay)
* @method array getReadPreference()
* @method static setReadPreference($read_preference, array $tags)
* @method static timeout()
* @method static info()
* @method bool dead()
* @method static reset()
* @method int count($foundOnly)
*/
class DocumentCursor implements \Iterator, \JsonSerializable
{
/**
* MongoCursor instance.
*
* @var \MongoCursor
*/
protected $cursor = null;
/**
* ODM component.
*
* @var ODM
*/
protected $odm = null;
/**
* Document class being iterated.
*
* @var string|null
*/
protected $class = '';
/**
* @param \MongoCursor $cursor
* @param ODM $odm
* @param string|null $class
* @param array $sort
* @param int $limit
* @param int $offset
*/
public function __construct(
\MongoCursor $cursor,
ODM $odm,
$class,
array $sort = [],
$limit = null,
$offset = null
) {
$this->cursor = $cursor;
$this->odm = $odm;
$this->class = $class;
!empty($sort) && $this->cursor->sort($sort);
!empty($limit) && $this->cursor->limit($limit);
!empty($offset) && $this->cursor->skip($offset);
}
/**
* Sets the fields for a query. Query will return arrays instead of Documents if selection
* fields are set.
*
* @link http://www.php.net/manual/en/mongocursor.fields.php
* @param array $fields Fields to return (or not return).
* @throws \MongoCursorException
* @return $this
*/
public function fields(array $fields)
{
$this->cursor->fields($fields);
$this->class = null;
return $this;
}
/**
* Select all documents.
*
* @return Document[]
* @throws ODMException
* @throws DefinitionException
*/
public function all()
{
$result = [];
foreach ($this as $document) {
$result[] = $document;
}
return $result;
}
/**
* {@inheritdoc}
*
* @return array|Document
* @throws ODMException
* @throws DefinitionException
*/
public function current()
{
$fields = $this->cursor->current();
if (empty($this->class)) {
return $fields;
}
return $fields ? $this->odm->document($this->class, $fields) : null;
}
/**
* {@inheritdoc}
*/
public function next()
{
$this->cursor->next();
}
/**
* {@inheritdoc}
*/
public function key()
{
return $this->cursor->key();
}
/**
* {@inheritdoc}
*/
public function valid()
{
return $this->cursor->valid();
}
/**
* {@inheritdoc}
*/
public function rewind()
{
$this->cursor->rewind();
}
/**
* Return the next object to which this cursor points, and advance the cursor
*
* @link http://www.php.net/manual/en/mongocursor.getnext.php
* @throws \MongoConnectionException
* @throws \MongoCursorTimeoutException
* @return array|Document Returns the next object
*/
public function getNext()
{
$this->cursor->next();
return $this->current();
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
$result = [];
foreach ($this as $document) {
$result[] = $document->publicFields();
}
return $result;
}
/**
* Forward call to cursor.
*
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call($method, array $arguments)
{
$result = call_user_func_array([$this->cursor, $method], $arguments);
if ($result === $this->cursor || $result === null) {
return $this;
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache;
use Spiral\Core\Container\InjectableInterface;
/**
* AbstractStore named like that for convenience and mapping.
*/
abstract class CacheStore implements StoreInterface, InjectableInterface
{
/**
* This is magick constant used by Spiral Container, it helps system to resolve controllable
* injections.
*/
const INJECTOR = CacheManager::class;
/**
* {@inheritdoc}
*/
public function pull($name)
{
$value = $this->get($name);
$this->delete($name);
return $value;
}
/**
* {@inheritdoc}
*/
public function remember($name, $lifetime, $callback)
{
if (!$this->has($name)) {
$this->set($name, $value = call_user_func($callback), $lifetime);
return $value;
}
return $this->get($name);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Debug\Logger;
use Monolog\Handler\AbstractHandler;
/**
* Stores log messages in memory.
*/
class SharedHandler extends AbstractHandler
{
/**
* @var array
*/
protected $records = [];
/**
* {@inheritdoc}
*/
public function handle(array $record)
{
$this->records[] = $record;
//Passing
return false;
}
/**
* All collected records.
*
* @return array
*/
public function getRecords()
{
return $this->records;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler;
use Spiral\Stempler\Exceptions\LoaderExceptionInterface;
/**
* View loader interface. Pretty simple class which is compatible with Twig loader.
*/
interface LoaderInterface
{
/**
* Get local (includable) filename for given view name, needed to highlight errors (if any).
*
* @param string $path
* @return string
* @throws LoaderExceptionInterface
*/
public function localFilename($path);
/**
* Get source for given name.
*
* @param string $path
* @return string
* @throws LoaderExceptionInterface
*/
public function getSource($path);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Exceptions;
use Spiral\Core\Exceptions\RuntimeException;
/**
* Error by RecordIterator.
*/
class IteratorException extends RuntimeException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite\Schemas;
use Spiral\Database\Entities\Schemas\AbstractTable;
/**
* SQLIte specific table schema, some alter operations emulated using temporary tables.
*/
class TableSchema extends AbstractTable
{
/**
* {@inheritdoc}
*/
protected function loadColumns()
{
$tableSQL = $this->driver->query(
"SELECT sql FROM sqlite_master WHERE type = 'table' and name = ?", [$this->getName()]
)->fetchColumn();
/**
* There is not really many ways to get extra information about column in SQLite, let's parse
* table schema. As mention, spiral SQLite schema reader will support fully only tables created
* by spiral as we expecting every column definition be on new line.
*/
$tableStatement = explode("\n", $tableSQL);
$columnsQuery = $this->driver->query("PRAGMA TABLE_INFO({$this->getName(true)})");
$primaryKeys = [];
foreach ($columnsQuery as $column) {
if (!empty($column['pk'])) {
$primaryKeys[] = $column['name'];
}
$column['tableStatement'] = $tableStatement;
$this->registerColumn($this->columnSchema($column['name'], $column));
}
$this->setPrimaryKeys($primaryKeys);
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadIndexes()
{
$indexesQuery = $this->driver->query("PRAGMA index_list({$this->getName(true)})");
foreach ($indexesQuery as $index) {
$index = $this->registerIndex($this->indexSchema($index['name'], $index));
if ($index->getColumns() == $this->getPrimaryKeys()) {
$this->forgetIndex($index);
}
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadReferences()
{
$foreignsQuery = $this->driver->query("PRAGMA foreign_key_list({$this->getName(true)})");
foreach ($foreignsQuery as $reference) {
$this->registerReference($this->referenceSchema($reference['id'], $reference));
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function synchroniseSchema()
{
if (!$this->requiresRebuild()) {
//Probably some index changed or table renamed
return parent::synchroniseSchema();
}
$this->logger()->debug("Rebuilding table {table} to apply required modifications.", [
'table' => $this->getName(true)
]);
//Temporary table is required to copy data over
$temporary = $this->createTemporary();
//Moving data over
$this->copyData($temporary, $this->columnsMapping(true));
//Dropping current table
$this->commander->dropTable($this->initial->getName());
//Renaming temporary table (should automatically handle table renaming)
$this->commander->renameTable($temporary->getName(), $this->getName());
//We can create needed indexes now
foreach ($this->getIndexes() as $index) {
$this->commander->addIndex($this, $index);
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function columnSchema($name, $schema = null)
{
return new ColumnSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function indexSchema($name, $schema = null)
{
return new IndexSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function referenceSchema($name, $schema = null)
{
return new ReferenceSchema($this, $name, $schema);
}
/**
* Rebuild is required when columns or foreign keys are altered.
*
* @return bool
*/
private function requiresRebuild()
{
$difference = [
count($this->comparator->addedColumns()),
count($this->comparator->droppedColumns()),
count($this->comparator->alteredColumns()),
count($this->comparator->addedForeigns()),
count($this->comparator->droppedForeigns()),
count($this->comparator->alteredForeigns())
];
return array_sum($difference) != 0;
}
/**
* Temporary table.
*
* @return TableSchema
*/
private function createTemporary()
{
//Temporary table is required to copy data over
$temporary = clone $this;
$temporary->setName('spiral_temp_' . $this->getName() . '_' . uniqid());
//We don't need any index in temporary table
foreach ($temporary->getIndexes() as $index) {
$temporary->forgetIndex($index);
}
$this->commander->createTable($temporary);
return $temporary;
}
/**
* Copy table data to another location.
*
* @see http://stackoverflow.com/questions/4007014/alter-column-in-sqlite
* @param AbstractTable $temporary
* @param array $mapping Association between old and new columns (quoted).
*/
private function copyData(AbstractTable $temporary, array $mapping)
{
$this->logger()->debug(
"Copying table data from {source} to {table} using mapping ({columns}) => ({target}).",
[
'source' => $this->driver->identifier($this->initial->getName()),
'table' => $temporary->getName(true),
'columns' => join(', ', $mapping),
'target' => join(', ', array_keys($mapping))
]
);
$query = \Spiral\interpolate(
"INSERT INTO {table} ({target}) SELECT {columns} FROM {source}",
[
'source' => $this->driver->identifier($this->initial->getName()),
'table' => $temporary->getName(true),
'columns' => join(', ', $mapping),
'target' => join(', ', array_keys($mapping))
]
);
//Let's go
$this->driver->statement($query);
}
/**
* Get mapping between new and initial columns.
*
* @param bool $quoted
* @return array
*/
private function columnsMapping($quoted = false)
{
$current = $this->getColumns();
$initial = $this->initial->getColumns();
$mapping = [];
foreach ($current as $name => $column) {
if (isset($initial[$name])) {
$mapping[$column->getName($quoted)] = $initial[$name]->getName($quoted);
}
}
return $mapping;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite;
use Spiral\Database\DatabaseInterface;
use Spiral\Database\Drivers\SQLite\Schemas\Commander;
use Spiral\Database\Drivers\SQLite\Schemas\TableSchema;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Exceptions\DriverException;
/**
* Talks to sqlite databases.
*/
class SQLiteDriver extends Driver
{
/**
* Driver type.
*/
const TYPE = DatabaseInterface::SQLITE;
/**
* Driver schemas.
*/
const SCHEMA_TABLE = TableSchema::class;
/**
* Commander used to execute commands. :)
*/
const COMMANDER = Commander::class;
/**
* Query compiler class.
*/
const QUERY_COMPILER = QueryCompiler::class;
/**
* Default timestamp expression.
*/
const TIMESTAMP_NOW = 'CURRENT_TIMESTAMP';
/**
* Get driver source database or file name.
*
* @return string
* @throws DriverException
*/
public function getSource()
{
//Remove "sqlite:"
return substr($this->config['connection'], 7);
}
/**
* {@inheritdoc}
*/
public function hasTable($name)
{
$query = 'SELECT sql FROM sqlite_master WHERE type = \'table\' and name = ?';
return (bool)$this->query($query, [$name])->fetchColumn();
}
/**
* {@inheritdoc}
*/
public function truncate($table)
{
$this->statement("DELETE FROM {$this->identifier($table)}");
}
/**
* {@inheritdoc}
*/
public function tableNames()
{
$tables = [];
foreach ($this->query("SELECT * FROM sqlite_master WHERE type = 'table'") as $table) {
if ($table['name'] != 'sqlite_sequence') {
$tables[] = $table['name'];
}
}
return $tables;
}
/**
* {@inheritdoc}
*/
protected function isolationLevel($level)
{
$this->logger()->alert(
"Transaction isolation level is not fully supported by SQLite ({level}).",
compact('level')
);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Exceptions;
/**
* Exceptions raised by ORM selector.
*/
class SelectorException extends ORMException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres\Schemas;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Injections\Fragment;
/**
* Postgres column schema.
*/
class ColumnSchema extends AbstractColumn
{
/**
* {@inheritdoc}
*/
protected $mapping = [
//Primary sequences
'primary' => ['type' => 'serial', 'autoIncrement' => true, 'nullable' => false],
'bigPrimary' => ['type' => 'bigserial', 'autoIncrement' => true, 'nullable' => false],
//Enum type (mapped via method)
'enum' => 'enum',
//Logical types
'boolean' => 'boolean',
//Integer types (size can always be changed with size method), longInteger has method alias
//bigInteger
'integer' => 'integer',
'tinyInteger' => 'smallint',
'bigInteger' => 'bigint',
//String with specified length (mapped via method)
'string' => 'character varying',
//Generic types
'text' => 'text',
'tinyText' => 'text',
'longText' => 'text',
//Real types
'double' => 'double precision',
'float' => 'real',
//Decimal type (mapped via method)
'decimal' => 'numeric',
//Date and Time types
'datetime' => 'timestamp without time zone',
'date' => 'date',
'time' => 'time',
'timestamp' => 'timestamp without time zone',
//Binary types
'binary' => 'bytea',
'tinyBinary' => 'bytea',
'longBinary' => 'bytea',
//Additional types
'json' => 'json'
];
/**
* {@inheritdoc}
*/
protected $reverseMapping = [
'primary' => ['serial'],
'bigPrimary' => ['bigserial'],
'enum' => ['enum'],
'boolean' => ['boolean'],
'integer' => ['int', 'integer', 'int4'],
'tinyInteger' => ['smallint'],
'bigInteger' => ['bigint', 'int8'],
'string' => ['character varying', 'character'],
'text' => ['text'],
'double' => ['double precision'],
'float' => ['real', 'money'],
'decimal' => ['numeric'],
'date' => ['date'],
'time' => ['time', 'time with time zone', 'time without time zone'],
'timestamp' => ['timestamp', 'timestamp with time zone', 'timestamp without time zone'],
'binary' => ['bytea'],
'json' => ['json']
];
/**
* Field is auto incremental.
*
* @var bool
*/
protected $autoIncrement = false;
/**
* Name of enum constraint associated with field.
*
* @var string
*/
protected $enumConstraint = '';
/**
* {@inheritdoc}
*/
public function getConstraints()
{
$constraints = parent::getConstraints();
if (!empty($this->enumConstraint)) {
$constraints[] = $this->enumConstraint;
}
return $constraints;
}
/**
* {@inheritdoc}
*/
public function abstractType()
{
if (!empty($this->enumValues)) {
return 'enum';
}
return parent::abstractType();
}
/**
* {@inheritdoc}
*/
public function primary()
{
$this->autoIncrement = true;
//Changing type of already created primary key (we can't use "serial" alias here)
if (!empty($this->type) && $this->type != 'serial') {
$this->type = 'integer';
return $this;
}
return parent::primary();
}
/**
* {@inheritdoc}
*/
public function bigPrimary()
{
$this->autoIncrement = true;
//Changing type of already created primary key (we can't use "serial" alias here)
if (!empty($this->type) && $this->type != 'bigserial') {
$this->type = 'bigint';
return $this;
}
return parent::bigPrimary();
}
/**
* {@inheritdoc}
*/
public function enum($values)
{
$this->enumValues = array_map('strval', is_array($values) ? $values : func_get_args());
$this->type = 'character';
foreach ($this->enumValues as $value) {
$this->size = max((int)$this->size, strlen($value));
}
return $this;
}
/**
* {@inheritdoc}
*/
public function sqlStatement()
{
$statement = parent::sqlStatement();
if ($this->abstractType() != 'enum') {
return $statement;
}
//We have add constraint for enum type
$enumValues = [];
foreach ($this->enumValues as $value) {
$enumValues[] = $this->table->driver()->getPDO()->quote($value);
}
return "$statement CONSTRAINT {$this->enumConstraint(true, true)} "
. "CHECK ({$this->getName(true)} IN (" . join(', ', $enumValues) . "))";
}
/**
* Generate set of altering operations should be applied to column to change it's type, size,
* default value or null flag.
*
* @param AbstractColumn $original
* @return array
*/
public function alteringOperations(AbstractColumn $original)
{
$operations = [];
$typeDefinition = [$this->type, $this->size, $this->precision, $this->scale];
$originalType = [$original->type, $original->size, $original->precision, $original->scale];
if ($typeDefinition != $originalType) {
if ($this->abstractType() == 'enum') {
//Getting longest value
$enumSize = $this->size;
foreach ($this->enumValues as $value) {
$enumSize = max($enumSize, strlen($value));
}
$type = "ALTER COLUMN {$this->getName(true)} TYPE character($enumSize)";
$operations[] = $type;
} else {
$type = "ALTER COLUMN {$this->getName(true)} TYPE {$this->type}";
if (!empty($this->size)) {
$type .= "($this->size)";
} elseif (!empty($this->precision)) {
$type .= "($this->precision, $this->scale)";
}
//Required to perform cross conversion
$operations[] = "{$type} USING {$this->getName(true)}::{$this->type}";
}
}
if ($original->abstractType() == 'enum' && !empty($this->enumConstraint)) {
$operations[] = 'DROP CONSTRAINT ' . $this->enumConstraint(true);
}
if ($original->defaultValue != $this->defaultValue) {
if (is_null($this->defaultValue)) {
$operations[] = "ALTER COLUMN {$this->getName(true)} DROP DEFAULT";
} else {
$operations[] = "ALTER COLUMN {$this->getName(true)} SET DEFAULT {$this->prepareDefault()}";
}
}
if ($original->nullable != $this->nullable) {
$operations[] = "ALTER COLUMN {$this->getName(true)} "
. (!$this->nullable ? 'SET' : 'DROP') . " NOT NULL";
}
if ($this->abstractType() == 'enum') {
$enumValues = [];
foreach ($this->enumValues as $value) {
$enumValues[] = $this->table->driver()->getPDO()->quote($value);
}
$operations[] = "ADD CONSTRAINT {$this->enumConstraint(true)} "
. "CHECK ({$this->getName(true)} IN (" . join(', ', $enumValues) . "))";
}
return $operations;
}
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->type = $schema['data_type'];
$this->defaultValue = $schema['column_default'];
$this->nullable = $schema['is_nullable'] == 'YES';
if (
in_array($this->type, ['int', 'bigint', 'integer'])
&& preg_match("/nextval(.*)/", $this->defaultValue)
) {
$this->type = ($this->type == 'bigint' ? 'bigserial' : 'serial');
$this->autoIncrement = true;
$this->defaultValue = new Fragment($this->defaultValue);
return;
}
if (
($this->type == 'character varying' || $this->type == 'character')
&& $schema['character_maximum_length']
) {
$this->size = $schema['character_maximum_length'];
}
if ($this->type == 'numeric') {
$this->precision = $schema['numeric_precision'];
$this->scale = $schema['numeric_scale'];
}
/**
* Attention, this is not default spiral enum type emulated via CHECK. This is real Postgres
* enum type.
*/
if ($this->type == 'USER-DEFINED' && $schema['typtype'] == 'e') {
$this->type = $schema['typname'];
$this->resolveNativeEnum();
}
//Potential enum with manually created constraint (check in)
if (
($this->type == 'character' || $this->type == 'character varying')
&& !empty($this->size)
) {
$this->checkCheckConstrain($schema['tableOID']);
}
$this->normalizeDefault();
}
/**
* {@inheritdoc}
*/
protected function prepareEnum()
{
return '(' . $this->size . ')';
}
/**
* Get name of enum constraint.
*
* @param bool $quote
* @param bool $temporary If true enumConstraint identifier will be generated only for visual
* purposes only.
* @return string
*/
private function enumConstraint($quote = false, $temporary = false)
{
if (empty($this->enumConstraint)) {
if ($temporary) {
return $this->table->getName() . '_' . $this->getName() . '_enum';
}
$this->enumConstraint = $this->table->getName() . '_' . $this->getName() . '_enum_' . uniqid();
}
return $quote ? $this->table->driver()->identifier($this->enumConstraint) : $this->enumConstraint;
}
/**
* Normalize default value.
*/
private function normalizeDefault()
{
if ($this->hasDefaultValue()) {
if (preg_match("/^'?(.*?)'?::(.+)/", $this->defaultValue, $matches)) {
//In database: 'value'::TYPE
$this->defaultValue = $matches[1];
} elseif ($this->type == 'bit') {
$this->defaultValue = bindec(
substr($this->defaultValue, 2, strpos($this->defaultValue, '::') - 3)
);
} elseif ($this->type == 'boolean') {
$this->defaultValue = (strtolower($this->defaultValue) == 'true');
}
}
}
/**
* Resolve native enum type.
**/
private function resolveNativeEnum()
{
$range = $this->table->driver()->query(
'SELECT enum_range(NULL::' . $this->type . ')'
)->fetchColumn(0);
$this->enumValues = explode(',', substr($range, 1, -1));
if (!empty($this->defaultValue)) {
//In database: 'value'::enumType
$this->defaultValue = substr(
$this->defaultValue,
1,
strpos($this->defaultValue, $this->type) - 4
);
}
}
/**
* Check if column was declared with check constrain. I love name of this method.
*
* @param string $tableOID
*/
private function checkCheckConstrain($tableOID)
{
$query = "SELECT conname, consrc FROM pg_constraint "
. "WHERE conrelid = ? AND contype = 'c' AND (consrc LIKE ? OR consrc LIKE ?)";
$constraints = $this->table->driver()->query(
$query, [$tableOID, '(' . $this->name . '%', '("' . $this->name . '%',]
);
foreach ($constraints as $constraint) {
if (preg_match('/ARRAY\[([^\]]+)\]/', $constraint['consrc'], $matches)) {
$enumValues = explode(',', $matches[1]);
foreach ($enumValues as &$value) {
if (preg_match("/^'?(.*?)'?::(.+)/", trim($value), $matches)) {
//In database: 'value'::TYPE
$value = $matches[1];
}
unset($value);
}
$this->enumValues = $enumValues;
$this->enumConstraint = $constraint['conname'];
}
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Debug\Traits;
use Interop\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Spiral\Debug\LogsInterface;
/**
* On demand logger creation. Allows class to share same logger between instances.
*/
trait LoggerTrait
{
/**
* @var LoggerInterface[]
*/
private static $loggers = [];
/**
* Private and null.
*
* @var LoggerInterface|null
*/
private $logger = null;
/**
* Sets a logger.
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Set class specific logger (associated with every instance).
*
* @param LoggerInterface $logger
*/
public static function shareLogger(LoggerInterface $logger)
{
self::$loggers[static::class] = $logger;
}
/**
* Get associated or create new instance of LoggerInterface.
*
* @return LoggerInterface
*/
protected function logger()
{
if (!empty($this->logger)) {
return $this->logger;
}
if (!empty(self::$loggers[static::class])) {
return self::$loggers[static::class];
}
//We are using class name as log channel (name) by default
return self::$loggers[static::class] = $this->createLogger();
}
/**
* Create new instance of associated logger.
*
* @return LoggerInterface
*/
protected function createLogger()
{
if (empty($container = $this->container()) || !$container->has(LogsInterface::class)) {
return new NullLogger();
}
//We are using class name as log channel (name) by default
return $container->get(LogsInterface::class)->getLogger(static::class);
}
/**
* @return ContainerInterface
*/
abstract protected function container();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Encrypter;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Encrypter\Exceptions\DecryptException;
use Spiral\Encrypter\Exceptions\EncrypterException;
/**
* Default implementation of spiral encrypter.
*
* @todo found some references to old mcrypt, to remove them
*/
class Encrypter extends Component implements EncrypterInterface, InjectableInterface
{
/**
* Injection is dedicated to outer class since Encrypter is pretty simple.
*/
const INJECTOR = EncrypterManager::class;
/**
* Keys to use in packed data. This is internal constants.
*/
const IV = 'a';
const DATA = 'b';
const SIGNATURE = 'c';
/**
* @var string
*/
private $key = '';
/**
* One of the openssl cipher values, or the name of the algorithm as string.
*
* @var string
*/
private $cipher = 'aes-256-cbc';
/**
* Encrypter constructor.
*
* @param string $key
* @param string $cipher
*/
public function __construct($key, $cipher = 'aes-256-cbc')
{
$this->setKey($key);
if (!empty($cipher)) {
//We are allowing to skip definition of cipher to be used
$this->cipher = $cipher;
}
}
/**
* {@inheritdoc}
*/
public function setKey($key)
{
$this->key = (string)$key;
return $this;
}
/**
* {@inheritdoc}
*/
public function getKey()
{
return $this->key;
}
/**
* Change encryption method. One of MCRYPT_CIPERNAME constants.
*
* @param string $cipher
* @return $this
*/
public function setCipher($cipher)
{
$this->cipher = $cipher;
return $this;
}
/**
* @return string
*/
public function getCipher()
{
return $this->cipher;
}
/**
* {@inheritdoc}
*
* @param bool $passWeak Do not throw an exception if result is "weak". Not recommended.
*/
public function random($length, $passWeak = false)
{
if ($length < 1) {
throw new EncrypterException("Random string length should be at least 1 byte long.");
}
if (!$result = openssl_random_pseudo_bytes($length, $cryptoStrong)) {
throw new EncrypterException(
"Unable to generate pseudo-random string with {$length} length."
);
}
if (!$passWeak && !(bool)$cryptoStrong) {
throw new EncrypterException("Weak random result received.");
}
return $result;
}
/**
* {@inheritdoc}
*
* Data encoded using json_encode method, only supported formats are allowed!
*/
public function encrypt($data)
{
if (empty($this->key)) {
throw new EncrypterException("Encryption key should not be empty.");
}
$vector = $this->createIV(openssl_cipher_iv_length($this->cipher));
try{
$serialized = json_encode($data);
} catch (\ErrorException $e){
throw new EncrypterException("Unsupported data format", null, $e);
}
$encrypted = openssl_encrypt(
$serialized,
$this->cipher,
$this->key,
false,
$vector
);
$result = json_encode([
self::IV => ($vector = bin2hex($vector)),
self::DATA => $encrypted,
self::SIGNATURE => $this->sign($encrypted, $vector)
]);
return base64_encode($result);
}
/**
* {@inheritdoc}
*
* json_decode with assoc flag set to true
*/
public function decrypt($payload)
{
try {
$payload = json_decode(base64_decode($payload), true);
if (empty($payload) || !is_array($payload)) {
throw new DecryptException("Invalid dataset.");
}
assert(!empty($payload[self::IV]));
assert(!empty($payload[self::DATA]));
assert(!empty($payload[self::SIGNATURE]));
} catch (\ErrorException $exception) {
throw new DecryptException("Unable to unpack provided data.");
}
//Verifying signature
if ($payload[self::SIGNATURE] !== $this->sign($payload[self::DATA], $payload[self::IV])) {
throw new DecryptException("Encrypted data does not have valid signature.");
}
try {
$decrypted = openssl_decrypt(
base64_decode($payload[self::DATA]),
$this->cipher,
$this->key,
true,
hex2bin($payload[self::IV])
);
return json_decode($decrypted, true);
} catch (\ErrorException $exception) {
throw new DecryptException($exception->getMessage(), $exception->getCode());
}
}
/**
* Sign string using private key.
*
* @param string $string
* @param string $salt
* @return string
*/
public function sign($string, $salt = null)
{
//todo: double check if this is good idea
return hash_hmac('sha256', $string . ($salt ? ':' . $salt : ''), $this->key);
}
/**
* Create an initialization vector (IV) from a random source with specified size.
*
* @param int $length
* @return string
*/
private function createIV($length = 16)
{
return !empty($length) ? $this->random($length, false) : '';
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Events;
use Symfony\Component\EventDispatcher\Event;
/**
* Raised after validation.
*/
class ValidatedEvent extends Event
{
/**
* Validation errors if any.
*
* @var array
*/
private $errors = [];
/**
* @param array $errors
*/
public function __construct(array $errors)
{
$this->errors = $errors;
}
/**
* @return bool
*/
public function hasErrors()
{
return !empty($this->errors);
}
/**
* @param array $errors
*/
public function setErrors($errors)
{
$this->errors = $errors;
}
/**
* @return array
*/
public function getErrors()
{
return $this->errors;
}
}<file_sep>Spiral Core Components
================================
[](https://packagist.org/packages/spiral/components) [](https://packagist.org/packages/spiral/components) [](https://packagist.org/packages/spiral/components)
[](https://travis-ci.org/spiral/components)
[](https://scrutinizer-ci.com/g/spiral/components/?branch=master) [](https://gitter.im/spiral/hotline)
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Traits;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\Entities\RecordSource;
use Spiral\ORM\Exceptions\ORMException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* Static record functionality including create and find methods.
*/
trait FindTrait
{
/**
* Find multiple records based on provided query.
*
* Example:
* User::find(['status' => 'active'], ['profile']);
*
* @param array $where Selection WHERE statement.
* @param array $load Array or relations to be pre-loaded.
* @return RecordSelector
*/
public static function find($where = [], array $load = [])
{
return static::source()->find($where)->load($load);
}
/**
* Fetch one record based on provided query or return null. Use second argument to specify
* relations to be loaded.
*
* Example:
* User::findOne(['name' => 'Wolfy-J'], ['profile'], ['id' => 'DESC']);
*
* @param array $where Selection WHERE statement.
* @param array $load Array or relations to be pre-loaded.
* @param array $orderBy Sort by conditions.
* @return RecordEntity|null
*/
public static function findOne($where = [], array $load = [], array $orderBy = [])
{
$source = static::find($where, $load);
foreach ($orderBy as $column => $direction) {
$source->orderBy($column, $direction);
}
return $source->findOne();
}
/**
* Find record using it's primary key. Relation data can be preloaded with found record.
*
* Example:
* User::findByID(1, ['profile']);
*
* @param mixed $primaryKey Primary key.
* @param array $load Array or relations to be pre-loaded.
* @return RecordEntity|null
*/
public static function findByPK($primaryKey, array $load = [])
{
return static::source()->find()->load($load)->findByPK($primaryKey);
}
/**
* Instance of ORM Selector associated with specific document.
*
* @see Component::staticContainer()
* @param ORM $orm ORM component, global container will be called if not instance provided.
* @return RecordSource
* @throws ORMException
*/
public static function source(ORM $orm = null)
{
/**
* Using global container as fallback.
*
* @var ORM $orm
*/
if (empty($orm)) {
//Using global container as fallback
$orm = self::staticContainer()->get(ORM::class);
}
return $orm->source(static::class);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Encrypter\Configs;
use Spiral\Core\InjectableConfig;
/**
* Encrypter configuration.
*/
class EncrypterConfig extends InjectableConfig
{
/**
* Configuration section.
*/
const CONFIG = 'encrypter';
/**
* Default algorythm.
*/
const DEFAULT_CIPHER = 'aes-256-cbc';
/**
* @var array
*/
protected $config = [
'key' => '',
'cipher' => ''
];
/**
* @return string
*/
public function getKey()
{
return $this->config['key'];
}
/**
* @return string
*/
public function getCipher()
{
if (empty($this->config['cipher'])) {
return static::DEFAULT_CIPHER;
}
return $this->config['cipher'];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
use Spiral\Models\Exceptions\FieldExceptionInterface;
/**
* When field can not be set or get.
*/
class FieldException extends DocumentException implements FieldExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Entities;
use Spiral\Core\Container\InjectableInterface;
use Spiral\ODM\ODM;
/**
* Simple spiral ODM wrapper at top of MongoDB.
*/
class MongoDatabase extends \MongoDB implements InjectableInterface
{
/**
* This is magick constant used by Spiral Container, it helps system to resolve controllable
* injections.
*/
const INJECTOR = ODM::class;
/**
* Profiling levels. Not identical to MongoDB profiling levels.
*/
const PROFILE_DISABLED = false;
const PROFILE_SIMPLE = 1;
const PROFILE_EXPLAIN = 2;
/**
* @var string
*/
private $name = '';
/**
* @var \Mongo|\MongoClient
*/
private $connection = null;
/**
* @var array
*/
protected $config = ['profiling' => self::PROFILE_DISABLED];
/**
* @invisible
* @var ODM
*/
protected $odm = null;
/**
* @param ODM $odm
* @param string $name
* @param array $config
*/
public function __construct(ODM $odm, $name, array $config)
{
$this->odm = $odm;
$this->name = $name;
$this->config = $config + $this->config;
//Selecting client
if (class_exists('MongoClient', false)) {
$this->connection = new \MongoClient($this->config['server'], $this->config['options']);
} else {
$this->connection = new \Mongo($this->config['server'], $this->config['options']);
}
parent::__construct($this->connection, $this->config['database']);
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* While profiling enabled driver will create query logging and benchmarking events. This is
* recommended option in* development environments. Profiling will be applied for ODM Collection
* queries only.
*
* @param bool|int $profiling Enable or disable driver profiling.
* @return $this
*/
public function setProfiling($profiling = self::PROFILE_SIMPLE)
{
$this->config['profiling'] = $profiling;
return $this;
}
/**
* Check if profiling mode is enabled.
*
* @return bool
*/
public function isProfiling()
{
return $this->config['profiling'] != self::PROFILE_DISABLED;
}
/**
* Get database profiling. Not identical to getProfilingLevel().
*
* @return int
*/
public function getProfiling()
{
return $this->config['profiling'];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core;
use Interop\Container\ContainerInterface;
use ReflectionFunctionAbstract as ContextFunction;
use Spiral\Core\Container\Context;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\Exceptions\Container\ArgumentException;
use Spiral\Core\Exceptions\Container\AutowireException;
use Spiral\Core\Exceptions\Container\ContainerException;
use Spiral\Core\Exceptions\Container\InjectionException;
/**
* Super simple auto-wiring container with auto SINGLETON and INJECTOR constants integration.
* Compatible with Container Interop.
*
* Container does not support setter injections, private properties and etc. Normally it will work
* with classes only.
*
* @see InjectableInterface
* @see SingletonInterface
*
* @todo polish parent usage in make method
*/
class Container extends Component implements ContainerInterface, FactoryInterface, ResolverInterface
{
/**
* IoC bindings.
*
* @invisible
* @var array
*/
protected $bindings = [];
/**
* Registered injectors.
*
* @invisible
* @var array
*/
protected $injectors = [];
/**
* {@inheritdoc}
*/
public function has($alias)
{
return isset($this->bindings[$alias]);
}
/**
* {@inheritdoc}
*
* Context parameter will be passed to class injectors, which makes possible to use this method
* as:
* $this->container->get(DatabaseInterface::class, 'default');
*
* @param string|null $context Call context.
*/
public function get($alias, $context = null)
{
//Direct bypass to construct, i might think about this option... or not.
return $this->make($alias, [], $context);
}
/**
* {@inheritdoc}
*
* @param string|null $context Related to parameter caused injection if any.
*/
public function make($class, $parameters = [], $context = null)
{
if (!isset($this->bindings[$class])) {
return $this->autowire($class, $parameters, $context);
}
if ($class == ContainerInterface::class && empty($parameters)) {
//self wrapping
return $this;
}
if (is_object($binding = $this->bindings[$class])) {
//Singleton
return $binding;
}
if (is_string($binding)) {
//Binding is pointing to something else
return $this->make($binding, $parameters, $context);
}
if (is_array($binding)) {
if (is_string($binding[0])) {
//Class name
$instance = $this->make($binding[0], $parameters, $context);
} elseif ($binding[0] instanceof \Closure) {
$reflection = new \ReflectionFunction($binding[0]);
//Invoking Closure
$instance = $reflection->invokeArgs(
$this->resolveArguments($reflection, $parameters)
);
} elseif (is_array($binding[0])) {
//In a form of resolver and method
list($resolver, $method) = $binding[0];
$method = new \ReflectionMethod($resolver = $this->get($resolver), $method);
$instance = $method->invokeArgs(
$resolver, $this->resolveArguments($method, $parameters)
);
} else {
throw new ContainerException("Invalid binding.");
}
if ($binding[1]) {
//Singleton
$this->bindings[$class] = $instance;
}
return $instance;
}
return null;
}
/**
* {@inheritdoc}
*/
public function resolveArguments(ContextFunction $reflection, array $parameters = [])
{
$arguments = [];
foreach ($reflection->getParameters() as $parameter) {
$name = $parameter->getName();
try {
$class = $parameter->getClass();
} catch (\ReflectionException $exception) {
throw new ContainerException(
$exception->getMessage(),
$exception->getCode(),
$exception
);
}
if ($class === Context::class) {
$arguments[] = new Context($reflection, $parameter);
continue;
}
if (empty($class)) {
if (array_key_exists($name, $parameters)) {
//Scalar value supplied by user
$arguments[] = $parameters[$name];
continue;
}
if ($parameter->isDefaultValueAvailable()) {
//Or default value?
$arguments[] = $parameter->getDefaultValue();
continue;
}
//Unable to resolve scalar argument value
throw new ArgumentException($parameter, $reflection);
}
if (isset($parameters[$name]) && is_object($parameters[$name])) {
//Supplied by user
$arguments[] = $parameters[$name];
continue;
}
try {
//Trying to resolve dependency (contextually)
$arguments[] = $this->get($class->getName(), $parameter->getName());
continue;
} catch (AutowireException $exception) {
if ($parameter->isDefaultValueAvailable()) {
//Let's try to use default value instead
$arguments[] = $parameter->getDefaultValue();
continue;
}
throw $exception;
}
}
return $arguments;
}
/**
* {@inheritdoc}
*
* @return $this
*/
public function bind($alias, $resolver)
{
if (is_array($resolver) || $resolver instanceof \Closure) {
$this->bindings[$alias] = [$resolver, false];
return $this;
}
$this->bindings[$alias] = $resolver;
return $this;
}
/**
* {@inheritdoc}
*
* @return $this
*/
public function bindSingleton($alias, $resolver)
{
if (is_object($resolver) && !$resolver instanceof \Closure) {
$this->bindings[$alias] = $resolver;
return $this;
}
$this->bindings[$alias] = [$resolver, true];
return $this;
}
/**
* {@inheritdoc}
*
* @return $this
*/
public function bindInjector($class, $injector)
{
$this->injectors[$class] = $injector;
return $this;
}
/**
* {@inheritdoc}
*/
public function replace($alias, $resolver)
{
$payload = [$alias, null];
if (isset($this->bindings[$alias])) {
$payload[1] = $this->bindings[$alias];
}
$this->bind($alias, $resolver);
return $payload;
}
/**
* {@inheritdoc}
*/
public function restore($replacePayload)
{
list($alias, $resolver) = $replacePayload;
unset($this->bindings[$alias]);
if (!empty($resolver)) {
//Restoring original value
$this->bindings[$alias] = $replacePayload;
}
}
/**
* {@inheritdoc}
*/
public function hasInstance($alias)
{
if (!$this->has($alias)) {
return false;
}
//Cross bindings
while (isset($this->bindings[$alias]) && is_string($this->bindings[$alias])) {
$alias = $this->bindings[$alias];
}
return isset($this->bindings[$alias]) && is_object($this->bindings[$alias]);
}
/**
* {@inheritdoc}
*/
public function removeBinding($alias)
{
unset($this->bindings[$alias]);
}
/**
* Every declared Container binding. Must not be used in production code due container format is
* vary.
*
* @return array
*/
public function getBindings()
{
return $this->bindings;
}
/**
* Every binded injector.
*
* @return array
*/
public function getInjectors()
{
return $this->injectors;
}
/**
* Automatically create class.
*
* @param string $class
* @param array $parameters
* @param string $context
* @return object
* @throws AutowireException
*/
protected function autowire($class, array $parameters, $context)
{
if (!class_exists($class)) {
throw new AutowireException("Undefined class or binding '{$class}'.");
}
//OK, we can create class by ourselves
$instance = $this->createInstance($class, $parameters, $context, $reflector);
/**
* Only for classes which are constructed using autowiring, SINGLETON logic can be rewritten
* or disabled using custom binding or factory.
*
* @var \ReflectionClass $reflector
*/
if (
$instance instanceof SingletonInterface
&& !empty($singleton = $reflector->getConstant('SINGLETON'))
) {
//Component declared SINGLETON constant, binding as constant value and class name.
$this->bindings[$singleton] = $instance;
}
return $instance;
}
/**
* Check if given class has associated injector.
*
* @param \ReflectionClass $reflection
* @return bool
*/
protected function hasInjector(\ReflectionClass $reflection)
{
if (isset($this->injectors[$reflection->getName()])) {
return true;
}
return $reflection->isSubclassOf(InjectableInterface::class);
}
/**
* Get injector associated with given class.
*
* @param \ReflectionClass $reflection
* @return InjectorInterface
*/
protected function getInjector(\ReflectionClass $reflection)
{
if (isset($this->injectors[$reflection->getName()])) {
return $this->get($this->injectors[$reflection->getName()]);
}
return $this->get($reflection->getConstant('INJECTOR'));
}
/**
* Create instance of desired class.
*
* @param string $class
* @param array $parameters Constructor parameters.
* @param string|null $context
* @param \ReflectionClass $reflection Instance of reflection associated with class,
* reference.
* @return object
* @throws ContainerException
*/
private function createInstance(
$class,
array $parameters,
$context = null,
\ReflectionClass &$reflection = null
) {
try {
$reflection = new \ReflectionClass($class);
} catch (\ReflectionException $exception) {
throw new ContainerException(
$exception->getMessage(), $exception->getCode(), $exception
);
}
//We have to construct class using external injector
if (empty($parameters) && $this->hasInjector($reflection)) {
//Creating class using injector/factory
$instance = $this->getInjector($reflection)->createInjection(
$reflection,
$context
);
if (!$reflection->isInstance($instance)) {
throw new InjectionException("Invalid injector response.");
}
//todo: potentially to be replaced with direct call logic (when method is specified
//todo: instead of class/binding name)
return $instance;
}
if (!$reflection->isInstantiable()) {
throw new ContainerException("Class '{$class}' can not be constructed.");
}
if (!empty($constructor = $reflection->getConstructor())) {
//Using constructor with resolved arguments
$instance = $reflection->newInstanceArgs(
$this->resolveArguments($constructor, $parameters)
);
} else {
//No constructor specified
$instance = $reflection->newInstance();
}
return $instance;
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Translator\Traits;
use Interop\Container\ContainerInterface;
use Spiral\Core\Container;
use Spiral\Translator\TranslatorInterface;
/**
* Add bundle specific translation functionality, class name will be used as translation bundle.
* In addition every default string message declared in class using [[]] braces can be indexed by
* spiral application.
*/
trait TranslatorTrait
{
/**
* Translate message using parent class as bundle name. Method will remove string braces ([[ and
* ]]) if specified.
*
* Example: $this->say("User account is invalid.");
*
* @param string $string
* @param array $options Interpolation options.
* @return string
*/
protected function say($string, array $options = [])
{
if (
substr($string, 0, 2) === TranslatorInterface::I18N_PREFIX
&& substr($string, -2) === TranslatorInterface::I18N_POSTFIX
) {
//This string was defined in class attributes
$string = substr($string, 2, -2);
}
if (empty($container = $this->container()) || !$container->has(TranslatorInterface::class)) {
//No translator available
return $string;
}
/**
* Potentially can be downgraded to Symfony\TranslatorInterface but without domains map
* feature
*
* @var TranslatorInterface $translator
*/
$translator = $container->get(TranslatorInterface::class);
//Translate class string using automatically resolved message domain
return $translator->trans($string, $options, $translator->resolveDomain(static::class));
}
/**
* @return ContainerInterface
*/
abstract protected function container();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL;
use Spiral\Database\Entities\QueryCompiler as AbstractCompiler;
use Spiral\Database\Injections\ParameterInterface;
/**
* MySQL syntax specific compiler.
*/
class QueryCompiler extends AbstractCompiler
{
/**
* {@inheritdoc}
*/
public function orderParameters(
$queryType,
array $whereParameters = [],
array $onParameters = [],
array $havingParameters = [],
array $columnIdentifiers = []
) {
if ($queryType == self::UPDATE_QUERY) {
//Where statement has pretty specific order
return array_merge($onParameters, $columnIdentifiers, $whereParameters);
}
return parent::orderParameters(
$queryType,
$whereParameters,
$onParameters,
$havingParameters,
$columnIdentifiers
);
}
/**
* {@inheritdoc}
*
* @link http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990
*/
protected function compileLimit($limit, $offset)
{
if (empty($limit) && empty($offset)) {
return '';
}
$statement = '';
if (!empty($limit) || !empty($offset)) {
//When limit is not provided but offset does we can replace limit value with PHP_INT_MAX
$statement = "LIMIT " . ($limit ?: '18446744073709551615') . ' ';
}
if (!empty($offset)) {
$statement .= "OFFSET {$offset}";
}
return trim($statement);
}
/**
* Resolve operator value based on value value. ;)
*
* @param mixed $parameter
* @param string $operator
* @return string
*/
protected function prepareOperator($parameter, $operator)
{
if (!$parameter instanceof ParameterInterface) {
//Probably fragment
return $operator;
}
if ($parameter->getType() == \PDO::PARAM_NULL) {
switch ($operator) {
case '=':
return 'IS';
case '!=':
return 'IS NOT';
}
}
return parent::prepareOperator($parameter, $operator);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres\Schemas;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Entities\Schemas\AbstractCommander;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Exceptions\SchemaException;
class Commander extends AbstractCommander
{
/**
* {@inheritdoc}
*/
public function alterColumn(
AbstractTable $table,
AbstractColumn $initial,
AbstractColumn $column
) {
if (!$initial instanceof ColumnSchema || !$column instanceof ColumnSchema) {
throw new SchemaException("Postgres commander can work only with Postgres columns.");
}
//Rename is separate operation
if ($column->getName() != $initial->getName()) {
$this->renameColumn($table, $initial, $column);
//This call is required to correctly built set of alter operations
$initial->setName($column->getName());
}
//Postgres columns should be altered using set of operations
if (!$operations = $column->alteringOperations($initial)) {
return $this;
}
//Postgres columns should be altered using set of operations
$query = \Spiral\interpolate('ALTER TABLE {table} {operations}', [
'table' => $table->getName(true),
'operations' => trim(join(', ', $operations), ', ')
]);
$this->run($query);
return $this;
}
/**
* @param AbstractTable $table
* @param ColumnSchema $initial
* @param ColumnSchema $column
*/
private function renameColumn(AbstractTable $table, ColumnSchema $initial, ColumnSchema $column)
{
$statement = \Spiral\interpolate('ALTER TABLE {table} RENAME COLUMN {column} TO {name}', [
'table' => $table->getName(true),
'column' => $initial->getName(true),
'name' => $column->getName(true)
]);
$this->run($statement);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database;
use Spiral\Database\Exceptions\DatabaseException;
/**
* Databases factory/manager.
*/
interface DatabasesInterface
{
/**
* Create specified or select default instance of DatabaseInterface.
*
* @param string $database Database alias.
* @return DatabaseInterface
* @throws DatabaseException
*/
public function database($database = null);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Events\Traits;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Event trait utilized Symfony\Events dispatcher to add class (not instance) specific dispatcher.
*/
trait EventsTrait
{
/**
* @var EventDispatcherInterface[]
*/
private static $dispatchers = [];
/**
* Set event dispatchers manually for current class. Can erase existed dispatcher by providing
* null as value.
*
* @param EventDispatcherInterface|null $dispatcher
*/
public static function setEvents(EventDispatcherInterface $dispatcher = null)
{
self::$dispatchers[static::class] = $dispatcher;
}
/**
* Get class associated event dispatcher or create default one.
*
* @return EventDispatcherInterface
*/
public static function events()
{
if (isset(self::$dispatchers[static::class])) {
return self::$dispatchers[static::class];
}
return self::$dispatchers[static::class] = new EventDispatcher();
}
/**
* Dispatch event. If no dispatched associated even will be returned without dispatching.
*
* @param string $name Event name.
* @param Event|null $event Event class if any.
* @return Event
*/
protected function dispatch($name, Event $event = null)
{
if (empty(self::$dispatchers[static::class])) {
//We can bypass dispatcher creation
return $event;
}
return static::events()->dispatch($name, $event);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer;
use Psr\Log\LoggerAwareInterface;
use Spiral\Database\Entities\QueryCompiler as AbstractCompiler;
use Spiral\Database\Entities\Quoter;
use Spiral\Database\Injections\Fragment;
use Spiral\Debug\Traits\LoggerTrait;
/**
* Microsoft SQL server specific syntax compiler.
*/
class QueryCompiler extends AbstractCompiler implements LoggerAwareInterface
{
/**
* There is few warning notices.
*/
use LoggerTrait;
/**
* @var SQLServerDriver
*/
protected $driver = null;
/**
* @param SQLServerDriver $driver
* @param Quoter $quoter
*/
public function __construct(SQLServerDriver $driver, Quoter $quoter)
{
parent::__construct($driver, $quoter);
}
/**
* {@inheritdoc}
*
* Attention, limiting and ordering UNIONS will fail in SQL SERVER < 2012.
* For future upgrades: think about using top command.
*
* @link http://stackoverflow.com/questions/603724/how-to-implement-limit-with-microsoft-sql-server
* @link http://stackoverflow.com/questions/971964/limit-10-20-in-sql-server
*/
public function compileSelect(
array $fromTables,
$distinct,
array $columns,
array $joinsStatement = [],
array $whereTokens = [],
array $havingTokens = [],
array $grouping = [],
array $ordering = [],
$limit = 0,
$offset = 0,
array $unionTokens = []
) {
if (
empty($limit) && empty($offset)
|| ($this->driver->serverVersion() >= 12 && !empty($ordering))
) {
//When no limits are specified we can use normal query syntax
return call_user_func_array(['parent', 'compileSelect'], func_get_args());
}
if ($this->driver->serverVersion() >= 12) {
$this->logger()->warning(
"You can't use query limiting without specifying ORDER BY statement, sql fallback used."
);
} else {
$this->logger()->warning(
"You are using older version of SQLServer, "
. "it has some limitation with query limiting and unions."
);
}
if (!empty($ordering)) {
$ordering = "ORDER BY {$this->compileOrdering($ordering)}";
} else {
$ordering = "ORDER BY (SELECT NULL)";
}
//Will be removed by QueryResult
$columns[] = new Fragment(
"ROW_NUMBER() OVER ($ordering) AS {$this->quote(QueryResult::ROW_NUMBER_COLUMN)}"
);
//Let's compile MOST of our query :)
$selection = parent::compileSelect(
$fromTables,
$distinct,
$columns,
$joinsStatement,
$whereTokens,
$havingTokens,
$grouping,
[],
0, //No limit or offset
0, //No limit or offset
$unionTokens
);
$limitStatement = $this->compileLimit($limit, $offset, QueryResult::ROW_NUMBER_COLUMN);
return "SELECT * FROM (\n{$selection}\n) AS [selection_alias] {$limitStatement}";
}
/**
* {@inheritdoc}
*
* @link http://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server
*/
protected function compileLimit($limit, $offset, $rowNumber = null)
{
if (empty($limit) && empty($offset)) {
return '';
}
//Modern SQLServer are easier to work with
if (empty($rowNumber) && $this->driver->serverVersion() >= 12) {
$statement = "OFFSET {$offset} ROWS ";
if (!empty($limit)) {
$statement .= "FETCH NEXT {$limit} ROWS ONLY";
}
return trim($statement);
}
$statement = "WHERE {$this->quote($rowNumber)} ";
//0 = row_number(1)
$offset = $offset + 1;
if (!empty($limit)) {
$statement .= "BETWEEN {$offset} AND " . ($offset + $limit - 1);
} else {
$statement .= ">= {$offset}";
}
return $statement;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Exceptions;
/**
* Errors related to field setting.
*/
interface FieldExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL;
use PDO;
use Spiral\Database\DatabaseInterface;
use Spiral\Database\Drivers\MySQL\Schemas\Commander;
use Spiral\Database\Drivers\MySQL\Schemas\TableSchema;
use Spiral\Database\Entities\Driver;
/**
* Talks to mysql databases.
*/
class MySQLDriver extends Driver
{
/**
* Driver type.
*/
const TYPE = DatabaseInterface::MYSQL;
/**
* Driver schemas.
*/
const SCHEMA_TABLE = TableSchema::class;
/**
* Commander used to execute commands. :)
*/
const COMMANDER = Commander::class;
/**
* Query compiler class.
*/
const QUERY_COMPILER = QueryCompiler::class;
/**
* Default timestamp expression.
*/
const TIMESTAMP_NOW = 'CURRENT_TIMESTAMP';
/**
* {@inheritdoc}
*/
protected $options = [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "UTF8"'
];
/**
* {@inheritdoc}
*/
public function identifier($identifier)
{
return $identifier == '*' ? '*' : '`' . str_replace('`', '``', $identifier) . '`';
}
/**
* {@inheritdoc}
*/
public function hasTable($name)
{
$query = 'SELECT COUNT(*) FROM `information_schema`.`tables` WHERE `table_schema` = ? AND `table_name` = ?';
return (bool)$this->query($query, [$this->getSource(), $name])->fetchColumn();
}
/**
* {@inheritdoc}
*/
public function tableNames()
{
$result = [];
foreach ($this->query('SHOW TABLES')->fetchMode(PDO::FETCH_NUM) as $row) {
$result[] = $row[0];
}
return $result;
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite\Schemas;
use Spiral\Database\Entities\Schemas\AbstractColumn;
/**
* SQLite column schema.
*/
class ColumnSchema extends AbstractColumn
{
/**
* {@inheritdoc}
*/
protected $mapping = [
//Primary sequences
'primary' => [
'type' => 'integer',
'primaryKey' => true,
'nullable' => false
],
'bigPrimary' => [
'type' => 'integer',
'primaryKey' => true,
'nullable' => false
],
//Enum type (mapped via method)
'enum' => 'enum',
//Logical types
'boolean' => 'boolean',
//Integer types (size can always be changed with size method), longInteger has method alias
//bigInteger
'integer' => 'integer',
'tinyInteger' => 'tinyint',
'bigInteger' => 'bigint',
//String with specified length (mapped via method)
'string' => 'text',
//Generic types
'text' => 'text',
'tinyText' => 'text',
'longText' => 'text',
//Real types
'double' => 'double',
'float' => 'real',
//Decimal type (mapped via method)
'decimal' => 'numeric',
//Date and Time types
'datetime' => 'datetime',
'date' => 'date',
'time' => 'time',
'timestamp' => 'timestamp',
//Binary types
'binary' => 'blob',
'tinyBinary' => 'blob',
'longBinary' => 'blob',
//Additional types
'json' => 'text'
];
/**
* {@inheritdoc}
*/
protected $reverseMapping = [
'primary' => [['type' => 'integer', 'primaryKey' => true]],
'enum' => ['enum'],
'boolean' => ['boolean'],
'integer' => ['int', 'integer', 'smallint', 'mediumint'],
'tinyInteger' => ['tinyint'],
'bigInteger' => ['bigint'],
'text' => ['text', 'string'],
'double' => ['double'],
'float' => ['real'],
'decimal' => ['numeric'],
'datetime' => ['datetime'],
'date' => ['date'],
'time' => ['time'],
'timestamp' => ['timestamp'],
'binary' => ['blob']
];
/**
* Is column primary key.
*
* @var bool
*/
protected $primaryKey = false;
/**
* {@inheritdoc}
*/
public function sqlStatement()
{
$statement = parent::sqlStatement();
if ($this->abstractType() != 'enum') {
return $statement;
}
$enumValues = [];
foreach ($this->enumValues as $value) {
$enumValues[] = $this->table->driver()->getPDO()->quote($value);
}
return "$statement CHECK ({$this->getName(true)} IN (" . join(', ', $enumValues) . "))";
}
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->name = $schema['name'];
$this->nullable = !$schema['notnull'];
$this->type = $schema['type'];
$this->primaryKey = (bool)$schema['pk'];
$this->defaultValue = $schema['dflt_value'];
if (preg_match('/^[\'""].*?[\'"]$/', $this->defaultValue)) {
$this->defaultValue = substr($this->defaultValue, 1, -1);
}
if (
!preg_match('/^(?P<type>[a-z]+) *(?:\((?P<options>[^\)]+)\))?/', $this->type, $matches)
) {
return;
}
$this->type = $matches['type'];
$options = null;
if (!empty($matches['options'])) {
$options = $matches['options'];
}
if ($this->type == 'enum') {
$name = $this->getName(true);
foreach ($schema['tableStatement'] as $column) {
if (preg_match("/$name +enum.*?CHECK *\\($name in \\((.*?)\\)\\)/i", trim($column),
$matches)) {
$enumValues = explode(',', $matches[1]);
foreach ($enumValues as &$value) {
if (preg_match("/^'?(.*?)'?$/", trim($value), $matches)) {
//In database: 'value'
$value = $matches[1];
}
unset($value);
}
$this->enumValues = $enumValues;
}
}
}
$options = array_map(function ($value) {
return intval($value);
}, explode(',', $options));
if (count($options) > 1) {
list($this->precision, $this->scale) = $options;
} elseif (!empty($options)) {
$this->size = $options[0];
}
}
/**
* {@inheritdoc}
*/
protected function prepareEnum()
{
return '';
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer\Prototypes;
use Psr\Log\LoggerAwareInterface;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\Tokenizer\Exceptions\LocatorException;
use Spiral\Tokenizer\Reflections\ReflectionFile;
use Spiral\Tokenizer\Tokenizer;
use Spiral\Tokenizer\TokenizerInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
/**
* Base class for Class and Invocation locators.
*/
class AbstractLocator extends Component implements InjectableInterface, LoggerAwareInterface
{
/**
* Injection over constant.
*/
use LoggerTrait;
/**
* Parent injector/factory.
*/
const INJECTOR = Tokenizer::class;
/**
* @invisible
* @var TokenizerInterface
*/
protected $tokenizer = null;
/**
* @var Finder
*/
protected $finder = null;
/**
* @param TokenizerInterface $tokenizer
* @param Finder $finder
*/
public function __construct(TokenizerInterface $tokenizer, Finder $finder)
{
$this->tokenizer = $tokenizer;
$this->finder = $finder;
}
/**
* Available file reflections. Generator.
*
*
* @generate ReflectionFile[]
*/
protected function availableReflections()
{
/**
* @var SplFileInfo $file
*/
foreach ($this->finder->getIterator() as $file) {
$reflection = $this->tokenizer->fileReflection((string)$file);
//We are not analyzing files which has includes, it's not safe to require such reflections
if ($reflection->hasIncludes()) {
$this->logger()->warning(
"File '{filename}' has includes and will be excluded from analysis.",
['filename' => (string)$file]
);
continue;
}
/**
* @var ReflectionFile $reflection
*/
yield $reflection;
}
}
/**
* Safely get class reflection, class loading errors will be blocked and reflection will be
* excluded from analysis.
*
* @param string $class
* @return \ReflectionClass|null
*/
protected function classReflection($class)
{
$loader = function ($class) {
throw new LocatorException("Class '{$class}' can not be loaded.");
};
//To suspend class dependency exception
spl_autoload_register($loader);
try {
return new \ReflectionClass($class);
} catch (\Exception $exception) {
$this->logger()->error(
"Unable to resolve class '{class}', error '{message}'.",
['class' => $class, 'message' => $exception->getMessage()]
);
return null;
} finally {
spl_autoload_unregister($loader);
}
}
/**
* Get every class trait (including traits used in parents).
*
* @param string $class
* @return array
*/
protected function getTraits($class)
{
$traits = [];
while ($class) {
$traits = array_merge(class_uses($class), $traits);
$class = get_parent_class($class);
}
//Traits from traits
foreach (array_flip($traits) as $trait) {
$traits = array_merge(class_uses($trait), $traits);
}
return array_unique($traits);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation;
/**
* Some objects can be validated by providing it's value in scalar/array form.
*/
interface ValueInterface
{
/**
* Convert object data into simple value.
*
* @return mixed
*/
public function serializeData();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM;
use Spiral\Models\AccessorInterface;
/**
* Declares requirement for every ODM field accessor to be an instance of AccessorInterface and
* declare it's default value and ability to build array of atomic updated for declared container.
*
* Parent model will not be supplied to accessor while schema analysis!
*/
interface DocumentAccessorInterface extends AccessorInterface
{
/**
* Check if object has any update.
*
* @return bool
*/
public function hasUpdates();
/**
* Mark object as successfully updated and flush all existed atomic operations and updates.
*/
public function flushUpdates();
/**
* Get generated and manually set document/object atomic updates.
*
* @param string $container Name of field or index where object stored under parent.
* @return array
*/
public function buildAtomics($container = '');
/**
* Accessor default value.
*
* @return mixed
*/
public function defaultValue();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas;
use Spiral\Database\Entities\Driver;
/**
* Holds set of DBMS specific element operations.
*/
abstract class AbstractCommander
{
/**
* @var Driver
*/
private $driver = null;
/**
* @param Driver $driver
*/
public function __construct(Driver $driver)
{
$this->driver = $driver;
}
/**
* Associated driver.
*
* @return Driver
*/
public function driver()
{
return $this->driver;
}
/**
* Create table!
*
* @param AbstractTable $table
* @return self
*/
public function createTable(AbstractTable $table)
{
//Executing!
$this->run($this->createStatement($table));
//Not all databases support adding index while table creation, so we can do it after
foreach ($table->getIndexes() as $index) {
$this->addIndex($table, $index);
}
return $this;
}
/**
* Drop table from database.
*
* @param string $table
*/
public function dropTable($table)
{
$this->run("DROP TABLE {$this->quote($table)}");
}
/**
* Rename table from one name to another.
*
* @param string $table
* @param string $name
* @return self
*/
public function renameTable($table, $name)
{
$this->run("ALTER TABLE {$this->quote($table)} RENAME TO {$this->quote($name)}");
return $this;
}
/**
* Driver specific column add command.
*
* @param AbstractTable $table
* @param AbstractColumn $column
* @return self
*/
public function addColumn(AbstractTable $table, AbstractColumn $column)
{
$this->run("ALTER TABLE {$table->getName(true)} ADD COLUMN {$column->sqlStatement()}");
return $this;
}
/**
* Driver specific column remove (drop) command.
*
* @param AbstractTable $table
* @param AbstractColumn $column
* @return self
*/
public function dropColumn(AbstractTable $table, AbstractColumn $column)
{
foreach ($column->getConstraints() as $constraint) {
//We have to erase all associated constraints
$this->dropConstrain($table, $constraint);
}
$this->run("ALTER TABLE {$table->getName(true)} DROP COLUMN {$column->getName(true)}");
return $this;
}
/**
* Driver specific column alter command.
*
* @param AbstractTable $table
* @param AbstractColumn $initial
* @param AbstractColumn $column
* @return self
*/
abstract public function alterColumn(
AbstractTable $table,
AbstractColumn $initial,
AbstractColumn $column
);
/**
* Driver specific index adding command.
*
* @param AbstractTable $table
* @param AbstractIndex $index
* @return self
*/
public function addIndex(AbstractTable $table, AbstractIndex $index)
{
$this->run("CREATE {$index->sqlStatement()}");
return $this;
}
/**
* Driver specific index remove (drop) command.
*
* @param AbstractTable $table
* @param AbstractIndex $index
* @return self
*/
public function dropIndex(AbstractTable $table, AbstractIndex $index)
{
$this->run("DROP INDEX {$index->getName(true)}");
return $this;
}
/**
* Driver specific index alter command, by default it will remove and add index.
*
* @param AbstractTable $table
* @param AbstractIndex $initial
* @param AbstractIndex $index
* @return self
*/
public function alterIndex(AbstractTable $table, AbstractIndex $initial, AbstractIndex $index)
{
return $this->dropIndex($table, $initial)->addIndex($table, $index);
}
/**
* Driver specific foreign key adding command.
*
* @param AbstractTable $table
* @param AbstractReference $foreign
* @return self
*/
public function addForeign(AbstractTable $table, AbstractReference $foreign)
{
$this->run("ALTER TABLE {$table->getName(true)} ADD {$foreign->sqlStatement()}");
return $this;
}
/**
* Driver specific foreign key remove (drop) command.
*
* @param AbstractTable $table
* @param AbstractReference $foreign
* @return self
*/
public function dropForeign(AbstractTable $table, AbstractReference $foreign)
{
return $this->dropConstrain($table, $foreign->getName());
}
/**
* Driver specific foreign key alter command, by default it will remove and add foreign key.
*
* @param AbstractTable $table
* @param AbstractReference $initial
* @param AbstractReference $foreign
* @return self
*/
public function alterForeign(
AbstractTable $table,
AbstractReference $initial,
AbstractReference $foreign
) {
return $this->dropForeign($table, $initial)->addForeign($table, $foreign);
}
/**
* Drop column constraint using it's name.
*
* @param AbstractTable $table
* @param string $constraint
* @return self
*/
public function dropConstrain(AbstractTable $table, $constraint)
{
$this->run("ALTER TABLE {$table->getName(true)} DROP CONSTRAINT {$this->quote($constraint)}");
return $this;
}
/**
* Execute statement.
*
* @param string $statement
* @param array $parameters
* @return \PDOStatement
*/
protected function run($statement, array $parameters = [])
{
return $this->driver->statement($statement, $parameters);
}
/**
* Quote identifier.
*
* @param string $identifier
* @return string
*/
protected function quote($identifier)
{
return $this->driver->identifier($identifier);
}
/**
* Get statement needed to create table.
*
* @param AbstractTable $table
* @return string
*/
protected function createStatement(AbstractTable $table)
{
$statement = ["CREATE TABLE {$table->getName(true)} ("];
$innerStatement = [];
//Columns
foreach ($table->getColumns() as $column) {
$innerStatement[] = $column->sqlStatement();
}
//Primary key
if (!empty($table->getPrimaryKeys())) {
$primaryKeys = array_map([$this, 'quote'], $table->getPrimaryKeys());
$innerStatement[] = 'PRIMARY KEY (' . join(', ', $primaryKeys) . ')';
}
//Constraints and foreign keys
foreach ($table->getForeigns() as $reference) {
$innerStatement[] = $reference->sqlStatement();
}
$statement[] = " " . join(",\n ", $innerStatement);
$statement[] = ')';
return join("\n", $statement);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas;
use Spiral\Database\Entities\Schemas\Prototypes\AbstractElement;
use Spiral\Database\Schemas\ReferenceInterface;
use Spiral\ODM\Exceptions\SchemaException;
/**
* Abstract foreign schema with read (see ReferenceInterface) and write abilities. Must be
* implemented by driver to support DBMS specific syntax and creation rules.
*/
abstract class AbstractReference extends AbstractElement implements ReferenceInterface
{
/**
* Local column name (key name).
*
* @var string
*/
protected $column = '';
/**
* Referenced table name (including prefix).
*
* @var string
*/
protected $foreignTable = '';
/**
* Linked foreign key name (foreign column).
*
* @var string
*/
protected $foreignKey = '';
/**
* Action on foreign column value deletion.
*
* @var string
*/
protected $deleteRule = self::NO_ACTION;
/**
* Action on foreign column value update.
*
* @var string
*/
protected $updateRule = self::NO_ACTION;
/**
* Mark schema entity as declared, it will be kept in final diff.
*
* @param bool $declared
* @return $this
*/
public function declared($declared = true)
{
if ($declared && $this->table->hasIndex([$this->column])) {
//Some databases require index for each foreign key
$this->table->index([$this->column])->declared(true);
}
return parent::declared($declared);
}
/**
* {@inheritdoc}
*
* @param string $name
* @return $this
*/
public function setName($name)
{
if (!empty($this->name)) {
throw new SchemaException("Changing reference name is not allowed.");
}
return parent::setName($name);
}
/**
* {@inheritdoc}
*
* @param bool $quoted Quote name.
*/
public function getName($quoted = false)
{
if (empty($this->name)) {
$this->setName($this->generateName());
}
return parent::getName($quoted);
}
/**
* {@inheritdoc}
*/
public function getColumn()
{
return $this->column;
}
/**
* {@inheritdoc}
*/
public function getForeignTable()
{
return $this->foreignTable;
}
/**
* {@inheritdoc}
*/
public function getForeignKey()
{
return $this->foreignKey;
}
/**
* {@inheritdoc}
*/
public function getDeleteRule()
{
return $this->deleteRule;
}
/**
* {@inheritdoc}
*/
public function getUpdateRule()
{
return $this->updateRule;
}
/**
* Set local column name foreign key relates to. Make sure column type is the same as foreign
* column one.
*
* @param string $column
* @return $this
*/
public function column($column)
{
$this->column = $column;
return $this;
}
/**
* Set foreign table name and key local column must reference to. Make sure local and foreign
* column types are identical.
*
* @param string $table Foreign table name without database prefix (will be added
* automatically).
* @param string $column Foreign key name (id by default).
* @return $this
*/
public function references($table, $column = 'id')
{
$this->foreignTable = $this->table->getPrefix() . $table;
$this->foreignKey = $column;
return $this;
}
/**
* Set foreign key delete behaviour.
*
* @param string $rule Possible values: NO ACTION, CASCADE, etc (driver specific).
* @return $this
*/
public function onDelete($rule = self::NO_ACTION)
{
$this->deleteRule = strtoupper($rule);
return $this;
}
/**
* Set foreign key update behaviour.
*
* @param string $rule Possible values: NO ACTION, CASCADE, etc (driver specific).
* @return $this
*/
public function onUpdate($rule = self::NO_ACTION)
{
$this->updateRule = strtoupper($rule);
return $this;
}
/**
* Foreign key creation syntax.
*
* @return string
*/
public function sqlStatement()
{
$statement = [];
$statement[] = 'CONSTRAINT';
$statement[] = $this->getName(true);
$statement[] = 'FOREIGN KEY';
$statement[] = '(' . $this->table->driver()->identifier($this->column) . ')';
$statement[] = 'REFERENCES ' . $this->table->driver()->identifier($this->foreignTable);
$statement[] = '(' . $this->table->driver()->identifier($this->foreignKey) . ')';
$statement[] = "ON DELETE {$this->deleteRule}";
$statement[] = "ON UPDATE {$this->updateRule}";
return join(" ", $statement);
}
/**
* Compare two elements together.
*
* @param self $initial
* @return bool
*/
public function compare(self $initial)
{
$normalized = clone $initial;
$normalized->declared = $this->declared;
return $this == $normalized;
}
/**
* Generate unique foreign key name.
*
* @return string
*/
protected function generateName()
{
$name = $this->table->getName() . '_foreign_' . $this->column . '_' . uniqid();
if (strlen($name) > 64) {
//Many dbs has limitations on identifier length
$name = md5($name);
}
return $name;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Configs;
use Spiral\Core\InjectableConfig;
use Spiral\Core\Traits\Config\AliasTrait;
/**
* Databases config.
*/
class DatabasesConfig extends InjectableConfig
{
use AliasTrait;
/**
* Configuration section.
*/
const CONFIG = 'databases';
/**
* @var array
*/
protected $config = [
'default' => 'default',
'aliases' => [],
'databases' => [],
'connections' => []
];
/**
* @return string
*/
public function defaultDatabase()
{
return $this->config['default'];
}
/**
* @param string $database
* @return bool
*/
public function hasDatabase($database)
{
return isset($this->config['databases'][$database]);
}
/**
* @param string $connection
* @return bool
*/
public function hasConnection($connection)
{
return isset($this->config['connections'][$connection]);
}
/**
* @return array
*/
public function databaseNames()
{
return array_keys($this->config['databases']);
}
/**
* @return array
*/
public function connectionNames()
{
return array_keys($this->config['connections']);
}
/**
* @param string $database
* @return string
*/
public function databaseConnection($database)
{
return $this->config['databases'][$database]['connection'];
}
/**
* @param string $database
* @return string
*/
public function databasePrefix($database)
{
if (isset($this->config['databases'][$database]['tablePrefix'])) {
return $this->config['databases'][$database]['tablePrefix'];
}
return '';
}
/**
* @param string $connection
* @return string
*/
public function connectionDriver($connection)
{
return $this->config['connections'][$connection]['driver'];
}
/**
* @param string $connection
* @return array
*/
public function connectionConfig($connection)
{
return $this->config['connections'][$connection];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Spiral\Database\Entities\Database;
use Spiral\Database\Query\QueryResult;
use Spiral\ORM\Entities\Loaders\RootLoader;
use Spiral\ORM\Exceptions\LoaderException;
use Spiral\ORM\LoaderInterface;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* ORM Loaders used to load an compile data tree based on results fetched from SQL databases,
* loaders can communicate with parent selector by providing it's own set of conditions, columns
* joins and etc. In some cases loader may create additional selector to load data using information
* fetched from previous query. Every loaded must be associated with specific record schema and
* relation (except RootLoader).
*
* Loaders can be used for both - loading and filtering of record data.
*
* Reference tree generation logic example:
* User has many Posts (relation "posts"), user primary is ID, post inner key pointing to user
* is USER_ID. Post loader must request User data loader to create references based on ID field
* values. Once Post data were parsed we can mount it under parent user using mount method:
*
* $this->parent->mount("posts", "ID", $data["USER_ID"], $data, true); //true = multiple
*
* @see Selector::load()
* @see Selector::with()
*/
abstract class Loader implements LoaderInterface
{
/**
* Default loading methods for ORM loaders.
*/
const INLOAD = 1;
const POSTLOAD = 2;
const JOIN = 3;
/**
* Relation type is required to correctly resolve foreign record class based on relation
* definition.
*/
const RELATION_TYPE = null;
/**
* Default load method (inload or postload).
*/
const LOAD_METHOD = null;
/**
* Internal loader constant used to decide how to aggregate data tree, true for relations like
* MANY TO MANY or HAS MANY.
*/
const MULTIPLE = false;
/**
* Count of Loaders requested data alias.
*
* @var int
*/
private static $counter = 0;
/**
* Unique loader data alias (only for loaders, not joiners).
*
* @var string
*/
private $alias = '';
/**
* Helper structure used to prevent data duplication when LEFT JOIN multiplies parent records.
*
* @invisible
* @var array
*/
private $duplicates = [];
/**
* Loader configuration options, can be edited using setOptions method or while declaring loader
* in Selector.
*
* @var array
*/
protected $options = [
'method' => null,
'alias' => null,
'using' => null,
'where' => null
];
/**
* Result of data compilation, only populated in cases where loader is primary Selector loader.
*
* @var array
*/
protected $result = [];
/**
* Container related to parent loader. Loaded data must be loaded using this container.
*
* @var string
*/
protected $container = '';
/**
* Indication that loaded already set columns and conditions to parent Selector.
*
* @var bool
*/
protected $configured = false;
/**
* Set of columns to be fetched from resulted query.
*
* @var array
*/
protected $dataColumns = [];
/**
* Loader data offset in resulted query row provided by parent Selector or Loader.
*
* @var int
*/
protected $dataOffset = 0;
/**
* Relation definition options if any.
*
* @var array
*/
protected $definition = [];
/**
* Inner (nested) loaders.
*
* @var LoaderInterface[]
*/
protected $loaders = [];
/**
* Loaders used purely for conditional purposes. Only ORM loaders can do that.
*
* @var Loader[]
*/
protected $joiners = [];
/**
* Set of keys requested by inner loaders to be pre-aggregated while query parsing. This
* structure if populated when new sub loaded registered.
*
* @var array
*/
protected $referenceKeys = [];
/**
* Chunks of parsed data associated with their reference key name and it's value. Used to
* compile data tree via php references.
*
* @var array
*/
protected $references = [];
/**
* Related record schema.
*
* @invisible
* @var array
*/
protected $schema = [];
/**
* ORM Loaders can only be nested into ORM Loaders.
*
* @invisible
* @var Loader|null
*/
protected $parent = null;
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* {@inheritdoc}
*/
public function __construct(
ORM $orm,
$container,
array $definition = [],
LoaderInterface $parent = null
) {
$this->orm = $orm;
//Related record schema
$this->schema = $orm->schema($definition[static::RELATION_TYPE]);
$this->container = $container;
$this->definition = $definition;
$this->parent = $parent;
//Compiling options
$this->options['method'] = static::LOAD_METHOD;
if (!empty($parent)) {
if (!$parent instanceof Loader || $parent->getDatabase() != $this->getDatabase()) {
//We have to force post-load (separate query) if parent loader database is different
$this->options['method'] = self::POSTLOAD;
}
}
$this->dataColumns = array_keys($this->schema[ORM::M_COLUMNS]);
}
/**
* Update loader options.
*
* @param array $options
* @return $this
* @throws LoaderException
*/
public function setOptions(array $options = [])
{
$this->options = $options + $this->options;
if (
$this->isJoinable()
&& !empty($this->parent)
&& $this->parent->getDatabase() != $this->getDatabase()
) {
throw new LoaderException("Unable to join tables located in different databases.");
}
return $this;
}
/**
* Table name loader relates to.
*
* @return mixed
*/
public function getTable()
{
return $this->schema[ORM::M_TABLE];
}
/**
* Every loader declares an unique alias for it's source table based on options or based on
* position in loaders chain. In addition, every loader responsible for data loading will add
* "_data" postfix to it's alias.
*
* @return string
*/
public function getAlias()
{
if (!empty($this->options['using'])) {
//We are using another relation (presumably defined by with() to load data).
return $this->options['using'];
}
if (!empty($this->options['alias'])) {
return $this->options['alias'];
}
//We are not really worrying about default loader aliases, joiners more important
if ($this->isLoadable()) {
if (!empty($this->alias)) {
//Alias was already created
return $this->alias;
}
//New alias is pretty simple and short
return $this->alias = 'd' . decoct(++self::$counter);
}
if (empty($this->parent)) {
$alias = $this->getTable();
} elseif ($this->parent instanceof RootLoader) {
//This is first level of relation loading, we can use relation name by itself
$alias = $this->container;
} else {
//Let's use parent alias to continue chain
$alias = $this->parent->getAlias() . '_' . $this->container;
}
return $alias;
}
/**
* Database name loader relates to.
*
* @return mixed
*/
public function getDatabase()
{
return $this->schema[ORM::M_DB];
}
/**
* Instance of Dbal\Database data associated with loader instance, used as primary database
* for selector is loader defined as primary selection loader.
*
* @return Database
*/
public function dbalDatabase()
{
return $this->orm->database($this->schema[ORM::M_DB]);
}
/**
* Get primary key name related to associated record.
*
* @return string|null
*/
public function getPrimaryKey()
{
if (!isset($this->schema[ORM::M_PRIMARY_KEY])) {
return null;
}
return $this->getAlias() . '.' . $this->schema[ORM::M_PRIMARY_KEY];
}
/**
* Pre-load data on inner relation or relation chain. Method automatically called by Selector,
* see load() method.
*
* @see Selector::load()
* @param string $relation Relation name, or chain of relations separated by.
* @param array $options Loader options (will be applied to last chain element only).
* @return LoaderInterface
* @throws LoaderException
*/
public function loader($relation, array $options = [])
{
if (($position = strpos($relation, '.')) !== false) {
//Chain of relations provided
$nested = $this->loader(substr($relation, 0, $position), []);
if (empty($nested) || !$nested instanceof self) {
//todo: Think about the options
throw new LoaderException(
"Only ORM loaders can be used to generate/configure chain of relation loaders."
);
}
//Recursively (will work only with ORM loaders).
return $nested->loader(substr($relation, $position + 1), $options);
}
if (!isset($this->schema[ORM::M_RELATIONS][$relation])) {
$container = $this->container ?: $this->schema[ORM::M_ROLE_NAME];
throw new LoaderException(
"Undefined relation '{$relation}' under '{$container}'."
);
}
if (isset($this->loaders[$relation])) {
$nested = $this->loaders[$relation];
if (!$nested instanceof self) {
throw new LoaderException(
"Only ORM loaders can be used to generate/configure chain of relation loaders."
);
}
//Updating existed loaded options
$nested->setOptions($options);
return $nested;
}
$relationOptions = $this->schema[ORM::M_RELATIONS][$relation];
//Asking ORM for loader instance
$loader = $this->orm->loader(
$relationOptions[ORM::R_TYPE],
$relation,
$relationOptions[ORM::R_DEFINITION],
$this
);
if (!empty($options) && !$loader instanceof self) {
//todo: think about alternatives again
throw new LoaderException(
"Only ORM loaders can be used to generate/configure chain of relation loaders."
);
}
$loader->setOptions($options);
$this->loaders[$relation] = $loader;
if ($referenceKey = $loader->getReferenceKey()) {
/**
* Inner loader requests parent to pre-collect some keys so it can build tree using
* references without looking up for correct record every time.
*/
$this->referenceKeys[] = $referenceKey;
$this->referenceKeys = array_unique($this->referenceKeys);
}
return $loader;
}
/**
* Filter data on inner relation or relation chain. Method automatically called by Selector,
* see with() method. Logic is identical to loader() method.
*
* @see Selector::load()
* @param string $relation Relation name, or chain of relations separated by.
* @param array $options Loader options (will be applied to last chain element only).
* @return Loader
* @throws LoaderException
*/
public function joiner($relation, array $options = [])
{
//We have to force joining method for full chain
$options['method'] = self::JOIN;
if (($position = strpos($relation, '.')) !== false) {
//Chain of relations provided
$nested = $this->joiner(substr($relation, 0, $position), []);
if (empty($nested) || !$nested instanceof self) {
//todo: DRY
throw new LoaderException(
"Only ORM loaders can be used to generate/configure chain of relation joiners."
);
}
//Recursively (will work only with ORM loaders).
return $nested->joiner(substr($relation, $position + 1), $options);
}
if (!isset($this->schema[ORM::M_RELATIONS][$relation])) {
$container = $this->container ?: $this->schema[ORM::M_ROLE_NAME];
throw new LoaderException(
"Undefined relation '{$relation}' under '{$container}'."
);
}
if (isset($this->joiners[$relation])) {
//Updating existed joiner options
return $this->joiners[$relation]->setOptions($options);
}
$relationOptions = $this->schema[ORM::M_RELATIONS][$relation];
$joiner = $this->orm->loader(
$relationOptions[ORM::R_TYPE],
$relation,
$relationOptions[ORM::R_DEFINITION],
$this
);
if (!$joiner instanceof self) {
//todo: DRY
throw new LoaderException(
"Only ORM loaders can be used to generate/configure chain of relation joiners."
);
}
return $this->joiners[$relation] = $joiner->setOptions($options);
}
/**
* {@inheritdoc}
*/
public function isMultiple()
{
return static::MULTIPLE;
}
/**
* {@inheritdoc}
*/
public function getReferenceKey()
{
//In most of cases reference key is inner key name (parent "ID" field name), don't be confused
//by INNER_KEY, remember that we building relation from parent record point of view
return $this->definition[RecordEntity::INNER_KEY];
}
/**
* {@inheritdoc}
*/
public function aggregatedKeys($referenceKey)
{
if (!isset($this->references[$referenceKey])) {
return [];
}
return array_unique(array_keys($this->references[$referenceKey]));
}
/**
* Create selector dedicated to load data for current loader.
*
* @return RecordSelector|null
*/
public function createSelector()
{
if (!$this->isLoadable()) {
return null;
}
$selector = $this->orm->selector($this->definition[static::RELATION_TYPE], $this);
//Setting columns to be loaded
$this->configureColumns($selector);
foreach ($this->loaders as $loader) {
if ($loader instanceof self) {
//Allowing sub loaders to configure required columns and conditions as well
$loader->configureSelector($selector);
}
}
foreach ($this->joiners as $joiner) {
//Joiners must configure selector as well
$joiner->configureSelector($selector);
}
return $selector;
}
/**
* Configure provided selector with required joins, columns and conditions, in addition method
* must pass configuration to sub loaders.
*
* Method called by Selector when loader set as primary selection loader.
*
* @param RecordSelector $selector
*/
public function configureSelector(RecordSelector $selector)
{
if (!$this->isJoinable()) {
//Loader can be used not only for loading but purely for filering
if (empty($this->parent)) {
foreach ($this->loaders as $loader) {
if ($loader instanceof self) {
$loader->configureSelector($selector);
}
}
foreach ($this->joiners as $joiner) {
//Nested joiners
$joiner->configureSelector($selector);
}
}
return;
}
if (!$this->configured) {
//We never configured loader columns before
$this->configureColumns($selector);
//Inload conditions and etc
if (empty($this->options['using']) && !empty($this->parent)) {
$this->clarifySelector($selector);
}
$this->configured = true;
}
foreach ($this->loaders as $loader) {
if ($loader instanceof self) {
$loader->configureSelector($selector);
}
}
foreach ($this->joiners as $joiner) {
$joiner->configureSelector($selector);
}
}
/**
* Implementation specific selector configuration, must create required joins, conditions and
* etc.
*
* @param RecordSelector $selector
*/
abstract protected function clarifySelector(RecordSelector $selector);
/**
* Parse QueryResult provided by parent loaders and populate data tree. Loader must pass parsing
* to inner loaders also.
*
* @param QueryResult $result
* @param int $rowsCount
* @return array
*/
public function parseResult(QueryResult $result, &$rowsCount)
{
foreach ($result as $row) {
$this->parseRow($row);
$rowsCount++;
}
return $this->result;
}
/**
* {@inheritdoc}
*
* Method will clarify Loader data tree result using nested loaders.
*/
public function loadData()
{
foreach ($this->loaders as $loader) {
if ($loader instanceof self && !$loader->isJoinable()) {
if (!empty($selector = $loader->createSelector())) {
//Data will be automatically linked via references and mount method
$selector->fetchData();
}
} else {
//Some other loader type or loader requested separate query to be created
$loader->loadData();
}
}
}
/**
* Get compiled data tree, method must be called only if loader were feeded with QueryResult
* using parseResult() method. Attention, method must be called AFTER loadData() with additional
* loaders were executed.
*
* @see loadData()
* @see parseResult()
* @return array
*/
public function getResult()
{
return $this->result;
}
/**
* {@inheritdoc}
*
* Data will be mounted using references.
*/
public function mount($container, $key, $criteria, array &$data, $multiple = false)
{
foreach ($this->references[$key][$criteria] as &$subset) {
if ($multiple) {
if (isset($subset[$container]) && in_array($data, $subset[$container])) {
unset($subset);
continue;
}
$subset[$container][] = &$data;
unset($subset);
continue;
}
if (isset($subset[$container])) {
$data = &$subset[$container];
} else {
$subset[$container] = &$data;
}
unset($subset);
}
}
/**
* {@inheritdoc}
*
* @param bool $reconfigure Use this option to reset configured flag to force query
* clarification on next query creation.
*/
public function clean($reconfigure = false)
{
$this->duplicates = [];
$this->references = [];
$this->result = [];
if ($reconfigure) {
$this->configured = false;
}
foreach ($this->loaders as $loader) {
if (!$loader instanceof self) {
continue;
}
//POSTLOAD loaders create unique Selector every time, meaning we will have to flush flag
//indicates that associated selector was configured
$loader->clean($reconfigure || !$this->isLoadable());
}
}
/**
* Destruct loader.
*/
public function __destruct()
{
$this->clean();
$this->loaders = [];
$this->joiners = [];
}
/**
* Indicates that loader columns must be included into query statement.
*
* @return bool
*/
protected function isLoadable()
{
if (!empty($this->parent) && !$this->parent->isLoadable()) {
//If parent not loadable we are no loadable also
return false;
}
return $this->options['method'] !== self::JOIN;
}
/**
* Indicated that loaded must generate JOIN statement.
*
* @return bool
*/
protected function isJoinable()
{
if (!empty($this->options['using'])) {
return true;
}
return in_array($this->options['method'], [self::INLOAD, self::JOIN]);
}
/**
* If loader is joinable we can calculate join type based on way loader going to be used
* (loading or filtering).
*
* @return string
* @throws LoaderException
*/
protected function joinType()
{
if (!$this->isJoinable()) {
throw new LoaderException("Unable to resolve Loader join type, Loader is not joinable.");
}
return $this->options['method'] == self::JOIN ? 'INNER' : 'LEFT';
}
/**
* Fetch record columns from query row, must use data offset to slice required part of query.
*
* @param array $row
* @return array
*/
protected function fetchData(array $row)
{
//Combine column names with sliced piece of row
return array_combine(
$this->dataColumns,
array_slice($row, $this->dataOffset, count($this->dataColumns))
);
}
/**
* In many cases (for example if you have inload of HAS_MANY relation) record data can be
* replicated by many result rows (duplicated). To prevent wrong data linking we have to
* deduplicate such records. This is only internal loader functionality and required due data
* tree are built using php references.
*
* Method will return true if data is unique handled before and false in opposite case.
* Provided data array will be automatically linked with it's unique state using references.
*
* @param array $data Reference to parsed record data, reference will be pointed to valid and
* existed data segment if such data was already parsed.
* @return bool
*/
protected function deduplicate(array &$data)
{
if (isset($this->schema[ORM::M_PRIMARY_KEY])) {
//We can use record id as de-duplication criteria
$criteria = $data[$this->schema[ORM::M_PRIMARY_KEY]];
} else {
//It is recommended to use primary keys in every record as it will speed up de-duplication.
$criteria = serialize($data);
}
if (isset($this->duplicates[$criteria])) {
//Duplicate is presented, let's reduplicate
$data = $this->duplicates[$criteria];
//Duplicate is presented
return false;
}
//Let's force placeholders for every sub loaded
foreach ($this->loaders as $container => $loader) {
$data[$container] = $loader->isMultiple() ? [] : null;
}
//Remember record to prevent future duplicates
$this->duplicates[$criteria] = &$data;
return true;
}
/**
* Generate sql identifier using loader alias and value from relation definition.
*
* Example:
* $this->getKey(Record::OUTER_KEY);
*
* @param string $key
* @return string|null
*/
protected function getKey($key)
{
if (!isset($this->definition[$key])) {
return null;
}
return $this->getAlias() . '.' . $this->definition[$key];
}
/**
* SQL identified to parent record outer key (usually primary key).
*
* @return string
* @throws LoaderException
*/
protected function getParentKey()
{
if (empty($this->parent)) {
throw new LoaderException("Unable to get parent key, no parent loader provided.");
}
return $this->parent->getAlias() . '.' . $this->definition[RecordEntity::INNER_KEY];
}
/**
* Configure columns required for loader data selection.
*
* @param RecordSelector $selector
*/
protected function configureColumns(RecordSelector $selector)
{
if (!$this->isLoadable()) {
return;
}
$this->dataOffset = $selector->generateColumns($this->getAlias(), $this->dataColumns);
}
/**
* Reference criteria is value to be used to mount data into parent loader tree.
*
* Example:
* User has many Posts (relation "posts"), user primary is ID, post inner key pointing to user
* is USER_ID. Post loader must request User data loader to create references based on ID field
* values. Once Post data were parsed we can mount it under parent user using mount method:
*
* $this->parent->mount("posts", "ID", $data["USER_ID"], $data, true); //true = multiple
*
* @see getReferenceKey()
* @param array $data
* @return mixed
*/
protected function fetchCriteria(array $data)
{
if (!isset($data[$this->definition[RecordEntity::OUTER_KEY]])) {
return null;
}
return $data[$this->definition[RecordEntity::OUTER_KEY]];
}
/**
* Parse single result row to generate data tree. Must pass parsing to every nested loader.
*
* @param array $row
* @return bool
*/
private function parseRow(array $row)
{
if (!$this->isLoadable()) {
//Nothing to parse, we are no waiting for any data
return;
}
//Fetching only required part of resulted row
$data = $this->fetchData($row);
if (empty($this->parent)) {
if ($this->deduplicate($data)) {
//Yes, this is reference, i'm using this method to build data tree using nested parsers
$this->result[] = &$data;
//Registering references to simplify tree compilation for post and inner loaders
$this->collectReferences($data);
}
$this->parseNested($row);
return;
}
if (!$referenceCriteria = $this->fetchCriteria($data)) {
//Relation not loaded
return;
}
if ($this->deduplicate($data)) {
//Registering references to simplify tree compilation for post and inner loaders
$this->collectReferences($data);
}
//Mounting parsed data into parent under defined container
$this->parent->mount(
$this->container,
$this->getReferenceKey(),
$referenceCriteria,
$data,
static::MULTIPLE
);
$this->parseNested($row);
}
/**
* Parse data using nested loaders.
*
* @param array $row
*/
private function parseNested(array $row)
{
foreach ($this->loaders as $loader) {
if ($loader instanceof self && $loader->isJoinable() && $loader->isLoadable()) {
$loader->parseRow($row);
}
}
}
/**
* Create internal references cache based on requested keys. For example, if we have request for
* "id" as reference key, every record will create following structure:
* $this->references[id][ID_VALUE] = ITEM
*
* Only deduplicated data must be collected!
*
* @see deduplicate()
* @param array $data
*/
private function collectReferences(array &$data)
{
foreach ($this->referenceKeys as $key) {
//Adding reference(s)
$this->references[$key][$data[$key]][] = &$data;
}
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Spiral\Database\Builders\Prototypes\AbstractSelect;
use Spiral\Database\Exceptions\BuilderException;
/**
* WhereDecorator used to trick user functions and route where() calls to specified destination
* (where, onWhere, etc). This functionality used to describe WHERE conditions in ORM loaders using
* unified where syntax.
*
* Decorator can additionally decorate target table name, using magic expression "{@}". Table name
* decoration is required as Loader target table can be unknown for user.
*/
class WhereDecorator
{
/**
* Target function postfix. All requests will be routed using this pattern and "or", "and"
* prefixes.
*
* @var string
*/
protected $target = 'where';
/**
* Decorator will replace {@} with this alias in every where column.
*
* @var string
*/
protected $alias = '';
/**
* Decorated query builder.
*
* @var AbstractSelect
*/
protected $query = null;
/**
* @param AbstractSelect $query
* @param string $target
* @param string $alias
*/
public function __construct(AbstractSelect $query, $target = 'where', $alias = '')
{
$this->query = $query;
$this->target = $target;
$this->alias = $alias;
}
/**
* Update target method all where requests should be router into.
*
* @param string $target
*/
public function setTarget($target)
{
$this->target = $target;
}
/**
* Get active routing target.
*
* @return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Simple WHERE condition with various set of arguments. Routed to where/on/having based
* on decorator settings.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function where($identifier, $variousA = null, $variousB = null, $variousC = null)
{
if ($identifier instanceof \Closure) {
call_user_func($identifier, $this);
return $this;
}
//We have to prepare only first argument
$arguments = func_get_args();
$arguments[0] = $this->prepare($arguments[0]);
//Routing where
call_user_func_array([$this->query, $this->target], $arguments);
return $this;
}
/**
* Simple AND WHERE condition with various set of arguments. Routed to where/on/having based
* on decorator settings.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function andWhere($identifier, $variousA = null, $variousB = null, $variousC = null)
{
if ($identifier instanceof \Closure) {
call_user_func($identifier, $this);
return $this;
}
//We have to prepare only first argument
$arguments = func_get_args();
$arguments[0] = $this->prepare($arguments[0]);
//Routing where
call_user_func_array([$this->query, 'and' . ucfirst($this->target)], $arguments);
return $this;
}
/**
* Simple OR WHERE condition with various set of arguments. Routed to where/on/having based
* on decorator settings.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function orWhere($identifier, $variousA = [], $variousB = null, $variousC = null)
{
if ($identifier instanceof \Closure) {
call_user_func($identifier, $this);
return $this;
}
//We have to prepare only first argument
$arguments = func_get_args();
$arguments[0] = $this->prepare($arguments[0]);
//Routing where
call_user_func_array([$this->query, 'or' . ucfirst($this->target)], $arguments);
return $this;
}
/**
* Helper function used to replace {@} alias with actual table name.
*
* @param mixed $where
* @return mixed
*/
protected function prepare($where)
{
if (is_string($where)) {
return str_replace('{@}', $this->alias, $where);
}
if (!is_array($where)) {
return $where;
}
$result = [];
foreach ($where as $column => $value) {
if (is_string($column) && !is_int($column)) {
$column = str_replace('{@}', $this->alias, $column);
}
$result[$column] = !is_array($value) ? $value : $this->prepare($value);
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders;
use Spiral\Database\Builders\Prototypes\AbstractAffect;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Entities\QueryCompiler;
use Spiral\Database\Exceptions\BuilderException;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Injections\ParameterInterface;
/**
* Update statement builder.
*/
class UpdateQuery extends AbstractAffect
{
/**
* Column names associated with their values.
*
* @var array
*/
protected $values = [];
/**
* {@inheritdoc}
*
* @param array $values Initial set of column updates.
*/
public function __construct(
Database $database,
QueryCompiler $compiler,
$table = '',
array $where = [],
array $values = []
) {
parent::__construct($database, $compiler, $table, $where);
$this->values = $values;
}
/**
* Change target table.
*
* @param string $table Table name without prefix.
* @return $this
*/
public function in($table)
{
$this->table = $table;
return $this;
}
/**
* Change value set to be updated, must be represented by array of columns associated with new
* value to be set.
*
* @param array $values
* @return $this
*/
public function values(array $values)
{
$this->values = $values;
return $this;
}
/**
* Get list of columns associated with their values.
*
* @return array
*/
public function getValues()
{
return $this->values;
}
/**
* Set update value.
*
* @param string $column
* @param mixed $value
* @return $this
*/
public function set($column, $value)
{
$this->values[$column] = $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function getParameters(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler;
}
$values = [];
foreach ($this->values as $value) {
if ($value instanceof QueryBuilder) {
foreach ($value->getParameters() as $parameter) {
$values[] = $parameter;
}
continue;
}
if ($value instanceof FragmentInterface && !$value instanceof ParameterInterface) {
//Apparently sql fragment
continue;
}
$values[] = $value;
}
//Join and where parameters are going after values
return $this->flattenParameters($compiler->orderParameters(
QueryCompiler::UPDATE_QUERY, $this->whereParameters, [], [], $values
));
}
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (empty($this->values)) {
throw new BuilderException("Update values must be specified.");
}
if (empty($compiler)) {
$compiler = $this->compiler->resetQuoter();
}
return $compiler->compileUpdate($this->table, $this->values, $this->whereTokens);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Importers;
use Spiral\Stempler\ImporterInterface;
/**
* {@inheritdoc}
*
* Simple aliased based import, declared relation between tag name and it's location. Element alias
* must be located in "as" attribute caused import, location in "path" attribute (will be passed
* thought Stempler->fetchLocation()).
*/
class Aliaser implements ImporterInterface
{
/**
* @var string
*/
private $alias = '';
/**
* @var mixed
*/
private $path = null;
/**
* {@inheritdoc}
*/
public function __construct($alias, $path)
{
$this->alias = $alias;
$this->path = $path;
}
/**
* {@inheritdoc}
*/
public function importable($element, array $token)
{
return strtolower($element) == strtolower($this->alias);
}
/**
* {@inheritdoc}
*/
public function resolvePath($element, array $token)
{
return $this->path;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Relations;
use Spiral\Database\Entities\Table;
use Spiral\Models\EntityInterface;
use Spiral\ORM\Entities\RecordIterator;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\RecordInterface;
use Spiral\ORM\RelationInterface;
/**
* ManyToMorphed relation used to aggregate multiple ManyToMany relations based on their role type.
* In addition it can route some function to specified nested ManyToMany relation based on record
* role.
*
* @see ManyToMany
*/
class ManyToMorphed implements RelationInterface
{
/**
* Nested ManyToMany relations.
*
* @var ManyToMany[]
*/
private $relations = [];
/**
* Parent Record caused relation to be created.
*
* @var RecordInterface
*/
protected $parent = null;
/**
* Relation definition fetched from ORM schema. Must already be normalized by RelationSchema.
*
* @invisible
* @var array
*/
protected $definition = [];
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* {@inheritdoc}
*/
public function __construct(
ORM $orm,
RecordInterface $parent,
array $definition,
$data = null,
$loaded = false
) {
$this->orm = $orm;
$this->parent = $parent;
$this->definition = $definition;
}
/**
* {@inheritdoc}
*/
public function isLoaded()
{
//Never loader
return false;
}
/**
* {@inheritdoc}
*
* We can return self:
* $tag->tagged->users->count();
*/
public function getRelated()
{
return $this;
}
/**
* {@inheritdoc}
*/
public function associate(EntityInterface $related = null)
{
throw new RelationException("Unable to associate with morphed relation.");
}
/**
* {@inheritdoc}
*/
public function saveAssociation($validate = true)
{
foreach ($this->relations as $relation) {
if (!$relation->saveAssociation($validate)) {
return false;
}
}
return true;
}
/**
* {@inheritdoc}
*/
public function reset(array $data = [], $loaded = false)
{
foreach ($this->relations as $relation) {
//Can be only flushed
$relation->reset([], false);
}
//Dropping relations
$this->relations = [];
}
/**
* {@inheritdoc}
*/
public function isValid()
{
foreach ($this->relations as $alias => $relation) {
if (!$relation->isValid()) {
return false;
}
}
return true;
}
/**
* {@inheritdoc}
*/
public function hasErrors()
{
foreach ($this->relations as $alias => $relation) {
if ($relation->hasErrors()) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function getErrors($reset = false)
{
$result = [];
foreach ($this->relations as $alias => $relation) {
if (!empty($errors = $relation->getErrors())) {
$result[$alias] = $errors;
}
}
return $result;
}
/**
* Count method will work with pivot table directly.
*
* @return int
*/
public function count()
{
$innerKey = $this->definition[RecordEntity::INNER_KEY];
return $this->pivotTable()->where([
$this->definition[RecordEntity::THOUGHT_INNER_KEY] => $this->parent->getField($innerKey)
])->count();
}
/**
* Get access to data instance stored in nested relation.
*
* Example:
* $tag->tagged->users;
* $tag->tagged->posts;
*
* @param string $alias
* @return RecordEntity|RecordIterator
*/
public function __get($alias)
{
return $this->morphed($alias)->getRelated();
}
/**
* Get access to sub relation.
*
* Example:
* $tag->tagged->users()->count();
* foreach($tag->tagged->users()->find(["status" => "active"]) as $user)
* {
* }
*
* @param string $alias
* @param array $arguments
* @return ManyToMany
*/
public function __call($alias, array $arguments)
{
return $this->morphed($alias);
}
/**
* Link morphed record to relation. Method will bypass request to appropriate nested relation.
*
* @param RecordInterface $record
* @param array $pivotData Custom pivot data.
*/
public function link(RecordInterface $record, array $pivotData = [])
{
$this->morphed($record->recordRole())->link($record, $pivotData);
}
/**
* Unlink morphed record from relation.
*
* @param RecordInterface $record
* @return int
*/
public function unlink(RecordInterface $record)
{
return $this->morphed($record->recordRole())->unlink($record);
}
/**
* Unlink every associated record, method will return amount of affected rows. Method will
* unlink only records matched WHERE_PIVOT by default. Set wherePivot to false to unlink every
* record.
*
* @param bool $wherePivot Use conditions specified by WHERE_PIVOT, enabled by default.
* @return int
*/
public function unlinkAll($wherePivot = true)
{
$innerKey = $this->definition[RecordEntity::INNER_KEY];
$query = [
$this->definition[RecordEntity::THOUGHT_INNER_KEY] => $this->parent->getField($innerKey)
];
if ($wherePivot && !empty($this->definition[RecordEntity::WHERE_PIVOT])) {
$query = $query + $this->definition[RecordEntity::WHERE_PIVOT];
}
return $this->pivotTable()->delete($query)->run();
}
/**
* Get nested-relation associated with one of record morph aliases.
*
* @param string $alias
* @return ManyToMany
*/
protected function morphed($alias)
{
if (isset($this->relations[$alias])) {
//Already loaded
return $this->relations[$alias];
}
if (
!isset($this->definition[RecordEntity::MORPHED_ALIASES][$alias])
&& !empty(
$reversed = array_search($alias, $this->definition[RecordEntity::MORPHED_ALIASES])
)
) {
//Requested by singular form of role name, let's reverse mapping
$alias = $reversed;
}
if (!isset($this->definition[RecordEntity::MORPHED_ALIASES][$alias])) {
throw new RelationException("No such morphed-relation or method '{$alias}'.");
}
//We have to create custom definition
$definition = $this->definition;
$roleName = $this->definition[RecordEntity::MORPHED_ALIASES][$alias];
$definition[RecordEntity::MANY_TO_MANY] = $definition[RecordEntity::MANY_TO_MORPHED][$roleName];
unset($definition[RecordEntity::MANY_TO_MORPHED], $definition[RecordEntity::MORPHED_ALIASES]);
//Creating many-to-many relation
$this->relations[$alias] = new ManyToMany($this->orm, $this->parent, $definition);
//We have to force role name
$this->relations[$alias]->setRole($roleName);
return $this->relations[$alias];
}
/**
* Instance of DBAL\Table associated with relation pivot table.
*
* @return Table
*/
protected function pivotTable()
{
return $this->orm->database($this->definition[ORM::R_DATABASE])->table(
$this->definition[RecordEntity::PIVOT_TABLE]
);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Spiral\Core\Component;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Models\SourceInterface;
use Spiral\ORM\Exceptions\SourceException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* Source class associated to one or multiple (default implementation) ORM models. Source can be
* used to write your own custom find method or change default selection.
*/
class RecordSource extends Component implements SourceInterface, \Countable
{
/**
* Sugary!
*/
use SaturateTrait;
/**
* Linked document model. ORM can automatically index and link user sources to models based on
* value of this constant.
*/
const RECORD = null;
/**
* Associated document class.
*
* @var string
*/
private $class = null;
/**
* @var RecordSelector
*/
private $selector = null;
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* @param string $class
* @param ORM $orm
* @throws SourceException
*/
public function __construct($class = null, ORM $orm = null)
{
if (empty($class)) {
if (empty(static::RECORD)) {
throw new SourceException("Unable to create source without associate class.");
}
$class = static::RECORD;
}
$this->class = $class;
$this->orm = $this->saturate($orm, ORM::class);
$this->setSelector($this->orm->selector($this->class));
}
/**
* Create new Record based on set of provided fields.
*
* @final Change static method of entity, not this one.
* @param array $fields
* @return RecordEntity
*/
final public function create($fields = [])
{
//Letting entity to create itself (needed
return call_user_func([$this->class, 'create'], $fields, $this->orm);
}
/**
* Find record by it's primary key.
*
* @see findOne()
* @param string|int $id Primary key value.
* @return RecordEntity|null
*/
public function findByPK($id)
{
return $this->find()->findByPK($id);
}
/**
* Select one record from mongo collection.
*
* @param array $where Where conditions in array form.
* @param array $orderBy In a form of [key => direction].
* @return RecordEntity|null
*/
public function findOne(array $where = [], array $orderBy = [])
{
return $this->find()->orderBy($orderBy)->findOne($where);
}
/**
* Get associated record selection with pre-configured query (if any).
*
* @param array $where Where conditions in array form.
* @return RecordSelector
*/
public function find(array $where = [])
{
return $this->selector()->where($where);
}
/**
* {@inheritdoc}
*/
public function count()
{
return $this->find()->count();
}
/**
* @return RecordSelector
*/
final protected function selector()
{
//Has to be cloned every time to prevent query collisions
return clone $this->selector;
}
/**
* @param RecordSelector $selector
*/
protected function setSelector(RecordSelector $selector)
{
$this->selector = $selector;
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders\Prototypes;
use Psr\Log\LoggerAwareInterface;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\QueryCompiler;
use Spiral\Debug\Traits\LoggerTrait;
/**
* Generic prototype for affect queries with WHERE and JOIN supports. At this moment used as parent
* for delete and update query builders.
*/
abstract class AbstractAffect extends AbstractWhere implements LoggerAwareInterface
{
/**
* Few builder warnings.
*/
use LoggerTrait;
/**
* Every affect builder must be associated with specific table.
*
* @var string
*/
protected $table = '';
/**
* {@inheritdoc}
*
* @param string $table Associated table name.
* @param array $where Initial set of where rules specified as array.
*/
public function __construct(
Database $database,
QueryCompiler $compiler,
$table = '',
array $where = []
) {
parent::__construct($database, $compiler);
$this->table = $table;
if (!empty($where)) {
$this->where($where);
}
}
/**
* {@inheritdoc}
*
* Affect queries will return count of affected rows.
*
* @return int
*/
public function run()
{
if (empty($this->whereTokens)) {
$this->logger()->warning("Affect query performed without any limiting condition.");
}
return $this->pdoStatement()->rowCount();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Exceptions;
/**
* ODM schema related exception.
*/
class SchemaException extends ODMException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Pagination;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
/**
* Default paginator implementation, uses active server request Uri to generate page urls.
*/
class Paginator implements PredictableInterface, \Countable
{
/**
* Default limit value.
*/
const DEFAULT_LIMIT = 25;
/**
* Default page parameter.
*/
const DEFAULT_PARAMETER = 'page';
/**
* The query array will be connected to every page URL generated by paginator.
*
* @var array
*/
private $queryData = [];
/**
* @var string
*/
private $pageParameter = 'page';
/**
* @var int
*/
private $pageNumber = 1;
/**
* @var int
*/
private $countPages = 1;
/**
* @var int
*/
private $limit = self::DEFAULT_LIMIT;
/**
* @var int
*/
private $count = 0;
/**
* @invisible
* @var ServerRequestInterface
*/
private $request = null;
/**
* @var UriInterface
*/
private $uri = null;
/**
* {@inheritdoc}
*/
public function __construct(
ServerRequestInterface $request,
$pageParameter = self::DEFAULT_PARAMETER
) {
$this->setRequest($request);
$this->setParameter($pageParameter);
}
/**
* @param ServerRequestInterface $request
*/
public function setRequest(ServerRequestInterface $request)
{
$this->request = $request;
$this->uri = $request->getUri();
}
/**
* {@inheritdoc}
*/
public function setUri(UriInterface $uri)
{
$this->uri = $uri;
return $this;
}
/**
* {@inheritdoc}
*/
public function getUri()
{
return $this->uri;
}
/**
* Specify the query (as array) which will be attached to every generated page URL.
*
* @param array $query
* @param bool $replace Replace existed query data entirely.
*/
public function setQuery(array $query, $replace = false)
{
$this->queryData = $replace ? $query : $query + $this->queryData;
}
/**
* @return array
*/
public function getQuery()
{
return $this->queryData;
}
/**
* Update page parameter name from request query. Page number should be fetched from queryParams
* of provided request instance.
*
* @param string $pageParameter
* @return self
*/
public function setParameter($pageParameter)
{
$this->pageParameter = $pageParameter;
$queryParams = $this->request->getQueryParams();
if (isset($queryParams[$this->pageParameter])) {
$this->setPage($queryParams[$this->pageParameter]);
}
return $this;
}
/**
* Get page query parameter name.
*
* @return string
*/
public function getParameter()
{
return $this->pageParameter;
}
/**
* {@inheritdoc}
*/
public function setCount($count)
{
$this->count = abs(intval($count));
if ($this->count > 0) {
$this->countPages = ceil($this->count / $this->limit);
} else {
$this->countPages = 1;
}
return $this;
}
/**
* {@inheritdoc}
*/
public function count()
{
return $this->count;
}
/**
* Set pagination limit.
*
* @param int $limit
* @return $this
*/
public function setLimit($limit)
{
$this->limit = abs(intval($limit));
if ($this->count > 0) {
$this->countPages = ceil($this->count / $this->limit);
} else {
$this->countPages = 1;
}
return $this;
}
/**
* Get pagination limit (items per page).
*
* @return int
*/
public function getLimit()
{
return $this->limit;
}
/**
* {@inheritdoc}
*/
public function setPage($number)
{
$this->pageNumber = abs(intval($number));
//Real page number
return $this->getPage();
}
/**
* {@inheritdoc}
*/
public function getPage()
{
if ($this->pageNumber < 1) {
return 1;
}
if ($this->pageNumber > $this->countPages) {
return $this->countPages;
}
return $this->pageNumber;
}
/**
* Get pagination offset.
*
* @return int
*/
public function getOffset()
{
return ($this->getPage() - 1) * $this->limit;
}
/**
* The count of pages required to represent all records using a specified limit value.
*
* @return int
*/
public function countPages()
{
return $this->countPages;
}
/**
* {@inheritdoc}
*/
public function countDisplayed()
{
if ($this->getPage() == $this->countPages) {
return $this->count - $this->getOffset();
}
return $this->limit;
}
/**
* {@inheritdoc}
*/
public function isRequired()
{
return ($this->countPages > 1);
}
/**
* {@inheritdoc}
*/
public function nextPage()
{
if ($this->getPage() != $this->countPages) {
return $this->getPage() + 1;
}
return false;
}
/**
* {@inheritdoc}
*/
public function previousPage()
{
if ($this->getPage() > 1) {
return $this->getPage() - 1;
}
return false;
}
/**
* {@inheritdoc}
*/
public function paginate(PaginableInterface $paginable)
{
$this->setCount($paginable->count());
$paginable->offset($this->getOffset());
$paginable->limit($this->getLimit());
return $paginable;
}
/**
* {@inheritdoc}
*/
public function uri($pageNumber)
{
return $this->uri->withQuery(http_build_query(
$this->getQuery() + [$this->pageParameter => $pageNumber]
));
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
/**
* Class responsible for "intelligent" table and column name quoting.
*
* Attention, Quoter does not support string literals at this moment, use FragmentInterface.
*/
class Quoter
{
/**
* Used to detect functions and expression.
*
* @var array
*/
private $stops = [")", "(", " "];
/**
* Cached list of table aliases used to correctly inject prefixed tables into conditions.
*
* @var array
*/
private $aliases = [];
/**
* @var PDODriver
*/
private $driver = null;
/**
* Database prefix.
*
* @var string
*/
private $prefix = '';
/**
* @param PDODriver $driver Driver needed to correctly quote identifiers and string quotes.
* @param string $prefix
*/
public function __construct(PDODriver $driver, $prefix)
{
$this->driver = $driver;
$this->prefix = $prefix;
}
/**
* Query query identifier, if identified stated as table - table prefix must be added.
*
* @param string $identifier Identifier can include simple column operations and functions,
* having "." in it will automatically force table prefix to first
* value.
* @param bool $table Set to true to let quote method know that identified is related
* to table name.
* @return mixed|string
*/
public function quote($identifier, $table = false)
{
if (preg_match('/ AS /i', $identifier, $matches)) {
list($identifier, $alias) = explode($matches[0], $identifier);
return $this->aliasing($identifier, $alias, $table);
}
if ($this->hasExpressions($identifier)) {
//Processing complex expression
return $this->expression($identifier);
}
if (strpos($identifier, '.') === false) {
//No table/column pair found
return $this->unpaired($identifier, $table);
}
//Contain table.column statement
return $this->paired($identifier);
}
/**
* Quoting columns and tables in complex expression.
*
* @param string $identifier
* @return mixed
*/
protected function expression($identifier)
{
return preg_replace_callback('/([a-z][0-9_a-z\.]*\(?)/i', function ($match) {
$identifier = $match[1];
//Function name
if ($this->hasExpressions($identifier)) {
return $identifier;
}
return $this->quote($identifier);
}, $identifier);
}
/**
* Handle "IDENTIFIER AS ALIAS" expression.
*
* @param string $identifier
* @param string $alias
* @param bool $table
* @return string
*/
protected function aliasing($identifier, $alias, $table)
{
$quoted = $this->quote($identifier, $table) . ' AS ' . $this->driver->identifier($alias);
if ($table && strpos($identifier, '.') === false) {
//We have to apply operation post factum to prevent self aliasing (name AS name)
//when db has prefix, expected: prefix_name as name)
$this->aliases[$alias] = $identifier;
}
return $quoted;
}
/**
* Processing pair of table and column.
*
* @param string $identifier
* @return string
*/
protected function paired($identifier)
{
//We expecting only table and column, no database name can be included (due database isolation)
list($table, $column) = explode('.', $identifier);
return "{$this->quote($table, true)}.{$this->driver->identifier($column)}";
}
/**
* Process unpaired (no . separator) identifier.
*
* @param string $identifier
* @param bool $table
* @return string
*/
protected function unpaired($identifier, $table)
{
if ($table && !isset($this->aliases[$identifier])) {
if (!isset($this->aliases[$this->prefix . $identifier])) {
//Generating our alias
$this->aliases[$this->prefix . $identifier] = $identifier;
}
$identifier = $this->prefix . $identifier;
}
return $this->driver->identifier($identifier);
}
/**
* Check if string has expression markers.
*
* @param string $string
* @return bool
*/
protected function hasExpressions($string)
{
foreach ($this->stops as $symbol) {
if (strpos($string, $symbol) !== false) {
return true;
}
}
return false;
}
/**
* Reset compiler aliases cache.
*
* @return $this
*/
public function reset()
{
$this->aliases = [];
return $this;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Injections;
use Spiral\Database\Entities\QueryCompiler;
/**
* Default implementation of ParameterInterface, provides ability to mock value or array of values
* and automatically create valid query placeholder at moment of query compilation (? vs (?, ?, ?)).
*
* In a nearest future Parameter class will be used for every QueryBuilder parameter, it can also
* be used to detect value type automatically.
*/
class Parameter implements ParameterInterface
{
/**
* Use in constructor to automatically detect parameter type.
*/
const DETECT_TYPE = 900888;
/**
* Mocked value or array of values.
*
* @var mixed|array
*/
private $value = null;
/**
* Parameter type.
*
* @var int|null
*/
private $type = null;
/**
* @param mixed $value
* @param int $type
*/
public function __construct($value, $type = self::DETECT_TYPE)
{
$this->value = $value;
if ($type == self::DETECT_TYPE && !is_array($value)) {
$this->type = $this->detectType($value);
} else {
$this->type = $type;
}
}
/**
* Change mocked parameter value.
*
* @param mixed $value
*/
public function setValue($value)
{
$this->value = $value;
}
/**
* {@inheritdoc}
*/
public function getValue()
{
return $this->value;
}
/**
* Parameter type.
*
* @return int
*/
public function getType()
{
return $this->type;
}
/**
* {@inheritdoc}
*/
public function flatten()
{
if (is_array($this->value)) {
$result = [];
foreach ($this->value as $value) {
if (!$value instanceof ParameterInterface) {
$value = new self($value, $this->type);
}
$result = array_merge($result, $value->flatten());
}
return $result;
}
return [$this];
}
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (is_array($this->value)) {
//Array were mocked
return '(' . trim(str_repeat('?, ', count($this->value)), ', ') . ')';
}
return '?';
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->sqlStatement();
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'statement' => $this->sqlStatement(),
'value' => $this->value
];
}
protected function detectType($value)
{
switch (gettype($value)) {
case "boolean":
return \PDO::PARAM_BOOL;
case "integer":
return \PDO::PARAM_INT;
case "NULL":
return \PDO::PARAM_NULL;
default:
return \PDO::PARAM_STR;
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL\Schemas;
use Spiral\Database\DatabaseManager;
use Spiral\Database\Drivers\MySQL\MySQLDriver;
use Spiral\Database\Entities\Schemas\AbstractColumn;
use Spiral\Database\Injections\Fragment;
/**
* MySQL column schema.
*/
class ColumnSchema extends AbstractColumn
{
/**
* {@inheritdoc}
*/
protected $mapping = [
//Primary sequences
'primary' => [
'type' => 'int',
'size' => 11,
'autoIncrement' => true,
'nullable' => false
],
'bigPrimary' => [
'type' => 'bigint',
'size' => 20,
'autoIncrement' => true,
'nullable' => false
],
//Enum type (mapped via method)
'enum' => 'enum',
//Logical types
'boolean' => ['type' => 'tinyint', 'size' => 1],
//Integer types (size can always be changed with size method), longInteger has method alias
//bigInteger
'integer' => ['type' => 'int', 'size' => 11],
'tinyInteger' => ['type' => 'tinyint', 'size' => 4],
'bigInteger' => ['type' => 'bigint', 'size' => 20],
//String with specified length (mapped via method)
'string' => 'varchar',
//Generic types
'text' => 'text',
'tinyText' => 'tinytext',
'longText' => 'longtext',
//Real types
'double' => 'double',
'float' => 'float',
//Decimal type (mapped via method)
'decimal' => 'decimal',
//Date and Time types
'datetime' => 'datetime',
'date' => 'date',
'time' => 'time',
'timestamp' => [
'type' => 'timestamp',
'defaultValue' => MySQLDriver::DEFAULT_DATETIME
],
//Binary types
'binary' => 'blob',
'tinyBinary' => 'tinyblob',
'longBinary' => 'longblob',
//Additional types
'json' => 'text'
];
/**
* {@inheritdoc}
*/
protected $reverseMapping = [
'primary' => [['type' => 'int', 'autoIncrement' => true]],
'bigPrimary' => ['serial', ['type' => 'bigint', 'autoIncrement' => true]],
'enum' => ['enum'],
'boolean' => ['bool', 'boolean', ['type' => 'tinyint', 'size' => 1]],
'integer' => ['int', 'integer', 'smallint', 'mediumint'],
'tinyInteger' => ['tinyint'],
'bigInteger' => ['bigint'],
'string' => ['varchar', 'char'],
'text' => ['text', 'mediumtext'],
'tinyText' => ['tinytext'],
'longText' => ['longtext'],
'double' => ['double'],
'float' => ['float', 'real'],
'decimal' => ['decimal'],
'datetime' => ['datetime'],
'date' => ['date'],
'time' => ['time'],
'timestamp' => ['timestamp'],
'binary' => ['blob', 'binary', 'varbinary'],
'tinyBinary' => ['tinyblob'],
'longBinary' => ['longblob']
];
/**
* List of types forbids default value set.
*
* @var array
*/
protected $forbiddenDefaults = [
'text',
'mediumtext',
'tinytext',
'longtext',
'blog',
'tinyblob',
'longblob'
];
/**
* Column is auto incremental.
*
* @var bool
*/
protected $autoIncrement = false;
/**
* {@inheritdoc}
*/
public function getDefaultValue()
{
$defaultValue = parent::getDefaultValue();
if (in_array($this->type, $this->forbiddenDefaults)) {
return null;
}
return $defaultValue;
}
/**
* {@inheritdoc}
*/
public function sqlStatement()
{
$defaultValue = $this->defaultValue;
if (in_array($this->type, $this->forbiddenDefaults)) {
//Flushing default value for forbidden types
$this->defaultValue = null;
}
$statement = parent::sqlStatement();
$this->defaultValue = $defaultValue;
if ($this->autoIncrement) {
return "{$statement} AUTO_INCREMENT";
}
return $statement;
}
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->type = $schema['Type'];
$this->nullable = strtolower($schema['Null']) == 'yes';
$this->defaultValue = $schema['Default'];
$this->autoIncrement = stripos($schema['Extra'], 'auto_increment') !== false;
if (!preg_match('/^(?P<type>[a-z]+)(?:\((?P<options>[^\)]+)\))?/', $this->type, $matches)) {
return;
}
$this->type = $matches['type'];
$options = null;
if (!empty($matches['options'])) {
$options = $matches['options'];
}
if ($this->abstractType() == 'enum') {
//Fetching enum values
$this->enumValues = array_map(function ($value) {
return trim($value, $value[0]);
}, explode(',', $options));
return;
}
$options = array_map(function ($value) {
return intval($value);
}, explode(',', $options));
if (count($options) > 1) {
list($this->precision, $this->scale) = $options;
} elseif (!empty($options)) {
$this->size = $options[0];
}
//Default value conversions
if ($this->type == 'bit' && $this->hasDefaultValue()) {
//Cutting b\ and '
$this->defaultValue = new Fragment($this->defaultValue);
}
if ($this->abstractType() == 'timestamp' && $this->defaultValue == '0000-00-00 00:00:00') {
$this->defaultValue = MySqlDriver::DEFAULT_DATETIME;
}
}
/**
* {@inheritdoc}
*/
protected function prepareDefault()
{
if ($this->abstractType() == 'timestamp' && is_scalar($this->defaultValue)) {
if (is_numeric($this->defaultValue)) {
//Nothing to do
return (int)$this->defaultValue;
}
$datetime = new \DateTime($this->defaultValue,
new \DateTimeZone(DatabaseManager::DEFAULT_TIMEZONE));
return $datetime->getTimestamp();
}
return parent::prepareDefault();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
/**
* Simple initial interface for ORM and ODM Source classes. Only share one common method - findByPK.
*/
interface SourceInterface
{
/**
* Create new entity based on set of provided fields.
*
* @param array $fields
* @return EntityInterface
*/
public function create($fields = []);
/**
* Find entity by primary key or return null.
*
* @param mixed $primaryKey
* @return IdentifiedInterface|null
*/
public function findByPK($primaryKey);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Injections;
use Spiral\Database\Entities\QueryCompiler;
/**
* Default implementation of SQLFragmentInterface, provides ability to inject custom SQL code into
* query builders. Usually used to mock database specific functions.
*
* Example: ...->where('time_created', '>', new SQLFragment("NOW()"));
*/
class Fragment implements FragmentInterface
{
/**
* @var string
*/
private $statement = null;
/**
* @param string $statement
*/
public function __construct($statement)
{
$this->statement = $statement;
}
/**
* {@inheritdoc}
*
* @param QueryCompiler $compiler
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
return $this->statement;
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->sqlStatement();
}
/**
* @return array
*/
public function __debugInfo()
{
return ['statement' => $this->sqlStatement()];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres;
use Spiral\Database\Drivers\Postgres\QueryCompiler as PostgresCompiler;
use Spiral\Database\Entities\QueryCompiler as AbstractCompiler;
use Spiral\Database\Exceptions\BuilderException;
use Spiral\Debug\Traits\LoggerTrait;
/**
* Postgres driver requires little bit different way to handle last insert id.
*/
class InsertQuery extends \Spiral\Database\Builders\InsertQuery
{
/**
* Debug messages.
*/
use LoggerTrait;
/**
* {@inheritdoc}
*/
public function sqlStatement(AbstractCompiler $compiler = null)
{
$driver = $this->database->driver();
if (
!$driver instanceof PostgresDriver
|| (!empty($compiler) && !$compiler instanceof PostgresCompiler)
) {
throw new BuilderException(
"Postgres InsertQuery can be used only with Postgres driver and compiler."
);
}
if ($primary = $driver->getPrimary($this->database->getPrefix() . $this->table)) {
$this->logger()->debug(
"Primary key '{sequence}' automatically resolved for table '{table}'.",
[
'table' => $this->table,
'sequence' => $primary
]
);
}
if (empty($compiler)) {
$compiler = $this->compiler->resetQuoter();
}
return $compiler->compileInsert($this->table, $this->columns, $this->rowsets, $primary);
}
/**
* {@inheritdoc}
*/
public function run()
{
return (int)$this->database->statement(
$this->sqlStatement(), $this->getParameters()
)->fetchColumn();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Validation\Checker;
/**
* Validations can't be fitted to any other checker.
*/
class MixedChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"cardNumber" => "[[Please enter valid card number.]]"
];
/**
* Check credit card passed by Luhn algorithm.
*
* @link http://en.wikipedia.org/wiki/Luhn_algorithm
* @param string $cardNumber
* @return bool
*/
public function cardNumber($cardNumber)
{
if (!is_string($cardNumber) || strlen($cardNumber) < 12) {
return false;
}
$result = 0;
$odd = strlen($cardNumber) % 2;
preg_replace('/[^0-9]+/', '', $cardNumber);
for ($i = 0; $i < strlen($cardNumber); $i++) {
$result += $odd
? $cardNumber[$i]
: (($cardNumber[$i] * 2 > 9) ? $cardNumber[$i] * 2 - 9 : $cardNumber[$i] * 2);
$odd = !$odd;
}
// Check validity.
return ($result % 10 == 0) ? true : false;
}
/**
* Check if value matches value from another field.
*
* @param string $value
* @param string $field
* @param bool $strict
* @return bool
*/
public function match($value, $field, $strict = false)
{
if ($strict) {
return $value === $this->validator()->field($field, null);
}
return $value == $this->validator()->field($field, null);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities\Schemas;
use Spiral\Database\Entities\Schemas\Prototypes\AbstractElement;
use Spiral\Database\Schemas\IndexInterface;
/**
* Abstract index schema with read (see IndexInterface) and write abilities. Must be implemented
* by driver to support DBMS specific syntax and creation rules.
*/
abstract class AbstractIndex extends AbstractElement implements IndexInterface
{
/**
* Index types.
*/
const NORMAL = 'INDEX';
const UNIQUE = 'UNIQUE';
/**
* Index type, by default NORMAL and UNIQUE indexes supported, additional types can be
* implemented on database driver level.
*
* @var string
*/
protected $type = self::NORMAL;
/**
* Columns used to form index.
*
* @var array
*/
protected $columns = [];
/**
* {@inheritdoc}
*
* @param bool $quoted Quote name.
*/
public function getName($quoted = false)
{
if (empty(parent::getName())) {
$this->setName($this->generateName());
}
return parent::getName($quoted);
}
/**
* {@inheritdoc}
*/
public function isUnique()
{
return $this->type == self::UNIQUE;
}
/**
* {@inheritdoc}
*/
public function getColumns()
{
return $this->columns;
}
/**
* Change index type and behaviour to unique/non-unique state.
*
* @param bool $unique
* @return $this
*/
public function unique($unique = true)
{
$this->type = $unique ? self::UNIQUE : self::NORMAL;
return $this;
}
/**
* Change set of index forming columns. Method must support both array and string parameters.
*
* Example:
* $index->columns('key');
* $index->columns('key', 'key2');
* $index->columns(['key', 'key2']);
*
* @param string|array $columns Columns array or comma separated list of parameters.
* @return $this
*/
public function columns($columns)
{
if (!is_array($columns)) {
$columns = func_get_args();
}
$this->columns = $columns;
return $this;
}
/**
* Index sql creation syntax.
*
* @param bool $includeTable Include table ON statement (not required for inline index
* creation).
* @return string
*/
public function sqlStatement($includeTable = true)
{
$statement = [$this->type];
if ($this->isUnique()) {
//UNIQUE INDEX
$statement[] = 'INDEX';
}
$statement[] = $this->getName(true);
if ($includeTable) {
$statement[] = "ON {$this->table->getName(true)}";
}
//Wrapping column names
$columns = join(', ', array_map([$this->table->driver(), 'identifier'], $this->columns));
$statement[] = "({$columns})";
return join(' ', $statement);
}
/**
* Compare two elements together.
*
* @param self $initial
* @return bool
*/
public function compare(self $initial)
{
$normalized = clone $initial;
$normalized->declared = $this->declared;
return $this == $normalized;
}
/**
* Generate unique index name.
*
* @return string
*/
protected function generateName()
{
//We can generate name
$name = $this->table->getName() . '_index_' . join('_', $this->columns) . '_' . uniqid();
if (strlen($name) > 64) {
//Many dbs has limitations on identifier length
$name = md5($name);
}
return $name;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation;
use Spiral\Core\Component;
use Spiral\Translator\Traits\TranslatorTrait;
use Spiral\Validation\Exceptions\ValidationException;
/**
* Checkers used to group set of validation rules under one roof.
*/
abstract class Checker extends Component
{
/**
* Every checker can defined it's own error messages.
*/
use TranslatorTrait;
/**
* Inherit parent validations.
*/
const INHERIT_TRANSLATIONS = true;
/**
* @var Validator
*/
private $validator = null;
/**
* Default error messages associated with checker method by name.
*
* @var array
*/
protected $messages = [];
/**
* Check value using checker method.
*
* @param string $method
* @param mixed $value
* @param array $arguments
* @param Validator $validator Parent validator.
* @return mixed
*/
public function check($method, $value, array $arguments = [], Validator $validator = null)
{
array_unshift($arguments, $value);
$this->validator = $validator;
try {
$result = call_user_func_array([$this, $method], $arguments);
} finally {
$this->validator = null;
}
return $result;
}
/**
* Return default error message for checker condition.
*
* @param string $method
* @param \ReflectionClass $reflection Internal, used to resolve parent messages.
* @return string
*/
public function getMessage($method, \ReflectionClass $reflection = null)
{
if (!empty($reflection)) {
$messages = $reflection->getDefaultProperties()['messages'];
if (isset($messages[$method])) {
//We are inheriting parent messages
return $this->say($messages[$method]);
}
} elseif (isset($this->messages[$method])) {
return $this->say($this->messages[$method]);
}
//Looking for message in parent realization
$reflection = $reflection ?: new \ReflectionClass($this);
if ($reflection->getParentClass() && $reflection->getParentClass()->isSubclassOf(self::class)) {
return $this->getMessage($method, $reflection->getParentClass());
}
return '';
}
/**
* Currently active validator instance.
*
* @return Validator
*/
protected function validator()
{
if (empty($this->validator)) {
throw new ValidationException("Unable to receive parent checker validator.");
}
return $this->validator;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Core\Component;
use Spiral\Models\IdentifiedInterface;
use Spiral\ORM\Exceptions\CacheException;
/**
* Entity cache support. Used to share same model instance across it's child or related objects.
*
* @todo Interface is needed
*/
class EntityCache extends Component
{
/**
* Indication that entity cache is enabled.
*
* @var bool
*/
private $enabled = true;
/**
* Maximum entity cache size. Null is unlimited.
*
* @var int|null
*/
private $cacheSize = null;
/**
* In cases when ORM cache is enabled every constructed instance will be stored here, cache used
* mainly to ensure the same instance of object, even if was accessed from different spots.
* Cache usage increases memory consumption and does not decreases amount of queries being made.
*
* @var RecordEntity[]
*/
private $cache = [];
/**
* Check if entity cache enabled.
*
* @return bool
*/
public function isEnabled()
{
return $this->enabled;
}
/**
* Enable or disable entity cache. Disabling cache will not flush it's values.
*
* @deprecated see configure
* @param bool $enabled
* @param int|null $maxSize Null = unlimited.
* @return $this
*/
public function configureCache($enabled, $maxSize = null)
{
return $this->configure($enabled, $maxSize);
}
/**
* Enable or disable entity cache. Disabling cache will not flush it's values.
*
* @param bool $enabled
* @param int|null $maxSize Null = unlimited.
* @return $this
*/
public function configure($enabled, $maxSize = null)
{
$this->enabled = (bool)$enabled;
if (!is_null($maxSize) && !is_int($maxSize)) {
throw new \InvalidArgumentException("Cache size value has to be null or integer.");
}
$this->cacheSize = $maxSize;
return $this;
}
/**
* Add Record to entity cache (only if cache enabled). Primary key is required for caching.
*
* @param IdentifiedInterface $entity
* @param bool $ignoreLimit Cache overflow will be ignored.
* @return IdentifiedInterface
* @throws CacheException
*/
public function remember(IdentifiedInterface $entity, $ignoreLimit = true)
{
if (empty($entity->primaryKey()) || !$this->enabled) {
return $entity;
}
if (!$ignoreLimit && count($this->cache) > $this->cacheSize) {
throw new CacheException("Entity cache size exceeded.");
}
return $this->cache[get_class($entity) . '.' . $entity->primaryKey()] = $entity;
}
/**
* Remove Record record from entity cache. Primary key is required for caching.
*
* @param IdentifiedInterface $entity
*/
public function forget(IdentifiedInterface $entity)
{
if (empty($entity->primaryKey())) {
return;
}
unset($this->cache[get_class($entity) . '.' . $entity->primaryKey()]);
}
/**
* Check if desired entity was already cached.
*
* @param string $class
* @param mixed $primaryKey
* @return bool
*/
public function has($class, $primaryKey)
{
return isset($this->cache[$class . '.' . $primaryKey]);
}
/**
* Fetch entity from cache.
*
* @param string $class
* @param mixed $primaryKey
* @return null|IdentifiedInterface
*/
public function get($class, $primaryKey)
{
if (empty($this->cache[$class . '.' . $primaryKey])) {
return null;
}
return $this->cache[$class . '.' . $primaryKey];
}
/**
* Flush content of entity cache.
*/
public function flushCache()
{
$this->cache = [];
}
/**
* Destructing.
*/
public function __destruct()
{
$this->flushCache();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders;
use Spiral\Database\Builders\Prototypes\AbstractAffect;
use Spiral\Database\Entities\QueryCompiler;
/**
* Update statement builder.
*/
class DeleteQuery extends AbstractAffect
{
/**
* Change target table.
*
* @param string $into Table name without prefix.
* @return $this
*/
public function from($into)
{
$this->table = $into;
return $this;
}
/**
* {@inheritdoc}
*/
public function getParameters(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler;
}
return $this->flattenParameters($compiler->orderParameters(
QueryCompiler::DELETE_QUERY, $this->whereParameters
));
}
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler->resetQuoter();
}
return $compiler->compileDelete($this->table, $this->whereTokens);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Events;
use Spiral\Events\Traits\EventsTrait;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class EventsTest extends \PHPUnit_Framework_TestCase
{
use EventsTrait;
public function testTrait()
{
$this->assertInstanceOf(EventDispatcherInterface::class, self::events());
$dispatcher = new EventDispatcher();
self::setEvents($dispatcher);
$this->assertEquals($dispatcher, self::events());
/**
* The rest is verified by Symfony, i assume...
*/
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM;
use Spiral\Models\EntityInterface;
/**
* Declares that object can be embedded into Document as some instance and control it's owm (located
* in instance) updates, public fields and validations. Basically it's embeddable entity.
*
* Compositable instance is primary entity type for ODM.
*/
interface CompositableInterface extends EntityInterface, DocumentAccessorInterface
{
/**
* {@inheritdoc}
*
* @param ODM $odm ODM component if any.
* @param mixed $options Implementation specific options. In ODM will always contain field type.
*/
public function __construct(
$value,
EntityInterface $parent = null,
ODM $odm = null,
$options = null
);
/**
* Instance must re-validate data.
*
* @return $this
*/
public function invalidate();
/**
* Every composited object must know how to give it's public data (safe to send to client) to
* parent.
*
* @return array
*/
public function publicFields();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Tokenizer;
use Spiral\Core\HippocampusInterface;
use Spiral\Files\FileManager;
use Spiral\Tokenizer\Configs\TokenizerConfig;
use Spiral\Tokenizer\Tokenizer;
use Spiral\Tokenizer\TokenizerInterface;
class TokenizerTest extends \PHPUnit_Framework_TestCase
{
public function testTokens()
{
$tokenizer = new Tokenizer(
new FileManager(),
new TokenizerConfig(),
$this->getMock(HippocampusInterface::class)
);
$expectedTokens = token_get_all(file_get_contents(__FILE__));
foreach ($tokenizer->fetchTokens(__FILE__) as $id => $token) {
$this->assertTrue(array_key_exists(TokenizerInterface::TYPE, $token));
$this->assertTrue(array_key_exists(TokenizerInterface::LINE, $token));
$this->assertTrue(array_key_exists(TokenizerInterface::CODE, $token));
$expected = $expectedTokens[$id];
if (is_array($expected)) {
$this->assertEquals($expected, $token);
} else {
$this->assertEquals($expected, $token[TokenizerInterface::CODE]);
}
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Validation\Checker;
/**
* Scalar number validations.
*/
class NumberChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"range" => "[[Your value should be in range of {0}-{1}.]]",
"higher" => "[[Your value should be higher than {0}.]]",
"lower" => "[[Your value should be lower than {0}.]]"
];
/**
* Check if number in specified range.
*
* @param float $value
* @param float $begin
* @param float $end
* @return bool
*/
public function range($value, $begin, $end)
{
return $value >= $begin && $value <= $end;
}
/**
* Check if value is bigger or equal that specified.
*
* @param float $value
* @param float $limit
* @return bool
*/
public function higher($value, $limit)
{
return $value >= $limit;
}
/**
* Check if value smaller of equal that specified.
*
* @param float $value
* @param float $limit
* @return bool
*/
public function lower($value, $limit)
{
return $value <= $limit;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Reflections;
use Spiral\Models\DataEntity;
/**
* Reflection associated with one specific DataEntity class.
*/
abstract class ReflectionEntity extends \ReflectionClass
{
/**
* Required to validly merge parent and children attributes.
*/
const BASE_CLASS = DataEntity::class;
/**
* Mutator names.
*/
const MUTATOR_SETTER = 'setter';
const MUTATOR_GETTER = 'getter';
const MUTATOR_ACCESSOR = 'accessor';
/**
* Properties cache.
*
* @invisible
* @var array
*/
private $cache = [];
/**
* @return array
*/
public function getSecured()
{
if ($this->property('secured', true) === '*') {
return $this->property('secured', true);
}
return array_unique($this->property('secured', true));
}
/**
* @return array
*/
public function getFillable()
{
return array_unique($this->property('fillable', true));
}
/**
* @return array
*/
public function getHidden()
{
return array_unique($this->property('hidden', true));
}
/**
* @return array
*/
public function getValidates()
{
return $this->property('validates', true);
}
/**
* @return array
*/
public function getSetters()
{
return $this->getMutators()[self::MUTATOR_SETTER];
}
/**
* @return array
*/
public function getGetters()
{
return $this->getMutators()[self::MUTATOR_GETTER];
}
/**
* @return array
*/
public function getAccessors()
{
return $this->getMutators()[self::MUTATOR_ACCESSOR];
}
/**
* Get methods declared in current class and exclude methods declared in parents.
*
* @return \ReflectionMethod[]
*/
public function getLocalMethods()
{
$methods = [];
foreach ($this->getMethods() as $method) {
if ($method->getDeclaringClass()->getName() != $this->getName()) {
continue;
}
$methods[] = $method;
}
return $methods;
}
/**
* Fields associated with their type.
*
* @return array
*/
abstract public function getFields();
/**
* Model mutators grouped by their type.
*
* @return array
*/
public function getMutators()
{
$mutators = [
self::MUTATOR_GETTER => [],
self::MUTATOR_SETTER => [],
self::MUTATOR_ACCESSOR => []
];
foreach ($this->property('getters', true) as $field => $filter) {
$mutators[self::MUTATOR_GETTER][$field] = $filter;
}
foreach ($this->property('setters', true) as $field => $filter) {
$mutators[self::MUTATOR_SETTER][$field] = $filter;
}
foreach ($this->property('accessors', true) as $field => $filter) {
$mutators[self::MUTATOR_ACCESSOR][$field] = $filter;
}
return $mutators;
}
/**
* @return string
*/
public function __toString()
{
return $this->getName();
}
/**
* Must return instance of ReflectionEntity or null if no parent found.
*
* @return self|null
*/
abstract protected function parentSchema();
/**
* Read default model property value, will read "protected" and "private" properties. Method
* raises entity event "describe" to allow it traits modify needed values.
*
* @param string $property Property name.
* @param bool $merge If true value will be merged with all parent declarations.
* @return mixed
*/
final protected function property($property, $merge = false)
{
if (isset($this->cache[$property])) {
//Property merging and trait events are pretty slow
return $this->cache[$property];
}
$properties = $this->getDefaultProperties();
if (isset($properties[$property])) {
$value = $properties[$property];
} else {
return null;
}
//Merge with parent value requested
if ($merge && ($this->getParentClass()->getName() != static::BASE_CLASS)) {
//For the reasons we can merge only arrays
if (is_array($value) && !empty($parent = $this->parentSchema())) {
$value = array_merge($parent->property($property, $merge), $value);
}
}
//To let traits apply schema changes
return $this->cache[$property] = call_user_func(
[$this->getName(), 'describeProperty'], $this, $property, $value
);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage\Servers;
use Spiral\Files\FilesInterface;
use Spiral\ODM\Entities\MongoDatabase;
use Spiral\ODM\ODM;
use Spiral\Storage\BucketInterface;
use Spiral\Storage\Exceptions\ServerException;
use Spiral\Storage\StorageServer;
/**
* Provides abstraction level to work with data located in GridFS storage.
*/
class GridfsServer extends StorageServer
{
/**
* @var array
*/
protected $options = [
'database' => 'default'
];
/**
* @var MongoDatabase
*/
protected $database = null;
/**
* @param FilesInterface $files
* @param ODM $odm
* @param array $options
*/
public function __construct(FilesInterface $files, ODM $odm, array $options)
{
parent::__construct($files, $options);
$this->database = $odm->database($this->options['database']);
}
/**
* {@inheritdoc}
*
* @return bool|\MongoGridFSFile
*/
public function exists(BucketInterface $bucket, $name)
{
return $this->gridFS($bucket)->findOne(['filename' => $name]);
}
/**
* {@inheritdoc}
*/
public function size(BucketInterface $bucket, $name)
{
if (!$file = $this->exists($bucket, $name)) {
return false;
}
return $file->getSize();
}
/**
* {@inheritdoc}
*/
public function put(BucketInterface $bucket, $name, $source)
{
//We have to remove existed file first, this might not be super optimal operation.
//Can be re-thinked
$this->delete($bucket, $name);
/**
* For some reason mongo driver i have don't want to read wrapped streams, it either dies
* with "error setting up file" or hangs.
*
* I was not able to debug cause of this error at this moment as i don't have Visual Studio
* at this PC.
*
* However, error caused by some code from this file. In a meantime i will write content to
* local file before sending it to mongo, this is DIRTY, but will work for some time.
*
* @link https://github.com/mongodb/mongo-php-driver/blob/master/gridfs/gridfs.c
*/
$tempFilename = $this->files->tempFilename();
copy($this->castFilename($source), $tempFilename);
if (!$this->gridFS($bucket)->storeFile($tempFilename, ['filename' => $name])) {
throw new ServerException("Unable to store {$name} in GridFS server.");
}
$this->files->delete($tempFilename);
return true;
}
/**
* {@inheritdoc}
*/
public function allocateStream(BucketInterface $bucket, $name)
{
if (!$file = $this->exists($bucket, $name)) {
throw new ServerException(
"Unable to create stream for '{$name}', object does not exists."
);
}
return \GuzzleHttp\Psr7\stream_for($file->getResource());
}
/**
* {@inheritdoc}
*/
public function delete(BucketInterface $bucket, $name)
{
$this->gridFS($bucket)->remove(['filename' => $name]);
}
/**
* {@inheritdoc}
*/
public function rename(BucketInterface $bucket, $oldname, $newname)
{
$this->delete($bucket, $newname);
return $this->gridFS($bucket)->update(
['filename' => $oldname],
['$set' => ['filename' => $newname]]
);
}
/**
* Get valid gridfs collection associated with container.
*
* @param BucketInterface $bucket Bucket instance.
* @return \MongoGridFS
*/
protected function gridFS(BucketInterface $bucket)
{
$gridFs = $this->database->getGridFS($bucket->getOption('collection'));
$gridFs->createIndex(['filename' => 1]);
return $gridFs;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
use Spiral\Models\Exceptions\EntityExceptionInterface;
use Spiral\Validation\ValidatesInterface;
/**
* Generic data entity instance.
*/
interface EntityInterface extends ValidatesInterface
{
/**
* Check if field known to entity, field value can be null!
*
* @param string $name
* @return bool
*/
public function hasField($name);
/**
* Set entity field value.
*
* @param string $name
* @param mixed $value
* @throws EntityExceptionInterface
*/
public function setField($name, $value);
/**
* Get value of entity field.
*
* @param string $name
* @param mixed $default
* @return mixed|AccessorInterface
* @throws EntityExceptionInterface
*/
public function getField($name, $default = null);
/**
* Update entity fields using mass assignment. Only allowed fields must be set.
*
* @param array|\Traversable $fields
* @throws EntityExceptionInterface
*/
public function setFields($fields = []);
/**
* Get entity field values.
*
* @return array
* @throws EntityExceptionInterface
*/
public function getFields();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLite;
use Spiral\Database\Entities\QueryCompiler as AbstractCompiler;
/**
* SQLite specific syntax compiler.
*/
class QueryCompiler extends AbstractCompiler
{
/**
* {@inheritdoc}
*/
public function compileInsert($table, array $columns, array $rowsets)
{
if (count($rowsets) == 1) {
return parent::compileInsert($table, $columns, $rowsets);
}
//SQLite uses alternative syntax
$statement = [];
$statement[] = "INSERT INTO {$this->quote($table, true)} ({$this->prepareColumns($columns)})";
foreach ($rowsets as $rowset) {
if (count($statement) == 1) {
$selectColumns = [];
foreach ($columns as $column) {
$selectColumns[] = "? AS {$this->quote($column)}";
}
$statement[] = 'SELECT ' . join(', ', $selectColumns);
} else {
$statement[] = 'UNION SELECT ' . trim(str_repeat('?, ', count($columns)), ', ');
}
}
return join("\n", $statement);
}
/**
* {@inheritdoc}
*
* @link http://stackoverflow.com/questions/10491492/sqllite-with-skip-offset-only-not-limit
*/
protected function compileLimit($limit, $offset)
{
if (empty($limit) && empty($offset)) {
return '';
}
$statement = '';
if (!empty($limit) || !empty($offset)) {
$statement = "LIMIT " . ($limit ?: '-1') . " ";
}
if (!empty($offset)) {
$statement .= "OFFSET {$offset}";
}
return trim($statement);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Spiral\Core\Component;
use Spiral\Database\Entities\Schemas\AbstractTable;
use Spiral\Database\Entities\SynchronizationBus;
use Spiral\ORM\Configs\ORMConfig;
use Spiral\ORM\Entities\Schemas\RecordSchema;
use Spiral\ORM\Exceptions\RecordSchemaException;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\Exceptions\SchemaException;
use Spiral\ORM\ORM;
use Spiral\ORM\Record;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\Schemas\RelationInterface;
use Spiral\Tokenizer\ClassLocatorInterface;
/**
* Schema builder responsible for static analysis of existed ORM Records, their schemas,
* validations, related tables, requested indexes and etc.
*/
class SchemaBuilder extends Component
{
/**
* @var RecordSchema[]
*/
private $records = [];
/**
* @var AbstractTable[]
*/
private $tables = [];
/**
* @var ORMConfig
*/
protected $config = null;
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* @param ORMConfig $config
* @param ORM $orm
* @param ClassLocatorInterface $locator
*/
public function __construct(ORMConfig $config, ORM $orm, ClassLocatorInterface $locator)
{
$this->config = $config;
$this->orm = $orm;
//Locating all models and sources
$this->locateRecords($locator)->locateSources($locator);
//Casting relations
$this->castRelations();
}
/**
* Check if Record class known to schema builder.
*
* @param string $class
* @return bool
*/
public function hasRecord($class)
{
return isset($this->records[$class]);
}
/**
* Instance of RecordSchema associated with given class name.
*
* @param string $class
* @return RecordSchema
* @throws SchemaException
* @throws RecordSchemaException
*/
public function record($class)
{
if ($class == RecordEntity::class || $class == Record::class) {
//No need to remember schema for abstract Document
return new RecordSchema($this, RecordEntity::class);
}
if (!isset($this->records[$class])) {
throw new SchemaException("Unknown record class '{$class}'.");
}
return $this->records[$class];
}
/**
* @return RecordSchema[]
*/
public function getRecords()
{
return $this->records;
}
/**
* Check if given table was declared by one of record or relation.
*
* @param string $database Table database.
* @param string $table Table name without prefix.
* @return bool
*/
public function hasTable($database, $table)
{
return isset($this->tables[$database . '/' . $table]);
}
/**
* Request table schema. Every non empty table schema will be synchronized with it's databases
* when executeSchema() method will be called.
*
* Attention, every declared table will be synced with database if their initiator allows such
* operation.
*
* @param string $database Table database.
* @param string $table Table name without prefix.
* @return AbstractTable
*/
public function declareTable($database, $table)
{
$database = $this->resolveDatabase($database);
if (isset($this->tables[$database . '/' . $table])) {
return $this->tables[$database . '/' . $table];
}
$schema = $this->orm->database($database)->table($table)->schema();
return $this->tables[$database . '/' . $table] = $schema;
}
/**
* Perform schema reflection to database(s). All declared tables will created or altered. Only
* tables linked to non abstract records and record with active schema parameter will be
* executed.
*
* SchemaBuilder will not allow (SchemaException) to create or alter tables columns declared
* by abstract or records with ACTIVE_SCHEMA constant set to false. ActiveSchema still can
* declare foreign keys and indexes (most of relations automatically request index or foreign
* key), but they are going to be ignored.
*
* Due principals of database schemas and ORM component logic no data or columns will ever be
* removed from database. In addition column renaming will cause creation of another column.
*
* Use database migrations to solve more complex database questions. Or disable ACTIVE_SCHEMA
* and live like normal people.
*
* @throws SchemaException
* @throws \Spiral\Database\Exceptions\SchemaException
* @throws \Spiral\Database\Exceptions\QueryException
* @throws \Spiral\Database\Exceptions\DriverException
*/
public function synchronizeSchema()
{
$bus = new SynchronizationBus($this->getTables());
$bus->syncronize();
}
/**
* Resolve real database name using it's alias.
*
* @see DatabaseProvider
* @param string|null $alias
* @return string
*/
public function resolveDatabase($alias)
{
return $this->orm->database($alias)->getName();
}
/**
* Get all mutators associated with field type.
*
* @param string $type Field type.
* @return array
*/
public function getMutators($type)
{
return $this->config->getMutators($type);
}
/**
* Get mutator alias if presented. Aliases used to simplify schema (accessors) definition.
*
* @param string $alias
* @return string|array
*/
public function mutatorAlias($alias)
{
return $this->config->mutatorAlias($alias);
}
/**
* Normalize record schema in lighter structure to be saved in ORM component memory.
*
* @return array
* @throws SchemaException
*/
public function normalizeSchema()
{
$result = [];
foreach ($this->records as $record) {
if ($record->isAbstract()) {
continue;
}
$schema = [
ORM::M_ROLE_NAME => $record->getRole(),
ORM::M_SOURCE => $record->getSource(),
ORM::M_TABLE => $record->getTable(),
ORM::M_DB => $record->getDatabase(),
ORM::M_PRIMARY_KEY => $record->getPrimaryKey(),
ORM::M_HIDDEN => $record->getHidden(),
ORM::M_SECURED => $record->getSecured(),
ORM::M_FILLABLE => $record->getFillable(),
ORM::M_COLUMNS => $record->getDefaults(),
ORM::M_NULLABLE => $record->getNullable(),
ORM::M_MUTATORS => $record->getMutators(),
ORM::M_VALIDATES => $record->getValidates(),
ORM::M_RELATIONS => $this->packRelations($record)
];
ksort($schema);
$result[$record->getName()] = $schema;
}
return $result;
}
/**
* Create appropriate instance of RelationSchema based on it's definition provided by ORM Record
* or manually. Due internal format first definition key will be stated as definition type and
* key value as record/entity definition relates too.
*
* @param RecordSchema $record
* @param string $name
* @param array $definition
* @return RelationInterface
* @throws SchemaException
*/
public function relationSchema(RecordSchema $record, $name, array $definition)
{
if (empty($definition)) {
throw new SchemaException("Relation definition can not be empty.");
}
reset($definition);
//Relation type must be provided as first in definition
$type = key($definition);
//We are letting ORM to resolve relation schema using container
$relation = $this->orm->relationSchema($type, $this, $record, $name, $definition);
if ($relation->hasEquivalent()) {
//Some relations may declare equivalent relation to be used instead,
//used for Morphed relations
return $relation->createEquivalent();
}
return $relation;
}
/**
* Get list of tables to be updated, method must automatically check if table actually allowed
* to be updated.
*
* @return AbstractTable[]
*/
public function getTables()
{
$tables = [];
foreach ($this->tables as $table) {
//We can only alter table columns if record allows us
$record = $this->findRecord($table);
if (empty($record)) {
$tables[] = $table;
//Potentially pivot table, no related records
continue;
}
if ($record->isAbstract() || !$record->isActive() || empty($table->getColumns())) {
//Abstract tables might declare table schema, but we are going to ignore it
continue;
}
$tables[] = $table;
}
return $tables;
}
/**
* Locate every available Record class.
*
* @param ClassLocatorInterface $locator
* @return $this
* @throws SchemaException
*/
protected function locateRecords(ClassLocatorInterface $locator)
{
//Table names associated with records
$tables = [];
foreach ($locator->getClasses(RecordEntity::class) as $class => $definition) {
if ($class == RecordEntity::class || $class == Record::class) {
continue;
}
$this->records[$class] = $record = new RecordSchema($this, $class);
if (!$record->isAbstract()) {
//See comment near exception
continue;
}
//Record associated tableID (includes resolved database name)
$tableID = $record->getTableID();
if (isset($tables[$tableID])) {
//We are not allowing multiple records talk to same database, unless they one of them
//is abstract
throw new SchemaException(
"Record '{$record}' associated with "
. "same source table '{$tableID}' as '{$tables[$tableID]}'."
);
}
$tables[$tableID] = $record;
}
return $this;
}
/**
* Locate ORM entities sources.
*
* @param ClassLocatorInterface $locator
* @return $this
*/
protected function locateSources(ClassLocatorInterface $locator)
{
foreach ($locator->getClasses(RecordSource::class) as $class => $definition) {
$reflection = new \ReflectionClass($class);
if ($reflection->isAbstract() || empty($record = $reflection->getConstant('RECORD'))) {
continue;
}
if ($this->hasRecord($record)) {
//Associating source with record
$this->record($record)->setSource($class);
}
}
return $this;
}
/**
* SchemaBuilder will request every located RecordSchema to declare it's relations. In addition
* this methods will create inversed set of relations.
*
* @throws SchemaException
* @throws RelationSchemaException
* @throws RecordSchemaException
*/
protected function castRelations()
{
$inversedRelations = [];
foreach ($this->records as $record) {
if ($record->isAbstract()) {
//Abstract records can not declare relations or tables
continue;
}
$record->castRelations();
foreach ($record->getRelations() as $relation) {
if ($relation->isInversable()) {
//Relation can be automatically inversed
$inversedRelations[] = $relation;
}
}
}
/**
* We have to perform inversion after every generic relation was defined. Sometimes records
* can define inversed relation by themselves.
*
* @var RelationInterface $relation
*/
foreach ($inversedRelations as $relation) {
if ($relation->isInversable()) {
//We have to check inversion again in case if relation name already taken
$relation->inverseRelation();
}
}
}
/**
* Find record related to given table. This operation is required to catch if some
* relation/schema declared values in passive (no altering) table. Might return if no records
* find (pivot or user specified tables).
*
* @param AbstractTable $table
* @return RecordSchema|null
*/
private function findRecord(AbstractTable $table)
{
foreach ($this->getRecords() as $record) {
if ($record->tableSchema() === $table) {
return $record;
}
}
//No associated record were found
return null;
}
/**
* Normalize and pack every declared record relation schema.
*
* @param RecordSchema $record
* @return array
*/
private function packRelations(RecordSchema $record)
{
$result = [];
foreach ($record->getRelations() as $name => $relation) {
$result[$name] = $relation->normalizeSchema();
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
use Doctrine\Common\Inflector\Inflector;
use Spiral\Core\Component;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Models\Events\DescribeEvent;
use Spiral\Models\Events\EntityEvent;
use Spiral\Models\Exceptions\AccessorExceptionInterface;
use Spiral\Models\Exceptions\EntityException;
use Spiral\Models\Exceptions\FieldExceptionInterface;
use Spiral\Models\Reflections\ReflectionEntity;
use Spiral\Validation\Events\ValidatedEvent;
use Spiral\Validation\Exceptions\ValidationException;
use Spiral\Validation\Traits\ValidatorTrait;
use Spiral\Validation\ValidatorInterface;
/**
* DataEntity in spiral used to represent basic data set with validation rules, filters and
* accessors. Most of spiral models (ORM and ODM, HttpFilters) will extend data entity. In addition
* it creates magic set of getters and setters for every field name (see validator trait) in model.
*/
class DataEntity extends Component implements
EntityInterface,
\JsonSerializable,
\IteratorAggregate,
\ArrayAccess
{
/**
* Every entity can be validated, in addition validation trait will load Translator and Event
* traits.
*/
use ValidatorTrait;
/**
* Field format declares how entity must process magic setters and getters. Available values:
* camelCase, tableize.
*/
const FIELD_FORMAT = 'camelCase';
/**
* Every entity might have set of traits which can be initiated manually or at moment of
* construction model instance. Array will store already initiated model names.
*
* @var array
*/
private static $initiated = [];
/**
* Indicates that model data have been validated since last change.
*
* @var bool
*/
private $validated = true;
/**
* List of fields must be hidden from publicFields() method.
*
* @see publicFields()
* @var array
*/
protected $hidden = [];
/**
* Set of fields allowed to be filled using setFields() method.
*
* @see setFields()
* @var array
*/
protected $fillable = [];
/**
* List of fields not allowed to be filled by setFields() method. Replace with and empty array
* to allow all fields.
*
* By default all entity fields are settable! Opposite behaviour has to be described in entity
* child implementations.
*
* @see setFields()
* @var array|string
*/
protected $secured = [];
/**
* @see setField()
* @var array
*/
protected $setters = [];
/**
* @see getField()
* @var array
*/
protected $getters = [];
/**
* Accessor used to mock field data and filter every request thought itself.
*
* @see getField()
* @see setField()
* @var array
*/
protected $accessors = [];
/**
* @param array $fields
*/
public function __construct(array $fields = [])
{
$this->fields = $fields;
if (!isset(self::$initiated[get_class($this)])) {
self::initialize();
}
}
/**
* Routes user function in format of (get|set)FieldName into (get|set)Field(fieldName, value).
*
* @see getFeld()
* @see setField()
* @param string $method
* @param array $arguments
* @return $this|mixed|null|AccessorInterface
* @throws EntityException
*/
public function __call($method, array $arguments)
{
if (method_exists($this, $method)) {
throw new EntityException(
"Method name '{$method}' is ambiguous and can not be used as magic setter."
);
}
if (strlen($method) <= 3) {
//Get/set needs exactly 0-1 argument
throw new EntityException("Undefined method {$method}.");
}
$field = substr($method, 3);
switch (static::FIELD_FORMAT) {
case 'camelCase':
$field = Inflector::camelize($field);
break;
case 'tableize':
$field = Inflector::tableize($field);
break;
default:
throw new EntityException(
"Undefined field format '" . static::FIELD_FORMAT . "'."
);
}
switch (substr($method, 0, 3)) {
case 'get':
return $this->getField($field);
case 'set':
if (count($arguments) === 1) {
$this->setField($field, $arguments[0]);
//setFieldA($a)->setFieldB($b)
return $this;
}
}
throw new EntityException("Undefined method {$method}.");
}
/**
* {@inheritdoc}
*
* @see $fillable
* @see $secured
* @see isFillable()
* @param array|\Traversable $fields
* @param bool $all Fill all fields including non fillable.
* @return $this
* @throws AccessorExceptionInterface
*/
public function setFields($fields = [], $all = false)
{
if (!is_array($fields) && !$fields instanceof \Traversable) {
return $this;
}
foreach ($fields as $name => $value) {
if ($all || $this->isFillable($name)) {
try {
$this->setField($name, $value, true);
} catch (FieldExceptionInterface $e) {
//We are supressing field setting exceptions
}
}
}
return $this;
}
/**
* {@inheritdoc}
*
* Every getter and accessor will be applied/constructed if filter argument set to true.
*
* @param bool $filter
* @throws AccessorExceptionInterface
*/
public function getFields($filter = true)
{
$result = [];
foreach ($this->fields as $name => $field) {
$result[$name] = $this->getField($name, null, $filter);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function hasField($name)
{
return array_key_exists($name, $this->fields);
}
/**
* {@inheritdoc}
*
* @param bool $filter If false, associated field setter or accessor will be ignored.
* @throws AccessorExceptionInterface
*/
public function setField($name, $value, $filter = true)
{
if ($value instanceof AccessorInterface) {
$this->fields[$name] = $value->embed($this);
return;
}
$this->validated = false;
if (!$filter) {
$this->fields[$name] = $value;
return;
}
if (!empty($accessor = $this->getMutator($name, 'accessor'))) {
$field = $this->fields[$name];
if (empty($field) || !($field instanceof AccessorInterface)) {
$this->fields[$name] = $field = $this->createAccessor($accessor, $field);
}
//Letting accessor to set value
$field->setValue($value);
return;
}
if (!empty($setter = $this->getMutator($name, 'setter'))) {
try {
$this->fields[$name] = call_user_func($setter, $value);
} catch (\ErrorException $exception) {
//Exceptional situation, we are choosing to keep original field value
}
} else {
$this->fields[$name] = $value;
}
}
/**
* {@inheritdoc}
*
* @param bool $filter If false, associated field getter will be ignored.
* @throws AccessorExceptionInterface
*/
public function getField($name, $default = null, $filter = true)
{
$value = $this->hasField($name) ? $this->fields[$name] : $default;
if ($value instanceof AccessorInterface) {
//Accessor will deal with setting value by itself
return $value;
}
if (!empty($accessor = $this->getMutator($name, 'accessor'))) {
return $this->fields[$name] = $this->createAccessor($accessor, $value);
}
if ($filter && !empty($getter = $this->getMutator($name, 'getter'))) {
try {
return call_user_func($getter, $value);
} catch (\ErrorException $exception) {
//Trying to filter null value, every filter must support it
return call_user_func($getter, null);
}
}
return $value;
}
/**
* Attach custom validator to model.
*
* @param ValidatorInterface $validator
*/
public function setValidator(ValidatorInterface $validator)
{
$this->validator = $validator;
$this->validated = false;
}
/**
* @param mixed $offset
* @return bool
*/
public function __isset($offset)
{
return $this->hasField($offset);
}
/**
* @param mixed $offset
* @return mixed
* @throws AccessorExceptionInterface
*/
public function __get($offset)
{
return $this->getField($offset);
}
/**
* @param mixed $offset
* @param mixed $value
* @throws AccessorExceptionInterface
*/
public function __set($offset, $value)
{
$this->setField($offset, $value);
}
/**
* @param mixed $offset
*/
public function __unset($offset)
{
$this->validated = false;
unset($this->fields[$offset]);
}
/**
* {@inheritdoc}
*/
public function offsetExists($offset)
{
return $this->__isset($offset);
}
/**
* {@inheritdoc}
*
* @throws AccessorExceptionInterface
*/
public function offsetGet($offset)
{
return $this->getField($offset);
}
/**
* {@inheritdoc}
*
* @throws AccessorExceptionInterface
*/
public function offsetSet($offset, $value)
{
$this->setField($offset, $value);
}
/**
* {@inheritdoc}
*/
public function offsetUnset($offset)
{
$this->__unset($offset);
}
/**
* {@inheritdoc}
*/
public function getIterator()
{
return new \ArrayIterator($this->getFields());
}
/**
* Get model fields but exclude hidden one.
*
* @see $hidden
* @see getFields()
* @return array
* @throws AccessorExceptionInterface
*/
public function publicFields()
{
$publicFields = $this->getFields();
foreach ($this->hidden as $secured) {
unset($publicFields[$secured]);
}
return $publicFields;
}
/**
* Serialize entity data into plain array.
*
* @return array
* @throws AccessorExceptionInterface
*/
public function serializeData()
{
$result = $this->fields;
foreach ($result as $field => $value) {
if ($value instanceof AccessorInterface) {
$result[$field] = $value->serializeData();
}
}
return $result;
}
/**
* {@inheritdoc}
*
* By default use publicFields to be json serialized.
*/
public function jsonSerialize()
{
return $this->publicFields();
}
/**
* Entity must re-validate data.
*
* @param bool $soft Do not invalidate nested models (if such presented).
* @return $this
*/
public function invalidate($soft = false)
{
$this->validated = false;
if ($soft) {
return $this;
}
//Invalidating all compositions
foreach ($this->getFields() as $value) {
//Let's force composition construction
if ($value instanceof self) {
$value->invalidate($soft);
}
}
return $this;
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'fields' => $this->getFields(),
'errors' => $this->getErrors()
];
}
/**
* Validate model fields.
*
* @param bool $reset
* @return bool
* @throws ValidationException
* @throws SugarException
* @event validation()
* @event validated($errors)
*/
protected function validate($reset = false)
{
if (empty($this->validates) && empty($this->validator)) {
//No validation rules assigned, nothing to do
$this->validated = true;
}
if ($this->validated && !$reset) {
//Nothing to do
return empty($this->errors);
}
//Refreshing validation fields
$this->validator()->setData($this->fields);
/**
* @var ValidatedEvent $validatedEvent
*/
$validatedEvent = $this->dispatch('validated', new ValidatedEvent(
$this->validator()->getErrors()
));
//Validation performed
$this->validated = true;
//Collecting errors if any
return empty($this->errors = $validatedEvent->getErrors());
}
/**
* Check if field can be set using setFields() method.
*
* @see setField()
* @see $fillable
* @see $secured
* @param string $field
* @return bool
*/
protected function isFillable($field)
{
if (!empty($this->fillable)) {
return in_array($field, $this->fillable);
}
if ($this->secured === '*') {
return false;
}
return !in_array($field, $this->secured);
}
/**
* Check and return name of mutator (getter, setter, accessor) associated with specific field.
*
* @param string $field
* @param string $mutator Mutator type (setter, getter, accessor).
* @return mixed|null
* @throws EntityException
*/
protected function getMutator($field, $mutator)
{
//We do support 3 mutators: getter, setter and accessor, all of them can be
//referenced to valid field name by adding "s" at the end
$mutator = $mutator . 's';
if (isset($this->{$mutator}[$field])) {
return $this->{$mutator}[$field];
}
return null;
}
/**
* Create instance of field accessor.
*
* @param string $accessor
* @param mixed $value
* @return AccessorInterface
* @throws AccessorExceptionInterface
*/
protected function createAccessor($accessor, $value)
{
return new $accessor($value, $this);
}
/**
* Destruct data entity.
*/
public function __destruct()
{
$this->fields = [];
$this->validator = null;
}
/**
* {@inheritdoc}
*/
public static function create($fields = [])
{
$entity = new static([]);
$entity->setFields($fields);
$entity->dispatch('created', new EntityEvent($entity));
return $entity;
}
/**
* Method used while entity static analysis to describe model related property using even
* dispatcher and associated model traits.
*
* @param ReflectionEntity $reflection
* @param string $property
* @param mixed $value
* @return mixed Returns filtered value.
* @event describe(DescribeEvent)
*/
public static function describeProperty(ReflectionEntity $reflection, $property, $value)
{
static::initialize(true);
/**
* Clarifying property value using traits or other listeners.
*
* @var DescribeEvent $describeEvent
*/
$describeEvent = static::events()->dispatch(
'describe', new DescribeEvent($reflection, $property, $value)
);
return $describeEvent->getValue();
}
/**
* Clear initiated objects list.
*/
public static function resetInitiated()
{
self::$initiated = [];
}
/**
* Initiate associated model traits. System will look for static method with "__init__" prefix.
* Attention, trait must
*
* @param bool $analysis Must be set to true while static reflection analysis.
*/
protected static function initialize($analysis = false)
{
$state = $class = static::class;
if ($analysis) {
//Normal and initialization for analysis must load different methods
$state = "{$class}~";
$prefix = '__describe__';
} else {
$prefix = '__init__';
}
if (isset(self::$initiated[$state])) {
//Already initiated (not for analysis)
return;
}
foreach (get_class_methods($class) as $method) {
if (strpos($method, $prefix) === 0) {
forward_static_call(['static', $method]);
}
}
self::$initiated[$state] = true;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Exceptions;
/**
* Entity cache exception.
*/
class CacheException extends ORMException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Exceptions;
/**
* When record schema defines index, column or relation incorrectly.
*/
class DefinitionException extends SchemaException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Pagination;
/**
* Paginator with predictable length (count).
*/
interface PredictableInterface extends PaginatorInterface
{
/**
* Change predicted length (count).
*
* @param int $count
*/
public function setCount($count);
/**
* The count of pages required to represent all records using a specified limit value.
*
* @return int
*/
public function countPages();
/**
* The count or records displayed on current page can vary from 0 to any limit value. Only the
* last page can have less records than is specified in the limit.
*
* @return int
*/
public function countDisplayed();
/**
* Does paginator needed to be applied? Should return false if all records can be shown on one
* page.
*
* @return bool
*/
public function isRequired();
/**
* Next page number. Should return will be false if the current page is the last page.
*
* @return bool|int
*/
public function nextPage();
/**
* Previous page number. Should return false if the current page is first page.
*
* @return bool|int
*/
public function previousPage();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Models\IdentifiedInterface;
/**
* Generic ORM contract for records to be constructed and updated by ORM.
*/
interface RecordInterface extends IdentifiedInterface
{
/**
* Due setContext() method and entity cache of ORM any custom initiation code in constructor
* must not depends on relations data.
*
* @see Component::staticContainer()
* @see setContext
* @param array $data
* @param bool|false $loaded
* @param ORM|null $orm
* @param array $ormSchema
*/
public function __construct(
array $data = [],
$loaded = false,
ORM $orm = null,
array $ormSchema = []
);
/**
* Indication that record data was deleted.
*
* @return bool
*/
public function isDeleted();
/**
* Role name used in morphed relations to detect outer record table and class. In general case
* must simply return unique name.
*
* @return string
*/
public function recordRole();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Injections;
use Spiral\Database\Entities\QueryCompiler;
/**
* Expressions require instance of QueryCompiler at moment of statementGeneration. For
* simplification purposes every expression is instance of fragment (no compiler is required),
* however such instance has to be provided at moment of compilation.
*/
interface ExpressionInterface extends FragmentInterface
{
/**
* @param QueryCompiler|null $compiler
* @return mixed
*/
public function sqlStatement(QueryCompiler $compiler = null);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Events;
use Spiral\Models\Reflections\ReflectionEntity;
use Symfony\Component\EventDispatcher\Event;
/**
* Raised while entity analysis to allow traits and other listeners apply changed to entity schema.
*/
class DescribeEvent extends Event
{
/**
* @var ReflectionEntity
*/
private $reflection = null;
/**
* @var string
*/
private $property = '';
/**
* @var mixed
*/
private $value = null;
/**
* @param ReflectionEntity $reflection
* @param string $property
* @param mixed $value
*/
public function __construct(ReflectionEntity $reflection, $property, $value)
{
$this->reflection = $reflection;
$this->property = $property;
$this->value = $value;
}
/**
* @return ReflectionEntity
*/
public function reflection()
{
return $this->reflection;
}
/**
* @return string
*/
public function getProperty()
{
return $this->property;
}
/**
* @param string $property
*/
public function setProperty($property)
{
$this->property = $property;
}
/**
* @return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* @param mixed $value
*/
public function setValue($value)
{
$this->value = $value;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Relations;
use Spiral\Models\EntityInterface;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\ORM\RecordEntity;
/**
* Similar to BelongsTo, however morph key value used to resolve parent record.
*/
class BelongsToMorphed extends BelongsTo
{
/**
* Relation type, required to fetch record class from relation definition.
*/
const RELATION_TYPE = RecordEntity::BELONGS_TO_MORPHED;
/**
* {@inheritdoc}
*/
public function associate(EntityInterface $related = null)
{
parent::associate($related);
$morphKey = $this->definition[RecordEntity::MORPH_KEY];
if (is_null($related)) {
$this->parent->setField($morphKey, null);
return;
}
/**
* @var RecordEntity $related
*/
$this->parent->setField($morphKey, $related->recordRole());
}
/**
* {@inheritdoc}
*/
protected function createSelector()
{
//To prevent morph key being added as where
$selector = new RecordSelector($this->orm, $this->getClass());
return $selector->where(
$selector->primaryAlias() . '.' . $this->definition[RecordEntity::OUTER_KEY],
$this->parent->getField($this->definition[RecordEntity::INNER_KEY], false)
);
}
/**
* {@inheritdoc}
*
* @throws RelationException
*/
protected function getClass()
{
$morphKey = $this->definition[RecordEntity::MORPH_KEY];
if (empty($this->parent->getField($morphKey))) {
throw new RelationException("Unable to resolve parent entity, morph key is empty.");
}
return parent::getClass()[$this->parent->getField($morphKey)];
}
/**
* {@inheritdoc}
*/
protected function deassociate()
{
parent::deassociate();
//Dropping morph key value
$this->parent->setField($this->definition[RecordEntity::MORPH_KEY], null);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Encrypter;
use Spiral\Encrypter\Encrypter;
class EncryptionTest extends \PHPUnit_Framework_TestCase
{
public function testEncryption()
{
$encrypter = $this->makeEncrypter();
$encrypted = $encrypter->encrypt('test string');
$this->assertNotEquals('test string', $encrypted);
$this->assertEquals('test string', $encrypter->decrypt($encrypted));
$encrypter->setKey('0987654321123456');
$encrypted = $encrypter->encrypt('test string');
$this->assertNotEquals('test string', $encrypted);
$this->assertEquals('test string', $encrypter->decrypt($encrypted));
$encrypter->setCipher('aes-128-cbc');
$encrypted = $encrypter->encrypt('test string');
$this->assertNotEquals('test string', $encrypted);
$this->assertEquals('test string', $encrypter->decrypt($encrypted));
}
/**
* @expectedException \Spiral\Encrypter\Exceptions\DecryptException
* @expectedExceptionMessage Invalid dataset.
*/
public function testBadData()
{
$encrypter = $this->makeEncrypter();
$encrypted = $encrypter->encrypt('test string');
$this->assertNotEquals('test string', $encrypted);
$this->assertEquals('test string', $encrypter->decrypt($encrypted));
$encrypter->decrypt('badData.' . $encrypted);
}
/**
* @expectedException \Spiral\Encrypter\Exceptions\DecryptException
* @expectedExceptionMessage Encrypted data does not have valid signature.
*/
public function testBadSignature()
{
$encrypter = $this->makeEncrypter();
$encrypted = $encrypter->encrypt('test string');
$this->assertNotEquals('test string', $encrypted);
$this->assertEquals('test string', $encrypter->decrypt($encrypted));
$encrypted = base64_decode($encrypted);
$encrypted = json_decode($encrypted, true);
$encrypted[Encrypter::SIGNATURE] = 'BADONE';
$encrypted = base64_encode(json_encode($encrypted));
$encrypter->decrypt($encrypted);
}
/**
* @param string $key
* @return Encrypter
*/
protected function makeEncrypter($key = '1234567890123456')
{
return new Encrypter($key);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
use Interop\Container\ContainerInterface;
/**
* Entity which code follows external behaviour schema.
*/
class SchematicEntity extends DataEntity
{
/**
* Schema constants. Starts with 4, but why not?
*/
const SH_HIDDEN = 4;
const SH_SECURED = 5;
const SH_FILLABLE = 6;
const SH_MUTATORS = 7;
const SH_VALIDATES = 8;
/**
* Behaviour schema.
*
* @var array
*/
private $schema = [];
/**
* @param array $fields
* @param array $schema
*/
public function __construct(array $fields, array $schema)
{
$this->schema = $schema;
parent::__construct($fields);
}
/**
* {@inheritdoc}
*
* Include every composition public data into result.
*/
public function publicFields()
{
$result = [];
foreach ($this->fields as $field => $value) {
if (in_array($field, $this->schema[self::SH_HIDDEN])) {
//We might need to use isset in future, for performance
continue;
}
$result[$field] = $this->getField($field);
}
return $result;
}
/**
* {@inheritdoc}
*/
protected function isFillable($field)
{
if (!empty($this->schema[self::SH_FILLABLE])) {
return in_array($field, $this->schema[self::SH_FILLABLE]);
}
if ($this->schema[self::SH_SECURED] === '*') {
return false;
}
return !in_array($field, $this->schema[self::SH_SECURED]);
}
/**
* {@inheritdoc}
*/
protected function getMutator($field, $mutator)
{
if (isset($this->schema[self::SH_MUTATORS][$mutator][$field])) {
return $this->schema[self::SH_MUTATORS][$mutator][$field];
}
return null;
}
/**
* {@inheritdoc}
*/
protected function createValidator(
array $rules = [],
ContainerInterface $container = null
) {
//Initiate validation using rules declared in model schema
return parent::createValidator(
!empty($rules) ? $rules : $this->schema[self::SH_VALIDATES],
$container
);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\MySQL\Schemas;
use Spiral\Database\Entities\Schemas\AbstractIndex;
/**
* MySQL index schema.
*/
class IndexSchema extends AbstractIndex
{
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
foreach ($schema as $index) {
$this->type = $index['Non_unique'] ? self::NORMAL : self::UNIQUE;
$this->columns[] = $index['Column_name'];
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Files;
use Spiral\Files\FileManager;
use Spiral\Files\FilesInterface;
class FilesTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
$filename = sys_get_temp_dir() . '/test.txt';
$directory = sys_get_temp_dir() . '/abc/cde';
if (is_file($filename)) {
unlink($filename);
}
if (is_dir($directory)) {
rmdir($directory);
rmdir(dirname($directory));
}
}
public function testReadWrite()
{
$files = new FileManager();
$filename = sys_get_temp_dir() . '/test.txt';
$files->write($filename, 'some data');
$this->assertEquals('some data', $files->read($filename));
$this->assertEquals(file_get_contents($filename), $files->read($filename));
}
public function testTime()
{
$files = new FileManager();
$filename = sys_get_temp_dir() . '/test.txt';
$files->write($filename, 'some data', FilesInterface::READONLY);
$this->assertEquals(filemtime($filename), $files->time($filename));
}
public function testMd5()
{
$files = new FileManager();
$filename = sys_get_temp_dir() . '/test.txt';
$files->write($filename, 'some data');
$this->assertEquals(md5_file($filename), $files->md5($filename));
}
/**
* @expectedException \Spiral\Files\Exceptions\FileNotFoundException
*/
public function testExceptions()
{
$files = new FileManager();
$filename = sys_get_temp_dir() . '/test.txt';
$this->assertFalse($files->exists($filename));
$files->read($filename);
}
public function testDirectoryRuntime()
{
$files = new FileManager();
$directory = sys_get_temp_dir() . '/abc/cde';
$this->assertFalse($files->isDirectory($directory));
$this->assertFalse($files->isDirectory(dirname($directory)));
$files->ensureDirectory($directory);
$this->assertTrue($files->isDirectory(dirname($directory)));
$this->assertTrue($files->isDirectory($directory));
}
public function testDirectoryReadonly()
{
$files = new FileManager();
$directory = sys_get_temp_dir() . '/abc/cde';
$this->assertFalse($files->isDirectory($directory));
$this->assertFalse($files->isDirectory(dirname($directory)));
$files->ensureDirectory($directory, FilesInterface::READONLY);
$this->assertTrue($files->isDirectory(dirname($directory)));
$this->assertTrue($files->isDirectory($directory));
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Database\Entities\Table;
use Spiral\Models\AccessorInterface;
use Spiral\Models\EntityInterface;
use Spiral\Models\Events\EntityEvent;
use Spiral\Models\Exceptions\AccessorExceptionInterface;
use Spiral\Models\SchematicEntity;
use Spiral\ORM\Exceptions\FieldException;
use Spiral\ORM\Exceptions\RecordException;
use Spiral\ORM\Exceptions\RelationException;
use Spiral\Validation\ValidatesInterface;
/**
* Record is base data entity for ORM component, it used to describe related table schema,
* filters, validations and relations to other records. You can count Record class as ActiveRecord
* pattern. ORM component will automatically analyze existed Records and create cached version of
* their schema.
*
* @TODO: Add ability to set primary key manually, for example fpr uuid like fields.
*/
class RecordEntity extends SchematicEntity implements RecordInterface
{
/**
* Static container fallback.
*/
use SaturateTrait;
/**
* Field format declares how entity must process magic setters and getters. Available values:
* camelCase, tableize.
*/
const FIELD_FORMAT = 'tableize';
/**
* We are going to inherit parent validation rules, this will let spiral translator know about
* it and merge i18n messages.
*
* @see TranslatorTrait
*/
const I18N_INHERIT_MESSAGES = true;
/**
* ORM records are be divided by two sections: active and passive records. When record is active
* ORM allowed to modify associated record table using declared schema and created relations.
*
* Passive records (ACTIVE_SCHEMA = false) however can only read table schema from database and
* forbidden to do any schema modification either by record or by relations.
*
* You can use ACTIVE_SCHEMA = false in cases where you need to create an ActiveRecord for
* existed table.
*
* @see RecordSchema
* @see \Spiral\ORM\Entities\SchemaBuilder
*/
const ACTIVE_SCHEMA = true;
/**
* Indication that record were deleted.
*/
const DELETED = 900;
/**
* Default ORM relation types, see ORM configuration and documentation for more information,
* i had to remove 200 lines of comments to make record little bit smaller.
*
* @see RelationSchemaInterface
* @see RelationSchema
*/
const HAS_ONE = 101;
const HAS_MANY = 102;
const BELONGS_TO = 103;
const MANY_TO_MANY = 104;
/**
* Morphed relation types are usually created by inversion or equivalent of primary relation
* types.
*
* @see RelationSchemaInterface
* @see RelationSchema
* @see MorphedRelation
*/
const BELONGS_TO_MORPHED = 108;
const MANY_TO_MORPHED = 109;
/**
* Constants used to declare relations in record schema, used in normalized relation schema.
*
* @see RelationSchemaInterface
*/
const OUTER_KEY = 901; //Outer key name
const INNER_KEY = 902; //Inner key name
const MORPH_KEY = 903; //Morph key name
const PIVOT_TABLE = 904; //Pivot table name
const PIVOT_COLUMNS = 905; //Pre-defined pivot table columns
const PIVOT_DEFAULTS = 906; //Pre-defined pivot table default values
const THOUGHT_INNER_KEY = 907; //Pivot table options
const THOUGHT_OUTER_KEY = 908; //Pivot table options
const WHERE = 909; //Where conditions
const WHERE_PIVOT = 910; //Where pivot conditions
/**
* Additional constants used to control relation schema behaviour.
*
* @see Record::$schema
* @see RelationSchemaInterface
*/
const INVERSE = 1001; //Relation should be inverted to parent record
const CONSTRAINT = 1002; //Relation should create foreign keys (default)
const CONSTRAINT_ACTION = 1003; //Default relation foreign key delete/update action (CASCADE)
const CREATE_PIVOT = 1004; //Many-to-Many should create pivot table automatically (default)
const NULLABLE = 1005; //Relation can be nullable (default)
const CREATE_INDEXES = 1006; //Indication that relation is allowed to create required indexes
const MORPHED_ALIASES = 1007; //Aliases for morphed sub-relations
/**
* Relations marked as embedded will be automatically saved/validated with parent model. In
* addition such models data can be set using setFields method (only for ONE relations).
*
* @see setFields()
* @see save()
* @see validate()
*/
const EMBEDDED_RELATION = 1008;
/**
* Constants used to declare indexes in record schema.
*
* @see Record::$indexes
*/
const INDEX = 1000; //Default index type
const UNIQUE = 2000; //Unique index definition
/**
* Errors in relations and acessors.
*
* @var array
*/
private $nestedErrors = [];
/**
* Indicates that record data were loaded from database (not recently created).
*
* @var bool
*/
private $loaded = false;
/**
* Schema provided by ORM component.
*
* @var array
*/
private $ormSchema = [];
/**
* SolidState will force record data to be saved as one big update set without any generating
* separate update statements for changed columns.
*
* @var bool
*/
private $solidState = false;
/**
* Populated when record loaded using many-to-many connection. Property will include every
* column of connection row in pivot table.
*
* @see setContext()
* @see getPivot();
* @var array
*/
private $pivotData = [];
/**
* Record field updates (changed values).
*
* @var array
*/
private $updates = [];
/**
* Constructed and pre-cached set of record relations. Relation will be in a form of data array
* to be created on demand.
*
* @see relation()
* @see __call()
* @see __set()
* @see __get()
* @var RelationInterface[]|array
*/
protected $relations = [];
/**
* Table name (without database prefix) record associated to, RecordSchema will generate table
* name automatically using class name, however i'm strongly recommend to declare table name
* manually as it gives more readable code.
*
* @var string
*/
protected $table = null;
/**
* Database name/id where record table located in. By default database will be used if nothing
* else is specified.
*
* @var string|null
*/
protected $database = null;
/**
* Set of indexes to be created for associated record table, indexes only created when record is
* not abstract and has active schema set to true.
*
* Use constants INDEX and UNIQUE to describe indexes, you can also create compound indexes:
* protected $indexes = [
* [self::UNIQUE, 'email'],
* [self::INDEX, 'board_id'],
* [self::INDEX, 'board_id', 'check_id']
* ];
*
* @var array
*/
protected $indexes = [];
/**
* Record relations and columns can be described in one place - record schema.
* Attention: while defining table structure make sure that ACTIVE_SCHEMA constant is set to t
* rue.
*
* Example:
* protected $schema = [
* 'id' => 'primary',
* 'name' => 'string',
* 'biography' => 'text'
* ];
*
* You can pass additional options for some of your columns:
* protected $schema = [
* 'pinCode' => 'string(128)', //String length
* 'status' => 'enum(active, hidden)', //Enum values
* 'balance' => 'decimal(10, 2)' //Decimal size and precision
* ];
*
* Every created column will be stated as NOT NULL with forced default value, if you want to
* have nullable columns, specify special data key: protected $schema = [
* 'name' => 'string, nullable'
* ];
*
* You can easily combine table and relations definition in one schema:
* protected $schema = [
*
* //Table schema
* 'id' => 'bigPrimary',
* 'name' => 'string',
* 'email' => 'string',
* 'phoneNumber' => 'string(32)',
*
* //Relations
* 'profile' => [
* self::HAS_ONE => 'Records\Profile',
* self::INVERSE => 'user'
* ],
* 'roles' => [
* self::MANY_TO_MANY => 'Records\Role',
* self::INVERSE => 'users'
* ]
* ];
*
* @var array
*/
protected $schema = [];
/**
* Default field values.
*
* @var array
*/
protected $defaults = [];
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* Due setContext() method and entity cache of ORM any custom initiation code in constructor
* must not depends on database data.
*
* @see setContext
* @param array $data
* @param bool|false $loaded
* @param ORM|null $orm
* @param array $ormSchema
* @throws SugarException
*/
public function __construct(
array $data = [],
$loaded = false,
ORM $orm = null,
array $ormSchema = []
) {
$this->loaded = $loaded;
//We can use global container as fallback if no default values were provided
$this->orm = $this->saturate($orm, ORM::class);
$this->ormSchema = !empty($ormSchema) ? $ormSchema : $this->orm->schema(static::class);
if (isset($data[ORM::PIVOT_DATA])) {
$this->pivotData = $data[ORM::PIVOT_DATA];
unset($data[ORM::PIVOT_DATA]);
}
foreach (array_intersect_key($data,
$this->ormSchema[ORM::M_RELATIONS]) as $name => $relation) {
$this->relations[$name] = $relation;
unset($data[$name]);
}
parent::__construct($data + $this->ormSchema[ORM::M_COLUMNS], $this->ormSchema);
if (!$this->isLoaded()) {
//Non loaded records should be in solid state by default and require initial validation
$this->solidState(true)->invalidate();
}
}
/**
* Change record solid state. SolidState will force record data to be saved as one big update
* set without any generating separate update statements for changed columns.
*
* Attention, you have to carefully use forceUpdate flag with records without primary keys due
* update criteria (WHERE condition) can not be easy constructed for records with primary key.
*
* @param bool $solidState
* @param bool $forceUpdate Mark all fields as changed to force update later.
* @return $this
*/
public function solidState($solidState, $forceUpdate = false)
{
$this->solidState = $solidState;
if ($forceUpdate) {
if ($this->ormSchema[ORM::M_PRIMARY_KEY]) {
$this->updates = $this->stateCriteria();
} else {
$this->updates = $this->ormSchema[ORM::M_COLUMNS];
}
}
return $this;
}
/**
* Is record is solid state?
*
* @see solidState()
* @return bool
*/
public function isSolid()
{
return $this->solidState;
}
/**
* {@inheritdoc}
*/
public function recordRole()
{
return $this->ormSchema[ORM::M_ROLE_NAME];
}
/**
* {@inheritdoc}
*/
public function primaryKey()
{
return isset($this->fields[$this->ormSchema[ORM::M_PRIMARY_KEY]])
? $this->fields[$this->ormSchema[ORM::M_PRIMARY_KEY]]
: null;
}
/**
* {@inheritdoc}
*/
public function isLoaded()
{
return (bool)$this->loaded && !$this->isDeleted();
}
/**
* {@inheritdoc}
*/
public function isDeleted()
{
return $this->loaded === self::DELETED;
}
/**
* Pivot data associated with record instance, populated only in cases when record loaded using
* Many-to-Many relation.
*
* @return array
*/
public function getPivot()
{
return $this->pivotData;
}
/**
* {@inheritdoc}
*
* @see $fillable
* @see $secured
* @see isFillable()
* @param array|\Traversable $fields
* @param bool $all Fill all fields including non fillable.
* @return $this
* @throws AccessorExceptionInterface
* @event setFields($fields)
*/
public function setFields($fields = [], $all = false)
{
parent::setFields($fields, $all);
foreach ($fields as $name => $nested) {
//We can fill data of embedded of relations (usually HAS ONE)
if ($this->isEmbedded($name)) {
//Getting relation instance
$relation = $this->relation($name);
//Getting related object
$related = $relation->getRelated();
if ($related instanceof EntityInterface) {
$related->setFields($nested);
}
}
}
return $this;
}
/**
* {@inheritdoc}
*
* Must track field updates. In addition Records will not allow to set unknown field.
*
* @throws RecordException
*/
public function setField($name, $value, $filter = true)
{
if (!array_key_exists($name, $this->fields)) {
throw new FieldException("Undefined field '{$name}' in '" . static::class . "'.");
}
$original = isset($this->fields[$name]) ? $this->fields[$name] : null;
if ($value === null && in_array($name, $this->ormSchema[ORM::M_NULLABLE])) {
//We must bypass setters and accessors when null value assigned to nullable column
$this->fields[$name] = null;
} else {
parent::setField($name, $value, $filter);
}
if (!array_key_exists($name, $this->updates)) {
$this->updates[$name] = $original instanceof AccessorInterface
? $original->serializeData()
: $original;
}
}
/**
* {@inheritdoc}
*
* Record will skip filtration for nullable fields.
*/
public function getField($name, $default = null, $filter = true)
{
if (!array_key_exists($name, $this->fields)) {
throw new FieldException("Undefined field '{$name}' in '" . static::class . "'.");
}
$value = $this->fields[$name];
if ($value === null && in_array($name, $this->ormSchema[ORM::M_NULLABLE])) {
if (!isset($this->ormSchema[ORM::M_MUTATORS]['accessor'][$name])) {
//We can skip setters for null values, but not accessors
return $value;
}
}
return parent::getField($name, $default, $filter);
}
/**
* Get or create record relation by it's name and pre-loaded (optional) set of data.
*
* @param string $name
* @param mixed $data
* @param bool $loaded
* @return RelationInterface
* @throws RelationException
* @throws RecordException
*/
public function relation($name, $data = null, $loaded = false)
{
if (array_key_exists($name, $this->relations)) {
if (!is_object($this->relations[$name])) {
$data = $this->relations[$name];
unset($this->relations[$name]);
//Loaded relation
return $this->relation($name, $data, true);
}
//Already created
return $this->relations[$name];
}
//Constructing relation
if (!isset($this->ormSchema[ORM::M_RELATIONS][$name])) {
throw new RecordException(
"Undefined relation {$name} in record " . static::class . "."
);
}
$relation = $this->ormSchema[ORM::M_RELATIONS][$name];
return $this->relations[$name] = $this->orm->relation(
$relation[ORM::R_TYPE], $this, $relation[ORM::R_DEFINITION], $data, $loaded
);
}
/**
* {@inheritdoc}
*
* @param string $field Specific field name to check for updates.
*/
public function hasUpdates($field = null)
{
if (empty($field)) {
if (!empty($this->updates)) {
return true;
}
foreach ($this->fields as $field => $value) {
if ($value instanceof RecordAccessorInterface && $value->hasUpdates()) {
return true;
}
}
return false;
}
if (array_key_exists($field, $this->updates)) {
return true;
}
$value = $this->getField($field);
if ($value instanceof RecordAccessorInterface && $value->hasUpdates()) {
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function flushUpdates()
{
$this->updates = [];
foreach ($this->fields as $value) {
if ($value instanceof RecordAccessorInterface) {
$value->flushUpdates();
}
}
}
/**
* {@inheritdoc}
*/
public function isValid()
{
$this->validate();
return empty($this->errors) && empty($this->nestedErrors);
}
/**
* {@inheritdoc}
*/
public function getErrors($reset = false)
{
return parent::getErrors($reset) + $this->nestedErrors;
}
/**
* {@inheritdoc}
*/
public function __isset($name)
{
if (isset($this->ormSchema[ORM::M_RELATIONS][$name])) {
return !empty($this->relation($name)->getRelated());
}
return parent::__isset($name);
}
/**
* {@inheritdoc}
*
* @throws RecordException
*/
public function __unset($offset)
{
throw new FieldException("Records fields can not be unsetted.");
}
/**
* {@inheritdoc}
*
* @see relation()
*/
public function __get($offset)
{
if (isset($this->ormSchema[ORM::M_RELATIONS][$offset])) {
//Bypassing call to relation
return $this->relation($offset)->getRelated();
}
return $this->getField($offset, true);
}
/**
* {@inheritdoc}
*
* @see relation()
*/
public function __set($offset, $value)
{
if (isset($this->ormSchema[ORM::M_RELATIONS][$offset])) {
//Bypassing call to relation
$this->relation($offset)->associate($value);
return;
}
$this->setField($offset, $value, true);
}
/**
* Direct access to relation by it's name.
*
* @see relation()
* @param string $method
* @param array $arguments
* @return RelationInterface|mixed|AccessorInterface
*/
public function __call($method, array $arguments)
{
if (isset($this->ormSchema[ORM::M_RELATIONS][$method])) {
return $this->relation($method);
}
//See FIELD_FORMAT constant
return parent::__call($method, $arguments);
}
/**
* @return array
*/
public function __debugInfo()
{
$info = [
'table' => $this->ormSchema[ORM::M_DB] . '/' . $this->ormSchema[ORM::M_TABLE],
'pivotData' => $this->pivotData,
'fields' => $this->getFields(),
'errors' => $this->getErrors()
];
if (empty($this->pivotData)) {
unset($info['pivotData']);
}
return $info;
}
/**
* Get associated Database\Table instance.
*
* @see save()
* @see delete()
* @return Table
*/
protected function sourceTable()
{
return $this->orm->database($this->ormSchema[ORM::M_DB])->table(
$this->ormSchema[ORM::M_TABLE]
);
}
/**
* Get WHERE array to be used to perform record data update or deletion. Usually will include
* record primary key.
*
* @return array
*/
protected function stateCriteria()
{
if (!empty($primaryKey = $this->ormSchema()[ORM::M_PRIMARY_KEY])) {
return [$primaryKey => $this->primaryKey()];
}
//We have to serialize record data
return $this->updates + $this->serializeData();
}
/**
* {@inheritdoc}
*/
protected function container()
{
if (empty($this->orm)) {
return parent::container();
}
return $this->orm->container();
}
/**
* Create set of fields to be sent to UPDATE statement.
*
* @see save()
* @return array
*/
protected function compileUpdates()
{
if (!$this->hasUpdates() && !$this->isSolid()) {
return [];
}
if ($this->isSolid()) {
return $this->solidUpdate();
}
$updates = [];
foreach ($this->fields as $field => $value) {
if ($value instanceof RecordAccessorInterface) {
if ($value->hasUpdates()) {
$updates[$field] = $value->compileUpdates($field);
continue;
}
//Will be handled as normal update if needed
$value = $value->serializeData();
}
if (array_key_exists($field, $this->updates)) {
$updates[$field] = $value;
}
}
//Primary key should not present in update set
unset($updates[$this->ormSchema[ORM::M_PRIMARY_KEY]]);
return $updates;
}
/**
* {@inheritdoc}
*
* Will validate every loaded and embedded relation.
*/
protected function validate($reset = false)
{
$this->nestedErrors = [];
//Validating all compositions/accessors
foreach ($this->fields as $field => $value) {
//Ensuring value state
$value = $this->getField($field);
if (!$value instanceof ValidatesInterface) {
continue;
}
if (!$value->isValid()) {
$this->nestedErrors[$field] = $value->getErrors($reset);
}
}
//We have to validate some relations before saving them
$this->validateRelations($reset);
parent::validate($reset);
return empty($this->errors + $this->nestedErrors);
}
/**
* {@inheritdoc}
*
* @see Component::staticContainer()
* @param array $fields Record fields to set, will be passed thought filters.
* @param ORM $orm ORM component, global container will be called if not instance provided.
* @event created()
*/
public static function create($fields = [], ORM $orm = null)
{
/**
* @var RecordEntity $record
*/
$record = new static([], false, $orm);
//Forcing validation (empty set of fields is not valid set of fields)
$record->setFields($fields)->dispatch('created', new EntityEvent($record));
return $record;
}
/**
* Change record loaded state.
*
* @param bool|mixed $loader
* @return $this
*/
protected function loadedState($loader)
{
$this->loaded = $loader;
return $this;
}
/**
* Related and cached ORM schema.
*
* @return array
*/
protected function ormSchema()
{
return $this->ormSchema;
}
/**
* Check if relation is embedded.
*
* @param string $relation
* @return bool
*/
protected function isEmbedded($relation)
{
return !empty(
$this->ormSchema[ORM::M_RELATIONS][$relation][ORM::R_DEFINITION][self::EMBEDDED_RELATION]
);
}
/**
* Full structure update.
*
* @return array
*/
private function solidUpdate()
{
$updates = [];
foreach ($this->fields as $field => $value) {
if ($value instanceof RecordAccessorInterface && $value->hasUpdates()) {
if ($value->hasUpdates()) {
$updates[$field] = $value->compileUpdates($field);
} else {
$updates[$field] = $value->serializeData();
}
continue;
}
$updates[$field] = $value;
}
return $updates;
}
/**
* Validate embedded relations.
*
* @param bool $reset
*/
private function validateRelations($reset)
{
foreach ($this->relations as $name => $relation) {
if (!$relation instanceof ValidatesInterface) {
//Never constructed
continue;
}
if ($this->isEmbedded($name) && !$relation->isValid()) {
$this->nestedErrors[$name] = $relation->getErrors($reset);
}
}
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Tokenizer\Exceptions\ReflectionException;
use Spiral\Tokenizer\Exceptions\TokenizerException;
/**
* Simple wrapper at top of token_get_all.
*/
interface TokenizerInterface
{
/**
* Token array constants.
*/
const TYPE = 0;
const CODE = 1;
const LINE = 2;
/**
* Fetch PHP tokens for specified filename. Usually links to token_get_all() function. Every
* token MUST be converted into array.
*
* @param string $filename
* @return array
*/
public function fetchTokens($filename);
/**
* Get file reflection for given filename.
*
* @param string $filename
* @return ReflectionFileInterface
* @throws TokenizerException
* @throws ReflectionException
*/
public function fileReflection($filename);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Traits;
/**
* Replaces {@} with valid table alias in array where.
*/
trait AliasTrait
{
/**
* Replace {@} in where statement with valid alias.
*
* @param string $alias
* @param array $where
* @return array
*/
protected function mountAlias($alias, array $where)
{
$result = [];
foreach ($where as $key => $value) {
if (strpos($key, '{@}') !== false) {
$key = str_replace('{@}', $alias, $key);
}
if (is_array($value)) {
$value = $this->mountAlias($alias, $where);
}
$result[$key] = $value;
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Query;
use PDOStatement;
use Spiral\Database\Entities\QueryInterpolator;
use Spiral\Database\ResultInterface;
/**
* Query result iteration class.
*
* Decorates PDOStatement.
*/
class QueryResult implements ResultInterface, \JsonSerializable
{
/**
* Limits after which no records will be dumped in __debugInfo.
*/
const DUMP_LIMIT = 500;
/**
* Cursor position, used to determinate current data index.
*
* @var int
*/
protected $cursor = null;
/**
* The number of rows selected by SQL statement.
*
* @var int
*/
protected $count = 0;
/**
* Last selected row array. This value is required to correctly emulate Iterator methods.
*
* @var mixed
*/
protected $rowData = null;
/**
* @invisible
* @var PDOStatement
*/
protected $statement = null;
/**
* PDOStatement prepare parameters.
*
* @var array
*/
protected $parameters = [];
/**
* @link http://php.net/manual/en/class.pdostatement.php
* @param PDOStatement $statement
* @param array $parameters
*/
public function __construct(PDOStatement $statement, array $parameters = [])
{
$this->statement = $statement;
$this->parameters = $parameters;
$this->count = $this->statement->rowCount();
//Forcing default fetch mode
$this->statement->setFetchMode(\PDO::FETCH_ASSOC);
}
/**
* Query string associated with PDOStatement. To be used for debug purposes only.
*
* @return string
*/
public function queryString()
{
return QueryInterpolator::interpolate($this->statement->queryString, $this->parameters);
}
/**
* {@inheritdoc}
*
* Attention, this method will return 0 for SQLite databases.
*
* @link http://php.net/manual/en/pdostatement.rowcount.php
* @link http://stackoverflow.com/questions/15003232/pdo-returns-wrong-rowcount-after-select-statement
* @return int
*/
public function count()
{
return $this->count;
}
/**
* {@inheritdoc}
*
* @link http://php.net/manual/en/pdostatement.columncount.php
*/
public function countColumns()
{
return $this->statement->columnCount();
}
/**
* Change fetching mode, use PDO::FETCH_ constants to specify required mode. If you want to
* keep
* compatibility with CachedQuery do not use other modes than PDO::FETCH_ASSOC and
* PDO::FETCH_NUM.
*
* @link http://php.net/manual/en/pdostatement.setfetchmode.php
* @param int $mode The fetch mode must be one of the PDO::FETCH_* constants.
* @return $this
*/
public function fetchMode($mode)
{
$this->statement->setFetchMode($mode);
return $this;
}
/**
* {@inheritdoc}
*/
public function fetch($mode = null)
{
if (!empty($mode)) {
$this->fetchMode($mode);
}
return $this->statement->fetch();
}
/**
* {@inheritdoc}
*/
public function fetchColumn($columnID = 0)
{
return $this->statement->fetchColumn($columnID);
}
/**
* {@inheritdoc}
*
* @link http://www.php.net/manual/en/function.PDOStatement-bindColumn.php
* @return $this
*/
public function bind($columnID, &$variable)
{
if (is_numeric($columnID)) {
//PDO columns are 1-indexed
$columnID = $columnID + 1;
}
$this->statement->bindColumn($columnID, $variable);
return $this;
}
/**
* {@inheritdoc}
*/
public function fetchAll($mode = null)
{
if (!empty($mode)) {
$this->fetchMode($mode);
}
return $this->statement->fetchAll();
}
/**
* All results in array form. Alias for fetch all.
*
* @return array
*/
public function all()
{
return $this->fetchAll();
}
/**
* {@inheritdoc}
*/
public function current()
{
return $this->rowData;
}
/**
* {@inheritdoc}
*/
public function next()
{
$this->rowData = $this->fetch();
$this->cursor++;
return $this->rowData;
}
/**
* {@inheritdoc}
*/
public function key()
{
return $this->cursor;
}
/**
* {@inheritdoc}
*/
public function valid()
{
//We can't use cursor or any other method to walk though data as SQLite will
//return 0 for count.
return $this->rowData !== false;
}
/**
* {@inheritdoc}
*/
public function rewind()
{
$this->rowData = $this->fetch();
$this->cursor = 0;
}
/**
* {@inheritdoc}
*
* @link http://php.net/manual/en/pdostatement.closecursor.php
* @return bool
*/
public function close()
{
return !empty($this->statement) && $this->statement->closeCursor();
}
/**
* Bypassing call to PDOStatement.
*
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call($method, array $arguments)
{
return call_user_func_array([$this->statement, $method], $arguments);
}
/**
* Destruct associated statement to free used memory.
*/
public function __destruct()
{
$this->close();
$this->statement = null;
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'statement' => $this->queryString(),
'count' => $this->count,
'rows' => $this->count > static::DUMP_LIMIT
? '[TOO MANY RECORDS TO DISPLAY]'
: $this->fetchAll(\PDO::FETCH_ASSOC)
];
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->fetchAll();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Loaders;
use Spiral\ORM\RecordEntity;
/**
* Responsible for loading data related to parent record in belongs to relation. Loading logic is
* identical to HasOneLoader however preferred loading methods is POSTLOAD.
*/
class BelongsToLoader extends HasOneLoader
{
/**
* Relation type is required to correctly resolve foreign record class based on relation
* definition.
*/
const RELATION_TYPE = RecordEntity::BELONGS_TO;
/**
* Default load method (inload or postload).
*/
const LOAD_METHOD = self::POSTLOAD;
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Traits;
use Interop\Container\ContainerInterface;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Core\FactoryInterface;
use Spiral\Events\Traits\EventsTrait;
use Spiral\Translator\Traits\TranslatorTrait;
use Spiral\Translator\TranslatorInterface;
use Spiral\Validation\Events\ValidatedEvent;
use Spiral\Validation\Events\ValidatorEvent;
use Spiral\Validation\Exceptions\ValidationException;
use Spiral\Validation\ValidatorInterface;
/**
* Provides set of common validation methods.
*/
trait ValidatorTrait
{
/**
* Will translate every message it [[]] used and fire some events.
*/
use TranslatorTrait, EventsTrait;
/**
* @var ValidatorInterface
*/
private $validator = null;
/**
* @internal DO NOT USE
* @whatif private
* @var array
*/
protected $errors = [];
/**
* Fields (data) to be validated. Named like that for convenience.
*
* @internal DO NOT USE
* @whatif private
* @var array
*/
protected $fields = [];
/**
* Validation rules defined in validator format. Named like that for convenience.
*
* @var array
*/
protected $validates = [];
/**
* Attach custom validator to model.
*
* @param ValidatorInterface $validator
*/
public function setValidator(ValidatorInterface $validator)
{
$this->validator = $validator;
}
/**
* Check if context data is valid.
*
* @return bool
*/
public function isValid()
{
$this->validate();
return empty($this->errors);
}
/**
* Check if context data has errors.
*
* @return bool
*/
public function hasErrors()
{
return !$this->isValid();
}
/**
* List of errors associated with parent field, every field should have only one error assigned.
*
* @param bool $reset Re-validate object.
* @return array
*/
public function getErrors($reset = false)
{
$this->validate($reset);
$errors = [];
foreach ($this->errors as $field => $error) {
if (
is_string($error)
&& substr($error, 0, 2) == TranslatorInterface::I18N_PREFIX
&& substr($error, -2) == TranslatorInterface::I18N_POSTFIX
) {
//We will localize only messages embraced with [[ and ]]
$error = $this->say($error);
}
$errors[$field] = $error;
}
return $errors;
}
/**
* Get associated instance of validator or return new one.
*
* @return ValidatorInterface
* @throws SugarException
*/
protected function validator()
{
if (!empty($this->validator)) {
return $this->validator;
}
return $this->validator = $this->createValidator();
}
/**
* Validate data using associated validator.
*
* @param bool $reset Implementation might reset validation if needed.
* @return bool
* @throws ValidationException
* @throws SugarException
* @event validated(ValidatedEvent)
*/
protected function validate($reset = false)
{
//Refreshing validation fields
$this->validator()->setData($this->fields);
/**
* @var ValidatedEvent $validatedEvent
*/
$validatedEvent = $this->dispatch('validated', new ValidatedEvent(
$this->validator()->getErrors()
));
//Collecting errors if any
return empty($this->errors = $validatedEvent->getErrors());
}
/**
* Attach error to data field. Internal method to be used in validations.
*
* @param string $field
* @param string $message
*/
protected function setError($field, $message)
{
$this->errors[$field] = $message;
}
/**
* Check if desired field caused some validation error.
*
* @param string $field
* @return bool
*/
protected function hasError($field)
{
return !empty($this->errors[$field]);
}
/**
* Create instance of ValidatorInterface.
*
* @param array $rules Non empty rules will initiate validator.
* @param ContainerInterface $container Will fall back to global container.
* @return ValidatorInterface
* @throws SugarException
* @event validator(ValidatorEvent)
*/
protected function createValidator(array $rules = [], ContainerInterface $container = null)
{
if (empty($container)) {
$container = $this->container();
}
if (empty($container) || !$container->has(ValidatorInterface::class)) {
//We can't create default validation without any rule, this is not secure
throw new SugarException(
"Unable to create Validator, no global container set or binding is missing."
);
}
//We need factory to create validator
if ($container instanceof FactoryInterface) {
$factory = $container;
} else {
$factory = $container->get(FactoryInterface::class);
}
//Receiving instance of validator from container
$validator = $factory->make(ValidatorInterface::class, [
'data' => $this->fields,
'rules' => !empty($rules) ? $rules : $this->validates
]);
/**
* @var ValidatorEvent $validatorEvent
*/
$validatorEvent = $this->dispatch('validator', new ValidatorEvent($validator));
return $validatorEvent->validator();
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database;
use Spiral\Database\Exceptions\QueryException;
/**
* DatabaseInterface is high level abstraction used to represent single database. You MUST always
* (you are good person) check database type using getType() method before writing plain SQL for
* execute and query methods.
*/
interface DatabaseInterface
{
/**
* Known database types.
*/
const MYSQL = 'MySQL';
const POSTGRES = 'Postgres';
const SQLITE = 'SQLite';
const SQL_SERVER = 'SQLServer';
/**
* @return string
*/
public function getName();
/**
* Database type matched to one of database constants. You MUST write SQL for execute and query
* methods by respecting result of this method.
*
* @return string
*/
public function getType();
/**
* Execute statement and return number of affected rows.
*
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @return int
* @throws QueryException
*/
public function execute($query, array $parameters = []);
/**
* Execute statement and return query iterator.
*
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @return ResultInterface
* @throws QueryException
*/
public function query($query, array $parameters = []);
/**
* Execute multiple commands defined by Closure function inside one transaction. Closure or
* function must receive only one argument - DatabaseInterface instance.
*
* @param callable $callback
* @return mixed
* @throws \Exception
*/
public function transaction(callable $callback);
/**
* Start database transaction.
*
* @link http://en.wikipedia.org/wiki/Database_transaction
* @return bool
*/
public function begin();
/**
* Commit the active database transaction.
*
* @return bool
*/
public function commit();
/**
* Rollback the active database transaction.
*
* @return bool
*/
public function rollback();
/**
* Check if table exists.
*
* @param string $name
* @return bool
*/
public function hasTable($name);
/**
* Get Table abstraction. Must return valid instance if table does not exists.
*
* @param string $name
* @return TableInterface
*/
public function table($name);
/**
* Get every available database Table abstraction.
*
* @return TableInterface[]
*/
public function getTables();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Validation\Checkers;
use Spiral\Validation\Checkers\StringChecker;
class StringCheckerTest extends \PHPUnit_Framework_TestCase
{
public function testShorter()
{
$checker = new StringChecker();
$this->assertFalse($checker->shorter('abc', 2));
$this->assertFalse($checker->shorter('абв', 2));
$this->assertTrue($checker->shorter('abc', 3));
$this->assertTrue($checker->shorter('абв', 3));
$this->assertTrue($checker->shorter('abc', 4));
$this->assertTrue($checker->shorter('абв', 4));
}
public function testLonger()
{
$checker = new StringChecker();
$this->assertTrue($checker->longer('abc', 2));
$this->assertTrue($checker->longer('абв', 2));
$this->assertTrue($checker->longer('abc', 3));
$this->assertTrue($checker->longer('абв', 3));
$this->assertFalse($checker->longer('abc', 4));
$this->assertFalse($checker->longer('абв', 4));
}
public function testLength()
{
$checker = new StringChecker();
$this->assertTrue($checker->length('abc', 3));
$this->assertTrue($checker->length('абв', 3));
$this->assertFalse($checker->length('abc', 5));
$this->assertFalse($checker->length('абв', 5));
}
public function testRange()
{
$checker = new StringChecker();
$this->assertTrue($checker->range('abc', 2, 4));
$this->assertTrue($checker->range('абв', 1, 100));
$this->assertTrue($checker->range('abc', 0, 3));
$this->assertTrue($checker->range('абв', 3, 20));
$this->assertFalse($checker->range('abc', 5, 10));
$this->assertFalse($checker->range('абв', 0, 2));
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Spiral\Core\Component;
use Spiral\Database\Exceptions\BuilderException;
use Spiral\Database\Exceptions\QueryException;
use Spiral\Database\Injections\ExpressionInterface;
use Spiral\Database\Injections\ParameterInterface;
/**
* QueryBuilder classes generate set of control tokens for query compilers, this is query level
* abstraction.
*
* @todo Need a way to use prepared query statement. Can be done using parameters (they all objects
* @todo and linked to values, but query builder should keep an instance of prepared statement.
*/
abstract class QueryBuilder extends Component implements ExpressionInterface
{
/**
* @invisible
* @var Database
*/
protected $database = null;
/**
* @invisible
* @var QueryCompiler
*/
protected $compiler = null;
/**
* @param Database $database Parent database.
* @param QueryCompiler $compiler Driver specific QueryCompiler instance (one per builder).
*/
public function __construct(Database $database, QueryCompiler $compiler)
{
$this->database = $database;
$this->compiler = $compiler;
}
/**
* Get ordered list of builder parameters. Attention, this method WILL return only
* ParameterInterface instances in future as scalar parameters will be dropped.
*
* @param QueryCompiler $compiler
* @return array|ParameterInterface[]
* @throws BuilderException
*/
abstract public function getParameters(QueryCompiler $compiler = null);
/**
* {@inheritdoc}
*
* @param QueryCompiler $compiler
*/
abstract public function sqlStatement(QueryCompiler $compiler = null);
/**
* Run built statement against parent database. Might return different values based on specific
* builder implementation.
*
* @return mixed
* @throws QueryException
*/
abstract public function run();
/**
* Get interpolated (populated with parameters) SQL which will be run against database, please
* use this method for debugging purposes only.
*
* @return string
*/
public function queryString()
{
return QueryInterpolator::interpolate($this->sqlStatement(), $this->getParameters());
}
/**
* @return string
*/
public function __toString()
{
return $this->sqlStatement();
}
/**
* @return array
*/
public function __debugInfo()
{
try {
$queryString = $this->queryString();
} catch (\Exception $exception) {
$queryString = "[ERROR: {$exception->getMessage()}]";
}
$debugInfo = [
'statement' => $queryString,
'compiler' => get_class($this->compiler),
'database' => $this->database
];
return $debugInfo;
}
/**
* Helper methods used to correctly fetch and split identifiers provided by function
* parameters.
* It support array list, string or comma separated list. Attention, this method will not work
* with complex parameters (such as functions) provided as one comma separated string, please
* use arrays in this case.
*
* @param array $identifiers
* @return array
*/
protected function fetchIdentifiers(array $identifiers)
{
if (count($identifiers) == 1 && is_string($identifiers[0])) {
return array_map('trim', explode(',', $identifiers[0]));
}
if (count($identifiers) == 1 && is_array($identifiers[0])) {
return $identifiers[0];
}
return $identifiers;
}
/**
* Expand all QueryBuilder parameters to create flatten list.
*
* @param array $parameters
* @return array
*/
protected function flattenParameters(array $parameters)
{
$result = [];
foreach ($parameters as $parameter) {
if ($parameter instanceof QueryBuilder) {
$result = array_merge($result, $parameter->getParameters());
continue;
}
$result[] = $parameter;
}
return $result;
}
/**
* Generate PDO statement based on generated sql and parameters.
*
* @return \PDOStatement
*/
protected function pdoStatement()
{
return $this->database->statement($this->sqlStatement(), $this->getParameters());
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\FactoryInterface;
use Spiral\Core\HippocampusInterface;
use Spiral\Debug\Traits\BenchmarkTrait;
use Spiral\Models\DataEntity;
use Spiral\Models\SchematicEntity;
use Spiral\ODM\Configs\ODMConfig;
use Spiral\ODM\Entities\DocumentSelector;
use Spiral\ODM\Entities\DocumentSource;
use Spiral\ODM\Entities\MongoDatabase;
use Spiral\ODM\Entities\SchemaBuilder;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\ODMException;
use Spiral\Tokenizer\ClassLocatorInterface;
/**
* ODM component used to manage state of cached Document's schema, document creation and schema
* analysis.
*/
class ODM extends Component implements SingletonInterface, InjectorInterface
{
/**
* Has it's own configuration, in addition MongoDatabase creation can take some time.
*/
use BenchmarkTrait;
/**
* Declares to IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* Memory section to store ODM schema.
*/
const MEMORY = 'odm.schema';
/**
* Class definition options.
*/
const DEFINITION = 0;
const DEFINITION_OPTIONS = 1;
/**
* Normalized document constants.
*/
const D_DEFINITION = self::DEFINITION;
const D_COLLECTION = 1;
const D_DB = 2;
const D_SOURCE = 3;
const D_HIDDEN = SchematicEntity::SH_HIDDEN;
const D_SECURED = SchematicEntity::SH_SECURED;
const D_FILLABLE = SchematicEntity::SH_FILLABLE;
const D_MUTATORS = SchematicEntity::SH_MUTATORS;
const D_VALIDATES = SchematicEntity::SH_VALIDATES;
const D_DEFAULTS = 9;
const D_AGGREGATIONS = 10;
const D_COMPOSITIONS = 11;
/**
* Normalized aggregation constants.
*/
const AGR_TYPE = 1;
const ARG_CLASS = 2;
const AGR_QUERY = 3;
/**
* Normalized composition constants.
*/
const CMP_TYPE = 0;
const CMP_CLASS = 1;
const CMP_ONE = 0x111;
const CMP_MANY = 0x222;
const CMP_HASH = 0x333;
/**
* @var ODMConfig
*/
protected $config = null;
/**
* Cached documents and collections schema.
*
* @var array|null
*/
protected $schema = null;
/**
* Mongo databases instances.
*
* @var MongoDatabase[]
*/
protected $databases = [];
/**
* @invisible
* @var HippocampusInterface
*/
protected $memory = null;
/**
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param ODMConfig $config
* @param HippocampusInterface $memory
* @param FactoryInterface $factory
*/
public function __construct(
ODMConfig $config,
HippocampusInterface $memory,
FactoryInterface $factory
) {
$this->config = $config;
$this->memory = $memory;
//Loading schema from memory
$this->schema = (array)$memory->loadData(static::MEMORY);
$this->factory = $factory;
}
/**
* Create specified or select default instance of MongoDatabase.
*
* @param string $database Database name (internal).
* @return MongoDatabase
* @throws ODMException
*/
public function database($database = null)
{
if (empty($database)) {
$database = $this->config->defaultDatabase();
}
//Spiral support ability to link multiple virtual databases together using aliases
$database = $this->config->resolveAlias($database);
if (isset($this->databases[$database])) {
return $this->databases[$database];
}
if (!$this->config->hasDatabase($database)) {
throw new ODMException(
"Unable to initiate mongo database, no presets for '{$database}' found."
);
}
$benchmark = $this->benchmark('database', $database);
try {
$this->databases[$database] = $this->factory->make(MongoDatabase::class, [
'name' => $database,
'config' => $this->config->databaseConfig($database),
'odm' => $this
]);
} finally {
$this->benchmark($benchmark);
}
return $this->databases[$database];
}
/**
* {@inheritdoc}
*/
public function createInjection(\ReflectionClass $class, $context = null)
{
return $this->database($context);
}
/**
* Create instance of document by given class name and set of fields, ODM component must
* automatically find appropriate class to be used as ODM support model inheritance.
*
* @param string $class
* @param array $fields
* @param CompositableInterface $parent
* @return Document
* @throws DefinitionException
*/
public function document($class, $fields, CompositableInterface $parent = null)
{
$class = $this->defineClass($class, $fields, $schema);
return new $class($fields, $parent, $this, $schema);
}
/**
* Get instance of ODM source associated with given model class.
*
* @param string $class
* @return DocumentSource
*/
public function source($class)
{
$schema = $this->schema($class);
if (empty($source = $schema[self::D_SOURCE])) {
$source = DocumentSource::class;
}
return new $source($class, $this);
}
/**
* Mongo collection associated with given model class.
*
* @param string $class
* @return \MongoCollection
*/
public function mongoCollection($class)
{
$schema = $this->schema($class);
return $this->database($schema[ODM::D_DB])->selectCollection($schema[ODM::D_COLLECTION]);
}
/**
* Get instance of ODM Selector associated with given class.
*
* @param $class
* @param array $query
* @return DocumentSelector
*/
public function selector($class, array $query = [])
{
$schema = $this->schema($class);
return new DocumentSelector($this, $schema[ODM::D_DB], $schema[ODM::D_COLLECTION], $query);
}
/**
* Define document class using it's fieldset and definition.
*
* @see Document::DEFINITION
* @param string $class
* @param array $fields
* @param array $schema Found class schema, reference.
* @return string
* @throws DefinitionException
*/
public function defineClass($class, $fields, &$schema = [])
{
$schema = $this->schema($class);
$definition = $schema[self::D_DEFINITION];
if (is_string($definition)) {
//Document has no variations
return $definition;
}
if (!is_array($fields)) {
//Unable to resolve
return $class;
}
$defined = $class;
if ($definition[self::DEFINITION] == DocumentEntity::DEFINITION_LOGICAL) {
//Resolve using logic function
$defined = call_user_func($definition[self::DEFINITION_OPTIONS], $fields, $this);
if (empty($defined)) {
throw new DefinitionException(
"Unable to resolve (logical definition) valid class for document '{$class}'."
);
}
} elseif ($definition[self::DEFINITION] == DocumentEntity::DEFINITION_FIELDS) {
foreach ($definition[self::DEFINITION_OPTIONS] as $field => $child) {
if (array_key_exists($field, $fields)) {
//Apparently this is child
$defined = $child;
break;
}
}
}
//Child may change definition method or declare it's own children
return $defined == $class ? $class : $this->defineClass($defined, $fields, $schema);
}
/**
* Get cached schema data by it's item name (document name, collection name).
*
* @param string $item
* @return array|string
* @throws ODMException
*/
public function schema($item)
{
if (!isset($this->schema[$item])) {
$this->updateSchema();
}
if (!isset($this->schema[$item])) {
throw new ODMException("Undefined ODM schema item '{$item}'.");
}
return $this->schema[$item];
}
/**
* Get primary document class to be associated with collection. Attention, collection may return
* parent document instance even if query was made using children implementation.
*
* @param string $database
* @param string $collection
* @return string
*/
public function primaryDocument($database, $collection)
{
return $this->schema($database . '/' . $collection);
}
/**
* Update ODM documents schema and return instance of SchemaBuilder.
*
* @param SchemaBuilder $builder User specified schema builder.
* @param bool $createIndexes
* @return SchemaBuilder
*/
public function updateSchema(SchemaBuilder $builder = null, $createIndexes = false)
{
if (empty($builder)) {
$builder = $this->schemaBuilder();
}
//We will create all required indexes now
if ($createIndexes) {
$builder->createIndexes();
}
//Getting cached/normalized schema
$this->schema = $builder->normalizeSchema();
//Saving
$this->memory->saveData(static::MEMORY, $this->schema);
//Let's reinitialize models
DataEntity::resetInitiated();
return $builder;
}
/**
* Get instance of ODM SchemaBuilder.
*
* @param ClassLocatorInterface $locator
* @return SchemaBuilder
*/
public function schemaBuilder(ClassLocatorInterface $locator = null)
{
return $this->factory->make(SchemaBuilder::class, [
'odm' => $this,
'config' => $this->config['schemas'],
'locator' => $locator
]);
}
/**
* Create valid MongoId object based on string or id provided from client side.
*
* @param mixed $mongoID String or MongoId object.
* @return \MongoId|null
*/
public static function mongoID($mongoID)
{
if (empty($mongoID)) {
return null;
}
if (!is_object($mongoID)) {
//Old versions of mongo api does not throws exception on invalid mongo id (1.2.1)
if (!is_string($mongoID) || !preg_match('/[0-9a-f]{24}/', $mongoID)) {
return null;
}
try {
$mongoID = new \MongoId($mongoID);
} catch (\Exception $exception) {
return null;
}
}
return $mongoID;
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models\Exceptions;
use Spiral\Core\Exceptions\RuntimeException;
/**
* Errors raised by Entity logic in runtime.
*/
class EntityException extends RuntimeException implements EntityExceptionInterface
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Loaders;
use Spiral\Database\Injections\Parameter;
use Spiral\ORM\Entities\Loader;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\Entities\WhereDecorator;
use Spiral\ORM\LoaderInterface;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* ManyToMany loader will not only load related data, but will include pivot table data into record
* property "@pivot". Loader support WHERE conditions for both related data and pivot table.
*
* It's STRONGLY recommended to load many-to-many data using postload method. However relation still
* can be used to filter query.
*/
class ManyToManyLoader extends Loader
{
/**
* Relation type is required to correctly resolve foreign record class based on relation
* definition.
*/
const RELATION_TYPE = RecordEntity::MANY_TO_MANY;
/**
* Default load method (inload or postload).
*/
const LOAD_METHOD = self::POSTLOAD;
/**
* Internal loader constant used to decide how to aggregate data tree, true for relations like
* MANY TO MANY or HAS MANY.
*/
const MULTIPLE = true;
/**
* We have to redefine default Loader deduplication as many to many dedup data based on pivot
* table, not record data itself.
*
* @var array
*/
protected $duplicates = [];
/**
* Set of pivot table columns has to be fetched from resulted query.
*
* @var array
*/
protected $pivotColumns = [];
/**
* Pivot columns offset in resulted query row.
*
* @var int
*/
protected $pivotOffset = 0;
/**
* {@inheritdoc}
*/
public function __construct(
ORM $orm,
$container,
array $definition = [],
LoaderInterface $parent = null
) {
parent::__construct($orm, $container, $definition, $parent);
$this->pivotColumns = $this->definition[RecordEntity::PIVOT_COLUMNS];
}
/**
* Pivot table name.
*
* @return string
*/
public function pivotTable()
{
return $this->definition[RecordEntity::PIVOT_TABLE];
}
/**
* Pivot table alias, depends on relation table alias.
*
* @return string
*/
public function pivotAlias()
{
if (!empty($this->options['pivotAlias'])) {
return $this->options['pivotAlias'];
}
return $this->getAlias() . '_pivot';
}
/**
* {@inheritdoc}
*
* @param string $parentRole Helps ManyToMany relation to force record role for morphed
* relations.
*/
public function createSelector($parentRole = '')
{
if (empty($selector = parent::createSelector())) {
return null;
}
//Pivot table joining (INNER in post selection)
$pivotOuterKey = $this->getPivotKey(RecordEntity::THOUGHT_OUTER_KEY);
$selector->innerJoin($this->pivotTable() . ' AS ' . $this->pivotAlias(), [
$pivotOuterKey => $this->getKey(RecordEntity::OUTER_KEY)
]);
//Pivot table conditions
$this->pivotConditions($selector, $parentRole);
if (empty($this->parent)) {
return $selector;
}
//Where and morph conditions
$this->mountConditions($selector);
if (empty($this->parent)) {
//For Many-To-Many loader
return $selector;
}
//Aggregated keys (example: all parent ids)
if (empty($aggregatedKeys = $this->parent->aggregatedKeys($this->getReferenceKey()))) {
//Nothing to postload, no parents
return null;
}
//Adding condition
$selector->where(
$this->getPivotKey(RecordEntity::THOUGHT_INNER_KEY),
'IN',
new Parameter($aggregatedKeys)
);
return $selector;
}
/**
* {@inheritdoc}
*/
protected function clarifySelector(RecordSelector $selector)
{
$selector->join(
$this->joinType(),
$this->pivotTable() . ' AS ' . $this->pivotAlias(),
[$this->getPivotKey(RecordEntity::THOUGHT_INNER_KEY) => $this->getParentKey()]
);
$this->pivotConditions($selector);
$pivotOuterKey = $this->getPivotKey(RecordEntity::THOUGHT_OUTER_KEY);
$selector->join($this->joinType(), $this->getTable() . ' AS ' . $this->getAlias(), [
$pivotOuterKey => $this->getKey(RecordEntity::OUTER_KEY)
]);
$this->mountConditions($selector);
}
/**
* {@inheritdoc}
*
* Pivot table columns will be included.
*/
protected function configureColumns(RecordSelector $selector)
{
if (!$this->isLoadable()) {
return;
}
$this->dataOffset = $selector->generateColumns(
$this->getAlias(),
$this->dataColumns
);
$this->pivotOffset = $selector->generateColumns(
$this->pivotAlias(),
$this->pivotColumns
);
}
/**
* Key related to pivot table. Must include pivot table alias.
*
* @see getKey()
* @param string $key
* @return null|string
*/
protected function getPivotKey($key)
{
if (!isset($this->definition[$key])) {
return null;
}
return $this->pivotAlias() . '.' . $this->definition[$key];
}
/**
* Mounting pivot table conditions including user defined and morph key.
*
* @param RecordSelector $selector
* @param string $parentRole
* @return RecordSelector
*/
protected function pivotConditions(RecordSelector $selector, $parentRole = '')
{
//We have to route all conditions to ON statement
$router = new WhereDecorator($selector, 'onWhere', $this->pivotAlias());
if (!empty($morphKey = $this->getPivotKey(RecordEntity::MORPH_KEY))) {
$router->where(
$morphKey,
!empty($parentRole) ? $parentRole : $this->parent->schema[ORM::M_ROLE_NAME]
);
}
if (!empty($this->definition[RecordEntity::WHERE_PIVOT])) {
//Relation WHERE_PIVOT conditions
$router->where($this->definition[RecordEntity::WHERE_PIVOT]);
}
//User specified WHERE conditions
!empty($this->options['wherePivot']) && $router->where($this->options['wherePivot']);
}
/**
* Set relational and user conditions.
*
* @param RecordSelector $selector
* @return RecordSelector
*/
protected function mountConditions(RecordSelector $selector)
{
//Let's use where decorator to set conditions, it will automatically route tokens to valid
//destination (JOIN or WHERE)
$decorator = new WhereDecorator(
$selector,
$this->isJoinable() ? 'onWhere' : 'where',
$this->getAlias()
);
if (!empty($this->definition[RecordEntity::WHERE])) {
//Relation WHERE conditions
$decorator->where($this->definition[RecordEntity::WHERE]);
}
//User specified WHERE conditions
!empty($this->options['where']) && $decorator->where($this->options['where']);
}
/**
* {@inheritdoc}
*
* We must parse pivot data.
*/
protected function fetchData(array $row)
{
$data = parent::fetchData($row);
$data[ORM::PIVOT_DATA] = array_combine(
$this->pivotColumns,
array_slice($row, $this->pivotOffset, count($this->pivotColumns))
);
return $data;
}
/**
* {@inheritdoc}
*
* Parent criteria located in pivot data, not in record itself.
*/
protected function fetchCriteria(array $data)
{
if (!isset($data[ORM::PIVOT_DATA][$this->definition[RecordEntity::THOUGHT_INNER_KEY]])) {
return null;
}
return $data[ORM::PIVOT_DATA][$this->definition[RecordEntity::THOUGHT_INNER_KEY]];
}
/**
* {@inheritdoc}
*
* We have to redefine default Loader deduplication as many to many dedup data based on pivot
* table, not record data itself.
*/
protected function deduplicate(array &$data)
{
$criteria = $data[ORM::PIVOT_DATA][$this->definition[RecordEntity::THOUGHT_INNER_KEY]]
. '.' . $data[ORM::PIVOT_DATA][$this->definition[RecordEntity::THOUGHT_OUTER_KEY]];
if (!empty($this->definition[RecordEntity::MORPH_KEY])) {
$criteria .= ':' . $data[ORM::PIVOT_DATA][$this->definition[RecordEntity::MORPH_KEY]];
}
if (isset($this->duplicates[$criteria])) {
//Duplicate is presented, let's reduplicate
$data = $this->duplicates[$criteria];
//Duplicate is presented
return false;
}
//Let's remember record to prevent future duplicates
$this->duplicates[$criteria] = &$data;
return true;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
/**
* Declares ability to be identified by primaryKey and it's loaded state. Probably not the best
* name.
*/
interface IdentifiedInterface extends EntityInterface
{
/**
* Indication that entity was fetched from it's primary source (database usually) and not just
* created. Flag must be set to true once entity will be successfully saved.
*
* @return bool
*/
public function isLoaded();
/**
* Primary entity key if any.
*
* @return mixed|null
*/
public function primaryKey();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Interop\Container\ContainerInterface;
use Spiral\Cache\StoreInterface;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Database\Builders\DeleteQuery;
use Spiral\Database\Builders\InsertQuery;
use Spiral\Database\Builders\SelectQuery;
use Spiral\Database\Builders\UpdateQuery;
use Spiral\Database\DatabaseInterface;
use Spiral\Database\DatabaseManager;
use Spiral\Database\Exceptions\DriverException;
use Spiral\Database\Exceptions\QueryException;
use Spiral\Database\Query\CachedResult;
use Spiral\Database\Query\QueryResult;
/**
* Database class is high level abstraction at top of Driver. Multiple databases can use same driver
* and use different by table prefix. Databases usually linked to real database or logical portion
* of database (filtered by prefix).
*/
class Database extends Component implements DatabaseInterface, InjectableInterface
{
/**
* This is magick constant used by Spiral Container, it helps system to resolve controllable
* injections.
*/
const INJECTOR = DatabaseManager::class;
/**
* Transaction isolation level 'SERIALIZABLE'.
*
* This is the highest isolation level. With a lock-based concurrency control DBMS
* implementation, serializability requires read and write locks (acquired on selected data) to
* be released at the end of the transaction. Also range-locks must be acquired when a SELECT
* query uses a ranged WHERE clause, especially to avoid the phantom reads phenomenon (see
* below).
*
* When using non-lock based concurrency control, no locks are acquired; however, if the system
* detects a write collision among several concurrent transactions, only one of them is allowed
* to commit. See snapshot isolation for more details on this topic.
*
* @link http://en.wikipedia.org/wiki/Isolation_(database_systems)
*/
const ISOLATION_SERIALIZABLE = 'SERIALIZABLE';
/**
* Transaction isolation level 'REPEATABLE READ'.
*
* In this isolation level, a lock-based concurrency control DBMS implementation keeps read and
* write locks (acquired on selected data) until the end of the transaction. However,
* range-locks are not managed, so phantom reads can occur.
*
* @link http://en.wikipedia.org/wiki/Isolation_(database_systems)
*/
const ISOLATION_REPEATABLE_READ = 'REPEATABLE READ';
/**
* Transaction isolation level 'READ COMMITTED'.
*
* In this isolation level, a lock-based concurrency control DBMS implementation keeps write
* locks
* (acquired on selected data) until the end of the transaction, but read locks are released as
* soon as the SELECT operation is performed (so the non-repeatable reads phenomenon can occur
* in this isolation level, as discussed below). As in the previous level, range-locks are not
* managed.
*
* Putting it in simpler words, read committed is an isolation level that guarantees that any
* data read is committed at the moment it is read. It simply restricts the reader from seeing
* any intermediate, uncommitted, 'dirty' read. It makes no promise whatsoever that if the
* transaction re-issues the read, it will find the same data; data is free to change after it
* is read.
*
* @link http://en.wikipedia.org/wiki/Isolation_(database_systems)
*/
const ISOLATION_READ_COMMITTED = 'READ COMMITTED';
/**
* Transaction isolation level 'READ UNCOMMITTED'.
*
* This is the lowest isolation level. In this level, dirty reads are allowed, so one
* transaction may see not-yet-committed changes made by other transactions.
*
* Since each isolation level is stronger than those below, in that no higher isolation level
* allows an action forbidden by a lower one, the standard permits a DBMS to run a transaction
* at an isolation level stronger than that requested (e.g., a "Read committed" transaction may
* actually be performed at a "Repeatable read" isolation level).
*
* @link http://en.wikipedia.org/wiki/Isolation_(database_systems)
*/
const ISOLATION_READ_UNCOMMITTED = 'READ UNCOMMITTED';
/**
* Default timestamp expression (must be handler by driver as native expressions).
*/
const TIMESTAMP_NOW = 'DRIVER_SPECIFIC_NOW_EXPRESSION';
/**
* @var Driver
*/
private $driver = null;
/**
* @var string
*/
private $name = '';
/**
* @var string
*/
private $prefix = '';
/**
* Needed to receive cache store on demand.
*
* @invisible
* @var ContainerInterface
*/
protected $container = null;
/**
* @todo replace container with factory?
* @param Driver $driver Driver instance responsible for database
* connection.
* @param string $name Internal database name/id.
* @param string $prefix Default database table prefix, will be used for
* all table identifiers.
* @param ContainerInterface $container Needed to receive cache store on demand.
*/
public function __construct(
Driver $driver,
$name,
$prefix = '',
ContainerInterface $container = null
) {
$this->driver = $driver;
$this->name = $name;
$this->setPrefix($prefix);
//No saturation here as container is not mandratory
$this->container = $container;
}
/**
* @return Driver
*/
public function driver()
{
return $this->driver;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function getType()
{
return $this->driver->getType();
}
/**
* @param string $prefix
* @return $this
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
return $this;
}
/**
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* {@inheritdoc}
*/
public function execute($query, array $parameters = [])
{
return $this->statement($query, $parameters)->rowCount();
}
/**
* {@inheritdoc}
*
* @return QueryResult
* @event statement($statement, $query, $parameters, $database): statement
*/
public function query($query, array $parameters = [])
{
return $this->driver->query($query, $parameters);
}
/**
* Get instance of PDOStatement from Driver.
*
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @return \PDOStatement
* @throws DriverException
* @throws QueryException
* @event statement($statement, $query, $parameters, $database): statement
*/
public function statement($query, array $parameters = [])
{
return $this->driver->statement($query, $parameters);
}
/**
* Execute statement or fetch result from cache and return cached query iterator.
*
* @param int $lifetime Cache lifetime in seconds.
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @param string $key Cache key to be used to store query result.
* @param StoreInterface $store Cache store to store result in, if null default store will
* be used.
* @return CachedResult
* @throws DriverException
* @throws QueryException
*/
public function cached(
$lifetime,
$query,
array $parameters = [],
$key = '',
StoreInterface $store = null
) {
if (empty($store) && empty($this->container())) {
throw new SugarException(
"Unable to receive cache 'StoreInterface', no container set or user store provided."
);
}
if (empty($store)) {
//We can request store from container
$store = $this->container()->get(StoreInterface::class);
}
if (empty($key)) {
//Trying to build unique query id based on provided options and environment.
$key = md5(serialize([$query, $parameters, $this->name, $this->prefix]));
}
$data = $store->remember($key, $lifetime, function () use ($query, $parameters) {
return $this->query($query, $parameters)->fetchAll();
});
return new CachedResult($store, $key, $query, $parameters, $data);
}
/**
* Get instance of InsertBuilder associated with current Database.
*
* @param string $table Table where values should be inserted to.
* @return InsertQuery
*/
public function insert($table = '')
{
return $this->driver->insertBuilder($this, compact('table'));
}
/**
* Get instance of UpdateBuilder associated with current Database.
*
* @param string $table Table where rows should be updated in.
* @param array $values Initial set of columns to update associated with their values.
* @param array $where Initial set of where rules specified as array.
* @return UpdateQuery
*/
public function update($table = '', array $values = [], array $where = [])
{
return $this->driver->updateBuilder($this, compact('table', 'where', 'values'));
}
/**
* Get instance of DeleteBuilder associated with current Database.
*
* @param string $table Table where rows should be deleted from.
* @param array $where Initial set of where rules specified as array.
* @return DeleteQuery
*/
public function delete($table = '', array $where = [])
{
return $this->driver->deleteBuilder($this, compact('table', 'where'));
}
/**
* Get instance of SelectBuilder associated with current Database.
*
* @param array|string $columns Columns to select.
* @return SelectQuery
*/
public function select($columns = '*')
{
$columns = func_get_args();
if (is_array($columns) && isset($columns[0]) && is_array($columns[0])) {
//Can be required in some cases while collecting data from Table->select(), stupid bug.
$columns = $columns[0];
}
return $this->driver->selectBuilder($this, ['columns' => $columns]);
}
/**
* {@inheritdoc}
*
* @param string $isolationLevel
* @throws \Exception
*/
public function transaction(callable $callback, $isolationLevel = null)
{
$this->begin($isolationLevel);
try {
$result = call_user_func($callback, $this);
$this->commit();
return $result;
} catch (\Exception $exception) {
$this->rollBack();
throw $exception;
}
}
/**
* {@inheritdoc}
*
* @link http://en.wikipedia.org/wiki/Isolation_(database_systems)
* @param string $isolationLevel
*/
public function begin($isolationLevel = null)
{
return $this->driver->beginTransaction($isolationLevel);
}
/**
* {@inheritdoc}
*/
public function commit()
{
return $this->driver->commitTransaction();
}
/**
* {@inheritdoc}
*/
public function rollback()
{
return $this->driver->rollbackTransaction();
}
/**
* {@inheritdoc}
*/
public function hasTable($name)
{
return $this->driver->hasTable($this->prefix . $name);
}
/**
* {@inheritdoc}
*
* @return Table
*/
public function table($name)
{
return new Table($this, $name);
}
/**
* {@inheritdoc}
*
* @return Table[]
*/
public function getTables()
{
$result = [];
foreach ($this->driver->tableNames() as $table) {
if ($this->prefix && strpos($table, $this->prefix) !== 0) {
//Logical partitioning
continue;
}
$result[] = $this->table(substr($table, strlen($this->prefix)));
}
return $result;
}
/**
* Shortcut to get table abstraction.
*
* @param string $name Table name without prefix.
* @return Table
*/
public function __get($name)
{
return $this->table($name);
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders\Prototypes;
use Spiral\Cache\StoreInterface;
use Spiral\Database\Builders\Traits\JoinsTrait;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Entities\QueryCompiler;
use Spiral\Database\Exceptions\BuilderException;
use Spiral\Database\Exceptions\QueryException;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Injections\Parameter;
use Spiral\Database\Injections\ParameterInterface;
use Spiral\Database\Query\CachedResult;
use Spiral\Database\Query\QueryResult;
use Spiral\Pagination\PaginableInterface;
use Spiral\Pagination\PaginatorAwareInterface;
use Spiral\Pagination\Traits\PaginatorTrait;
/**
* Prototype for select queries, include ability to cache, paginate or chunk results. Support WHERE,
* JOIN, HAVING, ORDER BY, GROUP BY, UNION and DISTINCT statements. In addition only desired set
* of columns can be selected. In addition select
*
* @see AbstractWhere
* @method int avg($identifier) Perform aggregation (AVG) based on column or expression value.
* @method int min($identifier) Perform aggregation (MIN) based on column or expression value.
* @method int max($identifier) Perform aggregation (MAX) based on column or expression value.
* @method int sum($identifier) Perform aggregation (SUM) based on column or expression value.
*/
abstract class AbstractSelect extends AbstractWhere implements
\IteratorAggregate,
PaginableInterface,
PaginatorAwareInterface,
\JsonSerializable
{
/**
* Abstract select query must fully support joins and be paginable.
*/
use JoinsTrait, PaginatorTrait;
/**
* Sort directions.
*/
const SORT_ASC = 'ASC';
const SORT_DESC = 'DESC';
/**
* Query must return only unique rows.
*
* @var bool|string
*/
protected $distinct = false;
/**
* Columns or expressions to be fetched from database, can include aliases (AS).
*
* @var array
*/
protected $columns = ['*'];
/**
* Set of generated having tokens, format must be supported by QueryCompilers.
*
* @see AbstractWhere
* @var array
*/
protected $havingTokens = [];
/**
* Parameters collected while generating HAVING tokens, must be in a same order as parameters
* in resulted query.
*
* @see AbstractWhere
* @var array
*/
protected $havingParameters = [];
/**
* Columns/expression associated with their sort direction (ASK|DESC).
*
* @var array
*/
protected $ordering = [];
/**
* Columns/expressions to group by.
*
* @var array
*/
protected $grouping = [];
/**
* Associated cache store.
*
* @var StoreInterface
*/
protected $cacheStore = null;
/**
* Cache lifetime in seconds.
*
* @var int
*/
protected $cacheLifetime = 0;
/**
* User specified cache key (optional).
*
* @var string
*/
protected $cacheKey = '';
/**
* {@inheritdoc}
*/
public function getParameters(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
//Using associated compiler
$compiler = $this->compiler;
}
return $this->flattenParameters(
$compiler->orderParameters(
QueryCompiler::SELECT_QUERY,
$this->whereParameters,
$this->onParameters,
$this->havingParameters
)
);
}
/**
* Mark query to return only distinct results.
*
* @param bool|string $distinct You are only allowed to use string value for Postgres databases.
* @return $this
*/
public function distinct($distinct = true)
{
$this->distinct = $distinct;
return $this;
}
/**
* Simple HAVING condition with various set of arguments.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function having($identifier, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken('AND', func_get_args(), $this->havingTokens, $this->havingWrapper());
return $this;
}
/**
* Simple AND HAVING condition with various set of arguments.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function andHaving($identifier, $variousA = null, $variousB = null, $variousC = null)
{
$this->whereToken('AND', func_get_args(), $this->havingTokens, $this->havingWrapper());
return $this;
}
/**
* Simple OR HAVING condition with various set of arguments.
*
* @see AbstractWhere
* @param string|mixed $identifier Column or expression.
* @param mixed $variousA Operator or value.
* @param mixed $variousB Value, if operator specified.
* @param mixed $variousC Required only in between statements.
* @return $this
* @throws BuilderException
*/
public function orHaving($identifier, $variousA = [], $variousB = null, $variousC = null)
{
$this->whereToken('OR', func_get_args(), $this->havingTokens, $this->havingWrapper());
return $this;
}
/**
* Sort result by column/expression. You can apply multiple sortings to query via calling method
* few times or by specifying values using array of sort parameters:
*
* $select->orderBy([
* 'id' => SelectQuery::SORT_DESC,
* 'name' => SelectQuery::SORT_ASC
* ]);
*
* @param string|array $expression
* @param string $direction Sorting direction, ASC|DESC.
* @return $this
*/
public function orderBy($expression, $direction = self::SORT_ASC)
{
if (!is_array($expression)) {
$this->ordering[] = [$expression, $direction];
return $this;
}
foreach ($expression as $nested => $direction) {
$this->ordering[] = [$nested, $direction];
}
return $this;
}
/**
* Column or expression to group query by.
*
* @param string $expression
* @return $this
*/
public function groupBy($expression)
{
$this->grouping[] = $expression;
return $this;
}
/**
* Mark selection as cached one, result will be passed thought database->cached() method and
* will be stored in cache storage for specified amount of seconds.
*
* @see Database::cached()
* @param int $lifetime Cache lifetime in seconds.
* @param string $key Optional, Database will generate key based on query.
* @param StoreInterface $store Optional, Database will resolve cache store using container.
* @return $this
*/
public function cache($lifetime, $key = '', StoreInterface $store = null)
{
$this->cacheLifetime = $lifetime;
$this->cacheKey = $key;
$this->cacheStore = $store;
return $this;
}
/**
* {@inheritdoc}
*
* @param bool $paginate Apply pagination to result, can be disabled in honor of count method.
* @return QueryResult|CachedResult
*/
public function run($paginate = true)
{
$backup = [$this->limit, $this->offset];
if ($paginate) {
$this->applyPagination();
} else {
//We have to flush limit and offset values when pagination is not required.
$this->limit = $this->offset = 0;
}
if (empty($this->cacheLifetime)) {
$result = $this->database->query(
$this->sqlStatement(),
$this->getParameters()
);
} else {
$result = $this->database->cached(
$this->cacheLifetime,
$this->sqlStatement(),
$this->getParameters(),
$this->cacheKey,
$this->cacheStore
);
}
//Restoring limit and offset values
list($this->limit, $this->offset) = $backup;
return $result;
}
/**
* Iterate thought result using smaller data chinks with defined size and walk function.
*
* Example:
* $select->chunked(100, function(QueryResult $result, $offset, $count) {
* dump($result);
* });
*
* You must return FALSE from walk function to stop chunking.
*
* @param int $limit
* @param callable $callback
*/
public function chunked($limit, callable $callback)
{
$count = $this->count();
$this->limit($limit);
$offset = 0;
while ($offset + $limit <= $count) {
$result = call_user_func_array($callback, [
$this->offset($offset)->getIterator(),
$offset,
$count
]);
if ($result === false) {
//Stop iteration
return;
}
$offset += $limit;
}
}
/**
* {@inheritdoc}
*
* Count number of rows in query. Limit, offset, order by, group by values will be ignored. Do
* not count united queries, or queries in complex joins.
*
* @param string $column Column to count by (every column by default).
* @return int
*/
public function count($column = '*')
{
$backup = [$this->columns, $this->ordering, $this->grouping, $this->limit, $this->offset];
$this->columns = ["COUNT({$column})"];
//Can not be used with COUNT()
$this->ordering = $this->grouping = [];
$this->limit = $this->offset = 0;
$result = $this->run(false)->fetchColumn();
list($this->columns, $this->ordering, $this->grouping, $this->limit, $this->offset) = $backup;
return (int)$result;
}
/**
* {@inheritdoc}
*
* Shortcut to execute one of aggregation methods (AVG, MAX, MIN, SUM) using method name as
* reference.
*
* Example:
* echo $select->sum('user.balance');
*
* @param string $method
* @param string $arguments
* @return int
* @throws BuilderException
* @throws QueryException
*/
public function __call($method, $arguments)
{
if (!in_array($method = strtoupper($method), ['AVG', 'MIN', 'MAX', 'SUM'])) {
throw new BuilderException("Unknown aggregation method '{$method}'.");
}
if (!isset($arguments[0]) || count($arguments) > 1) {
throw new BuilderException("Aggregation methods can support exactly one column.");
}
$columns = $this->columns;
$this->columns = ["{$method}({$arguments[0]})"];
$result = $this->run(false)->fetchColumn();
$this->columns = $columns;
return (int)$result;
}
/**
* {@inheritdoc}
*
* @return QueryResult
*/
public function getIterator()
{
return $this->run();
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->getIterator()->jsonSerialize();
}
/**
* Applied to every potential parameter while having tokens generation.
*
* @return \Closure
*/
private function havingWrapper()
{
return function ($parameter) {
if ($parameter instanceof FragmentInterface) {
//We are only not creating bindings for plan fragments
if (!$parameter instanceof ParameterInterface && !$parameter instanceof QueryBuilder) {
return $parameter;
}
}
if (is_array($parameter)) {
throw new BuilderException("Arrays must be wrapped with Parameter instance.");
}
//Wrapping all values with ParameterInterface
if (!$parameter instanceof ParameterInterface) {
$parameter = new Parameter($parameter, Parameter::DETECT_TYPE);
};
//Let's store to sent to driver when needed
$this->havingParameters[] = $parameter;
return $parameter;
};
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
* @copyright �2009-2015
*/
namespace Spiral\ODM\Entities;
use Spiral\Core\Component;
use Spiral\ODM\Configs\ODMConfig;
use Spiral\ODM\Document;
use Spiral\ODM\DocumentEntity;
use Spiral\ODM\Entities\Schemas\CollectionSchema;
use Spiral\ODM\Entities\Schemas\DocumentSchema;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\SchemaException;
use Spiral\ODM\ODM;
use Spiral\Tokenizer\ClassLocatorInterface;
/**
* Schema builder responsible for static analysis of existed Documents, their schemas, validations,
* requested indexes and etc.
*/
class SchemaBuilder extends Component
{
/**
* @var DocumentSchema[]
*/
private $documents = [];
/**
* @var CollectionSchema[]
*/
private $collections = [];
/**
* @var ODMConfig
*/
protected $config = null;
/**
* @invisible
* @var ODM
*/
protected $odm = null;
/**
* @param ODM $odm
* @param ODMConfig $config
* @param ClassLocatorInterface $locator
*/
public function __construct(ODM $odm, ODMConfig $config, ClassLocatorInterface $locator)
{
$this->config = $config;
$this->odm = $odm;
$this->locateDocuments($locator)->locateSources($locator);
$this->describeCollections();
}
/**
* @return ODM
*/
public function odm()
{
return $this->odm;
}
/**
* Resolve database alias.
*
* @param string $database
* @return string
*/
public function databaseAlias($database)
{
if (empty($database)) {
$database = $this->config->defaultDatabase();
}
//Spiral support ability to link multiple virtual databases together using aliases
return $this->config->resolveAlias($database);
}
/**
* Check if Document class known to schema builder.
*
* @param string $class
* @return bool
*/
public function hasDocument($class)
{
return isset($this->documents[$class]);
}
/**
* Instance of DocumentSchema associated with given class name.
*
* @param string $class
* @return DocumentSchema
* @throws SchemaException
*/
public function document($class)
{
if ($class == DocumentEntity::class || $class == Document::class) {
//No need to remember schema for abstract Document
return new DocumentSchema($this, DocumentEntity::class);
}
if (!isset($this->documents[$class])) {
throw new SchemaException("Unknown document class '{$class}'.");
}
return $this->documents[$class];
}
/**
* @return DocumentSchema[]
*/
public function getDocuments()
{
return $this->documents;
}
/**
* @return CollectionSchema[]
*/
public function getCollections()
{
return $this->collections;
}
/**
* Create every requested collection index.
*
* @throws \MongoException
*/
public function createIndexes()
{
foreach ($this->getCollections() as $collection) {
if (empty($indexes = $collection->getIndexes())) {
continue;
}
$odmCollection = $this->odm->database(
$collection->getDatabase()
)->selectCollection(
$collection->getName()
);
foreach ($indexes as $index) {
$options = [];
if (isset($index[DocumentEntity::INDEX_OPTIONS])) {
$options = $index[DocumentEntity::INDEX_OPTIONS];
unset($index[DocumentEntity::INDEX_OPTIONS]);
}
$odmCollection->createIndex($index, $options);
}
}
}
/**
* Normalize document schema in lighter structure to be saved in ODM component memory.
*
* @return array
* @throws SchemaException
* @throws DefinitionException
*/
public function normalizeSchema()
{
$result = [];
//Pre-packing collections
foreach ($this->getCollections() as $collection) {
$name = $collection->getDatabase() . '/' . $collection->getName();
$result[$name] = $collection->getParent()->getName();
}
foreach ($this->getDocuments() as $document) {
if ($document->isAbstract()) {
continue;
}
$schema = [
ODM::D_DEFINITION => $this->packDefinition($document->classDefinition()),
ODM::D_SOURCE => $document->getSource(),
ODM::D_HIDDEN => $document->getHidden(),
ODM::D_SECURED => $document->getSecured(),
ODM::D_FILLABLE => $document->getFillable(),
ODM::D_MUTATORS => $document->getMutators(),
ODM::D_VALIDATES => $document->getValidates(),
ODM::D_DEFAULTS => $document->getDefaults(),
ODM::D_AGGREGATIONS => $this->packAggregations($document->getAggregations()),
ODM::D_COMPOSITIONS => array_keys($document->getCompositions())
];
if (!$document->isEmbeddable()) {
$schema[ODM::D_COLLECTION] = $document->getCollection();
$schema[ODM::D_DB] = $document->getDatabase();
}
ksort($schema);
$result[$document->getName()] = $schema;
}
return $result;
}
/**
* Get all mutators associated with field type.
*
* @param string $type Field type.
* @return array
*/
public function getMutators($type)
{
return $this->config->getMutators($type);
}
/**
* Get mutator alias if presented. Aliases used to simplify schema definition.
*
* @param string $alias
* @return string|array
*/
public function mutatorAlias($alias)
{
return $this->config->mutatorAlias($alias);
}
/**
* Locate every available Document class.
*
* @param ClassLocatorInterface $locator
* @return $this
*/
protected function locateDocuments(ClassLocatorInterface $locator)
{
foreach ($locator->getClasses(DocumentEntity::class) as $class => $definition) {
if ($class == DocumentEntity::class || $class == Document::class) {
continue;
}
$this->documents[$class] = new DocumentSchema($this, $class);
}
return $this;
}
/**
* Locate ORM entities sources.
*
* @param ClassLocatorInterface $locator
* @return $this
*/
protected function locateSources(ClassLocatorInterface $locator)
{
foreach ($locator->getClasses(DocumentSource::class) as $class => $definition) {
$reflection = new \ReflectionClass($class);
if (
$reflection->isAbstract()
|| empty($document = $reflection->getConstant('DOCUMENT'))
) {
continue;
}
if ($this->hasDocument($document)) {
//Associating source with record
$this->document($document)->setSource($class);
}
}
return $this;
}
/**
* Create instances of CollectionSchema associated with found DocumentSchema instances.
*
* @throws SchemaException
*/
protected function describeCollections()
{
foreach ($this->getDocuments() as $document) {
if ($document->isEmbeddable()) {
//Skip embedded models
continue;
}
//Getting fully specified collection name (with specified db)
$collection = $document->getDatabase() . '/' . $document->getCollection();
if (isset($this->collections[$collection])) {
//Already described by parent
continue;
}
//Collection must be described by parent Document
$parent = $document->getParent(true);
$this->collections[$collection] = new CollectionSchema($parent);
}
}
/**
* Pack (normalize) class definition.
*
* @param mixed $definition
* @return array|string
*/
private function packDefinition($definition)
{
if (is_string($definition)) {
//Single collection class
return $definition;
}
return [
ODM::DEFINITION => $definition['type'],
ODM::DEFINITION_OPTIONS => $definition['options']
];
}
/**
* Pack (normalize) document aggregations.
*
* @param array $aggregations
* @return array
*/
private function packAggregations(array $aggregations)
{
$result = [];
foreach ($aggregations as $name => $aggregation) {
$result[$name] = [
ODM::AGR_TYPE => $aggregation['type'],
ODM::ARG_CLASS => $aggregation['class'],
ODM::AGR_QUERY => $aggregation['query']
];
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Injections;
/**
* Parameter interface is very similar to sql fragments, however it may not only mock sql
* expressions but also data-set of parameters to be injected into this expression.
*
* Usually used for complex set of parameters or late parameter binding.
*
* Database implementation must inject parameter SQL into expression, but use parameter value to be
* sent to database.
*/
interface ParameterInterface extends ExpressionInterface
{
/**
* Get mocked parameter value or values in array form.
*
* @return mixed|array
*/
public function getValue();
/**
* Change parameter value.
*
* @param mixed $value
*/
public function setValue($value);
/**
* Parameter type.
*
* @return int|mixed
*/
public function getType();
/**
* In cases when parameter mock arrays such method has to return all nested values on one level,
* when parameter mock singular value - it has to return array of itself.
*
* @return ParameterInterface[]
*/
public function flatten();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler;
use Spiral\Stempler\Behaviours\BlockBehaviour;
use Spiral\Stempler\Behaviours\ExtendsBehaviour;
use Spiral\Stempler\Behaviours\IncludeBehaviour;
use Spiral\Stempler\Exceptions\LoaderExceptionInterface;
use Spiral\Stempler\Exceptions\StemplerException;
use Spiral\Stempler\Importers\Stopper;
/**
* Supervisors used to control node behaviours and syntax.
*/
class Supervisor implements SupervisorInterface
{
/**
* Used to create unique node names when required.
*
* @var int
*/
private static $index = 0;
/**
* Active set of imports.
*
* @var ImporterInterface[]
*/
private $importers = [];
/**
* @var SyntaxInterface
*/
protected $syntax = null;
/**
* @var LoaderInterface
*/
protected $loader = null;
/**
* @param LoaderInterface $loader
* @param SyntaxInterface $syntax
*/
public function __construct(LoaderInterface $loader, SyntaxInterface $syntax)
{
$this->loader = $loader;
$this->syntax = $syntax;
}
/**
* {@inheritdoc}
*/
public function syntax()
{
return $this->syntax;
}
/**
* Add new elements import locator.
*
* @param ImporterInterface $import
*/
public function registerImporter(ImporterInterface $import)
{
array_unshift($this->importers, $import);
}
/**
* Active templater imports.
*
* @return ImporterInterface[]
*/
public function getImporters()
{
return $this->importers;
}
/**
* Remove all element importers.
*/
public function flushImporters()
{
$this->importers = [];
}
/**
* {@inheritdoc}
*/
public function tokenBehaviour(array $token, array $content, Node $node)
{
switch ($this->syntax->tokenType($token, $name)) {
case SyntaxInterface::TYPE_BLOCK:
//Tag declares block (section)
return new BlockBehaviour($name);
case SyntaxInterface::TYPE_EXTENDS:
//Declares parent extending
$extends = new ExtendsBehaviour(
$this->createNode($this->syntax->resolvePath($token), $token),
$token
);
//We have to combine parent imports with local one (this is why uses has to be defined
//after extends tag!)
$this->importers = $extends->parentImports();
//Sending command to extend parent
return $extends;
case SyntaxInterface::TYPE_IMPORTER:
//Implementation specific
$this->registerImporter($this->syntax->createImporter($token, $this));
//No need to include import tag into source
return BehaviourInterface::SKIP_TOKEN;
}
//We now have to decide if element points to external view (source) to be imported
foreach ($this->importers as $importer) {
if ($importer->importable($name, $token)) {
if ($importer instanceof Stopper) {
//Native importer tells us to treat this element as simple html
break;
}
//Let's include!
return new IncludeBehaviour(
$this, $importer->resolvePath($name, $token), $content, $token
);
}
}
return BehaviourInterface::SIMPLE_TAG;
}
/**
* Create node based on given location with identical supervisor (cloned).
*
* @param string $path
* @param array $token Context token.
* @return Node
* @throws StemplerException
*/
public function createNode($path, array $token = [])
{
//We support dots!
if (!empty($token)) {
$path = str_replace('.', '/', $path);
}
try {
$source = $this->loader->getSource($path);
} catch (LoaderExceptionInterface $exception) {
throw new StemplerException($exception->getMessage(), $token, 0, $exception);
}
try {
return new Node(clone $this, $this->uniquePlaceholder(), $source);
} catch (StemplerException $exception) {
//Wrapping to clarify location of error
throw $this->clarifyException($path, $exception);
}
}
/**
* Get unique placeholder name, unique names are required in some cases to correctly process
* includes and etc.
*
* @return string
*/
public function uniquePlaceholder()
{
return md5(self::$index++);
}
/**
* Clarify exeption with it's actual location.
*
* @param string $path
* @param StemplerException $exception
* @return StemplerException
*/
protected function clarifyException($path, StemplerException $exception)
{
if (empty($exception->getToken())) {
//Unable to locate
return $exception;
}
//We will need only first tag line
$target = explode("\n", $exception->getToken()[HtmlTokenizer::TOKEN_CONTENT])[0];
//Let's try to locate place where exception was used
$lines = explode("\n", $this->loader->getSource($path));
foreach ($lines as $number => $line) {
if (strpos($line, $target) !== false) {
//We found where token were used (!!)
$exception->setLocation($this->loader->localFilename($path), $number + 1);
break;
}
}
return $exception;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Stores;
use Spiral\Cache\CacheStore;
use Spiral\Files\FilesInterface;
/**
* Serializes data to file. Usually points to runtime directory.
*/
class FileStore extends CacheStore
{
/**
* @var string
*/
private $directory = '';
/**
* @var string
*/
private $extension = 'cache';
/**
* @invisible
* @var FilesInterface
*/
protected $files = null;
/**
* @param FilesInterface $files
* @param string $directory
* @param string $extension
*/
public function __construct(FilesInterface $files, $directory, $extension = 'cache')
{
$this->directory = $files->normalizePath($directory);
$this->extension = $extension;
$this->files = $files;
}
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return true;
}
/**
* {@inheritdoc}
*/
public function has($name)
{
if (!$this->files->exists($filename = $this->makeFilename($name))) {
return false;
}
$cacheData = unserialize($this->files->read($filename));
if (!empty($cacheData[0]) && $cacheData[0] < time()) {
$this->delete($name);
//Expired
return false;
}
return true;
}
/**
* {@inheritdoc}
*
* @param int $expiration Current expiration time value in seconds (reference).
*/
public function get($name, &$expiration = null)
{
if (!$this->files->exists($filename = $this->makeFilename($name))) {
return null;
}
$cacheData = unserialize($this->files->read($filename));
if (!empty($cacheData[0]) && $cacheData[0] < time()) {
$this->delete($name);
return null;
}
return $cacheData[1];
}
/**
* {@inheritdoc}
*/
public function set($name, $data, $lifetime)
{
return $this->files->write(
$this->makeFilename($name),
serialize([time() + $lifetime, $data])
);
}
/**
* {@inheritdoc}
*/
public function forever($name, $data)
{
return $this->files->write(
$this->makeFilename($name),
serialize([0, $data])
);
}
/**
* {@inheritdoc}
*/
public function delete($name)
{
$this->files->delete($this->makeFilename($name));
}
/**
* {@inheritdoc}
*/
public function inc($name, $delta = 1)
{
$value = $this->get($name, $expiration) + $delta;
$this->set($name, $value, $expiration - time());
return $value;
}
/**
* {@inheritdoc}
*/
public function dec($name, $delta = 1)
{
$value = $this->get($name, $expiration) - $delta;
$this->set($name, $value, $expiration - time());
return $value;
}
/**
* {@inheritdoc}
*/
public function flush()
{
foreach ($this->files->getFiles($this->directory, $this->extension) as $filename) {
$this->files->delete($filename);
}
}
/**
* Create filename using cache name.
*
* @param string $name
* @return string Filename.
*/
protected function makeFilename($name)
{
return $this->directory . '/' . md5($name) . '.' . $this->extension;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Encrypter\Exceptions;
use Spiral\Core\Exceptions\RuntimeException;
/**
* General encrypter exception (bad key and etc).
*/
class EncrypterException extends RuntimeException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Traits;
use Spiral\ODM\Document;
use Spiral\ODM\Entities\DocumentSelector;
use Spiral\ODM\Entities\DocumentSource;
use Spiral\ODM\ODM;
use Spiral\ORM\Exceptions\ORMException;
use Spiral\ORM\RecordEntity;
/**
* Static record functionality including create and find methods.
*/
trait FindTrait
{
/**
* Find multiple records based on provided query.
*
* Example:
* User::find(['status' => 'active'], ['profile']);
*
* @param array $where Selection WHERE statement.
* @return DocumentSelector
*/
public static function find($where = [])
{
return static::source()->find($where);
}
/**
* Fetch one record based on provided query or return null. Use second argument to specify
* relations to be loaded.
*
* Example:
* User::findOne(['name' => 'Wolfy-J'], ['profile'], ['id' => 'DESC']);
*
* @param array $where Selection WHERE statement.
* @param array $sortBy Sort by.
* @return RecordEntity|null
*/
public static function findOne($where = [], array $sortBy = [])
{
return static::source()->findOne($where, $sortBy);
}
/**
* Find record using it's primary key. Relation data can be preloaded with found record.
*
* Example:
* User::findByID(1, ['profile']);
*
* @param mixed $primaryKey Primary key.
* @return Document|null
*/
public static function findByPK($primaryKey)
{
return static::source()->findByPK($primaryKey);
}
/**
* Instance of ORM Selector associated with specific document.
*
* @see Component::staticContainer()
* @param ODM $odm ODM component, global container will be called if not instance provided.
* @return DocumentSource
* @throws ORMException
*/
public static function source(ODM $odm = null)
{
/**
* Using global container as fallback.
*
* @var ODM $odm
*/
if (empty($odm)) {
//Using global container as fallback
$odm = self::staticContainer()->get(ODM::class);
}
return $odm->source(static::class);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Debug;
use Monolog\Logger;
use Spiral\Core\Container\SingletonInterface;
/**
* SharedLogger used as global system logger to handle errors, debug messages and etc.
*
* This is "default" logger in spiral environment.
*/
class SharedLogger extends Logger implements SingletonInterface
{
/**
* This logger is global for whole application.
*/
const SINGLETON = self::class;
/**
* @param Debugger $debugger
*/
public function __construct(Debugger $debugger)
{
parent::__construct(static::class, $debugger->logHandlers(static::class));
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Entities;
use Psr\Log\LoggerAwareInterface;
use Spiral\Core\Component;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\ODM\Document;
use Spiral\ODM\DocumentEntity;
use Spiral\ODM\ODM;
use Spiral\Pagination\PaginableInterface;
use Spiral\Pagination\Traits\PaginatorTrait;
/**
* Mocks MongoCollection to aggregate query, limits and sorting values and product DocumentIterator
* as result.
*
* @see DocumentIterator
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
*
* Set of MongoCollection mocked methods:
* @method bool getSlaveOkay()
* @method bool setSlaveOkay($slave_okay)
* @method array getReadPreference()
* @method bool setReadPreference($read_preference, $tags)
* @method array drop()
* @method array validate($validate)
* @method bool|array insert($array_of_fields_OR_object, $options = [])
* @method mixed batchInsert($documents, $options = [])
* @method bool update($old_array_of_fields_OR_object, $new_fields_OR_object, $options = [])
* @method bool|array remove($array_of_fields_OR_object, $options = [])
* @method bool ensureIndex($key_OR_array_of_keys, $options = [])
* @method array deleteIndex($string_OR_array_of_keys)
* @method array deleteIndexes()
* @method array getIndexInfo()
* @method save($array_of_fields_OR_object, $options = [])
* @method array createDBRef($array_with_id_fields_OR_MongoID)
* @method array getDBRef($reference)
* @method array group($keys_or_MongoCode, $initial_value, $array_OR_MongoCode, $options = [])
* @method bool|array distinct($key, $query)
* @method array aggregate(array $pipeline, array $op, array $pipelineOperators)
*/
class DocumentSelector extends Component implements
\Countable,
\IteratorAggregate,
PaginableInterface,
LoggerAwareInterface,
\JsonSerializable
{
/**
* Collection queries can be paginated, in addition profiling messages will be dumped into log.
*/
use LoggerTrait, PaginatorTrait;
/**
* Sort order.
*
* @link http://php.net/manual/en/class.mongocollection.php#mongocollection.constants.ascending
*/
const ASCENDING = 1;
/**
* Sort order.
*
* @link http://php.net/manual/en/class.mongocollection.php#mongocollection.constants.descending
*/
const DESCENDING = -1;
/**
* @var string
*/
private $name = '';
/**
* @var string
*/
private $database = 'default';
/**
* Associated MongoCollection.
*
* @var \MongoCollection
*/
private $collection = null;
/**
* Fields and conditions to query by.
*
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
* @var array
*/
protected $query = [];
/**
* Fields to sort.
*
* @var array
*/
protected $sort = [];
/**
* @invisible
* @var ODM
*/
protected $odm = null;
/**
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
* @param ODM $odm ODMManager component instance.
* @param string $database Associated database name/id.
* @param string $collection Collection name.
* @param array $query Fields and conditions to query by.
*/
public function __construct(ODM $odm, $database, $collection, array $query = [])
{
$this->odm = $odm;
$this->name = $collection;
$this->database = $database;
$this->query = $query;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getDatabase()
{
return $this->database;
}
/**
* Set additional query, fields will be merged to currently existed request using array_merge.
*
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
* @param array $query Fields and conditions to query by.
* @return $this
*/
public function query(array $query = [])
{
array_walk_recursive($query, function (&$value) {
if ($value instanceof \DateTime) {
//MongoDate is always UTC, which is good :)
$value = new \MongoDate($value->getTimestamp());
}
});
$this->query = array_merge($this->query, $query);
return $this;
}
/**
* Set additional query field, fields will be merged to currently existed request using
* array_merge. Alias for query.
*
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
* @param array $query Fields and conditions to query by.
* @return $this
*/
public function where(array $query = [])
{
return $this->query($query);
}
/**
* Set additional query field, fields will be merged to currently existed request using
* array_merge. Alias for query.
*
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
* @param array $query Fields and conditions to query by.
* @return $this
*/
public function find(array $query = [])
{
return $this->query($query);
}
/**
* Fetch one record from database using it's primary key. You can use INLOAD and JOIN_ONLY
* loaders with HAS_MANY or MANY_TO_MANY relations with this method as no limit were used.
*
* @see findOne()
* @param mixed $id Primary key value.
* @return DocumentEntity|null
*/
public function findByPK($id)
{
return $this->findOne(['_id' => $this->odm->mongoID($id)]);
}
/**
* Select one document or it's fields from collection.
*
* @param array $query Fields and conditions to query by.
* @return DocumentEntity|array
*/
public function findOne(array $query = [])
{
return $this->createCursor($query, [], 1)->getNext();
}
/**
* Current fields and conditions to query by.
*
* @link http://docs.mongodb.org/manual/tutorial/query-documents/
* @return array
*/
public function getQuery()
{
return $this->query;
}
/**
* Sorts the results by given fields.
*
* @link http://www.php.net/manual/en/mongocursor.sort.php
* @param array $fields An array of fields by which to sort. Each element in the array has as
* key the field name, and as value either 1 for ascending sort, or -1 for
* descending sort.
* @return $this
*/
public function sortBy(array $fields)
{
$this->sort = $fields;
return $this;
}
/**
* Fetch all available document instances from query.
*
* @return Document[]
*/
public function fetchDocuments()
{
$result = [];
foreach ($this->createCursor() as $document) {
$result[] = $document;
}
return $result;
}
/**
* Fetch all available documents as arrays of fields.
*
* @param array $fields Fields of the results to return.
* @return array
*/
public function fetchFields($fields = [])
{
$result = [];
foreach ($this->createCursor([], $fields) as $document) {
$result[] = $document;
}
return $result;
}
/**
* {@inheritdoc}
*/
public function count()
{
return $this->mongoCollection()->count($this->query);
}
/**
* {@inheritdoc}
*
* @return DocumentCursor|Document[]
*/
public function getIterator()
{
return $this->createCursor();
}
/**
* Get instance of DocumentCursor.
*
* @return DocumentCursor
*/
public function getCursor()
{
return $this->createCursor();
}
/**
* Bypass call to MongoCollection.
*
* @param string $method Method name.
* @param array $arguments Method arguments.
* @return mixed
*/
public function __call($method, array $arguments = [])
{
return call_user_func_array([$this->mongoCollection(), $method], $arguments);
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->getIterator();
}
/**
* Destructing.
*/
public function __destruct()
{
$this->odm = $this->collection = $this->paginator = null;
$this->query = [];
}
/**
* @return array
*/
public function __debugInfo()
{
return [
'collection' => $this->database . '/' . $this->name,
'query' => $this->query,
'limit' => $this->limit,
'offset' => $this->offset,
'sort' => $this->sort
];
}
/**
* Create CursorReader based on stored query, limits and sorting.
*
* @param array $query Fields and conditions to query by.
* @param array $fields Fields of the results to return.
* @param int|null $limit Custom limit value.
* @return DocumentCursor
* @throws \MongoException
*/
protected function createCursor($query = [], $fields = [], $limit = null)
{
$this->query($query);
$this->applyPagination();
$cursorReader = new DocumentCursor(
$this->mongoCollection()->find($this->query, $fields),
$this->odm,
empty($fields) ? $this->primaryDocument() : null,
$this->sort,
!empty($limit) ? $limit : $this->limit,
$this->offset
);
if ((!empty($this->limit) || !empty($this->offset)) && empty($this->sort)) {
//Document can travel in mongo collection
$this->logger()->warning(
"MongoDB query executed with limit/offset but without specified sorting."
);
}
//This is not the same profiling as one defined in getProfilingLevel().
if (!$this->mongoDatabase()->isProfiling()) {
return $cursorReader;
}
$queryInfo = ['query' => $this->query, 'sort' => $this->sort];
if (!empty($this->limit)) {
$queryInfo['limit'] = !empty($limit) ? (int)$limit : (int)$this->limit;
}
if (!empty($this->offset)) {
$queryInfo['offset'] = (int)$this->offset;
}
if ($this->mongoDatabase()->getProfiling() == MongoDatabase::PROFILE_EXPLAIN) {
$queryInfo['explained'] = $cursorReader->explain();
}
$this->logger()->debug(
"{database}/{collection}: " . json_encode($queryInfo, JSON_PRETTY_PRINT),
[
'collection' => $this->name,
'database' => $this->database,
'queryInfo' => $queryInfo
]
);
return $cursorReader;
}
/**
* Associated document class.
*
* @return string
*/
protected function primaryDocument()
{
return $this->odm->primaryDocument($this->database, $this->name);
}
/**
* MongoDatabase instance.
*
* @return MongoDatabase
*/
protected function mongoDatabase()
{
return $this->odm->database($this->database);
}
/**
* Get associated mongo collection.
*
* @return \MongoCollection
*/
protected function mongoCollection()
{
if (!empty($this->collection)) {
return $this->collection;
}
return $this->collection = $this->mongoDatabase()->selectCollection($this->name);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Exceptions;
use Spiral\Core\Exceptions\LogicException;
/**
* Generic database exception.
*/
class DatabaseException extends LogicException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
* @copyright �2009-2015
*/
namespace Spiral\ODM\Entities;
use Interop\Container\ContainerInterface;
use Spiral\Core\Component;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Models\EntityInterface;
use Spiral\ODM\CompositableInterface;
use Spiral\ODM\Document;
use Spiral\ODM\DocumentEntity;
use Spiral\ODM\Exceptions\CompositorException;
use Spiral\ODM\Exceptions\DefinitionException;
use Spiral\ODM\Exceptions\ODMException;
use Spiral\ODM\ODM;
/**
* Compositor is responsible for managing set (array) of classes nested to parent DocumentEntity.
* Compositor can manage Documents and all it's children.
*/
class Compositor extends Component implements
CompositableInterface,
\IteratorAggregate,
\Countable,
\ArrayAccess
{
/**
* Optional arguments.
*/
use SaturateTrait;
/**
* Class being composited.
*
* @var string
*/
private $class = '';
/**
* When solid state is enabled no atomic operations will be pushed to databases and document
* composition will be saved as one big set. Enabled by default.
*
* @var bool
*/
private $solidState = true;
/**
* Indication that composition data were changed without using atomic operations, this flag
* will be set to true if any document added or removed via array operations. Atomic operation
* will be forbidden what this flag is set.
*
* @var bool
*/
private $changedDirectly = false;
/**
* Set of documents to be managed by Compositor.
*
* @var array|DocumentEntity[]
*/
protected $documents = [];
/**
* Set of atomic operation applied to whole composition set.
*
* @var array
*/
protected $atomics = [];
/**
* Error messages collected over nested documents.
*
* @var array
*/
protected $errors = [];
/**
* @invisible
* @var EntityInterface
*/
protected $parent = null;
/**
* @var ODM
*/
protected $odm = null;
/**
* {@inheritdoc}
*
* @param string $class Primary class being composited.
*/
public function __construct(
$value,
EntityInterface $parent = null,
ODM $odm = null,
$class = null
) {
$this->parent = $parent;
$this->class = $class;
if (!empty($value) && is_array($value)) {
$this->documents = $value;
}
if (empty($this->class)) {
throw new CompositorException("Compositor requires to know it's primary class name.");
}
//Allowed only when global container is set
$this->odm = $this->saturate($odm, ODM::class);
if (empty($this->odm)) {
throw new CompositorException("ODM instance if required for Compositor to work properly.");
}
}
/**
* {@inheritdoc}
*/
public function defaultValue()
{
return [];
}
/**
* Get primary compositor class.
*
* @return string
*/
public function getClass()
{
return $this->class;
}
/**
* Get composition parent.
*
* @return Document|null
*/
public function getParent()
{
return $this->parent;
}
/**
* When solid state is enabled no atomic operations will be pushed to databases and document
* composition will be saved as one big set.
*
* @param bool $solidState
* @return $this
*/
public function solidState($solidState)
{
$this->solidState = $solidState;
return $this;
}
/**
* Is compositor is solid state?
*
* @see solidState()
* @return bool
*/
public function isSolid()
{
return $this->solidState;
}
/**
* {@inheritdoc}
*
* Invalidates every composited document.
*
* @return $this
*/
public function invalidate()
{
foreach ($this->getIterator() as $document) {
$document->invalidate();
}
return $this;
}
/**
* {@inheritdoc}
*/
public function embed(EntityInterface $parent)
{
if ($parent === $this->parent) {
return $this;
}
if (empty($this->parent)) {
$this->parent = $parent;
//We are mounting new parent
return $this->solidState(true);
}
return new static(
$this->serializeData(),
$parent,
$this->class,
$this->odm
);
}
/**
* {@inheritdoc}
*
* @return $this
*/
public function setValue($data)
{
$this->changedDirectly = $this->solidState = true;
if (!is_array($data)) {
//Ignoring
return;
}
$this->documents = [];
//Filling documents
foreach ($data as $item) {
if (is_array($item)) {
$this->create($item);
}
if ($item instanceof CompositableInterface) {
$this->documents[] = $item;
}
}
}
/**
* {@inheritdoc}
*/
public function serializeData()
{
$result = [];
foreach ($this->documents as $document) {
$result[] = $document instanceof CompositableInterface
? $document->serializeData()
: $document;
}
return $result;
}
/**
* {@inheritdoc}
*/
public function publicFields()
{
$result = [];
foreach ($this->getIterator() as $document) {
$result[] = $document->publicFields();
}
return $result;
}
/**
* {@inheritdoc}
*/
public function hasUpdates()
{
if ($this->changedDirectly || !empty($this->atomics)) {
return true;
}
foreach ($this->documents as $document) {
if ($document instanceof CompositableInterface && $document->hasUpdates()) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function flushUpdates()
{
$this->atomics = [];
$this->changedDirectly = false;
foreach ($this->documents as $document) {
if ($document instanceof CompositableInterface) {
$document->flushUpdates();
}
}
}
/**
* {@inheritdoc}
*/
public function buildAtomics($container = '')
{
if (!$this->hasUpdates()) {
return [];
}
if ($this->solidState) {
return [DocumentEntity::ATOMIC_SET => [$container => $this->serializeData()]];
}
if ($this->changedDirectly) {
throw new CompositorException(
"Compositor data were changed with low level array manipulations, "
. "unable to generate atomic set (solid state off)."
);
}
$atomics = [];
//Documents handled by Compositor atomic operations
$handledDocuments = [];
foreach ($this->atomics as $operation => $items) {
if ($operation != '$pull') {
$handledDocuments = array_merge($handledDocuments, $items);
}
//Into array form
$atomics[$operation][$container]['$each'] = $this->serializeDocuments($items);
}
//Document specific atomic operations, make sure it's not colliding with Compositor level
//atomic operations
foreach ($this->documents as $offset => $document) {
if ($document instanceof CompositableInterface) {
if (in_array($document, $handledDocuments)) {
//Handler on higher level
continue;
}
$atomics = array_merge(
$atomics,
$document->buildAtomics(($container ? $container . '.' : '') . $offset)
);
}
}
return $atomics;
}
/**
* {@inheritdoc}
*/
public function count()
{
return count($this->documents);
}
/**
* {@inheritdoc}
*/
public function offsetExists($offset)
{
return isset($this->documents[$offset]);
}
/**
* {@inheritdoc}
* @throws CompositorException
*/
public function offsetGet($offset)
{
if (!isset($this->documents[$offset])) {
throw new CompositorException("Undefined offset '{$offset}'.");
}
return $this->getDocument($offset);
}
/**
* {@inheritdoc}
* @throws CompositorException
*/
public function offsetSet($offset, $value)
{
if (!$value instanceof CompositableInterface) {
throw new CompositorException("Compositor can contain only instances of Document.");
}
if (!$this->solidState) {
throw new CompositorException(
"Direct offset operation can not be applied for compositor in non solid state."
);
}
$this->changedDirectly = true;
if (is_null($offset)) {
$this->documents[] = $value;
} else {
$this->documents[$offset] = $value;
}
}
/**
* {@inheritdoc}
* @throws CompositorException
*/
public function offsetUnset($offset)
{
if (!$this->solidState) {
throw new CompositorException(
"Direct offset operation can not be applied for compositor in non solid state."
);
}
$this->changedDirectly = true;
unset($this->documents[$offset]);
}
/**
* {@inheritdoc}
*/
public function hasField($name)
{
return $this->offsetExists($name);
}
/**
* {@inheritdoc}
*/
public function setField($name, $value)
{
$this->offsetSet($name, $value);
}
/**
* {@inheritdoc}
*
* @throws CompositorException
*/
public function getField($name, $default = null)
{
if (!$this->hasField($name)) {
return $default;
}
return $this->offsetGet($name);
}
/**
* {@inheritdoc}
*/
public function setFields($fields = [])
{
$this->setValue($fields);
}
/**
* {@inheritdoc}
*/
public function getFields()
{
return $this->all();
}
/**
* Return all composited documents in array form.
*
* @return Document[]
*/
public function all()
{
$result = [];
foreach ($this->getIterator() as $document) {
$result[] = $document;
}
return $result;
}
/**
* {@inheritdoc}
*
* @return Document[]
*/
public function getIterator()
{
foreach ($this->documents as $offset => $document) {
$this->getDocument($offset);
}
return new \ArrayIterator($this->documents);
}
/**
* Create Document and add it to composition. Compositor will use it's primary class to
* construct document. You can* force custom class name to be added using second argument.
*
* @param array $fields
* @param string $class
* @return Document
* @throws CompositorException
* @throws DefinitionException
* @throws ODMException
*/
public function create(array $fields = [], $class = null)
{
if (!$this->solidState) {
throw new CompositorException(
"Direct offset operation can not be applied for compositor in non solid state."
);
}
//Locating class to be used
$class = !empty($class) ? $class : $this->class;
$this->changedDirectly = true;
$document = call_user_func([$class, 'create'], $fields, $this->odm)->embed($this);
$this->documents[] = $document;
return $document;
}
/**
* Clear all nested documents.
*
* @return $this
*/
public function clear()
{
$this->solidState = $this->changedDirectly = true;
$this->documents = [];
return $this;
}
/**
* Find documents based on provided field values or document instance. Only simple query support
* (one level array).
*
* Example:
* $user->cards->find(['active' => true]);
*
* @param array|DocumentEntity $query
* @return array|DocumentEntity[]
*/
public function find($query = [])
{
if ($query instanceof DocumentEntity) {
$query = $query->serializeData();
}
$result = [];
foreach ($this->documents as $offset => $document) {
//We have to pass document thought model construction to ensure default values
$document = $this->getDocument($offset);
$data = $document->serializeData();
if (empty($query) || (array_intersect_assoc($data, $query) == $query)) {
$result[] = $document;
}
}
return $result;
}
/**
* Find first composited (nested document) by matched query. Only simple query support (one
* level array).
*
* Example:
* $user->cards->findOne(['active' => true]);
*
* @param array|DocumentEntity $query
* @return null|DocumentEntity
*/
public function findOne($query = [])
{
if (empty($documents = $this->find($query))) {
return null;
}
return $documents[0];
}
/**
* Push new document to end of set. Set second argument to false to keep Compositor in solid
* state and save it as one big array of data.
*
* @param DocumentEntity $document
* @param bool $resetState Set to true to reset compositor solid state.
* @return $this|DocumentEntity[]
* @throws CompositorException
*/
public function push(DocumentEntity $document, $resetState = true)
{
if ($resetState) {
$this->solidState = false;
}
$this->documents[] = $document->embed($this);
if ($this->solidState) {
$this->changedDirectly = true;
return $this;
}
if (!empty($this->atomics) && !isset($this->atomics['$push'])) {
throw new CompositorException(
"Unable to apply multiple atomic operation to one Compositor."
);
}
$this->atomics['$push'][] = $document;
return $this;
}
/**
* Pulls document(s) from the set, query should represent document object matched fields. Set
* second argument to false to keep Compositor in solid state and save it as one big array of
* data.
*
* @param array|DocumentEntity $query
* @param bool $resetState Set to true to reset compositor solid state.
* @return $this|DocumentEntity[]
* @throws CompositorException
*/
public function pull($query, $resetState = true)
{
if ($resetState) {
$this->solidState = false;
}
if ($query instanceof DocumentEntity) {
$query = $query->serializeData();
}
foreach ($this->documents as $offset => $document) {
//We have to pass document thought model construction to ensure default values
$document = $this->getDocument($offset)->serializeData();
if (array_intersect_assoc($document, $query) == $query) {
unset($this->documents[$offset]);
}
}
if ($this->solidState) {
$this->changedDirectly = true;
return $this;
}
if (!empty($this->atomics) && !isset($this->atomics['$pull'])) {
throw new CompositorException(
"Unable to apply multiple atomic operation to composition."
);
}
$this->atomics['$pull'][] = $query;
return $this;
}
/**
* Add document to set, only one instance of document must be presented. Set second argument to
* false to keep Compositor in solid state and save it as one big array of data.
*
* @param DocumentEntity $document
* @param bool $resetState Set to true to reset compositor solid state.
* @return $this|DocumentEntity[]
* @throws CompositorException
*/
public function addToSet(DocumentEntity $document, $resetState = true)
{
if ($resetState) {
$this->solidState = false;
}
if (empty($this->findOne($document))) {
$this->documents[] = $document->embed($this);
}
if ($this->solidState) {
$this->changedDirectly = true;
return $this;
}
if (!empty($this->atomics) && !isset($this->atomics['$addToSet'])) {
throw new CompositorException(
"Unable to apply multiple atomic operation to composition."
);
}
$this->atomics['$addToSet'][] = $document;
return $this;
}
/**
* {@inheritdoc}
*/
public function isValid()
{
$this->validate();
return empty($this->errors);
}
/**
* {@inheritdoc}
*/
public function hasErrors()
{
return !$this->isValid();
}
/**
* {@inheritdoc}
*/
public function getErrors($reset = false)
{
$errors = $this->errors;
if ($reset) {
$this->errors = [];
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return $this->publicFields();
}
/**
* @return array
*/
public function __debugInfo()
{
$this->validate();
return [
'data' => $this->serializeData(),
'atomics' => $this->buildAtomics('@compositor'),
'errors' => $this->getErrors()
];
}
/**
* @return null|ContainerInterface
*/
protected function container()
{
if (!empty($this->parent) && $this->parent instanceof Component) {
return $this->parent->container();
}
return parent::container();
}
/**
* Validate every composited document.
*
* @return bool
*/
protected function validate()
{
$this->errors = [];
foreach ($this->documents as $offset => $document) {
//To ensure that instance is Document since components
//is lazy loading them
$document = $this->getDocument($offset);
if (!$document->isValid()) {
$this->errors[$offset] = $document->getErrors();
}
}
return empty($this->errors);
}
/**
* Fetch or create instance of document based on specified offset.
*
* @param int $offset
* @return DocumentEntity
*/
private function getDocument($offset)
{
/**
* @var array|Document $document
*/
$document = $this->documents[$offset];
if ($document instanceof CompositableInterface) {
return $document;
}
//Trying to create using ODM
return $this->documents[$offset] = $this->odm->document($this->class, $document, $this);
}
/**
* Serialize array of documents into simple array.
*
* @param array $documents
* @return array
*/
private function serializeDocuments(array $documents)
{
$result = [];
foreach ($documents as $document) {
if ($document instanceof CompositableInterface) {
$document = $document->serializeData();
}
$result[] = $document;
}
return $result;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Pagination\Traits;
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Spiral\Core\Exceptions\SugarException;
use Spiral\Core\FactoryInterface;
use Spiral\Pagination\Exceptions\PaginationException;
use Spiral\Pagination\Paginator;
use Spiral\Pagination\PaginatorInterface;
/**
* Provides ability to paginate associated instance. Will work with default Paginator or fetch one
* from container.
*
* Compatible with PaginatorAwareInterface.
*/
trait PaginatorTrait
{
/**
* @var PaginatorInterface
*/
private $paginator = null;
/**
* @var int
*/
protected $limit = 0;
/**
* @var int
*/
protected $offset = 0;
/**
* Count elements of an object.
*
* @link http://php.net/manual/en/countable.count.php
* @return int
*/
abstract public function count();
/**
* Set selection limit.
*
* @param int $limit
* @return mixed
*/
public function limit($limit = 0)
{
$this->limit = $limit;
return $this;
}
/**
* @return int
*/
public function getLimit()
{
return $this->limit;
}
/**
* Set selection offset.
*
* @param int $offset
* @return mixed
*/
public function offset($offset = 0)
{
$this->offset = $offset;
return $this;
}
/**
* @return int
*/
public function getOffset()
{
return $this->offset;
}
/**
* Manually set paginator instance for specific object.
*
* @param PaginatorInterface $paginator
* @return $this
*/
public function setPaginator(PaginatorInterface $paginator)
{
$this->paginator = $paginator;
return $this;
}
/**
* Get paginator for the current selection. Paginate method should be already called.
*
* @see isPaginated()
* @see paginate()
* @return PaginatorInterface|Paginator|null
*/
public function paginator()
{
return $this->paginator;
}
/**
* Indication that object was paginated.
*
* @return bool
*/
public function isPaginated()
{
return !empty($this->paginator);
}
/**
* Paginate current selection using Paginator class.
*
* @param int $limit Pagination limit.
* @param string $pageParameter Name of parameter in request query which is
* used to store the current page number. "page"
* by default.
* @param ServerRequestInterface $request Has to be specified if no global container set.
* @return $this
* @throws PaginationException
*/
public function paginate(
$limit = Paginator::DEFAULT_LIMIT,
$pageParameter = Paginator::DEFAULT_PARAMETER,
ServerRequestInterface $request = null
) {
//Will be used in two places
$container = $this->container();
if (empty($request)) {
if (empty($container) || !$container->has(ServerRequestInterface::class)) {
throw new SugarException(
"Unable to create pagination without specified request."
);
}
//Getting request from container scope
$request = $container->get(ServerRequestInterface::class);
}
if (empty($container) || !$container->has(PaginatorInterface::class)) {
//Let's use default paginator
$this->paginator = new Paginator($request, $pageParameter);
} else {
//We need constructor
if ($container instanceof FactoryInterface) {
$constructor = $container;
} else {
$constructor = $container->get(FactoryInterface::class);
}
//We can also create paginator using container
$this->paginator = $constructor->make(PaginatorInterface::class, compact(
'request', 'pageParameter'
));
}
$this->paginator->setLimit($limit);
return $this;
}
/**
* Apply pagination to current object. Will be applied only if internal paginator already
* constructed.
*
* @return $this
* @throws PaginationException
*/
protected function applyPagination()
{
if (empty($this->paginator)) {
return $this;
}
return $this->paginator->paginate($this);
}
/**
* @return ContainerInterface
*/
abstract protected function container();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation;
use Spiral\Validation\Exceptions\ValidationException;
/**
* Validators responsible for data validations. Validation rules are implementation dependent but
* should always be specified in array form relative to validator implementation.
*/
interface ValidatorInterface
{
/**
* @param array $rules Validation rules.
* @param array|\ArrayAccess $data Data to be validated.
*/
public function __construct(array $rules = [], $data = []);
/**
* Update validation rules.
*
* @param array $rules
* @return self
*/
public function setRules(array $rules);
/**
* Update validation data (context).
*
* @param array|\ArrayAccess $data
* @return self
* @throws ValidationException
*/
public function setData($data);
/**
* Register outer validation error.
*
* @param string $field
* @param string $error
* @return self
*/
public function registerError($field, $error);
/**
* Flush all registered errors.
*
* @return self
*/
public function flushRegistered();
/**
* Check if context data valid accordingly to provided rules.
*
* @return bool
* @throws ValidationException
*/
public function isValid();
/**
* Evil tween of isValid() method should return true if context data is not valid.
*
* @return bool
* @throws ValidationException
*/
public function hasErrors();
/**
* List of errors associated with parent field, every field should have only one error assigned.
*
* @return array
*/
public function getErrors();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Injections;
use Spiral\Database\Entities\QueryCompiler;
/**
* SQLExpression provides ability to mock part of SQL code responsible for operations involving
* table and column names. This class will quote and prefix every found table name and column while
* query compilation.
*
* Example: new SQLExpression("table.column = table.column + 1");
*
* I potentially should have an interface for such class.
*/
class Expression extends Fragment implements ExpressionInterface
{
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
//We might need to throw an exception here in some cases
return parent::sqlStatement();
}
return $compiler->quote(parent::sqlStatement($compiler));
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres;
use Spiral\Database\Entities\QueryCompiler as AbstractCompiler;
/**
* Postgres syntax specific compiler.
*/
class QueryCompiler extends AbstractCompiler
{
/**
* {@inheritdoc}
*/
public function compileInsert($table, array $columns, array $rowsets, $primaryKey = '')
{
return parent::compileInsert($table, $columns, $rowsets) . (!empty($primaryKey)
? ' RETURNING ' . $this->quote($primaryKey)
: ''
);
}
/**
* {@inheritdoc}
*/
protected function compileDistinct($distinct)
{
if (empty($distinct)) {
return '';
}
return "DISTINCT" . (is_string($distinct) ? '(' . $this->quote($distinct) . ')' : '');
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation\Checkers;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Validation\Checker;
use Spiral\Validation\Validator;
/**
* Validations based dependencies between fields.
*/
class RequiredChecker extends Checker implements SingletonInterface
{
/**
* Declaring to IoC to construct class only once.
*/
const SINGLETON = self::class;
/**
* {@inheritdoc}
*/
protected $messages = [
"with" => "[[This field is required.]]",
"withAll" => "[[This field is required.]]",
"without" => "[[This field is required.]]",
"withoutAll" => "[[This field is required.]]",
];
/**
* Check if field not empty but only if any of listed fields presented or not empty.
*
* @param mixed $value
* @param array $with
* @return bool
*/
public function with($value, array $with)
{
if (!empty($value)) {
return true;
}
foreach ($with as $field) {
if ($this->validator()->field($field)) {
//Some value presented
return false;
}
}
return Validator::STOP_VALIDATION;
}
/**
* Check if field not empty but only if all of listed fields presented and not empty.
*
* @param mixed $value
* @param array $with
* @return bool
*/
public function withAll($value, array $with)
{
if (!empty($value)) {
return true;
}
foreach ($with as $field) {
if (!$this->validator()->field($field)) {
return Validator::STOP_VALIDATION;
}
}
return false;
}
/**
* Check if field not empty but only if one of listed fields missing or empty.
*
* @param mixed $value
* @param array $without
* @return bool
*/
public function without($value, array $without)
{
if (!empty($value)) {
return true;
}
foreach ($without as $field) {
if (empty($this->validator()->field($field))) {
//Some value presented
return false;
}
}
return Validator::STOP_VALIDATION;
}
/**
* Check if field not empty but only if all of listed fields missing or empty.
*
* @param mixed $value
* @param array $without
* @return bool
*/
public function withoutAll($value, array $without)
{
if (!empty($value)) {
return true;
}
foreach ($without as $field) {
if ($this->validator()->field($field)) {
return Validator::STOP_VALIDATION;
}
}
return false;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Loaders;
use Spiral\ORM\Entities\RecordSelector;
use Spiral\ORM\Entities\WhereDecorator;
use Spiral\ORM\RecordEntity;
/**
* Dedicated to load HAS_MANY relation data, POSTLOAD is preferred loading method. Additional where
* conditions and morph keys are supported.
*/
class HasManyLoader extends HasOneLoader
{
/**
* Relation type is required to correctly resolve foreign record class based on relation
* definition.
*/
const RELATION_TYPE = RecordEntity::HAS_MANY;
/**
* Default load method (inload or postload).
*/
const LOAD_METHOD = self::POSTLOAD;
/**
* Internal loader constant used to decide how to aggregate data tree, true for relations like
* MANY TO MANY or HAS MANY.
*/
const MULTIPLE = true;
/**
* {@inheritdoc}
*
* Where conditions will be mounted using WhereDecorator to unify logic between POSTLOAD and
* INLOAD methods.
*/
protected function mountConditions(RecordSelector $selector)
{
$selector = parent::mountConditions($selector);
//Let's use where decorator to set conditions, it will automatically route tokens to valid
//destination (JOIN or WHERE)
$decorator = new WhereDecorator(
$selector, $this->isJoinable() ? 'onWhere' : 'where', $this->getAlias()
);
if (!empty($this->definition[RecordEntity::WHERE])) {
//Relation WHERE conditions
$decorator->where($this->definition[RecordEntity::WHERE]);
}
//User specified WHERE conditions
if (!empty($this->options['where'])) {
$decorator->where($this->options['where']);
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Stores;
use Spiral\Cache\CacheStore;
/**
* Talks to xcache functions.
*/
class XCacheStore extends CacheStore
{
/**
* @var string
*/
private $prefix = 'spiral:';
/**
* @param string $prefix
*/
public function __construct($prefix = 'spiral:')
{
$this->prefix = $prefix;
}
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return extension_loaded('xcache');
}
/**
* {@inheritdoc}
*/
public function has($name)
{
return xcache_isset($this->prefix . $name);
}
/**
* {@inheritdoc}
*/
public function get($name)
{
return xcache_get($this->prefix . $name);
}
/**
* {@inheritdoc}
*/
public function set($name, $data, $lifetime)
{
return xcache_set($this->prefix . $name, $data, $lifetime);
}
/**
* {@inheritdoc}
*/
public function forever($name, $data)
{
return xcache_set($this->prefix . $name, $data, 0);
}
/**
* {@inheritdoc}
*/
public function delete($name)
{
xcache_unset($this->prefix . $name);
}
/**
* {@inheritdoc}
*/
public function inc($name, $delta = 1)
{
return xcache_inc($this->prefix . $name, $delta);
}
/**
* {@inheritdoc}
*/
public function dec($name, $delta = 1)
{
return xcache_dec($this->prefix . $name, $delta);
}
/**
* {@inheritdoc}
*
* @throws \ErrorException
*/
public function flush()
{
xcache_clear_cache(XC_TYPE_VAR);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database;
use Spiral\Database\Exceptions\QueryException;
/**
* TableInterface is table level abstraction linked to existed or not existed database table. You
* can check if table really exist or not exist using "exists" method of table schema.
*/
interface TableInterface extends \Countable
{
/**
* Must return schema instance even if table does not exists.
*
* @return \Spiral\Database\Schemas\TableInterface
*/
public function schema();
/**
* Table name in a context of parent database (no prefix included).
*
* @return string
*/
public function getName();
/**
* Truncate (clean) current table.
*/
public function truncate();
/**
* Must perform single rowset insertion into table. Method must return lastInsertID on success.
*
* Example:
* $table->insert(["name" => "Bob"])
*
* @param array $rowset Associated array (key => value).
* @return mixed
* @throws QueryException
*/
public function insert(array $rowset = []);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Exceptions;
/**
* Error caused by strict mode enabled by node supervisor.
*
* @see SupervisorInterface
* @see Node
*/
class StrictModeException extends StemplerException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Files;
use Spiral\Core\Component;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Files\Exceptions\FileNotFoundException;
use Spiral\Files\Exceptions\FilesException;
use Spiral\Files\Exceptions\WriteErrorException;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator;
/**
* Default files storage, points to local hard drive.
*/
class FileManager extends Component implements SingletonInterface, FilesInterface
{
/**
* Declares to IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* Files to be removed when component destructed.
*
* @var array
*/
private $destruct = [];
/**
* New File Manager.
*
* @todo Potentially can be depended on Symfony Filesystem.
*/
public function __construct()
{
//Safety mechanism
register_shutdown_function([$this, '__destruct']);
}
/**
* {@inheritdoc}
*
* @param bool $recursive Every created directory will get specified permissions.
*/
public function ensureDirectory($directory, $mode = self::RUNTIME, $recursive = true)
{
$mode = $mode | 0111;
if (is_dir($directory)) {
//Exists :(
return $this->setPermissions($directory, $mode);
}
if (!$recursive) {
return mkdir($directory, $mode, true);
}
$directoryChain = [basename($directory)];
$baseDirectory = $directory;
while (!is_dir($baseDirectory = dirname($baseDirectory))) {
$directoryChain[] = basename($baseDirectory);
}
foreach (array_reverse($directoryChain) as $directory) {
if (!mkdir($baseDirectory = $baseDirectory . '/' . $directory)) {
return false;
}
chmod($baseDirectory, $mode);
}
return true;
}
/**
* {@inheritdoc}
*/
public function read($filename)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return file_get_contents($filename);
}
/**
* {@inheritdoc}
*
* @param bool $append To append data at the end of existed file.
*/
public function write($filename, $data, $mode = null, $ensureDirectory = false, $append = false)
{
try {
if ($ensureDirectory) {
$this->ensureDirectory(dirname($filename), $mode);
}
if (!empty($mode) && $this->exists($filename)) {
//Forcing mode for existed file
$this->setPermissions($filename, $mode);
}
$result = (file_put_contents(
$filename, $data, $append ? FILE_APPEND | LOCK_EX : LOCK_EX
) !== false);
if ($result && !empty($mode)) {
//Forcing mode after file creation
$this->setPermissions($filename, $mode);
}
} catch (\ErrorException $exception) {
throw new WriteErrorException(
$exception->getMessage(),
$exception->getCode(),
$exception
);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function append($filename, $data, $mode = null, $ensureDirectory = false)
{
return $this->write($filename, $data, $mode, $ensureDirectory, true);
}
/**
* {@inheritdoc}
*/
public function localUri($filename)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
//Since default implementation is local we are allowed to do that
return $filename;
}
/**
* {@inheritdoc}
*/
public function delete($filename)
{
if ($this->exists($filename)) {
return unlink($filename);
}
return false;
}
/**
* {@inheritdoc}
*
* @see http://stackoverflow.com/questions/3349753/delete-directory-with-files-in-it
* @param string $directory
* @param bool $contentOnly
* @throws FilesException
*/
public function deleteDirectory($directory, $contentOnly = false)
{
if (!$this->isDirectory($directory)) {
throw new FilesException("Undefined or invalid directory {$directory}");
}
$files = new \RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
$this->delete($file->getRealPath());
}
}
if (!$contentOnly) {
rmdir($directory);
}
}
/**
* {@inheritdoc}
*/
public function move($filename, $destination)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return rename($filename, $destination);
}
/**
* {@inheritdoc}
*/
public function copy($filename, $destination)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return copy($filename, $destination);
}
/**
* {@inheritdoc}
*/
public function touch($filename, $mode = null, $ensureLocation = false)
{
return touch($filename);
}
/**
* {@inheritdoc}
*/
public function exists($filename)
{
return file_exists($filename);
}
/**
* {@inheritdoc}
*/
public function size($filename)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return filesize($filename);
}
/**
* {@inheritdoc}
*/
public function extension($filename)
{
return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}
/**
* {@inheritdoc}
*/
public function md5($filename)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return md5_file($filename);
}
/**
* {@inheritdoc}
*/
public function time($filename)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return filemtime($filename);
}
/**
* {@inheritdoc}
*/
public function isDirectory($filename)
{
return is_dir($filename);
}
/**
* {@inheritdoc}
*/
public function isFile($filename)
{
return is_file($filename);
}
/**
* {@inheritdoc}
*/
public function getPermissions($filename)
{
if (!$this->exists($filename)) {
throw new FileNotFoundException($filename);
}
return fileperms($filename) & 0777;
}
/**
* {@inheritdoc}
*/
public function setPermissions($filename, $mode)
{
if (is_dir($filename)) {
$mode |= 0111;
}
return $this->getPermissions($filename) == $mode || chmod($filename, $mode);
}
/**
* {@inheritdoc}
*
* @param Finder $finder Optional initial finder.
*/
public function getFiles($location, $pattern = null, Finder $finder = null)
{
if (empty($finder)) {
$finder = new Finder();
}
$finder->files()->in($location);
if (!empty($pattern)) {
$finder->name($pattern);
}
$result = [];
foreach ($finder->getIterator() as $file) {
$result[] = $this->normalizePath((string)$file);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function tempFilename($extension = '', $location = null)
{
if (!empty($location)) {
$location = sys_get_temp_dir();
}
$filename = tempnam($location, 'spiral');
if ($extension) {
//I should find more original way of doing that
rename($filename, $filename = $filename . '.' . $extension);
$this->destruct[] = $filename;
}
return $filename;
}
/**
* {@inheritdoc}
*/
public function normalizePath($path, $directory = false)
{
$path = str_replace('\\', '/', $path);
//Potentially open links and ../ type directories?
return rtrim(preg_replace('/\/+/', '/', $path), '/') . ($directory ? '/' : '');
}
/**
* {@inheritdoc}
*
* @link http://stackoverflow.com/questions/2637945/getting-relative-path-from-absolute-path-in-php
*/
public function relativePath($path, $from)
{
$path = $this->normalizePath($path);
$from = $this->normalizePath($from);
$from = explode('/', $from);
$path = explode('/', $path);
$relative = $path;
foreach ($from as $depth => $dir) {
//Find first non-matching dir
if ($dir === $path[$depth]) {
//Ignore this directory
array_shift($relative);
} else {
//Get number of remaining dirs to $from
$remaining = count($from) - $depth;
if ($remaining > 1) {
//Add traversals up to first matching directory
$padLength = (count($relative) + $remaining - 1) * -1;
$relative = array_pad($relative, $padLength, '..');
break;
} else {
$relative[0] = './' . $relative[0];
}
}
}
return implode('/', $relative);
}
/**
* Destruct every temporary file.
*/
public function __destruct()
{
foreach ($this->destruct as $filename) {
$this->delete($filename);
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Debug;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Spiral\Core\Component;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Debug\Dumper\Style;
use Spiral\Debug\Traits\BenchmarkTrait;
use Spiral\Debug\Traits\LoggerTrait;
/**
* One of the oldest spiral parts, used to dump variables content in user friendly way.
*/
class Dumper extends Component implements SingletonInterface, LoggerAwareInterface
{
use LoggerTrait, BenchmarkTrait;
/**
* Declaring to IoC that class is singleton.
*/
const SINGLETON = self::class;
/**
* Options for dump() function to specify output.
*/
const OUTPUT_ECHO = 0;
const OUTPUT_RETURN = 1;
const OUTPUT_LOG = 2;
const OUTPUT_LOG_NICE = 3;
/**
* Deepest level to be dumped.
*
* @var int
*/
private $maxLevel = 10;
/**
* @invisible
* @var Style
*/
private $style = null;
/**
* @param int $maxLevel
* @param Style $styler Light styler to be used by default.
* @param LoggerInterface $logger
*/
public function __construct(
$maxLevel = 10,
Style $styler = null,
LoggerInterface $logger = null
) {
$this->maxLevel = $maxLevel;
$this->style = !empty($styler) ? $styler : new Style();
$this->logger = $logger;
}
/**
* Set dump styler.
*
* @param Style $style
* @return $this
*/
public function setStyle(Style $style)
{
$this->style = $style;
return $this;
}
/**
* Dump specified value.
*
* @param mixed $value
* @param int $output
* @return null|string
*/
public function dump($value, $output = self::OUTPUT_ECHO)
{
if (php_sapi_name() === 'cli' && $output == self::OUTPUT_ECHO) {
print_r($value);
if (is_scalar($value)) {
echo "\n";
}
return null;
}
//Dumping is pretty slow operation, let's record it so we can exclude dump time from application
//timeline
$benchmark = $this->benchmark('dump');
try {
switch ($output) {
case self::OUTPUT_ECHO:
echo $this->style->mountContainer($this->dumpValue($value, '', 0));
break;
case self::OUTPUT_RETURN:
return $this->style->mountContainer($this->dumpValue($value, '', 0));
break;
case self::OUTPUT_LOG:
$this->logger()->debug(print_r($value, true));
break;
case self::OUTPUT_LOG_NICE:
$this->logger()->debug($this->dump($value, self::OUTPUT_RETURN));
break;
}
return null;
} finally {
$this->benchmark($benchmark);
}
}
/**
* Variable dumper. This is the oldest spiral function originally written in 2007. :)
*
* @param mixed $value
* @param string $name Variable name, internal.
* @param int $level Dumping level, internal.
* @param bool $hideHeader Hide array/object header, internal.
* @return string
*/
private function dumpValue($value, $name = '', $level = 0, $hideHeader = false)
{
//Any dump starts with initial indent (level based)
$indent = $this->style->indent($level);
if (!$hideHeader && !empty($name)) {
//Showing element name (if any provided)
$header = $indent . $this->style->style($name, "name");
//Showing equal sing
$header .= $this->style->style(" = ", "syntax", "=");
} else {
$header = $indent;
}
if ($level > $this->maxLevel) {
//Dumper is not reference based, we can't dump too deep values
return $indent . $this->style->style('-too deep-', 'maxLevel') . "\n";
}
$type = strtolower(gettype($value));
if ($type == 'array') {
return $header . $this->dumpArray($value, $level, $hideHeader);
}
if ($type == 'object') {
return $header . $this->dumpObject($value, $level, $hideHeader);
}
if ($type == 'resource') {
//No need to dump resource value
$element = get_resource_type($value) . " resource ";
return $header . $this->style->style($element, "type", "resource") . "\n";
}
//Value length
$length = strlen($value);
//Including type size
$header .= $this->style->style("{$type}({$length})", "type", $type);
$element = null;
switch ($type) {
case "string":
$element = htmlspecialchars($value);
break;
case "boolean":
$element = ($value ? "true" : "false");
break;
default:
if ($value !== null) {
//Not showing null value, type is enough
$element = var_export($value, true);
}
}
//Including value
return $header . " " . $this->style->style($element, "value", $type) . "\n";
}
/**
* @param array $array
* @param int $level
* @param bool $hideHeader
* @return string
*/
private function dumpArray(array $array, $level, $hideHeader = false)
{
$indent = $this->style->indent($level);
if (!$hideHeader) {
$count = count($array);
//Array size and scope
$output = $this->style->style("array({$count})", "type", "array") . "\n";
$output .= $indent . $this->style->style("[", "syntax", "[") . "\n";
} else {
$output = '';
}
foreach ($array as $key => $value) {
if (!is_numeric($key)) {
if (is_string($key)) {
$key = htmlspecialchars($key);
}
$key = "'{$key}'";
}
$output .= $this->dumpValue($value, "[{$key}]", $level + 1);
}
if (!$hideHeader) {
//Closing array scope
$output .= $indent . $this->style->style("]", "syntax", "]") . "\n";
}
return $output;
}
/**
* @param object $object
* @param int $level
* @param bool $hideHeader
* @param string $class
* @return string
*/
private function dumpObject($object, $level, $hideHeader = false, $class = '')
{
$indent = $this->style->indent($level);
if (!$hideHeader) {
$type = ($class ?: get_class($object)) . " object ";
$header = $this->style->style($type, "type", "object") . "\n";
$header .= $indent . $this->style->style("(", "syntax", "(") . "\n";
} else {
$header = '';
}
//Let's use method specifically created for dumping
if (method_exists($object, '__debugInfo')) {
$debugInfo = $object->__debugInfo();
if (is_object($debugInfo)) {
//We are not including syntax elements here
return $this->dumpObject($debugInfo, $level, false, get_class($object));
}
return $header
. $this->dumpValue($debugInfo, '', $level + (is_scalar($object)), true)
. $indent . $this->style->style(")", "syntax", ")") . "\n";
}
$refection = new \ReflectionObject($object);
$output = '';
foreach ($refection->getProperties() as $property) {
$output .= $this->dumpProperty($object, $property, $level);
}
//Header, content, footer
return $header . $output . $indent . $this->style->style(")", "syntax", ")") . "\n";
}
/**
* @param object $object
* @param \ReflectionProperty $property
* @param int $level
* @return string
*/
private function dumpProperty($object, \ReflectionProperty $property, $level)
{
if ($property->isStatic()) {
return '';
}
if (
!($object instanceof \stdClass)
&& strpos($property->getDocComment(), '@invisible') !== false
) {
//Memory loop while reading doc comment for stdClass variables?
//Report a PHP bug about treating comment INSIDE property declaration as doc comment.
return '';
}
//Property access level
$access = $this->getAccess($property);
//To read private and protected properties
$property->setAccessible(true);
if ($object instanceof \stdClass) {
$access = 'dynamic';
}
//Property name includes access level
$name = $property->getName() . $this->style->style(":" . $access, "access", $access);
return $this->dumpValue($property->getValue($object), $name, $level + 1);
}
/**
* Property access level label.
*
* @param \ReflectionProperty $property
* @return string
*/
private function getAccess(\ReflectionProperty $property)
{
if ($property->isPrivate()) {
return 'private';
} elseif ($property->isProtected()) {
return 'protected';
}
return 'public';
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Validation;
/**
* Declares ability to be validated and raise error messages on failure.
*/
interface ValidatesInterface
{
/**
* Check if context data is valid.
*
* @return bool
*/
public function isValid();
/**
* Check if context data has errors.
*
* @return bool
*/
public function hasErrors();
/**
* List of errors associated with parent field, every field must have only one error assigned.
*
* @param bool $reset Force re-validation.
* @return array
*/
public function getErrors($reset = false);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Models;
use Spiral\Models\Exceptions\AccessorExceptionInterface;
use Spiral\Validation\ValueInterface;
/**
* Accessors used to mock access to model field, control value setting, serializing and etc.
*
* @todo think about constructor unification?
*/
interface AccessorInterface extends ValueInterface, \JsonSerializable
{
/**
* Accessors creation flow is unified and must be performed without Container for performance
* reasons.
*
* @param mixed $value
* @param EntityInterface $parent
* @throws AccessorExceptionInterface
*/
//public function __construct($value, EntityInterface $parent);
/**
* Must embed accessor to another parent model. Allowed to clone itself.
*
* @param EntityInterface $parent
* @return static
* @throws AccessorExceptionInterface
*/
public function embed(EntityInterface $parent);
/**
* Change mocked data.
*
* @param mixed $data
* @throws AccessorExceptionInterface
*/
public function setValue($data);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core;
/**
* Long memory cache. Something very fast on read and slow on write!
*/
interface HippocampusInterface
{
/**
* Read data from long memory cache. Must return exacts same value as saved or null.
*
* @param string $section Non case sensitive.
* @param string $location Specific memory location.
* @return string|array|null
*/
public function loadData($section, $location = null);
/**
* Put data to long memory cache. No inner references or closures are allowed.
*
* @param string $section Non case sensitive.
* @param string|array $data
* @param string $location Specific memory location.
*/
public function saveData($section, $data, $location = null);
/**
* Get all memory sections belongs to given memory location (default location to be used if
* none specified).
*
* @param string $location
* @return array
*/
public function getSections($location = null);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Storage;
use Spiral\Core\Component;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Core\FactoryInterface;
use Spiral\Storage\Configs\StorageConfig;
use Spiral\Storage\Entities\StorageBucket;
use Spiral\Storage\Entities\StorageObject;
use Spiral\Storage\Exceptions\StorageException;
/**
* Default implementation of StorageInterface.
*/
class StorageManager extends Component implements StorageInterface, InjectorInterface
{
/**
* Declares to IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* @var BucketInterface[]
*/
private $buckets = [];
/**
* @var ServerInterface[]
*/
private $servers = [];
/**
* @var StorageConfig
*/
protected $config = null;
/**
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param StorageConfig $config
* @param FactoryInterface $factory
*/
public function __construct(StorageConfig $config, FactoryInterface $factory)
{
$this->config = $config;
$this->factory = $factory;
//Loading buckets
foreach ($this->config->getBuckets() as $name => $bucket) {
//Using default implementation
$this->buckets[$name] = $this->createBucket($name, $bucket);
}
}
/**
* {@inheritdoc}
*/
public function registerBucket($name, $prefix, array $options = [], ServerInterface $server)
{
if (isset($this->buckets[$name])) {
throw new StorageException("Unable to create bucket '{$name}', name already taken.");
}
return $this->buckets[$name] = $this->factory->make(
StorageBucket::class,
['storage' => $this] + compact('prefix', 'options', 'server')
);
}
/**
* {@inheritdoc}
*/
public function bucket($bucket)
{
if (empty($bucket)) {
throw new StorageException("Unable to fetch bucket, name can not be empty.");
}
$bucket = $this->config->resolveAlias($bucket);
if (isset($this->buckets[$bucket])) {
return $this->buckets[$bucket];
}
throw new StorageException("Unable to fetch bucket '{$bucket}', no presets found.");
}
/**
* {@inheritdoc}
*/
public function createInjection(\ReflectionClass $class, $context = null)
{
if (empty($context)) {
throw new StorageException("Storage bucket can be requested without specified context.");
}
return $this->bucket($context);
}
/**
* {@inheritdoc}
*/
public function locateBucket($address, &$name = null)
{
/**
* @var BucketInterface $bestBucket
*/
$bestBucket = null;
foreach ($this->buckets as $bucket) {
if (!empty($prefixLength = $bucket->hasAddress($address))) {
if (empty($bestBucket) || strlen($bestBucket->getPrefix()) < $prefixLength) {
$bestBucket = $bucket;
$name = substr($address, $prefixLength);
}
}
}
return $bestBucket;
}
/**
* {@inheritdoc}
*/
public function server($server)
{
if (isset($this->servers[$server])) {
return $this->servers[$server];
}
if (!$this->config->hasServer($server)) {
throw new StorageException("Undefined storage server '{$server}'.");
}
return $this->servers[$server] = $this->factory->make(
$this->config->serverClass($server),
$this->config->serverOptions($server)
);
}
/**
* {@inheritdoc}
*/
public function put($bucket, $name, $source = '')
{
$bucket = is_string($bucket) ? $this->bucket($bucket) : $bucket;
return $bucket->put($name, $source);
}
/**
* {@inheritdoc}
*/
public function open($address)
{
return new StorageObject($address, $this);
}
/**
* Create bucket based configuration settings.
*
* @param string $name
* @param array $bucket
* @return BucketInterface
*/
private function createBucket($name, array $bucket)
{
$parameters = $bucket + compact('name');
if (!array_key_exists('options', $bucket)) {
throw new StorageException("Bucket configuration must include options.");
}
if (!array_key_exists('prefix', $bucket)) {
throw new StorageException("Bucket configuration must include prefix.");
}
if (!array_key_exists('server', $bucket)) {
throw new StorageException("Bucket configuration must include server id.");
}
$parameters['server'] = $this->server($bucket['server']);
$parameters['storage'] = $this;
return $this->factory->make(StorageBucket::class, $parameters);
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ODM\Entities;
use Spiral\Core\Component;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Models\SourceInterface;
use Spiral\ODM\DocumentEntity;
use Spiral\ODM\Exceptions\SourceException;
use Spiral\ODM\ODM;
/**
* Source class associated to one or multiple (default implementation) ODM models. Source can be
* used to write your own custom find method or change default selection.
*/
class DocumentSource extends Component implements SourceInterface, \Countable
{
/**
* Sugary!
*/
use SaturateTrait;
/**
* Linked document model. ODM can automatically index and link user sources to models based on
* value of this constant.
*/
const DOCUMENT = null;
/**
* Associated document class.
*
* @var string
*/
private $class = null;
/**
* @var DocumentSelector
*/
private $selector = null;
/**
* @invisible
* @var ODM
*/
protected $odm = null;
/**
* @param string $class
* @param ODM $odm
* @throws SourceException
*/
public function __construct($class = null, ODM $odm = null)
{
if (empty($class)) {
if (empty(static::DOCUMENT)) {
throw new SourceException("Unable to create source without associate class.");
}
$class = static::DOCUMENT;
}
$this->class = $class;
$this->odm = $this->saturate($odm, ODM::class);
$this->setSelector($this->odm->selector($this->class));
}
/**
* Create new DocumentEntity based on set of provided fields.
*
* @final Change static method of entity, not this one.
* @param array $fields
* @param string $class Due ODM models can be inherited you can use this argument to specify
* custom model class.
* @return DocumentEntity
*/
final public function create($fields = [], $class = null)
{
if (empty($class)) {
$class = $this->class;
}
//Letting entity to create itself (needed
return call_user_func([$class, 'create'], $fields, $this->odm);
}
/**
* Find document by it's primary key.
*
* @see findOne()
* @param string|\MongoId $id Primary key value.
* @return DocumentEntity|null
*/
public function findByPK($id)
{
return $this->find()->findByPK($id);
}
/**
* Select one document from mongo collection.
*
* @param array $query Fields and conditions to query by.
* @param array $sortBy
* @return DocumentEntity|null
*/
public function findOne(array $query = [], array $sortBy = [])
{
return $this->find()->sortBy($sortBy)->findOne($query);
}
/**
* Get associated document selection with pre-configured query (if any).
*
* @param array $query
* @return DocumentSelector
*/
public function find(array $query = [])
{
return $this->selector()->query($query);
}
/**
* {@inheritdoc}
*/
public function count()
{
return $this->find()->count();
}
/**
* @return DocumentSelector
*/
final protected function selector()
{
//Has to be cloned every time to prevent query collisions
return clone $this->selector;
}
/**
* @param DocumentSelector $selector
*/
protected function setSelector(DocumentSelector $selector)
{
$this->selector = $selector;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Exceptions;
/**
* Invalid argument or parameter provided for one of Database class.
*/
class InvalidArgumentException extends \Spiral\Core\Exceptions\InvalidArgumentException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations;
use Spiral\ORM\Entities\Schemas\RelationSchema;
use Spiral\ORM\RecordEntity;
/**
* Declares simple has one relation. Relations like that used when parent record has one child with
* [outer] key linked to value of [inner] key of parent mode.
*
* Example, [User has one Profile], user primary key is "id":
* - relation will create outer key "user_id" in "profiles" table (or other table name), nullable
* by default
* - relation will create index on column "user_id" in "profiles" table if allowed
* - relation will create foreign key "profiles"."user_id" => "users"."id" if allowed
*/
class HasOneSchema extends RelationSchema
{
/**
* {@inheritdoc}
*/
const RELATION_TYPE = RecordEntity::HAS_ONE;
/**
* {@inheritdoc}
*
* @invisible
*/
protected $defaultDefinition = [
//Let's use parent record primary key as default inner key
RecordEntity::INNER_KEY => '{record:primaryKey}',
//Outer key will be based on parent record role and inner key name
RecordEntity::OUTER_KEY => '{record:role}_{definition:innerKey}',
//Set constraints (foreign keys) by default
RecordEntity::CONSTRAINT => true,
//@link https://en.wikipedia.org/wiki/Foreign_key
RecordEntity::CONSTRAINT_ACTION => 'CASCADE',
//Relation allowed to create indexes in outer table
RecordEntity::CREATE_INDEXES => true,
//Has one counted as not nullable by default
RecordEntity::NULLABLE => false,
//Embedded relations are validated and saved with parent model and can accept values using
//setFields
RecordEntity::EMBEDDED_RELATION => true
];
/**
* {@inheritdoc}
*/
public function inverseRelation()
{
//Inverting definition
$this->outerRecord()->addRelation($this->definition[RecordEntity::INVERSE], [
RecordEntity::BELONGS_TO => $this->record->getName(),
RecordEntity::INNER_KEY => $this->definition[RecordEntity::OUTER_KEY],
RecordEntity::OUTER_KEY => $this->definition[RecordEntity::INNER_KEY],
RecordEntity::CONSTRAINT => $this->definition[RecordEntity::CONSTRAINT],
RecordEntity::CONSTRAINT_ACTION => $this->definition[RecordEntity::CONSTRAINT_ACTION],
RecordEntity::CREATE_INDEXES => $this->definition[RecordEntity::CREATE_INDEXES],
RecordEntity::NULLABLE => $this->definition[RecordEntity::NULLABLE]
]);
}
/**
* {@inheritdoc}
*/
public function buildSchema()
{
//Outer (related) table schema
$outerTable = $this->outerRecord()->tableSchema();
//Outer key type must much inner key type
$outerKey = $outerTable->column($this->getOuterKey());
$outerKey->setType($this->getInnerKeyType());
//We are only adding nullable flag if that was declared, if column were already nullable
//this behaviour will be kept
$outerKey->nullable($outerKey->isNullable() || $this->isNullable());
if ($this->hasMorphKey()) {
//Morph key will store outer record role name
$morphKey = $outerTable->column($this->getMorphKey());
//We have predefined morphed key size
$morphKey->string(static::MORPH_COLUMN_SIZE);
$morphKey->nullable($morphKey->isNullable() || $this->isNullable());
//No need to perform any other table operations, usually it's done by polymorphic
//schemas already
return;
}
if ($this->isIndexed()) {
//We can safely add index, it will not be created if outer record has passive schema
$outerKey->index();
}
if (!$this->isConstrained()) {
return;
}
//We are allowed to add foreign key, it will not be created if outer table has passive schema
$foreignKey = $outerKey->references(
$this->record->getTable(),
$this->getInnerKey()
);
$foreignKey->onDelete($this->getConstraintAction());
$foreignKey->onUpdate($this->getConstraintAction());
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Validation\Checkers;
use Spiral\Validation\Checkers\NumberChecker;
class NumberCheckerTest extends \PHPUnit_Framework_TestCase
{
public function testRange()
{
$checker = new NumberChecker();
$this->assertTrue($checker->range(10, 1, 100));
$this->assertTrue($checker->range(10, 10, 100));
$this->assertTrue($checker->range(10, 1, 10));
$this->assertTrue($checker->range(10.5, 1, 100));
$this->assertFalse($checker->range(10, 11, 100));
$this->assertFalse($checker->range(10, 10.1, 100));
$this->assertFalse($checker->range(10, 1, 9.99));
}
public function testHigher()
{
$checker = new NumberChecker();
$this->assertTrue($checker->higher(10, 10));
$this->assertTrue($checker->higher(10, 9));
$this->assertTrue($checker->higher(10, 9.99));
$this->assertFalse($checker->higher(10, 11));
}
public function testLower()
{
$checker = new NumberChecker();
$this->assertTrue($checker->lower(10, 11));
$this->assertTrue($checker->lower(10, 10.01));
$this->assertFalse($checker->lower(10, 9.99));
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer\Traits;
use Spiral\Tokenizer\TokenizerInterface;
/**
* Normalizes tokens by forcing them into same format.
*/
trait TokensTrait
{
/**
* Normalize tokens by wrapping every token into array and forcing line value.
*
* @param array $tokens
* @return array
*/
private function normalizeTokens(array $tokens)
{
$line = 0;
foreach ($tokens as &$token) {
if (isset($token[TokenizerInterface::LINE])) {
$line = $token[TokenizerInterface::LINE];
}
if (!is_array($token)) {
$token = [$token, $token, $line];
}
unset($token);
}
return $tokens;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Schemas;
/**
* Represents single foreign key and it's options.
*/
interface ReferenceInterface
{
/**
* Default delete and update foreign key rules.
*/
const CASCADE = 'CASCADE';
const NO_ACTION = 'NO ACTION';
/**
* Constraint name.
*
* @return string
*/
public function getName();
/**
* Get column name foreign key assigned to.
*
* @return string
*/
public function getColumn();
/**
* Foreign table name.
*
* @return string
*/
public function getForeignTable();
/**
* Foreign key (column name).
*
* @return string
*/
public function getForeignKey();
/**
* Get delete rule, possible values: NO ACTION, CASCADE and etc.
*
* @return string
*/
public function getDeleteRule();
/**
* Get update rule, possible values: NO ACTION, CASCADE and etc.
*
* @return string
*/
public function getUpdateRule();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Builders;
use Spiral\Database\Builders\Prototypes\AbstractSelect;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Entities\QueryCompiler;
use Spiral\Database\Injections\FragmentInterface;
/**
* SelectQuery extends AbstractSelect with ability to specify selection tables and perform UNION
* of multiple select queries.
*/
class SelectQuery extends AbstractSelect
{
/**
* Table names to select data from.
*
* @var array
*/
protected $tables = [];
/**
* Select queries represented by sql fragments or query builders to be united. Stored as
* [UNION TYPE, SELECT QUERY].
*
* @var array
*/
protected $unionTokens = [];
/**
* @param Database $database Parent database.
* @param QueryCompiler $compiler Driver specific QueryGrammar instance (one per builder).
* @param array $from Initial set of table names.
* @param array $columns Initial set of columns to fetch.
*/
public function __construct(
Database $database,
QueryCompiler $compiler,
array $from = [],
array $columns = []
) {
parent::__construct($database, $compiler);
$this->tables = $from;
if (!empty($columns)) {
$this->columns = $this->fetchIdentifiers($columns);
}
}
/**
* Set table names SELECT query should be performed for. Table names can be provided with
* specified alias (AS construction).
*
* @param array|string|mixed $tables Array of names, comma separated string or set of
* parameters.
* @return $this
*/
public function from($tables)
{
$this->tables = $this->fetchIdentifiers(func_get_args());
return $this;
}
/**
* Set columns should be fetched as result of SELECT query. Columns can be provided with
* specified alias (AS construction).
*
* @param array|string|mixed $columns Array of names, comma separated string or set of
* parameters.
* @return $this
*/
public function columns($columns)
{
$this->columns = $this->fetchIdentifiers(func_get_args());
return $this;
}
/**
* Alias for columns() method.
*
* @param array|string|mixed $columns Array of names, comma separated string or set of
* parameters.
* @return $this
*/
public function select($columns)
{
$this->columns = $this->fetchIdentifiers(func_get_args());
return $this;
}
/**
* Add select query to be united with.
*
* @param FragmentInterface $query
* @return $this
*/
public function union(FragmentInterface $query)
{
$this->unionTokens[] = ['', $query];
return $this;
}
/**
* Add select query to be united with. Duplicate values will be included in result.
*
* @param FragmentInterface $query
* @return $this
*/
public function unionAll(FragmentInterface $query)
{
$this->unionTokens[] = ['ALL', $query];
return $this;
}
/**
* {@inheritdoc}
*/
public function getParameters(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler;
}
$parameters = parent::getParameters($compiler);
//Unions always located at the end of query.
foreach ($this->unionTokens as $union) {
if ($union[0] instanceof QueryBuilder) {
$parameters = array_merge($parameters, $union[0]->getParameters($compiler));
}
}
return $parameters;
}
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler->resetQuoter();
}
//11 parameters!
return $compiler->compileSelect(
$this->tables,
$this->distinct,
$this->columns,
$this->joinTokens,
$this->whereTokens,
$this->havingTokens,
$this->grouping,
$this->ordering,
$this->limit,
$this->offset,
$this->unionTokens
);
}
/**
* Request all results as array.
*
* @return array
*/
public function all()
{
return $this->getIterator()->all();
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\Postgres\Schemas;
use Spiral\Database\Entities\Schemas\AbstractReference;
/**
* Postgres foreign key schema.
*/
class ReferenceSchema extends AbstractReference
{
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->column = $schema['column_name'];
$this->foreignTable = $schema['foreign_table_name'];
$this->foreignKey = $schema['foreign_column_name'];
$this->deleteRule = $schema['delete_rule'];
$this->updateRule = $schema['update_rule'];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler;
/**
* SupervisorInterface used by Node to define html syntax for control elements and create valid
* behaviour for html constructions.
*
* @see BehaviourInterface
* @see ExtendsBehaviourInterface
* @see BlockBehaviourInterface
* @see IncludeBehaviourInterface
*/
interface SupervisorInterface
{
/**
* @return SyntaxInterface
*/
public function syntax();
/**
* Define html tag behaviour based on supervisor syntax settings.
*
* @param array $token
* @param array $content
* @param Node $node Node which called behaviour creation. Just in case.
* @return mixed|BehaviourInterface
*/
public function tokenBehaviour(array $token, array $content, Node $node);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Entities;
use Spiral\Database\Injections\ParameterInterface;
/**
* Simple helper class used to interpolate query with given values. To be used for profiling and
* debug purposes only, unsafe SQL are generated!
*/
class QueryInterpolator
{
/**
* Helper method used to interpolate SQL query with set of parameters, must be used only for
* development purposes and never for real query.
*
* @param string $query
* @param array $parameters Parameters to be binded into query.
* @return mixed
*/
public static function interpolate($query, array $parameters = [])
{
if (empty($parameters)) {
return $query;
}
//Flattening first
$parameters = self::flattenParameters($parameters);
//Let's prepare values so they looks better
foreach ($parameters as &$parameter) {
$parameter = self::prepareParameter($parameter);
unset($parameter);
}
reset($parameters);
if (!is_int(key($parameters))) {
//Associative array
return \Spiral\interpolate($query, $parameters, '', '');
}
foreach ($parameters as $parameter) {
$query = preg_replace('/\?/', $parameter, $query, 1);
}
return $query;
}
/**
* Flatten all parameters into simple array.
*
* @param array $parameters
* @return array
*/
protected static function flattenParameters(array $parameters)
{
$flatten = [];
foreach ($parameters as $parameter) {
if ($parameter instanceof ParameterInterface) {
$flatten = array_merge($flatten, $parameter->flatten());
continue;
}
if (is_array($parameter)) {
$flatten = array_merge($flatten, $parameter);
}
$flatten[] = $parameter;
}
return $flatten;
}
/**
* Normalize parameter value to be interpolated.
*
* @param mixed $parameter
* @return string
*/
protected static function prepareParameter($parameter)
{
if ($parameter instanceof ParameterInterface) {
return self::prepareParameter($parameter->getValue());
}
switch (gettype($parameter)) {
case "boolean":
return $parameter ? 'true' : 'false';
case "integer":
return $parameter + 0;
case "NULL":
return 'NULL';
case "double":
return sprintf('%F', $parameter);
case "string":
return "'" . addcslashes($parameter, "'") . "'";
case 'object':
if (method_exists($parameter, '__toString')) {
return "'" . addcslashes((string)$parameter, "'") . "'";
}
}
return "[UNRESOLVED]";
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM;
use Spiral\Database\Exceptions\QueryException;
use Spiral\Models\ActiveEntityInterface;
use Spiral\Models\Events\EntityEvent;
use Spiral\ORM\Entities\RecordSource;
use Spiral\ORM\Exceptions\ORMException;
use Spiral\ORM\Exceptions\RecordException;
use Spiral\ORM\Traits\FindTrait;
/**
* Entity with ability to be saved and direct access to source.
*/
class Record extends RecordEntity implements ActiveEntityInterface
{
/**
* Static find methods.
*/
use FindTrait;
/**
* Indication that save methods must be validated by default, can be altered by calling save
* method with user arguments.
*/
const VALIDATE_SAVE = true;
/**
* {@inheritdoc}
*
* Create or update record data in database. Record will validate all EMBEDDED and loaded
* relations.
*
* @see sourceTable()
* @see updateChriteria()
* @param bool|null $validate Overwrite default option declared in VALIDATE_SAVE to force or
* disable validation before saving.
* @return bool
* @throws RecordException
* @throws QueryException
* @event saving()
* @event saved()
* @event updating()
* @event updated()
*/
public function save($validate = null)
{
if (is_null($validate)) {
//Using default model behaviour
$validate = static::VALIDATE_SAVE;
}
if ($validate && !$this->isValid()) {
return false;
}
if (!$this->isLoaded()) {
$this->dispatch('saving', new EntityEvent($this));
//Primary key field name (if any)
$primaryKey = $this->ormSchema()[ORM::M_PRIMARY_KEY];
//We will need to support records with multiple primary keys in future
unset($this->fields[$primaryKey]);
//Creating
$lastID = $this->sourceTable()->insert($this->fields = $this->serializeData());
if (!empty($primaryKey)) {
//Updating record primary key
$this->fields[$primaryKey] = $lastID;
}
$this->loadedState(true)->dispatch('saved', new EntityEvent($this));
} elseif ($this->isSolid() || $this->hasUpdates()) {
$this->dispatch('updating', new EntityEvent($this));
//Updating changed/all field based on model criteria (in usual case primaryKey)
$this->sourceTable()->update(
$this->compileUpdates(),
$this->stateCriteria()
)->run();
$this->dispatch('updated', new EntityEvent($this));
}
$this->flushUpdates();
$this->saveRelations($validate);
return true;
}
/**
* {@inheritdoc}
*
* @event deleting()
* @event deleted()
*/
public function delete()
{
$this->dispatch('deleting', new EntityEvent($this));
if ($this->isLoaded()) {
$this->sourceTable()->delete($this->stateCriteria())->run();
}
//We don't really need to delete embedded or loaded relations,
//we have foreign keys for that
$this->fields = $this->ormSchema()[ORM::M_COLUMNS];
$this->loadedState(self::DELETED)->dispatch('deleted', new EntityEvent($this));
}
/**
* Instance of ORM Selector associated with specific document.
*
* @see Component::staticContainer()
* @param ORM $orm ORM component, global container will be called if not instance provided.
* @return RecordSource
* @throws ORMException
*/
public static function source(ORM $orm = null)
{
/**
* Using global container as fallback.
*
* @var ORM $orm
*/
if (empty($orm)) {
//Using global container as fallback
$orm = self::staticContainer()->get(ORM::class);
}
return $orm->source(static::class);
}
/**
* Save embedded relations.
*
* @param bool $validate
*/
private function saveRelations($validate)
{
foreach ($this->relations as $name => $relation) {
if (!$relation instanceof RelationInterface) {
//Was never constructed
continue;
}
if ($this->isEmbedded($name) && !$relation->saveAssociation($validate)) {
throw new RecordException("Unable to save relation '{$name}'.");
}
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Debug\Configs;
use Spiral\Core\InjectableConfig;
/**
* Debug component configuration. Must only contain array of log handlers for monolog channels.
*/
class DebuggerConfig extends InjectableConfig
{
/**
* Configuration section.
*/
const CONFIG = 'monolog';
/**
* @var array
*/
protected $config = [];
/**
* @param string $channel
* @return array
*/
public function hasHandlers($channel)
{
return isset($this->config[$channel]);
}
/**
* @param string $channel
* @return array
*/
public function logHandlers($channel)
{
return $this->config[$channel];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database;
use Spiral\Core\Component;
use Spiral\Core\FactoryInterface;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Database\Configs\DatabasesConfig;
use Spiral\Database\Entities\Database;
use Spiral\Database\Entities\Driver;
use Spiral\Database\Exceptions\DatabaseException;
/**
* DatabaseManager responsible for database creation, configuration storage and drivers factory.
*/
class DatabaseManager extends Component implements InjectorInterface, DatabasesInterface
{
/**
* Declares to Spiral IoC that component instance should be treated as singleton.
*/
const SINGLETON = self::class;
/**
* By default spiral will force time conversion into single timezone before storing in
* database, it will help us to ensure that we have no problems with switching timezones and
* save a lot of time while development (potentially).
*
* Current implementation of drivers leaves a room and possibility to define driver/connection
* specific timezone.
*/
const DEFAULT_TIMEZONE = 'UTC';
/**
* @var Database[]
*/
private $databases = [];
/**
* @var Driver[]
*/
private $drivers = [];
/**
* @var DatabasesConfig
*/
protected $config = null;
/**
* @invisible
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param DatabasesConfig $config
* @param FactoryInterface $factory
*/
public function __construct(DatabasesConfig $config, FactoryInterface $factory)
{
$this->config = $config;
$this->factory = $factory;
}
/**
* {@inheritdoc}
*
* @return Database
*/
public function database($database = null)
{
if (empty($database)) {
$database = $this->config->defaultDatabase();
}
//Spiral support ability to link multiple virtual databases together using aliases
$database = $this->config->resolveAlias($database);
if (isset($this->databases[$database])) {
return $this->databases[$database];
}
if (!$this->config->hasDatabase($database)) {
throw new DatabaseException(
"Unable to create database, no presets for '{$database}' found."
);
}
//No need to benchmark here, due connection will happen later
$this->databases[$database] = $this->factory->make(Database::class, [
'name' => $database,
'driver' => $this->driver($this->config->databaseConnection($database)),
'prefix' => $this->config->databasePrefix($database)
]);
return $this->databases[$database];
}
/**
* Get driver by it's name. Every driver associated with configured connection, there is minor
* de-sync in naming due legacy code.
*
* @param string $connection
* @return Driver
* @throws DatabaseException
*/
public function driver($connection)
{
if (isset($this->drivers[$connection])) {
return $this->drivers[$connection];
}
if (!$this->config->hasConnection($connection)) {
throw new DatabaseException(
"Unable to create Driver, no presets for '{$connection}' found."
);
}
$this->drivers[$connection] = $this->factory->make(
$this->config->connectionDriver($connection),
[
'name' => $connection,
'config' => $this->config->connectionConfig($connection)
]
);
return $this->drivers[$connection];
}
/**
* Get instance of every available database.
*
* @return Database[]
* @throws DatabaseException
*/
public function getDatabases()
{
$result = [];
foreach ($this->config->databaseNames() as $name) {
$result[] = $this->database($name);
}
return $result;
}
/**
* Get instance of every available driver/connection.
*
* @return Driver[]
* @throws DatabaseException
*/
public function getDrivers()
{
$result = [];
foreach ($this->config->connectionNames() as $name) {
$result[] = $this->driver($name);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function createInjection(\ReflectionClass $class, $context = null)
{
//If context is empty default database will be returned
return $this->database($context);
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer\Schemas;
use Spiral\Database\Entities\Schemas\AbstractTable;
/**
* SQLServer table schema.
*/
class TableSchema extends AbstractTable
{
/**
* {@inheritdoc}
*/
protected function loadColumns()
{
$query = 'SELECT * FROM information_schema.columns INNER JOIN sys.columns AS sysColumns '
. 'ON (object_name(object_id) = table_name AND sysColumns.name = COLUMN_NAME) '
. 'WHERE table_name = ?';
foreach ($this->driver->query($query, [$this->getName()]) as $column) {
$this->registerColumn($this->columnSchema($column['COLUMN_NAME'], $column));
}
return $this;
}
/**
* {@inheritdoc}
*
* @link http://stackoverflow.com/questions/765867/list-of-all-index-index-columns-in-sql-server-db
*/
protected function loadIndexes()
{
$query = "SELECT indexes.name AS indexName, cl.name AS columnName, "
. "is_primary_key AS isPrimary, is_unique AS isUnique\n"
. "FROM sys.indexes AS indexes\n"
. "INNER JOIN sys.index_columns as columns\n"
. " ON indexes.object_id = columns.object_id AND indexes.index_id = columns.index_id\n"
. "INNER JOIN sys.columns AS cl\n"
. " ON columns.object_id = cl.object_id AND columns.column_id = cl.column_id\n"
. "INNER JOIN sys.tables AS t\n"
. " ON indexes.object_id = t.object_id\n"
. "WHERE t.name = ? ORDER BY indexes.name, indexes.index_id, columns.index_column_id";
$indexes = [];
$primaryKeys = [];
foreach ($this->driver->query($query, [$this->getName()]) as $index) {
if ($index['isPrimary']) {
$primaryKeys[] = $index['columnName'];
continue;
}
$indexes[$index['indexName']][] = $index;
}
$this->setPrimaryKeys($primaryKeys);
foreach ($indexes as $index => $schema) {
$this->registerIndex($this->indexSchema($index, $schema));
}
return $this;
}
/**
* {@inheritdoc}
*/
protected function loadReferences()
{
$references = $this->driver->query("sp_fkeys @fktable_name = ?", [$this->getName()]);
foreach ($references as $reference) {
$this->registerReference($this->referenceSchema($reference['FK_NAME'], $reference));
}
}
/**
* {@inheritdoc}
*/
protected function columnSchema($name, $schema = null)
{
return new ColumnSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function indexSchema($name, $schema = null)
{
return new IndexSchema($this, $name, $schema);
}
/**
* {@inheritdoc}
*/
protected function referenceSchema($name, $schema = null)
{
return new ReferenceSchema($this, $name, $schema);
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Core;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Validation\ValidatorInterface;
/**
* Simple Spiral components config interface.
*/
interface ConfigInterface extends InjectableInterface
{
/**
* Must populate validator rules or errors to be validated.
*
* @param ValidatorInterface $validator
* @return ValidatorInterface
*/
public function validate(ValidatorInterface $validator);
/**
* Serialize config into array.
*
* @return array
*/
public function toArray();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Stores;
use Spiral\Cache\CacheStore;
use Spiral\Cache\Exceptions\StoreException;
use Spiral\Cache\Stores\Memcache\DriverInterface;
use Spiral\Cache\Stores\Memcache\MemcachedDriver;
use Spiral\Cache\Stores\Memcache\MemcacheDriver;
/**
* Talks to Memcache and Memcached drivers using interface.
*/
class MemcacheStore extends CacheStore
{
/**
* Maximum expiration time you can set.
*
* @link http://www.php.net/manual/ru/memcache.set.php
*/
const MAX_EXPIRATION = 2592000;
/**
* @var string
*/
private $prefix = 'spiral:';
/**
* Currently active driver.
*
* @var DriverInterface
*/
private $driver = null;
/**
* @param string $prefix
* @param array $servers
* @param DriverInterface $driver Pre-created driver instance.
* @param bool $connect
*/
public function __construct(
$prefix = 'spiral:',
array $servers = [],
DriverInterface $driver = null,
$connect = true
) {
$this->prefix = $prefix;
if (is_object($driver)) {
$this->setDriver($driver, $connect);
return;
}
if (empty($servers)) {
throw new StoreException(
'Unable to create Memcache[d] cache store. A least one server has to be specified.'
);
}
//New Driver creation
if (class_exists('Memcache')) {
$this->setDriver(new MemcacheDriver($servers), true);
}
if (class_exists('Memcached')) {
$this->setDriver(new MemcachedDriver($servers), true);
}
if (empty($this->driver)) {
throw new StoreException('No available Memcache drivers found.');
}
}
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return $this->driver->isAvailable();
}
/**
* {@inheritdoc}
*/
public function has($name)
{
return $this->driver->get($this->prefix . $name);
}
/**
* {@inheritdoc}
*/
public function get($name)
{
return $this->driver->get($this->prefix . $name);
}
/**
* {@inheritdoc}
*
* Will apply MAX_EXPIRATION.
*/
public function set($name, $data, $lifetime)
{
$lifetime = min(self::MAX_EXPIRATION + time(), $lifetime + time());
if ($lifetime < 0) {
$lifetime = 0;
}
return $this->driver->set($this->prefix . $name, $data, $lifetime);
}
/**
* {@inheritdoc}
*/
public function forever($name, $data)
{
return $this->driver->forever($this->prefix . $name, $data);
}
/**
* {@inheritdoc}
*/
public function delete($name)
{
return $this->driver->delete($this->prefix . $name);
}
/**
* {@inheritdoc}
*/
public function inc($name, $delta = 1)
{
return $this->driver->inc($this->prefix . $name);
}
/**
* {@inheritdoc}
*/
public function dec($name, $delta = 1)
{
return $this->driver->dec($this->prefix . $name, $delta);
}
/**
* {@inheritdoc}
*/
public function flush()
{
$this->driver->flush();
}
/**
* Set pre-created Memcache driver.
*
* @param DriverInterface $driver Pre-created driver instance.
* @param bool $connect Force connection.
*/
protected function setDriver(DriverInterface $driver, $connect = false)
{
$this->driver = $driver;
if ($connect) {
$this->driver->connect();
}
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities\Schemas\Relations;
use Spiral\ORM\Entities\Schemas\RelationSchema;
use Spiral\ORM\Exceptions\RelationSchemaException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
/**
* Declares that parent record belongs to some parent based on value in [inner] key. Basically this
* relation is mirror copy of HasOne relation.
*
* BelongsTo relations inversion requires user to specify backward connection type (HAS_ONE or
* HAS_MANY), inversion may look like (based on example below) ["posts", self::HAS_MANY] (create
* HAS_MANY relation in User record under name "posts").
*
* Example, [Post has one User, relation name "author"], user primary key is "id":
* - relation will create inner key "author_id" in "posts" table (or other table name), nullable by
* default
* - relation will create index on column "author_id" in "posts" table if allowed
* - relation will create foreign key "posts"."author_id" => "users"."id" if allowed
*/
class BelongsToSchema extends RelationSchema
{
/**
* {@inheritdoc}
*/
const RELATION_TYPE = RecordEntity::BELONGS_TO;
/**
* {@inheritdoc}
*
* When relation states that record belongs to interface relation will be switched to
* BelongsToMorphed.
*/
const EQUIVALENT_RELATION = RecordEntity::BELONGS_TO_MORPHED;
/**
* {@inheritdoc}
*
* @invisible
*/
protected $defaultDefinition = [
//Outer key is primary key of related record by default
RecordEntity::OUTER_KEY => '{outer:primaryKey}',
//Inner key will be based on singular name of relation and outer key name
RecordEntity::INNER_KEY => '{name:singular}_{definition:outerKey}',
//Set constraints (foreign keys) by default
RecordEntity::CONSTRAINT => true,
//@link https://en.wikipedia.org/wiki/Foreign_key
RecordEntity::CONSTRAINT_ACTION => 'CASCADE',
//Relation allowed to create indexes in inner table
RecordEntity::CREATE_INDEXES => true,
//We are going to make all relations nullable by default, so we can add fields to existed
//tables without raising an exceptions
RecordEntity::NULLABLE => true
];
/**
* {@inheritdoc}
*/
public function inverseRelation()
{
/**
* Unfortunately BelongsTo relation can not be inversed without specifying backward relation
* type which can be either HAS_ONE or HAS_MANY.
*/
if (
!is_array($this->definition[RecordEntity::INVERSE])
|| !isset($this->definition[RecordEntity::INVERSE][1])
) {
throw new RelationSchemaException(
"Unable to revert BELONG_TO relation '{$this->record}'.'{$this}', " .
"backward relation type is missing or invalid."
);
}
//Inverting definition
$this->outerRecord()->addRelation($this->definition[RecordEntity::INVERSE][1], [
$this->definition[RecordEntity::INVERSE][0] => $this->record->getName(),
RecordEntity::OUTER_KEY => $this->definition[RecordEntity::INNER_KEY],
RecordEntity::INNER_KEY => $this->definition[RecordEntity::OUTER_KEY],
RecordEntity::CONSTRAINT => $this->definition[RecordEntity::CONSTRAINT],
RecordEntity::CONSTRAINT_ACTION => $this->definition[RecordEntity::CONSTRAINT_ACTION],
RecordEntity::CREATE_INDEXES => $this->definition[RecordEntity::CREATE_INDEXES],
RecordEntity::NULLABLE => $this->definition[RecordEntity::NULLABLE]
]);
}
/**
* {@inheritdoc}
*/
public function buildSchema()
{
//We are going to modify table related to parent record
$innerTable = $this->record->tableSchema();
//Inner key type must match outer key type
$innerKey = $innerTable->column($this->getInnerKey());
$innerKey->setType($this->getOuterKeyType());
//We are only adding nullable flag if that was declared, if column were already nullable
//this behaviour will be kept
$innerKey->nullable($innerKey->isNullable() || $this->isNullable());
if ($this->isIndexed()) {
//We can safely add index, it will not be created if outer record has passive schema
$innerKey->index();
}
if (!$this->isConstrained()) {
return;
}
//We are allowed to add foreign key, it will not be created if outer table has passive schema
$foreignKey = $innerKey->references(
$this->outerRecord()->getTable(),
$this->getOuterKey()
);
$foreignKey->onDelete($this->getConstraintAction());
$foreignKey->onUpdate($this->getConstraintAction());
}
/**
* Normalize schema definition into light cachable form.
*
* @return array
*/
protected function normalizeDefinition()
{
$definition = parent::normalizeDefinition();
if ($this->getOuterKey() == $this->outerRecord()->getPrimaryKey()) {
//Linked using primary key
$definition[ORM::M_PRIMARY_KEY] = $this->getOuterKey();
}
return $definition;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Pagination;
use Psr\Http\Message\UriInterface;
use Spiral\Pagination\Exceptions\PaginationException;
/**
* Paginates objects and arrays. Theoretically i should create another interface
* SimplePaginatorInterface without count related methods and extend this interface from simple
* one. Right now you can simply set count manually, in any scenario it's up to view how to render
* it.
*/
interface PaginatorInterface
{
/**
* Set page number.
*
* @param int $number
* @return int
*/
public function setPage($number);
/**
* Get current page number.
*
* @return int
*/
public function getPage();
/**
* Set initial paginator uri
*
* @param UriInterface $uri
*/
public function setUri(UriInterface $uri);
/**
* Create page URL using specific page number. No domain or schema information included by
* default, starts with path.
*
* @param int $pageNumber
* @return UriInterface
*/
public function uri($pageNumber);
/**
* Apply paginator to paginable object.
*
* @param PaginableInterface $paginable
* @return PaginableInterface
* @throws PaginationException
*/
public function paginate(PaginableInterface $paginable);
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Database\Drivers\SQLServer\Schemas;
use Spiral\Database\Entities\Schemas\AbstractReference;
/**
* SQLServer foreign key schema.
*/
class ReferenceSchema extends AbstractReference
{
/**
* {@inheritdoc}
*/
protected function resolveSchema($schema)
{
$this->column = $schema['FKCOLUMN_NAME'];
$this->foreignTable = $schema['PKTABLE_NAME'];
$this->foreignKey = $schema['PKCOLUMN_NAME'];
$this->deleteRule = $schema['DELETE_RULE'] ? self::NO_ACTION : self::CASCADE;
$this->updateRule = $schema['UPDATE_RULE'] ? self::NO_ACTION : self::CASCADE;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\ORM\Entities;
use Psr\Log\LoggerAwareInterface;
use Spiral\Cache\CacheInterface;
use Spiral\Core\Traits\SaturateTrait;
use Spiral\Database\Builders\Prototypes\AbstractSelect;
use Spiral\Database\Entities\QueryBuilder;
use Spiral\Database\Entities\QueryCompiler;
use Spiral\Database\Injections\FragmentInterface;
use Spiral\Database\Injections\ParameterInterface;
use Spiral\Database\Query\QueryResult;
use Spiral\Debug\Traits\BenchmarkTrait;
use Spiral\Debug\Traits\LoggerTrait;
use Spiral\ORM\Entities\Loaders\RootLoader;
use Spiral\ORM\Exceptions\SelectorException;
use Spiral\ORM\ORM;
use Spiral\ORM\RecordEntity;
use Spiral\ORM\RecordInterface;
/**
* Selectors provide QueryBuilder (see Database) like syntax and support for ORM records to be
* fetched from database. In addition, selection uses set of internal data loaders dedicated to
* every of record relation and used to pre-load (joins) or post-load (separate query) data for
* this relations, including additional where conditions and using relation data for parent record
* filtering queries.
*
* Selector loaders may not only be related to SQL databases, but might load data from external
* sources.
*
* @see with()
* @see load()
* @see LoaderInterface
* @see AbstractSelect
*/
class RecordSelector extends AbstractSelect implements LoggerAwareInterface
{
/**
* Selector provides set of profiling functionality helps to understand what is going on with
* query and data parsing.
*/
use LoggerTrait, BenchmarkTrait, SaturateTrait;
/**
* Class name of record to be loaded.
*
* @var string
*/
protected $class = '';
/**
* Data columns are set of columns automatically created by inner loaders using
* generateColumns() method, this is not the same column set as one provided by user using
* columns() method. Do not define columns using generateColumns() method outside of loaders.
*
* @see generateColumns()
* @var array
*/
protected $dataColumns = [];
/**
* We have to track count of loader columns to define correct offsets.
*
* @var int
*/
protected $countColumns = 0;
/**
* Primary selection loader.
*
* @var Loader
*/
protected $loader = null;
/**
* @invisible
* @var ORM
*/
protected $orm = null;
/**
* @param string $class
* @param ORM $orm
* @param Loader $loader
*/
public function __construct($class, ORM $orm = null, Loader $loader = null)
{
$this->class = $class;
$this->orm = $this->saturate($orm, ORM::class);
$this->columns = $this->dataColumns = [];
//We aways need primary loader
if (empty($this->loader = $loader)) {
//Selector always need primary data loaded to define data structure and perform query
//parsing, in most of cases we can easily use RootLoader associated with primary record
//schema
$this->loader = new RootLoader($this->orm, null, $this->orm->schema($class));
}
//Every ORM loader has ability to declare it's primary database, we are going to use
//primary loader database to initiate selector
$database = $this->loader->dbalDatabase();
//AbstractSelect construction
parent::__construct($database, $database->driver()->queryCompiler($database->getPrefix()));
}
/**
* Primary selection table.
*
* @return string
*/
public function primaryTable()
{
return $this->loader->getTable();
}
/**
* Primary alias points to table related to parent record.
*
* @return string
*/
public function primaryAlias()
{
return $this->loader->getAlias();
}
/**
* {@inheritdoc}
*/
public function columns($columns = ['*'])
{
$this->columns = $this->fetchIdentifiers(func_get_args());
return $this;
}
/**
* Automatically generate set of columns for specified table or alias, method used by loaders
* in cases where data is joined.
*
* @param string $table Source table name or alias.
* @param array $columns Original set of record columns.
* @return int
*/
public function generateColumns($table, array $columns)
{
$offset = count($this->dataColumns);
foreach ($columns as $column) {
$columnAlias = 'c' . (++$this->countColumns);
$this->dataColumns[] = $table . '.' . $column . ' AS ' . $columnAlias;
}
return $offset;
}
/**
* Request primary selector loader to pre-load relation name. Any type of loader can be used
* for
* data preloading. ORM loaders by default will select the most efficient way to load related
* data which might include additional select query or left join. Loaded data will
* automatically pre-populate record relations. You can specify nested relations using "."
* separator.
*
* Examples:
*
* //Select users and load their comments (will cast 2 queries, HAS_MANY comments)
* User::find()->with('comments');
*
* //You can load chain of relations - select user and load their comments and post related to
* //comment
* User::find()->with('comments.post');
*
* //We can also specify custom where conditions on data loading, let's load only public
* comments. User::find()->load('comments', [
* 'where' => ['{@}.status' => 'public']
* ]);
*
* Please note using "{@}" column name, this placeholder is required to prevent collisions and
* it will be automatically replaced with valid table alias of pre-loaded comments table.
*
* //In case where your loaded relation is MANY_TO_MANY you can also specify pivot table
* conditions,
* //let's pre-load all approved user tags, we can use same placeholder for pivot table alias
* User::find()->load('tags', [
* 'wherePivot' => ['{@}.approved' => true]
* ]);
*
* //In most of cases you don't need to worry about how data was loaded, using external query
* or
* //left join, however if you want to change such behaviour you can force load method to
* INLOAD
* User::find()->load('tags', [
* 'method' => Loader::INLOAD,
* 'wherePivot' => ['{@}.approved' => true]
* ]);
*
* Attention, you will not be able to correctly paginate in this case and only ORM loaders
* support different loading types.
*
* You can specify multiple loaders using array as first argument.
*
* Example:
* User::find()->load(['posts', 'comments', 'profile']);
*
* @see with()
* @param string $relation
* @param array $options
* @return $this
*/
public function load($relation, array $options = [])
{
if (is_array($relation)) {
foreach ($relation as $name => $subOption) {
if (is_string($subOption)) {
//Array of relation names
$this->load($subOption, $options);
} else {
//Multiple relations or relation with addition load options
$this->load($name, $subOption + $options);
}
}
return $this;
}
//We are requesting primary loaded to pre-load nested relation
$this->loader->loader($relation, $options);
return $this;
}
/**
* With method is very similar to load() one, except it will always include related data to
* parent query using INNER JOIN, this method can be applied only to ORM loaders and relations
* using same database as parent record.
*
* Method generally used to filter data based on some relation condition.
* Attention, with() method WILL NOT load relation data, it will only make it accessible in
* query.
*
* By default joined tables will be available in query based on realtion name, you can change
* joined table alias using relation option "alias".
*
* Do not forget to set DISTINCT flag while including HAS_MANY and MANY_TO_MANY relations. In
* other scenario you will not able to paginate data well.
*
* Examples:
*
* //Find all users who have comments comments
* User::find()->with('comments');
*
* //Find all users who have approved comments (we can use comments table alias in where
* statement).
* User::find()->with('comments')->where('comments.approved', true);
*
* //Find all users who have posts which have approved comments
* User::find()->with('posts.comments')->where('posts_comments.approved', true);
*
* //Custom join alias for post comments relation
* $user->with('posts.comments', [
* 'alias' => 'comments'
* ])->where('comments.approved', true);
*
* //If you joining MANY_TO_MANY relation you will be able to use pivot table used as relation
* name
* //plus "_pivot" postfix. Let's load all users with approved tags.
* $user->with('tags')->where('tags_pivot.approved', true);
*
* //You can also use custom alias for pivot table as well
* User::find()->with('tags', [
* 'pivotAlias' => 'tags_connection'
* ])
* ->where('tags_connection.approved', false);
*
* You can safely combine with() and load() methods.
*
* //Load all users with approved comments and pre-load all their comments
* User::find()->with('comments')->where('comments.approved', true)
* ->load('comments');
*
* //You can also use custom conditions in this case, let's find all users with approved
* comments
* //and pre-load such approved comments
* User::find()->with('comments')->where('comments.approved', true)
* ->load('comments', [
* 'where' => ['{@}.approved' => true]
* ]);
*
* //As you might notice previous construction will create 2 queries, however we can simplify
* //this construction to use already joined table as source of data for relation via "using"
* //keyword
* User::find()->with('comments')->where('comments.approved', true)
* ->load('comments', ['using' => 'comments']);
*
* //You will get only one query with INNER JOIN, to better understand this example let's use
* //custom alias for comments in with() method.
* User::find()->with('comments', ['alias' => 'commentsR'])->where('commentsR.approved', true)
* ->load('comments', ['using' => 'commentsR']);
*
* @see load()
* @param string $relation
* @param array $options
* @return $this
*/
public function with($relation, array $options = [])
{
if (is_array($relation)) {
foreach ($relation as $name => $options) {
if (is_string($options)) {
//Array of relation names
$this->with($options, []);
} else {
//Multiple relations or relation with addition load options
$this->with($name, $options);
}
}
return $this;
}
//Requesting primary loader to join nested relation, will only work for ORM loaders
$this->loader->joiner($relation, $options);
return $this;
}
/**
* Fetch one record from database using it's primary key. You can use INLOAD and JOIN_ONLY
* loaders with HAS_MANY or MANY_TO_MANY relations with this method as no limit were used.
*
* @see findOne()
* @param mixed $id Primary key value.
* @return RecordEntity|null
* @throws SelectorException
*/
public function findByPK($id)
{
$primaryKey = $this->loader->getPrimaryKey();
if (empty($primaryKey)) {
throw new SelectorException(
"Unable to fetch data by primary key, no primary key found."
);
}
//No limit here
return $this->findOne([$primaryKey => $id], false);
}
/**
* Fetch one record from database. Attention, LIMIT statement will be used, meaning you can not
* use loaders for HAS_MANY or MANY_TO_MANY relations with data inload (joins), use default
* loading method.
*
* @see findByPK()
* @param array $where Selection WHERE statement.
* @param bool $withLimit Use limit 1.
* @return RecordEntity|null
*/
public function findOne(array $where = [], $withLimit = true)
{
if (!empty($where)) {
$this->where($where);
}
$data = $this->limit($withLimit ? 1 : null)->fetchData();
if (empty($data)) {
return null;
}
//Letting ORM to do it's job
return $this->orm->record($this->class, $data[0]);
}
/**
* {@inheritdoc}
*/
public function sqlStatement(QueryCompiler $compiler = null)
{
if (empty($compiler)) {
$compiler = $this->compiler->resetQuoter();
}
//Primary loader may add custom conditions to select query
$this->loader->configureSelector($this);
if (empty($columns = $this->columns)) {
//If no user columns were specified we are going to use columns defined by our loaders
//in addition it will return RecordIterator instance as result instead of QueryResult
$columns = !empty($this->dataColumns) ? $this->dataColumns : ['*'];
}
return $compiler->compileSelect(
["{$this->primaryTable()} AS {$this->primaryAlias()}"],
$this->distinct,
$columns,
$this->joinTokens,
$this->whereTokens,
$this->havingTokens,
$this->grouping,
$this->ordering,
$this->limit,
$this->offset
);
}
/**
* {@inheritdoc}
*
* Return type will depend if custom columns set were used.
*
* @param array $callbacks Callbacks to be used in record iterator as magic methods.
* @return QueryResult|RecordIterator
*/
public function getIterator(array $callbacks = [])
{
if (!empty($this->columns) || !empty($this->grouping)) {
//QueryResult for user requests
return $this->run();
}
/*
* We are getting copy of ORM with cloned cache, so all our entities are isolated in it.
*/
return new RecordIterator(
clone $this->orm,
$this->class,
$this->fetchData(),
true,
$callbacks
);
}
/**
* All records.
*
* @return RecordInterface[]
*/
public function all()
{
return $this->getIterator()->all();
}
/**
* Execute query and every related query to compile records data in tree form - every relation
* data will be included as sub key.
*
* Attention, Selector will cache compiled data tree and not query itself to keep data integrity
* and to skip data compilation on second query.
*
* @return array
*/
public function fetchData()
{
//Pagination!
$this->applyPagination();
//Generating statement
$statement = $this->sqlStatement();
if (!empty($this->cacheLifetime)) {
$cacheKey = $this->cacheKey ?: md5(serialize([$statement, $this->getParameters()]));
if (empty($this->cacheStore)) {
$this->cacheStore = $this->orm->container()->get(CacheInterface::class)->store();
}
if ($this->cacheStore->has($cacheKey)) {
$this->logger()->debug("Selector result were fetched from cache.");
//We are going to store parsed result, not queries
return $this->cacheStore->get($cacheKey);
}
}
//We are bypassing run() method here to prevent query caching, we will prefer to cache
//parsed data rather that database response
$result = $this->database->query($statement, $this->getParameters());
//In many cases (too many inloads, too complex queries) parsing can take significant amount
//of time, so we better profile it
$benchmark = $this->benchmark('parseResult', $statement);
//Here we are feeding selected data to our primary loaded to parse it and and create
//data tree for our records
$this->loader->parseResult($result, $rowsCount);
$this->benchmark($benchmark);
//Memory freeing
$result->close();
//This must force loader to execute all post loaders (including ODM and etc)
$this->loader->loadData();
//Now we can request our primary loader for compiled data
$data = $this->loader->getResult();
//Memory free! Attention, it will not reset columns aliases but only make possible to run
//query again
$this->loader->clean();
if (!empty($this->cacheLifetime) && !empty($cacheKey)) {
//We are caching full records tree, not queries
$this->cacheStore->set($cacheKey, $data, $this->cacheLifetime);
}
return $data;
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tokenizer;
use Spiral\Tokenizer\Prototypes\AbstractLocator;
use Spiral\Tokenizer\Reflections\ReflectionInvocation;
/**
* Can locate invocations in a specified directory. Can only find simple invocations!
*
* @todo use ast
*/
class InvocationLocator extends AbstractLocator implements InvocationLocatorInterface
{
/**
* {@inheritdoc}
*/
public function getInvocations(\ReflectionFunctionAbstract $function)
{
$result = [];
foreach ($this->availableInvocations($function->getName()) as $invocation) {
if ($this->isTargeted($invocation, $function)) {
$result[] = $invocation;
}
}
return $result;
}
/**
* Invocations available in finder scope.
*
* @param string $signature Method or function signature (name), for pre-filtering.
* @return ReflectionInvocation[]
*/
protected function availableInvocations($signature = '')
{
$invocations = [];
$signature = strtolower(trim($signature, '\\'));
foreach ($this->availableReflections() as $reflection) {
/**
* @var ReflectionFileInterface $reflection
*/
foreach ($reflection->getInvocations() as $invocation) {
if (
!empty($signature)
&& strtolower(trim($invocation->getName(), '\\')) != $signature
) {
continue;
}
$invocations[] = $invocation;
}
}
return $invocations;
}
/**
* @param ReflectionInvocation $invocation
* @param \ReflectionFunctionAbstract $function
* @return bool
*/
protected function isTargeted(
ReflectionInvocation $invocation,
\ReflectionFunctionAbstract $function
) {
if ($function instanceof \ReflectionFunction) {
return !$invocation->isMethod();
}
if (empty($class = $this->classReflection($invocation->getClass()))) {
//Unable to get reflection
return false;
}
/**
* @var \ReflectionMethod $function
*/
$target = $function->getDeclaringClass();
if ($target->isTrait()) {
//Let's compare traits
return in_array($target->getName(), $this->getTraits($invocation->getClass()));
}
return $class->getName() == $target->getName() || $class->isSubclassOf($target);
}
}
<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler\Exceptions;
/**
* Syntax based exceptions.
*/
class SyntaxException extends StemplerException
{
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Stempler;
use Spiral\Stempler\Exceptions\SyntaxException;
/**
* Used to detect token behaviour based on internal rules.
*/
interface SyntaxInterface
{
/**
* Basic templater behaviours.
*/
const TYPE_BLOCK = 'block';
const TYPE_EXTENDS = 'extends';
const TYPE_IMPORTER = 'use';
const TYPE_INCLUDE = 'include';
const TYPE_NONE = 'none';
//todo: yep, self modifiable syntax
const TYPE_DIRECTIVE = 'directive';
/**
* In strict mode every unpaired close tag or other html error will raise an
* StrictModeException.
*
* @return bool
*/
public function isStrict();
/**
* Detect token behaviour.
*
* @param array $token
* @param string $name Node name stripper from token name.
* @return string
*/
public function tokenType(array $token, &$name = null);
/**
* Resolve include or extend location based on given token.
*
* @param array $token
* @return string
* @throws SyntaxException
*/
public function resolvePath(array $token);
/**
* @param array $token
* @param Supervisor $supervisor
* @return ImporterInterface
* @throws SyntaxException
*/
public function createImporter(array $token, Supervisor $supervisor);
/**
* Get all syntax block exporters.
*
* @return ExporterInterface[]
*/
public function blockExporters();
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Cache\Configs;
use Spiral\Core\InjectableConfig;
use Spiral\Core\Traits\Config\AliasTrait;
/**
* Cache component configuration manager.
*/
class CacheConfig extends InjectableConfig
{
use AliasTrait;
/**
* Configuration section.
*/
const CONFIG = 'cache';
/**
* @var array
*/
protected $config = [
'store' => '',
'stores' => []
];
/**
* @param string $store
* @return bool
*/
public function hasStore($store)
{
return isset($this->config['stores'][$store]);
}
/**
* @param string $store
* @return string
*/
public function storeClass($store)
{
if (class_exists($store)) {
//Legacy format support
return $store;
}
return $this->config['stores'][$store]['class'];
}
/**
* @param string $store
* @return array
*/
public function storeOptions($store)
{
return $this->config['stores'][$store];
}
}<file_sep><?php
/**
* Spiral Framework.
*
* @license MIT
* @author <NAME> (Wolfy-J)
*/
namespace Spiral\Tests\Cases\Encrypter;
use Spiral\Encrypter\Encrypter;
class RandomTest extends \PHPUnit_Framework_TestCase
{
public function testRandom()
{
$encrypter = $this->makeEncrypter();
$previousRandoms = [];
for ($try = 0; $try < 100; $try++) {
$random = $encrypter->random(32);
$this->assertTrue(strlen($random) == 32);
$this->assertNotContains($random, $previousRandoms);
$previousRandoms[] = $random;
}
}
/**
* @param string $key
* @return Encrypter
*/
protected function makeEncrypter($key = '1234567890123456')
{
return new Encrypter($key);
}
} | 570bd254ef80a730cb21c3e745dc16d2a9a3f309 | [
"Markdown",
"PHP"
] | 260 | PHP | tuneyourserver/components | e45beb56171d6e05962ee5146604292eba29bf64 | be1d0c37755d6b92ad88d5c2ba129f4eef4f65a5 |
refs/heads/master | <repo_name>BrittanyTinnin/combine-reducers-online-web-ft-092418<file_sep>/src/actions/index.js
export const addAuthor = author => {
console.log("app hit the addAuthor() in actions/index.js")
return {
type: 'ADD_AUTHOR',
author
};
};
export const removeAuthor = id => {
console.log("app hit the removeAuthor() in actions/index.js")
return {
type: 'REMOVE_AUTHOR',
id
};
};
export const addBook = book => {
console.log("app hit the addBook() in actions/index.js")
return {
type: 'ADD_BOOK',
book
};
};
export const removeBook = id => {
console.log("app hit the removeBook() in actions/index.js")
return {
type: 'REMOVE_BOOK',
id
};
};
| 921ccbc801fc688f97d3f67a6a4417b715c1f892 | [
"JavaScript"
] | 1 | JavaScript | BrittanyTinnin/combine-reducers-online-web-ft-092418 | f36b624fb2285854ef5abf558cf8708639a9eb1e | e714739afc981ba3ab68b0484dd513a1c8a4011b |
refs/heads/master | <file_sep>using bh.Shared;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System.Linq;
namespace bh.Server
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("bh.Server"));
});
services.AddMvc().AddNewtonsoftJson();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBlazorDebugging();
}
app.UseClientSideBlazorFiles<Client.Startup>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
});
}
}
}
<file_sep>using bh.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace bh.Shared{
public class ApplicationDbContext:DbContext{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
}
} | fdefac9d0950c0d2b69f4a89fbc4a2d8982b0942 | [
"C#"
] | 2 | C# | upretymadan45/BlazorBasics | 717f6b8a170b17da72bf504ef17a5245084308ec | cbc444b0457036206691670bcb1fba0c629a9f0d |
refs/heads/master | <repo_name>thewakingsands/ZeffUI<file_sep>/data/content_type.js
// Content manually placed over from https://github.com/quisquous/cactbot/blob/main/resources/content_type.ts because this project doesn't support typescript
var content_type = {
BeastTribeQuests: 13,
Companions: 12,
CustomDeliveries: 25,
DeepDungeons: 21,
DisciplesOfTheHand: 17,
DisciplesOfTheLand: 16,
Dungeons: 2,
DutyRoulette: 1,
Eureka: 26,
Fates: 8,
GoldSaucer: 19,
GrandCompany: 11,
Guildhests: 3,
Levequests: 10,
OverallCompletion: 14,
PlayerCommendation: 15,
Pvp: 6,
QuestBattles: 7,
Raids: 5,
RetainerVentures: 18,
TreasureHunt: 9,
Trials: 4,
UltimateRaids: 28,
WondrousTails: 24,
};
<file_sep>/scripts/default_settings.js
// External Globals
/* global callOverlayHandler */
// Function to initialize setting property, thanks MikeMatrix for the help with this.
function checkAndInitializeSetting(settingsObject, setting, defaultValue) {
if (settingsObject[setting] === undefined)
settingsObject[setting] = defaultValue;
}
// Gets the set language in FFXIV Plugin Settings
async function getACTLocale() {
let lang = await callOverlayHandler({ call: "getLanguage" });
switch (lang.language) {
case "English":
return "en";
case "German":
return "de";
case "French":
return "fr";
case "Japanese":
return "jp";
case "Chinese":
return "cn";
case "Korean":
return "kr";
case "default":
return "en";
}
}
/* exported checkAndInitializeDefaultSettingsObject */
async function checkAndInitializeDefaultSettingsObject(settings, lang = null) {
// PROFILE SETTINGS
checkAndInitializeSetting(settings, "profiles", {});
checkAndInitializeSetting(settings.profiles, "currentprofile", "");
checkAndInitializeSetting(settings.profiles, "profiles", {});
checkAndInitializeSetting(settings.profiles, "jobprofiles", {});
// LANGUAGE SETTINGS
if (!lang) {
lang = await getACTLocale();
}
checkAndInitializeSetting(settings, "language", lang);
// OVERRIDE SETTINGS
checkAndInitializeSetting(settings, "override", {});
checkAndInitializeSetting(settings.override, "enabled", false);
checkAndInitializeSetting(settings.override, "abilities", []);
// GENERAL SETTINGS
checkAndInitializeSetting(settings, "general", {});
checkAndInitializeSetting(settings.general, "usewebtts", false);
checkAndInitializeSetting(settings.general, "ttsearly", 5);
checkAndInitializeSetting(settings.general, "preventdoubletts", true);
checkAndInitializeSetting(settings.general, "usehdicons", false);
checkAndInitializeSetting(settings.general, "customcss", "");
// SKIN SETTINGS
checkAndInitializeSetting(settings, "skin", "default");
// FONT SETTINGS
checkAndInitializeSetting(settings, "font", "Arial");
checkAndInitializeSetting(settings, "customfonts", []);
// DEBUG SETTINGS
checkAndInitializeSetting(settings, "debug", {});
checkAndInitializeSetting(settings.debug, "enabled", false);
// GLOBAL SETTINGS
/* prettier-ignore */
checkAndInitializeSetting(settings, "partyorder",
[
// Tanks
"PLD", "GLA", "WAR", "MRD", "DRK", "GNB",
// Healers
"WHM", "CNJ", "SCH", "AST", "SGE",
// Melee DPS
"MNK", "PGL", "DRG", "LNC", "NIN", "ROG", "SAM", "RPR",
// Physical Ranged DPS
"BRD", "ARC", "MCH", "DNC",
// Caster DPS
"BLM", "THM", "SMN", "ACN", "RDM", "BLU"]
);
checkAndInitializeSetting(settings, "rolepartyorder", {});
checkAndInitializeSetting(
settings.rolepartyorder,
"tank",
settings.partyorder,
);
checkAndInitializeSetting(
settings.rolepartyorder,
"healer",
settings.partyorder,
);
checkAndInitializeSetting(
settings.rolepartyorder,
"dps",
settings.partyorder,
);
checkAndInitializeSetting(
settings.rolepartyorder,
"other",
settings.partyorder,
);
checkAndInsertMissingJobs(settings.partyorder);
checkAndInsertMissingJobs(settings.rolepartyorder.tank);
checkAndInsertMissingJobs(settings.rolepartyorder.healer);
checkAndInsertMissingJobs(settings.rolepartyorder.dps);
checkAndInsertMissingJobs(settings.rolepartyorder.other);
// HEALTHBAR SETTINGS
checkAndInitializeSetting(settings, "healthbar", {});
checkAndInitializeSetting(settings.healthbar, "enabled", true);
checkAndInitializeSetting(settings.healthbar, "hideoutofcombat", false);
checkAndInitializeSetting(settings.healthbar, "textenabled", true);
checkAndInitializeSetting(
settings.healthbar,
"color",
"--filter-dark-green",
);
checkAndInitializeSetting(settings.healthbar, "textformat", "");
checkAndInitializeSetting(settings.healthbar, "scale", 1);
checkAndInitializeSetting(settings.healthbar, "rotation", 0);
checkAndInitializeSetting(settings.healthbar, "x", 30);
checkAndInitializeSetting(settings.healthbar, "y", 216);
checkAndInitializeSetting(settings.healthbar, "align", "left");
checkAndInitializeSetting(settings.healthbar, "font", "Arial");
checkAndInitializeSetting(settings.healthbar, "fontxoffset", 0);
checkAndInitializeSetting(settings.healthbar, "fontyoffset", 0);
checkAndInitializeSetting(settings.healthbar, "staticfontsize", false);
checkAndInitializeSetting(settings.healthbar, "fontsize", 10);
// MANABAR SETTINGS
checkAndInitializeSetting(settings, "manabar", {});
checkAndInitializeSetting(settings.manabar, "enabled", true);
checkAndInitializeSetting(settings.manabar, "hideoutofcombat", false);
checkAndInitializeSetting(settings.manabar, "textenabled", true);
checkAndInitializeSetting(settings.manabar, "color", "--filter-light-pink");
checkAndInitializeSetting(settings.manabar, "textformat", "");
checkAndInitializeSetting(settings.manabar, "scale", 1);
checkAndInitializeSetting(settings.manabar, "rotation", 0);
checkAndInitializeSetting(settings.manabar, "x", 30);
checkAndInitializeSetting(settings.manabar, "y", 232);
checkAndInitializeSetting(settings.manabar, "align", "left");
checkAndInitializeSetting(settings.manabar, "font", "Arial");
checkAndInitializeSetting(settings.manabar, "fontxoffset", 0);
checkAndInitializeSetting(settings.manabar, "fontyoffset", 0);
checkAndInitializeSetting(settings.manabar, "staticfontsize", false);
checkAndInitializeSetting(settings.manabar, "fontsize", 10);
checkAndInitializeSetting(settings.manabar, "jobthresholdsenabled", true);
checkAndInitializeSetting(
settings.manabar,
"lowcolor",
"--filter-dark-red",
);
checkAndInitializeSetting(
settings.manabar,
"medcolor",
"--filter-light-blue",
);
checkAndInitializeSetting(settings.manabar, "BLM", {});
checkAndInitializeSetting(settings.manabar.BLM, "low", 2399);
checkAndInitializeSetting(settings.manabar.BLM, "med", 3999);
checkAndInitializeSetting(settings.manabar, "PLD", {});
checkAndInitializeSetting(settings.manabar.PLD, "low", 3600);
checkAndInitializeSetting(settings.manabar.PLD, "med", 9400);
checkAndInitializeSetting(settings.manabar, "DRK", {});
checkAndInitializeSetting(settings.manabar.DRK, "low", 2999);
checkAndInitializeSetting(settings.manabar.DRK, "med", 5999);
// MP TICKER SETTINGS
checkAndInitializeSetting(settings, "mpticker", {});
checkAndInitializeSetting(settings.mpticker, "enabled", false);
checkAndInitializeSetting(settings.mpticker, "hideoutofcombat", false);
checkAndInitializeSetting(settings.mpticker, "color", "--filter-grey");
checkAndInitializeSetting(settings.mpticker, "scale", 1);
checkAndInitializeSetting(settings.mpticker, "rotation", 0);
checkAndInitializeSetting(settings.mpticker, "x", 30);
checkAndInitializeSetting(settings.mpticker, "y", 248);
checkAndInitializeSetting(settings.mpticker, "specificjobsenabled", true);
checkAndInitializeSetting(settings.mpticker, "specificjobs", ["BLM"]);
checkAndInitializeSetting(settings.mpticker, "alwaystick", false);
// DOT TICKER SETTINGS
checkAndInitializeSetting(settings, "dotticker", {});
checkAndInitializeSetting(settings.dotticker, "enabled", false);
checkAndInitializeSetting(settings.dotticker, "hideoutofcombat", false);
checkAndInitializeSetting(settings.dotticker, "color", "--filter-grey");
checkAndInitializeSetting(settings.dotticker, "scale", 1);
checkAndInitializeSetting(settings.dotticker, "rotation", 0);
checkAndInitializeSetting(settings.dotticker, "x", 30);
checkAndInitializeSetting(settings.dotticker, "y", 264);
checkAndInitializeSetting(settings.dotticker, "specificjobsenabled", true);
checkAndInitializeSetting(settings.dotticker, "specificjobs", ["BRD"]);
// HOT TICKER SETTINGS
checkAndInitializeSetting(settings, "hotticker", {});
checkAndInitializeSetting(settings.hotticker, "enabled", false);
checkAndInitializeSetting(settings.hotticker, "hideoutofcombat", false);
checkAndInitializeSetting(settings.hotticker, "color", "--filter-grey");
checkAndInitializeSetting(settings.hotticker, "scale", 1);
checkAndInitializeSetting(settings.hotticker, "rotation", 0);
checkAndInitializeSetting(settings.hotticker, "x", 30);
checkAndInitializeSetting(settings.hotticker, "y", 280);
checkAndInitializeSetting(settings.hotticker, "specificjobsenabled", true);
checkAndInitializeSetting(settings.hotticker, "specificjobs", [
"AST",
"SCH",
"SGE",
"MNK",
"WHM",
]);
// PULLTIMER SETTINGS
checkAndInitializeSetting(settings, "timerbar", {});
checkAndInitializeSetting(settings.timerbar, "enabled", true);
checkAndInitializeSetting(settings.timerbar, "textenabled", true);
checkAndInitializeSetting(settings.timerbar, "color", "--filter-dark-red");
checkAndInitializeSetting(settings.timerbar, "scale", 1);
checkAndInitializeSetting(settings.timerbar, "rotation", 0);
checkAndInitializeSetting(settings.timerbar, "x", 30);
checkAndInitializeSetting(settings.timerbar, "y", 200);
checkAndInitializeSetting(settings.timerbar, "font", "Arial");
checkAndInitializeSetting(settings.timerbar, "fontxoffset", 0);
checkAndInitializeSetting(settings.timerbar, "fontyoffset", 0);
checkAndInitializeSetting(settings.timerbar, "staticfontsize", false);
checkAndInitializeSetting(settings.timerbar, "fontsize", 10);
// DOT TIMER SETTINGS
checkAndInitializeSetting(settings, "dottimerbar", {});
checkAndInitializeSetting(settings.dottimerbar, "enabled", true);
checkAndInitializeSetting(settings.dottimerbar, "hideoutofcombat", false);
checkAndInitializeSetting(
settings.dottimerbar,
"hidewhendroppedoff",
false,
);
checkAndInitializeSetting(settings.dottimerbar, "textenabled", true);
checkAndInitializeSetting(settings.dottimerbar, "imageenabled", true);
checkAndInitializeSetting(settings.dottimerbar, "ttsenabled", false);
checkAndInitializeSetting(settings.dottimerbar, "multidotenabled", true);
checkAndInitializeSetting(settings.dottimerbar, "growdirection", 1);
checkAndInitializeSetting(settings.dottimerbar, "padding", 20);
checkAndInitializeSetting(settings.dottimerbar, "scale", 1);
checkAndInitializeSetting(settings.dottimerbar, "rotation", 0);
checkAndInitializeSetting(settings.dottimerbar, "x", 30);
checkAndInitializeSetting(settings.dottimerbar, "y", 50);
checkAndInitializeSetting(settings.dottimerbar, "font", "Arial");
checkAndInitializeSetting(settings.dottimerbar, "fontxoffset", 0);
checkAndInitializeSetting(settings.dottimerbar, "fontyoffset", 0);
checkAndInitializeSetting(settings.dottimerbar, "staticfontsize", false);
checkAndInitializeSetting(settings.dottimerbar, "fontsize", 10);
// BUFF TIMER SETTINGS
checkAndInitializeSetting(settings, "bufftimerbar", {});
checkAndInitializeSetting(settings.bufftimerbar, "enabled", true);
checkAndInitializeSetting(settings.bufftimerbar, "hideoutofcombat", false);
checkAndInitializeSetting(
settings.bufftimerbar,
"hidewhendroppedoff",
false,
);
checkAndInitializeSetting(settings.bufftimerbar, "textenabled", true);
checkAndInitializeSetting(settings.bufftimerbar, "imageenabled", true);
checkAndInitializeSetting(settings.bufftimerbar, "ttsenabled", false);
checkAndInitializeSetting(settings.bufftimerbar, "growdirection", 1);
checkAndInitializeSetting(settings.bufftimerbar, "padding", 20);
checkAndInitializeSetting(settings.bufftimerbar, "scale", 1);
checkAndInitializeSetting(settings.bufftimerbar, "rotation", 0);
checkAndInitializeSetting(settings.bufftimerbar, "x", 30);
checkAndInitializeSetting(settings.bufftimerbar, "y", 100);
checkAndInitializeSetting(settings.bufftimerbar, "font", "Arial");
checkAndInitializeSetting(settings.bufftimerbar, "fontxoffset", 0);
checkAndInitializeSetting(settings.bufftimerbar, "fontyoffset", 0);
checkAndInitializeSetting(settings.bufftimerbar, "staticfontsize", false);
checkAndInitializeSetting(settings.bufftimerbar, "fontsize", 10);
// STACKBAR SETTINGS
checkAndInitializeSetting(settings, "stacksbar", {});
checkAndInitializeSetting(settings.stacksbar, "enabled", true);
checkAndInitializeSetting(settings.stacksbar, "hideoutofcombat", false);
checkAndInitializeSetting(
settings.stacksbar,
"color",
"--filter-bright-red",
);
checkAndInitializeSetting(settings.stacksbar, "scale", 1);
checkAndInitializeSetting(settings.stacksbar, "x", 30);
checkAndInitializeSetting(settings.stacksbar, "y", 170);
// RAIDBUFF SETTINGS
checkAndInitializeSetting(settings, "raidbuffs", {});
checkAndInitializeSetting(settings.raidbuffs, "enabled", true);
checkAndInitializeSetting(settings.raidbuffs, "ttsenabled", false);
checkAndInitializeSetting(settings.raidbuffs, "alwaysshow", true);
checkAndInitializeSetting(settings.raidbuffs, "hideoutofcombat", false);
checkAndInitializeSetting(settings.raidbuffs, "hidewhensolo", false);
checkAndInitializeSetting(settings.raidbuffs, "orderbypartymember", true);
checkAndInitializeSetting(settings.raidbuffs, "growleft", false);
checkAndInitializeSetting(settings.raidbuffs, "padding", 0);
checkAndInitializeSetting(settings.raidbuffs, "scale", 1);
checkAndInitializeSetting(settings.raidbuffs, "columns", 8);
checkAndInitializeSetting(settings.raidbuffs, "x", 30);
checkAndInitializeSetting(settings.raidbuffs, "y", 240);
checkAndInitializeSetting(settings.raidbuffs, "font", "Arial");
checkAndInitializeSetting(settings.raidbuffs, "fontxoffset", 0);
checkAndInitializeSetting(settings.raidbuffs, "fontyoffset", 0);
checkAndInitializeSetting(settings.raidbuffs, "staticfontsize", false);
checkAndInitializeSetting(settings.raidbuffs, "fontsize", 24);
checkAndInitializeSetting(settings.raidbuffs, "durationoutline", true);
checkAndInitializeSetting(settings.raidbuffs, "cooldownoutline", true);
checkAndInitializeSetting(settings.raidbuffs, "durationbold", true);
checkAndInitializeSetting(settings.raidbuffs, "cooldownbold", true);
checkAndInitializeSetting(settings.raidbuffs, "durationcolor", "#FFA500");
checkAndInitializeSetting(settings.raidbuffs, "cooldowncolor", "#FFFFFF");
checkAndInitializeSetting(
settings.raidbuffs,
"durationoutlinecolor",
"#000000",
);
checkAndInitializeSetting(
settings.raidbuffs,
"cooldownoutlinecolor",
"#000000",
);
// MITIGATION SETTINGS
checkAndInitializeSetting(settings, "mitigation", {});
checkAndInitializeSetting(settings.mitigation, "enabled", true);
checkAndInitializeSetting(settings.mitigation, "ttsenabled", false);
checkAndInitializeSetting(settings.mitigation, "alwaysshow", true);
checkAndInitializeSetting(settings.mitigation, "hideoutofcombat", false);
checkAndInitializeSetting(settings.mitigation, "hidewhensolo", false);
checkAndInitializeSetting(settings.mitigation, "growleft", false);
checkAndInitializeSetting(settings.mitigation, "padding", 0);
checkAndInitializeSetting(settings.mitigation, "scale", 1);
checkAndInitializeSetting(settings.mitigation, "columns", 8);
checkAndInitializeSetting(settings.mitigation, "x", 30);
checkAndInitializeSetting(settings.mitigation, "y", 280);
checkAndInitializeSetting(settings.mitigation, "font", "Arial");
checkAndInitializeSetting(settings.mitigation, "fontxoffset", 0);
checkAndInitializeSetting(settings.mitigation, "fontyoffset", 0);
checkAndInitializeSetting(settings.mitigation, "staticfontsize", false);
checkAndInitializeSetting(settings.mitigation, "fontsize", 24);
checkAndInitializeSetting(settings.mitigation, "durationoutline", true);
checkAndInitializeSetting(settings.mitigation, "cooldownoutline", true);
checkAndInitializeSetting(settings.mitigation, "durationbold", true);
checkAndInitializeSetting(settings.mitigation, "cooldownbold", true);
checkAndInitializeSetting(settings.mitigation, "durationcolor", "#FFA500");
checkAndInitializeSetting(settings.mitigation, "cooldowncolor", "#FFFFFF");
checkAndInitializeSetting(
settings.mitigation,
"durationoutlinecolor",
"#000000",
);
checkAndInitializeSetting(
settings.mitigation,
"cooldownoutlinecolor",
"#000000",
);
// PARTY COOLDOWN SETTINGS
checkAndInitializeSetting(settings, "party", {});
checkAndInitializeSetting(settings.party, "enabled", true);
checkAndInitializeSetting(settings.party, "ttsenabled", false);
checkAndInitializeSetting(settings.party, "alwaysshow", true);
checkAndInitializeSetting(settings.party, "hideoutofcombat", false);
checkAndInitializeSetting(settings.party, "hidewhensolo", false);
checkAndInitializeSetting(settings.party, "growleft", false);
checkAndInitializeSetting(settings.party, "padding", 0);
checkAndInitializeSetting(settings.party, "scale", 0.8);
checkAndInitializeSetting(settings.party, "x", 30);
checkAndInitializeSetting(settings.party, "y", 320);
checkAndInitializeSetting(settings.party, "font", "Arial");
checkAndInitializeSetting(settings.party, "fontxoffset", 0);
checkAndInitializeSetting(settings.party, "fontyoffset", 0);
checkAndInitializeSetting(settings.party, "staticfontsize", false);
checkAndInitializeSetting(settings.party, "fontsize", 24);
checkAndInitializeSetting(settings.party, "durationoutline", true);
checkAndInitializeSetting(settings.party, "cooldownoutline", true);
checkAndInitializeSetting(settings.party, "durationbold", true);
checkAndInitializeSetting(settings.party, "cooldownbold", true);
checkAndInitializeSetting(settings.party, "durationcolor", "#FFA500");
checkAndInitializeSetting(settings.party, "cooldowncolor", "#FFFFFF");
checkAndInitializeSetting(
settings.party,
"durationoutlinecolor",
"#000000",
);
checkAndInitializeSetting(
settings.party,
"cooldownoutlinecolor",
"#000000",
);
// CUSTOM COOLDOWN SETTINGS
checkAndInitializeSetting(settings, "customcd", {});
checkAndInitializeSetting(settings.customcd, "abilities", []);
checkAndInitializeSetting(settings.customcd, "enabled", true);
checkAndInitializeSetting(settings.customcd, "ttsenabled", false);
checkAndInitializeSetting(settings.customcd, "alwaysshow", true);
checkAndInitializeSetting(settings.customcd, "hideoutofcombat", false);
checkAndInitializeSetting(settings.customcd, "hidewhensolo", false);
checkAndInitializeSetting(settings.customcd, "growleft", false);
checkAndInitializeSetting(settings.customcd, "padding", 0);
checkAndInitializeSetting(settings.customcd, "scale", 1);
checkAndInitializeSetting(settings.customcd, "columns", 8);
checkAndInitializeSetting(settings.customcd, "x", 30);
checkAndInitializeSetting(settings.customcd, "y", 320);
checkAndInitializeSetting(settings.customcd, "font", "Arial");
checkAndInitializeSetting(settings.customcd, "fontxoffset", 0);
checkAndInitializeSetting(settings.customcd, "fontyoffset", 0);
checkAndInitializeSetting(settings.customcd, "staticfontsize", false);
checkAndInitializeSetting(settings.customcd, "fontsize", 24);
checkAndInitializeSetting(settings.customcd, "durationoutline", true);
checkAndInitializeSetting(settings.customcd, "cooldownoutline", true);
checkAndInitializeSetting(settings.customcd, "durationbold", true);
checkAndInitializeSetting(settings.customcd, "cooldownbold", true);
checkAndInitializeSetting(settings.customcd, "durationcolor", "#FFA500");
checkAndInitializeSetting(settings.customcd, "cooldowncolor", "#FFFFFF");
checkAndInitializeSetting(
settings.customcd,
"durationoutlinecolor",
"#000000",
);
checkAndInitializeSetting(
settings.customcd,
"cooldownoutlinecolor",
"#000000",
);
return settings;
}
function checkAndInsertMissingJobs(settingsObject) {
// Check for missing jobs
if (!settingsObject.includes("SGE")) {
// Add missing SGE job
settingsObject.splice(settingsObject.indexOf("AST") + 1, 0, "SGE");
}
if (!settingsObject.includes("RPR")) {
// Add missing RPR job
settingsObject.splice(settingsObject.indexOf("SAM") + 1, 0, "RPR");
}
}
<file_sep>/scripts/index.js
// ZeffUI globals
/* global abilityList, jobList, regexList, language, zone_info, content_type, checkAndInitializeDefaultSettingsObject */
// External Globals
/* global addOverlayListener, startOverlayEvents, interact, callOverlayHandler */
// UI related global variables
let ui = {
locked: true,
actlocked: false,
gridshown: false,
dragPosition: {},
activeSettingsWindow: null,
labels: {},
};
// Global variables for maintaining gamestate and settings
let currentSettings = null;
let gameState = {
inCombat: false,
blockRuinGained: false,
player: null,
playerPrevious: null,
playerTags: {},
playerPets: [],
currentrole: null,
zone: {},
partyList: [],
rawPartyList: [],
stats: {
skillSpeed: 0,
spellSpeed: 0,
stacks: 0,
maxStacks: 0,
},
previous_MP: 0,
};
// Global variables for maintaining active timers and elements that get reused
let activeElements = {
dotBars: new Map(),
buffBars: new Map(),
raidBuffs: new Map(),
mitigations: new Map(),
partyCooldowns: new Map(),
customCooldowns: new Map(),
countdowns: new Map(),
currentCharges: new Map(),
tts: new Map(),
ttsElements: new Map(),
ttsLastCalled: new Map(),
};
/* prettier-ignore */
const GAME_DATA = {
CONTENT_TYPE: [],
// MP Data copied from cactbot constants: https://github.com/quisquous/cactbot/blob/ecfa4665ba7652e9d4a278e360cc2aadab54bb5a/ui/jobs/constants.ts
EFFECT_TICK: 3.0,
MP_DATA: {
normal: 0.06,
combat: 0.02,
umbral_1: 0.30,
umbral_2: 0.45,
umbral_3: 0.60,
tick: 3.0
},
// Comes from https://www.akhmorning.com/allagan-studies/stats/speed/, will need to be updated when Endwalker comes out
SPEED_LOOKUP: new Map(
[
[1, 56], [2, 57], [3, 60], [4, 62], [5, 65], [6, 68], [7, 70], [8, 73], [9, 76], [10, 78],
[11, 82], [12, 85], [13, 89], [14, 93], [15, 96], [16, 100], [17, 104], [18, 109], [19, 113], [20, 116],
[21, 122], [22, 127], [23, 133], [24, 138], [25, 144], [26, 150], [27, 155], [28, 162], [29, 168], [30, 173],
[31, 181], [32, 188], [33, 194], [34, 202], [35, 209], [36, 215], [37, 223], [38, 229], [39, 236], [40, 244],
[41, 253], [42, 263], [43, 272], [44, 283], [45, 292], [46, 302], [47, 311], [48, 322], [49, 331], [50, 341],
[51, 342], [52, 344], [53, 345], [54, 346], [55, 347], [56, 349], [57, 350], [58, 351], [59, 352], [60, 354],
[61, 355], [62, 356], [63, 357], [64, 358], [65, 359], [66, 360], [67, 361], [68, 362], [69, 363], [70, 364],
[71, 365], [72, 366], [73, 367], [74, 368], [75, 370], [76, 372], [77, 374], [78, 376], [79, 378], [80, 380],
[81, 382], [82, 384], [83, 386], [84, 388], [85, 390], [86, 392], [87, 394], [88, 396], [89, 398], [90, 400]
]),
ZONE_INFO: []
};
const UPDATE_INTERVAL = 10;
// Add OverlayListeners, some events are found in Cactbot, others in OverlayPlugin itself.
// Overlay Plugin Events: https://ngld.github.io/OverlayPlugin/devs/event_types and https://github.com/ngld/OverlayPlugin/tree/0da98d8045ec220d6c3d64f4dcf0edd3cd44a8f3/OverlayPlugin.Core/EventSources
// Cactbot Events: https://github.com/quisquous/cactbot/blob/8615b69424360f69892bf81907d9cbdf3e752592/plugin/CactbotEventSource/CactbotEventSource.cs
addOverlayListener("onPlayerChangedEvent", (e) => onPlayerChangedEvent(e));
addOverlayListener("onLogEvent", (e) => onLogEvent(e));
addOverlayListener("onPartyWipe", () => onPartyWipe());
addOverlayListener("onInCombatChangedEvent", (e) => onInCombatChangedEvent(e));
addOverlayListener("ChangeZone", (e) => onChangeZone(e));
addOverlayListener("PartyChanged", (e) => onPartyChanged(e));
$(document).ready(() => {
startZeffUI();
});
async function startZeffUI() {
initializeContentZoneImports();
startOverlayEvents();
await loadSettings();
generateJobStacks();
toggleHideOutOfCombatElements();
waitFor("language", function () {
if (gameState.player === null) {
window
.callOverlayHandler({ call: "getCombatants" })
.then((e) => getPlayerChangedEventFromCombatants(e));
}
});
console.log("ZeffUI fully loaded.");
}
// Imports zone information constants into GAME_DATA for checking if PvP is in effect.
function initializeContentZoneImports() {
// Content manually placed over from https://github.com/quisquous/cactbot/blob/main/resources/zone_info.ts because this project doesn't support typescript
Object.assign(GAME_DATA.CONTENT_TYPE, content_type);
// Content manually placed over from https://github.com/quisquous/cactbot/blob/main/resources/content_type.ts because this project doesn't support typescript
Object.assign(GAME_DATA.ZONE_INFO, zone_info);
if (gameState.zone !== undefined) checkAndSetZoneInfo(gameState.zone.id);
}
// SETTINGS
// Legacy location for the settings, left in so people who hasn't played for a long time still have their settings. Also functions as a backup location for settings.
function initializeSettings() {
if (localStorage.getItem("settings") !== null) {
return JSON.parse(localStorage.getItem("settings"));
} else {
return {};
}
}
// Load settings through OverlayPlugin, these settings are stored in %appdata%\Advanced Combat Tracker\Config\RainbowMage.OverlayPlugin.config.json
async function loadSettings() {
let settings = {};
settings = await callOverlayHandler({ call: "loadData", key: "zeffUI" });
if (settings == null) {
settings = initializeSettings();
} else if (settings.data === undefined) {
settings = initializeSettings();
} else if (settings.data === null) {
settings = initializeSettings();
} else {
settings = settings.data;
}
settings = await checkAndInitializeDefaultSettingsObject(settings);
if (document.getElementById("language") === null) {
getScript(`data/language/${settings.language}.js`, () => {
loadContextMenu();
let reminder = document.getElementById("lock-overlay-reminder");
reminder.textContent = language.find(
(x) => x.id === "lockoverlay",
).string;
reminder.style.display = "none";
});
} else {
document.getElementById(
"language",
).src = `data/language/${settings.language}.js`;
}
// Check and load profiles
if (settings.profiles.profiles.length !== 0) {
let profiles = settings.profiles;
if (profiles.currentprofile) {
settings = JSON.parse(
JSON.stringify(profiles.profiles[profiles.currentprofile]),
);
settings = await checkAndInitializeDefaultSettingsObject(settings);
settings.profiles = profiles;
}
}
currentSettings = settings;
setLoadedElements();
saveSettings();
}
function setLoadedElements() {
let head = document.getElementsByTagName("head")[0];
let settings = currentSettings;
if (document.getElementById("customcss"))
document.getElementById("customcss").remove();
if (settings.general.customcss) {
let style = document.createElement("style");
style.id = "customcss";
style.textContent = settings.general.customcss;
head.appendChild(style);
}
document.documentElement.style.setProperty("--defaultFont", settings.font);
if (document.getElementById("skin") === null) {
let link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = `skins/${settings.skin}/styles/resources.css`;
link.id = "skin";
head.append(link);
} else {
document.getElementById(
"skin",
).href = `skins/${settings.skin}/styles/resources.css`;
}
// HEALTHBAR SETTINGS
let healthbar = document.getElementById("health-bar");
settings.healthbar.enabled
? (healthbar.style.display = "")
: (healthbar.style.display = "none");
healthbar.style.setProperty(
"--healthBarColor",
`var(${settings.healthbar.color})`,
);
healthbar.style.width = settings.healthbar.scale * 160;
healthbar.style.height = settings.healthbar.scale * 15;
healthbar.style.setProperty("--healthFont", settings.healthbar.font);
healthbar.style.transformOrigin = "top left";
ui.dragPosition["health-bar"] = {
x: settings.healthbar.x,
y: settings.healthbar.y,
};
healthbar.classList.add("ltr");
healthbar.style.transform = `translate(${settings.healthbar.x}px, ${
settings.healthbar.y
}px)${
settings.healthbar.rotation
? ` rotate(${settings.healthbar.rotation}deg`
: ""
}`;
healthbar.setAttribute(
"data-label",
currentSettings.healthbar.textenabled ? ui.labels.health : "",
);
// MANABAR SETTINGS
let manabar = document.getElementById("mana-bar");
settings.manabar.enabled
? (manabar.style.display = "")
: (manabar.style.display = "none");
manabar.style.setProperty(
"--manaBarColor",
`var(${settings.manabar.color})`,
);
manabar.style.width = settings.manabar.scale * 160;
manabar.style.height = settings.manabar.scale * 15;
manabar.style.setProperty("--manaFont", settings.manabar.font);
manabar.style.transformOrigin = "top left";
ui.dragPosition["mana-bar"] = {
x: settings.manabar.x,
y: settings.manabar.y,
};
manabar.classList.add("ltr");
manabar.style.transform = `translate(${settings.manabar.x}px, ${
settings.manabar.y
}px)${
settings.manabar.rotation
? ` rotate(${settings.manabar.rotation}deg`
: ""
}`;
manabar.setAttribute(
"data-label",
currentSettings.manabar.textenabled ? ui.labels.mana : "",
);
// MP TICKER SETTINGS
let mpticker = document.getElementById("mp-ticker-bar");
settings.mpticker.enabled
? (mpticker.style.display = "")
: (mpticker.style.display = "none");
mpticker.style.setProperty(
"--mptickerColor",
`var(${settings.mpticker.color})`,
);
mpticker.style.width = settings.mpticker.scale * 160;
mpticker.style.height = settings.mpticker.scale * 15;
mpticker.style.transformOrigin = "top left";
ui.dragPosition["mp-ticker-bar"] = {
x: settings.mpticker.x,
y: settings.mpticker.y,
};
mpticker.classList.add("ltr");
mpticker.style.transform = `translate(${settings.mpticker.x}px, ${
settings.mpticker.y
}px)${
settings.mpticker.rotation
? ` rotate(${settings.mpticker.rotation}deg`
: ""
}`;
// DOT TICKER SETTINGS
let dotticker = document.getElementById("dot-ticker-bar");
dotticker.style.display = settings.dotticker.enabled ? "block" : "none";
dotticker.style.setProperty(
"--dottickerColor",
`var(${settings.dotticker.color})`,
);
dotticker.style.width = settings.dotticker.scale * 160;
dotticker.style.height = settings.dotticker.scale * 15;
dotticker.style.transformOrigin = "top left";
ui.dragPosition["dot-ticker-bar"] = {
x: settings.dotticker.x,
y: settings.dotticker.y,
};
dotticker.classList.add("ltr");
dotticker.style.transform = `translate(${settings.dotticker.x}px, ${
settings.dotticker.y
}px)${
settings.dotticker.rotation
? ` rotate(${settings.dotticker.rotation}deg`
: ""
}`;
// HOT TICKER SETTINGS
let hotticker = document.getElementById("hot-ticker-bar");
hotticker.style.display = settings.hotticker.enabled ? "block" : "none";
hotticker.style.setProperty(
"--hottickerColor",
`var(${settings.hotticker.color})`,
);
hotticker.style.width = settings.hotticker.scale * 160;
hotticker.style.height = settings.hotticker.scale * 15;
hotticker.style.transformOrigin = "top left";
ui.dragPosition["hot-ticker-bar"] = {
x: settings.hotticker.x,
y: settings.hotticker.y,
};
hotticker.classList.add("ltr");
hotticker.style.transform = `translate(${settings.hotticker.x}px, ${
settings.hotticker.y
}px)${
settings.hotticker.rotation
? ` rotate(${settings.hotticker.rotation}deg`
: ""
}`;
// PULL TIMER SETTINGS
let timerbar = document.getElementById("timer-bar");
timerbar.style.setProperty(
"--pulltimerBarColor",
`var(${settings.timerbar.color})`,
);
timerbar.style.width = settings.timerbar.scale * 160;
timerbar.style.height = settings.timerbar.scale * 15;
timerbar.style.setProperty("--timerFont", settings.timerbar.font);
timerbar.style.transformOrigin = "top left";
ui.dragPosition["timer-bar"] = {
x: settings.timerbar.x,
y: settings.timerbar.y,
};
timerbar.classList.add("ltr");
timerbar.style.transform = `translate(${settings.timerbar.x}px, ${
settings.timerbar.y
}px)${
settings.timerbar.rotation
? ` rotate(${settings.timerbar.rotation}deg`
: ""
}`;
// DOT TIMER SETTINGS
let dottimerbar = document.getElementById("dot-timer-bar");
dottimerbar.style.width = settings.dottimerbar.scale * 160;
dottimerbar.style.height = settings.dottimerbar.scale * 15;
dottimerbar.style.setProperty("--dotFont", settings.dottimerbar.font);
let dotbar = document.getElementById("dot-bar");
dotbar.style.transform = `rotate(${settings.dottimerbar.rotation}deg)`;
dotbar.style.transformOrigin = "center";
ui.dragPosition["dot-timer-bar"] = {
x: settings.dottimerbar.x,
y: settings.dottimerbar.y,
};
dottimerbar.classList.add("ltr");
dottimerbar.style.transform = `translate(${settings.dottimerbar.x}px, ${settings.dottimerbar.y}px)`;
// BUFF TIMER SETTINGS
let bufftimerbar = document.getElementById("buff-timer-bar");
bufftimerbar.style.width = settings.bufftimerbar.scale * 160;
bufftimerbar.style.height = settings.bufftimerbar.scale * 15;
bufftimerbar.style.setProperty("--buffFont", settings.bufftimerbar.font);
let buffbar = document.getElementById("buff-bar");
buffbar.style.transform = `rotate(${settings.bufftimerbar.rotation}deg)`;
buffbar.style.transformOrigin = "center";
ui.dragPosition["buff-timer-bar"] = {
x: settings.bufftimerbar.x,
y: settings.bufftimerbar.y,
};
bufftimerbar.classList.add("ltr");
bufftimerbar.style.transform = `translate(${settings.bufftimerbar.x}px, ${settings.bufftimerbar.y}px)`;
// STACKBAR SETTINGS
let stacksbar = document.getElementById("stacks-bar");
stacksbar.style.width = settings.stacksbar.scale * (4 * 25);
stacksbar.style.height = settings.stacksbar.scale * 21;
let stackbgs = document.querySelectorAll("[id^=stacks-background]");
Array.prototype.forEach.call(stackbgs, (stack) => {
stack.style.marginLeft = 0 - settings.stacksbar.scale * 4;
});
stacksbar.style.setProperty(
"--stacksColor",
`var(${settings.stacksbar.color})`,
);
ui.dragPosition["stacks-bar"] = {
x: settings.stacksbar.x,
y: settings.stacksbar.y,
};
stacksbar.classList.add("ltr");
stacksbar.style.transform = `translate(${settings.stacksbar.x}px, ${settings.stacksbar.y}px) scale(${settings.stacksbar.scale})`;
stacksbar.style.display = settings.stacksbar.enabled
? "block !important"
: "none !important";
// RAIDBUFF SETTINGS
let raidbuffs = document.getElementById("raid-buffs-bar");
raidbuffs.style.display = settings.raidbuffs.enabled ? "block" : "none";
raidbuffs.style.display = settings.raidbuffs.hidewhensolo
? "none"
: "block";
raidbuffs.style.fontFamily = settings.raidbuffs.font;
ui.dragPosition["raid-buffs-bar"] = {
x: settings.raidbuffs.x,
y: settings.raidbuffs.y,
};
raidbuffs.classList.remove("ltr", "rtl");
raidbuffs.classList.add(`${settings.raidbuffs.growleft ? "rtl" : "ltr"}`);
raidbuffs.style.transform = `translate(${settings.raidbuffs.x}px, ${settings.raidbuffs.y}px)`;
// MITIGATION SETTINGS
let mitigation = document.getElementById("mitigation-bar");
mitigation.style.display = settings.mitigation.enabled ? "block" : "none";
mitigation.style.display = settings.mitigation.hidewhensolo
? "none"
: "block";
mitigation.style.fontFamily = settings.mitigation.font;
ui.dragPosition["mitigation-bar"] = {
x: settings.mitigation.x,
y: settings.mitigation.y,
};
mitigation.classList.remove("ltr", "rtl");
mitigation.classList.add(`${settings.mitigation.growleft ? "rtl" : "ltr"}`);
mitigation.style.transform = `translate(${settings.mitigation.x}px, ${settings.mitigation.y}px)`;
// PARTY COOLDOWN SETTINGS
let party = document.getElementById("party-bar");
party.style.display = settings.party.enabled ? "block" : "none";
party.style.display = settings.party.hidewhensolo ? "none" : "block";
party.style.fontFamily = settings.party.font;
ui.dragPosition["party-bar"] = {
x: settings.party.x,
y: settings.party.y,
};
party.classList.remove("ltr", "rtl");
party.classList.add(`${settings.party.growleft ? "rtl" : "ltr"}`);
party.style.transform = `translate(${settings.party.x}px, ${settings.party.y}px)`;
// CUSTOM COOLDOWN SETTINGS
let customcd = document.getElementById("customcd-bar");
customcd.style.display = settings.customcd.enabled ? "block" : "none";
customcd.style.display = settings.customcd.hidewhensolo ? "none" : "block";
customcd.style.fontFamily = settings.customcd.font;
ui.dragPosition["customcd-bar"] = {
x: settings.customcd.x,
y: settings.customcd.y,
};
customcd.classList.remove("ltr", "rtl");
customcd.classList.add(`${settings.customcd.growleft ? "rtl" : "ltr"}`);
customcd.style.transform = `translate(${settings.customcd.x}px, ${settings.customcd.y}px)`;
}
// Parse all current locations of components and then save them in localStorage (legacy) and OverlayPlugin located in %appdata%\Advanced Combat Tracker\Config\RainbowMage.OverlayPlugin.config.json
async function saveSettings() {
currentSettings.healthbar.x = parseInt(ui.dragPosition["health-bar"].x);
currentSettings.healthbar.y = parseInt(ui.dragPosition["health-bar"].y);
let healthbar = document.getElementById("health-bar");
healthbar.style.textAlign = currentSettings.healthbar.align;
switch (currentSettings.healthbar.align) {
case "left":
healthbar.style.setProperty(
"--healthFontX",
currentSettings.healthbar.scale * 8 +
currentSettings.healthbar.fontxoffset,
);
break;
case "center":
healthbar.style.setProperty(
"--healthFontX",
0 + currentSettings.healthbar.fontxoffset,
);
break;
case "right":
healthbar.style.setProperty(
"--healthFontX",
-Math.abs(
currentSettings.healthbar.scale * 8 +
currentSettings.healthbar.fontxoffset,
),
);
break;
default:
healthbar.style.setProperty(
"--healthFontX",
currentSettings.healthbar.scale * 8 +
currentSettings.healthbar.fontxoffset,
);
}
healthbar.style.setProperty(
"--healthFontSize",
currentSettings.healthbar.staticfontsize
? currentSettings.healthbar.fontsize
: currentSettings.healthbar.scale * 10,
);
healthbar.style.setProperty(
"--healthFontY",
currentSettings.healthbar.scale * -14 +
currentSettings.healthbar.fontyoffset,
);
currentSettings.manabar.x = parseInt(ui.dragPosition["mana-bar"].x);
currentSettings.manabar.y = parseInt(ui.dragPosition["mana-bar"].y);
let manabar = document.getElementById("mana-bar");
manabar.style.textAlign = currentSettings.manabar.align;
switch (currentSettings.manabar.align) {
case "left":
manabar.style.setProperty(
"--manaFontX",
currentSettings.manabar.scale * 8 +
currentSettings.manabar.fontxoffset,
);
break;
case "center":
manabar.style.setProperty(
"--manaFontX",
0 + currentSettings.manabar.fontxoffset,
);
break;
case "right":
manabar.style.setProperty(
"--manaFontX",
-Math.abs(
currentSettings.manabar.scale * 8 +
currentSettings.manabar.fontxoffset,
),
);
break;
default:
manabar.style.setProperty(
"--manaFontX",
currentSettings.manabar.scale * 8 +
currentSettings.manabar.fontxoffset,
);
}
manabar.style.setProperty(
"--manaFontSize",
currentSettings.manabar.staticfontsize
? currentSettings.manabar.fontsize
: currentSettings.manabar.scale * 10,
);
manabar.style.setProperty(
"--manaFontY",
currentSettings.manabar.scale * -14 +
currentSettings.manabar.fontyoffset,
);
currentSettings.mpticker.x = parseInt(ui.dragPosition["mp-ticker-bar"].x);
currentSettings.mpticker.y = parseInt(ui.dragPosition["mp-ticker-bar"].y);
currentSettings.dotticker.x = parseInt(ui.dragPosition["dot-ticker-bar"].x);
currentSettings.dotticker.y = parseInt(ui.dragPosition["dot-ticker-bar"].y);
currentSettings.hotticker.x = parseInt(ui.dragPosition["hot-ticker-bar"].x);
currentSettings.hotticker.y = parseInt(ui.dragPosition["hot-ticker-bar"].y);
currentSettings.timerbar.x = parseInt(ui.dragPosition["timer-bar"].x);
currentSettings.timerbar.y = parseInt(ui.dragPosition["timer-bar"].y);
let timerbar = document.getElementById("timer-bar");
timerbar.style.setProperty(
"--timerFontSize",
currentSettings.timerbar.staticfontsize
? currentSettings.timerbar.fontsize
: currentSettings.timerbar.scale * 10,
);
timerbar.style.setProperty(
"--timerFontX",
currentSettings.timerbar.scale * 8 +
currentSettings.timerbar.fontxoffset,
);
timerbar.style.setProperty(
"--timerFontY",
currentSettings.timerbar.scale * -14 +
currentSettings.timerbar.fontyoffset,
);
currentSettings.dottimerbar.x = parseInt(
ui.dragPosition["dot-timer-bar"].x,
);
currentSettings.dottimerbar.y = parseInt(
ui.dragPosition["dot-timer-bar"].y,
);
let dottimerbar = document.getElementById("dot-timer-bar");
dottimerbar.style.setProperty(
"--dotFontSize",
currentSettings.dottimerbar.staticfontsize
? currentSettings.dottimerbar.fontsize
: currentSettings.dottimerbar.scale * 10,
);
dottimerbar.style.setProperty(
"--dotFontX",
currentSettings.dottimerbar.scale * 8 +
currentSettings.dottimerbar.fontxoffset,
);
dottimerbar.style.setProperty(
"--dotFontY",
currentSettings.dottimerbar.scale * -14 +
currentSettings.dottimerbar.fontyoffset,
);
currentSettings.bufftimerbar.x = parseInt(
ui.dragPosition["buff-timer-bar"].x,
);
currentSettings.bufftimerbar.y = parseInt(
ui.dragPosition["buff-timer-bar"].y,
);
let bufftimerbar = document.getElementById("buff-timer-bar");
bufftimerbar.style.setProperty(
"--buffFontSize",
currentSettings.bufftimerbar.staticfontsize
? currentSettings.bufftimerbar.fontsize
: currentSettings.bufftimerbar.scale * 10,
);
bufftimerbar.style.setProperty(
"--buffFontX",
currentSettings.bufftimerbar.scale * 8 +
currentSettings.bufftimerbar.fontxoffset,
);
bufftimerbar.style.setProperty(
"--buffFontY",
currentSettings.bufftimerbar.scale * -14 +
currentSettings.bufftimerbar.fontyoffset,
);
currentSettings.stacksbar.x = parseInt(ui.dragPosition["stacks-bar"].x);
currentSettings.stacksbar.y = parseInt(ui.dragPosition["stacks-bar"].y);
currentSettings.raidbuffs.x = parseInt(ui.dragPosition["raid-buffs-bar"].x);
currentSettings.raidbuffs.y = parseInt(ui.dragPosition["raid-buffs-bar"].y);
currentSettings.mitigation.x = parseInt(
ui.dragPosition["mitigation-bar"].x,
);
currentSettings.mitigation.y = parseInt(
ui.dragPosition["mitigation-bar"].y,
);
currentSettings.customcd.x = parseInt(ui.dragPosition["customcd-bar"].x);
currentSettings.customcd.y = parseInt(ui.dragPosition["customcd-bar"].y);
currentSettings.party.x = parseInt(ui.dragPosition["party-bar"].x);
currentSettings.party.y = parseInt(ui.dragPosition["party-bar"].y);
if (currentSettings.profiles.currentprofile) {
let saveSettings = JSON.parse(JSON.stringify(currentSettings));
delete saveSettings.profiles;
currentSettings.profiles.profiles[
currentSettings.profiles.currentprofile
] = saveSettings;
}
await callOverlayHandler({
call: "saveData",
key: "zeffUI",
data: currentSettings,
});
localStorage.setItem("settings", JSON.stringify(currentSettings));
}
// UI Elements and functions
// Generate Profile options for context menu
function generateProfileItems() {
let profileItems = {};
for (let profile in currentSettings.profiles.profiles) {
profileItems[`profile_${profile}`] = {};
profileItems[`profile_${profile}`].name = profile;
}
return profileItems;
}
// Opens settings
function handleSettings() {
// This way of opening the settings window and propegate the made changes to the settings is a bit scuffed but currently can't think of a better way.
if (ui.activeSettingsWindow === null) {
openSettingsWindow();
} else {
if (
confirm(
language.find((x) => x.id === "activesettingswindow").string,
)
) {
ui.activeSettingsWindow.close();
ui.activeSettingsWindow = null;
openSettingsWindow();
}
}
}
// Context menu whenever someone rightclicks any UI component
function loadContextMenu() {
$(":root").contextMenu({
selector: "body",
callback: function (key) {
switch (key) {
case "lock": {
toggleLock();
break;
}
case "grid": {
toggleGrid();
break;
}
case "reload": {
location.reload();
break;
}
case "settings": {
handleSettings();
break;
}
case "en": {
setUILanguageAndReload("en");
break;
}
case "de": {
setUILanguageAndReload("de");
break;
}
case "fr": {
setUILanguageAndReload("fr");
break;
}
case "jp": {
setUILanguageAndReload("jp");
break;
}
case "cn": {
setUILanguageAndReload("cn");
break;
}
case "kr": {
setUILanguageAndReload("kr");
break;
}
}
if (key.includes("profile_")) {
let profile = key.split("_")[1];
loadProfile(profile);
}
},
items: {
lock: {
name: language.find((x) => x.id === "lock").string,
icon: "fas fa-lock-open",
},
grid: {
name: language.find((x) => x.id === "grid").string,
icon: "fas fa-border-all",
},
reload: {
name: language.find((x) => x.id === "reload").string,
icon: "fas fa-sync-alt",
},
settings: {
name: language.find((x) => x.id === "settings").string,
icon: "fas fa-cog",
},
profiles: {
name: language.find((x) => x.id === "profiles").string,
icon: "fas fa-user",
items: generateProfileItems(),
},
fold1: {
name: language.find((x) => x.id === "language").string,
icon: "fas fa-globe-americas",
items: {
en: { name: "English (default)", icon: "en" },
de: { name: "Deutsch", icon: "de" },
fr: { name: "Français", icon: "fr" },
jp: { name: "日本語", icon: "jp" },
cn: { name: "中文", icon: "cn" },
kr: { name: "한국어", icon: "kr" },
},
},
sep1: "---------",
quit: {
name: language.find((x) => x.id === "close").string,
icon: function () {
return "context-menu-icon context-menu-icon-quit";
},
},
},
});
}
// Sets the game language, saves the current settings and reloads the UI
function setUILanguageAndReload(language) {
currentSettings.language = language;
saveSettings();
location.reload();
}
// Loads profile
function loadProfile(profileName) {
saveSettings();
currentSettings.profiles.currentprofile = profileName;
let settings = JSON.parse(
JSON.stringify(currentSettings.profiles.profiles[profileName]),
);
settings.profiles = currentSettings.profiles;
currentSettings = JSON.parse(JSON.stringify(settings));
setLoadedElements();
reloadCooldownModules();
saveSettings();
//location.reload();
}
// Opens the settings window and tries to keep track to see if it's opened, also takes OVERLAY_WS parameters into account.
function openSettingsWindow() {
let parameters = new URLSearchParams(window.location.search);
let settingsUrl = parameters.has("OVERLAY_WS")
? `settings.html?OVERLAY_WS=${parameters.get("OVERLAY_WS")}`
: "settings.html";
ui.activeSettingsWindow = window.open(settingsUrl, "zeffui_settings");
ui.activeSettingsWindow.onbeforeunload = onSettingsWindowClose;
/*
ui.activeSettingsWindow.onload = function () {
this.onbeforeunload = function () {
loadSettings().then(() => {
if (gameState.player === null) {
ui.activeSettingsWindow = null;
return;
}
location.reload();
});
};
};
*/
}
function onSettingsWindowClose() {
ui.activeSettingsWindow = null;
location.reload();
}
// Draws a grid over the whole area for easier placement. It would be better if we could make all lines consistent and not depend on placement of Overlay in OverlayPlugin
function drawGrid() {
let width = window.innerWidth;
let height = window.innerHeight;
let grid = document.getElementById("grid");
grid.width = window.innerWidth;
grid.height = window.innerHeight;
let canvasContext = grid.getContext("2d");
canvasContext.beginPath();
for (let x = 0; x <= width; x += 25) {
canvasContext.moveTo(0.5 + x, 0);
canvasContext.lineTo(0.5 + x, height);
}
for (let y = 0; y <= height; y += 25) {
canvasContext.moveTo(0, 0.5 + y);
canvasContext.lineTo(width, 0.5 + y);
}
canvasContext.strokeStyle = "black";
canvasContext.stroke();
}
function waitFor(variable, callback) {
var interval = setInterval(function () {
if (window[variable]) {
clearInterval(interval);
callback();
}
}, 200);
}
function clearGrid() {
let grid = document.getElementById("grid");
grid.width = window.innerWidth;
grid.height = window.innerHeight;
let canvasContext = grid.getContext("2d");
canvasContext.clearRect(0, 0, grid.width, grid.height);
}
// Toggles the grid on and off (and draws them on demand)
function toggleGrid() {
if (!ui.gridshown) {
drawGrid();
ui.gridshown = true;
} else {
clearGrid();
ui.gridshown = false;
}
}
// Tries to show all components available when user unlocks/locks the UI and saves the locations of all the UI components
function toggleLock() {
interact("[id$=bar]").draggable({
enabled: ui.locked,
listeners: {
move(event) {
//let settings =
ui.dragPosition[event.target.id].x += event.dx;
ui.dragPosition[event.target.id].y += event.dy;
let rotate = null;
if (event.target.style.transform.includes("rotate"))
rotate = event.target.style.transform.split("rotate").pop();
event.target.style.transform = `translate(${parseInt(
ui.dragPosition[event.target.id].x,
)}px, ${parseInt(ui.dragPosition[event.target.id].y)}px)${
rotate ? `rotate${rotate}` : ""
}`;
},
end() {
saveSettings();
},
},
});
if (ui.locked) {
if (!ui.actlocked) {
document.getElementById("lock-overlay-reminder").style.display =
"block";
}
setAndCheckTickers(true);
let timerbar = document.getElementById("timer-bar");
timerbar.style.display = "block";
timerbar.setAttribute(
"data-label",
language.find((x) => x.id === "pulltimer").string,
);
let dottimerbar = document.getElementById("dot-timer-bar");
dottimerbar.style.display = "block";
dottimerbar.setAttribute(
"data-label",
language.find((x) => x.id === "dot-anchor").string,
);
let bufftimerbar = document.getElementById("buff-timer-bar");
bufftimerbar.style.display = "block";
bufftimerbar.setAttribute(
"data-label",
language.find((x) => x.id === "buff-anchor").string,
);
let raidbuffAnchor = document.createElement("span");
raidbuffAnchor.id = "raid-buffs-anchor";
raidbuffAnchor.className = "anchor-text";
raidbuffAnchor.textContent = language.find(
(x) => x.id === "raidbuffs-anchor",
).string;
document.getElementById("raid-buffs-bar").appendChild(raidbuffAnchor);
let mitigationAnchor = document.createElement("span");
mitigationAnchor.id = "mitigation-anchor";
mitigationAnchor.className = "anchor-text";
mitigationAnchor.textContent = language.find(
(x) => x.id === "mitigation-anchor",
).string;
document.getElementById("mitigation-bar").appendChild(mitigationAnchor);
let customcdAnchor = document.createElement("span");
customcdAnchor.id = "customcd-anchor";
customcdAnchor.className = "anchor-text";
customcdAnchor.textContent = language.find(
(x) => x.id === "customcd-anchor",
).string;
document.getElementById("customcd-bar").appendChild(customcdAnchor);
let partyAnchor = document.createElement("span");
partyAnchor.id = "party-anchor";
partyAnchor.className = "anchor-text";
partyAnchor.textContent = language.find(
(x) => x.id === "party-anchor",
).string;
if (document.querySelectorAll("#party-bar>div").length === 0) {
document.getElementById("party-bar").appendChild(partyAnchor);
} else {
document.getElementById("party-row-1").appendChild(partyAnchor);
}
toggleHideWhenSoloCombatElements(true);
adjustJobStacks(2, 4, true);
if (!gameState.inCombat) {
toggleHideOutOfCombatElements();
}
ui.locked = false;
document.documentElement.style.border = "solid";
} else {
setAndCheckTickers();
document.getElementById("timer-bar").style.display = "none";
document.getElementById("dot-timer-bar").style.display = "none";
document.getElementById("buff-timer-bar").style.display = "none";
document.getElementById("buff-timer-bar").style.display = "none";
document.getElementById("raid-buffs-anchor").remove();
document.getElementById("mitigation-anchor").remove();
document.getElementById("customcd-anchor").remove();
document.getElementById("party-anchor").remove();
toggleHideWhenSoloCombatElements();
adjustJobStacks(
gameState.stats.stacks,
gameState.stats.maxStacks,
true,
);
if (!gameState.inCombat) {
toggleHideOutOfCombatElements();
}
ui.locked = true;
document.getElementById("lock-overlay-reminder").style.display = "none";
document.documentElement.style.border = "none";
}
}
// Helper functions
// Puts a color filter over a HTML5 progress bar that's colorcoded in sepia colors so the bars actually gets colored
function applyFilterColorToElement(classId, filterColor) {
let barcolors = document.getElementById("bar-colors");
let filter = `.${classId}::-webkit-progress-value { filter: var(${filterColor}); }`;
barcolors.sheet.insertRule(filter);
}
// Vanilla JS way of loading a script and getting a callback
function getScript(scriptUrl, callback) {
const script = document.createElement("script");
script.src = scriptUrl;
script.onload = callback;
document.body.appendChild(script);
}
// Gets the correct settings/elements/active components for given selector
function getSelectorProperties(selector) {
let object = {};
switch (selector) {
case "RaidBuff": {
object = {
id: "raid-buffs",
settings: currentSettings.raidbuffs,
active: activeElements.raidBuffs,
};
break;
}
case "Mitigation": {
object = {
id: "mitigation",
settings: currentSettings.mitigation,
active: activeElements.mitigations,
};
break;
}
case "Party": {
object = {
id: "party",
settings: currentSettings.party,
active: activeElements.partyCooldowns,
};
break;
}
case "CustomCooldown": {
object = {
id: "customcd",
settings: currentSettings.customcd,
active: activeElements.customCooldowns,
};
break;
}
case "Buff": {
object = {
id: "buff",
settings: currentSettings.bufftimerbar,
active: activeElements.buffBars,
};
break;
}
}
return object;
}
// Handles showing/hiding of component based on player settings and if he's in combat
function toggleHideOutOfCombatElements() {
currentSettings.healthbar.hideoutofcombat && !gameState.inCombat
? document.getElementById("health-bar").classList.add("hide-in-combat")
: document
.getElementById("health-bar")
.classList.remove("hide-in-combat");
currentSettings.manabar.hideoutofcombat && !gameState.inCombat
? document.getElementById("mana-bar").classList.add("hide-in-combat")
: document
.getElementById("mana-bar")
.classList.remove("hide-in-combat");
currentSettings.mpticker.hideoutofcombat && !gameState.inCombat
? document
.getElementById("mp-ticker-bar")
.classList.add("hide-in-combat")
: document
.getElementById("mp-ticker-bar")
.classList.remove("hide-in-combat");
currentSettings.dotticker.hideoutofcombat && !gameState.inCombat
? document
.getElementById("dot-ticker-bar")
.classList.add("hide-in-combat")
: document
.getElementById("dot-ticker-bar")
.classList.remove("hide-in-combat");
currentSettings.hotticker.hideoutofcombat && !gameState.inCombat
? document
.getElementById("hot-ticker-bar")
.classList.add("hide-in-combat")
: document
.getElementById("hot-ticker-bar")
.classList.remove("hide-in-combat");
let bufftimers = document.querySelectorAll("[id$=buff-timer]");
let bufftimerimages = document.querySelectorAll("[id$=buff-image]");
if (currentSettings.bufftimerbar.hideoutofcombat && !gameState.inCombat) {
Array.prototype.forEach.call(bufftimers, (bufftimer) => {
bufftimer.classList.add("hide-in-combat");
});
Array.prototype.forEach.call(bufftimerimages, (bufftimerimage) => {
bufftimerimage.classList.add("hide-in-combat");
});
} else {
Array.prototype.forEach.call(bufftimers, (bufftimer) => {
bufftimer.classList.remove("hide-in-combat");
});
Array.prototype.forEach.call(bufftimerimages, (bufftimerimage) => {
bufftimerimage.classList.remove("hide-in-combat");
});
}
let dottimers = document.querySelectorAll("[id$=dot-timer]");
let dottimerimages = document.querySelectorAll("[id$=dot-image]");
if (currentSettings.dottimerbar.hideoutofcombat && !gameState.inCombat) {
Array.prototype.forEach.call(dottimers, (dottimer) => {
dottimer.classList.add("hide-in-combat");
});
Array.prototype.forEach.call(dottimerimages, (dottimerimage) => {
dottimerimage.classList.add("hide-in-combat");
});
} else {
Array.prototype.forEach.call(dottimers, (dottimer) => {
dottimer.classList.remove("hide-in-combat");
});
Array.prototype.forEach.call(dottimerimages, (dottimerimage) => {
dottimerimage.classList.remove("hide-in-combat");
});
}
currentSettings.stacksbar.hideoutofcombat && !gameState.inCombat
? document.getElementById("stacks-bar").classList.add("hide-in-combat")
: document
.getElementById("stacks-bar")
.classList.remove("hide-in-combat");
currentSettings.raidbuffs.hideoutofcombat && !gameState.inCombat
? document
.getElementById("raid-buffs-bar")
.classList.add("hide-in-combat")
: document
.getElementById("raid-buffs-bar")
.classList.remove("hide-in-combat");
currentSettings.mitigation.hideoutofcombat && !gameState.inCombat
? document
.getElementById("mitigation-bar")
.classList.add("hide-in-combat")
: document
.getElementById("mitigation-bar")
.classList.remove("hide-in-combat");
currentSettings.customcd.hideoutofcombat && !gameState.inCombat
? document
.getElementById("customcd-bar")
.classList.add("hide-in-combat")
: document
.getElementById("customcd-bar")
.classList.remove("hide-in-combat");
currentSettings.party.hideoutofcombat && !gameState.inCombat
? document.getElementById("party-bar").classList.add("hide-in-combat")
: document
.getElementById("party-bar")
.classList.remove("hide-in-combat");
}
// Handles showing/hiding of component based on player settings and if he's in a party
function toggleHideWhenSoloCombatElements(toggleLock = false) {
let show = gameState.partyList.length !== 1;
if (toggleLock) show = true;
if (currentSettings.raidbuffs.hidewhensolo)
document.getElementById("raid-buffs-bar").style.display = show
? "block"
: "none";
if (currentSettings.mitigation.hidewhensolo)
document.getElementById("mitigation-bar").style.display = show
? "block"
: "none";
if (currentSettings.customcd.hidewhensolo)
document.getElementById("customcd-bar").style.display = show
? "block"
: "none";
if (currentSettings.party.hidewhensolo)
document.getElementById("party-bar").style.display = show
? "block"
: "none";
}
// UI Generation for Job Stacks
function generateJobStacks() {
let stacks = document.getElementById("stacks-bar");
let range = document.createRange();
range.selectNodeContents(stacks);
range.deleteContents();
let stackfragment = document.createDocumentFragment();
for (let i = 1; i <= 4; i++) {
let stackbg = document.createElement("div");
stackbg.id = `stacks-background-${i}`;
stackbg.classList.add("stack-background", "stack-hidden");
let stack = document.createElement("img");
stack.id = `stacks-${i}`;
stack.className = "stack-color";
stack.src = `skins/${currentSettings.skin}/images/arrow-fill-empty.png`;
stackbg.appendChild(stack);
stackfragment.appendChild(stackbg);
}
stacks.appendChild(stackfragment);
}
// Check ticker settings and set the correct properties
function setAndCheckTickers(setAnchor = false) {
let tickerTypes = ["mp", "dot", "hot"];
for (let tickerType of tickerTypes) {
let tickerBar = document.getElementById(`${tickerType}-ticker-bar`);
if (setAnchor) {
tickerBar.style.display = "block";
tickerBar.setAttribute(
"data-label",
language.find((x) => x.id === `${tickerType}ticker`).string,
);
} else {
tickerBar.style.display = "none";
tickerBar.setAttribute("data-label", "");
}
if (currentSettings[`${tickerType}ticker`].enabled) {
if (currentSettings[`${tickerType}ticker`].specificjobsenabled) {
if (
currentSettings[
`${tickerType}ticker`
].specificjobs.includes(gameState.player.job)
) {
tickerBar.style.display = "block";
} else {
tickerBar.style.display = "none";
}
}
}
}
}
// Handles reloading all the modules (after for example changing settings or coming into a battle live)
function reloadCooldownModules() {
toLog([
`[reloadCooldownModules] Zone: ${gameState.zone.type} CurrentPartyList:`,
gameState.partyList,
]);
if (gameState.player.job === "SMN") {
initializeSmn();
adjustJobStacks(gameState.stats.stacks, gameState.stats.maxStacks);
}
generateCustomCooldowns();
if (gameState.zone.type == "Pvp") return;
generateRaidBuffs();
generateMitigation();
generatePartyCooldowns();
}
// UI Generation / Handling for all modules that use normal ability icons
function generateCustomCooldowns() {
toLog(["[generateCustomCooldowns]"]);
let customAbilityList = [];
let customcd = document.getElementById("customcd-bar");
let range = document.createRange();
range.selectNodeContents(customcd);
range.deleteContents();
let playerIndex = 0;
let currentJob = jobList.find((x) => x.name === gameState.player.job);
if (currentSettings.customcd.abilities.length === 0) return;
for (let ability of currentSettings.customcd.abilities.filter(
(x) => x.type === "CustomCooldown" && x.level <= gameState.player.level,
)) {
let pushAbility = false;
let base = "";
if (currentJob.base) base = currentJob.base;
if (
ability.job === currentJob.name ||
ability.job === currentJob.type ||
ability.job === currentJob.position_type ||
ability.job === base
) {
if (ability.extra.hide !== true) pushAbility = true;
}
if (pushAbility && ability.enabled) {
customAbilityList.push({
player: gameState.player.name,
playerIndex: playerIndex,
ability: ability,
});
}
}
if (currentSettings.customcd.alwaysshow && currentSettings.customcd.enabled)
generateIconBarElements(
"CustomCooldown",
customAbilityList,
currentSettings.customcd.columns,
);
}
// Sets up all the abilities for mitigation and then generates them
function generateMitigation() {
toLog(["[generateMitigation]"]);
let mitigationAbilityList = [];
let mitigation = document.getElementById("mitigation-bar");
let range = document.createRange();
range.selectNodeContents(mitigation);
range.deleteContents();
let playerIndex = 0;
let mergedAbilityList = abilityList.concat(
currentSettings.customcd.abilities,
);
let currentJob = jobList.find((x) => x.name === gameState.player.job);
for (let ability of mergedAbilityList.filter(
(x) => x.type === "Mitigation" && x.level <= gameState.player.level,
)) {
if (
currentSettings.override.abilities.some(
(x) => x.id === ability.id && x.type === ability.type,
)
) {
ability = currentSettings.override.abilities.find(
(x) => x.id === ability.id && x.type === ability.type,
);
}
let pushAbility = false;
let base = "";
if (currentJob.base) base = currentJob.base;
if (
ability.job === currentJob.name ||
ability.job === currentJob.type ||
ability.job === base
) {
pushAbility = true;
}
if (pushAbility && ability.enabled) {
mitigationAbilityList.push({
player: gameState.player.name,
playerIndex: playerIndex,
ability: ability,
});
}
}
if (
currentSettings.mitigation.alwaysshow &&
currentSettings.mitigation.enabled
)
generateIconBarElements(
"Mitigation",
mitigationAbilityList,
currentSettings.mitigation.columns,
);
}
// Sets up all the abilities for party cooldowns and then generates them
function generatePartyCooldowns() {
toLog(["[generatePartyCooldowns]"]);
let partyAbilityList = [];
let party = document.getElementById("party-bar");
let range = document.createRange();
range.selectNodeContents(party);
range.deleteContents();
let playerIndex = 0;
let mergedAbilityList = abilityList.concat(
currentSettings.customcd.abilities,
);
for (let partyMember of gameState.partyList) {
let base = "";
if (partyMember.base) base = partyMember.base;
for (let ability of mergedAbilityList.filter(
(x) =>
x.type === "Party" &&
(x.job === partyMember.job.name ||
x.job === partyMember.job.type ||
x.job === partyMember.job.position_type ||
x.job === base) &&
x.level <= gameState.player.level,
)) {
if (
currentSettings.override.abilities.some(
(x) => x.id === ability.id && x.type == ability.type,
)
) {
ability = currentSettings.override.abilities.find(
(x) => x.name === ability.name && x.type == ability.type,
);
}
let pushAbility = true;
if (pushAbility && ability.enabled) {
partyAbilityList.push({
player: partyMember,
playerIndex: playerIndex,
ability: ability,
});
}
}
playerIndex++;
}
if (currentSettings.party.alwaysshow && currentSettings.party.enabled)
generateIconBarElements("Party", partyAbilityList, 20);
}
// Sets up all the abilities for raidbuffs and then generates them
function generateRaidBuffs() {
toLog(["[generateRaidBuffs]"]);
let raidAbilityList = [];
let raidbuffs = document.getElementById("raid-buffs-bar");
let range = document.createRange();
range.selectNodeContents(raidbuffs);
range.deleteContents();
let playerIndex = 0;
let mergedAbilityList = abilityList.concat(
currentSettings.customcd.abilities,
);
for (let partyMember of gameState.partyList) {
let base = "";
if (partyMember.base) base = partyMember.base;
for (let ability of mergedAbilityList.filter(
(x) =>
x.type === "RaidBuff" &&
(x.job === partyMember.job.name ||
x.job === partyMember.job.type ||
x.job === partyMember.job.position_type ||
x.job === base) &&
x.level <= gameState.player.level,
)) {
if (
currentSettings.override.abilities.some(
(x) => x.id === ability.id && x.type == ability.type,
)
) {
ability = currentSettings.override.abilities.find(
(x) => x.id === ability.id && x.type == ability.type,
);
}
let pushAbility = true;
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (
Object.prototype.hasOwnProperty.call(
ability.extra,
"is_card",
) ||
Object.prototype.hasOwnProperty.call(
ability.extra,
"is_song",
) ||
Object.prototype.hasOwnProperty.call(
ability.extra,
"is_ss",
) ||
Object.prototype.hasOwnProperty.call(ability.extra, "is_ts")
) {
pushAbility = false;
}
}
if (pushAbility && ability.enabled) {
raidAbilityList.push({
player: partyMember,
playerIndex: playerIndex,
ability: ability,
});
}
}
playerIndex++;
}
if (!currentSettings.raidbuffs.orderbypartymember)
raidAbilityList.sort((a, b) => a.ability.order - b.ability.order);
if (
currentSettings.raidbuffs.alwaysshow &&
currentSettings.raidbuffs.enabled
)
generateIconBarElements(
"RaidBuff",
raidAbilityList,
currentSettings.raidbuffs.columns,
);
}
// Generates all the needed HTML elements for current abilities that are relevant for the current job
function generateIconBarElements(selector, iconAbilityList, columns) {
iconAbilityList.sort((a, b) => {
return (
a.playerIndex - b.playerIndex || a.ability.order - b.ability.order
);
});
let selectorProperties = getSelectorProperties(selector);
let barSelector = selectorProperties.id;
let selectedSettings = selectorProperties.settings;
let rows = Math.ceil(iconAbilityList.length / columns);
let abilityIndex = 0;
let barElement = document.getElementById(`${barSelector}-bar`);
let barFragment = document.createDocumentFragment();
if (selector !== "Party") {
for (let i = 1; i <= rows; i++) {
let barRow = document.createElement("div");
barRow.id = `${barSelector}-row-${i}`;
barRow.className = "ability-row";
barRow.style.marginTop = `${selectedSettings.padding}px`;
let barBox = document.createElement("div");
barBox.id = `${barSelector}-row-${i}-box`;
barBox.className = "ability-box";
if (selectedSettings.growleft)
barBox.classList.add("ability-reverse");
for (let j = 1; j <= columns; j++) {
let ability = iconAbilityList[abilityIndex];
barBox.appendChild(
generateAbilityIcon(
ability.playerIndex,
ability.ability,
i,
),
);
if (abilityIndex == iconAbilityList.length - 1) break;
abilityIndex++;
}
barRow.appendChild(barBox);
barFragment.appendChild(barRow);
}
barElement.appendChild(barFragment);
} else {
let currentPlayerIndex = 0;
let players = 8;
if (currentSettings.includealliance) players = 24;
let barRowArray = [];
let barBoxArray = [];
for (let i = 1; i <= players; i++) {
let barRow = document.createElement("div");
barRow.id = `${barSelector}-row-${i}`;
barRow.className = "ability-row";
barRow.style.marginTop = `${selectedSettings.padding}px`;
let barBox = document.createElement("div");
barBox.id = `${barSelector}-row-${i}-box`;
barBox.className = "ability-box";
if (selectedSettings.growleft)
barBox.classList.add("ability-reverse");
if (
iconAbilityList.filter(
(ability) => ability.playerIndex === i - 1,
).length === 0
) {
let dummyContainer = document.createElement("div");
dummyContainer.id = `${barSelector}-${i}-dummy-container`;
dummyContainer.className = "ability-container";
dummyContainer.style.width = `${selectedSettings.scale * 48}px`;
dummyContainer.style.height = `${
selectedSettings.scale * 48
}px`;
dummyContainer.style.marginRight = `${selectedSettings.padding}px`;
let dummyImage = document.createElement("img");
dummyImage.id = `${barSelector}-${i}-dummy-image`;
dummyImage.className = "ability-image";
dummyImage.src =
"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
dummyImage.width = selectedSettings.scale * 40;
dummyImage.height = selectedSettings.scale * 40;
dummyImage.style.top = `${selectedSettings.scale * 3}px`;
dummyContainer.appendChild(dummyImage);
barBox.appendChild(dummyContainer);
}
barRow.appendChild(barBox);
barBoxArray.push(barBox);
barRowArray.push(barRow);
}
for (let ability of iconAbilityList) {
if (currentPlayerIndex != ability.playerIndex)
currentPlayerIndex = ability.playerIndex;
barBoxArray[ability.playerIndex].appendChild(
generateAbilityIcon(
ability.playerIndex,
ability.ability,
ability.playerIndex + 1,
),
);
}
Array.prototype.forEach.call(barRowArray, (barRow) => {
barFragment.appendChild(barRow);
});
barElement.appendChild(barFragment);
}
}
// Generates a single ability icon based on player and ability
function generateAbilityIcon(playerIndex, ability, row, generateRow = false) {
ability.icon = processIconUrl(ability.icon);
let selectorProperties = getSelectorProperties(ability.type);
let barSelector = selectorProperties.id;
let selectedSettings = selectorProperties.settings;
if (generateRow) {
if (row === 0) row = 1;
if (
document.querySelectorAll(`#${barSelector}-row-${row}`).length === 0
) {
let barElement = document.createElement("div");
barElement.id = `${barSelector}-row-${row}`;
barElement.className = "ability-row";
barElement.style.marginTop = `${selectedSettings.padding}px`;
let barBox = document.createElement("div");
barBox.id = `${barSelector}-row-${row}-box`;
barBox.className = "ability-box";
barBox.style.marginTop = `${selectedSettings.padding}px`;
if (selectedSettings.growleft)
barBox.classList.add("ability-reverse");
barElement.appendChild(barBox);
document
.getElementById(`${barSelector}-bar`)
.appendChild(barElement);
}
}
let iconWidth = Math.ceil(selectedSettings.scale * 40);
let iconHeight = Math.ceil(selectedSettings.scale * 40);
let activeWidth = Math.ceil(selectedSettings.scale * 42);
let activeHeight = Math.ceil(selectedSettings.scale * 42);
let boxWidth = Math.ceil(selectedSettings.scale * 48);
let boxHeight = Math.ceil(selectedSettings.scale * 48);
let overlayWidth = Math.ceil(selectedSettings.scale * 48);
let overlayHeight = Math.ceil(selectedSettings.scale * 48);
let lineHeight = Math.ceil(selectedSettings.scale * 44);
let abilitySelector = `${barSelector}-${playerIndex}-${ability.id}`;
let abilityContainer = document.createElement("div");
abilityContainer.id = `${abilitySelector}-container`;
abilityContainer.className = "ability-container";
abilityContainer.style.width = `${boxWidth}px`;
abilityContainer.style.height = `${boxHeight}px`;
abilityContainer.style.marginRight = `${selectedSettings.padding}px`;
let abilityImage = document.createElement("img");
abilityImage.id = `${abilitySelector}-image`;
abilityImage.className = "ability-image";
abilityImage.src = ability.icon;
abilityImage.width = iconWidth;
abilityImage.height = iconHeight;
abilityImage.style.top = `${selectedSettings.scale * 2}px`;
abilityContainer.appendChild(abilityImage);
let abilityActive = document.createElement("img");
abilityActive.id = `${abilitySelector}-active`;
abilityActive.className = "icon-active";
abilityActive.src = `skins/${currentSettings.skin}/images/combo.gif`;
abilityActive.width = activeWidth;
abilityActive.height = activeHeight;
abilityActive.style.top = `${selectedSettings.scale * 1}px`;
abilityActive.style.display = "none";
abilityContainer.appendChild(abilityActive);
let abilityOverlay = document.createElement("img");
abilityOverlay.id = `${abilitySelector}-overlay`;
abilityOverlay.className = "icon-overlay";
abilityOverlay.src = `skins/${currentSettings.skin}/images/icon-overlay.png`;
abilityOverlay.width = overlayWidth;
abilityOverlay.height = overlayHeight;
abilityContainer.appendChild(abilityOverlay);
let abilityCooldown = document.createElement("span");
abilityCooldown.id = `${abilitySelector}-cooldown`;
abilityCooldown.className = "ability-text";
abilityCooldown.style.lineHeight = `${lineHeight}px`;
abilityCooldown.style.marginLeft = `${
selectedSettings.scale * 2 + selectedSettings.fontxoffset
}px`;
abilityCooldown.style.marginTop = `${selectedSettings.fontyoffset}px`;
abilityCooldown.style.color = selectedSettings.cooldowncolor;
abilityCooldown.style.fontSize = selectedSettings.staticfontsize
? selectedSettings.fontsize
: selectedSettings.scale * 24;
abilityCooldown.style.fontWeight = selectedSettings.cooldownbold
? "bold"
: "normal";
if (selectedSettings.cooldownoutline) {
abilityCooldown.style.webkitTextStroke = `1.5px ${selectedSettings.durationoutlinecolor}`;
}
abilityContainer.appendChild(abilityCooldown);
let abilityDuration = document.createElement("span");
abilityDuration.id = `${abilitySelector}-duration`;
abilityDuration.className = "ability-text";
abilityDuration.style.lineHeight = `${lineHeight}px`;
abilityDuration.style.marginLeft = `${
selectedSettings.scale * 2 + selectedSettings.fontxoffset
}px`;
abilityDuration.style.marginTop = `${selectedSettings.fontyoffset}px`;
abilityDuration.style.color = selectedSettings.durationcolor;
abilityDuration.style.fontSize = selectedSettings.staticfontsize
? selectedSettings.fontsize
: selectedSettings.scale * 24;
abilityDuration.style.fontWeight = selectedSettings.durationbold
? "bold"
: "normal";
if (selectedSettings.durationoutline) {
abilityDuration.style.webkitTextStroke = `1.5px ${selectedSettings.durationoutlinecolor}`;
}
abilityContainer.appendChild(abilityDuration);
return abilityContainer;
}
// Handlers for creating/maintaining party list
// Generates "raw" partylist that's in the format that generatePartyList expects, made for cases where a player joins late and other sources needs to be used to determine what job classes are in the players party
function generateRawPartyList(fromCombatants, combatants = null) {
if (fromCombatants) {
let partyList = combatants.filter((x) => x.PartyType !== 0);
let rawList = [];
for (let partyMember of partyList) {
rawList.push({
id: parseInt(partyMember.ID).toString(16).toUpperCase(),
inParty: partyMember.PartyType === 1,
job: partyMember.Job,
level: partyMember.Level,
name: partyMember.Name,
worldId: partyMember.WorldID,
});
}
return rawList;
}
return [
{
id: parseInt(gameState.player.id).toString(16).toUpperCase(),
inParty: false,
job: jobList.find((x) => x.name === gameState.player.job).id,
level: gameState.player.level,
name: gameState.player.name,
worldId: null,
},
];
}
function extractPlayerPets(combatants) {
gameState.playerPets = [];
for (let combatant of combatants) {
let ownerId = parseInt(combatant.OwnerID).toString(16).toUpperCase();
if (gameState.partyList.filter((x) => x.id == ownerId).length > 0) {
addPlayerPet({
name: combatant.Name,
id: parseInt(combatant.ID).toString(16).toUpperCase(),
ownerId: ownerId,
});
}
}
}
// Generate partylist with extra metadata (for example player jobs and what type the job is)
function generatePartyList(party) {
toLog(["[GeneratePartyList] RawPartyList:", party]);
gameState.rawPartyList = party;
gameState.partyList = [];
for (let partyMember of party) {
if (
!(
!partyMember.inParty &&
!currentSettings.includealliance &&
partyMember.name !== gameState.player.name
)
) {
if (partyMember.level == undefined)
partyMember.level = gameState.player.level;
gameState.partyList.push({
id: partyMember.id,
inParty: partyMember.inParty,
job: jobList.find((x) => x.id === partyMember.job),
level: partyMember.level,
name: partyMember.name,
worldId: partyMember.worldId,
});
}
}
let jobOrder = currentSettings.rolepartyorder[gameState.currentrole];
let currentPlayerElement = gameState.partyList.find(
(x) => x.name === gameState.player.name,
);
gameState.partyList.sort((a, b) => b.id - a.id);
gameState.partyList.sort(
(a, b) => jobOrder.indexOf(a.job.name) - jobOrder.indexOf(b.job.name),
);
gameState.partyList = gameState.partyList.filter(
(x) => x !== currentPlayerElement,
);
if (currentSettings.includealliance) {
let ownParty = gameState.partyList.filter((x) => x.inParty);
let alliance = gameState.partyList.filter((x) => !x.inParty);
gameState.partyList = ownParty.concat(alliance);
}
gameState.partyList.unshift(currentPlayerElement);
}
// Manual party check from getCombatants in case the players party is null (for example when player reloaded the UI)
function checkForParty(e) {
let combatants = e.combatants;
if (combatants === undefined || gameState.player === undefined) return;
let player = combatants.find((x) => x.ID === gameState.player.id);
let hasCombatants = false;
if (Object.prototype.hasOwnProperty.call(player, "PartyType")) {
hasCombatants = player.PartyType !== 0;
}
let partyList = generateRawPartyList(hasCombatants, combatants);
generatePartyList(partyList);
extractPlayerPets(combatants);
reloadCooldownModules();
}
// Timer and TTS handlers
// Handle ability timers when ability is used
function startAbilityIconTimers(
playerIndex,
ability,
onYou = true,
abilityHolder = null,
ignoreCooldown = false,
) {
toLog([
`[StartAbilityIconTimers] PlayerIndex: ${playerIndex} On You: ${onYou} Ignore Cooldown: ${ignoreCooldown}`,
ability,
abilityHolder,
]);
let abilityUsed = abilityHolder === null ? ability : abilityHolder;
let usingAbilityHolder = abilityHolder !== null;
if (
currentSettings.general.usehdicons &&
!ability.icon.includes("_hr1.png")
) {
ability.icon = ability.icon.replace(".png", "_hr1.png");
if (usingAbilityHolder && !abilityHolder.icon.includes("_hr1.png"))
abilityHolder.icon = abilityHolder.icon.replace(".png", "_hr1.png");
}
if (usingAbilityHolder) {
abilityHolder.icon = processIconUrl(abilityHolder.icon);
} else {
ability.icon = processIconUrl(ability.icon);
}
let selectorProperties = getSelectorProperties(ability.type);
let barSelector = selectorProperties.id;
let selectedSettings = selectorProperties.settings;
let selectedActive = selectorProperties.active;
if (!selectedSettings.enabled) return;
if (playerIndex == -1) return;
if (barSelector === "customcd" && playerIndex !== 0) return;
let selector = `${barSelector}-${playerIndex}-${abilityUsed.id}`;
let abilityIndex = `${playerIndex}-${ability.id}`;
let abilityHasCharges = false;
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (Object.prototype.hasOwnProperty.call(ability.extra, "charges")) {
abilityHasCharges = true;
let max_charges = ability.extra.charges;
if (!activeElements.currentCharges.has(abilityIndex)) {
activeElements.currentCharges.set(
abilityIndex,
max_charges - 1,
);
} else {
let currentCharges = activeElements.currentCharges.get(
abilityIndex,
);
activeElements.currentCharges.set(
abilityIndex,
currentCharges - 1,
);
}
}
}
if (
selectedActive.has(`${playerIndex}-${ability.id}`) &&
!abilityHasCharges
) {
if (activeElements.countdowns.has(`${selector}-duration`)) {
clearInterval(
activeElements.countdowns.get(`${selector}-duration`),
);
stopAbilityTimer(`${selector}-duration`, null);
}
if (
activeElements.countdowns.has(`${selector}-cooldown`) &&
!ignoreCooldown
) {
clearInterval(
activeElements.countdowns.get(`${selector}-cooldown`),
);
}
if (!ignoreCooldown) stopAbilityTimer(`${selector}-cooldown`, null);
}
handleAbilityTTS(ability, selector, onYou);
if (onYou) {
if (!selectedSettings.alwaysshow) {
let row = Math.ceil(selectedActive.size / selectedSettings.columns);
let abilityElement = generateAbilityIcon(
playerIndex,
ability,
row,
true,
);
if (row === 0) row = 1;
if (!document.getElementById(`${selector}-container`)) {
document
.getElementById(`${barSelector}-row-${row}-box`)
.appendChild(abilityElement);
}
}
if (document.getElementById(`${selector}-overlay`))
document.getElementById(
`${selector}-overlay`,
).src = `skins/${currentSettings.skin}/images/icon-overlay.png`;
if (document.getElementById(`${selector}-active`))
document.getElementById(`${selector}-active`).style.display =
"block";
if (document.getElementById(`${selector}-duration`)) {
document.getElementById(`${selector}-duration`).style.display =
"block";
document.getElementById(`${selector}-duration`).textContent =
ability.duration;
}
if (document.getElementById(`${selector}-cooldown`))
document.getElementById(`${selector}-cooldown`).style.display =
"none";
if (usingAbilityHolder) {
let previousIcon = `${abilityHolder.icon}`;
if (document.getElementById(`${selector}-image`)) {
document.getElementById(`${selector}-image`).src = ability.icon;
}
startAbilityTimer(
ability.duration,
`${selector}-duration`,
previousIcon,
abilityIndex,
);
} else {
startAbilityTimer(
ability.duration,
`${selector}-duration`,
null,
abilityIndex,
);
}
} else {
if (document.getElementById(`${selector}-overlay`)) {
document.getElementById(`${selector}-overlay`).src =
ability.cooldown > 0
? `skins/${currentSettings.skin}/images/icon-overlay-cooldown.png`
: `skins/${currentSettings.skin}/images/icon-overlay.png`;
}
if (document.getElementById(`${selector}-cooldown`)) {
document.getElementById(`${selector}-cooldown`).style.display =
"block";
document.getElementById(`${selector}-cooldown`).textContent =
ability.cooldown;
}
}
if (selectedSettings.alwaysshow && !ignoreCooldown)
startAbilityTimer(
ability.cooldown,
`${selector}-cooldown`,
null,
abilityIndex,
);
selectedActive.set(`${playerIndex}-${ability.id}`, selector);
}
// Handle ability bar timers when effects occur or certain cooldowns are used
function startAbilityBarTimer(
ability,
duration,
onYou,
extends_duration = false,
max_duration = 0,
abilityHolder = null,
) {
toLog([
`[StartAbilityBarTimer] Duration: ${duration} On You: ${onYou}`,
ability,
abilityHolder,
]);
let abilityUsed = abilityHolder === null ? ability : abilityHolder;
let usingAbilityHolder = abilityHolder !== null;
if (!currentSettings[`${ability.type.toLowerCase()}timerbar`].enabled)
return;
let targetBarSelector = `${ability.type.toLowerCase()}-timer-bar`;
let targetImageSelector = `${ability.type.toLowerCase()}-image`;
let targetPosition =
ui.dragPosition[`${ability.type.toLowerCase()}-timer-bar`];
let selectorBar = `${abilityUsed.id}-${ability.type.toLowerCase()}-timer`;
let selectorImage = `${abilityUsed.id}-${ability.type.toLowerCase()}-image`;
ability.duration = parseInt(duration);
if (
!activeElements.dotBars.has(abilityUsed.id) &&
!activeElements.buffBars.has(abilityUsed.id)
) {
switch (abilityUsed.type) {
case "DoT": {
activeElements.dotBars.set(abilityUsed.id, selectorBar);
break;
}
case "Buff": {
activeElements.buffBars.set(abilityUsed.id, selectorBar);
break;
}
}
let targetBar = document.getElementById(targetBarSelector);
let newBar = targetBar.cloneNode(true);
newBar.id = selectorBar;
newBar.style.display = "block";
newBar.classList.add(`bar-${ability.id}`);
newBar.classList.add(`${ability.type.toLowerCase()}-font-size`);
targetBar.insertAdjacentElement("afterend", newBar);
let targetImage = document.getElementById(targetImageSelector);
let newImage = targetImage.cloneNode(true);
newImage.id = selectorImage;
targetImage.insertAdjacentElement("afterend", newImage);
applyFilterColorToElement(`bar-${ability.id}`, ability.color);
newBar.setAttribute(
"data-font-size",
currentSettings[`${ability.type.toLowerCase()}timerbar`].scale * 10,
);
switch (
parseInt(
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.growdirection,
)
) {
case 1: {
// Down
newBar.style.transform = `translate(${targetPosition.x}px, ${
targetPosition.y +
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order
}px)`;
break;
}
case 2: {
// Up
newBar.style.transform = `translate(${targetPosition.x}px, ${
targetPosition.y -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order
}px)`;
break;
}
case 3: {
// Left
newBar.style.transform = `translate(${
targetPosition.x -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order
}px, ${targetPosition.y}px)`;
break;
}
case 4: {
// Right
newBar.style.transform = `translate(${
targetPosition.x +
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order
}px, ${targetPosition.y}px)`;
break;
}
}
if (
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.imageenabled
) {
newImage.style.display = "block";
newImage.src = ability.icon;
newImage.style.imageRendering =
currentSettings[`${ability.type.toLowerCase()}timerbar`].scale >
1
? "pixelated"
: "-webkit-optimize-contrast";
newImage.style.height =
currentSettings[`${ability.type.toLowerCase()}timerbar`].scale *
22;
let left = targetPosition.x;
let top = targetPosition.y;
switch (
parseInt(
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.growdirection,
)
) {
case 1: {
// Down
left =
left -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
30;
top =
top +
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
4;
break;
}
case 2: {
// Up
left =
left -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
30;
top =
top -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
4;
break;
}
case 3: {
// Left
top =
top -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
4;
left =
left -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
30;
break;
}
case 4: {
// Right
top =
top -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
4;
left =
left +
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.padding *
ability.order -
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.scale *
30;
break;
}
}
newImage.style.transform = `translate(${left}px, ${top}px)`;
}
}
if (
usingAbilityHolder &&
currentSettings[`${ability.type.toLowerCase()}timerbar`].imageenabled
)
document.getElementById(selectorImage).src = ability.icon;
if (usingAbilityHolder)
applyFilterColorToElement(`bar-${abilityUsed.id}`, ability.color);
if (activeElements.countdowns.has(selectorBar) && extends_duration) {
duration =
parseInt(document.getElementById(selectorBar).textContent) / 1000 +
parseInt(duration);
if (duration > max_duration) duration = max_duration;
}
if (activeElements.countdowns.has(selectorBar))
clearInterval(activeElements.countdowns.get(selectorBar));
handleAbilityTTS(ability, selectorBar, onYou);
startBarTimer(
duration,
selectorBar,
currentSettings[`${ability.type.toLowerCase()}timerbar`]
.hidewhendroppedoff,
);
}
// Start and handle actual timer for ability
function startAbilityTimer(
duration,
selector,
previousIcon = null,
abilityIndex = null,
) {
let timems = duration * 1000;
let abilityElement = document.getElementById(selector);
if (abilityElement) abilityElement.textContent = duration;
let timeLeft = timems;
let countdownTimer = setInterval(function () {
timeLeft -= UPDATE_INTERVAL;
if (abilityElement)
abilityElement.textContent = (timeLeft / 1000).toFixed(0);
if (timeLeft <= 0) {
clearInterval(countdownTimer);
setTimeout(function () {
stopAbilityTimer(selector, previousIcon, abilityIndex);
}, UPDATE_INTERVAL);
}
}, UPDATE_INTERVAL);
activeElements.countdowns.set(selector, countdownTimer);
}
function toggleTimerBarDisplay(selector, display) {
let bar = document.getElementById(selector);
let image = document.getElementById(selector.replace("timer", "image"));
if (bar) bar.style.display = display ? "block" : "none";
if (image) image.style.display = display ? "block" : "none";
}
// Start and handle actual timer for bars/effects
function startBarTimer(
duration,
selector,
hideTimer = false,
reverseBar = false,
loop = false,
) {
toLog([
`[StartBarTimer] Duration: ${duration} Selector: ${selector} Hidetimer: ${hideTimer} Reverse: ${reverseBar} Loop: ${loop}`,
]);
let timems = duration * 1000;
let barElement = document.getElementById(selector);
barElement.value = reverseBar ? 0 : timems;
barElement.max = timems;
if (!selector.endsWith("ticker-bar"))
barElement.setAttribute("data-label", timems);
if (hideTimer) toggleTimerBarDisplay(selector, true);
let timeLeft = timems;
let maxTime = timems;
let countdownTimer = setInterval(function () {
timeLeft -= UPDATE_INTERVAL;
let visualTime = 0;
if (reverseBar) {
visualTime = maxTime - timeLeft;
} else {
visualTime = timeLeft - UPDATE_INTERVAL;
}
if (barElement.value != visualTime) barElement.value = visualTime;
if (!selector.endsWith("ticker-bar"))
barElement.setAttribute("data-label", (timeLeft / 1000).toFixed(1));
if (timeLeft <= 0 && !loop) {
clearInterval(countdownTimer);
setTimeout(function () {
if (hideTimer) {
if (selector !== "timer-bar") {
removeTimerBar(selector);
} else {
toggleTimerBarDisplay(selector, false);
}
}
}, UPDATE_INTERVAL);
}
if (timeLeft <= 0 && loop) {
timeLeft = GAME_DATA.EFFECT_TICK * 1000;
}
}, UPDATE_INTERVAL);
activeElements.countdowns.set(selector, countdownTimer);
}
function getElementType(selector) {
if (selector.startsWith("raid-buffs")) return "raidbuffs";
if (selector.startsWith("mitigation")) return "mitigation";
if (selector.startsWith("party")) return "party";
if (selector.startsWith("customcd")) return "customcd";
return "undefined";
}
// Stop active ability timer right away and handles the visual aspect of it
function stopAbilityTimer(selector, previousIcon = null, abilityIndex = null) {
let elementType = getElementType(selector);
if (selector.endsWith("duration")) {
let cooldown = selector.replace("duration", "cooldown");
let image = selector.replace("duration", "image");
let active = selector.replace("duration", "active");
let overlay = selector.replace("duration", "overlay");
let container = selector.replace("duration", "container");
if (!currentSettings[elementType].alwaysshow) {
if (document.getElementById(container)) {
document.getElementById(container).remove();
}
}
if (document.getElementById(selector))
document.getElementById(selector).textContent = "";
if (previousIcon !== null && currentSettings[elementType].alwaysshow) {
document.getElementById(image).src = previousIcon;
}
if (document.getElementById(cooldown)) {
document.getElementById(cooldown).style.display = "block";
}
if (document.getElementById(active)) {
document.getElementById(active).style.display = "none";
}
if (document.getElementById(cooldown)) {
if (document.getElementById(cooldown).textContent.length !== 0) {
document.getElementById(
overlay,
).src = `skins/${currentSettings.skin}/images/icon-overlay-cooldown.png`;
}
}
}
if (selector.endsWith("cooldown")) {
if (abilityIndex) {
if (activeElements.currentCharges.has(abilityIndex)) {
activeElements.currentCharges.set(
abilityIndex,
parseInt(activeElements.currentCharges.get(abilityIndex)) +
1,
);
}
}
if (!currentSettings[elementType].alwaysshow) {
if (document.getElementById(selector))
document.getElementById(selector).remove();
return;
}
if (document.getElementById(selector)) {
document.getElementById(selector).textContent = "";
document.getElementById(
selector.replace("cooldown", "overlay"),
).src = `skins/${currentSettings.skin}/images/icon-overlay.png`;
}
}
}
function stopBarTimer(selector, hideTimer) {
if (document.getElementById(selector)) {
document.getElementById(selector).value = 0;
document.getElementById(selector).setAttribute("data-label", "");
if (hideTimer) toggleTimerBarDisplay(selector, false);
}
}
// Stop all active timers for certain player in your party (when he for example dies)
function stopPlayerDurationTimers(playerindex) {
activeElements.partyCooldowns.forEach((value, key) => {
if (key.split("-")[0] == playerindex) {
if (activeElements.countdowns.has(`${value}-duration`)) {
clearInterval(
activeElements.countdowns.get(`${value}-duration`),
);
}
stopAbilityTimer(`${value}-duration`, null);
}
});
if (playerindex === 0) {
activeElements.countdowns.forEach((value, key) => {
let split = key.split("-");
let last = split[split.length - 1];
if (last == "duration") {
clearInterval(activeElements.countdowns.get(key));
stopAbilityTimer(key, null);
}
});
}
}
// Stop remove active bar
function removeTimerBar(selector) {
document.getElementById(selector).remove();
document.getElementById(selector.replace("timer", "image")).remove();
if (activeElements.buffBars.has(parseInt(selector.match(/[0-9]+/g)[0])))
activeElements.buffBars.delete(parseInt(selector.match(/[0-9]+/g)[0]));
if (activeElements.dotBars.has(parseInt(selector.match(/[0-9]+/g)[0])))
activeElements.dotBars.delete(parseInt(selector.match(/[0-9]+/g)[0]));
}
// Reset all timers
function resetTimers() {
let tickerTypes = ["mp", "dot", "hot"];
for (let tickerType of tickerTypes) {
document.getElementById(`${tickerType}-ticker-bar`).value = 0;
document
.getElementById(`${tickerType}-ticker-bar`)
.setAttribute("data-label", "");
}
for (let [, countdownTimer] of activeElements.countdowns) {
clearInterval(countdownTimer);
}
for (let [, selector] of activeElements.buffBars) {
removeTimerBar(selector);
}
for (let [, selector] of activeElements.dotBars) {
removeTimerBar(selector);
}
activeElements.buffBars.clear();
activeElements.dotBars.clear();
activeElements.countdowns.clear();
}
// Set actual timer for when TTS needs to be played for certain abilities
function startTTSTimer(
duration,
selector,
text,
timeWhen = currentSettings.general.ttsearly * 1000,
) {
toLog([
`[StartTTSTimer] Duration: ${duration} Selector: ${selector} Text: ${text} TimeWhen: ${timeWhen}`,
]);
if (!activeElements.ttsElements.has(selector)) {
if (currentSettings.general.usewebtts)
activeElements.ttsElements[selector] = setWebTTS(text);
}
let timems = duration * 1000;
let timeLeft = timems;
let ttsTimer = setInterval(function () {
timeLeft -= UPDATE_INTERVAL;
if (timeLeft <= timeWhen) {
if (currentSettings.general.preventdoubletts) {
if (activeElements.ttsLastCalled.has(selector)) {
if (
Date.now() <
activeElements.ttsLastCalled.get(selector) + 2000
) {
clearInterval(ttsTimer);
return;
}
}
}
activeElements.ttsLastCalled.set(selector, Date.now());
currentSettings.general.usewebtts
? activeElements.ttsElements[selector].play()
: callOverlayHandler({ call: "cactbotSay", text: text });
clearInterval(ttsTimer);
setTimeout(function () {}, UPDATE_INTERVAL);
}
}, UPDATE_INTERVAL);
activeElements.tts.set(selector, ttsTimer);
}
// Set up event for when TTS needs to occur for certain abilities
function handleAbilityTTS(ability, selector, onYou = true) {
toLog([
`[HandleAbilityTTS] Ability: ${ability} Selector: ${selector} OnYou: ${onYou}`,
]);
if (activeElements.tts.has(selector))
clearInterval(activeElements.tts.get(selector));
switch (ability.type) {
case "DoT":
if (!currentSettings.dottimerbar.ttsenabled) return;
break;
case "Buff":
if (!currentSettings.bufftimerbar.ttsenabled) return;
break;
case "RaidBuff":
if (!currentSettings.raidbuffs.ttsenabled) return;
break;
case "Mitigation":
if (!currentSettings.mitigation.ttsenabled) return;
break;
case "Party":
if (!currentSettings.party.ttsenabled) return;
break;
case "CustomCooldown":
if (!currentSettings.customcd.ttsenabled) return;
break;
default:
break;
}
let name = ability.name;
switch (currentSettings.language) {
case "en":
name = ability.name_en;
break;
case "cn":
name = ability.name_cn;
break;
case "de":
name = ability.name_de;
break;
case "fr":
name = ability.name_fr;
break;
case "jp":
name = ability.name_jp;
break;
case "kr":
name = ability.name_kr;
break;
default:
break;
}
if (ability.tts) {
switch (parseInt(ability.ttstype)) {
case 0:
startTTSTimer(ability.cooldown, selector, name);
break;
case 1:
startTTSTimer(ability.duration, selector, name);
break;
case 2:
if (!onYou && ability.type == "RaidBuff") return;
startTTSTimer(0, selector, name, 0);
break;
default:
break;
}
}
}
// Replace icon based on settings
function processIconUrl(icon) {
if (
currentSettings.general.usehdicons &&
!icon.includes("_hr1.png") &&
currentSettings.language != "cn"
)
icon = icon.replace(".png", "_hr1.png");
if (currentSettings.language == "cn") {
icon = icon.replace("xivapi", "cafemaker.wakingsands");
}
return icon;
}
// Originally used for google TTS but this hack stopped working, still relevant for the TTS from Baidu
function setWebTTS(text) {
let iframe = document.createElement("iframe");
iframe.removeAttribute("sandbox");
iframe.style.display = "none";
document.body.appendChild(iframe);
let encText = encodeURIComponent(text);
// For CN User
// https://fanyi.baidu.com/gettts?lan=zh&spd=5&source=web&text=
iframe.contentDocument.body.innerHTML =
'<audio src="https://fanyi.baidu.com/gettts?lan=zh&spd=5&source=web&text=' +
encText +
'" id="TTS">';
this.item = iframe.contentDocument.body.firstElementChild;
return this.item;
}
// Sets Party Role based on current job
function setCurrentRole(job) {
if (job === null) return;
gameState.currentrole = jobList
.find((x) => x.name === job)
.type.toLowerCase();
if (gameState.currentrole.includes("dps")) gameState.currentrole = "dps";
if (
gameState.currentrole != "tank" &&
gameState.currentrole != "healer" &&
gameState.currentrole != "dps"
) {
gameState.currentrole = "other";
}
}
// Stack maintaining functions
function adjustJobStacks(value, max, noAdd = false) {
if (!noAdd) {
gameState.stats.stacks = value;
if (gameState.player.job === "SMN" && gameState.stats.maxStacks === 0) {
initializeSmn(true);
max = 4;
}
}
for (let i = 1; i <= 4; i++) {
let backgroundElement = document.getElementById(
`stacks-background-${i}`,
);
if (i <= max) {
if (backgroundElement.classList.contains("stack-hidden")) {
backgroundElement.classList.remove("stack-hidden");
}
} else {
if (!backgroundElement.classList.contains("stack-hidden")) {
backgroundElement.classList.add("stack-hidden");
}
}
document.getElementById(`stacks-${i}`).src =
i <= value
? `skins/${currentSettings.skin}/images/arrow-fill.png`
: `skins/${currentSettings.skin}/images/arrow-fill-empty.png`;
}
}
// Handles Ruin IV stacks for summoner
function initializeSmn(addStack = false) {
gameState.stats.stacks = addStack ? 1 : 0;
gameState.stats.maxStacks = 4;
}
// OverlayPlugin and Cactbot Event Handlers
// When user changes zones
function onChangeZone(e) {
gameState.zone = {
id: e.zoneID,
name: e.zoneName,
info: {},
type: "Unspecified",
};
if (gameState.player === null) return;
checkAndSetZoneInfo(e.zoneID);
if (gameState.player.job === "SMN") {
initializeSmn();
adjustJobStacks(gameState.stats.stacks, gameState.stats.maxStacks);
}
resetTimers();
}
// When user enters / leaves combat
function onInCombatChangedEvent(e) {
if (gameState.inCombat === e.detail.inGameCombat) {
return;
}
gameState.inCombat = e.detail.inGameCombat;
toggleHideOutOfCombatElements();
}
// When any log event occurs, then process them and forwards them to corresponding event
function onLogEvent(e) {
for (let logLine of e.detail.logs) {
toLog([`[OnLogEvent] ${logLine}`]);
for (let logType of Object.keys(regexList)) {
let regexObject = regexList[logType];
let regex = new RegExp(regexObject.regex);
if (regex.test(logLine)) {
let matches = regexObject.matches;
for (let match of Object.keys(matches)) {
let matchObject = matches[match];
let innerRegex = new RegExp(matchObject.regex);
let regexMatch = innerRegex.exec(logLine);
if (regexMatch !== null) {
let logFunction = window[matchObject.function];
if (typeof logFunction === "function") {
toLog([
`Executing function ${matchObject.function}`,
regexMatch.groups,
]);
logFunction(regexMatch.groups);
}
}
}
}
}
}
}
// Listens for user unlocks/locks the overlay in OverlayPlugin
document.addEventListener("onOverlayStateUpdate", function (e) {
let element = document.getElementById("lock-overlay-reminder");
if (!e.detail.isLocked) {
document.documentElement.style.background = "rgba(0,0,255,0.5)";
if (!ui.locked) element.style.display = "block";
} else {
document.documentElement.style.background = "";
if (!ui.locked) element.style.display = "none";
}
ui.actlocked = e.detail.isLocked;
});
// When user switches jobs
function onJobChange(job) {
if (language.find((x) => x.id === job.toLowerCase())) {
gameState.playerTags.job = language.find(
(x) => x.id === job.toLowerCase(),
).string;
}
if (
Object.prototype.hasOwnProperty.call(
currentSettings.profiles.jobprofiles,
job.toLowerCase(),
)
) {
loadProfile(currentSettings.profiles.jobprofiles[job.toLowerCase()]);
}
setAndCheckTickers();
if (job === "SMN") {
initializeSmn();
adjustJobStacks(gameState.stats.stacks, gameState.stats.maxStacks);
if (currentSettings.stacksbar.enabled) {
document.getElementById("stacks-bar").style.display = "block";
} else {
document.getElementById("stacks-bar").style.display = "none";
}
} else {
if (currentSettings.stacksbar.enabled) {
document.getElementById("stacks-bar").style.display = "block";
} else {
document.getElementById("stacks-bar").style.display = "none";
}
}
resetTimers();
if (gameState.partyList.length === 1) {
gameState.partyList = [];
}
}
// When anyone joins/leaves party
function onPartyChanged(e) {
toLog(["[onPartyChanged]", e]);
if (gameState.player === null) return;
let partyList = e.party;
if (partyList.length === 0) {
partyList = generateRawPartyList(false);
}
generatePartyList(partyList);
reloadCooldownModules();
toggleHideWhenSoloCombatElements();
}
// When the party wipes on an encounter
function onPartyWipe() {
if (gameState.player === null) return;
resetTimers();
reloadCooldownModules();
}
function getPlayerChangedEventFromCombatants(details) {
if (details.length === 0) return;
if (details.combatants.length === 0) return;
let player = details.combatants[0];
let job = jobList.find((x) => x.id === player.Job).name;
let e = {
detail: {
currentCP: player.CurrentMP,
currentGP: player.CurrentMP,
currentHP: player.CurrentHP,
currentMP: player.CurrentMP,
currentShield: 0,
currentTP: 0,
debugJob: null,
id: player.ID,
job: job,
jobDetail: null,
level: player.Level,
maxCP: player.MaxMP,
maxGP: player.MaxMP,
maxHP: player.MaxHP,
maxMP: player.MaxMP,
name: player.Name,
pos: {
x: player.PosX,
y: player.PosY,
z: player.PosZ,
},
},
};
onPlayerChangedEvent(e);
}
// When any change occurs to the player/players resources, mostly used for HP/MP and detecting job changes
function onPlayerChangedEvent(e) {
if (!window["language"]) return;
if (gameState.player !== null && gameState.player.job !== e.detail.job) {
onJobChange(e.detail.job);
setCurrentRole(e.detail.job);
}
gameState.playerPrevious = gameState.playerPrevious
? gameState.player
: e.detail;
gameState.player = e.detail;
if (gameState.currentrole === null) {
onJobChange(e.detail.job);
setCurrentRole(e.detail.job);
}
if (gameState.partyList.length === 0) {
setAndCheckTickers();
window
.callOverlayHandler({ call: "getCombatants" })
.then((e) => checkForParty(e));
}
// Check for CP/GP
if (gameState.player.maxGP) {
gameState.player.currentMP = gameState.player.currentGP;
gameState.player.maxMP = gameState.player.maxGP;
}
if (gameState.player.maxCP) {
gameState.player.currentMP = gameState.player.currentCP;
gameState.player.maxMP = gameState.player.maxCP;
}
handleHealthUpdate(gameState.player.currentHP, gameState.player.maxHP);
handleManaUpdate(gameState.player.currentMP, gameState.player.maxMP);
}
// Regex Event Handlers from ../data/regex.js
/* exported onInstanceStart */
function onInstanceStart() {
generatePartyList(gameState.rawPartyList);
reloadCooldownModules();
}
/* exported onInstanceEnd */
function onInstanceEnd() {
resetTimers();
reloadCooldownModules();
}
// Checks if current zone is available in static zone_info and sets it in the current gamestate
function checkAndSetZoneInfo(zoneId) {
if (GAME_DATA.ZONE_INFO[zoneId] !== undefined) {
gameState.zone.info = GAME_DATA.ZONE_INFO[zoneId];
if (gameState.zone.info.contentType !== undefined)
gameState.zone.type = Object.keys(GAME_DATA.CONTENT_TYPE).find(
(x) =>
GAME_DATA.CONTENT_TYPE[x] ===
gameState.zone.info.contentType,
);
}
}
function addPlayerPet(pet) {
gameState.playerPets.push({
name: pet.name,
id: pet.id,
ownerId: pet.ownerId,
});
}
/* exported handleAddNewCombatant */
function handleAddNewCombatant(parameters) {
if (
gameState.partyList.filter((x) => x.id == parameters.ownerId).length > 0
) {
addPlayerPet({
name: parameters.name,
id: parameters.id,
ownerId: parameters.ownerId,
});
}
if (gameState.partyList.filter((x) => x.id == parameters.id).length == 0) {
return;
}
let job = jobList.find((x) => x.id === parseInt(parameters.job, 16));
let player = gameState.partyList.find((x) => x.id == parameters.id);
let reload = false;
if (player.job != job) {
player.job = job;
reload = true;
toLog(
"[handleAddNewCombatant] Party Member Job Changed, cooldowns will be reloaded",
job,
);
}
if (player.level != parseInt(parameters.level, 16)) {
player.level = parseInt(parameters.level, 16);
reload = true;
toLog(
"[handleAddNewCombatant] Party Member Level Changed, cooldowns will be reloaded",
parseInt(parameters.level, 16),
);
}
if (reload) reloadCooldownModules();
}
/* exported handleRemoveCombatant */
function handleRemoveCombatant(parameters) {
let filter = gameState.playerPets.filter((x) => x.id == parameters.id);
if (filter.length == 1) {
gameState.playerPets.splice(gameState.playerPets.indexOf(filter[0]), 1);
}
}
// When user uses /countdown or /cd
/* exported handleCountdownTimer */
function handleCountdownTimer(parameters) {
if (!currentSettings.timerbar.enabled) return;
startBarTimer(parameters.seconds, "timer-bar", true);
}
// Whenever any DoT/HoT ticks
/* exported handleEffectTick */
function handleEffectTick(parameters) {
let type = parameters.effect.toLowerCase();
if (!currentSettings[`${type}ticker`].enabled) return;
if (currentSettings[`${type}ticker`].specificjobsenabled) {
if (
!currentSettings[`${type}ticker`].specificjobs.includes(
gameState.player.job,
)
)
return;
}
if (!activeElements.countdowns.has(`${type}-ticker-bar`)) {
startBarTimer(
GAME_DATA.EFFECT_TICK,
`${type}-ticker-bar`,
false,
true,
true,
);
}
}
// When user's mana changes
function handleManaTick(current, max) {
if (!currentSettings.mpticker.enabled) return;
if (currentSettings.mpticker.specificjobsenabled) {
if (
!currentSettings.mpticker.specificjobs.includes(
gameState.player.job,
)
)
return;
}
let delta = current - gameState.previous_MP;
gameState.previous_MP = current;
let tick = gameState.inCombat
? GAME_DATA.MP_DATA.combat
: GAME_DATA.MP_DATA.normal;
let umbralTick = 0;
if (gameState.player.job === "BLM") {
switch (gameState.player.jobDetail.umbralStacks) {
case -1: {
umbralTick = GAME_DATA.MP_DATA.umbral_1;
break;
}
case -2: {
umbralTick = GAME_DATA.MP_DATA.umbral_2;
break;
}
case -3: {
umbralTick = GAME_DATA.MP_DATA.umbral_3;
break;
}
}
}
let manaTick = Math.floor(max * tick) + Math.floor(max * umbralTick);
let duration = 0;
if (delta === manaTick) {
duration = GAME_DATA.MP_DATA.tick;
if (
gameState.player.job === "BLM" &&
gameState.player.jobDetail.umbralStacks > 0
)
duration = 0;
}
if (duration > 0) {
if (
currentSettings.mpticker.alwaystick &&
activeElements.countdowns.get("mp-ticker-bar") == undefined
) {
startBarTimer(duration, "mp-ticker-bar", false, true, true);
}
if (!currentSettings.mpticker.alwaystick) {
startBarTimer(duration, "mp-ticker-bar", false, true, false);
}
}
}
// Prepare health tags in ui object
function updateHealthTags() {
gameState.playerTags.percentHP = Math.round(
(100 * gameState.player.currentHP) / gameState.player.maxHP,
);
gameState.playerTags.deficitHP = `-${
gameState.player.maxHP - gameState.player.currentHP
}`;
gameState.playerTags.currentMaxHP = `${gameState.player.currentHP} / ${gameState.player.maxHP}`;
}
// Prepare mana tags in ui object
function updateManaTags() {
gameState.playerTags.percentMP = Math.round(
(100 * gameState.player.currentMP) / gameState.player.maxMP,
);
gameState.playerTags.deficitMP = `-${
gameState.player.maxMP - gameState.player.currentMP
}`;
gameState.playerTags.currentMaxMP = `${gameState.player.currentMP} / ${gameState.player.maxMP}`;
}
function abbreviateNumber(num) {
return Math.abs(num) > 999
? Math.sign(num) * (Math.abs(num) / 1000).toFixed(1) + "k"
: Math.sign(num) * Math.abs(num);
}
// Loop through all possible tags and returns text
function processTextFormat(text) {
let tagMap = {
"[health:current]": gameState.player.currentHP,
"[health:current-short]": abbreviateNumber(gameState.player.currentHP),
"[health:current-percent]":
gameState.player.currentHP === gameState.player.maxHP
? `${gameState.player.currentHP}`
: `${gameState.player.currentHP} - ${gameState.playerTags.percentHP}%`,
"[health:current-percent-short]":
gameState.player.currentHP === gameState.player.maxHP
? `${abbreviateNumber(gameState.player.currentHP)}`
: `${abbreviateNumber(gameState.player.currentHP)} - ${
gameState.playerTags.percentHP
}%`,
"[health:current-max]": gameState.playerTags.currentMaxHP,
"[health:max]": gameState.player.maxHP,
"[health:max-short]": abbreviateNumber(gameState.player.maxHP),
"[health:percent]": gameState.playerTags.percentHP,
"[health:deficit]": gameState.playerTags.deficitHP,
"[mana:current]": gameState.player.currentMP,
"[mana:current-short]": abbreviateNumber(gameState.player.currentMP),
"[mana:current-percent]":
gameState.player.currentMP === gameState.player.maxMP
? `${gameState.player.currentMP}`
: `${gameState.player.currentMP} - ${gameState.playerTags.percentMP}%`,
"[mana:current-percent-short]":
gameState.player.currentMP === gameState.player.maxMP
? `${abbreviateNumber(gameState.player.currentMP)}`
: `${abbreviateNumber(gameState.player.currentMP)} - ${
gameState.playerTags.percentMP
}%`,
"[mana:current-max]": gameState.playerTags.currentMaxMP,
"[mana:max]": gameState.player.maxMP,
"[mana:max-short]": abbreviateNumber(gameState.player.maxMP),
"[mana:percent]": gameState.playerTags.percentMP,
"[mana:deficit]": gameState.playerTags.deficitMP,
"[name]": gameState.player.name,
"[name:veryshort]": gameState.player.name.substr(0, 5),
"[name:short]": gameState.player.name.substr(0, 10),
"[name:medium]": gameState.player.name.substr(0, 15),
"[name:long]": gameState.player.name.substr(0, 20),
"[job]": gameState.playerTags.job,
"[job:short]": gameState.player.job,
" ": " ",
};
for (let [key, value] of Object.entries(tagMap)) {
text = text.split(key).join(value);
}
return text;
}
// When user's health changes
function handleHealthUpdate(current, max) {
if (
gameState.playerPrevious.currentHP !== current ||
gameState.playerPrevious.maxHP !== max ||
!ui.labels.health
) {
let health = document.getElementById("health-bar");
health.value = current;
health.max = max;
ui.labels.health = `${gameState.player.currentHP} / ${gameState.player.maxHP}`;
if (currentSettings.healthbar.textformat) {
updateHealthTags();
ui.labels.health = processTextFormat(
currentSettings.healthbar.textformat,
);
}
health.setAttribute(
"data-label",
currentSettings.healthbar.textenabled ? ui.labels.health : "",
);
}
}
// When user's mana changes
function handleManaUpdate(current, max) {
let mana = document.getElementById("mana-bar");
handleManaTick(current, max);
if (
gameState.playerPrevious.currentMP !== current ||
gameState.playerPrevious.maxMP !== max ||
!ui.labels.mana
) {
mana.value = current;
mana.max = max;
ui.labels.mana = `${gameState.player.currentMP} / ${gameState.player.maxMP}`;
if (currentSettings.manabar.textformat) {
updateManaTags();
ui.labels.mana = processTextFormat(
currentSettings.manabar.textformat,
);
}
mana.setAttribute(
"data-label",
currentSettings.manabar.textenabled ? ui.labels.mana : "",
);
}
if (!currentSettings.manabar.jobthresholdsenabled) return;
if (
gameState.player.job === "BLM" ||
gameState.player.job === "DRK" ||
gameState.player.job === "PLD"
) {
if (current <= currentSettings.manabar[gameState.player.job].low) {
mana.style.setProperty(
"--manaBarColor",
`var(${currentSettings.manabar.lowcolor})`,
);
} else if (
current <= currentSettings.manabar[gameState.player.job].med
) {
mana.style.setProperty(
"--manaBarColor",
`var(${currentSettings.manabar.medcolor})`,
);
} else {
mana.style.setProperty(
"--manaBarColor",
`var(${currentSettings.manabar.color})`,
);
}
}
}
// Handles majority of the logic on 15/16 log lines
/* exported handleSkill */
function handleSkill(parameters) {
if (gameState.player === null) return;
let byYou = parameters.player === gameState.player.name;
let onYou = false;
if (parameters.target) {
if (parameters.target === gameState.player.name) onYou = true;
}
let playerIndex = gameState.partyList.findIndex(
(x) => x.name === parameters.player,
);
let ability = undefined;
let mergedAbilityList = abilityList.concat(
currentSettings.customcd.abilities,
);
for (ability of mergedAbilityList.filter(
(x) => x.id == parseInt(parameters.skillid, 16),
)) {
if (ability === undefined) continue;
if (
currentSettings.override.abilities.some(
(x) => x.id == ability.id && x.type == ability.type,
)
) {
ability = currentSettings.override.abilities.find(
(x) => x.id == ability.id && x.type == ability.type,
);
}
if (!ability.enabled) continue;
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (
Object.prototype.hasOwnProperty.call(
ability.extra,
"is_trait_enhanced",
)
) {
if (
gameState.partyList[playerIndex].level ==
ability.extra.is_trait_enhanced[0]
) {
ability.cooldown = ability.extra.is_trait_enhanced[1];
}
}
}
if (ability.name === "Shoha" && byYou) {
adjustJobStacks(0, gameState.stats.maxStacks);
}
if (ability.name === "Ruin IV" && byYou) {
adjustJobStacks(
gameState.stats.stacks - 1,
gameState.stats.maxStacks,
);
gameState.blockRuinGained = true;
setTimeout(function () {
gameState.blockRuinGained = false;
}, 1000);
}
if (ability.type === "RaidBuff") {
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (ability.extra.is_card) {
let abilityHolder = mergedAbilityList.find(
(x) => x.name === "Play",
);
if (onYou) {
startAbilityIconTimers(
playerIndex,
ability,
true,
currentSettings.raidbuffs.alwaysshow
? abilityHolder
: ability,
);
}
}
if (ability.extra.cooldown_only) {
startAbilityIconTimers(playerIndex, ability, false);
}
if (ability.extra.is_song) {
let abilityHolder = mergedAbilityList.find(
(x) => x.name === "Song",
);
if (byYou) {
if (!currentSettings.raidbuffs.alwaysshow) {
for (let song of mergedAbilityList.filter(
(x) =>
Object.prototype.hasOwnProperty.call(
x,
"extra",
) &&
Object.prototype.hasOwnProperty.call(
x.extra,
"is_song",
),
)) {
let selector = `raid-buffs-${playerIndex}-${song.id}`;
if (
activeElements.countdowns.has(
`${selector}-duration`,
)
) {
clearInterval(
activeElements.countdowns.get(
`${selector}-duration`,
),
);
}
if (
activeElements.countdowns.has(
`${selector}-cooldown`,
)
) {
clearInterval(
activeElements.countdowns.get(
`${selector}-cooldown`,
),
);
}
stopAbilityTimer(`${selector}-cooldown`, null);
stopAbilityTimer(`${selector}-duration`, null);
}
}
startAbilityIconTimers(
playerIndex,
ability,
true,
currentSettings.raidbuffs.alwaysshow
? abilityHolder
: ability,
);
}
}
if (ability.extra.is_ss) {
let abilityHolder = mergedAbilityList.find(
(x) => x.id === 15997,
);
startAbilityIconTimers(
playerIndex,
ability,
true,
currentSettings.raidbuffs.alwaysshow
? abilityHolder
: ability,
true,
);
}
if (ability.extra.is_ts) {
let abilityHolder = mergedAbilityList.find(
(x) => x.id === 15998,
);
startAbilityIconTimers(
playerIndex,
ability,
true,
currentSettings.raidbuffs.alwaysshow
? abilityHolder
: ability,
byYou,
);
}
} else {
if (
(!onYou && ability.name === "Dragon Sight") ||
(byYou && ability.name === "Battle Voice")
) {
onYou = false;
} else {
onYou = true;
}
startAbilityIconTimers(playerIndex, ability, onYou);
}
}
if (ability.type === "Mitigation") {
if (onYou || byYou)
startAbilityIconTimers(playerIndex, ability, true);
}
if (ability.type === "Party") {
startAbilityIconTimers(playerIndex, ability, true);
}
if (ability.type === "CustomCooldown") {
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (ability.extra.shares_cooldown) {
let abilityHolder = mergedAbilityList.find(
(x) => x.id === ability.extra.shares_cooldown,
);
startAbilityIconTimers(
playerIndex,
ability,
true,
currentSettings.customcd.alwaysshow
? abilityHolder
: ability,
);
continue;
}
}
startAbilityIconTimers(playerIndex, ability, true);
}
}
}
// Handles majority of the logic on 1A log lines
/* exported handleGainEffect */
function handleGainEffect(parameters) {
if (gameState.player === null) return;
let byYou = parameters.player === gameState.player.name;
let onYou = parameters.target === gameState.player.name;
let playerIndex = gameState.partyList.findIndex(
(x) => x.name === parameters.player,
);
let ability = undefined;
let mergedAbilityList = abilityList.concat(
currentSettings.customcd.abilities,
);
for (ability of mergedAbilityList.filter(
(x) =>
x[`name_${currentSettings.language}`].toLowerCase() ==
parameters.effect.toLowerCase(),
)) {
if (ability === undefined) continue;
if (
currentSettings.override.abilities.some(
(x) => x.name === ability.name && x.type == ability.type,
)
) {
ability = currentSettings.override.abilities.find(
(x) => x.name === ability.name && x.type == ability.type,
);
}
if (!ability.enabled) continue;
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (
Object.prototype.hasOwnProperty.call(
ability.extra,
"is_trait_enhanced",
)
) {
if (
gameState.partyList[playerIndex].level ==
ability.extra.is_trait_enhanced[0]
) {
ability.cooldown = ability.extra.is_trait_enhanced[1];
}
}
}
if (ability.type === "RaidBuff") {
if (
ability.name === "Standard Step" ||
ability.name === "Technical Step" ||
ability.name === "Embolden"
)
continue;
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (ability.extra.isPetAbility) {
let pet = gameState.playerPets.find(
// This might change
(x) => x.id == parameters.playerId,
);
if (pet) {
playerIndex = gameState.partyList.findIndex(
(x) => x.id == pet.ownerId,
);
startAbilityIconTimers(playerIndex, ability, true);
}
}
if (ability.extra.is_card) continue;
if (ability.extra.is_song) {
let abilityHolder = mergedAbilityList.find(
(x) => x.name === "Song",
);
if (byYou) {
continue;
}
if (onYou) {
ability.duration = 5;
startAbilityIconTimers(
playerIndex,
ability,
true,
currentSettings.raidbuffs.alwaysshow
? abilityHolder
: ability,
);
}
}
}
if (onYou) startAbilityIconTimers(playerIndex, ability, true);
}
if (ability.type === "Mitigation") {
if (onYou || byYou) {
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (ability.extra.shares_cooldown) {
startAbilityIconTimers(playerIndex, ability, true);
startAbilityIconTimers(
playerIndex,
mergedAbilityList.find(
(x) => x.id === ability.extra.shares_cooldown,
),
false,
);
}
} else {
startAbilityIconTimers(playerIndex, ability, true);
}
}
}
if (ability.type === "Stacks" && byYou) {
if (!gameState.blockRuinGained)
adjustJobStacks(
gameState.stats.stacks + 1,
gameState.stats.maxStacks,
);
}
if (
(ability.type === "DoT" && byYou) ||
(ability.type === "Buff" && byYou)
) {
ability.duration = parameters.duration;
if (Object.prototype.hasOwnProperty.call(ability, "extra")) {
if (ability.extra.shares_cooldown) {
startAbilityBarTimer(
ability,
parameters.duration,
onYou,
false,
0,
mergedAbilityList.find(
(x) => x.id === ability.extra.shares_cooldown,
),
);
continue;
}
if (ability.extra.extends_duration) {
startAbilityBarTimer(
ability,
parameters.duration,
onYou,
true,
ability.extra.max_duration,
);
continue;
}
}
startAbilityBarTimer(ability, parameters.duration, onYou);
}
}
}
// Handles majority of the logic on 1E log lines
/* exported handleLoseEffect */
function handleLoseEffect(parameters) {
if (gameState.player === null) return;
//let byYou = (parameters.player === currentPlayer.name);
//let onYou = (parameters.target === currentPlayer.name);
let playerIndex = gameState.partyList.findIndex(
(x) => x.name === parameters.player,
);
let ability = undefined;
let mergedAbilityList = abilityList.concat(
currentSettings.customcd.abilities,
);
for (ability of mergedAbilityList.filter(
(x) =>
x[`name_${currentSettings.language}`].toLowerCase() ==
parameters.effect.toLowerCase(),
)) {
if (ability.name == "Standard Step") return;
if (ability.name == "Technical Step") return;
let selectorProperties = getSelectorProperties(ability.type);
let barSelector = selectorProperties.id;
let abilitySelector = `${barSelector}-${playerIndex}-${ability.id}`;
if (activeElements.countdowns.has(`${abilitySelector}-duration`)) {
clearInterval(
activeElements.countdowns.get(`${abilitySelector}-duration`),
);
stopAbilityTimer(`${abilitySelector}-duration`, null);
}
if (activeElements.countdowns.has(`${ability.id}-buff-timer`)) {
clearInterval(
activeElements.countdowns.get(`${ability.id}-buff-timer`),
);
let hideTimer = selectorProperties.settings.hidewhendroppedoff;
stopBarTimer(`${ability.id}-buff-timer`, hideTimer);
}
}
}
// Handles 19 log lines
/* exported handleDeath */
function handleDeath(parameters) {
let you = parameters.target === gameState.player.name;
let playerIndex = gameState.partyList.findIndex(
(x) => x.name === parameters.player,
);
stopPlayerDurationTimers(playerIndex);
if (you) {
if (gameState.player.job === "SMN") {
initializeSmn();
adjustJobStacks(gameState.stats.stacks, gameState.stats.maxStacks);
}
}
}
// Handles changed player stats, mostly to keep the current SKS/SPS modifiers up to date
/* exported handlePlayerStats */
function handlePlayerStats(parameters) {
gameState.stats.skillSpeed =
(1000 +
Math.floor(
(130 *
(parameters.sks -
GAME_DATA.SPEED_LOOKUP.get(gameState.player.level))) /
3300,
)) /
1000;
gameState.stats.spellSpeed =
(1000 +
Math.floor(
(130 *
(parameters.sps -
GAME_DATA.SPEED_LOOKUP.get(gameState.player.level))) /
3300,
)) /
1000;
}
// Functions for debugging
function toLog(parameters) {
if (currentSettings) {
if (!currentSettings.debug.enabled) return;
for (let parameter of parameters) {
console.log(parameter);
}
}
}
/* exported testLog */
function testLog(logLine) {
let logEvent = {
type: "onLogEvent",
detail: {
logs: [logLine],
},
};
onLogEvent(logEvent);
}
<file_sep>/CUSTOMCSS.md
Here I'll place some example CSS for some regularly asked features/setups.
## Skin the HP and MP bar regularly without using game images/textures.
This example has been made with some extra settings: https://i.imgur.com/bwTdWBH.png

```css
#health-bar,
#mana-bar {
-webkit-text-stroke: 0.45px rgba(0, 0, 0, 0.1);
font-weight: bold !important;
text-shadow: 1.5px 1.5px black;
-webkit-font-smoothing: antialiased;
width: 200px !important;
height: 40px !important;
}
#health-bar {
height: 40px !important;
}
#mana-bar {
height: 10px !important;
}
#health-bar::-webkit-progress-value,
#mana-bar::-webkit-progress-value {
background-size: auto !important;
background-image: linear-gradient(Gray, LightGray) !important;
}
#health-bar::-webkit-progress-bar,
#mana-bar::-webkit-progress-bar {
background-size: auto !important;
background-image: linear-gradient(black, black) !important;
border-style: solid;
border-width: 2px;
}
```
<br />
## HP/MP Text Color
```css
#health-bar:after,
#mana-bar:after {
color: red !important;
}
```
<br />
## Adjust Party Buff Rows per party member (adjust the numbers in each translate to the correct location).
If you use Grow to the left you need negative values.
```css
#party-row-1 {
position: absolute;
transform: translate(200px, 200px);
}
#party-row-2 {
position: absolute;
transform: translate(200px, 300px);
}
#party-row-3 {
position: absolute;
transform: translate(200px, 400px);
}
#party-row-4 {
position: absolute;
transform: translate(200px, 500px);
}
#party-row-5 {
position: absolute;
transform: translate(400px, 200px);
}
#party-row-6 {
position: absolute;
transform: translate(400px, 300px);
}
#party-row-7 {
position: absolute;
transform: translate(400px, 400px);
}
#party-row-8 {
position: absolute;
transform: translate(400px, 500px);
}
```
If you want any of the custom positioned Party Rows to grow from right to left, you need to add these to the #party-row-number css:
```css
right: 0px;
bottom: 0px;
```
And on flex-direction on the boxes:
```css
#party-row-1-box {
flex-direction: row-reverse;
}
```
<br />
## More Custom CSS Options for manually positioning Party Cooldowns by rhopland

```css
#party-row-1 {
grid-area: party-1;
/*border: 2px solid red; */
}
#party-row-2 {
grid-area: party-2;
/*border: 2px solid red;*/
}
#party-row-3 {
grid-area: party-3;
/*border: 2px solid red;*/
}
#party-row-4 {
grid-area: party-4;
/*border: 2px solid red; */
}
#party-row-5 {
grid-area: party-5;
/*border: 2px solid red; */
}
#party-row-6 {
grid-area: party-6;
/*border: 2px solid red; */
}
#party-row-7 {
grid-area: party-7;
/*border: 2px solid red;*/
}
#party-row-8 {
grid-area: party-8;
/*border: 2px solid red; */
}
#party-bar {
/*border: 2px solid black; */
display: grid !important;
grid-template-columns: fit-content(100px) 360px fit-content(100px) !important;
grid-template-rows: repeat(4, 80px) !important;
grid-template-areas:
"party-1 . party-2"
"party-3 . party-4"
"party-5 . party-6"
"party-7 . party-8" !important;
}
#party-row-1-box,
#party-row-2-box,
#party-row-3-box,
#party-row-4-box,
#party-row-5-box,
#party-row-6-box,
#party-row-7-box,
#party-row-8-box {
/*border: 2px solid yellow;*/
display: flex;
width: 200px;
height: 79px;
flex-wrap: wrap;
}
#party-row-1-box,
#party-row-3-box,
#party-row-5-box,
#party-row-7-box {
justify-content: right;
flex-direction: row-reverse;
}
```
<br />
## Nicer looking pulltimer by rhopland

```css
#timer-bar {
width: 600px !important;
height: 40px !important;
}
#timer-bar:after {
color: yellow !important;
font-size: 34px !important;
/*border: 2px solid red;*/
float: right;
margin-top: -25px;
margin-right: -45px;
}
#timer-bar::-webkit-progress-bar {
border-style: solid;
border-width: 1px;
background-size: auto !important;
background-image: linear-gradient(Gray, LightGray) !important;
}
#timer-bar::-webkit-progress-value {
background-size: auto !important;
background-image: linear-gradient(Gray, LightGray) !important;
}
```
## Miniguide by rhopland:
Do you want to see the structure as you change it? Remove the /* ... */ from all "border" elements.
This will let you see the outline.
Change width between left and right side of cooldown tracker:
1. Find `#party-bar`
2. Within the brackets {} after #party-bar, find `grid-template-columns`. Edit the center px value.
Change how many icons show before you break to next line:
1. Find `#party-row-X-box`, where X is 1 to 8. There should be a comma between each.
2. Within the brackets {}, find width. Make it smaller for fewer icons, or bigger for more.
Change height of the icon space (for party frames taller or shorter than 80px):
1. Find `#party-bar`
2. Within the brackets {}, find `grid-template-rows: repeat(4, 80px)` Change the pixel value to desired height.
3. Find `#party-row-X-box`, where X is 1 to 8. There should be a comma between each.
4. Change `height` to either the same as or 1 px smaller than the value you changed above.
5. (Optional) If you icons now seem small or overlap, go in ZeffUI settings and go to party frames options. Change the `scale` value as desired.
<file_sep>/data/regex.js
/* exported regexList */
var regexList = {
"00": {
regex: /^\[[^\]]+\] ChatLog 00:/,
matches: [
// CHINESE
{
regex: /距离战斗开始还有(?<seconds>[0-9]{1,2})秒!\s*(.{1,12})/,
function: "handleCountdownTimer",
},
{
regex: /“.*”任务开始。/,
function: "onInstanceStart",
},
{
regex: /“.*”任务结束了。/,
function: "onInstanceEnd",
},
// ENGLISH
{
regex: /Battle commencing in (?<seconds>[0-9]{1,2}) seconds! \([a-zA-Z-' ]{2,31}\)/,
function: "handleCountdownTimer",
},
{
regex: /[\w-'èéêîïôàæûç,:\-() ]{1,99} has begun\./,
function: "onInstanceStart",
},
{
regex: /[\w-'èéêîïôàæûç,:\-() ]{1,99} has ended\./,
function: "onInstanceEnd",
},
// FRENCH La mission “La Crique aux tributs” commence.
{
regex: /Début du combat dans (?<seconds>[0-9]{1,2}) secondes! \([a-zA-Z-w' ]{2,31}\)/,
function: "handleCountdownTimer",
},
{
regex: /La mission “.*” commence\./,
function: "onInstanceStart",
},
{
regex: /La mission “.*” prend fin\./,
function: "onInstanceEnd",
},
// GERMAN
{
regex: /Noch (?<seconds>[0-9]{1,2}) Sekunden bis Kampfbeginn! \([a-zA-Z-' ]{2,31}\)/,
function: "handleCountdownTimer",
},
{
regex: /„.*“ hat begonnen\./,
function: "onInstanceStart",
},
{
regex: /„.*“ wurde beendet\./,
function: "onInstanceEnd",
},
// JAPANESE
{
regex: /戦闘開始まで(?<seconds>[0-9]{1,2})秒! ([a-zA-Z-' ]{2,31})/,
function: "handleCountdownTimer",
},
{
regex: /「.*」の攻略を開始した。/,
function: "onInstanceStart",
},
{
regex: /「.*」の攻略を終了した。/,
function: "onInstanceEnd",
},
// KOREAN
{
regex: /\/전투 시작 (?<seconds>[0-9]{1,2})초 전! ([a-zA-Z-' ]{2,31})/,
function: "handleCountdownTimer",
},
{
regex: /.* 공략을 시작합니다./,
function: "onInstanceStart",
},
{
regex: /.* 공략을 종료했습니다./,
function: "onInstanceEnd",
},
// COMMAND
{
regex: /\/zeffui/,
function: "handleSettings",
},
],
},
"03": {
regex: /^\[[^\]]+\] AddCombatant 03:/,
matches: [
{
//regex: /(?<id>(?:[0-9A-F]{8})):Added new combatant (?<name>(?:[^:]*?))\. {2}Job: (?<job>(?:[^:]*?)) Level: (?<level>(?:[^:]*?)) Max HP: (?<hp>(?:[0-9]+))..*?Pos: \((?<x>(?:-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?)),(?<y>(?:-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?)),(?<z>(?:-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?))\)(?: \((?<npcId>(?:.*?))\))?\./,
regex: /^\[[^\]]+\] AddCombatant (?<type>03):(?<id>(?:[^:]*)):(?<name>(?:[^:]*)):(?<job>(?:[^:]*)):(?<level>(?:[^:]*)):(?<ownerId>(?:[^:]*)):(?<worldId>(?:[^:]*)):(?<world>(?:[^:]*)):(?<npcNameId>(?:[^:]*)):(?<npcBaseId>(?:[^:]*)):(?<currentHp>(?:[^:]*)):(?<hp>(?:[^:]*)):(?<currentMp>(?:[^:]*)):(?<mp>(?:[^:]*))(?::[^:]*){2}:(?<x>(?:[^:]*)):(?<y>(?:[^:]*)):(?<z>(?:[^:]*)):(?<heading>(?:[^:]*))(?:$|:)/,
function: "handleAddNewCombatant",
},
],
},
"04": {
regex: /^\[[^\]]+\] RemoveCombatant 04:/,
matches: [
{
//regex: /(?<id>(?:[0-9A-F]{8})):Added new combatant (?<name>(?:[^:]*?))\. {2}Job: (?<job>(?:[^:]*?)) Level: (?<level>(?:[^:]*?)) Max HP: (?<hp>(?:[0-9]+))..*?Pos: \((?<x>(?:-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?)),(?<y>(?:-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?)),(?<z>(?:-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?))\)(?: \((?<npcId>(?:.*?))\))?\./,
regex: /^\[[^\]]+\] RemoveCombatant (?<type>04):(?<id>(?:[^:]*)):(?<name>(?:[^:]*)):(?<job>(?:[^:]*)):(?<level>(?:[^:]*)):(?<owner>(?:[^:]*)):[^:]*:(?<world>(?:[^:]*)):(?<npcNameId>(?:[^:]*)):(?<npcBaseId>(?:[^:]*)):[^:]*:(?<hp>(?:[^:]*))(?::[^:]*){4}:(?<x>(?:[^:]*)):(?<y>(?:[^:]*)):(?<z>(?:[^:]*)):(?<heading>(?:[^:]*))(?:$|:)/,
function: "handleRemoveCombatant",
},
],
},
"0C": {
regex: /^\[[^\]]+\] PlayerStats 0C:/,
matches: [
{
//regex: /PlayerStats 0C: [0-9]{2}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:[0-9]{1,4}:(?<sks>[0-9]{1,4}):(?<sps>[0-9]{1,4}):0:[0-9]{1,4}/,
regex: /^\[[^\]]+\] PlayerStats (?<type>0C):(?<job>(?:[^:]*)):(?<strength>(?:[^:]*)):(?<dexterity>(?:[^:]*)):(?<vitality>(?:[^:]*)):(?<intelligence>(?:[^:]*)):(?<mind>(?:[^:]*)):(?<piety>(?:[^:]*)):(?<attackPower>(?:[^:]*)):(?<directHit>(?:[^:]*)):(?<criticalHit>(?:[^:]*)):(?<attackMagicPotency>(?:[^:]*)):(?<healMagicPotency>(?:[^:]*)):(?<determination>(?:[^:]*)):(?<sks>(?:[^:]*)):(?<sps>(?:[^:]*)):[^:]*:(?<tenacity>(?:[^:]*)):(?<localContentId>(?:[^:]*))(?:$|:)/,
function: "handlePlayerStats",
},
],
},
"1A": {
regex: /^\[[^\]]+\] StatusAdd 1A:/,
matches: [
{
//regex: /(?<targetid>[A-F0-9]{8}):(?<target>.*) gains the effect of (?<effect>.*) from (?<player>[^)]*) for (?<duration>\d{1,4}\.?(\d{1,2})?) Seconds\./,
regex: /^\[[^\]]+\] StatusAdd (?<type>1A):(?<effectId>(?:[^:]*)):(?<effect>(?:(?:[^:]|: )*?)):(?<duration>(?:[^:]*)):(?<playerId>(?:[^:]*)):(?<player>(?:[^:]*)):(?<targetId>(?:[^:]*)):(?<target>(?:[^:]*)):(?<count>(?:[^:]*)):(?<targetMaxHp>(?:[^:]*)):(?<sourceMaxHp>(?:[^:]*))(?:$|:)/,
function: "handleGainEffect",
},
],
},
"1E": {
regex: /^\[[^\]]+\] StatusRemove 1E:/,
matches: [
{
//regex: /(?<targetid>[A-F0-9]{8}):(?<target>.*) loses the effect of (?<effect>.*) from (?<player>[^)]*)\./,
regex: /^\[[^\]]+\] StatusRemove (?<type>1E):(?<effectId>(?:[^:]*)):(?<effect>(?:(?:[^:]|: )*?)):[^:]*:(?<playerId>(?:[^:]*)):(?<player>(?:[^:]*)):(?<targetId>(?:[^:]*)):(?<target>(?:[^:]*)):(?<count>(?:[^:]*))(?:$|:)/,
function: "handleLoseEffect",
},
],
},
15: {
regex: /^\[[^\]]+\] ActionEffect 15:/,
matches: [
{
//regex: /(?<playerid>[A-F0-9]{8}):(?<player>[^:]*):(?<skillid>[A-F0-9]{2,4}):(?<skillname>.*):(?<targetid>[A-F0-9]{8})?:(?<target>[^:]*)?:(?<power>\d)?[^:]+(?::[^:]*){37}$/,
regex: /^\[[^\]]+\] ActionEffect (?<type>(?:15|16)):(?<playerid>(?:[^:]*)):(?<player>(?:[^:]*)):(?<skillid>(?:[^:]*)):(?<skillname>(?:(?:[^:]|: )*?)):(?<targetid>(?:[^:]*)):(?<target>(?:[^:]*)):(?<flags>(?:[^:]*)):(?<damage>(?:[^:]*))(?::[^:]*){14}:(?<targetCurrentHp>(?:[^:]*)):(?<targetMaxHp>(?:[^:]*)):(?<targetCurrentMp>(?:[^:]*)):(?<targetMaxMp>(?:[^:]*))(?::[^:]*){2}:(?<targetX>(?:[^:]*)):(?<targetY>(?:[^:]*)):(?<targetZ>(?:[^:]*)):(?<targetHeading>(?:[^:]*)):(?<currentHp>(?:[^:]*)):(?<maxHp>(?:[^:]*)):(?<currentMp>(?:[^:]*)):(?<maxMp>(?:[^:]*))(?::[^:]*){2}:(?<x>(?:[^:]*)):(?<y>(?:[^:]*)):(?<z>(?:[^:]*)):(?<heading>(?:[^:]*)):(?<sequence>(?:[^:]*)):(?<targetIndex>(?:[^:]*))(?:$|:)/,
function: "handleSkill",
},
],
},
16: {
regex: /^\[[^\]]+\] AOEActionEffect 16:/,
matches: [
{
//regex: /(?<playerid>[A-F0-9]{8}):(?<player>[^:]*):(?<skillid>[A-F0-9]{2,4}):(?<skillname>.*):(?<targetid>[A-F0-9]{8})?:(?<target>[^:]*)?:(?<power>\d)?[^:]+(?::[^:]*){37}$/,
regex: /^\[[^\]]+\] AOEActionEffect (?<type>(?:15|16)):(?<playerid>(?:[^:]*)):(?<player>(?:[^:]*)):(?<skillid>(?:[^:]*)):(?<skillname>(?:(?:[^:]|: )*?)):(?<targetid>(?:[^:]*)):(?<target>(?:[^:]*)):(?<flags>(?:[^:]*)):(?<damage>(?:[^:]*))(?::[^:]*){14}:(?<targetCurrentHp>(?:[^:]*)):(?<targetMaxHp>(?:[^:]*)):(?<targetCurrentMp>(?:[^:]*)):(?<targetMaxMp>(?:[^:]*))(?::[^:]*){2}:(?<targetX>(?:[^:]*)):(?<targetY>(?:[^:]*)):(?<targetZ>(?:[^:]*)):(?<targetHeading>(?:[^:]*)):(?<currentHp>(?:[^:]*)):(?<maxHp>(?:[^:]*)):(?<currentMp>(?:[^:]*)):(?<maxMp>(?:[^:]*))(?::[^:]*){2}:(?<x>(?:[^:]*)):(?<y>(?:[^:]*)):(?<z>(?:[^:]*)):(?<heading>(?:[^:]*)):(?<sequence>(?:[^:]*)):(?<targetIndex>(?:[^:]*))(?:$|:)/,
function: "handleSkill",
},
],
},
18: {
regex: /^\[[^\]]+\] DoTHoT 18:/,
matches: [
{
//regex: /18:(?<ability>.*)?(?<effect>DoT|HoT) Tick on (?<target>.*) for (?<value>\d{1,6}) damage\./,
regex: /^\[[^\]]+\] DoTHoT (?<type>(?:18)):(?<playerid>(?:[^:]*)):(?<player>(?:[^:]*)):(?<effect>DoT|HoT):(?<skillid>[A-F0-9]{1,4}):(?<value>[A-F0-9]{1,4}):/,
function: "handleEffectTick",
},
],
},
19: {
regex: /^\[[^\]]+\] Death 19:/,
matches: [
{
//regex: /19:(?<target>.*) was defeated by (?<killer>.*)\./,
regex: /^\[[^\]]+\] Death (?<type>19):(?<targetId>(?:[^:]*)):(?<target>(?:[^:]*)):(?<killerId>(?:[^:]*)):(?<killer>(?:[^:]*))(?:$|:)/,
function: "handleDeath",
},
],
},
};
<file_sep>/TEXTFORMAT.md
The text format function is ElvUI inspired and these are the ones currently implemented:
[health:current] Current HP
[health:current-short] Current HP (short format like 132.1k)
[health:current-percent] Current HP and percent when not at full HP
[health:current-percent-short] Current HP and percent when not at full HP (short format like 132.1k)
[health:current-max] Current HP / Max HP (this is the default Health Format)
[health:max] Max HP
[health:max-short] Max HP (short format like 132.1k)
[health:percent] Current HP in percentage
[health:deficit] Current HP deficit
[mana:current] Current MP
[mana:current-short] Current MP (short format like 2.4k)
[mana:current-percent] Current MP and percent when not at full MP
[mana:current-percent-short] Current MP and percent when not at full MP (short format like 2.4k)
[mana:current-max] Current MP / Max MP (this is the default Mana Format)
[mana:max] Max MP
[mana:max-short] Max MP (short format like 2.4k)
[mana:percent] Current MP in percentage
[mana:deficit]: Current MP deficit
[name] Player Name
[name:veryshort] Player Name (5 chars)
[name:short] Player Name (10 chars)
[name:medium] Player Name (15 chars)
[name:long] Player Name (20 chars)
[job] Player Job
[job:short] Player Job Shorthand
<file_sep>/UIEXPORTS.md
## Zeffuro's UI (19th of August 2021)

##### ZeffUI Export
<details>
<KEY>
</details>
##### Kagerou Export
<details>
<KEY>
</details>
##### Kagerou Custom CSS
<details>
body {
font-weight: bold;
text-shadow: 1px 1px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000 !important;
}
#patchnote {
visibility: hidden;
}
#init-menu {
visibility: hidden;
}
.flex-column-i-name {
overflow: visible !important;
}
</details>
## Zeffuro's Kagerou (23th of September 2021)
Based on Vond's Kagerou Export (see our Discord for that).

<details> <KEY>
</details>
##### Kagerou Custom CSS
<details>
li#header {
background-color: rgba(61, 61, 61, 0.6) !important;
}
#header .flex-column {
border-top: none;
}
#header .flex-column-i-icon {
border: none;
}
#header .flex-column-deal-per-second {
border-top: none;
}
.container {
height: 25px !important;
}
span.flex-column {
padding: 0 5px;
border-top: 0.1em solid #000;
}
.flex-column-i-icon {
background-color: rgba(8,8,8,0.85);
border-right: 0.1em solid #000;
}
body {
transition: all .5s ease-in-out;
text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
text-rendering: optimizeLegibility;
}
nav {
height: 26px !important;
font-size: 11px !important;
line-height: normal !important;
background-color: rgba(61, 61, 61, 0.6) !important;
}
footer {
font-size: 12px !important;
background-color: rgba(61, 61, 61, 0.6) !important;
border-top: 0.1em solid #000;
}
.history {
position: relative;
align-items: center !important;
line-height: 25px !important;
overflow: hidden;
}
.history > .icon-container {
display: flex !important;
align-items: center;
}
#history-icon svg {
display: none;
}
#history-time {
margin-left: 4px;
font-size: 14px;
}
#history-mob {
margin-left: 4px;
height: 100%;
font-size: 14px;
}
#history-region {
display: none;
}
li#init-menu {
display: none !important;
}
#patchnote {
overflow: visible;
}
#patchnote:before {
content: '';
position: relative;
top: 8px;
font-size: 1.1em;
}
#patchnote > *{
display: none;
}
#background {
background-color: rgba(8, 8, 8, 0.6) !important;
}
.flex-column.flex-column-i-name {
width: auto;
flex-grow: 1;
min-width: 0;
align-self: stretch;
}
.flex-column.flex-column-deal-accuracy {
width: 3.5rem;
}
.flex-column.flex-column-heal-over,
.flex-column.flex-column-etc-death {
width: 2.5rem;
}
</details>
## Maximum-like UI (20th of August 2021)

This will serve as a starting point, however it's important to point out some differences: Maximum uses XIVLauncher plugins to seperate the official HP/MP bar with SimpleTweaks
He also mixes real actionbars in to keep track of certain combos and procs.
Also uses [Material Dark](https://github.com/skotlex/ffxiv-material-ui) Mod for the rest of his textures in his game.
##### ZeffUI Export
<details>
<KEY>
</details>
## Vivian Extra Party CDs Full Tank Defensive Kit

#### ZeffUI Export (Custom Cooldowns mostly)
<details>
<KEY>
</details>
| 9701c59142fc92a25ce8b253233c352017b18958 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | thewakingsands/ZeffUI | 54f9e79a174594595aa22bd31d9a74106c1d4021 | 5071224c3d0c623ed6a7d7f1e9814eb85e0d55d5 |
refs/heads/master | <file_sep>for i in (1...101)
if (i % 3 == 0) and (i % 5 == 0)
puts "FizzBuzz"
elsif (i % 3 == 0)
puts "Fizz"
elsif (i % 5 == 0)
puts "Buzz"
else
puts "#{i}"
end
end
| 00378bb6ce311d1c3475a41008a5215776a6a732 | [
"Ruby"
] | 1 | Ruby | shinyamagami/fizzbuzz_in_ruby | 8065358446e0df997161a0225f96b299ffcc1c4a | 039971e90ffb5c0097aa8e506bf426aa458dc5cc |
refs/heads/main | <repo_name>merihamidah/atw-project02<file_sep>/project/index.js
const express = require ('express')
const app = express();
const port = 3000
const path = require('path')
const bodyParser = require('body-parser');
const mongoose =require('mongoose');
const { Schema } = mongoose;
app.use(express.urlencoded({ extended:true}));
app.use(express.json());
app.use(express.static('public'))
app.set('views', './views')
app.set('view engine', 'ejs')
mongoose.connect('mongodb://localhost/atw',{useNewUrlParser: true, useUnifiedTopology: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log("horray terkoneksi ")
})
const ProductSchema = new Schema({
nama : String,
harga : Number,
stok : Number
})
const Product = mongoose.model('Product', ProductSchema)
app.get('/',(req,res)=> res.render("template"))
//index produk
app.get('/master-data/products', (req,res) => {
Product.find({}, (err, items) =>{
res.render("products/index", {items})
})
})
//create
app.get('/master-data/products/create', (req,res) => res.render("products/create"))
//store
app.post('/master-data/products', (req,res) => {
let product = new Product({
nama : req.body.nama,
harga : req.body.harga,
stok : req.body.stok
})
.save((err,item) => {
if(err) res.send("Error Menyimpan Data")
res.redirect("/master-data/products")
})
})
//show
app.get('/master-data/products/:id', (req,res) =>{
Product.findOne({_id: req.params.id},(err,item)=>{
if(err) res.render("errors/404")
res.render("products/show", {item})
})
})
//edit
app.get('/master-data/products/:id/edit', (req, res) => {
Product.findOne({ _id: req.params.id }, (err, item) => {
if (err) res.render("errors/404")
res.render("products/edit", { item })
})
})
//update
app.post('/master-data/products/:id', (req, res) => {
Product.findOne({ _id: req.params.id }, (err, product) => {
if (err) res.render("errors/404")
product.nama = req.body.nama
product.harga = req.body.harga
product.stok = req.body.stok
product.save((err,item) => {
if(err) res.send("Error menyimpan data")
res.redirect("/master-data/products")
})
})
})
//delete
app.get('/master-data/products/:id/delete', (req,res) => {
Product.deleteOne({_id: req.params.id},(err,product) =>{
if(err) res.render("errors/404")
res.redirect("/master-data/products");
})
})
app.listen(port, ()=> console.log("Server jalan diport "+port))
| 61e56f1b7991a120d09e8c89ed42afec89928480 | [
"JavaScript"
] | 1 | JavaScript | merihamidah/atw-project02 | 832bd47c050036bd9a588ebadc6478d2cad82d31 | e5a934874c29f946437eabbe36bbdf9c57bff2e7 |
refs/heads/master | <file_sep>// function
function playVieo() {
// video.play();
const match = video.paused ? 'play' : 'pause';
video[match]();
}
function changeButton() {
// console.log('btn')
const btn = video.paused ? '►' : 'l l';
button.textContent = btn;
}
function skipFuncton(e) {
// console.log(this.dataset.skip);
video.currentTime += parseFloat(this.dataset.skip);
}
function changeValueSpeed(e) {
// console.log(this.value);
video[this.name] = this.value;
}
function updateVideoLane() {
// console.log(video.currentTime);
// console.log(video.duration)
const timeLine = video.currentTime / video.duration * 100;
// console.log(timeLine);
progress__filled.style.flexBasis = `${timeLine}%`;
}
function mouseVideoUpdate(e) {
// console.log(e.offsetX);
// console.log('e.offsetX / progress.clientWidth', e.offsetX / progress.clientWidth);
// console.log('e.offsetX / progress.clientWidth * video.duration', e.offsetX / progress.clientWidth * video.duration);
const newTime = e.offsetX / progress.clientWidth * video.duration;
video.currentTime = newTime;
}
// Select element
const video = document.querySelector('.viewer');
const progress = document.querySelector('.progress');
const button = document.querySelector('.toggle');
const skips = document.querySelectorAll('.player__button');
const sliders = document.querySelectorAll('.player__slider');
const progress__filled = document.querySelector('.progress__filled');
//listenerd
video.addEventListener('click', playVieo);
video.addEventListener('play', changeButton);
video.addEventListener('pause', changeButton);
button.addEventListener('click', playVieo);
skips.forEach( skip => {
skip.addEventListener('click', skipFuncton);
})
sliders.forEach( slider => {
slider.addEventListener('change', changeValueSpeed);
slider.addEventListener('mousemove', changeValueSpeed);
})
video.addEventListener('timeupdate', updateVideoLane);
let isClicked = false;
progress.addEventListener('click', mouseVideoUpdate);
progress.addEventListener('mousemove', (e) => isClicked && mouseVideoUpdate(e));
progress.addEventListener('mouseup', () => isClicked = false);
progress.addEventListener('mousedown', () => isClicked = true);<file_sep>let countDown;
const blockLeft = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function time(seconds) {
clearInterval(countDown);
const now = Date.now();
const then = now + seconds * 1000;
displayTime(seconds);
displayEndTime(then);
countDown = setInterval( () => {
const secondLeft = Math.round( (then - Date.now()) / 1000);
if (secondLeft < 0) {
clearInterval(countDown);
return;
}
displayTime(secondLeft);
}, 1000)
}
function displayTime(seconds) {
const minutes = Math.floor(seconds / 60);
const secondLeft = seconds % 60;
const display = `${minutes}:${secondLeft < 10 ? '0' : ''}${secondLeft}`;
blockLeft.textContent = display;
// console.log(minutes, secondLeft);
}
function displayEndTime(seconds) {
const end = new Date(seconds);
const hour = end.getHours();
const minutes = end.getMinutes();
const display = `End time ${hour}:${minutes < 10 ? '0' : ''}${minutes}`
// console.log(end);
endTime.textContent = display;
}
function startTime() {
// console.log(this.dataset.time)
const data = parseInt(this.dataset.time);
time(data);
}
buttons.forEach( button => button.addEventListener('click', startTime) );
document.customForm.addEventListener('submit', function(e) {
e.preventDefault();
// console.log(this.minutes.value);
const minutes = this.minutes.value * 60;
time(minutes);
this.reset();
}); | b43da19737216d9b1981204702198087f75f31d6 | [
"JavaScript"
] | 2 | JavaScript | Illia-Sokol/JS30 | a8febb42abc00c458a3322581c93088c6c61a23c | 658dc9e9370fff088b0f75add29621f3e5b2bd38 |
refs/heads/master | <repo_name>ganeshkumar/cf-to-tf<file_sep>/tests/cleanHCL.js
const cleanHCL = require('./../lib/cleanHCL');
const path = require('path');
const fs = require('fs');
test('clean', () => {
const cwd = path.basename(__dirname);
const hcl = fs.readFileSync(cwd + '/fixtures/example.tf', 'utf8');
const expected = fs.readFileSync(cwd + '/fixtures/example-clean.tf', 'utf8');
const opts = {};
return cleanHCL.clean(opts, hcl).then(result => {
expect(result).toEqual(expected);
});
});
<file_sep>/README.md
<table width="100%">
<tr>
<td align="left" width="80%">
<strong>CloudFormation to Terraform</strong><br />
A simple cli tool for generating Terraform configuration for existing CloudFormation templates.
</td>
<td align="center" width="20%">
<a href="https://travis-ci.org/humanmade/cf-to-tf">
<img src="https://travis-ci.org/humanmade/cf-to-tf.svg?branch=master" alt="Build status">
</a>
</td>
</tr>
<tr>
<td align="center">
A <strong><a href="https://hmn.md/">Human Made</a></strong> project. Maintained by @nathanielks.
</td>
<td align="center">
<img src="https://hmn.md/content/themes/hmnmd/assets/images/hm-logo.svg" width="100" />
</td>
</tr>
</table>
# CloudFormation to Terraform
This node CLI tool is used for generating both Terraform configuration files as well as Terraform state so that you can use Terraform to manage CloudFormation templates. To further clarify, it does not generate terraform configuration for the individual resources CloudFormation provisions, it generates an `aws_cloudformation_stack` resource so that you can manage your existing CloudFormation stacks with Terraform instead of or in conjunction with the AWS Console and CLI.
## Getting Started
```
npm i -g @humanmade/cf-to-tf
```
### Recommended Dependencies
As this was designed to generate Terraform resources, it'd be a good idea to install [`terraform`](https://www.terraform.io/intro/getting-started/install.html). You can install the binary by itself or use a tool like `brew` to manage it for you.
It's also recommended to install [`json2hcl`](https://github.com/kvz/json2hcl) as this will assist in processing output from `cf-to-tf` later.
## Demo
Let's use the following CloudFormation Stack response as an example:
```
{
"Stacks": [
{
"StackId": "arn:aws:cloudformation:eu-central-1:123456789012:stack/foobarbaz/255491f0-71b8-11e7-a154-500c52a6cefe",
"Description": "FooBar Stack",
"Parameters": [
{
"ParameterValue": "bar",
"ParameterKey": "foo"
},
{
"ParameterValue": "baz",
"ParameterKey": "bar"
},
{
"ParameterValue": "qux",
"ParameterKey": "baz"
}
],
"Tags": [
{
"Value": "bar",
"Key": "foo"
},
{
"Value": "qux",
"Key": "baz"
}
],
"Outputs": [
{
"Description": "Foobarbaz",
"OutputKey": "FooBarBaz",
"OutputValue": "output value"
}
],
"CreationTime": "2017-07-26T04:08:57.266Z",
"Capabilities": [
"CAPABILITY_IAM"
],
"StackName": "foobarbaz",
"NotificationARNs": [],
"StackStatus": "CREATE_COMPLETE",
"DisableRollback": true
}
]
}
```
Running `cf-to-tf --stack foobarbaz config | json2hcl | cf-to-tf clean-hcl | terraform fmt -` will generate the following config:
```
resource "aws_cloudformation_stack" "network" {
capabilities = ["CAPABILITY_IAM"]
disable_rollback = true
name = "foobarbaz"
parameters = {
foo = "bar"
bar = "baz"
baz = "qux"
}
tags = {
foo = "bar"
baz = "qux"
}
}
```
## Usage
```
Usage: cf-to-tf [options] [command]
Options:
-s, --stack <stack> The CloudFormation stack to import
-r, --resource-name <resourceName> The name to assign the terraform resource
-h, --help output usage information
Commands:
config Generates Terraform configuration in JSON
state Generates Terraform state file in JSON
template Prints the CloudFormation Stack Template
clean-hcl Cleans generated HCL according to my preferences
```
### Terraform JSON Files
This tool is designed to be used in conjunction with other tools. It will only output the data to `STDOUT` and is designed to be piped to another program to write the file to a location. For example, to generate a configuration file for a stack named `lambda-resources`, we could do the following:
```
cf-to-tf -s lambda-resources config | tee main.tf.json
```
This command will fetch a CloudFormation stack named `lambda-resources` and generate the required Terraform configuration for it. We then pipe the output to `tee` which will write to a file named `main.tf.json`. Because HCL is JSON compatible, Terraform can read the `main.tf.json` natively.
### Terraform State
To generate the associated Terraform state for this CloudFormation stack, you would run the following:
```
cf-to-tf -s lambda-resources state | tee terraform.tfstate
```
This will create a state file from scratch. It assumes you don't already have an existing state file in place. I'm considering updating the tool to write just the resource portion of the state so it can be added to an existing state file, but that wasn't an immediate priority.
### Pretty Printing
Both of these commands will generate compressed JSON output, meaning whitespace has been stripped. To pretty print the output for enhanced readability, you could pipe the output to `jq`, and then to `tee`:
```
cf-to-tf -s lambda-resources config | jq '.' | tee main.tf.json
cf-to-tf -s lambda-resources state | jq '.' | tee terraform.tfstate
```
### Generating HCL
It's also possible to use a tool called [`json2hcl`](https://github.com/kvz/json2hcl) to generate HCL:
```
cf-to-tf -s lambda-resources config | json2hcl | tee main.tf
```
Unfortunately, while `json2hcl` outputs valid HCL, it's not in the format I like. To solve that problem, the `clean-hcl` command is also available. To output HCL in the format you'll normally see, you can execute this chain:
```
cf-to-tf -s lambda-resources config | json2hcl | cf-to-tf clean-hcl | terraform fmt - | tee main.tf
```
We're doing the same thing we were doing before, but now we're also piping the result to `cf-to-tf clean-hcl` which formats the file a certain way, then piping it to `terraform fmt -` which formats the file further (primarily, this tool aligns `=` and adds newlines where necessary).
### Reading from STDIN
It's also possible to have `cf-to-tf` read stack data from `STDIN`. For example, if you have the JSON response from the `aws-cli` call stored in a variable for re-use, you can do the following:
```
JSON="$(aws cloudformation describe-stacks --stack-name lambda-resources)"
echo "$JSON" | cf-to-tf -s - config
```
### AWS Authentication
The command uses the AWS SDK under the hood to retrieve the CloudFormation stack details, so set your authentication credentials as you would normally (`~/.aws/credentials`, `AWS_PROFILE`, `AWS_REGION`, etc).
### Batch Import scripts
For an example of how to use this script in batch operations importing multiple stacks in multiple regions, refer to [this gist](https://gist.github.com/nathanielks/9282d59ab065f8ee0e373ca7199df085).
<file_sep>/lib/stack.js
const AWS = require('aws-sdk');
module.exports = opts => {
const CF = new AWS.CloudFormation({ apiVersion: '2010-05-15' });
return CF.describeStacks({
StackName: opts.stack,
}).promise();
};
<file_sep>/tests/state.js
const state = require('./../lib/state');
const AWS = require('aws-sdk-mock');
describe('', () => {
test('generate', () => {
AWS.mock('CloudFormation', 'getTemplate', {
TemplateBody: '{"mocked": true}',
});
const cf = require('./fixtures/describe-stacks.json');
const expected = require('./fixtures/state.json');
const opts = {
stack: 'lambda-monitoring',
resourceName: 'network',
};
return state.generate(opts, cf.Stacks[0]).then(result => {
expect(result).toEqual(expected);
});
});
});
<file_sep>/lib/configuration.js
const shared = require('./shared');
module.exports = {
keyMapping: {
StackName: 'name',
Capabilities: {
name: 'capabilities',
default: [],
required: false,
},
DisableRollback: {
name: 'disable_rollback',
required: false,
},
},
generate(options, stack) {
const resource = Object.assign({}, shared.mapKeys(this.keyMapping, stack));
const things = [
{
key: 'parameters',
value: this.generateAttributeObject(
stack['Parameters'],
'ParameterKey',
'ParameterValue'
),
},
{
key: 'tags',
value: this.generateAttributeObject(stack['Tags'], 'Key', 'Value'),
},
];
const parameters = things.reduce((sum, thing) => {
if (typeof thing.value !== 'undefined') {
const newThing = Object.assign({}, sum, {
[thing.key]: [thing.value],
});
return newThing;
}
}, {});
const returns = {
resource: {
aws_cloudformation_stack: {
[options.resourceName]: Object.assign({}, resource, parameters),
},
},
};
return Promise.resolve(returns);
},
generateParameters(stack) {
return stack.Parameters.reduce((sum, parameter) => {
return Object.assign(sum, {
[parameter.ParameterKey]: parameter.ParameterValue,
});
}, {});
},
generateAttributeObject(attributes, attributeKey, attributeValue) {
if (!attributes) return;
const isObjectArray = this.isObjectArray(attributes);
return attributes.reduce((sum, thing, currentIndex) => {
if (isObjectArray) {
key = thing[attributeKey];
value = thing[attributeValue];
} else {
key = currentIndex;
value = thing;
}
return Object.assign(sum, {
[key]: value,
});
}, {});
},
isObjectArray(thing) {
return typeof thing === 'object' && typeof thing[0] === 'object';
},
};
<file_sep>/tests/configuration.js
const configuration = require('./../lib/configuration');
describe('', () => {
test('generate', () => {
const cf = require('./fixtures/describe-stacks.json');
const expected = require('./fixtures/example.tf.json');
const opts = {
stack: 'lambda-monitoring',
resourceName: 'network',
};
return configuration.generate(opts, cf.Stacks[0]).then(result => {
expect(result).toEqual(expected);
});
});
test('does not break when paremeters field is not present', () => {
const cf = require('./fixtures/describe-stacks.json');
const expected = require('./fixtures/example.tf.json');
delete cf.Stacks[0].Parameters;
delete expected.resource.aws_cloudformation_stack.network.parameters;
const opts = {
stack: 'lambda-monitoring',
resourceName: 'network',
};
return configuration.generate(opts, cf.Stacks[0]).then(result => {
expect(result).toEqual(expected);
});
});
test('sets different default value when it needs a different one', () => {
let cf = require('./fixtures/describe-stacks.json');
let expected = require('./fixtures/example.tf.json');
delete cf.Stacks[0].Capabilities;
delete expected.resource.aws_cloudformation_stack.network.capabilities;
const opts = {
stack: 'lambda-monitoring',
resourceName: 'network',
};
return configuration.generate(opts, cf.Stacks[0]).then(result => {
expect(result).toEqual(expected);
});
});
});
<file_sep>/lib/shared.js
module.exports = {
mapKeys(keyMapping, stack, opts) {
opts = opts || {};
const { stringify = false, allowMissing = false } = opts;
let resource = {};
for (const stackKey of Object.keys(keyMapping)) {
const property = keyMapping[stackKey];
const required =
typeof property.required === 'undefined' ? true : property.required;
if (typeof stack[stackKey] === 'undefined' && !required) continue;
const resourceKey =
typeof property.name === 'undefined' ? property : property.name;
const def =
typeof property.default === 'undefined' ? '' : property.default;
const value =
typeof stack[stackKey] === 'undefined' ? def : stack[stackKey];
resource[resourceKey] = stringify ? `${value}` : value;
}
return resource;
},
};
<file_sep>/index.js
#!/usr/bin/env node
const program = require('commander');
const awsGetStack = require('./lib/stack');
const awsGetTemplate = require('./lib/template');
const configuration = require('./lib/configuration');
const state = require('./lib/state');
const cleanHCL = require('./lib/cleanHCL');
const getStdin = require('get-stdin');
const formatOptions = opts => {
return {
stack: opts.parent.stack,
resourceName: opts.parent.resourceName || 'main',
};
};
const getStack = opts => {
return getStdin().then(result => stdinOrGetStack(result, opts));
};
const stdinOrGetStack = (result, opts) => {
if (result !== '' && opts.stack === '-') {
return JSON.parse(result);
}
return awsGetStack(opts);
};
const handleError = err => {
console.log(err);
process.exit(1);
};
program.option('-s, --stack <stack>', 'The CloudFormation stack to import');
program.option(
'-r, --resource-name <resourceName>',
'The name to assign the terraform resource'
);
program
.command('config')
.description('Generates Terraform configuration in JSON')
.action(options => {
const opts = formatOptions(options);
return getStack(opts)
.then(result => {
return configuration.generate(opts, result.Stacks[0]);
})
.then(result => console.log(JSON.stringify(result)))
.catch(err => handleError(err));
return getStack(opts)
.then(result => {
return configuration.generate(opts, result.Stacks[0]);
})
.then(result => console.log(JSON.stringify(result)))
.catch(err => handleError(err));
});
program
.command('state')
.description('Generates Terraform state file in JSON')
.action(options => {
const opts = formatOptions(options);
return getStack(opts)
.then(result => {
return state.generate(opts, result.Stacks[0]);
})
.then(result => console.log(JSON.stringify(result)))
.catch(err => handleError(err));
});
program
.command('template')
.description('Prints the CloudFormation Stack Template')
.action(options => {
const opts = formatOptions(options);
return awsGetTemplate(opts)
.then(result => console.log(JSON.stringify(result)))
.catch(err => handleError(err));
});
program
.command('clean-hcl')
.description('Cleans generated HCL according to my preferences')
.action(options => {
const opts = formatOptions(options);
return getStdin()
.then(str => cleanHCL.clean(opts, str))
.then(result => console.log(result))
.catch(err => handleError(err));
});
program.parse(process.argv);
// TODO mark required arguments
| 0eaec5ad7c3357b2d238ed5e36f22e878ebc057b | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | ganeshkumar/cf-to-tf | 733274defc3e4d1d566f31e5a2d962321bd50f35 | b2395d05d12f7ae2464f00b5d79bb8cef13a40d0 |
refs/heads/main | <file_sep>import discord
from discord.ext import commands
everything = {
'level': [
'Used to show own or someone else\'s level',
"level target",
"target here is the member whose level you wish to know (can be mention, id or username), if no target specified, own level is shown"
],
'lb': [
"Used to show server leaderboard",
"lb",
""
],
'giveexp': [
'(Mod) Used to award a certain amount of exp to a member',
"giveexp target amount",
'`target` here is the member who you wish to give exp points to\n'
'`amount` is the number of exp points you wish to award that person'
],
'setmultiplier': [
"(Mod) Used to set exp multiplier of a member",
"setmultiplier target multiplier",
"`target` here is the member whose multiplier you wish to set, can be mention, id or username\n"
"`multiplier` here is the exp multiplier you want to set, a value of 2 will indicate twice as fast levelling"
],
'setbd': [
"Used to save your own birthday in bot so others can see it",
"setbd date_of_birth",
"date_of_birth is the date on which you were born, the only acceptable format is:\n`DD MM YYYY`"
],
'bday': [
"Used to get a member's birthday",
"bday target",
"target here is the member whose birthday you wish to display, can be mention, id or username"
],
'prefix': [
'Used to set server prefix',
"prefix new_prefix",
"new_prefix here is the new server prefix that will be used for commands, can be up to 10 characters long"
],
'bdchannel': [
"Used to set birthday alert channel",
"bdaychannel target_channel",
"target_channel here is the server channel you wish to set for sending out birthday alerts, if not configured,"
"birthday alerts are not sent out."
],
'lockdown': [
"(Mod) Initiate a server wide message lockdown",
"lockdown",
f"Prevents the `@everyone` role from sending messages/adding reactions in the guild, useful in the event of"
f"a raid"
],
'unlock': [
"(Mod) Lifts the lockdown (if any)",
"unlock",
"Makes it so that the `everyone` role has the permission to send messages and add reactions in the guild."
],
'mute': [
"(Mod) Mutes a member preventing them from sending messages/adding reactions in the server",
"mute target duration",
"Target here is the member you'd like to mute, duration is the time you wish to mute them for, the only "
"acceptable format for time is shown by the example: \n`1d 2h 4m`\n"
"Therefore setting the duration to `1d 2h 4m` would mute your target for 1 day, 2 hours and 4 minutes"
],
'unmute': [
"(Mod) Unmutes an already muted member, allowing them to send messages/add reactions",
"unmute target",
"target here is the member you wish to unmute, note that unmuting a member with a timed mute will end their "
"mute period at that instant"
],
'bdalerttime': [
"(Admin) Sets the time at which the bot will send out birthday alerts in the server",
"bdalerttime time",
"`time` here is the time at which you want birthday alerts to be sent out on your server, it has to be in UTC, "
"and the ony acceptable format is `HH MM` where HH is hours of the day (in 24h format) and MM is the minutes "
"of the day"
],
'tag': [
'Retrieves an earlier stored tag',
'tag tagname',
'tagname here is the name of the tag you wish to fetch, for example to get a tag named '
'\'boop\' you would use `tag boop` '
],
'tag create': [
'Stores text for later retreival',
'tag create tagname content',
'tagname here is the name you wish the new tag to have content here is the text you wish to store, for example to '
'store the text "spaghetti" under the tagname "pasta"'
' you would use `tag create pasta spaghetti`'
],
'tag edit': [
'Edits a tag owned by you',
'tag edit tagname newcontent',
'tagname is the name of the tag you wish to edit, newcontent is the text you wish to replace it with, note that '
'you can only edit tags you own'
],
'tag delete': [
'Deletes a tag already created by someone',
'tag delete tagname',
"tagname here is the name of the tag you wish to delete, if you own it, you can delete it straightforwardly, if you don't you "
"will need the server permission 'Manage messages' in order to delete it."
],
'reddit': [
'Used to get a random post from a subreddit',
'reddit subreddit_name',
'subreddit_name here is the name of the subreddit from which you wish to get a post\n'
'Alternate names for this command: `r`'
],
'r': [
'Used to get a random post from a subreddit',
'reddit subreddit_name',
'subreddit_name here is the name of the subreddit from which you wish to get a post\n'
'Alternate names for this command: `r`'
]
}
categoryinfo = {
"Level System": [
'level', 'lb', 'giveexp', 'setmultiplier'
],
"Birthday system": [
'setbd', 'bday', 'bdchannel', 'bdalerttime'
],
"Utility": [
'tag', 'tag create', 'tag edit', 'tag delete', 'reddit'
],
"Moderation": [
'lockdown', 'unlock', 'mute', 'unmute'
],
"Admin": [
'prefix',
],
}
@commands.command()
async def help(ctx: commands.Context, *, arg: str = None):
if not arg:
title = "Commands"
text = ""
for category in categoryinfo:
text += f"```{category}```\n"
for command in categoryinfo[category]:
text += f"**{command}**\n{everything[command][0]}\n\n"
else:
data = everything.get(arg)
if not data:
await ctx.send(f"Couldn't find the command that you were looking for, please use `{ctx.prefix}help` to get"
f" a list of usable commands")
return
title = f"Command: {arg}"
text = f"""
**{data[0]}**
Usage:
```{ctx.prefix}{data[1]}```
{data[2]}
"""
embed = discord.Embed(title=title,
description=text,
colour=discord.Colour.green())
await ctx.send(embed=embed)
def setup(bot: commands.Bot):
bot.add_command(help)
<file_sep>import discord
from discord.ext import commands
class UtilityCog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
async def delete_tag(self, tagname, guildid):
query = "DELETE FROM tags WHERE name = $1 AND guildid = $2"
await self.bot.pool.execute(query, tagname, guildid)
@commands.group(invoke_without_command=True)
async def tag(self, ctx: commands.Context, *, tagname):
# Fetches a tag stored in db.
query = "SELECT content FROM tags WHERE name = $1 AND guildid = $2"
data = await self.bot.pool.fetchrow(query, tagname, ctx.guild.id)
if data:
content = data.get('content')
await ctx.send(content)
else:
await ctx.send("Could not find the tag you're looking for, it may not have been created in this guild "
"scope")
@tag.command()
async def create(self, ctx: commands.Context, tagname, *, content):
# Need to make sure that tag we're about to create doesn't already exist
checkquery = "SELECT exists(SELECT content FROM tags WHERE name = $1 AND guildid = $2)"
data = await self.bot.pool.fetchrow(checkquery, tagname, ctx.guild.id)
if data.get('exists'):
await ctx.send("A tag with that name already exists in this guild")
else:
# Basic sql query to insert data into the table
insertquery = "INSERT INTO tags(name, content, guildid, authorid) VALUES ($1, $2, $3, $4)"
await self.bot.pool.execute(insertquery, tagname, content, ctx.guild.id, ctx.author.id)
await ctx.send(embed=discord.Embed(description=f"Tag {tagname} successfully created",
colour=discord.Colour.green()))
@tag.command()
async def edit(self, ctx: commands.Context, tagname, *, content):
query = "UPDATE tags SET content = $1 WHERE name = $2 AND guildid = $3 AND authorid = $4"
# execute() returns postgres return code, we expect it to be "UPDATE 1" if tag edit was done successfully
# otherwise it means that it wasn't
retc = await self.bot.pool.execute(query, content, tagname, ctx.guild.id, ctx.author.id)
# Send messages
if int(retc[7:]) == 1:
await ctx.send(f"Tag {tagname} successfully updated")
else:
await ctx.send(f"Could not update tag {tagname} it may not exist or you may not be its owner")
@tag.command()
async def delete(self, ctx: commands.Context, tagname):
# If user has manage_messages permission, delete straignt away
if ctx.author.guild_permissions.manage_messages:
await self.delete_tag(tagname, ctx.guild.id)
await ctx.send(f"Tag {tagname} successfully deleted")
# Need to check if command user is the author of that tag or not
else:
checkquery = "SELECT authorid FROM tags WHERE name = $1 AND guildid = $2"
data = await self.bot.pool.fetchrow(checkquery, tagname, ctx.guild.id)
# Check if tag exists in the first place
if data:
# Check if user is tag author
if data.get('authorid') == ctx.author.id:
await self.delete_tag(tagname, ctx.guild.id)
await ctx.send(f"Tag `{tagname}` successfully deleted")
else:
await ctx.send("You need to have the `manage_messages` permission to delete someone else's tags")
else:
await ctx.send("Tag not found")
def setup(bot: commands.Bot):
bot.add_cog(UtilityCog(bot))
<file_sep>discord.py == 1.6.0
asyncpg == 0.21.0
jishaku == 172.16.17.320<file_sep>import os
import sys
import time
import discord
import asyncpg
import asyncio
import datetime
from discord.ext import commands
# Store time of starting
start = datetime.datetime.utcnow()
intents = discord.Intents.all()
"""-------------------Doing all the command prefix stuff here---------------------------"""
async def load_prefixes(bott: commands.Bot):
await bott.wait_until_ready()
async with bott.pool.acquire() as conn:
async with conn.transaction():
async for entry in conn.cursor("SELECT id, prefix FROM guilds"):
bott.prefixes[entry.get('id')] = entry['prefix']
async def get_pre(bott: commands.Bot, message: discord.Message):
prefix = bott.prefixes.get(message.guild.id)
if prefix:
return prefix
else:
return "."
bot = commands.Bot(command_prefix=get_pre, intents=intents)
bot.prefixes = {}
bot.remove_command('help')
"""---------------Database Utility Functions-----------------------"""
async def create_member_table(**kwargs):
"""Function to create a member table in the database for a particular guild, accepts both the guild as in a
discord.Guild object or simply the id of a guild, both accepted as keyword arguments
kwargs:
guild : the discord.Guild object\n
guild_id : the id of the guild
"""
if 'guild' in kwargs:
guild_id = kwargs['guild'].id
elif 'guild_id' in kwargs:
guild_id = kwargs['guild_id']
else:
raise ValueError("Guild id / guild not supplied.")
if type(guild_id) is not int:
raise ValueError("Guild id must be int")
async with bot.pool.acquire() as con:
await con.execute(f"CREATE TABLE IF NOT EXISTS server_members{guild_id} ("
f"id bigint, "
f"username varchar(255), "
f"level int, "
f"exp int, "
f"ispaused boolean, "
f"boost int, "
f"birthday date)")
await con.execute("INSERT INTO guilds (id) "
"VALUES ($1) ON CONFLICT (id) DO NOTHING", guild_id)
"""-----------------------Important things that need to happen as bot starts-------------------"""
async def connect_to_db():
bot.pool = await asyncpg.create_pool(os.environ['DATABASE_URL'], ssl='require', max_size=20)
async def check_tables():
"""
coro to check if tables exist for all guilds the bot is in, on startup and create table for any guild that isn't
there but should be,
"""
await bot.wait_until_ready()
for guild in bot.guilds:
await create_member_table(guild=guild)
async def change_presence():
await bot.wait_until_ready()
await bot.change_presence(activity=discord.Game("Type .help for usage!"))
asyncio.get_event_loop().run_until_complete(connect_to_db())
asyncio.get_event_loop().create_task(check_tables())
asyncio.get_event_loop().create_task(change_presence())
asyncio.get_event_loop().create_task(load_prefixes(bot))
"""------------Events that I didn't bother making a separate cog for, if they become too much might do the same------"""
@bot.event
async def on_guild_join(guild):
await create_member_table(guild=guild)
"""----------------------------Commands-------------------------------------------------------------------"""
def get_privileged_intents():
retval = ""
if bot.intents.members:
retval += "members\n"
if bot.intents.presences:
retval += "presences\n"
return retval
@bot.command()
async def info(ctx: commands.Context):
e = discord.Embed(title=f"{bot.user.name}",
description=f"A big dumdum discord bot made by {bot.get_user(501451372147769355)}",
colour=discord.Colour.blue())
# Calculate uptime
uptime = datetime.datetime.utcnow() - start
hours = int(uptime.seconds / 3600)
mins = (uptime.seconds // 60) % 60
secs = uptime.seconds - (hours * 3600 + mins * 60)
e.add_field(name="Uptime", value=f"{hours}:{mins}:{secs}", inline=True)
e.add_field(name="Websocket latency", value=f"{int(bot.latency * 1000)}ms", inline=True)
# Calculate database latency
temp_start = time.time()
await bot.pool.execute('select')
e.add_field(name="Database latency", value=f"{int((time.time() - temp_start) * 1000)}ms", inline=True)
e.add_field(name="Servers joined", value=len(bot.guilds), inline=True)
e.add_field(name="Users watched", value=len(bot.users), inline=True)
e.add_field(name="Privileged Intents", value=get_privileged_intents())
e.add_field(name="Python version", value=f"{sys.version[:5]}")
e.add_field(name="discord.py version", value=f"{discord.__version__}")
e.add_field(name="asyncpg version", value=f"{asyncpg.__version__}")
await ctx.send(embed=e)
"""-----------Load all the extensions one at a time like an absolute peasant heheheheheueueue-----------"""
bot.load_extension('exts.level_system')
bot.load_extension('exts.helpcmd')
bot.load_extension('exts.funcmds')
bot.load_extension('exts.GuildConfig')
bot.load_extension('exts.administration')
bot.load_extension('exts.errorhandler')
bot.load_extension('exts.utility')
bot.load_extension('jishaku')
print(f"Successfully started process at {datetime.datetime.utcnow()}")
bot.run(os.environ['BOT_TOKEN'])
<file_sep>import discord
from discord.ext import commands, tasks
from discord.utils import get
import datetime
async def create_mute_role(guild: discord.Guild):
"""Creates a mute role in a guild members having it can't send messages or add reactions"""
perms = discord.Permissions.none()
newrole = await guild.create_role(name="Muted", permissions=perms)
ow = discord.PermissionOverwrite(send_messages=False, add_reactions=False)
for channel in guild.channels:
await channel.set_permissions(newrole, overwrite=ow)
return newrole
# The database for mutes will be queried every this minutes
QUERY_INTERVAL_MINUTES = 30
# Converts a string of the format 1d 2h 3m into the equivalent number of minutes
def parsetime(time: str):
arr = time.lower().split(' ')
minutes = 0
for elem in arr:
if elem.endswith('h'):
minutes += int(elem[0:len(elem)-1]) * 60
elif elem.endswith('m'):
minutes += int(elem[0:len(elem) - 1])
elif elem.endswith('d'):
minutes += int(elem[0:len(elem) - 1]) * 60 * 24
return minutes
class administration(commands.Cog):
"""
Class that implements administration commands for a guild
"""
def __init__(self, bot: commands.Bot):
self.bot = bot
self._cache = {}
self.mute_poll.start()
async def load_cache(self):
"""Loads cache for moderative actions, not in use currently but future plans involve this as requirement"""
await self.bot.wait_until_ready()
for guild in self.bot.guilds:
self._cache[guild.id] = {}
# ------------------------------------Moderative actions--------------------------------------------
@commands.command()
@commands.has_permissions(administrator=True)
async def lockdown(self, ctx: commands.Context):
await ctx.guild.default_role.edit(permissions=discord.Permissions(send_messages=False, add_reactions=False))
await ctx.send(
embed=discord.Embed(title="A server-wide lockdown is now in effect", colour=discord.Colour.red()))
@commands.command()
@commands.has_guild_permissions(administrator=True)
async def unlock(self, ctx: commands.Context):
await ctx.guild.default_role.edit(permissions=discord.Permissions.general())
await ctx.send(
embed=discord.Embed(title="Lockdown lifted", colour=discord.Colour.green()))
@commands.command()
@commands.has_guild_permissions(manage_messages=True)
async def mute(self, ctx, target: discord.Member, *, time: str = None):
mr = get(ctx.guild.roles, name="Muted")
if not mr:
await ctx.send("Server doesn't seem to have mute configured yet, stand by please.")
async with ctx.channel.typing():
mr = await create_mute_role(ctx.guild)
await ctx.send("Configured mute successfully")
if not time:
await target.add_roles(mr)
e = discord.Embed(description=f"{target} has been muted", colour=discord.Colour.red())
e1 = discord.Embed(description=f"You have been muted from the server {ctx.guild} indefinitely, you'll only"
f"be able to send messages if a moderator unmutes you",
colour=discord.Colour.red())
await ctx.send(embed=e)
await target.send(embed=e1)
if time:
await target.add_roles(mr)
duration = parsetime(time)
muted_till = datetime.datetime.utcnow() + datetime.timedelta(minutes=duration)
await self.bot.pool.execute("INSERT INTO mutes (id, guildid, mutedtill) VALUES ($1, $2, $3)",
target.id, ctx.guild.id, muted_till)
e = discord.Embed(description=f"{target} has been muted till {muted_till}", colour=discord.Colour.red())
e1 = discord.Embed(description=f"You have been muted from the server {ctx.guild} for {muted_till} (UTC)",
colour=discord.Colour.red())
await ctx.send(embed=e)
await target.send(embed=e1)
if duration < QUERY_INTERVAL_MINUTES:
self.bot.loop.create_task(self.perform_unmute(ctx.guild.id, target.id, muted_till))
@commands.command()
@commands.has_guild_permissions(manage_messages=True)
async def unmute(self, ctx: commands.Context, target: discord.Member):
await self.perform_unmute(ctx.guild.id, target.id, datetime.datetime.utcnow())
await ctx.send(embed=discord.Embed(description=f"Unmuted {target.mention}", colour=discord.Colour.green()))
async def perform_unmute(self, guildid, targetid, when: datetime.datetime):
"""Unmutes a target in a guild at a specified time"""
# Gotta get the guild and member objects to perform the unmute
guild = self.bot.get_guild(guildid)
target = guild.get_member(targetid)
# Neat little feature to sleep till a specified timestamp in UTC
await discord.utils.sleep_until(when)
# This checks if the target left the server because angry on being muted
if target:
# Remove the muted role, currently using get, in the near future might just save the muted role ids into
# the database
role = get(guild.roles, name='Muted')
# Checks if member was already unmuted manually in which case no need to send the message
if role in target.roles:
await target.remove_roles(role)
# Send a message to the target informing them that they were unmuted
e = discord.Embed(description=f"Your mute period has been completed, you will now be able to send messages in "
f"{guild} again.", colour=discord.Colour.green())
await target.send(embed=e)
# Gotta delete the entry from the database now that the unmute has been done
await self.bot.pool.execute("DELETE FROM mutes WHERE id = $1 AND guildid = $2",
targetid, guildid)
@tasks.loop(minutes=QUERY_INTERVAL_MINUTES)
async def mute_poll(self):
"""Background loop that takes care of querying the databse and looking up entries where the time till
a target has been muted for is before the time the next iteration of the loop will happen."""
await self.bot.wait_until_ready()
async with self.bot.pool.acquire() as conn:
async with conn.transaction():
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=QUERY_INTERVAL_MINUTES)
async for entry in conn.cursor("SELECT * FROM mutes WHERE mutedtill < $1",
future):
# Creating an async task to perform unmutes, the future handling is done in the perform_unmute
# function itself
self.bot.loop.create_task(self.perform_unmute(entry.get('guildid'),
entry.get('id'),
entry.get('mutedtill')))
def setup(bot: commands.Bot):
bot.add_cog(administration(bot))
<file_sep>import discord
from discord.ext import commands
class ConfigCommands(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command()
@commands.has_guild_permissions(administrator=True)
async def prefix(self, ctx: commands.Context, prefix: str) -> None:
if len(prefix) > 10:
await ctx.send("Prefix must be less than 10 characters long")
return
else:
self.bot.prefixes[ctx.guild.id] = prefix
async with self.bot.pool.acquire() as conn:
await conn.execute("INSERT INTO guilds (id, prefix) "
"VALUES ($1, $2) ON CONFLICT (id) DO "
"UPDATE SET prefix = $3 WHERE guilds.id = $4",
ctx.guild.id,
prefix,
prefix,
ctx.guild.id)
e = discord.Embed(title='Success!',
description=f"The prefix for this server has been set to `{prefix}`",
colour=discord.Colour.green())
await ctx.send(embed=e)
@commands.command()
@commands.has_guild_permissions(administrator=True)
async def bdchannel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Sets the birthday alert channel for a particular guild"""
async with self.bot.pool.acquire() as conn:
await conn.execute("UPDATE guilds SET bdayalert = $1 WHERE id = $2", channel.id, ctx.guild.id)
e = discord.Embed(title='Success!',
description=f'The channel {channel.mention} will be used for auto birthday alerts',
colour=discord.Colour.green())
await ctx.send(embed=e)
def setup(bot: commands.Bot):
bot.add_cog(ConfigCommands(bot))
<file_sep>import random
import aiohttp
import discord
import datetime
from discord.ext import commands, tasks
class funcmds(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.bday_poll.start()
@commands.command()
async def bday(self, ctx: commands.Context, target: discord.Member) -> None:
"""
Fetches a member's birthday from the database, they need to have registered their birthday in that particular
guild for it to work.
:param ctx: invocation context
:param target: Target whose birthday to fetch
:return:
"""
async with self.bot.pool.acquire() as conn:
async with conn.transaction():
# Table name :kekw:
if type(ctx.guild.id) is not int:
raise ValueError("Guild id is somehow not int")
table_name = "server_members" + str(ctx.guild.id)
query = f"SELECT id, birthday FROM {table_name}" + " WHERE id = $1"
cur = await conn.cursor(query, target.id)
data = await cur.fetchrow()
# If birthday existed in db
if data.get('birthday'):
birthday = data.get('birthday').strftime("%d %B")
else:
# Send error message if birthday wasn't found
await ctx.send(f"Couldn't find {target}'s birthday in this server, tell them to set it using "
f"`{ctx.prefix}setbd`")
# Short circuit
return
# Send the birthday as a message
await ctx.send(f"{target}'s birthday is on {birthday}")
@commands.command()
async def setbd(self, ctx: commands.Context, *, birthday: str):
"""
Saves the birthday of a member into that guild's table.
Format: DD MM YYYY
:param ctx: Invocation context
:param birthday: (str) The birthday to save into the database
:return: None
"""
# Try except block to check if the date entered was of correct format
try:
datecheck = datetime.datetime.strptime(birthday, "%d %m %Y")
except ValueError:
# Error message sent when date format isn't the one bot is looking for
await ctx.send("Invalid date format, please try again, using `DD MM YYYY`")
# Short circuit
return
# Yeet it into dabatase
table_name = f"server_members{ctx.guild.id}"
query = f"UPDATE {table_name}" + " SET birthday=to_date($1, 'DD MM YYYY') WHERE id = $2"
await self.bot.pool.execute(query, birthday, ctx.author.id)
# Send confirmation message stating that the birthday was recorded successfully
embed = discord.Embed(title="Birthday recorded!",
description=f"Your day is on {datecheck.strftime('%d %B %Y')}",
colour=discord.Colour.green())
await ctx.send(embed=embed)
async def send_wish(self, guildid: int, channelid: int, memberid: int, when: datetime.datetime):
"""
Sends a birthday wish in a guild at a specified time in UTC
Args:
guildid:
channelid:
memberid:
when:
Returns: None
"""
await discord.utils.sleep_until(when)
guild = self.bot.get_guild(guildid)
channel = guild.get_channel(channelid)
m = guild.get_member(memberid)
e = discord.Embed(title=f"{m} has their birthday today!",
description=f"Reblog if u eating beans",
colour=discord.Colour.blue())
await channel.send(embed=e)
@tasks.loop(minutes=20)
async def bday_poll(self):
for guild in self.bot.guilds:
if type(guild.id) is not int:
raise TypeError("Somehow guild id is not an int")
table_name = f"server_members{guild.id}"
# Future is the time of the next iteration of the loop
now = datetime.datetime.utcnow()
future = now + datetime.timedelta(minutes=20)
# Query the database to find the time at which alert is to be sent out
query1 = f"SELECT id, bdayalert, bdayalerttime FROM guilds WHERE bdayalerttime < $1 AND bdayalerttime > $2"
# Query to fetch the members who have their birthday on that day
query = f"SELECT id, birthday FROM {table_name} " + "WHERE DATE_PART('day', birthday) = DATE_PART('day', CURRENT_DATE) AND DATE_PART('month', birthday) = DATE_PART('month', CURRENT_DATE)"
async with self.bot.pool.acquire() as conn:
async with conn.transaction():
async for guild_record in conn.cursor(query1, future, now):
# Converting alert time to string here as it needs to be merged with the whole
# date to make it datetime instead of just time
alert_time = guild_record.get('bdayalerttime').strftime("%H %M %S")
temp_time_str = datetime.datetime.utcnow().strftime('%d %m %y')
# Alert time is converted into datetime object with date of today
new_time = datetime.datetime.strptime(f"{temp_time_str} {alert_time}", "%d %m %y %H %M %S")
# Get the channel id in which to send alerts
alert_channel_id = guild_record.get('bdayalert')
# If an alert time and alert channel id have been set only then will an alert be sent.
if alert_time:
if alert_channel_id:
async for record in conn.cursor(query):
self.bot.loop.create_task(
self.send_wish(guild.id, alert_channel_id, record.get('id'), new_time))
@bday_poll.before_loop
async def kellog(self):
await self.bot.wait_until_ready()
@commands.command()
@commands.has_guild_permissions(manage_guild=True)
async def bdalerttime(self, ctx: commands.Context, *, time):
"""
Sets the time of the day at which birthday alerts will be sent on a guild. (UTC)
"""
tim = datetime.datetime.strptime(time, "%H %M").time()
await self.bot.pool.execute("UPDATE guilds SET bdayalerttime = $1 WHERE id = $2", tim, ctx.guild.id)
e = discord.Embed(title="Success!",
description=f"Birthday alerts will be sent out on this server at {tim.strftime('%H:%M')} (UTC)",
colour=discord.Colour.green())
await ctx.send(embed=e)
await self.bday_poll()
@commands.command()
@commands.check(lambda ctx: ctx.author.id == 501451372147769355)
async def checkbd(self, ctx: commands.Context):
await self.bday_poll()
@commands.command(aliases=['r'])
async def reddit(self, ctx: commands.Context, subreddit: str):
ROUTE = 'https://www.reddit.com/r/%s.json'
async with aiohttp.ClientSession() as cs:
async with cs.get(ROUTE % subreddit) as r:
d = await r.json()
# Count the number of nsfw/video posts in the subreddit as they don't go to discord
nsfw = 1
video = 1
# Max number of posts to look up
MAX_LOOKUPS = 25
# The reddit json api doesn't (seem to) return a 404 if subreddit doesn't exist, this seems like a workaround
# To check if the sub doesn't exist/is private
if len(d['data']['children']) == 0:
await ctx.send("Subreddit not found! It may be private or might not exist.")
return
# There was an attempt to ignore video/nsfw posts however for the video part, if the sub is a video only sub
# bad things happen and I really am not in the mood to investigate what's wrong (apparently the is_video bool
# is incorrect for some posts)
else:
posts = d['data']['children']
while nsfw < MAX_LOOKUPS and video < MAX_LOOKUPS:
selected = random.choice(posts)
if selected['data']['over_18']:
nsfw += 1
continue
if selected['data']['is_video']:
video += 1
continue
e = discord.Embed(title=selected['data']['title'],
colour=discord.Colour.red())
e.set_image(url=selected['data']['url_overridden_by_dest'])
await ctx.send(embed=e)
return
if nsfw >= MAX_LOOKUPS:
await ctx.send(f"Looked up {MAX_LOOKUPS} posts, all were nsfw, not posting")
elif video >= MAX_LOOKUPS:
await ctx.send(f"Looked up {MAX_LOOKUPS} posts, all were videos, can't post.")
def setup(bot: commands.Bot):
bot.add_cog(funcmds(bot))
<file_sep>import discord
from discord.ext import commands, tasks
from math import floor, sqrt
from typing import Union
import asyncio
def is_me(ctx):
return ctx.author.id == 5<PASSWORD>
class LevelSystem(commands.Cog):
"""
A Cog that implements a level system for messaging on multiple discord servers.\n
Attributes:
bot : the bot instance
_cache: protected cache attribute for rapid short term storage of the data, dumped into db every 10 minutes
Functions:
await give_exp(guild_id, member_id, amount=None) : give exp to a member\n
await add_to_cache(guild_id, member_id) : add a member to cache\n
await add_to_db(guild_id, member_id) : adds a member to the database of the respective server\n
"""
def __init__(self, bot):
self.bot = bot
# Look up implementation inside the add_to_cache function docstring
self._cache = {}
asyncio.get_event_loop().create_task(self.load_cache())
# Start the loop that dumps cache to database every 10 minutes
self.update_level_db.start()
async def load_cache(self):
for guild in self.bot.guilds:
self._cache[guild.id] = {}
async def give_exp(self, guild_id: int, member_id: int, amount=None) -> None:
"""
Function to give exp to a particular member
Parameters:
:param guild_id: The id of the guild in question
:param member_id: The id of the member in the guild
:param amount: The amount of exp to give, default to None in which case the default level up exp is awarded
:return: None
"""
if member_id not in self._cache[guild_id]:
await self.add_to_cache(guild_id, member_id)
if not amount:
amount = 5 * self._cache[guild_id][member_id]['boost']
self._cache[guild_id][member_id]['exp'] += amount
async def add_to_cache(self, guild_id: int, member_id: int) -> Union[dict, None]:
"""
Function that adds a member to the cache
Cache: \n
type = dict \n
format: \n
{
guild_id : {
member_id : {
'id' : "the id of the member",\n
'username' : "deprecated",\n
'level' : "the level of the member",\n
'exp' : "the exp of the member", \n
'boost' : "the boost multiplier", \n
'ispaused' "whether or not the member is pasued":
}
}
}
:param guild_id: the id of the guild
:param member_id: the id of the member belonging to that guild
:return: data(dict) - The member that was just put inside db, same format as cache.
"""
if guild_id in self._cache and member_id in self._cache[guild_id]:
pass
if type(guild_id) is not int:
raise TypeError("guild id must be int")
async with self.bot.pool.acquire() as conn:
async with conn.transaction():
# Set the table name
table_name = "server_members" + str(guild_id)
# The query to execute, $1 notation used for sanitization
query = f"SELECT * FROM {table_name} WHERE id = $1"
cur = await conn.cursor(query, member_id)
# The data returned by querying the database, defaults to None if record was not present
data = await cur.fetchrow()
# Can only do this stuff if there actually is relevant data in the database, otherwise,
# a separate function adds the default values into the database, this bit adds the data to the cache.
if data:
self._cache[guild_id][member_id] = {
'id': data.get('id'),
'username': data.get('username'),
'level': data.get('level'),
'exp': data.get('exp'),
'ispaused': data.get('ispaused'),
'boost': data.get('boost'),
}
else:
await self.add_to_db(guild_id, member_id)
await self.add_to_cache(guild_id, member_id) # important
return data
async def add_to_db(self, guild_id: int, member_id: int) -> None:
"""
A function that adds a new entry to the database with default values
(and not dump existing cache into database)
:param guild_id: The relevant guild
:param member_id: The id of the member
:return: None
"""
async with self.bot.pool.acquire() as conn:
table_name = "server_members" + str(guild_id)
query = f"INSERT INTO {table_name} (id, username, level, exp, ispaused, boost) " \
f"VALUES ($1, $2, $3, $4, $5, $6)"
await conn.execute(query, member_id, 'deprecated', 0, 0, False, 1)
async def dump_single_guild(self, guildid: int):
"""
Function that dumps all entries from a single guild in the cache to the database.
:param guildid: the id of the guild whose cache entry needs to be dumped
:return: None
"""
data = self._cache[guildid]
table_name = 'server_members' + str(guildid)
for memberid in data:
current = data[memberid]
query = f"UPDATE {table_name} " \
f"SET level = $1, " \
f"exp = $2, " \
f"ispaused = $3, " \
f"boost = $4" \
f"WHERE id = $5"
await self.bot.pool.execute(query,
current['level'],
current['exp'],
current['ispaused'],
current['boost'],
memberid)
async def fetch_top_n(self, guild: discord.Guild, limit: int):
"""
Function to fetch top n members of a guild based off exp, works by initially dumping the guild into the database
then using an sql query to fetch the top n members
:param guild: the guild in question
:param limit: the number of members to fetch
:return: None
"""
if guild.id in self._cache:
await self.dump_single_guild(guild.id)
table_name = 'server_members' + str(guild.id)
async with self.bot.pool.acquire() as conn:
async with conn.transaction():
top10 = []
rank = 1
async for entry in conn.cursor(f"SELECT id, exp, level FROM {table_name} ORDER BY exp DESC LIMIT $1", limit):
top10 += [{'rank': rank, 'id': entry.get('id'), 'exp': entry.get('exp'), 'level': entry.get('level')}]
rank += 1
return top10
@tasks.loop(minutes=10)
async def update_level_db(self):
"""
Loop that dumps the cache into db every 10 minutes
:return: None
"""
for guildId in self._cache:
await self.dump_single_guild(guildId)
self._cache[guildId] = {}
print("Database updated")
@update_level_db.before_loop
async def preloop(self) -> None:
"""
using this neat little feature in the library you can make sure the cache is ready before the loop starts
"""
await self.bot.wait_until_ready()
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
"""
The listener that takes care of awarding exp, levelling up the members
:param message: the discord.Message object
:return: None
"""
# Bots shouldn't be levelling up
if not message.author.bot:
# This bit awards exp points
if message.guild.id not in self._cache:
self._cache[message.guild.id] = {}
await self.add_to_cache(message.guild.id, message.author.id)
if message.author.id not in self._cache[message.guild.id]:
await self.add_to_cache(message.guild.id, message.author.id)
await self.give_exp(message.guild.id, message.author.id)
# This bit checks if level up happened
OldLevel = self._cache[message.guild.id][message.author.id]['level']
NewLevel = floor((25 + sqrt(625 + 100 * self._cache[message.guild.id][message.author.id]['exp'])) / 50)
if NewLevel > OldLevel:
self._cache[message.guild.id][message.author.id]['level'] = NewLevel
embed = discord.Embed(title=f"{message.author}",
description=f"GZ on level {NewLevel}, {message.author.mention}",
color=discord.Colour.green())
await message.channel.send(embed=embed)
@commands.command()
async def level(self, ctx: commands.Context, target: discord.Member = None):
"""
Displays the level and exp points of a target specified
If no target specified, shows own level
"""
if not target:
target = ctx.author
if ctx.guild.id in self._cache and target.id in self._cache[ctx.guild.id]:
data = self._cache[ctx.guild.id][target.id]
else:
data = await self.add_to_cache(ctx.guild.id, target.id)
if not data:
await ctx.send(f"{target} hasn't been ranked yet! tell them to send some messages to start.")
return
embed = discord.Embed(title=f"{target}",
description=f"You are currently on level : {data['level']}\n"
f"With exp : {data['exp']}",
colour=discord.Colour.blue())
await ctx.send(embed=embed)
@commands.command()
async def lb(self, ctx):
"""
Shows the top 10 server members based off their exp
"""
data = await self.fetch_top_n(ctx.guild, limit=10)
embed = discord.Embed(title="Server leaderboard",
colour=discord.Colour.green())
for entry in data:
embed.add_field(name=f"{entry.get('rank')}.{ctx.guild.get_member(entry.get('id')).display_name}",
value=f"Level: {entry.get('level')} Exp: {entry.get('exp')}",
inline=True)
await ctx.send(embed=embed)
@commands.command()
@commands.has_guild_permissions(manage_messages=True)
async def setmultiplier(self, ctx: commands.Context, target: discord.Member, multiplier: int):
"""
Command to set the multiplier of a member, setting it to 0 will make it so they don't get any level, eliminating
the need of having an "ispaused" field in the database which will be removed soon.\n
:param ctx:
:param target:
:param multiplier:
:return:
"""
if target.id not in self._cache[ctx.guild.id]:
await self.add_to_cache(ctx.guild.id, target.id)
self._cache[ctx.guild.id][target.id]['boost'] = int(multiplier)
await ctx.send(f"{target}'s multiplier has been set to {multiplier}")
@commands.command()
@commands.has_guild_permissions(manage_messages=True)
async def giveexp(self, ctx: commands.Context, target: discord.Member, amount: int):
await self.give_exp(ctx.guild.id, target.id, amount=int(amount))
e = discord.Embed(title="Success",
description=f"Added {amount} points to {target.mention}",
colour=discord.Colour.green())
await ctx.send(embed=e)
@commands.command()
@commands.check(is_me)
async def update_db(self, ctx):
"""
Command to update the database manually, mostly used for testing purposes, or when planning to take bot down
for maintenance
:param ctx:
:return:
"""
await self.update_level_db()
await ctx.send("db updated (hopefully)")
def setup(bot: commands.Bot):
bot.add_cog(LevelSystem(bot))
| caad5625aecf4f3cd7cda69a1c138ee405ee4aed | [
"Python",
"Text"
] | 8 | Python | mihirsh02/Zeta | 66830b296996a94df1e5b4ad42a2997fc6beeb79 | 875b66223c87f8da9acd809bc604ee90739c04b8 |
refs/heads/master | <repo_name>farjana-dipa/Estate-Agency-Projects<file_sep>/js/main.js
// SCROLLUP BUTTON
const scrollUp = document.querySelector('.scrollUp');
window.addEventListener('scroll', () => {
if(window.pageYOffset > 300){
scrollUp.classList.add('active');
}
else{
scrollUp.classList.remove('active');
}
});
// TESTIMONIAL CAROUSEL
$(document).ready(function(){
$('.slider2 .owl-carousel').owlCarousel({
animateOut: 'fadeOut',
items:1,
loop:false,
autoplayHoverPause: false,
autoplay: true,
smartSpeed: 1000,
});
});
$(document).ready(function(){
$('.owl-carousel').owlCarousel({
animateOut: 'fadeOut',
items:3,
loop:true,
autoplayHoverPause: false,
autoplay: true,
smartSpeed: 1500,
responsiveClass:true,
responsiveRefreshRate:true,
responsive:{
0:{
items:1
},
576:{
items:1
},
768:{
items:2
},
876:{
items:2
},
1000:{
items:3
},
1200:{
items:4
},
1920:{
items:4
},
}
});
});
// wow
new WOW().init();
// HUMBERGER MENU
function openMenu(){
document.getElementById('navbar1').style.height = "100%";
}
function closeMenu(){
document.getElementById('navbar1').style.height = "0%";
}
// SEARCH MENU DESIGN
function saveMenu(){
document.getElementById('search-menu1').style.height = "100%";
}
function deleteMenu(){
document.getElementById('search-menu1').style.height = "0%";
}
// PROPERTY MIXITUP
var mixer = mixitup('.property-filter');
| 46decbaeeb606cefc0c1e70b2fda24d700847ebc | [
"JavaScript"
] | 1 | JavaScript | farjana-dipa/Estate-Agency-Projects | 8fe2f2291dc2ace0ccd4c186cf9cbed9720cbbf9 | d893e296e1599b37fd8947de8ed24bb9171503f8 |
refs/heads/master | <repo_name>DeepakR63/Fund<file_sep>/component/messagebox.js
import { toast } from 'react-toastify';
//Show the message using toaster.
export function messageBox(msg)
{
if (!toast.isActive())
{
return(
toast.update(toast(msg,{autoClose:false}),
{
position: toast.POSITION.TOP_CENTER,
type: toast.TYPE.SUCCESS, autoClose:false
})
);
}
else
{
return null;
}
}<file_sep>/component/api.js
import axios from 'axios';
const BASE_URL = 'http://52.41.54.41:3001/';
export function getCall(url,params=null)
{
return axios.get(BASE_URL+url,{params : params});
}
export function putCall(url,body)
{
return axios.put(BASE_URL+url,body);
}
export function postCall(url,body)
{
return axios.post(BASE_URL+url,body);
}
//Set the authentication details to the header part of the API request.
export function setAuthentication()
{
var _auth=JSON.parse(localStorage.getItem('Auth'));
return (
axios.interceptors.request.use((config) => {
if( _auth )
{
config.headers['Auth'] = _auth;
return config;
}
else
{
return config;
}
})
);
}
<file_sep>/pages/signup.js
import React, { Component } from 'react';
import axios from 'axios';
import HeadBanner from '../component/head';
import { toast, ToastContainer } from 'react-toastify';
import { messageBox } from '../component/messagebox';
import { validEmail } from '../component/validation';
import { validPassword } from '../component/validation';
import { validPhone } from '../component/validation';
import { comparePassword } from '../component/validation';
import { validFundraiserType } from '../component/validation';
import { validOrganization } from '../component/validation';
import { postCall } from '../component/api';
//Component for Sign Up
class SignUp extends Component
{
constructor(props)
{
super(props);
this.state={
email:'',
password:'',
confirm_password:'',
fundraiser_type:'',
organization_name:'',
phone:''
}
this.emailChange=this.emailChange.bind(this);
this.passwordChange=this.passwordChange.bind(this);
this.confirmPasswordChange=this.confirmPasswordChange.bind(this);
this.fundraiserTypeChange=this.fundraiserTypeChange.bind(this);
this.organizationNameChange=this.organizationNameChange.bind(this);
this.phoneChange=this.phoneChange.bind(this);
}
//Validate the data given to the controls
validateEntries()
{
var _IsValid=true;
if(!validEmail(this.state.email))
{
messageBox('Please enter valid email.');
_IsValid=false;
}
else if(!validPassword(this.state.password))
{
messageBox('Password should contain an uppercase, a lowercase, a special character and the length is minimum of 6.');
_IsValid=false;
}
else if(!comparePassword(this.state.password,this.state.confirm_password))
{
messageBox('Confirm Password does not match.');
_IsValid=false;
}
else if(!validPhone(this.state.phone))
{
messageBox('Invalid Phone');
_IsValid=false;
}
else if(!validFundraiserType(this.state.fundraiser_type))
{
messageBox('Invalid Fundraiser Type.');
_IsValid=false;
}
else if(!validOrganization(this.state.organization_name))
{
messageBox('Invalid Organization Name.');
_IsValid=false;
}
return _IsValid;
}
//API request for sign up,After successful sign up redirect to the login page
doSignUp(event)
{
if(this.validateEntries())
{
var _url = "fundraisers/";
postCall(_url, this.state)
.then((response) => {
console.log(response);
if(response.status == 200)
{
console.log("Registration successfull");
messageBox("Registration successfull");
this.gotoLogin();
}
else
{
console.log("Failed. try again.");
messageBox("Failed. try again.");
}
})
.catch(function (error) {
console.log(error);
messageBox("Failed. try again.");
});
}
}
//*********** Set the state on the change of control values********
emailChange(e)
{
this.setState( { email: e.target.value } );
}
passwordChange(e)
{
this.setState( { password: e.target.value } );
}
confirmPasswordChange(e)
{
this.setState( { confirm_password: e.target.value } );
}
fundraiserTypeChange(e)
{
this.setState( { fundraiser_type: e.target.value } );
}
organizationNameChange(e)
{
this.setState( { organization_name: e.target.value } );
}
phoneChange(e)
{
this.setState( { phone: e.target.value } );
}
//********************************************************************
//Call signUp on submit button click
handleClick(event)
{
this.doSignUp(event);
}
//Redirect to the login page
gotoLogin()
{
this.props.history.push('/');
}
render()
{
return(
<div>
<HeadBanner/>
<div id="div-signup-title">
<span id="spn-signup-title"> Sign Up </span>
</div>
<div id="div-signup-body">
<div class="row form-group">
<div class="col-sm-12">
<input type="email" placeholder="email" class="form-control" onChange = {this.emailChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<input type="<PASSWORD>" placeholder="<PASSWORD>" class="form-control" onChange = {this.passwordChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<input type="<PASSWORD>" placeholder="<PASSWORD> password" class="form-control" onChange = {this.confirmPasswordChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<input type="text" placeholder="phone" class="form-control" onChange = {this.phoneChange} maxLength="10"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<input type="text" placeholder="fundraiser type" class="form-control" onChange = {this.fundraiserTypeChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<input type="text" placeholder="organization name" class="form-control" onChange = {this.organizationNameChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6">
</div>
<div class="col-sm-3">
<button class="btn btn-success " id="btn-submit" onClick={this.handleClick.bind(this)}> Submit </button>
</div>
<div class="col-sm-3">
<button class="btn btn-danger " id="btn-cancel" onClick={this.gotoLogin.bind(this)}> Cancel </button>
</div>
</div>
<ToastContainer/>
</div>
</div>
)
}
}
export default SignUp;<file_sep>/pages/imageupload.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import { toast, ToastContainer } from 'react-toastify';
import { messageBox } from '../component/messagebox';
import { validImage } from '../component/validation';
import ReactCrop from 'react-image-crop';
import { postCall, setAuthentication } from '../component/api';
//Component for Uploading the image.
class ImageUpload extends React.Component
{
constructor(props)
{
super(props);
this.state = {
file: '',
type:'',
user_id:'',
url:'',
crop:''
};
this.uploadImage=this.uploadImage.bind(this);
}
//Check the image is select
validateEntries()
{
var _isValid=true;
if(!validImage(this.state.file))
{
messageBox("Please select the valid image.");
_isValid=false;
}
return _isValid;
}
//Set the url to the state.
setURL(response)
{
this.setState(
{
url:response.data.image_url
})
}
//Upload the image and generate the url
getURL()
{
if(this.validateEntries())
{
const data = new FormData();
data.append('file', this.state.file);
data.append('type', this.props.imagetype);
data.append('user_id', this.props.userid);
var _url = "common/imageUpload";
setAuthentication();
postCall(_url, data).then((response) => {
console.log("Success",response);
this.setURL(response);
});
}
}
//Get the selected file details
changeImage(e)
{
e.preventDefault();
this.setState(
{
file:e.target.files[0]},
()=>{ this.getURL();
}
);
}
//Set the url for updation
uploadImage(e) {
if(this.validateEntries())
{
if(this.props.imagetype=='fundraiserProfile')
{
localStorage.setItem('profile_image',JSON.stringify(this.state.url));
}
else
{
localStorage.setItem('logo_image',JSON.stringify(this.state.url));
}
messageBox("Uploaded");
}
}
render()
{
//Check the component can activate or not.
if(!this.props.show)
{
return null;
}
return (
<div >
<div class="modal-content" id="div-modal-screen">
<div class="modal-header" id="div-profile-title">
<button type="button" class="close" data-dismiss="modal" onClick={this.props.onClose}>×</button>
<h4 class="modal-title"><span id="spn-profile-title">{this.props.imagetype}</span></h4>
</div>
<div class="modal-body">
<div className="previewComponent">
<form >
<input className="fileInput" type="file" onChange={this.changeImage.bind(this)} />
</form>
</div>
<div id="div-preview">
<img src={this.state.url} id="img-preview"/>
</div>
</div>
<div class="modal-footer" id="div-profile-title">
<button class="btn btn-success " id="btn-login" onClick={this.uploadImage.bind(this)}> Upload </button>
</div>
</div>
<ToastContainer/>
</div>
);
}
}
ImageUpload.propTypes = {
onClose: PropTypes.func.isRequired,
show: PropTypes.bool,
children: PropTypes.node
};
export default ImageUpload;
<file_sep>/pages/profileupdation.js
import React, { Component } from 'react';
import axios from 'axios';
import ImageUpload from '../pages/imageupload';
import { toast, ToastContainer } from 'react-toastify';
import { messageBox } from '../component/messagebox';
import { validFirstName } from '../component/validation';
import { validLastName } from '../component/validation';
import { validPhone } from '../component/validation';
import { validStreet } from '../component/validation';
import { validFundraiserType } from '../component/validation';
import { validOrganization } from '../component/validation';
import { validCity} from '../component/validation';
import { validCountryCode } from '../component/validation';
import { validZIP } from '../component/validation';
import { putCall, setAuthentication } from '../component/api';
import { stringToDate } from '../component/conversion';
import dateFormat from 'dateformat';
//Locally keeps the updating profile data
var editabledata={
first_name:'',
last_name:'',
dob:'',
phone:'',
email:'',
street:'',
city:'',
state:'',
country_code:'',
fundraiser_type:'',
organization_name:'',
facebook_link:'',
google_link:'',
twitter_link:'',
zip:'',
profile_image_url:'',
fundraiser_logo_url:''
}
//Component for profile updation
class UpdateProfile extends Component
{
constructor(props)
{
super(props);
this.logindata=JSON.parse(localStorage.getItem('UserProfile'));
this.updateProfileData=this.updateProfileData.bind(this);
}
validateEntries()
{
var _IsValid=true;
if(!validFirstName(editabledata.first_name))
{
messageBox("Invalid First Name.");
_IsValid=false;
}
else if(!validLastName(editabledata.last_name))
{
messageBox("Invalid Last Name.");
_IsValid=false;
}
else if(!validPhone(editabledata.phone))
{
messageBox("Invalid Phone.");
_IsValid=false;
}
else if(!validStreet(editabledata.street))
{
messageBox("Invalid Street.");
_IsValid=false;
}
else if(!validCity(editabledata.city))
{
messageBox("Invalid City.");
_IsValid=false;
}
else if(!validCountryCode(editabledata.country_code))
{
messageBox("Invalid Country Code.");
_IsValid=false;
}
else if(!validZIP(editabledata.zip))
{
messageBox("Invalid ZIP.");
_IsValid=false;
}
return _IsValid;
}
//Store the url of uploaded image
setImageDetails()
{
var profileimg=JSON.parse(localStorage.getItem('profile_image'));
var logo=JSON.parse(localStorage.getItem('logo_image'));
if(profileimg!=null)
{
editabledata.profile_image_url=profileimg;
}
if(logo!=null)
{
editabledata.fundraiser_logo_url=logo;
}
}
//Set the updated details to the controls and redirect to the profile page
setUpdatedData(response)
{
var _data=response.data;
localStorage.setItem('UserProfile',JSON.stringify(_data));
this.props.history.push('/home/profile');
}
//Request to the API for updation
updateProfileData()
{
if(this.validateEntries())
{
var _url = "fundraisers/"+parseInt(this.logindata.id);
setAuthentication();
this.setImageDetails();
putCall(_url, editabledata)
.then((response) => {
console.log(response);
if(response.status == 200)
{
console.log("Updation successfull");
this.setUpdatedData(response);
}
else
{
console.log("Failed. try again.");
messageBox("Failed. try again.");
}
})
.catch(function (error) {
console.log(error);
});
}
}
render()
{
//Check the authentication details are available or not
if(localStorage.getItem("Auth")==="")
{
(this.props.history.push('/'));
}
return(
<div class="container" id="div-update-body">
<div class="row" id="div-img-update">
<div class="col-sm-12">
<span> <img src="../img/update.jpeg" class="img-circle" id="img-update" onClick={this.updateProfileData} /></span>
</div>
</div>
<div class="row">
<div class="col-sm-10">
<Basic/>
</div>
</div>
<div class="row">
<div class="col-sm-10">
<Communication/>
</div>
</div>
<div class="row">
<div class="col-sm-10">
<Fundraiser/>
</div>
</div>
<div class="row">
<div class="col-sm-10">
<Connectivity/>
</div>
</div>
<ToastContainer/>
</div>
)
}
}
//Component for Profile Basic detail updation
class Basic extends Component
{
constructor(props)
{
super(props);
this.userdata=JSON.parse(localStorage.getItem('UserProfile'));
this.state = {
isHidden: true,
firstname:'',
lastname:'',
dob:'',
phone:'',
isOpen: false
}
editabledata.first_name=this.userdata.first_name;
editabledata.last_name=this.userdata.last_name;
editabledata.dob=this.userdata.dob;
editabledata.phone=this.userdata.phone;
editabledata.email=this.userdata.email;
editabledata.profile_image_url=this.userdata.profile_image_url;
{!this.state.isHidden && <span />}
this.firstnameChange=this.firstnameChange.bind(this);
this.lastnameChange=this.lastnameChange.bind(this);
this.dobChange=this.dobChange.bind(this);
this.phoneChange=this.phoneChange.bind(this);
}
//Toggle the ImageUpload component for profile image
toggleModal()
{
this.setState({
isOpen: !this.state.isOpen
});
}
//Toggle the Basic details
toggleHidden ()
{
this.setState({
isHidden: !this.state.isHidden
})
}
//**** Set the state details on changing the control values *****
firstnameChange(e)
{
this.setState( { firstname: e.target.value },
()=>{ editabledata.first_name=this.state.firstname; } );
}
lastnameChange(e)
{
this.setState( { lastname: e.target.value },
()=>{ editabledata.last_name=this.state.lastname; } );
}
dobChange(e)
{
this.setState({dob: moment(e.target.value).format('MM-DD-YYYY')},
()=>{ editabledata.dob=this.state.dob; }
);
}
phoneChange(e)
{
this.setState({phone: e.target.value},
()=>{ editabledata.phone=this.state.phone; } );
}
//******************************************************************
render()
{
return(
<div class="container" >
<div id="div-profile-pic" class="row">
<div class="col-sm-12">
<center><span> <img src={this.userdata.profile_image_url} ref={img => this.img = img} onError={ () => this.img.src = '../img/dob.jpeg'} class="img-circle" id="img-profile-update" onClick={this.toggleModal.bind(this)} data-toggle="tooltip" title="Change Photo" data-placement="right"/></span><ImageUpload show={this.state.isOpen} imagetype="fundraiserProfile" userid={this.userdata.id} onClose={this.toggleModal.bind(this)}></ImageUpload> </center>
</div>
</div>
<h3 onClick={this.toggleHidden.bind(this)}>Basic</h3>
<hr/>
{!this.state.isHidden &&<span class="spn-profile-update-body container">
<div class="row form-group">
<div class="col-sm-6">
<span id="spn-update-label">First Name : </span><input type="text" placeholder={this.userdata.first_name} class="form-control" onChange = {this.firstnameChange}/>
</div>
<div class="col-sm-6">
<span id="spn-update-label">Last Name : </span><input type="text" placeholder={this.userdata.last_name} class="form-control" onChange = {this.lastnameChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6">
<span id="spn-update-label">Dob : </span><input type="date" class="form-control" onChange = {this.dobChange} placeholder={this.userdata.dob}/>
</div>
<div class="col-sm-6">
<span id="spn-update-label">Phone : </span><input type="text" placeholder={this.userdata.phone} class="form-control" onChange = {this.phoneChange} maxLength="10"/>
</div>
</div>
</span>}
</div>
)
}
}
//Component for Profile communication updation
class Communication extends Component
{
constructor(props)
{
super(props);
this.userdata=JSON.parse(localStorage.getItem('UserProfile'));
this.state = {
isHidden: true,
street:'',
city:'',
state:'',
countrycode:'',
zip:''
}
editabledata.street=this.userdata.street;
editabledata.city=this.userdata.city;
editabledata.state=this.userdata.state;
editabledata.country_code=this.userdata.country_code;
editabledata.zip=this.userdata.zip;
{!this.state.isHidden && <span />}
this.streetChange=this.streetChange.bind(this);
this.cityChange=this.cityChange.bind(this);
this.countryChange=this.countryChange.bind(this);
this.stateChange=this.stateChange.bind(this);
this.zipChange=this.zipChange.bind(this);
}
//Toggle the communication detail
toggleHidden ()
{
this.setState({
isHidden: !this.state.isHidden
})
}
//************ Set the state details on changing the control values***
streetChange(e)
{
this.setState({street: e.target.value},
()=>{ editabledata.street=this.state.street; } );
}
cityChange(e)
{
this.setState({city: e.target.value},
()=>{ editabledata.city=this.state.city; });
}
countryChange(e)
{
this.setState({countrycode: e.target.value},
()=>{ editabledata.country_code=this.state.countrycode; } );
}
stateChange(e)
{
this.setState({state: e.target.value},
()=>{ editabledata.state=this.state.state; } );
}
zipChange(e)
{
this.setState({zip: e.target.value},
()=>{ editabledata.zip=this.state.zip; } );
}
//************************************************************************
render()
{
return(
<div class="container">
<h3 onClick={this.toggleHidden.bind(this)}>Communication</h3>
<hr/>
{!this.state.isHidden &&<span class="spn-profile-update-body container">
<div class="row form-group">
<div class="col-sm-6">
<span id="spn-update-label">Location : </span><input type="text" placeholder={this.userdata.location} class="form-control" disabled/>
</div>
<div class="col-sm-6">
<span id="spn-update-label">Street : </span><input type="text" placeholder={this.userdata.street} class="form-control" onChange = {this.streetChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6">
<span id="spn-update-label">City : </span><input type="text" placeholder={this.userdata.city} class="form-control" onChange = {this.cityChange}/>
</div>
<div class="col-sm-6">
<span id="spn-update-label">State : </span><input type="text" placeholder={this.userdata.state} class="form-control" onChange = {this.stateChange} disabled/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6">
<span id="spn-update-label">Country Code : </span><input type="text" placeholder={this.userdata.country_code} class="form-control" onChange = {this.countryChange}/>
</div>
<div class="col-sm-6">
<span id="spn-update-label">ZIP : </span><input type="text" placeholder={this.userdata.zip} class="form-control" onChange = {this.zipChange} maxLength="5"/>
</div>
</div>
</span>}
</div>
)
}
}
//Component for Profile fundraiser updation
class Fundraiser extends Component
{
constructor(props)
{
super(props);
this.userdata=JSON.parse(localStorage.getItem('UserProfile'));
this.state = {
isHidden: true,
type:'',
organization:'',
isOpen:false
}
editabledata.fundraiser_type=this.userdata.fundraiser_type;
editabledata.organization_name=this.userdata.organization_name;
editabledata.fundraiser_logo_url=this.userdata.fundraiser_logo_url;
{!this.state.isHidden && <span />}
this.typeChange=this.typeChange.bind(this);
this.organizationChange=this.organizationChange.bind(this);
}
//Toggle the ImageUpload component for fundraiser logo
toggleModal()
{
this.setState({
isOpen: !this.state.isOpen
});
}
//Toggle the Fundraiser details
toggleHidden ()
{
this.setState({
isHidden: !this.state.isHidden
})
}
//********** Set the state details on the changing of the control value
typeChange(e)
{
this.setState({type: e.target.value},
()=>{ editabledata.fundraiser_type=this.state.type; } );
}
organizationChange(e)
{
this.setState({organization: e.target.value},
()=>{ editabledata.organization_name=this.state.organization; } );
}
//***********************************************************************
render()
{
return(
<div class="container">
<h3 onClick={this.toggleHidden.bind(this)}>Fundraiser</h3>
<hr/>
{!this.state.isHidden &&<span class="spn-profile-update-body container">
<div class="row ">
<div class="col-sm-6">
<div class="row form-group">
<div class="col-sm-12">
<span id="spn-update-label">Type : </span><input type="text" placeholder={this.userdata.fundraiser_type} class="form-control" onChange = {this.typeChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<span id="spn-update-label">Organization : </span><input type="text" placeholder={this.userdata.organization_name} class="form-control" onChange = {this.organizationChange}/>
</div>
</div>
</div>
<div class="col-sm-6">
<center><span> <img src={this.userdata.fundraiser_logo_url} ref={img => this.img = img} onError={ () => this.img.src = '../img/dob.jpeg'} class="img-circle" id="img-fundraiser-logo-update" onClick={this.toggleModal.bind(this)} data-toggle="tooltip" title="Change Logo" data-placement="center"/></span> <ImageUpload show={this.state.isOpen} imagetype="fundraiserLogo" userid={this.userdata.id} onClose={this.toggleModal.bind(this)} >
</ImageUpload>
</center>
</div>
</div>
</span>}
</div>
)
}
}
//Component for Profile Connectivity updation
class Connectivity extends Component
{
constructor(props)
{
super(props);
this.userdata=JSON.parse(localStorage.getItem('UserProfile'));
this.state = {
isHidden: true,
google:this.userdata.google_link,
twitter:this.userdata.twitter_link,
fb:this.userdata.facebook_link
}
editabledata.google_link=this.userdata.google_link;
editabledata.twitter_link=this.userdata.twitter_link;
editabledata.facebook_link=this.userdata.facebook_link;
{!this.state.isHidden && <span />}
this.googleChange=this.googleChange.bind(this);
this.twitterChange=this.twitterChange.bind(this);
this.fbChange=this.fbChange.bind(this);
}
//Toggle the connectivity details
toggleHidden ()
{
this.setState({
isHidden: !this.state.isHidden
})
}
//*********** Set the state on changes the control value
googleChange(e)
{
this.setState({google: e.target.value},
()=>{ editabledata.google_link=this.state.google; } );
}
twitterChange(e)
{
this.setState({twitter: e.target.value},
()=>{ editabledata.twitter_link=this.state.twitter; } );
}
fbChange(e)
{
this.setState({fb: e.target.value},
()=>{ editabledata.facebook_link=this.state.fb; } );
}
//********************************************************
render()
{
return(
<div class="container">
<h3 onClick={this.toggleHidden.bind(this)}>Connectivity</h3>
<hr/>
{!this.state.isHidden &&<span class="spn-profile-update-body container">
<div class="row form-group">
<div class="col-sm-12">
<span id="spn-update-label"><img src="../img/fb.jpeg" class="img-circle" id="img-network"/></span><input type="text" placeholder={this.userdata.facebook_link} class="form-control" onChange = {this.fbChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<span id="spn-update-label"><img src="../img/twt.jpeg" class="img-circle" id="img-network"/></span><input type="text" placeholder={this.userdata.twitter_link} class="form-control" onChange = {this.twitterChange}/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<span id="spn-update-label"><img src="../img/gle.png" class="img-circle" id="img-network"/></span><input type="text" placeholder={this.userdata.google_link} class="form-control" onChange = {this.googleChange}/>
</div>
</div>
</span>}
</div>
)
}
}
export default UpdateProfile;<file_sep>/component/conversion.js
export function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(parseInt(dateItems[2]),parseInt(dateItems[0]),parseInt(dateItems[1]));
return (formatedDate);
}
| d864c4039cab15022942f1823ae0acccd3c8a3d8 | [
"JavaScript"
] | 6 | JavaScript | DeepakR63/Fund | 15f32f2395b7a6b2772be1dafc495dfe52d69dc7 | 188de1f5286fe15304f7efbbef153c99bab03c3c |
refs/heads/master | <repo_name>LuckyFox1/JQueryPlugin<file_sep>/js/script.js
$(function () {
var width;
var boundaryWidth = 980;
var isSlider = false;
var gallery = $('#gallery');
var images = gallery.children();
var amountImages = images.length;
if ($(window).innerWidth() < boundaryWidth) {
isSlider = true;
gallery.slider({gallery: gallery, isPagination: true, isArrows: true});
}
else {
isSlider = false;
}
$(window).resize(function () {
width = $(window).innerWidth();
if (width < boundaryWidth && !isSlider) {
isSlider = true;
gallery.slider({gallery: gallery, isPagination: true, isArrows: true});
}
if (width >= boundaryWidth && gallery.children().length > amountImages) {
isSlider = false;
gallery.slider('destroy');
}
});
var width2;
var boundaryWidth2 = 980;
var isSlider2 = false;
var gallery2 = $('#gallery2');
var images2 = gallery2.children();
var amountImages2 = images2.length;
if ($(window).innerWidth() < boundaryWidth2) {
isSlider2 = true;
gallery2.slider({gallery: gallery2, isPagination: true, isArrows: true});
}
else {
isSlider2 = false;
}
$(window).resize(function () {
width2 = $(window).innerWidth();
if (width2 < boundaryWidth2 && !isSlider2) {
isSlider2 = true;
gallery2.slider({gallery: gallery2, isPagination: true, isArrows: true});
}
if (width2 >= boundaryWidth2 && gallery2.children().length > amountImages2) {
isSlider2 = false;
gallery2.slider('destroy');
}
});
}); | 6681447490ec01d482081296769a517c5121fbcd | [
"JavaScript"
] | 1 | JavaScript | LuckyFox1/JQueryPlugin | 5d34c063d98f63660f24783ee2386e37abc96518 | fd3fb5b0e4e13ccf3cc9f3b157d96ca6a1935eef |
refs/heads/master | <repo_name>EyalBrilling/FlightSimulator_Web<file_sep>/Models/ServerManager.cs
using FlightSimulator_Web.Controllers.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace FlightSimulator_Web.Models
{
public class ServerManager {
private readonly HttpClient httpClient;
public ServerManager()
{
httpClient = new HttpClient();
}
internal async Task<List<Flight>> returnExternalFlights(List<Server> serverlist,string relative_to)
{
List<Flight> externalFlightsList = new List<Flight>();
foreach (Server server in serverlist)
{
string stringToGetFlight = "http://" + server.serverURL + "/api/Flights?relative_to=" + relative_to;
HttpResponseMessage response = await httpClient.GetAsync(stringToGetFlight);
string jsonString =await response.Content.ReadAsStringAsync();
List<Flight> flightsList = JsonConvert.DeserializeObject<List<Flight>>(jsonString);
foreach(Flight externalFlight in flightsList)
{
externalFlightsList.Add(externalFlight);
}
}
return externalFlightsList;
}
}
}
<file_sep>/Controllers/ServerController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FlightSimulator_Web.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FlightSimulator_Web.Controllers
{
[Route("api/Server")]
[ApiController]
public class ServerController : ControllerBase
{
private ServerManager serverManager;
}
}
<file_sep>/Models/FlightPlan.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace FlightSimulator_Web.Models
{
[Owned]
public class InitialLocation
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public DateTimeOffset Date_Time { get; set; }
}
[Owned]
public class Location
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public double TimeSpan_Seconds { get; set; }
}
public class FlightPlan
{
[Key]
public string FlightID { get; set; }
public int Passengers { get; set; }
public string Company_Name { get; set; }
public InitialLocation initial_Location { get; set; }
public List<Location> segments { get; set; }
public FlightPlan()
{
this.initial_Location = new InitialLocation();
this.segments = new List<Location>();
}
}
}
<file_sep>/Models/FlightsContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FlightSimulator_Web.Controllers.Models;
using Microsoft.EntityFrameworkCore;
namespace FlightSimulator_Web.Models
{
public class FlightsContext : DbContext
{
public FlightsContext(DbContextOptions<FlightsContext> options)
: base(options)
{
}
public DbSet<Flight> Flights { get; set; }
public DbSet<FlightPlan> FlightsPlans { get; set; }
public DbSet<Server> Servers { get; set; }
}
}
<file_sep>/Controllers/FlightsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using FlightSimulator_Web.Models;
using FlightSimulator_Web.Controllers.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Microsoft.AspNetCore.Routing;
namespace FlightSimulator_Web.Controllers
{
[Route("api")]
[ApiController]
public class FlightsController : ControllerBase
{
private readonly FlightsContext flightContext;
private FlightManager flightManager;
private ServerManager serverManager;
public FlightsController(FlightsContext context)
{
flightContext = context;
flightManager = new FlightManager();
serverManager = new ServerManager();
}
// GET(by ID): api/FlightPlan/5
[Route("FlightPlan/{id}")]
//[HttpGet("{id}")]
public async Task<ActionResult<FlightPlan>> GetFlightPlan(string id)
{
if(id.Length != 6)
{
return BadRequest("This server plane IDs are 6 letters long. did you mean to request other ID?");
}
FlightPlan flightPlan;
flightPlan = await flightContext.FlightsPlans.Include(r => r.initial_Location)
.Include(r => r.segments).FirstOrDefaultAsync(x => x.FlightID == id);
if (flightPlan == null)
{
return NotFound();
}
return flightPlan;
}
// POST: api/FlightPlan
[Route("FlightPlan")]
[HttpPost]
public async Task<ActionResult<FlightPlan>> PostFlightPlan(FlightPlan flightPlan)
{
if (!flightManager.CheckIfFlightPlanIsValid(flightPlan))
{
return BadRequest("the flight plan format is wrong. did you forget a field?");
}
string newID = flightManager.GenerateRandomID();
flightPlan.FlightID = newID;
flightContext.FlightsPlans.Add(flightPlan);
Flight flightFromFlightPlan = flightManager.CreateNewFlight(flightPlan);
flightContext.Flights.Add(flightFromFlightPlan);
await flightContext.SaveChangesAsync();
return CreatedAtAction("GetFlightPlan", new { id = flightPlan.FlightID }, flightPlan);
}
// DELETE(by ID): api/FlightPlans/5
[Route("FlightPlan/{id}")]
[HttpDelete]
public async Task<ActionResult<FlightPlan>> DeleteFlightPlan(string id)
{
FlightPlan flightPlan = await flightContext.FlightsPlans.FindAsync(id);
if (flightPlan == null)
{
return NotFound();
}
Flight flight = await flightContext.Flights.FindAsync(id);
flightContext.Flights.Remove(flight);
flightContext.FlightsPlans.Remove(flightPlan);
await flightContext.SaveChangesAsync();
return flightPlan;
}
[Route("flights")]
[HttpGet]
public async Task<ActionResult<IEnumerable<Flight>>> GetCurrentServerFlightsByDate(string relative_to)
{
string uri = Request.QueryString.ToString();
List<Flight> flightList = new List<Flight>();
//get List of all active flights with placment in relative_to the date variable "relative_to"
List<Flight> internalflightList = flightManager.FlightSituitionInSpecificDate(await flightContext.FlightsPlans.ToListAsync(), relative_to);
//get list of external flights in relative to the date variable "relative_to"
List<Flight> updatedExternalFlights =await serverManager.returnExternalFlights(await flightContext.Servers.ToListAsync(),relative_to);
//define external flights as external and add them to the flight list.
foreach(Flight externalFlight in updatedExternalFlights)
{
externalFlight.is_External = true;
if (!flightManager.CheckIfFlightIsValid(externalFlight))
{
return BadRequest("an external server sent wrong flight format. please check servers and try again.");
}
flightList.Add(externalFlight);
}
//recheck external variable in internal flights is not null and add to flightList
foreach (Flight internalFlight in internalflightList)
{
Flight flightToTakeExternalVariable = await flightContext.Flights.FirstOrDefaultAsync(plane => plane.Flight_ID == internalFlight.Flight_ID);
internalFlight.is_External = flightToTakeExternalVariable.is_External;
flightList.Add(internalFlight);
}
if (uri.Contains("sync_all"))
{
return flightList;
}
else
{
flightList = flightList.Where(flight => flight.is_External == false).ToList();
return flightList;
}
}
[Route("getallplanes")]
[HttpGet]
public async Task<ActionResult<FlightPlan>> GetAllPlanes()
{
return CreatedAtAction("GetAllPlanes", new { planes = flightContext.FlightsPlans });
}
}
}
<file_sep>/Models/FlightManager.cs
using FlightSimulator_Web.Controllers.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Security.Cryptography;
namespace FlightSimulator_Web.Models
{
public class FlightManager
{
private FlightPlan CreateNewFlightPlan(FlightPlan model)
{
// FlightPlan newFlightPlan = new FlightPlan();
// newFlightPlan.Passengers = model.Passengers;
// newFlightPlan.Company_Name = model.Company_Name;
// newFlightPlan.initial_Location.Latitude= model.initial_Location.Latitude;
// newFlightPlan.initial_Location.Longitude = model.initial_Location.Longitude;
// newFlightPlan.initial_Location.Date_Time = model.initial_Location.Date_Time;
//foreach (Location location in model.segments)
// {
// Location newLocation = new Location();
// newFlightPlan.segments.Add(newLocation);
// newLocation.Latitude = location.Latitude;
// newLocation.Longitude = location.Longitude;
// newLocation.TimeSpan_Seconds = location.TimeSpan_Seconds;
// }
// newFlightPlan.segments = model.segments;
return model;
}
public Flight CreateNewFlight(FlightPlan model)
{
Flight newFlight = new Flight();
newFlight.Flight_ID = model.FlightID;
newFlight.Longitude = model.initial_Location.Longitude;
newFlight.Latitude = model.initial_Location.Latitude;
newFlight.Passengers = model.Passengers;
newFlight.Company_Name = model.Company_Name;
newFlight.Date_Time = model.initial_Location.Date_Time;
newFlight.is_External = false;
return newFlight;
}
//return flights with information relative to the date(longitide,latitude...)
public List<Flight> FlightSituitionInSpecificDate(List<FlightPlan> flightList,string date)
{
List<Flight> flightsInDate = new List<Flight>();
foreach(FlightPlan flightPlan in flightList)
{
TimeSpan flightTime = ReturnFlightTime(flightPlan);
TimeSpan timeBetweenDateAndTakeoff = ReturnTakeoffTimePassedFromDate(date,flightPlan);
if (timeBetweenDateAndTakeoff > flightTime || timeBetweenDateAndTakeoff< TimeSpan.Zero)
{
//plane is not in the air
continue;
}
else
{
Flight flighInfoRelativeToDate = MakeNewFlightRelativeToTimeInAir(timeBetweenDateAndTakeoff, flightPlan);
flightsInDate.Add(flighInfoRelativeToDate);
}
}
return flightsInDate;
}
private Flight MakeNewFlightRelativeToTimeInAir(TimeSpan TimeOfFlightUntilDate, FlightPlan flightPlan)
{
Flight currentFlightInfo = new Flight();
currentFlightInfo.Flight_ID = flightPlan.FlightID;
currentFlightInfo.Passengers = flightPlan.Passengers;
currentFlightInfo.Company_Name = flightPlan.Company_Name;
currentFlightInfo.Date_Time = flightPlan.initial_Location.Date_Time.Add(TimeOfFlightUntilDate);
TimeSpan timeCounter = TimeSpan.Zero;
double previousSegmentLongitude = flightPlan.initial_Location.Longitude;
double previousSegmentLatitude = flightPlan.initial_Location.Latitude;
//go over each location until the segment is after the plane segment or end of segments
foreach (Location location in flightPlan.segments)
{
timeCounter =timeCounter.Add(TimeSpan.FromSeconds(location.TimeSpan_Seconds));
if(TimeOfFlightUntilDate.CompareTo(timeCounter) < 0)
{
//time start of segment in which the plane is
TimeSpan previousSegmentTimeCounter = timeCounter.Subtract(TimeSpan.FromSeconds(location.TimeSpan_Seconds));
//calculate in what part of segment the plane is
double partOfSegment = (TimeOfFlightUntilDate.TotalSeconds - previousSegmentTimeCounter.TotalSeconds) / (location.TimeSpan_Seconds);
//calculate longitude and latitude of plane relatve to the date
currentFlightInfo.Longitude =previousSegmentLongitude + (location.Longitude - previousSegmentLongitude) * partOfSegment;
currentFlightInfo.Latitude =previousSegmentLatitude + (location.Latitude - previousSegmentLatitude) * partOfSegment;
break;
}
//save previous segment location
previousSegmentLongitude = location.Longitude;
previousSegmentLatitude = location.Latitude;
}
return currentFlightInfo;
}
//return how much time passed from plane takeoff relative to date
private TimeSpan ReturnTakeoffTimePassedFromDate(string date,FlightPlan flightPlan)
{
DateTimeOffset dateTimeFromUser =DateTimeOffset.Parse(date);
DateTimeOffset dateTimeOfTakeoff = flightPlan.initial_Location.Date_Time;
//substract flight initial time from the date. give the space between them. if its minus,means date is before plane takeoff.
TimeSpan timeBetweenDates = dateTimeFromUser.Subtract(dateTimeOfTakeoff);
return timeBetweenDates;
}
//returns how much time the plane is in the air
public TimeSpan ReturnFlightTime(FlightPlan flight)
{
TimeSpan flightTime = new TimeSpan(0, 0, 0);
foreach(Location segment in flight.segments)
{
flightTime += TimeSpan.FromSeconds(segment.TimeSpan_Seconds);
}
return flightTime;
}
public string GenerateRandomID()
{
Random random = new Random();
string newID = string.Empty;
//append two randomhars (A-Z)
newID += (Convert.ToChar(random.Next(65, 90)));
newID += (Convert.ToChar(random.Next(65, 90)));
//apend 4 random numbers
newID += Convert.ToString(random.Next(1000, 9999));
return newID;
}
internal ActionResult ReturnInternalFlightsByDate(string date)
{
throw new NotImplementedException();
}
public string ChangeDateFormatToUTC(DateTimeOffset fullDate)
{
return fullDate.ToString();
}
public bool CheckIfFlightIsValid(Flight flight)
{
if (flight.Passengers < 0 || flight.Company_Name == null)
{
return false;
}
return true;
}
public bool CheckIfFlightPlanIsValid(FlightPlan flightPlan)
{
if(flightPlan.Passengers < 0 || flightPlan.Company_Name == null || flightPlan.segments == null)
{
return false;
}
return true;
}
}
}
<file_sep>/Controllers/FlightController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FlightSimulator_Web.Controllers.Models;
using FlightSimulator_Web.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace FlightSimulator_Web.Controllers
{
[Route("/api")]
[ApiController]
public class FlightController : ControllerBase
{
public FlightManager flightManager;
public FlightController(FlightManager flightManager)
{
this.flightManager = flightManager;
}
[Route("Flights/{givenDate:datetime?}")]
[HttpGet]
public ActionResult GetInternalFlights(string date)
{
return flightManager.ReturnInternalFlightsByDate(date);
}
//[Route("FlightPlan")]
//[HttpPost]
//public async Task<ActionResult<FlightPlan> PostFlightPlan(FlightPlan flightPlan)
//{
// //string recivedFlightPlanString = recivedFlightPlan.ToString();
// //flightManager.AddNewFlight(recivedFlightPlanString);
// //return Ok();
//}
}
}
<file_sep>/Controllers/ServersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using FlightSimulator_Web.Models;
using System.Net.Http;
namespace FlightSimulator_Web.Controllers
{
[Route("api/")]
[ApiController]
public class ServersController : ControllerBase
{
private readonly FlightsContext serverContext;
public ServersController(FlightsContext context)
{
serverContext = context;
}
// GET: api/servers
[Route("servers")]
[HttpGet]
public async Task<ActionResult<IEnumerable<Server>>> GetServers()
{
return await serverContext.Servers.ToListAsync();
}
// GET(by ID): api/servers/5
[Route("servers")]
[HttpGet("{id}")]
public async Task<ActionResult<Server>> GetServer(string id)
{
Server server = await serverContext.Servers.FindAsync(id);
if (server == null)
{
return NotFound();
}
return server;
}
// POST: api/servers
[Route("servers")]
[HttpPost]
public async Task<ActionResult<Server>> PostServer(Server server)
{
serverContext.Servers.Add(server);
try
{
await serverContext.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ServerExists(server.serverID))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction("GetServer", new { id = server.serverID }, server);
}
// DELETE: api/Servers/5
[HttpDelete("{id}")]
public async Task<ActionResult<Server>> DeleteServer(string id)
{
Server server = await serverContext.Servers.FindAsync(id);
if (server == null)
{
return NotFound();
}
serverContext.Servers.Remove(server);
await serverContext.SaveChangesAsync();
return server;
}
private bool ServerExists(string id)
{
return serverContext.Servers.Any(e => e.serverID == id);
}
}
}
| d6a3fa1896f37a52fc97c8ae6edbedd268d302d5 | [
"C#"
] | 8 | C# | EyalBrilling/FlightSimulator_Web | 36064e7085d6e6766269f0206ba17b9d3d92d918 | dfec653d2ed6b663f860b2d8de27555c057cc295 |
refs/heads/master | <file_sep>import numpy as np
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
iris_X = iris.data # use iris_X.shape --> SHAPE shows the dimensions. it's a property of numpy arrays
iris_Y = iris.target
np.random.seed(0)
indices = np.random.permutation(len(iris_X))
print(indices)
iris_X_train = iris_X[indices[:-10]] # use index -10 as [:-10] to avoid having to specify the length of the array and just select all data from 0 except the last 10
iris_Y_train = iris_Y[indices[:-10]] # WHAT IS indices? --> is the array went through a permutation with all the indices (all indices are the size of iris_X
iris_X_test = iris_X[indices[-10:]]
iris_Y_test = iris_Y[indices[-10:]]
knn = KNeighborsClassifier() # typing knn in the console shows you hte details of the classifier or regressor
knn.fit(iris_X_train,iris_Y_train)
print(knn.predict(iris_X_test))
print(iris_Y_test) #changing the seed used for the permutation, determines different train and test and therefore changes the fit
#PRESS SHIFT 2 TIMES TO SEARCH EVERYWHERE<file_sep>from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier # WHAT IS sklearn.neighbors? why from 'skelearn.neighbors import *' also works
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score
import seaborn as sns
sns.set_style('whitegrid') # FYI the “sns.set_style(‘whitegrid’)” just sets us up to use a nice pre set plot scheme, provided by the seaborn library
#PRESS SHIFT 2 TIMES TO SEARCH EVERYWHERE
numbers = datasets.load_digits()
print("The number of dimension of the data is {} and of the target is {}".format(numbers.data.shape, numbers.target.shape))
# plt.imshow(numbers.data)
# plt.show()
# for i in range(len(numbers.))
# print(numbers.data.reshape(1797,8,8)) # a = numbers.data has (1797,64) to convert into images need to do--> a.reshape(1797,8,8) and this becomes the same as numbers.images
# numbers['images'] = numbers.data.reshape(1797,8,8) # create new feature called images
# print (numbers.images) # can either use numbers['images'] or numbers.images
# fig, axes = plt.subplots(5,5)
# for i, ax in enumerate(axes.flat): # if you wanna iterary over the nd.array, you need to convert it into 1d. either .flat, .flatten() or .ravel() work fine
# ax.imshow(numbers.images[i], cmap ='binary', interpolation = 'nearest') # axes contains all the 1797 ax
# plt.show() # if put plt.show inside the for loop then it replaces always the same
# plt.imshow(numbers.images[0])
# plt.show()
# a = np.random.normal(0,1,(5,5)) # TRAIN YOUR DATA AND THEN GIVE IT RANDOM NUMBERS AND ASK WHICH NUMBER IT IS
# plt.imshow(a)
# plt.show()
numbers_train_X = numbers.data[:-10]
numbers_train_Y = numbers.target[:-10]
# numbers_test_X = numbers.data[-10::-1] # 1788 instances from 1797
numbers_test_X = numbers.data[-10:] # 10 instances
numbers_test_Y = numbers.target[-10:]
# print(numbers.data[-10::-1].shape, numbers.data[-10:].shape)
predict=[]
predict_name = []
knn = KNeighborsClassifier()
knn.fit(numbers_train_X,numbers_train_Y)
predict_knn = knn.predict(numbers_test_X)
predict.append(predict_knn)
print(predict_knn)
print(numbers_test_Y)
predict_name.append(str(predict_knn))
lin = LinearRegression()
lin.fit(numbers_train_X,numbers_train_Y)
predict_LinR = lin.predict(numbers_test_X)
predict.append(predict_LinR)
print(predict)
print(numbers_test_Y )
# #
lor = LogisticRegression()
lor.fit(numbers_train_X,numbers_train_Y)
predict_logR = lor.predict(numbers_test_X)
predict.append(predict_logR)
print(predict)
print(numbers_test_Y)
# #
sgd = SGDClassifier(random_state=42)
sgd.fit(numbers_train_X,numbers_train_Y)
predict_SGDclass = sgd.predict(numbers_test_X)
predict.append(predict_SGDclass)
print(predict)
print(numbers_test_Y)
# fig, ax1 = plt.subplots(nrow = 3,ncols = 1)
# for i,_ in enumerate(predict):
numbers_test_Y_string = str(numbers_test_Y).strip('[]')
for i in range(4):
plt.subplot(4,1,i+1)
plt.plot(numbers_test_Y_string.split(),predict[i], marker= 'o', linestyle = '', c = 'b' ,alpha = 0.5)
# plt.plot(numbers_test_Y_string.split(),predict[i], marker= 'o', linestyle = '', c = 'b' ,alpha = 0.5)
# # plt.ion()
plt.xlabel('data')
plt.ylabel('prediction')
plt.yticks(range(0,10))
plt.legend(handles = [], loc=1)
plt.show()
# add crosvalidation<file_sep>from sklearn import datasets
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import scatter_matrix
cali = datasets.fetch_california_housing()
print(type(cali))
#plt.imsho
cal = pd.DataFrame( data = cali.data, columns = cali.feature_names)
print(cal.describe(), cal.head(10), cal.info()) # head(50) shows the top 50, info shows #data points and data type for each feature
# cal.hist(bins = 50, figsize=(10,10))
# plt.show()
# cal.plot( kind = "scatter", x = cal['Longitude'], y = cal['Latitude'])
# plt.show()
# plt.scatter(x = cal['Longitude'], y = cal['Latitude'], c = np.log10(cal['Population']), cmap = 'viridis', linewidth = 0.5, alpha = 0.75, s = cal['Population']/100, label = "population")
# plt.axis(aspect = 'equal')
# plt.xlabel('longitude')
# plt.ylabel('latitude')
# plt.colorbar(label = 'log$_{10}$(Population')
# plt.clim(2,5)
# plt.show()
# plt.scatter(x = cal['Longitude'], y = cal['Latitude'], c = cal['MedInc'], cmap = plt.get_cmap('jet'), linewidth = 0.5, alpha = 0.4, s = cal['Population']/100, label = "population")
# plt.axis(aspect = 'equal')
# plt.xlabel('longitude')
# plt.ylabel('latitude')
# plt.colorbar(label = 'Median Income')
# plt.clim(2,5)
# plt.show()
# attributes = cal.columns
# scatter_matrix(cal[attributes], figsize=(20,15))
# plt.show()
corr_matrix = cal.corr(method = 'pearson')
print(corr_matrix)
print(corr_matrix['MedInc']>0.5) #fancy indexing because use boolean to select data
np.random.seed(0)
indices = np.random.permutation(len(cal['MedInc']))
cal_train = cal['MedInc'][indices[:-1000]]
# print(cal_train)
lnn = linear_model.LinearRegression()
# lnn.fit(cal_train['HouseAge'], cal_train['MedInc'])
| c37f8de740f54f9d291f710f17b5787af43d5b8a | [
"Python"
] | 3 | Python | fedegott/Intro_Machine_Learning | f8b47bd4adf3e8a24f76230cb67869165a08e5b3 | ac27bdd80c1aa467073c8e92fa5de0176e74a561 |
refs/heads/master | <file_sep># Text-Encryptior
http://wordencryptior.appspot.com/
Take text as a string. Then each alphabet replace with their ascii value with some addition/deduction.
<file_sep>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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.
#
import webapp2
front="""
<!--
Want to add some emotional text here . But I can't.
Rak1, SI and ATC must watch this and bring out something to crack new jokes. :(
-->
<div>
<b>
<h1>Welcome to Word encryptor !</h1>
</div>
<form method="post">
<select name="ROT">
<option value="0">13 Rotation in every step</option>
<option value="1">13 Rotation after 1 step(s)</option>
<option value="2">13 Rotation after 2 step(s)</option>
</select>
<br>
<br>
<div style="color: red">
<b>
%(error)s
</div>
<br>
<button type="submit" > Submit </button>
</form>
"""
rot="""
<div>
<b>
<h1>Rotation %(rotation)s</h1>
</div>
<form method="post">
<form method="post">
<!--
<input type="text" name='text' value="%(text)s" style="height: 100px; width: 400px;"> -->
<textarea name="text"
style="height: 100px; width: 400px;">%(text)s</textarea>
<br><br>
<button type="submit" value="Submit" >Submit </button>
</form>
<form action="./" >
<input type="submit" name="Home" value="Home">
</form>
"""
def encrypt(s,st):
s=s.lower();
s=list(s);
for i in range(len(s)):
if (s[i].isalpha()==True and (st==0 or (i+1)%st==0) ) :
s[i]=chr( ( (ord(s[i])-97)+13+26)%26+97 );
#x=chr(ord(s[0])-32);
#s[0]=x;
s="".join(s)
return s
def escape_html(s):
s=s.replace("&","&")
s=s.replace(">",">")
s=s.replace("<","<")
s=s.replace('"',""")
return s;
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(front%{"error":""} )
def post(self):
ROT=self.request.get('ROT')
if(ROT=="0"):
self.redirect('/rot13')
elif(ROT=="1"):
self.redirect('/rot13_1')
elif(ROT=="2"):
self.redirect('/rot13_2')
# else:
# self.response.out.write(front%{"error":"That page is under construction.Please try another option !"} )
class ROT13_0(webapp2.RequestHandler):
def get(self):
self.response.out.write(rot%{"text":"Enter your text here...","rotation":"13 Rotation in every step" } )
def post(self):
text=self.request.get('text')
self.response.out.write(rot%{"text":escape_html( encrypt(text,1) ),"rotation":"13 Rotation in every step" } )
class ROT13_1(webapp2.RequestHandler):
def get(self):
self.response.out.write(rot%{"text":"Enter your text here...","rotation":"13 Rotation in 1 step(s)" } )
def post(self):
text=self.request.get('text')
self.response.out.write(rot%{"text":escape_html( encrypt(text,2) ),"rotation":"13 Rotation in 1 step(s)" } )
class ROT13_2(webapp2.RequestHandler):
def get(self):
self.response.out.write(rot%{"text":"Enter your text here...","rotation":"13 Rotation in 2 step(s)" } )
def post(self):
text=self.request.get('text')
self.response.out.write(rot%{"text":escape_html( encrypt(text,3) ),"rotation":"13 Rotation in 2 step(s)" } )
app = webapp2.WSGIApplication([
('/', MainHandler),('/rot13',ROT13_0),('/rot13_1',ROT13_1),('/rot13_2',ROT13_2)
], debug=True)
| 03ebdb4195adf897cae29875e3662e18bb99f0b2 | [
"Markdown",
"Python"
] | 2 | Markdown | Kimbbakar/Text-Encryptior | 0f8ac9c1cbb3fc3171ee377588737ae2f5444550 | 85e83673f5de35eeb6d6229e468369ca682422e5 |
refs/heads/master | <repo_name>ArnabBasak/PythonRepository<file_sep>/python programs/calculator with function.py
#program to create calculator using function
def add(x,y):
z = x+y
print('addition is: ',z)
def sub(x,y):
z = x+y
print('substraction is: ',z)
def mul(x,y):
z = x*y
print('multiplication is: ',z)
def div(x,y):
z = x/y
print('division is: ',z)
num1 = int(input("enter number 1"))
num2 = int(input("enter number 2"))
choice = int(input('enter your choice\npress 1 for addition: \npress 2 for substraction: \npress 3 for multiplication: \npress 4 for division '))
if choice == 1:
add(num1,num2)
elif choice == 2:
sub(num1,num2)
elif choice == 3:
sub(num1,num2)
elif choice == 4:
sub(num1,num2)
else:
print('invalid options')
<file_sep>/Python_Programs/PythonCode/Guess_The_Number.py
"""
2. Guess the Number
The Goal: Similar to the first project, this project also uses the random module in Python.
The program will first randomly generate a number unknown to the user. The user needs to guess what that number is.
(In other words, the user needs to be able to input information.) If the user’s guess is wrong,
the program should return some sort of indication as to how wrong (e.g. The number is too high or too low).
If the user guesses correctly, a positive indication should appear.
You’ll need functions to check if the user input is an actual number,
to see the difference between the inputted number and the randomly generated numbers, and to then compare the numbers.
Concepts to keep in mind:
Random function
Variables
Integers
Input/Output
Print
While loops
If/Else statements
"""
import random
class NumberGuess:
def __init__(self):
self.score = 0
def userInput(self):
self.userinput = int(input('enter any number'))
if self.userinput not in range(1,99999):
print('sorry your inputed number is too large')
self.userInput()
def gamePlay(self):
self.randomNumber = random.randrange(1,99999)
if self.userInput == self.randomNumber:
self.score += 1
print("congratulation you won your score is",self.score)
self.userchoice = int(input('press 1 to play again'))
if self.userchoice == 1:
self.userInput()
self.gamePlay()
else:
print('Your final score is',self.score)
elif self.userInput != self.randomNumber:
self.score -= 1
if self.randomNumber < self.userinput:
print('Opps sorry you missed by',self.userInput - self.randomNumber,'as computer guessed',self.randomNumber)
self.userchoice = int(input('press 1 to play again'))
if self.userchoice == 1:
self.userInput()
self.gamePlay()
else:
print('Your final score is',self.score)
else:
print('Opps sorry you missed by',self.randomNumber - self.userinput,'as computer guessed',self.randomNumber)
self.userchoice = int(input('press 1 to play again'))
if self.userchoice == 1:
self.userInput()
self.gamePlay()
else:
print('Your final score is',self.score)
NG = NumberGuess()
NG.userInput()
NG.gamePlay()
<file_sep>/numpy.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 23:56:40 2018
@author: arnabbasak
"""
import numpy as np
import sys
import time
l = range(1000000000)
print(sys.getsizeof(1)*len(l))
array = np.arange(1000)
print(array.size*array.itemsize)
SIZE = 1000
l1 = range(SIZE)
l2 = range(SIZE)
a1 = np.arange(SIZE)
a2 = np.arange(SIZE)
#python list
start = time.time()
result = [(x + y) for x,y in zip(l1,l2)]
print('python list took',(time.time()-start)*1000)
#numpy
start = time.time()
result = a1 + a2
print('python numpy took',(time.time()-start)*1000)
#addition
array1 = np.arange(500)
array2 = np.arange(500)
print('addition is',array1 + array2)
print('multiplication is',array1 * array2)<file_sep>/python programs/database.py
import mysql.connector from mysql
db = mysql.connector.connect(user='root',password='<PASSWORD>',host='localhost',database='test')
<file_sep>/data_visualization/loading_data.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 22:48:40 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
#part 1
"""import csv
x = []
y = []
with open('example.txt','r') as csvfile:
plots = csv.reader(csvfile,delimiter=',')
for row in plots:
x.append(int (row[0]))
y.append(int (row[1]))
plt.plot(x,y,label='loaded from a file')"""
#part 2
import numpy as np
x,y = np.loadtxt('example.txt',delimiter=',',unpack=True)
plt.plot(x,y,label='loaded from a file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Intersting Graph\nCheck it out')
plt.legend()
plt.show()
<file_sep>/pythoncodes/movie.py
import numpy as np
import math
#this is the static data
moviedictionary = {
"Anand":8.7,
"Drishyam":8.6,
"Golmal":8.5,
"Black Friday":8.5,
"Dangal":8.4,
"<NAME>":8.4,
"<NAME>":8.4,
"3 ediots":8.4,
"<NAME>":8.4,
"Guide":8.3
}
#print(moviedictionary)
#this variable is to insert the users movie list
usermovielist = []
# if the movie is not present in the static data
newmovielist = []
#declaring the range
poorlist = (np.arange(0,4,0.1))
averagelist = (np.arange(4,6,0.1))
aboveaveragelist = (np.arange(6,8,0.1))
excellentlist = (np.arange(8,10,0.1))
#inserting the movie names
usersmovie1 = input("Enter the 1st movie name you watched\n")
if usersmovie1 in moviedictionary:
usermovielist.append(moviedictionary[usersmovie1])
else:
print('since this movie is not in our list we will be adding it in our list')
newmovielist.append(usersmovie1)
usersmovie2 = input("Enter the 2nd movie name you watched\n")
if usersmovie2 in moviedictionary:
usermovielist.append(moviedictionary[usersmovie2])
else:
print('since this movie is not in our list we will be adding it in our list')
newmovielist.append(usersmovie2)
usersmovie3 = input("Enter the 3rd movie name you watched\n")
if usersmovie3 in moviedictionary:
usermovielist.append(moviedictionary[usersmovie3])
else:
print('since this movie is not in our list we will be adding it in our list')
newmovielist.append(usersmovie3)
usersmovie4 = input("Enter the 4th movie name you watched\n")
if usersmovie4 in moviedictionary:
usermovielist.append(moviedictionary[usersmovie4])
else:
print('since this movie is not in our list we will be adding it in our list')
newmovielist.append(usersmovie4)
usersmovie5 = input("Enter the 5th movie name you watched\n")
if usersmovie5 in moviedictionary:
usermovielist.append(moviedictionary[usersmovie5])
else:
print('since this movie is not in our list we will be adding it in our list')
newmovielist.append(usersmovie5)
#calculating the mean for the users rating
usermean = np.mean(usermovielist)
roundingoff = math.floor(usermean)
print(newmovielist)
if roundingoff in poorlist:
print('user likes generally movies with poor ratings')
if roundingoff in averagelist:
print('user likes generally movies with average ratings')
if roundingoff in aboveaveragelist:
print('user likes generally movies with above ratings')
if roundingoff in excellentlist:
print('user likes generally movies with execellent ratings')
print('users average movie watching rating is ',usermean)
<file_sep>/pythonmongo/creatingdatabase.py
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 9 13:13:01 2018
@author: Arnab
"""
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
dblist = myclient.list_database_names()
print(dblist)
if mydb in dblist:
print('Database created successfully')
else:
print('Database is not created')
<file_sep>/practice.py
"""def solution(S):
Bcount = 0
Acount = 0
Ncount = 0
Ocount = 0
Lcount = 0
for elements in S:
if "B" in elements:
Bcount += 1
if "A" in elements:
Acount += 1
if "N" in elements:
Ncount += 1
if "L" in elements:
Lcount += 1
if "O" in elements:
Ocount += 1
if Bcount == Ncount == Acount and Lcount % 2 == 0 and Ocount % 2 == 0:
print("BALLOON is possible",Bcount,"times")
else:
print("BALLOON not possible from the inputted string")
solution("BALLOONBALLOONBALLOONBALLOON")"""
"""number = int(input('enter a number to find'))
nums = list(range(0,1000))
#print(nums)
if number in nums:
print("Yes")
else:
print("No")"""
"""mysentence = "It is a pleasent day today"
res = mysentence.split(" ")
even = 0
evenlist = []
longestword = 0
for elements in res:
if len(elements) % 2 == 0:
even += 1
evenlist.append(elements)
sortedlist = sorted(evenlist,key=len)
print(sortedlist[-1])"""
mystring = "This is my string"
res = mystring.split(" ")
secondstring = "This is my second string"
res2 = mystring.split(" ")
result = set(res) & set(res2)
print(result)
<file_sep>/python programs/sort methods and tupple.py
#sort methods of the list
mylist = [2.52847,123524.58971,96.325874,15142.1478,98745.014741]
print("the list consist of the following elements",mylist)
mylist.sort()
print("the list after sorting looks like",mylist);
#charaters or string sorting
print("my alphabets are after sorting",sorted('Arnab'))
#tupples
# tupples are nothing but similar to list which only store values,ans we can call the values but can't sort or add or delete the values
arnab = [20,42,85,78];
print("tuple arnab consist",arnab)
print("the value at index 2 is",arnab[2])
input("press enter to continue")
<file_sep>/progrms nltk/my first nltk.py
from nltk.tokenize import sent_tokenize, word_tokenize
example_text = "Hello Mr.Arnab,How are you doing. How is new life at Accenture? What is about the place Bangalore"
#print(sent_tokenize(example_text))
print(word_tokenize(example_text))
#for i in word_tokenize(example_text):
# print(i)
<file_sep>/python programs/LCM calculation.py
# LCM calculation
def LCM(x,y):
if x>y:
greater = x
else:
greater = y
while(True):
if(greater % x == 0) and (greater % y ==0):
lcm = greater
break
greater+=1
return lcm
num1 = int(input('enter number 1'))
num2 = int(input('enter number 2'))
print("the lcm of the given numbers are: ",LCM(num1,num2))
<file_sep>/Python_Programs/PythonCode/ButtonPractice.py
from tkinter import *
from tkinter import messagebox
top = Tk()
def fun():
messagebox.showinfo("Message","Hello all")
b1 = Button(top,text="Click Me",command=fun)
b1.pack(side=LEFT)
top.mainloop()
<file_sep>/data_visualization/scatter_plot.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 20:21:23 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8]
y = [5,2,4,3,8,1,7,10]
plt.scatter(x,y,label='scatterr',color='r',marker='*',s=500)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Intersting Graph\nCheck it out')
plt.legend()
plt.show()<file_sep>/NumPy_array.py
#!/usr/bin/env python
# coding: utf-8
# In[2]:
my_list = [1,2,3]
import numpy as np
arr = np.array(my_list)
arr
# In[3]:
my_mat = [[1,2,3],[4,5,6],[7,8,9]]
np.array(my_mat)
# In[4]:
np.arange(0,10)
# In[6]:
np.arange(0,11,2)
# In[7]:
np.zeros(3)
# In[9]:
np.zeros((2,3))
# In[10]:
np.ones((3,4))
# In[12]:
np.linspace(0,5,100)
# In[13]:
"""identiy matrix"""
np.eye(4)
# In[14]:
np.random.rand(5)
# In[15]:
np.random.rand(5,5)
# In[17]:
"""sample from gausian distribution/normal distribution"""
np.random.randn(4,4)
# In[18]:
np.random.randint(1,100)
# In[20]:
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
ranarr
# In[21]:
arr.reshape(5,5)
# In[22]:
ranarr
# In[23]:
ranarr.max() #find the max element
# In[25]:
ranarr.min() #find the min element
# In[26]:
ranarr.argmin() #index of max element
# In[27]:
ranarr.argmax() #index of min element
# In[28]:
arr = arr.reshape(5,5)
arr
# In[29]:
arr.shape #check the shape
# In[30]:
arr.dtype #check the datatype
# In[ ]:
<file_sep>/data_visualization/loading_data_internet.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 23:01:09 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates
def graph_data():
stock_price_url = 'https://pythonprogramming.net/yahoo_finance_replacement'
source_code = urllib.request.urlopen(stock_price_url).read().decode()
stock_data = []
split_source = source_code.split('\n')
for line in split_source:
split_line = line.split(',')
if len(split_line) == 6:
if "values" not in line:
stock_data.append(line)
date,closep,highp,lowp,volume = np.loadtxt(stock_data,
delimiter=',',
unpack=True,
# %Y = full year.2015
# %Y = partial year 15
# %m = number months
# %d = number day
# %H = Hours
# %M = minutes
# %s = seconds
#12-06-2014
# %m -%d -%y
converters={0:bytespdate2num('')})
plt.xlabel('x')
plt.ylabel('y')
plt.title('Intersting Graph\nCheck it out')
plt.legend()
plt.show()
<file_sep>/Python_Programs/PythonCode/simpleForm.py
from tkinter import *
parent = Tk()
name = Label(parent,text="Name").grid(row=0,column=0)
e1 = Entry(parent).grid(row = 0,column = 1)
password = Label(parent,text="<PASSWORD>").grid(row=1,column=0)
e2 = Entry(parent).grid(row = 1,column=1)
submit = Button(parent,text = "Submit").grid(row = 4, column = 0)
parent.mainloop()
<file_sep>/sentence_analysis.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from collections import Counter
import math
example_file = open('modi_speech.txt','r')
example_sent = example_file.read().replace('\n','')
print(len(example_sent))
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(example_sent)
filtered_sentence = [w for w in word_tokens if not w in stop_words ]
filtered_sentence = []
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
print('Token of the speech')
#print(word_tokens)
print()
print('filtered sentence')
#print(filtered_sentence)
print()
num = dict(Counter(filtered_sentence))
#print('word count')
#print(num)
print()
""" speech analysis"""
"""total words spoken by modi"""
print('total words spoken in the speech by modi',len(word_tokens))
print('total words spoken without stop words in the speech by modi',len(filtered_sentence))
print('total unique word spoken',len(num))
print('total stop word spoken',len(word_tokens) - len(filtered_sentence))
total_stop_word = len(word_tokens) - len(filtered_sentence)
percentage_of_stop_word_spoken = (total_stop_word/(len(word_tokens))*100)
print('total percentage of stop word spoken',math.floor(percentage_of_stop_word_spoken),"%")
"""most repeated word in the speech is I """
precentage_of_most_repeated_word = (54/len(filtered_sentence)*100)
print('precentage of most repeated word is',precentage_of_most_repeated_word)
#import nltk
#nltk.download('punkt')
<file_sep>/sliceing.py
example = [10,20,30,40,50,60,70,80,90]
print("my list is",example[: :])
print("my first part of the list",example[0:5])
print("my second part of the list",example[6:8])
print("my whole second part of the list",example[5:])
print(example[::2])
print(example[-2::-2])
<file_sep>/flask.py
from flask import Flask, render_template,request,json
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',user='user',password='<PASSWORD>',db='db',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
app = Flask(__name__)
@app.route("/get-reg")
def login():
return render_template('reg.html')
@app.route('/save-post',methods=['POST', 'GET'])
def signUp():
if request.method=='POST':
name=request.form['name']
email=request.form['email']
try:
with connection.cursor() as cursor:
# Read a single record
sql = "INSERT INTO userdata (username,email) VALUES (%s, %s)"
cursor.execute(sql, (name,email))
connection.commit()
finally:
connection.close()
return "Saved successfully."
else:
return "error"<file_sep>/Python_Programs/PythonCode/Dice_Rolling_Simulator.py
"""
1. Dice Rolling Simulator
The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
Concepts to keep in mind:
Random
Integer
Print
While Loops
"""
import random
class Simulator:
def __init__(self):
"""This is the init funtion where it will only set the score variable"""
self.playerScore = 0
def getInput(self):
"""This funtion will take the input from the user and intimate it if its fine or not"""
self.userchoice = int(input('enter any number between 1 and 6'))
if self.userchoice not in range(1,6):
print("the entereted number is not in range please enter again")
self.getInput()
def gamePlay(self):
"""This is the funtion where it will compare with the userchoice and the system choice"""
self.randomNumber = random.randrange(1,6)
if self.randomNumber == self.userchoice:
self.playerScore += 1
print("congratulation you won your score is: ",self.playerScore)
else:
print("Sorry you lost press 1 to play again")
self.userchoice = int(input())
if self.userchoice == 1:
self.getInput()
self.gamePlay()
else:
print("THANK YOU")
print("your final score is",self.playerScore)
s = Simulator()
s.getInput()
s.gamePlay()
<file_sep>/function and modules.py
number = input("enter a number: ")
number1 = input("enter second number: ")
ans = float(number)
ans2 = float(number1)
import math
print("The floor of the first number is",+math.floor(ans))
print("The floor of the second number is",+math.floor(ans2))
print("The square of the first number is",+math.sqrt(ans))
print("The floor of the second number is",+math.sqrt(ans2))
print("The absolute of the first number is",+abs(ans))
print("The absolute of the second number is",+abs(ans2))
print("The power of the first number is",+pow(ans,ans2))
input("press enter to continue...")
<file_sep>/python programs/CompareNumbers.py
#program to compare two numbers using function
def compare(x,y):
if x>y:
print(x,'number is greater')
elif y>x:
print(y,'number is greater')
else:
print('both the numbers are equal')
number1 = int(input('enter number 1'))
number2 = int(input('enter number 2'))
compare(number1,number2)<file_sep>/gui python/button example.py
import tkinter as tk
root = tk.Tk()
root.title("Buttons example")
button = tk.Button(root,text='Click me',command=root.destroy)
button.pack()
root.mainloop()
<file_sep>/Python_Programs/list_count.py
"""
write a python program to count the number 4 in the given list
"""
my_list = [4,4,1,2,3,4,2,10]
count = 0
for elements in my_list:
if elements == 4:
count = count+1
print(count)
<file_sep>/Python_Programs/PythonCode/TicketBooking.py
"""
An Amusement park company wants one application for
theirbilling counter to enable ticketsale.
Assume the Amusement park authorities approached Max to get this application developed.
This application should haveticket prize asRs400 per person and
if a person buys more than 10 tickets then personiseligiblefor 10 percent discount.
Calculatethe total bill or amount according to the number of tickets that are sold.
"""
from tkinter import *
from tkinter import messagebox
import datetime
root = Tk()
root.title('Ticket Booking')
root.geometry("400x200")
root.resizable(0,0)
label = Label(root,text="How many tickets do you want?").grid(row=0,column=1)
userinput = Entry(root)
userinput.grid(row = 0,column=2,ipady=10)
def calculate():
ticketvalue = userinput.get()
if len(ticketvalue) == 0:
messagebox.showinfo("Warning","Please insert proper ticket value")
elif int(ticketvalue) <= 10:
messagebox.showinfo("Total","Total Bill is: "+str(int(ticketvalue)*400))
elif int(ticketvalue) > 10:
messagebox.showinfo("Total","Total Bill is: "+str(int(int(ticketvalue)*400)-(400*0.1)))
calButton = Button(root,text="calculate",command=calculate).grid(row=1,column=2)
root.mainloop()
# class TicketBooking:
# def TicketBooking(self):
# self.numberoftickets = int(input('How many tickets do you want'))
# if self.numberoftickets > 10:
# print("You have to pay",self.numberoftickets * 400-(400*0.1))
# else:
# print("You have to pay",self.numberoftickets * 400)
#TB = TicketBooking()
#TB.TicketBooking()
<file_sep>/python programs/HCF.py
# HCF calculation using function
# LCM calculation
def HCF(x,y):
if x>y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if(x%i==0)and(y%i==0):
hcf= 1
return hcf
num1 = int(input('enter number 1'))
num2 = int(input('enter number 2'))
print("the HCF of the given numbers are: ",HCF(num1,num2))
<file_sep>/practice2.py
A = [1,4,-1,3,2]
print("The length of the list is",len(A))
for elements in range(len(A)):
print(elements,end = ' ')
print(A[elements])
<file_sep>/flask_coding_new/Login_Reg/index.py
from flask import *
import pymysql
app = Flask('app')
@app.route("/index")
def index():
return render_template('index.html')
@app.route("/login")
def login():
return render_template('login.html')
if __name__ == '__main__':
app.run(host="localhost",port=5000,debug=True)
<file_sep>/python programs/firstprogram.py
print('hello world')
display('press enter to continue')
<file_sep>/data_visualization/histogram.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 20:17:30 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
#Histogram
population_ages = [22,55,66,45,21,22,34,42,4,102,108,30,49,78,10,65,130,131,38,33,12,18,15,75,95,123,101]
#ids = [x for x in range(len(population_ages))]
bins = [0,10,20,30,40,50,60,80,90,100,110,120,130]
plt.xlabel('x')
plt.ylabel('y')
plt.title('interesting graph\ncheck it out')
plt.hist(population_ages,bins,histype='bar',rwidth=0.8)
<file_sep>/data_visualization/pie_charts.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 20:41:10 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
playing = [7,5,8,7,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow=True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
#plt.xlabel('x')
#plt.ylabel('y')
plt.title('Intersting Graph\nCheck it out')
#plt.legend()
plt.show()
<file_sep>/Python_Programs/PythonCode/newWindow.py
from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("200x200")
def run():
messagebox.showinfo("information","This button got clicked")
def open():
top = Toplevel(root)
topbtn = Button(top,text="Click Me",command=run).grid(row=0,column=0)
top.mainloop()
btn = Button(root,text="Click",command=open).grid(column=0,row=0)
root.mainloop()
<file_sep>/Arithmatic operators.py
a = input('enter a: ')
b = input('enter b: ')
sum = int(a) + int(b)
print('addition of the inputed numbers are: ')
print(sum)
sum = int(a) - int(b)
print('substraction of the inputed numbers are: ')
print(sum)
sum = int(a) * int(b)
print('multiplication of the inputed numbers are: ')
print(sum)
sum = float(a)/ float(b)
print('division of the inputed numbers are: ')
print(sum)
<file_sep>/pythoncodes/practicescript.py
#print('hello world')
#string variabe python
#position
a = " Hello All "
print("The charater at postiion 3 is ",a[3])
#substring get the characters from position 2 to 5
print("The characters from 2 to 5 are ",a[2:5])
#strip method
print(a.strip())
#length of the string
print("The length of the string is",len(a))
#lower function of the string
print("The lower case of the string is ",a.lower())
#upper function of the string
print("The upper case of the string is " ,a.upper())
#Replace function of the string
print("Replaceing H with L",a.replace("H","L"))
def frange(x,y,jump):
while x<y:
yield x
x+=jump
print(list(frange(0,10,0.1))[-1])
import numpy
print(type(numpy.arange(0,5,0.1)))
print(numpy.arange(0,4,0.1))
print(numpy.arange(4,6,0.1))
print(numpy.arange(6,8,0.1))
print(numpy.arange(8,10,0.1))
import math
a = 8.5333333
print(math.ceil(a))<file_sep>/python programs/socket programing.py
import pyping
r = pyping.ping('google.com')
if r.ret_code == 0:
print("not reachable")
else:
print("hello")<file_sep>/flask_coding_new/CURD_Flask/crud.py
import sqlite3
from flask import *
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/add")
def add():
return render_template('add.html')
@app.route("/savedetails",methods = ["POST","GET"])
def saveDetails():
if request.method == "POST":
try:
name = request.form["name"]
email = request.form["contact"]
address = request.form["address"]
con = sqlite3.connect("employee.db")
cur = con.cursor()
con.execute("INSERT into employee (name, email, address) values (?,?,?)",(name,email,address))
con.commit()
msg = "employee successfully added"
con.close()
return render_template("success.html",msg=msg)
except:
msg = "failed to add employee"
return render_template('success.html',msg=msg)
@app.route("/views")
def view():
con = sqlite3.connect('employee.db')
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute('select * from employee')
rows = cur.fetchall()
print(rows)
return render_template('views.html',rows=rows)
@app.route("/delete")
def delete():
return render_template("delete.html")
@app.route("/deleterecord",methods = ["POST"])
def deleterecord():
id = request.form["id"]
con = sqlite3.connect('employee.db')
try:
cur = con.cursor()
con.execute("delete from employee where id = ?",id)
con.commit()
msg = "record successfully deleted"
return render_template('delete_record.html',msg=msg)
except:
msg = "cannot delete"
return render_template('delete_record.html',msg=msg)
if __name__ == "__main__":
app.run(debug = True)
<file_sep>/pythongames.py
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 17 22:53:43 2018
@author: Arnab
"""
import pygame
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Snake Game')
pygame.display.update()
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameDisplay.fill(white)
pygame.display.update()
pygame.quit()
quit()
<file_sep>/flask_coding_new/Login_reg_security/index.py
from flask import *
import pymysql
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/register",methods=["POST","GET"])
def register():
msg = ""
if request.method == "POST":
name = request.form["name"]
email = request.form["email"]
city = request.form["city"]
password = request.form["password"]
username = request.form["username"]
reenterpassword = request.form["reenterpassword"]
if (len(name) and len(city) and len(username) and len(email) and len(city) and len(password) and len(reenterpassword)) == 0:
msg = "please fill the details properly"
return render_template('register.html',msg = msg)
elif password.lower() != reenterpassword.lower():
msg = "please check the reconfirm password"
return render_template('register.html',msg = msg)
else:
db = pymysql.connect("localhost","root","library","user")
cursor = db.cursor()
sql = """insert into user(name,email,address) values ('%s','%s','%s')""" %(name,email,city)
cursor.execute(sql)
db.commit()
sql = """insert into login(username,password) values ('%s','%s')""" %(username,password)
cursor.execute(sql)
db.commit()
msg = "Customer details saved successfully"
return render_template("register.html",msg=msg)
else:
return render_template('register.html')
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/python programs/Factorial.py
#To find the factorial of a number
num = int(input("enter the number"))
f = 1
if num <0:
print("sorry the factorial of negative number doesn't exits")
elif num == 0:
print("factorial of 0 is either 0 or 1")
else:
for i in range(1,num + 1):
f = f*i
print(f)<file_sep>/python programs/csv file seperation.py
#python program to seperate CSV file
import os
fileexits = os.path.isfile('J:\python programs\mycsv.csv')
if fileexits == True:
if os.stat('J:\python programs\mycsv.csv').st_size == 0:
print('sorry the file is empty')
else:
fob = open('J:\python programs\mycsv.csv','r')
fileread = fob.read()
print('their are ',len(fileread),'characters present in the file')
speacialcharacters = ''.join(e for e in fileread if not e.isalnum())
# print('the special characters in the file are',speacialcharacters)
speacialcharactersfob = open('j:\python programs\specialcharacters.txt','w')
speacialcharactersfob.write(speacialcharacters)
print('special character file created')
speacialcharactersfob.close()
print('the number of special characters are',len(speacialcharacters))
#this is to remove the special characters from the csv file
removal = ''.join(e for e in fileread if e.isalnum())
#print(removal)
alpabets = ''.join(e for e in removal if not e.isdigit())
alpabetsfob = open('j:\python programs\lphabets.txt','w')
alpabetsfob.write(alpabets)
print('alphabets file is created')
alpabetsfob.close()
lowercase = sum(1 for c in alpabets if c.islower())
print('the number of lower case letters in the file are',lowercase)
uppercase = sum(1 for c in alpabets if c.isupper())
print('the number od upper case letters in the file are',uppercase)
#print('the alphabets present in the file are',alpabets)
print('the number of alphabets present in the file are,',len(alpabets))
digits = ''.join(e for e in removal if not e.isalpha())
digitsfob=open('j:\python programs\digits.txt','w')
digitsfob.write(digits)
print('digits file is created')
digitsfob.close()
print('the number of digits present in the file are',len(digits))
fob.close()
else:
print('sorry file doesnt exits')
<file_sep>/python programs/ifthenelse.py
year =input('enter any year in yyyy format')
n = int(year)
number = n%4
if number > 0:
print('the given year is not a leap year')
else:
print('the given year is a leap year')
<file_sep>/decorator_func.py
"""decorators"""
import time
def time_it(func):
def wrapper(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
print(func.__name__+"took"+str((end-start)*1000) + "mil second")
return result
return wrapper
@time_it
def calc_square(numbers):
result = []
for number in numbers:
result.append(number*number)
return result
@time_it
def cal_cube(numbers):
result = []
for number in numbers:
result.append(number * number * number)
return result
<file_sep>/python programs/matrix multiplication.py
#python program for matrix multiplicaton
mat1 = [[1,2,3],[4,5,6],[7,8,9]]
mat2 = [[10,11,12],[13,14,15],[16,17,18]]
result = [[0,0,0],[0,0,0],[0,0,0]]
for i in range (len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j] +=mat1[i][k] * mat2[k][j]
for r in result:
print(r)<file_sep>/progrms nltk/named entity.py
#named entity recognisation
import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
tokenized = custom_sent_tokenizer.tokenize(sample_text)
def process_content():
try:
for i in tokenized[5:]:
words = nltk.word_tokenize(i)
tagged = nltk.pos_tag(words)
namedEnt = nltk.ne_chunk(tagged)
namedEnt.draw()
except Exception as e:
print(str(e))
process_content()
"""
Named entity type example(NE)
ORGANIZATION Georgia-Pacific Corp., WHO
PERSON <NAME> ,President Obama
LOCATION Murray River,Mount Everest
DATE June,2008-06-29
TIME two fifty a m, 1:30 p.m.
MONEY 175 million Canadian Dollars,GBP 10.40
PERCENT twenty pct,18.75%
FACILITY Washington Monument,Stonehenge
GPE Soutb East Asia,Midlothian
"""
<file_sep>/Data_Recovery/store_recovery_Python.py
import datetime
import pymysql
import pandas as pd
class recovery():
def __init__(self):
self.fromdate = ''
self.todate = ''
self.d1 = ''
self.d2 = ''
self.db = ''
self.diff = 0
self.dumpsCustomerDf = pd.DataFrame()
self.dumpsCustomerDf = self.dumpsCustomerDf.fillna(0)
self.liveCustomerDf = pd.DataFrame()
self.liveCustomerDf = self.liveCustomerDf.fillna(0)
def inputDate(self):
self.fromdate = input('enter the date from YYYY-MM--DD format when the data is missing')
self.todate = input('enter the date till YYYY-MM--DD format when the data is missing')
try:
self.d1 = datetime.datetime.strptime(self.fromdate, "%Y-%m-%d")
self.d2 = datetime.datetime.strptime(self.todate, "%Y-%m-%d")
print("d1,d2 is equal to: ",self.d1,self.d2)
self.diff = abs((self.d2 - self.d1).days)
except ValueError:
print(ValueError("Incorrect data format, should be YYYY-MM-DD"))
print('data was missing from',self.fromdate)
print('data was missing till',self.todate)
print('total number of days the data lost',self.diff)
def connectDb(self):
try:
self.db = pymysql.connect(host="localhost",user="root",passwd="<PASSWORD>",db="soa")
except Exception:
print("Error in MySQL connection")
def HighlevelFile(self):
pass
def countCustomer(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("SELECT count(*) FROM customer WHERE date_first_registered LIKE %s", ("%" + str(self.d1).strip("00:00:00") + "%",))
self.result = self.cur.fetchone()
print("the total number of customer is missing are:",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countRecord(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) From record where customer_arrival_time LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of records missing are:",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countSchemes(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from customer_contact_lens_scheme where scheme_state_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of schemes missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countSalesHeader(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from sales_header where sale_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of sales_header missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countSalesDetail(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from sales_detail where sales_header_id in (select sales_header_id from sales_header where sale_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of sales_header missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countSalesPayment(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from sales_payment where sales_header_id in (select sales_header_id from sales_header where sale_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of sales_payment missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countOdersModified(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from clinical_dispense_order where order_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of clinical_dispense_order updated are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countDispenseItem(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from dispense_item where clinical_dispense_order_id in (select clinical_dispense_order_id from clinical_dispense_order where order_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of dispense item missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countDispenseItemUpdated(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from dispense_item where collected_date like %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of dispense item updated are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countDispenseRx(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(d.*) from dispense_rx d, dispense_item di, clinical_dispense_order c where d.dispense_rx_id=di.dispense_item_id and di.clinical_dispense_order_id=c.clinical_dispense_order_id and c.order_date LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of dispense rx missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def countNhsVoucher(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
self.cur = self.db.cursor()
self.cur.execute("select count(*) from nhsvoucher where nhs_voucher_id in (select nhs_voucher_id from sight_test where tr_number in (select record_id from record where customer_arrival_time LIKE %s",("%" + str(self.d1).strip("00:00:00")+ "%",))
self.result = self.cur.fetchall()
print("The total number of NHS voucher missing are: ",self.result[0])
except Exception:
print(Exception)
else:
print('To date and from date is invalid')
def searchCustomerinDumps(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
#try:
cur = self.db.cursor()
#self.cur.execute("select n.first_name,n.last_name,c.date_of_birth, d.doctor_id from customer c inner join name n on n.name_id = c.name_id left outer join doctor d on d.doctor_id = c.doctor_id where c.date_first_registered LIKE %s", ("%" + str(self.d1).strip("00:00:00") + "%",))
self.cur.execute("SELECT count(*) FROM customer WHERE date_first_registered LIKE %s", ("%" + str(self.d1).strip("00:00:00") + "%",))
self.result = self.cur.fetchall()
self.result = pd.DataFrame()
print(self.result)
#except Exception:
# print(Exception)
else:
print('To date and from date is invalid')
# HIGH LEVEL ANALYSIS #
a = recovery()
a.inputDate()
a.countCustomer()
a.countRecord()
a.countSchemes()
a.countOdersModified()
a.countDispenseItem()
a.countDispenseItemUpdated()
a.countDispenseRx()
a.countNhsVoucher()
a.searchCustomerinDumps()
def searchCustomerinlive(self):
self.connectDb()
if self.d1 != '' and self.d2 != '':
try:
cur = db.cursor()
self.liveCustomerDf = pd.read_sql_query("select n.first_name,n.last_name,c.date_of_birth, d.doctor_id from customer c inner join name n on n.name_id = c.name_id left outer join doctor d on d.doctor_id = c.doctor_id where c.date_first_registered >= %s", ("%" + str(self.d1).strip("00:00:00") + "%",))
#result = cur.fetchall()
#print(result)
except Exception:
print("Error with query: " + query)
else:
print('To date and from date is invalid')
def compareCustomer():
dumpcustomer = open('dumpcus.txt','r')
livecustomer = open('livecus.txt','r')
same = set(dumpcustomer).intersection(livecustomer)
same.discard('\n')
file_out = ('output_file.txt','w')
for line in same:
file_out.write(line)
def checkSchemes():
connectDb()
if fromdate != '' and todate != '':
try:
cur = db.cursor()
query = """select * from customer_contact_lens_scheme where customer_id in (select customer_id from customer where date_first_registered >= '%s' and date_first_registered <= '%s') order by customer_id;""" %d1,d2
cur.execute(query)
result = cur.fetchall()
print(result)
except Exception:
print("Error with query: " + query)
else:
print('To date and from date is invalid')
<file_sep>/scientificcalculator/ScientificCalculator.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
print('**********WELCOME TO PYTHON CALCULATOR**********')
print('---ENTER YOUR OPRION---')
option = int(input('---1.NORMAL CALCULATOR---\n---2.SCIENTIFIC CALCULATOR---\n'))
if option == 1:
print('....THIS IS SIMPLE CALCULATOR....')
operator = input('a.ADDITION\ns.SUBSTRACTION\nm.MULTIPLY\nd.DIVISION\nx.EXIT\n')
if operator == 'a':
num = int(input('How many number do you want to addn\n'))
print('enter the numbers\n')
addlist = []
while len(addlist) < num:
numbers = int(input())
addlist.append(numbers)
print('Addition of all the numbers is',sum(addlist))
elif operator == 's':
print('Sorry its under development you can enter only two numbers for substraction\n')
number1 = int(input('enter number 1\n'))
number2 = int(input('enter number 2\n'))
print('Substraction is',number1 - number2)
elif operator == 'm':
num = int(input('How many number do you want to multiply\n'))
print('enter the numbers\n')
mullist = []
while len(mullist) < num:
numbers = int(input())
mullist.append(numbers)
result = np.prod(np.array(mullist))
print('multiplication of all the numbers is',result)
elif operator == 'd':
print('enter two numbers for division\n')
number1 = int(input('enter first number'))
number2 = int(input('enter second number'))
try:
result = number1/number2
except:
print('Second number is 0 so it cannot divide')
elif operator == 'x':
print('THANK YOU')
elif option == 2:
print('....THIS IS SCIENTIFIC CALCULATOR....')
part = int(input('Enter 1 for binary calculator\n Enter 2 for normal scientific calculation'))
if part == 1:
dec = int(input('enter a decimal number to convert'))
choice = input('enter b for binary\n o for octal \n h for hexadecimal\n')
if choice == 'b':
print("binary of the entered number is: ",bin(dec))
elif choice == 'o':
print("octal of the entered number is: ",oct(dec))
elif choice == 'h':
print("hexadecimal of the entered number is: ",hex(dec))
else:
print('Not proper input for binary conversion')
elif part == 2:
print('thanks for choosing that option, but sorry to say that its currently under development')
else:
print('please select the option properly')
else:
print('select proper option')
<file_sep>/python programs/playing around with string.py
# python program to play around with string
mystring = "hello wonderfull people,@#$, '112341,,,;"
print(len(mystring))
removal = ''.join(e for e in mystring if e.isalnum())
print('the string after the removal of the puncutation marks\n',removal,'\nthe length of the string now is',len(removal))
alphabetts = ''.join(e for e in removal if not e.isdigit())
print('the alphabets present in the string are:\n',alphabetts,'\n number of albhabets are:',len(alphabetts))
numbers = ''.join(e for e in removal if not e.isalpha())
print('the digits present in the string are\n',numbers,'\n the number of digits are',len(numbers))
specialcharacter = ''.join(e for e in mystring if not e.isalnum())
print(specialcharacter)<file_sep>/flask_coding_new/first_flask_application.py
from flask import Flask
app = Flask(__name__) #creating the flask object
@app.route('/')
def home():
return "hello this is first flask website"
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/python programs/EvenOdd.py
number = int(input("enter any number"))
if number%2==0:
print("the given number is even")
else:
print("the given number is odd")<file_sep>/python programs/posnegnumber.py
number = int(input("enter any number it can be postive negative or 0"))
if number == 0:
print("the number is nither negative nor postive its 0")
elif number>0:
print("the numer is postive")
elif number<0:
print("the number is negative")
else:
print("invalid input")
<file_sep>/TensorBoard/single_layer_perceptron.py
import numpy as np
import matplotlib.pyplot as plt
#nneural network for solving xor problem
#the xor logic gate is
# 1 1 ---> 0
# 1 0 ---> 1
# 0 1 ---> 1
# 0 0 ---> 0
#Activation funtion
def sigmoid(x):
return 1/(1 + np.exp(-x))
#sigmoid derivative for backpropogation
def sigmoid_deriv(x):
return sigmoid(x)*(1-sigmoid(x))
#the forward funtion
def forward(x,w1,w2,predict=False):
a1 = np.matmul(x,w1)
z1 = sigmoid(a1)
#create and add bais
bias = np.ones((len(z1),1))
z1 = np.concatenate((bias,z1),axis=1)
a2 = np.matmul(z1,w2)
z2 = sigmoid(a2)
if predict:
return z2
return a1,z1,a2,z2
def backprop(a2,z0,z1,z2,y):
delta2 = z2 - y
Delta2 = np.matmul(z1.T,delta2)
delta1 = (delta2.dot(w2[1:,:].T))*sigmoid_deriv(a1)
Delta1 = np.matmul(z0.T,delta1)
return delta2,Delta1,Delta2
#first column = bais
X = np.array([[1,1,0],
[1,0,1],
[1,0,0],
[1,1,1]])
#Output
y = np.array([[1],[1],[0],[0]])
#initialize weights
w1 = np.random.randn(3,5)
w2 = np.random.randn(6,1)
#initialize learning rate
lr = 0.89
costs = []
#initiate epochs
epochs = 15000
m = len(X)
#start training
for i in range(epochs):
#forward
a1,z1,a2,z2 = forward(X,w1,w2)
#backprop
delta2,Delta1,Delta2 = backprop(a2,X,z1,z2,y)
w1 -= lr*(1/m)*Delta1
w2 -= lr*(1/m)*Delta2
# add costs to list for plotting
c = np.mean(np.abs(delta2))
costs.append(c)
if i % 1000 == 0:
print(f"iteration: {i}. Error: {c}")
#training complete
print("Training complete")
#Make prediction
z3 = forward(X,w1,w2,True)
print("Precentages: ")
print(z3)
print("Predictions: ")
print(np.round(z3))
plt.plot(costs)
plt.show()
<file_sep>/gui python/messagebox.py
from tkinter import *
root = Tk()
message = "Whatever you do will be insignificant, but it is very important that you do it.\n(<NAME>)"
msg = Message(root,text=message)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.pack(fill=X)
root.mainloop()
<file_sep>/simple_projects/practicelist.py
"""
THIS IS THE PROGRAMS TO PRACTICE ON THE LIST DATA TYPE
"""
import random
class listOperation:
def __init__(self):
self.lower_range = random.randint(1,50)
self.higher_range = random.randint(51,100)
self.practice_list = list(range(self.lower_range,self.higher_range))
"""
1. SUM OF ALL THE ELEMENTS IN THE LIST
"""
def SumOfAllElements(self):
print(f'sum of all elements in the lists are {sum(self.practice_list)}')
"""
2. multiples OF ALL THE ELEMENTS IN THE LIST
"""
def multiplesofallElements(self):
pass
l = listOperation()
l.SumOfAllElements()
<file_sep>/python programs/sequences.py
friends=['Roshni','Ishwari','Tarun','Nikhil','Pranay']
print("First element is",friends[0])
friends[1]
friends[2]
friends[3]
friends[4]
friends[-1]
friends[-2]
friends[-3]
friends[-4]
friends[-5]
<file_sep>/thirdprogram.py
print('hello \nworld')
input('press enter to continue')
<file_sep>/python programs/MilkAndCokkies.py
t = int(input("enter the number of test cases"))
while t!=0:
n = int(input("enter the number of min limak spend"))
while(n!=0):
food = input("limak had")
if food == "cookies" and food == "milk":
boolean = True
elif food == "cookies" and food == "cookies":
boolean = False
elif food == "milk" and food == "milk":
boolean = True
elif food == "milk" and food == "cookies":
boolean = False
else:
boolean = False
n=n-1
t=t-1
print(boolean)
<file_sep>/swapping of numbers.py
a = input('enter a: ')
b = input('enter b: ')
c = a;
print('value of a',a)
print('value of b',b)
print('now c contains: ',c)
a = b;
print('now a contains: ',a)
b = c;
print('now b contains: ',b)
print('numers swapped')
print(a)
print(b)
<file_sep>/Python_Programs/linear_regression_single_variable/BatsmanDetailed_report.py
from tkinter import *
from tkinter import messagebox
import pickle
import pandas as pd
import numpy as np
root = Tk()
root.geometry('500x100')
root.title("Detailed Report")
root.resizable(0,0)
selectlabel = Label(root,text='Select a player name',font='segoe 13 bold').grid(row=0,column=0)
variable = StringVar(root)
variable.set("select")
playeroption = OptionMenu(root,variable,"<NAME>","<NAME>","<NAME>","<NAME>")
playeroption.grid(row=0,column=1)
labelvariable = StringVar(root)
def Check():
if variable.get() == "select":
messagebox.showinfo("Error","Please select a value")
elif variable.get() == "<NAME>":
vdata = pd.read_csv('viratODI.csv',sep="\t")
matches = vdata['Matches'].count()
runs = vdata['Runs'].max()
with open('Virat_Model','rb') as f:
vp = pickle.load(f)
vrecord = vp.predict(18246)
vrecord = int(vrecord) - int(matches)
messagebox.showinfo("Virat_Facts",'Virat played: \t'+str(matches)+" ODI matches""\n"+'and scored:\t'+str(runs)+" runs till now""\n"+"Virat requires: "+str(int(vrecord))+" more matches to break the record of sachin tendulkar's maximum ODI runs")
elif variable.get() == "<NAME>":
rdata = pd.read_csv('rohit.csv',sep="\t")
matches = rdata['Matches'].count()
runs = rdata['Runs'].max()
with open('rohit_model','rb') as f:
rp = pickle.load(f)
rrecord = rp.predict(18246)
rrecord = int(rrecord) - int(matches)
messagebox.showinfo("Rohit_Facts",'Rohit played: \t'+str(matches)+" ODI matches""\n"+'and scored:\t'+str(runs)+" runs till now""\n"+"Rohit requires: "+str(int(rrecord))+" more matches to break the record of sachin tendulkar's maximum ODI runs")
elif variable.get() == "<NAME>":
kdata = pd.read_csv('Kane.csv',sep="\t")
matches = kdata['Matches'].count()
runs = kdata['Aggr'].max()
with open('kane_model','rb') as f:
kp = pickle.load(f)
krecord = kp.predict(18246)
krecord = int(krecord) - int(matches)
messagebox.showinfo("Kane_Facts",'Kane played: \t'+str(matches)+" ODI matches""\n"+'and scored:\t'+str(runs)+" runs till now""\n"+"Kane requires: "+str(int(krecord))+" more matches to break the record of sachin tendulkar's maximum ODI runs")
elif variable.get() == "<NAME>":
sdata = pd.read_csv('steve.csv',sep="\t")
matches = sdata['Matches'].count()
runs = sdata['Runs'].max()
with open('steve_model','rb') as f:
sp = pickle.load(f)
srecord = sp.predict(18246)
srecord = int(srecord) - int(matches)
messagebox.showinfo("Steve_Facts",'Steve played: \t'+str(matches)+" ODI matches""\n"+'and scored:\t'+str(runs)+" runs till now""\n"+"Steve requires: "+str(int(srecord))+" more matches to break the record of sachin tendulkar's maximum ODI runs")
button = Button(root,text="submit",command=Check).grid(row=2,column=1)
root.mainloop()
<file_sep>/Django/WordCount-Project/WordCount/urls.py
"""WordCount URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('',views.login),
path('home/',views.home,name='home'),
path('count/',views.count,name='count'),
path('resultcount/',views.result,name='countresult'),
path('about/',views.about,name='about'),
path('textblob/',views.textblob,name='textblob'),
path('textblobresult/',views.textblobresult,name='textblobresult'),
path('vader/',views.vader,name='vader'),
path('vaderresult/',views.vaderresult,name='vaderresult'),
path('token/',views.token,name='token'),
path('tokenresult/',views.tokenresult,name='tokenresult'),
path('login/',views.login,name='logout'),
]
<file_sep>/pythoncodes/RockPaperScissors.py
"""Python program for Rock Paper Scissors"""
import datetime
import random
Playername = input('Enter your name\n')
"""this statement is comparing the current time with 12 o clock that is the mid day """
if datetime.datetime.now().time() <= datetime.datetime.now().time().replace(hour = 12,minute = 0,second = 0,microsecond = 0):
print('Hello\n',"Good Morning",Playername)
else:
print('Hello\n',"Good Evening",Playername)
choicelist = ['Rock','Paper','Scissors']
#print(random.choice(gamelist))
print('1 player game','or','2 Player game','Enter your choice\n')
Playerselection = int(input())
if Playerselection == 1:
Playerchoice = input('Enter your choice\n')
if Playerchoice == 'Rock' and random.choice(choicelist) == 'Rock':
print('Its a tie')
elif Playerchoice == 'Rock' and random.choice(choicelist) == 'Paper':
print(Playername,'Lose paper covers rock')
elif Playerchoice == 'Rock' and random.choice(choicelist) == 'Scissors':
print(Playername,'Won Congratulations Rock smashes Scissors')
elif Playerchoice == 'Paper' and random.choice(choicelist) == 'Rock':
print(Playername,'Won Congratulation paper covers rock')
elif Playerchoice == 'Paper' and random.choice(choicelist) == 'Paper':
print('Its a tie both of the player selected papers')
elif Playerchoice == 'Paper' and random.choice(choicelist) == 'Scissors':
print(Playername,'Lose Scissors cuts the paper')
elif Playerchoice == 'Scissors' and random.choice(choicelist) == 'Rock':
print(Playername,'Lose Rock smashes Scissors')
elif Playerchoice == 'Scissors' and random.choice(choicelist) == 'Paper':
print(Playername,'Won scissors cut paper')
elif Playerchoice == 'Scissors' and random.choice(choicelist) == 'Scissors':
print('Its a tie both the players selected Scissors')
else:
print('Please select a proper option')
elif Playerselection == 2:
Player2name = input('enter second player name')
Player1Choice = input('Player 1 Enter your choice\n')
Player2Choice = input('Player 2 Enter your choice\n')
if Player1Choice == 'Rock' and Player2Choice == 'Rock':
print('its a tie Both the players selected rock')
elif Player1Choice == 'Paper' and Player2Choice == 'Rock':
print(Playername,'Won congratulation paper covers Rock')
elif Player1Choice == 'Scissors' and Player2Choice =='Rock':
print(Player2name,'Won congratulation Rock Smashes Scissors')
elif Player1Choice == 'Rock' and Player2Choice == 'Paper':
print(Player2name,'Won congratulation Paper covers rock')
elif Player1Choice == 'Paper' and Player2Choice == 'Paper':
print('Its a tie both the players selected papers')
elif Player1Choice == 'Scissors' and Player2Choice =='Paper':
print(Playername,'Won congratulation Scissors cut paper ')
elif Player1Choice == 'Rock' and Player2Choice == 'Scissors':
print(Playername,'Won congratulation Rock smashes scissors')
elif Player1Choice == 'Paper' and Player2Choice == 'Scissors':
print(Player2name,'won congratulation Scissors cut paper')
elif Player1Choice == 'Scissors' and Player2Choice =='Scissors':
print('its a tie both players selected Scissors')
else:
print('please select a proper option to play')
else:
print('Please select a proper option to play')
<file_sep>/python programs/python alphabetic order.py
# python program for alphabetic order
my_string = input("enter any string")
words = my_string.split()
words.sort()
for i in words:
print(i)<file_sep>/comaprision.py
message = input('enter first number')
message1= input('enter second number')
number1 = int(message)
number2 = int(message1)
test1 = number1 == number2
print('if both the numbers are equal')
print(test1)
test2 = number1>number2;
print('if number1 is greater than number2')
print(test2)
test3 = number1<number2;
print('if number1 is less than number2')
print(test3)
test4 = number1>=number2;
print('if number1 is greater than equal to number2')
print(test4)
test5 = number1<=number2;
print('if number1 is less than equal to number2')
print(test5)
test6 = number1!=number2;
print('if number1 is not equal to number2')
print(test6)
input('press enter to continue....')
<file_sep>/pythongames/wordcountanalysis.py
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from collections import defaultdict
stop_words = set(stopwords.words('english'))
#print(type(stop_words))
input_sentence = "this is a .......!@#sentense sentense written written by me at a spider editor"
word_tokens = word_tokenize(input_sentence)
print(word_tokens)
#filtered_sentences = [w for w in word_tokens if not w in stop_words]
#filtered_sentences = []
#for w in word_tokens:
# if w not in stop_words:
# filtered_sentences.append(w)
##print(word_tokens)
##print(filtered_sentences)
##print(filtered_sentences)
#appearences = defaultdict(int)
#for x in filtered_sentences:
# appearences[x]+= 1
# print(x,appearences[x])
<file_sep>/python programs/editing sequence.py
family = ['maa','baba','me']
print("the list is",family)
print("maa in family",'maa' in family)
print("Roshni in family",'roshni' in family)
print(family*10)
friends = ['roshni','pranay','tarun','nikhil','ishwari']
print(family+friends)
number = [10,20,30,410]
print(number +['arnab'])
#display('press enter to continue')
<file_sep>/stringspython.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 23:43:19 2018
@author: arnabbasak
"""
message = "meet me tonight."
print(message)
message2 = 'meet me string'
print(message2)
print(message[0:4])
print(message[0:])
print(message[:15])
#srting is immutable<file_sep>/flask_coding_new/DatabasePractice/student.py
import sqlite3
con = sqlite3.connect("student.db")
print("successfully connected")
con.execute("""create table if not exists student(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
password TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
address TEXT NOT NULL)""")
print('student table created')
con.close()
<file_sep>/python datime module/datetime(time).py
import datetime
# datetime.time module
t = datetime.time(22,40,45)
print(t)
timenow = datetime.date.today()
print(timenow)
dt = datetime.datetime.today()
print(dt)
tdelta = datetime.timedelta(days = 7)
print('7 days from today exactly will be',dt + tdelta)
tdelta2 = datetime.timedelta(hours = 12)
print('12 hours from now will be',dt + tdelta2)
<file_sep>/python programs/armstrong number.py
# program for amstrong number
number = int(input("enter any number"))
sum = 0
temp = number
while temp>0:
digit = temp%10
sum+=digit**3
temp //= 10
if number == sum:
print('the given number is armstrong')
else:
print('the given number is not armstrong')
<file_sep>/Python_Programs/PythonCode/Hangman.py
"""
The Goal: Despite the name, the actual “hangman” part isn’t necessary. The main goal here is to create a sort of “guess the word” game. The user needs to be able to input letter guesses. A limit should also be set on how many guesses they can use. This means you’ll need a way to grab a word to use for guessing. (This can be grabbed from a pre-made list. No need to get too fancy.) You will also need functions to check if the user has actually inputted a single letter, to check if the inputted letter is in the hidden word (and if it is, how many times it appears), to print letters, and a counter variable to limit guesses.
Concepts to keep in mind:
Random
Variables
Boolean
Input and Output
Integer
Char
String
Length
Print
"""
#importing random to fetch the place and animal names randomdly
#importing textblob to do spell check for the user input
import random
from textblob import TextBlob
class Hangman:
def __init__(self):
#declaring the animal features
self.animal_dict = {
'sounds like meow':'cat',
'domestic animal':'dog',
'king of jundle':'lion',
'dangerous animal maneater':'tiger',
'stupid animal':'donkey',
'hardworking animal':'horse'
}
#declaring the place features
self.place_dict = {
'zero mile of india':'nagpur',
'IT hub of india':'bangalore',
'sweet part of india':'kolkata',
'financial capital of india':'mumbai',
'heart of india':'delhi',
'dosa capital':'chennai',
'portugues paradise':'goa',
'queen of hills':'shimla'
}
#saving the dictionary list for comparision
self.animal_list = list(self.animal_dict.values())
self.place_list = list(self.place_dict.values())
#declaring the score variable
self.userscore = 0
self.animalguess = False
self.placeguess = False
def userinput(self):
#obtaining a random value from animal dictionary
self.animal_key = random.choice(list(self.animal_dict.keys()))
print("guess the animal who is considered ",self.animal_key)
print()
#asking the user to guess the animal name
self.animal_name = input('enter your guess')
self.animal_name = self.animal_name.lower()
self.cleananimalname = TextBlob(self.animal_name).correct()
print()
#obtaining a random value from the place dictionary
self.place_key = random.choice(list(self.place_dict.keys()))
#asking the user to guess the place name
print("guess the city which is considered ",self.place_key)
print()
self.place_name = input('enter your guess')
#converting the user input to lower case
self.place_name = self.place_name.lower()
#spell checking it and correcting the input
self.cleanplacename = TextBlob(self.place_name).correct()
def gamePlay(self):
if self.cleananimalname in self.animal_list:
print('congratulation you have guessed the animal name right')
self.animalguess = True
if self.cleanplacename in self.place_list:
print('congratulation you have guessed the place name right')
self.placeguess = True
if self.animalguess == True and self.placeguess == False:
print('sorry you lost since you guessed the place name wrong')
elif self.animalguess == False and self.placeguess == True:
print('sorry you lost since you guessed the animal name wrong')
elif self.animalguess == False and self.placeguess == False:
print('sorry you lost since you guessed both the names wrong')
else:
print('congratulation you won the game')
h = Hangman()
h.userinput()
h.gamePlay()
<file_sep>/progrms nltk/stemming.py
#stemming is removing the ending part of a word such as "removing has ing attach to it so stemming will remove the ing part of it "
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
ps = PorterStemmer()
#example_words = ["program","programing","programmer","programmed"]
#for w in example_words:
# print(ps.stem(w))
new_text = "programming is a very good subject which is dear to a programmer and today most of the things are programmed"
words = word_tokenize(new_text)
for w in words:
print(ps.stem(w))
<file_sep>/NLTK gender guesser/Gender_Guesser.py
import nltk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import os
MainWindow = Tk()
MainWindow.title('Gender Guessing')
MainWindow.state("zoomed")
def AddFile():
file_path = filedialog.askopenfilename()
if os.stat(file_path).st_size > 0:
messagebox.showinfo("File Selected","Continue")
else:
messagebox.showerror("File Error","File you selected is empty")
button1 = Button(text ="Add file",command = AddFile)
button1.pack()
MainWindow.mainloop()<file_sep>/python programs/4program.py
message = ('good morning')
print(message)
input("press enter to continue...")
<file_sep>/movie project/js/Mainui.py
from tkinter import *
master = Tk()
w = Label(master,text="Enter The movie information")
Label(master,text="Movie Name").grid(row=0)
w.pack()
master.mainloop()
<file_sep>/Dash_Codes/cricketAnalytics.py
"""
In this file we will perfom some EDA on the cricket records using dash application
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
sachin_data = pd.read_csv('sachin.csv')
virat_data = pd.read_csv('virat.csv')
rohit_data = pd.read_csv('rohit.csv')
app = dash.Dash()
app.layout = html.Div(children=[
html.H1("ODI Runs analysis"),
dcc.Graph(id="Sachin_Record",
figure={
'data':[
{'x':sachin_data.Year,'y':sachin_data.Runs,'type':'bar','name':'runs'},
],
'layout':{
'title':"Sachin's ODI Runs"
}
}),
dcc.Graph(id="Virat_Record",
figure={
'data':[
{'x':virat_data.Year,'y':virat_data.Runs,'type':'bar','name':'runs'},
],
'layout':{
'title':"Virat's ODI Runs"
}
}),
dcc.Graph(id="Rohit_Record",
figure={
'data':[
{'x':rohit_data.Year,'y':rohit_data.Runs,'type':'bar','name':'runs'},
],
'layout':{
'title':"Rohit's ODI Runs"
}
}),
dcc.Graph(id="compare",
figure={
'data':[
{'x':rohit_data.Year,'y':rohit_data.Runs,'type':'line','name':'<NAME>'},
{'x':virat_data.Year,'y':virat_data.Runs,'type':'line','name':'<NAME>'},
],
'layout':{
'title':"Virat Kohli Rohit sharma's comparision"
}
}),
])
if __name__ == "__main__":
app.run_server(debug=True)
<file_sep>/store-recovery.py
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 22:34:29 2018
@author: Arnab
"""
import pymysql
import csv
#connecting to the database
connworld = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "store")
#selecting data and writing the data in the csv files for the customers
curcity_world = connworld.cursor()
curcity_world.execute("select * from releasedates")
resultcity_world = curcity_world.fetchall()
myfilecity_world = csv.writer(open('E:/pythonprograms/release_dates.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curcity_world.description]
myfilecity_world.writerow(col_names)
myfilecity_world.writerows(resultcity_world)
print("release_dates.csv file has been written")
#this is to check the counts
userinput = input ('enter the date to check')
curcity_world.execute("SELECT count(*) FROM releasedates WHERE rolloutdate LIKE %s",(userinput))
answer = curcity_world.fetchall()
finaloutput = "total number of store upgraded" + str(answer)
reportfile = open('outputfile.txt','w')
reportfile.write(finaloutput)
reportfile.close()
#analysis_file = open('analysis_file','a')
#analysis_file.write(answer)
<file_sep>/python programs/area of triangle.py
base = input('enter the base of the triangle: ')
height = input('enter the height of the triangle: ')
intermediate = float(base) * float(height)
area = intermediate/2
print('area of the triangle is:',area)
<file_sep>/numpyoperations.py
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
arr = np.arange(1,11)
arr
# In[3]:
arr + arr
# In[12]:
arr - arr
# In[5]:
arr * arr
# In[6]:
arr / arr
# In[7]:
arr + 100
# In[8]:
arr * 100
# In[9]:
arr - 100
# In[13]:
arr / arr
# In[14]:
1 / arr
# In[15]:
arr ** 2
# In[16]:
"""universal array function"""
np.sqrt(arr)
# In[17]:
np.exp(arr)
# In[18]:
np.max(arr)
# In[19]:
np.min(arr)
# In[20]:
np.sin(arr)
# In[ ]:
<file_sep>/flask_coding_old/httpMethods.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 21:18:14 2018
@author: Arnab
"""
from flask import Flask,request
app = Flask(__name__)
@app.route("/")
def index():
return "method used: %s" %request.method
@app.route("/mypage",methods=['GET','POST'])
def mypage():
if request.method == 'POST':
return "you are using post method"
else:
return "you are using get method"
if __name__ == "__main__":
app.run()<file_sep>/python programs/date identification.py
import datetime
import os
filecheck = os.path.isfile('E:\python programs\dates.txt')
if filecheck == False:
print('sorry file')
elif os.stat('E:\python programs\dates.txt').st_size == 0:
print('Sorry the file is empty')
else:
filelines = []
fileopen = open('E:\python programs\dates.txt','r')
for line in fileopen:
line = line.strip()
filelines.append(line)
print(filelines)
print(type(filelines))
print(len(filelines))
#filecontents = fileopen.read()
#print(filecontents)
<file_sep>/Python_Programs/equlidean_distance.py
import numpy as np
import math
x1 = np.array([1,2,3,4,5,6,7,8,9])
x2 = np.array([10,12,14,16,17,19,21,23,24])
y1 = np.array([-5,-4,-3,-2,-1,0,1,2,3])
y2 = np.array([-11,-10,-9,-8,-7,-6,-5,-4,-3])
x = (x1-x2)**2
y = (y1-y2)**2
print(np.sqrt(x+y))
<file_sep>/python projects/Rock paper scissor.py
import random
print("Some Basic rules to be followed while playing the game they are: \n1.Type the word as it is mentioned in the choice of list\n2.Don't give space in the prompt")
choice = ["Rock","Paper","Scissor"]
print(computerchoice)
userchoice = input("enter your choice from \n1.Rock,\n2.Scissor\n3.Paper\n")
print("user has selected: ",userchoice)
print("computer has selected: ",computerchoice)
if computerchoice == userchoice:
print("match drawn")
print("Since computer has selected: ",computerchoice)
elif computerchoice > userchoice:
print("Computer won")
print("Since computer selected: ",computerchoice)
elif computerchoice < userchoice:
print("Congratulation you won")
print("Since computer selected: ",computerchoice)
else:
print("sorry no result")
<file_sep>/flask_coding_old/BasicRouting.py
from flask import Flask
app = Flask(__name__)
#@ signifies a decorator - way to wrap a function and modifying its behaviour
@app.route('/')
def index():
return 'welcome to my home page of python'
@app.route('/arnab')
def arnab():
return'<h2> Arnab home page</h2>'
@app.route('/profile/<username>')
def profile(username):
return "<h2>hello %s </h2>" % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return "<h2>Post iD is %s </h2>" % post_id
if __name__== '__main__':
app.run()
<file_sep>/python programs/removal of puncuation marks.py
# python programs to remove puncutatuon marks
punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_string = input("enter any string with punctuation")
no_punct =""
for i in my_string:
if i not in punctuation:
no_punct = no_punct+i
print(no_punct)<file_sep>/python datime module/creating date.py
import datetime
# datetime .date module
d = datetime.date(2017,7,24)# creating the date
print('the date created is',d)
tday = datetime.date.today()# looking for todays date
print('todays date is',tday)
print('todays day is',tday.day) # for only the day
print('Current year is',tday.year) # for only the year
# for week day
print('Week of the day',tday.weekday()) # for weekday() Monday = 0 and Sunday = 6
print ('Week of the day',tday.isoweekday()) # for isoweekday() Monday = 1 and Sunday = 7
#creating time delta that is the set of time
tdelta = datetime.timedelta(days=7)
print('The date from today is',tday + tdelta) # to look what will be the date 7 days from today
print('the date which was 7 days back from today',tday - tdelta) # to look what was the date 7 days prior today
#date2 = date1 + timedelta
#timedelta = date1 + date2
#calculate the daya remaining in my birthday
bday = datetime.date(2017,9,26)
till_bday = bday - tday
print('days remaining in my birthday from today is',till_bday)
print('days remaining in my birthday from today is',till_bday.days) # To see only the days remaining
print('days remaining in my birthday from today is',till_bday.total_seconds) # to see total seconds remaing
<file_sep>/gui python/label color.py
from tkinter import *
root = Tk()
Label(root,text = "This text in Times new roman",fg = "red",font = "Times").pack()
Label(root,text = "This text is in Helvetica Font",fg = "green",font = "Helvitica 16 bold italic").pack()
Label(root,text = "This text is in Algerian Font",fg = "blue",font = "Algerian 22").pack()
root.mainloop()
<file_sep>/Python_Programs/PythonCode/Practice.py
import datetime
import math
import sys
import calendar
class Excerise:
#Excerise 1
def Display(self):
"""This funtion will create a poem twinkle twinkle little star"""
print('Twinkle, twinkle, little star,\n\tHow I wonder what you are!\n\t\tUp above the world so high,\n\t\tLike a diamond in the sky.\nTwinkle, twinkle, little star,\n\tHow I wonder what you are')
#Excerise 2
def version_check(self):
"""This funtion will return the python version running in the system"""
print("The current Python version is: \n",sys.version_info)
#Excerise 3
def current_datetime(self):
"""This funtion will return the current date and time"""
print("The current date and time is: ",datetime.datetime.now())
#Excerise 4
def area_of_circle(self):
"""This funtion will calculate the area of circle and radius of the circle"""
self.choice = int(input('enter 1 if you know the radius else press 2'))
if self.choice == 1:
self.radius = int(input('enter the radius of the circle'))
print('area of the circle is: ',3.14*self.radius*self.radius)
elif self.choice == 2:
self.area = int(input('enter the area of the circle'))
print('The radius of the circle is:',math.sqrt(self.area/3.14))
else:
print("invalid choice")
#Excerise 5
def reverse_name(self):
"""This funtion will reverse the inputed first name and last name"""
self.first_name = input('enter your first name')
self.last_name = input('enter your last name')
print(self.first_name[::-1],'',self.last_name[::-1])
#Excerise 6
def usercreated_list_tupple(self):
"""This funtion will take input from user in the form of list and convert it into tupple"""
self.values = input('enter number in a comman seperated manner')
print("Entered values in a list: ",self.values.split(","))
print("Entered values in a tupple: ",tuple(self.values.split(",")))
#Excerise 7
def color_list(self):
"""This funtion will give the first color present in the list and the last color present in the list"""
self.color_list = ["Red","Green","White","Black"]
print("First color in the list: ",self.color_list[0],"","Last color in the list: ",self.color_list[-1])
#Excerise 8
def compute_value_of_n(self):
"""This funtion will calculate n+nn+nnn where n is a string variable and will return an output in integer"""
self.n = input("enter the value of n")
#print("The value of n: ",self.n," ","The value of nn",self.n*self.n," ","The value of nnn",self.n*self.n*self.n)
#print("The value of n+nn+nnn",(self.n)+(self.n*self.n)+(self.n*self.n*self.n))
self.n1 = self.n+self.n
self.n2 = self.n+self.n+self.n
self.answer = int(self.n) + int(self.n1) + int(self.n2)
print("The output is: ",self.answer)
def farm_problem(self):
"""This funtion will calculate the number of animal legs of present in
each farm in this we will consider chickens have 2 legs cows have 4 legs and pigs have 4 legs"""
self.number_chicken = int(input('enter the number of chickens you have'))
self.number_cows = int(input('enter the number of cows you have'))
self.number_pigs = int(input('enter the number of pigs you have'))
print('Total number of legs in your farm is: ',(self.number_chicken*2)+(self.number_cows*4)+(self.number_pigs*4))
ex = Excerise()
#ex.Display()
#print()
#ex.version_check()
#print()
#ex.current_datetime()
#print()
#ex.area_of_circle()
#print()
#ex.reverse_name()
#print()
#ex.usercreated_list_tupple()
#print()
#ex.color_list()
#ex.compute_value_of_n()
#print(ex.compute_value_of_n.__doc__)
ex.farm_problem()
<file_sep>/python programs/strings.py
print("'hello nagpur'")
#escape sequence
print("i am a\"good\"boy")
a = input('your first name')
b = input('your second name')
print(a+b)
print(a,b)
<file_sep>/pythongames/nltkdownloaded.py
""" import nltk
nltk.download() """
import string
mystring = "this is ....... a string !!! creaated by me..{"
removedstring = mystring.translate(string.punctuation)
print(removedstring)<file_sep>/Python_Programs/linear_regression_single_variable/ODI_RunsPrediction.py
from tkinter import *
from tkinter import messagebox
import pickle
root = Tk()
root.title('Runs Prediction')
root.geometry('500x100')
root.resizable(0,0)
selectlabel = Label(root,text='Select a player name',font='segoe 13 bold').grid(row=0,column=0)
variable = StringVar(root)
variable.set("select")
playeroption = OptionMenu(root,variable,"<NAME>","<NAME>","<NAME>","<NAME>")
playeroption.grid(row=0,column=1)
def predict():
if variable.get() == "select":
messagebox.showinfo("Error",'Please select a player name')
elif variable.get() == "<NAME>":
with open('Virat_Model','rb') as f:
vp = pickle.load(f)
match = vp.predict(18246)
messagebox.showinfo("Answer","Virat will break sachin's ODI runs record of 18246 runs in his "+str(int(match))+" ODI match")
elif variable.get() == "<NAME>":
with open('rohit_model','rb') as f:
rmodel = pickle.load(f)
rmatch = rmodel.predict(18246)
messagebox.showinfo("Answer","Rohit will break sachin's ODI record of 18246 runs in his "+str(int(rmatch))+" ODI match")
elif variable.get() == "<NAME>":
with open('kane_model','rb') as f:
kanep = pickle.load(f)
kmatch = kanep.predict(18246)
messagebox.showinfo("Answer","<NAME> will break sachin's ODI runs record of 18246 runs in his "+str(int(kmatch))+" ODI match")
elif variable.get() == "<NAME>":
with open('steve_model','rb') as f:
smodel = pickle.load(f)
smatch = smodel.predict(18246)
messagebox.showinfo("Answer","<NAME> will break sachin's ODI runs record of 18246 runs in his "+str(int(smatch))+" ODI match")
predictButton = Button(root,text="Predict",command=predict,font = "Segoe 13 bold").grid(row=1,column=1)
root.mainloop()
<file_sep>/flask_coding_new/app_routing.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "hello this is my site"
@app.route('/home/<name>')
def name(name):
return "hello"+name
@app.route('/home/<int:age>')
def age(age):
return "Age = %d"%age;
if __name__ == '__main__':
app.run(host='localhost',port=5000,debug=True)
<file_sep>/python programs/list functions.py
numbers = [10,20,30,40,50,60]
print("the list is",numbers)
print("the length is the list is",len(numbers))
print("the maximum value of the list is",max(numbers))
print("the minimum value of the list is",min(numbers))
print("conversion of the list",list('arnab'))
numbers[3] = 27
print("the changed list is",numbers)
##n = input('enter the index number to delete: ')
##change = int(n)
del numbers[3]
print("the deleted list is",numbers)
<file_sep>/python programs/addition of two matrices.py
#python program for additon of two matrices
<file_sep>/more methods on list.py
# more methods on list
say = ['hey','brown','cow','how','are','you']
print(say)
print('the position of brown is',say.index('brown'))
say.pop(1)
print('after poping the 1st element',say)
say.insert(2,'goodlooking')
print('after inserting one element at postion 2',say)
say.remove('cow')
print('after removing and not returning an element',say)
say.reverse()
print('the reverse of the list is',say)
<file_sep>/6program.py
message = input('enter any number')
number = int(message)
print(number+1)
input('enter any key to continue....')
<file_sep>/python programs/secondprogram.py
print('good bye')
print('love you')
<file_sep>/data_visualization/firstprogram.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 13:35:06 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,6]
plt.plot(x,y)
plt.show()
<file_sep>/python programs/Sum of natural numbers.py
# python program to find sum of natural numbers
number = int(input('enter any number'))
if number<0:
print('enter a positive number')
else:
sum = 0
while(number>0):
sum = sum+number
number = number-1
print(sum)
<file_sep>/Python_Programs/data_recovery.py
"""
In this file we will try to automate the high level analysis of the store data recovery
using python
"""
import pandas as pd #importing this library for reading and storeing in data frame
import numpy as np #for calculation on the data
from tkinter import * #For UI creation
from tkinter import messagebox #to generate messages in the UI
import pymysql #to import data from mysql database
from sqlalchemy import create_engine #for ORM to import the data
import datetime #for filtering the data on basis of date and time
from datetime import datetime as dt # to remove the timestamps from the date
class dataRecovery:
def connection(self):
"""This funtion will create a connection and fetch the data from all the necessary tables in mysql"""
try:
self.engine = create_engine('mysql+pymysql://root:library@localhost:3306/soa')
self.customer_data = pd.read_sql_query('SELECT * FROM customer', self.engine)
self.record_data = pd.read_sql_query('SELECT * FROM record', self.engine)
self.scheme_data = pd.read_sql_query('SELECT * FROM customer_contact_lens_scheme', self.engine)
self.salesHeader_data = pd.read_sql_query('SELECT * FROM sales_header', self.engine)
self.ClinicalDispense_data = pd.read_sql_query('SELECT * FROM clinical_dispense_order', self.engine)
self.DispenseItem_data = pd.read_sql_query('SELECT * FROM dispense_item', self.engine)
self.NHSVoucer_data = pd.read_sql_query('SELECT * FROM nhsvoucher', self.engine)
except:
messagebox.showerror("error","something wrong with the connection")
def userInterface(self):
"""This funtion will create the necessary UI needed for the application """
mainwindow = Tk()
mainwindow.geometry('300x200')
mainwindow.title('Store Data recovery')
mainwindow.resizable(0,0)
self.userlabel = Label(mainwindow,text='username').grid(row=0,column=0)
self.usertext = Entry(mainwindow)
self.usertext.grid(row=0,column=1)
self.passlabel = Label(mainwindow,text="Password").grid(row=1,column=0)
self.passtext = Entry(mainwindow,show="*")
self.passtext.grid(row=1,column=1)
def login():
"""This funtion will login into the application and a new window will open"""
self.username = self.usertext.get()
self.password = self.passtext.get()
if self.username == 'admin' and self.password == '<PASSWORD>':
mainwindow.wm_iconify()
commandwindow = Toplevel(mainwindow)
commandwindow.title('Data Recovery')
commandwindow.geometry("700x500")
commandwindow.resizable(0,0)
date1label = Label(commandwindow,text="Enter the from Date").grid(row=0,column=0)
date1Entry = Entry(commandwindow)
date1Entry.grid(row=0,column=1)
date2label = Label(commandwindow,text="Enter the to Date").grid(row=0,column=2)
date2Entry = Entry(commandwindow)
date2Entry.grid(row=0,column=3)
days_text = StringVar(mainwindow)
display_days = Label(commandwindow,textvariable=days_text).grid(row=1,columnspan=3)
customer_text = StringVar(mainwindow)
display_customer = Label(commandwindow,textvariable=customer_text).grid(row=2,columnspan=3)
record_text = StringVar(mainwindow)
display_record = Label(commandwindow,textvariable=record_text).grid(row=3,columnspan=3)
scheme_text = StringVar(mainwindow)
display_scheme = Label(commandwindow,textvariable=scheme_text).grid(row=4,columnspan=3)
salesheader_text = StringVar(mainwindow)
salesheader_display = Label(commandwindow,textvariable=salesheader_text).grid(row=5,columnspan=3)
clinicaldispense_text = StringVar(mainwindow)
clinicaldispense_display = Label(commandwindow,textvariable=clinicaldispense_text).grid(row=6,columnspan=3)
dispense_item_text = StringVar(mainwindow)
dispense_item_display = Label(commandwindow,textvariable=dispense_item_text).grid(row=7,columnspan=3)
nhsvoucher_text = StringVar(commandwindow)
nhsvoucher_display = Label(commandwindow,textvariable=nhsvoucher_text).grid(row=8,columnspan=3)
sales_detail_text = StringVar(mainwindow)
sales_detail_display = Label(commandwindow,textvariable=sales_detail_text).grid(row=9,columnspan=3)
def HighLevelAnalysis():
date1 = date1Entry.get()
date2 = date2Entry.get()
try:
d1 = datetime.datetime.strptime(date1,"%Y-%m-%d") #This will check if the inputed date is in correct format
d2 = datetime.datetime.strptime(date2,"%Y-%m-%d")
days_dataloss = abs((d2-d1).days) #this is calculating the number of data loss happened
days_text.set("Total day(s) of data loss is: "+str(days_dataloss))
self.connection() #This is calling the above funtion if all the dates are inputed correctly
#customer data count
self.customer_data['date_first_registered'] = self.customer_data['date_first_registered'].dt.normalize()
customer_count = int(self.customer_data[['date_first_registered']][(self.customer_data['date_first_registered'] >= d1) & (self.customer_data['date_first_registered'] <= d2)].count())
customer_text.set("Total number of customer missing are: "+str(customer_count))
#obtaining customer missing customer list
customer_list = self.customer_data[['customer_id']][(self.customer_data['date_first_registered'] >= d1) & (self.customer_data['date_first_registered'] <= d2)].values.tolist()
new_customer_list = []
def flattenlist(customer_list):
"""This funtion will flatten the list from list for list to list"""
for i in customer_list:
if type(i) == list:
flattenlist(i)
else:
new_customer_list.append(i)
flattenlist(customer_list)
#counting the records missing
self.record_data['record_id'] = self.record_data['customer_id'].apply(lambda x: 'True' if x in new_customer_list else 'False') #this is fetching the missing records
record_list = self.record_data.record_id.value_counts().tolist() # output is a series so converting into a list
if len(record_list) == 2:
record_text.set('Total number of Records missing are: '+str(record_list[1])) #printing the second element of the list since the second element denotes the true values
else:
record_text.set('Total number of Records missing are: '+'0')
#counting schemes missing
self.scheme_data['customer_contact_lens_scheme_id'] = self.scheme_data['customer_id'].apply(lambda x: 'True' if x in new_customer_list else 'False')
scheme_list = self.scheme_data.customer_contact_lens_scheme_id.value_counts().tolist()
if len(scheme_list) == 2:
scheme_text.set('Total number of scheme missing are: '+str(scheme_list[1]))
else:
scheme_text.set('Total number of scheme missing are: '+'0')
#counting the sales header missing
self.salesHeader_data['sales_header_id'] = self.salesHeader_data['customer_id'].apply(lambda x: 'True' if x in new_customer_list else 'False')
sales_headerlist = self.salesHeader_data.sales_header_id.value_counts().tolist()
if len(sales_headerlist) == 2:
salesheader_text.set("Total number of sales header missing are: "+str(sales_headerlist[1]))
else:
salesheader_text.set("Total number of sales header missing are: "+'0')
#counting the clinical dispense order missing
self.ClinicalDispense_data['clinical_dispense_order_id'] = self.ClinicalDispense_data['customer_id'].apply(lambda x: 'True' if x in new_customer_list else 'False')
ClinicalDispense_list = self.ClinicalDispense_data.clinical_dispense_order_id.value_counts().tolist()
if len(ClinicalDispense_list) == 2:
clinicaldispense_text.set("Total number of clinical dispense order missing are: "+str(ClinicalDispense_list[1]))
else:
clinicaldispense_text.set("Total number of clinical dispense order missing are: "+'0')
#Dispense item count
dispense_item_count = int(self.DispenseItem_data[['collection_date']][(self.DispenseItem_data['collection_date'] >= d1) & (self.DispenseItem_data['collection_date'] <= d2)].count())
dispense_item_text.set("Total number of dispense item missing are: "+str(dispense_item_count))
#NHS Voucher count
self.NHSVoucer_data['test_date'] = pd.to_datetime(self.NHSVoucer_data['test_date'])
nhs_coucher_count = int(self.NHSVoucer_data[['test_date']][(self.NHSVoucer_data['test_date'] >= d1) & (self.NHSVoucer_data['test_date'] <= d2)].count())
nhsvoucher_text.set("Total number of NHS voucher missing are: "+str(nhs_coucher_count))
#sales_detail
d1 = datetime.datetime.date(d1)
d2 = datetime.datetime.date(d2)
sales_detail_query = "select count(*) from sales_detail where sales_header_id in (select sales_header_id from sales_header where customer_id in (select customer_id from customer where date_first_registered >= '{d1}' and date_first_registered <= '{d2}'))".format(d1=d1,d2=d2)
salesDetail_data = pd.read_sql_query(sales_detail_query,self.engine)
sales_detail_text.set("Total number of sales detail record missing are: "+str(int(salesDetail_data.values)))
except ValueError:
messagebox.showinfo("Error","Incorrect date format should be YYYY-MM-DD")
processButton = Button(commandwindow,text="Start Analysis",command=HighLevelAnalysis).grid(row=0,column=4)
else:
messagebox.showinfo("error","Invalid credentials")
loginButton = Button(mainwindow,text='Login',command=login).grid(row=2,column=0)
mainwindow.mainloop()
d = dataRecovery()
d.userInterface()
"""
Mapping
customer --> dates
record --> customer_id
customer_contact_lens_scheme --> customer_id
sales_header --> customer_id
sales_detail --> sales_header_id
sales_payment --> sales_header_id
clinical_dispense_order --> customer_id
dispense_item --> dates
nhsvoucher --> date
"""
<file_sep>/progrms nltk/NLTK practice.py
import os
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
filecheck = os.path.isfile('E:\python programs\progrms nltk\corpus.txt')
if filecheck == False:
print('file does not exits sorry we cannot proceed')
else:
ps = PorterStemmer() # object creation for the class for stemming the words
CorpusFileOpen = open('E:\python programs\progrms nltk\corpus.txt','r')
reading = CorpusFileOpen.read()
print('Total number of characters present in the file is',len(reading))
SentenceToken = sent_tokenize(reading)
#for w in sent_tokenize(reading):
#print(w)
WordTokenize = word_tokenize(reading)
stop_words = set(stopwords.words("english"))
StopwordFilteredSentence = []
#for i in word_tokenize(reading): # these two lines will tokenize the words and print one after the other
#print(i)
# print(ps.stem(i))
for word in WordTokenize:
if word not in stop_words:
StopwordFilteredSentence.append(word)
print(StopwordFilteredSentence)
<file_sep>/python programs/string n stuff 17t.py
variable = "hey %s how are you, how is the %s"
print('the orignal statement is',variable)
var = input('enter any persons name')
thing = input('enter any thing name')
var1 = (var,thing)
print('the modified statement is',variable % var1)
exmple = input('enter a statement')
print(exmple)
tofind = input('enter any word from your statement')
print(exmple.find(tofind))
<file_sep>/Dash_Codes/swingBowleranalysis.py
"""
In this file we will do analysis of swing bolwer <NAME> and <NAME>
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
wasim_data = pd.read_csv('wasim.csv')
james_data = pd.read_csv('anderson.csv')
glen_data = pd.read_csv('glen.csv')
waqar_data = pd.read_csv('waqar.csv')
app = dash.Dash()
app.layout = html.Div(children=[
html.H1("Swing bowler Analysis"),
dcc.Graph(id="Overs Bowled by individuals",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Overs,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Overs,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Overs,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Overs,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Overs bowled venus wise"
}
}),
dcc.Graph(id="Madiens Bowled by individuals",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Madiens,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Madiens,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Madiens,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Madiens,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Madiens bowled venus wise"
}
}),
dcc.Graph(id="Runs given by individuals",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Runs_Given,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Runs_Given,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Runs_Given,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Runs_Given,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Runs Given venus wise"
}
}),
dcc.Graph(id="Wickets Taken by individuals",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Wickets_Taken,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Wickets_Taken,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Wickets_Taken,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Wickets_Taken,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Wickets Taken venus wise"
}
}),
dcc.Graph(id="5 Wicket hauls individuals",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.four_wickets,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.four_wickets,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.four_wickets,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.four_wickets,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"5 Wicket hauls individuals"
}
}),
dcc.Graph(id="Average",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Avg,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Avg,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Avg,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Avg,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Average"
}
}),
dcc.Graph(id="Strike_Rate",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Strike_Rate,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Strike_Rate,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Strike_Rate,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Strike_Rate,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Strike Rate"
}
}),
dcc.Graph(id="Econ Rate",
figure={
'data':[
{'x':wasim_data.Venue,'y':wasim_data.Econ_Rate,'type':'bar','name':'<NAME>'},
{'x':james_data.Venue,'y':james_data.Econ_Rate,'type':'bar','name':'<NAME>'},
{'x':glen_data.Venue,'y':glen_data.Econ_Rate,'type':'bar','name':'<NAME>'},
{'x':waqar_data.Venue,'y':waqar_data.Econ_Rate,'type':'bar','name':'<NAME>'},
],
'layout':{
'title':"Economy Rate"
}
}),
])
if __name__ == "__main__":
app.run_server(debug=True)
<file_sep>/python programs/RegularExpress on corpus.py
import re
import os
CorpusCheck = os.path.isfile('E:\python programs\progrms nltk\corpus.txt')
if CorpusCheck == False:
print('file does not exist sorry we cannot proceed')
else:
FileOpen = open('E:\python programs\progrms nltk\corpus.txt','r')
FileRead = FileOpen.read()
numbers = re.findall(r'\d{1,9}',FileRead)
names = re.findall(r'[A-Z][a-z]*',FileRead)
print(numbers)
print(names)
print('total number of names found in the corpus is',len(names))
<file_sep>/flask_coding_new/login/index.py
from flask import *
import pymysql
app = Flask(__name__)
@app.route("/",methods=["POST","GET"])
def index():
msg = ""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
if (len(username) and len(password) == 0):
msg = "please fill the details properly"
return render_template('/',msg = msg)
else:
db = pymysql.connect("localhost","root","library","user")
cursor = db.cursor()
sql = """select username,password from login where username like ('%s') and password like ('%s')""" %(username,password)
output = cursor.execute(sql)
print(output)
if output == 2:
return render_template('home.html')
else:
msg = "invalid credentials"
return render_template('index.html',msg = msg)
return render_template('index.html')
@app.route("/register",methods=["POST","GET"])
def register():
msg = ""
if request.method == "POST":
name = request.form["name"]
email = request.form["email"]
city = request.form["city"]
password = request.form["password"]
username = request.form["username"]
reenterpassword = request.form["reenterpassword"]
if (len(name) or len(city) or len(username) or len(email) or len(city) or len(password) or len(reenterpassword)) == 0:
msg = "please fill the details properly"
return render_template('register.html',msg = msg)
elif password.lower() != reenterpassword.lower():
msg = "please check the reconfirm password"
return render_template('register.html',msg = msg)
else:
db = pymysql.connect("localhost","root","library","user")
cursor = db.cursor()
sql = """select username from login where username like ('%s')""" %(username)
username_check = cursor.execute(sql)
if username_check == 0:
sql = """insert into login(username,password) values ('%s','%s')""" %(username,password)
cursor.execute(sql)
db.commit()
msg = "Customer details saved successfully"
return render_template("register.html",msg=msg)
else:
msg = "username already exists"
return render_template("register.html",msg=msg)
sql = """insert into user(name,email,address) values ('%s','%s','%s')""" %(name,email,city)
cursor.execute(sql)
db.commit()
else:
return render_template('register.html')
@app.route("/home",methods=["GET","POST"])
def home():
msg = ""
if request.method == "POST":
first_num = request.form["first_num"]
second_num = request.form["second_num"]
option = request.form["operation"]
if len(first_num) and len(second_num) == 0:
msg = "please fill all the feilds properly"
return render_template("home.html",msg = msg)
else:
if option == "addition":
msg = "Addition is " + str(int(first_num) + int(second_num))
return render_template("home.html",msg = msg)
elif option == "substraction":
msg = "substraction is " + str(int(first_num) - int(second_num))
return render_template("home.html",msg = msg)
elif option == "division":
if second_num == 0:
msg = "sorry cannot divide "
return render_template("home.html",msg = msg)
else:
msg = "DIvision is " + str(int(first_num) / int(second_num))
return render_template("home.html",msg = msg)
elif option == "multiplication":
msg = msg = "multiplication is " + str(int(first_num) * int(second_num))
return render_template("home.html",msg = msg)
else:
msg = "Please select the option properly"
return render_template("home.html",msg = msg)
@app.route("/simpleinterest",methods=["GET","POST"])
def simpleinterest():
if method == request.method == "POST":
amount = request.form["principle"]
roi = request.form["roi"]
period = request.form["period"]
#if len(amount)
if __name__ == '__main__':
app.run(debug=True)
#PosSetUp@321
<file_sep>/python programs/images.py
from tkinter import *
root = Tk()
logo = PhotoImage(file="E:\python programs\gui python\logo-200.png")
w1 = Label(root,image=logo).pack(side="right")
explanation = """At present,only GIF and PPM/PGM
formats are supported,but an interface
exits to allow additional image file
formats to be added easily"""
w2 = Label(root,justify=LEFT,padx = 10,text=explanation).pack(side="left")
root.mainloop()
<file_sep>/lambdafunctions.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 23:12:47 2018
@author: arnabbasak
"""
# A simple function to calculate the value 3x+1
#anonymous function == lambda expression
#lambda just like function its perfectly acceptable to have a function without any name
#cannot use lambda expression for multiline values
def f(x):
return 3*x+1
print(f(2))
g = lambda x: 3*x+1
print(g(2))
#lambda expression with more than one input
#combine first and last name into a single name
full_name = lambda fn,ln:fn.strip().title() + " " + ln.strip().title()
print(full_name(" Arnab","BASAK"))
scifi_authors = ["<NAME>", "<NAME>", "<NAME>"," Arthur .c. Clark","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"]
#sort this list in alphabetic order through anonimous function
#sorting the list on the last name
scifi_authors.sort(key=lambda name:name.split(" ")[-1].lower())
print(scifi_authors)
def build_quadratic_equations(a,b,c):
return lambda x: a*x**2 + b*x + c
#f = build_quadratic_equations(2,3,-5)
#print(f(2))
print(build_quadratic_equations(3,0,1)(2)) # evaluate 3x^2+1
#common application for lambda expression is sorting and flitering data
<file_sep>/generating random numbers.py
import random
r = random.rad(100.0,101.5)
print(r)
<file_sep>/database using python/select data and writing in csv.py
import pymysql
import csv
#database connection for world database
connworld = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "world")
#selecting data from table city
curcity_world = connworld.cursor()
curcity_world.execute("select * from city")
resultcity_world = curcity_world.fetchall()
myfilecity_world = csv.writer(open('E:/python programs/database using python/world_city.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curcity_world.description]
myfilecity_world.writerow(col_names)
myfilecity_world.writerows(resultcity_world)
print("world_city.csv file has been written")
#selecting data from table country
curcountry_world = connworld.cursor()
curcountry_world.execute("select * from country")
resultcountry_world = curcountry_world.fetchall()
myfilecountry_world = csv.writer(open('E:/python programs/database using python/world_country.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curcountry_world.description]
myfilecountry_world.writerow(col_names)
myfilecountry_world.writerows(resultcountry_world)
print("world_country.csv file has been written")
#selecting data from table countrylanguage
curCL_world = connworld.cursor()
curCL_world.execute("select * from countrylanguage")
resultCL_world = curCL_world.fetchall()
myfileCL_world = csv.writer(open('E:/python programs/database using python/world_countrylanguage.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curCL_world.description]
myfileCL_world.writerow(col_names)
myfileCL_world.writerows(resultCL_world)
print("world_countrylanguage.csv file has been written")
connworld.close()
#dattabase connection for world2 databasse
connworld2 = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "world2")
#selecting data from table city
curcity_world2 = connworld2.cursor()
curcity_world2.execute("select * from city")
resultcity_world2 = curcity_world2.fetchall()
myfilecity_world2 = csv.writer(open('E:/python programs/database using python/world2_city.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curCL_world.description]
myfilecity_world2.writerow(col_names)
myfilecity_world2.writerows(resultcity_world2)
print("world2_city.csv file has been written")
#selecting data from table country
curcountry_world2 = connworld2.cursor()
curcountry_world2.execute("select * from country")
resultcountry_world2 = curcountry_world2.fetchall()
myfilecountry_world2 = csv.writer(open('E:/python programs/database using python/world2_country.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curcountry_world2.description]
myfilecountry_world2.writerow(col_names)
myfilecountry_world2.writerows(resultcountry_world2)
print("world2_country.csv file has been written")
#selecting data from table countrylanguage
curCL_world2 = connworld2.cursor()
curCL_world2.execute("select * from countrylanguage")
resultCL_world2 = curCL_world.fetchall()
myfileCL_world2 = csv.writer(open('E:/python programs/database using python/world2_countrylanguage.csv','w',encoding = 'utf-8'))
col_names = [i[0] for i in curCL_world2.description]
myfileCL_world2.writerow(col_names)
myfileCL_world2.writerows(resultCL_world2)
print("world2_countrylanguage.csv file has been written")
connworld2.close()
<file_sep>/multipliacation.py
#to print multiplication
num = int(input("enter any number"))
for i in range(1,11):
print(num*i)<file_sep>/database using python/select data.py
import pymysql
conn = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "world")
cur = conn.cursor()
cur.execute("select * from city")
#print(cur.description)
print()
for row in cur:
print(row)
cur.close()
conn.close()
<file_sep>/Dash_Codes/spin_bowler_analysis.py
"""
In this file we will analyse the spin bowling greats in the 90s
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
anil_data = pd.read_csv('anil.csv')
shane_data = pd.read_csv('shane.csv')
murli_data = pd.read_csv('murli.csv')
overall_data = pd.read_csv('overall.csv')
#print(anil_data.columns)
#print(anil_data.Runs_Conscided)
app = dash.Dash()
app.layout = html.Div(children=[
html.H1("Spin bowler Analysis"),
dcc.Graph(id="Overs Bowled by individuals",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Overs,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Overs,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Overs,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Overs bowled over the years"
}
}),
dcc.Graph(id="Maidens Bowled by individuals",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Maiden,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Maiden,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Maiden,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Maidens bowled over the years"
}
}),
dcc.Graph(id="Runs Consided Bowled by individuals",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Runs_Conscided,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Runs_Conscided,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Runs_Conscided,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Runs Consided over the years"
}
}),
dcc.Graph(id="Wickets Taken by individuals",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Wickets_Taken,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Wickets_Taken,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Wickets_Taken,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Wickets Taken over the years"
}
}),
dcc.Graph(id="Five wicket hauls",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.five_Wickets,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.five_Wickets,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.five_Wickets,'type':'bar','name':'Murli'},
],
'layout':{
'title':"5 for Taken over the years"
}
}),
dcc.Graph(id="ten wicket hauls",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.ten_Wickets,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.ten_Wickets,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.ten_Wickets,'type':'bar','name':'Murli'},
],
'layout':{
'title':"10 for Taken over the years"
}
}),
dcc.Graph(id="Average",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Avg,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Avg,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Avg,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Bowling average over the years"
}
}),
dcc.Graph(id="Strike_Rate",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Strike_Rate,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Strike_Rate,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Strike_Rate,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Strike Rate over the years"
}
}),
dcc.Graph(id="Econ_Rate",
figure={
'data':[
{'x':anil_data.Year,'y':anil_data.Econ_Rate,'type':'bar','name':'<NAME>'},
{'x':shane_data.Year,'y':shane_data.Econ_Rate,'type':'bar','name':'<NAME>'},
{'x':murli_data.Year,'y':murli_data.Econ_Rate,'type':'bar','name':'Murli'},
],
'layout':{
'title':"Economy Rate over the years"
}
}),
])
if __name__ == "__main__":
app.run_server(debug=True)
<file_sep>/python programs/Armstrong number is an interval.py
#program for calculating armstrong number in an interval
lowerrange = int(input('enter the lower range'))
higherrange = int(input('enter the higher range'))
for num in range(lowerrange,higherrange+1):
sum = 0
temp = num
while temp>0:
digit = temp %10
sum +=digit **3
temp //= 10
if num == sum:
print(num)<file_sep>/data_visualization/stack_plot.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 20:29:19 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
playing = [7,5,8,7,13]
plt.plot([],[],color='m',label='sleeping',linewidth=5)
plt.plot([],[],color='c',label='eating',linewidth=5)
plt.plot([],[],color='r',label='working',linewidth=5)
plt.plot([],[],color='b',label='playing',linewidth=5)
plt.stackplot(days,sleeping,eating,working,playing,colors=['m','c','r','b'])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Intersting Graph\nCheck it out')
plt.legend()
plt.show()<file_sep>/5program.py
message = input('enter your name')
print(message)
<file_sep>/crudexample/employee/views.py
from django.shortcuts import render,redirect
from employee.forms import EmployeeForm
from employee.models import Employee
def emp(request):
if request.method == 'POST':
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return
<file_sep>/python code.py
from tkinter import *
import pymysql
from tkinter import messagebox
top = Tk()
top.title('DataBase Interface')
L1 = Label(text="<NAME>")
L1.place(x=10,y=10)
L1.pack()
E1 = Entry(bd = 5)
E1.pack()
L2 = Label(text = "<NAME>")
L2.place(x=10,y=500)
L2.pack()
E2 = Entry(bd = 5)
E2.pack()
def getcontent():
E1content = E1.get()
E2content = E2.get()
if len(E1content) == 0 or len(E2content) == 0:
messagebox.showinfo("User Input","please fill the data properly")
else:
db_conn = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "student")
cursor_s = db_conn.cursor()
cursor_s.execute("insert into studentname(firstname,lastname) values(%s,%s)",(E1content,E2content))
db_conn.commit()
messagebox.showinfo("User Input","data inserted sucessfully")
#print(E1content)
#print(E2content)
B = Button(text = "Submit",command = getcontent)
B.pack()
top.state("zoomed")
top.mainloop()<file_sep>/Python_Programs/PythonCode/age_calulator.py
from tkinter import messagebox
from tkinter import *
import datetime
root = Tk()
root.title("Age Calculator")
label = Label(root,text="Age Calculator").grid(row=0,column=1)
namelabel = Label(root,text="Enter your name").grid(row=1,column=0)
nameentry = Entry(root)
nameentry.grid(row=1,column=1)
agelabel = Label(root,text="Enter your full Birth year").grid(row=2,column=0)
ageentry = Entry(root)
ageentry.grid(row=2,column=1)
def calculateage():
name = nameentry.get()
if len(ageentry.get()) < 4:
messagebox.showinfo("Error","Please enter year in 4 digits")
try:
age = int(ageentry.get())
except ValueError:
messagebox.showinfo("Error","Please enter an numbers")
if len(name) == 0 and len(age) == 0:
messagebox.showinfo("Error","Please enter the values properly")
elif len(str(age)) < 4:
messagebox.showinfo("Error","Please enter the year in 4 digit")
else:
birthcentenary = age + 100
if datetime.datetime.now().hour < 12:
messagebox.showinfo("Good morning",name+"You will complete birth birthcentenary in the year "+str(birthcentenary))
elif datetime.datetime.now().hour ==12:
messagebox.showinfo("Good Afternoon",name+"You will complete birth birthcentenary in the year "+str(birthcentenary))
elif datetime.datetime.now().hour > 12:
messagebox.showinfo("Good Evening",name+"You will complete birth birthcentenary in the year "+str(birthcentenary))
calculate = Button(root,text="Calculate",command=calculateage).grid(row=3,column=1)
root.mainloop()
<file_sep>/python programs/file reading and writing.py
# python program to read the content of a file
import os
filecheck = os.path.isfile('E:\python programs\myfile.txt')
if filecheck == False:
print('file does not exits')
print('file created')
fob = open('E:\python programs\myfile.txt','w+')
fob.write('hwllo world')
fob.close()
else:
fob = open('E:\python programs\myfile.txt', 'r')
print(fob.read()) # comment out any one of the print statement to see the proper output
print(fob.readline())
print(fob.readlines())
fob.close()
# appending of file
fob = open('E:\python programs\myfile.txt', 'a')
entertext = input('enter the text you want to enter in the file\n')
fob.write(entertext)
fob.close()
# creatiion of file
filecheck = os.path.isfile('E:\python programs\irst.txt')
if filecheck == True:
print('file already exist')
else:
fob = open('E:\python programs\irst.txt', 'w+')
filetext = input('enter any thing in the file\n')
fob.write(filetext)
fob.close()
<file_sep>/database using python/employee database.py
import pymysql
import csv
import os
#employees database connection
conn_employees = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "employees") # database connection for employees
#for table employees in employees database
cur_employees = conn_employees.cursor() # cursor for employees table in employees database
cur_employees.execute("select * from employees")
result_employees = cur_employees.fetchall()
employees_employees = csv.writer(open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/employees_employees.csv','w',encoding = 'utf-8'))
columnnames = [desc[0] for desc in cur_employees.description]
employees_employees.writerow(columnnames)
employees_employees.writerows(result_employees)
#print('employees tables data has been written in employees_employees.csv file')
conn_employees.close()
#emp database connection
conn_emp = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "emp")
#for table employees in emp database
cur_employees = conn_emp.cursor() # cursor for employees table in emp database
cur_employees.execute("select * from employees")
result_employees = cur_employees.fetchall()
emp_employees = csv.writer(open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/emp_employees.csv','w',encoding = 'utf-8'))
columnnames = [desc[0] for desc in cur_employees.description]
emp_employees.writerow(columnnames)
emp_employees.writerows(result_employees)
#print('employees tables data has been written in emp_employees.csv file')
conn_emp.close()
#employee database connection
conn_employee = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "employee")
#for table employees in employee database
cur_employees = conn_employee.cursor() # cursor for employees table in employee database
cur_employees.execute("select * from employees")
result_employees = cur_employees.fetchall()
employee_employees = csv.writer(open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/employee_employees.csv','w',encoding = 'utf-8'))
columnnames = [desc[0] for desc in cur_employees.description]
employee_employees.writerow(columnnames)
employee_employees.writerows(result_employees)
#print('employees tables data has been written in empployee_employees.csv file')
conn_employee.close()
def CsvDifference():
"This a CSV difference function"
file1 = open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/employees_employees.csv', 'r')
file2 = open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/emp_employees.csv', 'r')
file3 = open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/employee_employees.csv','r')
fileone = file1.readlines()
filetwo = file2.readlines()
filethree = file3.readlines()
with open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/updated_EmployeesDiff.csv', 'w') as outFile:
for line in fileone:
if line not in filetwo or line not in filethree:
#print(line)
outFile.write(line)
#print('difference file has been created')
else:
print('There is no difference in the csv file')
break
CsvDifference()
def CsvLenCompare():
"This is a CSV export"
employee_employeesFile = open("C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/employee_employees.csv")
emp_employeesFile = open("C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/emp_employees.csv")
employees_employeesFile = open("C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/employees_employees.csv")
employee_employeesFilelen = len(employee_employeesFile.readlines())
emp_employeesFilelen = len(emp_employeesFile.readlines())
employees_employeesFilelen = len(employees_employeesFile.readlines())
#comparing for the employees database
if employees_employeesFilelen >= employee_employeesFilelen and employees_employeesFilelen >= emp_employeesFilelen:
print("There is data in the employees table in the employees database if something is missing it cannot be restored from other database")
else:
print("data missing in the employees table in the employees database restoring it using updated_EmployeesDiff csv file")
#comparing for the emp database
if emp_employeesFilelen >= employee_employeesFilelen and emp_employeeFilelen >= employees_employeesFilelen:
print("data in the employees table of emp database is present if something is missing it connot be restored from other databases")
else:
print("data missing in the employees table in the emp database restoring it using updated_EmployeesDiff csv file")
conn_emp = pymysql.connect(host = "localhost",user = "root",password = "<PASSWORD>",db = "emp") # database connection for employees
cursor = conn_emp.cursor()
csv_data = csv.reader(open('C:/Users/arnab.jaydeb.basak/Documents/programs/pythonprograms/updated_EmployeesDiff.csv','r'))
for row in csv_data:
cursor.execute('INSERT INTO employees(emp_no,birth_date,first_name,last_name,gender,hire_date)''VALUES(%s","%s","%s","%s","%s","%s")')
conn_emp.commit()
conn_emp.close()
print('data has been restored please check from backend')
#comparing for the employee database
if employee_employeesFilelen >= emp_employeesFilelen and employee_employeesFilelen >= employees_employeesFilelen:
print("data in the employees table of employee database is present if something is missing it canoot be restored from other databases")
else:
print("data is missing in the employees table of the employee database restoring it using updated_EmployeesDiff csv file")
CsvLenCompare()
<file_sep>/practice3.py
def solution(S):
Bcount = 0
Acount = 0
Ncount = 0
Ocount = 0
Lcount = 0
for elements in S:
if "B" in elements:
Bcount += 1
if "A" in elements:
Acount += 1
if "N" in elements:
Ncount += 1
if "L" in elements:
Lcount += 1
if "O" in elements:
Ocount += 1
if Bcount == Ncount == Acount and Lcount % 2 == 0 and Ocount % 2 == 0:
print("BALLOON is possible",Bcount,"times")
else:
print("BALLOON not possible from the inputted string")
solution("BALLOONBALLOONBALLOONBALLOON")
<file_sep>/flask_coding_new/login/templates/addition.html
<html>
<head>
<title>
Login
</title>
<body align="center">
Login
<form action="/calculation" method="POST">
Enter 1st number: <input type="text",name="name"><br><br>
Enter 2nd number: <input type="text",name="email"><br><br>
Select Option:<select name="operation">
<option value="addition">Addition</option>
<option value="substraction">Substraction</option>
<option value="multiplication">Multiply</option>
<option value="division">Division</option>
</select><br>
<input type="submit" value="submit"/><br><br>
</form>
</body>
</head>
</html>
<file_sep>/OopsPython/StudentClass.py
class Addition:
def getdata(self):
self.num1 = int(input('enter number 1 '))
self.num2 = int(input('enter number 2'))
def calulcate(self):
self.num3 = self.num1+self.num2
def display(self):
print('addition is',self.num3)
class Substration:
def getdata(self):
self.num1 = int(input('enter number 1 '))
self.num2 = int(input('enter number 2'))
def calulcate(self):
self.num3 = self.num1 - self.num2
def display(self):
print('substraction is',self.num3)
class multiplication:
def getdata(self):
self.num1 = int(input('enter number 1 '))
self.num2 = int(input('enter number 2'))
def calulcate(self):
self.num3 = self.num1 * self.num2
def display(self):
print('multiplication is',self.num3)
class division:
def getdata(self):
self.num1 = float(input('enter number 1 '))
self.num2 = float(input('enter number 2'))
def calulcate(self):
self.num3 = self.num1/self.num2
def display(self):
print('division is',self.num3)
<file_sep>/OopsPython/PythonMain.py
from StudentClass import *
print('enter 1 for addition\n enter 2 for substraction\n enter 3 for multiplication \n enter 4 for division ')
userchoice = int(input('enter your choice'))
if userchoice == 1:
a = Addition()
a.getdata()
a.calulcate()
a.display()
elif userchoice == 2:
s = Substration()
s.getdata()
s.calulcate()
s.display()
elif userchoice == 3:
m = multiplication()
m.getdata()
m.calulcate()
m.display()
elif userchoice == 4:
d = division()
d.getdata()
d.calulcate()
d.display()
else:
print('invalid input')
<file_sep>/python programs/sliceing cont...py
#this is a slicing exxample
example = list('arnabdas')
print('the list contains',example)
example[5:] = list('basak')
print('the list contains',example)
example2=[7,8,9]
print("the second list is",example2)
example2[1:1] = [3,3,3]
print('the second list after modification is',example2)
example2[1:5] = []
print("after deletion of the list",example2)
<file_sep>/Deep Learning/Deeplearning with mnist fashion dataset.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import keras
print(keras.backend.backend())
<file_sep>/python programs/kilometer to miles.py
k = input('enter the kilometer: ')
fixpoint = 0.621371 ;
miles = float(k) * fixpoint
print('the conversion of the km in miles is: ',miles)
km = miles/fixpoint;
print('the given kilometer is: ',km)
<file_sep>/progrms nltk/parts of speach -exp.py
import nltk
from nltk.tokenize import PunktSentenceTokenizer
sample_text = "<NAME> is starting to find his foot in nltk with the help of sentdex and he is also interested in Sachin and cricket"
sentencetokenizer = PunktSentenceTokenizer(sample_text)
tokenized = sentencetokenizer.tokenize(sample_text)
def process_content():
try:
for i in tokenized:
words = nltk.word_tokenize(i)
tagged = nltk.pos_tag(words)
print(tagged)
except Exception as e:
print(str(e))
process_content()
<file_sep>/flask_coding_new/GuessingGame/app.py
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/home')
def home():
username = request.args.get('username')
password = request.args.get('password')
if username == "admin" and password == "<PASSWORD>":
return render_template('home.html')
else:
return render_template('login.html')
@app.route('/register')
def register():
return render_template('register.html')
@app.route('/login')
def login():
username = request.args.get('username')
password = request.args.get('password')
if username == "admin" and password == "<PASSWORD>":
return render_template('login.html')
else:
return render_template('register.html')
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/python programs/PasswordGenerator.py
import random
s = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
passlen = int(input("enter the length of the password"))
passo = "".join(random.sample(s,passlen))
print(passo)<file_sep>/TensorBoard/example2.py
import tensorflow as tf
tf.reset_default_graph() # To clear the defined variables and operations of the previous cell
# create the scalar variable
x_scalar = tf.get_variable('x_scalar', shape=[], initializer=tf.truncated_normal_initializer(mean=0, stddev=1))
# ____step 1:____ create the scalar summary
first_summary = tf.summary.scalar(name='My_first_scalar_summary', tensor=x_scalar)
init = tf.global_variables_initializer()
# launch the graph in a session
with tf.Session() as sess:
# ____step 2:____ creating the writer inside the session
writer = tf.summary.FileWriter('./graphs', sess.graph)
for step in range(100):
# loop over several initializations of the variable
sess.run(init)
# ____step 3:____ evaluate the scalar summary
summary = sess.run(first_summary)
# ____step 4:____ add the summary to the writer (i.e. to the event file)
writer.add_summary(summary, step)
print('Done with writing the scalar summary')
<file_sep>/numbers.py
message = input('enter a number')
number1 = int(message)
number2 = number1**2
number3 = number2**2
number4 = number3**2
number5 = number4**2
number6 = number5**2
number7 = number6**2
number8 = number7**2
print(number8)
print(number8**2)
input('press ENTER to continue....')
<file_sep>/Deorators.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 22:52:32 2018
@author: arnabbasak
"""
import time
def time_it(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
print(func.__name__+" took "+str((end-start)*1000) + "miliseconds")
return result
return wrapper
@time_it
def calc_squares(numbers):
result = []
for number in numbers:
result.append(number*number)
return result
@time_it
def calc_cubes(numbers):
result = []
for number in numbers:
result.append(number*number*number)
return number
array = range(1,100000)
out_square = calc_squares(array)
out_cubes = calc_cubes(array)<file_sep>/PrimeNumber_Range.py
lowerlimit=int(input("enter the lower limit"))
upperlimit = int(input("enter the higher limit"))
for num in range(lowerlimit,upperlimit+1):
if num>1:
for i in range(2,num):
if(num%i) == 0:
break
else:
print(num)
<file_sep>/Filereading.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 8 18:12:59 2018
@author: arnabbasak
"""
mytxtfile = open('modi_speech.txt','r')
example_sent = mytxtfile.read().replace('\n','')
print(len(example_sent))
uppercasecount = 0
lowercasecount = 0
for element in example_sent:
if(element.islower()):
uppercasecount = uppercasecount+1
elif(element.isupper()):
lowercasecount = lowercasecount+1
print('upper case count in the file is',uppercasecount)
print('lower case count in the file is',lowercasecount)
print('precentage of the upper case letter in the file')
print(((uppercasecount)/(len(example_sent)))*100)
print('precentage of the lower case letter in the file')
print(((lowercasecount)/(len(example_sent)))*100)
<file_sep>/string methods 18t.py
sequence = ['this','is','my','sequence']
print('the given sequence is',sequence)
glue =input('enter the word you want to join the sequence')
print(glue.join(sequence))
randomstring = input('enter a string with uppercase letter')
print(randomstring.lower())
truth = "i love milk"
print(truth)
print(truth.replace('milk','choclate'))
<file_sep>/Python_Programs/PythonCode/OpeningBattingrecords.py
import pandas as pd
import numpy as np
data = pd.read_html("https://stats.espncricinfo.com/ci/content/records/283512.html")
print(data.head())
<file_sep>/python programs/GUI in python.py
from tkinter import *
root = Tk()
thelabel = Label(root, text="this is a text")
thelabel.pack()
#root.mainloop()
#root = Tk()
topframe = Frame(root)
topframe.pack()
bottomframe = Frame(root)
bottomframe.pack(side=BOTTOM)
button1 = Button(topframe,text="button 1",fg="red")
button2 = Button(topframe,text="button 2",fg="blue")
button3 = Button(bottomframe,text="button 3",fg="green")
button4 = Button(bottomframe,text="button 4",fg="yellow")
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
button3.pack(side=RIGHT)
button4.pack(side=BOTTOM)
root.mainloop()
<file_sep>/Dash_Codes/3rd_example_part2.py
import pandas_datareader.data as web
import datetime
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output
app = dash.Dash()
app.layout = html.Div(children=[
html.Div(children='''
Symbol to graph:
'''),
dcc.Input(id='Input',value='',type='text'),
html.Div(id='output-graph'),
])
@app.callback(
Output(component_id='output-graph',component_property='children'),
[Input(component_id='Input',component_property='value')]
)
def update_value(input_data):
start = datetime.datetime(2015,1,1)
end = datetime.datetime.now()
df = web.DataReader(input_data,'yahoo',start,end)
return dcc.Graph(
id='example-graph',
figure={
'data':[
{'x':df.index,'y':df.Close,'type':'Line','name':input_data}
],
'layout':{
'title':input_data
}
}
)
if __name__ == '__main__':
app.run_server(debug=True)
<file_sep>/practice4.py
def solution():
mylist = [2,2,3,4,4,4,5,6,7,7,8,9]
length_of_list = len(mylist)
vallycount = 0
hillcount = 0
sublist1 = mylist[:2]
if sublist1[0] == sublist1[1]:
vallycount += 1
else:
hillcount += 1
sublist2 = mylist[2:4]
if sublist2[0] == sublist2[1]:
vallycount += 1
else:
hillcount += 1
sublist3 = mylist[4:6]
if sublist3[0] == sublist3[1]:
vallycount += 1
else:
hillcount += 1
sublist4 = mylist[6:8]
if sublist4[0] == sublist4[1]:
vallycount += 1
else:
hillcount += 1
sublist5 = mylist[8:10]
if sublist5[0] == sublist5[1]:
vallycount += 1
else:
hillcount += 1
sublist6 = mylist[10:12]
if sublist6[0] == sublist6[1]:
vallycount += 1
else:
hillcount += 1
print("there will be ",hillcount,"castle on hills")
print("there will be",vallycount,"castle on vally")
solution()
<file_sep>/Dash/First_DashApplication.py
import dash
import dash_html_components as html
import dash_core_components as dcc
app = dash.Dash()
app.layout = html.Div([
html.H1('Hello Dash!!!'),
html.Div('Dash is a data web development frame work')
])
if __name__ == '__main__':
app.run_server(port=4050)<file_sep>/generators.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 23:08:56 2018
@author: arnabbasak
"""
def fib():
a,b = 0,1
while True:
yield a
a,b = b,a+b
for f in fib():
if f > 13:
break
print (f)<file_sep>/SetOperation.py
list1 = ['a','b','c']
print('the list 1 is',list1)
pyset1 = set(list1)
print('the list 1 after converting into set ',pyset1)
list2 = ['a','c','d']
print('the list 2 is',list2)
pyset2 = set(list2)
print('the list 2 after converting into set ',pyset2)
totalset1 = pyset1 - pyset2
print('elements present only in set 1',totalset1)
totalset2 = pyset2 - pyset1
print('elements present only in set 2',totalset2)
intersectionset = pyset1 & pyset2
print('elements present in both the set',intersectionset)
<file_sep>/simple_projects/simple_calculator.py
class calculator:
def simple_calculator(self):
num1 = int(input('enter num1'))
num2 = int(input('enter num2'))
print(f'Addition of {num1} and {num2} is',num1 + num2)
print(f'Substraction of {num1} and {num2} is',num1 - num2)
print(f'Multiplication of {num1} and {num2} is',num1 * num2)
print(f'Division of {num1} and {num2} is',num1 / num2)
print(f'Modulus of {num1} and {num2} is',num1 % num2)
print(f'Floor division of {num1} and {num2} is',num1 // num2)
def simple_interest(self):
"""SIMPLE INTEREST"""
p = float(input('enter the Principle amount'))
n = float(input('enter the time duration in months'))
r = float(input('enter the rate of interest'))
if r == 0.0 or n == 0:
a = float(input('You have not entered the rate of interest please enter the amount you have to pay to calculate the rate of interest'))
r = ((p*n)/(100.0*a))
print(f'The rate of interest for the amount {a} after {n} months is: ',r)
else:
a = ((p*n*r)/100)
print(f'The total amount you have to pay after {n} months is {a+p}')
#c = calculator()
#c.simple_calculator()
#c.simple_interest()
class Calculate_area:
def __init__(self):
self.length = 0.0
self.radius = 0.0
self.breadth = 0.0
self.height = 0.0
self.userinput = 0
self.area = 0.0
self.side = 0.0
def areaofcircle(self):
self.radius = float(input('Enter the radius of the circle'))
self.area = 3.14*self.radius**2
print(f'The area of the circle is{self.area}')
def circumferenceofcircle(self):
self.radius = float(input('Enter the radius of the circle'))
self.area = 2*3.14*self.radius
def areaofrectangle(self):
self.length = float(input('Enter the length of the rectangle'))
self.breadth = float(input('Enter the breadth of the rectangle'))
self.area = self.length * self.breadth
print(f'area of rectangle is {self.area}')
def areaoftriangle(self):
self.length = float(input('Enter the length of the triangle'))
self.breadth = float(input('Enter the breadth of the triangle'))
self.height = float(input('Enter the height of the triangle'))
self.area = self.length * self.breadth * self.height
print(f'area of triangle is {self.area}')
def areaofsquare(self):
self.side = float(input('Enter the side of the square'))
self.area = self.side ** 2
print(f'area of square is{self.area}')
def dataInput(self):
print('-------PRESS 1 FOR AREA OF CIRCLE-------\n')
print('-------PRESS 2 FOR CRICUMFERENCE OF CRICLE-------\n')
print('-------PRESS 2 FOR AREA OF RECTANGLE-------\n')
print('-------PRESS 3 FOR AREA OF TRIANGLE-------\n')
print('-------PRESS 4 FOR AREA OF SQUARE-------\n')
self.userinput = int(input('ENTER YOUR OPTION FROM THE ABOVE MENU'))
if self.userinput == 1:
self.areaofcircle()
elif self.userinput == 2:
self.circumferenceofcircle()
elif self.userinput == 3:
self.areaofrectangle()
elif self.userinput == 4:
self.areaoftriangle()
elif self.userinput == 5:
self.areaofsquare()
else:
print('Please select a valid option')
#cal = Calculate_area()
#cal.dataInput()
class Pythongorus:
def __init__(self):
self.one_side = 0.0
self.other_side = 0.0
self.hyp = 0.0
self.area = 0.0
def checkifrightangletriangle(self):
self.area = (self.one_side ** 2) + (self.other_side ** 2)
if self.area ** 2 == self.hyp ** 2:
print('The triangle is right angle triangle')
else:
print('The triangle is not a right angle triangle')
def userinput(self):
self.one_side = float(input('Enter the values for 1st side'))
self.other_side = float(input('Enter the values for 2nd side'))
self.checkifrightangletriangle()
p = Pythongorus()
p.userinput()
<file_sep>/gui python/increment clock.py
import tkinter as tk
counter = 0
def counter_label(label):
def count():
global counter
counter = counter+1
label.config(text=str(counter))
label.after(1000,count)
count()
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root,fg="Red")
label.pack()
counter_label(label)
button = tk.Button(root,text='Stop',width=25,command=root.destroy)
button.pack()
root.mainloop()
<file_sep>/python programs/madlibs in python.py
# program to code a game called madlibs
playername = input('enter your name')
print("Hello\n",playername,"follow the prompt to play the game: ")
proper_name1 = input("Enter a name: ")
proper_name2 = input("Enter another name: ")
noun1 = input("Enter a proper title: ")
place1 = input("Enter a place: ")
place2 = input("Enter another place: ")
verb1 = input("Enter a present-tense verb: ")
noun3 = input("Enter a noun: ")
noun2 = input("Enter a plural noun: ")
noun4 = input("Enter another plural noun: ")
num2 = input("Enter a number: ")
num1 = input("Enter another number: ")
percent1 = input("Enter another number: ")
print("Dear {}, It is my pleasure to {} to you today. I am {} and I'm the "
"{} of {}. I have inherited {} {} but I need your help to get it to {}. "
"Please send me your {} and the sum of {} {} to get started, and I will "
"give you {} percent of my inheritance. Yours truly, {}".format(
proper_name1, verb1, proper_name2, noun1, place1, num1, noun2,
place2, noun3, num2, noun4, percent1, proper_name2))<file_sep>/Python_Ui.py
from tkinter import *
mainwindow = Tk()
mainwindow.title("Store Data Recovery")
main_label = Label(mainwindow,text="STORE DATA RECOVERY",fg="dark green",font="Verdana 15 bold")
main_label.pack()
soa_database_label=Label(mainwindow,text="select database",fg="dark green",font="Verdana 10")
soa_database_label.pack()
var1 = IntVar()
Checkbutton(mainwindow, text="SOA",variable="var1").pack()
var2 = IntVar()
Checkbutton(mainwindow, text="STORE",variable="var2").pack()
mainwindow.mainloop()
<file_sep>/flask_coding_new/CURD_Flask/EmoloyeeDB.py
import sqlite3
con = sqlite3.connect("employee.db")
print('successfully connected')
con.execute("""create table employee(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
address TEXT NOT NULL)""")
print("table created successfully")
con.close()
<file_sep>/python programs/celsius into fahrenhit.py
c = float(input('enter the temperature in celsius: '))
f = (c * 1.8)+32
print('the celsius to farenhit conversion is: ',f)
<file_sep>/data_visualization/barcharts.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 14:21:27 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
x = [2,4,6,8,10]
y = [6,7,8,9,4]
x2 = [1,3,5,7,9]
y2 = [7,8,2,4,2]
plt.bar(x,y,label="Bars1",color='r')
plt.bar(x2,y2,label="Bars2",color='c')
plt.xlabel('x')
plt.ylabel('y')
plt.title('interesting graph\ncheck it out')
plt.legend()
plt.show()
<file_sep>/python_oops/basicobjects.py
import mymodule
from decimal import Decimal
print(Decimal('3.5') + Decimal('3.5'))
myint = 5
mystr = 'Hello'
mylist = ['a','b','c','d']
mybool = True
mynone = None
def myfunc():
print('hello from myfunc')
print(type(myint))
print(type(mystr))
print(type(mybool))
print(type(myfunc))
print(type(mynone))
this_type = type(mylist)
print(type(this_type))
var = 5
print(dir(var))
print("numerator of the variable: ",var.numerator)
print("denominator of teh variable: ",var.denominator)
print("number of bit required to store: ",var.bit_length())
print(var.real)
print()
print('these are the data from mymodule')
print(mymodule.dothis())
print(mymodule.myvar)<file_sep>/myprogram.py
message = input('enter a number')
print(message)
message1 = int(20.02)
print(message1)
<file_sep>/json coding/jasondata.py
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 15 23:58:55 2018
@author: Arnab
"""
import json
#==============================================================================
# with open('bowler.json', 'r') as f:
# distros_dict = json.load(f)
# print(type(distros_dict))
# for distro in distros_dict:
# print(distro)
#==============================================================================
homewicketslist = []
awaywicketslist = []
with open('Waqar Younis.json') as wy:
wydict = json.load(wy)
with open('McGrath.json') as mg:
mgdict = json.load(mg)
with open('kumble.json') as k:
kdict = json.load(k)
with open('srinath.json') as s:
sdict = json.load(s)
with open('Lee.json') as l:
ldict = json.load(l)
with open("vaas.json") as v:
vdict = json.load(v)
with open('pollock.json') as p:
pdict = json.load(p)
with open('jayasuriya.json') as js:
jsdict = json.load(js)
with open('Wasim Akram.json') as wa:
wadict = json.load(wa)
with open('Muralitharan.json') as m:
mdict = json.load(m)
homewicketslist.append(wydict.get("Home"))
awaywicketslist.append(wydict.get("Away"))
homewicketslist.append(kdict.get("Home"))
awaywicketslist.append(kdict.get("Away"))
homewicketslist.append(sdict.get("Home"))
awaywicketslist.append(sdict.get("Away"))
homewicketslist.append(ldict.get("Home"))
awaywicketslist.append(ldict.get("Away"))
homewicketslist.append(vdict.get("Home"))
awaywicketslist.append(vdict.get("Away"))
homewicketslist.append(pdict.get("Home"))
awaywicketslist.append(pdict.get("Away"))
homewicketslist.append(jsdict.get("Home"))
awaywicketslist.append(jsdict.get("Away"))
homewicketslist.append(wadict.get("Home"))
awaywicketslist.append(wadict.get("Away"))
homewicketslist.append(mdict.get("Home"))
awaywicketslist.append(mdict.get("Away"))
maxhomewickets = max(homewicketslist)
maxawaywickets = max(awaywicketslist)
print(maxhomewickets)
print(maxawaywickets)
<file_sep>/python programs/ASCII value of a character.py
# ascii value of a character
character = input('enter a single character')
print('the ascii value of the',character, 'is: ',ord(character))<file_sep>/pythoncodes/pythondatetime.py
import datetime
import calendar
datedict = {"Monday" : 0,
"tuesday": 1,
"wednesday": 2,
"thursday": 3,
"friday": 4,
"saturday": 5,
"sunday": 6}
#print(datetime.datetime.today().weekday())
#my_date = date.today()
#print(calendar.day_name[my_date.weekday()])
#dt = '02/09/2018'
datefile = open('/home/arnab/Desktop/pythoncodes/dates.txt','r')
for dt in datefile:
day,month,year = (int (x) for x in dt.split('/'))
ans = datetime.date(year,month,day)
print(dt, ans.strftime("%A"))
<file_sep>/fibonacci.py
n = int(input("how a=many numbers do you want to create fibonacci series"))
def fib(n):
a,b = 0,1
while a < n:
print(a)
a,b = b,a+b
return(a)
print(fib(n))
<file_sep>/flask_coding_new/login/addition.py
from flask import *
app = Flask(__name__)
@app.route("/calculation",methods=["POST","GET"])
def addition():
msg = ""
if request.method == "POST":
name = request.form["name"]
email = request.form["email"]
#city = request.form["city"]
#password = request.form["password"]
#username = request.form["username"]
#reenterpassword = request.form["reenterpassword"]
return render_template('addition.html')
else:
return render_template('addition.html')
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/InterviewNotes.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""printing hello world"""
print('hello world')
# In[9]:
"""basic arithmatic"""
a,b = 9,2
print("addition is ",a+b)
print("substraction is ",a-b)
print("division is ",a/b)
print("Floor division ",a//b) """Floor division"""
print("modulus is ",a%b)
print("multiplication is ",a*b)
print("square is ",a**b)
# In[5]:
"""Taking user input"""
user_input = input('enter your name')
print('hello',user_input)
# In[13]:
"""even odd"""
a = 2
if a % 2 == 0:
print(a,'is even')
else:
print(b,'is odd')
# In[12]:
"""Positive negative zero"""
a = 3
if a > 0:
print(a,"is positive number")
elif a < 0:
print(a,"is negative number")
elif a == 0:
print(a,'is zero')
else:
print('enter a number')
# In[18]:
"""area of rectangel"""
l,b = 23,34
print('area of rectange',l*b)
"""area of circle"""
r= 23
print('area of circle',3.14*r*r)
"""are of square"""
s = 34
print('area of square',s*s)
"""area of triangle"""
a,b,c = 33,34,44
print('area of triangle',((a+b+c)/2))
# In[19]:
"""largest of three numbers"""
a,b,c = 564746,564434,567543
if a > b and a > c:
print(a,'is greater')
elif b > a and b > c:
print(b,'is greater')
elif c > a and c > b:
print(c,' is greater')
else:
print('all numbers are equal')
# In[22]:
"""palindrom of a string"""
mystring = 'aIbohPhoBiA'
clearstring = mystring.casefold()#ignores the case upper and lower
rev_String = reversed(clearstring)
if list(rev_String) == list(clearstring):
print('entered string is palindrome')
else:
print('entered string is not palindrome')
# In[26]:
"""prime numbers"""
num = 407
if num > 1:
for i in range(2,num):
if(num % i) == 0:
print(num,'is not prime')
print(i,"times",num //i,'=is',num)
break
else:
print(num,"is prime")
# In[36]:
"""factorial of a number"""
num = 7
factorial = 1
if num == 0:
print('there is no factorial for 0')
elif num < 0:
print('thre is no factorial for negative numbers')
else:
for i in range(1,num+1):
factorial = factorial *i
print("the factorial of ",num,"is",factorial)
# In[38]:
"""multiplication table"""
num = 12
for i in range(1,11):
print(num,"x",i,num*i)
# In[41]:
"""sum of natural numbers"""
num = 16
if num < 0:
print('enter a positive number')
else:
sum = 0
while (num > 0):
sum += num
print(sum)
num -= 1
print(num)
print('sum is ',sum)
# In[42]:
import math
num = 2
print("the square root of ",math.sqrt(num))
# In[43]:
"swapping of two variables with temporary variables and in single line"
a,b = 1,2
print('before swaping',a,b)
a,b = b,a
print('after swapping',a,b)
# In[44]:
"""Decimal to binary octal and hexadecimal conversion"""
num = 455
print('binary of ',num,bin(num))
print('octal of ',num,oct(num))
print('hexadecimal of ',num,hex(num))
# In[6]:
"""decorators"""
import time
def time_it(func):
def wrapper(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
print(func.__name__+"took"+str((end-start)*1000) + "mil second")
return result
return wrapper
@time_it
def calc_square(numbers):
result = []
for number in numbers:
result.append(number*number)
return result
@time_it
def cal_cube(numbers):
result = []
for number in numbers:
result.append(number * number * number)
return result
array = range(1,100000)
out_square = calc_square(array)
out_cube = cal_cube(array)
# In[9]:
"""Generators in python printing fibonaci sequence"""
def fib():
a,b = 0,1
while True:
yield a
a,b = b,a+b
for f in fib():
if f > 50:
break
print(f)
# In[8]:
# A simple function to calculate the value 3x+1
#anonymous function == lambda expression
#lambda just like function its perfectly acceptable to have a function without any name
#cannot use lambda expression for multiline values
def f(x):
return 3*x+1
print(f(2))
g = lambda x: 3*x+1
print(g(2))
#lambda expression with more than one input
#combine first and last name into a single name
full_name = lambda fn,ln:fn.strip().title() + " " + ln.strip().title()
print(full_name(" Arnab","BASAK"))
scifi_authors = ["<NAME>", "<NAME>", "<NAME>"," <NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"]
#sort this list in alphabetic order through anonimous function
#sorting the list on the last name
scifi_authors.sort(key=lambda name:name.split(" ")[-1].lower())
print(scifi_authors)
def build_quadratic_equations(a,b,c):
return lambda x: a*x**2 + b*x + c
#f = build_quadratic_equations(2,3,-5)
#print(f(2))
print(build_quadratic_equations(3,0,1)(2)) # evaluate 3x^2+1
#common application for lambda expression is sorting and flitering data
# In[24]:
"""reading a file and other file operation"""
my_file = open("/users/arnabbasak/Desktop/flask_blog/modi_speech.txt",'r')
example_sent = my_file.read().replace('\n','')
print(len(example_sent))
uppercasecount = 0
lowercasecount = 0
for element in example_sent:
if(element.islower()):
uppercasecount = uppercasecount+1
elif(element.isupper()):
lowercasecount = lowercasecount+1
print('upper case count in the file is',uppercasecount)
print('lower case count in the file is',lowercasecount)
print('precentage of the upper case letter in the file')
print(((uppercasecount)/(len(example_sent)))*100)
print('precentage of the lower case letter in the file')
print(((lowercasecount)/(len(example_sent)))*100)
# In[25]:
n = int(input("how a=many numbers do you want to create fibonacci series"))
def fib(n):
a,b = 0,1
while a < n:
print(a)
a,b = b,a+b
return(a)
print(fib(n))
# In[26]:
message = "meet me tonight."
print(message)
message2 = 'meet me string'
print(message2)
print(message[0:4])
print(message[0:])
print(message[:15])
#srting is immutable
# In[ ]:
<file_sep>/Akinator/guessing conversion rate.py
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 17 20:01:24 2018
@author: Arnab
"""
import pyttsx3
import pandas as pd
from pandasql import sqldf
engine = pyttsx3.init()
#mylist = ['arnab','basak']
#engine.say(mylist)
#engine.runAndWait()
bowler = pd.read_csv('E:/pythonprograms/Akinator/bowlerrecords.csv')
engine.say('welcome to cricket bowling records, check out the fasinating bowler records in history of cricket ')
engine.runAndWait()
userinput = input('waiting for your response\n')
if userinput == 'y':
highestwickettakerquery = "select Player from bowler where Wkts IN (select max(Wkts) from bowler)"
Highestwickettaker= sqldf(highestwickettakerquery,locals())
print(Highestwickettaker)
engine.say('highest wicket taker in cricket is')
engine.say(Highestwickettaker)
engine.runAndWait()
lowestwicktakerquery = "select Player from bowler where Wkts IN (select min(Wkts) from bowler)"
Lowestwickettaker = sqldf(lowestwicktakerquery,locals())
print(Lowestwickettaker)
engine.say('lowest wicket taker in cricket is')
engine.say(Lowestwickettaker)
engine.runAndWait()
highesteconomyratequery = "select Player from bowler where Econ IN(select max(Econ) from bowler)"
Highesteconomyrate = sqldf(highesteconomyratequery,locals())
print(Highesteconomyrate)
engine.say('bowler who has highest economy is')
engine.say(Highesteconomyrate)
engine.runAndWait()
lowesteconomyratequery = "select Player from bowler where Econ IN(select min(Econ) from bowler)"
Lowesteconomyrate = sqldf(lowesteconomyratequery,locals())
print(Lowesteconomyrate)
engine.say('bowler who has lowest econmy rate is')
engine.say(Lowesteconomyrate)
engine.runAndWait()
lowestaveragequery = "select Player from bowler where Ave IN(select min(Ave) from bowler)"
Lowestaverage = sqldf(lowestaveragequery,locals())
print(Lowestaverage)
engine.say('bowler who has lowest average is')
engine.say(Lowestaverage)
engine.runAndWait()
highestaveragequery = "select Player from bowler where Ave IN(select max(Ave) from bowler)"
Highestaverage = sqldf(highestaveragequery,locals())
print(Highestaverage)
engine.say('bowler who has highest average is')
engine.say(Highestaverage)
engine.runAndWait()
higheststrickratequery = "select Player from bowler where SR IN(select max(SR) from bowler)"
Higheststrickrate = sqldf(higheststrickratequery,locals())
print(Higheststrickrate)
engine.say('highest strike rate is')
engine.say(Higheststrickrate)
engine.runAndWait()
loweststrickratequery = "select Player from bowler where SR IN(select min(SR) from bowler)"
Loweststrickrate = sqldf(loweststrickratequery,locals())
engine.say('bowler with lowest strike rate is')
engine.say(Loweststrickrate)
engine.runAndWait()
mostbowlbowledquery = "select Player from bowler where balls IN(select max(balls) from bowler)"
Mostbowlbowled = sqldf(mostbowlbowledquery,locals())
print(Mostbowlbowled)
engine.say('the bowler who bowled most balls')
engine.say(Mostbowlbowled)
engine.runAndWait()
leastbowledquery = "select Player from bowler where balls IN()"
else:
engine.say('oh ok thanks have a great day')
engine.runAndWait()
<file_sep>/csvreading.py
#reading of the bumping file and storing in the list of list
import csv
store_list=[]
soa_list=[]
plato_list=[]
specs_list=[]
Headerfile = open('C:/Users/arnab.jaydeb.basak/Documents/store recovery automation/bumpKeyField-Fix-0835012317.csv','r')
for row in csv.reader(Headerfile):
if row[0] == 'Plato':
plato_list.append(row)
elif row[0] == 'Store':
store_list.append(row)
elif row[0] == 'SOA':
soa_list.append(row)
else:
specs_list.append(row)
Headerfile.close()
print("Printing store values\n")
print('Total missing values in the store database ',len(store_list))
print(store_list)
print()
store_flattendlist = [y for x in store_list for y in x]
print(store_flattendlist)
store_set = set(store_flattendlist)
print()
print(store_set)
<file_sep>/Dash_Codes/componentsDash.py
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
html.H1('Bar Chart'),
html.Div('This is a Bar chart'),
dcc.Graph(
id = 'Sample-Graph',
figure = {
'data':[
{'x':[5,6,7],'y':[12,15,18],'type':'bar','name':'First Chart'},
{'x':[5,6,7],'y':[10,12,25],'type':'bar','name':'Second Chart'}
],
'layout' : {
'title' : 'Sample Bar Chart'
}
}
)
])
if __name__ == '__main__':
app.run_server(port=4050)
<file_sep>/Python_Programs/PythonCode/numberGuessing.py
from tkinter import *
from tkinter import messagebox
import math
import random
root = Tk()
root.geometry("300x200")
root.resizable(0,0)
root.title("Number Guessing Game")
label = Label(root,text="Login here").grid(row=0,column=1)
label1 = Label(root,text="Username").grid(row=1,column=0)
entry1 = Entry(root)
entry1.grid(row=1,column=1)
label2 = Label(root,text="Password").grid(row=2,column=0)
entry2 = Entry(root,show="*")
entry2.grid(row=2,column=1)
def login():
username = entry1.get()
password = entry2.get()
if username == "admin" and password == "<PASSWORD>":
gamewindow = Toplevel(root)
variable = StringVar(gamewindow)
variable.set("select")
label = Label(gamewindow,text="select any value").grid(row=0,column=0)
option = OptionMenu(gamewindow,variable,"1","2","3","4","5","6","7","8","9","10")
option.grid(row=0,column=1)
def gamePlay():
systemgenerator = [1,2,3,4,5,6,7,8,9,10]
if variable.get() == "select":
messagebox.showinfo("error","Please select any value")
elif variable.get() == str(random.choice(systemgenerator)):
messagebox.showinfo("Congratulation","You have won as system also guessed the number "+str(random.choice(systemgenerator)))
elif variable.get() != str(random.choice(systemgenerator)):
diff = int(variable.get()) - int(random.choice(systemgenerator))
if diff < 0:
messagebox.showinfo("Sorry","You exceed by "+str(abs(diff)))
else:
messagebox.showinfo("Sorry","You were behind by "+str(diff))
playbutton = Button(gamewindow,text="submit",command=gamePlay).grid(row=1,column=1)
gamewindow.mainloop()
else:
messagebox.showinfo("error","invalid input")
submit = Button(root,text="Login",command=login).grid(row=3,column=1)
root.mainloop()
<file_sep>/Python_Programs/sentimentAnalysis.py
import tkinter as tk
from tkinter import messagebox
from tkinter import *
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from textblob import TextBlob
root = tk.Tk()
#This set the name for the window
root.title('Sentument analyzer')
#set set the default size of the window
root.geometry('800x200')
#this stops the window from getting maximized
root.resizable(0,0)
#This is setting the labbels
label = tk.Label(root,text='Sentiment analysis for the social media platform').grid(row=0,column=2)
statusLabel = tk.Label(root,text="Enter your status",).grid(row=2,column=1)
#This is setting the entry widget
statusEntry = tk.Entry(root,width=100)
statusEntry.grid(row=2,column=2,ipady=20)
#setting the radio button
radio = IntVar()
VaderSentiment = tk.Radiobutton(root,text="Vader Setiment",variable=radio,value=0).grid(row=3,column=2)
NltkSentiment = tk.Radiobutton(root,text="NLTK Setiment",variable=radio,value=1).grid(row=4,column=2)
#initializing the sentiment analyzer
obj = SentimentIntensityAnalyzer()
def SentumentCalculation():
selection = str(radio.get())
status = statusEntry.get()
if len(status) == 0:
messagebox.showinfo('warning',"Please enter the status")
else:
if selection == '0' : #vader sentiment
sentiment_dict = obj.polarity_scores(status)
if sentiment_dict['compound'] >= 0.05:
messagebox.showinfo("Sentiment","Status is positive")
elif sentiment_dict['compound'] <= -0.05:
messagebox.showinfo("Sentiment","Status is Negative")
else:
messagebox.showinfo("Sentiment","Status is neutral")
elif selection == '1': #NLTK Sentiment
analysis = TextBlob(status)
if analysis.sentiment.polarity > 0:
messagebox.showinfo('Sentiment',"Status is positive")
elif analysis.sentiment.polarity == 0:
messagebox.showinfo('Sentiment',"Status is neutral")
else:
messagebox.showinfo('Sentiment',"Status is negative")
else:
messagebox.showinfo('answer',status)
#This is setting the button
check = tk.Button(root,text="Check Status",command=SentumentCalculation).grid(row=5,column=2,padx=10,pady=10)
#This is packing all the widgets in the loop
root.mainloop()
<file_sep>/python programs/CSV file reading and writing.py
# reading a text file and making it to csv file
import os
import string
filexits = os.path.isfile('J:\python programs\mycsv.txt')
if filexits == False:
print('file not exits')
else:
fob = open('J:\python programs\mycsv.txt','r')
reading = fob.read()
#print(reading)
fob.close()
filexits = os.path.isfile('J:\python programs\mycsv.csv')
if filexits == True:
print('file already exists')
# print(reading)
else:
fob = open('J:\python programs\mycsv.csv','w+')
fob.write(reading)
print('file created')
fob.close()
<file_sep>/Movie Guesser/moviegenreguesser.py
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 25 19:23:04 2017
@author: Arnab
"""
import pandas as pd
from pandasql import sqldf
mymoviedataframe = pd.read_csv('MovieNames.csv')
#print(mymoviedataframe)
genre = "select DISTINCT genre from mymoviedataframe;"
genereoutput = sqldf(genre,locals())
print("You have watched ",len(genereoutput),"different genre of flims this year")
language = "select language from mymoviedataframe;"
languageoutput = sqldf(language,locals())
print(languageoutput)
<file_sep>/simple_projects/CRUD.py
import sqlite3
class databaseOperation:
def __init__(self):
self.query = ''
self.conn = sqlite3.connect('Student.db')
def createtable(self):
self.query = """
CREATE TABLE IF NOT EXISTS student (
ID int PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50));"""
self.conn.execute(self.query)
print('Table created successfully')
def insertdata(self):
self.query = f"INSERT INTO student(ID,name,age,address) values({self.id},'{self.name}',{self.age},'{self.address}')"
print(self.query)
self.conn.execute(self.query)
self.conn.commit()
def getdata(self):
self.id = int(input('enter ID'))
self.name = input('Enter your name')
self.age = int(input('Enter the age'))
self.address = input('Enter the address')
self.insertdata()
def readdata(self):
self.query = "select * from student"
self.data = self.conn.execute(self.query)
for items in self.data:
print(f"ID = {items[0]}")
print(f"NAME = {items[1]}")
print(f"AGE = {items[2]}")
print(f"ADDRESS = {items[3]}")
db = databaseOperation()
db.createtable()
db.getdata()
db.readdata()
<file_sep>/python_oops/staticmethod.py
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self,firstname,lastname,pay):
self.firstname = firstname
self.lastname = lastname
self.pay = pay
self.email = firstname + '.' + lastname + '@<EMAIL>'
"""since this should be constant for all the instence
of the class that's why there is no self"""
Employee.num_of_emps+=1
def fullname(self):
return '{} {}'.format(self.firstname,self.lastname)
def apply_raise(self):
#self.raise_amount is used since this has be to manupulated by the instence
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amt(cls,amount):
cls.raise_amount = amount
@classmethod
def from_string(cls,emp_str):
first,last,pay = emp_str.split('-')
return cls(first,last,pay)
employee1 = Employee('arnab','basak',50000)
employee2 = Employee('test','testing',60000)
<file_sep>/random numbers.py
import random
ss = int(input('enter the starting of the series: '))
ee = int(input('enter the ending of the series: '))
r = random.randint(ss,ee)
print('the random number is',r)
<file_sep>/Django/WordCount-Project/WordCount/views.py
from django.http import HttpResponse
from django.shortcuts import render
from datetime import datetime
import operator
from textblob import TextBlob
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from nltk.tokenize import sent_tokenize,word_tokenize
def home(request):
usertext = request.GET['text']
if len(usertext) == 0:
return render(request,'login.html')
else:
if datetime.now().hour > 12:
return render(request,'home.html',{'greetings':'Good evening','welcome':usertext})
else:
return render(request,'home.html',{'greetings':'Good morning','welcome':usertext})
def count(request):
return render(request,'count.html')
def result(request):
fulltext = request.GET['fulltext']
if len(fulltext) == 0:
return render(request,'resultcount.html',{'fulltext':'','count':len(fulltext)})
else:
wordlist = fulltext.split()
worddictionary = {}
for word in wordlist:
if word in worddictionary:
worddictionary[word] += 1
else:
worddictionary[word] = 1
sortedwords = sorted(worddictionary.items(),key=operator.itemgetter(1),reverse=True)
return render(request,'resultcount.html',{'fulltext':fulltext,'count':len(wordlist),'sortedwords':sortedwords})
def about(request):
return render(request,'about.html')
def textblob(request):
return render(request,'textblob.html')
def textblobresult(request):
sentimenttext = request.GET['sentimenttext']
if len(sentimenttext) == 0:
return render(request,'textblob.html')
else:
analysis = TextBlob(sentimenttext)
score = analysis.sentiment.polarity
if score > 0:
return render(request,'textblobresult.html',{'sentence':sentimenttext,'output':'sentence is positive','score':score})
elif score == 0:
return render(request,'textblobresult.html',{'sentence':sentimenttext,'output':'sentence is neutral','score':score})
else:
return render(request,'textblobresult.html',{'sentence':sentimenttext,'output':'sentence is negative','score':score})
def vader(request):
return render(request,'vader.html')
def vaderresult(request):
sentimenttext = request.GET['sentimenttext']
if len(sentimenttext) == 0:
return render(request,'vader.html')
else:
sid_obj = SentimentIntensityAnalyzer()
sentiment_dict = sid_obj.polarity_scores(sentimenttext)
neg_per = sentiment_dict['neg']*100
pos_per = sentiment_dict['pos']*100
neu_per = sentiment_dict['neu']*100
if sentiment_dict['compound'] >= 0.05:
overall = 'Positive'
elif sentiment_dict['compound'] <= -0.05:
overall = 'Negative'
else:
overall = 'Neutral'
return render(request,'vaderresult.html',{'sentence':sentimenttext,'output':sentiment_dict,'neg_per':neg_per,'pos_per':pos_per,'neu_per':neu_per,'overall':overall})
def login(request):
return render(request,'login.html')
def logout(request):
return render(request,'logout.html')
def token(request):
return render(request,'token.html')
def tokenresult(request):
tokentext = request.GET['tokentext']
if len(tokentext) == 0:
return render(request,'token.html')
else:
senttoken = sent_tokenize(tokentext)
wordtoken = word_tokenize(tokentext)
return render(request,'tokenresult.html',{'sentence':tokentext,'wordtoken':wordtoken,'senttoken':senttoken})
<file_sep>/Python_Programs/PythonCode/AdventureGame.py
"""
The Goal: Remember Adventure? Well, we’re going to build a more basic version of that.
A complete text game, the program will let users move through rooms based on user input and get descriptions of each room.
To create this, you’ll need to establish the directions in which the user can move,
a way to track how far the user has moved (and therefore which room he/she is in), and to print out a description.
You’ll also need to set limits for how far the user can move. In other words, create “walls” around the rooms that tell the user,
“You can’t move further in this direction.”
Concepts to keep in mind:
Strings
Variables
Input/Output
If/Else Statements
Print
List
Integers
The tricky parts here will involve setting up the directions and keeping track of just how far the user has “walked” in the game.
I suggest sticking to just a few basic descriptions or rooms, perhaps 6 at most.
This project also continues to build on using userinputted data.
It can be a relatively basic game, but if you want to build this into a vast, complex word,
the coding will get substantially harder, especially if you want your user to start interacting with actual objects within the game.
That complexity could be great, if you’d like to make this into a longterm project. *Hint hint.
"""
class AdventureGame:
def __init__(self):
self.house_one = 1
self.house_two = 2
self.house_three = 3
self.house_four = 4
self.house_five = 5
self.house_six = 6
self.rooms_house_one = ["Bedroom","Hall","Kitchen"]
self.rooms_house_two = ["MasterBedroom","Bedroom","Hall","Kitchen"]
self.rooms_house_three = ["MasterBedroom","Guestroom1","Guestroom2","Hall","Kitchen"]
self.rooms_house_four = ["MasterBedroom","Guestroom1","Guestroom2","Guestroom3","Hall","Kitchen"]
self.rooms_house_five = ["MasterBedroom","Guestroom1","Guestroom2","Guestroom3","Guestroom4","Hall","Kitchen"]
self.rooms_house_six = ["MasterBedroom","Guestroom1","Guestroom2","Guestroom3","Guestroom4","Guestroom5","Hall","Kitchen"]
self.description = {
'Bedroom' : 'This is a space having arrengment for the house owner to sleep',
'MasterBedroom' : 'This is space having arrengment for the house owner to sleep',
'Hall' : 'This is space where the living space is designed',
'Kitchen' : 'This is a space where cooking arrengments are made',
'Guestroom' : 'This space is designed for the guests to stay'
}
self.score = 0
def userinput(self):
print("Press 1 for House one")
print("Press 2 for House two")
print("Press 3 for House three")
print("Press 4 for House four")
print("Press 5 for House five")
print("Press 6 for House six")
print()
self.userchoice = int(input('Select from above option where do you want to enter'))
print()
if self.userchoice not in range(1,6):
print("invalid option please enter again")
self.userinput()
def gamePlay(self):
print("================================")
print("Press B for Bedroom")
print("Press M for MasterBedroom")
print("Press H for Hall")
print("Press K for Kitchen")
print("Press G for Guestroom")
print("================================")
print()
self.userroom = input('What do you think where did you entered choose from the above options')
print()
self.userdiscription = input('enter your discription for the room')
if self.userroom == 'B':
self.discriptiondata = self.description.get("Bedroom","")
self.score += 1
elif self.userroom == 'M':
self.discriptiondata = self.description.get("MasterBedroom","")
self.score += 1
elif self.userroom == 'H':
self.discriptiondata = self.description.get("Hall","")
self.score += 1
elif self.userroom == 'K':
self.discriptiondata = self.description.get("Kitchen","")
self.score += 1
elif self.userroom == 'G':
print("Sorry there is no such room")
self.score -= 1
else:
print("Sorry invalid option")
def Play(self):
if self.userchoice == 1:
print("YOU CHOOSE TO ENTER IN HOUSE 1 WHICH COMPRISES OF 3 ROOMS IN TOTAL")
self.gamePlay()
self.gamePlay()
self.gamePlay()
print("your final score is",self.score)
elif self.userchoice == 2:
print('YOU CHOOSE TO ENTER IN HOUSE 2 WHICH COMPRISES OF 4 ROOMS IN TOTAL')
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
print('Your final score is',self.score)
elif self.userchoice == 3:
print('YOU CHOOSE TO ENTER IN HOUSE 3 WHICH COMPRISES OF 5 ROOMS IN TOTAL')
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
print('Your final score is',self.score)
elif self.userchoice == 4:
print('YOU CHOOSE TO ENTER IN HOUSE 4 WHICH COMPRISES OF 6 ROOMS IN TOTAL')
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
print('Your final score is',self.score)
elif self.userchoice == 5:
print('YOU CHOOSE TO ENTER IN HOUSE 4 WHICH COMPRISES OF 7 ROOMS IN TOTAL')
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
print('Your final score is',self.score)
elif self.userchoice == 6:
print('YOU CHOOSE TO ENTER IN HOUSE 4 WHICH COMPRISES OF 8 ROOMS IN TOTAL')
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
self.gamePlay()
print('Your final score is',self.score)
else:
print('Please select a proper option')
Ag = AdventureGame()
Ag.userinput()
Ag.gamePlay()
Ag.Play()
<file_sep>/Python_Programs/frequenceCount.py
import time
def CountFrequency(mylist):
#creating an empty dictionary
freq={}
for item in mylist:
if(item in freq):
freq[item] += 1
else:
freq[item] = 1
for key,value in freq.items():
print("%d : %d"%(key,value))
#driver funtion
if __name__ == "__main__":
start = time.time()
mylist = [1,1,1,5,5,5,6,6,6,7,8,11,8,5,7,9,10,16,12,3]
CountFrequency(mylist)
end = time.time()
print("Total time taken is",(end-start)*1000)
def CountFrequency(mylist):
freq = {}
for items in mylist:
freq[items] = mylist.count(items)
print(freq)
if __name__ == "__main__":
start = time.time()
mylist = [1,1,1,5,5,5,6,6,6,7,8,11,8,5,7,9,10,16,12,3]
CountFrequency(mylist)
end = time.time()
print("total time taken is",(end-start)*1000)
import numpy as np
start = time.time()
a = np.array = ([10,10,20,10,20,20,20,30,40,50,60,60,50,0])
unique_elements,count_elements = np.unique(a,return_counts = True)
print(np.asarray((unique_elements,count_elements)))
end = time.time()
print("Total time taken is",(end-start)*1000)
<file_sep>/Dash_Codes/adding_styles.py
import dash
import dash_core_components dcc
import dash_html_components html
app = dash.Dash()
app.layout = html.Div([
html.H1(children = 'Bar Chart',),
])
<file_sep>/Python_Programs/PythonCode/simpleEntryForm.py
from tkinter import *
from tkinter import messagebox
import datetime
root = Tk()
root.title("Simple Form")
label1 = Label(root,text="Name").grid(row=0,column=0)
entry1 = Entry(root)
entry1.grid(row=0,column=1)
def output():
if datetime.datetime.now().hour < 12:
messagebox.showinfo("Message","Good Morning "+entry1.get())
elif datetime.datetime.now().hour >= 12 and datetime.datetime.now().hour < 15:
messagebox.showinfo("Message","Good Afternoon "+entry1.get())
elif datetime.datetime.now().hour > 15:
messagebox.showinfo("Message","Good Evening "+entry1.get())
submit = Button(root,text="submit",command=output).grid(row=1,column=1)
root.mainloop()
<file_sep>/python programs/transpose of a matrix.py
# program to find transpose of a matrix
mat1 = [[1,2],[4,5],[6,7]]
result = [[0,0,0],[0,0,0],[0,0,0]]
for k in mat1:
print(k)
for i in range(len(mat1)):
for j in range (len(mat1[0])):
result[j][i] = mat1[i][j]
for r in result:
print(r)
<file_sep>/matplotlib/firstgraph.py
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 11 14:26:57 2018
@author: Arnab
"""
import numpy as np
import matplotlib.pyplot as plt
#make the data
x = np.linspace(0,5)
y = np.exp(x)
print(x,y)
#plot the data
fignum = 1
plt.close(fignum)
plt.figure(fignum)
plt.plot(x,y)
plt.show()
<file_sep>/python programs/number conversion.py
# program for number conversion
decimal = int(input('enter any number'))
print('the octal of the given decimal number is: ',oct(decimal))
print('the hexadecimal of the given decimal number is: ',hex(decimal))
print('the binary of teh given decimal number is: ',bin(decimal))
<file_sep>/Dash_Codes/test.py
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
mapbox_access_token = '<KEY>'
app = dash.Dash()
app.layout = html.Div([
html.Div([
dcc.Graph(
id = "mapbox",
figure={
"data": [
dict(
type = "scattermapbox",
lat = ["45.5017", "46.829853"],
lon = ["-73.5673", "-71.254028"],
mode = "markers",
marker = dict(size = 14),
text = ["Montreal", "Quebec"])
],
'layout': dict(
autosize = True,
hovermode = "closest",
margin = dict(l = 0, r = 0, t = 0, b = 0),
mapbox = dict(
accesstoken = mapbox_access_token,
bearing = 0,
center = dict(lat = 45, lon = -73),
pitch = 0,
zoom = 5
)
)
},
style = {"height": "100%"}
)
],
style = {"height": "100%"}
),
html.Div([
dcc.Dropdown(
id = "dist-drop",
options = [{"label": "Montreal", "value": "Montreal"}, {"label": "Quebec", "value": "Quebec"}],
placeholder = "Select City")
],
style = {"position": "absolute", "top": "50px", "left": "50px", "width": "200px"}
)
], style = {"border-style": "solid", "height": "95vh"})
app.run_server()
<file_sep>/numpy_array_indexing.py
#!/usr/bin/env python
# coding: utf-8
# In[25]:
import numpy as np
arr = np.arange(1,11)
arr
# In[2]:
arr[8]
# In[4]:
arr[1:5]
# In[5]:
arr[0:5]
# In[6]:
arr[5:]
# In[7]:
arr[:5]
# In[8]:
arr[0:5] = 100
# In[9]:
arr
# In[11]:
arr
# In[13]:
slice_of_arr = arr[0:6]
slice_of_arr
# In[14]:
slice_of_arr[:] = 99
# In[15]:
arr
# In[17]:
arr_2d = np.array([[5,10,15],[20,25,30],[35,40,45]])
arr_2d
# In[18]:
arr_2d[0][1] #grabing element in first row in first column
# In[19]:
arr_2d[1][1] #this is called double bracket notation
# In[21]:
arr_2d[1,1] #this is a single bracket noation
# In[22]:
arr_2d[:2,1:]
# In[27]:
bool_arr = arr > 5
bool_arr
# In[26]:
arr[bool_arr]
# In[28]:
arr_2d = np.arange(50).reshape(5,10)
# In[31]:
arr_2d[1:3,3:5]
# In[ ]:
<file_sep>/movie project/main.py
import pandas as pd
from pandasql import sqldf
#from requests import get
usermovie_dataframe = pd.read_csv('mymovielist.csv')
#print(type(usermovie_dataframe))
#url = "https://www.imdb.com/india/top-rated-indian-movies/"
#response = get(url)
#print(response.text[:500])
#print(usermovie_dataframe["rating"].mean())
<file_sep>/Fibonacci Series.py
# program for fibonacci series
nterms = int(input('enter any sequetion of numbers'))
n1 = 0
n2 = 1
count = 2;
if nterms<=0:
print('enter positive numbers')
elif nterms ==1:
print(n1)
else:
print(n1, ",", n2, end=', ')
while count<nterms:
nth = n1+n2
print(nth, end=' , ')
n1 = n2
n2 = nth
count += 1<file_sep>/python programs/alphabetic comparison.py
message = input('enter any name')
message1 = input('enter name of other thing')
print('mesage<message1')
print(message<message1)
<file_sep>/flask_coding_new/login/encrypt_data.py
from cryptography.fernet import Fernet
key = Fernet.generate_key() #this is your "password"
cipher_suite = Fernet(key)
original_text = (bytes(input('enter text'),"utf-8"))
print(original_text)
encoded_text = cipher_suite.encrypt(original_text)
print(encoded_text)
decoded_text = cipher_suite.decrypt(encoded_text)
print(str(decoded_text))
<file_sep>/python programs/matrix addition.py
# python for matrix addition
mat1 = [[1,2,3],[4,5,6],[7,8,9]]
mat2 = [[10,11,12],[13,14,15],[16,17,18]]
result = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(mat1)):
for j in range(len(mat1[0])):
result[i][j] = mat1[i][j]+mat2[i][j]
for r in result:
print(r)
<file_sep>/Python_Programs/ticketbookingapp.py
from tkinter import *
from tkinter import messagebox
import pymysql
import datetime
root = Tk()
root.title('Ticket Booking')
root.geometry("300x100")
usernamelabel = Label(root,text="username").grid(row=0,column=0)
usertext = Entry(root)
usertext.grid(row=0,column=1)
passwordlabel = Label(root,text="<PASSWORD>").grid(row=1,column=0)
passwordtext = Entry(root,show="*")
passwordtext.grid(row=1,column=1)
def login():
username = usertext.get()
password = passwordtext.get()
if len(username) <= 0 and len(password) <=0:
messagebox.showinfo("Error","Invalid credentials")
else:
db = pymysql.connect(host="localhost",user="root",password="<PASSWORD>",db="ticket_booking")
cursor = db.cursor()
cursor.execute("select * from user")
results = cursor.fetchall()
for row in results:
name = row[0]
pwd = row[1]
if name == username and pwd == password:
#messagebox.showinfo("Info",'congratulations')
root.minsize()
ticket_booking = Toplevel(root)
ticket_booking.title("book tickets")
ticket_booking.geometry("500x500")
now = datetime.datetime.now().hour
if now < 8:
cursor = db.cursor()
cursor.execute("insert into tickets_booking values ")
elif now < 12:
greeting = Label(ticket_booking,text="Good Morning").grid(row=0,column=0)
elif now > 12:
greeting = Label(ticket_booking,text="Good Evening").grid(row=0,column=0)
ticket_booking.mainloop()
else:
messagebox.showinfo("Error","Invalid Credentials")
login = Button(root,text="Login",command=login).grid(row=2,column=1)
root.mainloop()
<file_sep>/progrms nltk/import nltk.py
import nltk
nltk.download()
# tokenizing are of two types 1.word tokenizer 2. sentence tokenizer
#corpora: body of text exp medical journal etc
#lexicon: words and their meanings
#for example investor say 'bull' then it means the market is quite good
#if in normal english langaage someone says 'bull' then it means an animal
<file_sep>/democonstructor.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 23:21:44 2018
@author: arnabbasak
"""
class computer:
pass
c1 = computer()
print(id(c1))<file_sep>/Python_Programs/numpy_practice.py
import numpy as np
print("a_list = [1,2,3,4]")
print("a_array = np.array([1,2,3,4])")
a_list = [1,2,3,4]
a_array = np.array([1,2,3,4])
print("adding the list that is a_list + a_list")
print("a_list+a_list") #it concatenates
print(a_list+a_list)
print()
print("adding the array")
print(a_array + a_array)
print("squaring elements in list")
print([x ** 2 for x in a_list ])
print("squaring elements in array")
print(a_array**2)
print(np.sqrt(a_array))
print(np.log(a_array))
print(np.exp(a_array))
<file_sep>/flask_coding_new/login/data_framecmp.py
import pandas as pd
import numpy as np
# df1 = pd.read_csv('df1.csv')
# df2 = pd.read_csv('df2.csv')
# df = pd.concat([df1,df2])
# df = df.reset_index(drop = True)
# df_grpby = df.groupby(list(df.columns))
# idx = [x[0] for x in df_grpby.groups.values()if len(x) == 1]
# print(idx)
file1 = open('df1.csv','r')
file2 = open('df2.csv','r')
file1data = file1.readlines()
file2data = file2.readlines()
updatefile = ('update.csv','w')
for data in file1:
if data not in file2:
updatefile.write(data)
updatefile.close()
updatefile = open('update.csv','r')
data = updatefile.readlines()
for elements in data:
print(elements)
<file_sep>/python_oops/mymodule.py
import matplotlib
import numpy
import sklearn
myvar = 10
def dothis():
print('this is do statement from the dothis function of my module')<file_sep>/Dash_Codes/3rd_example.py
"""
In this example we will create charts based on user input and dynamic data
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas_datareader.data as web
import datetime
start = datetime.datetime(2015,1,1)
end = datetime.datetime.now()
stocks = 'TSLA'
df = web.DataReader(stocks,'yahoo',start,end)
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('OMG finance'),
dcc.Graph(id='Example',
figure={
'data': [
{'x':df.index,'y':df.Close,'type':'line','name':stocks},
],
'layout':{
'title':stocks
}
})
])
if __name__ == '__main__':
app.run_server(debug=True)
<file_sep>/kk.py
from tkinter import *
root = Tk()
root.title("Message Box")
logo = PhotoImage(file="E:\python programs\gui python\logo-200.png")
explanation = """At present,only GIF and PPM/PGM
formats are supported,but an interface
exits to allow additional image file
formats to be added easily"""
w = Label(root,compound=CENTER,text=explanation,image=logo).pack(side="top")
root.mainloop()
<file_sep>/methods.py
# this is a method tutorial
AGE = [10,20,30,40];
print("the list is",AGE)
AGE.append(50)
print("the list is",AGE)
weight=[20,25,35,45,55,75,65]
AGE.extend(weight)
print("the extended list is",AGE)
apples = ['i','love','apples','apples','too','much']
print('the apples list consist of',apples)
print('the count of love in the list is',apples.count('love'))
<file_sep>/Python_Programs/cricket_analysis.py
"""
In this we will analyse the batting records for the batsman
1. Plot the TOP 5 run getters
2. Plot the TOP 5 century makers
3. Plot the TOP 5 half century makers
4. Plot the TOP 5 matches palyed
5, Plot the TOP 5 innings palyed
6. Plot the TOP 5 conversion Rate
"""
import pandas as pd
import numpy as np
import pymysql
from sqlalchemy import create_engine
from tkinter import *
from tkinter import messagebox
import matplotlib.pyplot as plt
class analysis:
def dataScreation(self):
"""This funtion is used for reading the html content into pandas dataframe"""
self.data = pd.read_html('https://stats.espncricinfo.com/ci/content/records/83548.html')
self.cricket_data = data[0]
self.cricket_data.to_csv('batting_statistics.csv')
def connection(self):
"""This funtion is reading the data from mysql table and creating a dataframe"""
self.engine = create_engine('mysql+pymysql://root:library@localhost:3306/cricket')
self.df = pd.read_sql_query('SELECT * FROM batting_statistics', self.engine)
print(self.df.head())
def userInterface(self):
root = Tk()
root.title("Cricket Analysis")
root.geometry('400x200')
root.resizable(0,0)
Top5Rungetterlabel = Label(root,text="Click below to get the info for top 5 run getter in ODI cricket").grid(row=0,column=0)
def RunGetter():
most_runs = self.df[['Player','Runs']].head(5)
most_runs.plot(kind='bar',x='Player',y='Runs',title='Most Runs')
plt.xlabel("Players Name")
plt.ylabel("Runs Scored")
plt.show()
Top5RunGetterButton = Button(root,text="Run Getter",command=RunGetter).grid(row=1,column=0)
root.mainloop()
a = analysis()
a.connection()
a.userInterface()
""" import mysql.connector as sql
import pandas as pd
db_connection = sql.connect(host='hostname', database='db_name', user='username', password='<PASSWORD>')
db_cursor = db_connection.cursor()
db_cursor.execute('SELECT * FROM table_name')
table_rows = db_cursor.fetchall()
df = pd.DataFrame(table_rows)
"""
<file_sep>/Akinator/Akinator code.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas
print('CRICKET AKINATOR THINK OF ANY CRICKETER AND I WILL GUESS IT\n PLEASE GIVE YES OR NO AS THE ANSWERS')
Userinput = input('IS YOUR CRICKETER A BATSMAN')
if Userinput == 'y':
print('your circketer is <NAME>')
elif Userinput == 'n':
Userinput = input('IS YOUR CRICKTER A BOWLER')
if Userinput == 'y':
bowlerdataframe = pandas.read_csv('E:/pythonprograms/Akinator/bowlerrecords.csv')
print(bowlerdataframe)
else:
print('PLEASE SELECT FOR A BOWLER OR A BATSMAN')
else:
print('INVALID INPUT PLEASE SELECT A PROPER ONE THAT IS ''y OR n''')
<file_sep>/python programs/database connectiviity.py
import mysql.connector
db = mysql.connector.connect("localhost","root","password","<PASSWORD>")
cursor =db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print(data)
<file_sep>/progrms nltk/stop words.py
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sentence = "this is a first sentence written by me in the nltk python."
stop_words = set(stopwords.words("english"))
print('original sentence is',example_sentence)
#print(stop_words)
words = word_tokenize(example_sentence)
filtered_sentence = []
for w in words:
if w not in stop_words:
filtered_sentence.append(w)
print(filtered_sentence)
#it can be done in one line as well
filtered_sentence1 = [w for w in words if not w in stop_words]
print(filtered_sentence1)
#stop words are the punctuation words which are used in the english sentence such as "is an etc"
<file_sep>/armstrong number.py
# program for amstrong number<file_sep>/Python_Programs/Madlibs_generator.py
"""
3. Mad Libs Generator
The Goal: Inspired by Summer Son’s Mad Libs project with Javascript.
The program will first prompt the user for a series of inputs a la Mad Libs.
For example, a singular noun, an adjective, etc. Then, once all the information
has been inputted, the program will take that data and place them into a premade
story template. You’ll need prompts for user input, and to then print out the full story at the end with the input included.
Concepts to keep in mind:
Strings
Variables
Concatenation
Print
A pretty fun beginning project that gets you thinking about how to manipulate userinputted data.
Compared to the prior projects, this project focuses far more on strings and concatenating.
Have some fun coming up with some wacky stories for this!
"""
class Madlibs:
def __init__(self):
pass
def userInput(self):
self.name = input("Enter a name of a person ")
self.place = input("Enter the name of a place")
self.animal = input("enter the name of an animal")
self.thing = input("enter the name of random thing")
self.verb = input("enter an action word that is verb")
self.adverb = input("enter an adverb")
self.adjective = input("enter and adjective")
def display(self):
print()
print("Hello {0}".format(self.name))
print("good to see you, how are you?,when did you came to {0},".format(self.place))
print("how is your pet {0},".format(self.animal))
print("what is the status of you buying a {0}".format(self.thing))
print("Do you {0} to office".format(self.verb))
print("Anyway {0} is good for health".format(self.adverb))
print("ofcourse you are a {0} person".format(self.adjective))
ML = Madlibs()
ML.userInput()
ML.display()
<file_sep>/Python_Programs/PythonCode/DiceGame.py
"""
will create a dice game using tkinter
"""
from tkinter import *
from tkinter import messagebox
import random
root = Tk()
root.title("The Dice Game")
label = Label(root,text="select any value").grid(row=0,column=0)
variable = StringVar(root)
variable.set("Select")
option = OptionMenu(root,variable,"1","2","3","4","5","6")
option.grid(row=0,column=1)
def gamePlay():
systemgenerator = [1,2,3,4,5,6]
if variable.get() == "Select":
messagebox.showinfo("Error","Please select a proper number")
elif int(variable.get()) == random.choice(systemgenerator):
messagebox.showinfo("Congratulation","You Won as system also selected "+str(random.choice(systemgenerator)))
elif int(variable.get()) != random.choice(systemgenerator):
messagebox.showinfo("Sorry","You lost as system selected "+str(random.choice(systemgenerator)))
play = Button(root,text="play",command=gamePlay).grid(row=1,column=1)
root.mainloop()
<file_sep>/snaity checks for pilot/sanity checks for pilot.py
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
import os
import subprocess
Mainwindow = Tk()
Mainwindow.title('Sanity Checks')
Mainwindow.configure(background='green')
main_label = Label(Mainwindow,text="SANITY TEST FOR PILOT STORES",fg="white",font="Timesnewroman 15 bold")
main_label.configure(background='green')
main_label.pack(fill=X,pady=5)
text_label=Label(Mainwindow,text="Enter IP for the stores",fg="white",font="Timesnewroman 10 bold")
text_label.configure(background = 'green')
text_label.pack()
Mytext = Text(Mainwindow,width=30,height=5)
Mytext.pack(pady=10)
#e.focus_set()
def callback():
#print (e.get())
content = Mytext.get("1.0","end-1c")
if len(content) <= 2:
messagebox.showerror('data info','please enter the IP properly')
else:
inputfile = open("/home/arnab/Desktop/inputfile.txt",'w')
inputfile.write(content)
inputfile.close()
""" executing the shell script make sure that this python script and the shell script is in same folder"""
subprocess.call(['bash','test.sh'])
"""reading the output file this should also be in the same location as the input file and the python script"""
outputfile = open("/home/arnab/Desktop/python_programs/output.txt",'r')
outputmatter = outputfile.read()
messagebox.showinfo("output",outputmatter)
Main_Button = Button(Mainwindow,text="Start",fg="green",font="calibari 10 bold", command=callback)
Main_Button.configure(background = "white")
Main_Button.pack()
w, h = Mainwindow.winfo_screenwidth(), Mainwindow.winfo_screenheight()
Mainwindow.geometry("%dx%d+0+0" % (w, h))
Mainwindow.mainloop()
<file_sep>/database using python/Comparing of CSV files.py
import csv
import itertools
reader1 = csv.reader(open('E:/Python programs/database using python/temp.csv', 'rb'))
reader2 = csv.reader(open('E:/Python programs/database using python/temp2.csv', 'rb'))
for lhs, rhs in itertools.zip(reader1, reader2):
if lhs != rhs:
print ("difference:", lhs, rhs)
<file_sep>/data_visualization/legends.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 14:19:28 2018
@author: Arnab
"""
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,6]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x,y, label = 'first line')
plt.plot(x2,y2,label = 'second line')
plt.xlabel('plot number')
plt.ylabel('important var')
plt.title('interesting graph\nCheck it out')
plt.legend()
plt.show()
<file_sep>/pythoncodes/statistics_calculation.py
import pandas as pd
from pandasql import sqldf
battingrecords = pd.read_excel('battin.xlsx')
#print(battingrecords)
centuries = "select Centuries from battingrecords where Player_name = 'Tendulkar'"
print(sqldf(centuries,locals()))
totalfiftyplusscore = "select (Centuries + HalfCenturies) from battingrecords where Player_name = 'Tendulkar'"
IndiaCenturylist = list((sqldf(centuries,locals())))
for element in IndiaCenturylist:
print(element)
#q = "select (((Centuries) / (Centuries + HalfCenturies)) * 100 ) as TOTAL_FIFTY from battingrecords where Country = 'INDIA'"
#print(sqldf(q,locals()))<file_sep>/flask_coding_old/HTML templates.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 21:35:28 2018
@author: Arnab
"""
from flask import Flask,render_template
app = Flask(__name__)
#@app.route("/profile/<name>")
#def profile(name):
# return render_template("profile.html",name=name)
@app.route("/")
@app.route("/<user>")
def index(user= None):
return render_template("user.html",user = user)
@app.route("/shopping")
def shopping():
food = ["cheese","cake","ice creame"]
return render_template("shopping.html",food=food)
if __name__ == "__main__":
app.run()<file_sep>/python programs/LeapYear.py
#leap Year
youryear = int(input('enter the year which you waant to check'))
if youryear%4 == 0:
if youryear%100 ==0:
if youryear%400 ==0:
print('the inputed year is a leap year')
else:
print("the inputed year is not a leap year")
else:
print("the inputed year is not a leap year")
else:
print("the inputed year is not a leap year")<file_sep>/python_json/jsondata.py
import json
with open('bowler.json', 'r') as f:
distros_dict = json.load(f)
for distro in distros_dict:
print(distro['Bowler'])<file_sep>/python programs/mathematical operation.py
number = input('enter 1 number')
number1 = input('enter second number')
addition = int(number)
addition1 = int(number1)
print("addition is ",+addition + addition1 )
print("substaction is ",+addition - addition1 )
print("multiplication is", +addition*addition)
print("division ",+addition / addition1 )
print("exponent is", +addition ** addition1)
print("modulus is" ,+addition% addition1)
| 838d23e9590bc855926628d0f7b4ffe73e108565 | [
"Python",
"HTML"
] | 205 | Python | ArnabBasak/PythonRepository | 388478fd33c4ed654eb6b1cba5e0cbdcfb90cf0e | ca475b1bc728ede1e033c54f40392f5b4c3494d4 |
refs/heads/master | <file_sep>'use strict'
console.log('\x1Bc')
const LOG = true
const DEBUG = false
global.cleanArray = actual => {
if (actual && actual.constructor === Array) {
let j = 0
for (let i = 0; i < actual.length; i++) {
if (actual[i]) {
actual[j++] = actual[i]
}
}
actual.length = j
return actual
}
return []
}
global.fixISO = str => {
return str.substr(0,4) + "-" + str.substr(4,2) + "-" + str.substr(6,5) + ":" + str.substr(11,2) + ":" + str.substr(13)
}
global.log = message => {
if (LOG) console.log((message) ? message : '')
}
global.debug = message => {
if (DEBUG) console.log(chalk.yellow('DEBUG:'), message)
}
const crypto = require('crypto')
const util = require('util')
const async = require('async')
const chalk = require('chalk')
const Discord = require('discord.js')
const findRemoveSync = require('find-remove')
const get = require('simple-get')
const moment = require('moment')
const nodePersist = require('node-persist')
const os = require('os-utils')
const Clan = require('./clash-of-clans-api/clans')
console.log(chalk.cyan('-'.repeat(17)))
console.log(chalk.cyan(' Discord War Bot '))
console.log(chalk.cyan('-'.repeat(17)))
global.config = require('./config')
log(chalk.bold('Server Permission URL:'))
log(chalk.magenta.bold('https://discordapp.com/oauth2/authorize?client_id=' + config.discord.clientId + '&scope=bot&permissions=134208\n'))
const DiscordClient = new Discord.Client()
const COC_API_BASE = 'https://api.clashofclans.com/v1'
global.DiscordChannelEmojis = {
'dwashield': '<:dwashield:316692730145275912>',
'dwashieldbroken': '<:dwashieldbroken:316692730191544321>',
'dwasword': '<:dwasword:316692748512133121>',
'dwaswordbroken': '<:dwaswordbroken:316692748675842048>',
'dwastarempty': '<:dwastarempty:316692653368410113>',
'dwastar': '<:dwastar:316692664919654400>',
'dwastarnew': '<:dwastarnew:316692675610935298>',
'elixir': '<:elixir:316692765817700352>',
'darkelixir': '<:darkelixir:316692780955074561>',
'gold': '<:gold:316692765473767425>',
'squaregold': '<:squaregold:316692808562114561>',
'diamondelixir': '<:diamondelixir:316692823854415872>',
'gems': '<:gems:316692795035484163>',
'versustrophies': '<:versustrophies:316692846411513856>',
}
global.DiscordTownHallEmojis = [
'<:townhall1:316693150603149312>',
'<:townhall2:316693150645354496>',
'<:townhall3:316693150783504404>',
'<:townhall4:316693150922178562>',
'<:townhall5:316693176280678400>',
'<:townhall6:316693232480288768>',
'<:townhall7:316693232643997696>',
'<:townhall8:316693232849256449>',
'<:townhall9:316693282119876609>',
'<:townhall10:316693308271493120>',
'<:townhall11:316693320237580300>',
'<:townhall12:471405233365319680>',
]
global.DiscordBuilderHallEmojis = [
'<:builderhall1:316693013718106123>',
'<:builderhall2:316693057988853760>',
'<:builderhall3:316693072022994944>',
'<:builderhall4:316693083754463232>',
'<:builderhall5:316693095448182784>',
'<:builderhall6:316693106651168769>',
'<:builderhall7:316693118269390848>',
'<:builderhall8:316693131770724353>',
]
global.DiscordTroopEmojis = {
'Barbarian': '<:barbarian:316393732671012864>',
'Archer': '<:archer:316393729542062081>',
'Goblin': '<:goblin:316393733493096448>',
'Giant': '<:giant:316393733501222923>',
'Wall Breaker': '<:wallbreaker:316393733501485056>',
'Balloon': '<:ballooncoc:316393733417467904>',
'Wizard': '<:wizard:316393732955963393>',
'Healer': '<:healer:316393732947705867>',
'Dragon': '<:dragoncoc:316393733216272386>',
'P.E.K.K.A': '<:pekka:316393733518000128>',
'Minion': '<:minion:316393733497290762>',
'Hog Rider': '<:hogrider:316393732641390604>',
'Valkyrie': '<:valkyrie:316393733576720394>',
'Golem': '<:golem:316393733308416011>',
'Witch': '<:witch:316393733224660995>',
'Lava Hound': '<:lavahound:316393733539102720>',
'Bowler': '<:bowler:316393732620419083>',
'Baby Dragon': '<:babydragon:316393730016018442>',
'Miner': '<:miner:316393733216272384>',
'Electro Dragon': '<:electrodragon:471407003969781780>',
'Battle Blimp': '<:battleblimp:471407003961524224>',
'Wall Wrecker': '<:wallwrecker:471407005257564181>',
'Raged Barbarian': '<:ragedbarbarian:316393733245632522>',
'Sneaky Archer': '<:sneakyarcher:316393733421793280>',
'Beta Minion': '<:betaminion:316393733211947008>',
'Boxer Giant': '<:boxergiant:316393732645584898>',
'Bomber': '<:bomber:316393732767481868>',
'Super P.E.K.K.A': '<:superpekka:316393733488771072>',
'Cannon Cart': '<:cannoncart:316393732825939969>',
'Drop Ship': '<:dropship:316393733207621634>',
'Night Witch': '<:nightwitch:316393733409079306>',
}
global.DiscordSpellEmojis = {
'Lightning Spell': '<:lightningspell:310230391489429506>',
'Healing Spell': '<:healingspell:310230391497687042>',
'Rage Spell': '<:ragespell:310230391187308545>',
'Jump Spell': '<:jumpspell:310230391002759179>',
'Freeze Spell': '<:freezespell:310230391569252352>',
'Poison Spell': '<:poisonspell:310230391074193411>',
'Earthquake Spell': '<:earthquakespell:310230390059040769>',
'Haste Spell': '<:hastespell:310230391317331968>',
'Clone Spell': '<:clonespell:310230390407430144>',
'Skeleton Spell': '<:skeletonspell:310230391262937094>',
}
global.DiscordHeroEmojis = {
'Barbarian King': '<:barbarianking:316393776765468674>',
'Archer Queen': '<:archerqueen:316393777075978251>',
'Grand Warden': '<:grandwarden:316393831660781569>',
'Battle Machine': '<:warmachine:316393831820165122>',
}
global.Clans = {}
global.Players = {}
const StarColors = config.starColors
global.Storage = nodePersist.create()
Storage.initSync()
global.AnnounceClans = Storage.getItemSync('AnnounceClans')
AnnounceClans = cleanArray(AnnounceClans)
if (!AnnounceClans) AnnounceClans = []
Storage.setItemSync('AnnounceClans', AnnounceClans)
global.announcingClan = (clanTag) => {
let count = 0
let match
AnnounceClans.forEach(clan => {
if (clan.tag === clanTag.toUpperCase().replace(/O/g, '0')) {
match = count
}
count++
})
return match
}
global.getClanChannel = (clanTag, done) => {
AnnounceClans.forEach(clan => {
if (clan.tag === clanTag.toUpperCase().replace(/O/g, '0')) {
done(clan.channels)
}
})
}
global.getChannelClan = (channelId, done) => {
AnnounceClans.forEach(clan => {
if (clan.channels.indexOf(channelId) > -1) {
done(clan.tag)
}
})
}
global.ChannelSettings = Storage.getItemSync('ChannelSettings')
ChannelSettings = cleanArray(ChannelSettings)
if (!ChannelSettings) ChannelSettings = []
Storage.setItemSync('ChannelSettings', ChannelSettings)
global.channelSettingsInit = (channelId) => {
let found = false
ChannelSettings.forEach(channel => {
if (channel.id === channelId) {
found = true
}
})
if (!found) {
ChannelSettings.push({ id: channelId })
}
}
global.channelSettingsGet = (channelId, option) => {
let returnValue
ChannelSettings.forEach(channel => {
if (channel.id === channelId) {
returnValue = channel[option]
}
})
return returnValue
}
global.channelSettingsSet = (channelId, option, value) => {
channelSettingsInit(channelId)
ChannelSettings.forEach(channel => {
if (channel.id === channelId) {
channel[option] = value
}
})
// console.log(ChannelSettings)
ChannelSettings = cleanArray(ChannelSettings)
Storage.setItemSync('ChannelSettings', ChannelSettings)
}
global.getChannelById = (channelId, done) => {
DiscordClient.channels.forEach(channel => {
if (channel.id == channelId) done(channel)
})
done()
}
global.getAnnouncerStats = () => {
let announcerStats = {
clanCount: AnnounceClans.length
}
let channels = []
AnnounceClans.forEach(announceClan => {
announceClan.channels.forEach(channel => {
if (channels.indexOf(channel) === -1) {
channels.push(channel)
}
})
})
announcerStats.channelCount = channels.length
return announcerStats
}
global.discordAttackMessage = (warId, WarData, clanTag, opponentTag, attackData, channelId) => {
debug(clanTag)
debug(attackData)
let style = channelSettingsGet(channelId, 'style')
let styleStars = channelSettingsGet(channelId, 'styleStars')
let filter = channelSettingsGet(channelId, 'filter')
if (!style) style = 6
if (!styleStars) styleStars = false
if (!filter) filter = 'all'
let emojis = DiscordChannelEmojis
let clanPlayer
let opponentPlayer
let attackDir = 'across'
if (attackData.who === 'clan') {
clanPlayer = Players[attackData.attackerTag]
opponentPlayer = Players[attackData.defenderTag]
if (clanPlayer.townhallLevel > opponentPlayer.townhallLevel) {
attackDir = 'down'
} else if (clanPlayer.townhallLevel < opponentPlayer.townhallLevel) {
attackDir = 'up'
}
} else if (attackData.who === 'opponent') {
opponentPlayer = Players[attackData.attackerTag]
clanPlayer = Players[attackData.defenderTag]
if (clanPlayer.townhallLevel < opponentPlayer.townhallLevel) {
attackDir = 'down'
} else if (clanPlayer.townhallLevel > opponentPlayer.townhallLevel) {
attackDir = 'up'
}
} else {
return
}
if ((filter === 'attacks' && attackData.who === 'opponent') || (filter === 'defenses' && attackData.who === 'clan') || (filter === 'none')) {
return
}
let attackMessage = (attackData.stars > 0) ? emojis.dwasword : emojis.dwaswordbroken
let defendMessage = (attackData.stars > 0) ? emojis.dwashieldbroken : emojis.dwashield
if (attackData.fresh) {
attackMessage += '\uD83C\uDF43' // 🍃
}
if (attackDir === 'up') {
attackMessage += '\uD83D\uDD3A' // 🔺
} else if (attackDir === 'down') {
attackMessage += '\uD83D\uDD3B' // 🔻
}
let messageStars = emojis.dwastar.repeat(attackData.stars-attackData.newStars) + emojis.dwastarnew.repeat(attackData.newStars) + emojis.dwastarempty.repeat(3 - attackData.stars)
let embed
let text
// \u200e = LEFT-TO-RIGHT MARK
if (style === 1) {
text = ''
text += DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + clanPlayer.name + '\u200e ' + ((attackData.who === 'clan') ? attackMessage : defendMessage)
text += messageStars + ' ' + attackData.destructionPercentage + '%'
text += ((attackData.who === 'clan') ? defendMessage : attackMessage) + ' ' + opponentPlayer.name + '\u200e ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1]
} else if (style === 2) {
text = ''
text += clanPlayer.name + '\u200e [' + clanPlayer.mapPosition + '] ' + DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + ((attackData.who === 'clan') ? attackMessage : defendMessage)
text += messageStars + ' ' + attackData.destructionPercentage + '%'
text += ((attackData.who === 'clan') ? defendMessage : attackMessage) + ' ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1] + ' [' + opponentPlayer.mapPosition + '] ' + opponentPlayer.name
} else if (style === 3) {
embed = new Discord.RichEmbed()
.setColor(StarColors[attackData.stars])
.addField(clanPlayer.name, (attackData.who === 'clan') ? attackMessage : defendMessage, true)
.addField(DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + clanPlayer.mapPosition + ' vs ' + opponentPlayer.mapPosition + ' ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1], messageStars + '\n\t\t' + attackData.destructionPercentage + '%', true)
.addField(opponentPlayer.name, (attackData.who === 'clan') ? defendMessage : attackMessage, true)
} else if (style === 4) {
attackMessage += '\n' + attackData.attackerTag
defendMessage += '\n' + attackData.defenderTag
embed = new Discord.RichEmbed()
.setColor(StarColors[attackData.stars])
.addField(clanPlayer.name, (attackData.who === 'clan') ? attackMessage : defendMessage, true)
.addField(DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + clanPlayer.mapPosition + ' vs ' + opponentPlayer.mapPosition + ' ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1], messageStars + '\n\t\t' + attackData.destructionPercentage + '%', true)
.addField(opponentPlayer.name, (attackData.who === 'clan') ? defendMessage : attackMessage, true)
} else if (style === 5) {
attackMessage += '\n'
defendMessage += '\n'
attackMessage += (attackData.who === 'clan') ? WarData.stats.clan.name : WarData.stats.opponent.name
defendMessage += (attackData.who === 'clan') ? WarData.stats.opponent.name : WarData.stats.clan.name
embed = new Discord.RichEmbed()
.setColor(StarColors[attackData.stars])
.addField(clanPlayer.name, (attackData.who === 'clan') ? attackMessage : defendMessage, true)
.addField(DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + clanPlayer.mapPosition + ' vs ' + opponentPlayer.mapPosition + ' ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1], messageStars + '\n\t\t' + attackData.destructionPercentage + '%', true)
.addField(opponentPlayer.name, (attackData.who === 'clan') ? defendMessage : attackMessage, true)
} else if (style === 6) {
attackMessage += '\n' + attackData.attackerTag
defendMessage += '\n' + attackData.defenderTag
embed = new Discord.RichEmbed()
.setColor(StarColors[attackData.stars])
.addField(clanPlayer.name, (attackData.who === 'clan') ? attackMessage : defendMessage, true)
.addField(DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + clanPlayer.mapPosition + ' vs ' + opponentPlayer.mapPosition + ' ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1], messageStars + '\n\t\t' + attackData.destructionPercentage + '%', true)
.addField(opponentPlayer.name, (attackData.who === 'clan') ? defendMessage : attackMessage, true)
.addField(WarData.stats.clan.name, WarData.stats.clan.tag, true)
.addField('\u200b', '\u200b', true)
.addField(WarData.stats.opponent.name, WarData.stats.opponent.tag, true)
} else if (style === 7) {
if (attackData.who === 'opponent') {
text = ''
text += '!wm ' + clanPlayer.mapPosition + 'd'
text += opponentPlayer.mapPosition + ' '
text += attackData.stars + ' ' + attackData.destructionPercentage
}
else if (attackData.who === 'clan'){
text = ''
text += '!wm ' + clanPlayer.mapPosition + 'a'
text += opponentPlayer.mapPosition + ' '
text += attackData.stars + ' ' + attackData.destructionPercentage
}
} else if (style === 8) {
if (attackData.who === 'opponent') {
text = ''
text += 'wm ' + clanPlayer.mapPosition + 'd'
text += opponentPlayer.mapPosition + ' '
text += attackData.stars + ' ' + attackData.destructionPercentage
}
else if (attackData.who === 'clan'){
text = ''
text += 'wm ' + clanPlayer.mapPosition + 'a'
text += opponentPlayer.mapPosition + ' '
text += attackData.stars + ' ' + attackData.destructionPercentage
}
} else if (style === 9) {
attackMessage += '\n' + attackData.attackerTag
defendMessage += '\n' + attackData.defenderTag
embed = new Discord.RichEmbed()
.setImage((attackData.who === 'clan') ? WarData.stats.clan.badge.small : WarData.stats.opponent.badge.small)
.setColor(StarColors[attackData.stars])
.addField(clanPlayer.name, (attackData.who === 'clan') ? attackMessage : defendMessage, true)
.addField(DiscordTownHallEmojis[clanPlayer.townhallLevel - 1] + ' ' + clanPlayer.mapPosition + ' vs ' + opponentPlayer.mapPosition + ' ' + DiscordTownHallEmojis[opponentPlayer.townhallLevel - 1], messageStars + '\n\t\t' + attackData.destructionPercentage + '%', true)
.addField(opponentPlayer.name, (attackData.who === 'clan') ? defendMessage : attackMessage, true)
.addField(WarData.stats.clan.name, WarData.stats.clan.tag, true)
.addField('\u200b', '\u200b', true)
.addField(WarData.stats.opponent.name, WarData.stats.opponent.tag, true)
}
if (styleStars && style > 2) {
embed
.addField(WarData.stats.clan.attacks + '/' + WarData.stats.clan.memberCount * 2 + ' ' + emojis.dwasword, WarData.stats.clan.destructionPercentage + '%', true)
.addField(WarData.stats.clan.memberCount + ' v ' + WarData.stats.opponent.memberCount, WarData.stats.clan.stars + ' ' + emojis.dwastarnew + ' vs ' + emojis.dwastarnew + ' ' + WarData.stats.opponent.stars, true)
.addField(WarData.stats.opponent.attacks + '/' + WarData.stats.opponent.memberCount * 2 + ' ' + emojis.dwasword, WarData.stats.opponent.destructionPercentage + '%', true)
} else if (styleStars) {
text += '\n'
text += WarData.stats.clan.destructionPercentage + '% '
text += WarData.stats.clan.stars + ' ' + emojis.dwastarnew + ' vs ' + emojis.dwastarnew + ' ' + WarData.stats.opponent.stars
text += WarData.stats.opponent.destructionPercentage + '%'
}
WarData.lastReportedAttack = attackData.order
ClanStorage.setItemSync(warId, WarData)
getChannelById(channelId, discordChannel => {
if (discordChannel && embed) discordChannel.send({embed}).then(debug).catch(log)
if (discordChannel && text) discordChannel.send(text).then(debug).catch(log)
})
}
global.discordHitrateMessage = (WarData, channelId) => {
debug(WarData)
if (WarData.stats.state === 'inWar' || WarData.stats.state === 'warEnded') {
let emojis = DiscordChannelEmojis
const embed = new Discord.RichEmbed()
.setTitle('Attack Hitrate')
.setFooter(WarData.stats.clan.tag + ' vs ' + WarData.stats.opponent.tag)
.setColor(0x007cff)
for (let th = 3; th <= 11; th++) {
if (WarData.stats.hitrate['TH' + th + 'v' + th].clan.attempt > 0 || WarData.stats.hitrate['TH' + th + 'v' + th].opponent.attempt > 0) {
let clanHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + th].clan.attempt > 0) clanHitRate = WarData.stats.hitrate['TH' + th + 'v' + th].clan.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + th].clan.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + th].clan.success / WarData.stats.hitrate['TH' + th + 'v' + th].clan.attempt * 100, 2) + '%'
let opponentHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + th].opponent.attempt > 0) opponentHitRate = WarData.stats.hitrate['TH' + th + 'v' + th].opponent.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + th].opponent.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + th].opponent.success / WarData.stats.hitrate['TH' + th + 'v' + th].opponent.attempt * 100, 2) + '%'
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th-1], clanHitRate, true)
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th-1], opponentHitRate, true)
embed.addBlankField(true)
}
if (th === 9) {
if (WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt > 0 || WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt > 0) {
let clanHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt > 0) clanHitRate = WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.success / WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt * 100, 2) + '%'
let opponentHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt > 0) opponentHitRate = WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.success / WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt * 100, 2) + '%'
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th], clanHitRate, true)
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th], opponentHitRate, true)
embed.addBlankField(true)
}
}
if (th === 10) {
if (WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt > 0 || WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt > 0) {
let clanHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt > 0) clanHitRate = WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.success / WarData.stats.hitrate['TH' + th + 'v' + (th+1)].clan.attempt * 100, 2) + '%'
let opponentHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt > 0) opponentHitRate = WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.success / WarData.stats.hitrate['TH' + th + 'v' + (th+1)].opponent.attempt * 100, 2) + '%'
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th], clanHitRate, true)
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th], opponentHitRate, true)
embed.addBlankField(true)
}
}
if (th === 11) {
if (WarData.stats.hitrate['TH' + th + 'v' + (th-1)].clan.attempt > 0 || WarData.stats.hitrate['TH' + th + 'v' + (th-1)].opponent.attempt > 0) {
let clanHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + (th-1)].clan.attempt > 0) clanHitRate = WarData.stats.hitrate['TH' + th + 'v' + (th-1)].clan.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + (th-1)].clan.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + (th-1)].clan.success / WarData.stats.hitrate['TH' + th + 'v' + (th-1)].clan.attempt * 100, 2) + '%'
let opponentHitRate = 'n/a'
if (WarData.stats.hitrate['TH' + th + 'v' + (th-1)].opponent.attempt > 0) opponentHitRate = WarData.stats.hitrate['TH' + th + 'v' + (th-1)].opponent.success + '/' + WarData.stats.hitrate['TH' + th + 'v' + (th-1)].opponent.attempt + ' - ' + Math.round(WarData.stats.hitrate['TH' + th + 'v' + (th-1)].opponent.success / WarData.stats.hitrate['TH' + th + 'v' + (th-1)].opponent.attempt * 100, 2) + '%'
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th-2], clanHitRate, true)
embed.addField(DiscordTownHallEmojis[th-1] + ' vs ' + DiscordTownHallEmojis[th-2], opponentHitRate, true)
embed.addBlankField(true)
}
}
}
embed.addField(WarData.stats.clan.name + ' vs ' + WarData.stats.opponent.name, '\u200b')
getChannelById(channelId, discordChannel => {
if (discordChannel) discordChannel.send({embed}).then(debug).catch(log)
})
} else {
getChannelById(channelId, discordChannel => {
if (discordChannel) discordChannel.send('No hitrate stats for this war check back later.').then(debug).catch(log)
})
}
}
global.discordStatsMessage = (WarData, channelId) => {
debug(WarData)
let emojis = DiscordChannelEmojis
let extraMessage = ''
if (WarData.stats.state === 'preparation') {
extraMessage = '\nWar starts ' + moment(WarData.stats.startTime).fromNow()
} else if (WarData.stats.state === 'inWar') {
extraMessage = '\nWar ends ' + moment(WarData.stats.endTime).fromNow()
} else if (WarData.stats.state === 'warEnded') {
extraMessage = '\nWar ended ' + moment(WarData.stats.endTime).fromNow()
}
const embed = new Discord.RichEmbed()
.setFooter(WarData.stats.clan.tag + ' vs ' + WarData.stats.opponent.tag)
.setColor(0x007cff)
.addField(WarData.stats.clan.attacks + '/' + WarData.stats.clan.memberCount * 2 + ' ' + emojis.dwasword, WarData.stats.clan.destructionPercentage + '%', true)
.addField(WarData.stats.clan.memberCount + ' v ' + WarData.stats.opponent.memberCount, WarData.stats.clan.stars + ' ' + emojis.dwastarnew + ' vs ' + emojis.dwastarnew + ' ' + WarData.stats.opponent.stars, true)
.addField(WarData.stats.opponent.attacks + '/' + WarData.stats.opponent.memberCount * 2 + ' ' + emojis.dwasword, WarData.stats.opponent.destructionPercentage + '%', true)
.addField(WarData.stats.clan.name + ' vs ' + WarData.stats.opponent.name, extraMessage)
getChannelById(channelId, discordChannel => {
if (discordChannel) discordChannel.send({embed}).then(debug).catch(log)
})
}
global.discordMissingAttackMessage = (clanTag, channelId, PlayersMissingAtack) => {
debug(clanTag)
let showmissing = channelSettingsGet(channelId, 'showmissing')
if (!showmissing) showmissing = 'no'
if (showmissing === 'yes' && PlayersMissingAtack.length > 0) {
PlayersMissingAtack.forEach(member => {
const embed = new Discord.RichEmbed()
.setTitle(Clans[clanTag].name + ' vs ' + Clans[clanTag].opponent.name)
.setFooter(clanTag + ' vs ' + Clans[clanTag].opponent.tag)
if (!member.attacks) {
embed.addField(member.name + " is missing 2 attacks!!!", member.tag)
.setColor(0xFF484E)
} else {
if (member.attacks.length != 2) {
embed.addField(member.name + " is missing 1 attack!", member.tag)
.setColor(0xFFBC48)
}
}
getChannelById(channelId, discordChannel => {
if (discordChannel) discordChannel.send({ embed }).then(debug).catch(log)
})
})
}
}
global.discordReportMessage = (warId, WarData, clanTag, message, channelId) => {
debug(clanTag)
let emojis = DiscordChannelEmojis
let clanPlayer
let opponentPlayer
// log(WarData)
// log(Clans[clanTag])
const embed = new Discord.RichEmbed()
.setTitle(Clans[clanTag].name + ' vs ' + Clans[clanTag].opponent.name)
.setFooter(clanTag + ' vs ' + Clans[clanTag].opponent.tag)
.setColor(message.color)
.addField(message.title, message.body)
ClanStorage.setItemSync(warId, WarData)
getChannelById(channelId, discordChannel => {
if (discordChannel) discordChannel.send({embed}).then(debug).catch(log)
})
}
global.getAnnouncingChannels = () => {
let channelIds = []
AnnounceClans.forEach(clan => {
clan.channels.forEach(channelId => {
if (channelIds.indexOf(channelId) < 0) channelIds.push(channelId)
})
})
return channelIds
}
let playerReport = (channel, data) => {
debug(data)
let embed = new Discord.RichEmbed()
.setAuthor(data.name + '\u200e ' + data.tag, (data.league) ? data.league.iconUrls.small : null)
.setThumbnail('https://coc.guide/static/imgs/other/town-hall-' + data.townHallLevel + '.png')
if (data.clan) embed.setFooter(data.role + ' of ' + data.clan.name + '\u200e ' + data.clan.tag, data.clan.badgeUrls.small)
embed.addField('League', (data.league) ? data.league.name : 'n/a', true)
embed.addField('Trophies', data.trophies , true)
embed.addField('War Stars', data.warStars , true)
embed.addField('Best Trophies', data.bestTrophies, true)
let troopLevels = ''
let count = 0
data.troops.forEach(troop => {
if (troop.village === 'home') {
count++
troopLevels += DiscordTroopEmojis[troop.name] + ' ' + troop.level
if (count > 0 && count % 8 === 0) {
if (troop.level === troop.maxLevel) {
troopLevels += '*\n'
} else {
troopLevels += '\n'
}
} else {
if (troop.level === troop.maxLevel) {
troopLevels += '*\u2002'
} else {
troopLevels += '\u2002\u2002'
}
}
}
})
if (troopLevels) embed.addField('Troop Levels', troopLevels.slice(0, troopLevels.length - 2))
let spellLevels = ''
count = 0
data.spells.forEach(spell => {
if (spell.village === 'home') {
count++
spellLevels += DiscordSpellEmojis[spell.name] + ' ' + spell.level
if (count > 0 && count % 8 === 0) {
if (spell.level === spell.maxLevel) {
spellLevels += '*\n'
} else {
spellLevels += '\n'
}
} else {
if (spell.level === spell.maxLevel) {
spellLevels += '*\u2002'
} else {
spellLevels += '\u2002\u2002'
}
}
}
})
if (spellLevels) embed.addField('Spell Levels', spellLevels.slice(0, spellLevels.length - 2))
let heroLevels = ''
count = 0
data.heroes.forEach(hero => {
if (hero.village === 'home') {
count++
heroLevels += DiscordHeroEmojis[hero.name] + ' ' + hero.level
if (count > 0 && count % 8 === 0) {
if (hero.level === hero.maxLevel) {
heroLevels += '*\n'
} else {
heroLevels += '\n'
}
} else {
if (hero.level === hero.maxLevel) {
heroLevels += '*\u2002'
} else {
heroLevels += '\u2002\u2002'
}
}
}
})
if (heroLevels) embed.addField('Hero Levels', heroLevels.slice(0, heroLevels.length - 2))
if (data.builderHallLevel) {
embed.addField('Builder Hall Level', DiscordBuilderHallEmojis[data.builderHallLevel - 1] + ' ' + data.builderHallLevel, true)
embed.addField('Versus Trophies', data.versusTrophies , true)
embed.addField('Versus Battle Wins', data.versusBattleWins , true)
embed.addField('Best Versus Trophies', data.bestVersusTrophies , true)
let troopLevels = ''
let count = 0
data.troops.forEach(troop => {
if (troop.village === 'builderBase') {
count++
troopLevels += DiscordTroopEmojis[troop.name] + ' ' + troop.level
if (count > 0 && count % 8 === 0) {
if (troop.level === troop.maxLevel) {
troopLevels += '*\n'
} else {
troopLevels += '\n'
}
} else {
if (troop.level === troop.maxLevel) {
troopLevels += '*\u2002'
} else {
troopLevels += '\u2002\u2002'
}
}
}
})
if (troopLevels) embed.addField('Troop Levels', troopLevels.slice(0, troopLevels.length - 2))
let spellLevels = ''
count = 0
data.spells.forEach(spell => {
if (spell.village === 'builderBase') {
count++
spellLevels += DiscordSpellEmojis[spell.name] + ' ' + spell.level
if (count > 0 && count % 8 === 0) {
if (spell.level === spell.maxLevel) {
spellLevels += '*\n'
} else {
spellLevels += '\n'
}
} else {
if (spell.level === spell.maxLevel) {
spellLevels += '*\u2002'
} else {
spellLevels += '\u2002\u2002'
}
}
}
})
if (spellLevels) embed.addField('Spell Levels', spellLevels.slice(0, spellLevels.length - 2))
let heroLevels = ''
count = 0
data.heroes.forEach(hero => {
if (hero.village === 'builderBase') {
count++
heroLevels += DiscordHeroEmojis[hero.name] + ' ' + hero.level
if (count > 0 && count % 8 === 0) {
if (hero.level === hero.maxLevel) {
heroLevels += '*\n'
} else {
heroLevels += '\n'
}
} else {
if (hero.level === hero.maxLevel) {
heroLevels += '*\u2002'
} else {
heroLevels += '\u2002\u2002'
}
}
}
})
if (heroLevels) embed.addField('Hero Levels', heroLevels.slice(0, heroLevels.length - 2))
}
channel.send({embed}).then(debug).catch(log)
}
let discordReady = () => {
let apiRequest = (task, cb) => {
get.concat({
url: task.url,
method: 'GET',
headers: {
'authorization': 'Bearer ' + config.coc.apiKey,
'Cache-Control':'no-cache'
}
}, function (err, res, jsonBuffer) {
cb()
if (jsonBuffer.length > 0) {
let data = JSON.parse(jsonBuffer)
task.done(data)
} else {
task.done(false)
}
})
}
global.apiQueue = async.queue(apiRequest, config.asyncLimit)
let getCurrentWar = (clanTag, done = () => {}) => {
apiQueue.push({
url: COC_API_BASE + '/clans/' + encodeURIComponent(clanTag) + '/currentwar',
done: done
})
}
let getWarLog = (clanTag, done = () => {}) => {
apiQueue.push({
url: COC_API_BASE + '/clans/' + encodeURIComponent(clanTag) + '/warlog',
done: done
})
}
global.getPlayer = (playerTag, done = () => {}) => {
playerTag = playerTag.toUpperCase().replace(/O/g, '0')
if (playerTag.match(/^#[0289PYLQGRJCUV]+$/)) {
apiQueue.push({
url: COC_API_BASE + '/players/' + encodeURIComponent(playerTag),
done: done
})
} else {
done('Invalid Tag')
}
}
async.each(AnnounceClans, (clan, done) => {
try {
let newClan = new Clan(clan.tag)
// console.log(newClan)
clan.channels.forEach(id => {
newClan.addChannel(id)
})
newClan.fetchCurrentWar(apiQueue, done)
Clans[newClan.getTag()] = newClan
} catch (err) {
if (err === 'missingTag') {
console.log('Attempted to create a Clan() with no tag.')
} else if (err === 'emptyTag') {
console.log('Attempted to create a Clan() with an empty string.')
} else {
console.log(err)
}
}
}, function(err) {
setTimeout(discordReady, 1000 * config.updateInterval)
})
}
DiscordClient.on('message', message => {
let messageContent = message.content.trim()
let prefix = config.commandPrefix || '!'
if (messageContent.slice(0, 1) === prefix) {
let channelId = message.channel.id
let splitMessage = messageContent.split(' ')
if (splitMessage[0].toLowerCase() === prefix + 'info') {
let announcerStats = getAnnouncerStats()
const embed = new Discord.RichEmbed()
.setFooter('Announcing wars since April 29th 2017 (' + moment('2017-04-29').fromNow() + ')')
.setColor(0x007cff)
.addField('Instance Owned By', '<@' + config.owner + '>', true)
.addField('Node Version', '[' + process.version + '](https://nodejs.org)', true)
.addField('Discord.JS Version', '[' + Discord.version + '](https://github.com/hydrabolt/discord.js)', true)
.addField('Tracking Stats', 'Announcing stats for ' + announcerStats.clanCount + ' clan' + ((announcerStats.clanCount != 1) ? 's' : '') + ' across ' + announcerStats.channelCount + ' channel' + ((announcerStats.channelCount != 1) ? 's' : ''))
.addField('Load Average', os.loadavg(10), true)
.addField('Process Started', moment().subtract(os.processUptime(), 's').fromNow(), true)
.addField('Free Memory', Math.round(os.freemem()) + 'MB', true)
.addField('Clash of Clans War Announcer', 'This is an instance of [Discord CoC War Announcer](https://github.com/spAnser/discord-coc-war-announcer). A node.js discord bot written to monitor the Clash of Clans API and announce war attacks to a discord channel.')
message.channel.send({embed}).then(debug).catch(log)
} else if (splitMessage[0].toLowerCase() === prefix + 'help') {
let helpMessage = '1. `' + prefix + 'announce #CLANTAG` Assign a clan to announce in a channel.\n'
helpMessage += '2. `' + prefix + 'unannounce #CLANTAG` Stop a clan from announcing in a channel.\n'
helpMessage += '3. `' + prefix + 'warstats #CLANTAG` Display war stats for a clan that is tracked by The Announcer. If not provided with a clan tag it will display war stats for all clans assigned to the channel the command was run in.\n'
helpMessage += '4. `' + prefix + 'hitrate #CLANTAG` Display hit rate stats for a clan that is tracked by The Announcer. If not provided with a clan tag it will display hit rate stats for all clans assigned to the channel the command was run in.\n'
helpMessage += '5. `' + prefix + 'playerstats #PLAYERTAG` Display player stats for any player tag provided.\n'
helpMessage += '6. `' + prefix + 'style [1-9](+)` Choose a style to use for war attacks in this channel. Requires a number to select style type, optionally append a `+` if you want war stats included in every message.\n'
helpMessage += '7. `' + prefix + 'filter all,attacks,defenses,none` Not yet implemented\n'
// helpMessage += '7. `' + prefix + 'filter all,attacks,defenses,none` Filter which attacks show up in the channel.\n'
helpMessage += '8. `' + prefix + 'info` Display bot information.\n'
helpMessage += '9. `' + prefix + 'identify` bot as clan member (!identify #aaaaaaa).\n'
helpMessage += '10. `' + prefix + 'showmissing yes,no` Show missing attacks with final hours and final minutes messages. Default value is no.\n'
message.channel.send(helpMessage).then(debug).catch(log)
} else if (splitMessage[0].toLowerCase() === prefix + 'announce') {
if (message.member.hasPermission('MANAGE_CHANNELS')) {
if (splitMessage[1]) {
let clanTag = splitMessage[1].toUpperCase().replace(/O/g, '0')
if (clanTag.match(/^#[0289PYLQGRJCUV]+$/)) {
if (!Clans[clanTag]) {
let newClan = new Clan(clanTag)
newClan.addChannel(message.channel.id)
newClan.fetchCurrentWar(apiQueue)
Clans[newClan.getTag()] = newClan
} else {
Clans[clanTag].addChannel(message.channel.id)
}
let announcingIndex = announcingClan(clanTag)
if (typeof announcingIndex === 'undefined') {
AnnounceClans.push({
tag: clanTag,
channels: [
channelId
]
})
message.channel.send('War announcements for ' + clanTag + ' registered in this channel.').then(debug).catch(log)
} else {
if (AnnounceClans[announcingIndex].channels.indexOf(channelId) > -1) {
message.channel.send('Provided clanTag is already registered to this channel.').then(debug).catch(log)
} else {
AnnounceClans[announcingIndex].channels.push(channelId)
message.channel.send('War announcements for ' + clanTag + ' registered in this channel.').then(debug).catch(log)
}
}
AnnounceClans = cleanArray(AnnounceClans)
Storage.setItemSync('AnnounceClans', AnnounceClans)
} else {
message.channel.send('Please provide a valid clan tag to announce. Valid tag characters are: \n```\n0289PYLQGRJCUV\n```').then(debug).catch(log)
}
} else {
message.channel.send('Please provide a clan tag to start announcements for.\n```\n!announce #clanTag\n```').then(debug).catch(log)
}
} else {
message.channel.send('Someone with the permissions to manage channels needs to run that command.').then(debug).catch(log)
}
} else if (splitMessage[0].toLowerCase() === prefix + 'unannounce') {
if (message.member.hasPermission('MANAGE_CHANNELS')) {
if (splitMessage[1]) {
let clanTag = splitMessage[1].toUpperCase().replace(/O/g, '0')
let announcingIndex = announcingClan(clanTag)
if (typeof announcingIndex !== 'undefined') {
let channelIndex = AnnounceClans[announcingIndex].channels.indexOf(channelId)
if (channelIndex > -1) {
if (AnnounceClans[announcingIndex].channels.length > 1) {
let tmpChannels = []
AnnounceClans[announcingIndex].channels.forEach(cId => {
if (cId != channelId) {
tmpChannels.push(cId)
}
})
AnnounceClans[announcingIndex].channels = tmpChannels
} else {
let tmpAnnounceClans = []
Object.keys(AnnounceClans).forEach(aId => {
if (aId != announcingIndex) {
tmpAnnounceClans[aId] = AnnounceClans[aId]
}
})
AnnounceClans = tmpAnnounceClans
}
message.channel.send('War announcements for ' + clanTag + ' have been stopped in this channel.').then(debug).catch(log)
} else {
message.channel.send('War announcements for ' + clanTag + ' were not registered in this channel.').then(debug).catch(log)
}
if (Clans[clanTag]) {
Clans[clanTag].removeChannel(channelId)
}
}
AnnounceClans = cleanArray(AnnounceClans)
Storage.setItemSync('AnnounceClans', AnnounceClans)
} else {
message.channel.send('Please provide a clan tag to stop announcements for.\n```\n!unannounce #clanTag\n```').then(debug).catch(log)
}
} else {
message.channel.send('Someone with the permissions to manage channels needs to run that command.').then(debug).catch(log)
}
} else if (splitMessage[0].toLowerCase() === prefix + 'warstats') {
if (splitMessage[1]) {
let clanTag = splitMessage[1].toUpperCase().replace(/O/g, '0')
if (Clans[clanTag]) {
let WarData = Clans[clanTag].getWarData()
let AnnouncingClan = AnnounceClans[announcingClan(clanTag)]
if (WarData) {
discordStatsMessage(WarData, channelId)
} else if (AnnouncingClan.state === 'notInWar') {
message.channel.send(clanTag + ' is not currently in war.').then(debug).catch(log)
} else if (AnnouncingClan.reason === 'accessDenied') {
message.channel.send(clanTag + '\'s war log is not public.').then(debug).catch(log)
} else {
message.channel.send('War data is missing try again in a little bit. I might still be fetching the data.').then(debug).catch(log)
}
} else {
message.channel.send('I don\'t appear to have any war data for that clan.').then(debug).catch(log)
}
} else {
getChannelClan(channelId, clanTag => {
let WarData = Clans[clanTag].getWarData()
let AnnouncingClan = AnnounceClans[announcingClan(clanTag)]
if (WarData) {
discordStatsMessage(WarData, channelId)
} else if (AnnouncingClan.state === 'notInWar') {
message.channel.send(clanTag + ' is not currently in war.').then(debug).catch(log)
} else if (AnnouncingClan.reason === 'accessDenied') {
message.channel.send(clanTag + '\'s war log is not public.').then(debug).catch(log)
} else {
message.channel.send('War data is missing try again in a little bit. I might still be fetching the data.').then(debug).catch(log)
}
})
}
} else if (splitMessage[0].toLowerCase() === prefix + 'hitrate') {
if (splitMessage[1]) {
let clanTag = splitMessage[1].toUpperCase().replace(/O/g, '0')
if (Clans[clanTag]) {
let clanTag = splitMessage[1]
let WarData = Clans[clanTag].getWarData()
let AnnouncingClan = AnnounceClans[announcingClan(clanTag)]
if (WarData) {
discordHitrateMessage(WarData, channelId)
} else if (AnnouncingClan.state === 'notInWar') {
message.channel.send(clanTag + ' is not currently in war.').then(debug).catch(log)
} else if (AnnouncingClan.reason === 'accessDenied') {
message.channel.send(clanTag + '\'s war log is not public.').then(debug).catch(log)
} else {
message.channel.send('War data is missing try again in a little bit. I might still be fetching the data.').then(debug).catch(log)
}
} else {
message.channel.send('I don\'t appear to have any war data for that clan.').then(debug).catch(log)
}
} else {
getChannelClan(channelId, clanTag => {
let WarData = Clans[clanTag].getWarData()
if (WarData) {
discordHitrateMessage(WarData, channelId)
} else {
message.channel.send('War data is missing try again in a little bit. I might still be fetching the data.').then(debug).catch(log)
}
})
}
} else if (splitMessage[0].toLowerCase() === prefix + 'playerstats') {
if (splitMessage[1]) {
getPlayer(splitMessage[1], data => {
if (data === 'Invalid Tag') {
message.channel.send('Please provide a valid player tag to look up. Valid tag characters are: \n```\n0289PYLQGRJCUV\n```').then(debug).catch(log)
} else if (data && !data.hasOwnProperty('reason')) {
playerReport(message.channel, data)
} else {
message.channel.send('There was an error fetching the player data.')
// TODO: include the error code and reason in the returned response to the user for easier troubleshooting
}
})
} else {
message.channel.send('Please provide a player tag to look up.\n```\n' + prefix + 'playerstats #playertag\n```').then(debug).catch(log)
}
} else if (splitMessage[0].toLowerCase() === prefix + 'filter') {
if (splitMessage[1] && (splitMessage[1].toLowerCase() === 'all' || splitMessage[1].toLowerCase() === 'attacks' || splitMessage[1].toLowerCase() === 'defenses' || splitMessage[1].toLowerCase() === 'none')) {
channelSettingsSet(message.channel.id, 'filter', splitMessage[1].toLowerCase())
if (splitMessage[1].toLowerCase() === 'all') {
message.channel.send('Announcer will now announce everything.')
} else if (splitMessage[1].toLowerCase() === 'attacks') {
message.channel.send('Announcer will now announce attacks only.')
} else if (splitMessage[1].toLowerCase() === 'defenses') {
message.channel.send('Announcer will now announce defenses only.')
} else if (splitMessage[1].toLowerCase() === 'none') {
message.channel.send('Announcer will now announce nothing.')
}
} else {
message.channel.send('Please choose a valid filter method `all, attacks, defenses, none`.')
}
} else if (splitMessage[0].toLowerCase() === prefix + 'showmissing') {
if (splitMessage[1] && (splitMessage[1].toLowerCase() === 'yes' || splitMessage[1].toLowerCase() === 'no')) {
channelSettingsSet(message.channel.id, 'showmissing', splitMessage[1].toLowerCase())
if (splitMessage[1].toLowerCase() === 'yes') {
message.channel.send('Announcer will now announce missing attacks with final hours and final minutes messages.')
} else if (splitMessage[1].toLowerCase() === 'no') {
message.channel.send('Announcer will now NOT announce missing attacks with final hours and final minutes messages.')
}
} else {
message.channel.send('Please choose a valid showmissing method `yes, no`.')
}
} else if (splitMessage[0].toLowerCase() === prefix + 'identify') {
if (splitMessage[1]) {
let identID = splitMessage[1]
message.channel.send('!wm identify ' + identID).then(debug).catch(log)
} else {
message.channel.send('error').then(debug).catch(log)
}
} else if (splitMessage[0].toLowerCase() === prefix + 'style') {
if (message.member.hasPermission('MANAGE_CHANNELS')) {
if (splitMessage[1]) {
let showStars = (splitMessage[1].indexOf('+') == 1)
let styleId = parseInt(splitMessage[1])
if (styleId > 0 && styleId < 10) {
channelSettingsSet(message.channel.id, 'style', styleId)
channelSettingsSet(message.channel.id, 'styleStars', showStars)
let extra = (showStars) ? ' w/ War Stats' : ''
message.channel.send('This channel will now announce attacks with style #' + styleId + extra).then(debug).catch(log)
} else {
message.channel.send('Invalid style id choose a number between 1-9').then(debug).catch(log)
}
} else {
message.channel.send('Please provide a style id to use for this channel.\n```\n' + prefix + 'style [1-8](+)\n```').then(debug).catch(log)
}
} else {
message.channel.send('Someone with the permissions to manage channels needs to run that command.').then(debug).catch(log)
}
} else if (splitMessage[0].toLowerCase() === prefix + 'styletest') {
let emojis = DiscordChannelEmojis
let text
let embed
message.channel.send('***Style #1***').then(debug).catch(log)
text = ''
text += DiscordTownHallEmojis[9] + ' Player Name ' + emojis.dwasword
text += emojis.dwastar.repeat(1) + emojis.dwastarnew.repeat(1) + emojis.dwastarempty.repeat(1) + ' ' + '75%'
text += emojis.dwashieldbroken + ' Opponent Name ' + DiscordTownHallEmojis[10]
message.channel.send(text).then(debug).catch(log)
message.channel.send('***Style #2***').then(debug).catch(log)
text = ''
text += 'Player Name [6] ' + DiscordTownHallEmojis[9] + ' ' + emojis.dwasword + '\uD83C\uDF43\uD83D\uDD3A'
text += emojis.dwastar.repeat(1) + emojis.dwastarnew.repeat(1) + emojis.dwastarempty.repeat(1) + ' ' + '75%'
text += emojis.dwashieldbroken + ' ' + DiscordTownHallEmojis[10] + ' [5] Opponent Name'
message.channel.send(text).then(debug).catch(log)
message.channel.send('***Style #3***').then(debug).catch(log)
embed = new Discord.RichEmbed()
.setColor(StarColors[2])
.addField('Player Name', emojis.dwasword + '\uD83C\uDF43\uD83D\uDD3A', true)
.addField(DiscordTownHallEmojis[9] + ' 6 vs 5 ' + DiscordTownHallEmojis[10], emojis.dwastar.repeat(1) + emojis.dwastarnew.repeat(1) + emojis.dwastarempty.repeat(1), true)
.addField('Opponent Name', emojis.dwashieldbroken + ' 75%', true)
message.channel.send({embed}).then(debug).catch(log)
message.channel.send('***Style #4***').then(debug).catch(log)
embed = new Discord.RichEmbed()
.setColor(StarColors[2])
.addField('Player Name', emojis.dwasword + '\uD83C\uDF43\uD83D\uDD3A\n#playerTag', true)
.addField(DiscordTownHallEmojis[9] + ' 6 vs 5 ' + DiscordTownHallEmojis[10], emojis.dwastar.repeat(1) + emojis.dwastarnew.repeat(1) + emojis.dwastarempty.repeat(1) + '\n\t\t' + '75%', true)
.addField('Opponent Name', emojis.dwashieldbroken + '\n#opponentTag', true)
message.channel.send({embed}).then(debug).catch(log)
message.channel.send('***Style #5***').then(debug).catch(log)
embed = new Discord.RichEmbed()
.setColor(StarColors[2])
.addField('Player Name', emojis.dwasword + '\uD83C\uDF43\uD83D\uDD3A\nClan Name', true)
.addField(DiscordTownHallEmojis[9] + ' 6 vs 5 ' + DiscordTownHallEmojis[10], emojis.dwastar.repeat(1) + emojis.dwastarnew.repeat(1) + emojis.dwastarempty.repeat(1) + '\n\t\t' + '75%', true)
.addField('Opponent Name', emojis.dwashieldbroken + '\nOpponent Clan Name', true)
message.channel.send({embed}).then(debug).catch(log)
message.channel.send('***Style #6 (default)***').then(debug).catch(log)
embed = new Discord.RichEmbed()
.setColor(StarColors[2])
.addField('Player Name', emojis.dwasword + '\uD83C\uDF43\uD83D\uDD3A\n#playerTag', true)
.addField(DiscordTownHallEmojis[9] + ' 6 vs 5 ' + DiscordTownHallEmojis[10], emojis.dwastar.repeat(1) + emojis.dwastarnew.repeat(1) + emojis.dwastarempty.repeat(1) + '\n\t\t' + '75%', true)
.addField('Opponent Name', emojis.dwashieldbroken + '\n#opponentTag', true)
.addField('Clan Name', '#clanTag', true)
.addField('\u200b', '\u200b', true)
.addField('Opponent Clan Name', '#opponentClanTag', true)
message.channel.send({embed}).then(debug).catch(log)
} else if (splitMessage[0].toLowerCase() === prefix + 'news' && message.author.id === config.owner) {
// Send global announcement to announcing channels from the bot owner. Will mainly be used for updates.
getAnnouncingChannels().forEach(channelId => {
getChannelById(channelId, discordChannel => {
if (discordChannel) discordChannel.send(splitMessage.slice(1).join(' ')).then(debug).catch(log)
})
})
}
}
})
DiscordClient.on('ready', () => {
discordReady()
})
DiscordClient.login(config.discord.userToken)
<file_sep>module.exports = {
owner: '', // Put your user id here. Try typing \@User#tag to get your id.
asyncLimit: 5,
updateInterval: 60 * 2, // 2 Minutes
commandPrefix: '!',
coc: {
apiKey: 'https://api.clashofclans.com/v1/clans/2929P89UL',
},
discord: {
clientId: '625606192047194112',
userToken: '<KEY>'
},
starColors: [
0xff484e, // 0 Stars
0xffbc48, // 1 Star
0xc7ff48, // 2 Stars
0x4dff48 // 3 Stars
],
finalMinutes: 15,
messages: {
prepDay: {
title: 'War has been declared',
body: 'The battle begins %date%\n@ %time%',
color: 0x007cff
},
battleDay: {
title: 'The war has begun!',
body: 'Attack!',
color: 0x007cff
},
lastHour: {
title: 'The final hour is upon us!',
body: 'If you haven\'t made both of your attacks you better get on it.',
color: 0x007cff
},
finalMinutes: {
title: 'The final minutes are here!',
body: 'If you haven\'t made both of your attacks you better get on it.',
color: 0x007cff
}
}
}
| 8f54fd087b02d5149cceaa7f58b17bcdcc51b5da | [
"JavaScript"
] | 2 | JavaScript | ShyRabbit-web/ttps-github.com-spAnser-discord-coc-war-announcer | 29de7da0c230b26b4acd08d2d32125c8bb82cd11 | c898c351ac1f9c2413f4754123621667abd4dae3 |
refs/heads/master | <repo_name>chenop2/interview-algorithms<file_sep>/src/Trees/BalancedTree.java
package trees;
/**
* Created by Chen.Oppenhaim on 3/7/2016.
*/
public class BalancedTree {
public static void main(String[] args) {
TreeNode root = TreeMockHelper.createTree();
System.out.println(isBalanceTree(root));
}
private static int isBalanceTree(TreeNode node) {
return getMaxHeight(node) - getMinHeight(node);
}
private static int getMinHeight(TreeNode node) {
if (node == null)
return 0;
return 1 + Math.min(getMinHeight(node.left) , getMinHeight(node.right));
}
private static int getMaxHeight(TreeNode node) {
if (node == null)
return 0;
return 1 + Math.max(getMaxHeight(node.left) , getMaxHeight(node.right));
}
}
<file_sep>/src/Trees/TreeMockHelper.java
package trees;
/**
* Created by Chen.Oppenhaim on 3/7/2016.
*/
public class TreeMockHelper {
public static TreeNode createTree() {
TreeNode leaf1211 = new TreeNode(0);
TreeNode leaf121 = new TreeNode(leaf1211, null, 1);
TreeNode leaf122 = new TreeNode(2);
TreeNode leaf12 = new TreeNode(leaf121, leaf122, 3);
TreeNode leaf11 = new TreeNode(4);
TreeNode leaf1 = new TreeNode(leaf11, leaf12, 5);
TreeNode leaf2 = new TreeNode(6);
TreeNode root = new TreeNode(leaf1, leaf2, 7);
return root;
}
}
<file_sep>/src/sort/SortUtils.java
package sort;
/**
* Created by Chen on 12/03/2016.
*/
public class SortUtils {
public static Integer[] createMockArray() {
return new Integer[]{5, 4, 3, 6, 7, 8, 2, 1, 9};
}
public static void printArray(Integer[] arr) {
for (int i = 0; i < arr.length; i++) {
Integer integer = arr[i];
System.out.println(integer);
}
}
}
<file_sep>/src/Graphs/IVisitor.java
package graphs;
import trees.TreeNode;
/**
* Created by Chen.Oppenhaim on 3/7/2016.
*/
public interface IVisitor {
void visit(TreeNode node);
}
<file_sep>/src/recursion/Fibonachi.java
package recursion;
/**
* Created by Chen on 09/03/2016.
*/
public class Fibonachi {
public static void main(String[] args) {
int n = 7;
System.out.println("n == " + n + ": " + doFib(n));;
}
public static int doFib(int n) {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
return doFib(n-1) + doFib(n-2);
}
}
| fd09114466f4b2678206aab6f13b899140e86950 | [
"Java"
] | 5 | Java | chenop2/interview-algorithms | 62c695cbc1dc6ee5da52332727af16f18b4e5462 | ba2affd8859314cec8ec59641aaff0b1587acd6c |
refs/heads/main | <file_sep>package me.doupay.sdk.net
enum class Language(var language: String) {
en_US("en_US"),
zh_CN("zh_CN"),
zh_TW("zh_TW"),
}<file_sep>package me.doupay.sdk.net.exception
import me.doupay.sdk.Constants.language
import me.doupay.sdk.net.Language
enum class ExceString(
var us: String,
var cn: String) {
ServerError("Network error", "网络错误"),
RequestError("Request error", "请求错误"),
ServerTimeOut("The network connection timed out. Please check your network status and try again later!", "网络连接超时,请检查您的网络状态,稍后重试!"),
ServerNullPointer("Null pointer exception", "空指针异常"),
ServerSslError("Certificate verification failed", "证书验证失败"),
ServerCastError("Type conversion error", "类型转换错误"),
ServerParseError("Parse error", "解析错误"),
ServerUnknown("unknown error", "未知错误");
companion object {
fun getString(str: ExceString): String {
return when (language) {
Language.en_US -> str.us
Language.zh_CN -> str.cn
else -> str.us
}
}
}
}<file_sep>package me.doupay.sdk.sign;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtils {
private static final String KEY_ALGORITHM = "RSA";
private static final int KEY_SIZE = 2048;//设置长度
public static final String PUBLIC_KEY_NAME = "publicKey";
public static final String PRIVATE_KEY_NAME = "privateKey";
public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
public static final String ENCODE_ALGORITHM = "SHA-256";
/**
* RSA加密
*/
public static String encryptData(String data, String publicKeyString) {
try {
PublicKey publicKey = getPublicKey(publicKeyString);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] dataToEncrypt = data.getBytes("utf-8");
byte[] encryptedData = cipher.doFinal(dataToEncrypt);
String encryptString = Base64Utils.encode(encryptedData);
return encryptString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* RSA解密
*/
public static String decryptData(String data, String privateKeyString) {
try {
PrivateKey privateKey = getPrivateKey(privateKeyString);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] descryptData = Base64Utils.decode(data);
byte[] descryptedData = cipher.doFinal(descryptData);
return new String(descryptedData, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解码PublicKey
*/
public static PublicKey getPublicKey(String key) {
try {
byte[] byteKey = Base64Utils.decode(key);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return keyFactory.generatePublic(x509EncodedKeySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解码PrivateKey
*/
public static PrivateKey getPrivateKey(String key) {
try {
byte[] byteKey = Base64Utils.decode(key);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 签名
* @param key 私钥
* @param requestData 请求参数
* @return
*/
public static String sign(String key, String requestData) {
String signature = null;
byte[] signed = null;
try {
PrivateKey privateKey = getPrivateKey(key);
Signature Sign = Signature.getInstance(SIGNATURE_ALGORITHM);
Sign.initSign(privateKey);
Sign.update(requestData.getBytes());
signed = Sign.sign();
signature = Base64Utils.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return signature;
}
/**
* 验签
*
* @param key 公钥
* @param requestData 请求参数
* @param signature 签名
* @returnm
*/
public static boolean verifySign(String key, String requestData, String signature) {
System.out.println("--------------------------------------------------------------------------");
System.out.println("publicKey:"+key);
System.out.println("str:"+requestData);
System.out.println("sign:"+signature);
System.out.println("--------------------------------------------------------------------------");
boolean verifySignSuccess = false;
try {
PublicKey publicKey = getPublicKey(key);
Signature verifySign = Signature.getInstance(SIGNATURE_ALGORITHM);
verifySign.initVerify(publicKey);
verifySign.update(requestData.getBytes());
// verifySignSuccess = verifySign.verify(Base64.getDecoder().decode(signature));
verifySignSuccess = verifySign.verify(Base64Utils.decode(signature));
System.out.println("===验签结果:" + verifySignSuccess);
} catch (Exception e) {
e.printStackTrace();
}
return verifySignSuccess;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("===开始RSA公、私钥测试===");
String stc = "appId=502808ee5427490abb40375022e28578,key=3";
String gj="appId=502808ee5427490abb40375022e28578,key=3,secertSign=<KEY>timeStamp=1610697341483";
String privateKey="<KEY>;
String publicKey="<KEY>";
String sign = sign(privateKey, gj);
System.out.println(sign);
verifySign(publicKey, gj, sign);
}
}
<file_sep>package me.doupay.sdk.bean;
public class MakeUpResponse {
/**
* appId :
* orderCode :
* userId : 0
*/
private String appId;
private String orderCode;
private int userId;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getOrderCode() {
return orderCode;
}
public void setOrderCode(String orderCode) {
this.orderCode = orderCode;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "MakeUpResponse{" +
"appId='" + appId + '\'' +
", orderCode='" + orderCode + '\'' +
", userId=" + userId +
'}';
}
}
<file_sep>package me.doupay.sdk.net.interceptors;
import java.io.IOException;
import okhttp3.Request;
public interface BufferListener {
String getJsonResponse(Request request) throws IOException;
}
<file_sep>package me.doupay.sdk.net.interceptors;
import okhttp3.internal.platform.Platform;
import static me.doupay.sdk.Constants.openSysLog;
public class I {
private static String[] prefix = {". ", " ."};
private static int index = 0;
protected I() {
throw new UnsupportedOperationException();
}
static void log(String msg) {
if (openSysLog) {
System.out.println(msg);
}
}
private static String getFinalTag(final String tag, final boolean isLogHackEnable) {
if (isLogHackEnable) {
index = index ^ 1;
return prefix[index] + tag;
} else {
return tag;
}
}
}
<file_sep>package me.doupay.sdk.net;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.doupay.sdk.net.exception.ApiException;
/**
*
*/
public class BaseVoObserver<D> implements Observer<BaseVo<D>> {
public BaseVoObserver() {
}
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
}
@Override
public synchronized void onError(Throwable e) {
//统一处理错误
String msg = ApiException.handlerException(e).getMsg();
int errorCode = ApiException.handlerException(e).getErrorCode();
String url = ApiException.handlerException(e).getUrl();
if (msg != null && msg.length() > 6400) {
msg = msg.substring(0, 6400);
}
onError(errorCode, msg);
}
/**
* 返回错误字符串
*/
public void onError(int errorCode, String msg) {
}
@Override
public void onNext(BaseVo<D> deBaseVo) {
if (deBaseVo.getCode() != 200) {
onError(new ApiException.ServerException(deBaseVo.getCode(), deBaseVo.getMsg(), ""));
return;
}
System.out.println(deBaseVo.getMsg());
onPlaintextSuccess(deBaseVo.getData());
}
public void onPlaintextSuccess(D data) {
}
}
<file_sep>package me.doupay.sdk.net.exception
import me.doupay.sdk.Constants
import me.doupay.sdk.net.Language
enum class ApiString(var us: String,
var cn: String) {
ApiParameteInitError("Please call Constants.getInstance().init() first","请先调用Constants.getInstance().init()"),
ApiDismissParameterError("Missing required parameters", "缺少必要参数"),
ApiDismissParameterError1("currencyCode and money parameters cannot be empty", "currencyCode和money不能为空"),
ApiDismissParameterError2("The coinName and amount parameters cannot be empty", "coinName和amount参数不能为空"),
ApiDismissParameterError3("The amount parameter is missing", "缺少amount参数"),
ApiDismissParameterError4("The money parameter is missing", "缺少money参数"),
ApiDismissParameterError5("Please pass in the signature and body", "请传入签名和body体"),
ApiDismissParameterError6("Failed to verify signature", "验证签名失败"),
ApiDismissParameterError7("orderType parameter is \"BY_AMOUNT\" or \"BY_MONEY\"", "orderType订单类型【BY_AMOUNT、BY_MONEY】"),
ApiDismissParameterError8("expireTime is greater than 1800 seconds and less than 7200 seconds", "expireTime大于1800秒小于7200秒");
companion object {
fun getString(str: ApiString): String {
return when (Constants.language) {
Language.en_US -> str.us
Language.zh_CN -> str.cn
else -> str.us
}
}
}
}<file_sep>package me.doupay.sdk.bean;
import java.util.List;
public class CoinResponseData {
private List<RecordsBean> records;
public List<RecordsBean> getRecords() {
return records;
}
public void setRecords(List<RecordsBean> records) {
this.records = records;
}
public static class RecordsBean {
/**
* coinName : BTC
* coinCode : 0001
*/
private String coinName;
private String coinCode;
public String getCoinName() {
return coinName;
}
public void setCoinName(String coinName) {
this.coinName = coinName;
}
public String getCoinCode() {
return coinCode;
}
public void setCoinCode(String coinCode) {
this.coinCode = coinCode;
}
@Override
public String toString() {
return "RecordsBean{" +
"coinName='" + coinName + '\'' +
", coinCode='" + coinCode + '\'' +
'}';
}
}
@Override
public String toString() {
return "CoinResponseData{" +
"records=" + records +
'}';
}
}
<file_sep>package me.doupay.sdk;
import me.doupay.sdk.bean.*;
import me.doupay.sdk.enums.RefundType;
import me.doupay.sdk.interfaceCallback.CallBackListener;
import me.doupay.sdk.net.BaseVo;
import me.doupay.sdk.net.ServerApi;
import me.doupay.sdk.net.exception.ApiString;
import me.doupay.sdk.sign.AES;
import me.doupay.sdk.sign.RSAUtils;
import org.json.JSONObject;
import retrofit2.Call;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* 没有展示的接口
*/
public class SimplePaymentInfo {
/**
*
* @return
*/
public static BaseVo<CoinChainCodeResp> getCoinChainCodes(CoinNameEnum coinName) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
Map<String,Object> map = new HashMap<>();
map.put("appId",Constants.getAppId());
map.put("coinName",coinName);
Call<BaseVo<CoinChainCodeResp>> currentList = ServerApi.SERVICE_API.getCoinChainCodes(Constants.basrUrl + "trade/getChainCoins",map);
try {
BaseVo<CoinChainCodeResp> body = currentList.execute().body();
return body;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
* 付款,当orderType为0001时,amount内容为金额,currencyCode为必传,当orderType为0002时amount内容为数量,coinName为必传
* @param amount 金额
* @param coinName 币种(BTC)
* @param currencyCode 法币(0001:人民币cny,美元usa)【长度3到4】
* @param merchantUser 商家用户【长度10到20之间】
* @param orderNo 订单号【长度10到30】
* @param subject 商品标题【长度5~10】
* @param body 商品描述信息【长度10到100】
* @param description 附加说明【长度10到50】
* @param orderType 订单类型(BY_AMOUNT、BY_MONEY)
*/
public static BaseVo<PayResponseData> pay( String money,
String amount, CoinNameEnum coinName, CurrencyCodeEnum currencyCode,
String merchantUser, String orderNo, String subject,
String body, String description,
OrderTypeCodeEnum orderType ) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
// 大于1800小于7200
if (new BigDecimal(Constants.getExpireTime()).compareTo(new BigDecimal("1800")) == -1) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError8));
}
if (new BigDecimal(Constants.getExpireTime()).compareTo(new BigDecimal("7200")) == 1) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError8));
}
if ( orderNo == null || orderType == null
|| subject == null || orderNo.isEmpty() || subject.isEmpty()
) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError));
}
if (orderType != OrderTypeCodeEnum.BY_AMOUNT
&& orderType != OrderTypeCodeEnum.BY_MONEY) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError7));
}
if (orderType == OrderTypeCodeEnum.BY_MONEY) {
if (currencyCode == null || money == null || money.equals("")) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError1));
}
}
if (orderType == OrderTypeCodeEnum.BY_AMOUNT) {
if (coinName == null || amount == null || amount.equals("")) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError2));
}
}
Map<String,Object> map = new HashMap<>();
map.put("appId",Constants.getAppId());
map.put("expireTime",Constants.getExpireTime());
if (merchantUser != null && !merchantUser.isEmpty()) {
map.put("merchantUser",merchantUser);
}
map.put("orderNo",orderNo);
map.put("orderType",orderType);
map.put("subject",subject);
if (body != null && !body.equals("")) {
map.put("body",body);
}
if (description != null && !description.equals("")) {
map.put("description",description);
}
if (orderType == OrderTypeCodeEnum.BY_MONEY) {
map.put("money",money);
map.put("currency",currencyCode);
}
if (orderType == OrderTypeCodeEnum.BY_AMOUNT) {
map.put("amount",amount);
map.put("coinName",coinName);
}
Call<BaseVo<PayResponseData>> gotoPay = ServerApi.SERVICE_API.gotoPay(Constants.basrUrl + "trade/pay",map);
try {
BaseVo<PayResponseData> responseBody = gotoPay.execute().body();
return responseBody;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
* 补单
* @param orderCode orderCode
* @return
*/
public static BaseVo<MakeUpResponse> maleUp(String remark, String orderCode) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if (orderCode == null || remark == null || orderCode.equals("") || remark.equals("")) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError));
}
Map<String,Object> map = new HashMap<>();
map.put("orderCode",orderCode);
map.put("appId",Constants.getAppId());
map.put("remark",remark);
map.put("timeStamp",System.currentTimeMillis());
Call<BaseVo<MakeUpResponse>> baseVoCall = ServerApi.SERVICE_API.makeup(Constants.basrUrl + "trade/makeUpOrder",map);
try {
BaseVo<MakeUpResponse> body = baseVoCall.execute().body();
return body;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
* 退款
* @param address 退款地址【长度5到50】
* @param amount 退款数量【长度1到50
* @param orderCode 订单编号【长度5到50】
* @param remark 退款描述【长度5到50】
*/
public static BaseVo<RefundResponseData> refund(RefundType refundType, String address, String amount, String orderCode, String remark) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if ( refundType == null || amount == null || remark == null || orderCode == null
|| remark.isEmpty() || orderCode.isEmpty() || amount.isEmpty()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError));
}
String appId = Constants.getAppId();
String timestamp = System.currentTimeMillis() + "";
String secertSign = AES.Encrypt(appId + timestamp,Constants.getSecret());
Map<String,Object> map = new HashMap<>();
map.put("refundType",refundType);
map.put("remark",remark);
map.put("amount",amount);
map.put("appId",appId);
map.put("orderCode",orderCode);
map.put("secretSign",secertSign);
map.put("timeStamp",timestamp);
if (address != null && !address.isEmpty()) {
map.put("address",address);
}
Call<BaseVo<RefundResponseData>> baseVoCall = ServerApi.SERVICE_API.gotoRefund(Constants.basrUrl + "trade/refund",map);
try {
BaseVo<RefundResponseData> body = baseVoCall.execute().body();
return body;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
* 获取退款信息
* @param orderCode 订单编号【长度20到50】
*/
public static BaseVo<RefundInfoResponseData> getRefunds(String orderCode) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if (orderCode == null || orderCode.isEmpty() ) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError));
}
Map<String,Object> map = new HashMap<>();
map.put("orderCode",orderCode);
Call<BaseVo<RefundInfoResponseData>> baseVoCall = ServerApi.SERVICE_API.getRefundInfo(Constants.basrUrl + "trade/getRefunds",map);
try {
BaseVo<RefundInfoResponseData> body = baseVoCall.execute().body();
return body;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
*提现
* @param address 地址
* @param amount 数量【最小0.000001】
* @param coinName 币种
* @param merchantUser 商家用户【长度10到20之间】
* @param orderNo 订单号【长度10到30】
*/
public static BaseVo<WithdrawResponse> withdraw(String protocolName,String address,String amount,CoinNameEnum coinName,String merchantUser,String orderNo,String money,OrderTypeCodeEnum orderType,CurrencyCodeEnum currencyCode) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if (address == null || coinName == null || merchantUser == null || orderNo == null || protocolName == null) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError));
}
Map<String,Object> map = new HashMap<>();
if (orderType == OrderTypeCodeEnum.BY_AMOUNT) {
if (amount == null || amount.equals("")) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError3));
}
map.put("amount",amount);
}
if (orderType == OrderTypeCodeEnum.BY_MONEY) {
if (money == null || money.equals("")) {
return new BaseVo<>(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError4));
}
map.put("money",money);
map.put("currency",currencyCode);
}
String appId = Constants.getAppId();
String timestamp = System.currentTimeMillis() + "";
String secertSign = AES.Encrypt(appId + timestamp,Constants.getSecret());
map.put("address",address);
map.put("appId",appId);
map.put("coinName",coinName);
map.put("merchantUser",merchantUser);
map.put("orderNo",orderNo);
// map.put("feeAmount",feeAmount);
map.put("timeStamp",timestamp);
map.put("orderType",orderType);
map.put("protocolName",protocolName);
Call<BaseVo<WithdrawResponse>> baseVoCall = ServerApi.SERVICE_API.withdraw(Constants.basrUrl + "trade/withdrawal",map);
try {
BaseVo<WithdrawResponse> body = baseVoCall.execute().body();
return body;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
* 获取单价汇率
* @param coinName coinName
* @param currencyCode currencyCodeEnum
* @return
*/
public static BaseVo<CoinPriceResponse> getCoinPrice(CoinNameEnum coinName,CurrencyCodeEnum currencyCode) {
if (!Constants.getInstance().isInitAllParameters()) {
return new BaseVo<>(9999, ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if (coinName == null || currencyCode == null ) {
return new BaseVo<>(9999, ApiString.Companion.getString(ApiString.ApiDismissParameterError));
}
Map<String,Object> map = new HashMap<>();
map.put("coinName",coinName);
map.put("currency",currencyCode);
Call<BaseVo<CoinPriceResponse>> baseVoCall = ServerApi.SERVICE_API.getPrice(Constants.basrUrl + "trade/getCurrencyCoinPrice",map);
try {
BaseVo<CoinPriceResponse> body = baseVoCall.execute().body();
return body;
}catch (Exception e) {
return new BaseVo<>(9999,e.getMessage());
}
}
/**
* 验证回调签名并组装回调对象
* @param headerSignString header中的签名(X-Merchant-sign)
* @param bodyString body体内容
* @param listener 回调结果
*/
public static void verifySignAndGetResult (String headerSignString,String bodyString,CallBackListener<PaymentCallBackResponse> listener,CallBackListener<UserWithdrawCallBackResponse> withdrawCalllBack,CallBackListener<MakeUpCallBackResponse> makeUpCallBackResponseCallBack) {
if (!Constants.getInstance().isInitAllParameters()) {
if (listener != null) {
listener.onError(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if (withdrawCalllBack != null) {
withdrawCalllBack.onError(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
if (makeUpCallBackResponseCallBack != null) {
makeUpCallBackResponseCallBack.onError(9999,ApiString.Companion.getString(ApiString.ApiParameteInitError));
}
return;
}
if (headerSignString == null || headerSignString.isEmpty() || bodyString == null || bodyString.isEmpty()) {
if (listener != null) {
listener.onError(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError5));
}
if (withdrawCalllBack != null) {
withdrawCalllBack.onError(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError5));
}
if (makeUpCallBackResponseCallBack != null) {
makeUpCallBackResponseCallBack.onError(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError5));
}
return;
}
// 拼接成a=b,c=d的形式
String signString = generateClearTextSign(bodyString);
// 验证签名
boolean isRight = RSAUtils.verifySign(Constants.getPublicKey(), signString, headerSignString);
JSONObject jsonObject = new JSONObject(bodyString);
String type = jsonObject.getString("orderType");
if (type.equals("payment")) { /// 用户付款
if (!isRight) { // 验签失败
listener.onError(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError6));
return;
}
String orderCode = jsonObject.getString("orderCode");
String coinName = jsonObject.getString("coinName");
String address = jsonObject.getString("address");
String amount = jsonObject.getString("amountPaid");
String protocolName = jsonObject.getString("protocolName");
String price = jsonObject.getString("price");
Integer paymentStatus = jsonObject.getInt("paymentStatus");
Boolean result = jsonObject.getBoolean("result");
String money = jsonObject.getString("money");
String orderNo = jsonObject.getString("orderNo");
PaymentCallBackResponse resultResponse = new PaymentCallBackResponse(type,orderCode,coinName,address,amount,protocolName,paymentStatus,result,price,money,orderNo);
listener.onFinish(resultResponse);
}else if (type.equals("withdraw")) { /// 用户提币
if (!isRight) { // 验签失败
withdrawCalllBack.onError(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError6));
return;
}
String orderCode = jsonObject.getString("orderCode");
String coinName = jsonObject.getString("coinName");
String protocolName = jsonObject.getString("protocolName");
String address = jsonObject.getString("address");
String currency = jsonObject.getString("currency");
String money = jsonObject.getString("money");
String price = jsonObject.getString("price");
String amount = jsonObject.getString("amountPaid");
String hashId = jsonObject.getString("hashId");
Boolean result = jsonObject.getBoolean("result");
String orderNo = jsonObject.getString("orderNo");
UserWithdrawCallBackResponse userWithdrawCallBackResponse = new UserWithdrawCallBackResponse(orderCode,type,coinName,protocolName,address,amount,result,price,money,currency,hashId,orderNo);
withdrawCalllBack.onFinish(userWithdrawCallBackResponse);
}
else if (type.equals("makeUp")) { /// 补单
if (!isRight) { // 验签失败
makeUpCallBackResponseCallBack.onError(9999,ApiString.Companion.getString(ApiString.ApiDismissParameterError6));
return;
}
String orderCode = jsonObject.getString("orderCode");
String coinName = jsonObject.getString("coinName");
String protocolName = jsonObject.getString("protocolName");
String price = jsonObject.getString("price");
String address = jsonObject.getString("address");
String money = jsonObject.getString("money");
String amountPaid = jsonObject.getString("amountPaid");
Integer paymentStatus = jsonObject.getInt("paymentStatus");
Boolean result = jsonObject.getBoolean("result");
String orderNo = jsonObject.getString("orderNo");
MakeUpCallBackResponse make = new MakeUpCallBackResponse(orderCode,type,coinName,protocolName,price,address,amountPaid,money,result,paymentStatus,orderNo);
makeUpCallBackResponseCallBack.onFinish(make);
}
}
/**
* 根据json串生成明文签名
*
* @param jsonStr
* @return
*/
public static String generateClearTextSign(String jsonStr) {
JSONObject jsonObject = new JSONObject(jsonStr);
Map<String, Object> treeMap = new TreeMap<>();
for (String key : jsonObject.keySet()) {
treeMap.put(key, jsonObject.get(key));
}
StringBuffer sb = new StringBuffer();
for (String key : treeMap.keySet()) {
// 字母序降序排列拼接
if (!(treeMap.get(key) instanceof List)) {
sb.append(key + "=" + treeMap.get(key) + ",");
}else {
sb.append(key + "=" + ((List<String>) treeMap.get(key)).get(0) + ",");
}
}
return sb.toString().substring(0, sb.length() - 1);
}
}
<file_sep>include ':sdk'
rootProject.name = "DouPaySDK"<file_sep>package me.doupay.sdk.net.exception;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializer;
import java.io.NotSerializableException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;
import javax.net.ssl.SSLHandshakeException;
import retrofit2.HttpException;
/**
* <pre>
* </pre>
*/
public class ApiException extends Exception {
private int errorCode;
private String msg;
private String url;
private ApiException(Throwable throwable, int errorCode) {
super(throwable);
this.errorCode = errorCode;
this.msg = throwable.getMessage();
}
public static ApiException handlerException(Throwable throwable) {
ApiException exception = null;
String errorUrl = "";
if (throwable instanceof HttpException) {
HttpException httpException = (HttpException) throwable;
exception = new ApiException(httpException, httpException.code());
if (exception.errorCode >= 500) {
exception.setMsg(ExceString.Companion.getString(ExceString.ServerError));
} else if (exception.errorCode >= 400) {
exception.setMsg(ExceString.Companion.getString(ExceString.RequestError));
}
} else if (throwable instanceof SocketTimeoutException || throwable instanceof ConnectException ||
throwable instanceof UnknownHostException) {
exception = new ApiException(throwable, ERROR.TIMEOUT_ERROR);
exception.setMsg(ExceString.Companion.getString(ExceString.ServerTimeOut));
} else if (throwable instanceof NullPointerException) {
exception = new ApiException(throwable, ERROR.NULL_POINTER_EXCEPTION);
exception.setMsg(ExceString.Companion.getString(ExceString.ServerNullPointer));
} else if (throwable instanceof SSLHandshakeException) {
exception = new ApiException(throwable, ERROR.SSL_ERROR);
exception.setMsg(ExceString.Companion.getString(ExceString.ServerSslError));
} else if (throwable instanceof ClassCastException) {
exception = new ApiException(throwable, ERROR.CAST_ERROR);
exception.setMsg(ExceString.Companion.getString(ExceString.ServerCastError));
} else if (throwable instanceof IllegalStateException) {
exception = new ApiException(throwable, ERROR.ILLEGAL_STATE_ERROR);
exception.setMsg(throwable.getMessage());
} else if (throwable instanceof JsonParseException || throwable instanceof JsonSerializer || throwable instanceof NotSerializableException || throwable instanceof ParseException) {
exception = new ApiException(throwable, ERROR.PARSE_ERROR);
exception.setMsg(ExceString.Companion.getString(ExceString.ServerParseError) + throwable.getMessage());
} else if (throwable instanceof ServerException) {
int errorCode = ((ServerException) throwable).getErrorCode();
String msg = ((ServerException) throwable).getErrorMsg();
errorUrl = ((ServerException) throwable).getUrl();
exception = new ApiException(throwable, errorCode);
exception.setMsg(msg);
} else {
exception = new ApiException(throwable, ERROR.UNKNOWN);
exception.setMsg(ExceString.Companion.getString(ExceString.ServerUnknown) + throwable.getMessage());
}
exception.setUrl(errorUrl);
return exception;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getMsg() {
if (msg == null) {
return "";
}
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* 约定异常
*/
public static class ERROR {
/**
* 未知错误
*/
public static final int UNKNOWN = 1000;
/**
* 连接超时
*/
public static final int TIMEOUT_ERROR = 1001;
/**
* 空指针错误
*/
public static final int NULL_POINTER_EXCEPTION = 1002;
/**
* 证书出错
*/
public static final int SSL_ERROR = 1003;
/**
* 类转换错误
*/
public static final int CAST_ERROR = 1004;
/**
* 解析错误
*/
public static final int PARSE_ERROR = 1005;
/**
* 非法数据异常
*/
public static final int ILLEGAL_STATE_ERROR = 1006;
}
/**
* 服务端异常
*/
public static class ServerException extends RuntimeException {
private int errorCode;
private String errorMsg;
private String url;
public ServerException(int errorCode, String errorMsg, String url) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.url = url;
}
public int getErrorCode() {
return this.errorCode;
}
public String getErrorMsg() {
return this.errorMsg;
}
public String getUrl() {
return url;
}
}
}
<file_sep>package me.doupay.sdk.net.interceptors;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* <pre>
* 描述 : 请求头属性拦截器
* </pre>
*/
public class HeaderInterceptor implements Interceptor {
public static String ANDROID_VERSION = "Android_0.0.2";
private Map<String, String> mHeaderParamsMap = new HashMap<>();
@Override
public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
// 添加新的参数,添加到url 中
/* HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host());*/
// 新的请求
Request.Builder requestBuilder = oldRequest.newBuilder();
requestBuilder.method(oldRequest.method(), oldRequest.body());
//添加公共参数,添加到header中
if (mHeaderParamsMap.size() > 0) {
for (Map.Entry<String, String> params : mHeaderParamsMap.entrySet()) {
requestBuilder.header(params.getKey(), params.getValue());
}
}
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
//获取当前的系统语言
public static String getLocalLanguage() {
String language = "";
String locale = Locale.getDefault().toString();
if (locale.contains("zh")) {
language = "zh_CN";
} else {
language = "en_US";
}
return language;
}
public static class Builder {
HeaderInterceptor mHttpCommonInterceptor;
public Builder() {
mHttpCommonInterceptor = new HeaderInterceptor();
}
public Builder addHeaderParams(String key, String value) {
mHttpCommonInterceptor.mHeaderParamsMap.put(key, value);
return this;
}
public Builder addHeaderParams(String key, int value) {
return addHeaderParams(key, String.valueOf(value));
}
public Builder addHeaderParams(String key, float value) {
return addHeaderParams(key, String.valueOf(value));
}
public Builder addHeaderParams(String key, long value) {
return addHeaderParams(key, String.valueOf(value));
}
public Builder addHeaderParams(String key, double value) {
return addHeaderParams(key, String.valueOf(value));
}
public HeaderInterceptor build() {
return mHttpCommonInterceptor;
}
}
}
<file_sep>package me.doupay.sdk.bean;
public enum CoinNameEnum {
BTC,
ETH,
TRX,
USDT
}
<file_sep>package me.doupay.sdk.bean;
public class UserWithdrawCallBackResponse {
/// 订单编号
private String orderCode;
/// 订单类型
private String orderType ;
/// 币种名称
private String coinName;
/// 协议名称
private String protocolName;
/// 地址
private String address;
/// 数量
private String amountPaid;
/// 结果
private Boolean result;
///单价
private String price;
///金额
private String money;
///法币标识
private String currency;
/// 交易哈希
private String hashId;
/// 商家订单号
private String orderNo;
public String getOrderCode() {
return orderCode;
}
public void setOrderCode(String orderCode) {
this.orderCode = orderCode;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getCoinName() {
return coinName;
}
public void setCoinName(String coinName) {
this.coinName = coinName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(String amountPaid) {
this.amountPaid = amountPaid;
}
public Boolean getResult() {
return result;
}
public void setResult(Boolean result) {
this.result = result;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getHashId() {
return hashId;
}
public void setHashId(String hashId) {
this.hashId = hashId;
}
public String getProtocolName() {
return protocolName;
}
public void setProtocolName(String protocolName) {
this.protocolName = protocolName;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public UserWithdrawCallBackResponse(String orderCode, String orderType, String coinName, String protocolName, String address, String amountPaid, Boolean result, String price, String money, String currency, String hashId, String orderNo) {
this.orderCode = orderCode;
this.orderType = orderType;
this.coinName = coinName;
this.protocolName = protocolName;
this.address = address;
this.amountPaid = amountPaid;
this.result = result;
this.price = price;
this.money = money;
this.currency = currency;
this.hashId = hashId;
this.orderNo = orderNo;
}
@Override
public String toString() {
return "UserWithdrawCallBackResponse{" +
"orderCode='" + orderCode + '\'' +
", orderType='" + orderType + '\'' +
", coinName='" + coinName + '\'' +
", protocolName='" + protocolName + '\'' +
", address='" + address + '\'' +
", amountPaid='" + amountPaid + '\'' +
", result=" + result +
", price='" + price + '\'' +
", money='" + money + '\'' +
", currency='" + currency + '\'' +
", hashId='" + hashId + '\'' +
", orderNo='" + orderNo + '\'' +
'}';
}
}
<file_sep># 该项目支持两种集成方式
## 1.maven,使用方法如下:
### 1.将 JitPack存储库添加到您的构建文件pom.xml
```javascript
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
```
### 2.添加依赖项
```javascript
<dependency>
<groupId>com.github.doupay</groupId>
<artifactId>doupay-java</artifactId>
<version>1.1.1</version>
</dependency>
```
#### 示例截图如下:
图中示例版本号"0.0.1"会随时变化,请随时关注本github更新,现在最新的版本号为1.1.1
<img width="864" alt="步骤" src="https://user-images.githubusercontent.com/86946898/124468680-feed5b80-ddcb-11eb-927f-c10855eeaf86.png">
### 项目中调用初始化方法,示例如下:

### 以下方法可以设置语言类别
```java
Constants.setLanguage(Language.zh_CN);/// 中文
Constants.setLanguage(Language.en_US);/// 英文
```
#### secret为商户管理后台创建app得到的,appid为创建app得到的,privateKey为自己的私钥,publicKey为交换公钥后得到的平台公钥,expireTime为订单过期时间,秒为单位,expireTime大于1800秒,小于7200秒
### 注意事项:使用完整功能的请使用PaymentInfo类,使用部分功能的请使用类SimplePaymentInfo,SimplePaymentInfo类中没有获取订单信息,支付信息,取消接口,这些功能由接入的h5完成
## sdk中各方法请求和响应参数,请参照[wiki](https://github.com/doupay/doupay-java/wiki)
<!-- ## 2.jar包引入
### 1.1 把jar包拖入项目,如下图所示:jar包在文件中即DouPaySdk.jar,也可以自己用源代码打包
<img width="1488" alt="1111" src="https://user-images.githubusercontent.com/86946898/127596834-639f94c0-e775-4911-9433-f976589852ee.png">
### 1.2 pom.xml配置文件中添加以下依赖,代码和截图见下方
```javascript
<dependency>
<groupId>com.github.doupay</groupId>
<artifactId>doupay-java</artifactId>
<version>1.0.8</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/DouPaySDK.jar</systemPath>
</dependency>
```
<img width="1644" alt="222" src="https://user-images.githubusercontent.com/86946898/127596733-766e8f04-8cd6-4d86-bc1a-d52e5c6e7213.png">
### 项目中调用初始化方法,示例如下:

#### secret为商户管理后台创建app得到的,appid为创建app得到的,privateKey为自己的私钥,publicKey为交换公钥后得到的平台公钥,expireTime为订单过期时间,秒为单位
## sdk中各方法请求和响应参数,请参照[wiki](https://github.com/doupay/doupay-java/wiki)
-->
<file_sep>package me.doupay.sdk.enums;
public enum RefundType {
// 新地址
NEW_ADDRESS,
// 原地址
OLD_ADDRESS
}
<file_sep>package me.doupay.sdk.bean;
public enum OrderTypeCodeEnum {
BY_MONEY,
BY_AMOUNT
}
<file_sep>package me.doupay.sdk.net.interceptors;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import me.doupay.sdk.Constants;
import me.doupay.sdk.net.exception.ApiException;
import me.doupay.sdk.sign.AES;
import me.doupay.sdk.sign.RSAUtils;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.platform.Platform;
public class LoggingInterceptor implements Interceptor {
private static final int JSON_INDENT = 3;
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final String OOM_OMITTED = LINE_SEPARATOR + "Output omitted because of Object size.";
private final boolean isDebug;
private final Builder builder;
private JsonParser parser = new JsonParser();
private LoggingInterceptor(Builder builder) {
this.builder = builder;
this.isDebug = builder.isDebug;
}
private static Runnable createPrintJsonRequestRunnable(final Builder builder, final Request request) {
return () -> Printer.printJsonRequest(builder, request);
}
private static Runnable createFileRequestRunnable(final Builder builder, final Request request) {
return () -> Printer.printFileRequest(builder, request);
}
private static Runnable createPrintJsonResponseRunnable(final Builder builder, final long chainMs, final boolean isSuccessful,
final int code, final String headers, final String bodyString, final List<String> segments, final String message, final String responseUrl) {
return () -> Printer.printJsonResponse(builder, chainMs, isSuccessful, code, headers, bodyString, segments, message, responseUrl);
}
private static Runnable createFileResponseRunnable(final Builder builder, final long chainMs, final boolean isSuccessful,
final int code, final String headers, final List<String> segments, final String message) {
return () -> Printer.printFileResponse(builder, chainMs, isSuccessful, code, headers, segments, message);
}
private static String getJsonString(final String msg) {
String message;
try {
String block = "{";
String brackets = "[";
if (msg.startsWith(block)) {
JSONObject jsonObject = new JSONObject(msg);
message = jsonObject.toString(JSON_INDENT);
} else if (msg.startsWith(brackets)) {
JSONArray jsonArray = new JSONArray(msg);
message = jsonArray.toString(JSON_INDENT);
} else {
message = msg;
}
} catch (JSONException e) {
message = msg;
} catch (OutOfMemoryError e1) {
message = OOM_OMITTED;
}
return message;
}
@Override
public synchronized Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String appId = "";
String timestamp = "";
// 重新组装 body
TreeMap<String, Object> params = null;
// FormBody.Builder newFormBody = null;
if (request.body() instanceof FormBody) {
params = new TreeMap<>();
FormBody oidFormbody = (FormBody) request.body();
for (int i = 0; i < oidFormbody.size(); i++) {
switch (oidFormbody.encodedName(i)) {
case "appId":
appId = oidFormbody.encodedValue(i);
params.put(oidFormbody.name(i), oidFormbody.value(i));
break;
case "timeStamp":
timestamp = oidFormbody.encodedValue(i);
params.put(oidFormbody.name(i), oidFormbody.value(i));
break;
default:
if (oidFormbody.value(i).contains("[")) {
String value = oidFormbody.value(i);
String valueSub = value.substring(1, value.length() - 1);
String[] valueArray = valueSub.split(",");
List<String> demoList = new ArrayList<>();
for (String s : valueArray) {
demoList.add(s.trim());
}
params.put(oidFormbody.name(i), demoList);
} else {
params.put(oidFormbody.name(i), oidFormbody.value(i));
}
break;
}
}
}
// 判断高权限
if (!appId.equals("") && !timestamp.equals("")) {
String secertSign = AES.Encrypt(appId + timestamp, Constants.getSecret());
params.put("secretSign", secertSign.replace("+", "%2B"));
}
// 组织加密数据
StringBuilder UrlSign = new StringBuilder();
if (params != null) {
for (String key : params.keySet()) {
if (params.get(key) instanceof String) {
UrlSign.append(key).append("=").append(params.get(key)).append(",");
}
}
}
String sign = UrlSign.substring(0, UrlSign.toString().length() - 1);
sign = URLDecoder.decode(sign, "utf-8");
// body
String bodyStr = new Gson().toJson(params);//加密前
bodyStr = URLDecoder.decode(bodyStr, "utf-8");
request = request.newBuilder().post(RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), bodyStr)).build();
// 添加头部签名
Request.Builder requestBuilder = request.newBuilder();
HashMap<String, String> headerMap = builder.getHeaders();
for (String key : headerMap.keySet()) {
requestBuilder.addHeader(key, headerMap.get(key));
}
if (!request.url().toString().contains("openApi")) {
requestBuilder.addHeader("X-Merchant-sign", RSAUtils.sign(Constants.getPrivateKey(), sign));
}
request = requestBuilder.build();
final RequestBody requestBody = request.body();
String rSubtype = null;
if (requestBody != null && requestBody.contentType() != null) {
rSubtype = requestBody.contentType().subtype();
}
Executor executor = this.builder.executor;
if (isNotFileRequest(rSubtype)) {
if (executor != null) {
executor.execute(createPrintJsonRequestRunnable(this.builder, request));
} else {
//打印request
// if (LogUtils.getConfig().isLogSwitch()) {
Printer.printJsonRequest(this.builder, request);
// }
}
} else {
if (executor != null) {
executor.execute(createFileRequestRunnable(this.builder, request));
} else {
Printer.printFileRequest(this.builder, request);
}
}
final long st = System.nanoTime();
Response response = null;
if (this.builder.isMockEnabled) {
try {
TimeUnit.MILLISECONDS.sleep(this.builder.sleepMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
response = new Response.Builder()
.body(ResponseBody.create(MediaType.parse("application/json"), this.builder.listener.getJsonResponse(request)))
.request(chain.request())
.protocol(Protocol.HTTP_2)
.message("Mock")
.code(200)
.build();
} else {
//TODO 发送请求
response = chain.proceed(request);
}
final long chainMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - st);
final List<String> segmentList = request.url().encodedPathSegments();
final String header = response.headers().toString();
final int code = response.code();
final boolean isSuccessful = response.isSuccessful();
final String message = response.message();
final ResponseBody responseBody = response.body();
final MediaType contentType = responseBody.contentType();
if (code != 200) {
//抛出异常,让rxjava捕获,便于统一处理
throw new ApiException.ServerException(code, message, request.url().toString());
}
String subtype = null;
final ResponseBody body;
if (contentType != null) {
subtype = contentType.subtype();
}
String bodyString = null;
bodyString = Printer.getJsonString(responseBody.string());
final String url = response.request().url().toString();
if (executor != null) {
executor.execute(createPrintJsonResponseRunnable(this.builder, chainMs, isSuccessful, code, header, bodyString,
segmentList, message, url));
} else {
// if (BaseConstants.LogSwitch) {
Printer.printJsonResponse(this.builder, chainMs, isSuccessful, code, header, bodyString,
segmentList, message, url);
// }
}
body = ResponseBody.create(contentType, bodyString);
return response.newBuilder().
body(body).
build();
}
private boolean isNotFileRequest(final String subtype) {
return subtype != null && (subtype.contains("json")
|| subtype.contains("xml")
|| subtype.contains("plain")
|| subtype.contains("html"));
}
@SuppressWarnings({"unused", "SameParameterValue"})
public static class Builder {
public static String TAG = "LoggingI";
public final HashMap<String, String> headers;
public final HashMap<String, String> queries;
public boolean isLogHackEnable = false;
public boolean isDebug;
public int type = Platform.INFO;
public String requestTag;
public String responseTag;
public Level level = Level.BASIC;
public Logger logger;
public Executor executor;
public boolean isMockEnabled;
public long sleepMs;
public BufferListener listener;
public Builder() {
headers = new HashMap<>();
queries = new HashMap<>();
}
int getType() {
return type;
}
Level getLevel() {
return level;
}
/**
* @param level set log level
* @return Builder
* @see Level
*/
public Builder setLevel(Level level) {
this.level = level;
return this;
}
HashMap<String, String> getHeaders() {
return headers;
}
HashMap<String, String> getHttpUrl() {
return queries;
}
String getTag(boolean isRequest) {
if (isRequest) {
return TextUtils.isEmpty(requestTag) ? TAG : requestTag;
} else {
return TextUtils.isEmpty(responseTag) ? TAG : responseTag;
}
}
Logger getLogger() {
return logger;
}
Executor getExecutor() {
return executor;
}
boolean isLogHackEnable() {
return isLogHackEnable;
}
/**
* @param name Filed
* @param value Value
* @return Builder
* Add a field with the specified value
*/
public Builder addHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* @param name Filed
* @param value Value
* @return Builder
* Add a field with the specified value
*/
public Builder addQueryParam(String name, String value) {
queries.put(name, value);
return this;
}
/**
* Set request and response each log tag
*
* @param tag general log tag
* @return Builder
*/
public Builder tag(String tag) {
TAG = tag;
return this;
}
/**
* Set request log tag
*
* @param tag request log tag
* @return Builder
*/
public Builder request(String tag) {
this.requestTag = tag;
return this;
}
/**
* Set response log tag
*
* @param tag response log tag
* @return Builder
*/
public Builder response(String tag) {
this.responseTag = tag;
return this;
}
/**
* @param isDebug set can sending log output
* @return Builder
*/
public Builder loggable(boolean isDebug) {
this.isDebug = isDebug;
return this;
}
/**
* @param type set sending log output type
* @return Builder
* @see Platform
*/
public Builder log(int type) {
this.type = type;
return this;
}
/**
* @param logger manuel logging interface
* @return Builder
* @see Logger
*/
public Builder logger(Logger logger) {
this.logger = logger;
return this;
}
/**
* @param executor manual executor for printing
* @return Builder
* @see Logger
*/
public Builder executor(Executor executor) {
this.executor = executor;
return this;
}
/**
* @param useMock let you use json file from asset
* @param sleep let you see progress dialog when you request
* @return Builder
* @see LoggingInterceptor
*/
public Builder enableMock(boolean useMock, long sleep, BufferListener listener) {
this.isMockEnabled = useMock;
this.sleepMs = sleep;
this.listener = listener;
return this;
}
/**
* Call this if you want to have formatted pretty output in Android Studio logCat.
* By default this 'hack' is not applied.
*
* @param useHack setup builder to use hack for Android Studio v3+ in order to have nice
* output as it was in previous A.S. versions.
* @return Builder
* @see Logger
*/
public Builder enableAndroidStudio_v3_LogsHack(final boolean useHack) {
isLogHackEnable = useHack;
return this;
}
public LoggingInterceptor build() {
return new LoggingInterceptor(this);
}
}
}
<file_sep>package me.doupay.sdk;
import me.doupay.sdk.bean.*;
import me.doupay.sdk.enums.RefundType;
import me.doupay.sdk.interfaceCallback.CallBackListener;
import me.doupay.sdk.net.BaseVo;
import me.doupay.sdk.net.Language;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.Random;
public class SDKtest {
public static void initAllParameters() {
String appId = "doupay_n62mewaVa9";
String secret = "cff7d04980ff1a720c8e8f61c73d4073";
String privateKey = "<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>sN8tLBA\n" +
"<KEY>\n" +
"<KEY>MBAAECggEBAI6r9sO+eNBe1CnXQBWjFSLTYT9zJ5eY6jw0Xz62nLkT\n" +
"UwGzMnz0Qjgwklrp3RO1HzWRdNgQbj/JgteV1dS7V7cPZS0OO2h1vGCQHluYZqEF\n" +
"VzpoiEk8CeTh7dtY/h3A4ZQugOXUlY1NBltcJOQcYow12BxYXTt5xskvNkd4hR9r\n" +
"uFhINtksfKvq/jdHJVis5t+4phUdeyYeE4CwFGGeBgwxMu/LkGNGU/zUQ1Kl7PZN\n" +
"TyEKm5uhzglV8nKvRc04FGOJcHi2jU98/nqBGnnrybqHaGfPO9BdmaVc9t5KI0Dq\n" +
"LrQKyGlT4UowUYW/6BU5KVuICfYZUXIrr7SMYakzc+ECgYEA7BbbC+EbmYJDuAMu\n" +
"HA5sDBV2y5ZIZ/+ljLFvL2tA8jFb2qbdgPQVkTX8TgUvA3oisq7i5Maps+KE/y1Z\n" +
"8Oaz4kg+nRiZQ3ms5JYHhAKZdFcm1Cf3n0ge09t6J/HqYClVdQfqOgmKjYJZ8CCN\n" +
"YsVIduK65EAVDo/YfMWYYxHllwcCgYEAxfBrAdLER/zu3V1+ONyFx+8ZVOafkk4O\n" +
"wkwwanWPd2a5NgDDaoY/xJylkBEdqlstLpkC4k0cdt/LRts9w63LDu9P6Na/r726\n" +
"jIZokK1yAcSHTATVKgfR6STo0nNFWn/Uk5CpBD0jgLsq6yB8wwLRVCqyaj5GGLoH\n" +
"<KEY>pNXtaUW\n" +
"<KEY>h<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>;
String publicKey = "<KEY>";
Constants.openSysLog = true;
Constants.setBasrUrl("http://192.168.11.113:9000/");
Constants.getInstance().init(secret,privateKey,publicKey,appId,"3600");
// Constants.setLanguage(Language.zh_TW);
}
@Test
public void getCoinList () {
initAllParameters();
BaseVo<CoinResponseData> baseVo = PaymentInfo.getCoinList();
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getCurrencyList() {
initAllParameters();
BaseVo<CurrencyResponseData> baseVo = PaymentInfo.getCurrencyList();
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getPay() {
initAllParameters();
String orderNo = "SJDD" + String.valueOf(System.currentTimeMillis());
BaseVo<PayResponseData> baseVo = PaymentInfo.pay("","10", CoinNameEnum.USDT, CurrencyCodeEnum.USD, "17788888888", orderNo,
"我要买买买", "", "", OrderTypeCodeEnum.BY_AMOUNT);
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void cancle() {
initAllParameters();
BaseVo<PayResponseData> baseVo = PaymentInfo.cancleOrder("ZF202108190219318429919697");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getOrderInfo() {
initAllParameters();
BaseVo<OrderInfoResponseData> baseVo = PaymentInfo.getOrderInfo("ZF202108180540250532839870");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getPaymentInfo() {
initAllParameters();
BaseVo<PaymentInfoResponseData> baseVo = PaymentInfo.getPaymentInfo(CoinNameEnum.USDT,"0004" ,"ZF202108130826005085856666");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getRefund() {
initAllParameters();
BaseVo<RefundResponseData> baseVo = PaymentInfo.refund(RefundType.NEW_ADDRESS,"TEQrvHyU54YibVHMGb7475n8y3mXBofaaR", "15.8", "ZF202108130826005085856666", "退1个,啦啦啦");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getRefundInfo() {
initAllParameters();
BaseVo<RefundInfoResponseData> baseVo = PaymentInfo.getRefunds("ZF202107280739365664124421");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getCoinChainCodes() {
initAllParameters();
BaseVo<CoinChainCodeResp> baseVo = PaymentInfo.getCoinChainCodes(CoinNameEnum.USDT);
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void withdraw() {
initAllParameters();
String orderNo = "SHYH" + String.valueOf(System.currentTimeMillis());
BaseVo<WithdrawResponse> baseVo = PaymentInfo.withdraw("TRC20","TEQrvHyU54YibVHMGb7475n8y3mXBofaaR", "8", CoinNameEnum.USDT, orderNo, orderNo,"500",OrderTypeCodeEnum.BY_AMOUNT,CurrencyCodeEnum.CNY);
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void makeup() {
initAllParameters();
BaseVo<MakeUpResponse> baseVo = PaymentInfo.maleUp("需要补单","ZF202108130838338493182222");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getCallBack() {
initAllParameters();
BaseVo<PaymentCallBackResponse> baseVo = PaymentInfo.getCallback("ZF202107221114581046391184");
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void getPrice() {
initAllParameters();
BaseVo<CoinPriceResponse> baseVo = PaymentInfo.getCoinPrice(CoinNameEnum.USDT,CurrencyCodeEnum.CNY);
if (baseVo.getCode() == 200) {
System.out.println("-------------------------" + baseVo.getData().toString());
}else {
System.out.println(baseVo.getCode() + "-------------------------" + baseVo.getMsg());
}
}
@Test
public void verifySignAndGetResult () {
initAllParameters();
String bodystring = "{\"address\":\"TQ1EgPhuDXLvDfycCBQadbfbLkBPhEDoZX\",\"amountPaid\":\"15.26717557\",\"coinName\":\"USDT\",\"orderCode\":\"ZF202106221133335640422688\",\"paymentStatus\":1,\"protocolName\":\"TRC20\",\"result\":true}";
String headstring = "uCJasnGz<KEY>;
PaymentInfo.verifySignAndGetResult(headstring, bodystring, new CallBackListener<PaymentCallBackResponse>() {
@Override
public void onFinish(PaymentCallBackResponse data) {
System.out.println("PaymentResultResponse = " + data.toString());
}
@Override
public void onError(int errorCode, String msg) {
System.out.println("errorCode=" + errorCode + "msg =" + msg);
}
}, new CallBackListener<UserWithdrawCallBackResponse>() {
@Override
public void onFinish(UserWithdrawCallBackResponse data) {
System.out.println("UserWithdrawCallBackResponse = " + data.toString());
}
@Override
public void onError(int errorCode, String msg) {
System.out.println("errorCode=" + errorCode + "msg =" + msg);
}
}, new CallBackListener<MakeUpCallBackResponse>() {
@Override
public void onFinish(MakeUpCallBackResponse data) {
System.out.println("UserWithdrawCallBackResponse = " + data.toString());
}
@Override
public void onError(int errorCode, String msg) {
System.out.println("errorCode=" + errorCode + "msg =" + msg);
}
});
}
@Test
public void getBillRecord () {
initAllParameters();
LocalDateTime start = LocalDateTime.now();
LocalDateTime end = LocalDateTime.now();
// PaymentInfo.getBillRecords( null, null, 10, 1, new CallBackListener<BillRecord>() {
// @Override
// public void onFinish(BillRecord data) {
//
// }
//
// @Override
// public void onError(int errorCode, String msg) {
//
// }
// });
}
}
<file_sep>package me.doupay.sdk.bean;
import java.util.List;
public class CurrencyResponseData {
private List<RecordsBean> records;
public List<RecordsBean> getRecords() {
return records;
}
public void setRecords(List<RecordsBean> records) {
this.records = records;
}
public static class RecordsBean {
/**
* isDefault : 0
* name : 美元
* currency : USA
*/
private int isDefault;
private String name;
private String currency;
public int getIsDefault() {
return isDefault;
}
public void setIsDefault(int isDefault) {
this.isDefault = isDefault;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
@Override
public String toString() {
return "RecordsBean{" +
"isDefault=" + isDefault +
", name='" + name + '\'' +
", currency='" + currency + '\'' +
'}';
}
}
@Override
public String toString() {
return "CurrencyResponseData{" +
"records=" + records +
'}';
}
}
<file_sep>package me.doupay.sdk.interfaceCallback;
public interface CallBackListener<T> {
void onFinish(T data);
void onError(int errorCode,String msg);
}
<file_sep>package me.doupay.sdk;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
import me.doupay.sdk.sign.AES;
public class AESTest {
@Test
public void sign() {
String timeStamp = "1610697341483";
String appId = "502808ee5427490abb40375022e28578";
String secret = "<KEY>";
// JDK 151 之前需要下载 JCE https://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters
String advancedPermissionsSign = AES.Encrypt(appId + timeStamp, secret);
System.out.println(advancedPermissionsSign);
}
}
<file_sep>plugins {
id 'java-library'
id 'kotlin'
}
apply from:"../JavaLib.gradle"
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
implementation 'org.json:json:20180813'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.json:json:20180813'
}<file_sep>package me.doupay.sdk.bean;
import java.util.List;
public class PaymentInfoResponseData {
/**
* address :
* amount :
* chainCoinCode :
* chainCoinName :
* exchangeRate :
* isDefault : 0
* paymentMethods : [{"channelList":[{"icon":"","link":"","name":"","remark":""}],"paymentMethodCode":"","paymentMethodName":""}]
* paymentStatus : 0
* protocolName :
*/
private String address;
private String amount;
private String chainCoinCode;
private String chainCoinName;
private String exchangeRate;
private int isDefault;
private int paymentStatus;
private String protocolName;
private List<PaymentMethodsBean> paymentMethods;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getChainCoinCode() {
return chainCoinCode;
}
public void setChainCoinCode(String chainCoinCode) {
this.chainCoinCode = chainCoinCode;
}
public String getChainCoinName() {
return chainCoinName;
}
public void setChainCoinName(String chainCoinName) {
this.chainCoinName = chainCoinName;
}
public String getExchangeRate() {
return exchangeRate;
}
public void setExchangeRate(String exchangeRate) {
this.exchangeRate = exchangeRate;
}
public int getIsDefault() {
return isDefault;
}
public void setIsDefault(int isDefault) {
this.isDefault = isDefault;
}
public int getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(int paymentStatus) {
this.paymentStatus = paymentStatus;
}
public String getProtocolName() {
return protocolName;
}
public void setProtocolName(String protocolName) {
this.protocolName = protocolName;
}
public List<PaymentMethodsBean> getPaymentMethods() {
return paymentMethods;
}
public void setPaymentMethods(List<PaymentMethodsBean> paymentMethods) {
this.paymentMethods = paymentMethods;
}
public static class PaymentMethodsBean {
/**
* channelList : [{"icon":"","link":"","name":"","remark":""}]
* paymentMethodCode :
* paymentMethodName :
*/
private String paymentMethodCode;
private String paymentMethodName;
private List<ChannelListBean> channelList;
public String getPaymentMethodCode() {
return paymentMethodCode;
}
public void setPaymentMethodCode(String paymentMethodCode) {
this.paymentMethodCode = paymentMethodCode;
}
public String getPaymentMethodName() {
return paymentMethodName;
}
public void setPaymentMethodName(String paymentMethodName) {
this.paymentMethodName = paymentMethodName;
}
public List<ChannelListBean> getChannelList() {
return channelList;
}
public void setChannelList(List<ChannelListBean> channelList) {
this.channelList = channelList;
}
public static class ChannelListBean {
/**
* icon :
* link :
* name :
* remark :
*/
private String icon;
private String link;
private String name;
private String remark;
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
@Override
public String toString() {
return "PaymentMethodsBean{" +
"paymentMethodCode='" + paymentMethodCode + '\'' +
", paymentMethodName='" + paymentMethodName + '\'' +
", channelList=" + channelList +
'}';
}
}
}
| 3d11e747e7aa4c601ddfa79adea104c702ad86ee | [
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 25 | Kotlin | doupay/doupay-java | 19be1e3b53f8edce926e5f68394278e5814bba06 | 94ec04a360cdcca06aa4b0b7a0b32957e7910af4 |
refs/heads/master | <repo_name>syo16/Advanced-Unix-Programming<file_sep>/section7/test7-4.c
#include "../apue.h"
int main(int argc, char *argv[]) {
for (int i=0; i < argc; i++) {
printf("%s\n", argv[i]);
}
}
<file_sep>/section7/test.c
#include "../apue.h"
int main() {
printf(getcwd());
}
| 7f9410d62278557833feb6bd14139e16041a73ed | [
"C"
] | 2 | C | syo16/Advanced-Unix-Programming | 18957bb921fd8a722428fb9ba1e03d687b3af588 | 0ac5695f410b615f527f87c2b2b7e7b57f3c6605 |
refs/heads/main | <repo_name>kidandcat/gigya-flutter-plugin<file_sep>/example/ios/Runner/GigyaProviders/GoogleWrapper.swift
//
// GoogleWrapper.swift
// GigyaSwift
//
// Created by <NAME> on 15/04/2019.
// Copyright © 2019 Gigya. All rights reserved.
//
import UIKit
import GoogleSignIn
import Gigya
class GoogleWrapper: ProviderWrapperProtocol {
var clientID: String?
private lazy var googleLogin: GoogleInternalWrapper = {
return GoogleInternalWrapper()
}()
required init() {
}
func login(params: [String: Any]? = nil, viewController: UIViewController? = nil,
completion: @escaping (_ jsonData: [String: Any]?, _ error: String?) -> Void) {
googleLogin.login(params: params, viewController: viewController, completion: completion)
}
func logout() {
googleLogin.logout()
}
}
private class GoogleInternalWrapper: NSObject {
let defaultScopes = ["https://www.googleapis.com/auth/plus.login", "email"]
var clientID: String? = {
return Bundle.main.infoDictionary?["GoogleClientID"] as? String
}()
var googleServerClientID: String? {
return Bundle.main.infoDictionary?["GoogleServerClientID"] as? String
}
lazy var googleLogin: GIDSignIn = {
return GIDSignIn.sharedInstance()
}()
private var completionHandler: (_ jsonData: [String: Any]?, _ error: String?) -> Void = { _, _ in }
override init() {
super.init()
googleLogin.clientID = clientID
googleLogin.serverClientID = googleServerClientID
googleLogin.scopes = defaultScopes
googleLogin.delegate = self
}
func login(params: [String: Any]? = nil, viewController: UIViewController? = nil,
completion: @escaping (_ jsonData: [String: Any]?, _ error: String?) -> Void) {
completionHandler = completion
GIDSignIn.sharedInstance().presentingViewController = viewController
googleLogin.signIn()
}
func logout() {
googleLogin.signOut()
}
}
extension GoogleInternalWrapper: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
guard error == nil else {
completionHandler(nil, error.localizedDescription)
return
}
let jsonData = ["accessToken": user.serverAuthCode ?? ""]
completionHandler(jsonData, nil)
}
func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
}
// Present a view that prompts the user to sign in with Google
func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
viewController.present(viewController, animated: true, completion: nil)
}
// Dismiss the "Sign in with Google" view
func sign(_: GIDSignIn!, dismiss viewController: UIViewController!) {
viewController.dismiss(animated: true, completion: nil)
}
}
<file_sep>/example/README.md
# gigya_flutter_plugin_example
Demonstrates how to use the gigya_flutter_plugin plugin.
<file_sep>/example/android/app/src/main/kotlin/com/sap/gigya_flutter_plugin_example/MainActivity.kt
package com.sap.gigya_flutter_plugin_example
import com.gigya.android.sdk.account.models.GigyaAccount
import com.sap.gigya_flutter_plugin.GigyaFlutterPlugin
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
// Copy this code to you Android app.
//
// Reference the plugin and register your SDK initialization parameters.
val plugin: GigyaFlutterPlugin= flutterEngine.plugins.get(GigyaFlutterPlugin::class.java) as GigyaFlutterPlugin
plugin.registerWith(application, GigyaAccount::class.java, flutterEngine.dartExecutor.binaryMessenger)
}
}
<file_sep>/ios/Classes/SwiftGigyaFlutterPluginTyped.swift
import Flutter
import UIKit
import Gigya
public class SwiftGigyaFlutterPluginTyped<T: GigyaAccountProtocol> : NSObject, FlutterPlugin, GigyaInstanceProtocol {
enum GigyaMethods: String {
case getPlatformVersion
case sendRequest
case loginWithCredentials
case registerWithCredentials
case isLoggedIn
case getAccount
case setAccount
case logOut
case socialLogin
case showScreenSet
case addConnection
case removeConnection
// intteruptions cases
case getConflictingAccounts
case linkToSite
case linkToScoial
case resolveSetAccount
}
var sdk: GigyaSdkWrapper<T>?
public static func register(with registrar: FlutterPluginRegistrar) {
// Stub. Not used.
// Registering using non static register method.
}
public func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "gigya_flutter_plugin", binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(self, channel: channel)
}
init(accountSchema: T.Type) {
sdk = GigyaSdkWrapper(accountSchema: accountSchema)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let method = GigyaMethods(rawValue: call.method)
// Methods without arguments
switch method {
case .getPlatformVersion:
result("iOS " + UIDevice.current.systemVersion)
return
case .isLoggedIn:
sdk?.isLoggedIn(result: result)
return
case .logOut:
sdk?.logOut(result: result)
return
case .getConflictingAccounts:
sdk?.resolveGetConflictingAccounts(result: result)
return
default:
break
}
// Methods with arguments
guard let args = call.arguments as? [String: Any] else {
result(FlutterError(code: PluginErrors.generalError, message: PluginErrors.generalErrorMessage, details: nil))
return
}
switch method {
case .sendRequest:
sdk?.sendRequest(arguments: args, result: result)
case .loginWithCredentials:
sdk?.loginWithCredentials(arguments: args, result: result)
case .registerWithCredentials:
sdk?.registerWithCredentials(arguments: args, result: result)
case .getAccount:
sdk?.getAccount(arguments: args, result: result)
case .setAccount:
sdk?.setAccount(arguments: args, result: result)
case .socialLogin:
sdk?.socialLogin(arguments: args, result: result)
case .showScreenSet:
sdk?.showScreenSet(arguments: args, result: result)
case .addConnection:
sdk?.addConnection(arguments: args, result: result)
case .removeConnection:
sdk?.removeConnection(arguments: args, result: result)
case .linkToSite:
sdk?.resolveLinkToSite(arguments: args, result: result)
case .linkToScoial:
sdk?.resolveLinkToSocial(arguments: args, result: result)
default:
result(nil)
}
}
}
<file_sep>/CHANGELOG.md
# 0.0.1
Inital release.
* Business APIs.
* Social login (View documentation for supported providers).
* Web Screen-Sets.
* Interruption handling.
# 0.0.2
Example & documentation.
* Example application updates.
* Documentation updates.<file_sep>/ios/Classes/ScreenSetsStreamHandler.swift
//
// ScreenSetsStreamHandler.swift
// gigya_flutter_plugin
//
// Created by <NAME> on 26/11/2020.
//
import Foundation
/**
Screensete event handler stream handler.
*/
class ScreenSetsStreamHandler: NSObject, FlutterStreamHandler {
var sink: FlutterEventSink?
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
sink = events
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
sink = nil
return nil
}
func destroy() {
sink = nil
}
}
<file_sep>/example/ios/Runner/UserHost.swift
//
// UserHost.swift
// Runner
//
// Created by <NAME> on 17/11/2020.
//
import Foundation
import Gigya
struct UserHost: GigyaAccountProtocol {
var UID: String?
var UIDSignature: String?
var apiVersion: Int?
var created: String?
var createdTimestamp: Double?
var isActive: Bool?
var isRegistered: Bool?
var isVerified: Bool?
var lastLogin: String?
var lastLoginTimestamp: Double?
var lastUpdated: String?
var lastUpdatedTimestamp: Double?
var loginProvider: String?
var oldestDataUpdated: String?
var oldestDataUpdatedTimestamp: Double?
var registered: String?
var registeredTimestamp: Double?
var signatureTimestamp: String?
var socialProviders: String?
var verified: String?
var verifiedTimestamp: Double?
var profile: GigyaProfile?
var data: [String: AnyCodable]?
func toJson() -> String {
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(self)
let jsonString = String(data: jsonData, encoding: .utf8)
return jsonString ?? ""
} catch {
print(error)
}
return ""
}
}
<file_sep>/README.md
# SAP CDC Gigya Flutter Plugin
A [Flutter](https://flutter.dev) plugin for interfacing Gigya's native SDKs into a Flutter application using [Dart](https://dart.dev).
## Description
Flutter plugin that provides an interface for the Gigya API.
## Developers Preview Status
The plugin allows you to use the core elements & business API flows available within the SAP Customer Data Cloud mobile SDKs.
This plugin is currently in an early developers preview stage.
## Setup & Gigya core integration
### Android setup
Add the following to your native implementation.
```kotlin
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
// Copy this code to you Android app.
//
// Reference the plugin and register your SDK initialization parameters.
val plugin: GigyaFlutterPlugin= flutterEngine.plugins.get(GigyaFlutterPlugin::class.java) as GigyaFlutterPlugin
plugin.registerWith(application, GigyaAccount::class.java)
}
}
```
Important:
Make sure you have [configured](https://developers.gigya.com/display/GD/Android+SDK+v4#AndroidSDKv4-ViaJSONconfigurationfile:)
the basic steps needed for integrating the Android SDK
### iOS setup
Navigate to **\<your project root\>/ios/Runner/AppDelegate.swift** and add the following:
```swift
import gigya_flutter_plugin
import Gigya
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Copy this code to you Android app.
//
GeneratedPluginRegistrant.register(with: self)
SwiftGigyaFlutterPlugin.register(accountSchema: UserHost.self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
```
Important:
Make sure you have [configured](https://developers.gigya.com/display/GD/Swift+SDK#SwiftSDK-ImplicitInitialization) your *info.plist* file accordinglty.
## Sending a simple request
Sending a request is available using the plugin **send** method.
```
GigyaSdk.instance.send('REQUEST-ENDPOINT', {PARAMETER-MAP}).then((result) {
debugPrint(json.encode(result));
}).catchError((error) {
debugPrint(error.errorDetails);
});
```
Example implementation is demonstrated in the *send_request.dart* class of the provided example application.
## Business APIs
The plugin provides an interface to these core SDK business APIs:
**login, register, getAccount, getAccount, isLoggedIn ,logOut, addConnection, removeConnection**
Implement them using the same request structure as shown above.
Example application includes the various implementations.
## Social login
Use the "socialLogin" interface in order to perform social login using supported providers.
The Flutter plugin supports the same *providers supported by the Core Gigya SDK.
Supported social login providers:
google, facebook, line, wechat, apple, amazon, linkedin, yahoo.
## Embedded social providers
Specific social providers (Facebook, Google) require additional setup. This due to the their
requirement for specific (embedded) SDKs.
```
Example for both Facebook & Google are implemented in the example application.
```
### Facebook
Follow the core SDK documentation and instructions for setting Facebook login.
[Android documentation](https://sap.github.io/gigya-android-sdk/sdk-core/#facebook)
[iOS documentation](https://sap.github.io/gigya-android-sdk/sdk-core/#facebook)
iOS: In addition add the following to your Runner's *AppDelegate.swift* file:
```swift
Gigya.sharedInstance(UserHost.self).registerSocialProvider(of: .facebook, wrapper: FacebookWrapper())
```
```
Instead of adding the provider's sdk using gradle/cocoapods you are able to add
the [flutter_facebook_login] plugin to your **pubspec.yaml** dependencies.
```
### Google
Follow the core SDK documentation and instructions for setting Google login.
[Android documentation](https://sap.github.io/gigya-android-sdk/sdk-core/#google)
[iOS documentation](https://sap.github.io/gigya-swift-sdk/GigyaSwift/#google)
iOS: In addition add the following to your Runner's *AppDelegate.swift* file:
```swift
Gigya.sharedInstance(UserHost.self).registerSocialProvider(of: .google, wrapper: GoogleWrapper())
```
```
Instead of adding the provider's sdk using gradle/cocoapods you are able to add
the [google_sign_in] plugin to your **pubspec.yaml** dependencies.
```
### LINE
In order to provider support for LINE provider, please follow the core SDK documentation.
[Android documentation](https://sap.github.io/gigya-android-sdk/sdk-core/#line)
[iOS documentation](https://sap.github.io/gigya-swift-sdk/GigyaSwift/#line)
### WeChat
In order to provider support for WeChat provider, please follow the core SDK documentation.
[Android documentation](https://sap.github.io/gigya-android-sdk/sdk-core/#wechat)
[iOS documentation](https://sap.github.io/gigya-swift-sdk/GigyaSwift/#wechat)
## Using screen-sets
The plugin supports the use of Web screen-sets using the following:
```
GigyaSdk.instance.showScreenSet("Default-RegistrationLogin", (event, map) {
debugPrint('Screen set event received: $event');
debugPrint('Screen set event data received: $map');
});
```
Optional {parameters} map is available.
As in the core SDKs the plugin provides a streaming channel that will stream the
Screen-Sets events (event, map).
event - actual event name.
map - event data map.
## Resolving interruptions
Much like the our core SDKs, resolving interruptions is available using the plugin.
Current supporting interruptions:
* pendingRegistration using the *PendingRegistrationResolver* class.
* pendingVerification using the *PendingVerificationResolver* class.
* conflictingAccounts using the *LinkAccountResolver* class.
Example for resolving **conflictingAccounts** interruptions:
```
GigyaSdk.instance.login(loginId, password).then((result) {
debugPrint(json.encode(result));
final response = Account.fromJson(result);
// Successfully logged in
}).catchError((error) {
// Interruption may have occurred.
if (error.getInterruption() == Interruption.conflictingAccounts) {
// Reference the correct resolver
LinkAccountResolver resolver = GigyaSdk.instance.resolverFactory.getResolver(error);
} else {
setState(() {
_inProgress = false;
_requestResult = 'Register error\n\n${error.errorDetails}';
});
}
});
```
Once you reference your resolver, create your relevant UI to determine if a site or social linking is
required (see example app for details) and use the relevant "resolve" method.
Example of resolving link to site when trying to link a new social account to a site account.
```
final String password = <PASSWORD>();
resolver.linkToSite(loginId, password).then((res) {
final Account account = Account.fromJson(res);
// Account successfully linked.
});
```
## Known Issues
None
## How to obtain support
* [Via Github issues](https://github.com/SAP/gigya-flutter-plugin/issues)
* [Via SAP standard support](https://developers.gigya.com/display/GD/Opening+A+Support+Incident)
## Contributing
Via pull request to this repository.
## To-Do (upcoming changes)
None
<file_sep>/android/src/main/kotlin/com/sap/gigya_flutter_plugin/GigyaFlutterPlugin.kt
package com.sap.gigya_flutter_plugin
import android.app.Application
import androidx.annotation.NonNull
import com.gigya.android.sdk.Gigya
import com.gigya.android.sdk.account.models.GigyaAccount
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
/** GigyaFlutterPlugin */
class GigyaFlutterPlugin : FlutterPlugin, MethodCallHandler {
lateinit var sdk: GigyaSDKWrapper<*>
/// Main communication method channel.
private lateinit var channel: MethodChannel
private var _messenger: BinaryMessenger? = null
fun <T : GigyaAccount> registerWith(application: Application, accountObj: Class<T>, messenger: BinaryMessenger) {
sdk = GigyaSDKWrapper(application, accountObj)
_messenger = messenger
}
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "gigya_flutter_plugin")
channel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
/// Main channel call handler. Will initiate native wrapper.
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
when (call.method) {
"getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
"sendRequest" -> sdk.sendRequest(call.arguments, result)
"loginWithCredentials" -> sdk.loginWithCredentials(call.arguments, result)
"registerWithCredentials" -> sdk.registerWithCredentials(call.arguments, result)
"isLoggedIn" -> sdk.isLoggedIn(result)
"getAccount" -> sdk.getAccount(call.arguments, result)
"setAccount" -> sdk.setAccount(call.arguments, result)
"logOut" -> sdk.logOut(result)
"socialLogin" -> sdk.socialLogin(call.arguments, result)
"addConnection" -> sdk.addConnection(call.arguments, result)
"removeConnection" -> sdk.removeConnection(call.arguments, result)
"showScreenSet" -> sdk.showScreenSet(call.arguments, result, _messenger)
"getConflictingAccounts" -> sdk.resolveGetConflictingAccounts(result)
"linkToSite" -> sdk.resolveLinkToSite(call.arguments, result)
"linkToSocial"-> sdk.resolveLinkToSocial(call.arguments, result)
"resolveSetAccount"-> sdk.resolveSetAccount(call.arguments, result)
else -> result.notImplemented()
}
}
}
<file_sep>/example/ios/Runner/GigyaProviders/FacebookWrapper.swift
//
// FacebookWrapper.swift
// GigyaSwift
//
// Created by <NAME> on 23/04/2019.
// Copyright © 2019 Gigya. All rights reserved.
//
import Foundation
import FBSDKCoreKit
import FBSDKLoginKit
import Gigya
class FacebookWrapper: ProviderWrapperProtocol {
private var completionHandler: (_ jsonData: [String: Any]?, _ error: String?) -> Void = { _, _ in }
var clientID: String?
private let defaultReadPermissions = ["email"]
lazy var fbLogin: LoginManager = {
return LoginManager()
}()
required init() {
}
func login(params: [String: Any]?, viewController: UIViewController?,
completion: @escaping (_ jsonData: [String: Any]?, _ error: String?) -> Void) {
completionHandler = completion
fbLogin.logIn(permissions: defaultReadPermissions, from: viewController) { (result, error) in
if result?.isCancelled != false {
completion(nil, "cancelled")
return
}
if let error = error {
completion(nil, error.localizedDescription)
}
let jsonData: [String: Any] = ["accessToken": result?.token?.tokenString ?? "", "tokenExpiration": result?.token?.expirationDate.timeIntervalSince1970 ?? 0]
completion(jsonData, nil)
}
}
func logout() {
fbLogin.logOut()
}
}
<file_sep>/ios/Classes/GigyaSdkWrapper.swift
import Gigya
/**
Plugin specific error constants.
*/
public class PluginErrors {
static let generalError = "700"
static let generalErrorMessage = "general error"
static let missingParameterError = "701"
static let missingParameterMessage = "request parameter missing"
}
public class GigyaSdkWrapper<T: GigyaAccountProtocol> :GigyaInstanceProtocol {
let sdk: GigyaCore<T>?
let resolverHelper: ResolverHelper<T> = ResolverHelper()
init(accountSchema: T.Type) {
// Initializing the Gigya SDK instance.
GigyaDefinitions.versionPrefix = "flutter_0.0.2_"
sdk = Gigya.sharedInstance(accountSchema)
}
// MARK: - Main instance
/**
Send general/antonymous request
*/
func sendRequest(arguments: [String: Any], result: @escaping FlutterResult) {
guard let endpoint = arguments["endpoint"] as? String,
let parameters = arguments["parameters"] as? [String:Any] else {
result(FlutterError(code: PluginErrors.missingParameterError, message: PluginErrors.missingParameterMessage, details: nil))
return
}
sdk?.send(api: endpoint, params: parameters) { (gigyaResponse) in
switch gigyaResponse {
case .success(let data):
let json = data.mapValues { $0.value }.asJson
result(json)
case .failure(let error):
switch error {
case .gigyaError(let d):
result(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
result(FlutterError(code: PluginErrors.generalError, message: PluginErrors.generalErrorMessage, details: nil))
}
}
}
}
/**
Login using credentials (loginId/password combination with optional parameter map).
*/
func loginWithCredentials(arguments: [String: Any], result: @escaping FlutterResult) {
guard let loginId = arguments["loginId"] as? String,
let password = arguments["password"] as? String else {
result(FlutterError(code: PluginErrors.missingParameterError, message: PluginErrors.missingParameterMessage, details: nil))
return
}
resolverHelper.currentResult = result
// Optional parameter map.
let parameters = arguments["parameters"] as? [String: Any] ?? [:]
sdk?.login(loginId: loginId, password: <PASSWORD>, params: parameters) { [weak self] loginResult in
switch loginResult {
case .success(let data):
let mapped = self?.mapObject(data)
self?.resolverHelper.currentResult?(mapped)
self?.resolverHelper.dispose()
case .failure(let error):
self?.saveResolvesIfNeeded(interruption: error.interruption)
switch error.error {
case .gigyaError(let ge):
self?.resolverHelper.currentResult?(FlutterError(code: "\(ge.errorCode)", message: ge.errorMessage, details: ge.toDictionary()))
default:
break;
}
}
}
}
/**
Register a new user using credentials (email/password combination with optional parameter map).
*/
func registerWithCredentials(arguments: [String: Any], result: @escaping FlutterResult) {
guard let email = arguments["email"] as? String,
let password = arguments["password"] as? String else {
result(FlutterError(code: PluginErrors.missingParameterError, message: PluginErrors.missingParameterMessage, details: nil))
return
}
resolverHelper.currentResult = result
// Optional parameter map.
let parameters = arguments["parameters"] as? [String: Any] ?? [:]
sdk?.register(email: email, password: <PASSWORD>, params: parameters) { [weak self] loginResult in
switch loginResult {
case .success(let data):
let mapped = self?.mapObject(data)
self?.resolverHelper.currentResult?(mapped)
self?.resolverHelper.dispose()
case .failure(let error):
self?.saveResolvesIfNeeded(interruption: error.interruption)
switch error.error {
case .gigyaError(let ge):
self?.resolverHelper.currentResult?(FlutterError(code: "\(ge.errorCode)", message: ge.errorMessage, details: ge.toDictionary()))
default:
break;
}
}
}
}
/**
Check login status.
*/
func isLoggedIn(result: @escaping FlutterResult) {
let logInState = sdk?.isLoggedIn() ?? false
result(logInState)
}
/**
Request active account.
*/
func getAccount(arguments: [String: Any], result: @escaping FlutterResult) {
// Optionals.
let clearCache = arguments["invalidate"] as? Bool ?? false
let parameters = arguments["parameters"] as? [String: Any] ?? [:]
sdk?.getAccount(clearCache, params: parameters) { [weak self] accountResult in
switch accountResult {
case .success(let data):
let mapped = self?.mapObject(data)
result(mapped)
case .failure(let error):
switch error {
case .gigyaError(let d):
result(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
result(FlutterError(code: PluginErrors.generalError, message: error.localizedDescription, details: nil))
}
}
}
}
/**
Update account information
*/
func setAccount(arguments: [String: Any], result: @escaping FlutterResult) {
let account = arguments["account"] as? [String: Any] ?? [:]
sdk?.setAccount(with: account, completion: { [weak self] accountResult in
switch accountResult {
case .success(let data):
let mapped = self?.mapObject(data)
result(mapped)
case .failure(let error):
switch error {
case .gigyaError(let d):
result(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
result(FlutterError(code: PluginErrors.generalError, message: error.localizedDescription, details: nil))
}
}
})
}
/**
Logout of existing session.
*/
func logOut(result: @escaping FlutterResult) {
sdk?.logout(completion: { gigyaResponse in
switch gigyaResponse {
case .success( _):
result(nil)
case .failure(let error):
switch error {
case .gigyaError(let d):
result(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
result(FlutterError(code: PluginErrors.generalError, message: error.localizedDescription, details: nil))
}
}
})
}
/**
Social login with given provider & provider sessions.
*/
func socialLogin(arguments: [String: Any], result: @escaping FlutterResult) {
guard
let viewController = getDisplayedViewController(),
let providerString = arguments["provider"] as? String,
let provider = GigyaSocialProviders(rawValue: providerString)
else {
result(FlutterError(code: PluginErrors.generalError, message: "provider not exists", details: nil))
return
}
resolverHelper.currentResult = result
let parameters = arguments["parameters"] as? [String: Any] ?? [:]
sdk?.login(
with: provider,
viewController: viewController,
params: parameters) { [weak self] (gigyaResponse) in
switch gigyaResponse {
case .success(let data):
let mapped = self?.mapObject(data)
self?.resolverHelper.currentResult?(mapped)
self?.resolverHelper.dispose()
case .failure(let error):
self?.saveResolvesIfNeeded(interruption: error.interruption)
switch error.error {
case .gigyaError(let d):
self?.resolverHelper.currentResult?(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
self?.resolverHelper.currentResult?(FlutterError(code: "", message: error.error.localizedDescription, details: nil))
}
}
}
}
func addConnection(arguments: [String: Any], result: @escaping FlutterResult) {
guard
let viewController = getDisplayedViewController(),
let providerString = arguments["provider"] as? String,
let provider = GigyaSocialProviders(rawValue: providerString)
else {
result(FlutterError(code: PluginErrors.generalError, message: "provider not exists", details: nil))
return
}
let parameters = arguments["parameters"] as? [String: Any] ?? [:]
sdk?.addConnection(
provider: provider,
viewController: viewController,
params: parameters) { [weak self] gigyaResponse in
switch gigyaResponse {
case .success(let data):
let mapped = self?.mapObject(data)
result(mapped)
case .failure(let error):
switch error {
case .gigyaError(let d):
result(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
result(FlutterError(code: PluginErrors.generalError, message: error.localizedDescription, details: nil))
}
}
}
}
func removeConnection(arguments: [String: Any], result: @escaping FlutterResult) {
guard
let providerString = arguments["provider"] as? String,
let provider = GigyaSocialProviders(rawValue: providerString)
else {
result(FlutterError(code: PluginErrors.generalError, message: "provider not exists", details: nil))
return
}
sdk?.removeConnection(provider: provider) { gigyaResponse in
switch gigyaResponse {
case .success(let data):
let returnData = data.mapValues { $0.value }
result(returnData)
case .failure(let error):
switch error {
case .gigyaError(let d):
result(FlutterError(code: "\(d.errorCode)", message: d.errorMessage, details: d.toDictionary()))
default:
result(FlutterError(code: PluginErrors.generalError, message: error.localizedDescription, details: nil))
}
}
}
}
/**
Show screensets call.
*/
func showScreenSet(arguments: [String: Any], result: @escaping FlutterResult) {
guard
let viewController = getDisplayedViewController(),
let screenSet = arguments["screenSet"] as? String else {
return
}
// Create streamer
var screenSetsEventHandler: ScreenSetsStreamHandler? = ScreenSetsStreamHandler()
let eventChannel = FlutterEventChannel(name: "screensetEvents", binaryMessenger: SwiftGigyaFlutterPlugin.registrar!.messenger())
eventChannel.setStreamHandler(screenSetsEventHandler)
// Release the await request
result(nil)
//TODO missing onAfterValidation in SDK.
sdk?.showScreenSet(
with: screenSet,
viewController: viewController,
params: arguments) { [weak self] event in
switch event {
case .error(let event):
screenSetsEventHandler?.sink?(["event":"onError", "data" : event])
case .onHide(let event):
screenSetsEventHandler?.sink?(["event":"onHide", "data" : event])
screenSetsEventHandler?.destroy()
screenSetsEventHandler = nil
case .onLogin(account: let account):
screenSetsEventHandler?.sink?(["event":"onLogin", "data" : self?.mapObject(account) ?? [:]])
case .onLogout:
screenSetsEventHandler?.sink?(["event":"onLogout"])
case .onConnectionAdded:
screenSetsEventHandler?.sink?(["event":"onConnectionAdded"])
case .onConnectionRemoved:
screenSetsEventHandler?.sink?(["event":"onConnectionRemoved"])
case .onBeforeScreenLoad(let event):
screenSetsEventHandler?.sink?(["event":"onBeforeScreenLoad", "data" : event])
case .onAfterScreenLoad(let event):
screenSetsEventHandler?.sink?(["event":"onAfterScreenLoad", "data" : event])
case .onBeforeValidation(let event):
screenSetsEventHandler?.sink?(["event":"onBeforeValidation", "data" : event])
case .onAfterValidation(let event):
screenSetsEventHandler?.sink?(["event":"onAfterValidation", "data" : event])
case .onBeforeSubmit(let event):
screenSetsEventHandler?.sink?(["event":"onBeforeSubmit", "data" : event])
case .onSubmit(let event):
screenSetsEventHandler?.sink?(["event":"onSubmit", "data" : event])
case .onAfterSubmit(let event):
screenSetsEventHandler?.sink?(["event":"onAfterSubmit", "data" : event])
case .onFieldChanged(let event):
screenSetsEventHandler?.sink?(["event":"onFieldChanged", "data" : event])
case .onCanceled:
screenSetsEventHandler?.sink?(["event":"onCanceled", "data" : [:]])
screenSetsEventHandler?.destroy()
screenSetsEventHandler = nil
}
}
}
}
// MARK: - Resolvers
extension GigyaSdkWrapper {
/**
Link account - handler for fetching conflicting accounts from current intrruption state.
*/
func resolveGetConflictingAccounts(result: @escaping FlutterResult) {
guard let resolver = resolverHelper.linkAccountResolver else {
result(FlutterError(code: PluginErrors.generalError, message: "resolver not found", details: nil))
return
}
result(mapObject(resolver.conflictingAccount!))
}
/**
Link account - resolving link to site.
*/
func resolveLinkToSite(arguments: [String: Any], result: @escaping FlutterResult) {
resolverHelper.currentResult = result
guard let resolver = resolverHelper.linkAccountResolver else {
result(FlutterError(code: PluginErrors.generalError, message: "resolver not found", details: nil))
return
}
guard
let loginId = arguments["loginId"] as? String ,
let password = arguments["password"] as? String else {
result(FlutterError(code: PluginErrors.generalError, message: PluginErrors.generalErrorMessage, details: nil))
return
}
resolver.linkToSite(loginId: loginId, password: password)
}
/**
Link account - resolving link to social.
*/
func resolveLinkToSocial(arguments: [String: Any], result: @escaping FlutterResult) {
resolverHelper.currentResult = result
guard let resolver = resolverHelper.linkAccountResolver else {
result(FlutterError(code: PluginErrors.generalError, message: "resolver not found", details: nil))
return
}
guard let viewController = getDisplayedViewController(),
let providerString = arguments["provider"] as? String,
let provider = GigyaSocialProviders(rawValue: providerString)
else {
result(FlutterError(code: PluginErrors.generalError, message: PluginErrors.generalErrorMessage, details: nil))
return
}
resolver.linkToSocial(provider: provider, viewController: viewController)
}
/**
Pending registration - resolving missing account data.
*/
func resolveSetAccount(arguments: [String: Any], result: @escaping FlutterResult) {
resolverHelper.currentResult = result
guard let resolver = resolverHelper.pendingRegistrationResolver else {
result(FlutterError(code: PluginErrors.generalError, message: "resolver not found", details: nil))
return
}
resolver.setAccount(params: arguments)
}
}
extension GigyaSdkWrapper {
private func saveResolvesIfNeeded(interruption: GigyaInterruptions<T>?) {
guard let interruption = interruption else {
return
}
switch interruption {
case .pendingRegistration(let resolver):
resolverHelper.pendingRegistrationResolver = resolver
case .pendingVerification(let regToken):
resolverHelper.regToken = regToken
case .conflitingAccount(let resolver):
resolverHelper.linkAccountResolver = resolver
default: break
}
}
}
class ResolverHelper<T: GigyaAccountProtocol> {
var currentResult: FlutterResult?
var linkAccountResolver: LinkAccountsResolver<T>?
var pendingRegistrationResolver: PendingRegistrationResolver<T>?
var regToken: String?
func dispose() {
linkAccountResolver = nil
pendingRegistrationResolver = nil
regToken = nil
}
}
<file_sep>/ios/Classes/SwiftGigyaFlutterPlugin.swift
import Flutter
import UIKit
import Gigya
public class SwiftGigyaFlutterPlugin: NSObject, FlutterPlugin {
static var registrar: FlutterPluginRegistrar?
public static func register(with registrar: FlutterPluginRegistrar) {
self.registrar = registrar
}
public static func register<T: GigyaAccountProtocol>(accountSchema: T.Type) {
guard let registrar = self.registrar else { return }
let instance = SwiftGigyaFlutterPluginTyped(accountSchema: accountSchema)
instance.register(with: registrar)
}
}
<file_sep>/android/src/main/kotlin/com/sap/gigya_flutter_plugin/GigyaSDKWrapper.kt
package com.sap.gigya_flutter_plugin
import android.app.Application
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import com.gigya.android.sdk.*
import com.gigya.android.sdk.account.models.GigyaAccount
import com.gigya.android.sdk.api.GigyaApiResponse
import com.gigya.android.sdk.api.IApiRequestFactory
import com.gigya.android.sdk.interruption.IPendingRegistrationResolver
import com.gigya.android.sdk.interruption.link.ILinkAccountsResolver
import com.gigya.android.sdk.network.GigyaError
import com.gigya.android.sdk.ui.plugin.GigyaPluginEvent
import com.gigya.android.sdk.utils.CustomGSONDeserializer
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import java.util.*
class GigyaSDKWrapper<T : GigyaAccount>(application: Application, accountObj: Class<T>) {
private var sdk: Gigya<T>
private var resolverHelper: ResolverHelper = ResolverHelper()
private var currentResult: MethodChannel.Result? = null
val gson = GsonBuilder().registerTypeAdapter(object : TypeToken<Map<String?, Any?>?>() {}.type, CustomGSONDeserializer()).create()
init {
Gigya.setApplication(application)
sdk = Gigya.getInstance(accountObj)
try {
val pInfo: PackageInfo = application.packageManager.getPackageInfo(application.packageName, 0)
val version: String = pInfo.versionName
val ref: IApiRequestFactory = Gigya.getContainer().get(IApiRequestFactory::class.java)
ref.setSDK("flutter_${version}_android_${(Gigya.VERSION).toLowerCase(Locale.ENGLISH)}")
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
/**
* Send general/antonymous request.
*/
fun sendRequest(arguments: Any, channelResult: MethodChannel.Result) {
val endpoint: String? = (arguments as Map<*, *>)["endpoint"] as String?
if (endpoint == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val parameters: Map<String, Any>? = arguments["parameters"] as Map<String, Any>?
if (parameters == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
sdk.send(endpoint, parameters, object : GigyaCallback<GigyaApiResponse>() {
override fun onSuccess(p0: GigyaApiResponse?) {
p0?.let {
channelResult.success(it.asJson())
} ?: channelResult.notImplemented()
}
override fun onError(p0: GigyaError?) {
p0?.let {
channelResult.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: channelResult.notImplemented()
}
})
}
/**
* Login using credentials (loginId/password combination with optional parameter map).
*/
fun loginWithCredentials(arguments: Any, channelResult: MethodChannel.Result) {
currentResult = channelResult
val loginId: String? = (arguments as Map<*, *>)["loginId"] as String?
if (loginId == null) {
currentResult!!.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val password: String? = arguments["password"] as String?
if (password == null) {
currentResult!!.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val parameters: Map<String, Any>? = arguments["parameters"] as Map<String, Any>?
val loginParams = mutableMapOf<String, Any>("loginID" to loginId, "password" to <PASSWORD>)
if (parameters != null) {
loginParams.putAll(parameters)
}
sdk.login(loginParams, object : GigyaLoginCallback<T>() {
override fun onSuccess(p0: T) {
resolverHelper.clear()
val mapped = mapObject(p0)
currentResult!!.success(mapped)
}
override fun onError(p0: GigyaError?) {
p0?.let {
currentResult!!.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: currentResult!!.notImplemented()
}
override fun onConflictingAccounts(response: GigyaApiResponse, resolver: ILinkAccountsResolver) {
resolverHelper.linkAccountResolver = resolver
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
override fun onPendingRegistration(response: GigyaApiResponse, resolver: IPendingRegistrationResolver) {
resolverHelper.pendingRegistrationResolver = resolver
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
override fun onPendingVerification(response: GigyaApiResponse, regToken: String?) {
resolverHelper.regToken = regToken
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
})
}
/**
* Register a new user using credentials (email/password combination with optional parameter map).
*/
fun registerWithCredentials(arguments: Any, channelResult: MethodChannel.Result) {
currentResult = channelResult;
val email: String? = (arguments as Map<*, *>)["email"] as String?
if (email == null) {
currentResult!!.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val password: String? = arguments["password"] as String?
if (password == null) {
currentResult!!.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val parameters: MutableMap<String, Any> = arguments["parameters"] as MutableMap<String, Any>?
?: mutableMapOf()
sdk.register(email, password, parameters!!, object : GigyaLoginCallback<T>() {
override fun onSuccess(p0: T) {
resolverHelper.clear()
val mapped = mapObject(p0)
currentResult!!.success(mapped)
}
override fun onError(p0: GigyaError?) {
p0?.let {
currentResult!!.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: currentResult!!.notImplemented()
}
override fun onConflictingAccounts(response: GigyaApiResponse, resolver: ILinkAccountsResolver) {
resolverHelper.linkAccountResolver = resolver
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
override fun onPendingRegistration(response: GigyaApiResponse, resolver: IPendingRegistrationResolver) {
resolverHelper.pendingRegistrationResolver = resolver
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
override fun onPendingVerification(response: GigyaApiResponse, regToken: String?) {
resolverHelper.regToken = regToken
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
})
}
/**
* Check login status.
*/
fun isLoggedIn(channelResult: MethodChannel.Result) {
val loginState = sdk.isLoggedIn
channelResult.success(loginState)
}
/**
* Request active account.
*/
fun getAccount(arguments: Any, channelResult: MethodChannel.Result) {
val invalidate: Boolean = (arguments as Map<*, *>)["invalidate"] as Boolean? ?: false
sdk.getAccount(invalidate, object : GigyaCallback<T>() {
override fun onSuccess(p0: T) {
val mapped = mapObject(p0)
channelResult.success(mapped)
}
override fun onError(p0: GigyaError?) {
p0?.let {
channelResult.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: channelResult.notImplemented()
}
})
}
/**
* Update account information
*/
fun setAccount(arguments: Any, channelResult: MethodChannel.Result) {
val account: MutableMap<String, Any>? = (arguments as Map<*, *>)["account"] as MutableMap<String, Any>?
if (account == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
sdk.setAccount(account, object : GigyaCallback<T>() {
override fun onSuccess(p0: T) {
val mapped = mapObject(p0)
channelResult.success(mapped)
}
override fun onError(p0: GigyaError?) {
p0?.let {
channelResult.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: channelResult.notImplemented()
}
})
}
/**
* Logout of existing session.
*/
fun logOut(channelResult: MethodChannel.Result) {
sdk.logout(object : GigyaCallback<GigyaApiResponse>() {
override fun onSuccess(p0: GigyaApiResponse?) {
channelResult.success(null)
}
override fun onError(p0: GigyaError?) {
p0?.let {
channelResult.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: channelResult.notImplemented()
}
});
}
/**
* Social login with given provider & provider sessions.
*/
fun socialLogin(arguments: Any, channelResult: MethodChannel.Result) {
currentResult = channelResult
val provider: String? = (arguments as Map<*, *>)["provider"] as String?
if (provider == null) {
currentResult!!.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val parameters: MutableMap<String, Any> = arguments["parameters"] as MutableMap<String, Any>?
?: mutableMapOf()
sdk.login(provider, parameters, object : GigyaLoginCallback<T>() {
override fun onSuccess(p0: T) {
val mapped = mapObject(p0)
resolverHelper.clear()
currentResult!!.success(mapped)
}
override fun onError(p0: GigyaError?) {
p0?.let {
currentResult!!.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: currentResult!!.notImplemented()
}
override fun onOperationCanceled() {
currentResult!!.error(CANCELED_ERROR, CANCELED_ERROR_MESSAGE, null)
}
override fun onConflictingAccounts(response: GigyaApiResponse, resolver: ILinkAccountsResolver) {
resolverHelper.linkAccountResolver = resolver
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
override fun onPendingRegistration(response: GigyaApiResponse, resolver: IPendingRegistrationResolver) {
resolverHelper.pendingRegistrationResolver = resolver
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
override fun onPendingVerification(response: GigyaApiResponse, regToken: String?) {
resolverHelper.regToken = regToken
currentResult!!.error(response.errorCode.toString(), response.errorDetails, response.asMap())
}
})
}
/**
* Add social connection to active session.
*/
fun addConnection(arguments: Any, channelResult: MethodChannel.Result) {
val provider: String? = (arguments as Map<*, *>)["provider"] as String?
if (provider == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
sdk.addConnection(provider, object : GigyaLoginCallback<T>() {
override fun onSuccess(p0: T) {
val mapped = mapObject(p0)
channelResult.success(mapped)
}
override fun onError(p0: GigyaError?) {
p0?.let {
channelResult.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: channelResult.notImplemented()
}
override fun onOperationCanceled() {
channelResult.error(CANCELED_ERROR, CANCELED_ERROR_MESSAGE, null)
}
})
}
/**
* Remove social connection.
*/
fun removeConnection(arguments: Any, channelResult: MethodChannel.Result) {
val provider: String? = (arguments as Map<*, *>)["provider"] as String?
if (provider == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
sdk.removeConnection(provider, object : GigyaCallback<GigyaApiResponse>() {
override fun onSuccess(p0: GigyaApiResponse?) {
p0?.let {
val mapped = gson.fromJson<Map<String, Any>>(it.asJson(), object : TypeToken<Map<String, Any>>() {}.type)
channelResult.success(mapped)
} ?: channelResult.notImplemented()
}
override fun onError(p0: GigyaError?) {
p0?.let {
channelResult.error(p0.errorCode.toString(), p0.localizedMessage, p0.data)
} ?: channelResult.notImplemented()
}
})
}
private var screenSetsEventsSink: EventChannel.EventSink? = null
private var screenSetEventsChannel: EventChannel? = null
private var screenSetsEventsHandler: EventChannel.StreamHandler? = null;
/**
* Trigger embedded web screen sets.
*/
fun showScreenSet(arguments: Any, channelResult: MethodChannel.Result, messenger: BinaryMessenger?) {
if (messenger == null) {
channelResult.error(GENERAL_ERROR, GENERAL_ERROR_MESSAGE, mapOf<String, Any>())
return
}
val screenSet: String? = (arguments as Map<*, *>)["screenSet"] as String?
if (screenSet == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val parameters: MutableMap<String, Any> = arguments["parameters"] as MutableMap<String, Any>?
?: mutableMapOf()
// Set events channel & handler.
screenSetEventsChannel = EventChannel(messenger, "screensetEvents")
screenSetsEventsHandler = object : EventChannel.StreamHandler {
override fun onListen(p0: Any?, sink: EventChannel.EventSink?) {
screenSetsEventsSink = sink
}
override fun onCancel(p0: Any?) {
screenSetEventsChannel = null
}
}
screenSetEventsChannel!!.setStreamHandler(screenSetsEventsHandler)
sdk.showScreenSet(screenSet, true, parameters, object : GigyaPluginCallback<T>() {
override fun onError(event: GigyaPluginEvent?) {
screenSetsEventsSink?.success(mapOf("event" to "onError", "data" to event!!.eventMap))
}
override fun onCanceled() {
screenSetsEventsSink?.error("200001", "Operation canceled", null)
screenSetsEventsHandler = null
screenSetEventsChannel = null
screenSetsEventsSink = null
}
override fun onHide(event: GigyaPluginEvent, reason: String?) {
screenSetsEventsSink?.success(mapOf("event" to "onHide", "reason" to reason!!, "data" to event.eventMap))
screenSetsEventsHandler = null
screenSetEventsChannel = null
screenSetsEventsSink = null
}
override fun onLogin(accountObj: T) {
screenSetsEventsSink?.success(mapOf("event" to "onLogin", "data" to mapObject(accountObj)))
}
override fun onLogout() {
screenSetsEventsSink?.success(mapOf("event" to "onLogout"))
}
override fun onConnectionAdded() {
screenSetsEventsSink?.success(mapOf("event" to "onConnectionAdded"))
}
override fun onConnectionRemoved() {
screenSetsEventsSink?.success(mapOf("event" to "onConnectionRemoved"))
}
override fun onBeforeScreenLoad(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onBeforeScreenLoad", "data" to event.eventMap))
}
override fun onAfterScreenLoad(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onAfterScreenLoad", "data" to event.eventMap))
}
override fun onBeforeValidation(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onBeforeValidation", "data" to event.eventMap))
}
override fun onAfterValidation(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onAfterValidation", "data" to event.eventMap))
}
override fun onBeforeSubmit(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onBeforeSubmit", "data" to event.eventMap))
}
override fun onSubmit(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onSubmit", "data" to event.eventMap))
}
override fun onAfterSubmit(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onAfterSubmit", "data" to event.eventMap))
}
override fun onFieldChanged(event: GigyaPluginEvent) {
screenSetsEventsSink?.success(mapOf("event" to "onFieldChanged", "data" to event.eventMap))
}
})
// Return void result. Streaming channel will handled plugin events.
channelResult.success(null)
}
/**
* Link account - handler for fetching conflicting accounts from current intrruption state.
*/
fun resolveGetConflictingAccounts(channelResult: MethodChannel.Result) {
resolverHelper.linkAccountResolver?.let { resolver ->
val conflictingAccounts = resolver.conflictingAccounts
channelResult.success(mapObject(conflictingAccounts));
} ?: channelResult.notImplemented()
}
/**
* Link account - resolving link to site.
*/
fun resolveLinkToSite(arguments: Any, channelResult: MethodChannel.Result) {
currentResult = channelResult
resolverHelper.linkAccountResolver?.let { resolver ->
val loginId: String? = (arguments as Map<*, *>)["loginId"] as String?
if (loginId == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
val password: String? = (arguments as Map<*, *>)["password"] as String?
if (password == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
resolver.linkToSite(loginId, password)
} ?: channelResult.notImplemented()
}
/**
* Link account - resolving link to social.
*/
fun resolveLinkToSocial(arguments: Any, channelResult: MethodChannel.Result) {
currentResult = channelResult
resolverHelper.linkAccountResolver?.let { resolver ->
val provider: String? = (arguments as Map<*, *>)["provider"] as String?
if (provider == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
resolver.linkToSocial(provider)
} ?: channelResult.notImplemented()
}
/**
* Pending registration - resolving missing account data.
*/
fun resolveSetAccount(arguments: Any, channelResult: MethodChannel.Result) {
currentResult = channelResult
resolverHelper.pendingRegistrationResolver?.let { resolver ->
val data: Map<String, Any>? = arguments as Map<String, Any>
if (data == null) {
channelResult.error(MISSING_PARAMETER_ERROR, MISSING_PARAMETER_MESSAGE, mapOf<String, Any>())
return
}
resolver.setAccount(data)
} ?: channelResult.notImplemented()
}
/**
* Map typed object to a Map<String, Any> object in order to pass on to
* the method channel response.
*/
private fun <V> mapObject(obj: V): Map<String, Any> {
val jsonString = gson.toJson(obj)
return gson.fromJson(jsonString, object : TypeToken<Map<String, Any>>() {}.type)
}
companion object {
const val GENERAL_ERROR = "700"
const val GENERAL_ERROR_MESSAGE = "general error"
const val MISSING_PARAMETER_ERROR = "701"
const val MISSING_PARAMETER_MESSAGE = "request parameter missing"
const val CANCELED_ERROR = "702"
const val CANCELED_ERROR_MESSAGE = "Operation canceled"
}
}
class ResolverHelper {
var linkAccountResolver: ILinkAccountsResolver? = null
var pendingRegistrationResolver: IPendingRegistrationResolver? = null
var regToken: String? = null
fun clear() {
linkAccountResolver = null
pendingRegistrationResolver = null
regToken = null
}
}<file_sep>/android/settings.gradle
rootProject.name = 'gigya_flutter_plugin'
<file_sep>/ios/Classes/GigyaSdk+Extensions.swift
//
// GigyaSdk+Extensions.swift
// gigya_flutter_plugin
//
// Created by <NAME> on 26/11/2020.
//
import Foundation
extension Dictionary {
var asJson: String {
if let jsonData: Data = try? JSONSerialization.data(withJSONObject: self, options:[]),
let result = String(data: jsonData, encoding: .utf8) {
return result
}
return ""
}
}
extension GigyaSdkWrapper {
/**
Get top view controller.
*/
func getDisplayedViewController() -> UIViewController? {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
}
/**
Mapping typed account object.
*/
func mapObject<T: Codable>(_ obj: T) -> [String: Any] {
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(obj)
let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: [])
as? [String: Any]
return dictionary ?? [:]
} catch {
print(error)
}
return [:]
}
}
| db11cd19ab46d259b4ca4a0b3fccee948929bec7 | [
"Swift",
"Kotlin",
"Markdown",
"Gradle"
] | 15 | Swift | kidandcat/gigya-flutter-plugin | e077647958ed5b31b10b7306cd01013ffa88ef2a | 3c07de148a64b1408a8bb190e854d03930237b56 |
refs/heads/master | <repo_name>NNN-kakimoto/sample_laravel<file_sep>/README.md
# フォームを使うサンプルアプリのリポジトリ
## メモ
- kakimotoが作る
- Aoki先輩にプルリク(とりあえず)
- コントローラとビューを作成してフォーム画面でなんやかんやするまでやる<file_sep>/app/Http/Controllers/top.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class top extends Controller
{
//index
public function index(){
return view('index');
}
public function send(Request $request){
$memo = $request->input('memo');
//$request = "めも";
//return view('pages.send', compact('memo'));
// 「,」以降でビューに送るデータを変数に、"ビューでの変数名"=>$コントローラでの変数名
}
}
| 2391976fc12435dc9cd589416b413171ee20e209 | [
"Markdown",
"PHP"
] | 2 | Markdown | NNN-kakimoto/sample_laravel | 4970921893d024a28af3efac7fb4cbf0e8a6e4ad | b906c78f574eaeeaaed124ff07a5e285771ebaa1 |
refs/heads/master | <repo_name>TomSpencerLondon/fizzbuzz<file_sep>/app.rb
require 'sinatra'
require './lib/fizzbuzz.rb'
enable :sessions
get '/' do
p session
@result = fizzbuzz(session[:guess].to_i)
erb :index
end
get '/fizz' do
session[:guess] = params[:guess]
redirect to ('/')
end
<file_sep>/README.md
Fizzbuzz Game
=====
This is a simple program that prints the numbers from 1 to 100. For multiples of three the program prints "Fizz" instead of the number and for multiples of five we print "Buzz". For numbers which are multiples of both three and five the program prints "FizzBuzz".
Objectives and Learning Achievements
=====
- pair coding: I worked with <NAME> and we finished this task extremely quickly together. It was fun to start pair coding.
- TDD: The task was an opportunity to introduce Test driven development, a software programming practice that increases code quality and program design. This is an important requirement throughout top software development companies.
<file_sep>/spec/fizzbuzz_spec.rb
require "fizzbuzz"
describe 'fizzbuzz' do
it 'returns "fizz" when passed 3' do
expect(fizzbuzz(3)).to eq 'fizz'
end
it 'returns "buzz" when passed 5' do
expect(fizzbuzz(5)).to eq 'buzz'
end
it 'returns "fizzbuzz" when passed 15' do
expect(fizzbuzz(15)).to eq 'fizzbuzz'
end
it 'returns "fizz" when passed a number divisible by three' do
expect(fizzbuzz(33)).to eq 'fizz'
end
it 'returns "buzz" when passed a number divisible by 5' do
expect(fizzbuzz(55)).to eq 'buzz'
end
it 'returns "fizzbuzz" when passed a number both divisible by 5 and 3' do
expect(fizzbuzz(45)).to eq 'fizzbuzz'
end
it 'returns the number when passed a number divisible by neither 3 nor 5' do
expect(fizzbuzz(1)).to eq 1
end
end
| b2bab18c69283ce9acf4985efdcbb7fa3d13681f | [
"Markdown",
"Ruby"
] | 3 | Ruby | TomSpencerLondon/fizzbuzz | 49c6146c88cfbc75ec6f83ce344f84bd66fb0099 | 71759afc34033cfeb7a3c141b3a2d0048e6b7c0b |
refs/heads/master | <repo_name>Mrz12345-controller/WxDemo<file_sep>/src/main/java/net/com/wxdemo/config/WeChatConfig.java
package net.com.wxdemo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value="classpath:application.properties")
public class WeChatConfig {
@Value("${WX.appid}")
private String appid;
@Value("${WX.app_sercet}")
private String appsercet;
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getAppsercet() {
return appsercet;
}
public void setAppsercet(String appsercet) {
this.appsercet = appsercet;
}
}
<file_sep>/src/main/java/net/com/wxdemo/controller/TestController.java
package net.com.wxdemo.controller;
import net.com.wxdemo.config.WeChatConfig;
import net.com.wxdemo.mapper.VideoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private WeChatConfig weChatConfig;
@GetMapping("test_config")
public String Test(){
System.out.println(weChatConfig.getAppid());
return "完成测试";
}
@Autowired
private VideoMapper videoMapper;
@RequestMapping("test")
public Object TestDB(){
return videoMapper.findAll();
}
}
<file_sep>/README.md
#测试微信
[微信openapi](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/api.html)
| 7a5248267e5fe979bc0254136f227338edcbf1d7 | [
"Markdown",
"Java"
] | 3 | Java | Mrz12345-controller/WxDemo | dae7c7bd316cbd47a276d2f467635198e5e2a72b | 1c87675e4660baa90ce49368f1e3846e16211354 |
refs/heads/master | <repo_name>mohammed-albeltagi/Library<file_sep>/Library.Repositories.Interfaces/IRepository.cs
using System.Linq;
using System.Threading.Tasks;
using Library.Models;
namespace Library.Repositories.Interfaces
{
public interface IRepository<T> where T : BaseEntity
{
IQueryable<T> GetAll();
Task<T> GetById(int id);
Task Add(T entity);
Task<T> Update(int id, T entity);
Task Delete(int id);
void Save();
}
}
<file_sep>/Library.DTO/DTOs/Category/CategoryDetails.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Library.DTO
{
public class CategoryDetails
{
}
}
<file_sep>/README.md
# Library
To build FE app
-- npm i
then
-- ng serve
For testing
-- http://localhost:4200/user
-- http://localhost:4200/register
-- http://localhost:4200/home for adding Categories and Subcategories
User just can register, login and add Categories and Subcategories
<file_sep>/Library-SPA/src/app/home/home.component.ts
import { ToastrService } from 'ngx-toastr';
import { UserService } from './../services/user.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styles: []
})
export class HomeComponent implements OnInit {
categories: any;
formModel = {
name: '',
parentCategoryId: null
};
constructor(private router: Router, private service: UserService, private toastr: ToastrService) { }
ngOnInit() {
this.service.getCategory().subscribe(
res => {
this.categories = res;
},
err => {
console.log(err);
},
);
}
onSubmit(form: NgForm) {
this.service.postCategory(form.value).subscribe(
res => {
this.ngOnInit();
this.formModel.name = '';
this.formModel.parentCategoryId = null;
},
err => {
if (err.status === 400) {
this.toastr.error('Incorrect username or password.', 'Authentication failed.');
} else {
console.log(err);
}
}
);
}
onLogout() {
localStorage.removeItem('token');
this.router.navigate(['/user']);
}
}
<file_sep>/Library.API/Controllers/CategoryController.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using Library.DTO;
using Library.Models;
using Library.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace Library.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class CategoryController : ControllerBase
{
private readonly ICategoryService _categoryService;
public CategoryController(ICategoryService categoryService)
{
_categoryService = categoryService;
}
[HttpGet]
//GET : /api/Category
public IActionResult Get()
{
var categories = _categoryService.GetAll();
return Ok(categories);
}
[HttpPost]
//GET : /api/Category
public IActionResult Post(CategoryCreate categoryCreate)
{
_categoryService.Create(categoryCreate);
return Ok();
}
}
}<file_sep>/Library.Models/Models/BaseEntity.cs
using System.ComponentModel.DataAnnotations;
namespace Library.Models
{
public class BaseEntity
{
[Key, Required]
public int Id { get; set; }
}
}
<file_sep>/Library-SPA/src/app/services/user.service.ts
import { Injectable } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private fb: FormBuilder, private http: HttpClient) { }
readonly BaseURI = 'http://localhost:53745/api';
login(formData) {
return this.http.post(this.BaseURI + '/ApplicationUser/Login', formData);
}
register(formData) {
return this.http.post(this.BaseURI + '/ApplicationUser/Register', formData);
}
postCategory(formData) {
return this.http.post(this.BaseURI + '/Category' , formData);
}
getCategory() {
return this.http.get(this.BaseURI + '/Category');
}
}
<file_sep>/Library.Models/Models/Book.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Library.Models
{
public class Book : BaseEntity
{
[Required]
public string Name { get; set; }
[Required]
public int CategoryId { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
}
<file_sep>/Library.DTO/DTOs/Category/CategoryCreate.cs
using System;
namespace Library.DTO
{
public class CategoryCreate
{
public string Name { get; set; }
public Nullable<int> ParentCategoryId { get; set; }
}
}
<file_sep>/Library.Services/CategoryService.cs
using Library.DTO;
using Library.Models;
using Library.Repositories.Interfaces;
using Library.Services.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Library.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> _repository;
public CategoryService(IRepository<Category> repository)
{
_repository = repository;
}
public IEnumerable<CategorySummary> GetAll()
{
return _repository.GetAll().Select(x => new CategorySummary
{
Name = x.Name,
Id = x.Id
});
}
public CategoryDetails Get(int id, Category category)
{
var cat = _repository.Update(id, category);
_repository.Save();
return cat == null ? null : Map(cat);
}
public void Create(CategoryCreate category)
{
var CategoryEntity = new Category
{
Name = category.Name,
ParentCategoryId = category.ParentCategoryId
};
_repository.Add(CategoryEntity);
_repository.Save();
}
private static CategoryDetails Map(Task<Category> category)
{
return new CategoryDetails
{
};
}
}
}
<file_sep>/Library.Services.Interfaces/ICategoryService.cs
using Library.DTO;
using Library.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Library.Services.Interfaces
{
public interface ICategoryService
{
IEnumerable<CategorySummary> GetAll();
CategoryDetails Get(int id, Category category);
void Create(CategoryCreate category);
}
}
<file_sep>/Library.API/Controllers/ApplicationUserController.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Library.DTO;
using Library.Models;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Options;
using System.Linq;
namespace Library.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ApplicationUserController : ControllerBase
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ApplicationSettings _appSettings;
private readonly SignInManager<IdentityUser> _signInManager;
public ApplicationUserController(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
IOptions<ApplicationSettings> appSettings)
{
_userManager = userManager;
_appSettings = appSettings.Value;
_signInManager = signInManager;
}
[HttpPost]
[Route("Login")]
//POST : /api/ApplicationUser/Login
public async Task<IActionResult> PostUserData(UserDTO model)
{
try
{
var user = await _userManager.FindByNameAsync(model.UserName);
var chkPass = await _userManager.CheckPasswordAsync(user, model.Password);
if (user != null && chkPass)
{
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("UserID",user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
return Ok(new { token });
}
else
return BadRequest(new { message = "Username or password is incorrect." });
}
catch (Exception)
{
return BadRequest(new { message = "Username or password is incorrect." });
}
}
[HttpPost]
[Route("Register")]
//POST : /api/ApplicationUser/Login
public async Task<IActionResult> RegisterUserData(UserDTO model)
{
try
{
if (ModelState.IsValid)
{
// Copy data from RegisterViewModel to IdentityUser
var user = new IdentityUser
{
UserName = model.UserName
};
// Store user data in AspNetUsers database table
var result = await _userManager.CreateAsync(user, model.Password);
// If user is successfully created, sign-in the user using
// SignInManager and redirect to index action of HomeController
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
if (user != null)
{
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("UserID",user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
return Ok(new { token });
}
}
// If there are any errors, add them to the ModelState object
// which will be displayed by the validation summary tag helper
if(result.Errors.Any())
{
return BadRequest();
}
}
return BadRequest();
}
catch (Exception)
{
return BadRequest(new { message = "Username or password is incorrect." });
}
}
}
}<file_sep>/Library.Models/Models/Category.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Library.Models
{
public class Category : BaseEntity
{
[Required]
public string Name { get; set; }
public Nullable<int> ParentCategoryId { get; set; }
[ForeignKey("ParentCategoryId")]
public Category SupCategory { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
}
<file_sep>/Library.Repositories/Repository.cs
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Library.Models;
using Library.Repositories.Interfaces;
namespace Library.Repositories
{
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private readonly DataContext _dbContext;
public Repository(DataContext dbContext)
{
_dbContext = dbContext;
}
IQueryable<T> IRepository<T>.GetAll()
{
return _dbContext.Set<T>().AsNoTracking();
}
public async Task<T> GetById(int id)
{
return await _dbContext.Set<T>()
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id);
}
public async Task Add(T entity)
{
await _dbContext.Set<T>().AddAsync(entity);
}
public async Task<T> Update(int id, T entity)
{
_dbContext.Set<T>().Update(entity);
return entity;
}
public async Task Delete(int id)
{
var entity = await GetById(id);
_dbContext.Set<T>().Remove(entity);
}
public void Save()
{
_dbContext.SaveChangesAsync();
}
}
}
| 215b79c968c47f7580abe3bc068530049315c39e | [
"Markdown",
"C#",
"TypeScript"
] | 14 | C# | mohammed-albeltagi/Library | 22161799f03e64a3323d6acb2b9c2b926a9d7301 | fe73f926992a53f280f559db9a48a738993e260b |
refs/heads/master | <file_sep>from models.corridor import Corridor
from text import epilogue, intro, run_corridor
def main():
corridor = Corridor()
with open("book/001-intro.md", "w") as intro_file:
intro_file.write("# Introduction\n\n")
intro_file.write(intro(corridor) + "\n\n")
corridor_history = (
f"Nobody knows who built the {corridor.name}, they only know that it's dangerous, "
"that it probably is populated by some creatures and possibly treasure."
)
intro_file.write(corridor_history + "\n")
messages = run_corridor(corridor)
for chapter, run_messages in messages.items():
number = str(chapter + 1).zfill(3)
with open(f"book/{number}-run.md", "w") as run_file:
for m in run_messages:
run_file.write(m + "\n\n")
number = chapter + 3
with open(f"book/{str(number).zfill(3)}-epilogue.md", "w") as epilogue_file:
epilogue_file.write("# Epilogue\n\n")
epilogue_file.write(epilogue(corridor) + "\n\n")
number += 1
with open(f"book/{str(number).zfill(3)}-appendix.md", "w") as appendix_file:
appendix_file.write("# Appendix\n")
for s in corridor.stats():
appendix_file.write(s + "\n")
if __name__ == "__main__":
main()
<file_sep># The Longest Corridor

[Photo by <NAME>](https://unsplash.com/photos/dbj0O83MM5Y/share)
### Requirements
- Python 3.7
- Pandoc
#### Arch linux
sudo pacman -S texlive-core pandoc # For generating the book
<file_sep>from typing import Any
from dragn.dice import D20
from dataclasses import dataclass
from models.weapons import Weapon
@dataclass
class Item:
kind: str
material: str
def __str__(self):
return f"{self.kind} of {self.material}"
@dataclass
class Scroll:
name: str
action: Any
description: str
def apply(self, character):
self.action(character)
return self.description.format(character.name)
def __str__(self):
return f"{self.name}"
@dataclass
class Food:
kind: str
amount: int
def get_amount_string(self):
amount_per_string = {
5: "a bit of",
10: "some",
15: "a portion of",
20: "a big chunk of",
}
for amount, string in amount_per_string.items():
if self.amount < amount:
return string
return "a banquet of"
def __str__(self):
return f"{self.get_amount_string()} {self.kind}".title()
<file_sep>import random
import uuid
from typing import Any, List
from dragn.dice import *
from dataclasses import dataclass
@dataclass
class Material:
name: str
difficulty_modifier: int
damage_modifier: int
def __str__(self):
return self.name
@dataclass
class WeaponKind:
name: str
damage_modifier: Any
difficulty_modifier: int
hit_choices: List[str]
def __str__(self) -> str:
return self.name
def __gt__(self, other):
return self.name > other.name
@dataclass
class Weapon:
kind: WeaponKind
material: Material
def __post_init__(self):
self.kills = {}
self.name = ""
def register_kill(self, killed_char):
race = str(killed_char.race)
if race in self.kills:
self.kills[race] += 1
else:
self.kills[race] = 1
number_of_kills = sum([k for k in self.kills.values()])
@property
def difficulty(self) -> int:
return self.material.difficulty_modifier + self.kind.difficulty_modifier
@property
def damage(self) -> int:
return self.material.damage_modifier + self.kind.damage_modifier()
def __str__(self) -> str:
if self.name:
return f"{self.name}"
else:
return f"{self.material} {self.kind}"
@property
def hit_str(self):
return random.choice(self.kind.hit_choices)
@property
def value(self):
return (self.material.damage_modifier + self.kind.damage_modifier.max_value) - (
self.kind.difficulty_modifier + self.material.difficulty_modifier
)
IRON = Material("Iron", 2, 2)
STEEL = Material("Steel", 3, 4)
MITHRIL = Material("Mithril", 1, 8)
WEAPON_KINDS = [
WeaponKind("Sword", D6, 1, ["slash", "takes a chunk out of"]),
WeaponKind("Greatsword", D20, 6, ["slash", "tore"]),
WeaponKind("Mace", D12, 4, ["whack", "smack"]),
WeaponKind("Halberd", D8, 4, ["slice", "poke"]),
]
def get_iron_weapon():
return Weapon(random.choice(WEAPON_KINDS), IRON)
def get_steel_weapon():
return Weapon(random.choice(WEAPON_KINDS), STEEL)
def get_mithril_weapon():
return Weapon(random.choice(WEAPON_KINDS), MITHRIL)
<file_sep>import random
import tracery
from tracery.modifiers import base_english
from combat import fight
from models.items import Food, Item, Scroll
from models.weapons import get_iron_weapon, Weapon, get_steel_weapon
NUMBER_OF_RUNS = 500
def _get_corpora(corpora_name):
with open(f"corpora/{corpora_name}.txt", "r") as corpora_file:
return [n.strip() for n in corpora_file.readlines()]
def get_str_from_rules(rules, part):
grammar = tracery.Grammar(rules)
grammar.add_modifiers(base_english)
return grammar.flatten(part)
def get_word_from_corpora(corpora_name):
return random.choice(_get_corpora(corpora_name))
def intro(corridor):
rules = {
"introduction": f"For years the {corridor.name} remained unexplored, until it was found out that it held the precious '#item#', from them on, countless adventurers ventured into the depths of the {corridor.name}, looking for fame and fortune.",
"item": str(corridor.boss),
}
return get_str_from_rules(rules, "#introduction#")
def run_corridor(corridor):
from models.characters import create_adventurer, Character
messages = {}
for chapter in range(1, NUMBER_OF_RUNS + 1):
messages[chapter] = []
msgs = messages[chapter]
# If the corridor has changed, this chapter will be about it
if corridor.has_changed:
msgs.append(f"# The {corridor.name}")
msgs.append(
f"The {corridor.name} contains a {corridor.boss} in the end of it."
)
msgs.append(f"The {corridor.name} also contains:")
for c in corridor.stuff_in_corridor:
if isinstance(c, Character):
msgs.append(f"- {c.full_description}")
corridor.has_changed = False
continue
character = create_adventurer()
msgs.append(f"# {character.name} {{#{character.name.replace(' ', '-')}}}")
rules = {
"introduction": f"{character.name} is a {character.race} #backstory#, they heard of the rumours and came to see the {corridor.name} for themselves.",
"backstory": [
"from a town nearby",
"looking for fame and fortune",
"looking for adventure",
],
}
msgs.append(get_str_from_rules(rules, "#introduction#"))
msgs.append(
f"{character.name} slowly steps into the dark {corridor.name} to start their walk..."
)
for challenge in corridor:
challenge_messages = deal_with_challenge(challenge, character, corridor)
msgs.extend(challenge_messages)
if not character.is_alive:
break
msgs.extend(corridor.update())
return messages
def deal_with_challenge(challenge, character, corridor):
from models.characters import Character, create_goblin
messages = [f"{character.name} takes a few more steps in the dark {corridor.name}"]
if isinstance(challenge, Character):
enemy = challenge
messages.append(
f"{character.name} finds {enemy.name}, a {enemy.race} and get's ready for a fight."
)
character, enemy, fight_message = fight(character, enemy)
messages.append(fight_message)
if not enemy.is_alive:
messages.append(f"{enemy.name} dies")
old_weapon = character.weapon
equiped = character.loot(enemy.weapon)
if equiped:
messages.append(
f"{character.name} equips {character.weapon} from the corpse"
)
enemy.weapon = old_weapon
elif isinstance(challenge, Item):
item = challenge
messages.append(f"{character.name} picks up the '{item}' triumphantly.")
messages.append(
f"The {character.name} gets corrupted by {item} and becomes the {corridor.name} master."
)
corridor.update_boss(character)
messages.extend(dm_creates_creatures(corridor))
elif isinstance(challenge, Scroll):
messages.append(f"{character.name} finds a dusty scroll and reads it.")
scroll = challenge
messages.append(scroll.apply(character))
corridor.remove_from_corridor(scroll)
messages.append(f"...the scroll crumbles into dust")
elif isinstance(challenge, Food):
messages.append(f"{character.name} finds a {challenge} and gobbles it down.")
character.eat(challenge)
elif isinstance(challenge, Weapon):
weapon = challenge
messages.append(f"{character.name} finds a {weapon}.")
old_weapon = character.weapon
equiped = character.loot(challenge)
if equiped:
messages.append(f"{character.name} equips {weapon}")
corridor.add_to_corridor(old_weapon)
corridor.remove_from_corridor(weapon)
else:
messages.append(
f"After some inspection, {character.name} decides not to take {weapon}"
)
#### #### #### #### ####
if not character.is_alive:
messages.append(f"{character.name} dies")
if character.level > 2:
messages.append(
f"{character.name} gets ressurected by the {corridor.name} and becomes a part of it."
)
corridor.add_to_corridor(character)
else:
messages.append(
f"{character.name} is not worthy for the {corridor.name}. Three goblins get spawned in their place."
)
corridor.add_to_corridor(create_goblin(character.weapon))
corridor.add_to_corridor(create_goblin())
corridor.add_to_corridor(create_goblin())
elif challenge == corridor.boss:
messages.append(f"The {character.name} becomes the new {corridor.name} master.")
corridor.update_boss(character)
messages.extend(dm_creates_creatures(corridor))
return messages
def dm_creates_creatures(corridor):
from models.characters import create_orc
messages = []
messages.append(f"{corridor.boss.name} calls forth the help of more creatures.")
for _ in range(corridor.boss.level):
creature = create_orc(get_steel_weapon())
messages.append(f"- {creature.full_description}")
corridor.add_to_corridor(creature)
return messages
def epilogue(corridor):
return f"This is the story of the {corridor.name}. Time will tell when the next adventurer dares to enter it."
<file_sep>import random
from dragn.dice import D4, D20
from dataclasses import dataclass
from models.weapons import Weapon, get_iron_weapon, get_mithril_weapon
from text import get_word_from_corpora
@dataclass
class Race:
name: str
health: int
armor: int
dex: int
def __str__(self):
return self.name
@dataclass
class Character:
name: str
race: Race
weapon: Weapon
exp: int = 0
level: int = 1
bonus_health: int = 0
bonus_dex: int = 0
bonus_armor: int = 0
def __post_init__(self):
self.health = self.race.health + self.bonus_health
self.armor = self.race.armor + self.bonus_armor
self.dex = self.race.dex + self.bonus_dex
self._max_health = self.health
self.is_zombie = False
self.characteristics = [
get_word_from_corpora("characteristics") for _ in range(3)
]
def resurrect(self):
if not self.is_alive:
self.make_zombie()
self.health = self._max_health
def make_zombie(self):
self.is_zombie = True
self.dex -= 4
self.armor -= 4
def __str__(self):
return self.name
@property
def full_description(self):
zombie = "zombie " if self.is_zombie else ""
characteristics = (
", ".join(self.characteristics[:2]) + " and " + self.characteristics[-1]
)
return f"{self.name} is a {zombie}{self.race}, yielding a {self.weapon}. They are {characteristics}"
@property
def is_alive(self):
if self.health <= 0:
return False
return True
def attack(self, other):
if self.dex + D20() > other.armor:
other.take_damage(self.weapon.damage)
return True
return False
@property
def value(self):
return (self.exp * self.level) + self.dex + self._max_health + self.armor
def gain_exp(self, other):
self.exp += other.value
return self.maybe_level_up()
def maybe_level_up(self):
lvl_by_xp = {2: 50, 3: 100, 4: 200, 5: 400, 6: 600, 7: 830, 8: 1000}
for lvl, xp in lvl_by_xp.items():
if self.level >= lvl:
continue
if self.exp >= xp:
self.level = lvl
self.level_up()
return True
return False
def level_up(self):
self.dex += 1
self.armor += 1
self.health += 5
self._max_health += 5
def eat(self, food):
self.heal(food.amount)
def heal(self, amount):
self.health += amount
if self.health > self._max_health:
self.health = self._max_health
def loot(self, weapon: Weapon):
if self.weapon.value < weapon.value:
self.weapon = weapon
return True
return False
def take_damage(self, damage):
self.health -= damage
@property
def name_and_link(self):
if self.is_adventurer:
return f"[{self.name}](#{self.name.replace(' ', '-')})"
else:
return self.name
@property
def is_adventurer(self):
return self.race not in (ORC, GOBLIN, OGRE)
@property
def stats(self):
zombie = "zombie " if self.is_zombie else ""
return (
f"{self.name_and_link}: a {zombie}{self.race} yielding a {self.weapon}, "
f"DEX: {self.dex} ARMOR: {self.armor} "
f"HP: {self._max_health} LVL: {self.level}"
)
HUMAN = Race("Human", 20, 10, 10)
DWARF = Race("Dwarf", 25, 12, 9)
ELF = Race("Dwarf", 18, 8, 13)
ORC = Race("Orc", 10, 10, 10)
GOBLIN = Race("Goblin", 5, 8, 13)
OGRE = Race("Ogre", 30, 14, 7)
def create_adventurer():
creator = random.choice([_create_dwarf, _create_human, _create_elf])
return creator(get_iron_weapon())
def _create_adventurer(race, weapon):
name = " ".join(
[get_word_from_corpora("first_names"), get_word_from_corpora("last_names")]
)
if random.choice([True, False]):
# May get a second last name
name += get_word_from_corpora("last_names")
return Character(
name, race, weapon, bonus_health=D4(), bonus_armor=D4(), bonus_dex=D4()
)
def _create_elf(weapon):
return _create_adventurer(ELF, weapon)
def _create_human(weapon):
return _create_adventurer(HUMAN, weapon)
def _create_dwarf(weapon):
return _create_adventurer(DWARF, weapon)
def create_enemy(zombie=False):
enemy = random.choice([create_orc, create_goblin])
return enemy(get_iron_weapon(), zombie)
def create_orc(weapon, zombie=False):
return _create_enemy(weapon, ORC, zombie)
def create_ogre():
weapon = get_iron_weapon()
return _create_enemy(weapon, OGRE, False)
def create_goblin(weapon=None, zombie=False):
if not weapon:
weapon = get_iron_weapon()
return _create_enemy(weapon, GOBLIN, zombie)
def _create_enemy(weapon, race, zombie):
character = Character(create_enemy_name(), race, weapon)
if zombie:
character.make_zombie()
return character
def create_enemy_name():
return get_word_from_corpora("enemy_names")
<file_sep>import random
from models.characters import Character, create_enemy, create_goblin, create_ogre
from models.items import Food, Item, Scroll
from models.weapons import Weapon, get_mithril_weapon
from text import get_word_from_corpora
class Corridor:
def __init__(self):
self.boss = create_item()
self.name = "corridor"
self.initial_creation()
self.reset()
self.index = len(self.corridor)
self.stuff_to_remove = []
self.archive = []
self.has_changed = True
def initial_creation(self):
self.stuff_in_corridor = []
self._add_treasure(1)
self._add_enemies(5)
self._add_food(3)
self._add_scrolls(2)
def reset(self):
random.shuffle(self.stuff_in_corridor)
self.corridor = [*self.stuff_in_corridor, self.boss][::-1]
def add_to_corridor(self, thing):
self.stuff_in_corridor.append(thing)
def remove_from_corridor(self, thing):
self.stuff_to_remove.append(thing)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.corridor[self.index]
def update_boss(self, new_boss):
new_boss.take_damage(new_boss.health)
new_boss.resurrect()
self.boss = new_boss
self.has_changed = True
def new_corridor_name(self):
possible_names = ["corridor", "tomb", "crypt", "dungeon", "lair"]
return random.choice([n for n in possible_names if n != self.name])
def update_for(self, name):
self.name = name
messages = []
if name == "crypt":
messages.append("Five zombies are added.")
self._add_zombies(5)
elif name == "lair":
messages.append("One Ogre appears.")
ogre = create_ogre()
self.stuff_in_corridor.append(ogre)
elif name == "corridor":
messages.append("Five different monsters show up to visit.")
ogre = create_ogre()
monsters = [create_enemy() for _ in range(5)]
self.stuff_in_corridor.extend(monsters)
elif name == "dungeon":
messages.append("A group of goblins take camp in the dungeon.")
monsters = [create_goblin() for _ in range(8)]
self.stuff_in_corridor.extend(monsters)
else:
messages.append("Five zombies are added.")
self._add_zombies(5)
return messages
def update(self):
messages = []
if self.has_changed:
new_name = self.new_corridor_name()
messages.append(
f"The {self.name} becomes a {new_name}. It is shuffled and all creatures are ressurected."
)
messages.extend(self.update_for(new_name))
else:
messages.append(
f"The {self.name} is shuffled and all creatures are ressurected."
)
messages.append("Two scrolls are added.")
self._add_scrolls(2)
self._shuffle()
return messages
def _get_number_of_zombies(self):
characters = [c for c in self.stuff_in_corridor if isinstance(c, Character)]
zombies = [c for c in characters if c.is_zombie]
return len(zombies)
def _shuffle(self):
self._ressurect_creatures()
self._remove_things()
self._add_food(int(len(self.stuff_in_corridor) / 10))
self.reset()
self.index = len(self.corridor)
def _ressurect_creatures(self):
for c in self.stuff_in_corridor:
if isinstance(c, Character):
if c.is_zombie and not c.is_alive:
self.stuff_in_corridor.append(c.weapon)
self.stuff_to_remove.append(c)
else:
c.resurrect()
def _add_food(self, amount):
food = [create_food() for _ in range(amount)]
self.stuff_in_corridor.extend(food)
def _add_scrolls(self, amount):
scrolls = [create_scroll() for _ in range(amount)]
self.stuff_in_corridor.extend(scrolls)
def _add_enemies(self, amount):
monsters = [create_enemy() for _ in range(amount)]
self.stuff_in_corridor.extend(monsters)
def _add_zombies(self, amount):
monsters = [create_enemy(zombie=True) for _ in range(amount)]
self.stuff_in_corridor.extend(monsters)
def _add_treasure(self, amount):
treasure = [get_mithril_weapon() for _ in range(amount)]
self.stuff_in_corridor.extend(treasure)
def _remove_things(self):
for s in self.stuff_in_corridor:
if isinstance(s, Food):
self.stuff_to_remove.append(s)
elif isinstance(s, Weapon):
if s.kills == {}:
self.stuff_to_remove.append(s)
for s in self.stuff_to_remove:
if isinstance(s, Character):
self.archive.append(s)
self.stuff_in_corridor = [
s for s in self.stuff_in_corridor if s not in self.stuff_to_remove
]
self.stuff_to_remove = []
def stats(self):
messages = []
messages.append(f"\n## The {self.name} contains:\n")
for c in self.stuff_in_corridor:
if isinstance(c, Character):
messages.append(f"- {c.stats}")
else:
messages.append(f"- {c}")
messages.append(f"- {self.boss.stats}")
messages.append("\n## Notable characters that died permanently:\n")
for c in self.archive:
if c.level > 1:
messages.append(f"- {c.name_and_link}: a {c.race} of level {c.level}")
## WEAPON STATS
messages.append("\n## Weapon stats\n")
weapons = sorted(
[c.weapon for c in self.stuff_in_corridor if isinstance(c, Character)],
key=lambda w: w.kind,
)
weapons.extend([w for w in self.stuff_in_corridor if isinstance(w, Weapon)])
weapons = filter(lambda w: bool(w.kills), weapons)
for w in weapons:
messages.append(f"- {w} killed: {w.kills}")
return messages
def create_item():
return Item(get_word_from_corpora("objects"), get_word_from_corpora("materials"))
def create_food():
return Food(get_word_from_corpora("food"), random.randint(1, 30))
def create_scroll():
scrolls = [
Scroll("Scroll of healing", lambda c: c.heal(5), "{} feels better."),
Scroll("Scroll of pain", lambda c: c.take_damage(5), "{} feels awful."),
Scroll(
"Scroll of uselessness", lambda c: None, "100 butterflies suddenly appear."
),
]
return random.choice(scrolls)
<file_sep>.PHONY: run book proper-book clean clean-proper-book pretty clean-all
run:
python make_book.py
cat book/*.md
book: clean
python make_book.py
pandoc --toc --top-level-division=chapter -f markdown+header_attributes -o the_longest_corridor.epub book/title.txt book/*.md
pandoc --toc -V documentclass=report --top-level-division=chapter -o the_longest_corridor.pdf book/title.txt book/*.md
cat book/*.md
clean:
rm -f book/*.md
rm -f the_longest_corridor.epub
rm -f the_longest_corridor.pdf
pretty:
isort
black .
<file_sep>from dragn.dice import D6
def fight(char1, char2):
if char1.dex + D6() > char2.dex + D6():
attacker, defender = char1, char2
else:
defender, attacker = char1, char2
fight_messages = []
while char1.is_alive and char2.is_alive:
messages = []
if fight_messages:
messages.append(
f"{attacker.name} grips their {attacker.weapon} and attempts to strike {defender.name} again"
)
else:
messages.append(
f"{attacker.name} pulls out their {attacker.weapon} and tries to strike {defender.name}"
)
result = attacker.attack(defender)
if result:
messages.append(f"They easily {attacker.weapon.hit_str} their foe.")
else:
messages.append(f"they miss.")
attacker, defender = defender, attacker
fight_messages.append(", ".join(messages))
if char1.is_alive:
leveled_up = char1.gain_exp(char2)
if leveled_up:
fight_messages.append(f"{char1.name} feels stronger.")
char1.weapon.register_kill(char2)
else:
leveled_up = char2.gain_exp(char1)
if leveled_up:
fight_messages.append(f"{char2.name} feels stronger.")
char2.weapon.register_kill(char1)
return char1, char2, " ".join(fight_messages)
| 233942c865865bc6cc9069a01e8ac77e8fadb258 | [
"Markdown",
"Python",
"Makefile"
] | 9 | Python | LuRsT/the_longest_corridor | 93e64171b723a99f1c1364364734977bb23eab10 | d13e248c258a29aeb79c41152509cab55913bfca |
refs/heads/master | <file_sep>using System.Collections;
using UnityEngine;
public enum TILETYPE
{
NORMAL = 0,
STAIR,
TRAP,
WALL
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct Tiles
{
public TILETYPE _type;
public Transform _tile;
}
public class MapManager : MonoBehaviour {
public Tiles[] _Tile;
public Tiles curTile;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MapManager))]
public class MapManagerInspector : Editor {
public void OnSceneGUI()
{
if (Application.isPlaying)
return;
MapManager mapManager = target as MapManager;
Handles.BeginGUI();
if(GUI.Button(new Rect(10, 10, 100, 30), "NORMAL"))
{
mapManager.curTile = mapManager._Tile[0];
}
if (GUI.Button(new Rect(10, 50, 100, 30), "STAIR"))
{
mapManager.curTile = mapManager._Tile[1];
}
if (GUI.Button(new Rect(10, 90, 100, 30), "TRAP"))
{
mapManager.curTile = mapManager._Tile[2];
}
if (GUI.Button(new Rect(10, 130, 100, 30), "WALL"))
{
mapManager.curTile = mapManager._Tile[3];
}
GUI.color = Color.green;
GUI.Label(new Rect(120, 10, 500, 30), "Edit Mode : " + mapManager.curTile._type);
GUI.color = Color.white;
Handles.EndGUI();
}
}
| 737aedc37a94133bca97e7d280cd956f175e94cc | [
"C#"
] | 3 | C# | GameDeveloperr/Avoid-Police | ddd1c055b9d42cfa697f0bf95e10f923ba8e2c96 | c2a70334fee1fe8de862e8de55d09ab6124384e2 |
refs/heads/master | <repo_name>sf-kansara/mongo<file_sep>/example/raw.js
const qe = require('../lib');
let query = qe('office_collection')
.raws(
['eq', 'character_name', '<NAME>'],
['notin', 'habits', 'manager', 'adult', 'HR'],
['select', true, 'name', 'age', 'address'],
['select', false, '_id'],
['>', 'age', 96],
['skip', 9]
)
.toQuery();
/*
query = {
filter: {
character_name: '<NAME>',
habits: { '$nin': ['manager', 'adult', 'HR'] },
age: { '$gt': 96 }
},
options: {
projection: { name: 1, age: 1, address: 1, _id: 0 },
skip: 9
}
}
*/
console.log(query);
<file_sep>/test/0.individual/query/test-data.js
const fil = require('../filter/test-data');
const opt = require('../option/test-data');
const collection = 'test';
const queries = {
simple: { ...fil.queries, ...opt.queries },
random: {
and: {
eq: ['name', '<NAME>'],
exists: ['job.HR', false],
or: {
in: ['hobby', ['rap', 'parkour']],
all: ['relationships', ['jan', 'pam\'s mom', 'carol', 'donna']],
nin: ['responsibilities', ['be', 'a', 'professional']],
gte: ['crimes', 2500],
lte: ['iq', 10],
lt: ['age', 30],
regex: ['spouse', new RegExp('holly', 'i')]
},
type: ['sales', 'number'],
nor: {
not: ['company', 'dundermifflin']
}
}
}
};
const result = {
simple: {
filter: { ...fil.result.combined },
options: { ...opt.result.combined }
},
random: {
filter: {
'$and': [
{ 'name': '<NAME>' },
{ 'job.HR': { '$exists': false } },
{
'$or': [
{ 'hobby': { '$in': ['rap', 'parkour'] } },
{
'relationships': {
'$all': [
'jan',
'pam\'s mom',
'carol',
'donna'
]
}
},
{ 'responsibilities': { '$nin': ['be', 'a', 'professional'] } },
{ 'crimes': { '$gte': 2500 } },
{ 'iq': { '$lte': 10 } },
{ 'age': { '$lt': 30 } },
{ 'spouse': { '$regex': new RegExp('holly', 'i') } }
]
},
{ 'sales': { '$type': 'number' } },
{ '$nor': [{ 'company': { '$not': 'dundermifflin' } }] }
]
},
options: {}
}
};
module.exports = {
collection, queries, result
};<file_sep>/test/0.individual/option/test-data.js
const collection = 'test';
const queries = {
limit: 10,
offset: 20,
sort: {
asc: ['asc', 'field1', 'field2'],
desc: ['desc', 'field3', 'field4']
},
select: {
select: [true, 'field1', 'field2'],
deselect: [false, 'field3', 'field4']
}
};
const result = {
limit: { limit: queries.limit },
offset: { skip: queries.offset },
sort: {
asc: { sort: { field1: 1, field2: 1 } },
desc: { sort: { field3: -1, field4: -1 } }
},
select: {
select: { projection: { field1: 1, field2: 1 } },
deselect: { projection: { field3: 0, field4: 0 } }
},
combined: {}
};
result.combined = {
...result.limit,
...result.offset,
sort: { ...result.sort.asc.sort, ...result.sort.desc.sort },
projection: { ...result.select.select.projection, ...result.select.deselect.projection }
};
module.exports = {
collection, queries, result
};<file_sep>/test/0.individual/filter/equality.test.js
const { expect } = require('chai');
const filter = require('../../../lib/filter/index');
const testData = require('./test-data');
describe('individual - filter', () => {
it('should throw collection error', () => {
expect(filter.bind({}, 123)).to.throw();
});
it('should build filter object', () => {
expect(filter.bind({}, testData.collection)).to.not.throw();
});
});
describe('individual - filter - eq', () => {
it('should build correct eq filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.eq(testData.queries.eq);
expect(fil.filter).to.eql(testData.result.eq);
});
it('should build correct eq filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.eq(...testData.queries.eq);
expect(fil.filter).to.eql(testData.result.eq);
});
it('should build correct eq filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('eq', testData.queries.eq);
expect(fil.filter).to.eql(testData.result.eq);
});
});
describe('individual - filter - neq', () => {
it('should build correct neq filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.neq(testData.queries.neq);
expect(fil.filter).to.eql(testData.result.neq);
});
it('should build correct neq filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.neq(...testData.queries.neq);
expect(fil.filter).to.eql(testData.result.neq);
});
it('should build correct neq filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('neq', testData.queries.neq);
expect(fil.filter).to.eql(testData.result.neq);
});
});
describe('individual - filter - lt', () => {
it('should build correct lt filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.lt(testData.queries.lt);
expect(fil.filter).to.eql(testData.result.lt);
});
it('should build correct lt filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.lt(...testData.queries.lt);
expect(fil.filter).to.eql(testData.result.lt);
});
it('should build correct lt filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('<', testData.queries.lt);
expect(fil.filter).to.eql(testData.result.lt);
});
});
describe('individual - filter - gt', () => {
it('should build correct gt filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.gt(testData.queries.gt);
expect(fil.filter).to.eql(testData.result.gt);
});
it('should build correct gt filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.gt(...testData.queries.gt);
expect(fil.filter).to.eql(testData.result.gt);
});
it('should build correct gt filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('>', testData.queries.gt);
expect(fil.filter).to.eql(testData.result.gt);
});
});
describe('individual - filter - lte', () => {
it('should build correct lte filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.lte(testData.queries.lte);
expect(fil.filter).to.eql(testData.result.lte);
});
it('should build correct lte filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.lte(...testData.queries.lte);
expect(fil.filter).to.eql(testData.result.lte);
});
it('should build correct lte filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('lte', testData.queries.lte);
expect(fil.filter).to.eql(testData.result.lte);
});
});
describe('individual - filter - gte', () => {
it('should build correct gte filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.gte(testData.queries.gte);
expect(fil.filter).to.eql(testData.result.gte);
});
it('should build correct gte filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.gte(...testData.queries.gte);
expect(fil.filter).to.eql(testData.result.gte);
});
it('should build correct gte filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('gte', testData.queries.gte);
expect(fil.filter).to.eql(testData.result.gte);
});
});
describe('individual - filter - regex', () => {
it('should build correct regex filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.regex(testData.queries.regex);
expect(fil.filter).to.eql(testData.result.regex);
});
it('should build correct regex filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.regex(...testData.queries.regex);
expect(fil.filter).to.eql(testData.result.regex);
});
it('should build correct regex filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('regex', testData.queries.regex);
expect(fil.filter).to.eql(testData.result.regex);
});
});<file_sep>/test/0.individual/option/option.test.js
const { expect } = require('chai');
const option = require('../../../lib/option/index');
const testData = require('./test-data');
describe('individual - options', () => {
it('should throw collection error', () => {
expect(option.bind({}, 123)).to.throw();
});
it('should build option object', () => {
expect(option.bind({}, testData.collection)).to.not.throw();
});
});
describe('individual - options - limit', () => {
it('should build correct limit condition', () => {
const opt = option.call({}, testData.collection);
opt.limit(testData.queries.limit);
expect(opt.option).to.eql(testData.result.limit);
});
it('should build correct limit condition by raw', () => {
const opt = option.call({}, testData.collection);
opt.raw('limit', testData.queries.limit);
expect(opt.option).to.eql(testData.result.limit);
});
});
describe('individual - options - offset', () => {
it('should build correct offset condition', () => {
const opt = option.call({}, testData.collection);
opt.offset(testData.queries.offset);
expect(opt.option).to.eql(testData.result.offset);
});
it('should build correct offset condition by raw', () => {
const opt = option.call({}, testData.collection);
opt.raw('offset', testData.queries.offset);
expect(opt.option).to.eql(testData.result.offset);
});
});
describe('individual - options - sort', () => {
it('should throw error for incorrect sort value', () => {
const opt = option.call({}, testData.collection);
opt.sort(testData.queries.sort.asc);
expect(opt.sort.bind({}, 'notascdesc', ...testData.queries.sort.asc)).to.throw();
});
it('should build correct asc sort condition by arg arr', () => {
const opt = option.call({}, testData.collection);
opt.sort(testData.queries.sort.asc);
expect(opt.option).to.eql(testData.result.sort.asc);
});
it('should build correct asc sort condition by multiple args', () => {
const opt = option.call({}, testData.collection);
opt.sort(...testData.queries.sort.asc);
expect(opt.option).to.eql(testData.result.sort.asc);
});
it('should build correct asc sort condition by raw', () => {
const opt = option.call({}, testData.collection);
opt.raw('sort', testData.queries.sort.asc);
expect(opt.option).to.eql(testData.result.sort.asc);
});
it('should build correct desc sort condition by arg arr', () => {
const opt = option.call({}, testData.collection);
opt.sort(testData.queries.sort.desc);
expect(opt.option).to.eql(testData.result.sort.desc);
});
it('should build correct desc sort condition by multiple args', () => {
const opt = option.call({}, testData.collection);
opt.sort(...testData.queries.sort.desc);
expect(opt.option).to.eql(testData.result.sort.desc);
});
it('should build correct desc sort condition by raw', () => {
const opt = option.call({}, testData.collection);
opt.raw('sort', testData.queries.sort.desc);
expect(opt.option).to.eql(testData.result.sort.desc);
});
});
describe('individual - options - select', () => {
it('should build correct select condition by arg arr', () => {
const opt = option.call({}, testData.collection);
opt.select(testData.queries.select.select);
expect(opt.option).to.eql(testData.result.select.select);
});
it('should build correct select condition by multiple args', () => {
const opt = option.call({}, testData.collection);
opt.select(...testData.queries.select.select);
expect(opt.option).to.eql(testData.result.select.select);
});
it('should build correct select condition by raw', () => {
const opt = option.call({}, testData.collection);
opt.raw('select', testData.queries.select.select);
expect(opt.option).to.eql(testData.result.select.select);
});
it('should build correct deselect condition by arg arr', () => {
const opt = option.call({}, testData.collection);
opt.select(testData.queries.select.deselect);
expect(opt.option).to.eql(testData.result.select.deselect);
});
it('should build correct deselect condition by multiple args', () => {
const opt = option.call({}, testData.collection);
opt.select(...testData.queries.select.deselect);
expect(opt.option).to.eql(testData.result.select.deselect);
});
it('should build correct deselect condition by raw', () => {
const opt = option.call({}, testData.collection);
opt.raw('select', testData.queries.select.deselect);
expect(opt.option).to.eql(testData.result.select.deselect);
});
});
describe('individual - options - combined', () => {
it('should build correct options', () => {
const opt = option.call({}, testData.collection);
opt
.limit(testData.queries.limit)
.raw('offset', testData.queries.offset)
.sort(testData.queries.sort.asc)
.sort(...testData.queries.sort.desc)
.select(testData.queries.select.select)
.raw('select', testData.queries.select.deselect);
expect(opt.option).to.eql(testData.result.combined);
});
it('should build correct options by raws', () => {
const opt = option.call({}, testData.collection);
opt
.raws(
['limit', testData.queries.limit],
['offset', testData.queries.offset],
['sort', testData.queries.sort.asc],
['sort', testData.queries.sort.desc],
['select', testData.queries.select.select],
['select', testData.queries.select.deselect]
);
expect(opt.option).to.eql(testData.result.combined);
});
});<file_sep>/test/0.individual/filter/misc.test.js
const { expect } = require('chai');
const filter = require('../../../lib/filter/index');
const testData = require('./test-data');
describe('individual - filter - exist', () => {
it('should build correct exist filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.exists(testData.queries.exists.exist);
expect(fil.filter).to.eql(testData.result.exists.exist);
});
it('should build correct exist filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.exists(...testData.queries.exists.exist);
expect(fil.filter).to.eql(testData.result.exists.exist);
});
it('should build correct exist filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('exists', testData.queries.exists.exist);
expect(fil.filter).to.eql(testData.result.exists.exist);
});
it('should build correct not exist filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.exists(testData.queries.exists.not_exist);
expect(fil.filter).to.eql(testData.result.exists.not_exist);
});
it('should build correct not exist filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.exists(...testData.queries.exists.not_exist);
expect(fil.filter).to.eql(testData.result.exists.not_exist);
});
it('should build correct not exist filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('exists', testData.queries.exists.not_exist);
expect(fil.filter).to.eql(testData.result.exists.not_exist);
});
});
describe('individual - filter - type', () => {
it('should build correct type filter by arg arr', () => {
const fil = filter.call({}, testData.collection);
fil.type(testData.queries.type);
expect(fil.filter).to.eql(testData.result.type);
});
it('should build correct type filter by multiple args', () => {
const fil = filter.call({}, testData.collection);
fil.type(...testData.queries.type);
expect(fil.filter).to.eql(testData.result.type);
});
it('should build correct type filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('type', testData.queries.type);
expect(fil.filter).to.eql(testData.result.type);
});
});
<file_sep>/lib/option/_type.js
const assert = require('../util/assert');
const definitions = {
limit: {
alias: ['limit'],
_sym: Symbol.for('limit')
},
offset: {
alias: ['offset', 'skip'],
_sym: Symbol.for('offset')
},
sort: {
alias: ['sort'],
_sym: Symbol.for('sort')
},
select: {
alias: ['select'],
_sym: Symbol.for('select')
}
};
let types = [], mapping = {};
Object.keys(definitions).forEach((def) => {
types = types.concat(definitions[def].alias);
definitions[def].alias.forEach((_alias) => mapping[_alias] = definitions[def]._sym);
});
/**
* @dev get Symbol for type
* @param {string} type
* @returns {Symbol} throws `AssertionError` when no matches found
*/
function getSym(type) {
assert.type('type', type, 'string');
type = type.toLowerCase();
assert.value('type', type, types, true);
return mapping[type];
}
module.exports = {
definitions, mapping,
getSym
};<file_sep>/test/2.live/array.test.js
const { expect } = require('chai');
const lo = require('lodash');
const mongodb = require('mongodb');
const faker = require('faker');
const query = require('../../lib/query/index');
const testData = require('../1.seed/test-data');
describe('it should perform array tests on server', () => {
let collection;
before((done) => {
mongodb.connect('mongodb://localhost:27017/my_test_db', { useUnifiedTopology: true }, (dbErr, db) => {
expect(dbErr).to.be.null;
collection = db.db().collection('test');
done();
});
});
it('should perform all test', () => {
let sports = testData.used.sports[faker.random.number({ min: 0, max: testData.used.sports.length - 1 })];
collection.find({
...query('test').all('sports', sports).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(
lo.isEqual(
lo.intersection(res.sports.sort(), sports),
sports
)
).to.be.true;
});
})
.catch((err) => { throw err; });
});
it('should perform in test', () => {
let sports = testData.used.sports[faker.random.number({ min: 0, max: testData.used.sports.length - 1 })];
collection.find({
...query('test').in('sports', sports).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(
lo.intersection(res.sports.sort(), sports).length
).to.be.gt(0);
});
})
.catch((err) => { throw err; });
});
it('should perform nin test', () => {
let sports = testData.used.sports[faker.random.number({ min: 0, max: testData.used.sports.length - 1 })];
collection.find({
...query('test').nin('sports', sports).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(
lo.intersection(res.sports.sort(), sports).length
).to.be.equal(0);
});
})
.catch((err) => { throw err; });
});
it('should perform size test', () => {
let sports = testData.used.sports[faker.random.number({ min: 0, max: testData.used.sports.length - 1 })];
collection.find({
...query('test').size('sports', sports.length).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(res.sports.length).to.be.equal(sports.length);
});
})
.catch((err) => { throw err; });
});
});<file_sep>/lib/option/offset.js
'use strict';
const lo = require('lodash');
const assert = require('../util/assert');
/**
* @dev set a offset after which records should be fetched
* @param {...any} args Array of arguments
* @returns {ThisParameterType} `this` argument
*/
function offset(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
assert.type('offset', args[0], 'number');
this.option.skip = args[0];
return this;
}
module.exports = offset;
<file_sep>/types/option.d.ts
// Type definitions for [@query-easy/mongo]
// Project: [Query Easy - Mongo]
// Definitions by: [<NAME>] [https://github.com/akash-kansara]
interface Option {
limit: typeof limit,
offset: typeof offset,
sort: typeof sort,
select: typeof select,
raw: typeof raw,
raws: typeof raws
}
declare function limit(limit: number): Option;
declare function offset(offset: number): Option;
declare function sort(order: string, path: string[]): Option;
declare function sort(order: string, ...path: string[]): Option;
declare function select(select: boolean, path: string[]): Option;
declare function select(select: boolean, ...path: string[]): Option;
declare function raw(type: string, args: any[]): Option;
declare function raw(type: string, ...args: any[]): Option;
declare function raws(rawArr: any[][]): Option;
declare function option(collection: string): Option;
<file_sep>/lib/option/select.js
'use strict';
const lo = require('lodash');
const assert = require('../util/assert');
/**
* @dev select / deselct fields
* @param {...any} args Array of arguments
* @returns {ThisParameterType} `this` argument
*/
function select(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
assert.type('select', args[0], 'boolean');
const select = args[0];
args = args.slice(1, args.length);
let i = 0;
for (; i < args.length; i++) {
assert.type('path', args[i], 'string');
}
if (select) {
i = 0;
for (; i < args.length; i++) {
lo.set(this.option, `projection.${args[i]}`, 1);
}
} else {
i = 0;
for (; i < args.length; i++) {
lo.set(this.option, `projection.${args[i]}`, 0);
}
}
return this;
}
module.exports = select;
<file_sep>/lib/util/assert.js
'use strict';
const assert = require('assert').strict;
const kindof = require('kindof');
/**
* @dev Assert type of variable
* @param {string} variable name of variable
* @param {any} val value to be tested
* @param {string} type type of value
* @returns {undefined} throws `AssertionError` if type does not match
*/
function type(variable, val, type) {
return assert.equal(
kindof(val),
type,
`"${variable}" should be of type "${type}"`
);
}
/**
* @dev Assert that 2 values are equal
* @param {string} variable name of variable
* @param {any} val value to be tested
* @param {Array<any> | any} lookup Check against array of values or single value
* @param {boolean=} arrayCheck Check against a value in array of `lookup` values
* @returns {undefined} throws `AssertionError` if type does not match
*/
function value(variable, val, lookup, arrayCheck = false) {
if (arrayCheck) {
type('lookup', lookup, 'array');
let i = 0, n = lookup.length, found = false;
for (; i < n && !found; i++) {
try {
assert.deepStrictEqual(val, lookup[i]);
found = true;
} catch (err) {
// empty
}
}
if (found)
return;
else
throw new assert.AssertionError({ message: `"${variable}" value must be one of [${lookup.join(', ')}]` });
} else {
assert.deepStrictEqual(val, lookup, `${variable} value must be equal to ${lookup}`);
}
}
module.exports = {
type,
value
};<file_sep>/test/0.individual/filter/combined.test.js
const { expect } = require('chai');
const filter = require('../../../lib/filter/index');
const testData = require('./test-data');
describe('individual - filter - combined', () => {
it('should build correct filter', () => {
const fil = filter.call({}, testData.collection);
fil
.eq(testData.queries.eq)
.neq(...testData.queries.neq)
.raw('<', testData.queries.lt)
.gt(...testData.queries.gt)
.lte(testData.queries.lte)
.raw('>=', testData.queries.gte)
.regex(testData.queries.regex)
.in(testData.queries.in)
.nin(...testData.queries.nin)
.raw('all', testData.queries.all)
.raw('size', testData.queries.size)
.exists(testData.queries.exists.exist)
.exists(...testData.queries.exists.not_exist)
.type(...testData.queries.type)
.raw('not', testData.queries.not)
.and((andCB) => {
andCB.neq(testData.queries.and.neq);
})
.or((orCB) => {
orCB.size(testData.queries.or.size);
})
.raw('nor', (norCB) => {
norCB.gt(testData.queries.nor.gt);
});
expect(fil.filter).to.eql(testData.result.combined);
});
it('should build correct filter by raws', () => {
const fil = filter.call({}, testData.collection);
fil
.raws(
['eq', testData.queries.eq],
['neq', testData.queries.neq],
['<', testData.queries.lt],
['>', testData.queries.gt],
['<=', testData.queries.lte],
['gte', testData.queries.gte],
['regex', testData.queries.regex],
['in', testData.queries.in],
['nin', testData.queries.nin],
['all', testData.queries.all],
['size', testData.queries.size],
['exists', testData.queries.exists.exist],
['exists', testData.queries.exists.not_exist],
['type', testData.queries.type],
['not', testData.queries.not],
['and', (andCB) => {
andCB.neq(testData.queries.and.neq);
}],
['or', (orCB) => {
orCB.size(testData.queries.or.size);
}],
['nor', (norCB) => {
norCB.gt(testData.queries.nor.gt);
}]
);
expect(fil.filter).to.eql(testData.result.combined);
});
});<file_sep>/test/0.individual/query/random.test.js
const { expect } = require('chai');
const query = require('../../../lib/query/index');
const testData = require('./test-data');
describe('individual - query - random', () => {
it('should compile a highly nested query', () => {
const qe = query.call({}, testData.collection);
const q = qe
.and((andCB) => {
andCB
.eq(testData.queries.random.and.eq)
.exists(testData.queries.random.and.exists)
.or((orCB) => {
orCB
.in(testData.queries.random.and.or.in)
.all(testData.queries.random.and.or.all)
.nin(testData.queries.random.and.or.nin)
.gte(testData.queries.random.and.or.gte)
.lte(testData.queries.random.and.or.lte)
.lt(testData.queries.random.and.or.lt)
.regex(testData.queries.random.and.or.regex);
})
.type(testData.queries.random.and.type)
.nor((norCB) => {
norCB.not(testData.queries.random.and.nor.not);
});
})
.toQuery();
expect(q).to.be.eql(testData.result.random);
});
});<file_sep>/lib/filter/all.js
'use strict';
const lo = require('lodash');
const assert = require('../util/assert');
/**
* @dev check value in `path` has all specified values
* @param {...any} args Array of arguments
* @returns {ThisParameterType} `this` argument
*/
function all(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
const value = Array.isArray(args[1]) ? args[1] : args.slice(1, args.length);
assert.type('path', args[0], 'string');
if (Array.isArray(this.filter)) {
const compiled = {};
compiled[args[0]] = { $all: value };
this.filter.push(compiled);
} else {
this.filter[args[0]] = { $all: value };
}
return this;
}
module.exports = all;
<file_sep>/test/2.live/misc.test.js
const { expect } = require('chai');
const kindof = require('kindof');
const mongodb = require('mongodb');
const query = require('../../lib/query/index');
describe('it should perform misc tests on server', () => {
let collection;
before((done) => {
mongodb.connect('mongodb://localhost:27017/my_test_db', { useUnifiedTopology: true }, (dbErr, db) => {
expect(dbErr).to.be.null;
collection = db.db().collection('test');
done();
});
});
it('should perform type test', () => {
collection.find({
...query('test').type('address', 'array').toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(kindof(res.address)).to.equal('array');
});
})
.catch((err) => { throw err; });
});
it('should perform exists test', () => {
collection.find({
...query('test').exists('department', true).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(res).to.haveOwnProperty('department');
});
})
.catch((err) => { throw err; });
});
it('should perform does not exist test', () => {
collection.find({
...query('test').exists('department', false).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(res).to.not.haveOwnProperty('department');
});
})
.catch((err) => { throw err; });
});
});<file_sep>/lib/query/index.js
'use strict';
const lo = require('lodash');
const kindof = require('kindof');
const assert = require('../util/assert');
const query = require('./_query');
const Filter = require('../filter');
const Option = require('../option');
/**
* @dev Build option from raw input
*/
function raw(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
const sym = query.getSym(args[0]);
let f;
switch (sym) {
case query.definitions.filter._sym: {
f = this.filRaw; break;
}
case query.definitions.option._sym: {
f = this.optRaw; break;
}
}
f(args);
return this;
}
function raws(...args) {
assert.type('raws', args, 'array');
while (args.length === 1) args = lo.flatten(args);
if (kindof(args[0]) != 'array')
args = [args];
for (let i = 0; i < args.length; i++) {
assert.type('raw', args[i], 'array');
raw.call(this, args[i]);
}
return this;
}
/**
* @dev Give query output
* @returns {object} Mongo query output
*/
function toQuery() {
return {
filter: this._filter.filter,
options: this._option.option
};
}
class Query {
constructor(collection) {
assert.type('collection', collection, 'string');
// Filter
this._filter = Filter.call(this, collection);
this.eq = this._filter.eq;
this.neq = this._filter.neq;
this.lt = this._filter.lt;
this.gt = this._filter.gt;
this.lte = this._filter.lte;
this.gte = this._filter.gte;
this.regex = this._filter.regex;
this.exists = this._filter.exists;
this.type = this._filter.type;
this.in = this._filter.in;
this.nin = this._filter.nin;
this.all = this._filter.all;
this.size = this._filter.size;
this.not = this._filter.not;
this.and = this._filter.and;
this.or = this._filter.or;
this.nor = this._filter.nor;
this.filRaw = this._filter.raw;
// Filter
// Option
this._option = Option.call(this, collection);
this.limit = this._option.limit;
this.offset = this._option.offset;
this.sort = this._option.sort;
this.select = this._option.select;
this.optRaw = this._option.raw;
// Option
this.raw = raw.bind(this);
this.raws = raws.bind(this);
this.toQuery = toQuery.bind(this);
}
}
/**
* @dev Construct and return a query object
* @param {string} collection Mongo collection
* @returns {Query} query object
*/
function queryEasy(collection) {
const queryObj = new Query(collection);
return queryObj;
}
module.exports = queryEasy;
<file_sep>/lib/filter/_condition.js
const assert = require('../util/assert');
const definitions = {
eq: {
alias: ['eq', '='],
_sym: Symbol.for('eq')
},
neq: {
alias: ['neq', '<>', '!='],
_sym: Symbol.for('neq')
},
lt: {
alias: ['lt', '<'],
_sym: Symbol.for('lt')
},
gt: {
alias: ['gt', '>'],
_sym: Symbol.for('gt')
},
lte: {
alias: ['lte', '<='],
_sym: Symbol.for('lte')
},
gte: {
alias: ['gte', '>='],
_sym: Symbol.for('gte')
},
regex: {
alias: ['regex'],
_sym: Symbol.for('regex')
},
exists: {
alias: ['exists'],
_sym: Symbol.for('exists')
},
type: {
alias: ['type'],
_sym: Symbol.for('type')
},
in: {
alias: ['in'],
_sym: Symbol.for('in')
},
nin: {
alias: ['nin', 'notin'],
_sym: Symbol.for('nin')
},
all: {
alias: ['all'],
_sym: Symbol.for('all')
},
size: {
alias: ['size'],
_sym: Symbol.for('size')
},
not: {
alias: ['not'],
_sym: Symbol.for('not')
},
and: {
alias: ['and', '&&'],
_sym: Symbol.for('and')
},
or: {
alias: ['or', '||'],
_sym: Symbol.for('or')
},
nor: {
alias: ['nor'],
_sym: Symbol.for('nor')
}
};
let conditions = [], mapping = {};
Object.keys(definitions).forEach((def) => {
conditions = conditions.concat(definitions[def].alias);
definitions[def].alias.forEach((_alias) => mapping[_alias] = definitions[def]._sym);
});
/**
* @dev get Symbol for condition
* @param {string} condition
* @returns {Symbol} throws `AssertionError` when no matches found
*/
function getSym(condition) {
assert.type('condition', condition, 'string');
condition = condition.toLowerCase();
assert.value('condition', condition, conditions, true);
return mapping[condition];
}
module.exports = {
definitions, mapping,
getSym
};<file_sep>/test/0.individual/filter/test-data.js
const collection = 'test';
const queries = {
eq: ['name.first', 'Drew'],
neq: ['gender', 'M'],
lt: ['age', 25],
gt: ['height', 172],
lte: ['bmi', 19],
gte: ['name', null],
regex: ['country', new RegExp('gotham', 'i')],
exists: {
exist: ['name.last', true],
not_exist: ['name.middle', false]
},
type: ['address', 'array'],
in: ['dept', 'dept1', 'dept2'],
nin: ['ageGroup', 'ADOLESCENT', 'OLD'],
all: ['sport', 'basketball', 'tennis'],
size: ['incidents', 5],
not: ['parent.name', 'Doe'],
and: { neq: ['weight', 60] },
or: { size: ['orders', 10] },
nor: { gt: ['footSize', 8] }
};
const result = {
eq: { 'name.first': queries.eq[1] },
neq: { gender: { $ne: queries.neq[1] } },
lt: { age: { $lt: queries.lt[1] } },
gt: { height: { $gt: queries.gt[1] } },
lte: { bmi: { $lte: queries.lte[1] } },
gte: { name: { $gte: queries.gte[1] } },
regex: { country: { $regex: queries.regex[1] } },
exists: {
exist: { 'name.last': { $exists: queries.exists.exist[1] } },
not_exist: { 'name.middle': { $exists: queries.exists.not_exist[1] } }
},
type: { address: { $type: queries.type[1] } },
in: { dept: { $in: queries.in.slice(1, queries.in.length) } },
nin: { ageGroup: { $nin: queries.nin.slice(1, queries.nin.length) } },
all: { sport: { $all: queries.all.slice(1, queries.all.length) } },
size: { incidents: { $size: queries.size[1] } },
not: { 'parent.name': { $not: queries.not[1] } },
and: { $and: [{ weight: { $ne: queries.and.neq[1] } }] },
or: { $or: [{ orders: { $size: queries.or.size[1] } }] },
nor: { $nor: [{ footSize: { $gt: queries.nor.gt[1] } }] },
combined: {}
};
result.combined = {
...result.eq, ...result.neq,
...result.lt, ...result.gt, ...result.lte, ...result.gte,
...result.regex,
...result.exists.exist, ...result.exists.not_exist,
...result.type,
...result.in, ...result.nin, ...result.all, ...result.size,
...result.not, ...result.and, ...result.or, ...result.nor
};
module.exports = {
collection, queries, result
};<file_sep>/types/index.d.ts
// Type definitions for [@query-easy/mongo]
// Project: [Query Easy - Mongo]
// Definitions by: [<NAME>] [https://github.com/akash-kansara]
/// <reference path="filter.d.ts" />
declare module "@query-easy/mongo" {
interface queryCB {
(queryCb: Filter): void
}
interface MongoQuery {
filter: object
options: object
}
function eq(path: string, value: any): Query;
function neq(path: string, value: any): Query;
function lt(path: string, value: any): Query;
function gt(path: string, value: any): Query;
function lte(path: string, value: any): Query;
function gte(path: string, value: any): Query;
function regex(path: string, regex: RegExp): Query;
function exists(path: string, exists: boolean): Query;
function type(path: string, bsonType: string): Query;
function _in(path: string, arr: any[]): Query;
function _in(path: string, ...arr: any[]): Query;
function nin(path: string, arr: any[]): Query;
function nin(path: string, ...arr: any[]): Query;
function all(path: string, arr: any[]): Query;
function all(path: string, ...arr: any[]): Query;
function size(path: string, size: number): Query;
function not(path: string, value: any): Query;
function and(andCB: queryCB): Query;
function or(orCB: queryCB): Query;
function nor(norCB: queryCB): Query;
function limit(limit: number): Query;
function offset(offset: number): Query;
function sort(order: string, path: string[]): Query;
function sort(order: string, ...path: string[]): Query;
function select(select: boolean, path: string[]): Query;
function select(select: boolean, ...path: string[]): Query;
function raw(type: string, args: any[]): Query;
function raw(type: string, ...args: any[]): Query;
function raws(rawArr: any[][]): Query;
function toQuery(): MongoQuery;
interface Query {
eq: typeof eq,
neq: typeof neq,
lt: typeof lt,
gt: typeof gt,
lte: typeof lte,
gte: typeof gte,
regex: typeof regex,
exists: typeof exists,
type: typeof type,
in: typeof _in,
nin: typeof nin,
all: typeof all,
size: typeof size,
not: typeof not,
and: typeof and,
or: typeof or,
nor: typeof nor,
limit: typeof limit,
offset: typeof offset,
sort: typeof sort,
select: typeof select,
raw: typeof raw,
raws: typeof raws,
toQuery: typeof toQuery
}
function qeMongo(collection: string): Query;
export = qeMongo;
}<file_sep>/test/0.individual/filter/logical-operator.test.js
const { expect } = require('chai');
const filter = require('../../../lib/filter/index');
const testData = require('./test-data');
describe('individual - filter - not', () => {
it('should build correct not filter', () => {
const fil = filter.call({}, testData.collection);
fil.not(testData.queries.not);
expect(fil.filter).to.eql(testData.result.not);
});
it('should build correct not filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('not', testData.queries.not);
expect(fil.filter).to.eql(testData.result.not);
});
});
describe('individual - filter - and', () => {
it('should build correct and filter', () => {
const fil = filter.call({}, testData.collection);
fil.and((andCB) => {
andCB.neq(testData.queries.and.neq);
});
expect(fil.filter).to.eql(testData.result.and);
});
it('should build correct and filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('and', (andCB) => {
andCB.raw('!=', testData.queries.and.neq);
});
expect(fil.filter).to.eql(testData.result.and);
});
});
describe('individual - filter - or', () => {
it('should build correct or filter', () => {
const fil = filter.call({}, testData.collection);
fil.or((orCB) => {
orCB.size(testData.queries.or.size);
});
expect(fil.filter).to.eql(testData.result.or);
});
it('should build correct or filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('or', (orCB) => {
orCB.size(testData.queries.or.size);
});
expect(fil.filter).to.eql(testData.result.or);
});
});
describe('individual - filter - nor', () => {
it('should build correct nor filter', () => {
const fil = filter.call({}, testData.collection);
fil.nor((norCB) => {
norCB.gt(testData.queries.nor.gt);
});
expect(fil.filter).to.eql(testData.result.nor);
});
it('should build correct nor filter by raw', () => {
const fil = filter.call({}, testData.collection);
fil.raw('nor', (norCB) => {
norCB.gt(testData.queries.nor.gt);
});
expect(fil.filter).to.eql(testData.result.nor);
});
});
<file_sep>/test/2.live/equality.test.js
const { expect } = require('chai');
const mongodb = require('mongodb');
const faker = require('faker');
const query = require('../../lib/query/index');
const testData = require('../1.seed/test-data');
describe('it should perform equality tests on server', () => {
let collection;
before((done) => {
mongodb.connect('mongodb://localhost:27017/my_test_db', { useUnifiedTopology: true }, (dbErr, db) => {
expect(dbErr).to.be.null;
collection = db.db().collection('test');
done();
});
});
it('should perform eq test', () => {
let country = testData.used.countries[faker.random.number({ min: 0, max: testData.used.countries.length - 1 })];
collection.find({
...query('test').eq('country', country).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(res.country).to.equal(country);
});
})
.catch((err) => { throw err; });
});
it('should perform neq test', () => {
let country = testData.used.countries[faker.random.number({ min: 0, max: testData.used.countries.length - 1 })];
collection.find({
...query('test').neq('country', country).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.be.gt(0);
results.forEach((res) => {
expect(res.country).to.not.equal(country);
});
})
.catch((err) => { throw err; });
});
it('should perform lt test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').lt('height', height).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(res.height).to.be.lt(height);
});
})
.catch((err) => { throw err; });
});
it('should perform gt test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').gt('height', height).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(res.height).to.be.gt(height);
});
})
.catch((err) => { throw err; });
});
it('should perform lte test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').lte('height', height).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(res.height).to.be.lte(height);
});
})
.catch((err) => { throw err; });
});
it('should perform gte test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').gte('height', height).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(res.height).to.be.gte(height);
});
})
.catch((err) => { throw err; });
});
it('should perform regex test', () => {
let namePrefix =
new RegExp(
testData.used.namePrefix[faker.random.number({ min: 0, max: testData.used.namePrefix.length - 1 })],
'i'
);
collection.find({
...query('test').regex('name', namePrefix).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(namePrefix.test(res.name)).to.be.true;
});
})
.catch((err) => { throw err; });
});
});<file_sep>/test/0.individual/query/simple.test.js
const { expect } = require('chai');
const query = require('../../../lib/query/index');
const testData = require('./test-data');
describe('individual - query', () => {
it('should throw collection error', () => {
expect(query.bind({}, 123)).to.throw();
});
it('should build filter object', () => {
expect(query.bind({}, testData.collection)).to.not.throw();
});
it('should throw query not matched error', () => {
expect(query(testData.collection).raw.bind({}, 'x', 'y')).to.throw();
});
});
describe('individual - query - simple', () => {
it('should build correct query for jumble #1', () => {
const qe = query.call({}, testData.collection);
qe
.eq(testData.queries.simple.eq)
.neq(...testData.queries.simple.neq)
.raw('<', testData.queries.simple.lt)
.gt(...testData.queries.simple.gt)
.lte(testData.queries.simple.lte)
.raw('>=', testData.queries.simple.gte)
.regex(testData.queries.simple.regex)
.in(testData.queries.simple.in)
.nin(...testData.queries.simple.nin)
.raw('all', testData.queries.simple.all)
.raw('size', testData.queries.simple.size)
.limit(testData.queries.simple.limit)
.raw('offset', testData.queries.simple.offset)
.sort(testData.queries.simple.sort.asc)
.sort(...testData.queries.simple.sort.desc)
.select(testData.queries.simple.select.select)
.raw('select', testData.queries.simple.select.deselect)
.exists(testData.queries.simple.exists.exist)
.exists(...testData.queries.simple.exists.not_exist)
.type(...testData.queries.simple.type)
.raw('not', testData.queries.simple.not)
.and((andCB) => {
andCB.neq(testData.queries.simple.and.neq);
})
.or((orCB) => {
orCB.size(testData.queries.simple.or.size);
})
.raw('nor', (norCB) => {
norCB.gt(testData.queries.simple.nor.gt);
});
expect(qe.toQuery()).to.eql(testData.result.simple);
});
it('should build correct query for jumble #2', () => {
const qe = query.call({}, testData.collection);
qe
.sort(...testData.queries.simple.sort.desc)
.eq(testData.queries.simple.eq)
.neq(...testData.queries.simple.neq)
.raw('select', testData.queries.simple.select.deselect)
.raw('<', testData.queries.simple.lt)
.gt(...testData.queries.simple.gt)
.lte(testData.queries.simple.lte)
.raw('offset', testData.queries.simple.offset)
.raw('>=', testData.queries.simple.gte)
.regex(testData.queries.simple.regex)
.in(testData.queries.simple.in)
.nin(...testData.queries.simple.nin)
.raw('all', testData.queries.simple.all)
.raw('size', testData.queries.simple.size)
.limit(testData.queries.simple.limit)
.sort(testData.queries.simple.sort.asc)
.select(testData.queries.simple.select.select)
.exists(...testData.queries.simple.exists.not_exist)
.type(...testData.queries.simple.type)
.raw('not', testData.queries.simple.not)
.and((andCB) => {
andCB.neq(testData.queries.simple.and.neq);
})
.or((orCB) => {
orCB.size(testData.queries.simple.or.size);
})
.raw('nor', (norCB) => {
norCB.gt(testData.queries.simple.nor.gt);
})
.exists(testData.queries.simple.exists.exist);
expect(qe.toQuery()).to.eql(testData.result.simple);
});
it('should build correct query by raws', () => {
const qe = query.call({}, testData.collection);
qe
.raws(
['eq', testData.queries.simple.eq],
['neq', testData.queries.simple.neq],
['<', testData.queries.simple.lt],
['>', testData.queries.simple.gt],
['<=', testData.queries.simple.lte],
['gte', testData.queries.simple.gte],
['regex', testData.queries.simple.regex],
['in', testData.queries.simple.in],
['nin', testData.queries.simple.nin],
['all', testData.queries.simple.all],
['size', testData.queries.simple.size],
['exists', testData.queries.simple.exists.exist],
['exists', testData.queries.simple.exists.not_exist],
['type', testData.queries.simple.type],
['not', testData.queries.simple.not],
['and', (andCB) => {
andCB.neq(testData.queries.simple.and.neq);
}],
['or', (orCB) => {
orCB.size(testData.queries.simple.or.size);
}],
['nor', (norCB) => {
norCB.gt(testData.queries.simple.nor.gt);
}],
['limit', testData.queries.simple.limit],
['offset', testData.queries.simple.offset],
['sort', testData.queries.simple.sort.asc],
['sort', testData.queries.simple.sort.desc],
['select', testData.queries.simple.select.select],
['select', testData.queries.simple.select.deselect]
);
expect(qe.toQuery()).to.eql(testData.result.simple);
});
});
<file_sep>/lib/option/index.js
'use strict';
const lo = require('lodash');
const kindof = require('kindof');
const assert = require('../util/assert');
const type = require('./_type');
const limit = require('./limit');
const offset = require('./offset');
const sort = require('./sort');
const select = require('./select');
/**
* @dev Build option from raw input
*/
function raw(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
const sym = type.getSym(args[0]);
let f;
switch (sym) {
case type.definitions.limit._sym: {
f = limit.bind(this); break;
}
case type.definitions.offset._sym: {
f = offset.bind(this); break;
}
case type.definitions.sort._sym: {
f = sort.bind(this); break;
}
case type.definitions.select._sym: {
f = select.bind(this); break;
}
}
f(args.slice(1, args.length));
return this;
}
function raws(...args) {
assert.type('raws', args, 'array');
while (args.length === 1) args = lo.flatten(args);
if (kindof(args[0]) != 'array')
args = [args];
for (let i = 0; i < args.length; i++) {
assert.type('raw', args[i], 'array');
raw.call(this, args[i]);
}
return this;
}
function option(collection) {
assert.type('collection', collection, 'string');
this.collection = collection;
this.option = {};
this.limit = limit.bind(this);
this.offset = offset.bind(this);
this.sort = sort.bind(this);
this.select = select.bind(this);
this.raw = raw.bind(this);
this.raws = raws.bind(this);
return this;
}
module.exports = option;
<file_sep>/lib/filter/index.js
'use strict';
const lo = require('lodash');
const kindof = require('kindof');
const assert = require('../util/assert');
const condition = require('./_condition');
const eq = require('./eq');
const neq = require('./neq');
const lt = require('./lt');
const gt = require('./gt');
const lte = require('./lte');
const gte = require('./gte');
const regex = require('./regex');
const exists = require('./exists');
const type = require('./type');
const _in = require('./in');
const nin = require('./nin');
const all = require('./all');
const size = require('./size');
const not = require('./not');
/* eslint-disable no-unused-vars */
/**
* @dev check that all conditions specified match
* @param {Function} cb Callback function
*/
function not_deprecated(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
assert.type('not callback', args[0], 'function');
const nots = {};
const fil = filter.call({}, this.collection, nots);
if (Array.isArray(this.filter)) {
this.filter.push({ $not: nots });
} else {
this.filter.$not = nots;
}
args[0](fil);
return this;
}
/**
* @dev check that all conditions specified match
* @param {Function} cb Callback function
*/
function and(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
assert.type('and callback', args[0], 'function');
const ands = [];
const fil = filter.call({}, this.collection, ands);
if (Array.isArray(this.filter)) {
this.filter.push({ $and: ands });
} else {
this.filter.$and = ands;
}
args[0](fil);
return this;
}
/**
* @dev check that at least one of the conditions specified match
* @param {Function} cb Callback function
*/
function or(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
assert.type('or callback', args[0], 'function');
const ors = [];
const fil = filter.call({}, this.collection, ors);
if (Array.isArray(this.filter)) {
this.filter.push({ $or: ors });
} else {
this.filter.$or = ors;
}
args[0](fil);
return this;
}
/**
* @dev logical nor operator on conditions specified
* @param {Function} cb Callback function
*/
function nor(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
assert.type('nor callback', args[0], 'function');
const nors = [];
const fil = filter.call({}, this.collection, nors);
if (Array.isArray(this.filter)) {
this.filter.push({ $nor: nors });
} else {
this.filter.$nor = nors;
}
args[0](fil);
return this;
}
/**
* @dev Build filter from raw input
*/
function raw(...args) {
while (Array.isArray(args[0])) args = lo.flatten(args);
const sym = condition.getSym(args[0]);
let f;
switch (sym) {
case condition.definitions.eq._sym: {
f = eq.bind(this); break;
}
case condition.definitions.neq._sym: {
f = neq.bind(this); break;
}
case condition.definitions.lt._sym: {
f = lt.bind(this); break;
}
case condition.definitions.gt._sym: {
f = gt.bind(this); break;
}
case condition.definitions.lte._sym: {
f = lte.bind(this); break;
}
case condition.definitions.gte._sym: {
f = gte.bind(this); break;
}
case condition.definitions.regex._sym: {
f = regex.bind(this); break;
}
case condition.definitions.exists._sym: {
f = exists.bind(this); break;
}
case condition.definitions.type._sym: {
f = type.bind(this); break;
}
case condition.definitions.in._sym: {
f = _in.bind(this); break;
}
case condition.definitions.nin._sym: {
f = nin.bind(this); break;
}
case condition.definitions.all._sym: {
f = all.bind(this); break;
}
case condition.definitions.size._sym: {
f = size.bind(this); break;
}
case condition.definitions.not._sym: {
f = not.bind(this); break;
}
case condition.definitions.and._sym: {
f = and.bind(this); break;
}
case condition.definitions.or._sym: {
f = or.bind(this); break;
}
case condition.definitions.nor._sym: {
f = nor.bind(this); break;
}
}
f(args.slice(1, args.length));
return this;
}
function raws(...args) {
assert.type('raws', args, 'array');
while (args.length === 1) args = lo.flatten(args);
if (kindof(args[0]) != 'array')
args = [args];
for (let i = 0; i < args.length; i++) {
assert.type('raw', args[i], 'array');
raw.call(this, args[i]);
}
return this;
}
function filter(collection, filter = {}) {
assert.type('collection', collection, 'string');
this.collection = collection;
this.filter = filter;
this.eq = eq.bind(this);
this.neq = neq.bind(this);
this.lt = lt.bind(this);
this.gt = gt.bind(this);
this.lte = lte.bind(this);
this.gte = gte.bind(this);
this.regex = regex.bind(this);
this.exists = exists.bind(this);
this.type = type.bind(this);
this.in = _in.bind(this);
this.nin = nin.bind(this);
this.all = all.bind(this);
this.size = size.bind(this);
this.not = not.bind(this);
this.and = and.bind(this);
this.or = or.bind(this);
this.nor = nor.bind(this);
this.raw = raw.bind(this);
this.raws = raws.bind(this);
return this;
}
module.exports = filter;
<file_sep>/test/2.live/option.test.js
const { expect } = require('chai');
const mongodb = require('mongodb');
const query = require('../../lib/query/index');
const testData = require('../1.seed/test-data');
describe('it should perform filter option tests on server', () => {
let collection;
before((done) => {
mongodb.connect('mongodb://localhost:27017/my_test_db', { useUnifiedTopology: true }, (dbErr, db) => {
expect(dbErr).to.be.null;
collection = db.db().collection('test');
done();
});
});
it('should perform offset test', () => {
collection.find({}, {
...query('test').offset(100).toQuery().options
}).toArray()
.then((results) => {
expect(results.length).to.be.equal(testData.data.length - 100);
})
.catch((err) => { throw err; });
});
it('should perform limit test', () => {
collection.find({}, {
...query('test').limit(100).toQuery().options
}).toArray()
.then((results) => {
expect(results.length).to.be.equal(100);
})
.catch((err) => { throw err; });
});
it('should perform sort asc test', () => {
collection.find({}, {
...query('test').sort('asc', 'height').toQuery().options
}).toArray()
.then((results) => {
let prev = Number.MIN_VALUE;
results.forEach((res) => {
expect(res.height >= prev).to.be.true;
prev = res.height;
});
})
.catch((err) => { throw err; });
});
it('should perform sort desc test', () => {
collection.find({}, {
...query('test').sort('desc', 'height').toQuery().options
}).toArray()
.then((results) => {
let prev = Number.MAX_VALUE;
results.forEach((res) => {
expect(res.height <= prev).to.be.true;
prev = res.height;
});
})
.catch((err) => { throw err; });
});
it('should perform select test', () => {
collection.find({}, {
...query('test').select(true, 'address', 'height').toQuery().options
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(res).to.haveOwnProperty('address');
expect(res).to.haveOwnProperty('height');
});
})
.catch((err) => { throw err; });
});
it('should perform deselect test', () => {
collection.find({}, {
...query('test').select(false, 'sports', 'name').toQuery().options
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(res).to.not.haveOwnProperty('sports');
expect(res).to.not.haveOwnProperty('name');
});
})
.catch((err) => { throw err; });
});
});<file_sep>/types/filter.d.ts
// Type definitions for [@query-easy/mongo]
// Project: [Query Easy - Mongo]
// Definitions by: [<NAME>] [https://github.com/akash-kansara]
interface Filter {
eq: typeof eq,
neq: typeof neq,
lt: typeof lt,
gt: typeof gt,
lte: typeof lte,
gte: typeof gte,
regex: typeof regex,
exists: typeof exists,
type: typeof type,
in: typeof _in,
nin: typeof nin,
all: typeof all,
size: typeof size,
not: typeof not,
and: typeof and,
or: typeof or,
nor: typeof nor,
raw: typeof raw,
raws: typeof raws
}
interface filterCB {
(filterCb: Filter): void
}
declare function eq(path: string, value: any): Filter;
declare function neq(path: string, value: any): Filter;
declare function lt(path: string, value: any): Filter;
declare function gt(path: string, value: any): Filter;
declare function lte(path: string, value: any): Filter;
declare function gte(path: string, value: any): Filter;
declare function regex(path: string, regex: RegExp): Filter;
declare function exists(path: string, exists: boolean): Filter;
declare function type(path: string, bsonType: string): Filter;
declare function _in(path: string, arr: any[]): Filter;
declare function _in(path: string, ...arr: any[]): Filter;
declare function nin(path: string, arr: any[]): Filter;
declare function nin(path: string, ...arr: any[]): Filter;
declare function all(path: string, arr: any[]): Filter;
declare function all(path: string, ...arr: any[]): Filter;
declare function size(path: string, size: number): Filter;
declare function not(path: string, value: any): Filter;
declare function and(andCB: filterCB): Filter;
declare function or(orCB: filterCB): Filter;
declare function nor(norCB: filterCB): Filter;
declare function raw(type: string, args: any[]): Filter;
declare function raw(type: string, ...args: any[]): Filter;
declare function raws(rawArr: any[][]): Filter;
declare function filter(collection: string, result: object | object[]): Filter;
<file_sep>/lib/query/_query.js
const assert = require('../util/assert');
const filterDef = require('../filter/_condition').definitions;
const optionDef = require('../option/_type').definitions;
const definitions = {
filter: { _sym: Symbol.for('filter') },
option: { _sym: Symbol.for('option') }
};
const queries = {
filter: [],
option: []
};
Object.keys(filterDef).forEach((def) => {
queries.filter = queries.filter.concat(filterDef[def].alias);
});
Object.keys(optionDef).forEach((def) => {
queries.option = queries.option.concat(optionDef[def].alias);
});
/**
* @dev get Symbol for query
* @param {string} query
* @returns {Symbol} throws `AssertionError` when no matches found
*/
function getSym(query) {
if (queries.filter.includes(query)) {
return definitions.filter._sym;
} else if (queries.option.includes(query)) {
return definitions.option._sym;
} else {
assert.value('query', query, [...queries.filter].concat([...queries.option]), true);
return;
}
}
module.exports = {
definitions,
getSym
};
<file_sep>/test/1.seed/seed.test.js
const { expect } = require('chai');
const mongodb = require('mongodb');
const testData = require('./test-data');
describe('seed data in mongo server', () => {
before((done) => {
mongodb.connect('mongodb://localhost:27017/my_test_db', { useUnifiedTopology: true }, (dbErr, db) => {
expect(dbErr).to.be.null;
const collection = db.db().collection('test');
collection.deleteMany({})
.then(() => collection.insertMany(testData.data))
.then(() => done())
.catch((err) => done(err));
});
});
});<file_sep>/test/2.live/logical-operator.test.js
const { expect } = require('chai');
const faker = require('faker');
const kindof = require('kindof');
const mongodb = require('mongodb');
const query = require('../../lib/query/index');
const testData = require('../1.seed/test-data');
describe('it should perform logical operator tests on server', () => {
let collection;
before((done) => {
mongodb.connect('mongodb://localhost:27017/my_test_db', { useUnifiedTopology: true }, (dbErr, db) => {
expect(dbErr).to.be.null;
collection = db.db().collection('test');
done();
});
});
it('should perform not test', () => {
collection.find({
...query('test').not('height', new RegExp('height')).toQuery().filter
}).toArray()
.then((results) => {
expect(results.length).to.equal(testData.data.length);
})
.catch((err) => { throw err; });
});
it('should perform and test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').and(
(andCB) => andCB.type('address', 'array').gt('height', height)
).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(
res.height > height && kindof(res.address) === 'array'
).to.be.true;
});
})
.catch((err) => { throw err; });
});
it('should perform or test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').or(
(orCB) => orCB.type('address', 'array').gt('height', height)
).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(
res.height > height || kindof(res.address) === 'array'
).to.be.true;
});
})
.catch((err) => { throw err; });
});
it('should perform nor test', () => {
let height = testData.used.heights[faker.random.number({ min: 0, max: testData.used.heights.length - 1 })];
collection.find({
...query('test').nor(
(norCB) => norCB.type('address', 'array').gt('height', height)
).toQuery().filter
}).toArray()
.then((results) => {
results.forEach((res) => {
expect(
!(res.height > height || !kindof(res.address) === 'array')
).to.be.true;
});
})
.catch((err) => { throw err; });
});
});<file_sep>/API.md
## Query Interface
A query interface can be created by import / require.
```
const qe = require('@query-easy/mongo')('collection_name');
```
`qe` object provides access to all APIs of [Filter Interface](API.md#filter-interface) and [Option Interface](API.md#option-interface).
### Raw builders
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
`raw` & `raws` on `qe` object handle raw builders of both [filter](API.md#raw-builders-1) & [option](API.md#raw-builders-2) interface
API:
```
qe.raw('limit', ...limit args ).raw('neq', ...neq args );
// is equivalent to
qe.raws(
['limit', ...limit args ],
['neq', ...neq args ]
)
```
### To Mongo query
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
API:
```
qe.eq( ...eq args ).limit( ...limit args )
const query = qe.toQuery();
console.log(query)
// Outputs
// {
// filter: // Mongo filter object
// options: // Mongo options object
// }
```
## Filter Interface
### Equal to
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: eq, =
<br />
API:
```
qe.eq('name', 'John').eq('age', 24)
// is equivalent to
qe.raw('eq', 'name', 'john').raw('=', 'age', 24)
// is equivalent to
qe.raws(
['eq', 'name', 'john'],
['=', 'age', 24]
)
```
### Not equal to
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: neq, <>, !=
<br />
API:
```
qe.neq('name', 'John').neq('age', 24)
// is equivalent to
qe.raw('neq', 'name', 'john').raw('!=', 'age', 24)
// is equivalent to
qe.raws(
['<>', 'name', 'john'],
['!=', 'age', 24]
)
```
### Less than
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: lt, <
<br />
API:
```
qe.lt('age', 25).lt('height', 173)
// is equivalent to
qe.raw('lt', 'age', 25).raw('<', 'height', 173)
// is equivalent to
qe.raws(
['lt', 'age', 25],
['<', 'age', 173]
)
```
### Greater than
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: gt, >
<br />
API:
```
qe.gt('age', 23).gt('height', 171)
// is equivalent to
qe.raw('gt', 'age', 23).raw('>', 'height', 171)
// is equivalent to
qe.raws(
['gt', 'age', 23],
['>', 'age', 171]
)
```
### Less than or equal to
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: lte, <=
<br />
API:
```
qe.lte('age', 24).lte('height', 172)
// is equivalent to
qe.raw('lte', 'age', 24).raw('<=', 'height', 172)
// is equivalent to
qe.raws(
['lte', 'age', 24],
['<=', 'age', 172]
)
```
### Greater than or equal to
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: gte, >=
<br />
API:
```
qe.gte('age', 23).gte('height', 171)
// is equivalent to
qe.raw('gte', 'age', 23).raw('>=', 'height', 171)
// is equivalent to
qe.raws(
['gte', 'age', 23],
['>=', 'age', 171]
)
```
### Regex
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: regex
<br />
API:
```
qe.regex('name', new RegExp('john', 'i'))
// is equivalent to
qe.raw('regex', 'name', new RegExp('john', 'i'))
// is equivalent to
qe.raws(
['regex', 'name', new RegExp('john', 'i')]
)
```
### Exists
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: exists
<br />
API:
```
qe.exists('name.first', true).exists('deparment', false)
// is equivalent to
qe.raw('exists', 'name.first', true).raw('exists', 'deparment', false)
// is equivalent to
qe.raws(
['exists', 'name.first', true],
['exists', 'deparment', false]
)
```
### Type
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: type
<br />
API:
```
qe.type('address', 'string')
// is equivalent to
qe.raw('type', 'address', 'string')
// is equivalent to
qe.raws(
['type', 'address', 'string']
)
```
### In
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: in
<br />
API:
```
qe.in('departments', ['sports', 'faculty', 'chess'])
// is equivalent to
qe.raw('in', ['departments', ['sports', 'faculty', 'chess']])
// is equivalent to
qe.raws(
['in', ['departments', 'sports', 'faculty', 'chess']]
)
```
### Not in
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: nin, notin
<br />
API:
```
qe.nin('departments', ['sports', 'faculty', 'chess'])
// is equivalent to
qe.raw('notin', ['departments', ['sports', 'faculty', 'chess']])
// is equivalent to
qe.raws(
['nin', ['departments', 'sports', 'faculty', 'chess']]
)
```
### All
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: all
<br />
API:
```
qe.all('departments', ['sports', 'faculty', 'chess'])
// is equivalent to
qe.raw('all', 'departments', ['sports', 'faculty', 'chess'])
// is equivalent to
qe.raws(
['all', ['departments', ['sports', 'faculty', 'chess']]]
)
```
### Array size
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: size
<br />
API:
```
qe.size('departments', 3)
// is equivalent to
qe.raw('size', 'departments', 3)
// is equivalent to
qe.raws(
['size', ['departments', 3]]
)
```
### Logical not operator
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: not
<br />
API:
```
qe.not('name', new RegExp('john', 'i'))
// is equivalent to
qe.raw('not', 'name', new RegExp('john', 'i'))
// is equivalent to
qe.raws(
['not', ['name', new RegExp('john', 'i')]]
)
```
### Logical and operator
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: and, &&
<br />
API:
```
qe.and((andCB) => { andCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) })
// is equivalent to
qe.raw('and', (andCB) => { andCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) })
// is equivalent to
qe.raws(
['&&', (andCB) => { andCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) }]
)
// Note: andCB only provides filter interface
```
### Logical or operator
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: or, ||
<br />
API:
```
qe.or((orCB) => { orCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) })
// is equivalent to
qe.raw('or', (orCB) => { orCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) })
// is equivalent to
qe.raws(
['||', (orCB) => { orCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) }]
)
// Note: orCB only provides filter interface
```
### Logical nor operator
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: nor
<br />
API:
```
qe.nor((norCB) => { norCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) })
// is equivalent to
qe.raw('nor', (norCB) => { norCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) })
// is equivalent to
qe.raws(
['nor', (norCB) => { norCB.raws(['eq', 'name', 'John'], ['eq', 'age', 24]) }]
)
// Note: norCB only provides filter interface
```
### Raw builders
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
API:
```
qe.raw('eq', ...equals args ).raw('!=', ...neq args );
// is equivalent to
qe.raws(
['eq', ...eq args ],
['!=', ...neq args ]
)
```
## Option Interface
### Limit
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: limit
<br />
API:
```
qe.limit(10)
// is equivalent to
qe.raw('limit', 10)
// is equivalent to
qe.raws(
['limit', 10]
)
```
### Offset
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: offset, skip
<br />
API:
```
qe.offset(15)
// is equivalent to
qe.raw('offset', 15)
// is equivalent to
qe.raws(
['skip', 15]
)
```
### Sort
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: sort
<br />
API:
```
qe.sort('asc', ['name.first', 'name.last']).sort('desc', 'deparment')
// is equivalent to
qe.raw('sort', 'asc', 'name.first', 'name.last').raw('sort', 'desc', 'deparment')
// is equivalent to
qe.raws(
['sort', ['asc', 'name.first', 'name.last']],
['sort', 'desc', 'deparment']
)
```
### Select
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
Alias: select
<br />
API:
```
qe.select(true, ['name.first', 'name.last']).select(false, '_id')
// is equivalent to
qe.raw('select', true, 'name.first', 'name.last').raw('select', false, '_id')
// is equivalent to
qe.raws(
['select', [true, 'name.first', 'name.last']],
['select', false, '_id']
)
```
### Raw builders
[Back to top](API.md#query-interface) [Filter Interface](API.md#filter-interface) [Option Interface](API.md#option-interface) <br />
API:
```
qe.raw('limit', ...limit args ).raw('skip', ...offset args );
// is equivalent to
qe.raws(
['limit', ...limit args ],
['offset', ...offset args ]
)
```<file_sep>/test/1.seed/test-data.js
const faker = require('faker');
const lo = require('lodash');
const sports = [
'basketball', 'kabaddi', 'chess', 'hockey', 'malakhamb',
'polo', 'tennis', 'football', 'paper toss'
];
let used = {
countries: [],
heights: [],
namePrefix: [],
sports: []
};
/**
* @dev push data usage for dynamic querying
* @param {string} type one of [country, height]
* @param {any} data
*/
const use = (type, data) => {
switch (type.toLowerCase()) {
case 'country': {
if (!used.countries.includes(data)) used.countries.push(data);
break;
}
case 'height': {
if (!used.heights.includes(data)) used.heights.push(data);
break;
}
case 'name': {
let prefix = data.split(' ')[0];
if (!used.namePrefix.includes(prefix)) used.namePrefix.push(prefix);
break;
}
case 'sports': {
let sportArr = data.sort();
let i = 0;
for (; i < used.sports.length; i++) {
if (lo.isEqual(used.sports[i], sportArr))
break;
}
if (i === used.sports.length)
used.sports.push(sportArr);
break;
}
}
};
const data = [];
for (let i = 0; i < 1000; i++) {
let sportsMin = faker.random.number({ min: 1, max: sports.length - 1 });
let sportsMax = faker.random.number({ min: sportsMin, max: sports.length });
let obj = {
country: faker.address.county(),
height: faker.random.number({ min: 100, max: 220 }),
name: `${faker.name.prefix()} ${faker.name.firstName()} ${faker.name.lastName()}`,
sports: sports.slice(sportsMin, sportsMax)
};
if (faker.random.number({ min: 1, max: 10 }) > 5)
obj.department = faker.commerce.department();
if (faker.random.number({ min: 1, max: 10 }) > 5)
obj.address = [faker.address.streetName(), faker.address.city(), faker.address.zipCode()];
else
obj.address = `${faker.address.streetName()} ${faker.address.city()} ${faker.address.zipCode()}`;
use('country', obj.country);
use('height', obj.height);
use('name', obj.name);
use('sports', obj.sports);
data.push(obj);
}
module.exports = {
data,
used
}; | d4ac2a9e41dbb0478d348fbed50de5b2841b72c3 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 32 | JavaScript | sf-kansara/mongo | 546c2f74126be1923d9fed3ac375c8150637d69e | 24de55cbf122ef3c7442a852fc2c099e02e322b3 |
refs/heads/master | <file_sep># SpiderGame
A squad of robotic spiders are to be sent to explore micro fractures on the wall of a building!
This wall, which is rectangular, must be navigated by the Spiders so that their on-board diagnostics can get a complete view of the wall from close up before sending the data back to the control deck. The spiders are highly autonomous and will follow the instructions sent to them in the start command.
A spider's position is represented by a combination of x and y coordinates and a current orientation. The wall is divided up into a grid to simplify navigation.
An example position might be “0 0 Up” which means the spider is in the bottom left corner and facing up the wall.
In order to control a spider, Control sends a simple string of letters:
The possible letters are 'L', 'R' and 'F'. 'L' and 'R' makes the spider spin 90 degrees left or right respectively, without moving from its current spot. 'F' means move forward one grid point, and maintain the same direction.
Assume that the square directly Up from (x, y) is (x, y+1).
INPUT
Three lines of input are to be received:
1) The first line of input is information pertaining to the size of the wall. 0 0 (bottom left) to x y (Top right) 2) The second line of input is information about the spider’s current location and orientation. This is made up of two integers and a word separated by spaces, corresponding to the x and y coordinates and the spider's orientation. E.g. 4 10 Left 3) The last line of input received is a series of instructions telling the spider how to explore the wall. E.g. FLFLFRFFLF
OUTPUT
The output for the spider should be its final co-ordinates and heading. E.g. 5 8 Right
Example
Test Input:
7 15 4 10 Left FLFLFRFFLF
Expected Output:
5 7 Right
<file_sep><?php
/*
* spider controller
*
*/
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once dirname(dirname(__FILE__)) . '/model/spider.php';
function spiderform_action() {
$x = isset($_POST['x']) ? $_POST['x'] : '';
$y = isset($_POST['y']) ? $_POST['y'] : '';
$m = isset($_POST['m']) ? $_POST['m'] : '';
$n = isset($_POST['n']) ? $_POST['n'] : '';
$path = isset($_POST['path']) ? $_POST['path'] : '';
$dir_str = isset($_POST['dir']) ? $_POST['dir'] : '';
$spider = new spider($x, $y, $m, $n, $dir_str, $path);
$spider->spider($x, $y, $m, $n, $dir_str, $path);
}
?>
<file_sep><?php
/*
* 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.
*/
require_once dirname(dirname(__FILE__)) . '/model/spider.php';
require_once 'PHPUnit/Autoload.php';
class Test extends PHPUnit_Framework_TestCase{
public function spiderUnitTest(){
$object = new spider();
$expected = array("5","7","Right");
$actual = $object->spider(20, 20, 4, 10, Left, FLFLFRFFLF);
$this->assertSame(array_diff($expected, $actual), array_diff($actual, $expected));
}
}
?><file_sep><?php
define('HOST', 'localhost');
define('APPLICATION', 'GameSpider');
?><file_sep><?php
/*
* user model class
*
*/
class spider {
private $x;
private $y;
private $m;
private $n;
private $path;
private $dir_str;
function __construct($x, $y, $m, $n, $dir_str, $path) {
$this->x = $x;
$this->y = $y;
$this->m = $m;
$this->n = $n;
$this->path = $path;
$this->dir_str = $dir_str;
}
public function getX() {
return $this->x;
}
public function getY() {
return $this->y;
}
public function getM() {
return $this->m;
}
public function getN() {
return $this->n;
}
public function getDir() {
return $this->$dir_str;
}
public function getPath() {
return $this->path;
}
public function spider($x, $y, $m, $n, $dir_str, $path) {
for ($i = 0; $i < strlen($path); $i++) {
if ($path[$i] == "F") {
if ($dir_str == "Up") {
$n++;
}
if ($dir_str == "Down") {
$n--;
}
if ($dir_str == "Left") {
$m--;
}
if ($dir_str == "Right") {
$m++;
}
} else if ($path[$i] == "L") {
if ($dir_str === "Up") {
$dir_str = "Left";
} else if ($dir_str == "Down") {
$dir_str = "Right";
} else if ($dir_str == "Left") {
$dir_str = "Down";
} else if ($dir_str == "Right") {
$dir_str = "Up";
}
} else if ($path[$i] == "R") {
if ($dir_str == "Up") {
$dir_str = "Right";
} else if ($dir_str == "Down") {
$dir_str = "Left";
} else if ($dir_str == "Left") {
$dir_str = "Up";
} else if ($dir_str == "Right") {
$dir_str = "Down";
}
}
}
print $m . " " . $n . " " . $dir_str;
}
}
?><file_sep>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/theme.css"></link>
</head>
<body>
<div class="main-container">
<?php
include_once dirname(__FILE__) . '/controller/spider.php';
include_once dirname(__FILE__) . '/view/spiderform.php';
spiderform_action();
?>
</div>
</body>
</html>
| 9b98ee9381804b8a8f471be761785ac85852bc03 | [
"Markdown",
"PHP"
] | 6 | Markdown | kedika/SpiderWall | 1b6db7d673e8a491ac7187c474d3bbb3797c202f | 7701c410794511dcb90ebe01919a8874ce422dd8 |
refs/heads/master | <repo_name>revialim/processing-webapp<file_sep>/public/cube-script.js
//cube initial setup
window.CubeContainer = {
alias: "genericCubeAlias",
boxX : 100,
boxY : 100,
cubeSize : 90,
rotX : 0.5,
rotY : 0.5
};
var cube1 = CubeContainer;
window.CubeArray = [cube1];
//list of all cubes
var allCubes;
//list of all cube sketches
var allCubeSketches;
//set slider function, so that sliders show (updated) CubeContainer values
function setSliders() {
document.getElementById("boxPosX").value = CubeContainer.boxX;
document.getElementById("boxPosY").value = CubeContainer.boxY;
document.getElementById("cubeSize").value = CubeContainer.cubeSize;
document.getElementById("rotationX").value = CubeContainer.rotX;
document.getElementById("rotationY").value = CubeContainer.rotY;
}
//set cube properties according to sliders
function setValue(elem, i) {
if(elem.id === "boxPosX") {
CubeContainer.boxX = i;
} else if(elem.id === "boxPosY") {
CubeContainer.boxY = i;
} else if (elem.id === "cubeSize") {
CubeContainer.cubeSize = i;
} else if (elem.id === "rotationX") {
CubeContainer.rotX = i;
} else if (elem.id === "rotationY") {
CubeContainer.rotY = i;
}
}
//add cube to cubeArray and lock it into position
function addCubeToCubeArray() {
var cube = {
alias : CubeContainer.alias,
boxX : CubeContainer.boxX,
boxY : CubeContainer.boxY,
cubeSize : CubeContainer.cubeSize,
rotX : CubeContainer.rotX,
rotY: CubeContainer.rotY
};
CubeArray.push(cube);
}
function allSketchesIntoHTML(sketches) {
var sketchesHTML = "";
var num = 1;
/*
[ {id: 123, cubes: [{cube1},{cube2}]}, {}, {}]
*/
sketches.forEach(function(sketch) {
sketchesHTML = sketchesHTML + "<div class=\"wrapper\"><div>"+ num +"</div>"+
"<ul>"+
"<li> ID: "+ sketch._id +"</li>"+
"<li> First cube's alias:"+ sketch.cubes[0].alias +"</li></ul>"+
"<button onclick=\"showSketch('"+ sketch._id +"')\"> Show </button></div>";
num = num + 1;
});
document.getElementById('saved-sketches-list').innerHTML = sketchesHTML;
}
function allCubesIntoHTML(cubes) {
var cubeHTML = "";
var num = 1;
cubes.forEach(function(cube) {
cubeHTML = cubeHTML + "<div class=\"wrapper\"><div>"+ num +"</div>"+
"<ul><li>" + cube._id +"</li>"+
"<li> Alias: "+ cube.alias +"</li>"+
"<li> x-coordinate: "+ cube.boxX +"</li>"+
"<li> y-coordinate: "+ cube.boxY +"</li>"+
"<li> cube size: "+ cube.cubeSize +"</li>"+
"<li> rotation x: "+ cube.rotX + "</li>"+
"<li> rotation y: "+ cube.rotY +"</li></ul>"+
"<button onclick=\"showCube('"+ cube._id +"')\"> Show </button></div>";
num = num + 1;
});
document.getElementById('saved-cubes-list').innerHTML = cubeHTML;
}
//get alias from input field
function updateAlias() {
if( document.getElementById('cubeAlias').value != ""){
CubeContainer.alias = document.getElementById('cubeAlias').value;
}
document.getElementById("cube-alias-input").innerHTML = "Current cube alias: "+ CubeContainer.alias;
}
//show cube, when button clicked
function showCube(id) {
//search for cube with correct id in allCubes list
//search field "_id"
allCubes.forEach( function(cube) {
if(cube._id === id){
CubeArray = [];
CubeArray.push(cube);
//set changeable cube to cube's coordinates
CubeContainer.alias = cube.alias;
CubeContainer.boxX = cube.boxX;
CubeContainer.boxY = cube.boxY;
CubeContainer.cubeSize = cube.cubeSize;
CubeContainer.rotX = cube.rotX;
CubeContainer.rotY = cube.rotY;
}
});
setSliders();
updateAlias();
}
function showSketch(id) {
allCubeSketches.forEach( function(sketch) {
if(sketch._id === id) {
CubeArray = []; //empty CubeArray first
sketch.cubes.forEach( function(cube){
CubeArray.push(cube);
} );
//set changeable cube to first cube's coordinates
var firstCube = sketch.cubes[0];
CubeContainer.alias = firstCube.alias;
CubeContainer.boxX = firstCube.boxX;
CubeContainer.boxY = firstCube.boxY;
CubeContainer.cubeSize = firstCube.cubeSize;
CubeContainer.rotX = firstCube.rotX;
CubeContainer.rotY = firstCube.rotY;
}
});
}
function clearCanvas() {
CubeArray = [cube1];
}
//update list of saved sketches
function updateSketchList() {
console.log("getting list of sketches");
var request = $.ajax({
type: "GET",
url: "/cubeSketches",
contentType: "text"
});
request.done(function(response){
allCubeSketches = response;
// add updated information to DOM
allSketchesIntoHTML(response);
});
}
//post sketch
function postSketch() {
console.log("posting sketch...");
$.ajax({
type: "POST",
url: "/cubeSketches",
processData: false,
contentType: "application/json",
data: JSON.stringify({"cubes": CubeArray})
}).done(function() {
console.log("Sketch was saved.");
updateSketchList();
});
}
//update cube list, find all cubes in DB
function updateCubeList() {
console.log("getting list of cubes");
var request = $.ajax({
type: "GET",
url: "/cubes",
contentType: "text"
});
request.done(function(response){
//console.log("allcubes: "+response);
allCubes = response;
// add updated information to DOM
allCubesIntoHTML(response);
});
}
//post cube values
function postValues() {
console.log("posting values");
$.ajax({
type: "POST",
// method: "POST",
url: "/cubes",
processData: false,
contentType: "application/json",
data: JSON.stringify(CubeContainer)
// dataType: "json"
}).done(function() {
console.log("Cube Data was saved.");
updateCubeList();
});
}
window.onload = function(){
updateCubeList();
updateSketchList();
};
<file_sep>/README.md
<h1> Processing Webapp </h1>
<h2> Technologies Used </h2>
<h3> Run project: </h3>
node app.js
<h3> ProcessingJS </h3>
<ul>
<li><a href="http://processingjs.org/">http://processing.org/</a></li>
<li><a href="http://processingjs.org/reference/">http://processingjs.org/reference/</a></li>
</ul>
<h3>ExpressJS</h3>
<ul>
<li><a href="https://expressjs.com/">https://expressjs.com/</a></li>
<li><a href="https://github.com/expressjs/express">https://github.com/expressjs/express</a></li>
</ul>
<h3>MongoDB</h3>
<ul>
<li><a href="https://www.mongodb.com/">https://www.mongodb.com/</a></li>
<li><a href="https://github.com/mongodb/mongo">https://github.com/mongodb/mongo</a></li>
</ul>
<h2> User Stories </h2>
<ul>
<li>user sees processing canvas and can interact with it
<ul><li>e.g. by changing appearance of an object displayed on the canvas</li></ul>
</li>
<li>save individual object settings to a database</li>
<li>load individual object settings from a list created by other users</li>
</ul>
<hr>
<h2> Run </h2>
<div> start mongodb with 'mongod' </div>
<div> start server with 'node app.js' </div>
<div> use application (port 4000) </div>
| 23b57f4b4ea670bcfb2a5b302d3f1697591bdc3f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | revialim/processing-webapp | 7c1f8f253156982d8c473cb86c62d36b382dd8e9 | 323717e5ae607815d86acd394d1087cf8d5834e0 |
refs/heads/master | <file_sep>## makeCacheMatrix takes as argument a square invertible matrix
## and returns a list of getter and setter methods for the matrix
## and its inverse.
## code of the form 'X<<-Y' assigns to X in the parent environment
makeCacheMatrix <- function(x =matrix() ) {
xinverse <- NULL
set <- function(y) {
x <<- y
xinverse <<- NULL
}
get <- function() x
setxinverse <- function(inverse){xinverse <<- inverse}
getxinverse <- function() xinverse
list(set = set, get = get,
setxinverse = setxinverse,
getxinverse = getxinverse)
}
## cacheSolve takes as argument a list, such as type returned by
## makeCacheMatrix. It then checks whether or not the inverse is already
## cached. If the inverse is already cached, it returns the cached inverse
## If the inverse is not already cached, then it calls solve()
## and the inverse setter method, and then returns the inverse.
cacheSolve <- function(x, ...) {
Xinverse <- x$getxinverse()
if(!is.null(Xinverse)) {
message("getting cached data")
return(Xinverse)
}
data <- x$get()
Xinverse <- solve(data, ...)
x$setxinverse(Xinverse)
Xinverse
}
| 6a2d44c6012f0715f1b1a3ca7c83bf07cb380d64 | [
"R"
] | 1 | R | jjsjamesj/ProgrammingAssignment2 | 21a0ca6fcf7b7e1fe7ade54d7ad7b38dea078125 | c4ef17755fb8a1fa1ed9f03d88fd428bbccc22ec |
refs/heads/master | <repo_name>zCodeLAT/STFapp<file_sep>/application/controllers/Registro.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Registro extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper(array('getmenu'));
$this->load->database();
$this->load->model('Users');
}
public function index(){
$data['menu'] = main_menu();
$this->load->view('registro', $data);
}
public function create(){
$username = $this->input->post('username');
$name = $this->input->post('name');
$lastname = $this->input->post('lastname');
$email = $this->input->post('email');
$password = $this->input->post('password');
$password_c = $this->input->post('password_confirm');
$datos = array(
'username'=> $username,
'name'=> $name,
'lastname'=> $lastname,
'email'=>$email,
'password'=>$<PASSWORD>,
);
$datos['menu'] = main_menu();
if(! $this->Users->create($datos)){
$data['msg']='Ocurrió un error';
$this->load->view('registro',$datos);
}
$data['msg']='Registrado correctamente.';
$this->load->view('registro',$datos);
}
}<file_sep>/application/models/Users.php
<?php
class Users extends CI_Model{
function __construct(){
$this->load->database();
}
public function create($datos){
$datos = array(
'username' => $datos['username'],
'name' => $datos['name'],
'lastname' => $datos['lastname'],
'email' => $datos['email'],
'password' => $datos['<PASSWORD>'],
'status' => 1,
'range' => 2,
);
if(!$this->db->insert('Usuarios', $datos)){
return false;
}
return true;
}
} | f83c406d31368005009d6e03159787ec823b5f25 | [
"PHP"
] | 2 | PHP | zCodeLAT/STFapp | f706b289a4112de762cc00f92555d8fedb174a31 | fd357138a43053929fd374d2000822e0f5cd1d38 |
refs/heads/master | <file_sep>/*
Comentario sobre las funciones:
- Las funciones son objetos
- Las funciones tienen propiedades
- Pueden asignarse a una variable
- Pueden pasarse como argumento a una función
- Pueden retornarse
*/
//mi primer funcion
function saludar (nombre) {
console.log(' Hola ' + nombre);
};
saludar('grupo de Node.js');
//operador para concer el tipo de dato de un elemento
// typeof
console.log(typeof('hola'));
console.log(typeof(123));
console.log(typeof(true));
console.log(typeof(saludar));
| 3c1ffb8fefeee2c9facfc4d078483e856601cc9c | [
"JavaScript"
] | 1 | JavaScript | max-munoz/Material | 9a9b7b62a61fa90b0011e92a102e8c559260b801 | c2ebd9b8a5ce63dce0f85482a993323ad8a26b67 |
refs/heads/master | <repo_name>StoneAngelTechnologiesLLC/ProductOrderForm-CS<file_sep>/CIS345Deliverable01/OrderAppJohnPietrangelo/OrederAppGUIForm.cs
//<NAME> CIS345 Tues/Thurs 9am <<<Late Submission>>>
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;
namespace OrderAppJohnPietrangelo
{
public partial class OrederAppGUIForm : Form
{
private static double balance = 300.00;
public OrederAppGUIForm()
{
InitializeComponent();
}
private void OrederAppGUIForm_Load(object sender, EventArgs e)
{
int colQty = 2;
int bldQty = 8;
int drkQty = 5;
int insQty = 15;
int dcfQty = 10;
double colPrice = 10.50;
double bldPrice = 13.00;
double drkPrice = 15.95;
double insPrice = 5.50;
double dcfPrice = 9.99;
DateTime date = DateTime.Now;
orderDateLbl.Text = date.ToString("MM/dd/yyyy");
orderTimeLbl.Text = date.ToString("HH:mm");
colPriceLbl.Text = colPrice.ToString("C");
bldPriceLbl.Text = bldPrice.ToString("C");
drkPriceLbl.Text = drkPrice.ToString("C");
insPriceLbl.Text = insPrice.ToString("C");
dcfPriceLbl.Text = dcfPrice.ToString("C");
colQtyLbl.Text = colQty.ToString();
bldQtyLbl.Text = bldQty.ToString();
drkQtyLbl.Text = drkQty.ToString();
insQtyLbl.Text = insQty.ToString();
dcfQtyLbl.Text = dcfQty.ToString();
balanceLbl.Text = balance.ToString("C");
colOrderQtyTxBx.Select();
}
private void resetBtn_Click(object sender, EventArgs e)
{
colSubTotalTxBx.Clear();
bldSubTotalTxBx.Clear();
drkSubTotalTxBx.Clear();
insSubTotalTxBx.Clear();
dcfSubTotalTxBx.Clear();
colOrderQtyTxBx.Text = "0";
bldOrderQtyTxBx.Text = "0";
drkOrderQtyTxBx.Text = "0";
insOrderQtyTxBx.Text = "0";
dcfOrderQtyTxBx.Text = "0";
cartTxBx.Clear();
}
private void addToCartBtn_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
double colPrice = 10.50;
double bldPrice = 13.00;
double drkPrice = 15.95;
double insPrice = 5.50;
double dcfPrice = 9.99;
int colOrderQty = Convert.ToInt32(colOrderQtyTxBx.Text);
int colInStock = Convert.ToInt32(colQtyLbl.Text);
int bldOrderQty = Convert.ToInt32(bldOrderQtyTxBx.Text);
int bldInStock = Convert.ToInt32(bldQtyLbl.Text);
int drkOrderQty = Convert.ToInt32(drkOrderQtyTxBx.Text);
int drkInStock = Convert.ToInt32(drkQtyLbl.Text);
int insOrderQty = Convert.ToInt32(insOrderQtyTxBx.Text);
int insInStock = Convert.ToInt32(insQtyLbl.Text);
int dcfOrderQty = Convert.ToInt32(dcfOrderQtyTxBx.Text);
int dcfInStock = Convert.ToInt32(dcfQtyLbl.Text);
double colSub = (colPrice * colOrderQty);
double bldSub = (bldPrice * bldOrderQty);
double drkSub = (drkPrice * drkOrderQty);
double insSub = (insPrice * insOrderQty);
double dcfSub = (dcfPrice * dcfOrderQty);
double total = ((colSub) + (bldSub) + (drkSub) + (insSub) + (dcfSub));
colSubTotalTxBx.Text = colSub.ToString("C");
bldSubTotalTxBx.Text = bldSub.ToString("C");
drkSubTotalTxBx.Text = drkSub.ToString("C");
dcfSubTotalTxBx.Text = dcfSub.ToString("C");
cartTxBx.Clear();
cartTxBx.AppendText("\t Current Order\n");
cartTxBx.AppendText("Coffee Type\t Order Quantity\n");
cartTxBx.AppendText("-------------------------------------------\n");
if (colOrderQty<=colInStock && bldOrderQty <= bldInStock && drkOrderQty <=drkInStock && insOrderQty<= insInStock && dcfOrderQty<= dcfInStock && total <= balance)
{
colSubTotalTxBx.Text = colSub.ToString("C");
bldSubTotalTxBx.Text = bldSub.ToString("C");
drkSubTotalTxBx.Text = drkSub.ToString("C");
insSubTotalTxBx.Text = insSub.ToString("C");
dcfSubTotalTxBx.Text = dcfSub.ToString("C");
cartTxBx.AppendText(colLbl.Text);
cartTxBx.AppendText("\t\t" + colOrderQtyTxBx.Text+"\n\n");
cartTxBx.AppendText(bldLbl.Text);
cartTxBx.AppendText("\t\t\t" + bldOrderQtyTxBx.Text+"\n\n");
cartTxBx.AppendText(drkLbl.Text);
cartTxBx.AppendText("\t\t" + drkOrderQtyTxBx.Text + "\n\n");
cartTxBx.AppendText(colLbl.Text);
cartTxBx.AppendText("\t\t" + insOrderQtyTxBx.Text + "\n\n");
cartTxBx.AppendText(dcfLbl.Text);
cartTxBx.AppendText("\t\t\t" + dcfOrderQtyTxBx.Text + "\n");
cartTxBx.AppendText("------------------------------------------\n\n");
cartTxBx.AppendText(" Grand Total: "+total.ToString("C"));
cartTxBx.AppendText("------------------------------------------\n");
cartTxBx.AppendText("\n Date & Time of Purchase\n\n");
cartTxBx.AppendText(" "+date.ToString("MM/dd/yyyy"+" ") + date.ToString("HH:mm"));
}
else if ( total > balance )
{
MessageBox.Show("Error!!! Total Price Exceeds Your Current Balance");
colOrderQtyTxBx.Text = "0";
bldOrderQtyTxBx.Text = "0";
drkOrderQtyTxBx.Text = "0";
insOrderQtyTxBx.Text = "0";
dcfOrderQtyTxBx.Text = "0";
colSubTotalTxBx.Clear();
bldSubTotalTxBx.Clear();
drkSubTotalTxBx.Clear();
insSubTotalTxBx.Clear();
dcfSubTotalTxBx.Clear();
cartTxBx.Clear();
}
else
{
MessageBox.Show("Error!!! Quanty Ordered Exceeds In-Stock Quantity Available");
colOrderQtyTxBx.Text = "0";
bldOrderQtyTxBx.Text = "0";
drkOrderQtyTxBx.Text = "0";
insOrderQtyTxBx.Text = "0";
dcfOrderQtyTxBx.Text = "0";
colSubTotalTxBx.Clear();
bldSubTotalTxBx.Clear();
drkSubTotalTxBx.Clear();
insSubTotalTxBx.Clear();
dcfSubTotalTxBx.Clear();
cartTxBx.Clear();
}
}
private void purchaseBtn_Click(object sender, EventArgs e)
{
double colPrice = 10.50;
double bldPrice = 13.00;
double drkPrice = 15.95;
double insPrice = 5.50;
double dcfPrice = 9.99;
int colOrderQty = Convert.ToInt32(colOrderQtyTxBx.Text);
int colInStock = Convert.ToInt32(colQtyLbl.Text);
int bldOrderQty = Convert.ToInt32(bldOrderQtyTxBx.Text);
int bldInStock = Convert.ToInt32(bldQtyLbl.Text);
int drkOrderQty = Convert.ToInt32(drkOrderQtyTxBx.Text);
int drkInStock = Convert.ToInt32(drkQtyLbl.Text);
int insOrderQty = Convert.ToInt32(insOrderQtyTxBx.Text);
int insInStock = Convert.ToInt32(insQtyLbl.Text);
int dcfOrderQty = Convert.ToInt32(dcfOrderQtyTxBx.Text);
int dcfInStock = Convert.ToInt32(dcfQtyLbl.Text);
double colSub = (colPrice * colOrderQty);
double bldSub = (bldPrice * bldOrderQty);
double drkSub = (drkPrice * drkOrderQty);
double insSub = (insPrice * insOrderQty);
double dcfSub = (dcfPrice * dcfOrderQty);
double total = ((colSub) + (bldSub) + (drkSub) + (insSub) + (dcfSub));
double newBalance = (balance - total);
int newColInStock = (Convert.ToInt32(colQtyLbl.Text) - colOrderQty);
int newBldInStock = (Convert.ToInt32(bldQtyLbl.Text) - bldOrderQty);
int newDrkInStock = (Convert.ToInt32(drkQtyLbl.Text) - drkOrderQty);
int newInsInStock = (Convert.ToInt32(insQtyLbl.Text) - insOrderQty);
int newDcfInStock = (Convert.ToInt32(dcfQtyLbl.Text) - dcfOrderQty);
colQtyLbl.Text = newColInStock.ToString();
bldQtyLbl.Text = newBldInStock.ToString();
drkQtyLbl.Text = newDrkInStock.ToString();
insQtyLbl.Text = newInsInStock.ToString();
dcfQtyLbl.Text = newDcfInStock.ToString();
colSubTotalTxBx.Clear();
bldSubTotalTxBx.Clear();
drkSubTotalTxBx.Clear();
insSubTotalTxBx.Clear();
dcfSubTotalTxBx.Clear();
colOrderQtyTxBx.Text = "0";
bldOrderQtyTxBx.Text = "0";
drkOrderQtyTxBx.Text = "0";
insOrderQtyTxBx.Text = "0";
dcfOrderQtyTxBx.Text = "0";
balance = newBalance;
balanceLbl.Text = newBalance.ToString("C");
cartTxBx.Clear();
}
private void exitBtn_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
}
}
<file_sep>/README.md
# ProductOrderForm-CS
Creation : 1st Form Application. Go Devils!
| 467d8d9236941f98edcbb6e65030d66715256d6e | [
"Markdown",
"C#"
] | 2 | C# | StoneAngelTechnologiesLLC/ProductOrderForm-CS | 899b10025a4ba58a684828bd6a8905282843e254 | 7c66a539d4050c2fbeca33320f71651cf9e87bac |
refs/heads/master | <repo_name>johnfelipe/mathamagik<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
MAX_PER_ROW = 5
SPANS_PER_NUM = 2
TOTAL_SPANS = 12
#OPERATIONS
OP_ADDITION = 1
OP_SUBSTRACTION = 2
OP_MULTIPLICATION = 3
OP_DIVISION = 4
OP_UNKNOWN = 0
def getoperation(action)
puts "OP action is" + action
if (action == "addition")
op= OP_ADDITION
symbol = 0x002b
elsif (action=="substraction")
op = OP_SUBSTRACTION
symbol = 0x2212
elsif (action == "division")
op = OP_DIVISION
symbol = 0x00f7
elsif (action == "multiplication")
op = OP_MULTIPLICATION
symbol = 0x00d7
else
op = OP_UNKNOWN
symbol = '??'
end
puts "returning" + op.to_s
return op, symbol
end
end<file_sep>/app/models/operation.rb
class Operation < ActiveRecord::Base
before_save :create_clientkey
attr_accessible :bottom, :top
serialize :top
serialize :bottom
serialize :options
private
def create_clientkey
self.cookie = SecureRandom.urlsafe_base64
end
end
<file_sep>/db/migrate/20130105224649_change_clientkey_type_of_operations_clientkey.rb
class ChangeClientkeyTypeOfOperationsClientkey < ActiveRecord::Migration
def up
change_table :operations do |t|
t.remove :clientkey
end
add_column :operations, :cookie, :string
end
def down
end
end
<file_sep>/db/migrate/20130101005235_create_operations.rb
class CreateOperations < ActiveRecord::Migration
def change
create_table :operations do |t|
t.text :top
t.text :bottom
t.timestamps
end
end
end
<file_sep>/app/controllers/settings_controller.rb
class SettingsController < ApplicationController
def self.nextindex
@@index ||= Setting.first
@@index = @@index +1
end
end
<file_sep>/app/models/setting.rb
class Setting < ActiveRecord::Base
attr_accessible :sequence
end
<file_sep>/app/controllers/static_pages_controller.rb
include ApplicationHelper
class StaticPagesController < ApplicationController
def new
puts "in New!\n"
end
def opactions
puts "YOA!!!!"
action = params[:value]
puts "got value " + action
@op,@symbol = getoperation(action)
puts "OPERATION ISS" + @op.to_s
end
def home
print "in home!\n"
@operation = params[:operation]
@value = params[:value]
puts @operation
puts @value
end
end
<file_sep>/README.md
mathamagik
==========
Mathamagik is a rails app that generates math tests for kids, similar to testing centers that kids go to. Choose what you want to do, do the math online, or print out sheets. Under development
see http:/www.mathamagik.com for current state
<file_sep>/app/helpers/operations_helper.rb
module OperationsHelper
#find the number of digits
def numDigits(num)
numdig = 0
if (num == 0)
numdig = 1
else
while (num > 0)
num /= 10
numdig = numdig+1
end
end
puts "digits: " + numdig.to_s
numdig
end
def numToArray(num)
digits = numDigits(num)
puts "got digits" + digits.to_s
exponent = 10**(digits-1)
puts "exponent is" + exponent.to_s
n = Array.new
j = digits -1
n[0]= num/exponent
j = digits-1
while j > 0
mod = 10**j
div = 10**(j-1)
n[digits-j]= num%mod/div
j=j-1
end
puts "array is " + n.to_s
n
end
end
<file_sep>/db/migrate/20130104164106_add_clientkey_to_operations.rb
class AddClientkeyToOperations < ActiveRecord::Migration
def change
add_column :operations, :clientkey, :integer
add_column :operations, :createtime, :date
end
end
<file_sep>/app/controllers/operations_controller.rb
include ApplicationHelper
class OperationsController < ApplicationController
def new
op = Operation.new
puts "Yo, operation"
puts params[:count]
puts params[:operation]
@operation = params[:operation]
@count = params[:count]
@symbol = ""
options = Array.new()
for j in (0..4)
#fragile - assumes no more than 4 options per
opt = "option" + j.to_s
if params[opt].present?
options[j] = opt
end
end
if (@operation == nil)
#dont allow direct access to page
redirect_to '/'
return
end
ret = getoperation(@operation)
optype = ret[0]
@symbol = ret[1]
#puts "OPERATION..........." + optype
#puts "SYMBOLS .........." + @symbol.to_s
#puts "OPTIONS............" + params[:options]
generate(@count)
postprocess_data(options, optype)
op.top = @top
op.bottom = @bottom
op.optype = optype
op.numdigits = @count.to_i
op.save
cookies.permanent[:cookie] = op.cookie
end
def postprocess_data(options, optype)
puts "POST!!!.."
if (options.size == 0)
puts "no options, returning !!"
return
else
if (optype == OP_ADDITION)
# only option is numberator bigger
puts "addition.."
if (@count.to_i == 1)
for j in (0..@top.count-1)
if (@top[j]+ @bottom[j] < 10 )
r = 1.times.map{Random.rand(10)}
@top[j] = @top[j]+r[0]
end
end
end
elsif (optype == OP_SUBSTRACTION)
puts "sub"
elsif (optype == OP_MULTIPLICATION)
puts "mult"
else (optype == OP_DIVISION)
puts "div"
end
end
end
def answer
puts "YO ANSWER+++++++++++++++++++++"
@op = Operation.find_by_cookie(cookies[:cookie])
# set a flag if the numerator is more digits than denominator
puts @op.optype
#@op.top[0] + @op.bottom[0]
respond_to do |format|
format.html {redirect_to "/"}
format.js {}
end
end
def generate(cnt)
puts "generating add for count #{@count}"
case @count.to_i
when 1
puts "COUNT IS 1!!!!!!!!"
@top = 10.times.map{ Random.rand(10) }
@bottom = 10.times.map{ Random.rand(10)}
when 2
@top = 10.times.map{ Random.rand(10..99)}
@bottom = 10.times.map{ Random.rand(10..99)}
when 3
@top = 10.times.map{ Random.rand(100..999) }
@bottom = 10.times.map{ Random.rand(100..999)}
when 4
@top = 10.times.map{ Random.rand(1000..9999) }
@bottom = 10.times.map{ Random.rand(1000..9999)}
when 5
@top = 10.times.map{ Random.rand(10000..99999) }
@bottom = 10.times.map{ Random.rand(10000..99999)}
end
#let's sort them nicely to make the client code easier
tmp =0
#puts "...TOP #{@top}, #{@bottom} , count #{@top.count}"
for i in 0..(@top.count()-1)
#puts "++ " + i.to_s + "++"
#puts "top" + @top[i].to_s + "bottom" + @bottom[i].to_s
if (@top[i] < @bottom[i])
tmp = @top[i]
@top[i] = @bottom[i]
@bottom[i] = tmp
end
#puts "top" + @top[i].to_s + "bottom" + @bottom[i].to_s
end
puts "...TOP #{@top}, #{@bottom}"
end
def solution
#puts "tops is" + @bottom
redirect_to '/'
end
def more
redirect_to '/'
end
end
| 397b3d9e15c83f75784dfd26bcd615680804b427 | [
"Markdown",
"Ruby"
] | 11 | Ruby | johnfelipe/mathamagik | c4aff781fed6037dc58b2a30ee96c44e02178a12 | 41d57f632d4c00a70105386791e477321f8797f5 |
refs/heads/master | <repo_name>taichi0529/ios-practice02<file_sep>/README.md
# ios 練習その2
## 内容
- GCDを使った並列プログラミング(キューを使った非同期処理)
- WKWebViewの表示(今後アップデート予定)
## GCDを使った並列プログラミング(キューを使った非同期処理)
iOS(macOS)は並列プログラミングをするときにキューを使った非同期処理として実装出来るようになっています。
自分でスレッド管理をしなくてよくなります。JavaScriptで非同期処理になれていればほぼほぼ違和感なく使えます。
デモでは実行すると「計算中...」と出ます。これはフィボナッチ数列の計算をサブスレッドで行い、メインスレッドで表示を制御しているためです。(多分)
直列の処理でコメントアウトしている方にして実行すると表示されません。
### 参考URL
- https://qiita.com/shoheiyokoyama/items/433ff8e6612d8d368875
- https://dev.classmethod.jp/smartphone/iphone/swift-3-how-to-use-gcd-api-1/
- https://qiita.com/marty-suzuki/items/f0547e40dc09e790328f
- https://developer.apple.com/jp/documentation/ConcurrencyProgrammingGuide.pdf
## Demo

<file_sep>/practice02/GCDViewController.swift
//
// GCDViewController.swift
// practice02
//
// Created by 中村太一 on 2017/11/21.
// Copyright © 2017年 Asaichi LLC. All rights reserved.
//
import UIKit
/// GCDの練習用クラス
/// 下記参照
/// https://developer.apple.com/jp/documentation/ConcurrencyProgrammingGuide.pdf
/// https://dev.classmethod.jp/smartphone/iphone/swift-3-how-to-use-gcd-api-1/
class GCDViewController: UIViewController {
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func serialButtonDIdTouch(_ sender: Any) {
let start = NSDate()
var result:Int = 0
let queueGroup = DispatchGroup()
let queue1 = DispatchQueue(label: "queue1")
// 非同期にしないとラベルが更新されない。
DispatchQueue.main.async() {
self.answerLabel.text = "計算中..."
self.resultLabel.text = "計算結果"
}
// キューとグループを紐付ける
queue1.async(group: queueGroup) {
//フィボナッチの計算を2回直列で行う
result += self.fib(40)
result += self.fib(40)
}
// タスクが全て完了したらメインスレッド上で処理を実行する
queueGroup.notify(queue: DispatchQueue.main) {
let elapsed = NSDate().timeIntervalSince(start as Date)
self.answerLabel.text = String(elapsed) + "秒"
self.resultLabel.text = String(result)
}
// 上記やっていることは下記と結果が同じだが「実行中...」が非同期でないと表示されないので上記の様になっている。
// let start = NSDate()
// var result:Int = 0
// self.answerLabel.text = "計算中..."
// self.resultLabel.text = "計算結果"
// result += fib(40)
// result += fib(40)
// let elapsed = NSDate().timeIntervalSince(start as Date)
// self.answerLabel.text = String(elapsed) + "秒"
// self.resultLabel.text = String(result)
}
@IBAction func conurrentButonDidTouch(_ sender: Any) {
let start = NSDate()
var result:Int = 0
let queueGroup = DispatchGroup()
let queue1 = DispatchQueue(label: "queue1")
let queue2 = DispatchQueue(label: "queue2")
// 非同期にしないとラベルが更新されない。
DispatchQueue.main.async() {
self.answerLabel.text = "計算中..."
self.resultLabel.text = "計算結果"
}
// キューとグループにしている
//フィボナッチの計算を2回非同期(並列)で行う
queue1.async(group: queueGroup) {
result += self.fib(40)
}
queue2.async(group: queueGroup) {
result += self.fib(40)
}
// タスクが全て完了したらメインスレッド上で処理を実行する
queueGroup.notify(queue: DispatchQueue.main) {
let elapsed = NSDate().timeIntervalSince(start as Date)
self.answerLabel.text = String(elapsed) + "秒"
self.resultLabel.text = String(result)
}
}
/// フィボナッチ数列
///
/// - Parameter n:
/// - Returns:
func fib(_ n: Int) -> Int {
return n < 2 ? n : fib(n - 1) + fib(n - 2)
}
}
| 4d70cc621a8e01be46f83f82b2412848f794569b | [
"Markdown",
"Swift"
] | 2 | Markdown | taichi0529/ios-practice02 | 6964cf96c123e4e86c21a5adf481f0d9a1d423ef | 5d61b7a1e1fa37d35ab4ff6a52a99119ccd70fc0 |
refs/heads/master | <repo_name>BlueSkyDetector/blank_detector<file_sep>/blank_detector.py
#!/usr/bin/env python
import ctypes
import struct
from logging import getLogger, StreamHandler, FileHandler, Formatter, INFO
import subprocess
import select
import threading
import time
import os
import signal
logger = getLogger(__name__)
formatter = Formatter('%(asctime)s - %(levelname)s: %(message)s',
'%Y/%m/%d %H:%M:%S')
handler = StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(INFO)
logger.setLevel(INFO)
logger.addHandler(handler)
STREAM_TYPE_STDOUT = 'stdout'
STREAM_TYPE_STDERR = 'stderr'
class DisplayDetector(object):
def __init__(self, display):
pass
def is_idle(self):
ret = False
return ret
class XscreensaverDetector(DisplayDetector):
def __init__(self, display):
self.display = display
self._last_status = False
def is_idle(self):
ret = False
my_env = os.environ.copy()
my_env['DISPLAY'] = self.display
try:
screen_status = subprocess.check_output(
['xscreensaver-command', '-time'],
env=my_env)
except subprocess.CalledProcessError:
logger.warning('"xscreensaver-command -time" is failed')
return ret
if screen_status.decode().find('screen non-blanked since') >= 0:
ret = False
else:
ret = True
if self._last_status != ret:
self._last_status = ret
if ret:
logger.info(
'xscreensaver status of \'%s\' is detected'
' as [blanked]'
% self.display)
else:
logger.info(
'xscreensaver status of \'%s\' is detected'
' as [non-blanked]'
% self.display)
return ret
class DpmsDetector(DisplayDetector):
ctypes.cdll.LoadLibrary('libXext.so')
__libXext = ctypes.CDLL('libXext.so')
DPMSFAIL = -1
DPMSModeOn = 0
DPMSModeStandby = 1
DPMSModeSuspend = 2
DPMSModeOff = 3
def __init__(self, display):
self.display = display
self.display_name_in_byte_string = self.display.encode('ascii')
self.dpms_state = self.DPMSFAIL
def get_DPMS_state(self, display_name_in_byte_string=b':0'):
state = self.DPMSFAIL
if not isinstance(display_name_in_byte_string, bytes):
raise TypeError
display_name = ctypes.c_char_p()
display_name.value = display_name_in_byte_string
self.__libXext.XOpenDisplay.restype = ctypes.c_void_p
display = ctypes.c_void_p(self.__libXext.XOpenDisplay(display_name))
dummy1_i_p = ctypes.create_string_buffer(8)
dummy2_i_p = ctypes.create_string_buffer(8)
if display.value:
if self.__libXext.DPMSQueryExtension(display,
dummy1_i_p,
dummy2_i_p)\
and self.__libXext.DPMSCapable(display):
onoff_p = ctypes.create_string_buffer(1)
state_p = ctypes.create_string_buffer(2)
if self.__libXext.DPMSInfo(display, state_p, onoff_p):
onoff = struct.unpack('B', onoff_p.raw)[0]
if onoff:
state = struct.unpack('H', state_p.raw)[0]
self.__libXext.XCloseDisplay(display)
return state
def is_idle(self):
ret = False
new_dpms_state = self.get_DPMS_state(self.display_name_in_byte_string)
if self.dpms_state != new_dpms_state:
self.dpms_state = new_dpms_state
if self.dpms_state == self.DPMSFAIL:
logger.info(
'DPMS state of \'%s\' is detected as [DPMSFAIL]'
% self.display)
elif self.dpms_state == self.DPMSModeOn:
logger.info(
'DPMS state of \'%s\' is detected as [DPMSModeOn]'
% self.display)
elif self.dpms_state == self.DPMSModeStandby:
logger.info(
'DPMS state of \'%s\' is detected as [DPMSModeStandby]'
% self.display)
elif self.dpms_state == self.DPMSModeSuspend:
logger.info(
'DPMS state of \'%s\' is detected as [DPMSModeSuspend]'
% self.display)
elif self.dpms_state == self.DPMSModeOff:
logger.info(
'DPMS state of \'%s\' is detected as [DPMSModeOff]'
% self.display)
if self.dpms_state in [self.DPMSFAIL, self.DPMSModeOn]:
ret = False
elif self.dpms_state in [self.DPMSModeStandby,
self.DPMSModeSuspend,
self.DPMSModeOff]:
ret = True
return ret
class Worker(threading.Thread):
def __init__(self, cmd, func_for_stdout, func_for_stderr, **kwargs):
threading.Thread.__init__(self, **kwargs)
self.daemon = True
self.cmd = cmd
self.func_for_stdout = func_for_stdout
self.func_for_stderr = func_for_stderr
self.subproc = None
def run(self):
self.subproc = subprocess.Popen(self.cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
universal_newlines=True,
preexec_fn=os.setsid)
def getfd(s):
return s.fileno()
while True:
reads = [getfd(self.subproc.stdout), getfd(self.subproc.stderr)]
ret = select.select(reads, [], [])
for fd in ret[0]:
if fd == getfd(self.subproc.stdout):
read = self.subproc.stdout.readline()
self.func_for_stdout(read, STREAM_TYPE_STDOUT)
if fd == getfd(self.subproc.stderr):
read = self.subproc.stderr.readline()
self.func_for_stderr(read, STREAM_TYPE_STDERR)
if self.subproc.poll() is not None:
break
def terminate(self):
os.killpg(os.getpgid(self.subproc.pid), signal.SIGTERM)
self.subproc.terminate()
class TaskController(object):
def __init__(self,
cmd,
func_for_stdout=None,
func_for_stderr=None):
self.cmd = cmd
if func_for_stdout is None:
self.func_for_stdout = self.default_func_for_stream
else:
self.func_for_stdout = func_for_stdout
if func_for_stderr is None:
self.func_for_stderr = self.default_func_for_stream
else:
self.func_for_stderr = func_for_stderr
self.__process = Worker(self.cmd,
self.func_for_stdout,
self.func_for_stderr)
def default_func_for_stream(self, cmd_output, stream_type):
if cmd_output == '':
return
elif stream_type == STREAM_TYPE_STDOUT:
logger.info('STDOUT: ' + cmd_output.rstrip('\r\n'))
elif stream_type == STREAM_TYPE_STDERR:
logger.warning('STDERR: ' + cmd_output.rstrip('\r\n'))
def is_running(self):
return self.__process.is_alive()
def start(self):
logger.info('Starting \'%s\'...' % self.cmd)
if self.__process.is_alive() is False:
self.__process = Worker(self.cmd,
self.func_for_stdout,
self.func_for_stderr)
self.__process.start()
logger.info('Started.')
else:
logger.info('Already started. Nothing to do.')
def stop(self):
logger.info('Stopping \'%s\'...' % self.cmd)
if self.__process.is_alive() is True:
self.__process.terminate()
logger.info('Stopped.')
else:
logger.info('Already stopped. Nothing to do.')
def main():
default_display = os.environ["DISPLAY"]
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-d',
'--display',
action='store',
default=default_display,
help='For detecting display blank, '
'specify target display name in format \':0.0\' '
'(default is taken from $DISPLAY)')
parser.add_argument('-c',
'--command',
action='store',
required=True,
help='Set a command to execute')
parser.add_argument('-m',
'--module',
action='store',
choices=['DpmsDetector', 'XscreensaverDetector'],
default='DpmsDetector',
help='Select detector module for display status '
'(default: DpmsDetector)')
parser.add_argument('-l',
'--log',
action='store',
help='Set log file path for logging')
args = parser.parse_args()
if args.log:
file_handler = FileHandler(args.log)
file_handler.setFormatter(formatter)
file_handler.setLevel(INFO)
logger.handlers = []
logger.addHandler(file_handler)
logger.info('#' * 80)
logger.info('############# \'%s\' (DISPLAY %s) started #############'
% (__file__, args.display))
display_detector_class = globals()[args.module]
display = display_detector_class(args.display)
task = TaskController(args.command)
try:
while True:
if display.is_idle():
if not task.is_running():
task.start()
else:
if task.is_running():
task.stop()
time.sleep(1)
except KeyboardInterrupt:
logger.info('Keyboard Interrupted...')
finally:
if task.is_running():
task.stop()
logger.info('############# \'%s\' terminating #############'
% __file__)
logger.info('#' * 80)
if __name__ == '__main__':
main()
<file_sep>/README.md
# Blank Detector Task Controller
A tool for running commands only when the display is blank or locked.
## Requirement
- Linux
- Python 2.7 or 3.x
- One of these for display status detector
- DPMS enabled X environment (Please check by 'xset q|grep DPMS')
- 'xscreensaver-command' for xscreensaver status
## Usage
```
$ ./blank_detector.py -h
usage: blank_detector.py [-h] [-d DISPLAY] -c COMMAND
[-m {DpmsDetector,XscreensaverDetector}] [-l LOG]
optional arguments:
-h, --help show this help message and exit
-d DISPLAY, --display DISPLAY
For detecting display blank, specify target display
name in format ':0.0' (default is taken from $DISPLAY)
-c COMMAND, --command COMMAND
Set a command to execute
-m {DpmsDetector,XscreensaverDetector}, --module {DpmsDetector,XscreensaverDetector}
Select detector module for display status (default:
DpmsDetector)
-l LOG, --log LOG Set log file path for logging
```
## Example
```
$ ./blank_detector.py -d ':0.0' -c 'command.sh arg1 arg2' -m DpmsDetector -l /path/to/app.log
```
```
$ ./blank_detector.py -d ':0.0' -c 'command.sh arg1 arg2' -m XscreensaverDetector -l /path/to/app.log
```
| 4c5c7a8776e1121965723e43100e585c59bb96b1 | [
"Markdown",
"Python"
] | 2 | Python | BlueSkyDetector/blank_detector | 8275885513780c4fc0482527f875d49f86260566 | 8160d7408b2882d8d766ae571f952fb644a9b2d9 |
refs/heads/master | <repo_name>bdtexas/Selenium2Library<file_sep>/src/Selenium2Library/keywords/__init__.py
from .logging import LoggingKeywords
from .runonfailure import RunOnFailureKeywords
from .browsermanagement import BrowserManagementKeywords
from .element import ElementKeywords
from .tableelement import TableElementKeywords
from .formelement import FormElementKeywords
from .selectelement import SelectElementKeywords
from .javascript import JavaScriptKeywords
from .cookie import CookieKeywords
from .screenshot import ScreenshotKeywords
from .waiting import WaitingKeywords
from .alert import AlertKeywords
__all__ = [
"LoggingKeywords",
"RunOnFailureKeywords",
"BrowserManagementKeywords",
"ElementKeywords",
"TableElementKeywords",
"FormElementKeywords",
"SelectElementKeywords",
"JavaScriptKeywords",
"CookieKeywords",
"ScreenshotKeywords",
"WaitingKeywords",
"AlertKeywords"
]
| eaa951a405b02175c08eb6e04285df0e496e253e | [
"Python"
] | 1 | Python | bdtexas/Selenium2Library | db0ae4fb856d37d5119be899df4429a2f5ab5ab8 | 6df67f59ba5f3d1ecfdf74bac5872e173bf74b9d |
refs/heads/master | <repo_name>sunshu/common-app<file_sep>/common/src/main/java/sunshu/me/common/widget/AdapterCallBack.java
package sunshu.me.common.widget;
/**
* author:sunshu
* time:2019/2/24:22:57
* desc:
*/
public interface AdapterCallBack<Data> {
void update(Data data,RecyclerAdapter.ViewHolder<Data> holder);
}
<file_sep>/common/src/main/java/sunshu/me/common/network/utils/NetErrStringUtils.java
package sunshu.me.common.network.utils;
import android.content.Context;
/**
* @Describe:网络错误提示工具类
* @Package: com.jy.core.lib.network.util
* @Author: wl
* @Date: 2018/1/17 0017 上午 10:46
* @Copyright: jingyou
*/
public class NetErrStringUtils {
public static final int ERR_404 = 404;
public static final int ERR_500 = 500;
public static final int ERR_502 = 502;
public static String getErrString(Context context, int code) {
String result;
switch (code) {
case ERR_404:
result = "无法找到指定位置的资源";
break;
case ERR_500:
result = "内部服务器错误";
break;
case ERR_502:
result = "网关错误";
break;
default:
result = "网络错误";
break;
}
return result;
}
public static String getErrString(Context context, Throwable t) {
String result;
if (t instanceof java.net.SocketTimeoutException) {
result = "网络超时";
} else if (t != null && t.getMessage() != null && t.getMessage().equalsIgnoreCase("canceled")) {
result = "请求已经取消";
} else {
result = "网络错误" + t.getMessage();
}
return result;
}
}
<file_sep>/common/src/main/java/sunshu/me/common/widget/RecyclerAdapter.java
package sunshu.me.common.widget;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import sunshu.me.common.R;
/**
* author:sunshu
* time:2019/2/24:22:40
* desc:通用adapter
*/
public abstract class RecyclerAdapter<Data>
extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder<Data>>
implements View.OnClickListener,View.OnLongClickListener ,AdapterCallBack<Data>{
private final List<Data> mDataList ;
private AdapterListener<Data> adapterListener;
public RecyclerAdapter() {
this(null);
}
public RecyclerAdapter(AdapterListener<Data> listener) {
this(new ArrayList<Data>(),listener);
}
public RecyclerAdapter(List<Data> dataList,AdapterListener<Data> listener) {
this.mDataList = dataList;
this.adapterListener = listener;
}
/**
* 复写默认的布局类型返回
* @param position
* @return
*/
@Override
public int getItemViewType(int position) {
return getItemViewType(position,mDataList.get(position));
}
/**
* 返回的都是XML布局的Id
* @param position
* @param data
* @return
*/
@LayoutRes
protected abstract int getItemViewType(int position,Data data);
/**
* 创建一个新的ViewHolder
* @param viewGroup
* @param viewType
* @return
*/
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View root = inflater.inflate(viewType,viewGroup,false);
ViewHolder holder = onCreateViewHolder(root,viewType);
root.setOnClickListener(this);
root.setOnLongClickListener(this);
root.setTag(R.id.tag_recycler_holder,holder);
holder.unbinder = ButterKnife.bind(holder,root);
holder.callBack = this;
return holder;
}
protected abstract ViewHolder<Data> onCreateViewHolder(View holder,int ViewType);
/**
* 绑定数据到Holder
* @param viewHolder
* @param i
*/
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
Data data = mDataList.get(i);
viewHolder.bind(data);
}
@Override
public int getItemCount() {
return mDataList.size();
}
public void addData(Data data){
mDataList.add(data);
notifyItemInserted(mDataList.size() -1);
}
public void addData(Data... dataList){
if (dataList!= null && dataList.length > 0){
int startPos = mDataList.size();
Collections.addAll(mDataList,dataList);
notifyItemRangeChanged(startPos,mDataList.size() -1);
}
}
public void addData(Collection dataList){
if (dataList!= null && dataList.size() > 0){
int startPos = mDataList.size();
mDataList.addAll(dataList);
notifyItemRangeChanged(startPos,mDataList.size() -1);
}
}
public void clean(){
mDataList.clear();
notifyDataSetChanged();
}
public void replace(Collection<Data> data){
mDataList.clear();
if (data != null && data.size() > 0){
mDataList.addAll(data);
}
notifyDataSetChanged();
}
@Override
public void onClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag(R.id.airPanelSubLayout);
if (adapterListener != null){
int position = viewHolder.getAdapterPosition();
adapterListener.onItemClick(viewHolder,mDataList.get(position));
}
}
@Override
public boolean onLongClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag(R.id.airPanelSubLayout);
if (adapterListener != null){
int position = viewHolder.getAdapterPosition();
adapterListener.onItemLongClick(viewHolder,mDataList.get(position));
return true;
}else {
return false;
}
}
public void setAdapterListener(AdapterListener listener){
this.adapterListener = listener;
}
public interface AdapterListener<Data>{
void onItemClick(RecyclerAdapter.ViewHolder holder,Data data);
void onItemLongClick(RecyclerAdapter.ViewHolder holder,Data data);
}
public static abstract class ViewHolder<Data> extends RecyclerView.ViewHolder {
protected Data mData;
private Unbinder unbinder;
private AdapterCallBack<Data> callBack;
public ViewHolder(@NonNull View itemView) {
super(itemView);
}
/**
* 用于绑定数据的触发
* @param data
*/
void bind(Data data){
this.mData = data;
onBind(data);
}
protected abstract void onBind(Data data);
public void update(Data data){
if (callBack != null){
callBack.update(data,this);
}
}
}
}
<file_sep>/common/src/main/java/sunshu/me/common/network/NetworkListener.java
package sunshu.me.common.network;
import okhttp3.ResponseBody;
/**
* @Describe:
* @Package: sunshu.me.common.network
* @Author: sunshu
* @Date: 2019/4/29/ 17:35
* @Copyright: jingyou
*/
public interface NetworkListener {
/**
* 服务器返回成功回调
* @param response
*/
void onDataSuccess(ResponseBody response);
/**
* 调用失败回调
*/
void onDataError(int requestCode, int responseCode, String message);
}
<file_sep>/README.md
"# common-app"
| c02d1c05edcde5b38ad5ac1145d5be977faa32d3 | [
"Markdown",
"Java"
] | 5 | Java | sunshu/common-app | bb2eed636f8b495a05fe628a4bccf942cd3f28fd | 98a3cdf916620b965e327cbac1256cad2038235c |
refs/heads/master | <repo_name>jovysun/UU<file_sep>/README.md
# jQuery插件集
## 前言
很早之前写的,现在用的场景应该越来越少了,简单整理下作个纪念吧。
## 插件包括
弹出框,倒计时,tab切,焦点图,商品轮播图,滚屏,插入多媒体(微博,flash等),懒加载。
## 配置
具体参数见注释
## 示例查看
```shell
npm install
```
```shell
gulp
```
<file_sep>/lib/UU-2.1.js
/*
* 依赖jquery1.7以上版本
*/
var UU = UU || {};
var products = undefined == products ? [] : products;
;(UU.init = function(){
// 悬浮框处理
$(window).scroll(function(){
var topHide = $(document).scrollTop(); //页面上部被卷去高度
var windowHeight = $(window).height(); //窗口可视区域高度
var bottomFloatHeight = $('#bottomFloat').height(); //底悬浮高度
var backTopFloatHeight = $('#backTopFloat').height();
var bottomTop = windowHeight+topHide-bottomFloatHeight;
var backTop = windowHeight+topHide-backTopFloatHeight-20;
//针对IE6不支持fixed的处理start
if ($.browser.msie && ($.browser.version == "6.0") && !$.support.style) {
$('#bottomFloat').stop().animate({'top':bottomTop},'fast');
$('#backTopFloat').stop().animate({'top':backTop},'fast');
}
//针对IE6不支持fixed的处理end
//滚动渐隐渐现左右悬浮start
if(topHide>300){
$('#leftFloat').show();
$('#rightFloat').show();
$('#backTopFloat').show();
}else{
$('#leftFloat').hide();
$('#rightFloat').hide();
$('#backTopFloat').hide();
}
//滚动渐隐渐现左右悬浮end
});
})();
// tab切
/*
* paneCount: Number;(tab切面板数量)
* uevent: String; (触发事件类型,'hover','click','doubleclick'等)
*/
UU.tab = function(elements, options){
// 默认值
var defaults = {
paneCount: 2,
uevent: 'hover'
};
var opts = $.extend({}, defaults, options);
var paneCount = opts.paneCount;
var uevent = opts.uevent;
$(elements).each(function(){
var tab = $(this);
var $tabBtn = tab.find('.tab-btn');
var $tabPane = tab.find('.tab-panes:first > .tab-pane');
$tabBtn.live(uevent,function(e){
e.stopPropagation();
var $this = $(this);
var index = $this.index();
$this.addClass('on').siblings().removeClass('on');
$tabPane.eq(index).addClass('on').siblings().removeClass('on');
});
})
}
// 焦点图
/*
* pageWidth: Number; (焦点图宽度)
* pageHeight: Number; (焦点图高度)
* pageCount: Number; (焦点图数量)
* interval: Number; (每张图播放间隔)
* speed: Number; (每张图播放速度)
* delay: Number; (悬浮停止后延迟多久恢复自动播放)
* auto: Boolean; (是否自动播放)
* easing: String; (动画函数,使用需要引入动画函数脚本或者扩展jquery的easing)
* pageNumberWidth: Number; (分页按钮宽度)
*/
UU.slideFocus = function(elements, options){
var defaults = {
pageWidth: 1000,
pageHeight: 500,
pageCount: 3,
interval: 3000,
delay: 5000,
speed: 500,
auto: true,
easing: 'linear',
pageNumWidth: 12
};
var opts = $.extend({}, defaults, options);
var pageWidth = opts.pageWidth;
var pageHeight = opts.pageHeight;
var pageCount = opts.pageCount;
var interval = opts.interval;
var delay = opts.delay;
var speed = opts.speed;
var auto = opts.auto;
var easing = opts.easing;
var pageNumWidth = opts.pageNumWidth;
var timer = null;
$(elements).each(function(){
var slide = $(this);
var btn = slide.find('.btn');
var btnL = slide.find(".prev");
var btnR = slide.find(".next");
var nums = slide.find(".nums");
var num = nums.find('.num');
var picBox = slide.find(".box");
var scrollContent = slide.find(".content");
var page = slide.find(".page");
var init = function(){
var numsWidth = (pageNumWidth+4)*pageCount;
nums.css({'width':numsWidth,'marginLeft':-numsWidth/2});
picBox.css({'width':pageWidth,'height':pageHeight,'overflow':'hidden'});
scrollContent.css({'width':pageWidth*pageCount*2,'left':-pageWidth*pageCount});
page.css({'width':pageWidth,'height':pageHeight});
scrollContent.append(scrollContent.html());
}();
var move = function(){
scrollContent.stop().animate({left:[-pageWidth*(pageCount+1),easing]},speed,function(){
var lis = scrollContent.find(".page");
scrollContent.append(lis.eq(0).clone());
lis.eq(0).remove();
scrollContent.css({left:-pageWidth*pageCount});
lightNum();
})
};
var lightNum = function(){
var activePageNum = slide.find('.page').eq(pageCount).attr('data-page');
slide.find('.num').eq(activePageNum-1).addClass('on').siblings().removeClass('on');
};
if (auto) {
timer = setInterval(move,interval);
slide.hover(function(){
clearInterval(timer);
},function(){
timer = setTimeout(function(){timer = setInterval(move,interval);},delay);
});
};
btnR.click(function(){
scrollContent.stop().animate({left:[-pageWidth*(pageCount+1),easing]},speed,function(){
var lis = scrollContent.find(".page");
scrollContent.append(lis.eq(0).clone());
lis.eq(0).remove();
scrollContent.css({left:-pageWidth*pageCount});
lightNum();
})
})
btnL.click(function(){
scrollContent.stop().animate({left:[-pageWidth*(pageCount-1),easing]},speed,function(){
var lis = scrollContent.find(".page");
var lastPageIndex = pageCount*2 -1;
scrollContent.prepend(lis.eq(lastPageIndex).clone());//这里的eq值等于page*2-1
lis.eq(lastPageIndex).remove();
scrollContent.css({left:-pageWidth*pageCount});
lightNum();
})
});
num.click(function(){
var _this = $(this);
var toPageNum = _this.index()+1;
var fromPageNum = slide.find('.page').eq(pageCount).attr('data-page');
var left = -pageWidth*pageCount - (toPageNum - fromPageNum)*pageWidth;
_this.addClass('on').siblings().removeClass('on');
scrollContent.stop().animate({left:[left,easing]},speed);
});
})
}
// 轮播商品图
/*
* pageWidth: Number; (焦点图宽度)
* pageHeight: Number; (焦点图高度)
* pageCount: Number; (焦点图数量)
* interval: Number; (每张图播放间隔)
* speed: Number; (每张图播放速度)
* delay: Number; (悬浮停止后延迟多久恢复自动播放)
* auto: Boolean; (是否自动播放)
* easing: String; (动画函数,使用需要引入动画函数脚本或者扩展jquery的easing)
* pageNumberWidth: Number; (分页按钮宽度)
*/
UU.slideProduct = function(elements, options){
var defaults = {
pageWidth: 1000,
pageHeight: 500,
pageCount: 3,
interval: 3000,
delay: 5000,
speed: 500,
auto: true,
easing: 'linear',
pageNumWidth: 12
};
var opts = $.extend({}, defaults, options);
var pageWidth = opts.pageWidth;
var pageHeight = opts.pageHeight;
var pageCount = opts.pageCount;
var interval = opts.interval;
var delay = opts.delay;
var speed = opts.speed;
var auto = opts.auto;
var easing = opts.easing;
var pageNumWidth = opts.pageNumWidth;
var timer = null, activePageIndex = 0;
$(elements).each(function(){
var slide = $(this);
var btn = slide.find('.btn');
var btnL = slide.find(".prev");
var btnR = slide.find(".next");
var nums = slide.find(".nums");
var num = nums.find('.num');
var picBox = slide.find(".box");
var scrollContent = slide.find(".content");
var page = slide.find(".page");
var init = function(){
var numsWidth = (pageNumWidth+4)*pageCount;
nums.css({'width':numsWidth,'marginLeft':-numsWidth/2});
picBox.css({'width':pageWidth,'height':pageHeight,'overflow':'hidden'});
scrollContent.css({'width':pageWidth*pageCount});
page.css({'width':pageWidth,'height':pageHeight});
}();
var move = function(direction){
if (direction === 'prev') {
activePageIndex = activePageIndex === 0 ? pageCount-1 : activePageIndex-1;
} else{
activePageIndex = activePageIndex === pageCount-1 ? 0 : activePageIndex+1;
};
scrollContent.stop().animate({left:[-pageWidth*activePageIndex,easing]},speed,function(){
lightNum(activePageIndex);
})
};
var lightNum = function(activePageIndex){
slide.find('.nums').find('li').eq(activePageIndex).addClass('on').siblings().removeClass('on');
};
if (auto) {
timer = setInterval(move,interval);
slide.hover(function(){
clearInterval(timer);
},function(){
timer = setTimeout(function(){timer = setInterval(move,interval);},delay);
});
};
btnL.click(function(){
move('prev');
});
btnR.click(function(){
move('next');
})
num.click(function(){
var _this = $(this);
var left = -pageWidth*_this.index();
_this.addClass('on').siblings().removeClass('on');
scrollContent.stop().animate({left:[left,easing]},speed);
});
})
}
// 不间断滚屏效果
/*
* itemWidth: Number; (条目宽度)
* itemHeight: Number; (条目高度)
* itemCount: Number; (条目数量)
* speed: Number; (滚屏速度)
* step: Number; (滚屏跨度)
* auto: Boolean; (是否自动播放)
* easing: String; (动画函数,使用需要引入动画函数脚本或者扩展jquery的easing)
* direction: String; (滚屏方向)
*/
UU.roll = function(elements, options){
var defaults = {
itemWidth: 150,
itemHeight: 40,
itemCount: 10,
speed: 20,
step: 1,
auto: true,
easing: 'linear',
direction: 'right-to-left'
};
var opts = $.extend({}, defaults, options);
var itemWidth = opts.itemWidth;
var itemHeight = opts.itemHeight;
var itemCount = opts.itemCount;
var speed = opts.speed;
var step = opts.step;
var auto = opts.auto;
var direction = opts.direction;
var pageWidth = 0, pageHeight = 0, timer = null;
$(elements).each(function(){
var roll = $(this);
var rollBox = roll.find('.roll-box');
var rollContent = roll.find('.roll-content');
var rollList = roll.find('.roll-list');
var rollItem = rollList.find('li');
var rollPrev = roll.find('.prev');
var rollNext = roll.find('.next');
var init = function(){
rollBox.css({'overflow': 'hidden'});
rollItem.css({'width': itemWidth, 'height': itemHeight, 'overflow': 'hidden'});
if (direction === 'right-to-left' || direction === 'left-to-right') {
// 左右滚动
pageWidth = itemWidth*itemCount;
pageHeight = itemHeight;
rollList.css({'width':pageWidth,'height':pageHeight});
rollContent.append(rollContent.html()).css({'width':pageWidth*2, 'height':pageHeight, 'left': -pageWidth});
}else{
// 上下滚动
pageWidth = itemWidth;
pageHeight = itemHeight*itemCount;
rollList.css({'width':pageWidth,'height':pageHeight});
rollContent.append(rollContent.html()).css({'width':pageWidth, 'height':pageHeight*2, 'top': -pageHeight});
}
}();
var play = function(direction){
if (direction === 'left-to-right') {
clearInterval(timer);
timer = setInterval(function(){
var left = parseInt(rollContent.css('left'));
if (left >= 0) {
rollContent.css('left',-pageWidth);
}else{
rollContent.css('left',left+step);
}
},speed);
}else if(direction === 'right-to-left'){
clearInterval(timer);
timer = setInterval(function(){
var left = parseInt(rollContent.css('left'));
if (left <= -pageWidth) {
rollContent.css('left',0);
}else{
rollContent.css('left',left-step);
}
},speed);
}else if(direction === 'top-to-bottom'){
clearInterval(timer);
timer = setInterval(function(){
var top = parseInt(rollContent.css('top'));
if (top >= 0) {
rollContent.css('top', -pageHeight);
}else{
rollContent.css('top',top+step);
}
},speed);
}else{
clearInterval(timer);
timer = setInterval(function(){
var top = parseInt(rollContent.css('top'));
if (top <= -pageHeight) {
rollContent.css('top',0);
}else{
rollContent.css('top',top-step);
}
},speed);
}
};
roll.hover(function(){
clearInterval(timer);
},function(){
play(direction);
});
// rollPrev.click(function(){
// direction = 'left-to-right';
// play(direction);
// });
// rollNext.click(function(){
// direction = 'right-to-left';
// play(direction);
// })
if (auto) {
timer = setInterval(function(){
play(direction);
},speed);
}
})
}
// 弹出框
/* 主要用于促销页面弹出图片
* dialogWidth: Number; (弹出框宽度)
* dialogHeight: Number; (弹出框高度)
* uevent: String; (触发事件类型,'hover','click','doubleclick'等)
*/
UU.dialog = function(elements, options){
var defaults = {
dialogWidth: 500,
dialogHeight: 400,
uevent: 'click'
};
var opts = $.extend({}, defaults, options);
var dialogWidth = opts.dialogWidth;
var dialogHeight = opts.dialogHeight;
var uevent = opts.uevent;
var UU_mask = $('#UU_mask'), UU_close = $('#UU_close'), UU_dialogCoat = $('#UU_dialogCoat'), UU_dialogContent = $('#UU_dialogContent');
var init = function(){
var initHtml = '<div id="UU_mask" style="width:100%;height:100%;position:fixed;z-index:999;left:0;top:0;background-color:#000;opacity:0.5;display:none;"></div>'
+'<div id="UU_dialogCoat" style="display:none;">'
+'<a href="javascript:void(0)" id="UU_close" style="width:100px;height:100px;position:absolute;right:0;top:0;z-index:2;"></a>'
+'<div id="UU_dialogContent" style="width:100%;height:100%;position:relative;"></div>'
+'</div>';
if ($('#UU_mask').length <= 0) {
$('body').append(initHtml);
UU_mask = $('#UU_mask'), UU_close = $('#UU_close'), UU_dialogCoat = $('#UU_dialogCoat'), UU_dialogContent = $('#UU_dialogContent');
}
}();
$(elements).live(uevent,function(){
var _this = $(this);
UU_dialogCoat.css({'width':dialogWidth,'height':dialogHeight,'position':'fixed','z-index':'1000','left':'50%','margin-left':-dialogWidth/2,'top':'50%','margin-top':-dialogHeight/2});
UU_dialogContent.html('<img src="' + _this.attr('data-src') + '">');
UU_mask.fadeIn();
UU_dialogCoat.fadeIn();
})
UU_close.live('click',function(){
UU_dialogCoat.fadeOut();
UU_mask.fadeOut();
})
}
// 倒计时
/* 可以实现“天时分秒”、“时分秒”、“分秒”倒计时
* fromStart: String; (倒计时颗粒度'day'/'hour'/'minute')
* endDate: String; (截止时间,注意格式'2018/06/15 00:00:00')
*/
UU.timedown = function(elements,options){
var defaults = {
fromStart: 'day',
endDate: '2018/06/15 00:00:00'
};
var opts = $.extend({}, defaults, options);
var fromStart = opts.fromStart;
var endDate = opts.endDate;
var spacing = opts.spacing;
var formatNum = function(num){
return num.toString().replace(/^(\d)$/, "0$1");
}
var validateDate = function(dateString){
var reg = /^(\d{1,4})(\/|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var r = dateString.match(reg);
if(r==null){
alert("日期格式不正确,请重新输入");
return false;
}else{
return true;
}
};
$(elements).each(function(){
var timedown = $(this);
if (!validateDate(endDate)) {
return false;
};
var endTime = new Date(endDate).getTime();
var nowTime = new Date().getTime();
var timer = null;
if (endTime > nowTime) {
var tdTime = (endTime - nowTime)/1000;
timer = setInterval(play,1000);
} else{
switch(fromStart){
case 'hour':
timedown.html('<span class="hour">00</span><span class="minute">00</span><span class="second">00</span>');
break;
case 'minute':
timedown.html('<span class="minute">00</span><span class="second">00</span>');
break;
default:
timedown.html('<span class="day">00</span><span class="hour">00</span><span class="minute">00</span><span class="second">00</span>');
}
}
function play(){
if (tdTime > 0) {
var _D = Math.floor(tdTime / 86400)
var _H = Math.floor((tdTime - 86400 * _D) / 3600);
var _M = Math.floor((tdTime - _D * 86400 - _H * 3600) / 60);
var _S = Math.floor(tdTime % 60);
switch(fromStart){
case 'hour':
timedown.html('<span class="hour">'+formatNum(_H + _D*24)+'</span><span class="minute">'+formatNum(_M)+'</span><span class="second">'+formatNum(_S)+'</span>');
break;
case 'minute':
timedown.html('<span class="minute">'+formatNum(_M + _H*60+ _D*24*60)+'</span><span>'+formatNum(_S)+'</span>');
break;
default:
timedown.html('<span class="day">'+formatNum(_D)+'</span><span class="hour">'+formatNum(_H)+'</span><span class="minute">'+formatNum(_M)+'</span><span class="second">'+formatNum(_S)+'</span>');
}
tdTime--;
} else{
clearInterval(timer);
}
}
})
}
// 添加多媒体
/* 实现添加flash,微博,html片段等多媒体
* mediaType: String; (要添加的多媒体类型)
* mediaContent: String; (多媒体内容,flash是地址链接,微博直播是话题,其他是html代码片段);
* width:Number; (展示宽度)
* height: Number; (展示高度)
* uid: String; (新浪微博:用户UID)
* listid: String; (新浪微博:指定分组ID,“特别推荐”标签中显示指定人员列表的微博, 可通过微集体管理器添加分组)
*/
UU.addMedia = function(element,options){
var defaults = {
mediaType: 'flash',
mediaContent: '',
width: 500,
height: 400,
uid: '', //新浪微博:用户UID
listid: '' //新浪微博:指定分组ID,“特别推荐”标签中显示指定人员列表的微博, 可通过微集体管理器添加分组
};
var opts = $.extend({}, defaults, options);
var mediaType = opts.mediaType;
var mediaContent = opts.mediaContent;
var width = opts.width;
var height = opts.height;
// 如果是新浪微博还得有以下两个参数
var uid = opts.uid;
var listid = opts.listid;
switch(mediaType){
case 'flash':
var flashHtml = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'">'
+'<param name="allowScriptAccess" value="always" />'
+'<param name="allowFullScreen" value="false" />'
+'<param name="movie" value="'+mediaContent+'" />'
+'<param name="quality" value="high" />'
+'<param name="wmode" value="transparent" />'
+'<param name="flashvars" value="ap=0" />'
+'<embed src="'+mediaContent+'" quality="high" wmode="transparent" width="'+width+'" height="'+height+'" name="focusshow" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_cn" flashvars="ap=0"></embed>'
+'</object>';
$(element).html(flashHtml);
break;
case 'weibo':
var weml = '<wb:livestream skin="silver" topic="'+mediaContent+'" width="'+width+'" height="'+height+'" uid="'+uid+'" listid="'+listid+'" ></wb:livestream>';
$('html').attr('xmlns:wb','http://open.weibo.com/wb');
$('head').append('<script src="http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=" type="text/javascript" charset="utf-8"></script>');
$(element).html(weml);
break;
default:
$(element).html(mediaContent);
}
}
// 懒加载
/* 实现图片、伪动态商品模块等的懒加载
* threshold: Number; (设置临界点)
* uevent: String; (触发时间类型,'scroll','click'等);
* dataAttribute:String; (图片懒加载中保存图片地址的属性名)
* placeholder: String; (占位图)
* callback: Function; (回调函数名)
* data: JSON; (伪动态商品数据)
*/
UU.lazyload = function(elements, options){
var defaults = {
threshold : 0,
uevent : "scroll",
dataAttribute : "src2",
placeholder : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC",
callback : null,
data : []
};
var opts = $.extend({}, defaults, options);
var $window = $(window);
var $elements = $(elements);
var threshold = opts.threshold;
var dataAttribute = opts.dataAttribute;
var uevent = opts.uevent;
var placeholder = opts.placeholder;
var data = opts.data;
var callback = opts.callback;
var inviewport = function(element) {
var $element = $(element);
var leftFold = $window.scrollLeft();
var topFold = $window.scrollTop();
var winWidth = $window.width();
var winHeight = $window.height();
var eleX = $element.offset().left;
var eleY = $element.offset().top;
return ((eleX-threshold) < (winWidth+leftFold)) && ((eleY-threshold) < (winHeight+topFold));
};
function update() {
$elements.each(function() {
if (inviewport(this)) {
$(this).trigger("appear");
}
});
}
$elements.each(function(index, element) {
var self = this;
var $self = $(self);
self.loaded = false;
if (!callback) {
if ($self.is("img")) {
$self.attr("src", placeholder);
}else{
$self.css("background-image", "url('" + placeholder + "')");
}
}
// 进入可视区域时触发加载
$self.one("appear", function() {
if (!this.loaded) {
if (!callback) {
var original = $self.attr(dataAttribute);
if ($self.is("img")) {
$self.attr("src", original);
} else {
$self.css("background-image", "url('" + original + "')");
}
} else{
if (undefined == data[index]) {
// console.log('productDoms:' + $elements.length + ' jsProducts:' + data.length);
return false;
}else{
callback($self, data[index]);
}
};
self.loaded = true;
// 移除已经加载的图片,以免下次循环再触发
elements = $.grep(elements, function(element) {
return !element.loaded;
});
}
});
});
$window.bind(uevent+' resize', function() {
update();
});
$(document).ready(function() {
update();
});
}<file_sep>/gulpfile.js
'use strict'
//引入gulp及各种组件;
const gulp = require('gulp');
const browserSync = require('browser-sync').create();
// 创建本地服务器,并实时更新页面
gulp.task('serve', function() {
browserSync.init({
// https: 'https',
port: 3000,
// browser: ["google chrome"],
server: {
baseDir: './',
index: 'examples/index.html'
}
});
});
gulp.task('default', gulp.series('serve')); | 6ac23d2060d98a1356adf5b019e346fbd9f97682 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | jovysun/UU | 138dc44c33dfdb06423a7f158a132205a4fef051 | d8ad119c0bdd0cb53126bda70f720b7da5a3d171 |
refs/heads/master | <repo_name>vsypraktikum/web<file_sep>/Mattes/2/app/view.py
# coding: utf-8
# sehr einfache Erzeugung des Markups f�r vollst�ndige Seiten
# jeweils 3 Abschnitte:
# - begin
# - content
# - end
# bei der Liste wird der content-Abschnitt wiederholt
# beim Formular nicht
import mako
import codecs
import os.path
import string
from mako import template
from mako.lookup import TemplateLookup
# ----------------------------------------------------------
class View_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
pass
# -------------------------------------------------------
def createstart_px(self):
# -------------------------------------------------------
return self.readFile_p('index.html')
# -------------------------------------------------------
def createStudentList_px(self, data_opl):
# -------------------------------------------------------
data_opl = data_opl['student']['list']
template_o = template.Template(self.readTemplate_p('student_list.tpl'))
return template_o.render(data_o=data_opl)
# -------------------------------------------------------
def createLehrerList_px(self, data_opl):
# -------------------------------------------------------
data_opl = data_opl['lehrer']['list']
template_o = template.Template(self.readTemplate_p('lehrer_list.tpl'))
return template_o.render(data_o = data_opl)
# -------------------------------------------------------
def createFirmenList_px(self, data_opl):
# -------------------------------------------------------
data_opl = data_opl['firma']['list']
template_o = template.Template(self.readTemplate_p('firma_list.tpl'))
return template_o.render(data_o=data_opl)
# -------------------------------------------------------
def createPPAList_px(self, data_opl):
# -------------------------------------------------------
data_opl = data_opl['ppangebot']['list']
template_o = template.Template(self.readTemplate_p('ppa_list.tpl'))
return template_o.render(data_o=data_opl)
# -------------------------------------------------------
def createAuswertungFirma_px(self, data_opl):
# -------------------------------------------------------
ppangebot = data_opl['ppangebot']['list']
ppaktuell = data_opl['ppaktuell']['list']
ppabgeschlossen = data_opl['ppabgeschlossen']['list']
for key in ppangebot:
ppangebot[key].update(data_opl['firma']['list'][ppangebot[key]['firmaid']])
for key in range(0, len(ppaktuell)):
ppaktuell[key].update(data_opl['firma']['list'][ppaktuell[key]['firmaid']])
ppaktuell.sort(key=lambda x: x['anfangsdatum'])
for key in range(0, len(ppabgeschlossen)):
ppabgeschlossen[key].update(data_opl['firma']['list'][ppabgeschlossen[key]['firmaid']])
ppabgeschlossen.sort(key=lambda x: x['anfangsdatum'])
template_o = template.Template(self.readTemplate_p('auswertungFirma.tpl'))
return template_o.render(ppangebot_o = ppangebot, ppaktuell_o = ppaktuell, ppabgeschlossen_o = ppabgeschlossen)
# -------------------------------------------------------
def createAuswertungStudent_px(self, data_opl):
# -------------------------------------------------------
ppaktuell = data_opl['ppaktuell']['list']
ppabgeschlossen = data_opl['ppabgeschlossen']['list']
for key in range(0, len(ppaktuell)):
ppaktuell[key].update(data_opl['student']['list'][ppaktuell[key]['matrikelid']])
ppaktuell.sort(key=lambda x: x['vorname'])
for key in range(0, len(ppabgeschlossen)):
ppabgeschlossen[key].update(data_opl['student']['list'][ppabgeschlossen[key]['matrikelid']])
ppabgeschlossen.sort(key=lambda x: x['vorname'])
template_o = template.Template(self.readTemplate_p('auswertungStudent.tpl'))
return template_o.render(ppaktuell_o = ppaktuell, ppabgeschlossen_o = ppabgeschlossen)
# -------------------------------------------------------
def createAuswertungLehrer_px(self, data_opl):
# -------------------------------------------------------
ppaktuell = data_opl['ppaktuell']['list']
ppabgeschlossen = data_opl['ppabgeschlossen']['list']
for key in range(0, len(ppaktuell)):
ppaktuell[key].update(data_opl['lehrer']['list'][ppaktuell[key]['lehrendenid']])
ppaktuell.sort(key=lambda x: x['vorname'])
for key in range(0, len(ppabgeschlossen)):
ppabgeschlossen[key].update(data_opl['lehrer']['list'][ppabgeschlossen[key]['lehrendenid']])
ppabgeschlossen.sort(key=lambda x: x['vorname'])
template_o = template.Template(self.readTemplate_p('auswertungLehrer.tpl'))
return template_o.render(ppaktuell_o = ppaktuell, ppabgeschlossen_o = ppabgeschlossen)
# -------------------------------------------------------
def createStudentForm_px(self, id_spl, data_opl):
# -------------------------------------------------------
# hier m�sste noch eine Fehlerbehandlung erg�nzt werden !
template_o = template.Template(self.readTemplate_p('studentform.tpl'))
return template_o.render(data_o=data_opl, key_s = id_spl)
# -------------------------------------------------------
def createLehrerForm_px(self, id_spl, data_opl):
# -------------------------------------------------------
# hier m�sste noch eine Fehlerbehandlung erg�nzt werden !
template_o = template.Template(self.readTemplate_p('lehrerform.tpl'))
return template_o.render(data_o=data_opl, key_s = id_spl)
# -------------------------------------------------------
def createFirmenForm_px(self, id_spl, data_opl):
# -------------------------------------------------------
# hier m�sste noch eine Fehlerbehandlung erg�nzt werden !
template_o = template.Template(self.readTemplate_p('firmaform.tpl'))
return template_o.render(data_o=data_opl, key_s = id_spl)
# -------------------------------------------------------
def createPPAForm_px(self, id_spl, data_opl, alert = ''):
# -------------------------------------------------------
# hier m�sste noch eine Fehlerbehandlung erg�nzt werden !
template_o = template.Template(self.readTemplate_p('ppaform.tpl'))
return template_o.render(data_o=data_opl, key_s = id_spl, alert = alert)
# -------------------------------------------------------
def createPPAuswahlForm_px(self, id_spl, data_opl, alert_s):
# -------------------------------------------------------
template_o = template.Template(self.readTemplate_p('ppauswahlform.tpl'))
return template_o.render(data_o=data_opl, key_s = id_spl, alert = alert_s)
# -------------------------------------------------------
def readFile_p(self, fileName_spl):
# -------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('static', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# -------------------------------------------------------
def readTemplate_p(self, fileName_spl):
# -------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('templates', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF
<file_sep>/WEB/Klausurvorbereitung/WEB/Unterlagen/3/book.js
function book_cl (title_spl, publisher_spl) { // constructor-function (CF)
this.title = title_spl;
this.publisher = publisher_spl;
}
console.log("- 01 - ", "prototype" in book_cl); // in: wertet prototype-chain aus
console.log("- 02 - ", "constructor" in book_cl);
console.log("- 03 - ", book_cl.hasOwnProperty("prototype")); // hasOwnProperty: untersucht nur das
console.log("- 04 - ", book_cl.hasOwnProperty("constructor")); // einzelne Objekt
book_cl.prototype.toString = function() {
return this.title + " / " + this.publisher;
}
function DoIt() {
var book = { // Objekt-Initialisierer, d.h.
title: "Titel", // es wird intern nur new Object ausgeführt
publisher: "MySelf" // und nicht die CF "book_cl" !
};
console.log("- 05 - ", book.toString());
console.log("- 06 - ", book.hasOwnProperty("publisher"));
console.log("- 07 - ", book.hasOwnProperty("toString"));
console.log("- 08 - ", book.hasOwnProperty("__proto__"));
console.log("- 09 - ", book.hasOwnProperty("prototype"));
console.log("- 09 - ", "publisher" in book);
console.log("- 10 - ", "toString" in book);
console.log("- 11 - ", "__proto__" in book);
console.log("- 12 - ", "mit Konstruktor-Funktion");
book = new book_cl("t", "p");
console.log("- 13 - ", book.toString());
console.log("- 14 - ", book.hasOwnProperty("prototype"));
console.log("- 15 - ", "prototype" in book);
console.log("- 16 - ", "prototype" in book_cl);
// Erweiterungen der vordefinierten (built-in) Javascript-Objekte
Function.prototype.test = function () { console.log("- 17 - ", "Function-test"); }
Object.prototype.otest = function () { console.log("- 18 - ", "Object-test"); }
book_cl.test();
book_cl.prototype.otest();
book_cl.prototype.constructor.test();
book.__proto__.constructor.test();
try {
book.test(); // klappt nicht! Warum? Machen Sie sich den Unterschied
// zwischen book_cl und book klar!
}
catch(e) {
console.log("- 19 - ", "klappt nicht!");
}
book.otest();
book_cl.prototype.test = function () { console.log("- 20 - ", "book_cl.prototype.test!"); }
book_cl.test();
book.test(); // Jetzt geht's! Warum? Was wird angezeigt?
}
DoIt();<file_sep>/WEB/p2_save/mhb/content/mhb_lv.js
var selected;
function get_tabellenzeile(event_opl){
if(event_opl.target.tagName.toLowerCase()=='td')
{
if (selected != undefined){
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "left";
}
selected = event_opl.target.parentNode.id;
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "center";
}// Klick auf Link zum Löschen
}
function delete_eintrag_lv() {
if (confirm("Wollen Sie diesen Eintrag wirklich löschen? " + selected.toString())){
document.location.href = "/delete_lv/" + selected.toString();
}
}
function edit_eintrag_lv() {
if (confirm("Wollen Sie diesen Eintrag wirklich bearbeiten? " + selected.toString())){
document.location.href = "/edit_lv/" + selected.toString();
}
}
window.onload=function(){
let list_lv_o = document.getElementById('idList_lv');
let button_create = document.getElementById('erfassen_lv');
let button_o = document.getElementById('deleter_lv');
let button_edit = document.getElementById('edit_lv');
list_lv_o.addEventListener('click',get_tabellenzeile,false);
button_o.addEventListener('click', delete_eintrag_lv, false);
button_edit.addEventListener('click', edit_eintrag_lv, false);
}
<file_sep>/WEB/p4/app/application.py
# coding: utf-8
# Demonstrator / keine Fehlerbehandlung
import cherrypy
import json
import os
import os.path
import codecs
import time
from .database import Database_cl
from .view import View_cl
# Method-Dispatching!
# Übersicht Anforderungen / Methoden
"""
Anforderung GET POST PUT DELETE
------------------------------------------------------------------------------
/ Liste neue /
liefern Daten / /
eintragen /
/{id} Detail bestehenden datensatz mit
mit {id} / Datensatz id loeschen
liefern bearbeiten/
ergaenzen
"""
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
exposed = True # gilt für alle Methoden
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung können hier eingetragen werden
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self, *args):
#-------------------------------------------------------
print(args[0])
if args[0] == "topics":
return self.getTopics(*args)
elif args[0] == "tags":
return self.getTags(*args)
elif args[0] == "favorites":
return self.getFavorites(*args)
elif args[0] == "missing":
return self.getMissing(*args)
elif args[0] == "orphans":
return self.getOrphans(*args)
else:
return ''
#-------------------------------------------------------
def getTopics(self, *args):
#-------------------------------------------------------
# /topics/ daten aller themen als liste ausliefern
# /topics/id daten eines themas anhand id liefern
retVal_s = ''
if len(args)==1:
retVal_s = self.getList_p()
else:
id = args[1]
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def getMissing(self, *args):
#-------------------------------------------------------
retVal_s = ''
if len(args)==1:
retVal_s = self.getMissingList_p()
else:
id = args[1]
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def getFavorites(self, *args):
#-------------------------------------------------------
retVal_s = ''
if len(args)==1:
retVal_s = self.getFavoritesList_p()
else:
id = args[1]
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def getOrphans(self, *args):
#-------------------------------------------------------
retVal_s = ''
if len(args)==1:
retVal_s = self.getOrphansList_p()
else:
id = args[1]
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def getTags(self, *args):
#-------------------------------------------------------
# /tags/ daten aller kategorien als liste ausliefern
# /tags/id daten eines kategorien anhand id liefern
retVal_s = ''
if len(args)==1:
retVal_s = self.getListTags_p()
else:
id = args[1]
retVal_s = self.getDetailTags_p(id)
return retVal_s
#-------------------------------------------------------
def POST(self, *args, **kwargs):
#-------------------------------------------------------
if args[0] == "topics":
return self.postTopics(*args, **kwargs)
else:
return ''
#-------------------------------------------------------
def postTopics(self, *args, **kwargs):
#-------------------------------------------------------
#print current date and time
print(time.strftime("%d.%m.%Y %H:%M:%S"))
print(kwargs)
print("args bei post", args)
data_tmp = self.db_o.data_o
if args[0] == None:
daten = {
"id": None,
#"id": kwargs["Bezeichnung"],
"Bezeichnung": args[1],
"Datum_Erstellung": time.strftime("%d.%m.%Y %H:%M:%S"),
"Datum_Aenderung" : time.strftime("%d.%m.%Y %H:%M:%S"),
"Titel": "Titel ist noch anzugeben",
"Text": "Text ist noch anzugeben",
"Kategorien": "Kategorien sind noch anzugeben"
}
else:
daten = {
"id": None,
#"id": kwargs["Bezeichnung"],
"Bezeichnung": kwargs["Bezeichnung"],
"Datum_Erstellung": time.strftime("%d.%m.%Y %H:%M:%S"),
"Datum_Aenderung" : time.strftime("%d.%m.%Y %H:%M:%S"),
"Titel": "Titel ist noch anzugeben",
"Text": "Text ist noch anzugeben",
"Kategorien": "Kategorien sind noch anzugeben"
}
#Erstellung einer ID die bei jedem Post hochgezählt wird
# Create-Operation
#id_s = self.db_o.create_px(data_o)
self.db_o.getNewID_p()
id_s = str(self.db_o.dataID_o)
daten["id"] = id_s
print(daten)
data_tmp.append(daten)
self.db_o.saveData_p()
self.db_o.readData_p()
return ''
#-------------------------------------------------------
def PUT(self, *args, **kwargs):
#-------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
print("ARGS: ", args)
print("kwargs: ", kwargs)
if args[1] == None:
return ''
else:
data_tmp = self.db_o.data_o
#print(data_tmp)
daten = {
"id": args[1],
"Bezeichnung": kwargs["Bezeichnung"],
"Datum_Erstellung": kwargs["Datum_Erstellung"],
"Datum_Aenderung" : time.strftime("%d.%m.%Y %H:%M:%S"),
"Titel": kwargs["Titel"],
"Text": kwargs["Text"],
"Kategorien": kwargs["Kategorien"]
}
#print(daten)
index = 0
for data in data_tmp:
#print("INDEX: ", index)
print("DATA: ", data)
if data['id'] == args[1]:
data_tmp[index] = daten
index = index + 1
self.db_o.saveData_p()
self.db_o.readData_p()
return '{}'
#-------------------------------------------------------
def DELETE(self, *args, **kwargs):
#-------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
if args[0] == "topics":
id = args[1]
count = 0
data_tmp = self.db_o.data_o
for data in data_tmp:
if data['id'] == id:
data_tmp.pop(count)
count = count + 1
self.db_o.saveData_p()
self.db_o.readData_p()
#-------------------------------------------------------
def getList_p(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
# default-Werte entfernen
# ndata_a = data_a[1:]
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getFavoritesList_p(self):
#-------------------------------------------------------
data_a = self.db_o.readFavorites_px()
# default-Werte entfernen
# ndata_a = data_a[1:]
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getMissingList_p(self):
#-------------------------------------------------------
data_a = self.db_o.readMissing_px()
# default-Werte entfernen
# ndata_a = data_a[1:]
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getOrphansList_p(self):
#-------------------------------------------------------
data_a = self.db_o.readOrphans_px()
# default-Werte entfernen
# ndata_a = data_a[1:]
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getDetail_p(self, id_spl):
#-------------------------------------------------------
data_o = self.db_o.read_px(id_spl)
if (data_o == None) and (id_spl != "null"):
self.postTopics(None, id_spl)
data_o = self.db_o.read_px(id_spl)
return self.view_o.createDetail_px(data_o)
#-------------------------------------------------------
def getListTags_p(self):
#-------------------------------------------------------
data_a = self.db_o.readTags_px()
# default-Werte entfernen
# ndata_a = data_a[1:]
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getDetailTags_p(self, id_spl):
#-------------------------------------------------------
data_o = self.db_o.readTags_px(id_spl)
return self.view_o.createDetail_px(data_o)
# EOF<file_sep>/Mattes/3/app/view_a.py
# coding: utf-8
# sehr einfache Erzeugung des Markups f�r vollst�ndige Seiten
# jeweils 3 Abschnitte:
# - begin
# - content
# - end
# bei der Liste wird der content-Abschnitt wiederholt
# beim Formular nicht
import codecs
import os.path
import string
from mako import template
from mako.lookup import TemplateLookup
# ----------------------------------------------------------
class View_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.ListTemplate_o = ''
with codecs.open(os.path.join('template', 'list_template.tpl'), 'r', 'utf-8') as fp_o:
self.ListTemplate_o = fp_o.read()
pass
#-------------------------------------------------------
def CreateIndexMarkup(self):
#-------------------------------------------------------
return self.readFile_p('hauptseite.html')
#-------------------------------------------------------
def CreateList_px(self, data_o, option):
#-------------------------------------------------------
template = template.Template(self.ListTemplate)
markup = ""
#Studentenliste
if option == 0:
markup = template.render(data_o = data_o['student']['list'], option = option)
#Lehrendenliste
elif option == 1:
markup = template.render(data_o = data_o['student']['lehrende']
, option = option)
#Firmaliste
elif option == 2:
markup = template.render(data_o = data_o['student']['firma']
, option = option)
#PPAngebotListe
elif option == 3:
markup = template.render(data_o = data_o['student']['ppangebot']
, option = option)
#Auswertung Firma
elif option == 4:
markup = template.render(data_o = data_o['student']['list']
, option = option)
#Auswertung Student
elif option == 5:
markup = template.render(data_o = data_o['student']['list']
, option = option)
#Auswertung Lehrenden
elif option == 6:
markup = template.render(data_o = data_o['student']['list']
, option = option)
return markup
# -------------------------------------------------------
def readFile_p(self, fileName_spl):
# -------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('static', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/layout.tpl.py
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1515077945.9251614
_enable_loop = True
_template_filename = '/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/layout.tpl'
_template_uri = 'layout.tpl'
_source_encoding = 'utf-8'
_exports = ['header']
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
def header():
return render_header(context._locals(__M_locals))
__M_writer = context.writer()
__M_writer('<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <link href="/mhb.css" rel="stylesheet">\r\n</head>\r\n<body>\r\n\t<div class="topnav">\r\n\t\tWebanwendung "Modulhandbuch (mhb)"\r\n\t\t<br>\r\n\t</div>\r\n\t<div class="content">\r\n\t\t')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'header'):
context['self'].header(**pageargs)
__M_writer('\r\n\t</div>\r\n</body>\r\n<script src="ajax.js"></script>\r\n</html>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_header(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
def header():
return render_header(context)
__M_writer = context.writer()
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"source_encoding": "utf-8", "line_map": {"16": 0, "34": 13, "28": 13, "45": 34, "23": 2}, "filename": "/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/layout.tpl", "uri": "layout.tpl"}
__M_END_METADATA
"""
<file_sep>/WEB/p2_sicherung6/mhb/content/mhb.js
var selected;
function get_tabellenzeile(event_opl){
if(event_opl.target.tagName.toLowerCase()=='td')
{
if (selected != undefined){
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "left";
}
selected = event_opl.target.parentNode.id;
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "center";
}// Klick auf Link zum Löschen
}
function delete_eintrag_studiengang() {
if (confirm("Wollen Sie diesen Eintrag wirklich löschen? " + selected.toString())){
document.location.href = "/delete_sg/" + selected.toString();
}
}
function edit_eintrag_studiengang() {
if (confirm("Wollen Sie diesen Eintrag wirklich bearbeiten? " + selected.toString())){
document.location.href = "/edit_sg/" + selected.toString();
}
}
function open_modulhandbuch() {
document.location.href = "/modulhandbuch/" + selected.toString();
}
window.onload=function(){
let list_s_o = document.getElementById('idList_s');
let list_m_o = document.getElementById('idList_m');
let button_o = document.getElementById('deleter_studiengang');
let button_edit = document.getElementById('edit_studiengang');
let button_edit_m = document.getElementById('edit_modul');
let button_modulhandbuch = document.getElementById('modulhandbuch');
list_s_o.addEventListener('click',get_tabellenzeile,false);
list_m_o.addEventListener('click',get_tabellenzeile,false);
button_o.addEventListener('click', delete_eintrag_studiengang, false);
button_edit.addEventListener('click', edit_eintrag_studiengang, false);
button_edit_m.addEventListener('click', edit_eintrag_modul, false);
button_modulhandbuch.addEventListener('click', open_modulhandbuch, false);
button_open_lehrveranstaltungen.addEventListener('click', open_lehrveranstaltungen, false);
}
<file_sep>/Mattes/lit-x/app/application.py
# coding: utf-8
import json
import cherrypy
from .database import SourceDatabase_cl, EvaluatedDatabase_cl
# Method-Dispatching!
# Übersicht Anforderungen / Methoden
"""
Anforderung GET POST PUT DELETE
----------------------------------------------------------------
/ Liste - - -
Literatur
liefern
/source Liste - - -
Literatur
liefern
/evaluated Liste - - -
Auswertungen
liefern
/source/0 Dokument Dokument - -
mit id=0 anlegen
liefern
(Vorgabe-Werte)
/evaluated/0 Dokument Dokument - -
mit id=0 anlegen
liefern
(Vorgabe-Werte)
/source/{id} Dokument - Dokument Dokument
mit {id} ändern löschen
liefern
(Literatur)
/evaluated/{id} Dokument - Dokument Dokument
mit {id} ändern löschen
liefern
(Auswertungen)
id > 0 !
"""
#-------------------------------------------------------
def adjustId_p(id_spl, data_opl):
#-------------------------------------------------------
if id_spl == None:
data_opl['id'] = ''
elif id_spl == '':
data_opl['id'] = ''
elif id_spl == '0':
data_opl['id'] = ''
else:
data_opl['id'] = id_spl
return data_opl
#----------------------------------------------------------
class Source_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = SourceDatabase_cl()
#-------------------------------------------------------
def GET(self, id):
#-------------------------------------------------------
retVal_o = {
'data': None
}
if id == None:
# Anforderung der Liste
retVal_o['data'] = self.db_o.read_px()
else:
# Anforderung eines Dokuments
data_o = self.db_o.read_px(id)
if data_o != None:
retVal_o['data'] = adjustId_p(id, data_o)
return retVal_o
#-------------------------------------------------------
def POST(self, data_opl):
#-------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
data_o = {
'name': data_opl["name_s"],
'typ': data_opl["typ_s"],
'referenz': data_opl["referenz_s"]
}
# Create-Operation
id_s = self.db_o.create_px(data_o)
retVal_o['id'] = id_s
return retVal_o
#-------------------------------------------------------
def PUT(self, data_opl):
#-------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
id_s = data_opl["id_s"]
data_o = {
'name': data_opl["name_s"],
'typ': data_opl["typ_s"],
'referenz': data_opl["referenz_s"]
}
# Update-Operation
retVal_o['id'] = id_s
if self.db_o.update_px(id_s, data_o):
pass
else:
retVal_o['id'] = None
return retVal_o
#-------------------------------------------------------
def DELETE(self, id):
#-------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if self.db_o.delete_px(id):
pass
else:
retVal_o['id'] = None
return retVal_o
#----------------------------------------------------------
class Evaluated_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = EvaluatedDatabase_cl()
#-------------------------------------------------------
def GET(self, id):
#-------------------------------------------------------
retVal_o = {
'data': None
}
if id == None:
# Anforderung der Liste
retVal_o['data'] = self.db_o.read_px()
else:
# Anforderung eines Dokuments
data_o = self.db_o.read_px(id)
if data_o != None:
retVal_o['data'] = adjustId_p(id, data_o)
return retVal_o
#-------------------------------------------------------
def POST(self, data_opl):
#-------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
data_o = {
'title': data_opl["title_s"],
'author': data_opl["author_s"],
'evalyear': data_opl["evalyear_s"]
}
# Create-Operation
id_s = self.db_o.create_px(data_o)
retVal_o['id'] = id_s
return retVal_o
#-------------------------------------------------------
def PUT(self, data_opl):
#-------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
id_s = data_opl["id_s"]
data_o = {
'title': data_opl["title_s"],
'author': data_opl["author_s"],
'evalyear': data_opl["evalyear_s"]
}
# Update-Operation
retVal_o['id'] = id_s
if self.db_o.update_px(id_s, data_o):
pass
else:
retVal_o['id'] = None
return retVal_o
#-------------------------------------------------------
def DELETE(self, id):
#-------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if self.db_o.delete_px(id):
pass
else:
retVal_o['id'] = None
return retVal_o
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
exposed = True # gilt für alle Methoden
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.handler_o = {
'source': Source_cl(),
'evaluated': Evaluated_cl()
}
# es wird keine index-Methode vorgesehen, weil stattdessen
# die Webseite index.html ausgeliefert wird (siehe Konfiguration)
#-------------------------------------------------------
def GET(self, path_spl = 'source', id=None):
#-------------------------------------------------------
retVal_o = {
'data': None
}
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].GET(id)
if retVal_o['data'] == None:
cherrypy.response.status = 404
return json.dumps(retVal_o)
#-------------------------------------------------------
def POST(self, path_spl = 'source', **data_opl):
#-------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].POST(data_opl)
if retVal_o['id'] == None:
cherrypy.response.status = 409
return json.dumps(retVal_o)
#-------------------------------------------------------
def PUT(self, path_spl = 'source', **data_opl):
#-------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].PUT(data_opl)
if retVal_o['id'] == None:
cherrypy.response.status = 404
return json.dumps(retVal_o)
#-------------------------------------------------------
def DELETE(self, path_spl = 'source', id=None):
#-------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].DELETE(id)
if retVal_o['id'] == None:
cherrypy.response.status = 404
return json.dumps(retVal_o)
#-------------------------------------------------------
def default(self, *arguments, **kwargs):
#-------------------------------------------------------
msg_s = "unbekannte Anforderung: " + \
str(arguments) + \
' ' + \
str(kwargs)
raise cherrypy.HTTPError(404, msg_s)
# EOF<file_sep>/WEB/WEB Praktika/demonstrator/static/main_c6.js
//------------------------------------------------------------------------------
//Demonstrator es/te/tm - Variante mit ES6-Classes
//------------------------------------------------------------------------------
// hier zur Vereinfachung (!) die Klassen in einer Datei
'use strict'
class DetailView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/" + id_spl;
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
this.configHandleEvent_p();
}
}
configHandleEvent_p () {
let el_o = document.querySelector("form");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.id == "idBack") {
APPETT.es_o.publish_px("app.cmd", ["idBack", null]);
event_opl.preventDefault();
}
}
}
class ListView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "idShowListEntry") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["detail", elx_o.id] );
}
event_opl.preventDefault();
}
}
}
class SideBar_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
let cmd_s = event_opl.target.dataset.action;
APPETT.es_o.publish_px("app.cmd", [cmd_s, null]);
}
}
class Application_cl {
constructor () {
// Registrieren zum Empfang von Nachrichten
APPETT.es_o.subscribe_px(this, "templates.loaded");
APPETT.es_o.subscribe_px(this, "templates.failed");
APPETT.es_o.subscribe_px(this, "app.cmd");
this.sideBar_o = new SideBar_cl("aside", "sidebar.tpl.html");
this.listView_o = new ListView_cl("main", "list.tpl.html");
this.detailView_o = new DetailView_cl("main", "detail.tpl.html");
}
notify_px (self, message_spl, data_opl) {
switch (message_spl) {
case "templates.failed":
alert("Vorlagen konnten nicht geladen werden.");
break;
case "templates.loaded":
// Templates stehen zur Verfügung, Bereiche mit Inhalten füllen
// hier zur Vereinfachung direkt
let markup_s;
let el_o;
markup_s = APPETT.tm_o.execute_px("header.tpl.html", null);
el_o = document.querySelector("header");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
markup_s = APPETT.tm_o.execute_px("footer.tpl.html", null);
el_o = document.querySelector("footer");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
let nav_a = [
["home", "Startseite"],
["list", "Liste"]
];
self.sideBar_o.render_px(nav_a);
markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
el_o = document.querySelector("main");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
break;
case "app.cmd":
// hier müsste man überprüfen, ob der Inhalt gewechselt werden darf
switch (data_opl[0]) {
case "home":
let markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
let el_o = document.querySelector("main");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
break;
case "list":
// Daten anfordern und darstellen
this.listView_o.render_px();
break;
case "detail":
this.detailView_o.render_px(data_opl[1]);
break;
case "idBack":
APPETT.es_o.publish_px("app.cmd", ["list", null]);
break;
}
break;
}
}
}
window.onload = function () {
APPETT.xhr_o = new APPETT.XHR_cl();
APPETT.es_o = new APPETT.EventService_cl();
var app_o = new Application_cl();
APPETT.tm_o = new APPETT.TemplateManager_cl();
}<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/ajax.js
function loadDocLogin() {
var xhttp = new XMLHttpRequest();
var username = document.getElementById("username").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("login").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/login/?username=" + username, true);
xhttp.send();
}
function loadDocLoginL() {
var xhttp = new XMLHttpRequest();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("loginL").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/loginL/?username=" + username + "&password=" + password, true);
xhttp.send();
}
function loadDoccreateStudiengang() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("formVerantwortlicherStudiengang").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/createStudiengang", true);
xhttp.send();
}
function loadDocstudiengangEdit() {
var get = document.getElementById("studiengang");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie einen Studiengang an");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("formVerantwortlicherStudiengang").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/editStudiengang" + selected.toString(), true);
xhttp.send();
}
<file_sep>/WEB/Vorlesung/javascript_beispiele/proto2.js
var object0_o = Object.create(Object.prototype);
var object1_o = Object.create(object0_o);
object1_o.name_s = "Mustermann1";
var object2_o = Object.create(object1_o);
object2_o.name_s = "Mustermann2";
object2_o.vorname_s = "Max";
function showName_p (object_opl) {
var result_s = "Ergebnis:";
if (object_opl.name_s != undefined) {
result_s += " " + object_opl.name_s;
}
if (object_opl.vorname_s != undefined) {
result_s += " " + object_opl.vorname_s;
}
return result_s;
}
console.log(showName_p(object0_o));
console.log(showName_p(object1_o));
console.log(showName_p(object2_o));
console.log(object0_o.toString());
console.log(object1_o.toString());
console.log(object2_o.toString());
object0_o.tofuck = function () {
return showName_p(this);
}
console.log(object0_o.tofuck());
console.log(object1_o.tofuck());
console.log(object2_o.tofuck());
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/loginStudierende.tpl.py
# -*- coding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1515082762.6377637
_enable_loop = True
_template_filename = '/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/loginStudierende.tpl'
_template_uri = 'loginStudierende.tpl'
_source_encoding = 'ascii'
_exports = ['header']
def _mako_get_namespace(context, name):
try:
return context.namespaces[(__name__, name)]
except KeyError:
_mako_generate_namespaces(context)
return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
pass
def _mako_inherit(template, context):
_mako_generate_namespaces(context)
return runtime._inherit_from(context, 'layout.tpl', _template_uri)
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
def header():
return render_header(context._locals(__M_locals))
__M_writer = context.writer()
__M_writer('\r\n')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'header'):
context['self'].header(**pageargs)
__M_writer('\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_header(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
def header():
return render_header(context)
__M_writer = context.writer()
__M_writer('\r\n\t<body>\r\n\t\t<div id="login">\r\n\t\t\t<form id="formlogin" action="" method="POST">\r\n\t\t\t\t<input type="text" id="username" name="username" value="" required />\r\n\t\t\t\t<button onclick="loadDocLogin()">Login</button>\r\n\t\t\t</form>\r\n\t\t</div>\r\n\t</body>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"line_map": {"34": 1, "51": 2, "39": 11, "57": 51, "27": 0, "45": 2}, "source_encoding": "ascii", "uri": "loginStudierende.tpl", "filename": "/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/loginStudierende.tpl"}
__M_END_METADATA
"""
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/content/mhb_student.js
var e = document.getElementById("studiengang");
var strUser = e.options[e.selectedIndex].value;
function studiengangAnzeige() {
document.location.href = "/studiengang/" + strUser.toString();
}
window.onload=function(){
let e = document.getElementById('studiengang');
e.addEventListener('click', studiengangAnzeige, false);
}<file_sep>/Mattes/4/app/auswertung.py
import json
import cherrypy
from .database import fehlerDatabase_cl, katursacheDatabase_cl, katfehlerDatabase_cl, projektDatabase_cl, komponenteDatabase_cl
# -------------------------------------------------------
def adjustId_p(id_spl, data_opl):
# -------------------------------------------------------
if id_spl == None:
data_opl['id'] = ''
elif id_spl == '':
data_opl['id'] = ''
elif id_spl == '0':
data_opl['id'] = ''
else:
data_opl['id'] = id_spl
return data_opl
# ----------------------------------------------------------
class ProList_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.db_o = fehlerDatabase_cl()
# -------------------------------------------------------
def GET(self, id):
# -------------------------------------------------------
retVal_o = {
'data': None,
'projekte': None,
'komponente': None
}
self.db_o.readData_p()
retVal_o['data'] = self.db_o.read_px()
db_opl = komponenteDatabase_cl()
db_opl.readData_p()
retVal_o['komponente'] = db_opl.read_px()
db_opl = projektDatabase_cl()
db_opl.readData_p()
retVal_o['projekte'] = db_opl.read_px()
return retVal_o
# -------------------------------------------------------
def POST(self, data_opl):
# -------------------------------------------------------
retVal_o = {
'id': None
}
return retVal_o
# -------------------------------------------------------
def PUT(self, data_opl):
retVal_o = {
'id': None
}
return retVal_o
# -------------------------------------------------------
def DELETE(self, id):
retVal_o = {
'id': None
}
return retVal_o
class KatList_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.db_o = fehlerDatabase_cl()
# -------------------------------------------------------
def GET(self, id):
# -------------------------------------------------------
retVal_o = {
'data': None,
'katfehler': None,
'katursache': None
}
self.db_o.readData_p()
retVal_o['data'] = self.db_o.read_px()
db_opl = katfehlerDatabase_cl()
db_opl.readData_p()
retVal_o['katfehler'] = db_opl.read_px()
db_opl = katursacheDatabase_cl()
db_opl.readData_p()
retVal_o['katursache'] = db_opl.read_px()
return retVal_o
# -------------------------------------------------------
def POST(self, data_opl):
# -------------------------------------------------------
retVal_o = {
'id': None
}
return retVal_o
# -------------------------------------------------------
def PUT(self, data_opl):
retVal_o = {
'id': None
}
return retVal_o
# -------------------------------------------------------
def DELETE(self, id):
retVal_o = {
'id': None
}
return retVal_o<file_sep>/Mattes/3/app/view.py
# coding: utf-8
import codecs
import os.path
import string
from mako import template
from mako.lookup import TemplateLookup
# ----------------------------------------------------------
class View_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.view = ['student'
,'lehrende'
,'firma'
,'ppangebot'
,'ppaktuell'
,'ppabgeschlossen']
pass
#-------------------------------------------------------
def CreateIndex_px(self):
#-------------------------------------------------------
return self.readFile_p('hauptseite.html')
#-------------------------------------------------------
def CreateList_px(self, data_o, ansicht):
#-------------------------------------------------------
ListTemplate = ''
with codecs.open(os.path.join('templates', 'list_template.tpl'), 'r', 'utf-8') as fp_o:
ListTemplate = fp_o.read()
template_o = template.Template(ListTemplate)
markup = ""
markup = template_o.render(data_o = data_o, ansicht = ansicht)
return markup
#-------------------------------------------------------
def CreateForm_px(self, data_o, option, ansicht, id_s):
#-------------------------------------------------------
FormTemplate = ''
with codecs.open(os.path.join('templates', 'form_template.tpl'), 'r', 'utf-8') as fp_o:
FormTemplate = fp_o.read()
template_o = template.Template(FormTemplate)
markup = template_o.render(data_o = data_o, option = option, ansicht = ansicht, id_s = id_s)
return markup
# -------------------------------------------------------
def readFile_p(self, fileName_spl):
# -------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('static', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF
<file_sep>/Mattes/2/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
import datetime
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
# da es hier nur darum geht, die Daten dauerhaft zu speichern,
# wird ein sehr einfacher Ansatz verwendet:
# - es k�nnen Daten zu genau 15 Teams gespeichert werden
# - je Team werden 2 Teilnehmer mit Namen, Vornamen und Matrikelnummer
# ber�cksichtigt
# - die Daten werden als eine JSON-Datei abgelegt
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.data_o = None
#-------------------------------------------------------
def savePPaktuell_px(self, **data_opl):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr�ge liefern
id = None
for key in self.data_o['student']['list']:
if self.data_o['student']['list'][key]['matrikelnr'] == int(data_opl['matrikelid']):
id = key
if id == None:
return -1
for key in range(0, len(self.data_o['ppaktuell']['list'])):
if(self.data_o['ppaktuell']['list'][key]['matrikelid'] == id):
return -2
anfangsdatum = data_opl['anfangsdatum'].split('.')
enddatum = data_opl['enddatum'].split('.')
data_a = {
"pptitel": data_opl['pptitel'],
"beschreibung": data_opl['beschreibung'],
"firmaid": data_opl['firmaid'],
"voraussetzung": data_opl['voraussetzung'],
"kontakt": data_opl['kontakt'],
"lehrendenid": data_opl['lehrendenid'],
"matrikelid": id,
"anfangsdatum": datetime.date(int(anfangsdatum[2]), int(anfangsdatum[1]), int(anfangsdatum[0])),
"enddatum": datetime.date(int(enddatum[2]),int(enddatum[1]),int(enddatum[0]))
}
self.data_o['ppaktuell']['list'].append(data_a)
del self.data_o['ppangebot']['list'][data_opl['id_s']]
self.saveData_p()
return 1
#-------------------------------------------------------
def readStudent_px(self, id_spl):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr�ge liefern
data_opl = None
if id_spl != None:
data_opl = self.data_o['student']['list'][id_spl]
return data_opl
#-------------------------------------------------------
def readLehrer_px(self, id_spl):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr�ge liefern
data_opl = None
if id_spl != None:
data_opl = self.data_o['lehrer']['list'][id_spl]
return data_opl
#-------------------------------------------------------
def readFirma_px(self, id_spl):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr�ge liefern
data_opl = None
if id_spl != None:
data_opl = self.data_o['firma']['list'][id_spl]
return data_opl
#-------------------------------------------------------
def readPPA_px(self, id_spl):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr�ge liefern
data_opl = None
if id_spl != None:
data_opl = self.data_o['ppangebot']['list'][id_spl]
return data_opl
#-------------------------------------------------------
def updateStudent_px(self, id_spl, data_opl):
#-------------------------------------------------------
self.data_o['student']['list'][id_spl] = data_opl
self.saveData_p()
return
#-------------------------------------------------------
def updateLehrer_px(self, id_spl, data_opl):
#-------------------------------------------------------
self.data_o['lehrer']['list'][id_spl] = data_opl
self.saveData_p()
return
#-------------------------------------------------------
def updateFirma_px(self, id_spl, data_opl):
#-------------------------------------------------------
self.data_o['firma']['list'][id_spl] = data_opl
self.saveData_p()
return
#-------------------------------------------------------
def updatePPA_px(self, id_spl, data_opl):
#-------------------------------------------------------
self.data_o['ppangebot']['list'][id_spl] = data_opl
self.saveData_p()
return
#-------------------------------------------------------
def createStudent_px(self, data_opl):
#-----------------------------------------------------
self.data_o['student']['list'].update({self.data_o['student']['count']: ''})
self.data_o['student']['list'][self.data_o['student']['count']] = data_opl
self.data_o['student']['count'] += 1
self.saveData_p();
return
#-------------------------------------------------------
def createLehrer_px(self, data_opl):
#-------------------------------------------------------
self.data_o['lehrer']['list'].update({self.data_o['lehrer']['count']: ''})
self.data_o['lehrer']['list'][self.data_o['lehrer']['count']] = data_opl
self.data_o['lehrer']['count'] += 1
self.saveData_p();
return
#-------------------------------------------------------
def createFirma_px(self, data_opl):
#-------------------------------------------------------
self.data_o['firma']['list'].update({self.data_o['firma']['count']: ''})
self.data_o['firma']['list'][self.data_o['firma']['count']] = data_opl
self.data_o['firma']['count'] += 1
self.saveData_p();
return
#-------------------------------------------------------
def createPPA_px(self, data_opl):
#-------------------------------------------------------
self.data_o['ppangebot']['list'].update({self.data_o['ppangebot']['count']: ''})
self.data_o['ppangebot']['list'][self.data_o['ppangebot']['count']] = data_opl
self.data_o['ppangebot']['count'] += 1
self.saveData_p();
return
#-------------------------------------------------------
def deleteStudent_px(self, id_spl):
#-------------------------------------------------------
del self.data_o['student']['list'][id_spl]
self.saveData_p()
return
#-------------------------------------------------------
def deleteLehrer_px(self, id_spl):
#-------------------------------------------------------
del self.data_o['lehrer']['list'][id_spl]
self.saveData_p()
return
#-------------------------------------------------------
def deleteFirma_px(self, id_spl):
#-------------------------------------------------------
del self.data_o['firma']['list'][id_spl]
self.saveData_p()
return
#-------------------------------------------------------
def deletePPA_px(self, id_spl):
#-------------------------------------------------------
del self.data_o['ppangebot']['list'][id_spl]
self.saveData_p()
return
#-------------------------------------------------------
def readData_p(self):
#-------------------------------------------------------
fp_o = codecs.open(os.path.join('data', 'ppm.json'), 'r', 'utf-8')
with fp_o:
self.data_o = json.load(fp_o)
for key in range(0, len(self.data_o['ppaktuell']['list'])):
anfangsdatum = self.data_o['ppaktuell']['list'][key]['anfangsdatum'].split('.')
self.data_o['ppaktuell']['list'][key]['anfangsdatum'] = datetime.date(int(anfangsdatum[2]), int(anfangsdatum[1]), int(anfangsdatum[0]))
enddatum = self.data_o['ppaktuell']['list'][key]['enddatum'].split('.')
self.data_o['ppaktuell']['list'][key]['enddatum'] = datetime.date(int(enddatum[2]),int(enddatum[1]),int(enddatum[0]))
for key in range(0, len(self.data_o['ppabgeschlossen']['list'])):
anfangsdatum = self.data_o['ppabgeschlossen']['list'][key]['anfangsdatum'].split('.')
self.data_o['ppabgeschlossen']['list'][key]['anfangsdatum'] = datetime.date(int(anfangsdatum[2]),int(anfangsdatum[1]),int(anfangsdatum[0]))
enddatum = self.data_o['ppabgeschlossen']['list'][key]['enddatum'].split('.')
self.data_o['ppabgeschlossen']['list'][key]['enddatum'] = datetime.date(int(enddatum[2]),int(enddatum[1]),int(enddatum[0]))
return self.data_o
#-------------------------------------------------------
def saveData_p(self):
#-------------------------------------------------------
for key in range(0, len(self.data_o['ppaktuell']['list'])):
self.data_o['ppaktuell']['list'][key]['anfangsdatum'] = self.data_o['ppaktuell']['list'][key]['anfangsdatum'].strftime('%d.%m.%Y')
self.data_o['ppaktuell']['list'][key]['enddatum'] = self.data_o['ppaktuell']['list'][key]['enddatum'].strftime('%d.%m.%Y')
for key in range(0, len(self.data_o['ppabgeschlossen']['list'])):
self.data_o['ppabgeschlossen']['list'][key]['anfangsdatum'] = self.data_o['ppabgeschlossen']['list'][key]['anfangsdatum'].strftime('%d.%m.%Y')
self.data_o['ppabgeschlossen']['list'][key]['enddatum'] = self.data_o['ppabgeschlossen']['list'][key]['enddatum'].strftime('%d.%m.%Y')
with codecs.open(os.path.join('data', 'ppm.json'), 'w', 'utf-8') as fp_o:
json.dump(self.data_o, fp_o)
# EOF<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/formModulhandbuch.tpl.py
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1513170036.3620503
_enable_loop = True
_template_filename = '/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formModulhandbuch.tpl'
_template_uri = 'formModulhandbuch.tpl'
_source_encoding = 'utf-8'
_exports = ['header']
def _mako_get_namespace(context, name):
try:
return context.namespaces[(__name__, name)]
except KeyError:
_mako_generate_namespaces(context)
return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
pass
def _mako_inherit(template, context):
_mako_generate_namespaces(context)
return runtime._inherit_from(context, 'layout.tpl', _template_uri)
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
id_s = context.get('id_s', UNDEFINED)
def header():
return render_header(context._locals(__M_locals))
data_mod = context.get('data_mod', UNDEFINED)
__M_writer = context.writer()
__M_writer('\r\n')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'header'):
context['self'].header(**pageargs)
__M_writer('\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_header(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
id_s = context.get('id_s', UNDEFINED)
def header():
return render_header(context)
data_mod = context.get('data_mod', UNDEFINED)
__M_writer = context.writer()
__M_writer('\r\n\t<body>\r\n\t\t<h1><u>Modulhandbuch zum Studiengang:</u> ')
__M_writer(str(id_s))
__M_writer('</h1>\r\n\t\t<div>\r\n')
for a in data_mod.values():
if a[8] == id_s:
__M_writer('\t\t\t\t\t<u>Bezeichnung des Moduls:</u> <p /> ')
__M_writer(str(a[0]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Beschreibung des Moduls:</u> <p /> ')
__M_writer(str(a[1]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Anzahl Kreditpunkte:</u> <p /> ')
__M_writer(str(a[2]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Anzahl Vorlesung:</u> <p /> ')
__M_writer(str(a[3]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Anzahl Übung:</u> <p /> ')
__M_writer(str(a[4]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Anzahl Praktikum:</u> <p /> ')
__M_writer(str(a[5]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Voraussetzungen:</u> <p /> ')
__M_writer(str(a[6]))
__M_writer(' <p />\r\n\t\t\t\t\t<u>Modulverantwortlicher</u> <p /> ')
__M_writer(str(a[7]))
__M_writer(' <p />\r\n')
__M_writer('\t\t</div>\r\n\t</body>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"uri": "formModulhandbuch.tpl", "source_encoding": "utf-8", "line_map": {"64": 10, "65": 11, "66": 11, "67": 12, "68": 12, "69": 13, "70": 13, "71": 14, "72": 14, "73": 15, "74": 15, "75": 16, "76": 16, "77": 19, "83": 77, "27": 0, "36": 2, "41": 21, "47": 3, "55": 3, "56": 5, "57": 5, "58": 7, "59": 8, "60": 9, "61": 9, "62": 9, "63": 10}, "filename": "/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formModulhandbuch.tpl"}
__M_END_METADATA
"""
<file_sep>/WEB/WEB Praktika/pl/app/application.py
# coding: utf-8
# Demonstrator / keine Fehlerbehandlung
import cherrypy
#neu
import json
import os
import os.path
import codecs
#ende neu
from .database import Database_cl
from .view import View_cl
# Method-Dispatching!
# Übersicht Anforderungen / Methoden
"""
Anforderung GET POST PUT DELETE
------------------------------------------------------------------------------
/ Liste neue /
liefern Daten / /
eintragen /
/{id} Detail bestehenden datensatz mit
mit {id} / Datensatz id loeschen
liefern bearbeiten/
ergaenzen
"""
@cherrypy.expose
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
exposed = True # gilt für alle Methoden
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung können hier eingetragen werden
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def DELETE(self, *args, **kwargs):
#-------------------------------------------------------
# /pensionaer/id daten eines pensionaers löschen
# /congratstmpl/id per path identifizierte vorlage löschen
if args[0] == "pensionaer":
id = args[1]
count = 0
d = None
data_tmp = self.db_o.pensionaere
for data in data_tmp:
if str(count) == id:
d = data_tmp.pop(count)
count = count + 1
self.db_o.saveData()
self.db_o.readData()
else:
if args[0] == "congratstempl":
self.VorlageLoeschen(*args, **kwargs)
#-------------------------------------------------------
def VorlageLoeschen(self, *args, **kwargs):
#print("in function VorlageLoeschen")
data_tmp = self.db_o.Congrats
id = args[1]
#print("ID: ", id)
count = 0
path = None
filepath = " "
for data in data_tmp:
if str(data_tmp[count]["ID"]) == str(id):
#print("VORLAGE LOESCHEN")
filepath = data_tmp[count]["Path"]
#path = os.path.join(cherrypy.Application.currentDir_s, "congratstempl", filepath)
#os.remove(path)
data_tmp.pop(count)
count = count + 1
self.db_o.saveCongrats()
self.db_o.readCongrats()
def PUT(self, *args, **kwargs):
#-------------------------------------------------------
# /pensionaer/id + daten daten eines pensionaers aktualisieren
print("ARGS: ", args)
if args[1] == None:
return ''
else:
data_tmp = self.db_o.pensionaere
#print(data_tmp)
daten = {
"id": args[1],
"Anrede":kwargs["Anrede"],
"Name": kwargs["Name"],
"Vorname":kwargs["Vorname"],
"Titel":kwargs["Titel"],
"Geburtsdatum":kwargs["Geburtsdatum"],
"Strasse":kwargs["Strasse"],
"Hausnummer":kwargs["Hausnummer"],
"Adresszusatz":kwargs["Adresszusatz"],
"Postleitzahl":kwargs["Postleitzahl"],
"Ort":kwargs["Ort"]
}
#print(daten)
index = 0
for data in data_tmp:
#print("INDEX: ", index)
#print("DATA: ", data)
if str(index) == args[1]:
#print("DATEN WERDEN EINGESPEICHERT")
data_tmp[index] = daten
#print("DATA[index]: ", data_tmp[index])
index = index + 1
self.db_o.saveData()
self.db_o.readData()
return '{}'
#-------------------------------------------------------
def POST(self, *args, **kwargs):
#-------------------------------------------------------
# /pensionaer/ daten daten eines neuen pensionaers speichern und ID liefern
# /congratstmpl/path + daten vorlage importieren/neue id liefern
# /annuallist/ jahresüberblick erzeugen
# /significantBirthdays/ + daten abfrage ausführen
# /congratulation/ + daten gratulationsschreiben erstellen
if args[0] == "pensionaer":
return self.postPensionaer(*args, **kwargs)
else:
if args[0] == "congratstempl":
return self.postCongratstempl(*args, **kwargs)
else:
if args[0] == "annuallist":
return self.postAnnuallist(*args, **kwargs)
else:
if args[0] == "significantbirthdays":
return self.postBirthdays(*args, **kwargs)
else:
if args[0] == "congratulation":
return self.postCongrats(*args, **kwargs)
def postCongratstempl(self, *args, **kwargs):
# /congratstmpl/path + daten vorlage importieren/neue id liefern
path = args[0]
filename = args[2]
beschreibung = kwargs["Beschreibung"]
print("PFAD: ", path)
print("ARGS: ", args)
print("KWARGS", kwargs)
self.db_o.readCongrats()
data_tmp = self.db_o.Congrats
retVal = {
"ID":"",
"Beschreibung":"",
"Path":""
}
count = 0
maxID = 0
for data in data_tmp:
if data_tmp[count]["ID"] > maxID:
maxID = data_tmp[count]["ID"] #finde höchste id
count = count + 1
maxID = int(maxID) + 1
retVal["ID"] = str(maxID)
retVal["Beschreibung"] = beschreibung
retVal["Path"] = filename
data_tmp.append(retVal)
self.db_o.saveCongrats()
self.db_o.readCongrats()
def postAnnuallist(self, *args, **kwargs):
# /annuallist/ jahresüberblick erzeugen
data_tmp = self.db_o.pensionaere
daten = [
{
"Name": "",
"Vorname":"",
"Geburtsdatum":"",
"Alter":""
}
]
tmp = None
count = 0
for data in data_tmp:
tmp = data_tmp[count]["Geburtsdatum"]
tmp = tmp[6:]
daten.append({})
daten[count]["Name"] = data_tmp[count]["Name"]
daten[count]["Vorname"] = data_tmp[count]["Vorname"]
daten[count]["Geburtsdatum"] = data_tmp[count]["Geburtsdatum"]
daten[count]["Alter"] = str(2017-int(tmp))
count = count + 1
return json.dumps(daten)
def postBirthdays(self, *args, **kwargs):
# /significantBirthdays/ + daten abfrage ausführen
uebergabeDatum = kwargs["Datum"]
uebergabeDauer = kwargs["Dauer"]
startmonat = int(uebergabeDatum[:2])
startjahr = int(uebergabeDatum[4:])
endmonat = int(uebergabeDauer)
print(startmonat, ".", startjahr, " - ", endmonat)
data_tmp = self.db_o.pensionaere
count = 0
daten = [
]
countSignificantBirthdays = 0
for data in data_tmp:
jahr = int(data_tmp[count]["Geburtsdatum"][6:])
monat = int(data_tmp[count]["Geburtsdatum"][3:5])
dateFound = 0
print(count, jahr, monat)
if monat <= endmonat and monat >= startmonat and dateFound == 0: #nur berechnen, falls geburtstagsmonat des pensionaers im angegebenen zeitraum liegt
#berechne ob geburtstag "SIGNIFIKANT" ist
for jahrIndex in range (0, 35, 5): #startjahr 5, bis 30, schritt: 5
if 2018-jahr == 70 + jahrIndex and dateFound == 0: # falls alter == 70, 75, 80, 85, 90, 95, 100
daten.append({})
daten[countSignificantBirthdays]['Name'] = data_tmp[count]["Name"]
daten[countSignificantBirthdays]['ID'] = data_tmp[count]["id"]
daten[countSignificantBirthdays]['Vorname'] = data_tmp[count]["Vorname"]
daten[countSignificantBirthdays]['Geburtstag'] = str(data_tmp[count]["Geburtsdatum"][:2] + "." + str(monat) + ".2018")
daten[countSignificantBirthdays]['Alter'] = str(70 + jahrIndex)
dateFound = 1
countSignificantBirthdays = countSignificantBirthdays + 1
count = count + 1
print(daten)
print(json.dumps(daten))
return json.dumps(daten)
#return json.dumps([{"ID":"1"}])
def postCongrats(self, *args, **kwargs):
# /congratulation/ + daten gratulationsschreiben erstellen
print(args, kwargs)
id = args[1]
retVal = [
{
"id": self.db_o.pensionaere[int(id)]["id"],
"Anrede":self.db_o.pensionaere[int(id)]["Anrede"],
"Name": self.db_o.pensionaere[int(id)]["Name"],
"Vorname":self.db_o.pensionaere[int(id)]["Vorname"],
"Titel":self.db_o.pensionaere[int(id)]["Titel"],
"Geburtsdatum":self.db_o.pensionaere[int(id)]["Geburtsdatum"],
"Strasse":self.db_o.pensionaere[int(id)]["Strasse"],
"Hausnummer":self.db_o.pensionaere[int(id)]["Hausnummer"],
"Adresszusatz":self.db_o.pensionaere[int(id)]["Adresszusatz"],
"Postleitzahl":self.db_o.pensionaere[int(id)]["Postleitzahl"],
"Ort":self.db_o.pensionaere[int(id)]["Ort"],
},
{
}
]
data_tmp = self.db_o.pensionaere
rentner = data_tmp[int(id)]
jahr = int(rentner["Geburtsdatum"][6:])
name = kwargs["vorlage"]
path = os.path.join(cherrypy.Application.currentDir_s, 'congratstempl', name)
datei = open(path, "r")
content = datei.read()
retVal[1] = content
print(json.dumps(retVal))
datei.close()
return json.dumps(retVal)
#return content
def postPensionaer(self, *args, **kwargs):
# /pensionaer/ daten daten eines neuen pensionaers speichern und ID liefern
data_tmp = self.db_o.pensionaere
daten = {
"id": None, #id wird später ermittelt
"Anrede":kwargs["Anrede"],
"Name": kwargs["Name"],
"Vorname":kwargs["Vorname"],
"Titel":kwargs["Titel"],
"Geburtsdatum":kwargs["Geburtsdatum"],
"Strasse":kwargs["Strasse"],
"Hausnummer":kwargs["Hausnummer"],
"Adresszusatz":kwargs["Adresszusatz"],
"Postleitzahl":kwargs["Postleitzahl"],
"Ort":kwargs["Ort"]
}
count = 0
for data in data_tmp:
count = count + 1 # zaehle anzahl datensätze
count = count + 1
maxID = 0
for i in range(0, count-1):
if data_tmp[i]["id"] > maxID:
maxID = data_tmp[i]["id"] #suche größte id
print("prev: ", maxID)
maxID = int(maxID) + 1
print ("after: ", maxID)
daten["id"] = maxID
data_tmp.append(daten)
self.db_o.saveData()
self.db_o.readData()
return ''
#-------------------------------------------------------
def GET(self, *args):
#-------------------------------------------------------
# /anzeigen startseite
# /pensionaer/ daten aller pensionaere als liste ausliefern
# /pensionaer/id daten eines pensionaers anhand id liefern
# /congratstmpl/ liste aller vorlagen liefern
# /congratstmpl/path inhalt pfad zur dateiauswahl für den import liefern
# /congratstmpl/id beschreibung für und inhalt der per id gewaehlten vorlage gratulationen liefern
# /significantBirthdays/ defaultwerte für ein formular zur abfrage der einstellungen liefern
if args[0] == "pensionaer":
return self.getPensionaer(*args)
else:
if args[0] == "congratstempl":
return self.getCongrats(*args)
else:
if args[0] == "significantbirthdays":
return self.getBirthdays()
else:
return ''
def getBirthdays(self):
# /significantBirthdays/ defaultwerte für ein formular zur abfrage der einstellungen liefern
# abfrage
pass
def getCongrats(self, *args):
# /congratstmpl/ liste aller vorlagen liefern
# /congratstmpl/path inhalt pfad zur dateiauswahl für den import liefern
# /congratstmpl/id beschreibung und inhalt der per id gewaehlten vorlage gratulationen liefern
#bei erfolgreichem import muss json automatisch erstellt werden client oder server?
path = args[2]
id = args[1]
if path == "-1" and id == "-1":
return self.CgetList()
else:
if path != "-1":
return self.CgetPathContent(path)
else:
if id != "-1":
return self.CgetTemplateById(id)
def CgetList(self):
# liste aller möglichen vorlagen
#informationen aus .json dateien in congratstempl
retVal_s = self.db_o.Congrats
return json.dumps(retVal_s)
def CgetPathContent(self, path):
#liste mit allen dateien im pfad die importiert werden können
# pfad muss sich in root von server befinden
#print("CgetPathContent")
retVal = [
]
_path = None
if path == "a":
_path = "congratstempl"
files_a = os.listdir(os.path.join(cherrypy.Application.currentDir_s, _path))
else:
_path = path
files_a = os.listdir(_path)
count = 0
for FileNames in files_a:
#print(FileNames)
#retVal[count]["Dateiname"] = FileNames
retVal.append(FileNames)
count = count + 1
return json.dumps(retVal)
def CgetTemplateById(self, id):
#waehle template anhand von id aus liste aus und liefere speicherort des templates
#und beschreibung
retVal = [
{
"ID":"",
"Beschreibung":"",
"Path":"",
"Text":""
}
]
self.db_o.readCongrats()
data_tmp = self.db_o.Congrats
path = None
count = 0
for data in data_tmp:
if str(data_tmp[count]['ID']) == str(id):
retVal[0]['ID'] = data_tmp[count]["ID"]
retVal[0]['Beschreibung'] = data_tmp[count]["Beschreibung"]
retVal[0]['Path'] = data_tmp[count]["Path"]
path = data_tmp[count]['Path']
file_x = codecs.open(os.path.join("congratstempl", path), 'r', 'utf-8')
content = file_x.read()
file_x.close()
retVal[0]['Text'] = content
#print(retVal)
return json.dumps(retVal)
count = count + 1
def getPensionaer(self, *args):
# /pensionaer/ daten aller pensionaere als liste ausliefern
# /pensionaer/id daten eines pensionaers anhand id liefern
retVal_s = ''
if len(args)==1:
retVal_s = self.getList_p()
else:
id = args[1]
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def getList_p(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
print(json.dumps(data_a))
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getDetail_p(self, id_spl):
#-------------------------------------------------------
data_o = self.db_o.read_px(id_spl)
return self.view_o.createDetail_px(data_o)
# EOF<file_sep>/WEB/Klausurvorbereitung/WEB/Praktika/p4/web_praktikum4/p4/bt/test/curl (2).txt
#!/bin/bash
function test {
url="http://127.0.0.1:8080/$1"
#rand=$(head -c 2 /dev/urandom)
echo "$url"
echo ""
echo "$1 list"
curl -s -S -f -G "$url" || echo "fail"
echo ""
echo ""
echo "$1 new"
tmp=""
tmp=$(curl -s -S -f -X POST -d "$2$3$rand" "$url" || echo "fail")
echo "$tmp"
tmp=$(echo "$tmp" | grep -o -P "\d*")
echo ""
echo "$1 edit"
curl -s -S -f -X PUT -d "$2$tmp$3" "$url" || echo -e "fail"
echo ""
echo ""
echo "$1 get"
[ -n "$tmp" ] && (curl -s -S -f -G "$url$tmp" || echo -e "fail")
[ -z "$tmp" ] && echo -e "skip"
echo ""
echo ""
echo "$1 delete"
[ -n "$tmp" ] && (curl -s -S -f -X DELETE -d "$2$3" "$url$tmp" || echo -e "fail")
[ -z "$tmp" ] && echo -e "skip"
echo ""
echo ""
}
function get {
url="http://127.0.0.1:8080/$1"
#echo "$url"
echo "$1"
curl -s -S -G "$url" || echo "fail"
echo ""
echo ""
}
rand=abc
echo "rest test script"
echo ""
test projekt/ "id_s=" "&name_s=$rand"
#kein fehler DELETE
test fehler/ "id_s=" "&komponente_s=$rand&beschreibung_s=$rand&mitarbeiter_s=$rand&datum_s=$rand&kategorie_s=$rand&fehlerstatus_s=$rand"
get fehler/?type=erkannt
get fehler/?type=behoben
#projektkomponenten:id
test komponente/ "id_s=" "&name_s=$rand&beschreibung_s=$rand&projekt_s=$rand"
#qsmitarbeiter 4x
#swentwickler 4x
#katursache 4x
#prolist
get prolist/
#katlist
get katlist/
#template
get templates/
<file_sep>/WEB/p2_sicherung6/mhb/app/view.py
# coding: utf-8
import os.path
import codecs
import string
from mako.template import Template
from mako.lookup import TemplateLookup
#----------------------------------------------------------
class View_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# Pfad hier zur Vereinfachung fest vorgeben
self.path_s = "C:\\Users\\Mark\\Python_Projects\\web\\p2\\mhb\\template"
self.lookup_o = TemplateLookup(directories=self.path_s)
# ... weitere Methoden
#-------------------------------------------------------
def createList_error_px(self, data_opl):
#-------------------------------------------------------
#Generierung des Loginforms für die Anmeldung mit dem Benutzernamen
return self.createTemplate_p('error_login.tpl', data_opl)
#-------------------------------------------------------
def createList_modulhandbuch_px(self, id_spl, data_opl):
#-------------------------------------------------------
#Generierung des Loginforms für die Anmeldung mit dem Benutzernamen
return self.createTemplate_p('liste_modulhandbuch.tpl', data_opl)
#-------------------------------------------------------
def createTemplate_p(self, template_spl, data_opl):
#-------------------------------------------------------
# Auswertung mit templates
template_o = self.lookup_o.get_template(template_spl)
# mit der Methode render wird das zuvor 'übersetzte' Template ausgeführt
# data_o sind die im Template angegebenen Daten
# data_opl die übergebenen Daten
markup_s = template_o.render(data_o = data_opl)
return markup_s
#-------------------------------------------------------
def createTemplate2_p(self, template_spl, data_opl, data_opl2):
#-------------------------------------------------------
# Auswertung mit templates
template_o = self.lookup_o.get_template(template_spl)
# mit der Methode render wird das zuvor 'übersetzte' Template ausgeführt
# data_o sind die im Template angegebenen Daten
# data_opl die übergebenen Daten
markup_s = template_o.render(data_o = data_opl, data_m = data_opl2)
return markup_s
#-------------------------------------------------------
def createForm_login_b_px(self, data_opl):
#-------------------------------------------------------
#Generierung des Loginforms für die Anmeldung mit dem Benutzernamen
return self.createTemplate_p('form_anmeldung_benutzername.tpl', data_opl)
#-------------------------------------------------------
#def createForm_login_bk_px(self, data_opl):
#-------------------------------------------------------
#Generierung des Loginforms für die Anmeldung mit Benutzername + Kennwort
#return self.createTemplate_p('form_anmeldung_kennwort.tpl', data_opl)
#-------------------------------------------------------
def createList_studiengaenge_student_px(self, data_opl):
#-------------------------------------------------------
return self.createTemplate_p('liste_studiengaenge_student.tpl', data_opl)
#-------------------------------------------------------
def createList_lehrveranstaltungen_px(self, data_opl):
#-------------------------------------------------------
return self.createTemplate_p('liste_lehrveranstaltungen.tpl', data_opl)
#-------------------------------------------------------
def createList_studiengaenge_module_px(self, data_opl, data_opl2):
#-------------------------------------------------------
return self.createTemplate2_p('liste_studiengaenge_module.tpl', data_opl, data_opl2)
#-------------------------------------------------------
def createList_studiengaenge_lv_module_px(self, data_opl, data_opl2):
#-------------------------------------------------------
return self.createTemplate2_p('liste_studiengaenge_lv_module.tpl', data_opl, data_opl2)
#-------------------------------------------------------
def createForm_studiengaenge_px(self, id_spl, data_opl):
#-------------------------------------------------------
#Generierung des Speichern/Bearbeitungsforms für die Studiengänge
# hier müsste noch eine Fehlerbehandlung ergänzt werden !
markup_s =''
markup_s += self.readFile_p('form_studiengaenge_0.tpl')
markupV_s = self.readFile_p('form_studiengaenge_1.tpl')
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (bezeichnung_s=data_opl[0]
, kurzbezeichnung_s=data_opl[1]
, beschreibung_s=data_opl[2]
, semesteranzahl_s=data_opl[3]
, id_s=id_spl
)
markup_s += self.readFile_p('form_studiengaenge_2.tpl')
markup_s += self.createTemplate_p('liste_lehrveranstaltungen.tpl', data_opl[5])
markup_s += self.readFile_p('form_studiengaenge_3.tpl')
return markup_s
#-------------------------------------------------------
def createForm_module_px(self, id_spl, data_opl):
#-------------------------------------------------------
#Generierung des Speichern/Bearbeitungsforms für die Studiengänge
# hier müsste noch eine Fehlerbehandlung ergänzt werden !
markup_s =''
markup_s += self.readFile_p('form_module_0.tpl')
markupV_s = self.readFile_p('form_module_1.tpl')
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (bezeichnung_s=data_opl[0]
, beschreibung_s=data_opl[1]
, anzahl_kreditpunkte_s=data_opl[2]
, anzahl_sws_vorlesung_s=data_opl[3]
, anzahl_sws_uebung_s=data_opl[4]
, anzahl_sws_praktikum_s=data_opl[5]
, voraussetzungen_s=data_opl[6]
, id_s=id_spl
)
markup_s += self.readFile_p('form_module_2.tpl')
return markup_s
#-------------------------------------------------------
def readFile_p(self, fileName_spl):
#-------------------------------------------------------
content_s =''
with codecs.open(os.path.join('template', fileName_spl),'r','utf-8')as fp_o:
content_s = fp_o.read()
return content_s
# EOF <file_sep>/WEB/Vorlesung/javascript_beispiele/proto1.js
var myObject_o = {
name_s: "Mustermann",
vorname_s: "Max"
}
// die allgemeine toString-Methode von Object wird verwendet
console.log(myObject_o.toString());
console.log(myObject_o.tofuck());
// spezielle toString-Methode als Eigenschaft erzeugen
myObject_o.toString = function () {
return this.vorname_s + " " + this.name_s;
}
// die allgemeine toString-Methode von Object wird verborgen
console.log(myObject_o.toString());
// Eigenschaften können auch gelöscht werden!
delete myObject_o.toString;
// die allgemeine toString-Methode von Object wird verwendet
console.log(myObject_o.toString());<file_sep>/Mattes/3/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
import datetime
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
# da es hier nur darum geht, die Daten dauerhaft zu speichern,
# wird ein sehr einfacher Ansatz verwendet:
# - es k�nnen Daten zu genau 15 Teams gespeichert werden
# - je Team werden 2 Teilnehmer mit Namen, Vornamen und Matrikelnummer
# ber�cksichtigt
# - die Daten werden als eine JSON-Datei abgelegt
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.view = ['student'
,'lehrende'
,'firma'
,'ppangebot'
,'ppangebot']
self.data_o = None
#self.readData_p()
def GetDefault(self, ansicht):
data_o = ''
if ansicht == 0:
data_o = {
"matrikelnr": '',
"name": '',
"vorname": ''
}
elif ansicht == 1:
data_o = {
"titel": '',
"name": '',
"vorname": '',
"lehrgebiet": ''
}
elif ansicht == 2:
data_o = {
"name": '',
"branche": '',
"schwerpunkt": '',
"sitz": '',
"mitarbeiteranzahl": ''
}
else:
data_o = {
"pptitel": '',
"beschreibung": '',
"firmaid": '',
"voraussetzung": '',
"kontakt": '',
"lehrendenid": '',
"matrikelid": '',
"anfangsdatum": '',
"enddatum": ''
}
return data_o
#-------------------------------------------------------
def updateRow(self, ansicht, id_s, data_s):
#-------------------------------------------------------
del self.data_o[self.view[ansicht]]['list'][id_s]
self.data_o[self.view[ansicht]]['list'].update({id_s: ''})
self.data_o[self.view[ansicht]]['list'][id_s] = eval(data_s)
self.saveData()
return
#-------------------------------------------------------
def getRow(self, ansicht, id_s):
#-------------------------------------------------------
return self.data_o[self.view[ansicht]]['list'][id_s]
#-------------------------------------------------------
def addRow(self, ansicht, data_s):
#-------------------------------------------------------
id_s = self.data_o[self.view[ansicht]]['count']
self.data_o[self.view[ansicht]]['count'] += 1
self.data_o[self.view[ansicht]]['list'].update({id_s: ''})
self.data_o[self.view[ansicht]]['list'][id_s] = eval(data_s)
self.saveData();
return
#-------------------------------------------------------
def deleteRow(self, ansicht, id_s):
#-------------------------------------------------------
del self.data_o[self.view[ansicht]]['list'][id_s]
self.saveData()
return
#-------------------------------------------------------
def pushPPA(self, id_s):
#-------------------------------------------------------
data_opl = self.data_o['ppangebot']['list'][id_s]
del self.data_o['ppangebot']['list'][id_s]
self.data_o['ppaktuell']['list'].append(data_opl)
self.saveData()
return
#-------------------------------------------------------
def ReadData(self):
#-------------------------------------------------------
fp_o = codecs.open(os.path.join('data', 'ppm.json'), 'r', 'utf-8')
with fp_o:
self.data_o = json.load(fp_o)
return self.data_o
#-------------------------------------------------------
def saveData(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'ppm.json'), 'w', 'utf-8') as fp_o:
json.dump(self.data_o, fp_o)
# EOF<file_sep>/Mattes/2/app/application.py
# coding: utf-8
import json
import cherrypy
from .database import Database_cl
from .view import View_cl
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung k�nnen hier eingetragen werden
self.db_o = Database_cl()
self.view_o = View_cl()
@cherrypy.expose
#-------------------------------------------------------
def index(self):
#-------------------------------------------------------
return self.view_o.createstart_px();
@cherrypy.expose
#-------------------------------------------------------
def createPPAuswahlForm(self, id):
#-------------------------------------------------------
return self.createPPAuswahlForm_p(id)
@cherrypy.expose
#-------------------------------------------------------
def addStudent(self):
#-------------------------------------------------------
return self.createStudentForm_p()
@cherrypy.expose
#-------------------------------------------------------
def addLehrer(self):
#-------------------------------------------------------
return self.createLehrerForm_p()
@cherrypy.expose
#-------------------------------------------------------
def addFirma(self):
#-------------------------------------------------------
return self.createFirmenForm_p()
@cherrypy.expose
#-------------------------------------------------------
def addPPA(self):
#-------------------------------------------------------
return self.createPPAForm_p()
@cherrypy.expose
#-------------------------------------------------------
def editStudent(self, id):
#-------------------------------------------------------
return self.createStudentForm_p(id)
@cherrypy.expose
#-------------------------------------------------------
def editLehrer(self, id):
#-------------------------------------------------------
return self.createLehrerForm_p(id)
@cherrypy.expose
def editFirma(self, id):
#-------------------------------------------------------
return self.createFirmenForm_p(id)
@cherrypy.expose
def editPPA(self, id):
#-------------------------------------------------------
return self.createPPAForm_p(id)
@cherrypy.expose
#-------------------------------------------------------
def saveStudent(self, **data_opl):
#-------------------------------------------------------
id_s = data_opl["id_s"]
data_a = {
"matrikelnr": int(data_opl["matrikelnr"])
, "name": data_opl["name"]
, "vorname": data_opl["vorname"]
}
if id_s != "None":
# Update-Operation
self.db_o.updateStudent_px(id_s, data_a)
else:
# Create-Operation
id_s = self.db_o.createStudent_px(data_a)
return self.createStudentList()
@cherrypy.expose
#-------------------------------------------------------
def saveLehrer(self, **data_opl):
#-------------------------------------------------------
id_s = data_opl["id_s"]
data_a = {
"titel": data_opl["titel"]
, "name": data_opl["name"]
, "vorname": data_opl["vorname"]
, "lehrgebiet": data_opl["lehrgebiet"]
}
if id_s != "None":
# Update-Operation
self.db_o.updateLehrer_px(id_s, data_a)
else:
# Create-Operation
id_s = self.db_o.createLehrer_px(data_a)
return self.createLehrerList()
@cherrypy.expose
#-------------------------------------------------------
def saveFirma(self, **data_opl):
#-------------------------------------------------------
id_s = data_opl["id_s"]
data_a = {
"name": data_opl["name"]
, "branche": data_opl["branche"]
, "schwerpunkt": data_opl["schwerpunkt"]
, "sitz": data_opl["sitz"]
, "mitarbeiteranzahl": int(data_opl["mitarbeiteranzahl"])
}
if id_s != "None":
# Update-Operation
self.db_o.updateFirma_px(id_s, data_a)
else:
# Create-Operation
id_s = self.db_o.createFirma_px(data_a)
return self.createFirmenList()
@cherrypy.expose
#-------------------------------------------------------
def savePPA(self, **data_opl):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
if data_opl["firmaid"] not in data_o['firma']['list']:
return self.view_o.createPPAForm_px(data_opl["id_s"], data_opl, 'Firma nicht gefunden!')
id_s = data_opl["id_s"]
data_a = {
"pptitel": data_opl['pptitel'],
"beschreibung": data_opl['beschreibung'],
"firmaid": data_opl['firmaid'],
"voraussetzung": data_opl['voraussetzung'],
"kontakt": data_opl['kontakt'],
"lehrendenid": data_opl['lehrendenid'],
"matrikelid": data_opl['matrikelid'],
"anfangsdatum": data_opl['anfangsdatum'],
"enddatum": data_opl['enddatum']
}
if id_s != "None":
# Update-Operation
self.db_o.updatePPA_px(id_s, data_a)
else:
# Create-Operation
self.db_o.createPPA_px(data_a)
return self.createPPAList()
@cherrypy.expose
#-------------------------------------------------------
def savePPAktuell(self, **data_opl):
#-------------------------------------------------------
self.db_o.readData_p();
case = self.db_o.savePPaktuell_px(**data_opl)
if case == 1:
return self.createPPAList()
elif case == -1:
return self.createPPAuswahlForm_p(data_opl['id_s'], 'Student nicht gefunden!')
elif case == -2:
return self.createPPAuswahlForm_p(data_opl['id_s'], 'Student bereits Eingetragen!')
@cherrypy.expose
#-------------------------------------------------------
def deleteStudent(self, id):
#-------------------------------------------------------
# Eintrag l�schen, dann Liste neu anzeigen
self.db_o.deleteStudent_px(id)
return self.createStudentList()
@cherrypy.expose
#-------------------------------------------------------
def deleteLehrer(self, id):
#-------------------------------------------------------
# Eintrag l�schen, dann Liste neu anzeigen
self.db_o.deleteLehrer_px(id)
return self.createLehrerList()
@cherrypy.expose
#-------------------------------------------------------
def deleteFirma(self, id):
#-------------------------------------------------------
# Eintrag l�schen, dann Liste neu anzeigen
self.db_o.deleteFirma_px(id)
return self.createFirmenList()
@cherrypy.expose
#-------------------------------------------------------
def deletePPA(self, id):
#-------------------------------------------------------
# Eintrag l�schen, dann Liste neu anzeigen
self.db_o.deletePPA_px(id)
return self.createPPAList()
@cherrypy.expose
#-------------------------------------------------------
def createStudentList(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createStudentList_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def createLehrerList(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createLehrerList_px(data_o)
@cherrypy.expose
def createFirmenList(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createFirmenList_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def createPPAList(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createPPAList_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def createAuswertungFirma(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createAuswertungFirma_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def createAuswertungStudent(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createAuswertungStudent_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def createAuswertungLehrer(self):
#-------------------------------------------------------
data_o = self.db_o.readData_p()
return self.view_o.createAuswertungLehrer_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def default(self, *arguments, **kwargs):
#-------------------------------------------------------
msg_s = "unbekannte Anforderung: " + \
str(arguments) + \
' ' + \
str(kwargs)
raise cherrypy.HTTPError(404, msg_s)
default.exposed= True
#-------------------------------------------------------
def createStudentForm_p(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
data_o = self.db_o.readStudent_px(id_spl)
else:
data_o = {
"matrikelnr": '',
"name": '',
"vorname": ''
}
# mit diesen Daten Markup erzeugen
return self.view_o.createStudentForm_px(id_spl, data_o)
#-------------------------------------------------------
def createLehrerForm_p(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
data_o = self.db_o.readLehrer_px(id_spl)
else:
data_o = {
"titel": '',
"name": '',
"vorname": '',
"lehrgebiet": ''
}
# mit diesen Daten Markup erzeugen
return self.view_o.createLehrerForm_px(id_spl, data_o)
#-------------------------------------------------------
def createFirmenForm_p(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
data_o = self.db_o.readFirma_px(id_spl)
else:
data_o = {
"name": '',
"branche": '',
"schwerpunkt": '',
"sitz": '',
"mitarbeiteranzahl": ''
}
# mit diesen Daten Markup erzeugen
return self.view_o.createFirmenForm_px(id_spl, data_o)
#-------------------------------------------------------
def createPPAForm_p(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
data_o = self.db_o.readPPA_px(id_spl)
else:
data_o = {
"pptitel": '',
"beschreibung": '',
"firmaid": '',
"voraussetzung": '',
"kontakt": '',
"lehrendenid": '',
"matrikelid": '',
"anfangsdatum": '',
"enddatum": ''
}
# mit diesen Daten Markup erzeugen
return self.view_o.createPPAForm_px(id_spl, data_o)
#-------------------------------------------------------
def createPPAuswahlForm_p(self, id_spl = None, alert = None):
#-------------------------------------------------------
data_o = self.db_o.readPPA_px(id_spl)
return self.view_o.createPPAuswahlForm_px(id_spl, data_o, alert)
# EOF
<file_sep>/WEB/Klausurvorbereitung/WEB/Praktika/p1/web/p1/webteams/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
# da es hier nur darum geht, die Daten dauerhaft zu speichern,
# wird ein sehr einfacher Ansatz verwendet:
# - es k?nnen Daten zu genau 15 Teams gespeichert werden
# - je Team werden 2 Teilnehmer mit Namen, Vornamen und Matrikelnummer
# ber?cksichtigt
# - die Daten werden als eine JSON-Datei abgelegt
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.data_o = None
self.readData_p()
#-------------------------------------------------------
def create_px(self, data_opl):
#-------------------------------------------------------
# ?berpr?fung der Daten m?sste erg?nzt werden!
if data_opl != "None":
# 'freien' Platz suchen,
# falls vorhanden: belegen und Nummer des Platzes als Id zur?ckgeben
id_s=None
for loop_i in range(0,15):
if self.data_o[str(loop_i)][0] == '':
id_s = str(loop_i)
self.data_o[id_s]=data_opl
self.saveData_p()
break
return id_s
#-------------------------------------------------------
def read_px(self, id_spl=None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr?ge liefern
data_o = None
if id_spl == None:
data_o = self.data_o
else:
if id_spl in self.data_o:
data_o = self.data_o[id_spl]
return data_o
#-------------------------------------------------------
def update_px(self, id_spl, data_opl):
#-------------------------------------------------------
# ?berpr?fung der Daten m?sste erg?nzt werden!
if id_spl != "None" and data_opl != "None":
status_b=False
if id_spl in self.data_o:
self.data_o[id_spl]=data_opl
self.saveData_p()
status_b=True
return status_b
#-------------------------------------------------------
def delete_px(self, id_spl):
#-------------------------------------------------------
status_b = False
if id_spl in self.data_o:
self.data_o[id_spl]=self.getDefault_px()
self.saveData_p()
# hier m?ssen Sie den Code erg?nzen
# L?schen als Zur?cksetzen auf die Default-Werte implementieren
# Ihre Erg?nzung
return status_b
#-------------------------------------------------------
def getDefault_px(self):
#-------------------------------------------------------
return['','','','','','']
#-------------------------------------------------------
def readData_p(self):
#-------------------------------------------------------
try:
fp_o =codecs.open(os.path.join('data','webteams.json'),'r','utf-8')
except:
# Datei neu anlegen
self.data_o={}
for loop_i in range (0,15):
self.data_o[str(loop_i)]=['','','','','','']
self.saveData_p()
else:
with fp_o:
self.data_o=json.load(fp_o)
return
#-------------------------------------------------------
def saveData_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data','webteams.json'),'w','utf-8')as fp_o:
json.dump(self.data_o, fp_o)
# EOF<file_sep>/WEB/Klausurvorbereitung/WEB/Praktika/p1/web/p1/webteams/content/Doku.md
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title></title>
<style type="text/css">code{white-space: pre;}</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<h2 id="webpraktikum">Webpraktikum</h2>
<p><strong>Gruppe C: <NAME>, <NAME></strong>:</p>
<p><strong>Aufbau Der Webanwendung</strong>: Die Webanwendug besteht aus zwei Seiten: -Startseite:Auflistung der Daten von Teammitgliedern (max.15). -Formular:Erfassung neuer Daten oder Bearbeitung vorhandener Daten.</p>
<p><em>mögliche Aktionen sind</em>:</p>
<p>-erfassen: führt in den Zustand "Detail-neu" -bearbeiten: führt in den Zustand "Detail-alt" -löschen: Daten eines Web-Teams entfernen und Liste wieder aneigen; d.h. der Zustand wird nicht verlassen</p>
<p><em>Zustand"Detail-neu"</em>: -es wird ein leeres Formular angezeigt <em>mögliche Aktionen sind</em>:<br> -abbrechen<br> -speichern</p>
<p><em>Zustand"Detail-neu"</em>: -das Formular zeigt die Daten des ausgewählten Teams an <em>mögliche Aktionen sind</em>:<br> -abbrechen<br>-speichern</p>
<p><strong>Duchgeführte Ergänzugen</strong>: -Überprüfung der Übergabewerte auf Inhalt<br> -Dateneingabe für die Daten des zweiten Teammitglieds hinzugefügt<br> -Aktion Abbrechen im Formular Implementiert<br> -CSS Stilregeln in die Datei webteams.css eingetragen<br> -Löschen der Daten eines Teams auf der Serverseite Implementiert<br> -Rückfrage an den Benutzer beim Löschen von Einträgen in der Liste vervollständigt</p>
<p><strong>Beschreibung des HTTP-Datenverkehrs</strong>:</p>
<p><em>Beim start der Anwendung</em>:</p>
<br><img src="vorher.png" alt="vorher">
<p><em>Beim Speichern von Formulardaten</em>:</p>
<br><img src="nachher.png" alt="nachher">
</body>
</html>
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/formVerantwortlicherStudiengang.tpl.py
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1515085284.3771296
_enable_loop = True
_template_filename = '/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/formVerantwortlicherStudiengang.tpl'
_template_uri = 'formVerantwortlicherStudiengang.tpl'
_source_encoding = 'utf-8'
_exports = []
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
data_o = context.get('data_o', UNDEFINED)
data_lehr = context.get('data_lehr', UNDEFINED)
data_mod = context.get('data_mod', UNDEFINED)
__M_writer = context.writer()
__M_writer('<div id="formVerantwortlicherStudiengang">\r\n\t<table style="text-align:center;">\r\n\t<h1>Form Lehrender Studiengang</h1>\r\n\t<br>\r\n\t\t<select id="studiengang" name="studiengang">\r\n\t\t\t<option value="0">Wählen Sie Ihren Studiengang:</option>\r\n')
for a in data_o.values():
__M_writer('\t\t\t\t<option value="')
__M_writer(str(a[1]))
__M_writer('">')
__M_writer(str(a[0]))
__M_writer('</option>\r\n')
__M_writer('\t\t</select>\r\n\t\t<button id="buttonstud">Studienganginfos und Modulhandbuch anzeigen</button>\r\n\t\t<p />\r\n\t\t<form id="createStudiengang" action="" method="POST">\r\n\t\t\t<button onclick="loadDoccreateStudiengang()">Studiengang Erfassen</button>\r\n\t\t</form> \r\n\t\t<form id="editStudiengang" action="" method="POST">\r\n\t\t\t<button onclick="loadDocstudiengangEdit()">Studiengang Bearbeiten</button>\r\n\t\t</form> \r\n\t\t<button id="buttonstuddelete">Studiengang Löschen</button><br>\r\n\t\t<p />\r\n\t\t<select id="lehr" name="lehr">\r\n\t\t\t<option value="0">Wählen Sie Ihre Lehrveranstaltung aus:</option>\r\n')
for b in data_lehr.values():
__M_writer('\t\t\t\t<option value="')
__M_writer(str(b[0]))
__M_writer('">')
__M_writer(str(b[0]))
__M_writer('</option>\r\n')
__M_writer('\t\t</select>\r\n\t\t<p />\r\n\t\t<form action="/createLehrveranstaltung" method="POST">\r\n\t\t\t<button type="submit">Lehrveranstaltung Erfassen</button><br>\r\n\t\t</form> \r\n\t\t<button id="buttonlehredit">Lehrveranstaltung Bearbeiten</button><br>\r\n\t\t<button id="buttonlehrdelete">Lehrveranstaltung Löschen</button><br>\r\n\t\t<p />\r\n\t\t<select id="modul" name="modul">\r\n\t\t\t<option value="0">Wählen Sie Ihr Modul aus:</option>\r\n')
for c in data_mod.values():
__M_writer('\t\t\t\t<option value="')
__M_writer(str(c[0]))
__M_writer('">')
__M_writer(str(c[0]))
__M_writer('</option>\r\n')
__M_writer('\t\t</select>\r\n\t\t<p />\r\n\t\t<form action="/createModul" method="POST">\r\n\t\t\t<button type="submit">Modul Erfassen</button><br>\r\n\t\t</form>\r\n\t\t<button id="buttonmoduledit">Modul Bearbeiten</button><br>\r\n\t\t<button id="buttonmoduldelete">Modul Löschen</button>\r\n\t\t<br>\r\n\t\t<p />\r\n\t\t<form action="/" method="POST">\r\n\t\t\t<button type="submit">Logout</button><br>\r\n\t\t</form> \r\n\t\t<script src="mhb_studiengang.js"></script>\r\n</div>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"filename": "/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/formVerantwortlicherStudiengang.tpl", "uri": "formVerantwortlicherStudiengang.tpl", "line_map": {"16": 0, "24": 2, "25": 8, "26": 9, "27": 9, "28": 9, "29": 9, "30": 9, "31": 11, "32": 24, "33": 25, "34": 25, "35": 25, "36": 25, "37": 25, "38": 27, "39": 37, "40": 38, "41": 38, "42": 38, "43": 38, "44": 38, "45": 40, "51": 45}, "source_encoding": "utf-8"}
__M_END_METADATA
"""
<file_sep>/WEB/p3/mhb/doc/mhd.md
Name: <NAME>\
Matrikelnummer: 1121869\
Gruppe: B\
Datum: 09.01.2018\
**Allgemeine Beschreibung der Lösung:**
Aufgabe der Anwendung:
Mit der Webanwendung werden die Beschreibungen der Studiengänge und Module abgerufen bzw. gepflegt.
Übersicht der fachlichen Funktionen:
Mit der Anwendung soll es möglich sein, neben der Datenpflege ein Modulhandbuch zu erstellen:
• das Modulhandbuch zu einem Studiengang enthält
◦ die Zusammenstellung der Angaben zum Studiengang
◦ eine Übersicht mit allen Lehrveranstaltungen, alphabetisch sortiert
▪ auch die Modulverantwortlichen werden aufgeführt
einen detaillierten Semesterplan:
▪ vom 1. bis zum letzten Semester des Studiengangs werden die Lehrveranstaltungen mit allen Daten ausgewiesen
▪ die je Semester erzielbaren Kreditpunkte werden ausgewiesen
▪ die insgesamt erzielbaren Kreditpunkte werden ausgewiesen
• es werden drei Rollen vorgesehen:
Rolle "Studierender":
▪ kann alle Studiengänge einsehen
▪ kann zu jedem Studiengang das Modulhandbuch abrufen
Rolle "Verantwortlicher Modul":
▪ kann die Daten der ihm zugewiesenen Module bearbeiten (aber keine Module erstellen oder löschen!)
▪ kann alle Studiengänge einsehen
▪ kann zu jedem Studiengang das Modulhandbuch abrufen
Rolle "Verantwortlicher Studiengang":
▪ erstellt und pflegt die Studiengänge
▪ erstellt die Module (gibt dabei nur Bezeichnung an - Pflege der weiteren Inhalte siehe andere Rolle)
▪ legt die Zuordnung der Benutzer der Rolle "Verantwortlicher Modul" zu Modulen fest
▪ kann Module löschen
▪ legt die Struktur eines Studiengangs anhand der Lehrveranstaltungen in den einzelnen Semestern fest
▪ legt die Zuordnung der Module zu Lehrveranstaltungen fest
▪ legt die Modulabhängigkeiten (Voraussetzungen) fest
**Aufgabenstellung Praktikum 3**
Änderung zu der Aufgabenstellung zu Praktikum 3 ist die Aufbereitung der Webanwendung als Single-Page-Application
Über Javascript wird nun der Aufruf der HTML-Seiten gesteuert.
Die URI im Browser verändert sich dabei nicht.
Es werden nur einzelne Teile der HTML-Seite neugeladen.
**Beschreibung der Komponenten des Servers:**
Application_cl:
- stellt die Verbindung zwischen Database_cl und View_cl her
- stellt die Funktionen der Anwendung bereit (save, edit, delete, login, modulhandbuch, etc.)
Database_cl:
- liest, bearbeitet, erstellt Einträge in den zugehörigen .json Dateien
View_cl:
- liest die erstellten Templates ein und gibt die Sicht der zugehörigen Anwendung aus
**Datenablage:**
web
/p2
/mhd
/app
/_init_.py <-- Initialisierung
/application.py <-- Anwendung
/database.py <-- Datenbasis
/view.py <-- Sicht
/content
/mhb.css
/mhb.js
/data
/benutzer.json <-- Daten
/studiengaenge.json
/module.json
/lehrveranstaltungen.json
/doc
/template
/form_anmeldung_benutzername.tpl <-- Formulare
/form_module_1.tpl
/form_module_2.tpl
/form_module_3.tpl
/form_studiengaenge_1.tpl
/form_studiengaenge_2.tpl
/form_studiengaenge_3.tpl
/form_lehrveranstaltungen_1.tpl
/form_lehrveranstaltungen_2.tpl
/form_lehrveranstaltungen_3.tpl
/liste_studiengaenge_vs.tpl <--- Listen
/liste_studiengaenge_vm.tpl
/liste_lehrveranstaltungen.tpl
**Konfiguration:**
#coding: utf-8
import os
import cherrypy
from app import application
#--------------------------------------
def main():
#--------------------------------------
# Get current directory
try:
current_dir = os.path.dirname(os.path.abspath(__file__))
except:
current_dir = os.path.dirname(os.path.abspath(sys.executable))
# disable autoreload and timeout_monitor
cherrypy.engine.autoreload.unsubscribe()
cherrypy.engine.timeout_monitor.unsubscribe()
# Static content config
staticConfig_o = {
'/': {
'tools.staticdir.root': current_dir,
'tools.staticdir.on': True,
'tools.staticdir.dir': './content',
}
}
cherrypy.config.update({
'tools.log_headers.on': True,
'tools.sessions.on': False,
'tools.encode.on': True,
'tools.encode.encoding': 'utf-8',
'server.socket_port': 8080,
'server.socket_timeout': 60,
'server.thread_pool': 10,
'server.environment': 'production',
'log.screen': True#,
#'request.show_tracebacks': False
})
# Request-Handler definieren
cherrypy.tree.mount(application.Application_cl(), '/', staticConfig_o)
# Start server
cherrypy.engine.start()
cherrypy.engine.block()
#--------------------------------------
if __name__ == '__main__':
#--------------------------------------
main()
# EOF
<file_sep>/WEB/p1/webteams/doc/webteams.md
Name: <NAME>\
Matrikelnummer: 1121869\
Gruppe: B\
Datum: 23.10.2017\
**Aufbau der Webanwendung:**
Eine Liste mit der Daten von Studenten erfasst, bearbeitet und gelöscht werden können.
Aufbau der Liste:
1. Name,
1. Vorname,
1. Matrikelnummer,
1. Semesteranzahl,
2. Name,
2. Vorname,
2. Matrikelnummer,
2. Semesteranzahl
**Verzeichnisstruktur:**
web
/p1
/webteams
/app
/_init_.py <-- Initialisierung
/application.py <-- Anwendung
/database.py <-- Datenbasis
/view.py <-- Sicht
/content
/form0.tpl <-- Formulare
/form1.tpl
/form2.tpl
/list0.tpl <-- Liste
/list1.tpl
/list2.tpl
/webteams.css
/webteams.js
/data
/webteams.json <-- Daten
/doc
**Durchgeführte Ergänzungen:**
- Dateneingabe für die Daten des 2. Team-Mitglieds im Formular
- zusätzliches Attribut "Semesteranzahl" (für beide Teammitglieder) in allen Listen und Formularen
sowie in der Datenbasis
- Aktion "Abbrechen" im Formular implementiert
- Gestaltung mit CSS: CSS-Stilregeln in die Datei webteams.css eingetragen
- Löschen der Daten eines Teams auf der Serverseite implementiert (siehe Datei database.py)
- Rückfrage an den Benutzer beim Löschen von Einträgen in der Liste Datei webteams.js
**Beschreibung des Datenverkehrs:**
Start der Anwendung:
Es werden drei Anfragen an die Adresse http://localhost:8080/ geschickt:
127.0.0.1 - - [23/Oct/2017:22:40:56] "GET / HTTP/1.1" 200 5198 "" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0"
127.0.0.1 - - [23/Oct/2017:22:40:56] "GET /webteams.js HTTP/1.1" 304 - "http://localhost:8080/" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0"
127.0.0.1 - - [23/Oct/2017:22:40:56] "GET /webteams.css HTTP/1.1" 304 - "http://localhost:8080/" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0"
Die GET-Befehle laden die HTML-Seite, das Javaskript und die CSS-Daten.
Beim Speichern von Formulardaten:
Die Formulardaten werden mit dem POST Befehl abgeschickt:
127.0.0.1 - - [23/Oct/2017:22:42:58] "POST /save HTTP/1.1" 200 2307 "http://localhost:8080/add" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0"
<file_sep>/WEB/WEB Praktika/mhb/app/months.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
# GET /months/ 0 - 6 Monate, in denen Artikel gemäß Änderungs-/Erstellungszeitpunkt auftreten
#----------------------------------------------------------
class Months_cl(object):
#----------------------------------------------------------
exposed = True
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
retVal_s = ''
data_months = [] # format 01.2018 for januar 2018
month = 9999
year = 9999
articleCount = 0
recentMonthYear = '00.0000'
lastAddedEntry = '00.0000'
i = 0
while i < 6:
recentMonthYear = self.findRecentMonthYear_p(data_a, lastAddedEntry[0:2], lastAddedEntry[3:7])
if recentMonthYear != '00.0000':
data_months.append(recentMonthYear)
lastAddedEntry = recentMonthYear
i = i + 1
#-------------------------------------------------------------------
retVal_s = self.view_o.createList_px(data_months)
return retVal_s
#-------------------------------------------------------
def findRecentMonthYear_p(self, data, month, year):
#-------------------------------------------------------
recentMonthYear = ''
if month == '00':
month = 9999
year = 9999
# find most recent year month combination
currentYear = 0
currentMonth = 0
for value in data:
if int(value['crdat'][6:10]) >= int(currentYear) and int(value['crdat'][6:10]) <= int(year):
if int(value['crdat'][6:10]) == int(year) and int(value['crdat'][3:5]) >= int(month):
pass
else:
currentYear = value['crdat'][6:10]
currentMonth = value['crdat'][3:5]
if int(value['chdat'][6:10]) >= int(currentYear) and int(value['chdat'][6:10]) <= int(year):
if int(value['chdat'][6:10]) == int(year) and int(value['chdat'][3:5]) >= int(month):
pass
else:
currentYear = value['chdat'][6:10]
currentMonth = value['chdat'][3:5]
#------------------------------------------------------------------------------------------
if currentMonth == 0:
currentMonth = '00'
currentYear = '0000'
recentMonthYear = str(currentMonth) + '.' + str(currentYear)
return recentMonthYear
# EOF<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/mhb_studiengang.js
function studiengangAnzeige() {
var get = document.getElementById("studiengang");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie einen Studiengang an");
}
else document.location.href = "/studiengang/" + selected.toString();
}
function studiengangEdit() {
var get = document.getElementById("studiengang");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie einen Studiengang an");
}
else document.location.href = "/editStudiengang/" + selected.toString();
}
function modulEdit() {
var get = document.getElementById("modul");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie ein Modul an");
}
else document.location.href = "/editModul/" + selected.toString();
}
function lehrEdit() {
var get = document.getElementById("lehr");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie eine Lehrveranstaltung an");
}
else document.location.href = "/editLehrveranstaltung/" + selected.toString();
}
function modulDelete() {
var get = document.getElementById("modul");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie ein Modul an");
}
else document.location.href = "/deleteModul/" + selected.toString();
}
function lehrDelete() {
var get = document.getElementById("lehr");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie eine Lehrveranstaltung an");
}
else document.location.href = "/deleteLehrveranstaltung/" + selected.toString();
}
function studDelete() {
var get = document.getElementById("studiengang");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie einen Studiengang an");
}
else document.location.href = "/deleteStudiengang/" + selected.toString();
}
window.onload=function(){
let studbutton = document.getElementById('buttonstud');
studbutton.addEventListener('click', studiengangAnzeige, false);
let studbuttonedit = document.getElementById('buttonstudedit');
studbuttonedit.addEventListener('click', studiengangEdit, false);
let studbuttondelete = document.getElementById('buttonstuddelete');
studbuttondelete.addEventListener('click', studDelete, false);
let modulbuttonedit = document.getElementById('buttonmoduledit');
modulbuttonedit.addEventListener('click', modulEdit, false);
let modulbuttondelete = document.getElementById('buttonmoduldelete');
modulbuttondelete.addEventListener('click', modulDelete, false);
let lehrbuttondelete = document.getElementById('buttonlehrdelete');
lehrbuttondelete.addEventListener('click', lehrDelete, false);
let lehrbuttonedit = document.getElementById('buttonlehredit');
lehrbuttonedit.addEventListener('click', lehrEdit, false);
}
<file_sep>/WEB/WEB Praktika/pl/doc/doku.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title></title>
<style type="text/css">code{white-space: pre;}</style>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1 id="web-praktikum-2-gruppe-c">WEB Praktikum 2 Gruppe C</h1>
<h2 id="joey-laschet-und-lukas-van-gemmeren"><NAME> und <NAME></h2>
<h2 id="aufbau-der-webanwendung">1. Aufbau der Webanwendung</h2>
<h3 id="framework">Framework</h3>
<p>Verwendetes Framework: CherryPi - ein einfaches Web Framework um Webanwendungen objektorientiert in der Sprache Python zu erstellen.</p>
<h3 id="server.py">server.py</h3>
<p>Startet den CherryPi Server, dient außerdem zur Konfiguration des Servers. Static Konfiguration für einige Elemente und das Mounten von 3 Klassen. (Siehe Konfiguration)</p>
<h3 id="application.py">application.py</h3>
<p>Stellt die Basis der Anwendung, von hier aus gelangt man in die Besucher und Sachbearbeiterklasse.</p>
<h3 id="besucher.py">Besucher.py</h3>
<p>Stellt die Methoden für einen Besucher bereit, wie etwa das anzeigen, buchen und stornieren von Veranstaltungen. Ruft Hauptsächlich Bview.py Methoden und die der Datenbank auf.</p>
<h3 id="sachbearbeiter.py">Sachbearbeiter.py</h3>
<p>Stellt alle Funktionen für den Sachbearbeiter bereit. Neben dem hinzufügen/löschen/bearbeiten von Veranstaltungen gibt es die Möglichkeit einzelne Teilobjekte aus denen Veranstaltungen bestehen zu bearbeiten, wie etwa Kategorien, Orte und Künstler. Ruft Hauptsächlich Sview.py Methoden und die der Datenbank auf.</p>
<h3 id="sview.py">Sview.py</h3>
<p>Stellt die Methoden bereit, um aus den Templates für den Sachbearbeiter fertigen Code zu erzeugen. Benutzt Template Engine Mako.</p>
<h3 id="bview.py">Bview.py</h3>
<p>Stellt die Methoden bereit, um aus den Templates für den Besucher fertigen Code zu erzeugen. Benutzt Template Engine Mako.</p>
<h3 id="database.py">database.py</h3>
<p>Verwaltung der Datenbank im Server. Diese Funktionen stellt die Schnittstelle zwischen dem Webserver und den zu verarbeitenden Daten dar. In diesem Fall werden die Daten sortiert nach Kategorien in .json abgelegt und zur Laufzeit in Dictionairies gehalten.</p>
<h3 id="templates-und-content-ordner">templates und content Ordner</h3>
<p>In diesem Ordner befinden sich alle Template Dateien, für jede mögliche Website eine. Weiterhin befinden sich eine JavaScript Datei für eine interaktive Benutzeroberfläche und eine CSS-Datei zum formatieren der Webseite.</p>
<h2 id="datenablage">Datenablage</h2>
<h3 id="json-dateien">.json Dateien</h3>
<p>In dieser vom Server angelegten Datei werden die Eingabedaten abgespeichert und auf Anfrage ausgelesen und in die Formulare/Templates eingebettet. Jede Datei stellt dabei eine Kategorie dar, wie etwa Veranstaltungen, Orte, Künstler und Besucher. In den Dictionairies befinden sich Arrays um alle Bestandteile der Daten zu trennen.</p>
<h2 id="konfiguration">Konfiguration</h2>
<h3 id="static">Static</h3>
<p>Statisch abgelegt wird die Allgemeingültige CSS Datei und die Javascript Datei die eine Sicherheitsabfrage vor dem Löschen bereitstellt.</p>
<h3 id="gemountete-module">Gemountete Module</h3>
<p>Die Wurzel / wird durch die Application.py dargestellt, welche nur die oberste Startseite bereitstellt. Sie hat keine Funktion außer die Sachbearbeiter und Besucher Klassen zu initialisieren. Sachbearbeiter und Besucher stellen die eigentliche Anwendung bereit, aufgeteilt in 2 Bereiche für 2 Benutzer.</p>
</body>
</html>
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/app/view.py
# coding: utf-8
import codecs
import os.path
import string
from mako.template import Template
from mako.lookup import TemplateLookup
#----------------------------------------------------------
class View_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.path_s = os.path.join(os.getcwd(), "templates")
self.lookup_o = TemplateLookup(directories=self.path_s, module_directory=self.path_s)
#-------------------------------------------------------
def loginfunc(self, template_spl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render()
return markup_s
#-------------------------------------------------------
def error(self, template_spl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render()
return markup_s
#-------------------------------------------------------
def loginfuncLehrender(self, template_spl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render()
return markup_s
#-------------------------------------------------------
def rolleStudent(self, template_spl, data_opl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(data_o = data_opl)
return markup_s
#-------------------------------------------------------
def rolleModul(self, template_spl, dat, modul):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(data_o = dat, data_modul = modul)
return markup_s
#-------------------------------------------------------
def rolleStudiengang(self, template_spl, dat, mod, lehr):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(data_o = dat, data_mod = mod, data_lehr = lehr)
return markup_s
#-------------------------------------------------------
def createModul(self, id_spl, data_opl, template_spl):
#-------------------------------------------------------
markup_s =''
template_o = self.lookup_o.get_template(template_spl)
markupV_s = template_o.render()
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (bezeichnungModul=data_opl[0]
, beschreibungModul=data_opl[1]
, anzahlCredits=data_opl[2]
, anzahlVorlesung=data_opl[3]
, anzahlUebung=data_opl[4]
, anzahlPraktika=data_opl[5]
, voraussetzungen=data_opl[6]
, modulVerantwortlicher=data_opl[7]
, studiengangKurzbezeichnung=data_opl[8]
, studiengangID=id_spl
)
return markup_s
#-------------------------------------------------------
def createStudiengang(self, id_spl, data_opl, template_spl):
#-------------------------------------------------------
markup_s =''
template_o = self.lookup_o.get_template(template_spl)
markupV_s = template_o.render()
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (bezeichnungStudiengang=data_opl[0]
, kurzbezeichnungStudiengang=data_opl[1]
, beschreibungStudiengang=data_opl[2]
, semesteranzahlStudiengang=data_opl[3]
, id_s=id_spl
)
return markup_s
#-------------------------------------------------------
def showStudiengang(self, id_spl, data_opl, data_opl2, data_opl3, template_spl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(id_s = id_spl, data_o = data_opl, data_mod = data_opl2, data_lehr = data_opl3)
return markup_s
#-------------------------------------------------------
def createLehrveranstaltung(self, id_spl, data_opl, template_spl):
#-------------------------------------------------------
markup_s =''
template_o = self.lookup_o.get_template(template_spl)
markupV_s = template_o.render()
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (bezeichnungLehrveranstaltung=data_opl[0]
, beschreibungLehrveranstaltung=data_opl[1]
, lageLehrveranstaltung=data_opl[2]
, modulLehrveranstaltung=data_opl[3]
, studiengangKurzbezeichnung=data_opl[4]
, id_s=id_spl
)
return markup_s
#-------------------------------------------------------
def createModulhandbuch(self, id_spl, data_opl, data_opl2, data_opl3, template_spl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(id_stg = id_spl, data_o = data_opl, data_l = data_opl2, data_m = data_opl3)
return markup_s
#-------------------------------------------------------
def showModulhandbuch(self, id_spl, data_opl, data_opl2, template_spl):
#-------------------------------------------------------
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(id_s = id_spl, data_o = data_opl, data_mod = data_opl2)
return markup_s
#-------------------------------------------------------
def readFile_p(self, fileName_spl):
#-------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('templates', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/formStudiengang.tpl.py
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1513169886.1454463
_enable_loop = True
_template_filename = '/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formStudiengang.tpl'
_template_uri = 'formStudiengang.tpl'
_source_encoding = 'utf-8'
_exports = ['header']
def _mako_get_namespace(context, name):
try:
return context.namespaces[(__name__, name)]
except KeyError:
_mako_generate_namespaces(context)
return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
pass
def _mako_inherit(template, context):
_mako_generate_namespaces(context)
return runtime._inherit_from(context, 'layout.tpl', _template_uri)
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
id_s = context.get('id_s', UNDEFINED)
data_lehr = context.get('data_lehr', UNDEFINED)
data_o = context.get('data_o', UNDEFINED)
data_mod = context.get('data_mod', UNDEFINED)
def header():
return render_header(context._locals(__M_locals))
__M_writer = context.writer()
__M_writer('\r\n')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'header'):
context['self'].header(**pageargs)
__M_writer('\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_header(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
id_s = context.get('id_s', UNDEFINED)
data_lehr = context.get('data_lehr', UNDEFINED)
data_o = context.get('data_o', UNDEFINED)
data_mod = context.get('data_mod', UNDEFINED)
def header():
return render_header(context)
__M_writer = context.writer()
__M_writer('\r\n\t<body>\t\t\r\n\t\t<h1><u>Informationen zum Studiengang:</u> ')
__M_writer(str(id_s))
__M_writer('</h1>\r\n\t\t<table id="studInfos">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Bezeichnung des Studiengangs</th>\r\n\t\t\t\t<th>Kurzbezeichnung des Studiengangs</th>\r\n\t\t\t\t<th>Beschreibung des Studiengangs</th>\r\n\t\t\t\t<th>Anzahl der Semester des Studiengangs</th>\r\n\t\t\t\t<tr>\r\n')
for a in data_o.values():
if a[1] == id_s:
__M_writer('\t\t\t\t\t\t\t\t<td>')
__M_writer(str(a[0]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t\t<td>')
__M_writer(str(a[1]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t\t<td>')
__M_writer(str(a[2]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t\t<td>')
__M_writer(str(a[3]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t\t</tr>\r\n')
__M_writer('\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<h1><u>Modulhandbuch:</u> ')
__M_writer(str(id_s))
__M_writer('</h1>\r\n\t\t<table id="modInfos">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Bezeichnung</th>\r\n\t\t\t\t<th>Beschreibung</th>\r\n\t\t\t\t<th>Kreditpunkte</th>\r\n\t\t\t\t<th>Anzahl Vorlesung</th>\r\n\t\t\t\t<th>Anzahl Übung</th>\r\n\t\t\t\t<th>Anzahl Praktikum</th>\r\n\t\t\t\t<th>Voraussetzungen</th>\r\n\t\t\t\t<th>Modulverantwortlicher</th>\r\n\t\t\t\t<tr>\r\n')
for b in data_mod.values():
if b[8] == id_s:
__M_writer('\t\t\t\t\t\t\t<td>')
__M_writer(str(b[0]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[1]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[2]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[3]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[4]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[5]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[6]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(b[7]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t</tr>\r\n')
__M_writer('\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<h1><u>Lehrveranstaltungen:</u> ')
__M_writer(str(id_s))
__M_writer('</h1>\r\n\t\t<table id="modInfos">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Bezeichnung</th>\r\n\t\t\t\t<th>Kurzbezeichnung</th>\r\n\t\t\t\t<th>Lage (Semester)</th>\r\n\t\t\t\t<th>Modul</th>\r\n\t\t\t\t<tr>\r\n')
for c in data_lehr.values():
if c[4] == id_s:
__M_writer('\t\t\t\t\t\t\t<td>')
__M_writer(str(c[0]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(c[1]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(c[2]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t<td>')
__M_writer(str(c[3]))
__M_writer('</td>\r\n\t\t\t\t\t\t\t</tr>\r\n')
__M_writer('\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<div>\r\n\t\t\t<p />\r\n\t\t\t<input type="reset" value="Logout" onclick="location.href = \'/\'"/><p />\r\n\t\t\t<button onclick="goBack()">Go Back</button>\r\n\t\t</div>\r\n\t\t<script>\r\n\t\tfunction goBack() {\r\n\t\t\twindow.history.back();\r\n\t\t}\r\n\t\t</script>\r\n\t</body>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"uri": "formStudiengang.tpl", "line_map": {"27": 0, "38": 2, "43": 81, "49": 3, "59": 3, "60": 5, "61": 5, "62": 13, "63": 14, "64": 15, "65": 15, "66": 15, "67": 16, "68": 16, "69": 17, "70": 17, "71": 18, "72": 18, "73": 22, "74": 24, "75": 24, "76": 36, "77": 37, "78": 38, "79": 38, "80": 38, "81": 39, "82": 39, "83": 40, "84": 40, "85": 41, "86": 41, "87": 42, "88": 42, "89": 43, "90": 43, "91": 44, "92": 44, "93": 45, "94": 45, "95": 49, "96": 51, "97": 51, "98": 59, "99": 60, "100": 61, "101": 61, "102": 61, "103": 62, "104": 62, "105": 63, "106": 63, "107": 64, "108": 64, "109": 68, "115": 109}, "filename": "/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formStudiengang.tpl", "source_encoding": "utf-8"}
__M_END_METADATA
"""
<file_sep>/WEB/p4_sicherung3/templates/detail_show.tpl.html
<!-- Template -->
<!-- Contentbereich -->
<form id="topicsData">
<h2>@if context!=null@ #context['Bezeichnung']# @endif@</h2>
<div>
<h2>@if context!=null@ #context['Titel']# @endif@</h2>
<h6>erstellt am: @if context!=null@ #context['Datum_Erstellung']# @endif@</h6>
<h6>geändert am: @if context!=null@ #context['Datum_Aenderung']# @endif@</h6>
</div>
<div>
<textarea id="Text" disabled cols="200" rows="10">@if context!=null@ #context['Text']# @endif@</textarea>
</div>
<div>
<textarea id="Kategorien" disabled cols="200" rows="5">@if context!=null@ #context['Kategorien']# @endif@</textarea>
</div>
<button id="idBack">Zurück</button>
<button id="topicbearbeiten" @if context!=null@ data-id="#context['id']#" @endif@">Bearbeiten</button>
</form>
<!-- EOF --><file_sep>/p1/webteams/doc/webteams.md
#Gruppeneinteilung#
Praktikumsgruppe - H
1. <NAME> 1008751
2. <NAME> 960310
Stand: 22.11.2017
#Aufbau der Webanwedung#

#Durchgeführte Ergänzungen#
Änderungen
-------------
application.py
Hinzufügen der Semesteranzahl
Zeile 50
Zeile 54
database.py
Hinzufügen von Platzhalter für Semester
Zeile 78
Zeile 89
Löschen-Funktion
Zeile 71-73
view.py
Hinzufügen von Semester in CreateList, sowie änderung der Arrayelemente
Zeile 38
Zeile 42
Hinzufügen von Semester in CreateForm, sowie änderung der Arrayelemente
Zeile 59
Zeile 63
form1.tpl
Hinzufügen der Semesteranzahl
Zeile 19-22
form2.tpl
Hinzufügen Abbrechen-Button
Zeile 4
list0.tpl
Hinzufügen der Semesteranzahl
Zeile 19
Zeile 23
list1.tpl
Hinzufügen der Semesteranzahl
Zeile 7
Zeile 11
webteams.css
Alles
webteams.js
Zeile 5 - 8 Abfrage löschen
#Beschreibung des HTTP-Datenverkehrs#
##beim Start der Anwendung##

##Beim speichern der Formular-Daten##

<file_sep>/WEB/WEB Praktika/pl/templates/congratstempimport.tpl.html
<!-- Template -->
<!-- Contentbereich -->
<h3>Wählen sie eine Vorlage zum importieren aus und geben sie eine Beschreibung an!</h3>
<table>
@var entry_a;@
@var loop_i;@
@for loop_i = 0; loop_i < context.length; loop_i++@
@entry_a = context[loop_i];@
<tr id="#entry_a#">
<td>#entry_a#</td>
</tr>
@endfor@
</table>
<form id="beschreibungsdaten">
<input type="text" name=Beschreibung id=Beschreibung>
</form>
<button id="importEntry">Anzeigen</button>
<!-- EOF --><file_sep>/WEB/WEB Praktika/mhb/app/database.py
# coding: UTF-8
import os
import os.path
import codecs
import json
import datetime
from cherrypy import log
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
def __init__(self):
#Datenmodell instanziieren
self.data_o = None
self.readData_p()
def delete_px(self, id):
for value in self.data_o:
if int(id) == int(value['id']):
self.data_o.remove(value)
self.saveData_p()
return str(id)
# Datensatz nach dem letzten Element hinzufügen
def update_px(self, id, data_opl):
# format for curl
if type(data_opl['tag'] is str):
data_opl['tag'] = data_opl['tag'].replace('[', '')
data_opl['tag'] = data_opl['tag'].replace(']', '')
data_opl['tag'] = data_opl['tag'].replace('\'', '')
data_opl['tag'] = data_opl['tag'].split(', ')
#datum
now = datetime.datetime.now()
currentDate = now.strftime("%d.%m.%Y")
for value in self.data_o:
if int(id) == int(value['id']):
value['title'] = data_opl['title']
value['chdat'] = currentDate
value['change'] = int(value['change']) + 1
value['tag'] = data_opl['tag']
self.saveData_p()
return str(data_opl['id'])
# Datensatz nach dem letzten Element hinzufügen
def create_px(self, data_opl):
# format for curl
if type(data_opl['tag'] is str):
data_opl['tag'] = data_opl['tag'].replace('[', '')
data_opl['tag'] = data_opl['tag'].replace(']', '')
data_opl['tag'] = data_opl['tag'].replace('\'', '')
data_opl['tag'] = data_opl['tag'].split(',')
id_s = len(self.data_o)
#datum
now = datetime.datetime.now()
currentDate = now.strftime("%d.%m.%Y")
data_add = {}
data_add['id'] = id_s
data_add['title'] = data_opl['title']
data_add['crdat'] = currentDate
data_add['chdat'] = currentDate
data_add['change'] = 0
data_add['tag'] = data_opl['tag']
self.data_o.append(data_add)
self.saveData_p()
return str(id_s)
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
self.readData_p()
if id_spl == None:
return self.data_o
else:
# else: return article with id
for value in self.data_o:
if int(id_spl) == int(value['id']):
return value
return -1
def readData_p(self):
try:
fp_o = codecs.open(os.path.join('data', 'artikel.json'), 'r', 'utf-8')
except:
# Bei Exception Datei neu anlegen
self.data_o = {}
self.data_o[0] = ['', '', '']
self.saveData_p()
else:
with fp_o:
self.data_o = json.load(fp_o)
return
def saveData_p(self):
with codecs.open(os.path.join('data', 'artikel.json'), 'w', 'utf-8') as fp_o:
json.dump(self.data_o, fp_o)
# EOF
<file_sep>/Mattes/lit-x/static/js/app.js
// ----------------------------------------------
// Beispiel lit-x
// app.js
// ----------------------------------------------
// Verwendung von jquery, Single-Page / Ajax, Event-Service
// REST-Interface
// ----------------------------------------------
'use strict'
// ----------------------------------------------
// Namensraum einrichten
// ----------------------------------------------
let APP = {};
// ----------------------------------------------
APP.Application_cl = class {
// ----------------------------------------------
constructor () {
this.content_o = null; // das jeweils aktuelle Objekt im Contentbereich
this.nav_o = new APP.Nav_cl();
this.listSources_o = new APP.ListView_cl('source', '/source/', 'sourceslist.tpl');
this.detailSources_o = new APP.SourceDetailView_cl('source', '/source/', 'sourcedetail.tpl');
this.listEvaluated_o = new APP.ListView_cl('evaluated', '/evaluated/', 'evaluatedlist.tpl');
this.detailEvaluated_o = new APP.DetailView_cl('evaluated', '/evaluated/', 'evaluateddetail.tpl');
// Registrierungen
APP.es_o.subscribe_px(this, 'app');
}
notify_px (self_opl, message_spl, data_apl) {
switch (message_spl) {
case 'app':
switch (data_apl[0]) {
case 'init':
APP.tm_o = new TemplateManager_cl();
break;
case 'templates.loaded':
self_opl.nav_o.render_px();
// Liste Quellen im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.listSources_o, data_apl[1]);
break;
case 'source':
// Liste Quellen im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.listSources_o, data_apl[1]);
break;
case 'source.add':
// (leeres) Detailformular im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.detailSources_o, data_apl[1]);
break;
case 'source.edit':
// Detailformular im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.detailSources_o, data_apl[1]);
break;
case 'evaluated':
// Liste Quellen im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.listEvaluated_o, data_apl[1]);
break;
case 'evaluated.add':
// (leeres) Detailformular im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.detailEvaluated_o, data_apl[1]);
break;
case 'evaluated.edit':
// Detailformular im Content-Bereich anzeigen
self_opl.setContent_p(self_opl.detailEvaluated_o, data_apl[1]);
break;
default:
console.warn('[Application_cl] unbekannte app-Notification: '+data_apl[0]);
break;
}
break;
default:
console.warn('[Application_cl] unbekannte Notification: '+message_spl);
break;
}
}
setContent_p (newContent_opl, data_opl) {
if (this.content_o != null) {
if (this.content_o === newContent_opl) { // Achtung: Vergleich auf Identität (===) und nicht nur auf Gleichheit (==)
// wird bereits angezeigt, keine Änderung
} else {
if (this.content_o.canClose_px()) {
this.content_o.close_px();
this.content_o = newContent_opl;
this.content_o.render_px(data_opl);
}
}
} else {
this.content_o = newContent_opl;
this.content_o.render_px(data_opl);
}
}
}
// ----------------------------------------------
$(document).ready(function(){
// ----------------------------------------------
// wird ausgeführt, wenn das Dokument vollständig geladen wurde
APP.es_o = new EventService_cl();
APP.app_o = new APP.Application_cl();
APP.es_o.publish_px('app', ['init', null]);
});
// EOF<file_sep>/Mattes/4/static/js/app.js
// ----------------------------------------------
// Bug-Tracker
// <NAME>, 1018387
// app.js
// ----------------------------------------------
'use strict'
let APP = {};
// ----------------------------------------------
APP.Application_cl = class {
// ----------------------------------------------
constructor() {
this.content_o = null; // das jeweils aktuelle Objekt im Contentbereich
this.nav_o = new APP.Nav_cl();
this.listProjekt_o = new APP.ListView_cl('projekt', '/projekt/', 'projektlist.tpl');
this.detailProjekt_o = new APP.DetailView_cl('projekt', '/projekt/', 'projektdetail.tpl');
this.listKomponente_o = new APP.ListView_cl('komponente', '/komponente/', 'komponentelist.tpl');
this.detailKomponente_o = new APP.DetailView_cl('komponente', '/komponente/', 'komponentedetail.tpl');
this.listQSMitarbeiter_o = new APP.ListView_cl('qsmitarbeiter', '/qsmitarbeiter/', 'mitarbeiterlist.tpl');
this.detailQSMitarbeiter_o = new APP.DetailView_cl('qsmitarbeiter', '/qsmitarbeiter/', 'mitarbeiterdetail.tpl');
this.listSWEntwickler_o = new APP.ListView_cl('swentwickler', '/swentwickler/', 'mitarbeiterlist.tpl');
this.detailSWEntwickler_o = new APP.DetailView_cl('swentwickler', '/swentwickler/', 'mitarbeiterdetail.tpl');
this.listKatFehler_o = new APP.ListView_cl('katfehler', '/katfehler/', 'katlist.tpl');
this.detailKatFehler_o = new APP.DetailView_cl('katfehler', '/katfehler/', 'katdetail.tpl');
this.listKatUrsache_o = new APP.ListView_cl('katursache', '/katursache/', 'katlist.tpl');
this.detailKatUrsache_o = new APP.DetailView_cl('katursache', '/katursache/', 'katdetail.tpl');
this.listFehler_o = new APP.FehlerListView_cl('fehler', '/fehler/', 'fehlerlist.tpl');
this.listFehlerBehoben_o = new APP.ListView_cl('fehler', '/fehler/behoben', 'fehlerbehobenlist.tpl');
this.listFehlerErkannt_o = new APP.ErkanntListView_cl('fehler', '/fehler/erkannt', 'fehlererkanntlist.tpl');
this.detailFehlerErfassen_o = new APP.DetailView_cl('fehler', '/fehler/', 'fehlererfassen.tpl');
this.detailSWEZuweisen_o = new APP.DetailView_cl('fehler', '/fehler/', 'entwicklerzuweisen.tpl');
this.detailLösungErfassen_o = new APP.DetailView_cl('fehler', '/fehler/', 'lösungerfassen.tpl');
this.detailLösungFreigeben_o = new APP.PatchDetailView_cl('fehler', '/fehler/', 'lösungfreigeben.tpl');
this.listProAuswertung_o = new APP.ProAuswertungListView_cl('prolist', '/prolist/','projektauswertung.tpl');
this.listKatAuswertung_o = new APP.KatAuswertungListView_cl('katlist', '/katlist/','kategorieauswertung.tpl');
this.menuMitarbeiter_o = new APP.MenuView_cl(JSON.parse('{"qsmitarbeiter": "QSMitarbiter", "swentwickler": "SWEntwickler"}'), 'menu.tpl');
this.menuKategorien_o = new APP.MenuView_cl(JSON.parse('{"katfehler": "FehlerKategorie", "katursache": "Ursachenkategorie"}'), 'menu.tpl');
// Registrierungen
APP.es_o.subscribe_px(this, 'app');
}
notify_px(self_opl, message_spl, data_apl) {
switch (message_spl) {
case 'app':
switch (data_apl[0]) {
case 'init':
APP.tm_o = new TemplateManager_cl();
break;
case 'templates.loaded':
self_opl.nav_o.render_px();
break;
//Fehler
case 'fehler':
self_opl.setContent_p(self_opl.listFehler_o, data_apl[1]);
break;
case 'fehler.behoben':
self_opl.setContent_p(self_opl.listFehlerBehoben_o, data_apl[1]);
break;
case 'fehler.erkannt':
self_opl.setContent_p(self_opl.listFehlerErkannt_o, data_apl[1]);
break;
case 'fehler.erfassen':
self_opl.setContent_p(self_opl.detailFehlerErfassen_o, data_apl[1]);
break;
case 'fehler.zuweisen':
self_opl.setContent_p(self_opl.detailSWEZuweisen_o, data_apl[1]);
break;
case 'fehler.fix':
self_opl.setContent_p(self_opl.detailLösungErfassen_o, data_apl[1]);
break;
case 'fehler.patch':
self_opl.setContent_p(self_opl.detailLösungFreigeben_o, data_apl[1]);
break;
//Auswertung
case 'prolist':
self_opl.setContent_p(self_opl.listProAuswertung_o, data_apl[1]);
break;
case 'katlist':
self_opl.setContent_p(self_opl.listKatAuswertung_o, data_apl[1]);
break;
//Projekte
case 'projekt':
self_opl.setContent_p(self_opl.listProjekt_o, data_apl[1]);
break;
case 'projekt.add':
self_opl.setContent_p(self_opl.detailProjekt_o, data_apl[1]);
break;
case 'projekt.edit':
self_opl.setContent_p(self_opl.detailProjekt_o, data_apl[1]);
break;
case 'komponente':
self_opl.setContent_p(self_opl.listKomponente_o, data_apl[1]);
break;
case 'komponente.add':
self_opl.setContent_p(self_opl.detailKomponente_o, data_apl[1]);
break;
case 'komponente.edit':
self_opl.setContent_p(self_opl.detailKomponente_o, data_apl[1]);
break;
//Mitarbeiter
case 'mitarbeiter':
self_opl.setContent_p(self_opl.menuMitarbeiter_o, data_apl[1]);
break;
case 'qsmitarbeiter':
self_opl.setContent_p(self_opl.listQSMitarbeiter_o, data_apl[1]);
break;
case 'qsmitarbeiter.add':
self_opl.setContent_p(self_opl.detailQSMitarbeiter_o, data_apl[1]);
break;
case 'qsmitarbeiter.edit':
self_opl.setContent_p(self_opl.detailQSMitarbeiter_o, data_apl[1]);
break;
case 'swentwickler':
self_opl.setContent_p(self_opl.listSWEntwickler_o, data_apl[1]);
break;
case 'swentwickler.add':
self_opl.setContent_p(self_opl.detailSWEntwickler_o, data_apl[1]);
break;
case 'swentwickler.edit':
self_opl.setContent_p(self_opl.detailSWEntwickler_o, data_apl[1]);
break;
//Kategorie
case 'kategorien':
self_opl.setContent_p(self_opl.menuKategorien_o, data_apl[1]);
break;
case 'katfehler':
self_opl.setContent_p(self_opl.listKatFehler_o, data_apl[1]);
break;
case 'katfehler.add':
self_opl.setContent_p(self_opl.detailKatFehler_o, data_apl[1]);
break;
case 'katfehler.edit':
self_opl.setContent_p(self_opl.detailKatFehler_o, data_apl[1]);
break;
case 'katursache':
self_opl.setContent_p(self_opl.listKatUrsache_o, data_apl[1]);
break;
case 'katursache.add':
self_opl.setContent_p(self_opl.detailKatUrsache_o, data_apl[1]);
break;
case 'katursache.edit':
self_opl.setContent_p(self_opl.detailKatUrsache_o, data_apl[1]);
break;
//---------------------------------------------------
default:
console.warn('[Application_cl] unbekannte app-Notification: ' + data_apl[0]);
break;
}
break;
default:
console.warn('[Application_cl] unbekannte Notification: ' + message_spl);
break;
}
}
setContent_p(newContent_opl, data_opl) {
if (this.content_o != null) {
if (this.content_o === newContent_opl) {
//Keine Änderung
} else {
if (this.content_o.canClose_px()) {
this.content_o.close_px();
this.content_o = newContent_opl;
this.content_o.render_px(data_opl);
}
}
} else {
this.content_o = newContent_opl;
this.content_o.render_px(data_opl);
}
}
}
// ----------------------------------------------
$(document).ready(function () {
// ----------------------------------------------
APP.es_o = new EventService_cl();
APP.app_o = new APP.Application_cl();
APP.es_o.publish_px('app', ['init', null]);
});
// EOF<file_sep>/Mattes/3/app/application.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung k�nnen hier eingetragen werden
self.view = ['student'
,'lehrende'
,'firma'
,'ppangebot']
self.db_o = Database_cl()
self.view_o = View_cl()
@cherrypy.expose
#-------------------------------------------------------
def index(self):
#-------------------------------------------------------
return self.view_o.CreateIndex_px()
@cherrypy.expose
#-------------------------------------------------------
def deleteRow(self, ansicht, id_s):
#-------------------------------------------------------
ansicht = int(ansicht)
self.db_o.deleteRow(ansicht, id_s)
data_o = self.db_o.ReadData()
data_o = data_o[self.view[ansicht]]['list']
return self.view_o.CreateList_px(data_o, ansicht)
@cherrypy.expose
#-------------------------------------------------------
def addRow(self, ansicht, data_s):
#-------------------------------------------------------
ansicht = int(ansicht)
self.db_o.addRow(ansicht, data_s)
return self.CreateList(ansicht)
@cherrypy.expose
#-------------------------------------------------------
def updateRow(self, ansicht, id_s, data_s):
#-------------------------------------------------------
ansicht = int(ansicht)
self.db_o.updateRow(ansicht, id_s, data_s)
if ansicht == 4:
self.db_o.pushPPA(id_s)
return self.CreateList(ansicht)
@cherrypy.expose
#-------------------------------------------------------
def checkID(self, ansicht, id_s):
#-------------------------------------------------------
ansicht = int(ansicht)
data_o = self.db_o.ReadData()
if ansicht == 0:
key = 'matrikelid'
elif ansicht == 1:
key = 'lehrendenid'
elif ansicht == 3:
key = 'firmaid'
elif ansicht == 4:
key = 'matrikelid'
else:
return "1"
for dct in data_o['ppaktuell']['list']:
if dct[key] == id_s:
return "1"
for dct in data_o['ppabgeschlossen']['list']:
if dct[key] == id_s:
return "1"
return "0"
@cherrypy.expose
#-------------------------------------------------------
def CreateList(self, ansicht):
#-------------------------------------------------------
ansicht = int(ansicht)
data_o = self.db_o.ReadData()
if ansicht > 3:
ppangebot = data_o['ppangebot']['list']
ppaktuell = data_o['ppaktuell']['list']
ppabgeschlossen = data_o['ppabgeschlossen']['list']
ppaktuell.sort(key=lambda x: x['anfangsdatum'])
ppabgeschlossen.sort(key=lambda x: x['anfangsdatum'])
if ansicht == 4:
for key in ppangebot:
ppangebot[key].update(data_o['firma']['list'][ppangebot[key]['firmaid']])
for key in range(0, len(ppaktuell)):
ppaktuell[key].update(data_o['firma']['list'][ppaktuell[key]['firmaid']])
for key in range(0, len(ppabgeschlossen)):
ppabgeschlossen[key].update(data_o['firma']['list'][ppabgeschlossen[key]['firmaid']])
elif ansicht == 5:
for key in range(0, len(ppaktuell)):
ppaktuell[key].update(data_o['student']['list'][ppaktuell[key]['matrikelid']])
for key in range(0, len(ppabgeschlossen)):
ppabgeschlossen[key].update(data_o['student']['list'][ppabgeschlossen[key]['matrikelid']])
elif ansicht == 6:
for key in range(0, len(ppaktuell)):
ppaktuell[key].update(data_o['lehrende']['list'][ppaktuell[key]['lehrendenid']])
for key in range(0, len(ppabgeschlossen)):
ppabgeschlossen[key].update(data_o['lehrende']['list'][ppabgeschlossen[key]['lehrendenid']])
data_o['ppangebot']['list'] = ppangebot
data_o['ppaktuell']['list'] = ppaktuell
data_o['ppabgeschlossen']['list'] = ppabgeschlossen
else:
data_o = data_o[self.view[ansicht]]['list']
return self.view_o.CreateList_px(data_o, ansicht)
@cherrypy.expose
#-------------------------------------------------------
def CreateForm(self, ansicht, id_s = ""):
#-------------------------------------------------------
data_o = self.db_o.ReadData()
ansicht = int(ansicht)
if id_s == "":
data_opl = self.db_o.GetDefault(ansicht)
id_s = ' '
else:
data_opl = self.db_o.getRow(ansicht, id_s)
return self.view_o.CreateForm_px(data_opl, data_o, ansicht, id_s)
# EOF
<file_sep>/p2/bmf/app/view.py
# coding: utf-8
# sehr einfache Erzeugung des Markups für vollständige Seiten
# jeweils 3 Abschnitte:
# - begin
# - content
# - end
# bei der Liste wird der content-Abschnitt wiederholt
# beim Formular nicht
import codecs
import os.path
import string
from .Erstellen import Mitarbeiter
from mako.template import Template
from mako.lookup import TemplateLookup
#--------------------------------------------------------
class View_cl(object):
#---------------------------------------------------------
#------------------------------------------------------
def __init__(self, path_spl):
#------------------------------------------------------
self.path_s = os.path.join(path_spl, "template")
self.lookup_o = TemplateLookup(directories=self.path_s)
#------------------------------------------------------
def create_p(self, template_spl, data_opl):
template_o = self.lookup_o.get_template(template_spl)
markup_s = template_o.render(data_o = data_opl)
return markup_s
def createMitarbeiter_E(self, data_opl):
markup_s = ''
markup_s += self.readFile_p('list0.tpl')
markupV_s = self.readFile_p('list1.tpl')
lineT_o = string.Template(markupV_s)
# mehrfach nutzen, um die einzelnen Zeilen der Tabelle zu erzeugen
for id_s in data_opl:
data_a = data_opl[str(id_s)]
markup_s += lineT_o.safe_substitute (name=data_a[0] # HIER müssen Sie eine Ergänzung vornehmen - erl
, vorname=data_a[1]
, akagra=data_a[2]
, taetigkeit=data_a[3]
)
markup_s += self.readFile_p('list2.tpl')
return self.create_p('liste.tpl', data_opl) #markup_s
def createList_px(self, data_opl): #createMitarbeiter_e
#------------------------------------------------------
# hier müsste noch eine Fehlerbehandlung ergänzt werden !
markup_s = ''
markup_s += self.readFile_p('list0.tpl')
markupV_s = self.readFile_p('list1.tpl')
lineT_o = string.Template(markupV_s)
# mehrfach nutzen, um die einzelnen Zeilen der Tabelle zu erzeugen
for id_s in data_opl:
data_a = data_opl[str(id_s)]
markup_s += lineT_o.safe_substitute (name_s=data_a[0] # HIER müssen Sie eine Ergänzung vornehmen - erl
, vorname_s=data_a[1]
, akadem_s=data_a[2]
, taetigkeit_s=data_a[3]
)
markup_s += self.readFile_p('list2.tpl')
return self.create_p('liste.tpl', data_opl) #markup_s
#------------------------------------------------------
def createForm_px(self, id_spl, data_opl):
#------------------------------------------------------
# hier müsste noch eine Fehlerbehandlung ergänzt werden !
markup_s = ''
markup_s += self.readFile_p('form0.tpl')
markupV_s = self.readFile_p('form1.tpl')
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (name1_s=data_opl[0] # HIER müssen Sie eine Ergänzung vornehmen - erl
, vorname1_s=data_opl[1]
, matrnr1_s=data_opl[2]
, sem1_s=data_opl[3]
, name2_s=data_opl[4]
, vorname2_s=data_opl[5]
, matrnr2_s=data_opl[6]
, sem2_s=data_opl[7]
, id_s=id_spl
)
markup_s += self.readFile_p('form2.tpl')
return markup_s
#------------------------------------------------------
def readFile_p(self, fileName_spl):
#------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('content', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF
<file_sep>/WEB/Vorlesung/domiterator/domiterator.js
// Konstruktor
// Parameter : DOM-Knoten, der als Ausgangspunkt dient
function DOMIterator (Root) {
this.Root = Root; // speichert Ausgangspunkt
this.Node = this.Root; // der aktuelle Knoten
this.Level = 0; // die aktuelle Tiefe
this.Dir = 0; // dient der Steuerung
this.Show = false; // dient der Steuerung
// Zugriff auf den ersten Knoten
this.First = function () {
this.Node = this.Root;
this.Level = 0;
this.Dir = 0;
this.Show = false;
return this.Node;
}
// Zugriff auf den naechsten Knoten
this.Next = function () {
while (this.Node != null) {
if (this.Show) {
this.Show = false;
break;
}
switch (this.Dir) {
case 0:
if (this.Node.firstChild != null) {
this.Node = this.Node.firstChild;
this.Show = true;
this.Level++;
} else {
this.Dir = 1;
}
break;
case 1:
if (this.Node === this.Root) {
// Ausgangspunkt erreicht
this.Node = null;
} else {
if (this.Node.nextSibling != null) {
this.Node = this.Node.nextSibling;
this.Dir = 0;
this.Show = true;
} else {
this.Dir = 2;
}
}
break;
case 2:
if (this.Node === this.Root) {
// Ausgangspunkt erreicht
this.Node = null;
} else {
this.Node = this.Node.parentNode;
if (this.Node === this.Root) {
// Ausgangspunkt erreicht
this.Node = null;
}
this.Level--;
}
this.Dir = 1;
break;
}
}
return this.Node;
}
}
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/loginLehrende.tpl.py
# -*- coding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1515084089.4438145
_enable_loop = True
_template_filename = '/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/loginLehrende.tpl'
_template_uri = 'loginLehrende.tpl'
_source_encoding = 'ascii'
_exports = []
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
__M_writer('<div id="loginL">\r\n\t<form id="loginL" action="" method="POST">\r\n\t\t<input type="text" id="username" name="username" value="" required />\r\n\t\t<input type="password" id="password" name="password" value="" required />\r\n\t\t<button onclick="loadDocLoginL()">Login</button>\r\n\t</form>\r\n</div>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"filename": "/mnt/607B-88B7/nextCloud/Frika/3. Semester/WEB/Praktikum/Praktikum3/mhb/templates/loginLehrende.tpl", "uri": "loginLehrende.tpl", "line_map": {"16": 0, "27": 21, "21": 1}, "source_encoding": "ascii"}
__M_END_METADATA
"""
<file_sep>/WEB/Vorlesung/javascript_beispiele/strict1.js
function Person_cl (name_spl) {
// Eigenschaften anlegen
this.name_s = name_spl;
}
// normale Verwendung als Konstruktor
var person1_o = new Person_cl("Mustermann1");
// name_s ist wie erwartet die Eigenschaft des erzeugten Objekts
console.log(person1_o.name_s);
// versehentliche Verwendung ohne den new-Operator
var person2_o = Person_cl("Mustermann2");
// name_s ist KEINE Eigenschaft des erzeugten Objekts
// person2_o erhält return-Wert der Funktion, diese liefert aber
// keinen return-Wert zurück, d.h. person2_o erhält
// den Wert undefined
try {
console.log(person2_o.name_s);
}
catch (error_o) {
console.warn("Zugriff nicht möglich!");
}
// Was gibt es stattdessen: eine Eigenschaft im global-Object!
console.log(name_s);
name_s = 'xyz';
console.log(name_s);
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/app/application.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
userrole = ""
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung können hier eingetragen werden
self.db_o = Database_cl()
self.view_o = View_cl()
@cherrypy.expose
#-------------------------------------------------------
def index(self):
#-------------------------------------------------------
return self.view_o.loginfunc("loginStudierende.tpl")
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def login(self, **data_opl):
#-------------------------------------------------------
dat = data_opl["username"]
if(dat.find("@stud.<EMAIL>") == -1):
return self.view_o.loginfuncLehrender("loginLehrende.tpl")
else:
return self.student()
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def studiengang(self, id):
#-------------------------------------------------------
data_o = self.db_o.readData_Studiengang()
data_mod = self.db_o.readData_Modul()
data_lehr = self.db_o.readData_Lehrveranstaltung()
for i in data_o.values():
if(i[1] == id):
return self.view_o.showStudiengang(id, data_o, data_mod, data_lehr, "formStudiengang.tpl")
return self.error()
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def editStudiengang(self, id):
#-------------------------------------------------------
return self.createStudiengang(id)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def editModul(self, id):
#-------------------------------------------------------
return self.createModul(id)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def editLehrveranstaltung(self, id):
#-------------------------------------------------------
return self.createLehrveranstaltung(id)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def deleteStudiengang(self, id):
#-------------------------------------------------------
self.db_o.delete_Studiengang(id)
return self.lehr()
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def deleteModul(self, id):
#-------------------------------------------------------
self.db_o.delete_Modul(id)
return self.lehr()
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def deleteLehrveranstaltung(self, id):
#-------------------------------------------------------
self.db_o.delete_Lehrveranstaltung(id)
return self.lehr()
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def error(self):
#-------------------------------------------------------
return self.view_o.error("formError.tpl")
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def loginL(self, **data_opl):
#-------------------------------------------------------
global userrole
name = data_opl["username"]
pw = data_opl["password"]
user = self.db_o.read_rolle(name)
if(name == user[0] and pw == user[1]):
if(user[2] == "mod"):
userrole = "Bernd"
return self.modul()
else:
return self.lehr()
else:
return self.view_o.loginfunc("loginStudierende.tpl")
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def student(self, **data_opl):
#-------------------------------------------------------
# self.db_o.readData_p("studiengang.json")
dat = self.db_o.data_o
return self.view_o.rolleStudent("formStudierender.tpl", dat)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def lehr(self, **data_opl):
#-------------------------------------------------------
# self.db_o.readData_p('studiengang.json')
dat = self.db_o.data_o
# self.db_o.readData_p('modul.json')
mod = self.db_o.data_m
lehr = self.db_o.data_l
return self.view_o.rolleStudiengang("formVerantwortlicherStudiengang.tpl", dat, mod, lehr)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def modul(self, **data_opl):
#-------------------------------------------------------
# self.db_o.readData_p('studiengang.json')
dat = self.db_o.data_o
# self.db_o.readData_p('modul.json')
modul = self.db_o.data_m
return self.view_o.rolleModul("formVerantwortlicherModul.tpl", dat, modul)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def createModul(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
dat_m = self.db_o.readData_Modul_single(id_spl)
else:
dat_m = self.db_o.getEmptyModul()
return self.view_o.createModul(id_spl, dat_m, "formCreateModul.tpl")
@cherrypy.expose
#-------------------------------------------------------
def createStudiengang(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
data_o = self.db_o.readData_Studiengang_single(id_spl)
else:
data_o = self.db_o.getEmptyStudiengang()
return self.view_o.createStudiengang(id_spl, data_o, "formCreateStudiengang.tpl")
@cherrypy.expose
#-------------------------------------------------------
def createLehrveranstaltung(self, id_spl = None):
#-------------------------------------------------------
if id_spl != None:
data_l = self.db_o.readData_Lehrveranstaltung_single(id_spl)
else:
data_l = self.db_o.getEmptyLehrveranstaltung()
return self.view_o.createLehrveranstaltung(id_spl, data_l, "formCreateLehrveranstaltung.tpl")
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def saveStudiengang(self, **data_opl):
#-------------------------------------------------------
id_s = data_opl["id_s"]
data_a = [ data_opl["bezeichnungStudiengang"]
, data_opl["kurzbezeichnungStudiengang"]
, data_opl["beschreibungStudiengang"]
, data_opl["semesteranzahlStudiengang"]
, []
]
if id_s != "None":
self.db_o.update_Studiengang(id_s, data_a)
else:
id_s = self.db_o.create_Studiengang(data_a)
return self.createStudiengang(id_s)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def saveLehrveranstaltung(self, **data_opl):
#-------------------------------------------------------
id_s = data_opl["id_s"]
data_l = [ data_opl["bezeichnungLehrveranstaltung"]
, data_opl["beschreibungLehrveranstaltung"]
, data_opl["lageLehrveranstaltung"]
, data_opl["modulLehrveranstaltung"]
, data_opl["studiengangKurzbezeichnung"]
, []
]
if id_s != "None":
self.db_o.update_Lehrveranstaltung(id_s, data_l)
else:
id_s = self.db_o.create_Lehrveranstaltung(data_l)
return self.createLehrveranstaltung(id_s)
#-------------------------------------------------------
@cherrypy.expose
#-------------------------------------------------------
def saveModul(self, **data_opl):
#-------------------------------------------------------
id_s = data_opl["studiengangID"]
data_z = [ data_opl["bezeichnungModul"]
, data_opl["beschreibungModul"]
, data_opl["anzahlCredits"]
, data_opl["anzahlVorlesung"]
, data_opl["anzahlUebung"]
, data_opl["anzahlPraktika"]
, data_opl["voraussetzungen"]
, data_opl["modulVerantwortlicher"]
, data_opl["studiengangKurzbezeichnung"]
]
if id_s != "None":
self.db_o.update_Modul(id_s, data_z)
else:
id_s = self.db_o.create_Modul(data_z)
return self.createModul(id_s)
# EOF
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/mhb_student.js
function studiengangAnzeige() {
var get = document.getElementById("studiengang");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie einen Studiengang an");
}
else document.location.href = "/studiengang/" + selected.toString();
}
window.onload=function(){
let e = document.getElementById('buttonstud');
e.addEventListener('click', studiengangAnzeige, false);
}
<file_sep>/WEB/WEB Praktika/pl/main_c6.js
//------------------------------------------------------------------------------
//Demonstrator es/te/tm - Variante mit ES6-Classes
//------------------------------------------------------------------------------
// hier zur Vereinfachung (!) die Klassen in einer Datei
'use strict'
class Significantbirthdays_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
this.doRender_p();
}
doRender_p (data_opl=null) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
this.configHandleEvent_p();
}
}
configHandleEvent_p () {
let el_o = document.querySelector("form");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.id == "significantbutton") {
event_opl.preventDefault();
APPETT.es_o.publish_px("app.cmd", ["significantbutton", null]);
}
}}
class Significantbirthdays2_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
var path3 = "/app/significantbirthdays/";
var form3 = document.getElementById("daten");
var data3 = new FormData(form3);
console.log(data3);
APPETT.xhr_o.request_px(path3,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, "POST", data3);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
console.info(data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "erstellung") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
var form4 = document.getElementById("vorlagenid");
var data4 = new FormData(form4);
APPETT.xhr_o.request_px("/app/congratulation/"+elx_o.id,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
//----------------------------------------------------------
var myWindow = window.open("", "MsgWindow", "width=500,height=500");
myWindow.document.write(responseText_spl);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, "POST", data4);
}
event_opl.preventDefault();
}
}}
class Congratstempl_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/congratstempl/-1/-1/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "idShowListEntryC") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["congratstempdetails", elx_o.id] );
}
event_opl.preventDefault();
} else if (event_opl.target.id == "DeleteC") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["deleteC", elx_o.id] );
}
event_opl.preventDefault();
} else if (event_opl.target.id == "ImportPath") {
APPETT.es_o.publish_px("app.cmd", ["ImportPath", document.getElementById("Path").value]);
event_opl.preventDefault();
}
}}
class Congratstempimport_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/congratstempl/-1/"+ id_spl;
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "importEntry") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["congratstempimportierung", elx_o.id] );
}
event_opl.preventDefault();
}
}}
class Congratstempdetails_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/congratstempl/"+id_spl+"/-1/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
}
class Annuallist_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/annuallist";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
,"POST");
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
}
class DetailView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.rentner_id=null
}
render_px (id_spl) {
// Daten anfordern
if(id_spl!=null){
this.rentner_id=id_spl;
let path_s = "/app/pensionaer/" + id_spl;
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
},
);
}
else
{
this.rentner_id=10000;
this.doRender_p(null);
}
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
this.configHandleEvent_p();
}
}
configHandleEvent_p () {
let el_o = document.querySelector("form");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
el_o.rentner_id=this.rentner_id;
}
}
handleEvent_p (event_opl) {
if (event_opl.target.id == "idBack") {
APPETT.es_o.publish_px("app.cmd", ["idBack", null]);
event_opl.preventDefault();
} else if(event_opl.target.id == "pensionaerspeichern"){
event_opl.preventDefault();
APPETT.es_o.publish_px("app.cmd", ["pensionaerspeichern", this.rentner_id]);
}
}}
class ListView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/pensionaer/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
console.info(data_opl);
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "idShowListEntry") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["detail", elx_o.id] );
}
event_opl.preventDefault();
} else if(event_opl.target.id == "idDeleteListEntry") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["pensionaerloeschen", elx_o.id] );
}
event_opl.preventDefault();
} else if (event_opl.target.id == "idNewListEntry") {
APPETT.es_o.publish_px("app.cmd", ["detail", null] );
}
event_opl.preventDefault();
}}
class SideBar_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
let cmd_s = event_opl.target.dataset.action;
APPETT.es_o.publish_px("app.cmd", [cmd_s, null]);
}}
class Application_cl {
constructor () {
// Registrieren zum Empfang von Nachrichten
APPETT.es_o.subscribe_px(this, "templates.loaded");
APPETT.es_o.subscribe_px(this, "templates.failed");
APPETT.es_o.subscribe_px(this, "app.cmd");
this.sideBar_o = new SideBar_cl("aside", "sidebar.tpl.html");
this.listView_o = new ListView_cl("main", "list.tpl.html");
this.detailView_o = new DetailView_cl("main", "pensionaer.tpl.html");
this.significantbirthdays_o=new Significantbirthdays_cl("main", "significantbirthdays.tpl.html");
this.significantbirthdays2_o=new Significantbirthdays2_cl("main", "significantbirthdays2.tpl.html");
this.annuallist_o=new Annuallist_cl("main", "annuallist.tpl.html");
this.congratstempl_o=new Congratstempl_cl("main", "congratstemplist.tpl.html");
this.congratstempdetails_o=new Congratstempdetails_cl("main", "congratstemp.tpl.html");
this.congratstempimport_o=new Congratstempimport_cl("main", "congratstempimport.tpl.html");
}
notify_px (self, message_spl, data_opl) {
switch (message_spl) {
case "templates.failed":
alert("Vorlagen konnten nicht geladen werden.");
break;
case "templates.loaded":
// Templates stehen zur Verfügung, Bereiche mit Inhalten füllen
// hier zur Vereinfachung direkt
let markup_s;
let el_o;
markup_s = APPETT.tm_o.execute_px("header.tpl.html", null);
el_o = document.querySelector("header");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
markup_s = APPETT.tm_o.execute_px("footer.tpl.html", null);
el_o = document.querySelector("footer");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
let nav_a = [
["home", "Startseite"],
["list", "Liste der Pensionäre"],
["congratstempl", "Vorlagen"],
["significantbirthdays", "Signifikante Geburtstage"],
["annuallist", "Jahresübersicht Geburtstage"],
];
self.sideBar_o.render_px(nav_a);
markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
el_o = document.querySelector("main");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
break;
case "app.cmd":
// hier müsste man überprüfen, ob der Inhalt gewechselt werden darf
switch (data_opl[0]) {
case "home":
let markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
let el_o = document.querySelector("main");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
break;
case "list":
// Daten anfordern und darstellen
this.listView_o.render_px();
break;
case "detail":
this.detailView_o.render_px(data_opl[1]);
break;
case "significantbirthdays":
this.significantbirthdays_o.render_px();
break;
case "annuallist":
this.annuallist_o.render_px(data_opl[1]);
break;
case "congratstempl":
this.congratstempl_o.render_px(data_opl[1]);
break;
case "idBack":
APPETT.es_o.publish_px("app.cmd", ["list", null]);
break;
case "pensionaerspeichern":
let versandmethode;
let path_s;
if(data_opl[1]==10000)
{versandmethode="POST"
path_s= "/app/pensionaer/";}
else
{versandmethode="PUT";
path_s = "/app/pensionaer/"+data_opl[1];}
var form = document.getElementById("pensidata");
var data = new FormData(form);
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, versandmethode, data);
APPETT.es_o.publish_px("app.cmd", ["list", null]);
break;
case "pensionaerloeschen":
let path_s2 = "/app/pensionaer/"+data_opl[1];
APPETT.xhr_o.request_px(path_s2,
function (responseText_spl) {
let data_o2 = JSON.parse(responseText_spl);
this.doRender_p(data_o2);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, "DELETE");
APPETT.es_o.publish_px("app.cmd", ["list", null]);
break;
case "ImportPath":
this.congratstempimport_o.render_px(data_opl[1]);
break;
case "congratstempdetails":
this.congratstempdetails_o.render_px(data_opl[1]);
break;
case "savecongratstempl":
APPETT.es_o.publish_px("app.cmd", ["list", null]);
break;
case "deleteC":
let path_s3 = "/app/congratstempl/"+data_opl[1];
APPETT.xhr_o.request_px(path_s3,
function (responseText_spl) {
let data_o2 = JSON.parse(responseText_spl);
this.doRender_p(data_o3);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, "DELETE");
APPETT.es_o.publish_px("app.cmd", ["congratstempl", null]);
break;
case "congratstempimportierung":
var path = "/app/congratstempl/-1/"+data_opl[1];
var form2 = document.getElementById("beschreibungsdaten");
var data2 = new FormData(form2);
APPETT.xhr_o.request_px(path,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o4);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, "POST", data2);
APPETT.es_o.publish_px("app.cmd", ["congratstempl", null]);
break;
case "significantbutton":
this.significantbirthdays2_o.render_px();
break;
}
break;
}
}
}
window.onload = function () {
APPETT.xhr_o = new APPETT.XHR_cl();
APPETT.es_o = new APPETT.EventService_cl();
var app_o = new Application_cl();
APPETT.tm_o = new APPETT.TemplateManager_cl();
}<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/formError.tpl.py
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1513173337.050694
_enable_loop = True
_template_filename = '/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formError.tpl'
_template_uri = 'formError.tpl'
_source_encoding = 'utf-8'
_exports = ['header']
def _mako_get_namespace(context, name):
try:
return context.namespaces[(__name__, name)]
except KeyError:
_mako_generate_namespaces(context)
return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
pass
def _mako_inherit(template, context):
_mako_generate_namespaces(context)
return runtime._inherit_from(context, 'layout.tpl', _template_uri)
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
def header():
return render_header(context._locals(__M_locals))
__M_writer = context.writer()
__M_writer('\r\n')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'header'):
context['self'].header(**pageargs)
__M_writer('\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_header(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
def header():
return render_header(context)
__M_writer = context.writer()
__M_writer('\r\n\t<body>\r\n\t\t<h1>Dieser Studiengang existiert nicht</h1>\r\n\t</body>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"source_encoding": "utf-8", "line_map": {"34": 2, "51": 3, "39": 7, "57": 51, "27": 0, "45": 3}, "uri": "formError.tpl", "filename": "/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formError.tpl"}
__M_END_METADATA
"""
<file_sep>/WEB/p4/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
#self.type_s = type_spl
#self.path_s = os.path.join('data', type_spl)
self.data_o = None #Liste
self.dataID_o = None
self.readData_p() #Filestream für Data_o --> .json
self.readDataID_p()
#-------------------------------------------------------
def create_px(self, data_opl):
#-------------------------------------------------------
self.getNewID_p()
id_s = str(self.dataID_o)
self.data_o[id_s] = data_opl
self.saveData_p()
return id_s
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = None
if id_spl == None:
data_o = self.data_o
else:
#id_i = int(id_spl)
for i in range(len(self.data_o)):
if (id_spl in self.data_o[i]["id"]) or (id_spl in self.data_o[i]["Bezeichnung"]):
data_o = self.data_o[i]
return data_o
#-------------------------------------------------------
def readFavorites_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = []
for i in range(len(self.data_o)):
if "favorites" in self.data_o[i]["Kategorien"]:
print(self.data_o[i]["Kategorien"])
data_o.append(self.data_o[i])
print(data_o)
return data_o
#-------------------------------------------------------
def readMissing_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = []
missing = None
marked = None
same = 0
if id_spl == None:
for i in range(len(self.data_o)):
missing = self.data_o[i]["Text"].split()
print(missing)
for missed in missing:
#if kategorie in kategorien: ---> hier weitermachen
if "[[" in missed:
marked = missed.replace("[[","")
marked = marked.replace("]]","")
print("das ist ein Thema", missed)
for j in range(len(self.data_o)):
if marked in self.data_o[j]["Bezeichnung"]:
print("übereinstimmendes thema", marked)
same = 1
if same == 0:
print("nicht übereinstimmend", marked)
data_o.append(marked)
same = 0
print("endergebnis")
print(data_o)
return data_o
#-------------------------------------------------------
def readOrphans_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = []
same = 0
for i in range(len(self.data_o)):
linked = "[[" + self.data_o[i]["Bezeichnung"] + "]]"
for j in range(len(self.data_o)):
print("linked: ", linked)
if linked in self.data_o[j]["Text"]:
print(self.data_o[j]["Bezeichnung"])
same = 1
if (same == 0) and (self.data_o[i]["Bezeichnung"] not in data_o):
data_o.append(self.data_o[i])
same = 0
print(data_o)
return data_o
#-------------------------------------------------------
def readTags_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = []
kategorien = None
if id_spl == None:
for i in range(len(self.data_o)):
if self.data_o[i]["Kategorien"] != "Kategorien sind noch anzugeben":
kategorien = self.data_o[i]["Kategorien"].split()
print(kategorien)
for kategorie in kategorien:
print(kategorie)
#if kategorie in kategorien: ---> hier weitermachen
if kategorie in data_o:
print("doppelter eintrag")
else:
data_o.append(kategorie)
print(data_o)
print("endergebnis")
print(data_o)
else:
#id_i = int(id_spl)
for i in range(len(self.data_o)):
if id_spl in self.data_o[i]["Kategorien"]:
print(self.data_o[i]["Kategorien"])
data_o.append(self.data_o[i])
print(data_o)
return data_o
#-------------------------------------------------------
def readData_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'topics.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_o = []
self.saveData_p()
pass
else:
with fp_o:
self.data_o = json.load(fp_o)
#-------------------------------------------------------
def readDataID_p(self):
#-------------------------------------------------------
try:
fp_id = codecs.open(os.path.join('data', 'ID.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.dataID_o = 0
self.saveDataID_p()
else:
with fp_id:
self.dataID_o = json.load(fp_id)
#-------------------------------------------------------
def saveData_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'topics.json'), 'w', 'utf-8')as fp_o:
json.dump(self.data_o, fp_o, sort_keys=True)
#-------------------------------------------------------
def saveDataID_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'ID.json'), 'w', 'utf-8') as fp_id:
json.dump(self.dataID_o, fp_id)
#-------------------------------------------------------
def getDefault_px(self):
#-------------------------------------------------------
return {
'bezeichnung': ''
}
#-------------------------------------------------------
def getNewID_p(self):
#-------------------------------------------------------
tmpID = None
self.tmpID = self.dataID_o
self.dataID_o = self.tmpID + 1
self.saveDataID_p()
# EOF<file_sep>/WEB/p4/static/main_c6.js
//------------------------------------------------------------------------------
//Demonstrator es/te/tm - Variante mit ES6-Classes
//------------------------------------------------------------------------------
// hier zur Vereinfachung (!) die Klassen in einer Datei
'use strict'
class DetailView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
//console.log(id_spl);
//alert("Die ID ist " + id_spl);
// Daten anfordern
let path_s = "/app/topics/" + id_spl;
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
if(this.template_s=="detail_show.tpl.html"){
var zaehler = 0;
while (zaehler <= 5){
//markup_s = markup_s.replace(/[[/g,"<a href='#' class='link'>").replace(/]]/g,"</a>");
markup_s = markup_s.replace("[[","<a href='#' class='link'>").replace("]]","</a>");
zaehler++;
}
}
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
this.configHandleEvent_p();
}
}
configHandleEvent_p () {
let el_o = document.querySelector("form");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.id == "idBack") {
//var check = confirm('Wenn Sie die Seite verlassen, können Daten verloren gehen. Seite verlassen?');
//if (check == false) {
// event_opl.preventDefault()
//} else{
APPETT.es_o.publish_px("app.cmd", ["idBack", null]);
event_opl.preventDefault();
// }
} else if((event_opl.target.tagName.toUpperCase() == "A") && (event_opl.target.className == "link")){
var bezeichnung = event_opl.target.innerText;
//alert(bezeichnung)
event_opl.preventDefault();
APPETT.es_o.publish_px("app.cmd", ["detail_show", bezeichnung]);
}
else if(event_opl.target.id == "topicerstellen"){
event_opl.preventDefault();
APPETT.es_o.publish_px("app.cmd", ["topicerstellen", this.topic_id]);
}
else if(event_opl.target.id == "topicspeichern"){
var topic_id = event_opl.target.dataset.id;
event_opl.preventDefault();
APPETT.es_o.publish_px("app.cmd", ["topicspeichern", topic_id]);
}
else if(event_opl.target.id == "topicloeschen"){
var topic_id = event_opl.target.dataset.id;
if(topic_id == "0"){
alert("Der Datensatz kann nicht gelöscht werden!")
event_opl.preventDefault()
}else{
var check = confirm('Wollen Sie den Datensatz wirklich löschen?');
if (check == false) {
event_opl.preventDefault()
}else{
APPETT.es_o.publish_px("app.cmd", ["topicloeschen", topic_id]);
}
}
}
else if(event_opl.target.id == "topicbearbeiten"){
var topic_id = event_opl.target.dataset.id;
//alert("das ist die bearbeiten topic"+topic_id)
event_opl.preventDefault();
APPETT.es_o.publish_px("app.cmd", ["detail_edit", topic_id]);
}
}
}
class DetailTagsView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/tags/" + id_spl;
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
this.configHandleEvent_p();
}
}
configHandleEvent_p () {
let el_o = document.querySelector("form");
//alert(el_o);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.id == "idBack") {
APPETT.es_o.publish_px("app.cmd", ["idBack", null]);
event_opl.preventDefault();
} else if ((event_opl.target.tagName.toUpperCase() == "A") && (event_opl.target.className == "tagtopics")){
var topic_id = event_opl.target.id;
alert("das ist tagtopic "+ topic_id);
APPETT.es_o.publish_px("app.cmd", ["detail_show", topic_id] );
event_opl.preventDefault();
}
event_opl.preventDefault();
}
}
class ListView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/topics/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "A" && (event_opl.target.className == "topics")) {
var topic_id = event_opl.target.id;
APPETT.es_o.publish_px("app.cmd", ["detail_show", topic_id] );
event_opl.preventDefault();
} else if (event_opl.target.id == "idNewListEntry") {
APPETT.es_o.publish_px("app.cmd", ["detail_create", null] );
event_opl.preventDefault();
}
event_opl.preventDefault();
}
}
class ListTagsView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/tags/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "A" && (event_opl.target.className == "tags")) {
var tag_id = event_opl.target.id;
APPETT.es_o.publish_px("app.cmd", ["detail_tags", tag_id] );
event_opl.preventDefault();
}
event_opl.preventDefault();
}
}
class ListFavoritesView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/favorites/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "A" && (event_opl.target.className == "favorites")) {
var topic_id = event_opl.target.id;
APPETT.es_o.publish_px("app.cmd", ["detail_show", topic_id] );
event_opl.preventDefault();
}
event_opl.preventDefault();
}
}
class ListMissingView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/missing/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "A" && (event_opl.target.className == "missing")) {
var topic_id = event_opl.target.id;
APPETT.es_o.publish_px("app.cmd", ["detail_show", topic_id] );
event_opl.preventDefault();
}
event_opl.preventDefault();
}
}
class ListOrphansView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/app/orphans/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "A" && (event_opl.target.className == "orphans")) {
var topic_id = event_opl.target.id;
APPETT.es_o.publish_px("app.cmd", ["detail_show", topic_id] );
event_opl.preventDefault();
}
event_opl.preventDefault();
}
}
class SideBar_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
let cmd_s = event_opl.target.dataset.action;
APPETT.es_o.publish_px("app.cmd", [cmd_s, null]);
}
}
class Application_cl {
constructor () {
// Registrieren zum Empfang von Nachrichten
APPETT.es_o.subscribe_px(this, "templates.loaded");
APPETT.es_o.subscribe_px(this, "templates.failed");
APPETT.es_o.subscribe_px(this, "app.cmd");
this.sideBar_o = new SideBar_cl("aside", "sidebar.tpl.html");
this.listView_o = new ListView_cl("main", "list.tpl.html");
this.favoritesView_o = new ListFavoritesView_cl("main", "favorites.tpl.html");
this.topicsView_o = new ListView_cl("main", "topics.tpl.html");
this.tagsView_o = new ListTagsView_cl("main", "tags.tpl.html");
this.missingView_o = new ListMissingView_cl("main", "missing.tpl.html");
this.orphansView_o = new ListOrphansView_cl("main", "orphans.tpl.html");
this.detail_createView_o = new DetailView_cl("main", "detail_create.tpl.html");
this.detail_showView_o = new DetailView_cl("main", "detail_show.tpl.html");
this.detail_editView_o = new DetailView_cl("main", "detail_edit.tpl.html");
this.detail_TagsView_o = new DetailTagsView_cl("main", "detailTags.tpl.html");
this.homeView_o = new DetailView_cl("main", "home.tpl.html");
}
notify_px (self, message_spl, data_opl) {
switch (message_spl) {
case "templates.failed":
alert("Vorlagen konnten nicht geladen werden.");
break;
case "templates.loaded":
// Templates stehen zur Verfügung, Bereiche mit Inhalten füllen
// hier zur Vereinfachung direkt
let markup_s;
let el_o;
markup_s = APPETT.tm_o.execute_px("header.tpl.html", null);
el_o = document.querySelector("header");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
markup_s = APPETT.tm_o.execute_px("footer.tpl.html", null);
el_o = document.querySelector("footer");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
let nav_a = [
["home", "[Home]"],
["favorites", "[Favoriten]"],
["topics", "[Alle Themen]"],
["tags", "[Alle Kategorien]"],
["missing", "[Fehlende Themen]"],
["orphans", "[Verwaiste Themen]"]
];
self.sideBar_o.render_px(nav_a);
//markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
//el_o = document.querySelector("main");
//if (el_o != null) {
// el_o.innerHTML = markup_s;
//}
this.homeView_o.render_px("0");
break;
case "app.cmd":
// hier müsste man überprüfen, ob der Inhalt gewechselt werden darf
let method = null;
let path_s = null;
switch (data_opl[0]) {
case "home":
//let markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
//let el_o = document.querySelector("main");
//if (el_o != null) {
// el_o.innerHTML = markup_s;
//}
this.homeView_o.render_px("0");
break;
case "list":
// Daten anfordern und darstellen
this.listView_o.render_px();
break;
case "detail_create":
this.detail_createView_o.render_px(data_opl[1]);
break;
case "detail_show":
this.detail_showView_o.render_px(data_opl[1]);
break;
case "detail_edit":
this.detail_editView_o.render_px(data_opl[1]);
break;
case "detail_tags":
this.detail_TagsView_o.render_px(data_opl[1]);
break;
case "favorites":
this.favoritesView_o.render_px();
break;
case "topics":
this.topicsView_o.render_px();
break;
case "tags":
this.tagsView_o.render_px();
break;
case "missing":
this.missingView_o.render_px();
break;
case "orphans":
this.orphansView_o.render_px();
break;
case "idBack":
APPETT.es_o.publish_px("app.cmd", ["topics", null]);
break;
case "topicerstellen":
method = "POST";
path_s = "/app/topics/";
var form = document.getElementById("topicsData");
var data = new FormData(form);
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, method, data);
APPETT.es_o.publish_px("app.cmd", ["topics", null]);
break;
case "topicspeichern":
method = "PUT";
//alert(data_opl[1])
path_s = "/app/topics/"+data_opl[1];
var form = document.getElementById("topicsData");
var data = new FormData(form);
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o2 = JSON.parse(responseText_spl);
this.doRender_p(data_o2);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, method, data);
APPETT.es_o.publish_px("app.cmd", ["detail_show", data_opl[1]]);
break;
case "topicloeschen":
method = "DELETE"
path_s = "/app/topics/"+data_opl[1];
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o3 = JSON.parse(responseText_spl);
this.doRender_p(data_o3);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
, method);
APPETT.es_o.publish_px("app.cmd", ["topics", null]);
break;
}
break;
}
}
}
window.onload = function () {
APPETT.xhr_o = new APPETT.XHR_cl();
APPETT.es_o = new APPETT.EventService_cl();
var app_o = new Application_cl();
APPETT.tm_o = new APPETT.TemplateManager_cl();
}<file_sep>/WEB/p4_sicherung/app/application.py
# coding: utf-8
# Demonstrator / keine Fehlerbehandlung
import cherrypy
import json
import os
import os.path
import codecs
from .database import Database_cl
from .view import View_cl
# Method-Dispatching!
# Übersicht Anforderungen / Methoden
"""
Anforderung GET
-------------------------
/ Liste
liefern
/{id} Detail
mit {id}
liefern
"""
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
exposed = True # gilt für alle Methoden
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung können hier eingetragen werden
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self, *args):
#-------------------------------------------------------
if args[0] == "topics":
return self.getTopics(*args)
else:
return ''
#-------------------------------------------------------
def getTopics(self, *args):
#-------------------------------------------------------
# /pensionaer/ daten aller pensionaere als liste ausliefern
# /pensionaer/id daten eines pensionaers anhand id liefern
retVal_s = ''
if len(args)==1:
retVal_s = self.getList_p()
else:
id = args[1]
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def POST(self, *args, **kwargs):
#-------------------------------------------------------
if args[0] == "topics":
return self.postTopics(*args, **kwargs)
else:
return ''
#-------------------------------------------------------
def postTopics(self, *args, **kwargs):
#-------------------------------------------------------
#die ID eines topics ist die Bezeichnung
data_tmp = self.db_o.data_o
daten = {
"id": None,
#"id": kwargs["Bezeichnung"],
"Bezeichnung": kwargs["Bezeichnung"]
}
#Erstellung einer ID die bei jedem Post hochgezählt wird
# Create-Operation
#id_s = self.db_o.create_px(data_o)
self.db_o.getNewID_p()
id_s = str(self.db_o.dataID_o)
daten["id"] = id_s
print(daten)
data_tmp.append(daten)
self.db_o.saveData_p()
self.db_o.readData_p()
return ''
#-------------------------------------------------------
def PUT(self, data_opl):
#-------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_s = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
id_s = data_opl["id_s"]
data_o = {
'name': data_opl["name_s"]
}
# Update-Operation
retVal_s['id'] = id_s
if self.db_o.update_px(id_s, data_o):
pass
else:
retVal_s['id'] = None
return retVal_s
#-------------------------------------------------------
def DELETE(self, id):
#-------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_s = {
'id': id
}
if self.db_o.delete_px(id):
pass
else:
retVal_s['id'] = None
return retVal_s
#-------------------------------------------------------
def getList_p(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
# default-Werte entfernen
# ndata_a = data_a[1:]
return self.view_o.createList_px(data_a)
#-------------------------------------------------------
def getDetail_p(self, id_spl):
#-------------------------------------------------------
data_o = self.db_o.read_px(id_spl)
return self.view_o.createDetail_px(data_o)
# EOF<file_sep>/Mattes/4/app/kategorie.py
import json
import cherrypy
from .database import katfehlerDatabase_cl, katursacheDatabase_cl
# -------------------------------------------------------
def adjustId_p(id_spl, data_opl):
# -------------------------------------------------------
if id_spl == None:
data_opl['id'] = ''
elif id_spl == '':
data_opl['id'] = ''
elif id_spl == '0':
data_opl['id'] = ''
else:
data_opl['id'] = id_spl
return data_opl
# ----------------------------------------------------------
class KatUrsache_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.db_o = katursacheDatabase_cl()
# -------------------------------------------------------
def GET(self, id):
# -------------------------------------------------------
retVal_o = {
'data': None,
}
if id == None:
# Anforderung der Liste
retVal_o['data'] = self.db_o.read_px()
else:
# Anforderung eines Dokuments
data_o = self.db_o.read_px(id)
if data_o != None:
retVal_o['data'] = adjustId_p(id, data_o)
return retVal_o
# -------------------------------------------------------
def POST(self, data_opl):
# -------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
id_s = data_opl["id_s"]
data_o = {
'title': data_opl["title_s"],
'reference': data_opl["reference_s"]
}
# Create-Operation
if self.db_o.update_px(id_s, data_o):
retVal_o['id'] = id_s
else:
retVal_o['id'] = None
return retVal_o
# -------------------------------------------------------
def PUT(self, data_opl):
# -------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
data_o = {
'title': data_opl["title_s"],
'reference': data_opl["reference_s"]
}
# Update-Operation
retVal_o['id'] = self.db_o.create_px(data_o)
return retVal_o
# -------------------------------------------------------
def DELETE(self, id):
# -------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if self.db_o.delete_px(id):
pass
else:
retVal_o['id'] = None
return retVal_o
# ----------------------------------------------------------
class KatFehler_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.db_o = katfehlerDatabase_cl()
# -------------------------------------------------------
def GET(self, id):
# -------------------------------------------------------
retVal_o = {
'data': None,
}
if id == None:
# Anforderung der Liste
retVal_o['data'] = self.db_o.read_px()
else:
# Anforderung eines Dokuments
data_o = self.db_o.read_px(id)
if data_o != None:
retVal_o['data'] = adjustId_p(id, data_o)
return retVal_o
# -------------------------------------------------------
def POST(self, data_opl):
# -------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
id_s = data_opl["id_s"]
data_o = {
'title': data_opl["title_s"],
'reference': data_opl["reference_s"]
}
# Create-Operation
if self.db_o.update_px(id_s, data_o):
retVal_o['id'] = id_s
else:
retVal_o['id'] = None
return retVal_o
# -------------------------------------------------------
def PUT(self, data_opl):
# -------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
data_o = {
'title': data_opl["title_s"],
'reference': data_opl["reference_s"]
}
# Update-Operation
retVal_o['id'] = self.db_o.create_px(data_o)
return retVal_o
# -------------------------------------------------------
def DELETE(self, id):
# -------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if self.db_o.delete_px(id):
pass
else:
retVal_o['id'] = None
return retVal_o<file_sep>/README.md
# web
Web-Praktika
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.dataID_o = None
self.data_o = None #Liste für Studiengänge
self.data_l = None #Liste für Lehrveranstaltungen
self.data_m = None #Liste für Module
self.data_u = None #Liste für Benutzer
self.data_temp = None #Liste für Temporäres
self.readDataID() #Filestream für ID --> ID.json
self.readData_Studiengang() #Filestream für Data_o --> studiengang.json
self.readData_User() #Filestream für Data_u --> user.json
self.readData_Lehrveranstaltung() #Filestream für Data_l --> lehrveranstaltung.json
self.readData_Modul() #Filestream für Data_l --> modul.json
#-------------------------------------------------------
def create_Studiengang(self, data_opl):
#-------------------------------------------------------
self.getNewID()
id_s = str(self.dataID_o)
self.data_o[id_s] = data_opl
self.saveData_Studiengang()
return
#-------------------------------------------------------
def create_Modul(self, data_opl):
#-------------------------------------------------------
self.getNewID()
id_s = str(self.dataID_o)
self.data_m[id_s] = data_opl
self.saveData_Modul()
return
#-------------------------------------------------------
def create_Lehrveranstaltung(self, data_opl):
#-------------------------------------------------------
self.getNewID()
id_s = str(self.dataID_o)
self.data_l[id_s] = data_opl
self.saveData_Lehrveranstaltung()
return
#-------------------------------------------------------
def delete_Studiengang(self, id_spl):
#-------------------------------------------------------
#Löschvorgang für Studiengaenge
status_b = False
for key in self.data_o:
if self.data_o[key][1] == id_spl:
del self.data_o[key]
self.saveData_Studiengang()
status_b = True
return status_b
return status_b
#-------------------------------------------------------
def delete_Modul(self, id_spl):
#-------------------------------------------------------
#Löschvorgang für Modul
status_b = False
for key in self.data_m:
if self.data_m[key][0] == id_spl:
del self.data_m[key]
self.saveData_Modul()
status_b = True
return status_b
return status_b
#-------------------------------------------------------
def delete_Lehrveranstaltung(self, id_spl):
#-------------------------------------------------------
#Löschvorgang für Lehrveranstaltung
status_b = False
for key in self.data_l:
if self.data_l[key][0] == id_spl:
del self.data_l[key]
self.saveData_Lehrveranstaltung()
status_b = True
return status_b
return status_b
#-------------------------------------------------------
def update_Studiengang(self, id_spl, data_opl):
#-------------------------------------------------------
status_b = False
for key in self.data_o:
if self.data_o[key][1] == id_spl:
self.data_o[key] = data_opl
self.saveData_Studiengang()
status_b = True
return self.data_o[key]
return status_b
#-------------------------------------------------------
def update_Modul(self, id_spl, data_opl):
#-------------------------------------------------------
status_b = False
for key in self.data_m:
if self.data_m[key][0] == id_spl:
self.data_m[key] = data_opl
self.saveData_Modul()
status_b = True
return self.data_m[key]
return status_b
#-------------------------------------------------------
def update_Lehrveranstaltung(self, id_spl, data_opl):
#-------------------------------------------------------
status_b = False
for key in self.data_l:
if self.data_l[key][0] == id_spl:
self.data_l[key] = data_opl
self.saveData_Lehrveranstaltung()
status_b = True
return self.data_l[key]
return status_b
#-------------------------------------------------------
def getNewID(self):
#-------------------------------------------------------
tmpID = None
self.tmpID = self.dataID_o
self.dataID_o = self.tmpID + 1
self.saveDataID()
#-------------------------------------------------------
def getEmptyModul(self):
#-------------------------------------------------------
return ['', '', '', '', '', '', '', '', '']
#-------------------------------------------------------
def getEmptyStudiengang(self):
#-------------------------------------------------------
return ['', '', '', '', '', '', '', '', '']
#-------------------------------------------------------
def getEmptyLehrveranstaltung(self):
#-------------------------------------------------------
return ['', '', '', '', '', '', '', '', '']
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
data_o = self.readData_Studiengang()
if id_spl == None:
data_o = self.data_o
else:
if id_spl in self.data_o:
data_o = self.data_o[id_spl]
return data_o
#-------------------------------------------------------
def read_modul_px(self, id_spl = None):
#-------------------------------------------------------
data_m = self.readData_Modul()
if id_spl == None:
data_m = self.data_m
else:
if id_spl in self.data_m:
data_m = self.data_m[id_spl]
return data_m
#-------------------------------------------------------
def read_lehrveranstaltung_px(self, id_spl = None):
#-------------------------------------------------------
data_l = self.readData_Lehrveranstaltung()
if id_spl == None:
data_l = self.data_l
else:
if id_spl in self.data_l:
data_l = self.data_l[id_spl]
return data_l
#-------------------------------------------------------
def readDataID(self):
#-------------------------------------------------------
try:
fp_id = codecs.open(os.path.join('data', 'ID.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.dataID_o = 0
self.saveDataID()
else:
with fp_id:
self.dataID_o = json.load(fp_id)
return self.dataID_o
#-------------------------------------------------------
def readData_p(self, dat):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', dat), 'r', 'utf-8')
except:
pass
else:
with fp_o:
self.data_temp = json.load(fp_o)
return self.data_temp
#-------------------------------------------------------
def readData_Studiengang(self):
#-------------------------------------------------------
try:
fp_s = codecs.open(os.path.join('data', 'studiengang.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_o = {}
self.saveData_Studiengang()
else:
with fp_s:
self.data_o = json.load(fp_s)
return self.data_o
#-------------------------------------------------------
def readData_User(self):
#-------------------------------------------------------
try:
fp_u = codecs.open(os.path.join('data', 'user.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_u = {}
self.saveData_User()
else:
with fp_u:
self.data_u = json.load(fp_u)
return self.data_u
#-------------------------------------------------------
def readData_Lehrveranstaltung(self):
#-------------------------------------------------------
try:
fp_l = codecs.open(os.path.join('data', 'lehrveranstaltung.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_l = {}
self.saveData_Lehrveranstaltung()
else:
with fp_l:
self.data_l = json.load(fp_l)
return self.data_l
#-------------------------------------------------------
def readData_Modul(self):
#-------------------------------------------------------
try:
fp_m = codecs.open(os.path.join('data', 'modul.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_m = {}
self.saveData_Modul()
else:
with fp_m:
self.data_m = json.load(fp_m)
return self.data_m
#-------------------------------------------------------
def readData_Modul_single(self, id_spl):
#-------------------------------------------------------
status_b = False
for key in self.data_m:
if self.data_m[key][0] == id_spl:
status_b = True
return self.data_m[key]
return status_b
#-------------------------------------------------------
def readData_Studiengang_single(self, id_spl):
#-------------------------------------------------------
status_b = False
for key in self.data_o:
if self.data_o[key][1] == id_spl:
status_b = True
return self.data_o[key]
return status_b
#-------------------------------------------------------
def readData_Lehrveranstaltung_single(self, id_spl):
#-------------------------------------------------------
status_b = False
for key in self.data_l:
if self.data_l[key][0] == id_spl:
status_b = True
return self.data_l[key]
return status_b
#-------------------------------------------------------
def read_rolle(self, id_name = None):
#-------------------------------------------------------
self.readData_User()
data_u = None
if id_name in self.data_u:
data_u = self.data_u[id_name]
return data_u
#-------------------------------------------------------
def saveData_p(self, dat):
#-------------------------------------------------------
with codecs.open(os.path.join('data', dat), 'w', 'utf-8') as fp_t:
json.dump(self.data_temp, fp_t)
#-------------------------------------------------------
def saveDataID(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'ID.json'), 'w', 'utf-8') as fp_id:
json.dump(self.dataID_o, fp_id)
#-------------------------------------------------------
def saveData_Studiengang(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'studiengang.json'), 'w', 'utf-8')as fp_o:
json.dump(self.data_o, fp_o, sort_keys=True)
#-------------------------------------------------------
def saveData_User(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'user.json'), 'w', 'utf-8')as fp_b:
json.dump(self.data_u, fp_b, sort_keys=True)
#-------------------------------------------------------
def saveData_Lehrveranstaltung(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'lehrveranstaltung.json'), 'w', 'utf-8')as fp_l:
json.dump(self.data_l, fp_l, sort_keys=True)
#-------------------------------------------------------
def saveData_Modul(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'modul.json'), 'w', 'utf-8')as fp_m:
json.dump(self.data_m, fp_m, sort_keys=True)
# EOF
<file_sep>/WEB/WEB Praktika/pl/doc/doku.md
# WEB Praktikum 2 Gruppe C
## <NAME> und <NAME>
## 1. Aufbau der Webanwendung
### Framework
Verwendetes Framework: CherryPi - ein einfaches Web Framework um Webanwendungen objektorientiert in der Sprache Python zu erstellen.
### server.py
Startet den CherryPi Server, dient außerdem zur Konfiguration des Servers. Static Konfiguration für einige Elemente und das Mounten von 3 Klassen. (Siehe Konfiguration)
### application.py
Stellt die Basis der Anwendung, von hier aus gelangt man in die Besucher und Sachbearbeiterklasse.
### Besucher.py
Stellt die Methoden für einen Besucher bereit, wie etwa das Anzeigen, Buchen und Stornieren von Veranstaltungen. Ruft hauptsächlich Bview.py-Methoden und die der Datenbank auf.
### Sachbearbeiter.py
Stellt alle Funktionen für den Sachbearbeiter bereit. Neben dem Hinzufügen/Löschen/Bearbeiten von Veranstaltungen gibt es die Möglichkeit einzelne Teilobjekte, aus denen Veranstaltungen bestehen zu bearbeiten, wie etwa Kategorien, Orte und Künstler. Ruft Hauptsächlich Sview.py-Methoden und die der Datenbank auf.
### Sview.py
Stellt die Methoden bereit, um aus den Templates für den Sachbearbeiter fertigen Code zu erzeugen. Benutzt Template Engine Mako.
### Bview.py
Stellt die Methoden bereit, um aus den Templates für den Besucher fertigen Code zu erzeugen. Benutzt Template Engine Mako.
### database.py
Verwaltung der Datenbank im Server. Diese Funktionen stellt die Schnittstelle zwischen dem Webserver und den zu verarbeitenden Daten dar. In diesem Fall werden die Daten sortiert nach Kategorien in .json abgelegt und zur Laufzeit in Dictionairies gehalten.
### templates und content Ordner
In diesem Ordner befinden sich alle Template Dateien, für jede mögliche Website eine. Weiterhin befinden sich eine JavaScript Datei für eine interaktive Benutzeroberfläche und eine CSS-Datei zum Formatieren der Webseite.
## Datenablage
### .json Dateien
In diesen vom Server angelegten Dateien werden die Eingabedaten abgespeichert und auf Anfrage
ausgelesen und in die Formulare/Templates eingebettet. Jede Datei stellt dabei eine Kategorie dar, wie etwa Veranstaltungen, Orte, Künstler und Besucher. In den Dictionairies befinden sich Arrays um alle Bestandteile der Daten zu trennen.
## Konfiguration
### Static
Statisch abgelegt wird die Allgemeingültige CSS Datei und die Javascript Datei die eine Sicherheitsabfrage vor dem Löschen bereitstellt.
### Gemountete Module
Die Wurzel / wird durch die Application.py dargestellt, welche nur die oberste Startseite bereitstellt. Sie hat keine Funktion außer die Sachbearbeiter und Besucher Klassen zu initialisieren.
Sachbearbeiter und Besucher stellen die eigentliche Anwendung bereit, aufgeteilt in 2 Bereiche für 2 Benutzer.<file_sep>/p2/bmf/app/Erstellen.py
'''
Created on 17.11.2017
@author: johannes
'''
import os
import os.path
import codecs
import json
import string
import cherrypy
from enum import Enum
def __init__(self):
pass
class Mitarbeiter(object):
def createMitarbeiter_E(self, data_opl):
markup_s = ''
markup_s += self.readFile_p('list0.tpl')
markupV_s = self.readFile_p('list1.tpl')
lineT_o = string.Template(markupV_s)
# mehrfach nutzen, um die einzelnen Zeilen der Tabelle zu erzeugen
for id_s in data_opl:
data_a = data_opl[str(id_s)]
markup_s += lineT_o.safe_substitute (name=data_a[0] # HIER müssen Sie eine Ergänzung vornehmen - erl
, vorname=data_a[1]
, akagra=data_a[2]
, taetigkeit=data_a[3]
)
markup_s += self.readFile_p('list2.tpl')
return self.create_p('liste.tpl', data_opl) #markup_s
class Weiterbildung(object):
bz_w = ' '
von = ' '
bis = ' '
bs_w = ' ' #txt = string?
max = ' ' #int = string?
min = ' ' #int = string?
def WB(self):
pass
class Teilnahme(Enum):
angemeldet = 1
nimmtteil = 2
storniert = 3
abgebrochen = 4
nichterfolgreich = 5
erfolgreich = 6
def TN(self):
pass
class Zertifikat(object):
bz_z = ' '
bs_z= ' ' #txt = string?
berechtigung = ' '
def ZF(self):
pass
class Qualifikation(object):
bz_q = ' '
bs_q = ' ' #txt = string?
def QA(self):
pass
#EoF
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/server.py
#coding: utf-8
import os
import cherrypy
from app import application
#--------------------------------------
def main():
#--------------------------------------
# Get current directory
try:
current_dir = os.path.dirname(os.path.abspath(__file__))
except:
current_dir = os.path.dirname(os.path.abspath(sys.executable))
# disable autoreload and timeout_monitor
cherrypy.engine.autoreload.unsubscribe()
cherrypy.engine.timeout_monitor.unsubscribe()
# Static content config
static_config = {
'/': {
'tools.staticdir.root': current_dir,
'tools.staticdir.on': True,
'tools.staticdir.dir': './templates'
}
}
cherrypy.config.update({
'tools.log_headers.on': True,
'tools.sessions.on': False,
'tools.encode.on': True,
'tools.encode.encoding': 'utf-8',
'server.socket_port': 8080,
'server.socket_timeout': 60,
'server.thread_pool': 10,
'server.environment': 'production',
'log.screen': True#,
#'request.show_tracebacks': False
})
# Mount static content handler
root_o = cherrypy.tree.mount(application.Application_cl(), '/', static_config)
# suppress traceback-info
cherrypy.config.update({'request.show_tracebacks': False})
# Start server
cherrypy.engine.start()
cherrypy.engine.block()
#--------------------------------------
if __name__ == '__main__':
#--------------------------------------
main()
# EOF<file_sep>/WEB/p2 - save2/mhb/content/mhb_login.js
function form_abschicken(path) {
var data = new FormData(document.getElementById("idWTForm"));
console.log(data)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML =
this.responseText;
}
};
xhttp.open("POST", path, true);
xhttp.send(data);
}<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/mhb_modul.js
function studiengangAnzeige() {
var get = document.getElementById("studiengang");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie einen Studiengang an");
}
else document.location.href = "/studiengang/" + selected.toString();
}
function modulEdit() {
var get = document.getElementById("modul");
var selected = get.options[get.selectedIndex].value;
if(selected == '0'){
alert("Bitte geben Sie ein Modul an");
}
else document.location.href = "/editModul/" + selected.toString();
}
window.onload=function(){
let studbutton = document.getElementById('buttonstud');
studbutton.addEventListener('click', studiengangAnzeige, false);
let modulbuttonedit = document.getElementById('buttonmoduledit');
modulbuttonedit.addEventListener('click', modulEdit, false);
}
<file_sep>/WEB/WEB Praktika/mhb/app/application.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
# GET / Anzeige Startseite
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
exposed = True
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self, id=None):
#-------------------------------------------------------
retVal_s = ''
if id == None:
# Anforderung der Liste
retVal_s = self.getList_p()
else:
# Anforderung eines Details
retVal_s = self.getDetail_p(id)
return retVal_s
#-------------------------------------------------------
def getList_p(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
# default-Werte entfernen
ndata_a = data_a[0:]
return self.view_o.createList_px(ndata_a)
#-------------------------------------------------------
def getDetail_p(self, id_spl):
#-------------------------------------------------------
data_o = self.db_o.read_px(id_spl)
return self.view_o.createDetail_px(data_o)
# EOF
<file_sep>/WEB/Klausurvorbereitung/WEB/Unterlagen/5/ws/quiz.js
/*
Beispiel Quiz mit Websockets
rev. 0, 24.01.2016 / Bm
*/
function disable_p () {
document.getElementById('idYes').disabled = true;
document.getElementById('idNo').disabled = true;
}
function enable_p () {
document.getElementById('idYes').disabled = false;
document.getElementById('idNo').disabled = false;
}
function showInfo_p (data_apl) {
var result_s = "<p>Ergebnisse aller Teilnehmer</p><table><tr><th>Frage</th><th>richtig</th><th>falsch</th>";
for (var loop_i = 0; loop_i < data_apl.length; loop_i++) {
result_s += "<tr><td>" + loop_i.toString() + "</td>";
result_s += "<td>" + data_apl[loop_i][0].toString() + "</td>";
result_s += "<td>" + data_apl[loop_i][1].toString() + "</td></tr>";
}
result_s += "</table>";
return result_s;
}
window.onload = function () {
disable_p();
/* EventHandler einrichten */
document.getElementById('idYes').onclick = function (event_opl) {
ws_o.send(JSON.stringify({"answer":"1"}));
disable_p();
}
document.getElementById('idNo').onclick = function (event_opl) {
var msg_s = JSON.stringify({"answer":"0"});
ws_o.send(msg_s);
disable_p();
}
/* Websocket-Verbindung einrichten */
var ws_o = new WebSocket('ws://localhost:8080');
/* EventHandler für das Websocket-Objekt einrichten */
ws_o.onopen = function (event_opl) {
document.getElementById('idStatus').innerHTML = "Verbindung hergestellt";
};
ws_o.onmessage = function (event_opl) {
var data_o = JSON.parse(event_opl.data);
console.log(data_o.cmd);
switch (data_o.cmd) {
case 'result':
var text_s = "Die Antwort zur Frage " + (data_o.qnr+1).toString() + " ist ";
if (data_o.result) {
text_s += "richtig!";
} else {
text_s += "falsch!";
}
document.getElementById('idAnswer').innerHTML = text_s;
break;
case 'question':
document.getElementById('idQuestion').innerHTML = data_o.question;
enable_p();
break;
case 'info':
document.getElementById('idInfo').innerHTML = showInfo_p(data_o.results);
break;
case 'end':
document.getElementById('idQuestion').innerHTML = "Keine weiteren Fragen!";
break;
}
};
ws_o.onclose = function (event_opl) {
document.getElementById('idStatus').innerHTML = "Verbindung gelöst";
};
}
// EOF
<file_sep>/WEB/Klausurvorbereitung/WEB/Praktika/p1/web/p1/webteams/content/Praktikum3.c
#include<wiringPi.h>
#include<signal.h>
#include<stdio.h>
#include<pthreahd.h>
#include<semaphre.h>
int status;
double distanz,
sem_t S_Messung, S_Anzeige, S_Bewegung;
double differenz;
void *Bewegung()
{
while (1) {
status = digitalRead (13);
if(status == 1){
sem_post (&S_Messung); //V-Operation
sem_wait(&S_Bewegung); //P-Operation
}
}
}
void *Entfernung(){
unsigned int t1,t2;
while(1){
sem_wait(&S_Messung); // P-Operation
if(status =1){
digitalWrite(6,1);
delay(0.01);
digitalWrite(6,0);
while(digitalRead(5) == 0){
t1=micros();
}
while(digitalRead(5) ==1){
t2 = micros();
}
differenz = (double) (t2 - t1);
differenz = differenz / 1000000
distanz = (differenz*34000)/2;
printf("Distanz: %lf\n",distanz);
}
sem_post(&S_Anzeige); // V-Operation
}
}
void *Anzeige(){
while(1){
sem_wait(&S_Anzeige); // P-Operation
digitalWrite(17,0);
digitalWrite(18,0);
digitalWrite(27,0);
if(distanz<15){
digitalWrite(17,1);
}
else if(distanz >15 && distanz < 30){
digitalWrite(18,1);
}
else if(distanz > 30){
digitalWrite(27,1);
}
sem_post(&S_Bewegung); // V-Operation
}
}
int main(void){
wiringPiSetupGpio();
pinMode(17, OUTPUT); //rot
pinMode(18, OUTPUT); //gelb
pinMode(27, OUTPUT); // grün
pinMode(6, OUTPUT); // trig
pinMode(5, OUTPUT); //echo
pinMode(13, OUTPUT); // bewegung
pthread_t thread1, thread2, thread3;
sem_init(&S_Bewegung,0,0);
sem_init(&S_Messung,0,0);
sem_init(&S_Anzeige,0,0);
delay(15000);
pthread_kill(thread1, 9); //9 = SIGKILL
pthread_kill(thread2, 9);
pthread_kill(thread3, 9);
return 0;
}
<file_sep>/WEB/p4/doc/doku.md
Name: <NAME>\
Matrikelnummer: 1121869\
Gruppe: B\
Datum: 05.02.2018\
**Allgemeine Beschreibung der Lösung:**
Aufgabe der Anwendung:
Mit der Webanwendung wird ein Wiki bereitgestellt mit dem man Themen erstellen und pflegen kann.
Mit einem Klick auf die Links wird eine Detailbeschreibung des Themas geöffnet.
Kategorien können einem Thema zugeordnet werden.
Übersicht der fachlichen Funktionen:
Mit der Anwendung soll es möglich sein, neben der Datenpflege auch verwaiste und fehlende Themen zu finden:
• fehlende Themen sind Themen auf die verwiesen wurde aber noch nicht in der Datenbank enthalten sind
◦ verwaiste Themen sind Themen die in der Datenbank enthalten sind, aber auf die nicht verwiesen wurde
ein detailliertes Thema:
▪ zeigt die Bezeichnung des Themas an
▪ dem Thema kann ein Titel und ein Text gegeben werden
▪ Kategorien können dem Thema zugewiesen werden
Favoriten:
▪ zeigt die Themen an die die Kategorie "favorite" enthalten
**Beschreibung der Komponenten des Servers:**
Application_cl:
- stellt die Verbindung zwischen Database_cl und View_cl her
- stellt alle Methoden für das Method-Dispatching bereit
- die Methoden GET, PUT, POST und DELETE sind implementiert
GET:
- holt sich die Daten auf der Datenbank "topics.json""
POST:
- fügt ein neues Thema der Datenbank hinzu
PUT:
- ändert ein bestehendes Thema
DELETE:
- löscht ein einzelnes Thema
Database_cl:
- liest, bearbeitet, erstellt Einträge in den zugehörigen .json Dateien
View_cl:
- gibt die Daten der GET-Anfragen aus
**Datenablage:**
web
/p4
/app
/_init_.py <-- Initialisierung
/application.py <-- Anwendung
/database.py <-- Datenbasis
/view.py <-- Sicht
/static
/es_to_c6.js
/main.css
/main.thml
/main_c6.js
/te_c6.js
/tm_c6.css
/xhr_c6.js
/data
/topics.json <-- Daten
/ID.json
/doc
/doku.md
/doku.html
/template
/detail_create.tpl.html
/detail_edit.tpl.html
/detail_show.tpl.html
/detailTags.tpl.html
/favorites.tpl.html
/footer.tpl.html
/header.tpl.html
/home.tpl.html
/missing.tpl.html
/orphans.tpl.html
/sidebar.tpl.html
/tags.tpl.html
/topics.tpl.html
**Beschreibung der Komponenten des Servers:**
- Der Server stellt jediglich die Daten bereit die in der Datenbank gespeichert wurden
- Die Methoden POST, GET, PUT, DELETE greifen auf die Datenbank zu und bearbeiten oder geben diese aus
**Beschreibung der Komponenten des Clients:**
main_c6.js
ist für die Verarbeitung auf dem Client zuständig. Der Event-Handler fängt die Anfragen vom Client ab und gibt die entsprechende angefragte Seite aus.
Die einzelnen Komponenten der HTML-Seite werden hier geladen.
<file_sep>/Mattes/1/webteams/content/webteams.js
function confirmDelete_p (event_opl) {
if ((event_opl.target.tagName.toLowerCase() == 'a') && (event_opl.target.className == "clDelete")) {
if(confirm("Are you sure?")){
alert("deleted")
}else{
event_opl.preventDefault();
}
// Klick auf Link zum L�schen
}
}
function redirect() {
window.location.replace("localhost:8089");
return false;
}
window.onload = function () {
let buttons = document.querySelectorAll("div.likeabutton");
body_o[0].addEventListener('click', confirmDelete_p, false);
}
<file_sep>/Mattes/1/webteams/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
# da es hier nur darum geht, die Daten dauerhaft zu speichern,
# wird ein sehr einfacher Ansatz verwendet:
# - es k�nnen Daten zu genau 15 Teams gespeichert werden
# - je Team werden 2 Teilnehmer mit Namen, Vornamen und Matrikelnummer
# ber�cksichtigt
# - die Daten werden als eine JSON-Datei abgelegt
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.data_o = None
self.readData_p()
#-------------------------------------------------------
def create_px(self, data_opl):
#-------------------------------------------------------
# �berpr�fung der Daten m�sste erg�nzt werden!
# 'freien' Platz suchen,
# falls vorhanden: belegen und Nummer des Platzes als Id zur�ckgeben
id_s = None
for loop_i in range(0,15):
if self.data_o[str(loop_i)][0] == '':
id_s = str(loop_i)
self.data_o[id_s] = data_opl
self.saveData_p()
break
return id_s
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Eintr�ge liefern
data_o = None
if id_spl == None:
data_o = self.data_o
else:
if id_spl in self.data_o:
data_o = self.data_o[id_spl]
return data_o
#-------------------------------------------------------
def update_px(self, id_spl, data_opl):
#-------------------------------------------------------
# �berpr�fung der Daten m�sste erg�nzt werden!
status_b = False
if id_spl in self.data_o:
self.data_o[id_spl] = data_opl
self.saveData_p()
status_b = True
return status_b
#-------------------------------------------------------
def delete_px(self, id_spl):
#-------------------------------------------------------
status_b = False
if id_spl in self.data_o:
self.data_o[id_spl] = self.getDefault_px()
self.saveData_p()
status_b = True
# hier m�ssen Sie den Code erg�nzen
# L�schen als Zur�cksetzen auf die Default-Werte implementieren
# Ihre Erg�nzung
return status_b
#-------------------------------------------------------
def getDefault_px(self):
#-------------------------------------------------------
return ['', '', '', '', '', '','',''] # HIER m�ssen Sie eine Erg�nzung vornehmen
#-------------------------------------------------------
def readData_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'webteams.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_o = {}
for loop_i in range(0,15):
self.data_o[str(loop_i)] = ['', '', '', '', '', '', '', ''] # HIER m�ssen Sie eine Erg�nzung vornehmen
self.saveData_p()
else:
with fp_o:
self.data_o = json.load(fp_o)
return
#-------------------------------------------------------
def saveData_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'webteams.json'), 'w', 'utf-8') as fp_o:
json.dump(self.data_o, fp_o)
# EOF<file_sep>/WEB/p2_sicherung3/mhb/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
# da es hier nur darum geht, die Daten dauerhaft zu speichern,
# wird ein sehr einfacher Ansatz verwendet:
# - es können Daten zu genau 15 Teams gespeichert werden
# - je Team werden 2 Teilnehmer mit Namen, Vornamen und Matrikelnummer
# berücksichtigt
# SOWIE ALS Ergänzung: Semesterzahl!
# - die Daten werden als eine JSON-Datei abgelegt
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.data_o = None #Liste für Studiengänge
self.data_b = None #Liste für Benutzer
self.data_l = None #Liste für Lehrveranstaltungen
self.data_m = None #Liste für Module
self.readData_p() #Filestream für Data_o --> studiengaenge.json
self.readData_benutzer_p() #Filestream für Data_b --> benutzer.json
self.readData_lehrveranstaltungen_p() #Filestream für Data_l --> lehrveranstaltungen.json
self.readData_module_p() #Filestream für Data_l --> lehrveranstaltungen.json
#-------------------------------------------------------
def create_px(self, data_opl):
#-------------------------------------------------------
# Überprüfung der Daten müsste ergänzt werden!
# 'freien' Platz suchen,
# falls vorhanden: belegen und Nummer des Platzes als Id zurückgeben
#---Länge der Daten aus der studiengaenge.json ermitteln und zurückgeben
id_s = None
data_o_len = self.data_o.__len__()
id_s = str(data_o_len)
for i in range(0, data_o_len):
if str(i) not in self.data_o:
id_s = str(i)
break
#for i in range(0, data_o_len):
# if data_opl[0] == self.data_o[str(i)][0]:
# return "Studiengang bereits vorhanden!"
self.data_o[id_s] = data_opl
self.saveData_p()
return id_s
#-------------------------------------------------------
def create_module_px(self, data_opl):
#-------------------------------------------------------
# Überprüfung der Daten müsste ergänzt werden!
# 'freien' Platz suchen,
# falls vorhanden: belegen und Nummer des Platzes als Id zurückgeben
#---Länge der Daten aus der studiengaenge.json ermitteln und zurückgeben
id_s = None
data_m_len = self.data_m.__len__()
id_s = str(data_m_len)
for i in range(0, data_m_len):
if str(i) not in self.data_m:
id_s = str(i)
break
#for i in range(0, data_o_len):
# if data_opl[0] == self.data_o[str(i)][0]:
# return "Studiengang bereits vorhanden!"
self.data_m[id_s] = data_opl
self.saveData_module_p()
return id_s
#-------------------------------------------------------
def create_lehrveranstaltungen_px(self, data_opl):
#-------------------------------------------------------
# Überprüfung der Daten müsste ergänzt werden!
# 'freien' Platz suchen,
# falls vorhanden: belegen und Nummer des Platzes als Id zurückgeben
#---Länge der Daten aus der studiengaenge.json ermitteln und zurückgeben
id_s = None
data_l_len = self.data_l.__len__()
id_s = str(data_l_len)
for i in range(0, data_l_len):
if str(i) not in self.data_l:
id_s = str(i)
break
#for i in range(0, data_o_len):
# if data_opl[0] == self.data_o[str(i)][0]:
# return "Studiengang bereits vorhanden!"
self.data_l[id_s] = data_opl
self.saveData_lehrveranstaltungen_p()
return id_s
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = None
if id_spl == None:
data_o = self.data_o
else:
if id_spl in self.data_o:
data_o = self.data_o[id_spl]
return data_o
#-------------------------------------------------------
def read_benutzer_px(self, id_spl = None):
#-------------------------------------------------------
# Read-Funktion für Benutzer
data_b = None
if id_spl == None:
data_b = self.data_b
else:
if id_spl in self.data_b:
data_b = self.data_b[id_spl]
return data_b
#-------------------------------------------------------
def read_lehrveranstaltungen_px(self, id_spl = None):
#-------------------------------------------------------
# Read-Funktion für Lehrveranstaltungen
data_l = None
if id_spl == None:
data_l = self.data_l
else:
if id_spl in self.data_l:
data_l = self.data_l[id_spl]
else: #----> hier bearbeitet
data_l = self.data_l
return data_l
#-------------------------------------------------------
def read_module_px(self, id_spl = None):
#-------------------------------------------------------
# Read-Funktion für Benutzer
data_m = None
if id_spl == None:
data_m = self.data_m
else:
if id_spl in self.data_m:
data_m = self.data_m[id_spl]
return data_m
#-------------------------------------------------------
def update_px(self, id_spl, data_opl):
#-------------------------------------------------------
# Überprüfung der Daten müsste ergänzt werden!
status_b = False
if id_spl in self.data_o:
self.data_o[id_spl] = data_opl
self.saveData_p()
status_b = True
return status_b
#-------------------------------------------------------
def update_module_px(self, id_spl, data_opl):
#-------------------------------------------------------
# Überprüfung der Daten müsste ergänzt werden!
status_b = False
if id_spl in self.data_m:
self.data_m[id_spl] = data_opl
self.saveData_module_p()
status_b = True
return status_b
#-------------------------------------------------------
def update_lehrveranstaltungen_px(self, id_spl, data_opl):
#-------------------------------------------------------
# Überprüfung der Daten müsste ergänzt werden!
status_b = False
if id_spl in self.data_l:
self.data_l[id_spl] = data_opl
self.saveData_lehrveranstaltungen_p()
status_b = True
return status_b
#-------------------------------------------------------
def delete_px(self, id_spl):
#-------------------------------------------------------
#Löschvorgang für Studiengaenge
status_b = False
if id_spl in self.data_o:
# pass
# hier müssen Sie den Code ergänzen
# Löschen als Zurücksetzen auf die Default-Werte implementieren
# Ihre Ergänzung
# self.data_o[id_spl] = ['', '', '', '']
# self.saveData_p()
# status_b = True
del self.data_o[id_spl]
self.saveData_p()
status_b = True
return status_b
#-------------------------------------------------------
def delete_m_px(self, id_spl):
#-------------------------------------------------------
#Löschvorgang für Studiengaenge
status_b = False
if id_spl in self.data_m:
# pass
# hier müssen Sie den Code ergänzen
# Löschen als Zurücksetzen auf die Default-Werte implementieren
# Ihre Ergänzung
# self.data_o[id_spl] = ['', '', '', '']
# self.saveData_p()
# status_b = True
del self.data_m[id_spl]
self.saveData_p()
status_b = True
return status_b
#-------------------------------------------------------
def delete_lv_px(self, id_spl):
#-------------------------------------------------------
#Löschvorgang für Studiengaenge
status_b = False
if id_spl in self.data_l:
# pass
# hier müssen Sie den Code ergänzen
# Löschen als Zurücksetzen auf die Default-Werte implementieren
# Ihre Ergänzung
# self.data_o[id_spl] = ['', '', '', '']
# self.saveData_p()
# status_b = True
del self.data_l[id_spl]
self.saveData_p()
status_b = True
return status_b
#-------------------------------------------------------
def getDefault_px(self):
#-------------------------------------------------------
return ['', '', '', '', self.getDefault_lehrveranstaltungen_px]
# 4 Felder für Studiengänge
#-------------------------------------------------------
def getDefault_lehrveranstaltungen_px(self):
#-------------------------------------------------------
return ['', '', '', '']
# 3 Felder für Lehrveranstaltungen
#-------------------------------------------------------
def getDefault_module_px(self):
#-------------------------------------------------------
return ['', '', '', '', '', '', '']
# 7 Felder für Lehrveranstaltungen
#-------------------------------------------------------
def readData_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'studiengaenge.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_o = {}
self.saveData_p()
else:
with fp_o:
self.data_o = json.load(fp_o)
#-------------------------------------------------------
def readData_benutzer_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'benutzer.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_b = {}
self.saveData_p()
else:
with fp_o:
self.data_b = json.load(fp_o)
#-------------------------------------------------------
def readData_lehrveranstaltungen_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'lehrveranstaltungen.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_l = {}
self.saveData_lehrveranstaltungen_p()
else:
with fp_o:
self.data_l = json.load(fp_o)
#-------------------------------------------------------
def readData_module_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'module.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_m = {}
self.saveData_module_p()
else:
with fp_o:
self.data_m = json.load(fp_o)
#-------------------------------------------------------
def saveData_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'studiengaenge.json'), 'w', 'utf-8')as fp_o:
json.dump(self.data_o, fp_o, sort_keys=True)
#-------------------------------------------------------
def saveData_benutzer_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'benutzer.json'), 'w', 'utf-8')as fp_b:
json.dump(self.data_b, fp_b, sort_keys=True)
#-------------------------------------------------------
def saveData_lehrveranstaltungen_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'lehrveranstaltungen.json'), 'w', 'utf-8')as fp_l:
json.dump(self.data_l, fp_l, sort_keys=True)
#-------------------------------------------------------
def saveData_module_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'module.json'), 'w', 'utf-8')as fp_m:
json.dump(self.data_m, fp_m, sort_keys=True)
# EOF<file_sep>/Mattes/3/doc/doku.md
# Dokumentation für den dritten Praktikumstermin von <NAME> und <NAME> aus Gruppe D. Krefeld, den 08.12.2016.
Ein Clentbasierter Praxisphasenmanager der nach den Vogegebenen Kriterien erstellt wurde und die gewünschten Funktionen aufweist.
Dieser wurde mit Python, Mako und Javascript realisiert. Als Datenbank dient eine JSONdatei.
Diese Anwendung dient dazu die Auswahl von Praxisphasen für Studenten zu erleichern und sie einer gewünschten Praxisphase in einem gewünschten Betrieb zuzuweisen.
Die Anwendung wurde nach den Vorgaben clientbasiert realisiert.
* Funktionsübersicht:
+ Erstellung von Studenten, Firmen, Lehrern und Praxisphasenangeboten.
+ Bearbeitung von Studenten, Firmen, Lehrern und Praxisphasenangeboten.
+ Löschen von Studenten, Firmen und Lehrern.
+ Sortierte Ausgabe der Praxisphasenangebote.
app.js : Funktionen dieser Datei dienen zur clientseitigen Funktionalität für das Kommunizieren mit dem Server,der Funktionalität für das Formular- und das Listen-Menü,
löschen, erstellen und bearbeiten von Zeilen, die Navigation und zur Programm Initialisierung.
Beispielfunktionen:
Bsp. function SetContent(view)
Bsp. function SetStatus(view)()
Bsp. function GetFormData()
view.js : Hier werden Funktionen zum fülen von Templates und dem erstellen von Formularen bereit gestellt.
application.py : Dient zur Erstellung von Listen und Forms, Außerdem werden hier Reihen hinzugefügt, bearbeitet und gelöscht.
Beispielfunktionen:
Bsp. create Funktion : def addRow()
Bsp. Editierfunktion : def updateRow()
Bsp. Löschfunktion : def deleteRow()
database.py:
Die Funktionen in database.py sind dafür zustäig Werte in die Jason Datei zu schreiben und zu löschen.
Außerdem werden durch die dortigen Funktionen Werte aus der Tabelle gelesen.
Beispielfunktionen
Bsp. Lesen : def readStudent_px(self, id_spl):.
Bsp. Schreiben: def saveData_p(self):.
Bsp. Löschen : def deleteStudent_px(self, id_spl):.
Die view.py dient zur Implementierung von Templates und als Markupgenerator.
Bsp. Funktion Templateimplementierung : def CreateForm_px(self, data_o, option, ansicht, id_s):.
* Datenablage :
Als Datenablage nutzen wir eine JSONdatei, welche wir in Dictionaries und Listen unterteilt haben.

* Validierte Seiten:
Validierter CSScode:

Validierte Indexseite:

Validierte view.js:

Validierte app.js:
<file_sep>/WEB/p4_sicherung2/app/database.py
# coding: utf-8
import os
import os.path
import codecs
import json
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
#self.type_s = type_spl
#self.path_s = os.path.join('data', type_spl)
self.data_o = None #Liste
self.dataID_o = None
self.readData_p() #Filestream für Data_o --> .json
self.readDataID_p()
#-------------------------------------------------------
def create_px(self, data_opl):
#-------------------------------------------------------
self.getNewID_p()
id_s = str(self.dataID_o)
self.data_o[id_s] = data_opl
self.saveData_p()
return id_s
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
# hier zur Vereinfachung:
# Aufruf ohne id: alle Einträge liefern
data_o = None
if id_spl == None:
data_o = self.data_o
else:
#id_i = int(id_spl)
for i in range(len(self.data_o)):
if id_spl in self.data_o[i]["id"]:
data_o = self.data_o[i]
return data_o
#-------------------------------------------------------
def readData_p(self):
#-------------------------------------------------------
try:
fp_o = codecs.open(os.path.join('data', 'topics.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.data_o = []
self.saveData_p()
pass
else:
with fp_o:
self.data_o = json.load(fp_o)
#-------------------------------------------------------
def readDataID_p(self):
#-------------------------------------------------------
try:
fp_id = codecs.open(os.path.join('data', 'ID.json'), 'r', 'utf-8')
except:
# Datei neu anlegen
self.dataID_o = 0
self.saveDataID_p()
else:
with fp_id:
self.dataID_o = json.load(fp_id)
#-------------------------------------------------------
def saveData_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'topics.json'), 'w', 'utf-8')as fp_o:
json.dump(self.data_o, fp_o, sort_keys=True)
#-------------------------------------------------------
def saveDataID_p(self):
#-------------------------------------------------------
with codecs.open(os.path.join('data', 'ID.json'), 'w', 'utf-8') as fp_id:
json.dump(self.dataID_o, fp_id)
#-------------------------------------------------------
def getDefault_px(self):
#-------------------------------------------------------
return {
'bezeichnung': ''
}
#-------------------------------------------------------
def getNewID_p(self):
#-------------------------------------------------------
tmpID = None
self.tmpID = self.dataID_o
self.dataID_o = self.tmpID + 1
self.saveDataID_p()
# EOF<file_sep>/WEB/Vorlesung/domiterator/showdom.js
// hier wird nur zur Vereinfachung der Demonstration direkt Markup in js verwendet
// NICHT nachahmen!
function ShowDom()
{
var DOMText = "<table>" +
"<tr><th>Level</th>" +
"<th>Type</th>" +
"<th>Name</th>" +
"<th>Value</th>" +
"<th>Attributes</th></tr>";
var Iterator = new DOMIterator(document);
var Node = Iterator.First();
while (Node != null) {
DOMText += "<tr><td>" + Iterator.Level.toString() +
"</td><td>" + Node.nodeType +
"</td><td>" + Node.nodeName +
"</td><td>" + Node.nodeValue +
"</td><td>" + ListAttributes(Node) +
"</td></tr>";
Node = Iterator.Next();
}
DOMText += "</table>";
document.getElementById("ShowDomTree").innerHTML = DOMText;
}
function ShowDomAsList()
{
var space_s = " ".repeat(20);
var DOMText = "<pre>" +
"Level" + space_s.substr(0, 15) + " // Type // Name // Value // Attributes\n\n";
var Iterator = new DOMIterator(document);
var Node = Iterator.First();
while (Node != null) {
DOMText += space_s.substr(0, 3*Iterator.Level) +
Iterator.Level.toString() +
space_s.substr(0, 20 - 3*Iterator.Level - 1) +
" // " + Node.nodeType +
" // " + Node.nodeName;
if (Node.nodeName == "#text") {
DOMText += " // [[" + Node.nodeValue + "]]";
} else {
DOMText += " // " + Node.nodeValue;
}
DOMText += " // " + ListAttributes(Node) +
"\n";
Node = Iterator.Next();
}
DOMText += "</pre>";
document.getElementById("ShowDomTree").innerHTML = DOMText;
}
function ListAttributes(Node_opl)
{
//debugger
var Content_s = "null";
if (Node_opl.attributes != null) {
Content_s = "";
for (var loop_i = 0;
loop_i < Node_opl.attributes.length;
loop_i++) {
// hier Attribute mit Wert null ausblenden,
// um die Anzeige zu vereinfachen
if (Node_opl.attributes[loop_i].nodeValue != null) {
Content_s += Node_opl.attributes[loop_i].nodeName + " : " +
Node_opl.attributes[loop_i].nodeValue + " / ";
}
}
}
return Content_s;
}
<file_sep>/WEB/p3/mhb/content/mhb_login.js
var selected;
function event_handler(event_opl){
if(event_opl.target.tagName.toLowerCase()=='td')
{
if (selected != undefined){
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "left";
}
selected = event_opl.target.parentNode.id;
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "center";
}// Klick auf Link zum Löschen
//Modulhandbuch Events
if(event_opl.target.id == "modulhandbuch"){
seite_anfragen("/modulhandbuch/" + selected.toString());
}
if(event_opl.target.id == "modulhandbuch_zurück"){
seite_anfragen("/studiengaenge/");
}
//Studiengang Events
if(event_opl.target.id == "create_studiengang"){
seite_anfragen("/add_sg/");
}
if(event_opl.target.id == "edit_studiengang"){
seite_anfragen("/edit_sg/" + selected.toString());
}
if(event_opl.target.id == "studiengang_speichern"){
form_abschicken("/save_sg/");
}
if(event_opl.target.id == "deleter_studiengang"){
seite_anfragen("/delete_sg/" + selected.toString());
}
//Module Events
if(event_opl.target.id == "create_modul"){
seite_anfragen("/add_m/");
}
if(event_opl.target.id == "edit_modul"){
seite_anfragen("/edit_m/" + selected.toString());
}
if(event_opl.target.id == "modul_speichern"){
form_abschicken("/save_m/");
}
if(event_opl.target.id == "deleter_modul"){
seite_anfragen("/delete_m/" + selected.toString());
}
//Lehrveranstaltungen Events
if(event_opl.target.id == "create_lv"){
seite_anfragen("/add_lv/");
}
if(event_opl.target.id == "edit_lv"){
seite_anfragen("/edit_lv/" + selected.toString());
}
if(event_opl.target.id == "lv_speichern"){
form_abschicken("/save_lv/");
}
if(event_opl.target.id == "deleter_lv"){
seite_anfragen("/delete_lv/" + selected.toString());
}
}
function form_abschicken(path) {
var data = new FormData(document.getElementById("idWTForm"));
console.log(data)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML =
this.responseText;
}
};
xhttp.open("POST", path, true);
xhttp.send(data);
}
function seite_anfragen(path) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML =
this.responseText;
}
};
xhttp.open("GET", path, true);
xhttp.send();
}
window.onload=function(){
let body_o = document.getElementById('body');
//let list_o = document.getElementById('idList');
//let button_modulhandbuch = document.getElementById('modulhandbuch');
body_o.addEventListener('click', event_handler, false)
//list_o.addEventListener('click',get_tabellenzeile,false);
//button_modulhandbuch.addEventListener('click', open_modulhandbuch, false);
}<file_sep>/WEB/Klausurvorbereitung/WEB/Praktika/p1/web/p1/webteams/app/view.py
# coding: utf-8
# sehr einfache Erzeugung des Markups f?r vollst?ndige Seiten
# jeweils 3 Abschnitte:
# - begin
# - content
# - end
# bei der Liste wird der content-Abschnitt wiederholt
# beim Formular nicht
import codecs
import os.path
import string
#---------------------------------------------------------
class View_cl(object):
#---------------------------------------------------------
#------------------------------------------------------
def __init__(self):
#------------------------------------------------------
pass
#------------------------------------------------------
def createList_px(self, data_opl):
#------------------------------------------------------
if data_opl != "None":
markup_s = ''
markup_s += self.readFile_p('list0.tpl')
markupV_s = self.readFile_p('list1.tpl')
lineT_o = string.Template(markupV_s)
# mehrfach nutzen, um die einzelnen Zeilen der Tabelle zu erzeugen
for loop_i in range(0,15):
data_a = data_opl[str(loop_i)]
markup_s += lineT_o.safe_substitute(name1_s=data_a[0]
, vorname1_s=data_a[1]
, matrnr1_s=data_a[2]
, name2_s=data_a[3]
, vorname2_s=data_a[4]
, matrnr2_s=data_a[5]
, id_s=str(loop_i)
)
markup_s += self.readFile_p('list2.tpl')
return markup_s
#------------------------------------------------------
def createForm_px(self, id_spl, data_opl):
#------------------------------------------------------
# hier m?sste noch eine Fehlerbehandlung erg?nzt werden !
if id_spl != "None" and data_opl != "None":
markup_s = ''
markup_s += self.readFile_p('form0.tpl')
markupV_s = self.readFile_p('form1.tpl')
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute(name1_s=data_opl[0]
, vorname1_s=data_opl[1]
, matrnr1_s=data_opl[2]
, name2_s=data_opl[3]
, vorname2_s=data_opl[4]
, matrnr2_s=data_opl[5]
, id_s=id_spl
)
markup_s += self.readFile_p('form2.tpl')
return markup_s
#------------------------------------------------------
def readFile_p(self,fileName_spl):
#------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('content', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF
<file_sep>/Mattes/4/app/application.py
# coding: utf-8
import json
import cherrypy
from .fehler import Fehler_cl
from .projekt import Project_cl
from .mitarbeiter import QSMitarbeiter_cl, SWEntwickler_cl
from .komponente import Component_cl
from .kategorie import KatFehler_cl, KatUrsache_cl
from .auswertung import KatList_cl, ProList_cl
# Method-Dispatching!
# -------------------------------------------------------
def adjustId_p(id_spl, data_opl):
# -------------------------------------------------------
if id_spl == None:
data_opl['id'] = ''
elif id_spl == '':
data_opl['id'] = ''
elif id_spl == '0':
data_opl['id'] = ''
else:
data_opl['id'] = id_spl
return data_opl
# ----------------------------------------------------------
# ----------------------------------------------------------
class Application_cl(object):
# ----------------------------------------------------------
exposed = True # gilt für alle Methoden
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.handler_o = {
'fehler': Fehler_cl(),
'projekt': Project_cl(),
'komponente': Component_cl(),
'qsmitarbeiter': QSMitarbeiter_cl(),
'swentwickler': SWEntwickler_cl(),
'katfehler': KatFehler_cl(),
'katursache': KatUrsache_cl(),
'prolist': ProList_cl(),
'katlist': KatList_cl()
}
# es wird keine index-Methode vorgesehen, weil stattdessen
# die Webseite index.html ausgeliefert wird (siehe Konfiguration)
# -------------------------------------------------------
def GET(self, path_spl, id=None):
# -------------------------------------------------------
retVal_o = {
'data': None
}
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].GET(id)
if retVal_o['data'] == None:
cherrypy.response.status = 404
return json.dumps(retVal_o)
# -------------------------------------------------------
def POST(self, path_spl, **data_opl):
# -------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].POST(data_opl)
if retVal_o['id'] == None:
cherrypy.response.status = 409
return json.dumps(retVal_o)
# -------------------------------------------------------
def PUT(self, path_spl, **data_opl):
# -------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].PUT(data_opl)
if retVal_o['id'] == None:
cherrypy.response.status = 404
return json.dumps(retVal_o)
# -------------------------------------------------------
def DELETE(self, path_spl, id=None):
# -------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if path_spl in self.handler_o:
retVal_o = self.handler_o[path_spl].DELETE(id)
if retVal_o['id'] == None:
cherrypy.response.status = 404
return json.dumps(retVal_o)
# -------------------------------------------------------
def default(self, *arguments, **kwargs):
# -------------------------------------------------------
msg_s = "unbekannte Anforderung: " + \
str(arguments) + \
' ' + \
str(kwargs)
raise cherrypy.HTTPError(404, msg_s)
# EOF
<file_sep>/WEB/Vorlesung/javascript_beispiele/proto4.js
class Rectangle {
constructor (length, width) {
this.length = length;
this.width = width;
}
getArea () {
return this.length * this.width;
}
toString () {
return "[Rectangle " + this.length + "x" + this.width + "]";
}
}
// Erbt von Rectangle
class Square extends Rectangle {
constructor (size) {
super(size, size); // Aufruf des Basisklassen-Constructor
}
toString () {
return "[Square " + this.length + "x" + this.width + "]";
}
}
var rect = new Rectangle(5, 10);
var square = new Square(6);
console.log(rect.getArea()); // 50
console.log(square.getArea()); // 36
console.log(rect.toString()); // "[Rectangle 5x10]"
console.log(square.toString()); // "[Square 6x6]"
console.log(rect instanceof Rectangle); // true
console.log(rect instanceof Object); // true
console.log(square instanceof Square); // true
console.log(square instanceof Rectangle); // true
console.log(square instanceof Object); // true
<file_sep>/WEB/WEB Praktika/mhb/app/articles.py
# coding: utf-8
import cherrypy
import datetime
from .database import Database_cl
from .view import View_cl
# GET /articles/all/ alle Artikel
# GET /articles/month/:month die Artikel, die im angegebenen Monat erstellt oder geändert wurden
# GET /articles/tag/:tag die Artikel, die die angegebene Marke enthalten
#----------------------------------------------------------
class Articles_cl(object):
#----------------------------------------------------------
exposed = True
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self, mode, parameter=None):
#-------------------------------------------------------
retVal_s = ''
if mode == 'all':
retVal_s = self.getList_p()
if mode == 'month':
retVal_s = self.getArticlesByMonth_p(parameter)
if mode == 'tag':
retVal_s = self.getArticlesByTag_p(parameter)
return retVal_s
#-------------------------------------------------------
def getList_p(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
# default-Werte entfernen
ndata_a = data_a[0:]
return self.view_o.createList_px(ndata_a)
#-------------------------------------------------------
def getArticlesByMonth_p(self, month):
#-------------------------------------------------------
# Format muss sein: 01.2018, also das Jahr muss einbezogen werden
year = month[3:7]
month = month[0:2]
data_a = self.db_o.read_px()
data_unsort = []
#--------------------------------
i = 0
for value in data_a:
if (int(value['chdat'][3:5]) == int(month) and int(value['chdat'][6:10]) == int(year)): # python slicing substring 4th element up to 5th element = month
data_unsort.append(value)
data_sort = []
data_unsort.sort(key=lambda x: x['chdat'])
data_sort = data_unsort[::-1]
return self.view_o.createList_px(data_sort)
#-------------------------------------------------------
def getArticlesByTag_p(self, tag):
#-------------------------------------------------------
data_a = self.db_o.read_px()
data_unsort = []
for value in data_a:
for valuetag in value['tag']:
if valuetag == tag:
data_unsort.append(value)
data_sort = []
data_unsort.sort(key=lambda x: x['chdat'])
data_sort = data_unsort[::-1]
return self.view_o.createList_px(data_sort)
# EOF<file_sep>/WEB/p1_sicherung/webteams/app/view.py
# coding: utf-8
# sehr einfache Erzeugung des Markups für vollständige Seiten
# jeweils 3 Abschnitte:
# - begin
# - content
# - end
# bei der Liste wird der content-Abschnitt wiederholt
# beim Formular nicht
import codecs
import os.path
import string
#----------------------------------------------------------
class View_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
pass
#-------------------------------------------------------
def createList_px(self, data_opl):
#-------------------------------------------------------
# hier müsste noch eine Fehlerbehandlung ergänzt werden !
markup_s = ''
markup_s += self.readFile_p('list0.tpl')
markupV_s = self.readFile_p('list1.tpl')
lineT_o = string.Template(markupV_s)
# mehrfach nutzen, um die einzelnen Zeilen der Tabelle zu erzeugen
for loop_i in range(0,15):
data_a = data_opl[str(loop_i)]
markup_s += lineT_o.safe_substitute (name1_s=data_a[0] # HIER müssen Sie eine Ergänzung vornehmen
, vorname1_s=data_a[1]
, matrnr1_s=data_a[2]
, name2_s=data_a[3]
, vorname2_s=data_a[4]
, matrnr2_s=data_a[5]
, id_s=str(loop_i)
)
markup_s += self.readFile_p('list2.tpl')
return markup_s
#-------------------------------------------------------
def createForm_px(self, id_spl, data_opl):
#-------------------------------------------------------
# hier müsste noch eine Fehlerbehandlung ergänzt werden !
markup_s = ''
markup_s += self.readFile_p('form0.tpl')
markupV_s = self.readFile_p('form1.tpl')
lineT_o = string.Template(markupV_s)
markup_s += lineT_o.safe_substitute (name1_s=data_opl[0] # HIER müssen Sie eine Ergänzung vornehmen
, vorname1_s=data_opl[1]
, matrnr1_s=data_opl[2]
, name2_s=data_opl[3]
, vorname2_s=data_opl[4]
, matrnr2_s=data_opl[5]
, id_s=id_spl
)
markup_s += self.readFile_p('form2.tpl')
return markup_s
#-------------------------------------------------------
def readFile_p(self, fileName_spl):
#-------------------------------------------------------
content_s = ''
with codecs.open(os.path.join('content', fileName_spl), 'r', 'utf-8') as fp_o:
content_s = fp_o.read()
return content_s
# EOF<file_sep>/WEB/WEB Praktika/mhb/static/xhr_c6.js
//------------------------------------------------------------------------------
// Anforderungen per XMLHTTPRequest
//------------------------------------------------------------------------------
'use strict'
if (APPETT == undefined) {
var APPETT = {};
}
APPETT.XHR_cl = class {
constructor () {
this.xhttp_o = new XMLHttpRequest();
this.xhttp_o.onreadystatechange = this.onreadystatechange_p.bind(this);
}
onreadystatechange_p () {
if (this.xhttp_o.readyState == 4 && this.xhttp_o.status == 200) {
this.success_p(this.xhttp_o.responseText);
} else if (this.xhttp_o.readyState == 4 && this.xhttp_o.status != 200) {
this.fail_p(this.xhttp_o.responseText);
}
}
request_px (path_spl, success_ppl, fail_ppl, method='GET', data_opl=null) {
this.success_p = success_ppl;
this.fail_p = fail_ppl;
this.xhttp_o.open(method, path_spl, true);
if(method != 'GET' && method != 'DELETE')
{
this.xhttp_o.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.xhttp_o.send(data_opl);
}
else
{
this.xhttp_o.send();
}
}
}
// EOF<file_sep>/Mattes/4/doc/doku.md
# WEB-Engeneering, Praktikum 4, Aufgabe: Bug-Tracker, <NAME>, 1018387
* ##1.0 Einleitung:
Der Bug-Tracker ist eine Web-Applikation basierend auf dem REST-Ansatz und umgesetzt in Javascript und Python. Aufgabe dieser Applikation ist das Speichern und Verarbeiten von Bug-Informationen. Zu diesem Zweck werden verschiedene Datensätze, die in Relation zu Bugs stehen, ebenfalls Verwaltet. Der Anwender kann Fehler protokollieren, Entwickler den Fehler zuweisen und Lösungen protokollieren und freigeben.
* ##2.0 Implementierung des Servers:
+ ###2.1 REST:
Der Server muss in der REST-Architektur einheitliche Schnittstellen bieten. Die Nachrichten müssen selbstbeschreibend sein. In diesem fall sind die durch die Standard-Methoden umgesetzt, die auf jeden Datenbestand anwendbar sind. Das Server-System ist mehrschichtig, wobei nur die Standard-Methoden "Exposed" sind. Der Server verwaltet keine Zustände.
+ ###2.2 Module:
- Application.py:
1. Application_cl:
Klasse die die Http-Anfragen Handelt. Alle Methoden dieser Klasse sind Exposed.
- database.py:
1. Database_cl
2. Ableitung der Klasse database_cl für jeden geführten Datensatz mit der überschriebenen Methode getDefault()
- navigation.py:
1. Navigation_cl:
Liefert alle Navigations-Elemente für die Webanwedung. Die Methode GET() ist Exposed.
- template.py:
1. Template_cl:
Liefert alle Templates für die Webanwedung. Die Methode GET() ist Exposed.
- fehler.py:
1. Fehler_cl:
Handler für die Http-Methoden
- projekt.py:
1. Projekt_cl:
Handler für die Http-Methoden
- komponente.py:
1. Komponente_cl:
Handler für die Http-Methoden
- kategorie.py:
1. katfehler_cl:
Handler für die Http-Methoden
2. katursache_cl:
handler für die Http-Methoden
- mitarbeiter.py:
1. SWEntwickler_cl:
handler für die Http-Methoden
2. QSMitarbeiter_cl:
Handler für die Http-Methoden
- Zusamenspiel der Klassen:
Die Klasse Application_cl nimmt die Standard Nachrichten entgegen und wählt die Handler-Klasse aus auf der die Methode aufgerufen werden soll. Diese Handler Klasse stellt dann die Nachricht zusammen die zurück geliefert wird und greift dabei auf die jeweilige abgeleitete Database-Klasse zu um die Datensätze manipilieren zu können oder zu lesen. Die Database-Klassen lesen und schreiben die Daten direkt aus dem Dateisystem des Servers. Die Klassen Navigation_cl und Template_cl sind direkt Ansprechbar von aussen und lifern bloß die Beschrieben Daten auf Anfrage an den Klienten.
+ ###2.3 Datenhaltung:
Datensätze werden im Json-Format, einzelnt in .dat Textdateien gespeicher. Wobei der Übergeordnete Ordner die Bezeichnung des Datensatz-Typ trägt und die Datensätze selber die ID als Bezeichner haben. In jedem dieser Ordner ist noch zusätzlich eine Datei ("maxid.dat") die als Zähler für die einmalige Vergabe einer ID fungiert.
* ##3.0 Implementierung des Klients:
+ ###3.1 Klassen:
1. Application_cl:
Diese Klasse Steuert welche Inhalte im Grundgerüst der Webanwendung dargestellt werden.
2. ListView_cl:
Diese Klasse fragt auf befehl hin nach aktuellen Daten beim Server und generiert daraus Markup, was dann in den Content-Bereich geschrieben wird. Zusätzlich fängt sie auch noch alle Events ab die mit dem generierten Markup erzeugt werden können. Sie ist speziell für Listen.
3. DetailView_cl:
Diese Klasse fragt auf befehl hin nach aktuellen Daten beim Server und generiert daraus Markup, was dann in den Content-Bereich geschrieben wird. Zusätzlich fängt sie auch noch alle Events ab die mit dem generierten Markup erzeugt werden können. Sie ist speziell für Formulare.
4. Nav_cl:
Diese Klasse fragt auf befehl hin nach aktuellen Daten beim Server und generiert daraus Markup, was dann in den Content-Bereich geschrieben wird. Zusätzlich fängt sie auch noch alle Events ab die mit dem generierten Markup erzeugt werden können. Sie ist speziell für die Navigation.
5. MenuView_cl:
Diese Klasse erstellt ein Menu für den Content bereich und fängt alle Events ab die damit erzeugt werden können.
6. EventService_cl:
Diese Klasse ist nötig für die asynchrone Kommunikation zwischen den Klassen. Sie ermöglicht es eine Methode einer Klasse zu hinterlegen, die dann asynchron auf die Nachrichten anderer Klassen aufgerufen werden kann.
7. TemplateManager_cl:
Diese Klasse erzeugt aus Nutzdaten und einem passenden Template Markup.
- Zusammenspiel der Klassen:
Die EventService-Klasse wird zu erst Initiallisiert und daraufhin die Application-Klasse. Im Konstruktor der Application_cl "subscribed" diese Klasse unter der "Rubrik" APP. Das macht sie in dem sie eine Referenz auf die eigene Instanz der Klasse, die Nachricht "APP" und die "Notify"-Methode übergibt. Welche auf den Befehl "App" aufgerufen werden soll. Wenn das Passiert ist wird die Erste Nachricht Publiziert, die der Application_cl den befehl gibt den Klienten zu Initallisieren. Das macht sie in dem sie eine neue Instanz der TemplateManager-Klasse im simulierten Namensraum "APP" erstellt. Die bei erfolgreichem Laden der Templates vom Server einen neue Nachricht Publiziert, die der Application_cl grünes Licht gibt für die Verwendung dieser und als erstes die Navigation füllt. Daraufhin kann die Logik hinter der Navigation ebenfalls Nachrichten über den Eventservice an Application_cl schicken, damit diese den Content-Bereich füllen kann. Alle Klassen die Hinter dem Markup für den Content-Bereich stehen, kommunizieren ebenfalls auf dem gleichen weg mit der Application-Klasse. Die Application_cl kann die Instanzen der Klassen für den Content- und Navigation-Bereich direkt erreichen in dem sie die Methoden dieser Aufruft.
+ ###3.2 Eventservice:
Siehe Zusammenspiel der Klassen in 3.1.
+ ###3.3 Templates:
Jedes template besteht aus drei prinzipiell gleichen Bereichen: Dem Header-, dem Content- und dem Menu-Bereich. Der größte Unterschied besteht im Content. Denn der Header soll nur zeigen wo man ist und das menu wird mit button gefüllt dessen Funktion vom Content-Bereich abhängt. Im Prinzip gibt es zwei Sorten von Templates in dieser Web-Anwendung: Die Listen und die Formulare. Die Listen erzeugen aus den Nutzdaten eine übersichtliche Tabelle. Die Formulare werden mit den übergebenen Nutzdaten gefüllt. Die Formulare werden durch die Menüpunkte der Listen aufgerufen und mit, aus der Liste gewählten, Datensätzen gefüllt.
- Beispiel Liste:

- Beispiel Formular:

* 4.0 Markup Validierung:
+ CSS: Wurde auf CSS Level 3 Validiert
+ index.html: Wurde ohne Fehler Validiert
+ Templates: Wurden ohne Fehler Validiert
<file_sep>/WEB/WEB Praktika/pl/app/database.py
# coding: utf-8
# Demonstrator!
import os
import os.path
import codecs
import json
import cherrypy
#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.pensionaere = [
{
"id":"0",
"Anrede": "-0",
"Name":"Mustermann",
"Vorname":"Max",
"Titel": " - ",
"Geburtsdatum": "31.08.1918",
"Strasse":"Teststrasse",
"Hausnummer":"1234",
"Adresszusatz":" - ",
"Postleitzahl": "47804",
"Ort":"Krefeld"
},
{
"id":"1",
"Anrede": "-1",
"Name":"Mustermann1",
"Vorname":"Max1",
"Titel": " -1 ",
"Geburtsdatum": "31.08.1828",
"Strasse":"Teststrasse 1",
"Hausnummer":"1234 1",
"Adresszusatz":" - 1",
"Postleitzahl": "47804 1",
"Ort":"Krefeld 1"
},
{
"id":"2",
"Anrede": "-2",
"Name":"Mustermann2",
"Vorname":"Max2",
"Titel": " -2 ",
"Geburtsdatum": "22.03.1938",
"Strasse":"Teststrasse 2",
"Hausnummer":"1234 2",
"Adresszusatz":" - 2",
"Postleitzahl": "47804 2",
"Ort":"Krefeld 2"
},
{
"id":"3",
"Anrede": "-3",
"Name":"Mustermann3",
"Vorname":"Max3",
"Titel": " -3 ",
"Geburtsdatum": "01.07.1908",
"Strasse":"Teststrasse 3",
"Hausnummer":"1234 3",
"Adresszusatz":" - 3",
"Postleitzahl": "47804 3",
"Ort":"Krefeld 3"
}
]
self.Congrats = [
{
"ID":"0",
"Beschreibung":"WatWeissIch",
"Path":"DaVorne"
},
{
"ID":"1",
"Beschreibung":"WatWeissIch1",
"Path":"DaVorne1"
},
{
"ID":"2",
"Beschreibung":"WatWeissIch2",
"Path":"DaVorne2"
}
]
self.readData()
self.readCongrats()
def saveCongrats(self):
with codecs.open(os.path.join('congratstempl', 'congrats.json'), 'w', 'utf-8') as file_x:
json.dump(self.Congrats, file_x)
def readCongrats(self):
try:
file_x = codecs.open(os.path.join('congratstempl', 'congrats.json'), 'r', 'utf-8')
except: #falls datei nicht vorhanden ist: datei anlegen durch speichern der werte
#speichere daten in josn datein
self.saveCongrats()
else:
with file_x:
self.Congrats = json.load(file_x)
self.saveCongrats()
#-------------------------------------------------------------------------
def saveData(self):
with codecs.open(os.path.join('data', 'daten.json'), 'w', 'utf-8') as file_x:
json.dump(self.pensionaere, file_x)
def readData(self):
try:
file_x = codecs.open(os.path.join('data', 'daten.json'), 'r', 'utf-8')
except: #falls datei nicht vorhanden ist: datei anlegen durch speichern der werte
#speichere daten in josn datein
self.saveData()
else:
with file_x:
self.pensionaere = json.load(file_x)
self.saveData()
#-------------------------------------------------------
def read_px(self, id_spl = None):
#-------------------------------------------------------
data_o = None
if id_spl == None:
data_o = self.pensionaere
else:
id_i = int(id_spl)
if id_i > 0 and id_i < len(self.pensionaere):
data_o = self.pensionaere[id_i]
else:
data_o = self.pensionaere[0]
return data_o
# EOF<file_sep>/WEB/WEB Praktika/mhb/app/tags.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
# GET /tags/ alle Marken und die Anzahl der Artikel
#----------------------------------------------------------
class Tags_cl(object):
#----------------------------------------------------------
exposed = True
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self):
#-------------------------------------------------------
data_a = self.db_o.read_px()
retVal_s = ''
data_tag = []
for value in data_a:
for tagvalue in value['tag']:
if tagvalue not in data_tag:
data_tag.append(tagvalue)
# return tags with occurring numbers
data_return = {}
i = 0
for value in data_tag:
data_single = {}
data_single['tag'] = value
#find data with tag
count = 0
for article in data_a:
if value in article['tag']:
count = count + 1
data_single['count'] = count
data_return[i] = data_single
i = i + 1
retVal_s = self.view_o.createList_px(data_return)
return retVal_s
# EOF<file_sep>/p1/webteams/.metadata/version.ini
#Fri Oct 20 15:24:57 CEST 2017
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.1.v20171009-0410
<file_sep>/WEB/p2_sicherung2/mhb/doc/mhd.md
Name: <NAME>\
Matrikelnummer: 1121869\
Gruppe: B\
Datum: 30.11.2017\
**Allgemeine Beschreibung der Lösung:**
Aufgabe der Anwendung:
Mit der Webanwendung werden die Beschreibungen der Studiengänge und Module abgerufen bzw. gepflegt.
Übersicht der fachlichen Funktionen:
Mit der Anwendung soll es möglich sein, neben der Datenpflege ein Modulhandbuch zu erstellen:
• das Modulhandbuch zu einem Studiengang enthält
◦ die Zusammenstellung der Angaben zum Studiengang
◦ eine Übersicht mit allen Lehrveranstaltungen, alphabetisch sortiert
▪ auch die Modulverantwortlichen werden aufgeführt
einen detaillierten Semesterplan:
▪ vom 1. bis zum letzten Semester des Studiengangs werden die Lehrveranstaltungen mit allen Daten ausgewiesen
▪ die je Semester erzielbaren Kreditpunkte werden ausgewiesen
▪ die insgesamt erzielbaren Kreditpunkte werden ausgewiesen
• es werden drei Rollen vorgesehen:
Rolle "Studierender":
▪ kann alle Studiengänge einsehen
▪ kann zu jedem Studiengang das Modulhandbuch abrufen
Rolle "Verantwortlicher Modul":
▪ kann die Daten der ihm zugewiesenen Module bearbeiten (aber keine Module erstellen oder löschen!)
▪ kann alle Studiengänge einsehen
▪ kann zu jedem Studiengang das Modulhandbuch abrufen
Rolle "Verantwortlicher Studiengang":
▪ erstellt und pflegt die Studiengänge
▪ erstellt die Module (gibt dabei nur Bezeichnung an - Pflege der weiteren Inhalte siehe andere Rolle)
▪ legt die Zuordnung der Benutzer der Rolle "Verantwortlicher Modul" zu Modulen fest
▪ kann Module löschen
▪ legt die Struktur eines Studiengangs anhand der Lehrveranstaltungen in den einzelnen Semestern fest
▪ legt die Zuordnung der Module zu Lehrveranstaltungen fest
▪ legt die Modulabhängigkeiten (Voraussetzungen) fest
**Beschreibung der Komponenten des Servers:**
Application_cl:
- stellt die Verbindung zwischen Database_cl und View_cl her
Database_cl:
- liest, bearbeitet, erstellt Einträge in den zugehörigen .json Dateien
View_cl:
- liest die erstellten Templates ein und gibt die Sicht der zugehörigen Anwendung aus
**Datenablage:**
web
/p2
/mhd
/app
/_init_.py <-- Initialisierung
/application.py <-- Anwendung
/database.py <-- Datenbasis
/view.py <-- Sicht
/content
/mhb.css
/mhb.js
/data
/benutzer.json <-- Daten
/studiengaenge.json
/module.json
/lehrveranstaltungen.json
/doc
/template
/form_anmeldung_benutzername.tpl <-- Formulare
/form_module_1.tpl
/form_module_2.tpl
/form_module_3.tpl
/form_studiengaenge_1.tpl
/form_studiengaenge_2.tpl
/form_studiengaenge_3.tpl
/liste_studiengaenge_module.tpl <--- Listen
**Durchgeführte Ergänzungen:**
- Dateneingabe für die Daten des 2. Team-Mitglieds im Formular
- zusätzliches Attribut "Semesteranzahl" (für beide Teammitglieder) in allen Listen und Formularen
sowie in der Datenbasis
- Aktion "Abbrechen" im Formular implementiert
- Gestaltung mit CSS: CSS-Stilregeln in die Datei webteams.css eingetragen
- Löschen der Daten eines Teams auf der Serverseite implementiert (siehe Datei database.py)
- Rückfrage an den Benutzer beim Löschen von Einträgen in der Liste Datei webteams.js <file_sep>/WEB/WEB Praktika/mhb/app/article.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
# GET /article/:id
# POST /article/ + Daten neuen Artikel mit den angegebenen Daten erstellen und id vergeben
# PUT /article/:id + Daten bestehenden Artikel aktualisieren
# DELETE /article/:id bestehenden Artikel löschen
#----------------------------------------------------------
class Article_cl(object):
#----------------------------------------------------------
exposed = True
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
self.db_o = Database_cl()
self.view_o = View_cl()
#-------------------------------------------------------
def GET(self, id):
#-------------------------------------------------------
data_o = self.db_o.read_px(id)
return self.view_o.createList_px(data_o)
#-------------------------------------------------------
def POST(self, **data_opl):
#-------------------------------------------------------
if data_opl is None:
return "-1"
else:
return self.db_o.create_px(data_opl)
#-------------------------------------------------------
def PUT(self, **data_opl):
#-------------------------------------------------------
if data_opl is None:
return "-1"
else:
return self.db_o.update_px(data_opl['id'], data_opl)
#-------------------------------------------------------
def DELETE(self, id):
#-------------------------------------------------------
if id is None:
return "-1"
else:
return self.db_o.delete_px(id)
# EOF<file_sep>/Mattes/4/app/fehler.py
import json
import cherrypy
from .database import fehlerDatabase_cl, katursacheDatabase_cl, katfehlerDatabase_cl, komponenteDatabase_cl, qsmitarbeiterDatabase_cl, swentwicklerDatabase_cl
# -------------------------------------------------------
def adjustId_p(id_spl, data_opl):
# -------------------------------------------------------
if id_spl == None:
data_opl['id'] = ''
elif id_spl == '':
data_opl['id'] = ''
elif id_spl == '0':
data_opl['id'] = ''
else:
data_opl['id'] = id_spl
return data_opl
# ----------------------------------------------------------
class Fehler_cl(object):
# ----------------------------------------------------------
# -------------------------------------------------------
def __init__(self):
# -------------------------------------------------------
self.db_o = fehlerDatabase_cl()
# -------------------------------------------------------
def GET(self, id):
# -------------------------------------------------------
retVal_o = {
'data': None,
'komp': None,
'katfehler': None,
'katursache': None,
'qsmitarbeiter': None,
'swentwickler': None
}
if id == None:
# Anforderung der Liste
retVal_o['data'] = self.db_o.read_px()
elif id == 'behoben':
retVal_o['data'] = {}
data_opl = self.db_o.read_px()
#Füllen mit den Datensätzen die mit 'behoben' markiert sind
for key in data_opl:
if data_opl[key]['status'] == 'behoben':
retVal_o['data'].update({key: ''})
retVal_o['data'][key] = data_opl[key]
elif id == 'erkannt':
retVal_o['data'] = {}
data_opl = self.db_o.read_px()
# Füllen mit den Datensätzen die mit 'erfasst' markiert sind
for key in data_opl:
if data_opl[key]['status'] == 'erkannt':
retVal_o['data'].update({key: ''})
retVal_o['data'][key] = data_opl[key]
else:
# Anforderung eines Dokuments
data_o = self.db_o.read_px(id)
if data_o != None:
retVal_o['data'] = adjustId_p(id, data_o)
db_opl = komponenteDatabase_cl()
retVal_o['komp'] = db_opl.read_px()
db_opl = katfehlerDatabase_cl()
retVal_o['katfehler'] = db_opl.read_px()
db_opl = katursacheDatabase_cl()
retVal_o['katursache'] = db_opl.read_px()
db_opl = qsmitarbeiterDatabase_cl()
retVal_o['qsmitarbeiter'] = db_opl.read_px()
db_opl = swentwicklerDatabase_cl()
retVal_o['swentwickler'] = db_opl.read_px()
return retVal_o
# -------------------------------------------------------
def POST(self, data_opl):
# -------------------------------------------------------
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
id_s = data_opl["id_s"]
data_o = {
'kompid': data_opl['kompid_s'],
'status': data_opl['status_s'],
'zustand': data_opl['zustand_s'],
'bug': {
'beschreibung': data_opl['bugbeschreibung_s'],
'katid': data_opl['bugkatid_s'],
'datum': data_opl['bugdatum_s'],
'empid': data_opl['bugempid_s']
},
'fix': {
'beschreibung': data_opl['fixbeschreibung_s'],
'katid': data_opl['fixkatid_s'],
'datum': data_opl['fixdatum_s'],
'empid': data_opl['fixempid_s']
}
}
# Create-Operation
if self.db_o.update_px(id_s, data_o):
retVal_o['id'] = id_s
else:
retVal_o['id'] = None
return retVal_o
# -------------------------------------------------------
def PUT(self, data_opl):
# -------------------------------------------------------
# Sichern der Daten: jetzt wird keine vollständige Seite
# zurückgeliefert, sondern nur noch die Information, ob das
# Speichern erfolgreich war
retVal_o = {
'id': None
}
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
data_o = {
'kompid': data_opl['kompid_s'],
'status': data_opl['status_s'],
'zustand': data_opl['zustand_s'],
'bug': {
'beschreibung': data_opl['bugbeschreibung_s'],
'katid': data_opl['bugkatid_s'],
'datum': data_opl['bugdatum_s'],
'empid': data_opl['bugempid_s']
},
'fix': {
'beschreibung': data_opl['fixbeschreibung_s'],
'katid': data_opl['fixkatid_s'],
'datum': data_opl['fixdatum_s'],
'empid': data_opl['fixempid_s']
}
}
# Update-Operation
retVal_o['id'] = self.db_o.create_px(data_o)
return retVal_o
# -------------------------------------------------------
def DELETE(self, id):
# -------------------------------------------------------
# Eintrag löschen, nur noch Rückmeldung liefern
retVal_o = {
'id': id
}
if self.db_o.delete_px(id):
pass
else:
retVal_o['id'] = None
return retVal_o<file_sep>/WEB/WEB Praktika/mhb/static/main_c6.js
//------------------------------------------------------------------------------
//Demonstrator es/te/tm - Variante mit ES6-Classes
//------------------------------------------------------------------------------
// hier zur Vereinfachung (!) die Klassen in einer Datei
class mainscreen_cl
{
constructor (el_spl) {
this.el_s = el_spl;
this.configHandleEvent_p();
}
render_px () {
let path_s = "/months/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
setTimeout(function(){this.doRender_p(data_o)}.bind(this),5000);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
var i;
var monat = [];
for (i=0;i<data_opl.length;i++){
if(data_opl[i][0]=="0"){
if(data_opl[i][1]=="1"){
monat.push("Januar");
}
if(data_opl[i][1]=="2"){
monat.push("Februar");
}
if(data_opl[i][1]=="3"){
monat.push("Marz");
}
if(data_opl[i][1]=="4"){
monat.push("April");
}
if(data_opl[i][1]=="5"){
monat.push("Mai");
}
if(data_opl[i][1]=="6"){
monat.push("Juni");
}
if(data_opl[i][1]=="7"){
monat.push("Juli");
}
if(data_opl[i][1]=="8"){
monat.push("August");
}
if(data_opl[i][1]=="9"){
monat.push("September");
}
}else if(data_opl[i][0]=="1"){
if(data_opl[i][1]=="0"){
monat.push("Oktober");
}
if(data_opl[i][1]=="1"){
monat.push("November");
}
if(data_opl[i][1]=="2"){
monat.push("Dezember");
}
}
}
var data_s =[];
data_s[0]=[];
data_s[1]=[];
setTimeout( function(){
let path_s = "/articles/month/" + data_opl[0];
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
data_s[0].push(JSON.parse(responseText_spl));
//data_temp = data_o[0];
//data_o[0].push(data_temp);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}.bind(this),200);
data_s[1] =monat;
setTimeout(function(){
let markup_s = APPETT.tm_o.execute_px("month.tpl.html", data_s);
//let el_o = document.querySelector(this.el_s);
let el_o = document.getElementById("idContent");
if (el_o != null) {
el_o.innerHTML = markup_s;
}}.bind(this),300);
}
configHandleEvent_p () {
//this.sideView_o.configHandleEvent_p();
}
handleEvent_p (event_opl) {
//this.sideView_o.handleEvent_p(event_opl);
}
}
'use strict'
class tags_cl{
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
let path_s = "/tags/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
//let el_o = document.querySelector(this.el_s);
let el_o = document.getElementById("tags");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
//let el_o = document.querySelector(this.el_s);
let el_o = document.getElementById("tags");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "idShowListEntry") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["detail", elx_o.id] );
}
event_opl.preventDefault();
}
}
}
class monthauswahl_cl{
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
this.listView_o = new ListView_cl("div", "listside.tpl.html");
}
render_px () {
let path_s = "/months/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
var i;
var monat = [];
for (i=0;i<data_opl.length;i++){
if(data_opl[i][0]=="0"){
if(data_opl[i][1]=="1"){
monat.push("Januar");
}
if(data_opl[i][1]=="2"){
monat.push("Februar");
}
if(data_opl[i][1]=="3"){
monat.push("Marz");
}
if(data_opl[i][1]=="4"){
monat.push("April");
}
if(data_opl[i][1]=="5"){
monat.push("Mai");
}
if(data_opl[i][1]=="6"){
monat.push("Juni");
}
if(data_opl[i][1]=="7"){
monat.push("Juli");
}
if(data_opl[i][1]=="8"){
monat.push("August");
}
if(data_opl[i][1]=="9"){
monat.push("September");
}
}else if(data_opl[i][0]=="1"){
if(data_opl[i][1]=="0"){
monat.push("Oktober");
}
if(data_opl[i][1]=="1"){
monat.push("November");
}
if(data_opl[i][1]=="2"){
monat.push("Dezember");
}
}
}
var data_s =[];
data_s[0]=[];
data_s[1]=[];
temp=[]
var j=0;
for (j=0; j< data_opl.length;j++){
var temp=[];
temp[j]=j;
setTimeout( function(){
let path_s = "/articles/month/" + data_opl[j];
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
data_s[0].push(JSON.parse(responseText_spl));
//data_temp = data_o[0];
//data_o[0].push(data_temp);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}.bind(this),3000*j);
}
data_s[1] =monat;
setTimeout(function(){
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_s);
//let el_o = document.querySelector(this.el_s);
let el_o = document.getElementById("hist");
if (el_o != null) {
el_o.innerHTML = markup_s;
}}.bind(this),30000);
}
configHandleEvent_p () {
//let el_o = document.querySelector(this.el_s);
let el_o = document.getElementById("hist");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
var value = event_opl.target.id;
}}
class DetailView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
}
render_px (id_spl) {
// Daten anfordern
let path_s = "/app/" + id_spl;
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("Detail - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.innerHTML = markup_s;
this.configHandleEvent_p();
}
}
configHandleEvent_p () {
let el_o = document.querySelector("form");
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.id == "idBack") {
APPETT.es_o.publish_px("app.cmd", ["idBack", null]);
event_opl.preventDefault();
let path_s = "/articles/";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
}.bind(this),
function (responseText_spl) {
alert("ListCon - render failed");
},
'POST',
);
}
}
}
class ListView_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px () {
// Daten anfordern
//month ausgabe
let path_s = "/articles/all";
APPETT.xhr_o.request_px(path_s,
function (responseText_spl) {
let data_o = JSON.parse(responseText_spl);
this.doRender_p(data_o);
}.bind(this),
function (responseText_spl) {
alert("List - render failed");
}
);
}
doRender_p (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
let el_o = document.getElementById("hist");
if(this.el_s == "main"){
el_o = document.querySelector(this.el_s);
}
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.getElementById("hist");
if(this.el_s == "main"){
el_o = document.querySelector(this.el_s);
}
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
if (event_opl.target.tagName.toUpperCase() == "TD") {
let elx_o = document.querySelector(".clSelected");
if (elx_o != null) {
elx_o.classList.remove("clSelected");
}
event_opl.target.parentNode.classList.add("clSelected");
event_opl.preventDefault();
} else if (event_opl.target.id == "idShowListEntry") {
let elx_o = document.querySelector(".clSelected");
if (elx_o == null) {
alert("Bitte zuerst einen Eintrag auswählen!");
} else {
APPETT.es_o.publish_px("app.cmd", ["detail", elx_o.id] );
}
event_opl.preventDefault();
}
}
}
class SideBarList_cl {
constructor (el_spl, template_spl) {
this.el_s = el_spl;
this.template_s = template_spl;
this.configHandleEvent_p();
}
render_px (data_opl) {
let markup_s = APPETT.tm_o.execute_px(this.template_s, data_opl);
//div mit id und nicht querysel
//let el_o = document.querySelector(this.el_s);
let el_o = document.getElementById("allArt"); //div mit id allArt
if (el_o != null) {
el_o.innerHTML = markup_s;
}
}
configHandleEvent_p () {
let el_o = document.getElementById("allArt"); //div mit id allArt
//let el_o = document.querySelector(this.el_s);
if (el_o != null) {
el_o.addEventListener("click", this.handleEvent_p);
}
}
handleEvent_p (event_opl) {
let cmd_s = event_opl.target.dataset.action;
APPETT.es_o.publish_px("app.cmd", [cmd_s, null]);
}
}
class SideBar_cl {
constructor (el_spl) {
this.listView_o = new monthauswahl_cl("div", "monthauswahl.tpl.html");
this.sideView_o = new SideBarList_cl("div","sidebar.tpl.html")
this.tags_o = new tags_cl("div","tags.tpl.html")
this.el_s = el_spl;
this.configHandleEvent_p();
}
render_px (data_opl) {
this.sideView_o.render_px(data_opl);
setTimeout(function(){this.tags_o.render_px()}.bind(this),8000);
setTimeout(function(){this.listView_o.render_px()}.bind(this),12000);
}
configHandleEvent_p () {
this.sideView_o.configHandleEvent_p();
}
handleEvent_p (event_opl) {
this.sideView_o.handleEvent_p(event_opl);
}
}
class Application_cl {
constructor () {
// Registrieren zum Empfang von Nachrichten
APPETT.es_o.subscribe_px(this, "templates.loaded");
APPETT.es_o.subscribe_px(this, "templates.failed");
APPETT.es_o.subscribe_px(this, "app.cmd");
this.sideBar_o = new SideBar_cl("aside");
this.listView_o = new ListView_cl("main","list.tpl.html");
this.detailView_o = new DetailView_cl("main", "detail.tpl.html");
this.mainscreen_o = new mainscreen_cl("main","month.tpl.html")
}
notify_px (self, message_spl, data_opl) {
switch (message_spl) {
case "templates.failed":
alert("Vorlagen konnten nicht geladen werden.");
break;
case "templates.loaded":
// Templates stehen zur Verfügung, Bereiche mit Inhalten füllen
// hier zur Vereinfachung direkt
let markup_s;
let el_o;
markup_s = APPETT.tm_o.execute_px("header.tpl.html", null);
el_o = document.querySelector("header");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
//footer wird nicht benötigt - siehe anforderung
/*
markup_s = APPETT.tm_o.execute_px("footer.tpl.html", null);
el_o = document.querySelector("footer");
if (el_o != null) {
el_o.innerHTML = markup_s;
}*/
let nav_a = [
["home", "Startseite"],
["list", "Alle"]
];
self.sideBar_o.render_px(nav_a);
markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
el_o = document.querySelector("main");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
self.mainscreen_o.render_px();
break;
case "app.cmd":
// hier müsste man überprüfen, ob der Inhalt gewechselt werden darf
switch (data_opl[0]) {
case "home":
let markup_s = APPETT.tm_o.execute_px("home.tpl.html", null);
let el_o = document.querySelector("main");
if (el_o != null) {
el_o.innerHTML = markup_s;
}
break;
case "list":
// Daten anfordern und darstellen
this.listView_o.render_px();
break;
case "detail":
this.detailView_o.render_px(data_opl[1]);
break;
case "idBack":
APPETT.es_o.publish_px("app.cmd", ["list", null]);
break;
}
break;
}
}
}
window.onload = function () {
APPETT.xhr_o = new APPETT.XHR_cl();
APPETT.es_o = new APPETT.EventService_cl();
var app_o = new Application_cl();
APPETT.tm_o = new APPETT.TemplateManager_cl();
}<file_sep>/WEB/p3/mhb/content/mhb.js
var selected;
function get_tabellenzeile(event_opl){
if(event_opl.target.tagName.toLowerCase()=='td')
{
if (selected != undefined){
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "left";
}
selected = event_opl.target.parentNode.id;
var tmp = document.getElementById(selected.toString())
tmp.style.textAlign = "center";
}
}
/*
function delete_eintrag_studiengang() {
if (confirm("Wollen Sie diesen Eintrag wirklich löschen? " + selected.toString())){
document.location.href = "/delete_sg/" + selected.toString();
}
}
function edit_eintrag_studiengang() {
if (confirm("Wollen Sie diesen Eintrag wirklich bearbeiten? " + selected.toString())){
document.location.href = "/edit_sg/" + selected.toString();
}
}
function delete_eintrag_modul() {
if (confirm("Wollen Sie diesen Eintrag wirklich löschen? " + selected.toString())){
document.location.href = "/delete_m/" + selected.toString();
}
}
function edit_eintrag_modul() {
if (confirm("Wollen Sie diesen Eintrag wirklich bearbeiten? " + selected.toString())){
document.location.href = "/edit_m/" + selected.toString();
}
}
*/
function open_modulhandbuch() {
path = document.location.href = "/modulhandbuch/" + selected.toString();
seite_anfragen(path);
}
function form_abschicken(path) {
var data = new FormData(document.getElementById("idWTForm"));
console.log(data);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML =
this.responseText;
}
};
xhttp.open("POST", path, true);
xhttp.send(data);
}
function seite_anfragen(path) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML =
this.responseText;
}
};
xhttp.open("GET", path, true);
xhttp.send();
}
window.onload=function(){
let list_o = document.getElementById("idList");
/*let button_delete = document.getElementById('deleter_studiengang');
let button_delete_m = document.getElementById('deleter_modul');
let button_edit = document.getElementById('edit_studiengang');
let button_edit_m = document.getElementById('edit_modul');
*/
let button_modulhandbuch = document.getElementById('modulhandbuch');
list_o.addEventListener('click',get_tabellenzeile, false);
/*
button_delete.addEventListener('click', delete_eintrag_studiengang, false);
button_delete_m.addEventListener('click', delete_eintrag_modul, false);
button_edit.addEventListener('click', edit_eintrag_studiengang, false);
button_edit_m.addEventListener('click', edit_eintrag_modul, false);
*/
button_modulhandbuch.addEventListener('click', open_modulhandbuch, false);
}
<file_sep>/WEB/WEB Praktika/Andi + Timo/mhb/templates/formVerantwortlicherModul.tpl.py
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1513178954.0201094
_enable_loop = True
_template_filename = '/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formVerantwortlicherModul.tpl'
_template_uri = 'formVerantwortlicherModul.tpl'
_source_encoding = 'utf-8'
_exports = ['header']
def _mako_get_namespace(context, name):
try:
return context.namespaces[(__name__, name)]
except KeyError:
_mako_generate_namespaces(context)
return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
pass
def _mako_inherit(template, context):
_mako_generate_namespaces(context)
return runtime._inherit_from(context, 'layout.tpl', _template_uri)
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
def header():
return render_header(context._locals(__M_locals))
data_modul = context.get('data_modul', UNDEFINED)
data_o = context.get('data_o', UNDEFINED)
__M_writer = context.writer()
__M_writer('\r\n')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'header'):
context['self'].header(**pageargs)
__M_writer('\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_header(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
def header():
return render_header(context)
data_modul = context.get('data_modul', UNDEFINED)
data_o = context.get('data_o', UNDEFINED)
__M_writer = context.writer()
__M_writer('\r\n\t<body>\r\n\t\t<table style="text-align:center;">\r\n\t\t<h1>Form Lehrender Modul</h1>\r\n\t\t<br>\r\n\t\t\t<select id="studiengang" name="studiengang">\r\n\t\t\t\t<option value="0">Wählen Sie Ihren Studiengang:</option>\r\n')
for a in data_o.values():
__M_writer('\t\t\t\t\t<option value="')
__M_writer(str(a[1]))
__M_writer('">')
__M_writer(str(a[0]))
__M_writer('</option>\r\n')
__M_writer('\t\t\t</select>\r\n\t\t\t<button id = "buttonstud">Studienganginfos und Modulhandbuch anzeigen</button>\r\n\t\t\t<p />\r\n\t\t\t<select id="modul" name="modul">\r\n\t\t\t\t<option value="0">Wählen Sie Ihr Modul aus:</option>\r\n')
for b in data_modul.values():
__M_writer('\t\t\t\t\t<option value="')
__M_writer(str(b[0]))
__M_writer('">')
__M_writer(str(b[0]))
__M_writer('</option>\r\n')
__M_writer('\t\t\t</select><br>\r\n\t\t\t<button id="buttonmoduledit">Modul Bearbeiten</button><br>\r\n\t\t\t<p />\r\n\t\t\t<form action="/" method="POST">\r\n\t\t\t\t<button type="submit">Logout</button><br>\r\n\t\t\t</form>\r\n\t\t\t<script src="mhb_modul.js"></script>\r\n\t</body>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"line_map": {"64": 19, "65": 19, "66": 19, "27": 0, "36": 2, "69": 21, "68": 19, "41": 29, "75": 69, "47": 3, "67": 19, "55": 3, "56": 10, "57": 11, "58": 11, "59": 11, "60": 11, "61": 11, "62": 13, "63": 18}, "uri": "formVerantwortlicherModul.tpl", "filename": "/mnt/607B-88B7/Projects/WEBPraktikum2/NEW/mhb/templates/formVerantwortlicherModul.tpl", "source_encoding": "utf-8"}
__M_END_METADATA
"""
<file_sep>/WEB/p2_sicherung2/mhb/app/application.py
# coding: utf-8
import cherrypy
from .database import Database_cl
from .view import View_cl
#----------------------------------------------------------
class Application_cl(object):
#----------------------------------------------------------
benutzer = ""
rolle = ""
#-------------------------------------------------------
def __init__(self):
#-------------------------------------------------------
# spezielle Initialisierung können hier eingetragen werden
self.view_o = View_cl()
self.db_o = Database_cl()
@cherrypy.expose
#-------------------------------------------------------
def index(self):
#-------------------------------------------------------
return self.anmeldung()
@cherrypy.expose
#-------------------------------------------------------
def test(self):
#-------------------------------------------------------
return benutzer;
@cherrypy.expose
#-------------------------------------------------------
def anmeldung(self):
#-------------------------------------------------------
return self.createForm_login_b_p()
@cherrypy.expose
#-------------------------------------------------------
def studiengaenge(self):
#-------------------------------------------------------
global rolle
if rolle == "vs":
return self.createList_studiengaenge_module_p()
elif rolle == "vm":
return self.createList_studiengaenge_lv_module_p()
elif rolle == "student":
return self.createList_studiengaenge_student_p()
@cherrypy.expose
#-------------------------------------------------------
def studiengaenge_vs(self):
#-------------------------------------------------------
return self.createList_studiengaenge_module_p()
@cherrypy.expose
#-------------------------------------------------------
def studiengaenge_vm(self):
#-------------------------------------------------------
return self.createList_studiengaenge_lv_module_p()
@cherrypy.expose
#-------------------------------------------------------
def delete_sg(self, id):
#-------------------------------------------------------
self.db_o.delete_px(id)
return self.studiengaenge()
@cherrypy.expose
#-------------------------------------------------------
def delete_lv(self, id):
#-------------------------------------------------------
self.db_o.delete_lv_px(id)
return self.studiengaenge()
@cherrypy.expose
#-------------------------------------------------------
def delete_m(self, id):
#-------------------------------------------------------
self.db_o.delete_m_px(id)
return self.studiengaenge()
@cherrypy.expose
#-------------------------------------------------------
def add_sg(self):
#-------------------------------------------------------
return self.createForm_studiengaenge_p()
@cherrypy.expose
#-------------------------------------------------------
def add_lv(self):
#-------------------------------------------------------
return self.createForm_lehrveranstaltungen_p()
@cherrypy.expose
#-------------------------------------------------------
def add_m(self):
#-------------------------------------------------------
return self.createForm_module_p()
@cherrypy.expose
#-------------------------------------------------------
def edit_sg(self, id):
#-------------------------------------------------------
return self.createForm_studiengaenge_p(id)
@cherrypy.expose
#-------------------------------------------------------
def edit_lv(self, id):
#-------------------------------------------------------
return self.createForm_lehrveranstaltungen_p(id)
@cherrypy.expose
#-------------------------------------------------------
def edit_m(self, id):
#-------------------------------------------------------
return self.createForm_module_p(id)
@cherrypy.expose
#-------------------------------------------------------
def save_sg(self, **data_opl):
#-------------------------------------------------------
# Sichern der Daten: aufgrund der Formularbearbeitung muss
# eine vollständige HTML-Seite zurückgeliefert werden!
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
# HIER müssen Sie die Semesterzahl(en) ergänzen
id_s = data_opl["id_s"]
data_a = [ data_opl["bezeichnung_s"]
, data_opl["kurzbezeichnung_s"]
, data_opl["beschreibung_s"]
, data_opl["semesteranzahl_s"] # Semesterzahl ergänzt
, []
]
if id_s != "None":
# Update-Operation
self.db_o.update_px(id_s, data_a)
else:
# Create-Operation
id_s = self.db_o.create_px(data_a)
return self.createForm_studiengaenge_p(id_s)
@cherrypy.expose
#-------------------------------------------------------
def save_m(self, **data_opl):
#-------------------------------------------------------
# Sichern der Daten: aufgrund der Formularbearbeitung muss
# eine vollständige HTML-Seite zurückgeliefert werden!
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
# HIER müssen Sie die Semesterzahl(en) ergänzen
id_s = data_opl["id_s"]
data_z = [ data_opl["bezeichnung_s"]
, data_opl["beschreibung_s"]
, data_opl["anzahl_kreditpunkte_s"]
, data_opl["anzahl_sws_vorlesung_s"]
, data_opl["anzahl_sws_uebung_s"]
, data_opl["anzahl_sws_praktikum_s"]
, data_opl["voraussetzungen_s"]
]
if id_s != "None":
# Update-Operation
self.db_o.update_module_px(id_s, data_z)
else:
# Create-Operation
id_s = self.db_o.create_module_px(data_z)
return self.createForm_module_p(id_s)
@cherrypy.expose
#-------------------------------------------------------
def save_lv(self, **data_opl):
#-------------------------------------------------------
# Sichern der Daten: aufgrund der Formularbearbeitung muss
# eine vollständige HTML-Seite zurückgeliefert werden!
# data_opl: Dictionary mit den gelieferten key-value-Paaren
# hier müsste man prüfen, ob die Daten korrekt vorliegen!
# HIER müssen Sie die Semesterzahl(en) ergänzen
id_s = data_opl["id_s"]
data_z = [ data_opl["bezeichnung_s"]
, data_opl["kurzbezeichnung_s"]
, data_opl["lage_semester_s"]
]
if id_s != "None":
# Update-Operation
self.db_o.update_lehrveranstaltungen_px(id_s, data_z)
else:
# Create-Operation
id_s = self.db_o.create_lehrveranstaltungen_px(data_z)
return self.createForm_lehrveranstaltungen_p(id_s)
@cherrypy.expose
#-------------------------------------------------------
def login(self, **data_opl):
#-------------------------------------------------------
# Hier soll der Benutzername überprüft werden
data_b = self.db_o.read_benutzer_px()
global benutzer
global rolle
benutzer = data_opl["benutzername_s"]
kennwort = data_opl["<PASSWORD>"]
if "@stud.<EMAIL>" in benutzer:
rolle = "student"
return self.studiengaenge()
#else:
for i in range(0, len(data_b)):
#Wenn Benutzer in der benutzer.json dann geh in login_bk
if (benutzer == data_b[str(i)][0]) and (kennwort == data_b[str(i)][1]):
#return data_b[str(i)][0]
#return "Benutzer ist kein Student!"
#return self.view_o.createForm_login_bk_px(data_opl)
#---------> hier weitermachen für kennwort
rolle = data_b[str(i)][2]
return self.studiengaenge()
#if (rolle=="vm"):
#return "Hier ist Verantwortlicher Module"
# return self.createList_studiengaenge_lv_module_p()
#elif (rolle=="vs"):
#return "Hier ist Verantwortlicher Studiengang"
# return self.createList_studiengaenge_module_p()
elif (benutzer == data_b[str(i)][0]) and (kennwort != data_b[str(i)][1]):
#"Kennwort ist falsch!"
return self.error()
@cherrypy.expose
#-------------------------------------------------------
def beziehung_sg_lv(self, id):
#-------------------------------------------------------
#---> hier weitermachen
if id_spl != None:
data_sg_lv = self.db_o.read_module_px(id_spl)
else:
data_m = self.db_o.getDefault_module_px()
@cherrypy.expose
#-------------------------------------------------------
def error(self):
#-------------------------------------------------------
data_o = {}
return self.view_o.createList_error_px(data_o)
@cherrypy.expose
#-------------------------------------------------------
def modulhandbuch(self, id):
#-------------------------------------------------------
#data_o = {}
data_o = self.db_o.read_px()
data_l = self.db_o.read_lehrveranstaltungen_px()
data_m = self.db_o.read_module_px()
return self.view_o.createList_modulhandbuch_px(id, data_o, data_l, data_m)
@cherrypy.expose
#-------------------------------------------------------
def lehrveranstaltungen(self, id):
#-------------------------------------------------------
return self.createList_lehrveranstaltungen_p(id)
@cherrypy.expose
#-------------------------------------------------------
#def login_bk(self, benutzer, rolle):
#-------------------------------------------------------
# return benutzer + rolle
#@<EMAIL>
#-------------------------------------------------------
def createList_studiengaenge_student_p(self):
#-------------------------------------------------------
# mit diesen Daten Markup erzeugen
data_o = self.db_o.read_px()
return self.view_o.createList_studiengaenge_student_px(data_o)
#-------------------------------------------------------
def createList_studiengaenge_module_p(self):
#-------------------------------------------------------
# mit diesen Daten Markup erzeugen
data_o = self.db_o.read_px()
#data_l = self.db_o.read_lehrveranstaltungen_px()
data_m = self.db_o.read_module_px()
return self.view_o.createList_studiengaenge_module_px(data_o, data_m)
#-------------------------------------------------------
def createList_studiengaenge_lv_module_p(self):
#-------------------------------------------------------
# mit diesen Daten Markup erzeugen
data_o = self.db_o.read_px()
#data_l = self.db_o.read_lehrveranstaltungen_px()
data_m = self.db_o.read_module_px()
return self.view_o.createList_studiengaenge_lv_module_px(data_o, data_m)
#-------------------------------------------------------
def createList_lehrveranstaltungen_p(self, id):
#-------------------------------------------------------
# mit diesen Daten Markup erzeugen
data_l = self.db_o.read_lehrveranstaltungen_px(id)
return self.view_o.createList_lehrveranstaltungen_px(data_l)
#-------------------------------------------------------
def createForm_studiengaenge_p(self, id_spl = None):
#-------------------------------------------------------
#Erstellung des Forms für die Studiengänge
data_l = self.db_o.read_lehrveranstaltungen_px()
if id_spl != None:
data_o = self.db_o.read_px(id_spl)
else:
data_o = self.db_o.getDefault_px()
# mit diesen Daten Markup erzeugen
return self.view_o.createForm_studiengaenge_px(id_spl, data_o, data_l)
#-------------------------------------------------------
def createForm_module_p(self, id_spl = None):
#-------------------------------------------------------
#Erstellung des Forms für die Module
if id_spl != None:
data_m = self.db_o.read_module_px(id_spl)
else:
data_m = self.db_o.getDefault_module_px()
# mit diesen Daten Markup erzeugen
return self.view_o.createForm_module_px(id_spl, data_m)
#-------------------------------------------------------
def createForm_lehrveranstaltungen_p(self, id_spl = None):
#-------------------------------------------------------
#Erstellung des Forms für die Module
if id_spl != None:
data_l = self.db_o.read_lehrveranstaltungen_px(id_spl)
else:
data_l = self.db_o.getDefault_lehrveranstaltungen_px()
# mit diesen Daten Markup erzeugen
return self.view_o.createForm_lehrveranstaltungen_px(id_spl, data_l)
#-------------------------------------------------------
#def default(self, *arguments, **kwargs):
#-------------------------------------------------------
# msg_s = "unbekannte Anforderung: " + \
# str(arguments) + \
# ' ' + \
# str(kwargs)
#raise cherrypy.HTTPError(404, msg_s)
#default.exposed= True
#-------------------------------------------------------
def createForm_login_b_p(self):
#-------------------------------------------------------
# mit diesen Daten Markup erzeugen
data_b = self.db_o.read_px()
return self.view_o.createForm_login_b_px(data_b)
#-------------------------------------------------------
#def createForm_login_bk_p(self):
#-------------------------------------------------------
# mit diesen Daten Markup erzeugen
#data_b = self.db_o.read_px()
#return self.view_o.createForm_login_bk_px(data_b)
# EOF<file_sep>/Mattes/1/webteams/doc/webteams.md
Dokumentation 1 Praktikumstermin 13.10.2016
<NAME>, <NAME>
1. Aufbau der Webannwendung
Dateien und Verzeichnisstruktur:
* webteams
- server.py
- app
+ __init__.py //Kennzeichnet Verzeichnis als Pythonpackage
+ application.py //Anwendungslogik
+ database.py //Datenbanklogik
+ view.py //Praesentation
-__pycache
- content
+ form0.tpl //Template für HTML
+ form1.tpl
+ form2.tpl
+ list0.tpl
+ list1.tpl
+ list2.tpl
+ webteams.css // Designvorschriften
+ webteams.js // Javascript Funktionssammlung
- data
+ webteams.json // Datenbank
- doc
+ a.mk
+ b.html
+ webteams.md // Dokumentation
2. Ergänzungen:
- Erweiterung des Formulares in form1.tpl.
- Ergaenzung in den Funktionen createList_px und createForm_px aus der Datei view.py um die Semesterzahlen
beider Studenten. Sowie in den Funktionen getDefault_px und readData_p die Arrays um zwei leere stellen ergaenzt werden mussten.
- Formular mit "Abbrechen" Button in form2.tpl eingefuegt.
- Veraenderungen an Body und Table-Elementen mit Hilfe von CSS, ausgelagert in die Datei "webteams.css".
- Ergaenzen der Funktion delete_px in der Datei "database.py" innerhalb der if-Verzweigung um die Zeilen:
self.data_o[id_spl] = self.getDefault_px()
self.saveData_p()
status_b = True
- Ergaenzung der Funktion confirmDelete_p in Datei webteams.js um die Zeilen:
if(confirm("Are you sure?")){
alert("deleted")
}else{
event_opl.preventDefault();
}
3. Beschreibung des HTTP Datenverkehrs
- Start der anwendung:
* 
- Speichern:
* 
| 88a09da8a01b01316da0eff9f3f61f0cd2dfad78 | [
"HTML",
"JavaScript",
"Markdown",
"INI",
"Python",
"C",
"Shell"
] | 88 | Python | vsypraktikum/web | 47ec56a275891e041646edb1612b905c17fdfc04 | 6bb80e20ca57480e3315911f509492a8e703bd33 |
refs/heads/main | <file_sep>package middleware
import (
"github.com/gin-gonic/gin"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/config"
)
// RateLimiterMiddleware 请求频率限制中间件
func RateLimiterMiddleware(skippers ...SkipperFunc) gin.HandlerFunc {
cfg := config.C.RateLimiter
if !cfg.Enable {
return EmptyMiddleware()
}
return func(c *gin.Context) {
if SkipHandler(c, skippers...) {
c.Next()
return
}
// TODO:
c.Next()
}
}
<file_sep>package mock
import (
"github.com/gin-gonic/gin"
"github.com/google/wire"
)
// OrdinarySet 注入Ordinary
var OrdinarySet = wire.NewSet(wire.Struct(new(Ordinary), "*"))
// Ordinary 普通克力金
type Ordinary struct {
}
// Query 查询插值生成的网格数据
// @Tags 普通克力金
// @Summary 查询插值生成的网格数据
// @Param body body schema.OrdinaryQueryGridParam true "请求参数"
// @Success 200 {object} schema.OrdinaryGridInfo "插值的网格数据"
// @Failure 400 {object} schema.ErrorResult "{error:{code:0,message:无效的请求参数}}"
// @Failure 500 {object} schema.ErrorResult "{error:{code:0,message:服务器错误}}"
// @Router /api/v1/ordinary/grid [post]
func (a *Ordinary) Grid(c *gin.Context) {
}
// Get 查询插值生成的图片
// @Tags 普通克力金
// @Summary 查询插值生成图片
// @Produce png
// @Param body body schema.OrdinaryQueryGridPngParam true "请求参数"
// @Success 200 "文件图片"
// @Failure 400 {object} schema.ErrorResult "{error:{code:0,message:无效的请求参数}}"
// @Failure 500 {object} schema.ErrorResult "{error:{code:0,message:服务器错误}}"
// @Router /api/v1/ordinary/grid-png [post]
func (a *Ordinary) GridPng(c *gin.Context) {
}
<file_sep>module github.com/liuvigongzuoshi/go-kriging-service
go 1.15
require (
github.com/LyricTian/gzip v0.1.1
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
github.com/fatih/camelcase v1.0.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/gin-contrib/cors v1.3.1
github.com/gin-gonic/gin v1.6.3
github.com/google/gops v0.3.12
github.com/google/uuid v1.1.2
github.com/google/wire v0.4.0
github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a
github.com/json-iterator/go v1.1.10
github.com/koding/multiconfig v0.0.0-20171124222453-69c27309b2d7
github.com/liuvigongzuoshi/go-kriging v0.0.1-alpha.14
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.6.0
github.com/stretchr/testify v1.6.1
github.com/swaggo/gin-swagger v1.3.0
github.com/swaggo/swag v1.7.0
github.com/urfave/cli/v2 v2.3.0
gopkg.in/yaml.v2 v2.3.0
)
// replace github.com/liuvigongzuoshi/go-kriging => ./../go-kriging
<file_sep># go-kriging-service
Golang Service for [go-kriging](https://github.com/liuvigongzuoshi/go-kriging) (Golang Multi-Goroutine spatial interpolation algorithm library for geospatial prediction and mapping via ordinary kriging.)
<file_sep>package bll
import (
"github.com/google/wire"
)
// BllSet bll注入
var BllSet = wire.NewSet(
OrdinarySet,
)
<file_sep>package schema
import (
"github.com/liuvigongzuoshi/go-kriging/ordinarykriging"
)
// Ordinary
//type Ordinary struct {
// ID string `json:"-"` // 唯一标识
// CreatedAt time.Time `json:"-"` // 请求时间
// UpdatedAt time.Time `json:"-"` // 返回时间
//}
// OrdinaryTrainParam 训练模型参数
type OrdinaryTrainParam struct {
Values []float64 `json:"values" binding:"required" example:"9.6,10.2,5.4"` // 权重值数组
Lons []float64 `json:"lons" binding:"required" example:"102.68,99.36,101.23"` // 经度数组
Lats []float64 `json:"lats" binding:"required" example:"25.95,25.81,25.95"` // 纬度数组
Sigma2 float64 `json:"sigma2" binding:"" default:"0" example:"0"` // sigma2
Alpha float64 `json:"alpha" binding:"" default:"0" example:"100"` // alpha
Model uint16 `json:"model" binding:"required,oneof=1 2 3" example:"1"` // 函数模型(1:"spherical" 2:"exponential" 3:"gaussian")
ModelType ordinarykriging.ModelType `json:"-"`
}
// OrdinaryGridParam 插值网格参数
type OrdinaryGridParam struct {
Polygon string `json:"polygon" binding:"required" example:"{\"type\": \"Polygon\",\"coordinates\": [[[103.614373, 27.00541],[104.174357, 26.635252],[104.356163, 28.018448],[103.614373, 27.00541]]]}"` // Polygon Geometry String
PolygonGeometry ordinarykriging.PolygonGeometry `json:"-"` // Polygon Geometry
Width float64 `json:"width" binding:"required" example:"0.01" example:"0.01"` // 网格单元宽度
}
// OrdinaryPlotPngParam 插值图片参数
type OrdinaryPlotPngParam struct {
Width int `json:"width" binding:"required,gte=1" example:"100"` // 图片宽度
Height int `json:"height" binding:"required,gte=1" example:"100"` // 图片高度
Xlim [2]float64 `json:"xlim" binding:"required" example:"103.614373,104.356163"` // Xlim
Ylim [2]float64 `json:"Ylim" binding:"required" example:"26.635252,28.018448"` // Ylim
Colors []GridLevelColor `json:"colors" binding:"required,dive,required"` // colors
}
type GridLevelColor struct {
Value [2]float64 `json:"value" binding:"required,unique" example:"0,15"` // 值区间 [0, 15]
Color [4]uint8 `json:"rgba" binding:"dive,gte=0,lte=255" example:"255,128,169,255"` // RGBA颜色 [255, 255, 255, 255]
}
// OrdinaryQueryGridParam 生成插值网格参数
type OrdinaryQueryGridParam struct {
TrainParam OrdinaryTrainParam `json:"train"`
GridParam OrdinaryGridParam `json:"grid"`
}
// OrdinaryQueryGridPngParam 生成插值图片参数
type OrdinaryQueryGridPngParam struct {
TrainParam OrdinaryTrainParam `json:"train"`
GridParam OrdinaryGridParam `json:"grid"`
PlotPngParam OrdinaryPlotPngParam `json:"plotPng"`
}
// OrdinaryGridInfo 插值的网格数据
type OrdinaryGridInfo struct {
GridMatrices *ordinarykriging.GridMatrices `json:"grid"`
Variogram *ordinarykriging.Variogram `json:"-"`
TimeCost string `json:"timeCost"` // 耗时
}
// OrdinaryQueryOptions 示例对象查询可选参数项
//type OrdinaryQueryOptions struct {
// OrderFields []*OrderField // 排序字段
//}
// OrdinaryQueryResult 示例对象查询结果
//type OrdinaryQueryResult struct {
// Data []*Ordinary
// PageResult *PaginationResult
//}
<file_sep>package router
import (
"github.com/gin-gonic/gin"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/middleware"
)
// RegisterAPI register api group router
func (a *Router) RegisterAPI(app *gin.Engine) {
g := app.Group("/api")
g.Use(middleware.RateLimiterMiddleware())
v1 := g.Group("/v1")
{
gOrdinary := v1.Group("ordinary")
{
gOrdinary.POST("grid", a.OrdinaryAPI.Grid)
gOrdinary.POST("grid-png", a.OrdinaryAPI.GridPng)
}
}
}
<file_sep>// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag
package swagger
import (
"bytes"
"encoding/json"
"strings"
"github.com/alecthomas/template"
"github.com/swaggo/swag"
)
var doc = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{.Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/api/v1/ordinary/grid": {
"post": {
"tags": [
"普通克力金"
],
"summary": "查询插值生成的网格数据",
"parameters": [
{
"description": "请求参数",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/schema.OrdinaryQueryGridParam"
}
}
],
"responses": {
"200": {
"description": "插值的网格数据",
"schema": {
"$ref": "#/definitions/schema.OrdinaryGridInfo"
}
},
"400": {
"description": "{error:{code:0,message:无效的请求参数}}",
"schema": {
"$ref": "#/definitions/schema.ErrorResult"
}
},
"500": {
"description": "{error:{code:0,message:服务器错误}}",
"schema": {
"$ref": "#/definitions/schema.ErrorResult"
}
}
}
}
},
"/api/v1/ordinary/grid-png": {
"post": {
"produces": [
"image/png"
],
"tags": [
"普通克力金"
],
"summary": "查询插值生成图片",
"parameters": [
{
"description": "请求参数",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/schema.OrdinaryQueryGridPngParam"
}
}
],
"responses": {
"200": {
"description": "文件图片"
},
"400": {
"description": "{error:{code:0,message:无效的请求参数}}",
"schema": {
"$ref": "#/definitions/schema.ErrorResult"
}
},
"500": {
"description": "{error:{code:0,message:服务器错误}}",
"schema": {
"$ref": "#/definitions/schema.ErrorResult"
}
}
}
}
}
},
"definitions": {
"ordinarykriging.GridMatrices": {
"type": "object",
"properties": {
"data": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "number"
}
}
},
"width": {
"type": "number"
},
"xLim": {
"type": "array",
"items": {
"type": "number"
}
},
"yLim": {
"type": "array",
"items": {
"type": "number"
}
},
"zLim": {
"type": "array",
"items": {
"type": "number"
}
}
}
},
"schema.ErrorItem": {
"type": "object",
"properties": {
"code": {
"description": "错误码",
"type": "integer"
},
"message": {
"description": "错误信息",
"type": "string"
}
}
},
"schema.ErrorResult": {
"type": "object",
"properties": {
"error": {
"description": "错误项",
"$ref": "#/definitions/schema.ErrorItem"
}
}
},
"schema.GridLevelColor": {
"type": "object",
"required": [
"value"
],
"properties": {
"rgba": {
"description": "RGBA颜色 [255, 255, 255, 255]",
"type": "array",
"items": {
"type": "integer"
},
"example": [
255,
128,
169,
255
]
},
"value": {
"description": "值区间 [0, 15]",
"type": "array",
"items": {
"type": "number"
},
"example": [
0,
15
]
}
}
},
"schema.OrdinaryGridInfo": {
"type": "object",
"properties": {
"grid": {
"$ref": "#/definitions/ordinarykriging.GridMatrices"
},
"timeCost": {
"description": "耗时",
"type": "string"
}
}
},
"schema.OrdinaryGridParam": {
"type": "object",
"required": [
"polygon",
"width"
],
"properties": {
"polygon": {
"description": "Polygon Geometry String",
"type": "string",
"example": "{\"type\": \"Polygon\",\"coordinates\": [[[103.614373, 27.00541],[104.174357, 26.635252],[104.356163, 28.018448],[103.614373, 27.00541]]]}"
},
"width": {
"description": "网格单元宽度",
"type": "number",
"example": 0.01
}
}
},
"schema.OrdinaryPlotPngParam": {
"type": "object",
"required": [
"Ylim",
"colors",
"height",
"width",
"xlim"
],
"properties": {
"Ylim": {
"description": "Ylim",
"type": "array",
"items": {
"type": "number"
},
"example": [
26.635252,
28.018448
]
},
"colors": {
"description": "colors",
"type": "array",
"items": {
"$ref": "#/definitions/schema.GridLevelColor"
}
},
"height": {
"description": "图片高度",
"type": "integer",
"example": 100
},
"width": {
"description": "图片宽度",
"type": "integer",
"example": 100
},
"xlim": {
"description": "Xlim",
"type": "array",
"items": {
"type": "number"
},
"example": [
103.614373,
104.356163
]
}
}
},
"schema.OrdinaryQueryGridParam": {
"type": "object",
"properties": {
"grid": {
"$ref": "#/definitions/schema.OrdinaryGridParam"
},
"train": {
"$ref": "#/definitions/schema.OrdinaryTrainParam"
}
}
},
"schema.OrdinaryQueryGridPngParam": {
"type": "object",
"properties": {
"grid": {
"$ref": "#/definitions/schema.OrdinaryGridParam"
},
"plotPng": {
"$ref": "#/definitions/schema.OrdinaryPlotPngParam"
},
"train": {
"$ref": "#/definitions/schema.OrdinaryTrainParam"
}
}
},
"schema.OrdinaryTrainParam": {
"type": "object",
"required": [
"lats",
"lons",
"model",
"values"
],
"properties": {
"alpha": {
"description": "alpha",
"type": "number",
"default": 0,
"example": 100
},
"lats": {
"description": "纬度数组",
"type": "array",
"items": {
"type": "number"
},
"example": [
25.95,
25.81,
25.95
]
},
"lons": {
"description": "经度数组",
"type": "array",
"items": {
"type": "number"
},
"example": [
102.68,
99.36,
101.23
]
},
"model": {
"description": "函数模型(1:\"spherical\" 2:\"exponential\" 3:\"gaussian\")",
"type": "integer",
"example": 1
},
"sigma2": {
"description": "sigma2",
"type": "number",
"default": 0,
"example": 0
},
"values": {
"description": "权重值数组",
"type": "array",
"items": {
"type": "number"
},
"example": [
9.6,
10.2,
5.4
]
}
}
}
},
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
}`
type swaggerInfo struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
}
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = swaggerInfo{
Version: "1.0.0",
Host: "",
BasePath: "/",
Schemes: []string{"http", "https"},
Title: "go-kriging-service",
Description: "GIN + WIRE.",
}
type s struct{}
func (s *s) ReadDoc() string {
sInfo := SwaggerInfo
sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1)
t, err := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
}).Parse(doc)
if err != nil {
return doc
}
var tpl bytes.Buffer
if err := t.Execute(&tpl, sInfo); err != nil {
return doc
}
return tpl.String()
}
func init() {
swag.Register(swag.Name, &s{})
}
<file_sep>package mock
import "github.com/google/wire"
// MockSet 注入mock
var MockSet = wire.NewSet(
OrdinarySet,
)
<file_sep>package router
import (
"github.com/gin-gonic/gin"
"github.com/google/wire"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/api"
)
var _ IRouter = (*Router)(nil)
// RouterSet 注入router
var RouterSet = wire.NewSet(wire.Struct(new(Router), "*"), wire.Bind(new(IRouter), new(*Router)))
// IRouter 注册路由
type IRouter interface {
Register(app *gin.Engine) error
Prefixes() []string
}
// Router 路由管理器
type Router struct {
OrdinaryAPI *api.Ordinary
}
// Register 注册路由
func (a *Router) Register(app *gin.Engine) error {
a.RegisterAPI(app)
return nil
}
// Prefixes 路由前缀列表
func (a *Router) Prefixes() []string {
return []string{
"/api/",
}
}
<file_sep>package bll
import (
"context"
"fmt"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/schema"
"github.com/liuvigongzuoshi/go-kriging-service/pkg/errors"
"image/color"
"net/http"
"time"
"github.com/google/wire"
"github.com/liuvigongzuoshi/go-kriging/ordinarykriging"
)
// OrdinarySet 注入Ordinary
var OrdinarySet = wire.NewSet(wire.Struct(new(Ordinary), "*"))
// Ordinary
type Ordinary struct {
}
// Grid 插值生成网格数据
func (a *Ordinary) Grid(ctx context.Context, trainParam schema.OrdinaryTrainParam, gridParam schema.OrdinaryGridParam) (*schema.OrdinaryGridInfo, error) {
model := trainParam.Model
if model == 1 {
trainParam.ModelType = ordinarykriging.Spherical
} else if model == 2 {
trainParam.ModelType = ordinarykriging.Exponential
} else if model == 3 {
trainParam.ModelType = ordinarykriging.Gaussian
} else {
return nil, errors.New400Response("模型类型错误")
}
start := time.Now()
ordinaryKriging := ordinarykriging.NewOrdinary(trainParam.Values, trainParam.Lons, trainParam.Lats)
if _, err := ordinaryKriging.Train(trainParam.ModelType, trainParam.Sigma2, trainParam.Alpha); err != nil {
return nil, errors.New400Response("训练模型参数有误")
}
gridMatrices := ordinaryKriging.Grid(gridParam.PolygonGeometry.Coordinates, gridParam.Width)
tc := time.Since(start)
timeCost := fmt.Sprintf("time cost = %v s", tc.Seconds())
gridInfo := &schema.OrdinaryGridInfo{GridMatrices: gridMatrices, Variogram: ordinaryKriging, TimeCost: timeCost}
return gridInfo, nil
}
// GridPng 插值生成网格图片
func (a *Ordinary) GridPng(ctx context.Context, w http.ResponseWriter, gridInfo *schema.OrdinaryGridInfo, params schema.OrdinaryPlotPngParam) error {
ordinaryKriging := gridInfo.Variogram
var gridLevelColor []ordinarykriging.GridLevelColor
for _, item := range params.Colors {
gridLevelColor = append(gridLevelColor, ordinarykriging.GridLevelColor{Value: item.Value, Color: color.RGBA{R: item.Color[0], G: item.Color[1], B: item.Color[2], A: item.Color[3]}})
}
canvasX := ordinaryKriging.Plot(gridInfo.GridMatrices, params.Width, params.Height, params.Xlim, params.Ylim, gridLevelColor)
//subTitle := &canvas.TextConfig{
// Text: "球面半变异函数模型",
// FontName: "testdata/fonts/source-han-sans-sc/regular.ttf",
// FontSize: 28,
// Color: color.RGBA{R: 0, G: 0, B: 0, A: 255},
// OffsetX: 252,
// OffsetY: 40,
// AlignX: 0.5,
//}
//if err := canvasX.DrawText(subTitle); err != nil {
// return nil, err
//}
buffer, err := canvasX.Output()
if err != nil {
return err
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Type", "image/png")
w.Write(buffer)
//filePath := fmt.Sprintf("%v/%v %v", "tmp", time.Now().Format("2006-01-02 15-04-05"), "grid-png.png")
//if err := canvasX.SavePNG(filePath); err != nil {
// errors.New500Response("保存插值生成网格图片失败")
//}
return nil
}
<file_sep>package main
import (
"context"
"os"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app"
"github.com/liuvigongzuoshi/go-kriging-service/pkg/logger"
"github.com/urfave/cli/v2"
)
// VERSION 版本号,可以通过编译的方式指定版本号:go build -ldflags "-X main.VERSION=x.x.x"
var VERSION = "0.0.5"
func main() {
logger.SetVersion(VERSION)
ctx := logger.NewTagContext(context.Background(), "__main__")
app := cli.NewApp()
app.Name = "go-kriging-service"
app.Version = VERSION
app.Usage = "Golang Service for go-kriging (Golang library for geospatial prediction and mapping via ordinary kriging.)\n"
app.Commands = []*cli.Command{
newWebCmd(ctx),
}
err := app.Run(os.Args)
if err != nil {
logger.WithContext(ctx).Errorf(err.Error())
}
}
func newWebCmd(ctx context.Context) *cli.Command {
return &cli.Command{
Name: "web",
Usage: "运行web服务",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "conf",
Aliases: []string{"c"},
Usage: "配置文件(.json,.yaml,.toml)",
Required: true,
},
},
Action: func(c *cli.Context) error {
return app.Run(ctx,
app.SetConfigFile(c.String("conf")),
app.SetVersion(VERSION))
},
}
}
<file_sep>package config
import (
"github.com/liuvigongzuoshi/go-kriging-service/pkg/util/json"
"os"
"strings"
"sync"
"github.com/koding/multiconfig"
)
var (
// C 全局配置(需要先执行MustLoad,否则拿不到配置)
C = new(Config)
once sync.Once
)
// MustLoad 加载配置
func MustLoad(fpaths ...string) {
once.Do(func() {
loaders := []multiconfig.Loader{
&multiconfig.TagLoader{},
&multiconfig.EnvironmentLoader{},
}
for _, fpath := range fpaths {
if strings.HasSuffix(fpath, "toml") {
loaders = append(loaders, &multiconfig.TOMLLoader{Path: fpath})
}
if strings.HasSuffix(fpath, "json") {
loaders = append(loaders, &multiconfig.JSONLoader{Path: fpath})
}
if strings.HasSuffix(fpath, "yaml") {
loaders = append(loaders, &multiconfig.YAMLLoader{Path: fpath})
}
}
m := multiconfig.DefaultLoader{
Loader: multiconfig.MultiLoader(loaders...),
Validator: multiconfig.MultiValidator(&multiconfig.RequiredValidator{}),
}
m.MustLoad(C)
})
}
// PrintWithJSON 基于JSON格式输出配置
func PrintWithJSON() {
if C.PrintConfig {
b, err := json.MarshalIndent(C, "", " ")
if err != nil {
os.Stdout.WriteString("[CONFIG] JSON marshal error: " + err.Error())
return
}
os.Stdout.WriteString(string(b) + "\n")
}
}
// Config 配置参数
type Config struct {
RunMode string
Swagger bool
PrintConfig bool
HTTP HTTP
Log Log
Monitor Monitor
RateLimiter RateLimiter
CORS CORS
GZIP GZIP
}
// IsDebugMode 是否是debug模式
func (c *Config) IsDebugMode() bool {
return c.RunMode == "debug"
}
// Log 日志配置参数
type Log struct {
Level int
Format string
Output string
OutputFile string
}
// HTTP http配置参数
type HTTP struct {
Host string
Port int
CertFile string
KeyFile string
ShutdownTimeout int
MaxContentLength int64
MaxLoggerLength int `default:"4096"`
}
// Monitor 监控配置参数
type Monitor struct {
Enable bool
Addr string
ConfigDir string
}
// RateLimiter 请求频率限制配置参数
type RateLimiter struct {
Enable bool
Count int64
}
// CORS 跨域请求配置参数
type CORS struct {
Enable bool
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
AllowCredentials bool
MaxAge int
}
// GZIP gzip压缩
type GZIP struct {
Enable bool
ExcludedExtentions []string
ExcludedPaths []string
}
<file_sep>package test
import (
"net/http/httptest"
"testing"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/schema"
"github.com/stretchr/testify/assert"
)
func TestOrdinary(t *testing.T) {
const router = apiPrefix + "v1/ordinary"
var err error
w := httptest.NewRecorder()
// post /ordinary/grid
grid := &schema.OrdinaryQueryGridParam{
TrainParam: schema.OrdinaryTrainParam{
Values: []float64{45.986076009952846, 46.223032113384235, 52.821454425024626, 89.19253247046487, 31.062802427638776},
Lons: []float64{31.995986076009952, 31.99622303211338, 32.002821454425025, 32.03919253247046, 31.981062802427637},
Lats: []float64{117.99598607600996, 117.99622303211338, 118.00282145442502, 118.03919253247047, 117.98106280242764},
Sigma2: 0, Alpha: 100, Model: 1,
},
GridParam: schema.OrdinaryGridParam{
Polygon: "{\"type\": \"Polygon\",\"coordinates\": [[[103.614373, 27.00541],[104.174357, 26.635252],[104.356163, 28.018448],[103.614373, 27.00541]]]}",
Width: 0.01,
},
}
engine.ServeHTTP(w, newPostRequest("%s/%s", grid, router, "grid"))
assert.Equal(t, 200, w.Code)
var gridRes schema.OrdinaryGridInfo
err = parseReader(w.Body, &gridRes)
assert.Nil(t, err)
assert.Equal(t, 0.01, gridRes.GridMatrices.Width)
// post /ordinary/grid-png
gridPng := &schema.OrdinaryQueryGridPngParam{
TrainParam: schema.OrdinaryTrainParam{
Values: []float64{45.986076009952846, 46.223032113384235, 52.821454425024626, 89.19253247046487, 31.062802427638776},
Lons: []float64{31.995986076009952, 31.99622303211338, 32.002821454425025, 32.03919253247046, 31.981062802427637},
Lats: []float64{117.99598607600996, 117.99622303211338, 118.00282145442502, 118.03919253247047, 117.98106280242764},
Sigma2: 0, Alpha: 100, Model: 1,
},
GridParam: schema.OrdinaryGridParam{
Polygon: "{\"type\": \"Polygon\",\"coordinates\": [[[103.614373, 27.00541],[104.174357, 26.635252],[104.356163, 28.018448],[103.614373, 27.00541]]]}",
Width: 0.01,
},
PlotPngParam: schema.OrdinaryPlotPngParam{
Width: 100, Height: 100,
Ylim: [2]float64{26.635252, 28.018448}, Xlim: [2]float64{103.614373, 104.356163},
Colors: []schema.GridLevelColor{schema.GridLevelColor{Value: [2]float64{0, 15}, Color: [4]uint8{255, 128, 169, 255}}},
},
}
engine.ServeHTTP(w, newPostRequest("%s/%s", gridPng, router, "grid-png"))
assert.Equal(t, 200, w.Code)
}
<file_sep>package api
import (
"github.com/gin-gonic/gin"
"github.com/google/wire"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/bll"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/ginx"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/schema"
"github.com/liuvigongzuoshi/go-kriging-service/pkg/errors"
"github.com/liuvigongzuoshi/go-kriging-service/pkg/util/json"
"github.com/liuvigongzuoshi/go-kriging/ordinarykriging"
)
// OrdinarySet 注入Ordinary
var OrdinarySet = wire.NewSet(wire.Struct(new(Ordinary), "*"))
// Ordinary
type Ordinary struct {
OrdinaryBll *bll.Ordinary
}
// Grid 插值生成网格数据
func (a *Ordinary) Grid(c *gin.Context) {
ctx := c.Request.Context()
var item schema.OrdinaryQueryGridParam
if err := ginx.ParseJSON(c, &item); err != nil {
ginx.ResError(c, err)
return
}
if err := json.Unmarshal([]byte(item.GridParam.Polygon), &item.GridParam.PolygonGeometry); err != nil {
ginx.ResError(c, err)
return
}
gridInfo, err := a.OrdinaryBll.Grid(ctx, item.TrainParam, item.GridParam)
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResSuccess(c, gridInfo)
}
// GridPng 插值生成网格图片
func (a *Ordinary) GridPng(c *gin.Context) {
ctx := c.Request.Context()
var item schema.OrdinaryQueryGridPngParam
if err := ginx.ParseJSON(c, &item); err != nil {
ginx.ResError(c, err)
return
}
var polygonGeometry ordinarykriging.PolygonGeometry
if err := json.Unmarshal([]byte(item.GridParam.Polygon), &polygonGeometry); err != nil {
ginx.ResError(c, err)
return
} else if polygonGeometry.Coordinates == nil || len(polygonGeometry.Coordinates) == 0 || len(polygonGeometry.Coordinates[0]) == 0 {
// TODO: validator validate polygonGeometry
ginx.ResError(c, errors.New400Response("Polygon 类型错误"))
return
}
item.GridParam.PolygonGeometry = polygonGeometry
gridInfo, err := a.OrdinaryBll.Grid(ctx, item.TrainParam, item.GridParam)
if err != nil {
ginx.ResError(c, err)
return
}
err = a.OrdinaryBll.GridPng(ctx, c.Writer, gridInfo, item.PlotPngParam)
if err != nil {
ginx.ResError(c, err)
return
}
}
<file_sep>package api
import "github.com/google/wire"
// APISet 注入api
var APISet = wire.NewSet(
OrdinarySet,
)
<file_sep>// +build wireinject
// The build tag makes sure the stub is not built in the final build.
package app
import (
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/api"
bll "github.com/liuvigongzuoshi/go-kriging-service/internal/app/bll"
"github.com/google/wire"
"github.com/liuvigongzuoshi/go-kriging-service/internal/app/router"
)
// BuildInjector 生成注入器
func BuildInjector() (*Injector, func(), error) {
// 默认使用gorm存储注入,这里可使用 InitMongoDB & mongoModel.ModelSet 替换为 gorm 存储
wire.Build(
InitGinEngine,
bll.BllSet,
api.APISet,
router.RouterSet,
InjectorSet,
)
return new(Injector), nil, nil
}
<file_sep># 运行模式(debug:调试,test:测试,release:正式)
RunMode = "debug"
# 是否启用swagger
Swagger = true
# 启动时是否打印配置参数
PrintConfig = true
[HTTP]
# http监听地址
Host = "0.0.0.0"
# http监听端口
Port = 18899
# 证书路径
CertFile = ""
# 证书密钥
KeyFile = ""
# http优雅关闭等待超时时长(单位秒)
ShutdownTimeout = 300
# 允许的最大内容长度(128M)
MaxContentLength = 134217728
# 允许输出的最大日志长度
MaxLoggerLength = 4096
[Log]
# 日志级别(1:fatal 2:error,3:warn,4:info,5:debug,6:trace)
Level = 5
# 日志格式(支持输出格式:text/json)
Format = "text"
# 日志输出(支持:stdout/stderr/file)
Output = "stderr"
# 指定日志输出的文件路径
OutputFile = "data/go-kriging-service.log"
# 服务监控(GOPS:https://github.com/google/gops)
[Monitor]
# 是否启用
Enable = false
# HTTP的监听地址和端口
Addr = "127.0.0.1:16060"
# 配置文件目录(为空则使用默认目录)
ConfigDir = ""
# 请求频率限制 功能未完成
[RateLimiter]
# 是否启用
Enable = false
# 每分钟每个用户允许的最大请求数量
Count = 300
[CORS]
# 是否启用
Enable = true
# 允许跨域请求的域名列表(*表示全部允许)
AllowOrigins = ["*"]
# 允许跨域请求的请求方式列表
AllowMethods = ["GET","POST","PUT","DELETE","PATCH"]
# 允许客户端与跨域请求一起使用的非简单标头的列表
AllowHeaders = ['content-type', 'authorization']
# 请求是否可以包含cookie,HTTP身份验证或客户端SSL证书等用户凭据
AllowCredentials = true
# 可以缓存预检请求结果的时间(以秒为单位)
MaxAge = 7200
[GZIP]
# 是否启用
Enable = false
# 排除的文件扩展名
ExcludedExtentions = [".png",".gif",".jpeg",".jpg"]
# 排除的请求路径
ExcludedPaths = []
| f03ddb33a6cae98a44c135394ab99b11fb54e683 | [
"Markdown",
"TOML",
"Go Module",
"Go"
] | 18 | Go | liuvigongzuoshi/go-kriging-service | 92682a10d955376fa6964e2a54828f46363c5821 | 50f118d711d12bcd61142d264fc70dae7eae77eb |
refs/heads/master | <repo_name>AlvaroOrduna/alvaroorduna.github.io<file_sep>/Gemfile
source "https://rubygems.org"
ruby RUBY_VERSION
gem "jekyll"
gem "sass"
gem "jemoji"
<file_sep>/_includes/portfolio/summary.html
<h2>
<i class="fa fa-user"></i>Summary</h2>
<div>
<p>I am currently finishing a Master Degree in Computer Engineering at the Public University of Navarra. I consider myself
a hardworking person who likes to learn. Every day I end up reading something new about how the world works. I like to
learn and to make learn to those who are next to me.</p>
</div>
<file_sep>/404.md
---
layout: not-found
title: Not found
permalink: /404.html
---
<file_sep>/_layouts/portfolio.html
<!doctype html>
<html lang="en">
{% include head.html %}
<body class="light portfolio">
<main role="main">
<div class="content">
<section class="summary">{% include portfolio/summary.html %}</section>
<section class="experience">{% include portfolio/experience.html %}</section>
<section class="projects">{% include portfolio/projects.html %}</section>
<section class="skills">{% include portfolio/skills.html %}</section>
</div>
<div class="dark sidebar">{% include portfolio/sidebar.html %}</div>
</main>
</body>
</html><file_sep>/index.md
---
layout: portfolio
title: Portfolio
description: Exhibition of my skills and achievements throughout my professional and academic life
---
| 1576831ee38c7292d3b24dfd2ed44eee0cb5f91d | [
"Markdown",
"Ruby",
"HTML"
] | 5 | Ruby | AlvaroOrduna/alvaroorduna.github.io | 13f997389ba25a5960a286cc4ac88bd0d8f97419 | f53ef20bdaa77b5c00cde8775557f8d59f02b9e9 |
refs/heads/master | <repo_name>levsha87/meditation-app<file_sep>/main.js
const song = document.querySelector('.song'),
video = document.querySelector('.vid-container video'),
play = document.querySelector('.play'),
replay = document.querySelector('.replay'),
outline = document.querySelector('.moving-outline circle'),
forwardRight = document.querySelector('.forward-right');
//Sounds
const sounds = document.querySelectorAll('.sound-picker button');
//Time Display
const timeDisplay = document.querySelector('.time-display');
const outlineLength = outline.getTotalLength();
//Duration
const timeSelect = document.querySelectorAll('.time-select button');
let timeDuration = 600;
outline.style.strokeDashoffset = outlineLength;
outline.style.strokeDasharray = outlineLength;
timeDisplay.textContent = `${Math.floor(timeDuration / 60)}:${plusZero(
Math.floor(timeDuration % 60)
)}`;
sounds.forEach((sound) => {
sound.addEventListener('click', function () {
song.src = this.getAttribute('data-sound');
video.src = this.getAttribute('data-video');
checkPlaying(song);
});
});
play.addEventListener('click', function () {
checkPlaying(song);
});
replay.addEventListener('click', function () {
restartSong(song);
});
const restartSong = (song) => {
song.currentTime = 0;
};
timeSelect.forEach((valueTime) => {
valueTime.addEventListener('click', function () {
timeDuration = this.getAttribute('data-time');
timeDisplay.textContent = `${Math.floor(timeDuration / 60)}:${plusZero(
Math.floor(timeDuration % 60)
)}`;
restartSong(song);
});
});
const checkPlaying = (song) => {
if (song.paused) {
song.play();
video.play();
play.src = './svg/pause.svg';
} else {
song.pause();
video.pause();
play.src = './svg/play.svg';
}
};
function plusZero(n) {
return (parseInt(n, 10) < 10 ? '0' : '') + n;
}
song.ontimeupdate = function () {
getCurrentTime();
displayProgress();
if (currentTime > timeDuration) {
song.pause();
song.currentTime = 0;
play.src = './svg/play.svg';
video.pause();
}
};
function getCurrentTime() {
currentTime = song.currentTime;
}
function displayProgress() {
let timePassed = timeDuration - currentTime;
let seconds = plusZero(Math.floor(timePassed % 60));
let minuts = Math.floor(timePassed / 60);
timeDisplay.textContent = `${minuts}:${seconds}`;
let progress = outlineLength * (1 - currentTime / timeDuration);
outline.style.strokeDashoffset = progress;
}
forwardRight.addEventListener('click', function () {
if (timeDuration - currentTime < 10) {
song.currentTime = timeDuration;
currentTime = song.currentTime;
song.pause();
play.src = './svg/play.svg';
video.pause();
checkPlaying(song);
} else {
song.currentTime += 10;
currentTime = song.currentTime;
}
});
| 3fddea57daa6cfec49861950bef5b51c983c1ec2 | [
"JavaScript"
] | 1 | JavaScript | levsha87/meditation-app | 6490339c0bf6e57696a98e4414904d0dfea118df | f4aa7535e43f7e17165118b01b6fdc212c852939 |
refs/heads/master | <repo_name>EduardoDuQuesne/challenge-number-loop<file_sep>/script.js
//What is the difference between the sum of the squares of the first
//ten natural numbers, and the square of the sum of the first ten
//natural numbers
let sumNum = 0;
let eachNumSquare = 0;
for (let i = 1; i <= 10; i++) {
eachNumSquare += i * i;
sumNum += i;
}
let allNumSquare = sumNum * sumNum;
let diffSquare = allNumSquare - eachNumSquare;
console.log(diffSquare);
//Difference = 2640
<file_sep>/README.md
# Nasvhille Software School: Front-End Challenge
## Challenge #6
What is the difference between the sum of the squares of the first ten natural numbers, and the square of the sum of the first ten natural numbers?
| a302ee16e5adabae76723dee3b80c94d1c5c3a69 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | EduardoDuQuesne/challenge-number-loop | f813d59063493fdff632b848a91e0522589e5e5c | e33e0542fd16ceb831f264cd660cec9e01f6c1d3 |
refs/heads/master | <file_sep># benchinit
Benchmark the initialization cost of your packages or programs.
Requires Go 1.19 or later.
go install mvdan.cc/benchinit@latest
This includes the cost of `init` functions and initialising globals.
In other words, a package's contribution to the slowness before `main` is run.
### Quickstart
Benchmarking a single package is simple:
benchinit cmd/go
You can benchmark multiple packages too; there must be at most one main package:
benchinit cmd/go go/parser go/build
You can also include all dependencies in the benchmark:
benchinit -r cmd/go
Finally, like any other benchmark, you can pass in `go test` flags:
benchinit -r -count=5 -benchtime=2s cmd/go
### Further reading
The original tool was result of a discussion with [@josharian](https://github.com/josharian).
You can read more about Josh's idea in his [blog post](https://commaok.xyz/post/benchmark-init/).
Since then, `GODEBUG=inittrace=1` was [added in Go 1.16](https://go.dev/doc/go1.16#runtime),
which this tool now uses.
The following design decisions were made:
* `GODEBUG=inittrace=1` requires us to run a new Go process for every benchmark
iteration, so `benchinit` sets up a wrapping benchmark `BenchmarkInit` which
does this and collects the `inittrace` output. `BenchmarkInit` then produces
one `BenchmarkPkgPath` result per package passed to `benchinit`, which is
shown to the user.
* `benchinit` supports most build and test flags, which are passed down as
needed. For example, you can use `-benchtime` and `-count` to control how the
benchmark is run, and `-tags` to use build tags. Note that some test flags
like `-bench` aren't supported, as we always run only `BenchmarkInit`.
* To avoid building a new binary, `BenchmarkInit` reuses its own test binary to
run the Go process for each benchmark iteration. To prevent test globals and
`init` funcs from being part of the result, all `*_test.go` files are masked
as deleted via `-overlay`. The same overlay is used to insert a temporary file
containing `BenchmarkInit`.
* `BenchmarkInit` only runs one Go process per benchmark iteration, even when
benchmarking multiple packages at once. This is possible since `inittrace`
prints one line per package being initialized, so we only need to ensure
the test binary imports all the necessary packages to initialize them.
For the same reason, we can only benchmark one `main` package at a time.
* If none of the given packages are a `main` package, the benchmark is run from
the first given package. This helps us support benchmarking internal packages.
<file_sep>module mvdan.cc/benchinit
go 1.19
require (
github.com/rogpeppe/go-internal v1.9.0
golang.org/x/exp v0.0.0-20230310171629-522b1b587ee0
)
require github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e // indirect
<file_sep>// Copyright (c) 2018, <NAME> <<EMAIL>>
// See LICENSE for licensing information
package main
import (
"bufio"
"bytes"
_ "embed"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"golang.org/x/exp/maps"
)
// TODO: "recursive" should exclude the init cost of "runtime" and its deps,
// as those can never be avoided as part of a program's init.
// And the same for "testing" and its deps, given that we run the benchmark as a test binary.
var recursive = flagSet.Bool("r", false, "")
// keep benchmain types in sync with benchmain_test.go.
type benchmainInput struct {
AllImportPaths []string
BenchPkgs []benchmainPackage
Recursive bool
}
type benchmainPackage struct {
ImportPath string
Deps []string
}
//go:embed benchmain_test.go
var benchmainSource string
func main() { os.Exit(main1()) }
func main1() int {
buildflags, testflags, rest := filterFlags(os.Args[1:])
flagSet.Usage = usage
if err := flagSet.Parse(rest); err != nil {
if err == flag.ErrHelp {
return 2
}
}
pkgs, err := listPackages(flagSet.Args(), buildflags)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
// From this point onwards, errors are straightforward.
if err := doBench(pkgs, buildflags, testflags); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}
func doBench(pkgs []*Package, buildflags, testflags []string) error {
// Prepare the packages to be benchmarked.
tmpDir, err := os.MkdirTemp("", "benchinit")
if err != nil {
return fmt.Errorf("setup: %w", err)
}
defer os.RemoveAll(tmpDir)
overlay := struct{ Replace map[string]string }{
Replace: make(map[string]string, len(pkgs)),
}
input := benchmainInput{Recursive: *recursive}
var mainPkg *Package
allPkgs := make(map[string]bool)
for _, pkg := range pkgs {
allPkgs[pkg.ImportPath] = true
for _, dep := range pkg.Deps {
allPkgs[dep] = true
}
input.BenchPkgs = append(input.BenchPkgs, benchmainPackage{
ImportPath: pkg.ImportPath,
Deps: pkg.Deps,
})
if pkg.Name != "main" {
continue
}
if mainPkg != nil {
return fmt.Errorf("can only benchmark up to one main package at a time; found %s and %s", mainPkg.ImportPath, pkg.ImportPath)
}
mainPkg = pkg
}
input.AllImportPaths = maps.Keys(allPkgs)
sort.Strings(input.AllImportPaths)
if mainPkg == nil {
mainPkg = pkgs[0]
}
// Pretend like the main package we use for testing does not have any other
// test files, as we are not interested in the init cost of tests.
for _, testFile := range mainPkg.TestGoFiles {
overlay.Replace[testFile] = ""
}
for _, testFile := range mainPkg.XTestGoFiles {
overlay.Replace[testFile] = ""
}
// Place our template in the main package's directory via the overlay.
const genName = "benchinit_generated_test.go"
benchmain := benchmainSource
benchmain = strings.Replace(benchmain, "package main_test", "package "+mainPkg.Name+"_test", 1)
var insertImports strings.Builder
for _, pkg := range input.BenchPkgs {
fmt.Fprintf(&insertImports, "import _ %q\n", pkg.ImportPath)
}
benchmain = strings.Replace(benchmain, "//go:insert imports", insertImports.String(), 1)
// for debugging
// println("--")
// println(benchmain)
// println("--")
replaceDst := filepath.Join(tmpDir, genName)
if err := os.WriteFile(replaceDst, []byte(benchmain), 0o666); err != nil {
return fmt.Errorf("setup: %w", err)
}
replaceSrc := filepath.Join(mainPkg.Dir, genName)
overlay.Replace[replaceSrc] = replaceDst
args := []string{
"test",
"-run=^$", // disable all tests
"-vet=off", // disable vet
"-bench=^BenchmarkGeneratedBenchinit$", // only run the one benchmark
}
overlayBytes, err := json.Marshal(overlay)
if err != nil {
return fmt.Errorf("setup: %w", err)
}
overlayPath := filepath.Join(tmpDir, "overlay.json")
if err := os.WriteFile(overlayPath, overlayBytes, 0o666); err != nil {
return fmt.Errorf("setup: %w", err)
}
args = append(args, "-overlay="+overlayPath)
inputBytes, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("setup: %w", err)
}
inputPath := filepath.Join(tmpDir, "input.json")
if err := os.WriteFile(inputPath, inputBytes, 0o666); err != nil {
return fmt.Errorf("setup: %w", err)
}
// Benchmark the packages with 'go test -bench'.
args = append(args, buildflags...) // add the user's build flags
args = append(args, testflags...) // add the user's test flags
args = append(args, mainPkg.Dir)
cmd := exec.Command("go", args...)
pr, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("test: %w", err)
}
cmd.Stderr = cmd.Stdout
cmd.Env = append(os.Environ(), "BENCHINIT_JSON_INPUT="+inputPath)
if err := cmd.Start(); err != nil {
return fmt.Errorf("test: %w", err)
}
// Get our benchinit result lines.
// Note that "go test" will often run a benchmark function multiple times
// with increasing b.N values, to estimate an N for e.g. -benchtime=1s.
// We only want the last benchinit result, the one directly followed by the
// original continuation to the BenchmarkGeneratedBenchinit line. For example:
//
// BenchmarkGeneratedBenchinit-16
// benchinit: BenchmarkGoBuild 1 7000 ns/op 5344 B/op 47 allocs/op
// continuation:
// benchinit: BenchmarkGoBuild 100 5880 ns/op 5080 B/op 45 allocs/op
// continuation:
// benchinit: BenchmarkGoBuild 1224 5803 ns/op 5059 B/op 45 allocs/op
// continuation: 1224 961433 ns/op
var errorBuffer bytes.Buffer // to print the whole output if we fail
var benchinitResults []string
var benchinitResultsNumber string // e.g. "100"
var resultsPrinted int
rxBenchinitResult := regexp.MustCompile(`^benchinit: (\w+\s+(\d+).*)`)
rxFinalResult := regexp.MustCompile(`^continuation:.*\d\s`)
// These must be printed directly as-is during normal runs.
// We don't do "FAIL", as we already print the entire output on any failure.
// We don't do "ok" nor "pkg:", as we always only test one ad-hoc package.
// Note that some may be "continuation" lines.
rxPassthrough := regexp.MustCompile(`^(continuation: )?((goos:|goarch:|cpu:|PASS\s).*)`)
scanner := bufio.NewScanner(io.TeeReader(pr, &errorBuffer))
for scanner.Scan() {
line := scanner.Text()
if match := rxBenchinitResult.FindStringSubmatch(line); match != nil {
number := match[2]
if number != benchinitResultsNumber {
benchinitResultsNumber = number
benchinitResults = benchinitResults[:0]
}
benchinitResults = append(benchinitResults, match[1])
} else if rxFinalResult.MatchString(line) {
if len(benchinitResults) != len(input.BenchPkgs) {
panic("did not find benchinit's results?")
}
for _, result := range benchinitResults {
fmt.Println(result)
}
resultsPrinted++
} else if match := rxPassthrough.FindStringSubmatch(line); match != nil {
fmt.Println(match[2])
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("scanner: %w", err)
}
if err := cmd.Wait(); err != nil {
return fmt.Errorf("test: %v:\n%s", err, errorBuffer.Bytes())
}
if resultsPrinted == 0 {
return fmt.Errorf("got no results; output:\n%s", errorBuffer.Bytes())
}
return nil
}
var flagSet = flag.NewFlagSet("benchinit", flag.ContinueOnError)
func usage() {
fmt.Fprintf(os.Stderr, `
Usage of benchinit:
benchinit [benchinit flags] [go test flags] [packages]
For example:
benchinit -count=10 .
All flags accepted by 'go test', including the benchmarking ones, should be
accepted. See 'go help testflag' for a complete list.
benchinit also accepts the following flags:
-r
include init cost of transitive dependencies
`[1:])
}
<file_sep>// Copyright (c) 2018, <NAME> <<EMAIL>>
// See LICENSE for licensing information
package main
import (
"os"
"path/filepath"
"testing"
"github.com/rogpeppe/go-internal/gotooltest"
"github.com/rogpeppe/go-internal/testscript"
)
func TestMain(m *testing.M) {
os.Exit(testscript.RunMain(m, map[string]func() int{
"benchinit": main1,
}))
}
func TestScripts(t *testing.T) {
t.Parallel()
params := testscript.Params{
Dir: filepath.Join("testdata", "script"),
RequireExplicitExec: true,
}
if err := gotooltest.Setup(¶ms); err != nil {
t.Fatal(err)
}
testscript.Run(t, params)
}
<file_sep>// Copyright (c) 2018, <NAME> <<EMAIL>>
// See LICENSE for licensing information
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os/exec"
"strings"
)
// listPackages is akin to go/packages, but more specific to `go list`.
// In particular, it helps us reach fields like Dir and Deps.
// Moreover, by using `go test`, we are tightly coupled with cmd/go already.
func listPackages(args, flags []string) ([]*Package, error) {
// Load the packages.
var pkgs []*Package
listArgs := []string{"list", "-json"}
listArgs = append(listArgs, flags...)
listArgs = append(listArgs, args...)
cmd := exec.Command("go", listArgs...)
pr, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("list: %w", err)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("list: %w", err)
}
dec := json.NewDecoder(pr)
for {
var pkg Package
if err := dec.Decode(&pkg); err == io.EOF {
break
} else if err != nil {
return nil, fmt.Errorf("list: %w", err)
}
pkgs = append(pkgs, &pkg)
}
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("list: %v:\n%s", err, stderr.Bytes())
}
return pkgs, nil
}
type Package struct {
Dir string
ImportPath string
Name string
GoFiles []string
TestGoFiles []string
XTestGoFiles []string
Deps []string
}
// The code below was initially borrowed from github.com/burrowers/garble,
// which has to pass flags down to cmd/go in a very similar way.
// forwardBuildFlags is obtained from 'go help build' as of Go 1.18beta1.
var forwardBuildFlags = map[string]bool{
// These shouldn't be used in nested cmd/go calls.
"a": false,
"n": false,
"x": false,
"v": false,
"asan": true,
"asmflags": true,
"buildmode": true,
"buildvcs": true,
"compiler": true,
"gccgoflags": true,
"gcflags": true,
"installsuffix": true,
"ldflags": true,
"linkshared": true,
"mod": true,
"modcacherw": true,
"modfile": true,
"msan": true,
"overlay": true,
"p": true,
"pkgdir": true,
"race": true,
"tags": true,
"toolexec": true,
"trimpath": true,
"work": true,
"workfile": true,
}
// booleanFlags is obtained from 'go help build' and 'go help testflag' as of Go 1.19beta1.
var booleanFlags = map[string]bool{
// Global help.
"h": true,
// Shared build flags.
"a": true,
"i": true,
"n": true,
"v": true,
"work": true,
"x": true,
"race": true,
"msan": true,
"asan": true,
"linkshared": true,
"modcacherw": true,
"trimpath": true,
"buildvcs": true,
// Test flags (TODO: support its special -args flag)
"c": true,
"json": true,
"cover": true,
"failfast": true,
"short": true,
"benchmem": true,
// benchinit flags
"r": true,
}
func filterFlags(flags []string) (build, test, rest []string) {
for i := 0; i < len(flags); i++ {
arg := flags[i]
if !strings.HasPrefix(arg, "-") {
return build, test, append(rest, flags[i:]...)
}
arg = strings.TrimLeft(arg, "-") // `-name` or `--name` to `name`
name, _, _ := strings.Cut(arg, "=") // `name=value` to `name`
start := i
if strings.Contains(arg, "=") {
// `-flag=value`
} else if booleanFlags[name] {
// `-boolflag`
} else {
// `-flag value`
if i+1 < len(flags) {
i++
}
}
toAppend := flags[start : i+1]
if forwardBuildFlags[name] { // build flag
build = append(build, toAppend...)
} else if name == "h" || flagSet.Lookup(name) != nil { // benchinit flag
rest = append(rest, toAppend...)
} else { // by elimination, a test flag
test = append(test, toAppend...)
}
}
return build, test, rest
}
<file_sep>// Copyright (c) 2018, <NAME> <<EMAIL>>
// See LICENSE for licensing information
package main_test
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"testing"
"time"
)
//go:insert imports
// keep benchmain types in sync with main.go.
type benchmainInput struct {
AllImportPaths []string
BenchPkgs []benchmainPackage
Recursive bool
}
type benchmainPackage struct {
ImportPath string
Deps []string
}
func BenchmarkGeneratedBenchinit(b *testing.B) {
inputPath := os.Getenv("BENCHINIT_JSON_INPUT")
if inputPath == "" {
b.Fatal("this benchmark is only used internally by benchinit")
}
inputBytes, err := os.ReadFile(inputPath)
if err != nil {
b.Fatal(err)
}
var input benchmainInput
if err := json.Unmarshal(inputBytes, &input); err != nil {
b.Fatal(err)
}
execPath, err := os.Executable()
if err != nil {
b.Fatal(err)
}
type totals struct {
Clock time.Duration
Bytes uint64
Allocs uint64
}
pkgTotals := make(map[string]*totals, len(input.AllImportPaths))
for _, pkg := range input.AllImportPaths {
pkgTotals[pkg] = new(totals)
}
rxInitTrace := regexp.MustCompile(`(?m)^init (?P<pkg>[^ ]+) (?P<time>@[^ ]+ [^ ]+), (?P<clock>[^ ]+ [^ ]+) clock, (?P<bytes>[^ ]+) bytes, (?P<allocs>[^ ]+) allocs$`)
rxIndexPkg := rxInitTrace.SubexpIndex("pkg")
rxIndexClock := rxInitTrace.SubexpIndex("clock")
rxIndexBytes := rxInitTrace.SubexpIndex("bytes")
rxIndexAllocs := rxInitTrace.SubexpIndex("allocs")
for i := 0; i < b.N; i++ {
cmd := exec.Command(execPath, "-h")
// Some Go code will behave slightly differently if it notices it's
// running within a Go test, e.g. if os.Args[0] ends with ".test".
// Make the execution look more like a regular program.
cmd.Args[0] = "main"
// TODO: do not override existing GODEBUG values
cmd.Env = append(os.Environ(), "GODEBUG=inittrace=1")
out, err := cmd.CombinedOutput()
if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 2 {
// Sometimes -h will result in an exit code 2 rather than 0.
} else if err != nil {
b.Fatalf("%v: %s", err, out)
}
for _, match := range rxInitTrace.FindAllSubmatch(out, -1) {
pkg := string(match[rxIndexPkg])
totals := pkgTotals[pkg]
if totals == nil {
continue // not a package we count, e.g. runtime
}
clock, err := time.ParseDuration(strings.Replace(string(match[rxIndexClock]), " ", "", 1))
if err != nil {
b.Fatal(err)
}
bytes, err := strconv.ParseUint(string(match[rxIndexBytes]), 10, 64)
if err != nil {
b.Fatal(err)
}
allocs, err := strconv.ParseUint(string(match[rxIndexAllocs]), 10, 64)
if err != nil {
b.Fatal(err)
}
totals.Clock += clock
totals.Bytes += bytes
totals.Allocs += allocs
}
}
for _, pkg := range input.BenchPkgs {
totals := *pkgTotals[pkg.ImportPath]
if input.Recursive {
for _, dep := range pkg.Deps {
depTotals := *pkgTotals[dep]
totals.Clock += depTotals.Clock
totals.Bytes += depTotals.Bytes
totals.Allocs += depTotals.Allocs
}
}
// Turn "golang.org/x/foo" into "GolangOrgXFoo".
name := pkg.ImportPath
name = strings.ReplaceAll(name, "/", " ")
name = strings.ReplaceAll(name, ".", " ")
name = strings.Title(name)
name = strings.ReplaceAll(name, " ", "")
// We are printing between "BenchmarkGeneratedBenchinit" and its results,
// which would usually go on the same line.
// Break the line with a leading newline, show our separate results,
// and then let the continuation of the original line go below.
// TODO: include the -N CPU suffix, like in BenchmarkGeneratedBenchinit-16.
fmt.Printf("\nbenchinit: Benchmark%s\t%d\t%d ns/op\t%d B/op\t%d allocs/op\ncontinuation: ",
name, b.N, totals.Clock.Nanoseconds()/int64(b.N), totals.Bytes/uint64(b.N), totals.Allocs/uint64(b.N))
}
// TODO: complain if any of our packages are not seen N times
}
| b72a4f830a8b32156a2d902ccdd9053215d2d1c4 | [
"Markdown",
"Go Module",
"Go"
] | 6 | Markdown | mvdan/benchinit | a1c84b4c2101da1204889faea72b9e16e7fb85d7 | 8f2043de8551529c7a646947bb94defc35a0b018 |
refs/heads/dev | <file_sep>var vow = require('vow'),
vowFs = require('vow-fs'),
fsExtra = require('fs-extra');
modules.define('providerFile', ['logger', 'util'], function(provide, logger, util) {
logger = logger(module);
provide({
init: function() {
//stub method
},
/**
* Returns loaded and parsed content of json file
* @param options - {Object} with fields
* - path {String} path to file
* @returns {vow promise object}
*/
load: function(options) {
logger.debug('load data from file file %s', options.path);
return vowFs.read(options.path)
.then(function(buf) {
return options.archive ? util.unzip(buf) : vow.resolve(buf);
})
.then(function(content) {
return content.toString('utf-8');
});
},
/**
* Stringify and save data object into json file
* @param options - {Object} with fields:
* - path {String} path to target file
* - data {String} content for file
* @returns {vow promise object}
*/
save: function(options) {
logger.debug('save data to file file %s', options.path ? options.path : 'unknown file');
return vowFs.write(options.path, options.data, 'utf8');
},
/**
* Makes directory for given options
* @param options - {Object} with fields:
* - path {String} path to target file
* @returns {*}
*/
makeDir: function(options) {
logger.debug('make directory %s', options.path);
return vowFs.makeDir(options.path);
},
/**
* Removes directory with all files and subdirectories
* @param options - {Object} with fields:
* - path {String} path to target file
* @returns {*}
*/
removeDir: function(options) {
logger.debug('remove directory %s', options.path);
var def = vow.defer();
fsExtra.remove(options.path, function(err) {
if(err) {
def.reject(err);
}
def.resolve();
});
return def.promise();
},
/**
* Removes file with given options
* @param options - {Object} with fields:
* - path {String} path to target file
* @returns {*}
*/
remove: function(options) {
logger.debug('remove file %s', options.path);
return this.exists(options).then(function(isExists) {
if(isExists) {
return vowFs.remove(options.path);
} else {
logger.warn('file %s does not exists', options.path);
return vow.resolve();
}
});
},
exists: function(options) {
return vowFs.exists(options.path);
}
});
});
<file_sep># Несколько вариантов реализации работы со списками с генераторами и без них
Задача реализовать механизм функции plus в двух алгоритмах поведения(вариант1 и вариант2 приведены ниже). Также приведен пример реализации plus, основанный на генераторах \[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators\].
Вариант 1
plus(3);//null
plus(4);//7
plus(10);/null
plus(1);//11
Вариант 2
plus(3);//3
plus(4);//7
plus(10);//17
plus(1);//18
Оба варианта без генераторов и с генераторами
Решения:
### Без генераторов
Решение варианта 1 основано на реализации "в лоб", что значения null и числовые чередуются. Решение основано на добавлении поочередно в массив значений до тех пор,пока инкрементирующий индекс не станет четным числом.
Код доступен по ссылке: [http://jsfiddle.net/5ZzLw/3/][0]
var plus = function(num){
if(typeof(plus.nums)=='undefined'){
plus.nums = [];
}
plus.nums.push(num);
if(plus.nums.length == 2){
res = plus.nums.reduce(function(m,n){return m+n;},0);
plus.nums = [];
return res;
}
return null;
};
console.log(plus(3));
console.log(plus(4));
console.log(plus(10));
console.log(plus(1));
Еще одно оригинальное решение:
function makeplus(summand){
var oldVal = null;
var counter = 0;
return function(summand){
var sum;
if ( counter++ % 2 ) {
sum = oldVal + summand;
}
else {
oldVal = summand;
sum = null;
}
return sum;
};
}
var plus = makeplus();
console.log(plus(3));
console.log(plus(4));
console.log(plus(10));
console.log(plus(1));
Следующая реализация варианта 1 представляет собой "хардкорное" решение, советуем прочитать, понять и забыть:) Решение основано на чередовании переопределения window.plus c plusOne на plusTwo. Для сложения первое значения f.store хранится в объекте с предыдущего шага, а следующее из вызова plus(second = arguments\[0\]). Так делать не стоит, поскольку каждый раз мы работаем в глобольном контексте window. Код доступен по ссылке:
[http://jsfiddle.net/TZV5Y/9/][1]
window.plusOne = function(num){
var f = function(){
return window.plusTwo(f.store,arguments[0]);
};
f.store = num;
window.plus = f;
return null;
};
window.plusTwo = function(a,b){
window.plus = window.plusOne;
return a + b;
};
window.plus = plusOne;
console.log(plus(3));
console.log(plus(4));
console.log(plus(10));
console.log(plus(1));
Реализация варианта 2),заключающегося в суммировании чисел массива из двух элементов:1-ый эелемент-входящее значение,втрой - результат предыдущего вызова функции.
Код доступен по ссылке: [http://jsfiddle.net/pyfub/8/][2]
function realize(fn){
var slice = Array.prototype.slice,
res = 0;
return function(){
//new_args = slice.call(arguments) - аргументы функции newadd
var new_args = slice.call(arguments);
new_args.push(res);
//console.log(new_args);
self++;
res = fn.apply(null, new_args);
return res;
}
}
function add(x,y){
return x + y;
}
var newadd = realize(add);
console.log(newadd(3));//3
console.log(newadd(4));//7
console.log(newadd(10));//17
console.log(newadd(1));//18
Рассмотрим другие идеи реализации варианта 2). Можно его сделать создавая для каждого вызова экземпляр объекта хранилища входящих параметров и вызывая общий прототип для хранения всех данных входящих. Далее можно выбрать один из алгоритов суммирования, например, записав его в prototype sum
Ссылка на код: [http://jsfiddle.net/PaU2z/3/][3]
function plus(x,y){
this.masArgs = Array.prototype.slice.call(arguments,0);
var a = new storage(this.masArgs);
}
function storage(arrayArgs){
this.args = arrayArgs || [];
return this.collectArgs();
}
storage.prototype.collectArgs = function(){
if (typeof this.newarrayArgs === "undefined") this.newarrayArgs = [];
this.newarrayArgs.push(this.args);
console.log(this.newarrayArgs);
}
console.log(plus(3));
console.log(plus(4));
console.log(plus(5,6));
### С генераторами
[http://jsfiddle.net/Wjr24/9/][4]
var generator = function* (){
while(1){
var a = yield a+b;
var b = yield null;
}
};
var plus = function(num){
if(typeof(gen)=='undefined' || gen == null){
gen=generator();
gen.next();
}
return gen.next(num).value;
}
console.log(plus(3));
console.log(plus(4));
console.log(plus(10));
console.log(plus(1));
реализация с генераторами примера 2\.
[http://jsfiddle.net/Wjr24/6/][5]
var generator = function(){
var sum = 0;
while(1){
var a = yield sum;
sum = sum + a;
}
};
var plus = function(num){
if(typeof(gen)=='undefined' || gen == null){
gen=generator();
gen.next();
}
return gen.next(num).value;
}
console.log(plus(3)); //3
console.log(plus(4));//7
console.log(plus(10));//17
console.log(plus(1));//18
[0]: http://jsfiddle.net/5ZzLw/3/
[1]: http://jsfiddle.net/TZV5Y/9/
[2]: http://jsfiddle.net/pyfub/8/
[3]: http://jsfiddle.net/PaU2z/3/
[4]: http://jsfiddle.net/Wjr24/9/
[5]: http://jsfiddle.net/Wjr24/6/<file_sep># Пишем парсер на NodeJS
Официально заявляю, что легче всего написать Parser именно на Javascript, ибо тут сам язык давно привык работать с DOM'ом и придуманы хорошие удобные способы работы с этим чудом.
Но я пишу этот материал, не только для того чтобы рассказать как, но и проактуализировать выводы на 2014 год.
Раньше основной библиотекой для парсинга был JSDOM, который страдал излишней тяжеловесностью и на самом деле тормозил скорее процесс парсинга. Но время изменились и пришел [cheerio][0]. Он делает почти все то же самое, и отбрасывает лишние из процесса, при этом сам реализует какую-то часть jQuery(а именно ту, которая нам нужна для парсинга). И за счет этого позволяет наконец написать не тормозящий парсер, при этом не используя regexp'ы ради увеличения производительности.
### Технологии
Мы будем использовать [Q][1] - для создания Defered и построения асинхронной очереди, [request][2] - для добычи контента, и [cheerio][0] для уже самого парсинга.
### Пример в вакууме №1
request(url, function(err, res, body){
if(err){console.log(err);}
else{
$ = cheerio.load(body);
var cards = [];
$('.card').each(function(){
cards.push({
title:$('.title',this).text(),
url:$('a',this).attr('href')
});
});
}
}
Таким не хитрым образом можно спарсить страницу :)
Но что делать если страницы больше, чем одна? У нас появятся 2 проблемы если мы будем решать в лоб не используя Promise. Первая - уход в stack, вторая - уход в память через дублирование scope. Корень всего зла конечно рекурсивная функция, которая нам не сильно подходит при парсинге, соотвественно нам нужно построить асинхронную очередь без увеличения уровня скопа.
Для этого делим нашу программу на 2 этапа:
**Этап 1:** взятие страницы с пагинатором и узнавание количества страниц всего.
**Этап 2:** создание асинхронной очереди, в которую мы цепляем нашу парсящую функцию.
Функция которая будет выполнятся в асинхронной очереди может быть сделана 2мя способами.
Первый: мы порождаем подскопы на каждый из вызовов заранее(код ниже требует доработки прежде чем войти в production):
for(var i = 0; i<l;i+=){
chain.then(asyncF.bind({page: i}));
}
внутри асинхронной функции должно быть тогда чтение контекста из this.page.
Другой же способ состоит в том чтобы иметь общий поток данных в глобальном виде, а внутрь асинхронных функций просто передавать число которое будет увеличиваться уже в самой асинхронной функции, как это сделано ниже:
### Пример в вакууме №2
//stage 1
request('pager',function(err,res, body){
$ = cheerio.load(body);
var pager = $('.pager');
var limitPage = parseInt( pager.eq(pager.length-1).text().trim(), 10);
//stage 2
function parsePage(page){
var defer = Q.defer();
request('/pager/'+page,function(err,res, body){
if(page<=limitPage){
defer.resolve(page+1); //инкрементируем счетчик страниц прямо в асинхронной последовательности передавая его в качестве аргумента следующим вызовам
} else {
defere.reject();
}
//тут код из первого абстракного примера
});
//возвращаем promise чтобы на нем построить последовательность.
return defer.promise;
}
var chain = Q.fcall(function(){
return parsePage(1);
});
for(var i = 2; i<limitPage;i++){
chain = chain.then(function(page){
return parsePage(page); // цепляем в цепь новые задачи на парсинг, как старые выполнятся.
});
}
});
[0]: https://github.com/MatthewMueller/cheerio
[1]: https://github.com/kriskowal/q
[2]: https://github.com/mikeal/request<file_sep># Прокси-объект
> Объект, являющийся хранилищем получаемых данных. Необходим для того, чтобы, например, при работе с ajax не запрашивать уже полученные данные снова у сервера, а отдавать их по ключу запроса. Request(key) - ajax, mapReduce ...
>
[http://jsfiddle.net/GD9nj/][0]
function proxy(key){
if (typeof(data) == 'undefined'){
obj = {};
}
if (obj[key] == undefined){
obj[key] = request(key);
}
return obj[key]
}
[0]: http://jsfiddle.net/GD9nj/<file_sep># Анаграмма
**Исходный набор слов: \[ 'пот', 'топ', 'вафля', 'взор', 'ровз' \]**
Выходной массив: \[\[ 'пот', 'топ' \], \[ 'взор', 'ровз'\], \[ 'вафля' \]\]. Порядок в выходящем массиве не важен. Важно чтобы анаграммы были соединенные в один подмассив.
Результаты([http://jsfiddle.net/NT4G3/6/][0])
var a = ['пот', 'топ', 'вафля', 'взор', 'ровз'],
term, b = {}, res = [];
for (var i = a.length; i--;) {
term = a[i].split('').sort().join('');
if (b[term]) {
b[term].push(a[i]);
} else {
b[term] = [a[i]];
};
}
for (i in b) {
if (b.hasOwnProperty(i)) {
res.push(b[i]);
}
}
console.log(res);
[0]: http://jsfiddle.net/NT4G3/6/<file_sep># MySQL блокировки

## Введение
При разработке конкурентного приложения, всегда сталкиваешься с проблемами адекватности и актуальности информации при обработке запроса.
Самым часто встречающимся примером является конечно комментарии и их добавление. Обычно происходят следующие действия:
* проверка на то когда было последнее собщение, дабы избежать флудинга, double клика на отправку и ботования, через 1го юзера
* проверка на права пользователя, является ли он вообще зарегистрированным
* проверка находится ли в тексте мат
* увеличение количество комментов у материала, дабы каждый раз не делать агрегирующий count запрос при выводе количества комментов
* собственно само добавление коммента
И встают трудности. Во-первых это конечно, вопрос процессинга, как сделать так чтобы в логике не было дыр.
Нужно задать себе вопрос, а что если..?
_А что если сервер упадет в процессе или произойдет ошибка в одном из запросов?_
Конечно на вопрос о том как защитить себя от этого является **транзакция**, о ней подробнее чуть позже. Стандартный движок MyISAM правда этого не поддерживает, поэтому сразу можно говорить, о том что, только InnoDB мы будем в дальнейшем рассматривать как более менее надежный движок. Тем более что единственный способ создания блокировки в MyISAM является LOCK TABLE, т.е. есть возможность блокировать записи только на уровне таблицы, но не на уровне конкретной строки, как это умеет делать InnoDB.
_А что если приходят два запроса одновременно и при этом оба прошли первую стадию и готовятся к выполнению?_
Не допускать этого - используя в качестве блокировки нечто общее, на что и идет проверка. Но это фактически означает, что мы объявляем некий код, код который фактически исполняется только в однопоточном режиме и мы должным понимать, что если таких операций много, то мы скатимся к тому что сервер основное время будет ждать, что конечно не сильно напряжно, но в определенных случаях очередь может начать копится, и тогда весь процесс рухнет. Впрочем если мы делаем блокировку на логическом уровне, то можно делать ее даже не средствами базой данных, а на уровне логики приложения, что однако не спасает нас от того, что база может работать с еще одним приложением, но в таком случае не будет порождено лишнего коннекта.
_А что если мне при этом данные нужны всегда актуальные? А что если у меня deadlock?_
Вот тут уже всегда приходятся решать для себя самостоятельно.
## Транзакции
Транзакции - основа всей safe направленности SQL. Они направлены на то, чтобы в любой момент можно было отменить последовательность действий. Вы начинаете транзакцию и говорите в конце commmit = что означает, что все изменения вступят в силу и отменить их будет отдельный геморой, либо rollback, что откатит все внесенные вами изменения во время транзакции. Транзакции жизнено важны для функционирования серьезных систем с массой проверок и действий, т.к. отказ может быть уже после 100го изменения, а как вернуть изначальное состояние в этом случае совсем геморойная задача. Но это конечно не волшебство и поэтому они имеют тонкости внутри.
#### Синтаксис
Обычно у транзакции имеется следующий синтаксис:
**START TRANSACTION** / **BEGIN WORK** - команда показывающая, что в текущем соединение с сервером начата транзакция, и все последующие операции связаны именно с ней, до того как произойдет commit или rollback или какая-то ошибка, которая автоматически приведет к rollback'у данных.
**COMMIT** - заканчивает транзакцию, все изменения произведенные в ней множеством операций накладываются уже на базу и не подлежат откатке через транзакцию.
**ROLLBACK** - заканчивает транзакцию, наоборот откатывая назад все изменения внутри нее, как будто и не было этой транзакции.
Все операции **UPDATE**/**DELETE** становятся блокирующими на уровне строк, с которыми шла работа.
У **SELECT** появляется возможность дописать **FOR UPDATE**/**LOCK IN SHARE MODE**, который также делает блокирующим и его, любой другой запрос **UPDATE**/**DELETE**, такой же **SELECT...FOR UPDATE**, будет ждать пока транзакция не кончится.
#### Уровни изоляции
Уровень изоляции фактически определяет как будут видны изменения внутри транзакции и снаружи ее. И как будут блокироваться структуры внутри таблицы.
К примеру у нас есть таблица **info** со следующей структурой:
* id(primary int autoincrement)
* data(varchar)
в ней 20 пустых строк, только id.
Представим, что у нас есть 2 клиента, которые чего-то хотят от базы.
**CLIENT 1:**
_START TRANSACTION;_
_INSERT INTO info VALUES ();_
_SELECT \* FROM INFO;_
**CLIENT 2:**
_SELECT \* FROM info;_
Мы увидим, что добавилась новая строка с **CLIENT 1**, но не увидим ее из под **CLIENT 2**.
Существует несколько уровней изоляции транзакции: _REPEATABLE READ, READ COMMITTED, READ UNCOMMITTED, SERIALIZABLE_.
Каждый из этих уровней закрывает собой какую-то проблему.
* Транзакция 0-го уровня **READ UNCOMMITTED** позволяет только откатыватся назад, но не создает какую-либо изоляцию, и любой процесс может прочесть данные, которые еще не были даже закомитены. Зато таким образом всегда самые свежие, пусть возможно и ложные данные.
**CLIENT 1:**
_START TRANSACTION;_
_UPDATE info SET data = 'fafa' where id = 1;_
_SELECT \* FROM INFO where id = 1;_
**CLIENT 2:**
_SELECT \* FROM info where id = 1;_
Второй клиент видит данные которые изменил первый в транзакции. _\[data:'fafa', id: 1\]_
* **READ COMMITTED** создает фактически отдельный скоп для транзакции, не давая читать из вне данные, которые еще не были закомитены. Этот случай рассмотрен первым.
* **REPEATABLE READ** расширяет скоп из _READ COMMITTED_ добавляя в него еще тот факт, что если произошли изменениями с теми данными, которые уже были прочитаны в транзакции, то результат чтения останется тем же самым, не смотря на эти изменения.
**CLIENT 1:**
_START TRANSACTION;_
_SELECT \* FROM INFO where id = 1;_
**CLIENT 2:**
_START TRANSACTION;_
_UPDATE info SET data = 'fafa' where id = 1;_
_COMMIT;_
**CLIENT 1:**
_SELECT \* FROM INFO where id = 1;_
CLIENT 1 получит все еще данные без 'fafa', хотя данные уже закомичены.
По default'у в InnoDB стоит именно этот режим.
* **SERIALIZABLE** все то же самое что _REPEATABLE READ_, но добавляет что всякий _SELECT_ будет преобразован в _SELECT...LOCK IN SHARE MODE_. Таким образом внося больше блокировок.
Можно настроить, чтобы каждая транзакция запускалась со своим уровнем блокировки перед этим написав _SET TRANSACTION ISOLATION LEVEL LEVEL\_NAME_, но почему-то у меня эта возможность заработала криво, так что потребовало перезапуска сервера.
#### О блокировках
Фактически **SELECT** может использоватся для блокировки связанной с обработкой бизнес логики. Например вы всегда можете **SELECT**'ить запись пользователя через **SELECT...FOR UPDATE** при том что он выполняет какое-то действие, таким образом вы поставите все действия конкретного пользователя в очередь используя силы MySQL.
**UPDATE**/**DELETE** конечно же блокирует использование записи в другой транзакции, но служит уже скорее окончательными постулатами после ряда проверок.
**SELECT** впрочем не так то прост. Помимо **SELECT...FOR UPDATE** активно используется **SELECT...LOCK IN SHARE MODE**. В чем же отличие?
**SELECT...LOCK IN SHARE MODE** используется больше для объявления, того чтобы никто не изменял и не удалял эту строку, но при этом разрешено чтение всем остальным, кто придет с таким же **SELECT...LOCK IN SHARE MODE**, в то время как **SELECT...FOR UPDATE** блокирует, помимо **UPDATE** и **DELETE**, так еще и **SELECT...LOCK IN SHARE MODE** и **SELECT...FOR UPDATE** от других транзакций. Т.е. **SELECT...FOR UPDATE** это исключительная блокировка, в то время как **SELECT..LOCK IN SHARE MODE** это блокировка записи от уничтожения или изменения, блокировка на совместно чтение.
Все блокировки конечно же снимаются как только транзакция заканчивается.
## Проза
При написание программы, в которой вы управляете процессом вполне хватает уровня изоляции **READ COMMITTED**, так как мне лично кажется, что это перебор все таки играть с **REAPEATABLE READ**, в связи с тем, что я наоборот хочу получать актуальные данные и если король оказался голым то откатить текущую транзакцию, вместо того чтобы притворится истинным гением.
Помимо того что существует сама транзакция, вы должны понимать, что каждая транзакция должна быть в отдельном соединение. Не то чтобы поднимать соединения тяжко, но на каждую транзакцию вы обязаны сделать отдельное соединение. В то время как на обычные запросы, которые занимаются аналитикой или выводом только, можно составить пул из ограниченного количества соединений и наоборот заранее прогреть, что называется соединения. Подготовится.
Добавления комментария в любом случае нужно делать _отдельным собитем_ в том в плане, чтобы блокировать все левые поползновения в этом плане, иначе проблем с адекватностью данных прибавится. **SELECT...FOR UPDATE** желательно наложить на тот же самый коммент при редактирование или на пользователя при добавление комментарии, дабы не дать прокомментировать 2 раза подряд. С другой стороны можно взять id пользователя и по нему на стороне приложения сделать очередь через id.
Надеюсь, что сии рассуждения вам как-то помогли и просветили насчет блокировок в MySQL.
Удачи в ваших исследованиях.<file_sep># Трюки с + и alert
> Задача состоит в том, чтобы один и тот же экземпляр random выводил разные значения в alert. Подвох заключается том, что alert преобразует входящие параметры через toString
>
function RandomNumber(){
//this.a = Math.ceil(Math.random() *100);
}
RandomNumber.prototype.toString = function(){
this.a = Math.ceil(Math.random() *100);
return this.a.valueOf()
}
var random = new RandomNumber();
//alert(random); // 46
//alert(random); // 87
> Подвох снова заключается в alert. В первом вызове в конечном итоге 20 + '0' = 200\. При суммировании значения складываются по valueOf(), уже потом alert преобразует это значение путем toString(). Фишка вызова с ((2).multiply(10)+0) заключается в том, что ссылка на возвращаемый объект multiply теряется и alert вызывает нативный метод Number.prototype.toString(). Первый же вызов возвращает объект. Т.к. alert преобразует входящие аргументы в тип toString(), втроенные во входящие аргументы, то объекта obj вызовится его метод toString() переписанный нами.
>
Number.prototype.multiply = function(a){
var obj = {};
var number = this;
obj.valueOf = function(){
return number * a
}
obj.toString = function(){
return obj.valueOf() + '0'
}
return obj
//то, что вернет наша функция multiply
}
alert((2).multiply(10)) // 200
alert( ((2).multiply(10)+0) ) // 20
Код доступен по ссылкам: [http://jsfiddle.net/Jdv2k/1/][0]
[http://jsfiddle.net/Jdv2k/][1]
[0]: http://jsfiddle.net/Jdv2k/1/
[1]: http://jsfiddle.net/Jdv2k/<file_sep>modules.define('i-bem__dom', ['jquery'], function(provide, $, BEMDOM) {
BEMDOM.decl('block', {
onSetMod: {
js: {
inited: function() {
var _this = this,
tabs = _this.findBlockInside('tabs');
_this.wrapTables();
if(tabs) {
_this._openTabFromUrl(tabs);
// support back/next button in browser (html5 history api)
_this.bindToWin('popstate', function() {
_this._openTabFromUrl(tabs);
});
// set url for the current tab (html5 history api)
tabs.on('select', function(e, data) {
var tabName = data.newTab.data('tab');
_this._setTabUrl(tabName);
if(tabName === 'examples') {
_this._loadExamples();
}
});
}
}
}
},
wrapTables: function() {
var tables = this.domElem.find('table');
if(tables.length) {
tables.each(function() {
$(this).wrap('<div class="table-container"></div>');
});
}
},
// When page load, first time open tabs
// if the name of a tab in the location.pathname
_openTabFromUrl: function(tabs) {
if(this._isTabNameInPath()) {
this._openTabByDataName(tabs, this._getTabName());
} else {
tabs.setActiveTab(0);
}
this._loadExamples();
},
_isTabNameInPath: function() {
return this._getTabName() ? true : false;
},
_openTabByDataName: function(tabs, tabName) {
tabs.elem('tab').each(function(idx, tab) {
if($(tab).data('tab') === tabName) {
tabs.setActiveTab($(tab));
}
});
},
_getTabName: function() {
// get tabName without slashes
var tabName = window.location.pathname.match(/\/(docs|jsdoc|examples)\/$/);
return tabName ? tabName[1] : false;
},
_setTabUrl: function(tabName) {
// inherit form page block
if(window.legacyIE) return;
// Fix duplicate name tab in location.pathname, 'button/docs/jsdoc/examples/docs/'
// when tabname is isset in location.pathname,
// in this case get direct block path with regexp + tab name
if(this._isTabNameInPath()) {
tabName = window.location.pathname.match(/\S+(?=(docs)|(jsdoc)|(examples))/)[0] + tabName;
}
window.history.pushState(null, null, tabName + '/');
},
_loadExamples: function() {
var self = this;
this.findBlocksInside('block-example').forEach(function(example) {
// lazy loading for default examples in tab 'examples'
if(example.hasMod('view', 'default') && self._getTabName() !== 'examples') {
return false;
}
example
.setMod('js', 'inited')
.loadIframe('live');
});
}
});
provide(BEMDOM);
});
<file_sep>modules.define('menu-list', ['i-bem__dom', 'jquery'], function(provide, BEMDOM, $) {
'use strict';
provide(BEMDOM.decl({ block: 'menu-list', modName: 'type', modVal: 'level' }, {
onSetMod: {
js: {
inited: function() {
this._selectLevel = this.findBlockInside('level-select', 'select');
this._selectLevel.on('change', this._showLevel, this);
}
}
},
_showLevel: function() {
var self = this,
$groups = this.elem('level-group'),
level = this._selectLevel.getVal();
this.delMod($groups, 'hide');
if(level === 'all levels') {
return false;
}
$groups.each(function(idx, el) {
var $group = $(el);
!($group.data('level') === level) && self.setMod($group, 'hide', 'yes');
});
return this;
}
}));
});
<file_sep>var md = require('marked');
var renderer;
function createRenderer() {
renderer = new md.Renderer();
/**
* Fix marked issue with cyrillic symbols replacing
* @param text - {String} test of header
* @param level - {Number} index of header
* @param raw
* @param options - {Object} options
* @returns {String} - result header string
*/
renderer.heading = function(text, level, raw, options) {
var specials = null,
anchor;
/* jshint ignore:start */
specials = ['-','[',']','/','{','}','(',')','*','+','?','.','\\','^','$','|','\ ','\'','\"'];
/* jshint ignore:end */
options = options || {};
options.headerPrefix = options.headerPrefix || '';
anchor = options.headerPrefix + raw.replace(RegExp('[' + specials.join('\\') + ']', 'g'), '-');
return '<h' + level + ' id="' + anchor + '"><a href="#' + anchor + '" class="anchor"></a>' + text + '</h' + level + '>\n';
};
// Fix(hidden) post scroll, when it contains wide table
renderer.table = function(header, body) {
return '<div class="table-container">' +
'<table>\n' +
'<thead>\n' +
header +
'</thead>\n' +
'<tbody>\n' +
body +
'</tbody>\n' +
'</table>\n' +
'</div>';
};
// Add container for inline html tables
renderer.html = function(source) {
var newHtml = source.replace(/<table>/, '<div class="table-container"><table>');
return newHtml.replace(/<\/table>/, '</table></div>');
};
return renderer;
}
exports.getRenderer = function() {
return renderer || createRenderer();
};
<file_sep># Рекурсия(числа Фиббоначи)
0,1,1,2,3,5,8,13,21... - последовательность чисел Фиббоначи
function fib(n) {
var a = 1, b = 1;
for (var i = 3; i <= n; i++) {
var c = _.reduce([a,b], function(memo, num){
return memo + num;
}, 0);
a = b;
b = c;
}
return b;
}
console.log(fib(2));//1
console.log(fib(3));//2
console.log(fib(8));//21
[http://jsfiddle.net/XEkwv/1/][0]
[0]: http://jsfiddle.net/XEkwv/1/<file_sep># Перерыв на Олимпиаду!
Друзья, всем привет!
Моих постов долгое время не было, и это неслучайно! В нашей стране проводятся Олимпиада и Паралимпийские игры, и, вот я, как и все болельщики нашей страны, несколько подвисла с активностью:) Но тем не менее, за это время пришло достаточное количество хороших мыслей, с которыми в ближайшем будущем я буду делиться. Каждой игре по огоньку и адресую их всем неравнодушным: [http://alvov.github.io/rhombus-fire/][0]
[0]: http://alvov.github.io/rhombus-fire/<file_sep># Pattern Responsible chain(Цепочка обязанностей)
[http://jsfiddle.net/qHL6e/6/][0]
function func1(next, val){
if(true){
console.log('1');
next();
} else {
next(false);
}
}
function func2(next, val){
console.log('2');
next();
}
function func3(next, val){
console.log('3');
next();
}
function fail(){
console.log('fail baby');
}
function Chain(){
}
Chain.prototype.next = function(){
if (arguments.length>0)
this.handlerFail(this.val);
else{
if (this.handlers[++this.index]!=undefined) this.handlers[this.index(this.next.bind(this), this.val);
}
}
Chain.prototype.add = function(handler){
if (typeof(this.handlers) == 'undefined'){
this.handlers = [];
}
this.handlers.push(handler);
return this;
}
Chain.prototype.fail = function(handler){
this.handlerFail = handler;
return this;
}
Chain.prototype.execute = function(val){
this.val = val;
this.index = 0;
if (this.handlers.length>0)
this.handlers[this.index](this.next.bind(this), val);
}
var chain = new Chain();
chain.add(func1).add(func2).add(func3).fail(fail).execute(123);
Результат выполнения:
1
2
3
[0]: http://jsfiddle.net/qHL6e/6/<file_sep># Прелести underscore
Задача сделать typing для онлайн чата была бы жутчайшим занятием без полезной библиотеки underscore. То, о чем мы говорили в первом подкасте(о важности знать удобные тулзы и библиотеки, которые облегчают и упрощают написание сложных проверок, алгоритмов фильтрации и прочее). Зацените выборки неповторяющихся элементов в массивах:
var a = {"1":"asdasd","2":"sdf","3":"iui","4":"hjhj","5":"shdjsdf","6":"sjdhfsdhf"};
var b = {"1":"ajsgdjsg","5":"jsdh","3":"mnb","8":"asdas","5":"shgda","6":"djshf"};
console.log(_.keys(a));
function difference(){
var A = _.keys(a),B = _.keys(b);
var removed = _.difference(A, B);
var added = _.difference(B, A);
console.log('removed' + removed);
console.log('added' + added);
}
difference();<file_sep># Пример переопределения нативного метода push у объектов типа Array
var MyArray = function(){
Array.prototype.push.apply(this, Array.prototype.slice.call(arguments, 0));
}
> //F = function(){};
> //F.prototype = Array.prototype;
> MyArray.prototype = new Array(); //new F
Две формы записи (с вспомоготельным объектом F и только с Array) имеют место быть. Использовать дополнительный объект правильнее в данном случае, поскольку функция F имеет пустую функцию-конструктор, а Array обладает непустым конструктором.
MyArray.prototype.push = function(){
Array.prototype.push.apply(this, arguments);
}
a = new MyArray(1,2,3);
a.push(4);
Пример на переопределения нативного push:
function MyArray() {
this.args = Array.prototype.slice.call(arguments)||[];
}
MyArray.prototype.push = function(b) {
this.args.push(b);
console.log(b);
}
MyArray.prototype = Array.prototype
var myArr = new MyArray(3,5,6);
myArr.push(1);
Еще один способ переопределения:
var MyArray = function(){
Array.prototype.push.apply(this, Array.prototype.slice.call(arguments, 0));
}
MyArray.prototype = new Array(); //new F
MyArray.prototype.push = function(){
console.log(arguments);
Array.prototype.push.apply(this, arguments);
}
a = new MyArray(1,2,3);
a.push(4);
console.log(a);<file_sep>modules.define('middleware__page-title', ['config', 'logger'], function(provide, config, logger) {
logger = logger(module);
provide(function() {
return function(req, res, next) {
logger.debug('get title by request %s', req.url);
var node = req.__data.node,
traverseTreeNodes = function(node) {
node.url && node.title && titles.push(node.title[req.lang]);
node.parent && traverseTreeNodes(node.parent);
},
titles = [];
if(req.url === '/') {
req.__data.title = node.title[req.lang];
return next();
}
traverseTreeNodes(node);
//add common suffix from application configuration
titles.push(config.get('title')[req.lang]);
req.__data.title = titles.join(' / ');
return next();
};
});
});
<file_sep># 3K Programming Cast
### dadad
****dadad
Привет всем и каждому в отдельности! Я и компания моих друзей-разработчиков, Коли и Кирилла, они являются топовыми разработчиками по JS, PHP, NodeJS, Java стали вести с прошлой недели серии подкастов о программировании на JS и цунами веб-технологий и т.д. Вот пара подкастов была вводных, мы говорили о работе веб-разработчика, о мотивациях, о стеке технологий, которые желательно изучать начинающим и опытным разработчикам JS, о различных собеседованиях и делились опытом, которые получали являясь в свое время и кандидатами при приеме на работу и, собственно говоря, руководящими людьми в этом процессе. Этот блог я буду посвящать нашим выпускам, делать небольшие ревью по темам.
Слушайте нас([http://3k.rpod.ru/][0]), читайте и изучайте все по JS, что вам кажется интересным, все в этой жизни нужно, полезно и интересно знать!
Следующие выпуски подкастов будут более детальными по технологиям, углубляться будм в детали особо важные, расскажем про experience.
- item
- item
- item
[0]: http://3k.rpod.ru/<file_sep>
bem-site-engine
========
Платформа для создания сайтов с документацией.
В настоящее время на базе данной платформы созданы и работают следующие сайты:
* [Bem-Info](http://bem.info)
### Установка, сборка и запуск
Клонируем проект:
```
$ git clone git://github.com/bem/bem-site-engine.git && cd bem-site-engine
```
##### Установка, сборка данных и запуск приложения одной командой
```
npm run make
```
##### Команды
* Установка зависимостей: `npm install && node postinstall.js`
* Запуск сервера: `npm start`
* Удаление логов: `npm run clean_logs`
* Удаление кеша примеров блоков: `npm run clean_cache`
* Удаление всех собранных данных: `npm run clean_data`
* Запуск тестов jshint и jscs: `npm run test`
Сборка данных:
* development: `node bin/data.js development`
* testing: `node bin/data.js testing`
* production: `node bin/data.js production -v latest`
Более подробно о командах сборки данных можно прочитать в [Соответствующем руководстве](./docs/data_compiling.ru.md)
### Документация
* [Создание модели](./docs/model.ru.md)
* [Конфигурация](./docs/config.ru.md)
* [Описание middleware модулей](./docs/middleware.ru.md)
* [Описание процесса сборки](./docs/data_compiling.ru.md)
Ответственные за разработку:
* [<NAME>](https://github.com/tormozz48)
* [<NAME>](https://github.com/tavriaforever)
* [<NAME>](https://github.com/tadatuta)
* [<NAME>](https://github.com/andrewblond)
* [<NAME>](https://github.com/dab)
<file_sep># Наследование
За теоретическую основу и реализацию самой функции наследования был взят материал <NAME>(Шаблоны Проктирования) и раздел ООП(\[javascrit.ru\]).
Код приведённый ниже доступен по ссылке: [http://jsfiddle.net/5F9gM/4/][0]
function extend(Child, Parent) {
var F = function() { }
F.prototype = Parent.prototype
Child.prototype = new F()
Child.prototype.constructor = Child
Child.superclass = Parent.prototype
}
function A(){
}
A.prototype.say = function(){
console.log('a');
}
function B(){
}
function C(){
}
function D(){
}
extend(B,A);
extend(C,A);
extend(D,C);
var a,b,c;
a = new A();
b = new B();
c = new C();
d = new D();
B.prototype.say = function(){
B.superclass.say();//вызывает say() суперродителя(самый верхний элемент в графе потомков)
console.log('b');
}
C.prototype.say = function(){
C.superclass.say();
console.log('c');
}
D.prototype.say = function(){
D.superclass.say();
console.log('d');
}
a.say();//a
b.say();//a b
c.say();//a c
d.say();//a c d
В данной цепочке интересен вызов метода через superclass(это не встроенный метод, его можно назвать как угодно(uber у Стефанова)).Superclass примененный к методу отыскивает его во всей цепочке прототипов пока не найдет самого главного Parent(тот метод-родитель от которого выполнялся extend класса), содержащего метод say. Например, у инстанса с от объекта C есть свой метод say(), но superclass будут методы,содержащиеся в prototype A. Таким образом, D являющийся копией объекта С, имеет ссылку superclass на методы prototype C, но это не самый верхний родитель, здесь superclass пойдет дальше искать родителей класса C. Т.к. наследование C проводилось от объекта A,то ссылка superclass укажет также и на prototype метода A.
#### Еще один интересный пример:
var ClassP = function(src){
this.src = src;
};
ClassP.prototype.do = function(a){
console.log(this.src,a);
};
var Child = function(){
ClassP.apply(this, arguments);
};
var F=function(){};
F.prototype = ClassP.prototype;
Child.prototype = new F();
Child.prototype.do = function(a){
ClassP.prototype.do.apply(this, arguments);
alert(this.src+a);
};
var c = new Child('fenshuj');
c.do('ffff');
Вывод:
alert(fenshujffff);
console.log('fenshuj ffff ');
Можно сказать,что наследование такое же как в extend правда без ссылки на объект superclass. Метод do объекта Child расширен методом ClassP с добавлние функциональности.
[0]: http://jsfiddle.net/5F9gM/4/<file_sep># NodeTypes
Написать функцию, которая принимает html element node'у и возвращает результирующий массив текстовых нод(text node) которые находятся внутри. Использовать возможности нативного языка.
Пример html-разметки:
<div id="init">
<!-- fgsjhfsja -->
<span>lsjdflsk
<a href="/gb">ajhsdjagsjd</a>
</span>ewrhekrg
</div>
Решение завязано на свойствах js **childNodes** и **nodeType**:([http://jsfiddle.net/B2BZh/1/][0]). В отличии от children() jquery, нативный childNodes возвращает набор элементов-потомков с дополнительной информацией о том какого типа пришла node(element, textnode, comment, etc.). Более подробно о nodeTypes в [http://www.w3schools.com/jsref/prop][1]_node_nodetype.asp
function getTextNodes(el){
var res = [],
term;
for(var i = 0,l=el.childNodes.length;i < l;i++){
if (el.childNodes[i].nodeType===3){
if (term = el.childNodes[i].data.trim()){
res.push(term);
}
} else if (el.childNodes[i].nodeType===1){
res = res.concat(getTextNodes(el.childNodes[i]));
}
}
return res;
}
var el = document.getElementById('init'),
result = getTextNodes(el);
console.log(result);
[0]: http://jsfiddle.net/B2BZh/1/
[1]: http://www.w3schools.com/jsref/prop<file_sep>modules.define('i-bem__dom', ['jquery'], function(provide, $, BEMDOM) {
BEMDOM.decl('block-example', {
onSetMod: {
'js' : {
'inited': function() {
var self = this;
this.bindTo('source-switcher', 'pointerclick', function(e) {
e.preventDefault();
var target = $(e.target),
typeSource = this.getMod(target, 'type');
if(self._typeSource && self._typeSource !== typeSource) {
self
.delMod(self.elem('source-switcher'), 'active')
.delMod(self.elem('source-item'), 'visible');
}
self._typeSource = typeSource;
self.toggleSource(typeSource);
if(typeSource === 'html') {
self._getHtml(self.elemParams(target).urlBemhtml);
}
if(typeSource === 'bemjson') {
self.loadIframe('source-code');
}
});
this.loadComplete = {};
}
}
},
changeHeight: function(el) {
var iframe = this.elem(el),
doc = iframe[0].contentDocument || iframe[0].contentWindow && iframe[0].contentWindow.document,
height;
if (!doc) return;
height = doc.documentElement.scrollHeight || doc.body.scrollHeight;
if(el === 'source-code') {
// fix visible scroll
height += 5;
}
if (this._actualHeight !== height) {
iframe.attr('height', height);
this._actualHeight = height;
}
},
toggleSource: function(type) {
this
.toggleMod(this.elem('source-switcher', 'type', type), 'active', 'yes', '')
.toggleMod(this.elem('source-item', 'type', type), 'visible', true, '');
},
_getHtml: function(url) {
$.ajax({ url: url, dataType: 'text', context: this })
.done(function(html) {
html += ' ';
this.elem('source-code', 'type', 'html').text(html);
})
.fail(function(error) { console.log('error', error); });
},
loadIframe: function(el) {
if(this.loadComplete[el]) return;
var _this = this,
iframe = _this.elem(el),
url = iframe.data('url'),
isLive = (el === 'live');
isLive && this._toggleSpin();
iframe.attr('src', url);
iframe.load(function() {
isLive && _this._toggleSpin();
_this.changeHeight(el);
_this.loadComplete[el] = true;
});
},
_toggleSpin: function() {
this.findBlockInside('live-spin', 'spin').toggleMod('progress', true, '');
}
});
provide(BEMDOM);
});
<file_sep>var fs = require('fs');
var dirmd = 'md';
var files = fs.readdirSync(dirmd);
files.forEach(function(file, i){
// var content = fs.readFileSync(dirmd+'/'+file, {encoding: 'utf8'});
fs.readFile(dirmd+'/'+file, {encoding: 'utf8'}, function (err,data) {
if (err) {
return console.log(err);
}
var title = data.split('\n')[0].substr(2).trim();
var res = '# '+ title.replace(/\,(.+)\,\,/, function(str, p1, p2, offset, s){
console.log(arguments[1]);
return arguments[1]
}) + '\n' + data.split('\n').slice(1).join('\n');
fs.writeFile(dirmd+'/'+file, res, 'utf8', function (err) {
if (err) return console.log(err);
});
});
});<file_sep># Способы создания разреженного массива
Array.prototype.slice.call({length:5},0);
Array.prototype.push.apply(a,{length:5});
a = []; a.length = 5;
b = Array();//или new Array(), это одно и тоже<file_sep># Новый JSBoom
<file_sep># Масса бесполезных фактов об оптимизации V8/NodeJS (часть 1)
Мы снова в деле после долгого отсутствия. Поводом послужила моя попытка разогнать Javascript для одного из конкурсов и в процессе разгона, я понял довольно много о том, где есть узкие места в коде. Понятно, конечно что разгон оптимизаторство не сильно хорошая идея в JS, по хорошему все оптимизации должен делать JIT максимально интеллектуальным способом, да и самые лучшие разгоны от смены бизнес логики/алгоритма, а не от смены пары выражений. Тем не менее мне было очень интересно поковыряться и посравнивать, чтобы что-то себе обосновать я заодно пытался прочесть исходники V8, но к сожалению, мало что осмысленного сумел выудить, как именно работает JIT, я так и не догнал, но провел анализ на уровне последствий. Наверное это будет в несколько частей, поскольку довольно много всякого раскопал, ваши комментарии приветствуются :)
#### Switch
Плохо работает не с Integer: switch преобразуется таким образом в набор if/else. При большом количестве case'ов(я так думаю где-то от 10 case'ов среднее по switch'у будет хуже чем объект) лучше преобразовать этот набор в объект, где выборка происходит за константное время. В случае с Integer все гораздо быстрее. Как точно я сказать не могу, по исходному коду V8, сначала идет typecheck, а затем уже сравнение. Однако чисто по скорости выходит, что судя по всему происходит BTree внутри, если там Integer.
Link: [Benchmark][0].
Результаты бенчмарка:
Switch со строковыми 4мя case'ами(сразу взял худший случай):
**switch 4 x 33,643,664 ops/sec ±4.56% (84 runs sampled)**
Объект с 4мя property:
**obj 4 x 29,894,294 ops/sec ±1.33% (97 runs sampled)**
Чуть хуже результат.
Switch со строковыми 24мя case'ами, худший/лучший случай:
**switch 24 best x 57,746,772 ops/sec ±3.34% (65 runs sampled)**
**switch 24 worst x 9,067,273 ops/sec ±4.27% (82 runs sampled)**
Видно, что очень сильно разнятся эти случаи по скорости.
Объект с 24мя property:
**obj 24 x 33,022,036 ops/sec ±0.78% (99 runs sampled)**
Вот тут нету разницы между 4 property или 24 property.
Switch 24 case'а все integer, худший случай/лучший случай:
**switch int best x 51,757,926 ops/sec ±3.99% (90 runs sampled)
switch int worst x 47,792,792 ops/sec ±9.16% (82 runs sampled)**
По скорости тут не очень большая разница в скорости проверки.
Объект с 4мя property и ключи Integer:
**obj int x 22,696,294 ops/sec ±1.04% (99 runs sampled)**
Тут тратится дополнительное время на преобразование из Integer в String и только потом берется по ключу.
Все результаты конечно проводились не в ваакуме. Чтобы провести аналогичный скачайте себе файл из pastebin и поставить nodejs, а также модуль **benchmark** этой командой:
`npm install benchmark`
#### Динамическое создание функций
Фактически в javascript'е есть 3 способа создания функции:
**1\.** Первый самый обычный способ через function name(){} или var b = function(){}, статический способ, который будет обработан компилятором самым лучшим образом;
**2\.** Второй это вызвать тот же самый статический код через eval, но это страдает от того что он не будет отоптимизирован еще до применения и судя по тестам в дальнейшем также не будет оптимизирован.
**3\.** Создать функцию через **new Function**. Последним аргументом будет телом функции, а те что идут до должны являться строками, которые будут обозначать будущие аргументы. Например:
`var double = new Function('num','return num*2;');`
равнозначно
`var double = function(num){ return num*2; }`
Link: [Benchmark][1].
Результаты:
**static function x 60,944,355 ops/sec ±2.69% (81 runs sampled)
eval function x 5,327,642 ops/sec ±2.44% (86 runs sampled)
new Function x 40,244,307 ops/sec ±2.06% (89 runs sampled)**
По результатам сразу видно, что **eval** совсем отстойно отрабатывает. А вот **new Function** работает всего в 1.5 раза медленее, чем статическая функция, хотя в идеале все должно работать с одинаковой скоростью, но видимо v8 все таки еще не умеет до конца разгонять динамические функции.
[0]: http://pastebin.com/x9XGMGfT
[1]: http://pastebin.com/XpQAHyRq<file_sep># Load Balancing(Scale) Socket.IO c NGINX
Socket.IO замечательная штука для написания Realtime приложений(об это вы можете прочитать [здесь][0], в число ее многочисленных плюсов входит отслеживание heartbeat'а клиента и самостоятельное отключение его в случае если он отсутствует, востановление соединения в случае если оно было потеряно и конечно поддержка умелого даунгрейда. Но и у него есть пара минусов. Например ее невозможно использовать без sticky сессий(закрепленных за одним сервером), просто положившись на Round Robin, и она вообще слабо дружит с LB.
**Что будет если использовать без sticky session?**
Так как socket.io работает через handshake, где делает первый запрос, затем чтобы сервер ответил какие способы соединения может использовать клиент, и только потом идет попытка установить полноценное соединение через websocket. Соотвественно первый запрос приходит на сервер 1, а второй уже на сервер 2, таким образом получается, что клиента на 2м сервере заново просят пройти handshake.
## NGINX
В качестве Load Balancer'а у нас выступает nginx хотя HAProxy несомнено хорош, но в случае сайта, все таки имеет смысл сразу делать статику на nginx и соотвественно проксировать это там же.
Load Balancing на nginx со sticky session можно сделать следующими способами(их больше чем здесь перечислено, но я лично выбирал лишь из этого, потому что ставить модуль на ubuntu и отдельно компилить nginx не хотелось):
1\. начиная с 1.5.7 версии есть директива [sticky][1] у nginx.
2\. (им я пользуюсь) Load Balancing на клиенте, через Javascript, который рандомит функцию:
Псевдокод **JS**
var servers = [1,2,3,4];
if(typeof(getCookie('server'))=='undefined') setCokie('server', randomFrom(servers),{path:'/'});
Проставляем куку на клиенте до запроса к Socket.IO.
**NGINX**
map $cookie_server $balance {
default 127.0.0.1:3000;
1 127.0.0.1:3000;
2 127.0.0.1:3001;
3 127.0.0.1:3002;
4 127.0.0.1:3003;
}
Мапим по куке до конкретного сервера NodeJs.
location /socket.io/ {
proxy_pass http://$balance$uri;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
Там где у нас socket.io отдаем уже через reverse proxy'рование.
К тому что сверху и там там следует только дописать, что делать в случае падение одного из серверов и можно балансить как-то поумнее, но в принципе и так неплохо выходит.
Вот мы и сделали sticky session на nginx.
## Socket.IO
К сожалению проблема не исчерпана на этот момент. Балансится замечательно и красиво. Вот только нету у нас единной шины сообщений и хранилища между этими серверами. На помощь нам приходит [Redis][2], в качестве системы хранения данных и шины сообщений:
var RedisStore = require('socket.io/lib/stores/redis')
, redis = require('socket.io/node_modules/redis')
, pub = redis.createClient()
, sub = redis.createClient()
, client = redis.createClient();
io.set('store', new RedisStore({
redisPub : pub
, redisSub : sub
, redisClient : client
}));
Вуаля! Готово. Вот теперь ваше приложение на Socket.IO масштабируется! :)
[0]: http://socket.io
[1]: http://nginx.org/en/docs/http/ngx_http_upstream_module.html#sticky
[2]: http://redis.io/<file_sep>var path = require('path'),
util = require('util'),
cp = require('child_process'),
_ = require('lodash'),
vow = require('vow'),
vowFs = require('vow-fs');
function getEnvironment() {
//TODO implement your own environment detection
return 'development';
}
function runCommand(cmd, opts, name) {
var baseOpts = {
encoding: 'utf8',
maxBuffer: 1000000 * 1024
};
function _exec(cmd, options) {
var proc = cp.exec(cmd, options),
def = vow.defer(),
output = '';
proc.on('exit', function(code) {
if (code === 0) { return def.resolve(); }
def.reject(new Error(util.format('%s failed: %s', cmd, output)));
});
proc.stderr.on('data', function(data) { output += data; });
proc.stdout.on('data', function(data) { output += data; });
return def.promise();
}
console.info('execute command %s', cmd);
return _exec(cmd, _.extend(opts, baseOpts))
.then(function() {
console.info('command completed %s', name);
return vow.resolve();
})
.fail(function(error) {
console.error('command %s failed with error %s', name, error);
return vow.reject(error);
});
}
function checkOrCreateDir(dir) {
var directory = path.join(process.cwd(), dir),
createDir = function() {
console.info('create %s directory', dir);
return vowFs.makeDir(directory);
};
return vowFs.isDir(directory)
.then(function(isDir) {
if(!isDir) {
return createDir();
}
console.warn('directory %s already exists', dir);
return vow.resolve();
})
.fail(createDir);
}
console.info('--- application install ---');
return vow.all([
checkOrCreateDir('logs'),
checkOrCreateDir('backups'),
checkOrCreateDir('cache').then(function() {
return vow.all([
checkOrCreateDir('cache/branch'),
checkOrCreateDir('cache/tag')
]);
})
])
.then(function() {
return runCommand(util.format('ln -snf %s current', process.env.NODE_ENV || 'dev'), {
cwd: path.join(process.cwd(), 'configs')
}, 'set config');
})
.then(function() {
var borschikPath = path.join('configs', 'current', 'borschik');
return vowFs.exists(borschikPath).then(function(exists) {
if(exists) {
return runCommand(util.format('ln -sfn %s .borschik', borschikPath), {}, 'make borschik symlink');
}
return vow.resolve();
});
})
.then(function() {
return runCommand('bower-npm-install --non-interactive', {}, 'bower-npm-install');
})
.then(function() {
return runCommand(util.format('YENV=%s enb make --no-cache', getEnvironment()), {}, 'enb make');
})
.then(function() {
return console.info('--- application installed successfully ---');
});
<file_sep>var fs = require('fs');
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
};
var vow = require('vow');
var userMap = {
root: 'pulpiks',
'<NAME>': 'klond90'
};
var dirmd = './md';
var files = fs.readdirSync(dirmd);
function readFileInfo(file){
var dfd = vow.defer();
execute("git log --format='%aN' "+file+" | sort -u", function(res){
// console.log(file);
var authors = res.trim().split('\n').map(function(x){var r = x.trim(); return userMap[r]?userMap[r]:r;});
var title = fs.readFileSync(file, {encoding: 'utf8'}).split('\n')[0].substr(2);
var content = 'https://github.com/pulpiks/jsboom-bem/blob/dev/'+file;
var obj = {
title: title,
route: file.split('/').pop().split('.md')[0],
source: {
ru: {
title: title,
createDate: '12-09-2014',
authors: authors,
content: content
}
}
};
// console.log(obj);
dfd.resolve(obj);
});
return dfd.promise();
};
var chain;
var items = [];
files.forEach(function(curFileName){
var file = 'md/'+curFileName;
if (chain){
chain = chain.then((function(file, result){
items.push(result);
return readFileInfo(file);
}).bind(null, file));
} else {
chain = readFileInfo(file);
}
}, []);
chain.then(function(result){
items.push(result);
fs.writeFileSync('model/data.json', JSON.stringify(items), {encoding: 'utf8'});
console.log('result is written');
});<file_sep># Пре-пост выполнения функции
Код доступен по ссылкам: [http://jsfiddle.net/q5Swt/10/][0]
[http://jsfiddle.net/mycwy/28/][1]
obj = {
'method1': function(){
console.log(1);
},
'method2': function(){console.log(2);},
'method3': function(){console.log(3);},
};
obj.beforeCall = function(callback){
var curMeth;
for (var meth in this){
if (this.hasOwnProperty(meth) && typeof this[meth] === 'function' &&
meth !== 'beforeCall' && meth !== 'afterCall'){
curMeth = this[meth];
this[meth] = (function(oldmeth){
return function(){
if (typeof callback === 'function'){
callback();
}
return oldmeth.apply(this, arguments);
}
})(curMeth);
}
}
return this;
}
obj.afterCall = function(callback){
var curMeth;
for (var meth in this){
if (this.hasOwnProperty(meth) && typeof this[meth] === 'function' &&
meth !== 'beforeCall' && meth !== 'afterCall'){
curMeth = this[meth];
this[meth] = (function(meth){
return function(){
var result = meth.apply(this, arguments);
if (typeof callback === 'function'){
callback();
}
return result;
}
})(curMeth);
}
}
return this;
}
obj
.beforeCall(
function(){console.log('pre');}
)
.afterCall(
function(){console.log('post');}
)
;
obj.method1();
Результат:
pre
1
post
Заменим сравнение meth !== 'beforeCall' && meth !== 'afterCall'и контекст передаваемый в замыкание:
obj = {
'method1': function(){
console.log(1);
},
'method2': function(){console.log(2);},
'method3': function(){console.log(3);},
};
Object.prototype.beforeCall = function(cbBefore){
var self = this;
for(var p in this){
if(typeof(this[p])=='function' && this.hasOwnProperty(p)){
this[p]=(function(){
var proxyBefore = self[p];
return function(){
cbBefore();
return proxyBefore.apply(self, arguments);
};
})();
}
}
return this;
};
Object.prototype.afterCall = function(cbAfter){
var self = this;
for(var p in this){
if(typeof(this[p])=='function' && this.hasOwnProperty(p)){
this[p]=(function(){
var proxyAfter = self[p];
return function(){
result = proxyAfter.apply(self, arguments);
cbAfter();
return result;
};
})();
}
}
return this;
};
obj.beforeCall(function(){console.log('pre');}).afterCall(function(){console.log('post');});
obj.method1();
obj.method2();
obj.method1();
Результаты исполнения:
pre
1
post
pre
2
post
pre
1
post
[0]: http://jsfiddle.net/q5Swt/10/
[1]: http://jsfiddle.net/mycwy/28/<file_sep>#!/bin/bash
git pull origin
node getinfo.js
node bin/data.js development
if [ -f "./node.pid" ]
then
kill -9 $(cat ./node.pid)
fi
nohup node bin/app.js > ./node.log 2>&1 & echo $! > ./node.pid<file_sep># Маленькая задача по сортировке(sort)
**Задание из Яндекса**: Нечетные числа должны быть отсортированы друг с другом. А четные должны остаться на своем вместе. Т.е. входящий массив может выглядеть: \[3,1,4,8,9,5,4,6,0\], а выходящий: \[1,3,4,8,5,9,4,6,0\]
Варианты решения:
1) Решение "в лоб". Сохраним в отдельный массив нечетные значения с их индексами в исходном массиве.([http://jsfiddle.net/UevJv/10/][0])
function sortFunction(a, b, index){
if(a[index]<b[index])
return -1;
if(a[index]>b[index])
return 1;
return 0;
}
function sortMy(mas){
var newmas = [], indexes = [];
for(var i=0; i<mas.length; i++){
if (mas[i]%2!=0){
newmas.push([mas[i],i]);
indexes.push(i);
}
}
indexes = indexes.sort();
newmas = newmas.sort(sortFunction,0);
for(var j=0;j<newmas.length;j++){
mas[indexes[j]] = newmas[j][0];
}
return mas;
}
var mas = [3,1,4,8,9,5,4,6,0];
console.log(sortMy(mas));
И ниже с сортировкой в двумерном массиве(можно считать, что отличие только в записи)
function sortMy2(mas){
var newmas = [], newindexes = [];
for(var i=0; i<mas.length; i++){
if (mas[i]%2!=0){
newmas.push([mas[i],i]);
}
}
newmas = newmas.sort(sortFunction,0);
newindexes = newmas.sort(sortFunction,1);
for(var j=0;j<newindexes.length;j++){
mas[newindexes[j][1]] = newmas[j][0];
}
return mas;
}
console.log('Новый массив', sortMy2(mas));
2) Решением с "функцией сортировки" в которой заложено(сортировка только четных чисел) - [http://jsfiddle.net/UevJv/11/][1] . Немного сложнее и проще одновременно:
function sortFunction(a, b){
if (a%2!==0 && b%2!==0){
if(a<b) return -1;
if (a>b) return 1;
}
return 0;
}
var arr = [3,1,4,8,9,5,4,6,0];
arr.sort(sortFunction);
[0]: http://jsfiddle.net/UevJv/10/
[1]: http://jsfiddle.net/UevJv/11/<file_sep># Паттерн publisher - subscriber
function Publisher(){
}
Publisher.prototype.subscribe = function(event, func){
if (typeof(this.events) == 'undefined'){
this.events = {};
}
if (event!=''){
if (typeof(this.events[event]) == 'undefined')
this.events[event] = [];
this.events[event].push(func);
}
}
Publisher.prototype.fire = function(event, data){
for(var i=0; i<this.events[event].length; i++)
this.events[event][i](data);
}
publisher = new Publisher();
publisher.subscribe('info',function(a){console.log('2'+a);});
publisher.subscribe('info',function(a){console.log('1'+a);});
publisher.fire('info', 50);
результат:
250
150
Код доступен по ссылкам: [http://jsfiddle.net/SapTX/6/][0]
[0]: http://jsfiddle.net/SapTX/6/<file_sep># Переопределение нативного метода javascript window.console
Перепишем в соответствии с условием,чтобы на каждый вызов console.log происходил вызов alert этой переменной.
### 1\. Переопределение через вспомогательную функцию
myConsole = {};
myConsole = window.console;
myConsole.print = window.console.log;
console.log = function(){
var args = [];
args = Array.prototype.slice.call(arguments, 0);
for(var i=0; i< args.length; i++){
myConsole.print(args[i]);
alert(args[i]);
}
}
console.log('Слово',1,2,')))');
### 2\. Каррирование
console.log = (
function(){
var log = console.log;
return function(){
for(var i =0;i<arguments.length;i++){
alert(arguments[i]);
log.call(console,arguments[i]);
}
};
}
)();
console.log('Слово',1,2,')))');
Код выложен по ссылкам:
[http://jsfiddle.net/KZDFz/4/][0]
[http://jsfiddle.net/cnjsG/1/][1]
[0]: http://jsfiddle.net/KZDFz/4/
[1]: http://jsfiddle.net/cnjsG/1/<file_sep>// var express = require('express');
var fs = require('fs');
var util = require('util');
try{
var items = JSON.parse(fs.readFileSync('model/data.json', {encoding: 'utf8'}));
}catch(e){
console.log('\n', process.cwd(), '\n')
console.log(e);
console.log(e.printStackTrace())
process.exit(1);
}// var app = express();
// app.get('/', function(req, res){
// res.send('hello world');
// });
module.exports = {
get: function() {
return [
getMain(),
getCustom()
// getDocs()
// getLibraries(),
// getAuthors(),
// getTags()
];
}
};
var getCustom = function() {
var obj = {
title: 'Статьи',
route: {
name: 'articles',
pattern: '/articles(/<id>)(/)'
},
items: items
};
console.log(util.inspect(obj, {showHidden: false, depth: null}));
return obj;
};
var getMain = function() {
return {
title: 'Привет Bem-Engine',
route: {
name: 'index',
pattern: '/'
},
source: {
ru: {
title: 'Bem-site-engine',
createDate: '12-07-2014',
authors: ['pulpiks'],
tags: ['readme'],
content: 'https://github.com/pulpiks/jsboom-bem/blob/dev/md/0.md'
}
}
};
};
var getDocs = function() {
return {
title: 'Документация',
route: {
name: 'documentation',
pattern: '/documentation(/<id>)(/)'
},
items: [
{
title: 'Создание модели',
route: 'model',
source: {
ru: {
title: 'Создание модели',
createDate: '12-07-2014',
authors: ['kuznetsov-andrey'],
tags: ['documentation', 'model'],
content: 'https://github.com/bem/bem-site-engine/blob/dev/docs/model.ru.md'
}
}
},
{
title: 'Конфигурация',
route: 'config',
source: {
ru: {
title: 'Руководство по конфигурированию приложения',
createDate: '12-07-2014',
authors: ['kuznetsov-andrey'],
tags: ['documentation', 'config'],
content: 'https://github.com/bem/bem-site-engine/blob/dev/docs/config.ru.md'
}
}
},
{
title: 'Описание middleware модулей',
route: 'middleware',
source: {
ru: {
title: 'Описание middleware модулей',
createDate: '12-07-2014',
authors: ['kuznetsov-andrey'],
tags: ['documentation', 'middleware'],
content: 'https://github.com/bem/bem-site-engine/blob/dev/docs/middleware.ru.md'
}
}
},
{
title: 'Процесс сборки данных',
route: 'compile',
source: {
ru: {
title: 'Процесс сборки данных',
createDate: '12-07-2014',
authors: ['kuznetsov-andrey'],
tags: ['documentation', 'data-compile'],
content: 'https://github.com/bem/bem-site-engine/blob/dev/docs/data_compiling.ru.md'
}
}
}
]
};
};
var getLibraries = function() {
return {
title: 'Библиотеки',
route: {
name: 'libs',
pattern: '/libs(/<lib>)(/<version>)(/<level>)(/<block>)(/<id>)(/docs|jsdoc|examples)(/)'
},
source: {
ru: {
title: 'Библиотеки',
content: 'https://github.com/bem/bem-site-engine/blob/dev/README.md'
}
},
items: [
getLib('bem-components')
]
};
};
var getAuthors = function() {
return {
title: {
en: "Authors",
ru: "Авторы"
},
route:{
name: "authors",
pattern: "/authors(/<id>)(/)"
},
view: "authors",
items: [
{
title: {
en: "Authors",
ru: "Авторы"
},
dynamic: "authors"
}
]
};
};
var getTags = function() {
return {
title: {
en: "Tags",
ru: "Теги"
},
route:{
name: "tags",
pattern: "/tags(/<id>)(/)"
},
view: "tags",
source: "https://github.com/bem/bem-method/tree/bem-info-data/pages/dummy",
items: [
{
title: "Теги",
hidden: ['en'],
dynamic: "tags:ru"
}
]
};
};
var getLib = function(lib) {
return {
title: lib,
route: {
conditions: {
lib: lib
}
},
type: 'select',
lib: lib
};
};
<file_sep># Deffered & Promises различные алгоритмы и варианты реализации
Deffered - варианты написания асинхронных функций "в строчку"(т.е. избегая записи колбэк в колбэке в колбэке, что присутствует в NodeJS без использования сторонних библиотек). Готовые решения есть и они почти всегда устраивают. Jquery($.Deffered), Coffescript(await ... defer), AsyncJS. Эти библиотеки позволяю грамотно структурировать код и обеспечивать его поддерживаемость. Вместо лестничного написания кода, код оформляется "столбиком". Смысл deffered заключается в том, что в программе имеется множество асинхронных функций, c определенным порядком выполнения. Например, скрипт должен вызвать колбэк самой поздней из одновременно исполняемых асинхронных функций без прибегания к хардкорным решениям вроде setTimeInterval и т.д. Или же реализовать нативный паттерн NodeJS, вызывать один скрипт в колбэке другого и т.д. для каждой внутренней асинхронной функции. Для реализации такой сложной задачи необходимо грамотно продумать архитектуру приложения с запасом на будущее и быстрое внесение доработок и поправок.
Promise - как раз паттерн реализации асинхронных функций в последовательном выполнении.
### 1\. Паттерн then
Через 3 сек вызывается callback finished1,через следующие 3 сек - finished 2\.
var asyncFunction = function(text,cb){
setTimeout(function(){
console.log(text);
cb();
}, 3000)
};
function callback(){
console.log('world is wonderful!');
}
function Promise(){
this.arrFunction = [];
}
Promise.prototype.then = function(func){
var args = Array.prototype.slice.call(arguments,1);
this.arrFunction.push({'func':func, 'args':args});
return this;
}
Promise.prototype.execute = function(){
if (this.arrFunction.length>0){
var curObj = this.arrFunction.shift();
console.log(curObj.args);
curObj.func.apply(this, curObj.args);
}
}
var myPromise = new Promise();
myPromise.then(asyncFunction, 'finished 1').then(asyncFunction, 'finished 2').execute();
#### 2\. Паттерн async execute
Все асинхронные методы в then выполняются одновременно, задачей является отлавливать callbackот каждой асинхронной функции. Причем рассмотрим общий случай,когда количество asyncFunction и callback может быть записаны в массив.
var asyncFunction = function(text,time,cb){
var cb = cb;
setTimeout(function(){
console.log(text);
cb();
}, time)
};
function Promise(){
this.arrFunction = [];
}
Promise.prototype.then = function(func){
//var args = Array.prototype.slice.call(arguments);
if (func instanceof Array){
var tmpArr = [];
for(var i=0; i<func.length; i++){
tmpArr.push({'func':func[i][0], 'args':func[i].slice(1)});
}
this.arrFunction.push(tmpArr);
}
else{
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
}
return this;
};
Promise.prototype.start = function(){
this.execute();
};
Promise.prototype.execute = function(){
console.log('qqq', this.arrFunction);
;
if (this.arrFunction.length>0){
var curStep = this.arrFunction.shift();
var self = this;
if (!(curStep instanceof Array)){
console.log('func');
curStep.args.push(function(){self.execute();});
curStep.func.apply(null, curStep.args);
}
else{
console.log('Array');
this.counterSync = curStep.length;
for(var j=0; j<curStep.length;j++){
curStep[j].args.push(function(){
self.counterSync--;
if (self.counterSync == 0)
self.execute();
});
curStep[j].func.apply(null, curStep[j].args);
}
}
}
}
var myPromise = new Promise();
myPromise.then([[asyncFunction, 'finished 1.1',400],[asyncFunction, 'finished 1.2',2000],[asyncFunction, 'finished 1.3', 1000]]).then(asyncFunction, 'finished 2',2000).start();
Второй вариант реализации
var asyncFunction = function(text,cb){
var cb = cb;
setTimeout(function(){
console.log(text);
cb();
}, 3000)
};
function Promise(){
this.arrFunction = [];
}
Promise.prototype.then = function(func){
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
return this;
};
Promise.prototype.start = function(){
this.execute();
};
Promise.prototype.execute = function(){
if (this.arrFunction.length>0){
var curObj = this.arrFunction.shift();
var self = this;
curObj.args.push(function(){self.execute();});
curObj.func.apply(null, curObj.args);
}
}
var myPromise = new Promise();
myPromise.then(asyncFunction, 'finished 1').then(asyncFunction, 'finished 2').start();
var asyncFunction = function(text,time,cb){
var cb = cb;
setTimeout(function(){
console.log(text);
cb();
}, time)
};
function Promise(){
this.arrFunction = [];
}
Promise.prototype.then = function(func){
//var args = Array.prototype.slice.call(arguments);
if (func instanceof Array){
var tmpArr = [];
for(var i=0; i<func.length; i++){
tmpArr.push({'func':func[i][0], 'args':func[i].slice(1)});
}
this.arrFunction.push(tmpArr);
}
else{
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
}
return this;
};
Promise.prototype.start = function(){
this.execute();
};
Promise.prototype.execute = function(){
console.log('qqq', this.arrFunction);
;
if (this.arrFunction.length>0){
var curStep = this.arrFunction.shift();
var self = this;
if (!(curStep instanceof Array)){
console.log('func');
curStep.args.push(function(){self.execute();});
curStep.func.apply(null, curStep.args);
}
else{
console.log('Array');
this.counterSync = curStep.length;
for(var j=0; j<curStep.length;j++){
curStep[j].args.push(function(){
self.counterSync--;
if (self.counterSync == 0)
self.execute();
});
curStep[j].func.apply(null, curStep[j].args);
}
}
}
}
var myPromise = new Promise();
myPromise.then([[asyncFunction, 'finished 1.1',400],[asyncFunction, 'finished 1.2',2000],[asyncFunction, 'finished 1.3', 1000]]).then(asyncFunction, 'finished 2',2000).start();
Вариант сложного promise
var asyncFunction = function(text,time,cb){
var cb = cb;
setTimeout(function(){
console.log(text);
cb();
}, time)
};
var getData = function(id,cb){
var cb = cb, id = id;
setTimeout(function(){cb(4);},1000);
};
var multiplyData = function(num,cb){
console.log('num=',num);
var cb = cb, num = num;
setTimeout(function(){cb(num*4);},1000);
};
var consoleData = function(text,cb){
var text = text, cb = cb;
setTimeout(function(){console.log(text);cb(text);},1000);
};
function Promise(){
this.arrFunction = [];
}
Promise.prototype.thenParam = function(func){
debugger;
//var args = Array.prototype.slice.call(arguments);
if (func instanceof Array){
var tmpArr = [];
for(var i=0; i<func.length; i++){
tmpArr.push({'func':func[i][0], 'args':func[i].slice(1)});
}
this.arrFunction.push(tmpArr);
}
else{
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
}
return this;
};
Promise.prototype.then = function(func){
//var args = Array.prototype.slice.call(arguments);
if (func instanceof Array){
var tmpArr = [];
for(var i=0; i<func.length; i++){
tmpArr.push({'func':func[i][0], 'args':func[i].slice(1)});
}
this.arrFunction.push(tmpArr);
}
else{
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
}
return this;
};
Promise.prototype.start = function(){
this.execute();
};
Promise.prototype.execute = function(params){
debugger;
console.log('qqq', this.arrFunction);
if (typeof(params)=='undefined'){
params = [];
}
;
if (this.arrFunction.length>0){
var curStep = this.arrFunction.shift();
var self = this;
if (!(curStep instanceof Array)){
console.log('func');
var res = curStep.args.concat(params);
res.push(function(){
debugger;
self.execute(Array.prototype.slice.call(arguments, 0));
});
curStep.func.apply(null, res);
}
else{
console.log('Array');
this.counterSync = curStep.length;
for(var j=0; j<curStep.length;j++){
curStep[j].args.push(function(){
self.counterSync--;
if (self.counterSync == 0)
self.execute();
});
curStep[j].func.apply(null, curStep[j].args);
}
}
}
}
var myPromise = new Promise();
myPromise.thenParam(getData,2).thenParam(multiplyData).thenParam(consoleData).start();
/*
myPromise.then([[asyncFunction, 'finished 1.1',400],[asyncFunction, 'finished 1.2',2000],[asyncFunction, 'finished 1.3', 1000]]).then(asyncFunction, 'finished 2',2000).start();*/
//
var asyncFunction = function(text,cb){
var cb = cb;
setTimeout(function(){
console.log(text);
cb();
}, 3000)
};
function Promise(){
this.arrFunction = [];
}
Promise.prototype.then = function(func){
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
return this;
};
Promise.prototype.start = function(){
this.execute();
};
Promise.prototype.execute = function(){
if (this.arrFunction.length>0){
var curObj = this.arrFunction.shift();
var self = this;
curObj.args.push(function(){self.execute();});
curObj.func.apply(null, curObj.args);
}
}
var myPromise = new Promise();
myPromise.then(asyncFunction, 'finished 1').then(asyncFunction, 'finished 2').start();
var asyncFunction = function(text,time,cb){
var cb = cb;
setTimeout(function(){
console.log(text);
cb();
}, time)
};
function Promise(){
this.arrFunction = [];
}
Promise.prototype.then = function(func){
//var args = Array.prototype.slice.call(arguments);
if (func instanceof Array){
var tmpArr = [];
for(var i=0; i<func.length; i++){
tmpArr.push({'func':func[i][0], 'args':func[i].slice(1)});
}
this.arrFunction.push(tmpArr);
}
else{
var args = Array.prototype.slice.call(arguments, 1);
//args = args.slice(1);
console.log(arguments, args);
this.arrFunction.push({'func':func, 'args':args});
}
return this;
};
Promise.prototype.start = function(){
this.execute();
};
Promise.prototype.execute = function(){
console.log('qqq', this.arrFunction);
;
if (this.arrFunction.length>0){
var curStep = this.arrFunction.shift();
var self = this;
if (!(curStep instanceof Array)){
console.log('func');
curStep.args.push(function(){self.execute();});
curStep.func.apply(null, curStep.args);
}
else{
console.log('Array');
this.counterSync = curStep.length;
for(var j=0; j<curStep.length;j++){
curStep[j].args.push(function(){
self.counterSync--;
if (self.counterSync == 0)
self.execute();
});
curStep[j].func.apply(null, curStep[j].args);
}
}
}
}
var myPromise = new Promise();
myPromise.then([[asyncFunction, 'finished 1.1',400],[asyncFunction, 'finished 1.2',2000],[asyncFunction, 'finished 1.3', 1000]]).then(asyncFunction, 'finished 2',2000).start();
Код выложен по ссылкам
[http://jsfiddle.net/eRpUw/16/][0]
[http://jsfiddle.net/eRpUw/11/][1]
[http://jsfiddle.net/8U9Yc/1/][2]
[http://jsfiddle.net/TKfz2/][3]
[0]: http://jsfiddle.net/eRpUw/16/
[1]: http://jsfiddle.net/eRpUw/11/
[2]: http://jsfiddle.net/8U9Yc/1/
[3]: http://jsfiddle.net/TKfz2/
| e7aeb80373a58621f61f9be963d1775a5491dd74 | [
"JavaScript",
"Markdown",
"Shell"
] | 35 | JavaScript | pulpiks/jsboom-bem | bccd6d55f5acafb3e7aea5f8877684614d2fade2 | 8eae385da02d8e967dff96330bcfb3009f3a685b |
refs/heads/master | <repo_name>moesurevo/nan3_backend<file_sep>/app/Repositories/Replier/ReplierInterface.php
<?php
namespace App\Repositories\Replier;
/**
* Interface DashboardRepository
* @package App\Repositories\Dashboard
*/
interface ReplierInterface
{
// public function findOrThrowException($id);
public function getAllRepliers($order_by = 'id', $sort = 'asc');
public function createReplier($name,$email,$phone_no);
}
?><file_sep>/app/Model/Question.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
protected $fillable = ['quiztitleid', 'questioneng','questionmm','multiple_select'];
public function quiztitle()
{
return $this->belongsTo('App\Model\Quiztitle','quiztitleid');
}
public function answer(){
return $this->hasMany('App\Model\Answer');
}
}
<file_sep>/app/Repositories/User/UserInterface.php
<?php
namespace App\Repositories\User;
/**
* Interface DashboardRepository
* @package App\Repositories\Dashboard
*/
interface UserInterface
{
// public function findOrThrowException($id);
public function getAllUser($order_by = 'id', $sort = 'asc');
}
?><file_sep>/database/migrations/2018_10_10_033857_create_quiztitles_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateQuiztitlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('quiztitles', function (Blueprint $table) {
$table->increments('id');
$table->string('title_no');
$table->string('mm_title_no');
$table->string('titleeng');
$table->string('titlemm');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('quiztitles');
}
}
<file_sep>/app/Http/Controllers/Api/NAN3Controller.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\API\APIBaseController as APIBaseController;
use App\Repositories\Quiztitle\QuiztitleRepository;
use App\Repositories\Question\QuestionRepository;
use App\Repositories\Answer\AnswerRepository;
use App\Repositories\Result\ResultRepository;
use App\Repositories\Replier\ReplierRepository;
class NAN3Controller extends APIBaseController
{
public function __construct(QuiztitleRepository $quiz_title,QuestionRepository $question,AnswerRepository $answer,ResultRepository $result,ReplierRepository $replier){
$this->quiz_title = $quiz_title;
$this->question = $question;
$this->answer = $answer;
$this->result = $result;
$this->replier = $replier;
}
public function get_all_records(){
$quiz_title = $this->quiz_title->getAllQuiztitle();
$question = $this->question->getAllQuestion();
$answer = $this->answer->getAllAnswer();
$result = $this->result->getAllResult();
$data = array(
"quiz_title" => $quiz_title->toArray(),
"question" => $question->toArray(),
"answer" => $answer->toArray(),
"result" => $result->toArray(),
);
return $this->sendResponse($data, 'All Data retrieved successfully.');
}
public function create_replier(Request $request){
$name = $request['name'];
$email = $request['email'];
$phone_no = $request['phone_no'];
$this->replier->createReplier($name,$email,$phone_no);
return $this->sendResponse($data=null, 'All Data created successfully.');
}
}
<file_sep>/app/Repositories/User/UserRepository.php
<?php
namespace App\Repositories\User;
use Illuminate\Database\Eloquent\Model;
use App\User;
class UserRepository implements UserInterface{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(User $model)
{
$this->model = $model;
}
public function getAllUser($order_by = 'created_at', $sort = 'asc')
{
return $this->model->orderBy($order_by, $sort)->get();
}
}
?><file_sep>/app/Repositories/Quiztitle/QuiztitleInterface.php
<?php
namespace App\Repositories\Quiztitle;
/**
* Interface DashboardRepository
* @package App\Repositories\Dashboard
*/
interface QuiztitleInterface
{
// public function findOrThrowException($id);
public function getAllQuiztitle($order_by = 'id', $sort = 'asc');
public function createQuiztitle($input,$type);
public function findOrThrowException($id);
public function destroyQuiztitle($id);
}
?><file_sep>/app/Repositories/Question/QuestionRepository.php
<?php
namespace App\Repositories\Question;
use Illuminate\Database\Eloquent\Model;
use App\Model\Question;
class QuestionRepository implements QuestionInterface{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(Question $model)
{
$this->model = $model;
}
public function findOrThrowException($id)
{
if (! is_null(Question::where('id',$id))) {
return Question::find($id);
}
throw new GeneralException(trans('exceptions.backend.access.Question.not_found'));
}
public function getAllQuestion($order_by = 'created_at', $sort = 'asc')
{
return $this->model->orderBy($order_by, $sort)->get();
}
public function createQuestion($input,$type)
{
$multiple_select = 0;
if(isset($input['multiple_select'])){
$multiple_select = $input['multiple_select'];
}
$question = new Question;
$question->serial_no = $input['serial_no'];
$question->quiztitleid = $input['quiztitleid'];
$question->questioneng = $input['questioneng'];
$question->questionmm = $input['questionmm'];
$question->multiple_select =$multiple_select;
$question->save();
if($question->serial_no != 0){
$question->serial_no = $input['serial_no'];
}else{
$question->serial_no = $question->id;
}
$question->save();
return true;
}
public function update($id, $input)
{
$question = $this->findOrThrowException($id);
$multiple_select = 0;
if ($question->update($input)) {
if(isset($input['multiple_select'])){
$multiple_select = $input['multiple_select'];
}
$question->serial_no = $input['serial_no'];
$question->quiztitleid = $input['quiztitleid'];
$question->questioneng = $input['questioneng'];
$question->questionmm = $input['questionmm'];
$question->multiple_select =$multiple_select;
$question->save();
if($question->serial_no != 0){
$question->serial_no = $input['serial_no'];
}else{
$question->serial_no = $question->id;
}
return true;
}
throw new GeneralException(trans('exceptions.backend.access.question.update_error'));
}
public function destroyQuestion($id){
$question = $this->findOrThrowException($id);
if ($question->delete()) {
return true;
}
}
}
?><file_sep>/app/Repositories/Answer/AnswerRepository.php
<?php
namespace App\Repositories\Answer;
use Illuminate\Database\Eloquent\Model;
use App\Model\Answer;
class AnswerRepository implements AnswerInterface{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(Answer $model)
{
$this->model = $model;
}
public function findOrThrowException($id)
{
if (! is_null(Answer::where('id',$id))) {
return Answer::find($id);
}
throw new GeneralException(trans('exceptions.backend.access.Answer.not_found'));
}
public function getAllAnswer($order_by = 'created_at', $sort = 'asc')
{
return $this->model->orderBy($order_by, $sort)->get();
}
public function createAnswer($input,$type)
{
$answer = new Answer;
$answer->serial_no = $input['serial_no'];
$answer->questionid = $input['questionid'];
$answer->answermm = $input['answermm'];
$answer->answereng = $input['answereng'];
$answer->point = $input['point'];
$answer->save();
if($answer->serial_no != 0){
$answer->serial_no = $input['serial_no'];
}else{
$answer->serial_no = $answer->id;
}
$answer->save();
return true;
}
public function update($id, $input)
{
$answer = $this->findOrThrowException($id);
if ($answer->update($input)) {
$answer->serial_no = $input['serial_no'];
$answer->questionid = $input['questionid'];
$answer->answermm = $input['answermm'];
$answer->answereng = $input['answereng'];
$answer->point = $input['point'];
$answer->save();
if($answer->serial_no != 0){
$answer->serial_no = $input['serial_no'];
}else{
$answer->serial_no = $answer->id;
}
$answer->save();
return true;
}
throw new GeneralException(trans('exceptions.backend.access.answer.update_error'));
}
public function destroyAnswer($id){
$answer = $this->findOrThrowException($id);
if ($answer->delete()) {
return true;
}
}
}
?><file_sep>/app/Repositories/Result/ResultInterface.php
<?php
namespace App\Repositories\Result;
/**
* Interface DashboardRepository
* @package App\Repositories\Dashboard
*/
interface ResultInterface
{
// public function findOrThrowException($id);
public function getAllResult($order_by = 'id', $sort = 'asc');
public function createResult($input,$type);
public function findOrThrowException($id);
public function destroyResult($id);
}
?><file_sep>/app/Model/Result.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Result extends Model
{
protected $fillable = ['quizid', 'resulteng','resultmm','pointminimum','pointmaximum'];
public function quiztitle()
{
return $this->belongsTo('App\Model\Quiztitle','quizid');
}
}
<file_sep>/app/Repositories/Question/QuestionInterface.php
<?php
namespace App\Repositories\Question;
/**
* Interface DashboardRepository
* @package App\Repositories\Dashboard
*/
interface QuestionInterface
{
// public function findOrThrowException($id);
public function getAllQuestion($order_by = 'serial_no', $sort = 'asc');
public function createQuestion($input,$type);
public function findOrThrowException($id);
public function destroyQuestion($id);
}
?><file_sep>/database/migrations/2018_10_10_065505_create_results_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateResultsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('results', function (Blueprint $table) {
$table->increments('id');
$table->integer('quizid')->unsigned();
$table->string('resulteng');
$table->string('resultmm');
$table->integer('pointminimum');
$table->integer('pointmaximum');
$table->string('video_url')->nullable();;
$table->timestamps();
$table->foreign('quizid')->references('id')->on('quiztitles')->onDelete('cascade');
$table->index(['quizid']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('results');
}
}
<file_sep>/app/Model/Quiz.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Quiz extends Model
{
protected $fillable = ['questionid', 'answereng','answermm','answereng'];
public function question()
{
return $this->belongsTo('App\Model\Question');
}
public function result(){
return $this->belongsTo('App\Model\Result');
}
}
<file_sep>/app/Repositories/Replier/ReplierRepository.php
<?php
namespace App\Repositories\Replier;
use Illuminate\Database\Eloquent\Model;
use App\Model\Replier;
class ReplierRepository implements ReplierInterface{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(Replier $model)
{
$this->model = $model;
}
public function getAllRepliers($order_by = 'created_at', $sort = 'asc')
{
return $this->model->orderBy($order_by, $sort)->get();
}
public function createReplier($name,$email,$phone_no){
$replier = new Replier;
$replier->name = $name;
$replier->email = $email;
$replier->phone_no = $phone_no;
$replier->save();
return true;
}
}
?><file_sep>/app/Http/Controllers/AnswerController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\Question\QuestionRepository;
use App\Repositories\Answer\AnswerRepository;
use App\Http\Requests\AnswerRequest;
class AnswerController extends Controller
{
public function __construct(QuestionRepository $question,AnswerRepository $answer){
$this->middleware('auth');
$this->question = $question;
$this->answer = $answer;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$answer_data = $this->answer->getAllAnswer();
return view('pages.answer.index',compact('answer_data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$question_data = $this->question->getAllQuestion();
return view('pages.answer.new',compact('question_data'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(AnswerRequest $request)
{
$answer_data = $this->answer->createAnswer($request->all(),'answer');
return redirect('answer')->with('status', 'Answer is successfully created!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$answer = $this->answer->findOrThrowException($id);
return view('pages.answer.show',compact('answer'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$question_data = $this->question->getAllQuestion();
$answer = $this->answer->findOrThrowException($id);
return view('pages.answer.edit',compact('question_data','answer'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(AnswerRequest $request, $id)
{
$this->answer->update($id, $request->all());
return redirect()->route('answer.index')->with('status','Answer has been updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$answer = $this->answer->destroyAnswer($id);
return redirect()->route('answer.index')->with('status','Answer has been destroyed');
}
}
<file_sep>/app/Repositories/Result/ResultRepository.php
<?php
namespace App\Repositories\Result;
use Illuminate\Database\Eloquent\Model;
use App\Model\Result;
class ResultRepository implements ResultInterface{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(Result $model)
{
$this->model = $model;
}
public function findOrThrowException($id)
{
if (! is_null(Result::where('id',$id))) {
return Result::find($id);
}
throw new GeneralException(trans('exceptions.backend.access.Result.not_found'));
}
public function getAllResult($order_by = 'created_at', $sort = 'asc')
{
return $this->model->orderBy($order_by, $sort)->get();
}
public function createResult($input,$type)
{
$result = new Result;
$result->quizid = $input['quizid'];
$result->resulteng = $input['resulteng'];
$result->resultmm = $input['resultmm'];
$result->pointminimum = $input['pointminimum'];
$result->pointmaximum = $input['pointmaximum'];
$result->video_url = $input['video_url'];
$result->save();
return true;
}
public function update($id, $input)
{
$result = $this->findOrThrowException($id);
if ($result->update($input)) {
$result->quizid = $input['quizid'];
$result->resulteng = $input['resulteng'];
$result->resultmm = $input['resultmm'];
$result->pointminimum = $input['pointminimum'];
$result->pointmaximum = $input['pointmaximum'];
$result->video_url = $input['video_url'];
$result->save();
return true;
}
throw new GeneralException(trans('exceptions.backend.access.result.update_error'));
}
public function destroyResult($id){
$result = $this->findOrThrowException($id);
if ($result->delete()) {
return true;
}
}
}
?><file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\Replier\ReplierRepository;
use App\Repositories\Quiztitle\QuiztitleRepository;
use App\Repositories\Question\QuestionRepository;
use App\Repositories\Answer\AnswerRepository;
class HomeController extends Controller
{
public function __construct(QuiztitleRepository $quiz_title, ReplierRepository $replier,QuestionRepository $question,AnswerRepository $answer){
$this->middleware('auth');
$this->quiz_title = $quiz_title;
$this->replier = $replier;
$this->question= $question;
$this->answer = $answer;
}
/**
* Create a new controller instance.
*
* @return void
*/
// public function __construct()
// {
// $this->middleware('auth');
// }
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$quiz_title_data = $this->quiz_title->getAllQuiztitle();
$replier_data = $this->replier->getAllRepliers();
$question_data = $this->question->getAllQuestion();
$answer_data = $this->answer->getAllAnswer();
return view('pages.dashboard.index',compact('quiz_title_data','replier_data','question_data','answer_data'));
}
}
<file_sep>/app/Model/Replier.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Replier extends Model
{
//
}
<file_sep>/public/js/custom.js
$(document).ready(function(){
$('#example1').DataTable();
})
$('.delete').click(function(){
var currentForm = $(this).closest("form");
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this file!",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
currentForm.submit();
}
});
});
function goBack() {
window.history.back();
}<file_sep>/app/Http/Controllers/QuiztitleController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\Quiztitle\QuiztitleRepository;
use App\Http\Requests\QuiztitleRequest;
class QuiztitleController extends Controller
{
public function __construct(QuiztitleRepository $quiz_title){
$this->middleware('auth');
$this->quiz_title = $quiz_title;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$quiz_title_data = $this->quiz_title->getAllQuiztitle();
return view('pages.quiz_title.index',compact('quiz_title_data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('pages.quiz_title.new');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(QuiztitleRequest $request)
{
$quiz_title = $this->quiz_title->createQuiztitle($request->all(),'quiz_title');
return redirect('quiz_title')->with('status', 'Quiz title is successfully created!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$quiz_title = $this->quiz_title->findOrThrowException($id);
return view('pages.quiz_title.show',compact('quiz_title'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$quiz_title = $this->quiz_title->findOrThrowException($id);
return view('pages.quiz_title.edit',compact('quiz_title'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(QuiztitleRequest $request, $id)
{
$this->quiz_title->update($id, $request->all());
return redirect()->route('quiz_title.index')->with('status','Quiz title has been updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$quiztitle = $this->quiz_title->destroyQuiztitle($id);
return redirect()->route('quiz_title.index')->with('status','Quiz title has been destroyed');
}
}
<file_sep>/app/Http/Requests/QuiztitleRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class QuiztitleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title_no' => 'required',
'mm_title_no' => 'required',
'titleeng' => 'required',
'titlemm' => 'required',
'promomm' => 'required',
'promoeng' => 'required',
];
}
}
<file_sep>/app/Model/Answer.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Answer extends Model
{
protected $fillable = ['questionid', 'answereng','answermm','point'];
public function question()
{
return $this->belongsTo('App\Model\Question','questionid');
}
}
<file_sep>/app/Repositories/Answer/AnswerInterface.php
<?php
namespace App\Repositories\Answer;
/**
* Interface DashboardRepository
* @package App\Repositories\Dashboard
*/
interface AnswerInterface
{
// public function findOrThrowException($id);
public function getAllAnswer($order_by = 'serial_no', $sort = 'asc');
public function createAnswer($input,$type);
public function findOrThrowException($id);
public function destroyAnswer($id);
}
?><file_sep>/app/Repositories/Quiztitle/QuiztitleRepository.php
<?php
namespace App\Repositories\Quiztitle;
use Illuminate\Database\Eloquent\Model;
use App\Model\Quiztitle;
class QuiztitleRepository implements QuiztitleInterface{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(Quiztitle $model)
{
$this->model = $model;
}
public function findOrThrowException($id)
{
if (! is_null(Quiztitle::where('id',$id))) {
return Quiztitle::find($id);
}
throw new GeneralException(trans('exceptions.backend.access.Quiztitle.not_found'));
}
public function getAllQuiztitle($order_by = 'created_at', $sort = 'asc')
{
return $this->model->orderBy($order_by, $sort)->get();
}
public function createQuiztitle($input,$type)
{
$quiz_title = new Quiztitle;
$quiz_title->title_no = $input['title_no'];
$quiz_title->mm_title_no = $input['mm_title_no'];
$quiz_title->titlemm = $input['titlemm'];
$quiz_title->titleeng = $input['titleeng'];
$quiz_title->promomm = $input['promomm'];
$quiz_title->promoeng = $input['promoeng'];
$quiz_title->save();
return true;
}
public function update($id, $input)
{
$quiz_title = $this->findOrThrowException($id);
if ($quiz_title->update($input)) {
$quiz_title->title_no = $input['title_no'];
$quiz_title->mm_title_no = $input['mm_title_no'];
$quiz_title->titleeng = $input['titleeng'];
$quiz_title->titlemm = $input['titlemm'];
$quiz_title->promomm = $input['promomm'];
$quiz_title->promoeng = $input['promoeng'];
$quiz_title->save();
return true;
}
throw new GeneralException(trans('exceptions.backend.access.quiz_title.update_error'));
}
public function destroyQuiztitle($id){
$quiz_title = $this->findOrThrowException($id);
if ($quiz_title->delete()) {
return true;
}
}
}
?><file_sep>/app/Http/Controllers/ResultController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\Quiztitle\QuiztitleRepository;
use App\Repositories\Result\ResultRepository;
use App\Http\Requests\ResultRequest;
class ResultController extends Controller
{
public function __construct(ResultRepository $result,QuiztitleRepository $quiz_title){
$this->middleware('auth');
$this->result = $result;
$this->quiz_title = $quiz_title;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$result_data = $this->result->getAllResult();
return view('pages.result.index',compact('result_data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$quiz_title_data = $this->quiz_title->getAllQuiztitle();
return view('pages.result.new',compact('quiz_title_data'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(ResultRequest $request)
{
$result_data = $this->result->createResult($request->all(),'result');
return redirect('result')->with('status', 'Result is successfully created!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$result = $this->result->findOrThrowException($id);
return view('pages.result.show',compact('result'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$quiz_title_data = $this->quiz_title->getAllQuiztitle();
$result = $this->result->findOrThrowException($id);
return view('pages.result.edit',compact('quiz_title_data','result'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(ResultRequest $request, $id)
{
$this->result->update($id, $request->all());
return redirect()->route('result.index')->with('status','Result has been updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->result->destroyResult($id);
return redirect()->route('result.index')->with('status','Result has been destroyed');
}
}
<file_sep>/app/Http/Requests/ResultRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ResultRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'quizid' => 'required',
'resulteng' => 'required',
'resultmm' => 'required',
'pointminimum' => 'required',
'pointmaximum' => 'required',
// 'video_url' => 'required'
];
}
}
<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
\App\Repositories\Quiztitle\QuiztitleInterface::class,
\App\Repositories\Quiztitle\QuiztitleRepository::class
);
$this->app->bind(
\App\Repositories\Question\QuestionInterface::class,
\App\Repositories\Question\QuestionRepository::class
);
$this->app->bind(
\App\Repositories\Answer\AnswerInterface::class,
\App\Repositories\Answer\AnswerRepository::class
);
$this->app->bind(
\App\Repositories\Replier\ReplierInterface::class,
\App\Repositories\Replier\ReplierRepository::class
);
$this->app->bind(
\App\Repositories\Result\ResultInterface::class,
\App\Repositories\Result\ResultRepository::class
);
$this->app->bind(
\App\Repositories\User\UserInterface::class,
\App\Repositories\User\UserRepository::class
);
}
}
<file_sep>/app/Model/Quiztitle.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Quiztitle extends Model
{
protected $fillable = ['title_no', 'mm_title_no','titleeng','titlemm','promomm','promoeng'];
public function question()
{
return $this->hasMany('App\Model\Question');
}
}
| 02103acf1a6ca34896e8ac00721fa846a35c4d4f | [
"JavaScript",
"PHP"
] | 29 | PHP | moesurevo/nan3_backend | 6b4abf30811b6c68fd5549459b6313dfcb4eaa96 | 33e4a9140971c563a16857da1b217cc11ee15908 |
refs/heads/main | <repo_name>Yoskele/freeBackLink<file_sep>/src/components/createAccount/CreateAccount.js
import React, { useState, useContext } from "react";
import firebase from "../../Firebase";
import { Redirect } from "react-router-dom";
import { AuthContext } from "../contexts/AuthContext";
const CreateAccount = () => {
const { loginUser, logOutUser } = useContext(AuthContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [redirectUser, SetRedirectUser] = useState(false);
const createAccount = async (e) => {
e.preventDefault();
if (email === "" || password === "") {
setErrorMessage("Fields are required");
return; // to break the function.
}
try {
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(() => SetRedirectUser(!redirectUser))
.catch((err) => {
setErrorMessage(err.message);
console.log("this is error message ", err.message);
});
console.log("userAdded");
} catch (error) {
console.log(error);
}
};
if (redirectUser === true) {
console.log("redirectUser...");
return <Redirect to="/user-dashboard" />;
}
return (
<div>
<form
onSubmit={createAccount}
className="card mx-auto p-3"
style={{ width: "300px" }}
>
{errorMessage}
<label className="mt-1 mb-0"> Email: </label>
<input
type="text"
name="username"
placeholder="Email adress..."
className="p-1 rounded"
onChange={(e) => setEmail(e.target.value)}
/>
<label className="mt-3 mb-0">Password:</label>
<input
type="password"
name="password"
placeholder="password..."
className="p-1 rounded"
onChange={(e) => setPassword(e.target.value)}
/>
<hr />
<button type="submit" className="btn btn-primary mt-2">
{" "}
Create{" "}
</button>
</form>
{/* <button onClick={() => logOutUser()}>LogOut </button> */}
</div>
);
};
export default CreateAccount;
<file_sep>/src/components/pages/HomePage.js
import React, { useState, useRef, useContext, useEffect } from "react";
import LoginUser from "../user/LoginUser";
import "./style/homePage.css";
import CreateAccount from "../createAccount/CreateAccount";
import $ from "jquery";
import partnerImage from "../../images/partnerImage.png";
import { ArticleContext } from "../contexts/ArticleContext";
import firebase from "../../Firebase";
import "firebase/storage";
import ImageOne from "../../images/imageOne.jpeg";
import ImageTwo from "../../images/imageTwo.jpeg";
import ImageThree from "../../images/imageThree.png";
import Top5LatestArticles from "../lists/Top5LatestArticles";
const HomePage = () => {
const [displayLogin, setDisplayLogin] = useState(true);
const [width, setWidth] = useState(window.innerWidth);
const { articles } = useContext(ArticleContext);
const [display, setDisplay] = useState("");
let imageLength = "0px";
if (width < 500) {
imageLength = "300px";
} else if (width < 800) {
imageLength = "400px";
} else {
imageLength = "500px";
}
const containerRef = useRef(null);
// If user change the login to create account the container will go up and down.
const toogleWindow = () => {
const container = containerRef;
$(container.current).slideUp().slideDown("slow");
};
return (
<div>
<div className="headBanner p-5">
<div className=" row mx-auto headBanner-wrapper">
<div className="col-sm-6" style={{ color: "white" }}>
<h5> We are offering you 3 backlinks </h5>
<p>We have over 40 in DA, we get over 1000 user per month.</p>
<p>
So why wouldn't you want to link your website with our website.
</p>
<p>
It has never been easier to get free backlinks you only need to
create an account and upload your article with your anchar tag.
</p>
<p>
Select the category the article will go to and just click on save
and woala your article has been saved and is displaying on our
website.
</p>
</div>
<div className="loginInContainer col-sm-6">
<div ref={containerRef}>
{displayLogin ? <LoginUser /> : <CreateAccount />}
</div>
<p
style={{ color: "white", cursor: "pointer" }}
onClick={(e) => {
toogleWindow();
setDisplayLogin(!displayLogin);
if (e.target.textContent === "Create Account") {
e.target.textContent = "Login";
} else {
e.target.textContent = "Create Account";
}
}}
>
Create Account
</p>
</div>
</div>
</div>
<div id="articleContainer"></div>
<div className="row m-5">
<div className="col-sm-6 p-3">
<h4> Latest Article </h4>
<Top5LatestArticles />
</div>
<div className="col-sm-6">
<img
src={partnerImage}
alt=""
className="img-fluid rounded"
style={{
width: `${imageLength}`,
boxShadow: " 10px 10px 20px -10px rgba(0,0,0,.9)",
}}
/>
</div>
</div>
<div className="row justify-content-center mt-5 mb-4 w-100">
<div className="col-sm-3 m-3 p-2" style={{ height: "250px" }}>
<img src={ImageOne} alt="" />
<h5 className="mt-2">Analysis your keywords</h5>
</div>
<div className="col-sm-3 m-3 p-2" style={{ height: "250px" }}>
<img src={ImageTwo} alt="" />
<h5 className="mt-2">Act on your decision</h5>
</div>
<div className="col-sm-3 m-3 p-2" style={{ height: "250px" }}>
<img src={ImageThree} alt="" />
<h5 className="mt-2">Enjoy the ride</h5>
</div>
</div>
</div>
);
};
export default HomePage;
// rules_version = '2';
// service cloud.firestore {
// match /databases/{database}/documents {
// match /{document=**} {
// allow read, write: if
// request.time < timestamp.date(2020, 11, 19);
// }
// }
// }
<file_sep>/src/components/contexts/AuthContext.js
import React, { createContext, useEffect, useState } from "react";
import firebase from "../../Firebase";
import "firebase/auth";
export const AuthContext = createContext();
const AuthContextProvider = (props) => {
const [user, setUser] = useState("");
const [userState, setUserState] = useState(false);
// const [userArticles, setUserArticles] = useState([]);
const getUser = async () => {
//return user from firebase
try {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// If we have a user.
console.log("Got User ", user.email);
setUser(user);
setUserState(true);
} else {
// If we dont have a user.
console.log("No User Redicect", user);
setUserState(false);
}
});
} catch (err) {
console.log("catch error");
}
};
useEffect(() => {
if (!user) {
getUser();
}
}, [user]);
const loginUser = async (email, password) => {
console.log("login...");
try {
let userFromFirebase = await firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
// console.log("user ", user);
setUser({ user });
setUserState(true);
getUser();
return true;
})
.catch((err) => {
// setErrorMessage(err.message);
});
return userFromFirebase;
} catch (err) {
console.log(err);
}
};
const logOutUser = () => {
try {
firebase
.auth()
.signOut()
.then((res) => {
setUserState(!userState);
window.location.href = "/";
})
.catch((err) => {
console.log(err);
});
} catch (err) {
console.log(err);
}
};
// useEffect(() => {
// const getUserArticles = () => {
// console.log("getUserArticles");
// // Loop through all the collections and see if user has any articles.
// let categoryList = ["fashion", "cars", "travel", "No Category"];
// categoryList.forEach((category) => {
// firebase
// .firestore()
// .collection(category)
// .where("post_by", "==", `${user.email}`)
// .onSnapshot((querySnapshot) => {
// // merging in the articles to array.
// querySnapshot.forEach((doc) => {
// setUserArticles((userArticles) => [...userArticles, doc.data()]);
// });
// });
// });
// };
// getUserArticles();
// }, [user]);
return (
<AuthContext.Provider
value={{
user,
userState,
loginUser,
logOutUser,
getUser,
setUserState,
// userArticles,
}}
>
{props.children}
</AuthContext.Provider>
);
};
export default AuthContextProvider;
// useEffect(() => {
// const userArticles = () => {
// firebase
// .firestore()
// .collection("fashion")
// .where("user", "==", `${user.email}`)
// .get()
// .then((snapshot) => {
// const newArticles = snapshot.docs.map((doc) => ({
// id: doc.id,
// ...doc.data(),
// }));
// setUserArticleArray(newArticles);
// })
// .catch(function (error) {
// console.log("Error getting documents: ", error);
// });
// };
// userArticles();
// }, [user]);
<file_sep>/src/components/pages/ArticlePage.js
import React from "react";
import ReactDOM from "react-dom";
const ArticlePage = (props) => {
const closeWindow = () => {
window.location.reload(false);
};
// Create a Div container.
const title = React.createElement("h1", {}, props.title);
const content = React.createElement("p", {
dangerouslySetInnerHTML: {
__html: props.content,
},
});
const closeButton = React.createElement(
"div",
{
className: "closeButtonArticle",
onClick: () => {
closeWindow();
},
},
"X"
);
const container = React.createElement(
"div",
{ className: "articlePaperContainer" },
title,
content,
closeButton
);
ReactDOM.render(container, document.getElementById("articleContainer"));
};
export default ArticlePage;
<file_sep>/src/components/links/EditArticle.js
import React, { useState, useContext, useRef } from "react";
import { ArticleContext } from "../contexts/ArticleContext";
const EditArticle = () => {
const {
article,
saveChangesOnArticle,
setEditContainer,
editContainer,
} = useContext(ArticleContext);
const [message, setMessage] = useState(false);
const titleRef = useRef(null);
const contentRef = useRef(null);
const onSubmitForm = (e) => {
e.preventDefault();
console.log("article id ", article.id);
const updateArticle = {
id: article.id,
title: titleRef.current.value,
content: contentRef.current.value,
category: article.category,
};
saveChangesOnArticle(updateArticle);
setMessage(true);
};
let messageBox;
if (message) {
messageBox = (
<div>
<h6>Updated!</h6>
</div>
);
}
return (
<div className="">
<div className="container mx-auto">
<h4>Don't forget to save.</h4>
<button
className="btn btn-danger float-right"
onClick={() => setEditContainer(!editContainer)}
>
Close window
</button>
{messageBox}
<form onSubmit={onSubmitForm}>
<input
type="text"
placeholder="Title"
ref={titleRef}
defaultValue={article.title}
/>
<textarea
style={{ minHeight: "400px" }}
className="p-1 linkInput form-control mt-3"
ref={contentRef}
defaultValue={article.content}
/>
<button
type="submit"
className="btn btn-success mt-2 float-right"
style={{ width: "200px" }}
>
Save
</button>
</form>
</div>
</div>
);
};
export default EditArticle;
<file_sep>/src/components/user/LoginUser.js
import React, { useState, useContext } from "react";
import { AuthContext } from "../contexts/AuthContext";
import { Redirect } from "react-router-dom";
const LoginUser = () => {
const { loginUser } = useContext(AuthContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [redirect, setRedirect] = useState(false);
const onSubmit = async (e) => {
e.preventDefault();
console.log("submit");
try {
const userExist = await loginUser(email, password);
if (userExist) {
setRedirect(!redirect);
} else {
console.log("no user here...");
}
} catch (err) {
console.log("err ", err);
}
};
if (redirect) {
return <Redirect to="/user-dashboard" />;
}
return (
<div>
<form
onSubmit={onSubmit}
className="card mx-auto p-3"
style={{ maxWidth: "300px" }}
>
{/* {errorMessage} */}
<label className="mt-1 mb-0"> Email: </label>
<input
type="text"
name="username"
placeholder="Email adress..."
className="p-1 rounded"
onChange={(e) => setEmail(e.target.value)}
/>
<label className="mt-3 mb-0">Password:</label>
<input
type="<PASSWORD>"
name="password"
placeholder="password..."
className="p-1 rounded"
onChange={(e) => setPassword(e.target.value)}
/>
<hr />
<button type="submit" className="btn btn-success mt-2">
{" "}
Login{" "}
</button>
</form>
</div>
);
};
export default LoginUser;
<file_sep>/src/Routes.js
import React from "react";
import { Switch, Route } from "react-router-dom";
import CreateAccount from "./components/createAccount/CreateAccount";
import HomePage from "./components/pages/HomePage";
import UserDashboard from "./components/user/UserDashboard";
import EditArticle from "./components/links/EditArticle";
const Routes = () => {
return (
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/user-dashboard">
{" "}
<UserDashboard />{" "}
</Route>
<Route exact path="/user-dashboard/edit-:id" component={EditArticle} />
<Route exact path="/create-account" component={CreateAccount} />
</Switch>
);
};
export default Routes;
<file_sep>/src/components/lists/Top5LatestArticles.js
import React, { useState, useEffect, useRef } from "react";
import firebase from "../../Firebase";
import ArticlePage from "../pages/ArticlePage";
const Top5LatestArticles = () => {
const [topList, setTopList] = useState([]);
const top5List = topList.slice(1, 3);
const getUserArticles = () => {
// Loop through all the collections and see if user has any articles.
let categoryList = ["fashion", "cars", "travel", "No Category"];
categoryList.forEach((category) => {
firebase
.firestore()
.collection(category)
.onSnapshot((querySnapshot) => {
const newList = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
// We take the newList and insert it into userArticles so we can display.
setTopList((topList) => topList.concat(newList));
});
});
};
useEffect(() => {
getUserArticles();
}, []);
const list = top5List.length ? (
<div>
<ul className="">
{top5List.map((article, index) => {
return (
<li
key={index}
className="m-3 mx-auto listArticle"
style={{
minWidth: "200px",
backgroundColor: "white",
fontSize: "1.5rem",
borderRadius: "10px",
cursor: "pointer",
}}
onClick={() => ArticlePage(article)}
>
{article.title}
</li>
);
})}
</ul>{" "}
</div>
) : (
<div>...</div>
);
return list;
};
export default Top5LatestArticles;
<file_sep>/src/Firebase.js
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "freebacklink-c56ae.firebaseapp.com",
databaseURL: "https://freebacklink-c56ae.firebaseio.com",
projectId: "freebacklink-c56ae",
storageBucket: "freebacklink-c56ae.appspot.com",
messagingSenderId: "433826682890",
appId: "1:433826682890:web:594ce5f113cabe8c77a7f3",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase;
<file_sep>/src/components/contexts/FashionContext.js
import React, { createContext, useEffect, useState } from "react";
import firebase from "../../Firebase";
import "firebase/storage";
export const FashionContext = createContext();
const FashionContextProvider = (props) => {
const [fashionArticles, setFashionArticles] = useState([]);
const dataBase = firebase.firestore().collection("fashion");
function getArticles() {
dataBase.onSnapshot((snap) => {
const list = [];
snap.forEach((doc) => {
list.push(doc.data());
});
setFashionArticles(list);
});
}
useEffect(() => {
getArticles();
}, []);
return (
<FashionContext.Provider value={{ fashionArticles }}>
{props.children}
</FashionContext.Provider>
);
};
export default FashionContextProvider;
| ef0539ed12e1e30181db98d1cc9ad6e459cb8bec | [
"JavaScript"
] | 10 | JavaScript | Yoskele/freeBackLink | 6020ceca5e7d05e2bb30326c2a40e7f13fcda8f3 | 6ef55eaacf4bb5cbe91011fa7cd3bc024377ca57 |
refs/heads/master | <repo_name>shreyakapadia10/assignment2-module2-solution<file_sep>/app.js
(function () {
'use strict';
angular.module("ShoppingListCheckOff", [])
.controller("ToBuyController", ToBuyController)
.controller("AlreadyBoughtController", AlreadyBoughtController)
.service("ShoppingListCheckOffService", ShoppingListCheckOffService);
ToBuyController.$inject = ["ShoppingListCheckOffService"];
AlreadyBoughtController.$inject = ["ShoppingListCheckOffService"];
function ToBuyController(ShoppingListCheckOffService) {
var tbc = this;
tbc.itemName = "";
tbc.itemQuantity = "";
tbc.to_buy = ShoppingListCheckOffService.getBuyList();
tbc.buyItem = function (itemIndex) {
ShoppingListCheckOffService.buyItem(itemIndex);
};
};
function AlreadyBoughtController(ShoppingListCheckOffService) {
var abc = this;
abc.already_bought = ShoppingListCheckOffService.getBoughtList();
};
function ShoppingListCheckOffService() {
var service = this;
var to_buy = [
{
name: "Cookies",
quantity: 10
},
{
name: "Cakes",
quantity: 5
},
{
name: "Biscuits",
quantity: 3
},
{
name: "Pastry",
quantity: 10
},
{
name: "Chips",
quantity: 6
}];
var already_bought = [];
service.buyItem = function (itemIndex) {
var removedItem = to_buy.splice(itemIndex, 1);
already_bought.push(removedItem[0]);
};
service.getBuyList = function () {
return to_buy;
};
service.getBoughtList = function () {
return already_bought;
};
};
})(); | 5d8b38c78585bbe97fa5337d8d19fbafe97765b0 | [
"JavaScript"
] | 1 | JavaScript | shreyakapadia10/assignment2-module2-solution | d6b5a142887f61476873e619ba764d5d7bd3213b | 29a9c63c557fa62878d6f35027f37c3adde36b76 |
refs/heads/master | <repo_name>harmingcola/photosorter<file_sep>/src/main/java/org/seegee/photosorter/utils/ImageUtil.java
package org.seegee.photosorter.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class ImageUtil {
public static boolean isImage(File file) {
String fileName = file.getName().toLowerCase();
return fileName.endsWith("jpg")
|| fileName.endsWith("jpeg")
|| fileName.endsWith("png");
}
public static Image scaleImage(Image image, int imageType, int newWidth, int newHeight) {
double thumbRatio = (double) newWidth / (double) newHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double aspectRatio = (double) imageWidth / (double) imageHeight;
if (thumbRatio < aspectRatio) {
newHeight = (int) (newWidth / aspectRatio);
} else {
newWidth = (int) (newHeight * aspectRatio);
}
BufferedImage newImage = new BufferedImage(newWidth, newHeight, imageType);
Graphics2D graphics2D = newImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, newWidth, newHeight, null);
return newImage;
}
}
<file_sep>/src/main/java/org/seegee/photosorter/ui/DirectoryViewerPanel.java
package org.seegee.photosorter.ui;
import static org.seegee.photosorter.context.ApplicationContext.service;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.*;
public class DirectoryViewerPanel extends JScrollPane implements ActionListener {
private List<DirectoryButton> buttons = new ArrayList();
public void loadDirectories(File destination) {
List<File> directories = Arrays.stream(destination.listFiles())
.filter(File::isDirectory)
.sorted()
.collect(Collectors.toList());
displayDirectories(directories);
}
private void displayDirectories(List<File> directories) {
JPanel buttonsPanel = new JPanel(new GridLayout(directories.size(), 1));
for(File directory : directories) {
DirectoryButton button = new DirectoryButton(directory);
button.addActionListener(this);
buttonsPanel.add(button);
buttons.add(button);
}
this.setViewportView(buttonsPanel);
this.repaint();
this.revalidate();
}
@Override
public void actionPerformed(ActionEvent e) {
DirectoryButton destinationDirectoryButton = (DirectoryButton) e.getSource();
File destinationDirectory = destinationDirectoryButton.getDirectory();
service().moveCurrentPhotoTo(destinationDirectory);
service().reload();
}
public void enableMoving() {
for(DirectoryButton button : buttons) {
button.setEnabled(true);
}
}
public void disableMoving() {
for(DirectoryButton button : buttons) {
button.setEnabled(false);
}
}
}
<file_sep>/src/main/java/org/seegee/photosorter/ui/PhotoViewerPanel.java
package org.seegee.photosorter.ui;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import org.seegee.photosorter.utils.ImageUtil;
public class PhotoViewerPanel extends JPanel {
private File currentPhoto;
public PhotoViewerPanel() {
this.setLayout(new BorderLayout());
}
public void setPhoto(File photoFile) {
this.currentPhoto = photoFile;
try {
Image image = ImageIO.read(photoFile);
image = ImageUtil.scaleImage(image, BufferedImage.TYPE_INT_RGB, this.getWidth(), this.getHeight());
ImageIcon imageIcon = new ImageIcon(image);
JLabel label = new JLabel("", imageIcon, JLabel.CENTER);
this.removeAll();
this.add(label, BorderLayout.CENTER);
this.revalidate();
this.repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
public void clearPhoto() {
this.removeAll();
this.revalidate();
this.repaint();
}
public File getCurrentPhoto() {
return currentPhoto;
}
}
<file_sep>/src/main/java/org/seegee/photosorter/ui/DirectoryButton.java
package org.seegee.photosorter.ui;
import java.io.File;
import javax.swing.*;
public class DirectoryButton extends JButton {
private final File directory;
public DirectoryButton(File directory) {
super(directory.getName());
this.directory = directory;
this.setHorizontalAlignment(SwingConstants.LEFT);
}
public File getDirectory() {
return directory;
}
}
<file_sep>/src/main/java/org/seegee/photosorter/process/HashIndexProcess.java
package org.seegee.photosorter.process;
import static org.seegee.photosorter.context.ApplicationContext.hashIndex;
import java.io.File;
import org.seegee.photosorter.context.ApplicationContext;
import org.seegee.photosorter.utils.FileUtil;
import org.seegee.photosorter.utils.ImageUtil;
public class HashIndexProcess implements Runnable {
private File startDirectory;
public HashIndexProcess(File startDirectory) {
this.startDirectory = startDirectory;
}
@Override
public void run() {
analyzeDirectory(startDirectory);
ApplicationContext.photoInfoPanel().refresh();
}
private void analyzeDirectory(File startDirectory) {
for(File file : startDirectory.listFiles()) {
if(file.isDirectory()) {
analyzeDirectory(file);
} else {
analyzeFile(file);
}
}
}
private void analyzeFile(File file) {
if(ImageUtil.isImage(file)) {
String hash = FileUtil.generateHash(file);
hashIndex().put(hash, file);
}
}
}
| 5764b9b3eeedf86aaa3d1701c72dd95a0ee01593 | [
"Java"
] | 5 | Java | harmingcola/photosorter | 958413b5ee2c17517255cc629138bdb2d75a2cea | 26a7cc39e01237af949e0e6e5a3b4a72f1a0f710 |
refs/heads/master | <file_sep><?php
Route::get('/', 'WebCrawlerController@get');<file_sep><h2 align="center">Web Crawling Using PHP</h2>
## About
This is a very simple Web crawler with the following functionalities:
- Can get total number of words in a page
- Can get average title length
- Find the number of unique internal and external links
- Find the number of unique images inside a URL
There is no user authentication now to perform those operations.
## Setup
To set up the repo please follow the following steps:
1. Download the repo into your local directory from https://github.com/CudaRabbani/WebCrawler.git
2. From downloaded project directory open a terminal and enter the following commands:
- **cd WebCrawler**
- **composer install**
3. Run the app by typing into terminal: **php artisan serve**
Please note the URL in the terminal for Laravel server (i.e: http://127.0.0.1:8000)
We should be ready to see the result now.<file_sep><?php
namespace App;
use DOMDocument;
use App\WebCrawlerResult;
class WebCrawler
{
private $url;
private $depth;
private $host;
private $useHttpAuth = false;
private $seen = array();
private $_filter = array();
private $uniqueImages;
private $unique_internal_links;
private $unique_external_links;
private $counter;
const BASE_URL = 'agencyanalytics.com';
private $result;
public function __construct($url, $depth = 5)
{
$this->url = $url;
$this->depth = $depth;
$parse = parse_url($url);
$this->host = $parse['host'];
$this->unique_internal_links = [];
$this->unique_external_links = [];
$this->uniqueImages = [];
$this->result = [];
$this->counter = 0;
}
private function isExternalLink (string $link): bool {
return (strpos($link, self::BASE_URL) === false && strpos($link, 'http') !== false) ;
}
private function processImages($content) {
$dom = new DOMDocument('1.0');
@$dom->loadHTML($content);
$imagesOnPage = $dom->getElementsByTagName('img');
$srcCounter = 0;
$images = [];
$uniqueImages = [];
foreach ($imagesOnPage as $image) {
$images[] = $image->getAttribute('src');
$srcCounter++;
}
$imageSummary = array_count_values($images);
foreach ($imageSummary as $image=>$count) {
if ($count === 1) {
$uniqueImages[] = $image;
}
}
return $uniqueImages;
}
private function countWordsInPage($url) {
$pageText = @file_get_contents($url);
$search = array('@<script[^>]*?>.*?</script>@si',
// '@<head>.*?</head>@siU', // Lose the head section
'@<style[^>]*?>.*?</style>@siU',
'@<![\s\S]*?--[ \t\n\r]*>@'
);
$contents = preg_replace($search, '', $pageText);
return str_word_count(strip_tags($contents));
}
private function getTitle($content) {
$dom = new DOMDocument('1.0');
@$dom->loadHTML($content);
$anchors = $dom->getElementsByTagName('title');
return $anchors->item(0)->nodeValue;
}
private function processLink($content, $url, $depth, $httpcode, $time)
{
$dom = new DOMDocument('1.0');
@$dom->loadHTML($content);
$anchors = $dom->getElementsByTagName('a');
$links = [];
$uniqueImages = $this->processImages($content);
$wordsInPage = $this->countWordsInPage($url);
$title = $this->getTitle($content);
foreach ($anchors as $a) {
$links[] = $a->getAttribute('href');
}
$linkSummary = array_count_values($links);
$externalLinks = [];
$internalLinks = [];
foreach ($linkSummary as $link => $count) {
if ($count === 1) {
if ($this->isExternalLink($link)) {
$externalLinks[] = $link;
}
else {
$internalLinks[] = $link;
}
}
}
$this->result[] = new WebCrawlerResult(
$url,
$uniqueImages,
$externalLinks,
$internalLinks,
$time,
$httpcode,
$title,
$wordsInPage
);
foreach ($anchors as $element) {
$href = $element->getAttribute('href');
if (0 !== strpos($href, 'http')) {
$path = '/' . ltrim($href, '/');
if (extension_loaded('http')) {
$href = http_build_url($url, array('path' => $path));
} else {
$parts = parse_url($url);
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass'])) {
$href .= $parts['user'] . ':' . $parts['pass'] . '@';
}
$href .= $parts['host'];
if (isset($parts['port'])) {
$href .= ':' . $parts['port'];
}
$href .= $path;
}
}
$this->crawl_page($href, $depth - 1);
}
}
private function getContent($url)
{
$handle = curl_init($url);
if ($this->useHttpAuth) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($handle, CURLOPT_USERPWD, $this->_user . ":" . $this->_pass);
}
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$time = curl_getinfo($handle, CURLINFO_TOTAL_TIME);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
return array($response, $httpCode, $time);
}
private function isValid($url, $depth)
{
if (strpos($url, $this->host) === false
|| $depth === 0
|| isset($this->seen[$url])
) {
return false;
}
foreach ($this->_filter as $excludePath) {
if (strpos($url, $excludePath) !== false) {
return false;
}
}
return true;
}
public function crawl_page($url, $depth)
{
if (!$this->isValid($url, $depth)) {
return;
}
$this->seen[$url] = true;
list($content, $httpcode, $time) = $this->getContent($url);
$this->processLink($content, $url, $depth, $httpcode, $time);
}
private function countUniqueItems($item) {
$itemList = [];
$itemRef = null;
foreach ($this->result as $result) {
switch ($item) {
case 'internalLink':
$itemRef = $result->getInternalLinks();
break;
case 'externalLink':
$itemRef = $result->getExternalLinks();
break;
case 'image':
$itemRef = $result->getImages();
break;
}
if (!is_null($itemRef)) {
array_push($itemList, array_values($itemRef));
}
}
$flat = collect($itemList)->flatten()->all();
$countItems = array_count_values($flat);
$countItems = array_filter($countItems, function($value) {
return $value === 1;
});
return count($countItems);
}
private function calculateItemAverage($item) {
$total = 0;
foreach ($this->result as $result) {
switch ($item) {
case 'pageLoad':
$total += $result->getLoadTime();
break;
case 'wordCount':
$total += $result->getWordCounts();
break;
case 'titleLength':
$total += $result->getTitleLength();
break;
}
}
return $total/count($this->result);
}
public function getScrawledPageWithStatusCode() {
$allResult = [];
$counter = 0;
foreach ($this->result as $result) {
$data['id'] = ++$counter;
$data['url'] = $result->getURL();
$data['status_code'] = $result->getStatusCode();
$data['avg_load_time'] = $result->getLoadTime();
$allResult[] = $data;
}
return $allResult;
}
public function run()
{
$this->crawl_page($this->url, $this->depth);
$data = [];
$data['total_pages'] = count($this->result);
$data['unique_internal_links'] = $this->countUniqueItems('internalLink');
$data['unique_external_links'] = $this->countUniqueItems('externalLink');
$data['unique_images'] = $this->countUniqueItems('image');
$data['avg_page_load'] = $this->calculateItemAverage('pageLoad');
$data['avg_word_count'] = $this->calculateItemAverage('wordCount');
$data['avg_title_length'] = $this->calculateItemAverage('titleLength');
return $data;
}
}<file_sep><?php
namespace App\Http\Controllers;
use App\WebCrawler;
class WebCrawlerController extends Controller
{
public function get() {
$url = 'https://agencyanalytics.com/';
$webCrawler = new WebCrawler($url, 5);
$crawlingData = $webCrawler->run();
return view('crawling',
[
'summaryData'=>$crawlingData,
'crawlingData'=>$webCrawler->getScrawledPageWithStatusCode()
]
);
}
}
<file_sep><?php
namespace App;
class WebCrawlerResult
{
private $url;
private $uniqueExternalLinks;
private $uniqueInternalLinks;
private $uniqueImages;
private $wordCount;
private $statusCode;
private $title;
private $loadTime;
public function __construct($pageUrl, $images, $externalLinks, $internalLinks, $loadTime, $statusCode, $title, $words) {
$this->url = $pageUrl;
$this->uniqueExternalLinks = $externalLinks;
$this->uniqueInternalLinks = $internalLinks;
$this->uniqueImages = $images;
$this->wordCount = $words;
$this->statusCode = $statusCode;
$this->loadTime = $loadTime;
$this->title = $title;
}
public function getWordCounts() {
return $this->wordCount;
}
public function getStatusCode() {
return $this->statusCode;
}
public function getLoadTime() {
return $this->loadTime;
}
public function getExternalLinks() {
return $this->uniqueExternalLinks;
}
public function getInternalLinks() {
return $this->uniqueInternalLinks;
}
public function getImages() {
return $this->uniqueImages;
}
public function getTitleLength() {
return strlen($this->title);
}
public function getURL() {
return $this->url;
}
} | 78277b8b56fd0c4cbcacb34092f1bd1daea2b477 | [
"Markdown",
"PHP"
] | 5 | PHP | CudaRabbani/WebCrawler | 93ff25a65cefc0df2ad2704b0b91f3e5f4bde57d | e7418b1f9a6a6b9baa0d049a05eae4b58867191f |
refs/heads/main | <file_sep># Copyright 2020 getcarrier.io
#
# 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.
import pika
from json import dumps
from uuid import uuid4
from time import sleep
from arbiter.config import Config
from arbiter.event.process import ProcessEventHandler
class ProcessWatcher:
def __init__(self, process_id, host, port, user, password, vhost="carrier", all_queue="arbiterAll",
wait_time=2.0):
self.config = Config(host, port, user, password, vhost, None, all_queue)
self.connection = self._get_connection()
self.process_id = process_id
self.state = {}
self.subscriptions = dict()
self.arbiter_id = str(uuid4())
self.handler = ProcessEventHandler(self.config, self.subscriptions, self.state, self.process_id)
self.handler.start()
self.handler.wait_running()
self.wait_time = wait_time
def _get_connection(self): # This code duplication needed to avoid thread safeness problem of pika
_connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=self.config.host,
port=self.config.port,
virtual_host=self.config.vhost,
credentials=pika.PlainCredentials(
self.config.user,
self.config.password
)
)
)
channel = _connection.channel()
return channel
def send_message(self, msg, queue="", exchange=""):
self._get_connection().basic_publish(
exchange=exchange, routing_key=queue,
body=dumps(msg).encode("utf-8"),
properties=pika.BasicProperties(
delivery_mode=2
)
)
def collect_state(self, tasks):
if self.process_id not in self.state:
self.state[self.process_id] = {
"running": [],
"done": []
}
message = {
"type": "task_state",
"tasks": tasks,
"arbiter": self.process_id
}
self.send_message(message, exchange=self.config.all)
sleep(self.wait_time)
return self.state.get(self.process_id, {})
def clear_state(self, tasks):
message = {
"type": "clear_state",
"tasks": tasks,
"arbiter": self.process_id
}
self.send_message(message, exchange=self.config.all)
sleep(self.wait_time)
def close(self):
self.handler.stop()
self._get_connection().queue_delete(queue=self.process_id)
self.handler.join()
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import logging
logging.basicConfig(
level=logging.INFO,
datefmt="%Y.%m.%d %H:%M:%S %Z",
format="%(asctime)s - %(levelname)8s - %(name)s - %(message)s",
)
class Config(object):
def __init__(self, host, port, user, password, vhost, queue, all_queue):
self.host = host
self.port = port
self.user = user
self.password = <PASSWORD>
self.vhost = vhost
self.queue = queue
self.all = all_queue
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import json
import logging
import multiprocessing
from uuid import uuid4
from traceback import format_exc
from ..event.base import BaseEventHandler
from ..tasks import ProcessWatcher
mp = multiprocessing.get_context("spawn")
class TaskEventHandler(BaseEventHandler):
def __init__(self, settings, subscriptions, state, task_registry, wait_time=2.0, pool_size=1):
super().__init__(settings, subscriptions, state, wait_time=wait_time)
self.pool_size = pool_size
self.task_registry = task_registry
self.pool = mp.Pool(pool_size)
def _connect_to_specific_queue(self, channel):
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=self.settings.queue,
on_message_callback=self.queue_event_callback
)
logging.info("[%s] Waiting for task events", self.ident)
return channel
def queue_event_callback(self, channel, method, properties, body): # pylint: disable=R0912,R0915
_ = properties, self, channel, method
event = json.loads(body)
try:
self.state["active_workers"] += 1
# new tasks will be w/o key testing purpose only
# do not use in prod implementation
if not event.get("task_key"):
event["task_key"] = uuid4()
event_type = event.get("type", "task")
logging.info("[%s] [TaskEvent] Type: %s", self.ident, event_type)
if event_type == "task":
if event.get("arbiter"):
self.respond(channel, {"type": "task_state_change", "task_key": event.get("task_key"),
"task_state": "running"}, event.get("arbiter"))
logging.info("[%s] [TaskEvent] Starting worker process", self.ident)
if event.get("task_name") not in self.task_registry:
raise ModuleNotFoundError("Task is not a part of this worker")
worker = self.pool.apply_async(self.task_registry[event.get("task_name")],
event.get("args", []),
event.get("kwargs", {}))
self.state[event.get("task_key")] = {
"process": worker,
"status": "running"
}
while not worker.ready():
if self.state[event.get('task_key')]["status"] == "canceled":
self.pool.close()
self.pool.terminate()
self.pool.join()
self.pool = mp.Pool(self.pool_size)
break
channel._connection.sleep(1.0) # pylint: disable=W0212
result = worker.get() if self.state[event.get('task_key')]["status"] != "canceled" else "canceled"
logging.info("[%s] [TaskEvent] Worker process stopped", self.ident)
if event.get("arbiter"):
self.respond(channel, {"type": "task_state_change", "task_key": event.get("task_key"),
"result": result, "task_state": "done"}, event.get("arbiter"))
self.state[event.get('task_key')]["status"] = "done"
if not event.get("callback", False):
self.state.pop(event.get("task_key"))
elif event_type == "callback":
callback_key = event.get("task_key")
minibitter = ProcessWatcher(callback_key, self.settings.host, self.settings.port, self.settings.user,
self.settings.password, vhost=self.settings.vhost, wait_time=self.wait_time)
state = minibitter.collect_state(event.get("tasks_array"))
if all(task in state.get("done", []) for task in event.get("tasks_array") if task != callback_key):
if not event.get("callback", False):
minibitter.clear_state(event.get("tasks_array"))
event.pop("tasks_array")
event["type"] = "task"
minibitter.close()
self.respond(channel, event, self.settings.queue)
else:
logging.info("********************************************")
logging.info("Callback: waiting till all tasks are done")
logging.info("********************************************")
minibitter.close()
self.respond(channel, event, self.settings.queue, 60)
elif event_type == "finalize":
finalizer_key = event.get("task_key")
minibitter = ProcessWatcher(finalizer_key, self.settings.host, self.settings.port, self.settings.user,
self.settings.password, vhost=self.settings.vhost, wait_time=self.wait_time)
state = minibitter.collect_state(event.get("tasks_array"))
if all(task in state.get("done", []) for task in event.get("tasks_array")):
event["type"] = "task"
minibitter.clear_state(event.get("tasks_array"))
minibitter.close()
event.pop("tasks_array")
self.respond(channel, event, self.settings.queue)
else:
minibitter.close()
logging.info("********************************************")
logging.info("Finalizer: waiting till all tasks are done")
logging.info("********************************************")
self.respond(channel, event, self.settings.queue, 90)
except:
logging.exception("[%s] [TaskEvent] Got exception", self.ident)
if event.get("arbiter"):
self.respond(channel, {"type": "task_state_change", "task_key": event.get("task_key"),
"result": format_exc(), "task_state": "exception"}, event.get("arbiter"))
self.state["active_workers"] -= 1
channel.basic_ack(delivery_tag=method.delivery_tag)
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import logging
import pika
from uuid import uuid4
from json import dumps
from arbiter.config import Config
from arbiter.event.arbiter import ArbiterEventHandler
connection = None
channel = None
class Base:
def __init__(self, host, port, user, password, vhost="carrier", queue=None, all_queue="arbiterAll", wait_time=2.0):
self.config = Config(host, port, user, password, vhost, queue, all_queue)
self.state = dict()
self.wait_time = wait_time
def _get_connection(self):
global connection
global channel
if not connection:
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=self.config.host,
port=self.config.port,
virtual_host=self.config.vhost,
credentials=pika.PlainCredentials(
self.config.user,
self.config.password
)
)
)
if not channel:
channel = connection.channel()
if self.config.queue:
channel.queue_declare(
queue=self.config.queue, durable=True
)
channel.exchange_declare(
exchange=self.config.all,
exchange_type="fanout", durable=True
)
try:
connection.process_data_events()
except:
connection = None
channel = None
return self._get_connection()
return channel
@staticmethod
def disconnect():
global connection
global channel
if connection:
connection.close()
connection = None
channel = None
def send_message(self, msg, reply_to="", queue="", exchange=""):
self._get_connection().basic_publish(
exchange=exchange, routing_key=queue,
body=dumps(msg).encode("utf-8"),
properties=pika.BasicProperties(
reply_to=reply_to,
delivery_mode=2
)
)
def wait_for_tasks(self, tasks):
tasks_done = []
while not all(task in tasks_done for task in tasks):
for task in tasks:
if task not in tasks_done and self.state[task]["state"] == 'done':
tasks_done.append(task)
yield self.state[task]
def add_task(self, task, sync=False):
generated_queue = False
if not task.callback_queue and sync:
generated_queue = True
queue_id = str(uuid4())
self._get_connection().queue_declare(
queue=queue_id, durable=True
)
task.callback_queue = queue_id
tasks = []
for _ in range(task.tasks_count):
task_key = str(uuid4()) if task.task_key == "" else task.task_key
tasks.append(task_key)
if task.callback_queue and task_key not in self.state:
self.state[task_key] = {
"task_type": task.task_type,
"state": "initiated"
}
logging.debug(f"Task body {task.to_json()}")
message = task.to_json()
message["task_key"] = task_key
self.send_message(message, reply_to=task.callback_queue, queue=task.queue)
yield task_key
if generated_queue:
handler = ArbiterEventHandler(self.config, {}, self.state, task.callback_queue)
handler.start()
if sync:
for message in self.wait_for_tasks(tasks):
yield message
if generated_queue:
handler.stop()
self._get_connection().queue_delete(queue=task.callback_queue)
handler.join()
self.disconnect()
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import json
import logging
from arbiter.event.base import BaseEventHandler
class ArbiterEventHandler(BaseEventHandler):
def __init__(self, settings, subscriptions, state, arbiter_id):
super().__init__(settings, subscriptions, state)
self.arbiter_id = arbiter_id
def _connect_to_specific_queue(self, channel):
channel.queue_declare(
queue=self.arbiter_id, durable=True
)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=self.arbiter_id,
on_message_callback=self.queue_event_callback
)
logging.info("[%s] Waiting for task events", self.ident)
return channel
def queue_event_callback(self, channel, method, properties, body): # pylint: disable=R0912,R0915
_ = properties, self, channel, method
event = json.loads(body)
try:
event_type = event.get("type")
logging.info("[%s] [ArbiterEvent] Type: %s", self.ident, event_type)
if event.get("task_key") and event.get("task_key") not in self.state:
self.state[event.get("task_key")] = {}
if event_type in ["task_state_change"]:
self.state[event.get("task_key")]["state"] = event.get("task_state")
if event.get("result"):
self.state[event.get("task_key")]["result"] = event.get("result")
if event_type == "state":
queue = event["queue"]
del event["type"]
del event["queue"]
if "state" not in self.state:
self.state["state"] = {}
if queue not in self.state["state"]:
self.state["state"][queue] = {}
for key, value in event.items():
if key not in self.state["state"][queue]:
self.state["state"][queue][key] = 0
self.state["state"][queue][key] += value
if event_type == "result":
self.state[event.get("task_key")]["state"] = "done"
self.state[event.get("task_key")]["result"] = event.get("message")
except:
logging.exception("[%s] [TaskEvent] Got exception", self.ident)
channel.basic_ack(delivery_tag=method.delivery_tag)
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import pika
from time import sleep
from uuid import uuid4
from json import loads, dumps
import logging
from arbiter.event.base import BaseEventHandler
class RPCClintEventHandler(BaseEventHandler):
def __init__(self, settings, subscriptions, state):
super().__init__(settings, subscriptions, state)
self.callback_queue = None
self.correlation_id = None
self.response = None
self.client = self._get_channel()
def _connect_to_specific_queue(self, channel):
result = channel.queue_declare(queue='', exclusive=True)
self.callback_queue = result.method.queue
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=self.callback_queue,
on_message_callback=self.queue_event_callback,
auto_ack=True
)
logging.info("[%s] Waiting for task events", self.ident)
return channel
def queue_event_callback(self, channel, method, properties, body): # pylint: disable=R0912,R0915
if self.correlation_id == properties.correlation_id:
self.response = body
def call(self, tasks_module, task, args, kwargs):
self.response = None
self.correlation_id = str(uuid4())
message = {
"task_name": task,
"args": args,
"kwargs": kwargs
}
logging.info(message)
try:
self.client.basic_publish(
exchange='',
routing_key=tasks_module,
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.correlation_id,
),
body=dumps(message).encode("utf-8"))
except (pika.exceptions.ConnectionClosedByBroker,
pika.exceptions.AMQPChannelError,
pika.exceptions.AMQPConnectionError,
pika.exceptions.StreamLostError):
sleep(0.1)
self.client = self._get_channel()
return self.call(tasks_module, task, args, kwargs)
while self.response is None:
self.client.connection.process_data_events()
resp = loads(self.response)
if resp.get("type") == "exception":
raise ChildProcessError(resp["message"])
return resp.get("message")
<file_sep>from time import sleep
from arbiter import Arbiter, Task
arbiter_host = "localhost"
def simple_task_in_task():
arbiter = Arbiter(host=arbiter_host, port=5672, user='user', password='<PASSWORD>')
print(arbiter.workers())
task_keys = arbiter.apply("add", task_args=[1, 2])
for task_key in task_keys:
print(arbiter.status(task_key))
for message in arbiter.wait_for_tasks(task_keys):
print(message)
for task_key in task_keys:
print(arbiter.status(task_key))
arbiter.close()
def tasks_squad():
arbiter = Arbiter(host=arbiter_host, port=5672, user='user', password='<PASSWORD>')
tasks = []
for _ in range(20):
tasks.append(Task("simple_add", queue="test", task_args=[1, 2]))
squad_id = arbiter.squad(tasks)
while arbiter.status(squad_id).get("state") != "done":
sleep(1)
print(arbiter.status(squad_id))
arbiter.close()
def tasks_group():
arbiter = Arbiter(host=arbiter_host, port=5672, user='user', password='<PASSWORD>')
tasks = []
callback = Task("simple_add", task_args=[1, 2])
for _ in range(20):
tasks.append(Task("simple_add", task_args=[1, 2]))
squad_id = arbiter.group(tasks, callback)
while arbiter.status(squad_id).get("state") != "done":
sleep(1)
print(arbiter.status(squad_id))
arbiter.close()
def tasks_pipe():
arbiter = Arbiter(host=arbiter_host, port=5672, user='user', password='<PASSWORD>')
tasks = []
for _ in range(20):
tasks.append(Task("add_in_pipe", task_args=[2]))
pipe_id = None
for message in arbiter.pipe(tasks, persistent_args=[2]):
if "pipe_id" in message:
pipe_id = message["pipe_id"]
print(message)
print(arbiter.status(pipe_id))
arbiter.close()
if __name__ == "__main__":
#simple_task_in_task()
tasks_squad()
#tasks_group()
#tasks_pipe()
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import time
import json
import threading
import pika
import logging
class BaseEventHandler(threading.Thread):
""" Basic representation of events handler"""
def __init__(self, settings, subscriptions, state, wait_time=2.0):
super().__init__(daemon=True)
self.settings = settings
self.state = state
self.subscriptions = subscriptions
self._stop_event = threading.Event()
self.started = False
self.wait_time = wait_time
def _get_connection(self):
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=self.settings.host,
port=self.settings.port,
virtual_host=self.settings.vhost,
credentials=pika.PlainCredentials(
self.settings.user,
self.settings.password
)
)
)
return connection
def _get_channel(self, connection=None):
if not connection:
connection = self._get_connection()
channel = connection.channel()
if self.settings.queue:
channel.queue_declare(
queue=self.settings.queue, durable=True
)
channel.exchange_declare(
exchange=self.settings.all,
exchange_type="fanout", durable=True
)
channel = self._connect_to_specific_queue(channel)
return channel
def _connect_to_specific_queue(self, channel):
raise NotImplemented
def wait_running(self):
while not self.started:
time.sleep(0.5)
def run(self):
""" Run handler thread """
logging.info("Starting handler thread")
channel = None
while not self.stopped():
logging.info("Starting handler consuming")
try:
channel = self._get_channel()
logging.info("[%s] Waiting for task events", self.ident)
self.started = True
channel.start_consuming()
except pika.exceptions.ConnectionClosedByBroker:
logging.info("Connection Closed by Broker")
time.sleep(5.0)
continue
except pika.exceptions.AMQPChannelError:
logging.info("AMQPChannelError")
except pika.exceptions.StreamLostError:
logging.info("Recovering from error")
time.sleep(5.0)
continue
except pika.exceptions.AMQPConnectionError:
logging.info("Recovering from error")
time.sleep(5.0)
continue
channel.stop_consuming()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
@staticmethod
def respond(channel, message, queue, delay=0):
logging.debug(message)
if delay and isinstance(delay, int):
time.sleep(delay)
channel.basic_publish(
exchange="", routing_key=queue,
body=json.dumps(message).encode("utf-8"),
properties=pika.BasicProperties(
delivery_mode=2,
)
)
def queue_event_callback(self, channel, method, properties, body): # pylint: disable=R0912,R0915
raise NotImplemented
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import json
import logging
from arbiter.event.base import BaseEventHandler
class GlobalEventHandler(BaseEventHandler):
def _connect_to_specific_queue(self, channel):
exchange_queue = channel.queue_declare(queue="", exclusive=True)
channel.queue_bind(
exchange=self.settings.all,
queue=exchange_queue.method.queue
)
channel.basic_consume(
queue=exchange_queue.method.queue,
on_message_callback=self.queue_event_callback,
auto_ack=True
)
logging.info("Waiting for global events")
return channel
def queue_event_callback(self, channel, method, properties, body):
""" Process event """
_ = properties, self, channel, method
try:
event = json.loads(body)
#
event_type = event.get("type", None)
logging.info("[GlobalEvent] Type: %s", event_type)
#
if event_type in ["stop_task", "purge_task"]:
task_key = event.get("task_key")
if task_key in self.state and not self.state[task_key]["process"].ready():
logging.info("[GlobalEvent] Terminating task %s", task_key)
self.state[task_key]["status"] = "canceled"
elif event_type == "subscription_notification":
subscription = event.get("subscription")
if subscription in self.subscriptions:
logging.info("[GlobalEvent] Got data for subscription %s", subscription)
self.subscriptions[subscription] = event.get("data")
elif event_type == "state":
message = {"queue": self.state["queue"], "active": self.state["active_workers"],
"total": self.state["total_workers"],
"available": self.state["total_workers"] - self.state["active_workers"],
"type": "state"}
logging.debug(json.dumps(message, indent=2))
self.respond(channel, message, event["arbiter"])
elif event_type == "task_state":
response = {"type": "task_state"}
for each in event.get("tasks", []):
if each in self.state:
response[each] = True if self.state[each]["status"] != "done" else False
self.respond(channel, response, event["arbiter"])
elif event_type == "clear_state":
for task in event.get("tasks", []):
if task in self.state:
self.state.pop(task)
except: # pylint: disable=W0702
logging.exception("[GlobalEvent] Got exception")
<file_sep>PyYAML==5.3
requests==2.25.0
pika==1.1.0
<file_sep>from arbiter import Minion
import logging
from time import sleep
app = Minion(host="localhost", port=5672, user='user', password='<PASSWORD>', queue="test")
@app.task(name="add")
def add(x, y):
logging.info("Running task 'add'")
# task that initiate new task within same app
increment = 0
for message in app.apply('simple_add', task_args=[3, 4]):
if isinstance(message, dict):
increment = message["result"]
logging.info("sleep done")
return x + y + increment
@app.task(name="simple_add")
def adds(x, y):
logging.info(f"Running task 'add_small' with params {x}, {y}")
sleep(30)
return x + y
@app.task(name="add_in_pipe")
def addp(x, y, upstream=0):
logging.info("Running task 'add_in_pipe'")
return x + y + upstream
if __name__ == "__main__":
app.run(workers=7)
# app.rpc(workers=3, blocking=True)
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
class Task:
def __init__(self, name, queue='default', tasks_count=1, task_key="", task_type="task",
task_args=None, task_kwargs=None, callback=False, callback_queue=None):
if not task_args:
task_args = []
if not task_kwargs:
task_kwargs = {}
self.task_type = task_type
self.task_key = task_key
self.name = name
self.queue = queue
self.tasks_count = tasks_count
self.task_args = task_args
self.task_kwargs = task_kwargs
self.callback = callback
self.callback_queue = callback_queue
self.tasks_array = [] # this is for a task ids that need to be verified to be done before callback
def to_json(self):
return {
"type": self.task_type,
"queue": self.queue,
"task_name": self.name,
"task_key": self.task_key,
"args": self.task_args,
"kwargs": self.task_kwargs,
"arbiter": self.callback_queue,
"callback": self.callback,
"tasks_array": self.tasks_array
}
<file_sep>#!/usr/bin/python3
# coding=utf-8
# Copyright 2021 getcarrier.io
#
# 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.
"""
RPC node
Allows to call and register RPC functions
Uses existing EventNode as a transport
"""
import uuid
import queue
import threading
import functools
from arbiter import log
class RpcNode: # pylint: disable=R0902
""" RPC node - register and call remote functions """
def __init__(self, event_node, id_prefix=None):
self.event_node = event_node
self.event_node_was_started = False
#
self.functions = dict()
self.requests = dict()
#
self.id_prefix = id_prefix if id_prefix is not None else ""
#
self.lock = threading.Lock()
self.proxy = RpcProxy(self)
#
self.started = False
def start(self):
""" Start RPC node """
if self.started:
return
#
if not self.event_node.started:
self.event_node.start()
self.event_node_was_started = True
#
self.event_node.subscribe("rpc_request", self._rpc_request_callback)
self.event_node.subscribe("rpc_response", self._rpc_response_callback)
#
self.started = True
def stop(self):
""" Stop RPC node """
self.event_node.unsubscribe("rpc_request", self._rpc_request_callback)
self.event_node.unsubscribe("rpc_response", self._rpc_response_callback)
#
if self.event_node_was_started:
self.event_node.stop()
def register(self, func, name=None):
""" Register RPC function """
if name is None:
name = self._get_callable_name(func)
#
with self.lock:
self.functions[name] = func
def unregister(self, func, name=None):
""" Unregister RPC function """
if name is None:
name = self._get_callable_name(func)
#
with self.lock:
if name in self.functions:
self.functions.pop(name)
def call(self, func, *args, **kvargs):
""" Invoke RPC function """
if not self.started:
raise RuntimeError("RpcNode is not started")
#
if func in self.functions:
return self.functions[func](*args, **kvargs)
#
request_id = self._make_request(func, args, kvargs)
response = self.requests[request_id].get()
with self.lock:
self.requests.pop(request_id)
#
if "raise" in response:
raise response.get("raise")
return response.get("return", None)
def call_with_timeout(self, func, timeout, *args, **kvargs):
""" Invoke RPC function with timeout """
if not self.started:
raise RuntimeError("RpcNode is not started")
#
if func in self.functions:
return self.functions[func](*args, **kvargs)
#
request_id = self._make_request(func, args, kvargs)
try:
response = self.requests[request_id].get(timeout=timeout)
finally:
with self.lock:
self.requests.pop(request_id)
#
if "raise" in response:
raise response.get("raise")
return response.get("return", None)
def timeout(self, timeout):
""" Get RpcTimeoutProxy instance """
return RpcTimeoutProxy(self, timeout)
def _rpc_request_callback(self, event_name, event_payload):
_ = event_name
#
for key in ["request_id", "func", "args", "kvargs"]:
if key not in event_payload:
log.error("Invalid RPC request, skipping")
return
#
if event_payload["func"] not in self.functions:
return
#
try:
return_data = self.functions[event_payload["func"]](
*event_payload["args"], **event_payload["kvargs"]
)
self.event_node.emit(
"rpc_response",
{
"request_id": event_payload["request_id"],
"return": return_data,
}
)
except BaseException as exception_data: # pylint: disable=W0703
log.exception("RPC function exception")
self.event_node.emit(
"rpc_response",
{
"request_id": event_payload["request_id"],
"raise": exception_data,
}
)
def _rpc_response_callback(self, event_name, event_payload):
_ = event_name
#
for key in ["request_id"]:
if key not in event_payload:
log.error("Invalid RPC response, skipping")
return
#
if event_payload["request_id"] not in self.requests:
return
#
self.requests[event_payload["request_id"]].put(event_payload)
def _make_request(self, func, args, kvargs):
# Generate request ID
with self.lock:
while True:
request_id = f"{self.id_prefix}{str(uuid.uuid4())}"
if request_id not in self.requests:
self.requests[request_id] = queue.Queue()
break
# Emit request event
self.event_node.emit(
"rpc_request",
{
"request_id": request_id,
"func": func,
"args": args,
"kvargs": kvargs,
}
)
# Return request ID
return request_id
def _get_callable_name(self, func):
if hasattr(func, "__name__"):
return func.__name__
if isinstance(func, functools.partial):
return self._get_callable_name(func.func)
raise ValueError("Cannot guess callable name")
class RpcProxy: # pylint: disable=R0903
""" RPC proxy - syntax sugar for RPC calls """
def __init__(self, rpc_node):
self.__rpc_node = rpc_node
def __invoke(self, func, *args, **kvargs):
return self.__rpc_node.call(func, *args, **kvargs)
def __getattr__(self, name):
return functools.partial(self.__invoke, name)
class RpcTimeoutProxy: # pylint: disable=R0903
""" RPC proxy - syntax sugar for RPC calls - with timeout support """
def __init__(self, rpc_node, timeout):
self.__rpc_node = rpc_node
self.__timeout = timeout
def __invoke(self, func, *args, **kvargs):
return self.__rpc_node.call_with_timeout(func, self.__timeout, *args, **kvargs)
def __getattr__(self, name):
return functools.partial(self.__invoke, name)
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
from arbiter.arbiter import Arbiter
from arbiter.minion import Minion
from arbiter.eventnode import EventNode, MockEventNode
from arbiter.rpcnode import RpcNode
from arbiter.rpcclient import RPCClient
from arbiter.task import Task<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import logging
from uuid import uuid4
from time import sleep
from .base import Base
from .event.arbiter import ArbiterEventHandler
from .task import Task
class Arbiter(Base):
def __init__(self, host, port, user, password, vhost="carrier", all_queue="arbiterAll", start_consumer=True):
super().__init__(host, port, user, password, vhost, all_queue=all_queue)
self.arbiter_id = None
self.state = dict(groups=dict())
self.subscriptions = dict()
self.handler = None
if start_consumer:
self.arbiter_id = str(uuid4())
self.handler = ArbiterEventHandler(self.config, self.subscriptions, self.state, self.arbiter_id)
self.handler.start()
self.handler.wait_running()
def apply(self, task_name, queue="default", tasks_count=1, task_args=None, task_kwargs=None, sync=False):
task = Task(name=task_name, queue=queue, tasks_count=tasks_count,
task_args=task_args, task_kwargs=task_kwargs, callback_queue=self.arbiter_id)
return list(self.add_task(task, sync=sync))
def kill(self, task_key, sync=True):
message = {
"type": "stop_task",
"task_key": task_key,
"arbiter": self.arbiter_id
}
self.send_message(message, exchange=self.config.all)
if sync:
while True:
if task_key in self.state and self.state[task_key]["state"] == "done":
break
sleep(self.wait_time)
def kill_group(self, group_id):
tasks = []
for task_id in self.state["groups"][group_id]:
if task_id in self.state:
tasks.append(task_id)
self.kill(task_id, sync=False)
tasks_done = []
logging.info("Terminating ...")
while not all(task in tasks_done for task in tasks):
for task in tasks:
if task not in tasks_done and self.state[task]["state"] == 'done':
tasks_done.append(task)
sleep(self.wait_time)
def status(self, task_key):
if task_key in self.state:
return self.state[task_key]
elif task_key in self.state["groups"]:
group_results = {
"state": "done",
"initiated": 0,
"running": 0,
"done": 0,
"tasks": []
}
for task_id in self.state["groups"][task_key]:
if task_id in self.state:
if self.state[task_id]["state"] in ["running", "initiated"]:
group_results["state"] = self.state[task_id]["state"]
group_results[self.state[task_id]["state"]] += 1
group_results["tasks"].append(self.state[task_id])
else:
logging.info(f"[Group status] {task_id} is missing")
group_results["state"] = "running"
return group_results
else:
raise NameError("Task or Group not found")
def close(self):
self.handler.stop()
self._get_connection().queue_delete(queue=self.arbiter_id)
self.handler.join()
self.disconnect()
def workers(self):
message = {
"type": "state",
"arbiter": self.arbiter_id
}
if "state" in self.state:
del self.state["state"]
self.send_message(message, exchange=self.config.all)
sleep(self.wait_time)
return self.state["state"]
def squad(self, tasks, callback=None):
"""
Set of tasks that need to be executed together
"""
workers_count = {}
for each in tasks:
if each.task_type != "finalize":
if each.queue not in list(workers_count.keys()):
workers_count[each.queue] = 0
workers_count[each.queue] += each.tasks_count
stats = self.workers()
logging.info(f"Workers: {stats}")
logging.info(f"Tests to run {workers_count}")
for key in workers_count.keys():
if not stats.get(key) or stats[key]["available"] < workers_count[key]:
raise NameError(f"Not enough of {key} workers")
return self.group(tasks, callback)
def group(self, tasks, callback=None):
"""
Set of tasks that need to be executed regardless of order
"""
group_id = str(uuid4())
self.state["groups"][group_id] = []
tasks_array = []
finalizer = None
for each in tasks:
if each.task_type == "finalize":
finalizer = each
continue
task_id = str(uuid4())
tasks_array.append(task_id)
each.task_key = task_id
each.callback_queue = self.arbiter_id
if callback:
each.callback = True
for each in tasks:
if each.task_type == "finalize":
continue
for task in self.add_task(each):
self.state["groups"][group_id].append(task)
if callback:
callback.tasks_array = tasks_array
callback.task_key = group_id
callback.callback_queue = self.arbiter_id
callback.task_type = "callback"
if finalizer:
callback.callback = True
tasks_array.append(callback.task_key)
for task in self.add_task(callback):
self.state["groups"][group_id].append(task)
if finalizer:
finalizer.tasks_array = tasks_array
finalizer.task_key = group_id
finalizer.callback_queue = self.arbiter_id
for task in self.add_task(finalizer):
self.state["groups"][group_id].append(task)
return group_id
def pipe(self, tasks, persistent_args=None, persistent_kwargs=None):
"""
Set of tasks that need to be executed sequentially
NOTE: Persistent args always before the task args
Task itself need to have **kwargs if you want to ignore upstream results
"""
pipe_id = str(uuid4())
self.state["groups"][pipe_id] = []
if not persistent_args:
persistent_args = []
if not persistent_kwargs:
persistent_kwargs = {}
res = {}
yield {"pipe_id": pipe_id}
for task in tasks:
task.callback_queue = self.arbiter_id
task.task_args = persistent_args + task.task_args
for key, value in persistent_kwargs:
if key not in task.task_kwargs:
task.task_kwargs[key] = value
if res:
task.task_kwargs['upstream'] = res.get("result")
res = list(self.add_task(task, sync=True))
self.state["groups"][pipe_id].append(res[0])
res = res[1]
yield res
<file_sep>#!/usr/bin/python3
# coding=utf-8
# Copyright 2021 getcarrier.io
#
# 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.
"""
Event node
Allows to emit and consume global events
Emit an event: main thread
Listen for events from queue: thread one
Run callbacks: thread two
Listening and running threads are synced using local Queue
Event payloads are serialized, gziped and signed before sending to queue
"""
import threading
import pickle
import queue
import time
import gzip
import hmac
import pika # pylint: disable=E0401
from arbiter import log
from arbiter.config import Config
class EventNode: # pylint: disable=R0902
""" Event node - allows to subscribe to events and to emit new events """
def __init__(
self, host, port, user, password, vhost="carrier", event_queue="events",
hmac_key=None, hmac_digest="sha512", callback_workers=1,
ssl_context=None, ssl_server_hostname=None,
): # pylint: disable=R0913
self.queue_config = Config(host, port, user, password, vhost, event_queue, all_queue=None)
self.event_callbacks = dict() # event_name -> [callbacks]
#
self.ssl_context = ssl_context
self.ssl_server_hostname = ssl_server_hostname
#
self.hmac_key = hmac_key
self.hmac_digest = hmac_digest
if self.hmac_key is not None and isinstance(self.hmac_key, str):
self.hmac_key = self.hmac_key.encode("utf-8")
#
self.retry_interval = 3.0
#
self.stop_event = threading.Event()
self.event_lock = threading.Lock()
self.sync_queue = queue.Queue()
#
self.listening_thread = threading.Thread(target=self._listening_worker, daemon=True)
self.callback_threads = list()
for _ in range(callback_workers):
self.callback_threads.append(
threading.Thread(target=self._callback_worker, daemon=True)
)
#
self.ready_event = threading.Event()
self.started = False
def start(self):
""" Start event node """
if self.started:
return
#
self.listening_thread.start()
for callback_thread in self.callback_threads:
callback_thread.start()
#
self.ready_event.wait()
self.started = True
def stop(self):
""" Stop event node """
self.stop_event.set()
@property
def running(self):
""" Check if it is time to stop """
return not self.stop_event.is_set()
def subscribe(self, event_name, callback):
""" Subscribe to event """
with self.event_lock:
if event_name not in self.event_callbacks:
self.event_callbacks[event_name] = list()
if callback not in self.event_callbacks[event_name]:
self.event_callbacks[event_name].append(callback)
def unsubscribe(self, event_name, callback):
""" Unsubscribe from event """
with self.event_lock:
if event_name not in self.event_callbacks:
return
if callback not in self.event_callbacks[event_name]:
return
self.event_callbacks[event_name].remove(callback)
def emit(self, event_name, payload=None):
""" Emit event with payload data """
connection = self._get_connection()
channel = self._get_channel(connection)
#
event = {
"name": event_name,
"payload": payload,
}
body = gzip.compress(pickle.dumps(event, protocol=pickle.HIGHEST_PROTOCOL))
if self.hmac_key is not None:
digest = hmac.digest(self.hmac_key, body, self.hmac_digest)
body = body + digest
#
channel.basic_publish(
exchange=self.queue_config.queue,
routing_key="",
body=body,
properties=pika.BasicProperties(
delivery_mode=2
)
)
#
connection.close()
def _listening_worker(self):
while self.running:
try:
connection = self._get_connection()
channel = self._get_channel(connection)
#
exchange_queue = channel.queue_declare(queue="", exclusive=True)
channel.queue_bind(
exchange=self.queue_config.queue,
queue=exchange_queue.method.queue
)
channel.basic_consume(
queue=exchange_queue.method.queue,
on_message_callback=self._listening_callback,
auto_ack=True
)
#
self.ready_event.set()
#
channel.start_consuming()
except: # pylint: disable=W0702
log.exception(
"Exception in listening thread. Retrying in %s seconds", self.retry_interval
)
time.sleep(self.retry_interval)
finally:
try:
connection.close()
except: # pylint: disable=W0702
pass
def _listening_callback(self, channel, method, properties, body):
_ = channel, method, properties
self.sync_queue.put(body)
def _callback_worker(self):
while self.running:
try:
body = self.sync_queue.get()
#
if self.hmac_key is not None:
hmac_obj = hmac.new(self.hmac_key, digestmod=self.hmac_digest)
hmac_size = hmac_obj.digest_size
#
body_digest = body[-hmac_size:]
body = body[:-hmac_size]
#
digest = hmac.digest(self.hmac_key, body, self.hmac_digest)
#
if not hmac.compare_digest(body_digest, digest):
log.error("Invalid event digest, skipping")
continue
#
event = pickle.loads(gzip.decompress(body))
#
event_name = event.get("name")
event_payload = event.get("payload")
#
with self.event_lock:
if event_name not in self.event_callbacks:
continue
callbacks = self.event_callbacks[event_name].copy()
#
for callback in callbacks:
try:
callback(event_name, event_payload)
except: # pylint: disable=W0702
log.exception("Event callback failed, skipping")
except: # pylint: disable=W0702
log.exception("Error during event processing, skipping")
def _get_connection(self):
while self.running:
try:
#
pika_ssl_options = None
if self.ssl_context is not None:
pika_ssl_options = pika.SSLOptions(self.ssl_context, self.ssl_server_hostname)
#
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=self.queue_config.host,
port=self.queue_config.port,
virtual_host=self.queue_config.vhost,
credentials=pika.PlainCredentials(
self.queue_config.user,
self.queue_config.password
),
ssl_options=pika_ssl_options,
)
)
connection.process_data_events()
return connection
except: # pylint: disable=W0702
log.exception(
"Failed to create connection. Retrying in %s seconds", self.retry_interval
)
time.sleep(self.retry_interval)
def _get_channel(self, connection):
channel = connection.channel()
channel.exchange_declare(
exchange=self.queue_config.queue,
exchange_type="fanout",
durable=True
)
return channel
class MockEventNode: # pylint: disable=R0902
""" Event node - allows to subscribe to events and to emit new events - local-only mock """
def __init__(self): # pylint: disable=R0913
self.event_callbacks = dict() # event_name -> [callbacks]
self.started = True
def start(self):
""" Start event node """
def stop(self):
""" Stop event node """
@property
def running(self):
""" Check if it is time to stop """
return True
def subscribe(self, event_name, callback):
""" Subscribe to event """
if event_name not in self.event_callbacks:
self.event_callbacks[event_name] = list()
if callback not in self.event_callbacks[event_name]:
self.event_callbacks[event_name].append(callback)
def unsubscribe(self, event_name, callback):
""" Unsubscribe from event """
if event_name not in self.event_callbacks:
return
if callback not in self.event_callbacks[event_name]:
return
self.event_callbacks[event_name].remove(callback)
def emit(self, event_name, payload=None):
""" Emit event with payload data """
if event_name not in self.event_callbacks:
return
for callback in self.event_callbacks[event_name]:
try:
callback(event_name, payload)
except: # pylint: disable=W0702
log.exception("Event callback failed, skipping")
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import json
import logging
from arbiter.event.base import BaseEventHandler
class ProcessEventHandler(BaseEventHandler):
def __init__(self, settings, subscriptions, state, process_id):
super().__init__(settings, subscriptions, state)
self.process_id = process_id
def _connect_to_specific_queue(self, channel):
channel.queue_declare(
queue=self.process_id, durable=True
)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=self.process_id,
on_message_callback=self.queue_event_callback
)
logging.info("[%s] Waiting for task events", self.ident)
return channel
def queue_event_callback(self, channel, method, properties, body):
""" Process event """
_ = properties, self, channel, method
try:
logging.info(f"[ProcessHandler] {body}")
event = json.loads(body)
event_type = event.get("type", None)
logging.info("[ProcessEvent] Type: %s", event_type)
if event_type == "subscription_notification":
subscription = event.get("subscription")
if subscription in self.subscriptions:
self.subscriptions[subscription] = event.get("data")
if event_type == "task_state":
event.pop("type")
for key, value in event.items():
if not value and self.process_id in self.state and key not in self.state[self.process_id]["done"]:
self.state[self.process_id]["done"].append(key)
elif value and self.process_id in self.state and key not in self.state[self.process_id]["running"]:
self.state[self.process_id]["running"].append(key)
logging.info(self.state)
except: # pylint: disable=W0702
logging.exception("[ProcessEvent] Got exception")
channel.basic_ack(delivery_tag=method.delivery_tag)
<file_sep>from arbiter import RPCClient
arbiter_host = "localhost"
queue = "default"
rpc = RPCClient(arbiter_host, port=5672, user='user', password='<PASSWORD>')
print(rpc.call(queue, 'simple_add', [1, 7]))
print(rpc.call(queue, 'add', [1, 7]))
rpc.disconnect()
<file_sep>## Testing app for arbiter
Launch rabbitmq container
```
docker run -d --rm --hostname arbiter-rabbit --name arbiter-rabbit \
-p 5672:5672 -p 15672:15672 -e RABBITMQ_DEFAULT_USER=user \
-e RABBITMQ_DEFAULT_PASS=<PASSWORD> \
-e RABBITMQ_DEFAULT_VHOST=carrier \
rabbitmq:3-management
```
Launch minion app with `python minion.py`
Access rabbit management console through `http://localhost:15672`
go to Queues and select `arbiterHeavy`
click on `publish message` and post following message to body
```json
{
"type": "task",
"task_name": "add",
"task_key": "2",
"args": [1,2]
}
```
in the logs of running minion.py you need to see a record that task was executed and result published
<file_sep>#!/usr/bin/python
# coding=utf-8
#!/usr/bin/python3
# coding=utf-8
# Copyright 2020 getcarrier.io
#
# 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.
""" Worker """
import os
from argparse import ArgumentParser
def arg_parse():
parser = ArgumentParser(description='Arbiter worker processot')
parser.add_argument('-a', '--app', type=str, default=os.environ("ARBITER_TASKS"),
help="Name of installed package to get tasks from")
parser.add_argument('-w', '--workers', type=int, default=os.environ("ARBITER_WORKER_COUNT", 1),
help="Quantity of workers to be spawned. Default: 1")
parser.add_argument('-t', '--worker_type', type=str, default=os.environ("ARBITER_WORKER_TYPE"),
help="Type of a worker for arbiter [heavy, light], can be set in ARBITER_WORKER_TYPE env var")
args, _ = parser.parse_known_args()
return args
def main():
""" Main thread: start all and listen for broadcasts """
# Parse settings
settings = arg_parse()
if __name__ == "__main__":
main()
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import pika
import json
import logging
from traceback import format_exc
from arbiter.event.base import BaseEventHandler
class RPCEventHandler(BaseEventHandler):
def __init__(self, settings, subscriptions, state, task_registry, wait_time=2.0):
super().__init__(settings, subscriptions, state, wait_time=wait_time)
self.task_registry = task_registry
def _connect_to_specific_queue(self, channel):
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=self.settings.queue,
on_message_callback=self.queue_event_callback
)
logging.info("[%s] Waiting for task events", self.ident)
return channel
@staticmethod
def rpc_respond(channel, queue, body, correlation_id):
channel.basic_publish(exchange='', routing_key=queue,
body=json.dumps(body).encode("utf-8"),
properties=pika.BasicProperties(
correlation_id=correlation_id
))
def queue_event_callback(self, channel, method, properties, body): # pylint: disable=R0912,R0915
event = json.loads(body)
try:
logging.info("[%s] [RPCEvent]", self.ident)
logging.info("[%s] [RPCEvent] Starting worker process", self.ident)
if event.get("task_name") not in self.task_registry:
raise ModuleNotFoundError("Task is not a part of this worker")
result = self.task_registry[event.get("task_name")](*event.get("args", []), **event.get("kwargs", {}))
logging.info("[%s] [TaskEvent] Worker process stopped", self.ident)
self.rpc_respond(channel, properties.reply_to,
{"type": "result", "message": result, "task_key": event.get("task_key")},
properties.correlation_id)
except:
logging.exception("[%s] [TaskEvent] Got exception", self.ident)
self.rpc_respond(channel, properties.reply_to,
{"type": "exception", "message": format_exc(), "task_key": event.get("task_key")},
properties.correlation_id)
channel.basic_ack(delivery_tag=method.delivery_tag)
<file_sep># Arbiter
Distributed tasks queue use RabbitMQ as broker. Consists of arbiter and minion.
## Installation
Clone git repo
```bash
git clone https://github.com/carrier-io/arbiter.git
```
and install by running
```bash
cd arbiter
python setup.py install
```
## Basic scenario
Launch RabbitMQ, as it required for everything to work
```bash
docker run -d --rm --hostname arbiter-rabbit --name arbiter-rabbit \
-p 5672:5672 -p 15672:15672 -e RABBITMQ_DEFAULT_USER=user \
-e RABBITMQ_DEFAULT_PASS=<PASSWORD> \
-e RABBITMQ_DEFAULT_VHOST=carrier \
rabbitmq:3-management
```
### Create simple task
You need to initiate minion and provide connection details:
```python
from arbiter import Minion
app = Minion(host="localhost", port=5672,
user='user', password='<PASSWORD>')
```
then you can declare tasks by decorating callable with `@app.task`
```python
@app.task(name="simple_add")
def adds(x, y):
return x + y
```
Every task need to have a name, which it will be referred by when initiated from arbiter.
this is pretty much it to create first task
Now we need to create execution point
```python
if __name__ == "__main__":
app.run(worker_type="heavy", workers=3)
```
where `worker_type` can be either light or heavy, and quantity of worker slots to do the job(s)
Run created script. Minion is ready to accept work orders.
example of minion can be found at `test_app\minion.py`
### Call created task from arbiter
Arbiter is job initiator, it maintain the state of all jobs it created and can retrieve results.
Each arbiter have it's own communication channel, so job results won't mess between two different arbiters
Declaring the arbiter
```python
from arbiter import Arbiter
arbiter = Arbiter(host='localhost', port=5672, user='user', password='<PASSWORD>')
```
to call the task and track it till it done (tasks are obviously async)
```python
task_keys = arbiter.apply("simple_add", tasks_count=1, task_args=[1, 2]) # will return array of task ids
# while loop with returns results of each task once it done
for message in arbiter.wait_for_tasks(task_keys):
print(message)
```
Alternatively you can get task result by calling
```python
arbiter.status(task_keys[0])
```
it will return `json` where `result` will be one of the keys
Example of arbiter can be found in `test_app/comander.py`<file_sep># Copyright (c) 2020 getcarrier.io
#
# 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.
from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name='arbiter',
version='1.0.0',
description='Distributed queue',
long_description='Lightweight distributed task queue',
url='https://getcarrier.io',
license='Apache License 2.0',
author='arozumenko, LifeDJIK',
author_email='<EMAIL>, <EMAIL>',
packages=find_packages(),
install_requires=required
)
<file_sep># Copyright 2020 getcarrier.io
#
# 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.
import logging
from .base import Base
from .event.task import TaskEventHandler
from .event.broadcast import GlobalEventHandler
from .event.rpcServer import RPCEventHandler
from .task import Task
class Minion(Base):
def __init__(self, host, port, user, password, vhost="carrier", queue="default", all_queue="arbiterAll"):
super().__init__(host, port, user, password, vhost, queue, all_queue)
self.task_registry = {}
self.task_handlers = []
def apply(self, task_name, queue=None, tasks_count=1, task_args=None, task_kwargs=None, sync=True):
task = Task(task_name, queue=queue if queue else self.config.queue,
tasks_count=tasks_count, task_args=task_args, task_kwargs=task_kwargs)
for message in self.add_task(task, sync=sync):
yield message
def task(self, *args, **kwargs):
""" Task decorator """
def inner_task(func):
def create_task(**kwargs):
def _create_task(func):
return self._create_task_from_callable(func, **kwargs)
return _create_task
if callable(func):
return create_task(**kwargs)(func)
raise TypeError('@task decorated function must be callable')
return inner_task
def _create_task_from_callable(self, func, name=None, **kwargs):
name = name if name else f"{func.__name__}.{func.__module__}"
if name not in self.task_registry:
self.task_registry[name] = func
return self.task_registry[name]
def rpc(self, workers, blocking=False):
self.rpc = True
state = dict()
subscriptions = dict()
logging.info("Starting '%s' RPC", self.config.queue)
state["queue"] = self.config.queue
for _ in range(workers):
self.task_handlers.append(RPCEventHandler(self.config, subscriptions, state,
self.task_registry, wait_time=self.wait_time))
self.task_handlers[-1].start()
self.task_handlers[-1].wait_running()
if blocking:
for prcsrs in self.task_handlers:
prcsrs.join()
def run(self, workers):
state = dict()
subscriptions = dict()
logging.info("Starting '%s' worker", self.config.queue)
# Listen for task events
state["queue"] = self.config.queue
state["total_workers"] = workers
state["active_workers"] = 0
for _ in range(workers):
TaskEventHandler(self.config, subscriptions, state, self.task_registry, wait_time=self.wait_time).start()
# Listen for global events
global_handler = GlobalEventHandler(self.config, subscriptions, state)
global_handler.start()
global_handler.join()<file_sep># Copyright 2020 getcarrier.io
#
# 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.
from arbiter.base import Base
from arbiter.event.rpcClient import RPCClintEventHandler
class RPCClient(Base):
def __init__(self, host, port, user, password, vhost="carrier", all_queue="arbiterAll"):
super().__init__(host, port, user, password, vhost, all_queue=all_queue)
self.subscriptions = {}
self.handler = RPCClintEventHandler(self.config, self.subscriptions, self.state)
self.handler.start()
self.handler.wait_running()
def call(self, tasks_module, task_name, *args, **kwargs):
task_args = args if args else []
task_kwargs = kwargs if kwargs else {}
return self.handler.call(tasks_module, task_name, task_args, task_kwargs)
| 6412e4382e55fdfe362886aa5342c04ea401c648 | [
"Markdown",
"Python",
"Text"
] | 25 | Python | hunkom/arbiter | 3d7aa1e225c311696e086429bc78bdc7f0f477e2 | e42a0c3c23805a2d6ecb7e6751e7ca4443f0effd |
refs/heads/master | <file_sep>package com.example.luckyticketkotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun ticketText(view: android.view.View) {
val editText = findViewById<View>(R.id.ticketNumber) as EditText
val ticketInput = editText.text.toString();
val item = ticketInput.toCharArray()
val bulbId = findViewById<ImageView>(R.id.bulbId)
when (item.size) {
6 -> if (item[0].code + item[1].code + item[2].code == item[3].code + item[4].code
+ item[5].code
) {
bulbId.setImageResource(R.drawable.green)
} else {
bulbId.setImageResource(R.drawable.red)
}
else -> Toast.makeText(this, "Потрібно ввести 6 символів!", Toast.LENGTH_LONG).show()
}
}
} | 5b2e664bbf4179b3bc6ab00acf229edf4ec7e92f | [
"Kotlin"
] | 1 | Kotlin | MRAndrd/LuckyTicketKotlin | fb492ee645416cf698b90b9c5c6cb913a10ce5f5 | 0f59991fc25e78440b32670ed7e388cf125e5bc5 |
refs/heads/master | <repo_name>aman0511/geekapp<file_sep>/run.py
import os
from app import app
port = int(os.getenv('VCAP_APP_PORT', 5000))
if __name__ == "__main__":
app.run(debug=True,port=int(port))<file_sep>/app/oauth.py
from rauth import OAuth1Service, OAuth2Service
from flask import url_for, request, redirect, session
from config import OAUTH_CREDENTIALS
class OAuthSignIn(object):
providers = None
def __init__(self, provider_name):
self.provider_name = provider_name
self.consumer_id = OAUTH_CREDENTIALS[provider_name]['id']
self.consumer_secret = OAUTH_CREDENTIALS[provider_name]['secret']
def authorize(self):
pass
def callback(self):
pass
def get_callback_url(self):
return url_for('oauth_callback', provider=self.provider_name,
_external=True)
@classmethod
def get_provider(self, provider_name):
if self.providers is None:
self.providers = {}
for provider_class in self.__subclasses__():
provider = provider_class()
self.providers[provider.provider_name] = provider
return self.providers[provider_name]
class FacebookSignIn(OAuthSignIn):
def __init__(self):
super(FacebookSignIn, self).__init__('facebook')
self.service = OAuth2Service(
name='facebook',
client_id=self.consumer_id,
client_secret=self.consumer_secret,
authorize_url='https://graph.facebook.com/oauth/authorize',
access_token_url='https://graph.facebook.com/oauth/access_token',
base_url='https://graph.facebook.com/'
)
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='email',
response_type='code',
redirect_uri=self.get_callback_url())
)
def callback(self):
if 'code' not in request.args:
return None, None, None
oauth_session = self.service.get_auth_session(
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()}
)
me = oauth_session.get('me').json()
me = {
'email': me['email'],
'name': me['name'],
'image': "//graph.facebook.com/"+me['id']+"/picture?type=large",
'id': me['id']
}
return me
class TwitterSignIn(OAuthSignIn):
def __init__(self):
super(TwitterSignIn, self).__init__('twitter')
self.service = OAuth1Service(
name='twitter',
consumer_key=self.consumer_id,
consumer_secret=self.consumer_secret,
request_token_url='https://api.twitter.com/oauth/request_token',
authorize_url='https://api.twitter.com/oauth/authorize',
access_token_url='https://api.twitter.com/oauth/access_token',
base_url='https://api.twitter.com/1.1/'
)
def authorize(self):
request_token = self.service.get_request_token(
params={'oauth_callback': self.get_callback_url()}
)
session['request_token'] = request_token
return redirect(self.service.get_authorize_url(request_token[0]))
def callback(self):
request_token = session.pop('request_token')
if 'oauth_verifier' not in request.args:
return None, None, None
oauth_session = self.service.get_auth_session(
request_token[0],
request_token[1],
data={'oauth_verifier': request.args['oauth_verifier']}
)
me = oauth_session.get('account/verify_credentials.json').json()
social_id = 'twitter$' + str(me.get('id'))
username = me.get('screen_name')
me = {
'email': '<EMAIL>',
'name': str(me.get('screen_name')),
'image': "",
'id': str(me.get('id'))
}
return me # Twitter does not provide email
class LinkedinSignIn(OAuthSignIn):
"""docstring for Link"""
def __init__(self):
super(LinkedinSignIn, self).__init__('linkedin')
self.service = OAuth1Service(
name='linkedin',
consumer_key=self.consumer_id,
consumer_secret=self.consumer_secret,
request_token_url='https://api.linkedin.com/uas/oauth/requestToken',
authorize_url='https://api.linkedin.com/uas/oauth/authorize',
access_token_url='https://api.linkedin.com/uas/oauth/accessToken',
base_url='http://api.linkedin.com/v1/'
)
def authorize(self):
request_token = self.service.get_request_token(
params={'oauth_callback': self.get_callback_url(),
'scope': "r_fullprofile r_emailaddress r_network"}
)
session['request_token'] = request_token
return redirect(self.service.get_authorize_url(request_token[0]))
def callback(self):
request_token = session.pop('request_token')
if 'oauth_verifier' not in request.args:
return None, None, None
oauth_session = self.service.get_auth_session(
request_token[0],
request_token[1],
data={'oauth_verifier': request.args['oauth_verifier']},
header_auth=True
)
me = oauth_session.get('people/~:(id,first-name,last-name,headline,maiden-name,formatted-name,picture-url,email-address)',
params={'type': 'SHAR', 'format': 'json'},
header_auth=True).json()
me = {
'email': me['emailAddress'],
'name': me['formattedName'],
'image': me['pictureUrl'],
'id': me['id']
}
return me
<file_sep>/app/templates/name.html
<div class="row" style="margin-top:30px">
<div class="col-sm-push-3 col-sm-9 col-md-10 col-md-push-2">
{% for data in datas %}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><a href="/person/{{data.id}}">{{data.name}} </a></h3>
<h3 id="avg-{{data.id}}" class="text-success pull-right">{{data.total_avg|float|round(1)}} %</h3>
</div>
<div class="panel-body">
<dl class="dl-horizontal col-md-9">
<dt>Constituency:</dt>
<dd>{{data.constituency}}</dd>
<dt>State:</dt>
<dd>{{data.state}}</dd>
<dt>Seat No.</dt>
<dd>{{data.division_or_seat_no}}</dd>
<dt>Loksabha</dt>
<dd>{{data.Loksabha}}th</dd>
</dl>
<div id="table-{{data.id}}"></div>
<div id="chart-{{data.id}}">
</div>
</div>
</div>
{% endfor %}
</div>
</div><file_sep>/requirements.txt
Flask==0.10.1
Flask-JSGlue==0.3
Flask-Login==0.2.11
Flask-Migrate==1.3.0
Flask-SQLAlchemy==2.0
Flask-Script==2.0.5
Flask-WTF==0.11
Flask-WhooshAlchemy==0.56
Jinja2==2.7.3
Mako==1.0.1
MarkupSafe==0.23
MySQL-python==1.2.5
ProxyTypes==0.9
SQLAlchemy==0.9.8
Tempita==0.5.2
WTForms==2.0.2
Werkzeug==0.9.6
Whoosh==2.6.0
alembic==0.7.4
argparse==1.2.1
blinker==1.3
boto==2.36.0
decorator==3.4.0
gunicorn==19.1.1
ipython==2.3.1
itsdangerous==0.24
pbr==0.10.7
python-loaders==0.2.3
rauth==0.7.1
redis==2.10.3
requests==2.5.1
six==1.9.0
sqlalchemy-migrate==0.9.4
sqlparse==0.1.14
wsgiref==0.1.2
<file_sep>/config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'mysql://root:route91cap%@springboard-rds.corrsqtz0i3y.ap-southeast-1.rds.amazonaws.com/geekApp'
SECRET_KEY = '<PASSWORD>'
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
WHOOSH_BASE = os.path.join(basedir, 'search.db')
OAUTH_CREDENTIALS = {
'facebook': {
'id': '808299189209040',
'secret': '<KEY>'
},
'twitter': {
'id': 'Zel5GJWtHMlTBm8jmLGZsGdeo',
'secret': '<KEY>'
},
'linkedin': {
'id': '78puisghrag04v',
'secret': '<KEY>'
}
}<file_sep>/app/static/js/app.js
var availableTags = [];
$('document').ready(function () {
var $loading = $('#spinner').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
$('[data-toggle=offcanvas]').click(function () {
$('.row-offcanvas').toggleClass('active');
});
});
var search = function (parameter,value){
console.log('hello');
if(value){
data={
value: value,
parameter: parameter
}
$.ajax({
url: '/search/page/' ,
type: "POST",
data: data,
success: function(data) {
$("#result").html("");
$("#result").html(data['html']);
}
});
}
}
function person(url){
console.log(url);
$.ajax({
url: url,
type: "POST",
data: data,
success: function(data) {
html=data;
for(key in html){
$('#table-'+key).html("");
$('#table-'+key).html(html[key]);
}
}
});
}
$('#searchbox').change(function(){
search($('#search_param').val(), this.value);
});<file_sep>/app/views.py
import json
import os
from flask import render_template, request, g, url_for, redirect
from app import app, lm
from models import MemberDetails, memberSession, User
from app import db
from flask import Flask, jsonify
from flask.ext.login import login_user, current_user, logout_user, \
login_required
from oauth import OAuthSignIn
@lm.user_loader
def load_user(id):
return User.query.get(id)
@app.before_request
def before_request():
g.user = current_user
@app.route('/datainsert/')
def base():
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
json_url = os.path.join(SITE_ROOT, "static/js", "data.json")
data = json.load(open(json_url))
for i, data in enumerate(data['data']):
kwargs = dict()
# kwargs['name'] = str(data[2])
# kwargs['division_or_seat_no'] = str(data[1])
# kwargs['Loksabha'] = str(data[3])
# kwargs['state'] = str(data[5])
# kwargs['constituency'] = str(data[6])
# member = MemberDetails(**kwargs)
kwargs['id'] = str(data[0])
kwargs['Loksabha_session'] = str(data[4])
kwargs['total_sitting'] = str(data[7])
kwargs['no_days_member_signed_the_register'] = str(data[8])
try:
total = int(data[7])
except:
total = 0
try:
total_sitting = int(data[8])
except:
total_sitting = 0
try:
avg = (float(total_sitting)/total)*100
except:
avg = 0
kwargs['session_avg'] = str(round(avg, 2))
member = memberSession(**kwargs)
db.session.add(member)
db.session.commit()
member = MemberDetails.get_member(int(kwargs['id']))
total_sitting = 0
total = 0
for sess in member.sessions:
try:
total += int(sess.total_sitting)
except:
total += 0
try:
total_sitting += int(sess.no_days_member_signed_the_register)
except:
total_sitting += 0
percentage = (float(total_sitting)/total)*100
member.total_avg = percentage
db.session.merge(member)
db.session.commit()
return render_template('base.html')
@app.route('/search/page/', methods=['GET', 'POST'])
def search_page():
if request.method == 'POST':
if request.form['parameter'] == "all":
datas = MemberDetails.query.whoosh_search('soni').all()
elif request.form['parameter'] == "state":
datas = MemberDetails.query.filter(MemberDetails.state.like
(request.form['value']+"%")
).all()
elif request.form['parameter'] == "name":
datas = MemberDetails.query.filter(MemberDetails.name.like
("%"+request.form['value']+"%")
).all()
elif request.form['parameter'] == "constituency":
datas = MemberDetails.query.filter(MemberDetails.constituency.like
("%"+request.form['value']+"%")
).all()
else:
datas = []
template_data = {}
template_data['html'] = render_template('name.html', datas=datas)
return jsonify(template_data)
return "404"
# output = []
# for data in datas:
# row = {}
# print MemberDetails.__table__.c
# for column in MemberDetails.__table__.columns:
# row[str(column.name)] = getattr(data, str(column.name))
# output.append(row)
# return jsonify(result=output)
@app.route('/index/')
def index():
return render_template('base.html')
@app.route('/list/', methods=['GET', 'POST'])
def auto_listing():
if request.method == 'POST':
if request.form['parameter'] == "all":
datas = MemberDetails.query.whoosh_search('soni').all()
elif request.form['parameter'] == "state":
datas = MemberDetails.query.with_entities(MemberDetails.state.distinct()).all()
elif request.form['parameter'] == "name":
datas = MemberDetails.query.with_entities(MemberDetails.name.distinct()).all()
elif request.form['parameter'] == "constituency":
datas = MemberDetails.query.with_entities(MemberDetails.constituency.distinct()).all()
else:
datas = []
tags = []
for data in datas:
tags.append(data[0].rstrip())
# for data in datas:
# row = {}
# print MemberDetails.__table__.c
# for column in MemberDetails.__table__.columns:
# row[str(column.name)] = getattr(data, str(column.name))
# output.append(row)
return jsonify(result=tags)
@app.route('/no_of_analaysis/')
def data_analaysis():
sessions = db.session.query(memberSession.Loksabha_session.distinct()).all()
kwargs = dict()
for sessions in sessions:
kwargs[sessions.Loksabha_session] = sessions.Loksabha_session
print kwargs
return "sucees"
@app.route('/authorize/<provider>', methods=['GET', 'POST'])
def oauth_authorize(provider=None):
if not g.user.is_anonymous():
return redirect(url_for('index'))
else:
oauth = OAuthSignIn.get_provider(provider)
return oauth.authorize()
@app.route('/callback/<provider>')
def oauth_callback(provider):
if not g.user.is_anonymous():
return redirect(url_for('home'))
oauth = OAuthSignIn.get_provider(provider)
me = oauth.callback()
kwargs = dict()
kwargs['email'] = me['email']
kwargs['social_id'] = me['id']
kwargs['name'] = me['name']
user = User.authenticate_user(**kwargs)
if user:
login_user(user)
return redirect(url_for('index'))
else:
try:
user = User(**kwargs)
login_user(user, True)
db.session.add(user)
db.session.commit()
except Exception as e:
print e
return redirect(url_for('index'))
@app.route('/logout')
def logout():
''' logout view '''
logout_user()
return redirect(url_for('index'))
@app.route('/person/<id>',methods=['GET','POST'])
def person(id):
member = MemberDetails.get_member(int(id))
datas = MemberDetails.query.with_entities(MemberDetails.name.distinct()).all()
graphdata = dict()
for sessions in member.sessions:
graphdata[sessions.Loksabha_session]=sessions.no_days_member_signed_the_register
print graphdata
return render_template('person.html',person=member,graphdata=graphdata)
<file_sep>/app/models.py
from app import db, app
import sys
from flask.ext.login import UserMixin
if sys.version_info >= (3, 0):
enable_search = False
else:
enable_search = True
import flask.ext.whooshalchemy as whooshalchemy
class MemberDetails(db.Model):
__tablename__ = "member"
__searchable__ = ['name']
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=True)
division_or_seat_no = db.Column(db.String(255), nullable=True)
Loksabha = db.Column(db.String(255), nullable=True)
state = db.Column(db.String(255), nullable=False)
constituency = db.Column(db.String(255), nullable=False)
sessions = db.relationship('memberSession',
backref=db.backref('MemberDetails',
lazy='joined'),
lazy='dynamic')
total_avg = db.Column(db.String(255), nullable=True)
errors = {}
def __init__(self, **kwargs):
"""Initialize the MemberAttendance object based on the method"""
for key, value in kwargs.iteritems():
try:
setattr(self, key, value)
except:
# Returns a dictionary of empty field errors
MemberDetails.errors[key] = "EMPTY FIELD"
@staticmethod
def get_member(id):
return db.session.query(MemberDetails).filter_by(
id=id).first()
if enable_search:
whooshalchemy.whoosh_index(app, MemberDetails)
class memberSession(db.Model):
"""docstring for session"""
__tablename__ = "membersession"
id = db.Column(db.Integer, primary_key=True)
Loksabha_session = db.Column(db.String(255), nullable=False)
speaker_id = db.Column(db.Integer, db.ForeignKey('member.id'))
total_sitting = db.Column(db.String(255))
session_avg = db.Column(db.String(255), nullable=True)
no_days_member_signed_the_register = db.Column(db.String(255))
errors = {}
def __init__(self, **kwargs):
member = MemberDetails.get_member(int(kwargs['id']))
kwargs.pop('id')
self.MemberDetails = member
for key, value in kwargs.iteritems():
try:
setattr(self, key, value)
except:
MemberDetails.errors = "empty field"
class User(db.Model, UserMixin):
''' User Table containing all primary data '''
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), index=True, nullable=False)
social_id = db.Column(db.String(255), nullable=True, unique=True)
email = db.Column(db.String(255), index=True, nullable=False)
errors = {}
def __init__(self, **kwargs):
for key, value in kwargs.iteritems():
try:
setattr(self, key, value)
except:
# Returns a dictionary of empty field errors
User.errors[key] = "empty Field"
@staticmethod
def get_user(token=None):
"""returns user object for a specific user"""
if token:
return db.session.query(User).filter_by(
social_id=token).first()
@staticmethod
def authenticate_user(**kwargs):
""" authenticates a user and also enforces validations"""
if kwargs['social_id']:
user = User.get_user(token=kwargs['social_id'])
if user:
return user
return
else:
User.errors['social_id'] = "AUTHENTICATION_FAIL"
return
| 45497c3c985e8a5a265303dc43550bcc3c475824 | [
"JavaScript",
"Python",
"Text",
"HTML"
] | 8 | Python | aman0511/geekapp | b18cdc92c430b719f2efd0b97b073f6fae475492 | ed29ed21e7db48eafcdd458dc04b06cb95a11c51 |
refs/heads/master | <file_sep># SecretHoldEm
A Texas hold 'em poker game implemented as a Secret Contract for the Secret Network
Demo: https://holdem.enigma.co
<file_sep>.PHONY: all build clean store find-floating-points
all: build
build:
RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown --locked
wasm-opt -Oz ./target/wasm32-unknown-unknown/release/*.wasm -o ./contract.wasm
cat ./contract.wasm | gzip -9 > ./contract.wasm.gz
find-floating-points:
cargo build --release --target wasm32-unknown-unknown --locked
twiggy paths ./target/wasm32-unknown-unknown/release/*.wasm > find_floats_twiggy.txt
wasm2wat ./target/wasm32-unknown-unknown/release/*.wasm | grep -B 20 -P 'f(64|32)' > find_floats_grep.txt
clean:
cargo clean
-rm -f ./contract.wasm ./contract.wasm.gz
store: build
secretcli tx compute store contract.wasm.gz --from lll -y --gas 10000000 --source "https://github.com/enigmampc/SecretHoldEm/blob/$(shell git show --oneline -s | cut -f 1 -d ' ')/contract" -b block
sim-play: build
./sim.sh
<file_sep>import React from "react";
import * as SecretJS from "secretjs";
import * as bip39 from "bip39";
import { Hand, Table, Card } from "react-casino";
import { Button, Form } from "semantic-ui-react";
import Slider from "rc-slider";
import {
NotificationContainer,
NotificationManager,
} from "react-notifications";
import "rc-slider/assets/index.css";
import "semantic-ui-css/semantic.min.css";
import "./App.css";
import "react-notifications/lib/notifications.css";
const PokerSolver = require("pokersolver").Hand;
const nf = new Intl.NumberFormat("en-US", { maximumFractionDigits: 6 });
const codeId = 4;
console.log("Code ID:", codeId);
const refreshTableStateInterval = 2000;
const BIG_BLIND = 1_000_000;
const MAX_TABLE_BIG_BLINDS = 100;
const MIN_TABLE_BIG_BLINDS = 20;
const emptyState = {
game_address: "",
all_rooms: [],
community_cards: [],
my_hand: [{}, {}],
player_a_hand: [{}, {}],
player_b_hand: [{}, {}],
player_a: "",
player_a_bet: 0,
player_a_wallet: 0,
player_b: "",
player_b_bet: 0,
player_b_wallet: 0,
stage: "",
turn: "",
new_room_name: "",
createLoading: false,
joinLoading: false,
checkLoading: false,
callLoading: false,
raiseLoading: false,
withdrawLoading: false,
depositLoading: false,
raiseAmount: 25000,
depositAmount: 0,
rematchLoading: false,
player_a_wants_rematch: false,
player_b_wants_rematch: false,
player_a_win_counter: 0,
player_b_win_counter: 0,
tie_counter: 0,
myWalletBalanceUscrt: 0,
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = Object.assign({}, emptyState, {
game_address: window.location.hash.replace("#", ""),
});
}
async componentDidMount() {
window.onhashchange = async () => {
this.setState(
Object.assign({}, emptyState, {
game_address: window.location.hash.replace("#", ""),
})
);
};
let mnemonic = localStorage.getItem("mnemonic");
if (!mnemonic) {
mnemonic = bip39.generateMnemonic();
localStorage.setItem("mnemonic", mnemonic);
}
let tx_encryption_seed = localStorage.getItem("tx_encryption_seed");
if (tx_encryption_seed) {
tx_encryption_seed = Uint8Array.from(
JSON.parse(`[${tx_encryption_seed}]`)
);
} else {
tx_encryption_seed = SecretJS.EnigmaUtils.GenerateNewSeed();
localStorage.setItem("tx_encryption_seed", tx_encryption_seed);
}
const signingPen = await SecretJS.Secp256k1Pen.fromMnemonic(mnemonic);
const myWalletAddress = SecretJS.pubkeyToAddress(
SecretJS.encodeSecp256k1Pubkey(signingPen.pubkey),
"secret"
);
const secretJsClient = new SecretJS.SigningCosmWasmClient(
"https://bootstrap.pub.testnet2.enigma.co",
myWalletAddress,
(signBytes) => signingPen.sign(signBytes),
tx_encryption_seed,
{
init: {
amount: [{ amount: "250000", denom: "uscrt" }],
gas: "250000",
},
exec: {
amount: [{ amount: "250000", denom: "uscrt" }],
gas: "250000",
},
}
);
this.setState({ secretJsClient, myWalletAddress, mnemonic });
const refreshAllRooms = async () => {
if (window.location.hash !== "") {
return;
}
try {
console.log("refreshAllRooms");
const data = await secretJsClient.getContracts(codeId);
this.setState({
all_rooms: data,
});
} catch (e) {
console.log("refreshAllRooms", e);
NotificationManager.error("refreshAllRooms", e.message, 5000);
}
};
setTimeout(refreshAllRooms, 0);
setInterval(refreshAllRooms, refreshTableStateInterval);
const refreshMyHand = async () => {
if (window.location.hash === "") {
return;
}
if (!this.state.player_a || !this.state.player_b) {
return;
}
if (
this.state.player_a !== this.state.myWalletAddress &&
this.state.player_b !== this.state.myWalletAddress
) {
return;
}
if (
JSON.stringify(this.state.my_hand) !== JSON.stringify([{}, {}]) &&
this.state.stage !== "PreFlop"
) {
// this should work because when switching room (= switching hash location)
// we set an empty state
return;
}
const secret = +localStorage.getItem(this.state.game_address);
try {
console.log("refreshMyHand");
const data = await secretJsClient.queryContractSmart(
this.state.game_address,
{ get_my_hand: { secret } }
);
this.setState({
my_hand: data,
});
if (this.state.myWalletAddress === this.state.player_a) {
this.setState({
player_a_hand: this.state.my_hand,
});
} else if (this.state.myWalletAddress === this.state.player_b) {
this.setState({
player_b_hand: this.state.my_hand,
});
}
} catch (e) {
console.log("refreshMyHand", e);
NotificationManager.error("refreshMyHand", e.message, 5000);
}
};
setTimeout(refreshMyHand, 0);
setInterval(refreshMyHand, refreshTableStateInterval);
const refreshMyWalletBalance = async () => {
try {
console.log("refreshMyWalletBalance");
const data = await secretJsClient.getAccount(myWalletAddress);
if (!data) {
this.setState({
myWalletBalanceUscrt: 0,
myWalletBalance: (
<span>
(No funds - Go get some{" "}
<a
href="https://faucet.pub.testnet2.enigma.co"
rel="noopener noreferrer"
target="_blank"
>
from the faucet
</a>
)
</span>
),
});
} else {
this.setState({
myWalletBalanceUscrt: +data.balance[0].amount,
myWalletBalance: `(${nf.format(
+data.balance[0].amount / 1000000
)} SCRT)`,
});
}
} catch (e) {
console.log("refreshMyWalletBalance", e);
NotificationManager.error("refreshMyWalletBalance", e.message, 5000);
}
};
setTimeout(refreshMyWalletBalance, 0);
setInterval(refreshMyWalletBalance, refreshTableStateInterval * 5);
const refreshTableState = async () => {
if (window.location.hash === "") {
return;
}
try {
console.log("refreshTableState");
const data = await secretJsClient.queryContractSmart(
this.state.game_address,
{ get_public_data: {} }
);
if (data.player_a_hand.length === 0) {
data.player_a_hand = [{}, {}];
}
if (data.player_b_hand.length === 0) {
data.player_b_hand = [{}, {}];
}
if (this.state.myWalletAddress === data.player_a) {
this.setState({
player_a_hand: this.state.my_hand,
player_b_hand: data.player_b_hand,
});
} else if (this.state.myWalletAddress === data.player_b) {
this.setState({
player_a_hand: data.player_a_hand,
player_b_hand: this.state.my_hand,
});
} else {
this.setState({
player_a_hand: data.player_a_hand,
player_b_hand: data.player_b_hand,
});
}
this.setState({
community_cards: data.community_cards
.concat([{}, {}, {}, {}, {}])
.slice(0, 5),
player_a: data.player_a,
player_a_bet: data.player_a_bet,
player_a_wallet: data.player_a_wallet,
player_b: data.player_b,
player_b_bet: data.player_b_bet,
player_b_wallet: data.player_b_wallet,
stage: data.stage,
starter: data.starter,
turn: data.turn,
last_play: data.last_play,
player_a_wants_rematch: data.player_a_wants_rematch,
player_b_wants_rematch: data.player_b_wants_rematch,
player_a_win_counter: data.player_a_win_counter,
player_b_win_counter: data.player_b_win_counter,
tie_counter: data.tie_counter,
});
} catch (e) {
console.log("refreshTableState", e);
NotificationManager.error("refreshTableState", e.message, 5000);
}
};
setTimeout(refreshTableState, 0);
setInterval(refreshTableState, refreshTableStateInterval);
}
async createRoom() {
this.setState({ createLoading: true });
try {
await this.state.secretJsClient.instantiate(
codeId,
{
create_room: { big_blind: BIG_BLIND },
},
this.state.new_room_name
);
} catch (e) {
console.log("createRoom", e);
NotificationManager.error("createRoom", e.message, 5000);
}
setTimeout(
() =>
this.setState({
new_room_name: "",
createLoading: false,
}),
refreshTableStateInterval
);
}
async joinRoom() {
if (!this.state.game_address) {
// ah?
return;
}
this.setState({ joinLoading: true });
let secret = +localStorage.getItem(this.state.game_address);
if (!secret) {
const seed = SecretJS.EnigmaUtils.GenerateNewSeed();
secret = Buffer.from(seed.slice(0, 8)).readUInt32BE(0); // 64 bit
}
localStorage.setItem(this.state.game_address, secret);
try {
await this.state.secretJsClient.execute(
this.state.game_address,
{
join: { secret },
},
"",
[
{
amount: `${this.state.depositAmount}`,
denom: "uscrt",
},
]
);
} catch (e) {
console.log("join", e);
NotificationManager.error("join", e.message, 5000);
}
setTimeout(
() => this.setState({ joinLoading: false, depositAmount: 0 }),
refreshTableStateInterval
);
}
async fold() {
this.setState({ foldLoading: true });
try {
await this.state.secretJsClient.execute(this.state.game_address, {
fold: {},
});
} catch (e) {
console.log("fold", e);
NotificationManager.error("fold", e.message, 5000);
}
setTimeout(
() => this.setState({ foldLoading: false }),
refreshTableStateInterval
);
}
async check() {
this.setState({ checkLoading: true });
try {
await this.state.secretJsClient.execute(this.state.game_address, {
check: {},
});
} catch (e) {
console.log("check", e);
NotificationManager.error("check", e.message, 5000);
}
setTimeout(
() => this.setState({ checkLoading: false }),
refreshTableStateInterval
);
}
async call() {
this.setState({ callLoading: true });
try {
await this.state.secretJsClient.execute(this.state.game_address, {
call: {},
});
} catch (e) {
console.log("call", e);
NotificationManager.error("call", e.message, 5000);
}
setTimeout(
() => this.setState({ callLoading: false }),
refreshTableStateInterval
);
}
async raise() {
this.setState({ raiseLoading: true });
try {
await this.state.secretJsClient.execute(this.state.game_address, {
raise: { amount: this.state.raiseAmount },
});
} catch (e) {
console.log("raise", e);
NotificationManager.error("raise", e.message, 5000);
}
setTimeout(
() => this.setState({ raiseLoading: false, raiseAmount: 25000 }),
refreshTableStateInterval
);
}
async rematch() {
this.setState({ rematchLoading: true });
try {
await this.state.secretJsClient.execute(this.state.game_address, {
rematch: {},
});
} catch (e) {
console.log("rematch", e);
NotificationManager.error("rematch", e.message, 5000);
}
setTimeout(
() => this.setState({ rematchLoading: false }),
refreshTableStateInterval
);
}
async withdraw() {
this.setState({ withdrawLoading: true });
try {
await this.state.secretJsClient.execute(this.state.game_address, {
withdraw: {},
});
} catch (e) {
console.log("withdraw", e);
NotificationManager.error("withdraw", e.message, 5000);
}
setTimeout(
() => this.setState({ withdrawLoading: false }),
refreshTableStateInterval
);
}
async deposit() {
this.setState({ depositLoading: true });
try {
await this.state.secretJsClient.execute(
this.state.game_address,
{
top_up: {},
},
"",
[{ amount: `${this.state.depositAmount}`, denom: "uscrt" }]
);
} catch (e) {
console.log("deposit", e);
NotificationManager.error("deposit", e.message, 5000);
}
setTimeout(
() => this.setState({ depositLoading: false, depositAmount: 0 }),
refreshTableStateInterval
);
}
getMe() {
if (!this.state.myWalletAddress) {
return null;
}
if (this.state.myWalletAddress === this.state.player_a) {
return {
player: "A",
address: this.state.player_a,
bet: this.state.player_a_bet,
wallet: this.state.player_a_wallet,
wants_rematch: this.state.player_a_wants_rematch,
};
}
if (this.state.myWalletAddress === this.state.player_b) {
return {
player: "B",
address: this.state.player_b,
bet: this.state.player_b_bet,
wallet: this.state.player_b_wallet,
wants_rematch: this.state.player_b_wants_rematch,
};
}
return null;
}
getOther() {
if (!this.state.myWalletAddress) {
return null;
}
if (this.state.myWalletAddress !== this.state.player_a) {
return {
player: "A",
address: this.state.player_a,
bet: this.state.player_a_bet,
wallet: this.state.player_a_wallet,
wants_rematch: this.state.player_a_wants_rematch,
};
}
if (this.state.myWalletAddress !== this.state.player_b) {
return {
player: "B",
address: this.state.player_b,
bet: this.state.player_b_bet,
wallet: this.state.player_b_wallet,
wants_rematch: this.state.player_b_wants_rematch,
};
}
return null;
}
render() {
if (window.location.hash === "") {
return (
<div style={{ color: "white" }}>
<Table>
{/* wallet */}
<div
style={{
position: "absolute",
top: 0,
left: 0,
padding: 10,
}}
>
<div
style={{
position: "relative",
zIndex: 9999,
}}
>
You: {this.state.myWalletAddress} {this.state.myWalletBalance}
</div>
</div>
<div
style={{
position: "relative",
zIndex: 9999,
}}
>
<div
style={{
textAlign: "center",
}}
>
<Form.Input
placeholder="Room name"
value={this.state.new_room_name}
onChange={(_, { value }) =>
this.setState({ new_room_name: value })
}
/>
<Button
loading={this.state.createLoading}
disabled={this.state.createLoading}
onClick={this.createRoom.bind(this)}
>
Create!
</Button>
</div>
<br />
<center>
<table>
<thead>
<tr>
<th>Room Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.all_rooms.map((r, i) => (
<tr key={i}>
<td>{r.label}</td>
<td>
<a href={"#" + r.address}>{r.address}</a>
</td>
</tr>
))}
</tbody>
</table>
</center>
</div>
</Table>
<NotificationContainer />
</div>
);
}
const handA = this.state.player_a_hand
.concat(this.state.community_cards)
.map(stateCardToPokerSoverCard)
.filter((x) => x);
let rankHandA = "Unknown";
if (handA.length > 5 || (this.getMe() && this.getMe().player === "A")) {
try {
const solve = PokerSolver.solve(handA);
rankHandA = solve.descr;
} catch (e) {}
}
const handB = this.state.player_b_hand
.concat(this.state.community_cards)
.map(stateCardToPokerSoverCard)
.filter((x) => x);
let rankHandB = "Unknown";
if (handB.length > 5 || (this.getMe() && this.getMe().player === "B")) {
try {
const solve = PokerSolver.solve(handB);
rankHandB = solve.descr;
} catch (e) {}
}
let stage = this.state.stage;
if (stage.includes("EndedWinner")) {
const winner = stage.replace("EndedWinner", "");
stage = (
<span>
<div>
<b>Player {winner} Wins!</b>
</div>
{typeof this.state.last_play === "string" &&
!this.state.last_play.includes("fold") ? (
rankHandA !== rankHandB ? (
<div>
<b>{winner === "A" ? rankHandA : rankHandB}</b> vs. a lousy{" "}
<b>{winner === "A" ? rankHandB : rankHandA}</b>
</div>
) : (
<div>
Both with <b>{rankHandA}</b>, {winner} won with a kicker!
</div>
)
) : null}
</span>
);
} else if (stage.includes("EndedDraw")) {
stage = `It's a Tie of ${rankHandA}!`;
} else if (stage === "WaitingForPlayersToJoin") {
const isLoading =
this.state.joinLoading ||
!!this.getMe() ||
!!(
this.state.myWalletBalance &&
typeof this.state.myWalletBalance === "string" &&
!this.state.myWalletBalance.includes("SCRT")
);
stage = (
<span>
<div>Waiting for players</div>
<div>
<Button
loading={isLoading}
disabled={
isLoading ||
this.state.myWalletBalanceUscrt === 0 ||
this.state.depositAmount === 0
}
onClick={this.joinRoom.bind(this)}
>
Join and Deposit
{` (${nf.format(
this.state.depositAmount / 1000000
)} SCRT = ${nf.format(this.state.depositAmount)} credits)`}
</Button>
<center hidden={isLoading || this.state.myWalletBalanceUscrt === 0}>
<Slider
style={{ width: "400px" }}
min={
this.state.myWalletBalanceUscrt === 0
? 0
: MIN_TABLE_BIG_BLINDS * BIG_BLIND
}
value={this.state.depositAmount}
max={Math.min(
this.state.myWalletBalanceUscrt,
MAX_TABLE_BIG_BLINDS * BIG_BLIND
)}
onChange={(v) => this.setState({ depositAmount: v })}
/>
</center>
</div>
</span>
);
} else if (stage) {
stage += " betting round";
}
let turn = "Player A";
let turnDirection = "->";
let lastPlay = this.state.last_play || "";
if (this.state.turn === this.state.player_b) {
turn = "Player B";
turnDirection = "<-";
}
turn = "Turn: " + turn;
if (
!this.state.stage ||
!this.state.turn ||
this.state.stage.includes("Ended") ||
this.state.stage.includes("Waiting")
) {
turn = "";
turnDirection = "";
lastPlay = "";
}
if (typeof this.state.last_play === "string") {
if (this.state.last_play.includes("fold")) {
lastPlay = this.state.last_play;
} else if (this.state.last_play.includes("raised")) {
try {
const amount = +this.state.last_play.match(/\d+/g)[0];
lastPlay = this.state.last_play.replace(
`${amount}`,
nf.format(amount)
);
} catch (e) {}
}
}
let rematch = null;
if (
typeof this.state.stage === "string" &&
this.state.stage.includes("Ended")
) {
rematch = (
<div>
{this.getMe() && this.getOther() ? (
<Button
loading={this.state.rematchLoading || this.getMe().wants_rematch}
onClick={this.rematch.bind(this)}
disabled={
this.state.rematchLoading ||
this.getMe().wallet === 0 ||
this.getOther().wallet === 0 ||
this.getMe().wants_rematch
}
>
Rematch!
</Button>
) : null}
{this.state.player_a_wants_rematch ? (
<div style={{ padding: 10 }}>Rematch: Waiting for player B.</div>
) : null}
{this.state.player_b_wants_rematch ? (
<div style={{ padding: 10 }}>Rematch: Waiting for player A.</div>
) : null}
</div>
);
}
let room = "";
if (this.state.game_address) {
room = "Room: " + this.state.game_address;
}
let minDeposit = 0;
let maxDeposit = 0;
if (this.getMe()) {
const alreadyInside = this.getMe().wallet + this.getMe().bet;
maxDeposit = BIG_BLIND * MAX_TABLE_BIG_BLINDS - alreadyInside;
maxDeposit = Math.max(maxDeposit, 0);
minDeposit = BIG_BLIND * MIN_TABLE_BIG_BLINDS - alreadyInside;
minDeposit = Math.max(minDeposit, 0);
}
return (
<div style={{ color: "white" }}>
<Table>
{/* wallet + scoreboard */}
<div
style={{
position: "absolute",
top: 0,
left: 0,
padding: 10,
}}
>
<div style={{ width: "700px" }}>
<div
style={{
position: "relative",
zIndex: 9999,
}}
>
You: {this.state.myWalletAddress} {this.state.myWalletBalance}
</div>
<div>
<Button
loading={this.state.withdrawLoading}
onClick={this.withdraw.bind(this)}
disabled={
this.state.withdrawLoading ||
!this.getMe() ||
this.getMe().wallet === 0
}
>
{!this.state.stage.includes("Ended") &&
!this.state.stage.includes("Waiting")
? "Fold + "
: ""}
Withdraw
{this.getMe()
? ` (${nf.format(this.getMe().wallet / 1000000)} SCRT)`
: ""}
</Button>
<Button
loading={this.state.depositLoading}
onClick={this.deposit.bind(this)}
disabled={
this.state.depositLoading ||
this.state.depositAmount === 0 ||
!this.getMe()
}
>
Deposit
{this.getMe()
? ` (${nf.format(
this.state.depositAmount / 1000000
)} SCRT = ${nf.format(this.state.depositAmount)} credits)`
: ""}
</Button>
<div hidden={!this.getMe() || minDeposit >= maxDeposit}>
<Slider
style={{ width: "400px" }}
min={minDeposit}
value={this.state.depositAmount}
max={maxDeposit}
onChange={(v) => this.setState({ depositAmount: v })}
/>
</div>
</div>
</div>
<div
style={{
marginTop: 30,
position: "relative",
zIndex: 9999,
}}
>
<table>
<thead>
<tr>
<td>
<center>Wins:</center>
</td>
</tr>
</thead>
<tbody>
<tr>
<th>Player A</th>
<td>{this.state.player_a_win_counter}</td>
</tr>
<tr>
<th>Player B</th>
<td>{this.state.player_b_win_counter}</td>
</tr>
<tr>
<th>Ties</th>
<td>{this.state.tie_counter}</td>
</tr>
</tbody>
</table>
</div>
</div>
{/* return to lobby */}
<div
style={{
position: "absolute",
top: 0,
right: 15,
padding: 10,
}}
>
<a
style={{
position: "relative",
zIndex: 9999,
}}
href="/#"
>
Return to lobby
</a>
</div>
{/* community cards */}
<div
style={{ position: "absolute", width: "100%", textAlign: "center" }}
>
<div
style={{
position: "relative",
zIndex: 9999,
}}
>
<div>{room}</div>
<div>{stage}</div>
<div>{turn}</div>
<div>{turnDirection}</div>
<br />
{this.state.community_cards.map((c, i) =>
stateCardToReactCard(c, true, i)
)}
<div style={{ padding: 35, textAlign: "center" }}>
<span style={{ marginRight: 125 }}>
B's Total Bet: {nf.format(this.state.player_b_bet)}
</span>
<span style={{ marginLeft: 125 }}>
A's Total Bet: {nf.format(this.state.player_a_bet)}
</span>
</div>
<div
hidden={!lastPlay}
style={{ padding: 35, textAlign: "center" }}
>
{lastPlay}
</div>
<div
hidden={!rematch}
style={{ padding: 35, textAlign: "center" }}
>
{rematch}
</div>
</div>
</div>
{/* player a */}
<div
style={{
position: "absolute",
bottom: 0,
right: 0,
padding: 10,
textAlign: "center",
}}
>
{turn.includes("Player A") ? (
<div className="ui active inline loader" />
) : null}
<div>
Player A
{this.state.player_a === this.state.myWalletAddress
? " (You)"
: ""}
</div>
<div>
Hand: <b>{rankHandA}</b>
</div>
<div>Credits left: {nf.format(this.state.player_a_wallet)}</div>
<div>{this.state.player_a}</div>
</div>
<Hand
style={{ position: "absolute", right: "35vw" }}
cards={this.state.player_a_hand.map((c) => stateCardToReactCard(c))}
/>
{/* controls */}
<div
style={{
position: "fixed",
bottom: 0,
padding: 10,
width: "100%",
textAlign: "center",
zIndex: 999,
}}
hidden={
!this.getMe() ||
this.state.stage.includes("Ended") ||
this.state.stage.includes("Waiting")
}
>
<Button
loading={this.state.checkLoading}
onClick={this.check.bind(this)}
disabled={
this.state.player_a_bet !== this.state.player_b_bet ||
!this.state.turn ||
this.state.turn !== this.state.myWalletAddress ||
this.state.stage.includes("Ended") ||
this.state.stage.includes("Waiting") ||
this.state.callLoading ||
this.state.raiseLoading ||
this.state.foldLoading ||
this.state.checkLoading
}
>
Check
</Button>
<Button
loading={this.state.callLoading}
onClick={this.call.bind(this)}
disabled={
this.state.player_a_bet === this.state.player_b_bet ||
!this.state.turn ||
this.state.turn !== this.state.myWalletAddress ||
this.state.stage.includes("Ended") ||
this.state.stage.includes("Waiting") ||
this.state.callLoading ||
this.state.raiseLoading ||
this.state.foldLoading ||
this.state.checkLoading
}
>
Call
</Button>
<Button
loading={this.state.raiseLoading}
onClick={this.raise.bind(this)}
disabled={
!this.state.turn ||
this.state.turn !== this.state.myWalletAddress ||
this.state.stage.includes("Ended") ||
this.state.stage.includes("Waiting") ||
this.state.callLoading ||
this.state.raiseLoading ||
this.state.foldLoading ||
this.state.checkLoading ||
this.state.raiseAmount <= 0
}
>
{this.getMe() &&
this.getOther() &&
this.state.raiseAmount + this.getOther().bet ===
this.getMe().wallet + this.getMe().bet
? "All in!"
: `${
this.getMe() &&
this.getOther() &&
this.getMe().bet === 0 &&
this.getOther().bet === 0
? "Bet"
: "Raise"
} ${nf.format(this.state.raiseAmount)}`}
</Button>
<Button
loading={this.state.foldLoading}
onClick={this.fold.bind(this)}
disabled={
!this.state.turn ||
this.state.turn !== this.state.myWalletAddress ||
this.state.stage.includes("Ended") ||
this.state.stage.includes("Waiting") ||
this.state.callLoading ||
this.state.raiseLoading ||
this.state.foldLoading ||
this.state.checkLoading
}
>
Fold
</Button>
<center>
<div style={{ padding: 10, width: "300px" }}>
<Slider
min={0}
value={this.state.raiseAmount}
max={
this.getOther() && this.getMe()
? Math.min(
this.getOther().wallet,
this.getMe().wallet -
(this.getOther().bet - this.getMe().bet)
)
: 0
}
onChange={(v) => this.setState({ raiseAmount: v })}
/>
</div>
</center>
</div>
{/* player b */}
<div
style={{
position: "absolute",
bottom: 0,
left: 0,
padding: 10,
textAlign: "center",
}}
>
{turn.includes("Player B") ? (
<div className="ui active inline loader" />
) : null}
<div>
Player B{" "}
{this.state.player_b === this.state.myWalletAddress
? " (You)"
: ""}
</div>
<div>
Hand: <b>{rankHandB}</b>
</div>
<div>Credits left: {nf.format(this.state.player_b_wallet)}</div>
<div>{this.state.player_b}</div>
</div>
<Hand
style={{ position: "absolute", left: "23vw" }}
cards={this.state.player_b_hand.map((c) => stateCardToReactCard(c))}
/>
</Table>
<NotificationContainer />
</div>
);
}
}
function stateCardToReactCard(c, component = false, index) {
if (!c.value || !c.suit) {
if (component) {
return <Card key={index} />;
} else {
return {};
}
}
let suit = {
Spade: "S",
Club: "C",
Heart: "H",
Diamond: "D",
}[c.suit];
let face = {
Two: "2",
Three: "3",
Four: "4",
Five: "5",
Six: "6",
Seven: "7",
Eight: "8",
Nine: "9",
Ten: "T",
Jack: "J",
Queen: "Q",
King: "K",
Ace: "A",
}[c.value];
if (component) {
return <Card key={index} face={face} suit={suit} />;
} else {
return { face, suit };
}
}
function stateCardToPokerSoverCard(c) {
if (!c.value || !c.suit) {
return null;
}
let type = {
Spade: "s",
Club: "c",
Heart: "h",
Diamond: "d",
}[c.suit];
let rank = {
Two: "2",
Three: "3",
Four: "4",
Five: "5",
Six: "6",
Seven: "7",
Eight: "8",
Nine: "9",
Ten: "T",
Jack: "J",
Queen: "Q",
King: "K",
Ace: "A",
}[c.value];
return rank + type;
}
export default App;
<file_sep>#!/bin/bash
set -ve
CODE_ID=$(
secretcli tx compute store contract.wasm.gz --from 1 -y --gas 10000000 -b block |
jq -r '.logs[].events[].attributes[] | select(.key == "code_id") | .value'
)
CONTRACT=$(
secretcli tx compute instantiate "$CODE_ID" "{}" --from 1 --label test -y -b block |
jq -r '.logs[].events[].attributes[] | select(.key == "contract_address") | .value'
)
secretcli tx compute execute "$CONTRACT" '{"join":{"secret":123}}' --from 1 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq -r .output_data |
base64 -d
secretcli tx compute execute "$CONTRACT" '{"join":{"secret":234}}' --from 3 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq -r .output_data |
base64 -d
# Player A Hand:
secretcli q compute contract-state smart "$CONTRACT" '{"get_my_hand":{"secret":123}}'
# Player B Hand:
secretcli q compute contract-state smart "$CONTRACT" '{"get_my_hand":{"secret":234}}'
# Table:
secretcli q compute contract-state smart "$CONTRACT" '{"get_public_data":{}}' | jq .
# A checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 1 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# B checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 3 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# Table:
secretcli q compute contract-state smart "$CONTRACT" '{"get_public_data":{}}' | jq .
# A checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 1 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# B checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 3 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# Table:
secretcli q compute contract-state smart "$CONTRACT" '{"get_public_data":{}}' | jq .
# A checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 1 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# B checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 3 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# Table:
secretcli q compute contract-state smart "$CONTRACT" '{"get_public_data":{}}' | jq .
# A checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 1 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# B checks
secretcli tx compute execute "$CONTRACT" '{"check":{}}' --from 3 -b block -y |
jq .txhash |
xargs secretcli q compute tx |
jq .
# Table:
secretcli q compute contract-state smart "$CONTRACT" '{"get_public_data":{}}' | jq .<file_sep>use cosmwasm_std::{
Api, BankMsg, Binary, Coin, CosmosMsg, Env, Extern, HandleResponse, HandleResult, HumanAddr,
InitResponse, InitResult, Querier, QueryResult, StdError, StdResult, Storage, Uint128,
};
use rand::{seq::SliceRandom, SeedableRng};
use rand_chacha::ChaChaRng;
use rs_poker::core::{Card, Deck, Rankable};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json_wasm as serde_json;
use sha2::{Digest, Sha256};
#[derive(Serialize, Deserialize, Clone)]
struct Table {
game_counter: u64,
player_a: Option<HumanAddr>,
player_a_wallet: i64,
player_a_bet: u64,
player_b: Option<HumanAddr>,
player_b_wallet: i64,
player_b_bet: u64,
starter: Option<HumanAddr>,
turn: Option<HumanAddr>, // round ends if after a bet: starter != turn && player_a_bet == player_b_bet or if someone called
last_play: Option<String>,
stage: Stage,
community_cards: Vec<Card>,
player_a_hand: Vec<Card>,
player_b_hand: Vec<Card>,
player_a_wants_rematch: bool,
player_b_wants_rematch: bool,
player_a_win_counter: u64,
player_b_win_counter: u64,
tie_counter: u64,
max_credit: u64,
min_credit: u64,
big_blind: u64,
}
// struct Player {
// address: Option<HumanAddr>,
// position: u8,
// wallet: u128,
// current_bet: i64
// }
/////////////////////////////// Init ///////////////////////////////
//
////////////////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InitMsg {
CreateRoom { big_blind: u64 },
}
pub fn init<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
_env: Env,
msg: InitMsg,
) -> InitResult {
match msg {
InitMsg::CreateRoom { big_blind } => {
let table = Table {
game_counter: 0,
player_a: None,
player_b: None,
player_a_wallet: 0,
player_b_wallet: 0,
player_a_bet: 0,
player_b_bet: 0,
stage: Stage::WaitingForPlayersToJoin,
starter: None,
turn: None,
last_play: None,
community_cards: vec![],
player_a_hand: vec![],
player_b_hand: vec![],
player_a_wants_rematch: false,
player_b_wants_rematch: false,
player_a_win_counter: 0,
player_b_win_counter: 0,
tie_counter: 0,
max_credit: big_blind * MAX_TABLE_BIG_BLINDS,
min_credit: big_blind * MIN_TABLE_BIG_BLINDS,
big_blind,
};
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(InitResponse::default())
}
}
}
/////////////////////////////// Handle ///////////////////////////////
//
//////////////////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
#[repr(u8)]
enum Stage {
WaitingForPlayersToJoin,
PreFlop,
Flop,
Turn,
River,
EndedWinnerA,
EndedWinnerB,
EndedDraw,
}
impl Stage {
fn no_more_action(&self) -> bool {
match &self {
Self::EndedWinnerA
| Self::EndedWinnerB
| Self::EndedDraw
| Self::WaitingForPlayersToJoin => true,
_ => false,
}
}
fn next_round(&self) -> Self {
match &self {
Self::PreFlop => Self::Flop,
Self::Flop => Self::Turn,
Self::Turn => Self::River,
_ => Self::PreFlop,
}
}
}
const MAX_TABLE_BIG_BLINDS: u64 = 100;
const MIN_TABLE_BIG_BLINDS: u64 = 20;
// indexes of cards in the deck
const PLAYER_A_FIRST_CARD: usize = 0;
const PLAYER_B_FIRST_CARD: usize = 1;
const PLAYER_A_SECOND_CARD: usize = 2;
const PLAYER_B_SECOND_CARD: usize = 3;
// Pre-flop betting round - burn index 4
const FLOP_FIRST_CARD: usize = 5;
const FLOP_SECOND_CARD: usize = 6;
const FLOP_THIRD_CARD: usize = 7;
// Flop betting round - burn index 8
const TURN_CARD: usize = 9;
// Turn betting round - burn index 10
const RIVER_CARD: usize = 11;
// River betting round
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HandleMsg {
Join { secret: u64 },
Raise { amount: u64 },
Call {},
Fold {},
Check {},
Rematch {},
Withdraw {},
TopUp {},
}
pub fn winner_winner_chicken_dinner(
contract_address: HumanAddr,
player: HumanAddr,
amount: Uint128,
) -> HandleResponse {
HandleResponse {
messages: vec![CosmosMsg::Bank(BankMsg::Send {
from_address: contract_address,
to_address: player,
amount: vec![Coin {
denom: "uscrt".to_string(),
amount,
}],
})],
log: vec![],
data: None,
}
}
fn can_deposit(env: &Env, table: &Table, current_amount: u64) -> StdResult<i64> {
let deposit: Uint128;
if env.message.sent_funds.len() == 0 {
return Err(StdError::generic_err("SHOW ME THE MONEY"));
} else {
if env.message.sent_funds[0].denom != "uscrt" {
return Err(StdError::generic_err("WRONG MONEY"));
}
deposit = env.message.sent_funds[0].amount;
if deposit.u128() as u64 + current_amount < table.min_credit {
return Err(StdError::generic_err("GTFO DIRTY SHORT STACKER"));
}
if deposit.u128() as u64 + current_amount > table.max_credit {
return Err(StdError::generic_err("GTFO DIRTY DEEP STACKER"));
}
}
Ok(deposit.u128() as i64)
}
pub fn handle<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
msg: HandleMsg,
) -> HandleResult {
return match msg {
HandleMsg::TopUp {} => {
let me = Some(env.message.sender.clone());
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if me == table.player_b {
let deposit = can_deposit(&env, &table, table.player_b_wallet as u64)?;
table.player_b_wallet += deposit;
} else if me == table.player_a {
let deposit = can_deposit(&env, &table, table.player_a_wallet as u64)?;
table.player_a_wallet += deposit;
} else {
return Err(StdError::generic_err(
"You are not a player, or you are broke! Either way, go away!",
));
}
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
HandleMsg::Withdraw {} => {
let player_name = Some(env.message.sender.clone());
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if player_name == table.player_b && table.player_b_wallet != 0 {
//fold player b
if !table.stage.no_more_action() {
table.stage = Stage::EndedWinnerA;
table.player_a_wallet += (table.player_a_bet + table.player_b_bet) as i64;
table.player_a_bet = 0;
table.player_b_bet = 0;
table.player_a_win_counter += 1;
table.last_play = Some(String::from("Player B folded"));
}
let amount = table.player_b_wallet;
table.player_b_wallet = 0;
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
return Ok(winner_winner_chicken_dinner(
env.contract.address,
player_name.unwrap(),
Uint128(amount as u128),
));
} else if player_name == table.player_a && table.player_a_wallet != 0 {
//fold player a
if !table.stage.no_more_action() {
table.stage = Stage::EndedWinnerB;
table.player_b_wallet += (table.player_a_bet + table.player_b_bet) as i64;
table.player_a_bet = 0;
table.player_b_bet = 0;
table.player_b_win_counter += 1;
table.last_play = Some(String::from("Player A folded"));
}
let amount = table.player_a_wallet;
table.player_a_wallet = 0;
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
return Ok(winner_winner_chicken_dinner(
env.contract.address,
player_name.unwrap(),
Uint128(amount as u128),
));
}
Err(StdError::generic_err(
"You are not a player, or you are broke! Either way, go away!",
))
}
HandleMsg::Join { secret } => {
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
let deposit = can_deposit(&env, &table, 0)?;
if table.player_a.is_some() && table.player_b.is_some() {
return Err(StdError::generic_err("Table is full."));
}
let player_secret = &secret.to_be_bytes();
if table.player_a.is_none() {
// player a - just store
deps.storage.set(b"player_a_secret", player_secret);
table.player_a = Some(env.message.sender.clone());
table.player_a_wallet = deposit;
table.starter = Some(env.message.sender.clone());
table.turn = Some(env.message.sender.clone());
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
return Ok(HandleResponse::default());
}
// player b - we can now shuffle the deck
deps.storage.set(b"player_b_secret", player_secret);
let player_a_secret = deps.storage.get(b"player_a_secret").unwrap();
let mut combined_secret = player_a_secret.clone();
combined_secret.extend(player_secret);
combined_secret.extend(&(0 as u64).to_be_bytes()); // game counter
let seed: [u8; 32] = Sha256::digest(&combined_secret).into();
let mut rng = ChaChaRng::from_seed(seed);
let mut deck: Vec<Card> = Deck::default().into_iter().collect();
deck.shuffle(&mut rng);
deps.storage
.set(b"deck", &serde_json::to_vec(&deck).unwrap());
table.player_b = Some(env.message.sender.clone());
table.player_b_wallet = deposit;
table.stage = table.stage.next_round();
table.starter = table.player_a.clone();
table.turn = table.player_a.clone();
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
HandleMsg::Raise { amount } => {
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if table.stage.no_more_action() {
return Err(StdError::generic_err("Action hasn't started yet"));
}
let me = Some(env.message.sender.clone());
if me != table.player_a && me != table.player_b {
return Err(StdError::generic_err("You are not a player, go away!"));
}
if me != table.turn {
return Err(StdError::generic_err("It's not your turn."));
}
if me == table.player_a {
if table.player_a_wallet < amount as i64 {
return Err(StdError::generic_err(
"You cannot raise more than you have!",
));
}
// I'm player A
table.player_a_wallet -= (table.player_b_bet + amount - table.player_a_bet) as i64;
if table.player_a_wallet < 0 {
return Err(StdError::generic_err(
"You don't have enough credits to raise by that much.",
));
}
table.player_a_bet = table.player_b_bet + amount;
table.last_play = Some(String::from(format!(
"Player A raised by {} credits",
amount
)));
table.turn = table.player_b.clone();
} else {
// I'm player B
if table.player_b_wallet < amount as i64 {
return Err(StdError::generic_err(
"You cannot raise more than you have!",
));
}
table.player_b_wallet -= (table.player_a_bet + amount - table.player_b_bet) as i64;
if table.player_b_wallet < 0 {
return Err(StdError::generic_err(
"You don't have enough credits to raise by that much.",
));
}
table.player_b_bet = table.player_a_bet + amount;
table.last_play = Some(String::from(format!(
"Player B raised by {} credits",
amount
)));
table.turn = table.player_a.clone();
}
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
HandleMsg::Call {} => {
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if table.stage.no_more_action() {
return Err(StdError::generic_err("Action hasn't started yet"));
}
let me = Some(env.message.sender.clone());
if me != table.player_a && me != table.player_b {
return Err(StdError::generic_err("You are not a player, go away!"));
}
if me != table.turn {
return Err(StdError::generic_err("It's not your turn."));
}
if me == table.player_a {
// I'm player A
table.player_a_wallet -= (table.player_b_bet - table.player_a_bet) as i64;
if table.player_a_wallet < 0 {
return Err(StdError::generic_err(
"You cannot Call, your bet is bigger or equals to the other player's bet.",
));
}
table.player_a_bet = table.player_b_bet;
table.last_play = Some(String::from("Player A called"));
} else {
// I'm player B
table.player_b_wallet -= (table.player_a_bet - table.player_b_bet) as i64;
if table.player_b_wallet < 0 {
return Err(StdError::generic_err(
"You cannot Call, your bet is bigger or equals to the other player's bet.",
));
}
table.player_b_bet = table.player_a_bet;
table.last_play = Some(String::from("Player B called"));
}
table.turn = table.player_a.clone();
table.goto_next_stage(deps);
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
HandleMsg::Fold {} => {
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if table.stage.no_more_action() {
return Err(StdError::generic_err("Action hasn't started yet"));
}
let me = Some(env.message.sender.clone());
if me != table.player_a && me != table.player_b {
return Err(StdError::generic_err("You are not a player, go away!"));
}
if me != table.turn {
return Err(StdError::generic_err("It's not your turn."));
}
if me == table.player_a {
table.stage = Stage::EndedWinnerB;
table.player_b_wallet += (table.player_a_bet + table.player_b_bet) as i64;
table.player_b_win_counter += 1;
table.last_play = Some(String::from("Player A folded"));
} else {
table.stage = Stage::EndedWinnerA;
table.player_a_wallet += (table.player_a_bet + table.player_b_bet) as i64;
table.player_a_win_counter += 1;
table.last_play = Some(String::from("Player B folded"));
}
table.player_a_bet = 0;
table.player_b_bet = 0;
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
HandleMsg::Check {} => {
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if table.stage.no_more_action() {
return Err(StdError::generic_err("Action hasn't started yet"));
}
let me = Some(env.message.sender.clone());
if me != table.player_a && me != table.player_b {
return Err(StdError::generic_err("You are not a player, go away!"));
}
if me != table.turn {
return Err(StdError::generic_err("It's not your turn."));
}
if table.player_a_bet != table.player_b_bet {
return Err(StdError::generic_err(
"You cannot check, must Call, Raise or Fold.",
));
}
if me == table.player_a {
table.last_play = Some(String::from("Player A checked"));
table.turn = table.player_b.clone();
} else {
table.last_play = Some(String::from("Player B checked"));
table.turn = table.player_a.clone();
}
if table.turn == table.starter {
table.goto_next_stage(deps);
}
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
HandleMsg::Rematch {} => {
let mut table: Table =
serde_json::from_slice(&deps.storage.get(b"table").unwrap()).unwrap();
if !table.stage.no_more_action() {
return Err(StdError::generic_err("You can't start a new game now!"));
}
let me = Some(env.message.sender.clone());
if me != table.player_a && me != table.player_b {
return Err(StdError::generic_err("You are not a player, go away!"));
}
if table.player_b_wallet == 0 || table.player_a_wallet == 0 {
return Err(StdError::generic_err(
"One of the players must deposit to continue playing",
));
}
if me == table.player_a {
table.player_a_wants_rematch = true;
} else {
table.player_b_wants_rematch = true;
}
if !table.player_b_wants_rematch || !table.player_a_wants_rematch {
// not everyone approved a rematch yet
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
return Ok(HandleResponse::default());
}
table.game_counter += 1;
let player_a_secret = deps.storage.get(b"player_a_secret").unwrap();
let player_b_secret = deps.storage.get(b"player_b_secret").unwrap();
let mut combined_secret = player_a_secret.clone();
combined_secret.extend(player_b_secret);
combined_secret.extend(&table.game_counter.to_be_bytes()); // game counter
let seed: [u8; 32] = Sha256::digest(&combined_secret).into();
let mut rng = ChaChaRng::from_seed(seed);
let mut deck: Vec<Card> = Deck::default().into_iter().collect();
deck.shuffle(&mut rng);
deps.storage
.set(b"deck", &serde_json::to_vec(&deck).unwrap());
table.stage = Stage::PreFlop;
table.turn = table.starter.clone();
table.last_play = None;
table.community_cards = vec![];
table.player_a_bet = 0;
table.player_b_bet = 0;
table.player_a_hand = vec![];
table.player_b_hand = vec![];
table.player_a_wants_rematch = false;
table.player_b_wants_rematch = false;
deps.storage
.set(b"table", &serde_json::to_vec(&table).unwrap());
Ok(HandleResponse::default())
}
};
}
impl Table {
fn goto_next_stage<S: Storage, A: Api, Q: Querier>(&mut self, deps: &mut Extern<S, A, Q>) {
let deck: Vec<Card> = serde_json::from_slice(&deps.storage.get(b"deck").unwrap()).unwrap();
match self.stage {
Stage::PreFlop => {
self.stage = Stage::Flop;
self.community_cards = vec![
deck[FLOP_FIRST_CARD],
deck[FLOP_SECOND_CARD],
deck[FLOP_THIRD_CARD],
];
}
Stage::Flop => {
self.stage = Stage::Turn;
self.community_cards = vec![
deck[FLOP_FIRST_CARD],
deck[FLOP_SECOND_CARD],
deck[FLOP_THIRD_CARD],
deck[TURN_CARD],
];
}
Stage::Turn => {
self.stage = Stage::River;
self.community_cards = vec![
deck[FLOP_FIRST_CARD],
deck[FLOP_SECOND_CARD],
deck[FLOP_THIRD_CARD],
deck[TURN_CARD],
deck[RIVER_CARD],
];
}
Stage::River => {
let mut player_a_7_card_hand = self.community_cards.clone();
player_a_7_card_hand
.extend(vec![deck[PLAYER_A_FIRST_CARD], deck[PLAYER_A_SECOND_CARD]]);
let player_a_rank = player_a_7_card_hand.rank();
let mut player_b_7_card_hand = self.community_cards.clone();
player_b_7_card_hand
.extend(vec![deck[PLAYER_B_FIRST_CARD], deck[PLAYER_B_SECOND_CARD]]);
let player_b_rank = player_b_7_card_hand.rank();
if player_a_rank > player_b_rank {
self.stage = Stage::EndedWinnerA;
self.player_a_wallet += (self.player_a_bet + self.player_b_bet) as i64;
self.player_a_win_counter += 1;
} else if player_a_rank < player_b_rank {
self.stage = Stage::EndedWinnerB;
self.player_b_wallet += (self.player_a_bet + self.player_b_bet) as i64;
self.player_b_win_counter += 1;
} else {
self.stage = Stage::EndedDraw;
self.player_a_wallet += (self.player_a_bet) as i64;
self.player_b_wallet += (self.player_b_bet) as i64;
self.tie_counter += 1;
}
self.player_a_bet = 0;
self.player_b_bet = 0;
self.player_a_hand = vec![deck[PLAYER_A_FIRST_CARD], deck[PLAYER_A_SECOND_CARD]];
self.player_b_hand = vec![deck[PLAYER_B_FIRST_CARD], deck[PLAYER_B_SECOND_CARD]];
return;
}
Stage::WaitingForPlayersToJoin => {
return;
}
Stage::EndedWinnerA => {
return;
}
Stage::EndedWinnerB => {
return;
}
Stage::EndedDraw => {
return;
}
}
// Turn ended with both player out of cash, just play it out
if self.player_a_wallet == 0 || self.player_b_wallet == 0 {
while self.stage != Stage::EndedDraw
&& self.stage != Stage::EndedWinnerA
&& self.stage != Stage::EndedWinnerB
{
self.goto_next_stage(deps);
}
return;
}
}
}
/////////////////////////////// Query ///////////////////////////////
// These are getters, we only return what's public
// player get their private information as a response to txs (handle)
///////////////////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
GetMyHand { secret: u64 },
GetPublicData {},
}
pub fn query<S: Storage, A: Api, Q: Querier>(deps: &Extern<S, A, Q>, msg: QueryMsg) -> QueryResult {
match msg {
QueryMsg::GetPublicData {} => {
return Ok(Binary(deps.storage.get(b"table").unwrap()));
}
QueryMsg::GetMyHand { secret } => {
let secret_bytes = secret.to_be_bytes().to_vec();
let player_a_secret = match deps.storage.get(b"player_a_secret") {
None => {
return Err(StdError::generic_err(
"You are not a player, but there are still two seats left.",
))
}
Some(x) => x,
};
let player_b_secret = match deps.storage.get(b"player_b_secret") {
None => {
return Err(StdError::generic_err(
"You are not a player, but there is still one seat left.",
))
}
Some(x) => x,
};
let first_card_index;
let second_card_index;
if secret_bytes == player_a_secret {
first_card_index = PLAYER_A_FIRST_CARD;
second_card_index = PLAYER_A_SECOND_CARD;
} else if secret_bytes == player_b_secret {
first_card_index = PLAYER_B_FIRST_CARD;
second_card_index = PLAYER_B_SECOND_CARD;
} else {
return Err(StdError::generic_err("You are not a player, go away!"));
}
let deck: Vec<Card> =
serde_json::from_slice(&deps.storage.get(b"deck").unwrap()).unwrap();
let first_card: Card = deck[first_card_index];
let second_card: Card = deck[second_card_index];
return Ok(Binary(
serde_json::to_vec(&vec![first_card, second_card]).unwrap(),
));
}
}
}
| 4fdd0c04972b5ad3b918894fb141693571f40885 | [
"Markdown",
"JavaScript",
"Makefile",
"Rust",
"Shell"
] | 5 | Markdown | lindlof/SecretHoldEm | 3b8043e8bc0661a7ead1274bdf802f0b10bda4f5 | 7ea5990461b230392982c3d1d5c213de3727987d |
refs/heads/master | <file_sep>//
// ViewController.swift
// CarAppIOS2
//
// Created by <NAME> on 5/8/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var carImages: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func button1(_ sender: UIButton) {
carImages.image = UIImage(named: "Car 1.jpeg")
}
@IBAction func button2(_ sender: UIButton) {
carImages.image = UIImage(named: "Car 2.jpeg")
}
@IBAction func button3(_ sender: UIButton) {
carImages.image = UIImage(named: "Car 3.png")
}
@IBAction func button4(_ sender: UIButton) {
carImages.image = UIImage(named: "Car 4.jpg")
}
@IBAction func button5(_ sender: UIButton) {
carImages.image = UIImage(named: "Car 5.jpeg")
}
}
| 9660a958382e74130ea9a5e60d2b5e8a38fa447a | [
"Swift"
] | 1 | Swift | Dylansweaver/CarAppIOS2 | ed130594ceb44c1291801b639c3879df656ca317 | 16d8e42589b66c932519a5034073d1a72c39d4df |
refs/heads/master | <repo_name>troynt/serialize.js<file_sep>/README.md
# Goal
A lightweight $.param to be included in your JS.
# Notes
There are some slight differences between $.param and the function provided here.
decodeURI($.param({a: [1,2,3]})) produces a[]=1&a[]=2&a[]=3
decodeURI(serialize({a: [1,2,3]})) produces a[0]=1&a[1]=2&a[2]=3
<file_sep>/test/test.js
test("serialize()", function() {
var params = {foo:"bar", baz:42, quux:"All your base are belong to us"};
equal( decodeURIComponent(serialize(params)), "foo=bar&baz=42&quux=All+your+base+are+belong+to+us", "simple" );
params = {someName: [1, 2, 3], regularThing: "blah" };
equal( decodeURIComponent(serialize(params)), "someName[0]=1&someName[1]=2&someName[2]=3®ularThing=blah", "with array" );
params = {foo: ["a", "b", "c"]};
equal( decodeURIComponent(serialize(params)), "foo[0]=a&foo[1]=b&foo[2]=c", "with array of strings" );
params = {foo: ["baz", 42, "All your base are belong to us"] };
equal( decodeURIComponent(serialize(params)), "foo[0]=baz&foo[1]=42&foo[2]=All+your+base+are+belong+to+us", "more array" );
params = {foo: { bar: "baz", beep: 42, quux: "All your base are belong to us" } };
equal( decodeURIComponent(serialize(params)), "foo[bar]=baz&foo[beep]=42&foo[quux]=All+your+base+are+belong+to+us", "even more arrays" );
});
test("serialize() Constructed prop values", function() {
expect( 4 );
function Record() {
this.prop = "val";
}
var params = { "test": new String("foo") };
equal( serialize( params, false ), "test=foo", "Do not mistake new String() for a plain object" );
params = { "test": new Number(5) };
equal( serialize( params, false ), "test=5", "Do not mistake new Number() for a plain object" );
params = { "test": new Date() };
ok( serialize( params, false ), "(Non empty string returned) Do not mistake new Date() for a plain object" );
// should allow non-native constructed objects
params = { "test": new Record() };
equal( serialize( params, false ), serialize({ "test": { prop: "val" } }), "Allow non-native constructed objects" );
});
| 28a0b2e5b9b1ee802af32edd72062405607592de | [
"Markdown",
"JavaScript"
] | 2 | Markdown | troynt/serialize.js | a2910f3d08077437c9d4e0d839308625a7c86668 | b37717d3d6f2cabb692d4566feef7aa05d4758c9 |
refs/heads/main | <repo_name>ponaravindb/StudentRecordMaintenance<file_sep>/fileexist.c
#include<stdio.h>
#include<conio.h>
/*
int isFileExists(const char *path)
{
{ // Try to open file FILE
*fp = fopen(path, "rb");
int status = 0; // If file does not exists
if (fp != NULL)
{
status = 1; // File exists hence close file
fclose(fp); }
return status;
}
return 0;
}
<file_sep>/welcomemessage.c
#include<stdio.h>
#include<conio.h>
/*
int main ()
{
//clrscr();
printf("\n\n\n\n\n");
printf("\n\t\t\t **-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
printf("\n\t\t\t =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\n\t\t\t = WELCOME =");
printf("\n\t\t\t = TO =");
printf("\n\t\t\t = Student Record =");
printf("\n\t\t\t = MANAGEMENT =");
printf("\n\t\t\t = SYSTEM =");
printf("\n\t\t\t =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\n\t\t\t **-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
printf("\n\n\n\t\t\t Enter any key to continue.....");
//getch();
return 0;
}
| e3ff48f08a6e59897e5dd31d5f872a6d5be62ed2 | [
"C"
] | 2 | C | ponaravindb/StudentRecordMaintenance | 522bbe8456625d9021c46458bc0a6242001e590e | 4ad0f90014072da2cc2e0fd725b77ca7ce1855ba |
refs/heads/master | <repo_name>felipepessoto/InstaEvent<file_sep>/src/Instaeventos.Web/Controllers/EventController.cs
using Instaeventos.Core;
using Instaeventos.Web.ViewModels;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Instaeventos.Web.Controllers
{
public partial class EventController : Controller
{
public virtual ActionResult Index(int id)
{
using (InstaeventosContext context = new InstaeventosContext())
{
var currentEvent = context.Events.Find(id);
context.SaveChanges();
return View(id);
}
}
public virtual ActionResult Configure(int? id)
{
using (InstaeventosContext context = new InstaeventosContext())
{
var viewModel = id.HasValue ?
context.Events.Where(x => x.Id == id.Value).Select(x => new EventConfigureSave { Name = x.Name, HashTag = x.HashTag, AutomaticApproval = x.AutomaticApproval }).Single() :
new EventConfigureSave();
return View(viewModel);
}
}
[HttpPost]
public virtual ActionResult Configure(int? id, EventConfigureSave data)
{
if (ModelState.IsValid)
{
using (InstaeventosContext context = new InstaeventosContext())
{
var editedEvent = id.HasValue ? context.Events.Find(id.Value) : context.Events.Add(new Event()
{
User = context.Users.Single(x=>x.UserName == User.Identity.Name),
BackgroundUrl = "/Content/Images/1.jpg",
CreatedDate = DateTime.Now,
Enabled = true,
IsPublic = true,
StartDate = new DateTime(2013, 1, 1),
EndDate = new DateTime(2014, 1, 1),
SliderEffect = "normal",
});
editedEvent.Name = data.Name;
editedEvent.HashTag = data.HashTag;
editedEvent.AutomaticApproval = data.AutomaticApproval;
context.SaveChanges();
return RedirectToAction("Approve", new { id = editedEvent.Id });
}
}
return View();
}
public virtual async Task<ActionResult> Approve(int id)
{
var config = new InstaSharp.InstagramConfig("554dfe9286994bbe98417d8dc7b69a24", "39de8776637b47d2829cd1a4708ae180");
using (InstaeventosContext context = new InstaeventosContext())
{
await new InstagramPhotoFetcher(context, config).ImportNewPhotos(id);
context.SaveChanges();
return View(context.InstagramPhotos.Where(x => x.Event.Id == id && x.Approved == false).ToList());
}
}
[HttpPost]
public virtual ActionResult Approve(int id, int[] selectedItems)
{
using (InstaeventosContext context = new InstaeventosContext())
{
foreach (var item in context.InstagramPhotos.Where(x => selectedItems.Contains(x.Id)).ToList())
{
item.Approved = true;
}
context.SaveChanges();
}
return RedirectToAction("Approve");
}
public virtual ActionResult Album(int id)
{
var config = new InstaSharp.InstagramConfig("554dfe9286994bbe98417d8dc7b69a24", "39de8776637b47d2829cd1a4708ae180");
using (InstaeventosContext context = new InstaeventosContext())
{
return View(context.InstagramPhotos.Where(x => x.Event.Id == id && x.Approved == true).ToList());
}
}
}
}<file_sep>/src/Instaeventos.Web/Controllers/InstagramPhotoController.cs
using Instaeventos.Core;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
namespace Instaeventos.Web.Controllers
{
public class InstagramPhotoController : ApiController
{
// GET api/<controller>
public async Task<IEnumerable<InstagramPhoto>> Get(int idEvent, bool newPhotos=false)
{
var config = new InstaSharp.InstagramConfig("554dfe9286994bbe98417d8dc7b69a24", "<KEY>");
using (InstaeventosContext context = new InstaeventosContext())
{
if (context.Events.Any(x => x.Id == idEvent && x.AutomaticApproval))
{
await new InstagramPhotoFetcher(context, config).ImportNewPhotos(idEvent);
context.SaveChanges();
}
IQueryable<InstagramPhoto> query = context.InstagramPhotos.Where(x =>x.Event.Id == idEvent && x.Approved);
if (newPhotos)
{
query = query.Where(x => x.NeverShown);
}
else
{
query = query.OrderByDescending(x => x.CreatedDate);
}
var photos = query.ToList();
foreach (var item in photos)
{
item.NeverShown = false;
}
context.SaveChanges();
return photos;
}
}
}
}<file_sep>/src/Instaeventos.Core/Event.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instaeventos.Core
{
public class Event
{
public int Id { get; set; }
public ApplicationUser User { get; set; }
public string Name { get; set; }
public string HashTag { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool Enabled { get; set; }
public string BackgroundUrl { get; set; }
public string SliderEffect { get; set; }
public bool AutomaticApproval { set; get; }
public bool IsPublic { get; set; }
public string NextMinTagId { get; set; }
public DateTime CreatedDate { get; set; }
}
}
<file_sep>/src/Instaeventos.Web/Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Instaeventos.Web.Startup))]
namespace Instaeventos.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
<file_sep>/src/Instaeventos.Core/InstaeventosContext.cs
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instaeventos.Core
{
public class InstaeventosContext : IdentityDbContext<ApplicationUser>
{
public InstaeventosContext()
: base("InstaeventosContext")
{
}
public DbSet<Event> Events { get; set; }
public DbSet<InstagramPhoto> InstagramPhotos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<InstagramPhoto>().ToTable("InstagramPhotos");
}
}
}
<file_sep>/src/Instaeventos.Core/InstagramPhoto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instaeventos.Core
{
public class InstagramPhoto
{
public int Id { get; set; }
public Event Event { get; set; }
public string FullResponse { get; set; }
public string InstagramUsername { get; set; }
public string ImageUrl { get; set; }
public string PostUrl { get; set; }
public DateTime PublishDate { get; set; }
public string IdInstagram { get; set; }
public string Description { get; set; }
public bool Approved { get; set; }
public bool NeverShown { get; set; }
public DateTime CreatedDate { get; set; }
}
}
<file_sep>/src/Instaeventos.Core/InstagramPhotoFetcher.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InstaSharp;
using InstaSharp.Models;
namespace Instaeventos.Core
{
public class InstagramPhotoFetcher
{
private readonly InstagramConfig instagramConfig;
private readonly InstaeventosContext context;
public InstagramPhotoFetcher(InstaeventosContext context, InstagramConfig instagramConfig)
{
this.instagramConfig = instagramConfig;
this.context = context;
}
public async Task ImportNewPhotos(int idEvent)
{
var currentEvent = context.Events.Find(idEvent);
var postsTag = await new InstaSharp.Endpoints.Tags(instagramConfig).Recent(currentEvent.HashTag, currentEvent.NextMinTagId);
List<Media> fotos = postsTag.Data;
string nextMaxId = postsTag.Pagination.NextMaxId;
string nextMinId = postsTag.Pagination.NextMinId;
while (nextMaxId != null)
{
var postsTagPaginado = await new InstaSharp.Endpoints.Tags(instagramConfig).Recent(currentEvent.HashTag, null, nextMaxId);
fotos.AddRange(postsTagPaginado.Data);
nextMaxId = postsTagPaginado.Pagination.NextMaxId;
}
var idsRetorno = fotos.Select(x => x.Id).ToArray();
var idsInstagramExistentes = context.InstagramPhotos.Where(x => idsRetorno.Contains(x.IdInstagram)).Select(x => x.IdInstagram).ToArray();
foreach (var item in fotos.Where(x => idsInstagramExistentes.Contains(x.Id) == false))
{
context.InstagramPhotos.Add(new InstagramPhoto
{
Event = currentEvent,
FullResponse = item.ToString(),
InstagramUsername = item.User.Username,
ImageUrl = item.Images.StandardResolution.Url,
PublishDate = item.CreatedTime,
IdInstagram = item.Id,
Description = item.Caption != null ? item.Caption.Text : "",
PostUrl = item.Link,
Approved = currentEvent.AutomaticApproval,
NeverShown = true,
CreatedDate = DateTime.Now
});
}
if (nextMinId != null)
{
try
{
if (long.Parse(nextMinId) > long.Parse(currentEvent.NextMinTagId ?? "0"))
{
currentEvent.NextMinTagId = nextMinId;
}
}
catch
{
currentEvent.NextMinTagId = nextMinId;
}
}
}
}
}
<file_sep>/src/Instaeventos.Web/ViewModels/EventConfigureSave.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Instaeventos.Web.ViewModels
{
public class EventConfigureSave
{
public string Name { get; set; }
public string HashTag { get; set; }
public bool AutomaticApproval { get; set; }
}
}<file_sep>/src/Instaeventos.Core/ApplicationUser.cs
using Microsoft.AspNet.Identity.EntityFramework;
using System;
namespace Instaeventos.Core
{
// You can add profile data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public ApplicationUser() : base()
{
CreatedDate = DateTime.Now;
}
public ApplicationUser(string userName)
: base(userName)
{
CreatedDate = DateTime.Now;
}
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Cpf { get; set; }
public string Email { get; set; }
public DateTime CreatedDate { get; set; }
}
} | ea40725240159712dbdee204a51a61d72b50ccd9 | [
"C#"
] | 9 | C# | felipepessoto/InstaEvent | b21d563fbd2f38db4e0a633fb68deadf01df93ce | d07366aaa04155c81389ff59352ca7243d33f097 |
refs/heads/master | <repo_name>thomascolomba/vue_simpleEventBus<file_sep>/README.md
# ejemplo12
## Project setup
```
src/events/BusinessEventList.js -> list of business events
src/view/Home.vue -> emits an event
src/components/HelloWorld/HelloWorld.js -> receives the event
<file_sep>/src/components/HelloWorld/HelloWorld.js
import EventBus from '@/events/EventBus'
import { BusinessEventList } from '@/events/BusinessEventList'
export default {
name: 'HelloWorld',
mounted: function () {
EventBus.$on(BusinessEventList().userOrderedANewSandwich, this.sandwichOrderedHandler)
},
beforeDestroy: function () {
EventBus.$off(BusinessEventList().userOrderedANewSandwich, this.sandwichOrderedHandler)
},
methods: {
sandwichOrderedHandler: function (payLoad) {
console.log('event received in HelloWorld : A sandwich was ordered')
var li = document.createElement('LI')
var textLi = document.createTextNode('event received in HelloWorld : A sandwich was ordered, ingredients : ' + payLoad.ingredients)
li.appendChild(textLi)
var ul = document.getElementById('listEventsReceived')
ul.appendChild(li)
}
}
}
| aa11b57b85398d7e866dd624618e30d411a8dcce | [
"Markdown",
"JavaScript"
] | 2 | Markdown | thomascolomba/vue_simpleEventBus | 47de12d56cbea7920c24f18f235e977d20e520e1 | e6635ff8f9cd0561f994d70db83a0af5a8bfd9de |
refs/heads/master | <file_sep># che-sample-custom-openocd-extension
Sample Eclipse Che Plugin to create custom actions for gdb-openocd debugger
<file_sep>/*******************************************************************************
* Copyright (c) 2012-2016 <NAME>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* <NAME>. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.openocdexample.server;
import org.eclipse.che.api.debugger.server.DebuggerManager;
import org.eclipse.che.api.debug.shared.model.action.Action;
import org.eclipse.che.api.debug.shared.model.action.SuspendAction;
import org.eclipse.che.dto.server.DtoFactory;
import org.eclipse.che.api.debug.shared.dto.action.SuspendActionDto;
import org.eclipse.che.api.debugger.server.Debugger;
import org.eclipse.che.api.debugger.server.exceptions.DebuggerException;
import org.eclipse.che.api.debugger.server.exceptions.DebuggerNotFoundException;
import com.google.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
@Path("hello")
public class MyService {
private final DebuggerManager debuggerManager;
@Inject
public MyService(DebuggerManager debuggerManager) {
this.debuggerManager = debuggerManager;
}
@GET
@Path("{name}")
public String sayHello(@PathParam("name") String name,
@QueryParam("actionParam") String actionParam) {
Debugger debugger = null;
String sessionIdFound = null;
if(actionParam.equals("DISCONNECT")) {
int tempSessionId = 0;
String tempSessionIdS = "0";
debugger = null;
/** Search for active Debugger sessionId **/
while((debugger == null) && (tempSessionId < 255)){
tempSessionIdS = Integer.toString(tempSessionId);
try {
if(debuggerManager.getDebuggerType(tempSessionIdS).equals("gdbOpenocd")) {
debugger = debuggerManager.getDebugger(tempSessionIdS);
sessionIdFound = tempSessionIdS;
} else {
tempSessionId++;
}
} catch (DebuggerNotFoundException e) {
/* continue to search sessionId */
tempSessionId++;
}
}
}
if(debugger == null){
return name + " Failed. Debugger Problem (Not gdbOpenocd or disconnected).";
}
else{
String debuggerName = "";
int tempLoop = 0;
try {
/** Suspend Active Debugger **/
SuspendActionDto actionSusp = DtoFactory.newDto(SuspendActionDto.class);
actionSusp.setType(Action.TYPE.SUSPEND);
debugger.suspend((SuspendAction)actionSusp);
debuggerName = debuggerManager.getDebuggerType(sessionIdFound);
debuggerName = debuggerName + ": " + debugger.getInfo().getName();
/** Disconnect Debugger **/
debugger.disconnect();
do {
try {
Thread.sleep(2000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
tempLoop++;
try {
debugger = debuggerManager.getDebugger(sessionIdFound);
} catch (DebuggerNotFoundException e) {
debugger = null;
}
} while ((debugger != null) && (tempLoop < 5));
/** debugger is now null, ready for restart **/
} catch(DebuggerException ex) {
debuggerName = "";
}
if(actionParam.equals("DISCONNECT")) {
if(debuggerName.equals("")) {
return name + " Debugger Disconnect failed";
} else {
return name + " Debugger Ready for restart! " + debuggerName;
}
} else {
return name + " :-)";
}
}
}
}
<file_sep>/*******************************************************************************
* Copyright (c) 2012-2016 <NAME>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* <NAME>. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.openocdexample.ide;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.constraints.Constraints;
import org.eclipse.che.ide.api.extension.Extension;
import org.eclipse.che.plugin.debugger.ide.actions.DisconnectDebuggerAction;
import org.eclipse.che.plugin.debugger.ide.actions.SuspendAction;
import org.eclipse.che.plugin.debugger.ide.debug.DebuggerPresenter;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_MAIN_MENU;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_RUN;
import static org.eclipse.che.ide.api.constraints.Constraints.LAST;
@Singleton
@Extension(title = "My Extension", version = "1.0.0")
public class MyExtension {
@Inject
public MyExtension(MyResources resources,
ActionManager actionManager,
DebuggerPresenter debuggerPresenter,
MyAction action,
SuspendAction suspendAction
) {
DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU);
DefaultActionGroup myMenu = new DefaultActionGroup("OpenOCD Menu", true, actionManager);
mainMenu.add(myMenu, Constraints.LAST);
actionManager.registerAction("MyMenuID", myMenu);
actionManager.registerAction("MyActionID", action);
/* suspend action already registered in DebuggerExtension */
myMenu.add(action);
myMenu.add(suspendAction, LAST);
/* Add My action to existing Run Menu */
DefaultActionGroup runMenu = (DefaultActionGroup)actionManager.getAction(GROUP_RUN);
runMenu.addSeparator();
runMenu.add(action, LAST);
/* Add My action to existing debuggerToolbarActionGroup */
DefaultActionGroup myDebuggerToolbarActionGroup = new DefaultActionGroup(actionManager);
myDebuggerToolbarActionGroup.add(action);
debuggerPresenter.getDebuggerToolbar().bindCenterGroup(myDebuggerToolbarActionGroup);
}
}
| f51804dee40f52c9394e49958963b666650c2f95 | [
"Markdown",
"Java"
] | 3 | Markdown | schervet/che-sample-custom-openocd-extension | 8b1644f865639a401f3709f34b806a476c37e1fe | 6e39cf341a74e2952805c1c23989691f4a031d9c |
refs/heads/master | <repo_name>yoramdelangen/timecap<file_sep>/app/Http/Controllers/Api/RegistrationController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Registration;
use Illuminate\Http\Request;
class RegistrationController extends Controller
{
protected $registration;
public function __construct(Registration $registration)
{
$this->registration = $registration;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
return $this->registration->limit($request->get('limit'))
->get()
->map(function ($registration) {
return [
'id' => $registration->id,
'title' => $registration->title,
'registered_on' => $registration->registered_on->toDateString(),
'decorator' => $registration->decorator,
'register_value' => $registration->register_value,
'created_at' => $registration->created_at->toDateTimeString(),
];
});
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'decorator' => 'required|min:2',
'register_value' => 'required|numeric',
'title' => 'required|min:2',
'registered_on' => 'required|date',
]);
$registration = $this->registration->create([
'user_id' => 1,
'decorator' => trim(ltrim($request->get('decorator'), '+')),
'register_value' => $request->get('register_value'),
'title' => $request->get('title'),
'registered_on' => $request->get('registered_on'),
]);
// update the users current balance
$user = \App\Models\User::find(1);
$totalBalance = $user->current_balance + $request->get('register_value');
$user->update([
'current_balance' => $totalBalance,
'current_decorator' => $this->formatBalance($totalBalance),
]);
return $this->show($registration->id);
}
/**
* Update a registration and recalculate all registrations.
*
* @param int $id
*
* @return Response
*/
public function update(Registration $registration, Request $request)
{
$this->validate($request, [
'decorator' => 'required|min:2',
'register_value' => 'required|numeric',
'title' => 'required|min:2',
'registered_on' => 'required|date',
]);
// update the registration.
$registration->update([
'title' => $request->get('title'),
'register_value' => $request->get('register_value'),
'decorator' => $request->get('decorator'),
'registered_on' => $request->get('registered_on'),
]);
// recalculate the user SUM
$userBalance = (int) Registration::selectRaw('sum(register_value) as counting')
->pluck('counting')
->first();
// @TODO: after the calculation create a decorator (e.g. 2d 8h 30m)
$user = \App\Models\User::find(1);
$user->update([
'current_balance' => $userBalance,
'current_decorator' => $this->formatBalance($userBalance),
]);
return $this->show($registration->id);
}
/**
* Display the specified resource.
*
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// @TODO: fix login
$user = \App\Models\User::find(1);
$registration = $this->registration->findOrFail($id);
return [
'id' => $registration->id,
'title' => $registration->title,
'registered_on' => $registration->registered_on->toDateString(),
'decorator' => $registration->decorator,
'register_value' => $registration->register_value,
'created_at' => $registration->created_at->toDateTimeString(),
'user' => [
'balance' => $user->current_balance,
'decorator' => $user->current_decorator,
],
];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
if ($registration = $this->registration->find($id)) {
$registration->delete();
}
return 1;
}
/**
* Format the current balance.
*
* @param int $balance
*
* @return string
*/
public function formatBalance(int $balance): string
{
$minutesToDays = (60 * 8);
$days = 0;
$hours = 0;
// checkout if thre is more then a day
if ($balance >= $minutesToDays) {
$days = floor($balance / $minutesToDays);
}
// get hours remaining
if (($remain = $balance % $minutesToDays) > 0) {
$hours = floor($remain / 60);
}
$minutes = round($balance % 60);
$format = [];
if ($days > 0) {
$format[] = $days . 'd';
}
if ($hours > 0) {
$format[] = $hours . 'h';
}
if ($minutes > 0) {
$format[] = $minutes . 'm';
}
return implode(' ', $format);
}
}
<file_sep>/app/Http/Controllers/Api/UserController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function index()
{
$user = \App\Models\User::find(1);
return [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'current_balance' => $user->current_balance,
'current_decorator' => $user->current_decorator,
'time_notation_per_day' => $user->time_notation_per_day,
];
}
}
<file_sep>/app/Models/Registration.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Registration extends Model
{
use SoftDeletes;
protected $fillable = ['user_id', 'decorator', 'register_value', 'title', 'registered_on'];
protected $casts = [
'user_id' => 'integer',
'register_value' => 'integer',
];
// @TODO: registered_on with tz
protected $dates = ['registered_on'];
}
<file_sep>/database/migrations/2016_12_27_181357_create_registrations_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRegistrationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('registrations', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id'); // default: 1
$table->string('decorator'); // +3h 20m or -1h
$table->integer('register_value'); // 200 or -60
$table->string('title');
$table->timestamp('registered_on');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('registrations');
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::get('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
Route::get('/', function () {
if (!auth()->check()) {
return redirect()->route('login');
}
return view('home');
});
Route::get('{app}/{action?}/{action1?}', function () {
return view('home');
});
<file_sep>/resources/assets/js/models.js
export {default as registration} from './models/registration'
export {default as user} from './models/user'<file_sep>/resources/assets/js/models/registration.js
import user from './user'
export default {
registrations: [],
retrieve() {
const p = axios.get('/api/registrations');
p.then(rsp => this.registrations = rsp.data);
return p;
},
update(id, decorator, title, registeredOn, isNegative) {
let total = this._totalRegistered(decorator)
if (isNegative) {
total = total * -1
}
let p = axios.put('/api/registrations/' + id, {
'decorator': decorator,
'register_value': total,
'title': title,
'registered_on': registeredOn
});
p.then(rsp => {
user.setBalance(rsp.data.user.balance);
user.setDecorator(rsp.data.user.decorator);
})
p.catch(err => {
console.log(err)
});
return p;
},
create(decorator, title, registeredOn, isNegative) {
let total = this._totalRegistered(decorator)
if (isNegative) {
total = total * -1
}
let p = axios.post('/api/registrations', {
'decorator': decorator,
'register_value': total,
'title': title,
'registered_on': registeredOn
});
p.then(rsp => {
this.registrations.push(rsp.data)
user.setBalance(rsp.data.user.balance)
user.setDecorator(rsp.data.user.decorator)
})
p.catch(err => {
console.log(err)
});
return p;
},
all() {
return this.registrations;
},
_totalRegistered(input) {
// for every timeInput element
let m = 0;
let dt = user.get('time_notation_per_day') || 8;
_.each(_.filter(input.split(' ')), t => {
let b = t.match(/[0-9]+|[a-zA-Z]+/g);
let v = parseInt(_.head(b), 0);
switch(_.last(b)) {
case 'd': m = m + ((v * dt) * 60); break;
case 'h': m = m + (v * 60); break;
default: m = m + v; break;
}
});
return m;
}
}<file_sep>/readme.md
# Timecap
Build with Laravel and Vue to register overtime and keep track of it.
Its not fully finished but its a start.
### Todos
* Registering holiday
* Improve registering overtime.
* Admin panel for overviewing everyone's hours
* ...<file_sep>/resources/assets/js/router.js
export default [
{ path: '/dashboard', name: 'dashboard', component: require('./components/Dashboard.vue') },
{ path: '/registrations', name: 'registrations', component: require('./components/Registrations.vue'), children: [
{ path: '/registrations/:id/edit', name: 'registrations.name', component: require('./components/RegistrationEdit.vue') }
]},
{ path: '/', redirect: { name: 'dashboard'} }
];<file_sep>/resources/assets/js/models/user.js
export default {
user: {},
fetchUser() {
const p = axios.get('/api/user')
p.then(rsp => this.user = rsp.data)
return p
},
get(key) {
if (key) {
return this.user[key]
}
return this.user
},
setBalance(u) {
this.user.current_balance = u
},
setDecorator(d) {
this.user.current_decorator = d
}
} | 75a4b129fef2be18377a8f1b144c6eb6a486ed19 | [
"JavaScript",
"Markdown",
"PHP"
] | 10 | PHP | yoramdelangen/timecap | 8a13290c79a25a1ee321245c879caba16fbecb86 | ab721e10caef6b72f3531e70ca497a12e81736dc |
refs/heads/master | <file_sep>#!/usr/bin/python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import getpass
import time
email=raw_input("email: ")
password=<PASSWORD>("Password: ")
driver = webdriver.Firefox()
driver.get("http://www.quora.com")
time.sleep(5)
Form=driver.find_element_by_xpath("//div[@class='form_inputs']")
driver.find_element_by_name("email").send_keys(email)
time.sleep(4)
Form.find_element_by_name("password").send_keys(password)
time.sleep(2)
Form.find_element_by_xpath("//input[@value='Login']").click()
#assert
#kk=driver.find_elements_by_xpath("//*[@type='text']")
#driver.find_element_by_id("__w2_CjFuiv2_email").send_keys("viv")
#driver.find_element_by_name("email").send_keys(email)
#kk.send_keys("viv")
#pass_elem=driver.find_element_by_name("password")
#pass_elem.send_keys(<PASSWORD>)
#driver.find_element_by_class_name("submit_button").click()
<file_sep>
This library uses selenium to help automate activities and extraction from quora, simply by using terminal.
| 61fa9421ef915aab6f9aada898df5d1c8245e261 | [
"Markdown",
"Python"
] | 2 | Python | viv1/Q_api | 13e216fba7d001a6be50a90c840407abb197c094 | 2b73979f26de9d589d552b211fc46e8f456f35a4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.