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>reachanavi/SimpleVueMapPopup<file_sep>/src/index.js
import 'whatwg-fetch';
import Vue from 'vue';
import store from './store'
import Vuetify from 'vuetify';
import 'vuetify/dist/vuetify.min.css'
import App from './App.vue';
import VueWindowModal from 'vue-window-modal';
import DialogDrag from 'vue-dialog-drag';
import * as VueWindow from '@hscmap/vue-window';
let geoJsonCurrentGauges;
let geoJsonGaugeDataForecast;
Vue.use(Vuetify);
Vue.use(VueWindowModal);
Vue.prototype.$eventHub = new Vue();
let vm = new Vue({
el: '#app',
store,
template:'<App/>',
components:{
App
},
data: {
message: 'Hello Vue!'
}
});
|
9263666626f7f97767b8840de55a3ec7e0db9ef2
|
[
"JavaScript"
] | 1 |
JavaScript
|
reachanavi/SimpleVueMapPopup
|
81d346bb68c355586e6703c6b36dc0e4368b04b6
|
605f8e3e3def276fd3ec5c0c07097faefc5b5b43
|
refs/heads/main
|
<repo_name>EldirTorres/crud-react-redux-rest-axios<file_sep>/src/store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk'; //Variación de redux que permite trabajar funciones asincronas
import reducer from './reducers'; //como el archivo se llama index.js no es necesario colocar /index
/* Maneja el state de toda la aplicación
esta es la nueva implementación que funciona apartir de recat 7 */
const store = createStore(
reducer,
compose( applyMiddleware(thunk), //"applyMiddleware" Permite agregar un middleware
//Validación para que funcione cuando tenemos redux devtool y cuando no se tebga tambienx
typeof window === 'object' &&
typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined' ?
window.__REDUX_DEVTOOLS_EXTENSION__() : f => f //Para que detecte que se esta usando redux
)
);
export default store;
|
4933e9e209dddb66004bffba7c8e9a58a3509511
|
[
"JavaScript"
] | 1 |
JavaScript
|
EldirTorres/crud-react-redux-rest-axios
|
fc38e855aa5e2a36e9fc429bb454ccb18f71b977
|
086f39dde04f4ca2481f75d8278916674b756417
|
refs/heads/master
|
<repo_name>boshek/cansim<file_sep>/fix_meta.sh
og_img1='<meta property="og:image" content="/logo.png"'
og_img2='<meta property="og:image" content="https://mountainmath.github.io/cansim/logo.png"'
replace_meta () {
file=$(find . -name '*.html')
for i in $file; do
cat "${i}" | sed "s,${og_img1},${og_img2},g" > "temp"
cat "temp" > "${i}"
done
rm temp
}
cd ./docs
replace_meta
cd articles
replace_meta
cd ..
cd news
replace_meta
cd ..
cd reference
replace_meta
cd ..
cd ..
<file_sep>/NEWS.md
# cansim 0.3.7
## Minor changes
* Fix problem with UTF-8 encoding on solaris
* move dbplyr dependence from Imports to Suggests
# cansim 0.3.6
## Major changes
* Fold part of `normalize_cansim_values` into the default table and vector output, in particular always add a scaled variable column called `val_norm` and an imputed `Date` column and covert categories to factors by default.
* New `get_cansim_sqlite` function that stores tables in an SQLite database and facilitates access and managemet of data.
## Minor changes
* Adapt to changes in dplyr, tidyr, and tibble
* fix a bug that would not properly add hierarchies when category names are repeated
* Use system unzip if `getOption("unzip")` is set to enable unzip for files larger than 4GB on unix-like systems
# cansim 0.3.5
## Minor changes
- Exclude all vignettes and example code from compilation as this may cause CRAN check errors when StatCan servers are down or otherwise temporarily unavailable
# cansim 0.3.4
## Minor changes
- Expand `get_cansim_table_notes()` functionality
- Add functionality to access the new cube list API
# cansim 0.3.3
## Minor changes
- Fix time zone problem when parsing and formatting times for the StatCan API
# cansim 0.3.2
## Minor changes
- Adjust package for changes in StatCan API with different metadata format
# cansim 0.3.1
## Major changes
- Fixes issues arising from StatCan changing their API row limit
## Minor changes
- Optimize vector retrieval by REF_DATE
# cansim 0.3.0
## Minor changes
- Fixes issues arising from StatCan changing their API
- Member Names come concatenated with Classification Code by default, this could break existing code.
- Adds option to change fields to factors
- Adds option to strip Classification Codes from fields
- Exposes timeout limit to deal with slow connections and large tables
# cansim 0.2.3
## Minor changes
- More robust table download functions
- Improved documentation
# cansim 0.2.2
## Major changes
- Initial CRAN release
- French metadata implemented
<file_sep>/cran-comments.md
## Test environments
* local OS X install, R 4.0.5
* GitHub Action macOS-latest, windows-lastest (3.6), ubuntu-16.04 (devel, release, oldrel), ubuntu-16.04 (3.4, 3.5)
## R CMD check results
There were no ERRORs or WARNINGs or NOTEs.
## Changes from version 0.2.1
* Redundancies removed from package title
* Implement timeout and retry for API requests to remote servers
* Reduced number of vignettes to be generated during package build--putting them online on an accompanying package website instead.
## Changes from version 0.2.2
* Correct problem with incorrect encoding
## Changes from version 0.2.3
* Fixes issues arising from StatCan changing their API
* Adds some post-processing options in normalize_cansim_values
## Changes from version 0.3.0
* Fixes issues arising from StatCan changing their API row limit
* Optimize vector retrieval by REF_DATE
## Changes from version 0.3.1
* Adjust package for changes in StatCan API with different metadata format
## Changes from version 0.3.2
* Fix time zone problem when parsing and formatting times for the StatCan API
## Changes from version 0.3.3
* Expand get_cansim_table_notes functionality
* Add functionality to access the new cube list API
## Changes from version 0.3.4
* Exclude all vignettes and example code from compilation as this may cause CRAN check errors when StatCan servers are down or otherwise temporarily unavailable
## Changes from version 0.3.5
* Fold part of `normalize_cansim_values` into the default table and vector output, in particular always add a scaled variable column called `val_norm` and an imputed `Date` column and covert categories to factors by default.
* New `get_cansim_sqlite` function that stores tables in an SQLite database and facilitates access and managemet of data.
* Adapt to changes in dplyr, tidyr, and tibble
* fix a bug that would not properly add hierarchies when category names are repeated
* Use system unzip if `getOption("unzip")` is set to enable unzip for files larger than 4GB on unix-like systems
# Changes from version 0.3.6
* Fix problem with UTF-8 encoding on solaris
* move dbplyr dependence from Imports to Suggests
<file_sep>/R/cansim_sql.R
TIME_FORMAT <- "%Y-%m-%d %H:%M:%S"
#' Retrieve a Statistics Canada data table using NDM catalogue number as SQLite database connection
#'
#' Retrieves a data table using an NDM catalogue number as an SQLite table. Retrieved table data is
#' cached permanently if a chache path is supplied or for duration of the current R session.
#' This function is useful for large tables that don't have very often.
#'
#' @param cansimTableNumber the NDM table number to load
#' @param language \code{"en"} or \code{"english"} for English and \code{"fr"} or \code{"french"} for French language versions (defaults to English)
#' @param refresh (Optional) When set to \code{TRUE}, forces a reload of data table (default is \code{FALSE})
#' @param timeout (Optional) Timeout in seconds for downloading cansim table to work around scenarios where StatCan servers drop the network connection.
#' @param cache_path (Optional) Path to where to cache the table permanently. By default, the data is cached
#' in the path specified by `getOption("cansim.cache_path")`, if this is set. Otherwise it will use `tempdir()`.
# Set to higher values for large tables and slow network connection. (Default is \code{1000}).
#'
#' @return tibble format data table output with added Date column with inferred date objects and
#' a "val_norm" column with normalized VALUE using the supplied scale factor
#'
#' @examples
#' \donttest{
#' con <- get_cansim_sqlite("34-10-0013")
#'
#' # Work with the data connection
#' head(con)
#'
#' disconnect_cansim_sqlite(con)
#' }
#' @export
get_cansim_sqlite <- function(cansimTableNumber, language="english", refresh=FALSE, timeout=1000,
cache_path=getOption("cansim.cache_path")){
have_custom_path <- !is.null(cache_path)
if (!have_custom_path) cache_path <- tempdir()
cleaned_number <- cleaned_ndm_table_number(cansimTableNumber)
cleaned_language <- cleaned_ndm_language(language)
base_table <- naked_ndm_table_number(cansimTableNumber)
table_name<-paste0("cansim_",base_table,"_",cleaned_language)
cache_path <- file.path(cache_path,table_name)
if (!dir.exists(cache_path)) dir.create(cache_path)
path <- paste0(base_path_for_table_language(cansimTableNumber,language),".zip")
sqlite_path <- paste0(base_path_for_table_language(cansimTableNumber,language,cache_path),".sqlite")
if (refresh | !file.exists(sqlite_path)){
if (cleaned_language=="eng")
message(paste0("Accessing CANSIM NDM product ", cleaned_number, " from Statistics Canada"))
else
message(paste0("Acc",intToUtf8(0x00E9),"der au produit ", cleaned_number, " CANSIM NDM de Statistique Canada"))
url=paste0("https://www150.statcan.gc.ca/n1/tbl/csv/",file_path_for_table_language(cansimTableNumber,language),".zip")
time_check <- Sys.time()
response <- get_with_timeout_retry(url,path=path,timeout=timeout)
if (is.null(response)) return(response)
data <- NA
na_strings=c("<NA>",NA,"NA","","F")
exdir=file.path(tempdir(),file_path_for_table_language(cansimTableNumber,language))
uzp <- getOption("unzip")
if (is.null(uzp)) uzp <- "internal"
utils::unzip(path,exdir=exdir,unzip=uzp)
unlink(path)
if(cleaned_language=="eng") {
message("Parsing data")
delim <- ","
value_column="VALUE"
} else {
message(paste0("Analyser les donn",intToUtf8(0x00E9),"es"))
delim <- ";"
value_column="VALEUR"
}
meta <- suppressWarnings(readr::read_delim(file.path(exdir, paste0(base_table, "_MetaData.csv")),
delim=delim,
na=na_strings,
#col_names=FALSE,
locale=readr::locale(encoding="UTF-8"),
col_types = list(.default = "c")))
meta_base_path <- paste0(base_path_for_table_language(cansimTableNumber,language,cache_path),".Rda")
parse_metadata(meta,data_path = meta_base_path)
headers <- readr::read_delim(file.path(exdir, paste0(base_table, ".csv")),
delim=delim,
col_types = list(.default = "c"),
n_max = 1) %>%
names()
to_drop <- intersect(headers,"TERMINATED") # not in use yet
scale_string <- ifelse(language=="fr","IDENTIFICATEUR SCALAIRE","SCALAR_ID")
value_string <- ifelse(language=="fr","VALEUR","VALUE")
# scale_string2 <- ifelse(language=="fr","FACTEUR SCALAIRE","SCALAR_FACTOR")
dimension_name_column <- ifelse(cleaned_language=="eng","Dimension name","Nom de la dimension")
geography_column <- ifelse(cleaned_language=="eng","Geography",paste0("G",intToUtf8(0x00E9),"ographie"))
data_geography_column <- ifelse(cleaned_language=="eng","GEO",paste0("G",intToUtf8(0x00C9),"O"))
coordinate_column <- ifelse(cleaned_language=="eng","COORDINATE",paste0("COORDONN",intToUtf8(0x00C9),"ES"))
meta2 <- readRDS(paste0(meta_base_path,"2"))
geo_column_pos <- which(pull(meta2,dimension_name_column)==geography_column)
if (length(geo_column_pos)==1) {
hierarchy_prefix <- ifelse(cleaned_language=="eng","Hierarchy for",paste0("Hi",intToUtf8(0x00E9),"rarchie pour"))
hierarchy_name <- paste0(hierarchy_prefix," ", data_geography_column)
}
csv2sqlite(file.path(exdir, paste0(base_table, ".csv")),
sqlite_file = sqlite_path,
table_name=table_name,
col_types = list(.default = "c"),
na = na_strings,
delim = delim,
transform=function(data){
data <- data %>%
dplyr::mutate_at(value_string,as.numeric)
if (length(geo_column_pos)==1)
data <- data %>%
fold_in_metadata_for_columns(meta_base_path,geography_column) %>%
select(-!!as.name(hierarchy_name))
data
})
unlink(exdir,recursive = TRUE)
date_field=ifelse(cleaned_language=="fra",paste0("P",intToUtf8(0x00C9),"RIODE DE R",intToUtf8(0x00C9),"F",intToUtf8(0x00C9),"RENCE"),"REF_DATE")
fields <- pull(meta2,dimension_name_column) %>%
gsub(geography_column,data_geography_column,.) %>%
c(.,date_field,"DGUID")
if (length(geo_column_pos)==1) fields <- c(fields,"GeoUID")
con <- DBI::dbConnect(RSQLite::SQLite(), dbname=sqlite_path)
for (field in fields) {
message(paste0("Indexing ",field))
create_index(con,table_name,field)
}
DBI::dbDisconnect(con)
# saving timestamp
saveRDS(strftime(time_check,format=TIME_FORMAT),paste0(meta_base_path,"_time"))
} else {
if (cleaned_language=="eng")
message(paste0("Reading CANSIM NDM product ",cleaned_number)," from cache.")
else
message(paste0("Lecture du produit ",cleaned_number)," de CANSIM NDM ",intToUtf8(0x00E0)," partir du cache.")
}
if (have_custom_path||TRUE) {
meta_base_path <- paste0(base_path_for_table_language(cansimTableNumber,language,cache_path),".Rda")
meta_grep_string <- basename(meta_base_path)
meta_dir_name <- dirname(meta_base_path)
meta_files <- dir(meta_dir_name,pattern=meta_grep_string)
for (f in meta_files) file.copy(file.path(meta_dir_name,f),file.path(tempdir(),f))
}
con <- DBI::dbConnect(RSQLite::SQLite(), dbname=sqlite_path) %>%
dplyr::tbl(table_name)
con
}
#' disconnect from a cansim database connection
#'
#' @param connection connection to database
#' @return `NULL``
#'
#' @examples
#' \donttest{
#' con <- get_cansim_sqlite("34-10-0013")
#' disconnect_cansim_sqlite(con)
#' }
#' @export
disconnect_cansim_sqlite <- function(connection){
DBI::dbDisconnect(connection$src$con)
}
#' collect data from connection and normalize cansim table output
#'
#' @param connection connection to database
#' @param replacement_value (Optional) the name of the column the manipulated value should be returned in. Defaults to adding the `val_norm` value field.
#' @param normalize_percent (Optional) When \code{true} (the default) normalizes percentages by changing them to rates
#' @param default_month The default month that should be used when creating Date objects for annual data (default set to "01")
#' @param default_day The default day of the month that should be used when creating Date objects for monthly data (default set to "01")
#' @param factors (Optional) Logical value indicating if dimensions should be converted to factors. (Default set to \code{false}).
#' @param strip_classification_code (strip_classification_code) Logical value indicating if classification code should be stripped from names. (Default set to \code{false}).
#' @return a tibble with the normalized data
#'
#' @examples
#' \donttest{
#' library(dplyr)
#'
#' con <- get_cansim_sqlite("34-10-0013")
#' data <- con %>%
#' filter(GEO=="Ontario") %>%
#' collect_and_normalize()
#'
#' disconnect_cansim_sqlite(con)
#' }
#' @export
collect_and_normalize <- function(connection,
replacement_value="val_norm", normalize_percent=TRUE,
default_month="07", default_day="01",
factors=FALSE,strip_classification_code=FALSE){
c <- connection$ops
while ("x" %in% names(c)) {c <- c$x}
cansimTableNumber <- c[[1]] %>%
gsub("^cansim_|_fra$|_eng$","",.) %>%
cleaned_ndm_table_number()
connection %>%
collect() %>%
normalize_cansim_values(replacement_value=replacement_value,
normalize_percent=normalize_percent,
default_month=default_month,
default_day=default_day,
factors=TRUE,
cansimTableNumber = cansimTableNumber)
}
#' List cached cansim SQLite database
#'
#' @param cache_path Optional, default value is `getOption("cansim.cache_path")`.
#' @return A tibble with the list of all tables that are currently cached at the given cache path.
#' @examples
#' \donttest{
#' list_cansim_sqlite_cached_tables()
#' }
#' @export
list_cansim_sqlite_cached_tables <- function(cache_path=getOption("cansim.cache_path")){
have_custom_path <- !is.null(cache_path)
if (!have_custom_path) cache_path <- tempdir()
result <- dplyr::tibble(path=dir(cache_path,"cansim_")) %>%
dplyr::mutate(cansimTableNumber=gsub("^cansim_|_eng$|_fra$","",.data$path) %>% cleaned_ndm_table_number()) %>%
dplyr::mutate(language=gsub("^cansim_\\d+_","",.data$path)) %>%
dplyr::mutate(title=NA_character_,
timeCached=NA_character_,
sqliteSize=NA_character_) %>%
dplyr::select(.data$cansimTableNumber,.data$language,.data$timeCached,.data$sqliteSize,
.data$title,.data$path)
if (nrow(result)>0) {
result$timeCached <- do.call("c",
lapply(result$path,function(p){
pp <- dir(file.path(cache_path,p),"\\.Rda_time")
if (length(pp)==1) {
d<-readRDS(file.path(cache_path,p,pp))
dd<- strptime(d,format=TIME_FORMAT)
} else {
dd <- NA
}
dd
}))
result$sqliteSize <- do.call("c",
lapply(result$path,function(p){
pp <- dir(file.path(cache_path,p),"\\.sqlite")
if (length(pp)==1) {
d<-file.size(file.path(cache_path,p,pp))
dd<- format_file_size(d,"auto")
} else {
dd <- NA
}
dd
}))
result$title <- do.call("c",
lapply(result$path,function(p){
pp <- dir(file.path(cache_path,p),"\\.Rda1")
if (length(pp)==1) {
d <- readRDS(file.path(cache_path,p,pp))
dd <- as.character(d[1,1])
} else {
dd <- NA
}
dd
}))
}
result
}
#' Remove cached cansim SQLite database
#'
#' @param cansimTableNumber Number of the table to be removed
#' @param language Language for which to remove the cached data. If unspecified (`NULL`) tables for all languages
#' will be removed
#' @param cache_path Optional, default value is `getOption("cansim.cache_path")`
#' @return `NULL``
#'
#' @examples
#' \donttest{
#' con <- get_cansim_sqlite("34-10-0013")
#' disconnect_cansim_sqlite(con)
#' remove_cansim_sqlite_cached_table("34-10-0013")
#' }
#' @export
remove_cansim_sqlite_cached_table <- function(cansimTableNumber,language=NULL,cache_path=getOption("cansim.cache_path")){
have_custom_path <- !is.null(cache_path)
if (!have_custom_path) cache_path <- tempdir()
cleaned_number <- cleaned_ndm_table_number(cansimTableNumber)
cleaned_language <- ifelse(is.null(language),c("eng","fra"),cleaned_ndm_language(language))
tables <- list_cansim_sqlite_cached_tables(cache_path) %>%
dplyr::filter(.data$cansimTableNumber==!!cansimTableNumber,
.data$language %in% cleaned_language)
for (index in seq(1,nrow(tables))) {
path <- tables[index,]$path
message("Removing cached data for ",tables[index,]$cansimTableNumber," (",tables[index,]$language,")")
unlink(file.path(cache_path,tables[index,]$path),recursive=TRUE)
}
NULL
}
#' create database index
#'
#' @param connection connection to database
#' @param table_name sql table name
#' @param field name of field to index
#' @keywords internal
create_index <- function(connection,table_name,field){
field_index=paste0("index_",gsub("[^[:alnum:]]","_",field))
query=paste0("CREATE INDEX IF NOT EXISTS ",field_index," ON ",table_name," (`",field,"`)")
#print(query)
r<-DBI::dbSendQuery(connection,query)
DBI::dbClearResult(r)
NULL
}
#' convert csv to sqlite
#' adapted from https://rdrr.io/github/coolbutuseless/csv2sqlite/src/R/csv2sqlite.R
#'
#' @param csv_file input csv path
#' @param sqlite_file output sql database path
#' @param table_name sql table name
#' @param transform optional function that transforms each chunk
#' @param chunk_size optional chunk size to read/write data, default=1,000,000
#' @param append optional parameter, append to database or overwrite, defaul=`FALSE`
#' @param col_types optional parameter for csv column types
#' @param na na character strings
#' @param text_encoding encoding of csv file (default UTF-8)
#' @param delim (Optional) csv deliminator, default is ","
#' @keywords internal
csv2sqlite <- function(csv_file, sqlite_file, table_name, transform=NULL,chunk_size=5000000,
append=FALSE,col_types=NULL,na=c(NA,"..","","...","F"),
text_encoding="UTF-8",delim = ",") {
# Connect to database.
if (!append && file.exists(sqlite_file)) file.remove(sqlite_file)
con <- DBI::dbConnect(RSQLite::SQLite(), dbname=sqlite_file)
chunk_handler <- function(df, pos) {
if (nrow(readr::problems(df)) > 0) print(readr::problems(df))
if (!is.null(transform)) df <- df %>% transform
DBI::dbWriteTable(con, table_name, as.data.frame(df), append=TRUE)
}
readr::read_delim_chunked(csv_file, delim=delim,
callback=readr::DataFrameCallback$new(chunk_handler),
col_types=col_types,
chunk_size = chunk_size,
locale=readr::locale(encoding = text_encoding),
na=na)
DBI::dbDisconnect(con)
}
|
4d6362387b5298134a063fffdfc6b678c95d384a
|
[
"Markdown",
"R",
"Shell"
] | 4 |
Shell
|
boshek/cansim
|
3ffcb951cb0f32cdd58bb5b5775802a619864aae
|
14e36dc97ecc6d05be16b0bf9b29e4de1870509e
|
refs/heads/main
|
<file_sep>package myui.ui.monet.colorscience
import myui.ui.monet.MathUtils
import kotlin.math.pow
import kotlin.math.roundToInt
class MonetColor(val argb: Int) {
val hex: String
val lstar: Double
val rgb = toRgb(argb)
val xyz: DoubleArray
override fun toString(): String {
return "Color{hex='$hex', argb=$argb, xyz=$xyz, rgb=$rgb}"
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other == null || MonetColor::class.java != other.javaClass) {
return false
}
return argb == (other as MonetColor).argb
}
override fun hashCode(): Int {
return arrayOf(Integer.valueOf(argb)).hashCode()
}
companion object {
var srgbToXyz = arrayOf(
doubleArrayOf(0.4124574456426238, 0.3575758652297323, 0.1804372478276439),
doubleArrayOf(0.2126733704094779, 0.7151517304594646, 0.07217489913105756),
doubleArrayOf(0.01933394276449797, 0.1191919550765775, 0.9503028385589246)
)
var xyzToSrgb = arrayOf(
doubleArrayOf(3.240446254174338, -1.537134761595519, -0.4985301929498981),
doubleArrayOf(-0.9692666062874638, 1.876011959871178, 0.04155604221626438),
doubleArrayOf(0.05564350356396922, -0.2040261797345535, 1.057226567715413)
)
private fun getBlue(i: Int): Int {
return i and 255
}
private fun getGreen(i: Int): Int {
return i and 65280 shr 8
}
private fun getRed(i: Int): Int {
return i and 16711680 shr 16
}
fun toRgb(i: Int): DoubleArray {
return doubleArrayOf(
getRed(i).toDouble(),
getGreen(i).toDouble(), getBlue(i).toDouble()
)
}
fun toHex(i: Int): String {
var hexString = i.toString(16)
while (hexString.length < 6) {
hexString = "0$hexString"
}
return "#$hexString"
}
fun toXyz(i: Int): DoubleArray {
val rgb = toRgb(i)
return MathUtils.matrixMultiply(
doubleArrayOf(
linearized(rgb[0] / 255.0) * 100.0, linearized(
rgb[1] / 255.0
) * 100.0, linearized(rgb[2] / 255.0) * 100.0
), srgbToXyz
)
}
fun fromXyz(dArr: DoubleArray): MonetColor {
return MonetColor(intFromXyz(dArr))
}
fun intFromXyz(dArr: DoubleArray): Int {
val matrixMultiply: DoubleArray = MathUtils.matrixMultiply(
dArr.map { it / 100.0 }.toDoubleArray(),
xyzToSrgb
)
return intFromRgb(
matrixMultiply.map {
(delinearized(it) * 255.0).coerceIn(0.0..255.0).roundToInt()
}.toIntArray()
)
}
fun intFromRgb(iArr: IntArray): Int {
return iArr[2] and 255 or (iArr[0] and 255 shl 16) or (iArr[1] and 255 shl 8)
}
fun linearized(d: Double): Double {
return if (d <= 0.04045) d / 12.92 else ((d + 0.055) / 1.055).pow(2.4)
}
fun delinearized(d: Double): Double {
return if (d <= 0.0031308) d * 12.92 else d.pow(1.0 / 2.4) * 1.055 - 0.055
}
}
val y: Float
get() = xyz[1].toFloat()
init {
val xyz = toXyz(argb)
this.xyz = xyz
hex = toHex(argb)
lstar = Contrast.yToLstar(xyz[1])
}
}<file_sep>package myui.ui.monet
object MathUtils {
fun lerp(d: Double, d2: Double, d3: Double): Double {
return (1.0 - d3) * d + d3 * d2
}
fun matrixMultiply(dArr: DoubleArray, dArr2: Array<DoubleArray>): DoubleArray {
return doubleArrayOf(
dArr[0] * dArr2[0][0] + dArr[1] * dArr2[0][1] + dArr[2] * dArr2[0][2],
dArr[0] * dArr2[1][0] + dArr[1] * dArr2[1][1] + dArr[2] * dArr2[1][2],
dArr[0] * dArr2[2][0] + dArr[1] * dArr2[2][1] + dArr[2] * dArr2[2][2]
)
}
}<file_sep>package myui.ui.clustering.kmeans
import java.util.*
class KMeans(val allPoints: List<Point>, val k: Int) {
private var pointClusters: Clusters? = null //the k Clusters
private fun getPointByLine(line: String): Point {
val xyz = line.split(",").toTypedArray()
return Point(xyz[0].toDouble(), xyz[1].toDouble(), xyz[2].toDouble())
}
/**step 1: get random seeds as initial centroids of the k clusters
*/
private val initialKRandomSeeds: Unit
get() {
pointClusters = Clusters(allPoints)
val kRandomPoints: List<Point> = kRandomPoints
for (i in 0 until k) {
kRandomPoints[i].index = i
pointClusters!!.add(Cluster(kRandomPoints[i]))
}
}
private val kRandomPoints: List<Point>
get() {
val kRandomPoints: MutableList<Point> = ArrayList<Point>()
val alreadyChosen = BooleanArray(allPoints.size)
var size = allPoints.size
for (i in 0 until k) {
var index = -1
val r = random.nextInt(size--) + 1
for (j in 0 until r) {
index++
while (alreadyChosen[index]) index++
}
kRandomPoints.add(allPoints[index])
alreadyChosen[index] = true
}
return kRandomPoints
}
/**step 2: assign points to initial Clusters
*/
private val initialClusters: Unit
get() {
pointClusters!!.assignPointsToClusters()
}
/** step 3: update the k Clusters until no changes in their members occur
*/
private fun updateClustersUntilNoChange() {
var isChanged = pointClusters!!.updateClusters()
while (isChanged) isChanged = pointClusters!!.updateClusters()
}
/**do K-means clustering with this method
*/
val pointsClusters: List<Cluster>?
get() {
if (pointClusters == null) {
initialKRandomSeeds
initialClusters
updateClustersUntilNoChange()
}
return pointClusters?.toList()
}
companion object {
private val random = Random()
}
}<file_sep>plugins {
id("com.android.application")
id("kotlin-android")
}
android {
compileSdkPreview = "S"
buildToolsVersion = "31.0.0 rc4"
defaultConfig {
applicationId = "myui.ui"
minSdk = 21
targetSdkPreview = "S"
versionCode = 1
versionName = "1.0"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = listOf(
"-P",
"plugin:androidx.compose.compiler.plugins.kotlin:suppressKotlinVersionCompatibilityCheck=true"
)
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.0.0-SNAPSHOT"
}
}
dependencies {
val compose = "1.0.0-SNAPSHOT"
val accompanist = "0.10.0"
implementation("androidx.activity:activity-compose:1.3.0-SNAPSHOT")
implementation("androidx.appcompat:appcompat:1.4.0-alpha01")
implementation("androidx.compose.ui:ui:$compose")
implementation("androidx.compose.material:material:$compose")
implementation("androidx.compose.material:material-icons-extended:$compose")
implementation("androidx.compose.ui:ui-tooling:$compose")
implementation("androidx.constraintlayout:constraintlayout-compose:1.0.0-alpha07")
implementation("androidx.core:core-ktx:1.6.0-SNAPSHOT")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-SNAPSHOT")
implementation("com.google.accompanist:accompanist-coil:$accompanist")
implementation("com.google.accompanist:accompanist-flowlayout:$accompanist")
implementation("com.google.accompanist:accompanist-insets:$accompanist")
implementation("com.google.accompanist:accompanist-pager:$accompanist")
implementation("com.google.accompanist:accompanist-systemuicontroller:$accompanist")
implementation("com.google.android.material:material:1.4.0-beta01")
}<file_sep>package myui.ui.theme
import androidx.compose.material.Typography
val Typography = Typography()<file_sep>package myui.ui
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.core.graphics.scale
import coil.ImageLoader
import coil.request.ImageRequest
import coil.request.SuccessResult
import com.google.accompanist.flowlayout.FlowRow
import com.google.accompanist.flowlayout.MainAxisAlignment
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import myui.ui.clustering.kmeans.Cluster
import myui.ui.clustering.kmeans.KMeans
import myui.ui.clustering.kmeans.Point
import myui.ui.monet.ColorScheme
import myui.ui.monet.colorscience.MonetColor
import myui.ui.theme.MYUITheme
import kotlin.math.roundToInt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MYUITheme {
val url = "https://picsum.photos/300/300"
val systemUiController = rememberSystemUiController()
var themeColorText by remember { mutableStateOf(TextFieldValue("0000ff")) }
var themeColorText2 by remember { mutableStateOf("0000ff") }
LaunchedEffect(themeColorText.text) {
themeColorText2 = themeColorText.text
while (themeColorText2.length < 6) {
themeColorText2 = "f$themeColorText2"
}
}
val themeColor = Color("ff$themeColorText2".toLong(16))
var colorScheme by remember {
mutableStateOf(ColorScheme(themeColor.toArgb(), false))
}
LaunchedEffect(themeColor) {
withContext(Dispatchers.IO) {
colorScheme = ColorScheme(themeColor.toArgb(), false)
}
}
val (a1, a2, a3, n1, n2) = listOf(
colorScheme.allAccentColors.subList(0, 11),
colorScheme.allAccentColors.subList(11, 22),
colorScheme.allAccentColors.subList(22, 33),
colorScheme.allNeutralColors.subList(0, 11),
colorScheme.allNeutralColors.subList(11, 22)
)
val (ra1, ra2, ra3, rn1, rn2) = listOf(a1, a2, a3, n1, n2).map {
Color("ff${MonetColor(it[4]).hex.drop(1)}".toLong(16))
}
val bgColor = Color("ff${MonetColor(n1[0]).hex.drop(1)}".toLong(16))
SideEffect {
systemUiController.setSystemBarsColor(bgColor)
}
var bitmap by remember {
mutableStateOf(Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888))
}
val colors = remember { mutableStateListOf<Point>() }
val clusters = remember { mutableStateListOf<Point>() }
LaunchedEffect(url) {
withContext(Dispatchers.IO) {
val loader = ImageLoader(this@MainActivity)
val request = ImageRequest.Builder(this@MainActivity)
.data(url)
.allowHardware(false)
.build()
val result = (loader.execute(request) as SuccessResult).drawable
bitmap = (result as BitmapDrawable).bitmap
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val scaledBitmap = bitmap.scale(50, 50)
for (i in 0 until scaledBitmap.width) {
for (j in 0 until scaledBitmap.height) {
val color = scaledBitmap.getColor(i, j)
colors.add(
Point(
color.red().toDouble(),
color.green().toDouble(),
color.blue().toDouble()
)
)
}
}
val kMeans = KMeans(colors, 6)
val pointsClusters: List<Cluster>? = kMeans.pointsClusters
for (i in 0 until kMeans.k) {
with(pointsClusters!![i].centroid) {
clusters.add(Point(x, y, z))
}
}
}
}
}
Surface(
Modifier.fillMaxSize(),
color = bgColor
) {
Column(Modifier.verticalScroll(rememberScrollState())) {
Spacer(Modifier.height(56.dp))
Text(
"Monet Color System",
Modifier.padding(24.dp, 48.dp),
fontWeight = FontWeight.Medium,
style = MaterialTheme.typography.h4
)
Row(
Modifier.padding(horizontal = 24.dp),
verticalAlignment = Alignment.CenterVertically
) {
Surface(
Modifier.size(48.dp),
shape = CircleShape,
color = themeColor
) {}
Spacer(Modifier.width(24.dp))
TextField(
themeColorText,
{ themeColorText = it },
Modifier.clip(CircleShape),
label = { Text("Theme color") },
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
textColor = Color(
"ff${MonetColor(colorScheme.allAccentColors[4]).hex.drop(1)}"
.toLong(16)
),
backgroundColor = Color(
"ff${MonetColor(colorScheme.allNeutralColors[1]).hex.drop(1)}"
.toLong(16)
),
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
)
)
}
Spacer(Modifier.height(24.dp))
Card(
Modifier.padding(16.dp),
shape = RoundedCornerShape(32.dp),
backgroundColor = Color.White,
elevation = 0.dp
) {
Column(
Modifier
.fillMaxWidth()
.clickable { }
.padding(16.dp)
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
bitmap.asImageBitmap(), null,
Modifier
.padding(horizontal = 16.dp)
.clip(RoundedCornerShape(16.dp))
)
Text(
"Generate palette from image",
color = Color.Black,
fontWeight = FontWeight.Medium,
style = MaterialTheme.typography.body1
)
}
Spacer(Modifier.height(16.dp))
FlowRow(
Modifier.fillMaxWidth(),
mainAxisAlignment = MainAxisAlignment.Center
) {
println(clusters.joinToString())
clusters.forEachIndexed { i, point ->
val color = with(point) {
Color(
(0xFF * x).toInt(),
(0xFF * y).toInt(),
(0xFF * z).toInt()
)
}
TextButton((i + 1).toString(), color) {
themeColorText = themeColorText.copy(
"ff${
(0xFF * point.x).toLong().toString(16)
}${
(0xFF * point.y).toLong().toString(16)
}${(0xFF * point.z).toLong().toString(16)}"
)
}
}
}
}
}
Spacer(Modifier.height(48.dp))
Palette("A-1", a1, ra1)
Palette("A-2", a2, ra2)
Palette("A-3", a3, ra3)
Palette("N-1", n1, rn1)
Palette("N-2", n2, rn2)
}
}
}
}
}
@Composable
fun Palette(
name: String,
colors: List<Int>,
rippleColor: Color
) {
FlowRow {
TextButton(name, rippleColor = rippleColor)
colors.forEachIndexed { i, color ->
TextButton(
(if (i == 0) 50 else i * 100).toString(),
Color("ff${MonetColor(color).hex.drop(1)}".toLong(16)),
rippleColor
)
}
}
Spacer(Modifier.height(32.dp))
}
@Composable
fun TextButton(
text: String,
color: Color = Color.White,
rippleColor: Color = Color.White,
onClick: () -> Unit = {}
) {
val scope = rememberCoroutineScope()
val radius = remember { Animatable(50f) }
val rippleSize = remember { Animatable(0f) }
val rippleAlpha = remember { Animatable(0f) }
Box(
Modifier
.padding(4.dp)
.size(94.dp)
.clip(RoundedCornerShape(radius.value.roundToInt()))
.background(color)
.pointerInput(Unit) {
detectTapGestures(onPress = {
scope.launch {
radius.animateTo(25f, spring(stiffness = Spring.StiffnessHigh))
radius.animateTo(50f, spring(stiffness = Spring.StiffnessLow))
}
scope.launch {
rippleSize.animateTo(1f, spring(stiffness = 600f))
}
scope.launch {
rippleAlpha.animateTo(1f, spring(stiffness = 600f))
}
awaitPointerEventScope {
waitForUpOrCancellation()
scope.launch {
rippleSize.animateTo(1f, spring(stiffness = 600f))
scope.launch {
rippleAlpha.animateTo(0f, spring(stiffness = 600f))
rippleSize.animateTo(0f, spring(stiffness = 600f))
}
}
}
}) { onClick() }
}
) {
Surface(
Modifier
.fillMaxSize(rippleSize.value)
.align(Alignment.Center),
shape = CircleShape,
color = rippleColor.copy(rippleAlpha.value)
) {}
Text(
text,
Modifier.align(Alignment.Center),
color = if (color.luminance() <= 0.5f) Color.White else Color.Black,
fontWeight = FontWeight.Medium,
style = MaterialTheme.typography.body1
)
}
}
}<file_sep>package myui.ui.monet.colorscience
import android.util.Log
import myui.ui.monet.MathUtils
import kotlin.math.*
class CAM16Color private constructor(
monetColor: MonetColor,
cAM16ViewingConditions: CAM16ViewingConditions
) {
val C: Double
val J: Double
val M: Double
val Q: Double
val h: Double
val color: MonetColor
private val mViewingConditions: CAM16ViewingConditions
val s: Double
val ucs: DoubleArray
companion object {
private val DEBUG: Boolean = true
private val LMS_TO_XYZ = arrayOf(
doubleArrayOf(1.862067855087233, -1.011254630531684, 0.1491867754444517),
doubleArrayOf(0.3875265432361371, 0.6214474419314753, -0.008973985167612517),
doubleArrayOf(-0.01584149884933386, -0.03412293802851557, 1.04996443687785)
)
val XYZ_TO_LMS = arrayOf(
doubleArrayOf(0.401288, 0.650173, -0.051461),
doubleArrayOf(-0.250268, 1.204414, 0.045854),
doubleArrayOf(-0.002079, 0.048952, 0.953127)
)
fun fromRgb(i: Int): CAM16Color {
return CAM16Color(MonetColor(i))
}
private fun relativeLuminance(d: Double, d2: Double, d3: Double): Double {
return MonetColor.fromXyz(xyzFromJch(d, d2, d3)).xyz[1]
}
fun binarySearchForYByJ(d: Double, d2: Double, d3: Double): Double {
var d4 = 0.0
var d5 = 100.0
var d6 = -1.0
var d7 = -1.0
while (abs(d4 - d5) > 0.1) {
val d8 = (d5 - d4) / 2.0 + d4
val relativeLuminance = relativeLuminance(d8, d2, d3)
val abs = abs(relativeLuminance - d)
if (d7 == -1.0 || abs < d7) {
d6 = d8
d7 = abs
}
if (relativeLuminance < d) {
d4 = d8
} else {
d5 = d8
}
}
return d6
}
fun gamutMap(d: Double, d2: Double, d3: Double): MonetColor {
val d4 = d
val binarySearchForYByJ = binarySearchForYByJ(d, d2, d3)
val fromXyz = MonetColor.fromXyz(xyzFromJch(binarySearchForYByJ, d2, d3))
val abs = abs(d3 - CAM16Color(fromXyz).h)
val abs2 = abs(d4 - fromXyz.xyz[1])
if (abs <= 1.0 && abs2 <= 1.0) {
return fromXyz
}
val z = DEBUG
if (z) {
Log.d(
"CAM16Color",
"launching second search because hueDelta is $abs and y delta is $abs2"
)
}
val d5 = d
val str = "CAM16Color"
val d6 = abs2
val binarySearchForYByChroma =
binarySearchForYByChroma(d5, 0.0, d2, binarySearchForYByJ, d3)
val d7 = d3
val fromXyz2 = MonetColor.fromXyz(
xyzFromJch(
binarySearchForYByJ(d5, binarySearchForYByChroma, d7),
binarySearchForYByChroma,
d7
)
)
val cAM16Color = CAM16Color(fromXyz2)
val abs3 = abs(d3 - cAM16Color.h)
val abs4 = abs(d2 - cAM16Color.C)
val abs5 = abs(d4 - fromXyz2.xyz[1])
val monetColor = fromXyz
val str2 = " hue delta = "
val d8 = abs4
if ((d6 <= 1.0 || abs5 > d6) && (abs5 >= 1.0 && abs5 >= d6 || abs3 >= abs)) {
val str3 = str2
val d9 = d8
if (z) {
val d10 = abs3
Log.d(
str,
"round #2 was worse; asked for y ${d4.toInt()} got ${fromXyz2.xyz[1].toInt()} at C = ${cAM16Color.C} J = ${cAM16Color.J}. Error y = ${abs5.toInt()} chroma = ${d9.toInt()}$str3$d10"
)
}
return monetColor
}
if (z) {
Log.d(
str,
"round #2 was better; asked for y ${d4.toInt()} got ${fromXyz2.xyz[1].toInt()} at C = ${cAM16Color.C} J = ${cAM16Color.J}. Error y = ${abs5.toInt()} chroma = ${d8.toInt()}$str2$abs3"
)
}
return fromXyz2
}
fun binarySearchForYByChroma(
d: Double,
d2: Double,
d3: Double,
d4: Double,
d5: Double
): Double {
val z = relativeLuminance(d4, d2, d5) > relativeLuminance(d4, d3, d5)
var d6 = d3
var d7 = 0.0
var d8 = -1.0
var d9 = d2
while (abs(d9 - d6) > 0.1) {
val d10 = (d6 - d9) / 2.0 + d9
val relativeLuminance = relativeLuminance(d4, d10, d5)
val abs = abs(relativeLuminance - d)
if (d8 == -1.0 || abs < d8) {
d7 = d10
d8 = abs
}
if (if (!z) relativeLuminance <= d else relativeLuminance > d) {
d9 = d10
} else {
d6 = d10
}
}
return d7
}
fun xyzFromJch(d: Double, d2: Double, d3: Double): DoubleArray {
var d4 = 0.0
if (d2 >= 0.0) {
val sqrt = sqrt(d) * 0.1
if (sqrt != 0.0) {
d4 = d2 / sqrt
}
return xyzFromJrootAlphaHue(sqrt, d4, d3, CAM16ViewingConditions.DEFAULT)
}
throw IllegalArgumentException()
}
private fun xyzFromJrootAlphaHue(
d: Double,
d2: Double,
d3: Double,
cAM16ViewingConditions: CAM16ViewingConditions
): DoubleArray {
val cAM16ViewingConditions2: CAM16ViewingConditions = cAM16ViewingConditions
val radians = Math.toRadians(d3)
val pow =
((1.64 - 0.29.pow(cAM16ViewingConditions2.mBackgroundYToWhitepointY)).pow(-0.73) * d2).pow(
1.0 / 0.9
)
val pow2: Double = cAM16ViewingConditions2.mAw * d.pow(
2.0 / cAM16ViewingConditions2.mC / (sqrt(
cAM16ViewingConditions2.mBackgroundYToWhitepointY
) + 1.48)
)
val cos: Double =
cAM16ViewingConditions2.mNC * 50000.0 / 13.0 * cAM16ViewingConditions2.mNcb * (cos(
radians + 2.0
) + 3.8) * 0.25
val d4: Double = pow2 / cAM16ViewingConditions2.mNbb
val cos2 = cos(radians)
val sin = sin(radians)
val d5 = (0.305 + d4) * 23.0 * pow / (cos * 23.0 + pow * (11.0 * cos2 + 108.0 * sin))
val d6 = cos2 * d5
val d7 = d5 * sin
val d8 = d4 * 460.0
val dArr = doubleArrayOf(
(451.0 * d6 + d8 + 288.0 * d7) / 1403.0,
(d8 - 891.0 * d6 - 261.0 * d7) / 1403.0,
(d8 - d6 * 220.0 - d7 * 6300.0) / 1403.0
)
dArr[0] = cAM16ViewingConditions2.unadapt(dArr[0])
dArr[1] = cAM16ViewingConditions2.unadapt(dArr[1])
dArr[2] = cAM16ViewingConditions2.unadapt(dArr[2])
return MathUtils.matrixMultiply(
multiply(dArr, cAM16ViewingConditions2.mDrgbInverse),
LMS_TO_XYZ
)
}
private fun multiply(dArr: DoubleArray, dArr2: DoubleArray): DoubleArray {
val dArr3 = DoubleArray(dArr.size)
for (i in dArr.indices) {
dArr3[i] = dArr[i] * dArr2[i]
}
return dArr3
}
}
constructor(monetColor: MonetColor) : this(monetColor, CAM16ViewingConditions.DEFAULT)
override fun toString(): String {
return "CAM16Color{color=${color.hex}, J=${J.toInt()}, C=${C.toInt()}, h=${h.toInt()}, Q=${Q.toInt()}, M=${M.toInt()}, s=${s.toInt()}}"
}
init {
val cAM16ViewingConditions2: CAM16ViewingConditions = cAM16ViewingConditions
mViewingConditions = cAM16ViewingConditions2
color = monetColor
val multiply = multiply(
MathUtils.matrixMultiply(monetColor.xyz, XYZ_TO_LMS),
cAM16ViewingConditions2.mDrgb
)
val dArr = doubleArrayOf(
cAM16ViewingConditions2.adapt(multiply[0]), cAM16ViewingConditions2.adapt(
multiply[1]
), cAM16ViewingConditions2.adapt(multiply[2])
)
val d = dArr[0]
val d2 = dArr[1]
val d3 = dArr[2]
var d4 = (-12.0 * d2 + d3) / 11.0 + d
val d5 = d + d2
var d6 = (d5 - d3 * 2.0) / 9.0
var atan2 = atan2(d6, d4)
var degrees = Math.toDegrees(atan2)
if (abs(d4) < 0.007 && abs(d6) < 0.007) {
d6 = 0.0
d4 = 0.0
atan2 = 0.0
degrees = 0.0
}
h = if (degrees < 0.0) degrees + 360.0 else degrees
val pow =
(cAM16ViewingConditions2.mNbb * (d * 2.0 + d2 + 0.05 * d3) / cAM16ViewingConditions2.mAw).pow(
cAM16ViewingConditions2.mC * 0.5 * cAM16ViewingConditions2.mZ
)
val d7 = 100.0 * pow * pow
J = d7
Q =
4.0 / cAM16ViewingConditions2.mC * pow * (cAM16ViewingConditions2.mAw + 4.0) * cAM16ViewingConditions2.mFLRoot
val pow2 =
(cAM16ViewingConditions2.mNC * 50000.0 / 13.0 * cAM16ViewingConditions2.mNcb * ((cos(
atan2 + 2.0
) + 3.8) * 0.25) * sqrt(
d4 * d4 + d6 * d6
) / ((d5 + (d3 * 1.05)) + 0.305)).pow(0.9) * (1.64 - 0.29.pow(cAM16ViewingConditions2.mBackgroundYToWhitepointY)).pow(
0.73
)
val d8 = pow * pow2
C = d8
val d9: Double = d8 * cAM16ViewingConditions2.mFLRoot
M = d9
s = sqrt((cAM16ViewingConditions2.mC * pow2) / (cAM16ViewingConditions2.mAw + 4.0)) * 50.0
val log = ln((d9 * 0.0228) + 1.0) / 0.0228
ucs = doubleArrayOf(
(1.7 * d7) / ((d7 * 0.007) + 1.0),
cos(atan2) * log,
log * sin(atan2)
)
}
}<file_sep>package myui.ui.clustering.kmeans
class Clusters(val allPoints: List<Point>) : ArrayList<Cluster>() {
private var isChanged = false
/**@param point
* @return the index of the Cluster nearest to the point
*/
fun getNearestCluster(point: Point): Int {
var minSquareOfDistance = Double.MAX_VALUE
var itsIndex = -1
for (i in 0 until size) {
val squareOfDistance: Double = point.getSquareOfDistance(get(i).centroid)
if (squareOfDistance < minSquareOfDistance) {
minSquareOfDistance = squareOfDistance
itsIndex = i
}
}
return itsIndex
}
fun updateClusters(): Boolean {
for (cluster in this) {
cluster.updateCentroid()
cluster.points.clear()
}
isChanged = false
assignPointsToClusters()
return isChanged
}
fun assignPointsToClusters() {
for (point in allPoints) {
val previousIndex: Int = point.index
val newIndex = getNearestCluster(point)
if (previousIndex != newIndex) isChanged = true
val target: Cluster = get(newIndex)
point.index = newIndex
target.points.add(point)
}
}
companion object {
private const val serialVersionUID = 1L
}
}<file_sep>package myui.ui.monet
import myui.ui.monet.ColorShades.shadesOf
import myui.ui.monet.colorscience.CAM16Color
import kotlin.jvm.internal.Intrinsics
import kotlin.jvm.internal.Lambda
class ColorScheme(i: Int, private val darkTheme: Boolean) {
val accent1: List<Int>
private val accent2: List<Int>
private val accent3: List<Int>
private val neutral1: List<Int>
private val neutral2: List<Int>
val allAccentColors: List<Int>
get() {
val arrayList: ArrayList<Int> = ArrayList()
arrayList.addAll(accent1)
arrayList.addAll(accent2)
arrayList.addAll(accent3)
return arrayList
}
val allNeutralColors: List<Int>
get() {
val arrayList: ArrayList<Int> = ArrayList()
arrayList.addAll(neutral1)
arrayList.addAll(neutral2)
return arrayList
}
private fun humanReadable(list: List<Int>): String {
return listOf(
list,
null,
null,
null,
0,
null,
HumanReadable.INSTANCE,
31,
null
).joinToString()
}
override fun toString(): String {
return """ColorScheme {
neutral1: ${humanReadable(neutral1)}
neutral2: ${humanReadable(neutral2)}
accent1: ${humanReadable(accent1)}
accent2: ${humanReadable(accent2)}
accent3: ${humanReadable(accent3)}
}"""
}
internal class HumanReadable : Lambda<CharSequence?>(1), Function1<Int?, CharSequence?> {
companion object {
val INSTANCE = HumanReadable()
}
operator fun invoke(i: Int): CharSequence {
return "#${i.toString(16)}"
}
override fun invoke(obj: Int?): CharSequence {
return invoke(obj)
}
}
init {
val fromRgb = CAM16Color.fromRgb(i)
val y = fromRgb.color.y.toDouble()
val cAM16Color = CAM16Color(CAM16Color.gamutMap(y, 48.0, fromRgb.h))
val cAM16Color2 = CAM16Color(CAM16Color.gamutMap(y, 16.0, fromRgb.h))
val cAM16Color3 = CAM16Color(CAM16Color.gamutMap(y, 32.0, fromRgb.h + 60.0))
val cAM16Color4 = CAM16Color(CAM16Color.gamutMap(y, 8.0, fromRgb.h))
val cAM16Color5 = CAM16Color(CAM16Color.gamutMap(y, 4.0, fromRgb.h))
val shadesOf = shadesOf(cAM16Color.h, cAM16Color.C)
Intrinsics.checkNotNullExpressionValue(shadesOf, "shadesOf(camAccent1.h, camAccent1.C)")
accent1 = shadesOf.toList()
val shadesOf2 = shadesOf(cAM16Color2.h, cAM16Color2.C)
Intrinsics.checkNotNullExpressionValue(shadesOf2, "shadesOf(camAccent2.h, camAccent2.C)")
accent2 = shadesOf2.toList()
val shadesOf3 = shadesOf(cAM16Color3.h, cAM16Color3.C)
Intrinsics.checkNotNullExpressionValue(shadesOf3, "shadesOf(camAccent3.h, camAccent3.C)")
accent3 = shadesOf3.toList()
val shadesOf4 = shadesOf(cAM16Color4.h, cAM16Color4.C)
Intrinsics.checkNotNullExpressionValue(shadesOf4, "shadesOf(camNeutral1.h, camNeutral1.C)")
neutral1 = shadesOf4.toList()
val shadesOf5 = shadesOf(cAM16Color5.h, cAM16Color5.C)
Intrinsics.checkNotNullExpressionValue(shadesOf5, "shadesOf(camNeutral2.h, camNeutral2.C)")
neutral2 = shadesOf5.toList()
}
}<file_sep>package myui.ui.monet.colorscience
import myui.ui.monet.MathUtils
import kotlin.math.*
class CAM16ViewingConditions @JvmOverloads constructor(
dArr: DoubleArray? = D65,
d: Double = 40.0,
d2: Double = 18.0,
d3: Double = 2.0,
z: Boolean = false
) {
var mAdaptingLuminance = 0.0
var mAw = 0.0
var mBackgroundRelativeLuminance = 0.0
var mBackgroundYToWhitepointY = 0.0
var mC = 0.0
var mDiscountingIlluminant = false
val mDrgb: DoubleArray
val mDrgbInverse: DoubleArray
var mFL = 0.0
var mFLRoot = 0.0
private var mK = 0.0
var mNC = 0.0
var mNbb = 0.0
var mNcb = 0.0
var mSurround = 0.0
private var mSurroundFactor = 0.0
val mWhitepoint: DoubleArray
var mZ = 0.0
companion object {
val D65 = doubleArrayOf(95.04705587, 100.0, 108.88287364)
val DEFAULT = CAM16ViewingConditions()
}
fun adapt(d: Double): Double {
val pow = (mFL * abs(d) * 0.01).pow(0.42)
return sign(d) * 400.0 * pow / (pow + 27.13)
}
fun unadapt(d: Double): Double {
val pow = 100.0 / mFL * 27.13.pow(1.0 / 0.42)
val abs = abs(d)
return sign(d) * pow * abs(abs / (400.0 - abs)).pow(1.0 / 0.42)
}
init {
val d4: Double
val d5: Double
val d6: Double
requireNotNull(dArr) { "Whitepoint is null" }
if (dArr.size == 3) {
mWhitepoint = dArr
mAdaptingLuminance = d
mBackgroundRelativeLuminance = d2
mSurround = d3
mDiscountingIlluminant = z
d4 = if (d3 >= 1.0) {
MathUtils.lerp(0.59, 0.69, d3 - 1.0)
} else {
MathUtils.lerp(0.525, 0.59, d3)
}
mC = d4
d5 = if (d4 >= 0.59) {
MathUtils.lerp(0.9, 1.0, (d4 - 0.59) / 0.1)
} else {
MathUtils.lerp(0.8, 0.9, (d4 - 0.525) / 0.065)
}
mSurroundFactor = d5
mNC = d5
val d10 = 1.0 / (d * 5.0 + 1.0)
mK = d10
val pow = d10.pow(4.0)
val d11 = 1.0 - pow
val pow2 = pow * d + 0.1 * d11 * d11 * (5.0 * d).pow(1.0 / 3.0)
mFL = pow2
mFLRoot = pow2.pow(0.25)
val d12 = d2 / dArr[1]
mBackgroundYToWhitepointY = d12
mZ = sqrt(d12) + 1.48
val pow3 = (if (d12 != 0.0) d12.pow(-0.2) else 0.0) * 0.725
mNbb = pow3
mNcb = pow3
d6 = if (z) {
1.0
} else {
((1.0 - exp((-d - 42.0) / 92.0) / 3.6) * d5).coerceIn(0.0..1.0)
}
val matrixMultiply: DoubleArray =
MathUtils.matrixMultiply(dArr, CAM16Color.XYZ_TO_LMS)
val dArr3 = doubleArrayOf(
MathUtils.lerp(1.0, dArr[1] / matrixMultiply[0], d6),
MathUtils.lerp(1.0, dArr[1] / matrixMultiply[1], d6),
MathUtils.lerp(1.0, dArr[1] / matrixMultiply[2], d6)
)
mDrgb = dArr3
mDrgbInverse = doubleArrayOf(1.0 / dArr3[0], 1.0 / dArr3[1], 1.0 / dArr3[2])
val dArr4 = doubleArrayOf(
matrixMultiply[0] * dArr3[0],
matrixMultiply[1] * dArr3[1],
matrixMultiply[2] * dArr3[2]
)
val dArr5 = doubleArrayOf(adapt(dArr4[0]), adapt(dArr4[1]), adapt(dArr4[2]))
mAw = pow3 * (dArr5[0] * 2.0 + dArr5[1] + dArr5[2] * 0.05)
} else {
throw IllegalArgumentException("Whitepoint needs 3 coordinates in XYZ space")
}
}
}<file_sep>package myui.ui.clustering.kmeans
class Point(var x: Double, var y: Double, var z: Double) {
var index = -1 //denotes which Cluster it belongs to
fun getSquareOfDistance(anotherPoint: Point): Double {
return (x - anotherPoint.x) * (x - anotherPoint.x) + (y - anotherPoint.y) * (y - anotherPoint.y) + (z - anotherPoint.z) * (z - anotherPoint.z)
}
override fun toString(): String {
return "($x,$y,$z)"
}
}<file_sep>package myui.ui.clustering.kmeans
class Cluster(firstPoint: Point) {
val points: MutableList<Point> = arrayListOf()
var centroid: Point = firstPoint
fun updateCentroid() {
var newx = 0.0
var newy = 0.0
var newz = 0.0
for (point in points) {
newx += point.x
newy += point.y
newz += point.z
}
centroid = Point(newx / points.size, newy / points.size, newz / points.size)
}
override fun toString(): String {
val builder = StringBuilder("This cluster contains the following points:\n")
for (point in points) builder.append("$point,\n")
return builder.deleteCharAt(builder.length - 2).toString()
}
}<file_sep>package myui.ui.monet.colorscience
import kotlin.math.pow
object Contrast {
fun lstarToY(d: Double): Double {
return (if (d > 8.0) ((d + 16.0) / 116.0).pow(3.0) else d / 903.0) * 100.0
}
fun yToLstar(d: Double): Double {
val d2 = d / 100.0
return if (d2 <= 0.008856451679035631) d2 * 24389.0 / 27.0 else Math.cbrt(d2) * 116.0 - 16.0
}
}<file_sep>package myui.ui.monet
import android.util.Log
import myui.ui.monet.colorscience.CAM16Color
import myui.ui.monet.colorscience.Contrast.lstarToY
import myui.ui.monet.colorscience.MonetColor
object ColorShades {
private val DEBUG: Boolean = true
fun shadesOf(d: Double, d2: Double): IntArray {
val iArr = IntArray(11)
iArr[0] = getShade(95.0, d, d2).argb
var i = 1
while (i < 11) {
iArr[i] = getShade(if (i == 5) 49.6 else (100 - i * 10).toDouble(), d, d2).argb
i++
}
return iArr
}
private fun getShade(d: Double, d2: Double, d3: Double): MonetColor {
val gamutMap = CAM16Color.gamutMap(lstarToY(d), d3, d2)
val cAM16Color = CAM16Color(gamutMap)
if (DEBUG) {
Log.d(
"ColorShades",
"requested LHC ${d.toInt()}, ${d2.toInt()}, ${d3.toInt()}"
)
Log.d(
"ColorShades",
"got LHC ${gamutMap.lstar.toInt()}, ${cAM16Color.h.toInt()}, ${cAM16Color.C.toInt()}"
)
}
return gamutMap
}
}
|
728dc46763ac14d53d349c1cadf4aac73293bc8f
|
[
"Kotlin"
] | 14 |
Kotlin
|
HiFiiDev/MYUI
|
03473ff226603132c693a80a49b9a03426285a56
|
dc79f69954916f58904c22ba828b239b92e01933
|
refs/heads/master
|
<repo_name>alialialiali111/Ip<file_sep>/install.sh
echo "installing :)"
sleep 5
pip2 install requests
pip2 install flask
clear
echo "enjoy :)"
clear
python2 get-ip.py
|
06b384e12f9632b214761b0521dd9e829c466fea
|
[
"Shell"
] | 1 |
Shell
|
alialialiali111/Ip
|
5b51e47d78aea2382a9eab15587587b403c3d134
|
079cabd7e0cc2a615a207cc3f737b1d9593f970c
|
refs/heads/master
|
<repo_name>test-all-green/TAG_vue_admin<file_sep>/src/api/user.js
import { post, get, put, _delete } from '@/utils/http'
export function testAPI(data) {
return post('/api',data);
}
<file_sep>/src/utils/token.js
import Cookies from 'js-cookie'
const key = 'token'
export function getToken() {
return Cookies.get(key)
}
export function setToken(token) {
return Cookies.set(key, token)
}
export function removeToken() {
return Cookies.remove(key)
}
|
5be35cda68d819d91b4073adacb984848c974953
|
[
"JavaScript"
] | 2 |
JavaScript
|
test-all-green/TAG_vue_admin
|
cc2a50664ab57547fb565dd7f205b5e25246b458
|
0f0028d0109842d10831407038739373b4a3ca2e
|
refs/heads/master
|
<repo_name>crookescout/Unit_8<file_sep>/assignmentCalculator.py
# <NAME>, 11/19/19, this program is a calculator
from tkinter import *
root = Tk()
root.configure(background="pink")
def add_zero():
new_result = display_result.get()
new_result += "0"
display_result.set(new_result)
def add_one():
new_result = display_result.get()
new_result += "1"
display_result.set(new_result)
def add_two():
new_result = display_result.get()
new_result += "2"
display_result.set(new_result)
def add_three():
new_result = display_result.get()
new_result += "3"
display_result.set(new_result)
def add_four():
new_result = display_result.get()
new_result += "4"
display_result.set(new_result)
def add_five():
new_result = display_result.get()
new_result += "5"
display_result.set(new_result)
def add_six():
new_result = display_result.get()
new_result += "6"
display_result.set(new_result)
def add_seven():
new_result = display_result.get()
new_result += "7"
display_result.set(new_result)
def add_eight():
new_result = display_result.get()
new_result += "8"
display_result.set(new_result)
def add_nine():
new_result = display_result.get()
new_result += "9"
display_result.set(new_result)
def clear():
new_result = ""
display_result.set(new_result)
def divide():
new_result = display_result.get()
new_result += "/"
display_result.set(new_result)
def multiply():
new_result = display_result.get()
new_result += "*"
display_result.set(new_result)
def subtract():
new_result = display_result.get()
new_result += "-"
display_result.set(new_result)
def add():
new_result = display_result.get()
new_result += "+"
display_result.set(new_result)
def equal():
new_result = display_result.get()
new_result = eval(new_result)
display_result.set(new_result)
def percent():
new_result = display_result.get()
new_result = float(new_result) / 100
display_result.set(new_result)
def dot():
new_result = display_result.get()
new_result += "."
display_result.set(new_result)
def plus_minus():
new_result = display_result.get()
new_result = float(new_result) * -1
display_result.set(new_result)
display_result = StringVar()
display = Entry(root, textvariable=display_result, justify="right")
display.grid(row=2, column=1, columnspan=4, padx=5, pady=5)
display.configure(background="light blue")
title = Label(root, text="Calculator", font="Helvetica 20")
title.grid(row=1, column=1, columnspan=4)
title.configure(background="pink")
clear_button = Button(root, text="Clear", width=4, font="Helvetica 16", command=clear)
clear_button.grid(row=3, column=1, pady=5)
plus_minus_button = Button(root, text="+/-", width=4, font="Helvetica 16", command=plus_minus)
plus_minus_button.grid(row=3, column=2, pady=5)
percent_button = Button(root, text="%", width=4, font="Helvetica 16", command=percent)
percent_button.grid(row=3, column=3, pady=5)
divide_button = Button(root, text="/", width=4, font="Helvetica 16", command=divide)
divide_button.grid(row=3, column=4, pady=5)
seven_button = Button(root, text="7", width=4, font="Helvetica 16", command=add_seven)
seven_button.grid(row=4, column=1, pady=5)
eight_button = Button(root, text="8", width=4, font="Helvetica 16", command=add_eight)
eight_button.grid(row=4, column=2, pady=5)
nine_button = Button(root, text="9", width=4, font="Helvetica 16", command=add_nine)
nine_button.grid(row=4, column=3, pady=5)
multiply_button = Button(root, text="*", width=4, font="Helvetica 16", command=multiply)
multiply_button.grid(row=4, column=4, pady=5)
four_button = Button(root, text="4", width=4, font="Helvetica 16", command=add_four)
four_button.grid(row=5, column=1, pady=5)
five_button = Button(root, text="5", width=4, font="Helvetica 16", command=add_five)
five_button.grid(row=5, column=2, pady=5)
six_button = Button(root, text="6", width=4, font="Helvetica 16", command=add_six)
six_button.grid(row=5, column=3, pady=5)
minus_button = Button(root, text="-", width=4, font="Helvetica 16", command=subtract)
minus_button.grid(row=5, column=4, pady=5)
one_button = Button(root, text="1", width=4, font="Helvetica 16", command=add_one)
one_button.grid(row=6, column=1, pady=5)
two_button = Button(root, text="2", width=4, font="Helvetica 16", command=add_two)
two_button.grid(row=6, column=2, pady=5)
three_button = Button(root, text="3", width=4, font="Helvetica 16", command=add_three)
three_button.grid(row=6, column=3, pady=5)
plus_button = Button(root, text="+", width=4, font="Helvetica 16", command=add)
plus_button.grid(row=6, column=4, pady=5)
zero_button = Button(root, text="0", width=4, font="Helvetica 16", command=add_zero)
zero_button.grid(row=7, column=1, pady=5)
dot_button = Button(root, text=".", width=4, font="Helvetica 16", command=dot)
dot_button.grid(row=7, column=2, pady=5)
equal_button = Button(root, text="=", width=9, font="Helvetica 16", command=equal)
equal_button.grid(row=7, column=3, columnspan=2, pady=5)
root.mainloop()
<file_sep>/daily_exercises.py
# <NAME>, 11/15/19, this function works on daily exerceises for Unit 8
from tkinter import *
root = Tk()
# 1
#
# hello_label = Label(root, text="Hello, World")
# hello_label.grid(row=1, column=1)
# 2
#
# def say_hello():
# other_name = user_name.get()
# if other_name == "":
# name.set("You forgot to enter your name")
# else:
# name.set("Hello, " + other_name)
#
#
# user_name = StringVar()
# name = StringVar()
# enter_name = Entry(root, textvariable=user_name)
# enter_name.grid(row=1, column=1)
#
# hello_label = Label(root, textvariable=name)
# hello_label.grid(row=2, column=1)
#
# hello_button = Button(root, text="Say Hello", command=say_hello)
# hello_button.grid(row=3, column=1)
# 3
def convert_temp():
new_temp = (temp - 32) * 5/9
return new_temp
temp = IntVar()
new_temp = IntVar()
enter_temp = Entry(root, text="degrees F:", textvariable=temp)
enter_temp.grid(row=1, column=2)
degreeF_label = Label(root, text="degrees F:")
degreeF_label.grid(row=1, column=1)
degreeC_label = Label(root, text="degrees C:")
degreeC_label.grid(row=2, column=1)
convert_button = Button(root, text="Convert", command=convert_temp)
convert_button.grid(row=3, column=2)
root.mainloop()
|
4e0f8c43b5b3ae456897d810d1c3ec2dd2ba435e
|
[
"Python"
] | 2 |
Python
|
crookescout/Unit_8
|
0d219761b479344c30aa035f2df1f334e1bb2eb5
|
099ae134ba7e1d70e6f3180fb177fd9f331019a1
|
refs/heads/master
|
<repo_name>kombojiec/github-search<file_sep>/src/components/Repos.js
import React from 'react';
const Repos = ({repos}) => {
const repositories = repos.map(repo => (
<li className="repo__item" key={repo.id}>
<a
href={repo.html_url}
target="_blank"
rel="noreferrer"
className="repo__link"
>{repo.name}</a>
</li>
))
return(
<div className="repo">
<h1 className='repo__title'>Rpositories</h1>
<ul className="repo__list">
{repositories}
</ul>
</div>
)
}
export default Repos;<file_sep>/README.md
# github-search
**О проекте**
Этот [проект](https://kombojiec.github.io/github-search/) является реализацией работы с использованием библиотеки React.js с использованием функциональных компонентов. API предоставляет github.
Проект реализован на React.js и препроцессоре SCSS. В проекте отрабатываются базове возможности библиотеки:
* работа с функциональными компонентами
* работа слокальным стэйтом
* работа с данными, полученными с сервера
<file_sep>/src/components/Navbar.js
import React from 'react';
import {NavLink} from 'react-router-dom';
const Navbar = props => {
return(
<nav className="nav">
<div className="nav__logo">Github Search</div>
<ul className="nav__list">
<li className="nav__item">
<NavLink to="/" exact className="nav__link">Home</NavLink>
</li>
<li className="nav__item">
<NavLink to="/about" className="nav__link">About</NavLink>
</li>
</ul>
</nav>
)
}
export default Navbar;<file_sep>/src/components/Alert.js
import React, {useContext} from 'react';
import AlertContext from '../context/alert/AlertContext';
const Alert = () => {
const {alert, hide} = useContext(AlertContext);
return(
alert?
<div className={`alert ${alert.type || ''}`}>
{alert.text || 'some information'}
<button className="alert__button" onClick={hide}></button>
</div>:
null)
}
export default Alert;
|
3d46b063e708b3a74d0901ff415c37a1dfdf8601
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
kombojiec/github-search
|
73ee2f6d04e60e5ac32384d18165142bc72e7b2c
|
e1fe16c9284d5da486260a78f948ce3cc129e1a7
|
refs/heads/master
|
<file_sep>---------------------------------------------
------------- GENERAL TEMPLATE---------------
------------ by VADS \\--// 2014 ------------
---------------------------------------------
--() Shortcuts ()--
-------------------
local graphics = love.graphics
local mouse = love.mouse
--Set Default image filter
graphics.setDefaultFilter("nearest", "nearest")
--// Imports \\--
-----------------
--Utils (Misc Stuff)
require("libs.Utils")
local flux = require("libs.flux")
local Fader = require("game.Fader")
local SceneManager = require("libs.SceneManager")
local Console = require("game.objects.Console")
--TSerial (Serialization)
require("libs.TSerial")
-- // Scenes \\ --
------------------
local Splash = require("scenes.Splash")
local MainMenu = require("scenes.MainMenu")
local GameScreen = require("scenes.GameScreen")
-- // Constants \\ --
---------------------
--Original scale
ORSCALEX, ORSCALEY = 3, 3
--Original dimensions
ORWIDTH, ORHEIGHT = love.window.getDimensions()
-- // Globals \\ --
-------------------
WIDTH, HEIGHT = ORWIDTH, ORHEIGHT
SCALEX, SCALEY = ORSCALEX, ORSCALEY
-- // Fonts \\ --
FONTS = {
tiny = graphics.newFont("assets/fonts/font.ttf", 16),
small = graphics.newFont("assets/fonts/font.ttf", 20),
medium = graphics.newFont("assets/fonts/font.ttf", 30),
}
function love.load()
-- Setup scenes
SceneManager.newScene(Splash, "Splash")
SceneManager.newScene(MainMenu, "MainMenu")
SceneManager.newScene(GameScreen, "GameScreen")
-- Set first scene
SceneManager.setScene("Splash")
-- Setup Console
Console:create(64, HEIGHT - 86, WIDTH - 128, 86)
end
function love.update(dt)
--Lurker (Realtime Code Changing)
require('libs.lurker'):update(dt)
SceneManager.update(dt)
Fader.update(dt)
flux.update(dt)
Console:update(dt)
end
function love.draw()
SceneManager.draw()
Fader.draw()
Console:draw()
end
function love.keypressed(key)
if not Console.active then SceneManager.keypressed(key) end
Console:keypressed(key)
end
function love.mousepressed(x, y, button)
SceneManager.mousepressed(x, y, button)
end
function love.textinput(t)
Console:textinput(t)
end
function love.resize(w, h)
WIDTH, HEIGHT = w, h
SCALEX = (WIDTH / ORWIDTH) * ORSCALEX
SCALEY = (HEIGHT / ORHEIGHT) * ORSCALEY
SceneManager.resize(w, h)
end
function love.visible(v)
SceneManager.visible(v)
end
<file_sep>
------------ GAMESTATE MainMenu--------------
------------ by VADS \\--// 2014 ------------
---------------------------------------------
local MainMenu = {}
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local Fader = require("game.Fader")
local ButtonManager = require("game.ButtonManager")
local SceneManager = require("libs.SceneManager")
-- Variables
local buttons = ButtonManager:create()
local gameLogo = love.graphics.newImage("assets/gfx/main_logo.png")
function MainMenu:enter()
-- Setup buttons
buttons:clear()
buttons:addButton("New Game", "text", ORWIDTH / 2, ORHEIGHT / 2 + 70, function() Fader.fadeTo("GameScreen") end)
buttons:addButton("Options", "text", ORWIDTH / 2, ORHEIGHT / 2 + 100, function()end)
local function visitHomepage() love.system.openURL("http://www.indiedb.com/company/destructivereality") end
buttons:addButton("Developer Page", "text", ORWIDTH / 2, ORHEIGHT / 2 + 130, visitHomepage)
buttons:addButton("Exit to Desktop", "text", ORWIDTH / 2 , ORHEIGHT / 2 + 160, function() Fader.fadeTo("exit") end)
end
function MainMenu:leave()end
function MainMenu:init() end
function MainMenu:update(dt)
buttons:update(dt)
end
function MainMenu:draw()
local imgw, imgh = gameLogo:getWidth() * SCALEX, gameLogo:getHeight() * SCALEY
graphics.draw(gameLogo, WIDTH / 2 - imgw / 2, HEIGHT / 2 - imgh / 2 - 64, 0, SCALEX, SCALEY)
buttons:draw()
end
function MainMenu:keypressed(key)
if key == "return" then SceneManager.setScene("GameScreen") end
if key == "escape" then SceneManager.setScene("Splash") end
end
function MainMenu:mousepressed(x, y, button)
buttons:mousepressed(x, y, button)
end
function MainMenu:resize(w, h)
self:enter()
end
function MainMenu:visible(v) end
function MainMenu:quit() end
return MainMenu
<file_sep>
------------ GAMESTATE GameScreen------------
------------ by VADS \\--// 2014 ------------
---------------------------------------------
local GameScreen = {}
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
-- Animation library
require("libs.AnAL")
local SceneManager = require("libs.SceneManager")
--Requires
local moneyManager = require("game.MoneyManager")
local Toolbar = require("game.Toolbar")
local Journal = require("game.Journal")
local Phone = require("game.objects.Phone")
local TimeBox = require("game.objects.TimeBox")
local Calender = require("game.objects.Calender")
local Console = require("game.objects.Console")
local Window = require("game.objects.Window")
--Sprites
local background = graphics.newImage("assets/gfx/game_room.png")
local infobar = graphics.newImage("assets/gfx/ui_bar.png")
local speechbox = graphics.newImage("assets/gfx/ui_speechbubble.png")
--Animation sprites
local advisorImg = graphics.newImage("assets/gfx/advisor_anim.png")
--Animations
local advisor = newAnimation(advisorImg, 16, 16, 0.3, 0)
function GameScreen:enter()
--Loading stuff
self.textbox = Console.textbox
Toolbar:setup()
Journal:setup()
moneyManager:setup()
Phone:setup()
TimeBox:setup()
Calender:setup()
Window:setup()
self.textbox:pushMessage("Game started!", "info")
end
function GameScreen:leave()end
function GameScreen:init()end
function GameScreen:update(dt)
--Animation updates
advisor:update(dt)
--Toolbar/Journal update
Toolbar:update(dt)
Journal:update(dt)
-- Objects
Phone:update(dt)
TimeBox:update(dt)
Calender:update(dt)
Window:update(dt)
end
function GameScreen:draw()
-- Draw stuff
graphics.draw(background, 0, 0, 0, SCALEX, SCALEY)
graphics.draw(infobar, WIDTH - infobar:getWidth() * SCALEX - 8 * (SCALEX / ORSCALEX), 10 * (SCALEY / ORSCALEY), 0, SCALEX, SCALEY)
-- Objects
Window:draw()
Calender:draw()
moneyManager:draw()
TimeBox:draw()
Toolbar:draw()
Journal:draw()
Phone:draw()
--Speechbubble
graphics.draw(speechbox, 16 * SCALEX, 5 * SCALEY, 0 ,SCALEX, SCALEY)
printFont(FONTS.tiny, "Hey! What's up?", 130, 32)
--Animations
advisor:draw(2.5 * SCALEX, 5 * SCALEY, 0, SCALEX, SCALEY)
end
function GameScreen:keypressed(key)
if key == "escape" then SceneManager.setScene("MainMenu") end
end
function GameScreen:mousepressed(x, y, button)
Toolbar:mousepressed(x, y, button)
Journal:mousepressed(x, y, button)
Phone:mousepressed(x, y, button)
TimeBox:mousepressed(x, y, button)
Calender:mousepressed(x, y, button)
end
function GameScreen:resize(w, h)
Toolbar:setupObjects()
Journal:setupObjects()
moneyManager:setupObjects()
Phone:setupObjects()
TimeBox:setupObjects()
Calender:setupObjects()
end
function GameScreen:visible(v)end
return GameScreen
<file_sep>
-- // TimeBox \\ --
-------------------
local Object = require("game.objects.Object")
local TimeBox = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local ButtonManager = require("game.ButtonManager")
local moneyManager = require("game.MoneyManager")
-- // Variables \\ --
---------------------
local monthDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
local monthNames = {"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"}
--Time advancing speed
local speed = { stop = 0, slow = .05, medium = .2, fast = 5 }
-- Create Button Handler
local buttons = ButtonManager:create()
local button1, button2, button3
local function setSelected(currentButton)
for i, button in ipairs(buttons:getArray()) do
button:setColor({150, 150, 150}, {255, 255, 255})
if currentButton == button then
button:setColor({50, 200, 50}, {50, 255, 50})
end
end
end
function TimeBox:setup()
self.day = 27
self.month = 4
self.year = 1960
self.timer = 0
self.speed = .1
self.money = 10000
self.font = FONTS.medium
self:setupObjects()
end
function TimeBox:setupObjects()
-- Setup object
self:setImage(graphics.newImage("assets/gfx/ui_box.png"))
self:setPosition(304, 7)
-- Setup Buttons
buttons:clear()
-- // Stop \\ --
------------------------
button0 = buttons:addButton("Stop", "image", 0, 0, function()
self.speed = speed.stop
setSelected(button0)
button0:setColor({200, 50, 50}, {255, 100, 100})
end)
button0:setImage(graphics.newImage("assets/gfx/ui_timeButton0.png"))
button0:setParent(self)
button0:setPosition(self:getWidth() / 2 - 42 - button0:getWidth() / 2, 38)
-- // Normal Speed \\ --
------------------------
button1 = buttons:addButton("Normal Time", "image", 0, 0, function()
self.speed = speed.slow
setSelected(button1)
end)
button1:setImage(graphics.newImage("assets/gfx/ui_timeButton1.png"))
button1:setParent(self)
button1:setPosition(self:getWidth() / 2 - 19 - button1:getWidth() / 2, 35)
setSelected(button1)
-- // Double Speed \\ --
------------------------
button2 = buttons:addButton("Double Time", "image", 0, 0, function()
self.speed = speed.medium
setSelected(button2)
end)
button2:setImage(graphics.newImage("assets/gfx/ui_timeButton2.png"))
button2:setParent(self)
button2:setPosition(self:getWidth() / 2 - 6, 35)
-- // Triple Speed \\ --
------------------------
button3 = buttons:addButton("Triple Time", "image", 0, 0, function()
self.speed = speed.fast
setSelected(button3)
end)
button3:setImage(graphics.newImage("assets/gfx/ui_timeButton3.png"))
button3:setParent(self)
button3:setPosition(self:getWidth() / 2 + 36 - button3:getWidth() / 2, 35)
end
function TimeBox:update(dt)
-- Update buttons
buttons:update(dt)
--Updating/increasing time
if self.speed > 0 then self.timer = self.timer + dt end
if self.timer >= 1 / self.speed then
self:nextDay()
self.timer = 0
end
end
function TimeBox:draw()
--Draws the money value on the screen
graphics.draw(self.image, self.x, self.y, 0, SCALEX, SCALEY)
printFontCentered(self.font, self:getDateString(), self.x + self.w / 2, self.y + self.h / 2 - 28, WIDTH)
-- Set button color if selected
-- Draw Buttons
buttons:draw()
end
function TimeBox:mousepressed(x, y, button)
buttons:mousepressed(x, y, button)
end
function TimeBox:getDateString()
return self.day..". "..monthNames[self.month].." "..self.year
end
function TimeBox:nextDay()
--Counting up day/month
if self.day == monthDays[self.month] then
self.day = 1
self.month = self.month + 1
--Calls both the day and month action function
self:actionOnDay()
self:actionOnMonth()
else
self.day = self.day + 1
--Calls the day action function
self:actionOnDay()
end
--Counting up year
if self.month > 12 then
self.year = self.year + 1
self.month = 1
--Calls the action on year function
self:actionOnYear()
if self.year % 4 == 0 then
if self.year % 100 == 0 then
if self.year % 400 == 0 then
monthDays[2] = 29
else
monthDays[2] = 28
end
else
monthDays[2] = 29
end
else
monthDays[2] = 28
end
end
end
function TimeBox:addDays(days)
for i = 0, days - 1, 1 do
self:nextDay()
end
end
function TimeBox:actionOnDay()
end
function TimeBox:actionOnMonth()
moneyManager.money = moneyManager.money + 1000
self:setTimeState("stop")
end
function TimeBox:actionOnYear()
end
--Todo - Funktioniert so nicht, hält nur die Zeit an
function TimeBox:toggleTimeAdvancing()
button0.action()
end
function TimeBox:setTimeState(state)
if state == "stop" then button0.action() end
if state == "slow" then button1.action() end
if state == "medium" then button2.action() end
if state == "fast" then button3.action() end
end
function TimeBox:getCurrentMonthName()
return monthNames[self.month]
end
function TimeBox:isTimeAdvancing()
return self.speed > 0
end
return TimeBox
<file_sep>
------------ Toolbar --------------
------------ by VADS \\--// 2014 --
-----------------------------------
local Object = require("game.objects.Object")
local Toolbar = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local flux = require("libs.flux")
local ButtonManager = require("game.ButtonManager")
local Journal = require("game.Journal")
local textBox = require("game.objects.TextBox")
-- Variables
local buttons = ButtonManager:create()
local buttonFinancial, buttonJournal, buttonClose
local icons = graphics.newImage("assets/gfx/ui_toolIcons.png")
local function moveToolbar()
local self = Toolbar
if self.state ~= ("movingin" or "movingout") then
if self.state == "in" then
self.state = "movingout"
--move the Toolbar to the right
flux.to(self, 0.5, { x = - self.image:getWidth() * SCALEX + 2 * SCALEX }):oncomplete(function() self.state = "out" end)
elseif self.state == "out" then
self.state = "movingin"
--Move the Toolbar to the left
flux.to(self, 0.5, { x = 0 }):oncomplete(function() self.state = "in" end)
end
end
end
function Toolbar:setup()
self.state = "in"
self:setupObjects()
self.drawHitboxes = false
end
function Toolbar:setupObjects()
-- Setup object
self:setImage(graphics.newImage("assets/gfx/ui_tools.png"))
self:setPosition(0, 120)
-- Setup buttons
buttons:clear()
-- // CLOSE \\ --
-----------------
buttonClose = buttons:addButton("Close", "image", 0, 0, moveToolbar)
buttonClose:setImage(graphics.newImage("assets/gfx/ui_toolsbutton.png"))
buttonClose:setParent(Toolbar)
buttonClose:setPosition(self:getWidth() - 2 , 10)
-- // FINANCIAL \\ --
---------------------
local w, h = 12, 6
buttonFinancial = buttons:addButton("Financial", "image", 1, 15, function() Journal:setActive(not Journal.active) end)
buttonFinancial:setDimensions(w, h)
buttonFinancial:setImage(graphics.newQuad(1, 1, w, h, 112, 8), icons)
buttonFinancial:setParent(Toolbar)
-- // JOURNAL \\ --
-------------------
w, h = 8, 8 -- local
buttonJournal = buttons:addButton("Journal", "image", 7, 48, function() Journal:setActive(not Journal.active) end)
buttonJournal:setDimensions(w, h)
buttonJournal:setImage(graphics.newQuad(17, 0, w, h, 112, 8), icons)
buttonJournal:setParent(Toolbar)
end
function Toolbar:update(dt)
buttons:update(dt)
end
function Toolbar:draw()
-- Draw Toolbar Image
graphics.draw(self.image, self.x, self.y, 0, SCALEX, SCALEY)
-- Draw Buttons
buttons:draw()
-- Draw Hitboxes
if self.drawHitboxes then
for _, button in ipairs(buttons:getArray()) do button:setHitboxVisible(true) end
end
-- Reset Color
graphics.setColor(255, 255, 255, 255)
end
function Toolbar:mousepressed(x, y, button)
buttons:mousepressed(x, y, button)
end
return Toolbar
<file_sep>
-------------------------
-- // ButtonManager \\ --
-------------------------
local ButtonManager = {}
ButtonManager.__index = ButtonManager
-- // Dependencies \\ --
------------------------
local Button = require("game.objects.Button")
function ButtonManager:create()
local self = setmetatable({}, ButtonManager)
self.buttons = {}
return self
end
function ButtonManager:getArray()
return self.buttons
end
function ButtonManager:addButton(name, mode, x, y, action)
local button = Button:create(name, mode, x, y, action)
table.insert(self.buttons, button)
return button
end
function ButtonManager:clear()
self.buttons = {}
end
function ButtonManager:update(dt)
for k, v in ipairs(self.buttons) do
v:update(dt)
end
end
function ButtonManager:draw()
for k, v in ipairs(self.buttons) do
v:draw()
end
end
function ButtonManager:mousepressed(x, y, button)
for k, v in ipairs(self.buttons) do
if button == "l" and v.selected then v.action() end
end
end
return ButtonManager
<file_sep>
-- // DEBUG COSOLE \\ --
------------------------
local Object = require("game.objects.Object")
local Console = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local InputBox = require("game.objects.InputBox")
local TextBox = require("game.objects.TextBox")
function Console:create(x, y, w, h)
self.x = x
self.y = y
self.w = w
self.h = h
self.active = false
self.textbox = TextBox:create(self.x + 2, self.y + 2, self.w - 4, self.h - self.h / 3)
self.textbox:pushMessage("'Credits, Please' Console", "")
self.textbox:pushMessage("------------------", "")
self.inputbox = InputBox:create(self.x + 2, self.y + self.h - 24, self.w - 4)
self.inputbox:setTarget(self.textbox)
end
function Console:update(dt)
if self.active then
self.inputbox:update(dt)
end
end
function Console:draw()
if self.active then
graphics.setColor(15, 5, 5, 220)
graphics.rectangle("fill", self.x, self.y, self.w, self.h)
graphics.setColor(255, 255, 255, 255)
self.inputbox:draw()
self.textbox:draw()
end
end
function Console:keypressed(key)
if key == "f1" then
self.active = not self.active
end
if self.active then
if key == "escape" then self.active = false end
self.inputbox:keypressed(key)
end
end
function Console:textinput(t)
if self.active then self.inputbox:textinput(t) end
end
return Console
<file_sep>
-- // TEXT BOX \\ --
--------------------
local Object = require("game.objects.Object")
local TextBox = Object:create()
TextBox.__index = TextBox
--() Shortcuts ()--
-------------------
local graphics = love.graphics
local types = {
["system"] = {name = "System: ", color = {255, 255, 255}},
["warning"] = {name = "Warning: ", color = {180, 0, 0}},
["info"] = {name = "Info: ", color = {0, 180, 0}},
[""] = {name = "", color = {255, 255, 255}},
}
function TextBox:pushMessage(text, msgType)
local newMessage = {}
newMessage.x = self.x
newMessage.y = self.y + self.h - self.font:getHeight()
newMessage.msgType = types[msgType]
newMessage.text = types[msgType].name..text
newMessage.color = types[msgType].color or {255, 255, 255}
-- Update positions
for _, message in ipairs(self.textArray) do
message.y = message.y - self.font:getHeight()
end
-- Insert message
table.insert(self.textArray, newMessage)
-- Delete oldest message
if #self.textArray > self.h / self.font:getHeight() then
table.remove(self.textArray, 1)
end
end
function TextBox:create(x, y, w, h)
local self = setmetatable({}, TextBox)
self.font = FONTS.tiny
self.textArray = {}
self.w = w or WIDTH
self.h = h or self.font:getHeight() * 2
self.x = x
self.y = y
return self
end
function TextBox:draw()
graphics.setColor(255, 255, 255, 100)
graphics.rectangle("fill", self.x, self.y, self.w, self.h)
for k, message in ipairs(self.textArray) do
local r, g, b = message.color[1], message.color[2], message.color[3]
graphics.setColor(r, g, b, 255)
printFont(self.font, message.text, message.x, message.y)
end
graphics.setColor(255, 255, 255, 255)
end
return TextBox
<file_sep>
return {
-- // Cheapest \\ --
["hair salon"] = {
category = "Low risk",
description =
"I need a credit to accomplish my dream of an own hair salon.",
cost = 16000,
risk = .1, -- 10 % to fail
bonus = 0,
},
["auto shop"] = {
description = [[
]],
cost = 12000,
},
-- // cheap \\ --
["wild west park"] = {
description = [[
]],
cost = 16990,
},
-- // expensive \\ --
["swimming bath"] = {
description = [[
]],
cost = 16990,
},
[""] = {
},
["wild west park"] = {
},
["super market"] = {
description = [[
]],
cost = 16990,
},
["gas station"] = {
description = [[
]],
cost = 16990,
},
}<file_sep>
-- // Base Object Class \\ --
-----------------------------
local Object = {}
Object.__index = Object
-- Variables
Object.removed = false
local function boxCollision(a, b)
return a.x + a.w > b.x and a.x < b.x + b.w and
a.y + a.h > b.y and a.y < b.y + b.h
end
function Object:create()
local self = setmetatable({}, Object)
self.removed = false
return self
end
function Object:destroy()
self.removed = true
end
-- // HITBOXES \\ --
--------------------
function Object:setHitbox(x, y, w, h)
self.hitbox = {x = x, y = y, w = w, h = h}
end
function Object:getHitbox()
return {x = self.hitbox.x, y = self.hitbox.y, w = self.hitbox.w, h = self.hitbox.h}
end
-- // COLLISION \\ --
---------------------
function Object:boxCollision(Object)
if not self.hitbox then assert("No hitbox set!") end
if boxCollision(self.hitbox, Object) then return true end
end
-- // FONT \\ --
----------------
function Object:setFont(font)
self.font = font
self.w = self.font:getWidth(self.name)
self.h = self.font:getHeight()
end
-- // POSITION \\ --
--------------------
function Object:setPosition(x, y)
if x then
self.startx = x * (SCALEX / ORSCALEX)
self.x = self.startx
end
if y then
self.starty = y * (SCALEY / ORSCALEY)
self.y = self.starty
end
self:setHitbox(self.x, self.y, self.w, self.h)
end
function Object:getPosition()
return self.x, self.y
end
-- // IMAGE / QUAD \\ --
------------------------
function Object:setImage(image, quadImage)
self.image = image
if quadImage then
self.quadImage = quadImage
else
self.w = self.image:getWidth() * SCALEX
self.h = self.image:getHeight() * SCALEY
end
self:setHitbox(self.x, self.y, self.w, self.h)
end
-- // WIDTH / HEIGHT \\ --
--------------------------
function Object:setDimensions(w, h)
self.w, self.h = w * SCALEX, h * SCALEY
self:setHitbox(self.x, self.y, self.w, self.h)
end
function Object:getWidth()
return self.w / (SCALEX / ORSCALEX)
end
function Object:getHeight()
return self.h / (SCALEY / ORSCALEY)
end
-- // OTHER \\ --
-----------------
function Object:setActive(v)
self.active = v
end
function Object:setParent(parent)
self.parent = parent
end
return Object
<file_sep>
------------ GAMESTATE Splash--------------
------------ by VADS \\--// 2014 ----------
-------------------------------------------
local Splash = {}
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local SceneManager = require('libs.SceneManager')
local Fader = require("game.Fader")
local flux = require("libs.flux")
-- Variables
local drLogo, drBackground
function Splash:setupObjects()
--Splash screen gameLogo
drBackground = love.graphics.newImage("assets/gfx/drBackground.png")
drLogo = { x = ORWIDTH / 2, y = ORHEIGHT / 2, alpha = 0, img = graphics.newImage("assets/gfx/drLogo.png"),
scaleX = SCALEX / 2 , scaleY = SCALEY / 2}
end
function Splash:enter()
self:setupObjects()
flux.to(drLogo, 2, {alpha = 255, scaleX = SCALEX / 1.5, scaleY = SCALEY / 1.5})
:delay(.5)
:after(drLogo, 0.5, {alpha = 255})
:delay(1.5)
:oncomplete(function() Fader.fadeTo("MainMenu", 150) end)
end
function Splash:leave()
Fader.clear()
if flux.tweens[1] then flux.remove(1) end
end
function Splash:init()end
function Splash:update(dt)end
function Splash:draw()
--previous Color
local r,g,b,a = graphics.getColor()
love.graphics.draw(drBackground, 0, 0, 0, SCALEX, SCALEY)
graphics.setColor(255, 255, 255, drLogo.alpha)
graphics.draw(drLogo.img, drLogo.x * (SCALEX / ORSCALEX), drLogo.y * (SCALEY / ORSCALEY), 0, drLogo.scaleX, drLogo.scaleY,
drLogo.img:getWidth() / 2, drLogo.img:getHeight() / 2)
--Reapply previous color
graphics.setColor(r,g,b,a)
end
function Splash:keypressed(key)
if key == "r" then
SceneManager.setScene("Splash")
Fader.clear()
if flux.tweens[1] then flux.remove(1) end
end
if key == " " then
SceneManager.setScene("MainMenu")
Fader.clear()
if flux.tweens[1] then flux.remove(1) end
end
if key == "escape" then love.event.quit() end
end
function Splash:mousepressed(x, y, button)
SceneManager.setScene("MainMenu")
Fader.clear()
if flux.tweens[1] then flux.remove(1) end
end
function Splash:resize(w, h)
self:setupObjects()
end
function Splash:visible(v)end
return Splash
<file_sep>
------------ Journal --------------
------------ by VADS \\--// 2014 --
-----------------------------------
local Object = require("game.objects.Object")
local Journal = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local ButtonManager = require("game.ButtonManager")
local textBox = require("game.objects.TextBox")
-- Variables
local buttons = ButtonManager:create()
local buttonClose
function Journal:setup()
self.alpha = 255
self.active = false
self:setupObjects()
--For debugging
self.drawHitboxes = false
end
function Journal:setupObjects()
-- Setup object
self:setImage(graphics.newImage("assets/gfx/ui_journal.png"))
self:setPosition(ORWIDTH / 2 - self:getWidth() / 2, ORHEIGHT / 2 - self:getHeight() / 2)
-- Setup buttons
buttons:clear()
-- // CLOSE \\ --
-----------------
buttonClose = buttons:addButton("Close", "image", 0, 0, function() self:setActive(false) end)
buttonClose:setImage(graphics.newImage("assets/gfx/ui_windowButton.png"))
buttonClose:setParent(self)
buttonClose:setPosition(self:getWidth() - buttonClose:getWidth(), 0)
end
function Journal:draw()
if self.active then
graphics.draw(self.image, self.x, self.y, 0, SCALEX, SCALEY)
buttons:draw()
-- Draw Hitboxes
if self.drawHitboxes then
graphics.setColor(255, 0, 0, 255)
for _, button in ipairs(buttons:getArray()) do
local hitbox = button:getHitbox()
graphics.rectangle("line", hitbox.x, hitbox.y, hitbox.w, hitbox.h)
end
end
graphics.setColor(255, 255, 255)
end
end
function Journal:update(dt)
buttons:update(dt)
end
function Journal:mousepressed(x, y, button)
if self.active then
buttons:mousepressed(x, y, button)
end
end
return Journal
<file_sep>
-------------------------
-- // ObjectHandler \\ --
-------------------------
local ObjectHandler = {}
ObjectHandler.__index = ObjectHandler
--[[
Copyright (c) 2013 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--]]
------------------------
-- // Declarations \\ --
------------------------
function ObjectHandler.new(o)
local self = o or {}
self.name = self.name or "Handler"
self.container = {}
setmetatable(self, ObjectHandler)
return self
end
function ObjectHandler:add(v)
table.insert(self.container, v)
end
function ObjectHandler:destroy()
self.container = {}
end
function ObjectHandler:getAmount(name)
local amount = 0
for k = 1, #self.container do
local v = self.container[k]
if v.name == name then amount = amount + 1 end
end
return amount
end
function ObjectHandler:update(dt)
for k = #self.container, 1, -1 do
local v = self.container[k]
if not v.removed then
v:update(dt)
else
table.remove(self.container, k)
end
end
end
function ObjectHandler:draw()
for k = 1, #self.container do
local v = self.container[k]
v:draw()
end
end
function ObjectHandler:mousepressed(...)
for _,v in ipairs(self.container) do
if v.mousepressed then v:mousepressed(...) end
end
end
function ObjectHandler:mousereleased(...)
for _,v in ipairs(self.container) do
if v.mousereleased then v:mousereleased(...) end
end
end
function ObjectHandler:keypressed(...)
for _,v in ipairs(self.container) do
if v.keypressed then v:keypressed(...) end
end
end
function ObjectHandler:keyreleased(x, y, button)
for _,v in ipairs(self.container) do
if v.keyreleased then v:keyreleased(x, y, button) end
end
end
return ObjectHandler
<file_sep>
local commands = {}
-- // Dependencies \\ --
------------------------
local SceneManager = require("libs.SceneManager")
local moneyManager = require("game.MoneyManager")
local TimeBox = require("game.objects.TimeBox")
local function newCommand(name, text, msgType, action)
local command = {}
command.text = text
command.msgType = msgType or "system"
command.action = action
commands[name] = command
end
newCommand("test", "Does work!", "info")
newCommand("exit", "", "info", function() love.event.quit() end)
newCommand("restart", "", "info", function() love.load() end)
newCommand("goto", "", "info",
function(textbox, scene)
if scene and scene ~= "" then
SceneManager.setScene(scene)
textbox:pushMessage("Scene '"..scene.."' has been set.", "info")
else
textbox:pushMessage("Try again: goto SCENENAME", "warning")
end
end)
newCommand("addmoney", "", "info",
function(textbox, money)
money = tonumber(money)
if money and money > 0 then
moneyManager:addMoney(money)
textbox:pushMessage("Added "..money.."$ to your account.", "info")
else textbox:pushMessage("Try again: addmoney AMOUNT", "warning") end
end)
newCommand("time", "Time toogled!", "info", function(textbox, v) if v == "toogle" then TimeBox:toggleTimeAdvancing() end end)
newCommand("vsync", "Vsync changed!", "info",
function(textbox, v)
if not v then
love.window.setMode(WIDTH, HEIGHT, {vsync = not vsync})
end
if v == "off" then love.window.setMode(WIDTH, HEIGHT, {vsync=false})
elseif v == "on" then love.window.setMode(WIDTH, HEIGHT, {vsync=true})
end
end)
newCommand("fullscreen", "fullscreen toogled!", "info",
function()
if love.window.getFullscreen() then love.window.setFullscreen(false)
else love.window.setFullscreen(true)
end
end)
newCommand("fps", "", "", function(textbox) textbox:pushMessage("FPS: "..love.timer.getFPS(), "system")end)
-- Help command
local function helpFunction(textbox)
local list = ""
for k, command in pairs(commands) do
list = list.." "..k
end
textbox:pushMessage(list, "system")
end
newCommand("help", "Available commands:", "system", helpFunction)
return commands
<file_sep>
-- // Button Class \\ --
------------------------
local Object = require("game.objects.Object")
local Button = Object:create()
Button.__index = Button
--() Shortcuts ()--
-------------------
local graphics = love.graphics
function Button:create(name, mode, x, y, action)
local self = setmetatable({}, Button)
self.name = name
self.startx = x * (SCALEX / ORSCALEX)
self.starty = y * (SCALEY / ORSCALEY)
self.x = x
self.y = y
self.mode = mode
self.active = true
self.selected = false
self.rotation = 0
self.color = {150, 150, 150}
self.selectedColor = {255, 255, 255}
self.isHitboxVisible = false
self.action = action or nil
-- Setup text button
if mode == "text" then
self:setFont(FONTS.medium)
self:setPosition(self.x - (self:getWidth() / 2), self.y - (self.h / 2 / self:getHeight()))
self:setHitbox(self.x, self.y + 8, self.w, self.h - 14)
end
return self
end
function Button:setSelected(boolean)
self.selected = boolean
end
function Button:setMode(mode)
self.mode = mode
end
function Button:setColor(normal, selected)
self.color = normal
self.selectedColor = selected
end
function Button:setHitboxVisible(v)
self.isHitboxVisible = v
end
function Button:update(dt)
local mouse = {x = love.mouse.getX(), y = love.mouse.getY(), w = 1, h = 1}
if self.active and self.hitbox then
self.selected = false
if self:boxCollision(mouse) then
self.selected = true
end
end
-- Update position
if self.parent then
self.x = self.startx + self.parent.x
self.y = self.starty + self.parent.y
self:setHitbox(self.x, self.y, self.w , self.h)
end
end
function Button:draw()
-- Set Color
local r, g, b = unpack(self.selectedColor)
if self.selected then
graphics.setColor(r, g, b, 255)
else
r, g, b = unpack(self.color)
graphics.setColor(r, g, b, 255)
end
-- TEXT BUTTON --
-----------------
if self.mode == "text" then
printFont(self.font, self.name, self.x, self.y)
end
-- IMAGE BUTTON --
------------------
if self.mode == "image" then
if not self.image then assert(self.image, "No image set!") end
if self.quadImage then graphics.draw(self.quadImage, self.image, self.x, self.y, self.rotation, SCALEX, SCALEY)
else graphics.draw(self.image, self.x, self.y, self.rotation, SCALEX, SCALEY) end
end
if self.isHitboxVisible then
local hitbox = self.hitbox
graphics.setColor(255, 0, 0, 255)
if hitbox then graphics.rectangle("line", hitbox.x, hitbox.y, hitbox.w, hitbox.h) end
end
graphics.setColor(255, 255, 255, 255)
end
function Button:mousepressed(x, y, button)
if button == "l" and self.selected then self.action() end
end
return Button
<file_sep>
-- // INPUT BOX \\ --
---------------------
local Object = require("game.objects.Object")
local InputBox = Object:create()
InputBox.__index = InputBox
--() Shortcuts ()--
-------------------
local graphics = love.graphics
local keyboard = love.keyboard
-- // Dependencies \\ --
------------------------
local commands = require("scripts.commands")
function InputBox:create(x, y, w, h)
local self = setmetatable({}, InputBox)
self.font = FONTS.tiny
self.text = ""
self.w = w or WIDTH
self.h = h or self.font:getHeight()
self.x = x
self.y = y
self.timer = 0
self.delay = .125
return self
end
function InputBox:setTarget(textbox)
self.textbox = textbox
end
function InputBox:update(dt)
self.timer = self.timer + dt
if self.timer > self.delay then
if keyboard.isDown("delete") or keyboard.isDown("backspace") then
self.text = self.text:sub( 1, math.max( 0, #self.text - 1 ) )
self.timer = 0
end
end
end
function InputBox:draw()
graphics.setColor(255, 255, 255, 100)
graphics.rectangle("fill", self.x, self.y, self.w, self.h)
graphics.setColor(255, 255, 255, 255)
printFont(self.font, self.text, self.x, self.y)
end
function InputBox:keypressed(key)
local exist
if key == "return" then
if self.text ~= "" then
for k, command in pairs(commands) do
-- Get current command
local currentCommand = k
local first, last = self.text:find(currentCommand)
-- Found matching command !
if first then
exist = true
local cmd = commands[currentCommand]
-- command got parameters
if self.text:len() > last then
local p1 = self.text:sub(last+2)
if cmd.text and cmd.text ~= "" then self.textbox:pushMessage("'"..p1.."' :"..cmd.text, cmd.msgType) end
cmd.action(self.textbox, p1)
else -- Command don't have any parameters
if cmd.text and cmd.text ~= "" then self.textbox:pushMessage(cmd.text, cmd.msgType) end
if cmd.action then cmd.action(self.textbox) end
end
end
end
-- Does not exist!
if not exist then self.textbox:pushMessage("'"..self.text.."' :".."Unknown command!", "warning") end
end
-- Delete input
self.text = ""
end
end
function InputBox:textinput(t)
self.text = self.text..t
end
return InputBox
<file_sep>
local Fader = {}
local _r, _g, _b, _a = 0, 0, 0, 0
local _state = "ready"
local _scene, _speed
------------------------
-- // Dependencies \\ --
------------------------
local SceneManager = require("libs.SceneManager")
function Fader.clear()
_scene = ""
_state = "ready"
_r, _g, _b, _a = 0, 0, 0, 0
end
function Fader.fadeTo(scene, speed)
_scene = scene
_speed = speed or 400
_state = "out"
end
function Fader.update(dt)
if _state == "out" then
if _a < 245 then
_a = _a + _speed * dt
else
_a = 255
if _scene ~= "exit" then SceneManager.setScene(_scene)
else love.event.quit() end
_state = "in"
end
end
if _state == "in" then
if _a > 10 then
_a = _a - _speed * dt
else
_a = 0
_state = "ready"
end
end
end
function Fader.draw()
love.graphics.setColor(_r, _g, _b, _a)
love.graphics.rectangle("fill", 0, 0, WIDTH, HEIGHT)
love.graphics.setColor(255, 255, 255, 255)
end
return Fader<file_sep>
-- // Calender \\ --
--------------------
local Object = require("game.objects.Object")
local Calender = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local ButtonManager = require("game.ButtonManager")
local Console = require("game.objects.Console")
local flux = require("libs.flux")
-- Variables
local buttons = ButtonManager:create()
local function moveCalender()
local self = Calender
if self.state ~= ("movingin" or "movingout") then
if self.state == "in" then
self.state = "movingout"
-- Move down
flux.to(self, 1, { y = self.starty + self:getHeight()}):oncomplete(function() self.state = "out" end)
elseif self.state == "out" then
self.state = "movingin"
-- Move up
flux.to(self, 1, { y = self.starty}):oncomplete(function() self.state = "in" end)
end
end
end
function Calender:setup()
self.state = "in"
self.timer = 0
self.textbox = Console.textbox
self:setupObjects()
end
function Calender:setupObjects()
self:setImage(graphics.newImage("assets/gfx/ui_calender.png"))
self.startx = 505
self.starty = 90
self:setPosition(self.startx, self.starty - self:getHeight())
-- Setup buttons
buttons:clear()
-- // Calender Object \\ --
---------------------------
local top = buttons:addButton("Calender", "image", 0, 0, function() moveCalender() end)
top:setPosition(505, 70)
top:setColor({235, 235, 235}, {255, 255, 255})
top:setImage(graphics.newImage("assets/gfx/ui_calenderTop.png"))
end
function Calender:update(dt)
buttons:update(dt)
end
function Calender:draw()
graphics.setScissor(self.startx, self.starty + self:getHeight(), self:getWidth(), self:getHeight())
if self.state ~= "in" then
graphics.draw(self.image, self.x, self.y, 0, SCALEX, SCALEY)
end
graphics.setScissor()
buttons:draw()
end
function Calender:mousepressed(x, y, button)
buttons:mousepressed(x, y, button)
end
return Calender
<file_sep>
-- // PHONE \\ --
-----------------
local Object = require("game.objects.Object")
local Phone = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local Button = require("game.objects.Button")
local Console = require("game.objects.Console")
-- Variables
local phoneRinging
-- Width and height
local imgw, imgh = 10, 8
function Phone:setup()
self.animRinging = newAnimation(graphics.newImage("assets/gfx/phone_ringing.png"), imgw, imgh, 0.16, 0)
self.isRinging = false
self.timer = 0
self.ringTime = math.random(10, 30)
self.ringTimer = 0
self.hover = false
self.active = true
self.actionTime = math.random(5, 30)
self.textbox = Console.textbox
self:setupObjects()
end
function Phone:setupObjects()
-- Setup phone object
self:setPosition(140, 380)
self:setDimensions(imgw, imgh)
-- Setup button (hitbox only)
self.button = Button:create("Phone", "hitbox", self.x, self.y, function()
self.timer = 0
self.actionTime = math.random(5, 30)
self.ringTime = math.random(10, 20)
self.ringTimer = 0
self.isRinging = false
self.animRinging:seek(1)
end)
self.button:setDimensions(self.w / SCALEX, self.h / SCALEY)
self.button:setHitboxVisible(false)
end
function Phone:update(dt)
if self.active then
self.timer = self.timer + dt
if self.timer > self.actionTime then
self.isRinging = true
self.ringTimer = self.ringTimer + dt
if self.ringTimer > self.ringTime then
self.button.action()
end
end
-- Update Button
self.button:update(dt)
if self.isRinging then
-- Update Animation
self.animRinging:update(dt)
end
end
end
function Phone:draw()
if self.button.selected then
graphics.setColor(255, 255, 255)
else
graphics.setColor(185, 185, 185)
end
self.animRinging:draw(self.x, self.y, 0, SCALEX, SCALEY)
self.button:draw()
graphics.setColor(255, 255, 255)
end
function Phone:mousepressed(x, y, button)
self.button:mousepressed(x, y, button)
end
return Phone
<file_sep>
function circleCollision(a, b)
return math.sqrt(math.pow(a.x-b.x, 2) + math.pow(a.y-b.y, 2)) < a.r + b.r
end
function printMidText(text, y, font)
prevFont = graphics.getFont()
graphics.setFont(font)
graphics.printf(text, WIDTH * 0.5 - 999 * 0.5, y, 999, "center")
graphics.setFont(prevFont)
end
function printFont(font, text, x, y, r, sx, sy, ox, oy)
local previousFont = love.graphics.getFont()
love.graphics.setFont(font)
love.graphics.print(text, x, y, r, sx, sy, ox, oy)
love.graphics.setFont(previousFont)
end
function printFontCentered(font, text, x, y, width)
local previousFont = love.graphics.getFont()
love.graphics.setFont(font)
love.graphics.printf(text, x - width / 2, y, width, "center")
love.graphics.setFont(previousFont)
end
<file_sep>
-- // Window \\ --
-----------------
local Object = require("game.objects.Object")
local Window = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
-- // Dependencies \\ --
------------------------
local Console = require("game.objects.Console")
-- Variables
local clouds = {}
local cloudImage = graphics.newImage("assets/gfx/game_clouds.png")
local quads = {
graphics.newQuad(0, 0, 15, 4, cloudImage:getWidth(), cloudImage:getHeight()),
graphics.newQuad(15, 0, 15, 4, cloudImage:getWidth(), cloudImage:getHeight()),
graphics.newQuad(30, 0, 15, 4, cloudImage:getWidth(), cloudImage:getHeight()),
}
local function newCloud()
local self = Window
local cloud = {}
cloud.quad = quads[math.random(1, #quads)]
cloud.x = self.x + self.w
cloud.y = self.y + math.random(16, 48)
cloud.w = 15 * SCALEX
cloud.h = 4 * SCALEY
cloud.speed = math.random(5, 20)
table.insert(clouds, cloud)
end
function Window:setup()
self.timer = 0
self.cloudSpawnRate = .5
self.textbox = Console.textbox
self:setupObjects()
end
function Window:setupObjects()
-- Setup Window object
self:setPosition(440, 230)
self:setImage(graphics.newImage("assets/gfx/game_window.png"))
end
function Window:update(dt)
-- Generate clouds
self.timer = self.timer + dt
if self.timer > self.cloudSpawnRate then
newCloud()
self.timer = 0
self.cloudSpawnRate = math.random(3, 6)
end
-- Update clouds
for i, cloud in ipairs(clouds) do
cloud.x = cloud.x - cloud.speed * dt
if cloud.x + cloud.w < self.x then table.remove(clouds, i) end
end
end
function Window:draw()
graphics.draw(self.image, self.x, self.y, 0, SCALEX, SCALEY)
graphics.setScissor(self.x + 12, self.y, self:getWidth() - 21, self:getHeight())
for i, cloud in ipairs(clouds) do
graphics.draw(cloudImage, cloud.quad, cloud.x, cloud.y, 0, SCALEX, SCALEY)
end
graphics.setScissor()
end
function Window:mousepressed(x, y, button)
end
return Window<file_sep>
-- // INPUT BOX \\ --
---------------------
local Object = require("game.objects.Object")
local MessageBox = Object:create()
MessageBox.__index = MessageBox
--() Shortcuts ()--
-------------------
local graphics = love.graphics
local keyboard = love.keyboard
-- // Dependencies \\ --
------------------------
local commands = require("scripts.commands")
function MessageBox:create(x, y, w, h)
local self = setmetatable({}, MessageBox)
self.font = FONTS.tiny
self.text = ""
self.w = w or WIDTH
self.h = h or self.font:getHeight()
self.x = x
self.y = y
self.stopTime = true
self.timer = 0
self.delay = .125
return self
end
function MessageBox:setTarget(textbox)
self.textbox = textbox
end
function MessageBox:update(dt)
end
function MessageBox:draw()
graphics.setColor(255, 255, 255, 100)
graphics.rectangle("fill", self.x, self.y, self.w, self.h)
graphics.setColor(255, 255, 255, 255)
printFont(self.font, self.text, self.x, self.y)
end
function MessageBox:keypressed(key)
end
function MessageBox:textinput(t)
end
return MessageBox
<file_sep>------------------------
-- // SceneManager \\ --
------------------------
--[[
Copyright (c) 2013 <NAME>
modified with further Callbacks by <NAME> (c) 2014
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--]]
------------------------
-- // Declarations \\ --
------------------------
local SceneManager = {}
local _scenes = {}
local _overlay, _currentScene, _mode
local function initScene(scene)
if not scene.loaded then
if scene.init then scene:init() end
scene.loaded = true
end
if scene.enter then scene:enter() end
end
function SceneManager.newScene(scene, name)
local _scene = scene
_scene.name = name
_scenes[name] = _scene
end
function SceneManager.setScene(scene)
local _scene = _scenes[scene] or nil
if _currentScene and _currentScene.leave then _currentScene:leave() end
_currentScene = _scene
SceneManager.setOverlay()
if _scene then initScene(_scene)
elseif scene ~= nil then assert(_scene, "Scene '"..scene.."' does not exist!")
end
end
function SceneManager.setOverlay(scene, mode)
local _scene = _scenes[scene]
if _overlay and _overlay.leave then _overlay:leave() end
_overlay = _scene
_mode = mode
if _scene then initScene(_scene) end
end
function SceneManager.getScene()
return _currentScene.name or assert(_currentScene.name, "There's no scene set!")
end
function SceneManager.getOverlay()
return _overlay
end
function SceneManager.update(dt)
if _currentScene and _mode ~= "draw" then
_currentScene:update(dt)
end
if _overlay then _overlay:update(dt) end
end
function SceneManager.draw()
if _currentScene then _currentScene:draw() end
if _overlay then _overlay:draw() end
end
function SceneManager.keypressed(...)
if _overlay and _overlay.keypressed then _overlay:keypressed(...)
elseif _currentScene and _currentScene.keypressed then _currentScene:keypressed(...) end
end
function SceneManager.keyreleased(...)
if _overlay and _overlay.keyreleased then _overlay:keyreleased(...)
elseif _currentScene and _currentScene.keyreleased then _currentScene:keyreleased(...) end
end
function SceneManager.mousepressed(...)
if _overlay and _overlay.mousepressed then _overlay:mousepressed(...)
elseif _currentScene and _currentScene.mousepressed then _currentScene:mousepressed(...) end
end
function SceneManager.mousereleased(...)
if _overlay and _overlay.mousereleased then _overlay:mousereleased(...)
elseif _currentScene and _currentScene.mousereleased then _currentScene:mousereleased(...) end
end
function SceneManager.gamepadpressed(...)
if _overlay and _overlay.gamepadpressed then _overlay:gamepadpressed(...)
elseif _currentScene and _currentScene.gamepadpressed then _currentScene:gamepadpressed(...) end
end
function SceneManager.gamepadreleased(...)
if _overlay and _overlay.gamepadreleased then _overlay:gamepadreleased(...)
elseif _currentScene and _currentScene.gamepadreleased then _currentScene:gamepadreleased(...) end
end
function SceneManager.resize(...)
if _overlay and _overlay.resize then _overlay:resize(...)
elseif _currentScene and _currentScene.resize then _currentScene:resize(...) end
end
function SceneManager.visible(...)
if _overlay and _overlay.visible then _overlay:visible(...)
elseif _currentScene and _currentScene.visible then _currentScene:visible(...) end
end
function SceneManager.quit(...)
if _overlay and _overlay.quit then _overlay:quit(...)
elseif _currentScene and _currentScene.quit then _currentScene:quit(...) end
end
return SceneManager
<file_sep>
------------ MoneyManager ---------
------------ by VADS \\--// 2014 --
-----------------------------------
local Object = require("game.objects.Object")
local MoneyManager = Object:create()
--() Shortcuts ()--
-------------------
local graphics = love.graphics
function MoneyManager:setup()
self.money = 10000
self:setupObjects()
end
function MoneyManager:setupObjects()
-- Setup object
self:setImage(graphics.newImage("assets/gfx/ui_money.png"))
self:setPosition(ORWIDTH - self:getWidth() - 28, 4)
end
function MoneyManager:draw()
--Draws the money value on the screen
graphics.draw(self.image, self.x, self.y, 0, SCALEX, SCALEY)
printFontCentered(FONTS.small, "Money:", self.x + self.w / 2, self.y + self.h / 2 - 26, WIDTH)
printFontCentered(FONTS.medium, self.money.."$", self.x + self.w / 2, self.y + self.h / 2 - 8, WIDTH)
end
function MoneyManager:addMoney(amount)
if not amount then assert(amount, "No amount set!") end
self.money = self.money + amount
end
return MoneyManager
|
7d652c8a9a66de277b629fe5214947b64f29d7ec
|
[
"Lua"
] | 24 |
Lua
|
VADS/Credit-please
|
4fef189ed0a35664eee05a758a0aa999f5dc0023
|
5738721b5b99357d55db9d4dd898977ee46c3203
|
refs/heads/main
|
<repo_name>Dinmukh/Fundamentals-Of-Programming-3LID-A<file_sep>/Lab04-09-11-2020/Lab4-09-11-2020/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
namespace Lab4_09_11_2020
{
class Program
{
static void Main(string[] args)
{
Ex3();
}
public static double Median(int[] arr)
{
Array.Sort(arr);
if (arr.Length % 2 == 0)
{
return (arr[ (arr.Length / 2) - 1] + arr[(arr.Length / 2)]) / 2.0;
}
else
{
return arr[arr.Length / 2];
}
}
public static int Mode(int[] arr)
{
return arr.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
}
public static double StdDev(int[] arr)
{
double avg = arr.Average();
return Math.Sqrt(arr.Average(v => Math.Pow(v - avg, 2)));
}
public static void Ex1()
{
Console.WriteLine("Enter the size of array");
var N = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[N];
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine("Enter the number");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Array.Sort(arr);
Console.WriteLine($"Mean is {arr.Average()}, median is { Median(arr)}, mode is { Mode(arr)}, stdDev is { StdDev(arr)}");
}
public static void Ex2()
{
Console.WriteLine("Enter the size of array");
var N = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[N];
for (int i = N - 1; i >= 0; i--)
{
Console.WriteLine("Enter the number");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++)
{
Console.Write($"{arr[i]} ");
}
}
public static void Ex3()
{
Console.WriteLine("Enter the size of array");
var N = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[N];
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine("Enter the number");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
var dict = new Dictionary<int,int>();
foreach (int a in arr)
{
if (dict.ContainsKey(a))
dict[a] = dict[a] + 1;
else
dict[a] = 1;
}
foreach (KeyValuePair<int, int> kvp in dict)
{
if (kvp.Value > 1)
{
Console.WriteLine($"Duplicate of {kvp.Key}, {kvp.Value} times");
}
}
//dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);
}
public static void Ex4()
{
int[,] array1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] array2 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] array3 = new int[3,3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
}
}
}
}
}
|
3e9d247933ad67729ee80453d1832c3e95bd034a
|
[
"C#"
] | 1 |
C#
|
Dinmukh/Fundamentals-Of-Programming-3LID-A
|
02754534e997d6ff6bf2c16e747e190eaecb5c39
|
13a9c11216994a0472f41fdb4e6493c437068e49
|
refs/heads/main
|
<repo_name>vbarajas4/20-react-portfolio<file_sep>/src/components/pages/Resume.js
import React from 'react';
export default function Resume() {
const h1 = {
fontSize: '50px',
padding: '15px 15px 15px 15px'
}
const divStyle = {
display: 'flex',
justifyContent: 'center',
alignText: 'center',
backgroundColor: '#d8e1ff'
}
return (
<div style = { divStyle }>
<div>
<h1 style={ h1 }>Resume</h1>
<p>Download my <a href={require("../../assets/VM-Resume-ATS.pdf").default}>Resume</a></p>
<h2>Front-End Proficiencies</h2>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>JQuery</li>
<li>React</li>
<li>Bootstrap</li>
</ul>
<h2>Back-End Proficiencies</h2>
<ul>
<li>APIs</li>
<li>Node</li>
<li>Express</li>
<li>MySQL</li>
<li>MVC</li>
<li>MongoDB</li>
</ul>
</div>
</div>
)
}<file_sep>/README.md
# 20 React: React Portfolio
[Link to deployed Webpage](https://vbarajas4.github.io/20-react-portfolio)
## User Story
```md
AS AN employer looking for candidates with experience building single-page applications
I WANT to view a potential employee's deployed React portfolio of work samples
SO THAT I can assess whether they're a good candidate for an open position
```
## Project Outline
```md
GIVEN a single-page application portfolio for a web developer
WHEN I load the portfolio
THEN I am presented with a page containing a header, a section for content, and a footer
WHEN I view the header
THEN I am presented with the developer's name and navigation with titles corresponding to different sections of the portfolio
WHEN I view the navigation titles
THEN I am presented with the titles About Me, Portfolio, Contact, and Resume, and the title corresponding to the current section is highlighted
WHEN I click on a navigation title
THEN I am presented with the corresponding section below the navigation without the page reloading and that title is highlighted
WHEN I load the portfolio the first time
THEN the About Me title and section are selected by default
WHEN I am presented with the About Me section
THEN I see a recent photo or avatar of the developer and a short bio about them
WHEN I am presented with the Portfolio section
THEN I see titled images of six of the developer’s applications with links to both the deployed applications and the corresponding GitHub repositories
WHEN I am presented with the Contact section
THEN I see a contact form with fields for a name, an email address, and a message
WHEN I move my cursor out of one of the form fields without entering text
THEN I receive a notification that this field is required
WHEN I enter text into the email address field
THEN I receive a notification if I have entered an invalid email address
WHEN I am presented with the Resume section
THEN I see a link to a downloadable resume and a list of the developer’s proficiencies
WHEN I view the footer
THEN I am presented with text or icon links to the developer’s GitHub and LinkedIn profiles, and their profile on a third platform (Stack Overflow, Twitter)
```
## Screenshot of my Live Github Page
About Page
<img width="1242" alt="Screen Shot 2021-08-04 at 5 37 35 PM" src="https://user-images.githubusercontent.com/79430431/128273236-b58b7a8f-2274-466d-9869-502908addcd3.png">
Portfolio Page
<img width="1242" alt="Screen Shot 2021-08-04 at 5 35 39 PM" src="https://user-images.githubusercontent.com/79430431/128273240-852dd076-f089-481c-b754-de0e806d45a7.png">
Contact Page
<img width="1242" alt="Screen Shot 2021-08-04 at 5 36 21 PM" src="https://user-images.githubusercontent.com/79430431/128273246-65363aee-9f27-4d58-80da-04c440e76e74.png">
Resume Page
<img width="1242" alt="Screen Shot 2021-08-04 at 5 36 57 PM" src="https://user-images.githubusercontent.com/79430431/128273254-5571e24e-550e-4861-a5ac-47f6aba61062.png">
## Important Links
[GitHub Repository Link](https://github.com/vbarajas4/20-react-portfolio)
[Link to GitHub deployed Webpage](https://vbarajas4.github.io/20-react-portfolio)
## Framework/Technolgies
React
Bootstrap
fontaweesome
coolers
## Contact Information
[Email](<EMAIL>)
[LinkIn](https://www.linkedin.com/in/vanessa-maldonado-90668110a/)
## License
[](https://opensource.org/licenses/MIT)
<font size="2">Copyright (c) 2021 <NAME></font>
<font size="1">Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.</font> <file_sep>/src/components/Project.js
import React from 'react';
function Project (props) {
const {deployedLink, imageIcon, descriptionImage, projectName, projectDescription, githubLink } = props.project;
const containerStyle = {
display:'flex',
flexWrap: 'wrap',
justifyContent: 'center',
position: 'relative',
height: '70%',
width: '70%',
marginTop: '70px',
marginLeft: '20px',
marginBottom: '70px',
};
return (
<div className="col">
<div className="card h-100" style={containerStyle}>
<a href={ deployedLink }>
<img src={require(`../assets/${imageIcon}`).default} className="card-img-top" alt={ descriptionImage }/></a>
<div className="card-body">
<h5 className="card-title"> { projectName }</h5>
<p className="card-text"> { projectDescription }</p>
<a href={ githubLink } className="btn btn-primary">View Github Project</a>
</div>
</div>
</div>
)
}
export default Project;
<file_sep>/src/App.js
import React from 'react';
import { Route, BrowserRouter, Switch } from 'react-router-dom';
//import { Route } from 'react-router-dom';
import Nav from './components/Nav';
import Footer from './components/Footer';
import About from "./components/pages/About";
import Contact from "./components/pages/Contact";
import Portfolio from "./components/pages/Portfolio";
import Resume from "./components/pages/Resume";
function App() {
document.body.style.backgroundColor = '#d8e1ff';
return (
<div id='app'>
<BrowserRouter basename={ process.env.PUBLIC_URL }>
<Nav />
<Switch>
<Route path='/' exact component={ About }></Route>
<Route path='/portfolio' component={ Portfolio } ></Route>
<Route path='/contact' component={ Contact }></Route>
<Route path='/resume'component={ Resume }></Route>
<Route component = { About }></Route>
</Switch>
<Footer />
</BrowserRouter>
</div>
);
}
export default App;
<file_sep>/src/components/pages/Portfolio.js
import React from 'react';
import Project from '../../components/Project';
const projectCard = [
{
deployedLink: "https://damaximum.github.io/Productivity-Hub/",
imageIcon: "Productivity-Hub-SS.png",
descriptionImage: "Productivity Hub",
projectName: "Productivity Hub",
projectDescription: "A productivity app that helps you stay focus and stay on task.",
githubLink: "https://github.com/Damaximum/Productivity-Hub",
id: 1
},
{
deployedLink: "https://drive.google.com/file/d/1s9tP2GXIVzUjj3-pFf9cVIeCK2VXAXbX/view",
imageIcon: "Team-Profile-Cards.png",
descriptionImage: "Profile Cards",
projectName: "Team Profile",
projectDescription: "An application that helps you keep track of your employees profile.",
githubLink: "https://github.com/vbarajas4/10-OOP-Team-Profile",
id: 2
},
{
deployedLink: "https://vbarajas4.github.io/05-Third-Party-API-WorkDayScheduler/",
imageIcon: "Daily-Planner-Blank.png",
descriptionImage: "work schedule",
projectName: "Daily Work Planner",
projectDescription: "An application that allows the user to see their appointments for the day color coding times by past, present, and future events.",
githubLink: "https://github.com/vbarajas4/05-Third-Party-API-WorkDayScheduler",
id: 3
},
{
deployedLink: "https://vbarajas4.github.io/06-Server-Side-APIs-Weather-Dashboard/",
imageIcon: "Weather-Dashboard.png",
descriptionImage: "Weather Dashboard",
projectName: "Weather Dashboard",
projectDescription: "An application that lets the user see the current weather and the forecast for the next 5 days.",
githubLink: "https://github.com/vbarajas4/06-Server-Side-APIs-Weather-Dashboard",
id: 4
},
{
deployedLink: "https://vbarajas4.github.io/03-HW-Password-Generator/",
imageIcon: "Password-Generator-SS.png",
descriptionImage: "Password Generator",
projectName: "Password Generator",
projectDescription: "An application that generates a random password for a user based on the criteria selected.",
githubLink: "https://github.com/vbarajas4/03-HW-Password-Generator",
id: 5
}
];
function Portfolio() {
return (
<div>
{projectCard.map((project ) => (
<Project project = { project } />
))}
</div>
)
};
export default Portfolio;
|
d2d699dc6d86acbd76b46f24dbd0fa7e3b8c6146
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
vbarajas4/20-react-portfolio
|
37d3bfa65eecff69d4de3e58666bec164cc76685
|
efc4d29a79384ffdc314f1d9384e02d4395c6670
|
refs/heads/master
|
<file_sep>package threads.animation;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Ball {
int xLoc = 0;
int yLoc = 0;
int xdir = 10;
int ydir = 10;
int size = 50;
int delay = 50;
JComponent parent;
public Ball(JComponent parent){
this.parent = parent;
}
public void paint(Graphics g){
g.fillOval(xLoc, yLoc, size, size);
}
void move(){
if (xLoc+xdir > parent.getWidth()-(size*.75) || xLoc+xdir <= -(size*.25)) xdir *= -1;
xLoc += xdir;
if (xLoc > parent.getWidth()) xLoc -= size*2;
if (yLoc+ydir > parent.getHeight()-(size*.75) || yLoc+ydir <= -(size*.25)) ydir *= -1;
yLoc += ydir;
if (yLoc > parent.getHeight()) yLoc -= size*2;
}
}
<file_sep>package threads.animation;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Animator extends JFrame implements ActionListener {
JButton start, stop;
JPanel ballPanel;
Ball ball;
boolean animate;
Timer timer = new Timer(100, this);
public Animator(){
super("Animation");
start = new JButton("Start");
stop = new JButton("Stop");
Box buttons = new Box(BoxLayout.X_AXIS);
buttons.add(start);
buttons.add(stop);
getContentPane().add(buttons, BorderLayout.NORTH);
ballPanel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
ball.paint(g);
}
};
ball = new Ball(ballPanel);
getContentPane().add(ballPanel);
start.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand() + " fired");
timer.start();
worker.execute();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//animate = false;
timer.stop();
}
});
}
SwingWorker worker = new SwingWorker<Ball, Void>() {
@Override
protected Ball doInBackground() throws Exception {
animate = true;
while(animate){
repaint();
/* try{
Thread.sleep(100);
} catch (InterruptedException ex){
ex.printStackTrace();
}*/
}
return ball;
}
};
public static void main(String[] args){
JFrame f = new Animator();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(300, 300, 300, 200);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Timer Event Fired");
ball.move();
}
}
|
99ce8a4e4ca9480f991bd17432d58cfad59a4d33
|
[
"Java"
] | 2 |
Java
|
jonje/jjensen_Threads
|
56d7c588e5e1e07b4c154c63aae58b2a40366073
|
ea93578f830b3fe97603a4a77ac56ceca94b4abd
|
refs/heads/master
|
<file_sep>import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import matplotlib.pyplot as plt
import json
from bs4 import BeautifulSoup
import pandas as pd
# Functions for navigating Amazon's website
def go_back(driver):
driver.execute_script("window.history.go(-1)")
def go_to_next_page(driver,text=''):
"""Go to the next page of search results """
try:
next_button = driver.find_elements_by_class_name('a-last')
if 'a-disabled' in next_button[0].get_attribute('class'):
print('Reached end of list '+text)
return False
next_button[0].click()
return True
except:
print('Reached end of list '+text)
return False
def wait(amount=2):
time.sleep(amount)
def get_database(fname = 'review_db.csv'):
try:
reviews_df = pd.read_csv(fname,index_col=0)
except:
print('File not found. Making new database')
info = {'Name':['fake_entry'],
'n_reviews':[0],
'Reviews':[['some','fake','placeholder reviews']],
'ReviewRatings':[[0,1,2]],
'Price':['$15.99'],
'Brand':['FakeBrand'],
'img_url':["https://images-na.ssl-images-amazon.com/images/I/61o7KJvI3cL._SX300_QL70_.jpg"],
'details':[''],
'star_rating':["4.5 out of 5 stars"]}
reviews_df = pd.DataFrame(info)
reviews_df = reviews_df.drop(0)
return reviews_df
########################
def get_info(driver):
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
item_info = {}
# This block of code will help extract the Brand of the item
for divs in soup.findAll('div', attrs={'class': 'a-box-group'}):
try:
item_info['Brand'] = divs['data-brand']
break
except:
pass
# This block of code will help extract the Product Title of the item
for spans in soup.findAll('span', attrs={'id': 'productTitle'}):
name_of_product = spans.text.strip()
item_info['Name'] = name_of_product
break
# This block of code will help extract the price of the item in dollars
for divs in soup.findAll('div'):
try:
price = str(divs['data-asin-price'])
item_info['Price'] = '$' + price
break
except:
pass
# This block of code will help extract the image of the item
for divs in soup.findAll('div', attrs={'id': 'imgTagWrapperId'}):
for img_tag in divs.findAll('img', attrs={'id': 'landingImage'}):
item_info['img_url'] = img_tag['data-old-hires']
break
# This block of code will help extract the average star rating of the product
for i_tags in soup.findAll('i',
attrs={'data-hook': 'average-star-rating'}):
for spans in i_tags.findAll('span', attrs={'class': 'a-icon-alt'}):
item_info['star_rating'] = spans.text.strip()
break
# This block of code will help extract the number of customer reviews of the product
for spans in soup.findAll('span', attrs={'id': 'acrCustomerReviewText'
}):
if spans.text:
review_count = spans.text.strip()
item_info['n_reviews'] = review_count
break
# This block of code will help extract top specifications and details of the product
item_info['details'] = []
for ul_tags in soup.findAll('ul',
attrs={'class': 'a-unordered-list a-vertical a-spacing-none'
}):
for li_tags in ul_tags.findAll('li'):
for spans in li_tags.findAll('span',
attrs={'class': 'a-list-item'}, text=True,
recursive=False):
item_info['details'].append(spans.text.strip())
# This block of code will help extract the product description
item_info['description'] = []
for ul_tags in soup.findAll('div',
attrs={'id': 'productDescription'
}):
for paragraphs in ul_tags.findAll('p'):
item_info['description'].append(paragraphs.text.strip())
return item_info<file_sep>awsebcli==3.15.3
beautifulsoup4==4.8.0
blessed==1.15.0
botocore==1.12.239
cached-property==1.5.1
cement==2.8.2
certifi==2022.12.7
chardet==3.0.4
Click==7.0
colorama==0.3.9
docker==3.7.3
docker-compose==1.23.2
docker-pycreds==0.4.0
dockerpty==0.4.1
docopt==0.6.2
docutils==0.15.2
Flask==2.3.2
future==0.18.3
idna==2.7
itsdangerous==1.1.0
Jinja2==2.11.3
jmespath==0.9.4
jsonschema==2.6.0
MarkupSafe==1.1.1
numpy==1.22.0
pandas==0.25.1
pathspec==0.5.9
python-dateutil==2.8.0
pytz==2019.2
PyYAML==5.4
requests==2.20.1
semantic-version==2.5.0
six==1.11.0
soupsieve==1.9.4
termcolor==1.1.0
texttable==0.9.1
urllib3==1.26.5
wcwidth==0.1.7
websocket-client==0.56.0
Werkzeug==2.2.3
<file_sep># !/anaconda3/envs/insight/bin/python
from mypuzzle import application
if __name__ == '__main__':
application.run(debug = False)<file_sep>import torch, torchvision
from torchvision import datasets, models, transforms
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import time
from torchsummary import summary
import numpy as np
import matplotlib.pyplot as plt
import os
from PIL import Image
import matplotlib.pyplot as plt
# Applying Transforms to the Data
def make_transforms():
""" Makes image transforms to get input data into the right format
for resnet / pytorch"""
image_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(size=256, scale=(0.8, 1.0)),
transforms.RandomRotation(degrees=15),
transforms.RandomHorizontalFlip(),
transforms.CenterCrop(size=224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
]),
'valid': transforms.Compose([
transforms.Resize(size=256),
transforms.CenterCrop(size=224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
]),
'test': transforms.Compose([
transforms.Resize(size=256),
transforms.CenterCrop(size=224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
}
return image_transforms
def train_and_validate(model, loss_criterion, optimizer,train_data_loader,valid_data_loader,
train_data_size,valid_data_size,epochs=25,dataset=''):
'''
Function to train and validate
Parameters
:param model: Model to train and validate
:param loss_criterion: Loss Criterion to minimize
:param optimizer: Optimizer for computing gradients
:param epochs: Number of epochs (default=25)
Returns
model: Trained Model with best validation accuracy
history: (dict object): Having training loss, accuracy and validation loss, accuracy
'''
start = time.time()
history = []
best_acc = 0.0
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
for epoch in range(epochs):
epoch_start = time.time()
print("Epoch: {}/{}".format(epoch+1, epochs))
# Set to training mode
model.train()
# Loss and Accuracy within the epoch
train_loss = 0.0
train_acc = 0.0
valid_loss = 0.0
valid_acc = 0.0
for i, (inputs, labels) in enumerate(train_data_loader):
inputs = inputs.to(device)
labels = labels.to(device)
# Clean existing gradients
optimizer.zero_grad()
# Forward pass - compute outputs on input data using the model
outputs = model(inputs)
# Compute loss
loss = loss_criterion(outputs, labels)
# Backpropagate the gradients
loss.backward()
# Update the parameters
optimizer.step()
# Compute the total loss for the batch and add it to train_loss
train_loss += loss.item() * inputs.size(0)
# Compute the accuracy
ret, predictions = torch.max(outputs.data, 1)
correct_counts = predictions.eq(labels.data.view_as(predictions))
# Convert correct_counts to float and then compute the mean
acc = torch.mean(correct_counts.type(torch.FloatTensor))
# Compute total accuracy in the whole batch and add to train_acc
train_acc += acc.item() * inputs.size(0)
#print("Batch number: {:03d}, Training: Loss: {:.4f}, Accuracy: {:.4f}".format(i, loss.item(), acc.item()))
# Validation - No gradient tracking needed
with torch.no_grad():
# Set to evaluation mode
model.eval()
# Validation loop
for j, (inputs, labels) in enumerate(valid_data_loader):
inputs = inputs.to(device)
labels = labels.to(device)
# Forward pass - compute outputs on input data using the model
outputs = model(inputs)
# Compute loss
loss = loss_criterion(outputs, labels)
# Compute the total loss for the batch and add it to valid_loss
valid_loss += loss.item() * inputs.size(0)
# Calculate validation accuracy
ret, predictions = torch.max(outputs.data, 1)
correct_counts = predictions.eq(labels.data.view_as(predictions))
# Convert correct_counts to float and then compute the mean
acc = torch.mean(correct_counts.type(torch.FloatTensor))
# Compute total accuracy in the whole batch and add to valid_acc
valid_acc += acc.item() * inputs.size(0)
#print("Validation Batch number: {:03d}, Validation: Loss: {:.4f}, Accuracy: {:.4f}".format(j, loss.item(), acc.item()))
# Find average training loss and training accuracy
avg_train_loss = train_loss/train_data_size
avg_train_acc = train_acc/train_data_size
# Find average training loss and training accuracy
avg_valid_loss = valid_loss/valid_data_size
avg_valid_acc = valid_acc/valid_data_size
history.append([avg_train_loss, avg_valid_loss, avg_train_acc, avg_valid_acc])
epoch_end = time.time()
print("Epoch : {:03d}, Training: Loss: {:.4f}, Accuracy: {:.4f}%, \n\t\tValidation : Loss : {:.4f}, Accuracy: {:.4f}%, Time: {:.4f}s".format(epoch, avg_train_loss, avg_train_acc*100, avg_valid_loss, avg_valid_acc*100, epoch_end-epoch_start))
# Save if the model has best accuracy till now
torch.save(model, dataset+'_model_'+str(epoch)+'.pt')
return model, history
def computeTestSetAccuracy(model, loss_criterion):
'''
Function to compute the accuracy on the test set
Parameters
:param model: Model to test
:param loss_criterion: Loss Criterion to minimize
'''
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
test_acc = 0.0
test_loss = 0.0
all_predictions = []
# Validation - No gradient tracking needed
with torch.no_grad():
# Set to evaluation mode
model.eval()
# Validation loop
for j, (inputs, labels) in enumerate(test_data_loader):
inputs = inputs.to(device)
labels = labels.to(device)
# Forward pass - compute outputs on input data using the model
outputs = model(inputs)
# Compute loss
loss = loss_criterion(outputs, labels)
# Compute the total loss for the batch and add it to valid_loss
test_loss += loss.item() * inputs.size(0)
# Calculate validation accuracy
ret, predictions = torch.max(outputs.data, 1)
correct_counts = predictions.eq(labels.data.view_as(predictions))
all_predictions.append(predictions)
# Convert correct_counts to float and then compute the mean
acc = torch.mean(correct_counts.type(torch.FloatTensor))
# Compute total accuracy in the whole batch and add to valid_acc
test_acc += acc.item() * inputs.size(0)
print("Test Batch number: {:03d}, Test: Loss: {:.4f}, Accuracy: {:.4f}".format(j, loss.item(), acc.item()))
# Find average test loss and test accuracy
avg_test_loss = test_loss/test_data_size
avg_test_acc = test_acc/test_data_size
print("Test accuracy : " + str(avg_test_acc))
return all_predictions
def predict(model, test_image_name,image_transforms,idx_to_class,silent=False,return_scores=False):
'''
Function to predict the class of a single test image
Parameters
:param model: Model to test
:param test_image_name: Test image
'''
transform = image_transforms['test']
test_image = Image.open(test_image_name)
plt.imshow(test_image)
test_image_tensor = transform(test_image)
if torch.cuda.is_available():
test_image_tensor = test_image_tensor.view(1, 3, 224, 224).cuda()
else:
test_image_tensor = test_image_tensor.view(1, 3, 224, 224)
with torch.no_grad():
model.eval()
# Model outputs log probabilities
out = model(test_image_tensor)
ps = torch.exp(out)
topk, topclass = ps.topk(3, dim=1)
if not silent:
for i in range(3):
print("Prediction", i+1, ":", idx_to_class[topclass.cpu().numpy()[0][i]], ", Score: ", topk.cpu().numpy()[0][i])
top_classes = topclass.cpu().numpy()[0]
top_scores = topk.cpu().numpy()[0]
if return_scores:
return [top_classes,top_scores]
else:
return top_classes[0]
def plot_confusion_matrix(conf_matrix,cats=[],save=False,
cmap=plt.cm.Blues):
n_classes = len(cats)
# Format the class names
class_names = [c.replace('_',' ') for c in cats]
plt.clf()
plt.imshow(conf_matrix,cmap=cmap)
fmt = '.2f'
thresh = conf_matrix.max() / 2.
for i in range(conf_matrix.shape[0]):
for j in range(conf_matrix.shape[1]):
if conf_matrix[i,j] > thresh:
col = "white"
else:
col = 'black'
plt.gca().text(j, i, format(conf_matrix[i, j], fmt),
ha="center", va="center",color=col)
plt.xticks(np.arange(n_classes),class_names,rotation=45,ha='right')
plt.yticks(np.arange(n_classes),class_names)
plt.xlim(-0.5,n_classes-0.5)
plt.ylim(n_classes-0.5,-0.5)
plt.ylabel('True label')
plt.xlabel('Predicted')
plt.tight_layout()
#
if save:
plt.savefig(save,dpi=300)
plt.show()<file_sep>from flask import Flask
application = Flask(__name__)
from . import views<file_sep>from flask import request,render_template
from mypuzzle import application
import pandas as pd
import numpy as np
@application.route('/')
def home():
selected_options={}
for key in ['animals','art','fantasy','food','landscape','licensed','towns_and_cities']:
selected_options[key]=""
for key in ['abstract','collage','hand','photo']:
selected_options[key]=""
return render_template("index.html",selected_options=selected_options)
@application.route('/index',methods=['GET','POST'])
def index():
selected_options={}
for key in ['animals','art','fantasy','food','landscape','licensed','towns_and_cities']:
selected_options[key]=""
for key in ['abstract','collage','hand','photo']:
selected_options[key]=""
return render_template("index.html",selected_options=selected_options)
@application.route('/submit',methods=['GET','POST'])
def submit():
if request.method == 'POST':
print(request.form)
print(request.data)
# print(dir(request))
# Load the dfs
product_df = pd.read_csv('clean_product_df.csv')
######
# Art style selection
######
art_style = request.form['selectStyle']
######
# Theme selection
######
theme = request.form['selectTheme']
# Select the right puzzles
# Handle the case where either or both category can be "any" (i.e. no selection)
if art_style == 'any_style' and theme == 'any_theme':
right_puzzles = np.repeat(True,product_df.shape[0])
trimmed_df = product_df
elif art_style == 'any_style':
right_puzzles = (product_df['theme'] == theme)
trimmed_df = product_df[right_puzzles]
elif theme == 'any_theme':
right_puzzles = (product_df['art_style'] == art_style)
trimmed_df = product_df[right_puzzles]
else:
right_puzzles = (product_df['theme'] == theme) & (product_df['art_style'] == art_style)
trimmed_df = product_df[right_puzzles]
n_puzzles_left = right_puzzles.sum()
print(np.unique(product_df['art_style']),art_style)
print(np.unique(product_df['theme']),theme)
print(n_puzzles_left,'puzzles remaining')
######
# Sort-by features
######
# Order by the selected attribute and put in a list to make it easy
sort_by = request.form['selectFeature']
# From the model:
if sort_by == 'image_quality':
sort_col = 'score_quality'
elif sort_by == 'difficulty':
sort_col = 'score_difficulty'
elif sort_by == 'fit_of_pieces':
sort_col = 'score_fit'
elif sort_by == 'missing_pieces':
sort_col = 'score_missing_pieces'
elif sort_by == 'amazon_rating':
sort_col = 'star_rating'
vals_to_sort = trimmed_df[sort_col].values
sort_ix = np.argsort(vals_to_sort)[::-1] # put into descending order
# Reorder the output list
output_list = []
for ix in range(np.min([n_puzzles_left,60])):
return_ix = sort_ix[ix]
output_list.append(trimmed_df.iloc[return_ix])
# What options were selected for the drop down menus?
selected_options={}
for key in ['animals','art','fantasy','food','landscape','licensed','towns_and_cities']:
selected_options[key]=""
for key in ['abstract','collage','hand','photo']:
selected_options[key]=""
selected_options[theme] = True
selected_options[art_style] = True
selected_options[sort_by] = True
return render_template("output.html",output_list = output_list,selected_options=selected_options)
<file_sep>import numpy as np
import pandas as pd
import glob
import psycopg2
import nltk
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation as LDA
import os
import matplotlib.pyplot as plt
def connect_to_db():
try:
conn = psycopg2.connect("dbname='mypuzzle' user=''"+os.environ['MYPUZZLE_UN']+\
"' host='localhost' password='"+os.environ['<PASSWORD>']+"'")
cursor = conn.cursor()
print("Connected to database")
except:
print("Unable to connect to database!")
return conn
##########
# Model file tools
def save_model(pkl_filename,model):
with open(pkl_filename, 'wb') as file:
pickle.dump(model, file)
def load_model(pkl_filename):
with open(pkl_filename, 'rb') as file:
pickle_model = pickle.load(file)
return pickle_model
##########
def clean(review):
# Remove unwanted characters
for char in """(),"[]""":
review = review.replace(char,'')
review = review.replace('!','.')
review = review.replace('?','.')
review = review.replace('\n',' ')
# And double spaces and ellipsis
for ix in range(5):
review = review.replace(' ',' ').replace('..','.')
# lowercase
review = review.lower()
for x in ['puzzle','ravensburger','white mountain','puzzles']:
review = review.replace(x,'')
return review
##########
def plot_confusion_matrix(conf_matrix,cats=[],save=False,
cmap=plt.cm.Blues):
n_classes = len(cats)
plt.clf()
plt.imshow(conf_matrix,cmap=cmap)
fmt = '.2f'
thresh = conf_matrix.max() / 2.
for i in range(conf_matrix.shape[0]):
for j in range(conf_matrix.shape[1]):
if conf_matrix[i,j] > thresh:
col = "white"
else:
col = 'black'
plt.gca().text(j, i, format(conf_matrix[i, j], fmt),
ha="center", va="center",color=col)
plt.xticks(np.arange(n_classes),cats,rotation=45,ha='right')
plt.yticks(np.arange(n_classes),cats)
plt.xlim(-0.5,n_classes-0.5)
plt.ylim(n_classes-0.5,-0.5)
plt.ylabel('True label')
plt.xlabel('Predicted')
plt.tight_layout()
#
if save:
plt.savefig(save,dpi=300)
plt.show()<file_sep># jigsaw
Insight Data Science project, improving the search for jigsaw puzzles through puzzle image and amazon review data.
This project was completed over 4 weeks in September 2019 as part of the Insight Data Science Fellowship.
Check out more of my work here:
https://www.anthonycheetham.com/
and the completed website here:
http://www.mypuzzle.xyz/
This repo has 3 main parts:
1. A web app running on ElasticBeanstalk, located in the mypuzzle directory.
2. One jupyter notebook to train a model and classify puzzle images by their art style, and a second notebook to
repeat the same procedure to classify their theme. These are located in the image_classification directory.
3. A jupyter notebook to parse amazon reviews and calculate average sentiment in a number of different categories,
located in the review_scores directory.
The results of each model are stored in pandas dataframes, and then combined into the final clean_product_df.csv
file used by the web app.
## Image classification
The ResNet-50 model is used for each classification. The last layer of the model was replaced and the new model
trained on a few hundred hand-labelled images using the Adam optimizer and the negative log likelihood loss function.
## Review classification
The sentences are processed using TF-IDF to generate a feature vector, and then a random forest model is used to
classify them by topic. The RF model was trained on 500 hand-labelled sentences.
## Possible expansions
While this project achieved my goal of improving the jigsaw puzzle search experience, there are a lot of ways it
could be improved with a greater time investment. There were two I was most interested in.
- Currently it is not an online learner, and represents the state of the market in September 2019, so updating the
data and models automatically would be a valuable addition.
- Incorporating a search function using item descriptions would be valuable for users.
|
8d77cbaddb8a33869e62fc6394793d1cd9bb5038
|
[
"Markdown",
"Python",
"Text"
] | 8 |
Python
|
AnthonyCheetham/jigsaw
|
9d753499023eff00080bfda64ec2f7d1d74353ba
|
ae87249c8fe8ca43780878bdf7b1e8cfccf1edef
|
refs/heads/master
|
<repo_name>konecka-p/flare-beagle<file_sep>/flare_beagle_web/app/routes.py
from flask import jsonify
from app import app
from flask import request
from flask_pymongo import PyMongo
from bson.json_util import dumps
from bson.json_util import loads
mongo = PyMongo(app)
@app.route('/')
@app.route('/test', methods=['GET'])
def ping_pong():
return jsonify('test!')
@app.route('/index')
def index():
pass
@app.route('/api/events', methods=['GET'])
def get_events():
# page = request.args.get('page')
# print(page)
# per_page = request.args.get('per_page')
events = mongo.db.flares.find({}, {'_id': 0})
# events = mongo.db.flares.find({}, {'_id': 0}).limit(int(per_page)).skip(page-1 * per_page)
return jsonify({
'status': 'success',
'events': loads(dumps(events))
})<file_sep>/flare_beagle_web/client/src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Events from '@/components/Events/Events.vue';
Vue.use(VueRouter);
export default new VueRouter({
routes: [
{
path: '/',
name: 'Events',
component: Events,
},
],
mode: 'history',
});
<file_sep>/flare_beagle_web/database.py
# from pymongo import Connection
# import gridfs<file_sep>/flare_beagle_web/config.py
import os
class Config(object):
DEBUG = False
CSRF_ENABLED = True
# SECRET_KEY = 'YOUR_RANDOM_SECRET_KEY'
SECRET_KEY = os.environ.get('SECRET>_KEY') or "my_secret_key"
MONGODB_DB = 'flare_beagleDB'
MONGODB_HOST = '0.0.0.0'
MONGODB_PORT = 27017
ENV = 'development'
# SERVER_NAME = '0.0.0.0:5000'
SERVER_NAME = 'localhost:5000'
MONGO_URI = "mongodb://localhost:27017/flare_beagleDB"
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True<file_sep>/flare_beagle_web/run.py
from flask import jsonify
from app import app
from flask_cors import CORS
CORS(app, resources=r'/api/events', allow_headers='Content-Type')
events = [
{'date_start': 0,
'date_end': '1',
'area': '1',
'ap': '1',
'duration': '1992'},
{'date_start': 0,
'date_end': '1',
'area': '1',
'ap': '1',
'duration': '1'},
{'date_start': 0,
'date_end': '1',
'area': '1',
'ap': '1',
'duration': '1992'}
]
# events = mongo.db.flares.find({}, {'_id': 0}).limit(1)
if __name__ == '__main__':
app.run()
<file_sep>/flare_beagle_app/my_scheduler.py
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
executors = {
'default': ThreadPoolExecutor(10),
'processpool': ProcessPoolExecutor(10)
}
# job_defaults = {
# 'coalesce': False, # Объединение
# 'max_instances': 5
# }
scheduler = BackgroundScheduler(executors=executors)
<file_sep>/flare_beagle_app/get_jsoc_data.py
from dotenv import load_dotenv
from datetime import datetime, timedelta
import drms
import os
load_dotenv()
def aia_download_one(date, wave, out_dir):
date = str(date).replace(' ', '_')
qstr = '%s[%s][%d]{%s}' % ('aia.lev1_euv_12s', date, wave, 'image')
if not os.path.exists(out_dir):
os.makedirs(out_dir)
c = drms.Client()
r = c.export(qstr, method='url', protocol='fits', email=os.environ['JSOC_EXPORT_EMAIL'])
r.download(out_dir)
fmt = '%Y-%m-%dT%H%M%SZ'
filename = r.data['filename'][0]
real_date = datetime.strptime(filename.split('.')[2], fmt)
return filename, real_date
def aia_download_series(date_start, date_end, wave, out_dir):
date_start = str(date_start).replace(' ', '_')
date_end = str(date_end).replace(' ', '_')
qstr = '%s[%s_UTC-%s_UTC][%d]{%s}' % ('aia.lev1_euv_12s', date_start, date_end, wave, 'image')
if not os.path.exists(out_dir):
os.makedirs(out_dir)
c = drms.Client()
r = c.export(qstr, method='url', protocol='fits', email=os.environ['JSOC_EXPORT_EMAIL'])
r.download(out_dir)
def download_hmi_mag_45s(date_start, date_end, out_dir):
date_start = str(date_start).replace(' ', '_')
date_end = str(date_end).replace(' ', '_')
qstr = '%s[%s_UTC-%s_UTC]' % ('hmi.M_45s', date_start, date_end)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
c = drms.Client()
r = c.export(qstr, method='url', protocol='fits', email=os.environ['JSOC_EXPORT_EMAIL'])
r.download(out_dir)
if __name__ == "__main__":
# my_date_start = datetime.datetime(2019, 7, 18, 4, 30, 30, 5)
# my_date_end = datetime.datetime(2019, 7, 18, 4, 31, 30, 5)
my_date_start = datetime(2013, 9, 29, 21, 15, 00, 00)
my_date_end = datetime(2013, 9, 30, 8, 00, 30, 00)
# aia_download_series(my_date_start, my_date_end, 171, 'downloads/full_flare_12s')
# download_hmi_mag_45s(my_date_start, my_date_end, 'downloads/hmi')
download_aia_3m(my_date_start, 304, 'downloads/ris3')
<file_sep>/flare_beagle_app/image_processing.py
import math
from astropy.io import fits
import matplotlib.pyplot as plt
import glob
import cv2
import numpy as np
from scipy import interpolate
from astropy.wcs import WCS
def dist(p1, p2):
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
def create_circular_mask(shape, center, radius):
h, w = shape
y, x = np.ogrid[:h, :w]
circular_mask = np.sqrt((x - center[0])**2 + (y-center[1])**2) <= radius
return circular_mask
def preprocessing(fits_file):
norm_img = np.uint8(cv2.normalize(fits_file[1].data, None, 0, 255, cv2.NORM_MINMAX))
# radius of the Sun’s image in pixels
r_sun = fits_file[1].header['r_sun'] - 50
# location of disk center in x and y directions on image
crpix = (fits_file[1].header['crpix1'], fits_file[1].header['crpix2'])
mask = create_circular_mask(norm_img.shape, crpix, r_sun)
masked_img = norm_img.copy()
masked_img[~mask] = 0
blur = cv2.GaussianBlur(masked_img, (5, 5), 0)
# three sigma rule
threshold = np.mean(blur) + 3 * np.std(blur)
thresh = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY)[1]
return thresh
def get_sunspot(cnt):
m = cv2.moments(cnt)
cx = int(m["m10"] / m["m00"])
cy = int(m["m01"] / m["m00"])
sunspot = {'center': (cx, cy), 'cnt': cnt}
return sunspot
def coord_system_rotate(cnt, angle):
c, s = math.cos(angle), math.sin(angle)
# v = np.array((c, s, -s, c))
v = np.array((c, -s, s, c))
v = v.reshape((2, 2))
new_cnt = cnt.copy()
new_cnt = np.dot(new_cnt, v)
return new_cnt.astype('int32')
def get_close_spots(sunspots):
close_spots = {}
for i in range(len(sunspots) - 1):
for j in range(i + 1, len(sunspots)):
center_1 = sunspots[i]['center']
center_2 = sunspots[j]['center']
if dist(center_1, center_2) < 500:#1500
if center_1[0] < center_2[0]:
s1 = i
s2 = j
elif center_1[0] > center_2[0]:
s1 = j
s2 = i
elif center_1[0] == center_2[0]:
if center_1[1] < center_2[1]:
s1 = i
s2 = j
else:
s1 = j
s2 = i
a = math.atan2(sunspots[s2]['center'][1] - sunspots[s1]['center'][1],
sunspots[s2]['center'][0] - sunspots[s1]['center'][0])
cnt_1 = sunspots[s1]['cnt']
cnt_2 = sunspots[s2]['cnt']
new_cntL = coord_system_rotate(cnt_1, a)
new_cntR = coord_system_rotate(cnt_2, a)
rightmost_l = new_cntL[new_cntL[:, :, 0].argmax()][0]
leftmost_r = new_cntR[new_cntR[:, :, 0].argmin()][0]
dist_x = leftmost_r[0] - rightmost_l[0]
if abs(dist_x) < 15: #150
topmost_l = new_cntL[:, :, 1].argmax()
bottommost_l = new_cntL[:, :, 1].argmin()
topmost_r = new_cntR[:, :, 1].argmax()
bottommost_r = new_cntR[:, :, 1].argmin()
close_spots[(s1, s2)] = [topmost_l, bottommost_l, topmost_r, bottommost_r]
return close_spots
def get_actual_id(id, sunspots_history):
while id != sunspots_history[id]:
id = sunspots_history[id]
return id
def get_neighbors(cnt, point_id, direction, num):
if direction == 'ccw':
if point_id - num > 0:
return cnt[point_id:point_id - num:-3]
else:
return np.concatenate((cnt[point_id:0:-3], cnt[0:point_id-num]))
elif direction == 'cw':
if (point_id + num) > len(cnt):
return(np.concatenate((cnt[point_id:len(cnt):3], cnt[:len(cnt)-num:3])))
else:
return(cnt[point_id:point_id+num:3])
def get_cnt_piece(cnt, start, end, direction):
piece = []
ids = []
if direction == 'cw':
if (start - end) < 0:
for p in range(start, 0, -1):
piece.append(cnt[p])
ids.append(p)
for p in range(0, end + 1):
piece.append(cnt[p])
ids.append(p)
else:
for p in range(start, len(cnt)):
piece.append(cnt[p])
ids.append(p)
for p in range(0, end+1):
piece.append(cnt[p])
ids.append(p)
return np.array(ids), np.array(piece)
def spline(line, s):
x_points = []
y_points = []
for x in line[:, :, 0]:
x_points.append(*x)
for y in line[:, :, 1]:
y_points.append(*y)
x = np.array(x_points)
y = np.array(y_points)
dist = np.sqrt((x[:-1] - x[1:]) ** 2 + (y[:-1] - y[1:]) ** 2)
dist_along = np.concatenate(([0], dist.cumsum()))
spline, u = interpolate.splprep([x, y], u=dist_along, s=0)
d = np.arange(u[s-1], u[s+1], 0.1)
# d = np.arange(u[s], u[s+2], 0.1)
interp_x, interp_y = interpolate.splev(d, spline)
interp_x = np.rint(interp_x)
interp_y = np.rint(interp_y)
return np.array(interp_x), np.array(interp_y)
def merge_close(sunspots, close_spots, img, sunspots_history):
new_cnts = []
img_points = img.copy()
for cs in close_spots:
actual_id = [get_actual_id(sunspots_history[cs[0]], sunspots_history),
get_actual_id(sunspots_history[cs[1]], sunspots_history)]
spot_one = sunspots[actual_id[0]]
spot_two = sunspots[actual_id[1]]
topmost_l = close_spots[cs][0]
bottommost_l = close_spots[cs][1]
topmost_r = close_spots[cs][2]
bottommost_r = close_spots[cs][3]
piece1 = get_cnt_piece(spot_one['cnt'], topmost_l, bottommost_l, 'cw')[0]
piece2 = get_cnt_piece(spot_two['cnt'], bottommost_r, topmost_r, 'cw')[0]
piece2 = piece2[::-1]
union_points = []
for p1 in piece1:
for p2 in piece2:
d = dist(spot_one['cnt'][p1][0], spot_two['cnt'][p2][0])
if d < 25: #100
union_points.append((p1, p2))
if len(union_points) > 2:
# Индексы точек объединения
up1 = union_points[0]
up2 = union_points[-1]
# Получение точек для построения сплайна
# -------------------------------------------------------------------------------------
line_one_1 = get_neighbors(spot_one['cnt'], up1[0], 'ccw', 15)[::-1]
line_one_2 = get_neighbors(spot_two['cnt'], up1[1], 'cw', 15)
line_two_1 = get_neighbors(spot_one['cnt'], up2[0], 'cw', 15)[::-1]
line_two_2 = get_neighbors(spot_two['cnt'], up2[1], 'ccw', 15)
line_one = np.concatenate((line_one_1, line_one_2))
line_two = np.concatenate((line_two_1, line_two_2))
for l in line_two:
cv2.circle(img_points, (l[0][0], l[0][1]), 1, (150, 150, 150), 2)
for l in line_one:
cv2.circle(img_points, (l[0][0], l[0][1]), 1, (150, 150, 150), 2)
# Сплайн
if len(line_one) > 3:
xnew, ynew = spline(line_one, len(line_one_1))
l = np.unique(np.array(np.c_[xnew, ynew]), axis=0)
for i in l:
img[int(i[1]), int(i[0])] = 255
pass
if len(line_two) > 3:
xnew, ynew = spline(line_two, len(line_two_1))
l = np.unique(np.array(np.c_[xnew, ynew]), axis=0)
for i in l:
img[int(i[1]), int(i[0])] = 255
pass
# -------------------------------------------------------------------------------------
# Изменение контура
cnt_part_1 = get_cnt_piece(spot_one['cnt'], up2[0], up1[0], 'cw')[1]
cnt_part_2 = get_cnt_piece(spot_two['cnt'], up1[1], up2[1], 'cw')[1]
# print(spot_one['cnt'][up1[0]], spot_two['cnt'][up1[1]], line_one[0], line_one[-1])
# print(np.where(spot_one['cnt'][-1] == line_one))
new_cnt = np.concatenate((cnt_part_1[1:-1], line_one, cnt_part_2[1:-1], line_two))
# print(cnt_part_1[-1], line_one[0])
# new_cnt = get_cnt_piece(spot_one['cnt'], up2[0], up1[0], 'cw')[1]
# new_cnt = np.concatenate((new_cnt, get_cnt_piece(spot_two['cnt'], up1[1], up2[1], 'cw')[1]))
# cv2.drawContours(img, [new_cnt], -1, (255, 255, 255), -1)
# cv2.drawContours(img, [new_cnt], -1, (255, 255, 255), 1)
new_cnts.append(new_cnt)
sunspots_history[actual_id[0]] = sunspots_history[actual_id[1]] = len(sunspots)
sunspots_history = np.append(sunspots_history, len(sunspots_history))
sunspots[len(sunspots_history)-1] = get_sunspot(new_cnt)
return img, img_points
import sunpy.visualization.colormaps as cm
sdoaia171 = plt.get_cmap('sdoaia171')
def detect_flare(fits_img_one, fits_img_two):
spots = []
# смотрим разницу между обработанными изображениями
diff = cv2.absdiff(preprocessing(fits_img_two), preprocessing(fits_img_one))
# морфологические операции, чтобы убрать лишний мусор
diff = cv2.morphologyEx(diff, cv2.MORPH_OPEN, np.ones((3, 3)), iterations=2)
diff = cv2.morphologyEx(diff, cv2.MORPH_CLOSE, np.ones((3, 3)), iterations=1)
# поиск контуров с большой площадью
cnts, _ = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = [cnt for cnt in cnts if cv2.contourArea(cnt) >= 500]
# если обнаружили что-то большое
if len(cnts) > 0:
x = y = []
for cnt in cnts:
m = cv2.moments(cnt)
cx = int(m["m10"] / m["m00"])
cy = int(m["m01"] / m["m00"])
x.append(cx)
y.append(cy)
spots.append((int(np.mean(x)), int(np.mean(y))))
diff.fill(0)
cv2.drawContours(diff, cnts, -1, (255, 255, 255), -1)
return spots, diff
def accum(files, spots):
# al = cv2.bitwise_or(al, diff)
# print(np.var(img_next)) -- иногда приходит мусор, его можно почистить вот так
sum_contour = np.zeros((4096, 4096), dtype='uint8')
print("---", len(files))
for i in range(0, len(files)):
f = fits.open(files[i])
f.verify("silentfix")
image_prep = preprocessing(f)
thresh = cv2.morphologyEx(image_prep, cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)), iterations=1)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)), iterations=1)
cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# cnts = [cnt for cnt in cnts if cv2.contourArea(cnt) > 150]
# thresh.fill(0)
# cv2.drawContours(thresh, cnts, -1, (255, 255, 255), -1)
sunspots = {}
sum_contour = cv2.bitwise_or(thresh, sum_contour)
for i, cnt in enumerate(cnts):
s = get_sunspot(cnt)
# print(dist(s['center'], spots[0]) )
if dist(s['center'], spots[0]) < 500:
pass
# sunspots.append(s)
# cv2.drawContours(sum_contour, [cnt], -1, (255, 255, 255), -1)
return sum_contour
def hmi_calс(img_hmi, cnt, header_aia, header_hmi):
aia_wcs = WCS(header_aia)
hmi_wcs = WCS(header_hmi)
# a = np.zeros_like((4096, 4096), dtype='uint8')
a = np.zeros_like(img_hmi)
for i, p in enumerate(cnt):
aia_pix2world = aia_wcs.wcs_pix2world(((p[0][0], p[0][1]),), 1)
new_pix = hmi_wcs.wcs_world2pix(aia_pix2world, 0)
cv2.circle(img_hmi, (int(new_pix[0][0]), int(new_pix[0][1])), 1, (3000, 3000, 3000), 20)
# cnt[i] = np.rint(new_pix)
return img_hmi
if __name__ == "__main__":
# files_12s = glob.glob("downloads/2013_12s/*.image_lev1.fits")
# files_12s = glob.glob("downloads/full_flare_12s/*.image_lev1.fits")
# files_5m = glob.glob("downloads/2013_5m/*.image_lev1.fits")
# files_hmi = glob.glob("downloads/hmi/*.magnetogram.fits")<file_sep>/flare_beagle_app/main.py
from datetime import datetime
import time
import os
import random
from datetime import datetime, timedelta
from database import storeDB, flaresDB
from my_scheduler import scheduler
from get_jsoc_data import download_aia_3m, download_aia_12s, download_hmi_mag_45s
def get_aia_3m():
if storeDB.aia171_3m.count_documents({}) == 0:
# вот тут надо взять ту дату, которая вернулась рельная с запроса.
download_date = str(datetime(2013, 9, 29, 22, 0, 0, 1))
record = {'download_date' : download_date, 'date': datetime.utcnow()}
storeDB.aia171_3m.insert_one(record).inserted_id
else:
download_date = storeDB.aia171_3m.find_one(sort=[{'_id', -1}])['download_date']
download_date = str(datetime.strptime(download_date, '%Y-%m-%d %H:%M:%S.%f') + timedelta(minutes=5))
record = {'download_date': download_date, 'date': datetime.utcnow()}
storeDB.aia171_3m.insert_one(record).inserted_id
file_name = download_aia_3m(download_date, 171, 'downloads/test_aia3m')
#тут надо перезаписать дату
# db_schedule.aia171_3m.update_one({'download_date': download_date}, {'$set': {'downloaded': True},
# {'file_name' : file_name}}, upsert=True)
def event_detector():
if storeDB.aia171_3m.count_documents({}) >= 2:
pass
def test():
print('i test task')
time.sleep(10)
if __name__ == '__main__':
# max_instances - задание может исполняться в более чем одном экземпляре процесса (7)
# scheduler.add_job(get_aia_3m, 'interval', minutes=5, max_instances=5, executor='default')
# scheduler.add_job(event_detector, 'interval', minutes=5, max_instances=5, executor='default')
test_job = scheduler.add_job(test, 'interval', seconds=3, max_instances=5, executor='default')
print(test_job)
scheduler.start()
test_job.remove()
try:
while True:
time.sleep(3)
except KeyboardInterrupt:
pass
scheduler.shutdown()<file_sep>/spots_merge.py
import math
from astropy.io import fits
import matplotlib.pyplot as plt
import glob
import cv2
import numpy as np
from scipy.interpolate import lagrange
def dist(p1, p2):
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
def create_circular_mask(shape, center, radius):
h, w = shape
y, x = np.ogrid[:h, :w]
circular_mask = np.sqrt((x - center[0]) ** 2 + (y-center[1]) ** 2) <= radius
return circular_mask
def coord_system_rotation(cnt, angle):
c, s = math.cos(angle), math.sin(angle)
# v = np.array((c, s, -s, c))
v = np.array((c, -s, s, c))
v = v.reshape((2, 2))
new_cnt = cnt.copy()
new_cnt = np.dot(new_cnt, v)
return new_cnt.astype('int32')
def preprocessing(fits_file):
norm_img = np.uint8(cv2.normalize(fits_file[1].data, None, 0, 255, cv2.NORM_MINMAX))
# Radius of the Sun’s image in pixels
r_sun = fits_file[1].header['r_sun']
# location of disk center in x and y directions on image
crpix = (fits_file[1].header['crpix1'], fits_file[1].header['crpix2'])
mask = create_circular_mask(norm_img.shape, crpix, r_sun)
masked_img = norm_img.copy()
masked_img[~mask] = 0
blur = cv2.medianBlur(masked_img, 7)
# Cреднее значение плюс стандартное отклонение, умноженное на три / three sigma rule
threshold = np.mean(blur) + 3 * np.std(blur)
thresh = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, np.ones((4, 4)), iterations=1)
return thresh
def get_sunspot(cnt):
M = cv2.moments(cnt)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
sunspot = {'center': (cX, cY), 'cnt': cnt}
return sunspot
def get_close_spots(sunspots):
close_spots = {}
for i in range(len(sunspots) - 1):
for j in range(i + 1, len(sunspots)):
center_1 = sunspots[i]['center']
center_2 = sunspots[j]['center']
if dist(center_1, center_2) < 500:
if center_1[0] < center_2[0]:
s1 = i
s2 = j
elif center_1[0] > center_2[0]:
s1 = j
s2 = i
elif center_1[0] == center_2[0]:
if center_1[1] < center_2[1]:
s1 = i
s2 = j
else:
s1 = j
s2 = i
a = math.atan2(sunspots[s2]['center'][1] - sunspots[s1]['center'][1],
sunspots[s2]['center'][0] - sunspots[s1]['center'][0])
cnt_1 = sunspots[s1]['cnt']
cnt_2 = sunspots[s2]['cnt']
new_cntL = coord_system_rotation(cnt_1, a)
new_cntR = coord_system_rotation(cnt_2, a)
rightmost_l = new_cntL[new_cntL[:, :, 0].argmax()][0]
leftmost_r = new_cntR[new_cntR[:, :, 0].argmin()][0]
dist_x = leftmost_r[0] - rightmost_l[0]
if abs(dist_x) < 15:
topmost_l = new_cntL[:, :, 1].argmax()
bottommost_l = new_cntL[:, :, 1].argmin()
topmost_r = new_cntR[:, :, 1].argmax()
bottommost_r = new_cntR[:, :, 1].argmin()
close_spots[(s1, s2)] = [topmost_l, bottommost_l, topmost_r, bottommost_r]
return close_spots
def get_actual_id(id, sunspots_history):
while id != sunspots_history[id]:
id = sunspots_history[id]
return id
def get_cnt_piece(cnt, start, end, direction):
piece = []
ids = []
if direction == 'cw':
if (start - end) < 0:
for p in range(start, 0, -1):
piece.append(cnt[p])
ids.append(p)
for p in range(0, end + 1):
piece.append(cnt[p])
ids.append(p)
else:
for p in range(start, len(cnt)):
piece.append(cnt[p])
ids.append(p)
for p in range(0, end+1):
piece.append(cnt[p])
ids.append(p)
return np.array(ids), np.array(piece)
def merge_close(sunspots, close_spots, img, sunspots_history):
for cs in close_spots:
actual_id = [get_actual_id(sunspots_history[cs[0]], sunspots_history),
get_actual_id(sunspots_history[cs[1]], sunspots_history)]
spot_one = sunspots[actual_id[0]]
spot_two = sunspots[actual_id[1]]
topmost_l = close_spots[cs][0]
bottommost_l = close_spots[cs][1]
topmost_r = close_spots[cs][2]
bottommost_r = close_spots[cs][3]
piece1 = get_cnt_piece(spot_one['cnt'], topmost_l, bottommost_l, 'cw')[0]
piece2 = get_cnt_piece(spot_two['cnt'], bottommost_r, topmost_r, 'cw')[0]
piece2 = piece2[::-1]
union_points = []
for p1 in piece1:
for p2 in piece2:
d = dist(spot_one['cnt'][p1][0], spot_two['cnt'][p2][0])
if d < 25:
union_points.append((p1, p2))
if len(union_points) > 2:
# neighbors_one = get_neighbors(spot_one['cnt'], topmost_l, 'ccw', 100)
# neighbors_two = get_neighbors(spot_two['cnt'], topmost_r, 'cw', 100)
# Изменение контура
up1 = union_points[0]
up2 = union_points[-1]
new_cnt = get_cnt_piece(spot_one['cnt'], up2[0], up1[0], 'cw')[1]
new_cnt = np.concatenate((new_cnt, get_cnt_piece(spot_two['cnt'], up1[1], up2[1], 'cw')[1]))
cv2.drawContours(img, [new_cnt], -1, (150, 150, 150), 2)
sunspots_history[actual_id[0]] = sunspots_history[actual_id[1]] = len(sunspots)
sunspots_history = np.append(sunspots_history, len(sunspots_history))
sunspots[len(sunspots_history)-1] = get_sunspot(new_cnt)
return img
if __name__ == "__main__":
plt.ion()
# files = glob.glob("JSOC_20200215_259/*.image_lev1.fits")
files = glob.glob("downloads/2013_5m/*.image_lev1.fits")
# files = glob.glob("downloads/2013_12s/*.image_lev1.fits")
# files = glob.glob("downloads/aia/*.image_lev1.fits")
for i in range(1, len(files), 1):
f = fits.open(files[i])
f.verify("silentfix")
thresh = preprocessing(f)
cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = [cnt for cnt in cnts if cv2.contourArea(cnt) >= 500]
sunspots = {}
for i, cnt in enumerate(cnts):
sunspots[i] = get_sunspot(cnt)
sunspots_history = np.arange(0, len(sunspots))
close_spots = get_close_spots(sunspots)
merged = merge_close(sunspots, close_spots, thresh.copy(), sunspots_history)
# al = cv2.bitwise_or(diff, prev_diff)
plt.subplot(2, 1, 1)
plt.imshow(thresh, origin='lower')
plt.subplot(2, 1, 2)
plt.imshow(merged, origin='lower')
plt.show()
plt.pause(10)<file_sep>/README.md
# flare-beagle
Module for searching geoeffective events on the sun's surface (solar flares)
<file_sep>/flare_beagle_app/database.py
from pymongo import MongoClient
client = MongoClient()
storeDB = client.storeDB
flare_beagleDB = client.flare_beagleDB
if __name__ == "__main__":
pass<file_sep>/flare_beagle_web/.flaskenv
FLASK_ENV=development
FLASK_APP=run.py
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=5000
FLASK_DEBUG=1
|
482f29101b731cf04ca25b2c0a01b998bb905d1e
|
[
"JavaScript",
"Python",
"Markdown",
"Shell"
] | 13 |
Python
|
konecka-p/flare-beagle
|
79f6760dc61ff2185eba609d9968ee234d1fd9f9
|
4d135bb686536a24d7832f6bee08af92fc8b29fe
|
refs/heads/master
|
<repo_name>davydes/gym<file_sep>/spec/support/redis.rb
# Use fakeredis gem
require 'fakeredis/rspec'<file_sep>/db/migrate/20160708085201_create_references_equipment_joins.rb
class CreateReferencesEquipmentJoins < ActiveRecord::Migration
def change
create_table :references_equipment_joins, id: false do |t|
t.references :equipment, index: true
t.references :equipmentable, polymorphic: true
t.foreign_key :references_equipment, column: :equipment_id
end
add_index :references_equipment_joins, [:equipmentable_id, :equipmentable_type, :equipment_id], name: 'pk_references_equipment_joins', unique: true
end
end
<file_sep>/app/models/references/equipment_join.rb
class References::EquipmentJoin < ActiveRecord::Base
self.primary_keys = :equipmentable_id, :equipmentable_type, :equipment_id
belongs_to :equipment, :class_name => 'References::Equipment'
belongs_to :equipmentable, polymorphic: true
validates_uniqueness_of :equipment_id, scope: [:equipmentable_id, :equipmentable_type]
end<file_sep>/db/migrate/20150714065207_create_body_parts_exercises.rb
class CreateBodyPartsExercises < ActiveRecord::Migration
def change
create_table :body_parts_exercises, :id => false do |t|
t.references :body_part, index: true, foreign_key: true
t.references :exercise, index: true, foreign_key: true
end
end
end
<file_sep>/config/deploy/staging.rb
set :rails_env, 'staging'
set :rake_env, 'staging'
set :user, 'deploy'
ask :server, 'dev.logym.ru'
server fetch(:server),
user: "#{fetch(:user)}",
roles: %w{app db web}<file_sep>/app/serializers/references/muscle_short_serializer.rb
class References::MuscleShortSerializer < ActiveModel::Serializer
attributes :id, :name, :alias, :shape
end
<file_sep>/app/models/journal.rb
class Journal < ActiveRecord::Base
belongs_to :user
has_many :items, -> { order(executed_at: :desc) },
class_name: 'Journal::Item',
dependent: :destroy
validates :user, presence: true
end
<file_sep>/spec/models/references/exercise_spec.rb
require 'rails_helper'
RSpec.describe References::Exercise, type: :model do
it_behaves_like 'anatomic'
it 'should create muscle' do
expect { create(:exercise_with_muscle) }.to change{References::Muscle.count}.by(1)
end
it 'should create body_part' do
expect { create(:exercise_with_body_part) }.to change{References::BodyPart.count}.by(1)
end
end
<file_sep>/spec/controllers/references/exercises_controller_spec.rb
require 'rails_helper'
RSpec.describe References::ExercisesController, type: :controller do
before (:context) do
@exercise = create(:exercise)
end
describe "GET index" do
it "assigns @exercises" do
get :index
expect(assigns(:exercises)).to eq([@exercise])
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
end
end
describe "GET show" do
it "assigns @exercise" do
get :show, id: @exercise.id
expect(assigns(:exercise)).to eq(@exercise)
end
it "renders the show template" do
get :show, id: @exercise.id
expect(response).to render_template("show")
end
end
describe "GET new" do
describe "when user logged in" do
login(admin: true)
it "renders the new template" do
get :new
expect(response).to render_template("new")
end
end
describe "when user logged out" do
it 'should redirect to sign_in' do
get :new
expect(subject).to redirect_to("/users/sign_in")
end
end
end
describe "POST create" do
describe "when user logged in" do
login(admin: true)
let(:attr) do
attributes_for(:exercise)
end
before(:each) do
post :create, exercise: attr
@exercise = References::Exercise.last
end
it { expect(response).to redirect_to(@exercise) }
it { expect(@exercise.name).to eql attr[:name] }
it { expect(@exercise.alias).to eql attr[:alias] }
end
end
describe "GET edit" do
describe "when user logged in" do
login(admin: true)
it "assigns @exercise" do
get :edit, id: @exercise.id
expect(assigns(:exercise)).to eq(@exercise)
end
it "renders the edit template" do
get :edit, id: @exercise.id
expect(response).to render_template("edit")
end
end
describe "when user logged out" do
it 'should redirect to sign_in' do
get :edit, id: @exercise.id
expect(subject).to redirect_to("/users/sign_in")
end
end
end
describe "PUT update" do
describe "when user logged in" do
login(admin: true)
let(:attr) do
{ :name => 'new name', :alias => 'new_alias' }
end
before(:example) do
@exercise = create(:exercise)
end
before(:each) do
put :update, :id => @exercise.id, :exercise => attr
@exercise.reload
end
it { expect(response).to redirect_to(@exercise) }
it { expect(@exercise.name).to eql attr[:name] }
it { expect(@exercise.alias).to eql attr[:alias] }
end
end
describe "DELETE destroy" do
describe "when user logged in" do
login(admin: true)
before(:example) do
@exercise = create(:exercise)
end
it "should destroy exercise" do
expect{delete :destroy, :id => @exercise.id}.to change{References::Exercise.count}.by(-1)
end
it "should redirect to exercises_path" do
delete :destroy, :id => @exercise.id
expect(response).to redirect_to(references_exercises_path)
end
end
end
context 'JSON' do
let (:exercises) { create_list(:exercise, 5) }
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
describe 'GET #index' do
describe 'responds exercises as json with' do
it 'right count' do
count = References::Exercise.count+exercises.count
get :index
json = JSON.parse(response.body)
expect(json.length).to eq(count)
end
it 'extended format' do
get :index
json = JSON.parse(response.body)
expect(json.first.keys).to eq(%w(id name alias description equipments muscles body_parts))
end
it 'short format' do
get :index, {short:1}
json = JSON.parse(response.body)
expect(json.first.keys).to eq(%w(id name alias))
end
end
end
end
end
<file_sep>/db/migrate/20160607131217_create_workout_items.rb
class CreateWorkoutItems < ActiveRecord::Migration
def change
create_table :workout_items do |t|
t.belongs_to :workout, index: true, foreign_key: true, null: false
t.belongs_to :exercise, index: true, foreign_key: true, null: false
t.text :description
t.text :sets, null: false
t.integer :pos, null: false
t.timestamps null: false
end
add_index :workout_items, [:workout_id, :pos], :unique => true
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def auth_provider_to_css(provider)
case provider.to_s
when 'vkontakte'
return 'vk';
when 'google_oauth2'
return 'google-plus';
else
return provider.to_s
end
end
def get_href(name = nil, options = nil, html_options = nil, &block)
html_options, options, name = options, name, block if block_given?
options ||= {}
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
html_options['href'] ||= url
end
def menu_link_to(name = nil, options = nil, html_options = nil, &block)
link = get_href name, options, html_options, &block
content_tag :li, class: ('active' if current_page?(link)) do
link_to name, options, html_options, &block
end
end
def index_of_model_path(model)
send(model.class.to_s.underscore.tr('/','_').pluralize+'_path')
end
def markdown(text)
renderer = Redcarpet::Render::HTML.new(hard_wrap: true, filter_html: true)
options = {
autolink: true,
no_intra_emphasis: true,
fenced_code_blocks: true,
lax_html_blocks: true,
strikethrough: true,
superscript: true,
space_after_headers: true,
tables: true
}
Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end
def page_title
title = content_for?(:title) ? yield(:title) : I18n.t(:sitename)
title = '[DEVELOP] ' + title if Rails.env.development?
title = '[STAGING] ' + title if Rails.env.staging?
title
end
def json_for(target, options = {})
options[:scope] ||= self
options[:url_options] ||= url_options
ActiveModelSerializers::SerializableResource.new(target, options).to_json
end
end<file_sep>/spec/models/workout/item_spec.rb
require 'rails_helper'
RSpec.describe Workout::Item, type: :model do
let (:workout) { create :workout }
let (:exercise) { create :exercise }
let (:item) { build :workout_item, workout: workout, exercise: exercise }
describe 'validation' do
it { expect(item).to be_valid }
describe 'should be invalid' do
describe 'when attribute' do
context 'exercise' do
it 'is nil' do
item.exercise = nil
expect(item).to_not be_valid
end
end
context 'sets' do
it 'is nil' do
item.sets = nil
expect(item).to_not be_valid
end
it 'has wrong type' do
expect{ item.sets = 'string value' }.to raise_error ActiveRecord::SerializationTypeMismatch
end
end
context 'pos' do
it 'is nil' do
item.pos = nil
expect(item).not_to be_valid
end
it 'less than 1' do
item.pos = 0
expect(item).not_to be_valid
end
it 'has wrong value' do
item.pos = 'val'
expect(item).not_to be_valid
end
it 'has exists value in workout scope' do
item.pos = 1
create :workout_item, workout: workout, exercise: exercise, pos: item.pos
expect(item).not_to be_valid
end
end
end
end
end
end
<file_sep>/app/controllers/pictures_controller.rb
class PicturesController < ApplicationController
respond_to :json
before_action :authenticate_user!
load_resource except: [:create]
authorize_resource
def index
if params[:obj_type] && params[:obj_id]
@pictures = Picture.for_obj(params[:obj_type], params[:obj_id])
else
@pictures = Picture.all
end
respond_with @pictures
end
def create
@picture = Picture.create(resource_params)
respond_with @picture
end
def update
@picture.update(resource_params)
respond_with @picture
end
def destroy
@picture.destroy!
respond_with @picture
end
private
def resource_params
accessible = [ :name, :image, :description ]
params.require(:picture).permit(accessible)
end
end
<file_sep>/spec/controllers/pictures_controller_spec.rb
require 'rails_helper'
RSpec.describe PicturesController, type: :controller do
let (:pictures) { create_list(:picture, 5) }
context 'JSON' do
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
context 'when logged in as admin' do
login(admin: true)
describe 'GET #index' do
it 'responds pictures as json' do
count = pictures.count
get :index
json = JSON.parse(response.body)
expect(json.length).to eq(count)
end
it 'responds pictures as json without muscle pictures' do
muscle = create(:muscle, pictures: [pictures.first])
get :index, {obj_type: 'References::Muscle', obj_id: muscle.id}
json = JSON.parse(response.body)
expect(json.length).to eq(pictures.count-muscle.pictures.count)
end
end
describe 'POST #create' do
it 'increase pictures count' do
params = { picture: attributes_for(:picture) }
expect{ post :create, params }.to change { Picture.count }.by 1
expect(response).to be_success
end
end
describe 'PUT #update' do
it 'change name' do
picture = pictures.first
params = { id: picture.id, picture: { name: 'new_name' } }
put :update, params
picture.reload
expect(response).to be_success
expect(picture.name).to eq 'new_name'
end
end
describe 'DELETE #destroy' do
it 'decrease pictures count' do
picture = pictures.first
params = { id: picture.id }
expect{ delete :destroy, params }.to change { Picture.count }.by -1
expect(response).to be_success
end
end
end
context 'when logged in as user' do
login(admin: false)
describe 'GET #index' do
it {
expect { get :index }.to raise_error CanCan::AccessDenied
}
end
describe 'POST #create' do
it {
params = { picture: attributes_for(:picture) }
expect { post :create, params }.to raise_error CanCan::AccessDenied
}
end
describe 'PUT #update' do
it {
picture = pictures.first
params = { id: picture.id, picture: { name: 'new_name' } }
expect { put :update, params }.to raise_error CanCan::AccessDenied
}
end
describe 'DELETE #destroy' do
it {
picture = pictures.first
params = { id: picture.id }
expect { delete :destroy, params }.to raise_error CanCan::AccessDenied
}
end
end
end
context 'DEFAULT' do
context 'when user not logged in' do
describe 'GET #index' do
it {
get :index
expect(response).to redirect_to '/users/sign_in'
}
end
end
context 'when logged in as user' do
login(admin: false)
describe 'GET #index' do
it { expect { get :index }.to raise_error CanCan::AccessDenied }
end
describe 'POST #create' do
it {
params = { picture: attributes_for(:picture) }
expect { post :create, params }.to raise_error CanCan::AccessDenied
}
end
describe 'PUT #update' do
it {
params = { id: pictures.first.id, picture: attributes_for(:picture) }
expect { put :update, params }.to raise_error CanCan::AccessDenied
}
end
describe 'DELETE #destroy' do
it {
params = { id: pictures.first.id }
expect { delete :destroy, params }.to raise_error CanCan::AccessDenied
}
end
end
context 'when logged in as admin' do
login(admin: true)
describe 'GET #index' do
it {
expect { get :index }.to raise_error ActionController::UnknownFormat
}
end
describe 'POST #create' do
it {
params = { picture: attributes_for(:picture) }
expect { post :create, params }.to raise_error ActionController::UnknownFormat
}
end
describe 'PUT #update' do
it {
params = { id: pictures.first.id, picture: attributes_for(:picture) }
expect { put :update, params }.to raise_error ActionController::UnknownFormat
}
end
describe 'DELETE #destroy' do
it {
params = { id: pictures.first.id }
expect { delete :destroy, params }.to raise_error ActionController::UnknownFormat
}
end
end
end
end
<file_sep>/spec/factories/references_body_parts.rb
FactoryGirl.define do
factory :body_part, class: 'References::BodyPart' do
sequence (:alias) { |n| "body_part#{n}" }
name 'Example BodyPart'
description 'BodyPart Description'
factory :body_part_with_muscle do
after(:create) do |body_part|
create(:muscle, body_parts: [body_part])
end
end
factory :body_part_with_exercise do
after(:create) do |body_part|
create(:exercise, body_parts: [body_part])
end
end
end
end<file_sep>/config/initializers/sidekiq.rb
if Rails.env.development?
require 'sidekiq/testing'
Sidekiq::Testing.inline!
end
Sidekiq.configure_client do |config|
config.redis = { :size => 1 }
end
Sidekiq.configure_server do |config|
config.redis = { :size => 7 }
end
schedule_file = "config/schedule.yml"
if File.exists?(schedule_file) && Sidekiq.server?
Sidekiq::Cron::Job.load_from_hash YAML.load_file(schedule_file)
end<file_sep>/db/migrate/20160611085817_drop_alias_from_workouts.rb
class DropAliasFromWorkouts < ActiveRecord::Migration
def change
remove_column :workouts, :alias
end
end
<file_sep>/spec/controllers/references/muscles_controller_spec.rb
require 'rails_helper'
RSpec.describe References::MusclesController, type: :controller do
before (:context) do
@muscle = create(:muscle)
end
describe "GET index" do
it "assigns @muscles" do
get :index
expect(assigns(:muscles)).to eq([@muscle])
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
end
end
describe "GET show" do
it "assigns @muscle" do
get :show, id: @muscle.id
expect(assigns(:muscle)).to eq(@muscle)
end
it "renders the show template" do
get :show, id: @muscle.id
expect(response).to render_template("show")
end
end
describe "GET new" do
describe "when user logged in" do
login(admin: true)
it "renders the new template" do
get :new
expect(response).to render_template("new")
end
end
describe "when user logged out" do
it 'should redirect to sign_in' do
get :new
expect(subject).to redirect_to("/users/sign_in")
end
end
end
describe "POST create" do
describe "when user logged in" do
login(admin: true)
let(:attr) do
attributes_for(:muscle)
end
before(:each) do
post :create, muscle: attr
@muscle = References::Muscle.last
end
it { expect(response).to redirect_to(@muscle) }
it { expect(@muscle.name).to eql attr[:name] }
it { expect(@muscle.alias).to eql attr[:alias] }
it { expect(@muscle.shape).to eql attr[:shape] }
end
end
describe "GET edit" do
describe "when user logged in" do
login(admin: true)
it "assigns @muscle" do
get :edit, id: @muscle.id
expect(assigns(:muscle)).to eq(@muscle)
end
it "renders the edit template" do
get :edit, id: @muscle.id
expect(response).to render_template("edit")
end
end
describe "when user logged out" do
it 'should redirect to sign_in' do
get :edit, id: @muscle.id
expect(subject).to redirect_to("/users/sign_in")
end
end
end
describe "PUT update" do
describe "when user logged in" do
login(admin: true)
let(:attr) do
{ :name => 'new name', :alias => 'new_alias', :shape => 'short' }
end
before(:example) do
@muscle = create(:muscle)
end
before(:each) do
put :update, :id => @muscle.id, :muscle => attr
@muscle.reload
end
it { expect(response).to redirect_to(@muscle) }
it { expect(@muscle.name).to eql attr[:name] }
it { expect(@muscle.alias).to eql attr[:alias] }
it { expect(@muscle.shape).to eql attr[:shape] }
end
end
describe "DELETE destroy" do
describe "when user logged in" do
login(admin: true)
before(:example) do
@muscle = create(:muscle)
end
it "should destroy muscle" do
expect{delete :destroy, :id => @muscle.id}.to change{References::Muscle.count}.by(-1)
end
it "should redirect to muscles_path" do
delete :destroy, :id => @muscle.id
expect(response).to redirect_to(references_muscles_path)
end
end
end
end
<file_sep>/app/mailers/statistics_mailer.rb
class StatisticsMailer < ApplicationMailer
def common
@stats = {
users: User.count,
body_parts: References::BodyPart.count,
exercises: References::Exercise.count,
muscles: References::Muscle.count,
workouts: Workout.count,
workout_items: Workout::Item.count,
jounal_items: Journal::Item.count
}
mail(to: User.all.where(admin: true).map(&:email), subject: 'Common Stats')
end
end
<file_sep>/app/serializers/picture_serializer.rb
class PictureSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :url, :thumb, :image_processing
def url
object.image_url
end
def thumb
object.image_url(:thumb)
end
end<file_sep>/app/models/references/equipment.rb
class References::Equipment < ActiveRecord::Base
include Anatomic
end
<file_sep>/spec/models/journal/item_spec.rb
require 'rails_helper'
RSpec.describe Journal::Item, type: :model do
let (:item) { build :journal_item, :with_journal, :with_workout }
describe 'validations' do
it { expect(item).to be_valid }
describe 'should be invalid when attribute' do
it 'journal is nil' do
item.journal = nil
expect(item).not_to be_valid
expect(item.errors.keys).to be == [:journal]
end
it 'workout is nil' do
item.workout = nil
expect(item).not_to be_valid
expect(item.errors.keys).to be == [:workout]
end
describe :executed_at do
it 'is nil' do
item.executed_at = nil
expect(item).not_to be_valid
expect(item.errors.keys).to be == [:executed_at]
end
it 'from future' do
item.executed_at = Time.now + 1.day
expect(item).not_to be_valid
expect(item.errors.keys).to be == [:executed_at]
end
end
end
end
end<file_sep>/spec/factories/journals.rb
FactoryGirl.define do
factory :journal do
trait :with_user do
user factory: :user
end
trait :with_items do
after :create do |journal|
create_list :journal_item, 3,
:journal => journal,
:workout => create(:workout, :with_items)
end
end
end
end
<file_sep>/Gemfile
ruby '2.1.10'
source 'https://rubygems.org'
gem 'rails', '~> 4.2.5'
gem 'sinatra', :require => nil
gem 'sidekiq'
gem 'sidekiq-cron', '~> 0.4.0'
gem 'composite_primary_keys', '~> 8.0'
gem 'rails-i18n', github: 'svenfuchs/rails-i18n', branch: 'rails-4-x'
gem 'omniauth'
#gem 'omniauth-twitter'
#gem 'omniauth-facebook'
#gem 'omniauth-linkedin'
gem 'omniauth-vkontakte'
gem 'omniauth-google-oauth2'
gem 'devise'
gem 'cancan'
gem 'fog'
gem 'carrierwave', github: 'carrierwaveuploader/carrierwave', branch: '0.11-stable'
gem 'carrierwave_backgrounder'
gem 'active_model_serializers', '~> 0.10'
gem 'mini_magick'
gem 'figaro'
# Interpreters
gem 'therubyracer', platforms: :ruby
gem 'haml-rails'
gem 'coffee-rails', '~> 4.1.0'
gem 'less-rails'
gem 'uglifier', '~> 3'
gem 'sass-rails'
gem 'redcarpet' # Markdown
# Assests
gem 'i18n-js', '>= 3.0.0.rc11'
gem 'jquery-rails'
gem 'twitter-bootstrap-rails'
gem 'handlebars_assets'
gem 'hamlbars'
gem 'rails-backbone'
gem 'momentjs-rails', '>= 2.9.0'
gem 'bootstrap-datepicker-rails'
gem 'bootstrap3-datetimepicker-rails', '~> 4.17.37'
gem 'lightbox2-rails', '~> 2.7.0'
group :production, :staging do
gem 'pg'
gem 'rails_12factor'
gem 'yui-compressor'
gem 'unicorn-rails'
end
group :development, :test do
gem 'spring'
gem 'sqlite3'
end
group :development do
gem 'pry-rails'
gem 'letter_opener'
gem 'better_errors'
gem 'byebug'
gem 'binding_of_caller'
gem 'foreman'
gem 'puma'
gem 'capistrano', '~> 3.1'
gem 'capistrano-rails', '~> 1.1'
gem 'capistrano-bundler', '~> 1.1.2'
gem 'capistrano-rvm'
gem 'capistrano-faster-assets', '~> 1.0'
end
group :test do
gem 'timecop'
gem 'rspec-rails'
gem 'fakeredis'
gem 'factory_girl_rails'
gem 'database_cleaner'
gem 'codeclimate-test-reporter', require: nil
gem 'capybara'
gem 'selenium-webdriver'
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
# validations
# REGEX
REAL_NAME_REGEX = /\A[\da-zа-яё ,.'\-_]*\z/i
devise :omniauthable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
validates :email, :city, :country, length: { maximum: 100 }
validates :first_name, :last_name, format: { with: REAL_NAME_REGEX }, length: { maximum: 50 }
validates :gender, inclusion: [:m, :f, 'm', 'f', nil]
validate :at_least_18
#callbacks
before_save {
self.email = email.downcase if email
}
# associations
has_many :identities, :dependent => :delete_all
has_one :journal, dependent: :destroy
#methods
# use lazy user journal creation
alias :original_journal_method :journal
def journal
if original_journal_method.nil?
Rails.logger.warn "Create journal for user_id #{self.id}"
Journal.create(user: self)
else
original_journal_method
end
end
def self.new_with_session(params, session)
super.tap do |user|
if (data = session["devise.auth_data"])
data = Utils::OAuth.normalize data
user.email = data.info.email if user.email.blank?
end
end
end
def self.find_for_oauth(normalized_auth, signed_in_user = nil)
identity = Identity.find_for_oauth normalized_auth
user = identity.user || signed_in_user || User.find_by_email(identity.email)
if user.nil?
generated_password = Devise.friendly_token.first(8)
user = User.new(
email: identity.email,
confirmed_at: DateTime.now,
first_name: normalized_auth.info.first_name,
last_name: normalized_auth.info.last_name,
password: <PASSWORD>,
password_confirmation: <PASSWORD>
)
user.skip_confirmation!
user.save!
UserMailer.delay.welcome(user.id, generated_password) if user.persisted?
end
if user.persisted? && identity.user != user
identity.user = user
identity.save!
end
user
end
private
def at_least_18
if self.date_of_birth
errors.add(:date_of_birth, I18n.t('users.error.too_young')) if self.date_of_birth >= 18.years.ago
end
end
end
<file_sep>/app/serializers/references/body_part_serializer.rb
class References::BodyPartSerializer < ActiveModel::Serializer
attributes :id, :name, :alias, :description
has_many :muscles, serializer: References::MuscleShortSerializer
has_many :exercises, serializer: References::ExerciseShortSerializer
end<file_sep>/app/serializers/references/equipment_serializer.rb
class References::EquipmentSerializer < ActiveModel::Serializer
attributes :id, :name, :alias
end<file_sep>/app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: Rails.application.secrets.mail_from
layout 'mailer'
end
<file_sep>/config/initializers/carrierwave.rb
CarrierWave.configure do |config|
# Disable processing in tests
if Rails.env.test? || Rails.env.cucumber?
config.enable_processing = false
end
if Rails.env.development? || Rails.env.test? || Rails.env.cucumber?
config.storage = :file
else
config.storage = :fog
config.fog_credentials = {
provider: 'Google',
google_storage_access_key_id: Rails.application.secrets.fog_accesskey,
google_storage_secret_access_key: Rails.application.secrets.fog_secretkey
}
config.fog_directory = Rails.application.secrets.fog_directory
end
end<file_sep>/db/migrate/20160218074741_create_picture_imageables.rb
class CreatePictureImageables < ActiveRecord::Migration
def change
reversible do |dir|
dir.up do
create_table :picture_links, id: false do |t|
t.references :picture, index: true, foreign_key: true
t.references :pictureable, polymorphic: true
end
add_index :picture_links, [:pictureable_id, :pictureable_type, :picture_id], name: 'pk_picture_links', unique: true
execute <<-SQL
INSERT INTO picture_links (picture_id, pictureable_type, pictureable_id)
SELECT id, imageable_type, imageable_id from pictures
SQL
remove_columns :pictures, :imageable_id, :imageable_type
end
dir.down do
add_reference :pictures, :imageable, polymorphic: true, index: true
execute <<-SQL
UPDATE pictures
SET imageable_id = (select picture_links.pictureable_id
from picture_links
where picture_links.picture_id = pictures.id),
imageable_type = (select picture_links.pictureable_type
from picture_links
where picture_links.picture_id = pictures.id)
WHERE EXISTS(
SELECT *
FROM picture_links
WHERE picture_links.picture_id = pictures.id
)
SQL
remove_foreign_key :pk_picture_links, :picture
remove_index(:picture_links, :name => 'pk_picture_links')
drop_table :picture_links
end
end
end
end
<file_sep>/app/controllers/references/body_parts_controller.rb
class References::BodyPartsController < AnatomicController
def index
@body_parts = References::BodyPart.all.eager_load(:exercises, :muscles)
respond_with @body_parts,
each_serializer: request.format == :json && params[:short] ?
References::BodyPartShortSerializer :
References::BodyPartSerializer
end
private
def resource_params
accessible = [ :name, :alias, :description, :shape, :muscle_ids => [], :exercise_ids => [] ]
params.require(:body_part).permit(accessible)
end
end
<file_sep>/lib/utils/enum.rb
module Utils
class Enum < String
class_attribute :i18n_scope
class_attribute :valid_values
def self.values
@values ||= Array(valid_values).map { |val| new(val) }
end
def initialize(s)
unless s.in?(Array(valid_values))
raise ArgumentError, "#{s.inspect} is not a valid #{self.class} value"
end
super
end
def human_name
if i18n_scope.blank?
raise NotImplementedError, 'Your subclass must define :i18n_scope'
end
I18n.t!(value, scope: i18n_scope)
end
def value
to_s
end
def as_json(opts = nil)
{
'value' => value,
'human_name' => human_name
}
end
def self.load(value)
if value.present?
new(value)
else
# Don't try to convert nil or empty strings
value
end
end
def self.dump(obj)
obj.to_s
end
end
end<file_sep>/app/serializers/workout/item_serializer.rb
class Workout::ItemSerializer < ActiveModel::Serializer
attributes :pos, :sets, :exercise_id
end
<file_sep>/app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def welcome(user_id, generated_password)
@user = User.find(user_id)
@password = <PASSWORD>
mail(to: @user.email, subject: 'Welcome')
end
end<file_sep>/spec/factories/users.rb
FactoryGirl.define do
factory :user do
transient do
sequence (:name) { |n| "user#{n}" }
end
first_name { "firstname_#{name}" }
last_name { "lastname_#{name}" }
gender { [:f, :m].sample }
country { ['country 1', 'country 2', 'country 3'].sample }
city { ['city 1','city 2','city 3'].sample }
date_of_birth { rand(18..90).year.ago }
email { <EMAIL>" }
password "<PASSWORD>"
password_confirmation "<PASSWORD>"
factory :admin do
admin true
end
end
end
<file_sep>/app/controllers/references/pictures_controller.rb
class References::PicturesController < ApplicationController
respond_to :html, only: [:index]
respond_to :json
before_action :authenticate_user!
authorize_resource
before_action :load_parent, only: [:index, :show, :create, :destroy]
def index
@pictures = @parent.pictures.all
respond_with @pictures
end
def show
@picture = @parent.pictures.find(params[:id])
respond_with @picture
end
def create
@picture = Picture.find(params[:l_id])
@parent.pictures << @picture
respond_with @picture
end
def destroy
@picture = Picture.find(params[:id])
@picture = @parent.pictures.delete(@picture)
respond_with @picture
end
private
def load_parent
parent_klasses = %w[muscle]
if klass = parent_klasses.detect { |pk| params[:"#{pk}_id"].present? }
@parent = "References::#{klass.camelize}".constantize.find params[:"#{klass}_id"]
end
end
end
<file_sep>/db/migrate/20160620110952_add_workoutable_to_workout.rb
class AddWorkoutableToWorkout < ActiveRecord::Migration
def up
change_table :workouts do |t|
t.references :workoutable, polymorphic: true, index: true
end
Journal::Item.all.each do |item|
Workout.connection.execute(
"UPDATE workouts " +
" SET workoutable_type = 'Journal::Item', workoutable_id = #{item.id} " +
" WHERE id = #{item.workout_id}"
)
end
change_table :journal_items do |t|
t.remove_references :workout, index: true, foreign_key: true, null: false
end
end
def down
change_table :journal_items do |t|
t.references :workout, index: true, foreign_key: true
end
Workout.all.each do |workout|
Journal::Item.connection.execute(
"UPDATE journal_items " +
" SET workout_id = '#{workout.id}' " +
" WHERE 'Journal::Item' = '#{workout.workoutable_type}' and id = '#{workout.workoutable_id}'"
)
end
change_column_null :journal_items, :workout_id, false
change_table :workouts do |t|
t.remove_references :workoutable, polymorphic: true, index: true
end
end
end
<file_sep>/spec/models/references/muscle_spec.rb
require 'rails_helper'
RSpec.describe References::Muscle, type: :model do
it_behaves_like 'anatomic'
let (:muscle) { build :muscle }
describe 'validation:' do
describe 'should be valid' do
context 'when attribute' do
it 'shape is valid' do
Muscles::Shape.values.each do |shape|
muscle.shape = shape
expect(muscle).to be_valid
end
end
end
end
describe 'should be invalid' do
context 'when attribute' do
it 'shape is empty' do
muscle.shape = nil
expect(muscle).to be_invalid
expect(muscle.errors.messages.keys).to eq [:shape]
end
end
end
end
it 'should raise ArgumentError with wrong shape' do
def build_resource
build :muscle, shape: 'non-existing shape'
end
expect { build_resource }.to raise_error(ArgumentError)
end
it 'should create body_part' do
expect { create(:muscle_with_body_part) }.to change{References::BodyPart.count}.by(1)
end
it 'should create exercise' do
expect { create(:muscle_with_exercise) }.to change{References::Exercise.count}.by(1)
end
end<file_sep>/app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
# GET /resource/change_general
def edit
render get_action
end
# PUT /resource
# We need to use a copy of the resource because we don't want to change
# the current user in place.
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
resource_updated = update_resource(resource, account_update_params)
yield resource if block_given?
if resource_updated
if is_flashing_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
set_flash_message :notice, flash_key
end
sign_in resource_name, resource, bypass: true
respond_with resource do |format|
format.html {render :action => get_action}
end
else
clean_up_passwords resource
respond_with resource, :action => get_action
end
end
protected
def get_action
case params['act']
when 'password'
return :change_password
when 'contacts'
return :change_contacts
else
return :change_general
end
end
def update_resource(resource, params)
if params['password'] || params['current_password']
resource.update_with_password(params)
else
resource.update_without_password(params)
end
end
end
<file_sep>/lib/validators/time_range_validator.rb
class TimeRangeValidator < ActiveModel::EachValidator
MESSAGES = { :is => :wrong_time, :minimum => :too_early_time, :maximum => :too_later_time }.freeze
CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
RESERVED_OPTIONS = [:minimum, :maximum, :within, :in, :is]
def initialize(options)
if range = (options.delete(:in) || options.delete(:within))
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
options[:minimum], options[:maximum] = range.begin, range.end
options[:maximum] -= 1.day if range.exclude_end?
end
super
end
def check_validity!
keys = CHECKS.keys & options.keys
if keys.empty?
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
end
keys.each do |key|
value = options[key]
unless (value.is_a?(Time) || value.is_a?(Proc))
raise ArgumentError, ":#{key} must be a Time or Proc instead #{value.class}"
end
end
if keys.include?(:minimum) && keys.include?(:maximum) && options[:maximum] <= options[:minimum]
raise ArgumentError, 'maximum time must be later minimum time'
end
end
def validate_each(record, attribute, value)
return if value.nil?
raise(ArgumentError, "'A Time object was expected instead #{value.class}") unless value.kind_of? Time
CHECKS.each do |key, validity_check|
next unless check_value = (options[key].is_a?(Proc) ? options[key].call : options[key])
next if value.send(validity_check, check_value)
errors_options = options.except(*RESERVED_OPTIONS)
errors_options[:time] = check_value
default_message = options[MESSAGES[key]]
errors_options[:message] ||= default_message if default_message
record.errors.add(attribute, MESSAGES[key], errors_options)
end
end
end
<file_sep>/app/models/references/muscle.rb
class References::Muscle < ActiveRecord::Base
include Anatomic
has_and_belongs_to_many :body_parts
has_and_belongs_to_many :exercises
serialize :shape, Muscles::Shape
validates_inclusion_of :shape, in: Muscles::Shape.values
scope :no_bodypart, -> {
where('id NOT IN (SELECT DISTINCT(muscle_id) FROM references_body_parts_muscles)')
}
has_many :picture_links, as: :pictureable, dependent: :destroy
has_many :pictures, through: :picture_links
end
<file_sep>/spec/factories/pictures.rb
FactoryGirl.define do
factory :picture do
name 'Test Picture'
description 'Test Picture'
image { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'pictures', 'test_image.jpg'), "image/jpeg") }
end
end
<file_sep>/spec/factories/references_muscles.rb
FactoryGirl.define do
factory :muscle, class: 'References::Muscle' do
sequence (:alias) { |n| "muscle#{n}" }
name 'Example Muscle'
description 'Muscle Description'
shape 'long'
factory :muscle_with_body_part do
after(:create) do |muscle|
create(:body_part, muscles: [muscle])
end
end
factory :muscle_with_exercise do
after(:create) do |muscle|
create(:exercise, muscles: [muscle])
end
end
end
end
<file_sep>/spec/controllers/references/body_parts_controller_spec.rb
require 'rails_helper'
RSpec.describe References::BodyPartsController, type: :controller do
before (:context) do
@body_part = create(:body_part)
end
describe "GET index" do
it "assigns @body_parts" do
get :index
expect(assigns(:body_parts)).to eq([@body_part])
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
end
end
describe "GET show" do
it "assigns @body_part" do
get :show, id: @body_part.id
expect(assigns(:body_part)).to eq(@body_part)
end
it "renders the show template" do
get :show, id: @body_part.id
expect(response).to render_template("show")
end
end
describe "GET new" do
describe "when user logged in" do
login(admin: true)
it "renders the new template" do
get :new
expect(response).to render_template("new")
end
end
describe "when user logged out" do
it 'should redirect to sign_in' do
get :new
expect(subject).to redirect_to("/users/sign_in")
end
end
end
describe "POST create" do
describe "when user logged in" do
login(admin: true)
let(:attr) do
attributes_for(:body_part)
end
before(:each) do
post :create, body_part: attr
@body_part = References::BodyPart.last
end
it { expect(response).to redirect_to(@body_part) }
it { expect(@body_part.name).to eql attr[:name] }
it { expect(@body_part.alias).to eql attr[:alias] }
end
end
describe "GET edit" do
describe "when user logged in" do
login(admin: true)
it "assigns @body_part" do
get :edit, id: @body_part.id
expect(assigns(:body_part)).to eq(@body_part)
end
it "renders the edit template" do
get :edit, id: @body_part.id
expect(response).to render_template("edit")
end
end
describe "when user logged out" do
it 'should redirect to sign_in' do
get :edit, id: @body_part.id
expect(subject).to redirect_to("/users/sign_in")
end
end
end
describe "PUT update" do
describe "when user logged in" do
login(admin: true)
let(:attr) do
{ :name => 'new name', :alias => 'new_alias' }
end
before(:example) do
@body_part = create(:body_part)
end
before(:each) do
put :update, :id => @body_part.id, :body_part => attr
@body_part.reload
end
it { expect(response).to redirect_to(@body_part) }
it { expect(@body_part.name).to eql attr[:name] }
it { expect(@body_part.alias).to eql attr[:alias] }
end
end
describe "DELETE destroy" do
describe "when user logged in" do
login(admin: true)
before(:example) do
@body_part = create(:body_part)
end
it "should destroy body_part" do
expect{delete :destroy, :id => @body_part.id}.to change{References::BodyPart.count}.by(-1)
end
it "should redirect to body_parts_path" do
delete :destroy, :id => @body_part.id
expect(response).to redirect_to(references_body_parts_path)
end
end
end
context 'JSON' do
let (:body_parts) { create_list(:body_part, 5) }
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
describe 'GET #index' do
describe 'responds body_parts as json with' do
it 'right count' do
count = References::BodyPart.count+body_parts.count
get :index
json = JSON.parse(response.body)
expect(json.length).to eq(count)
end
it 'extended format' do
get :index
json = JSON.parse(response.body)
expect(json.first.keys).to eq(%w(id name alias description muscles exercises))
end
it 'short format' do
get :index, {short:1}
json = JSON.parse(response.body)
expect(json.first.keys).to eq(%w(id name alias))
end
end
end
end
end
<file_sep>/config/deploy/production.rb
set :rails_env, 'production'
set :rake_env, 'production'
set :user, 'deploy'
ask :server, 'logym.ru'
server fetch(:server),
user: "#{fetch(:user)}",
roles: %w{app db web}<file_sep>/app/uploaders/picture_uploader.rb
class PictureUploader < CarrierWave::Uploader::Base
include ::CarrierWave::Backgrounder::Delay
include CarrierWave::MiniMagick
def store_dir
"#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png tif tiff)
end
process convert: 'jpg'
process resize_to_limit: [2000, 2000]
version :small do
process resize_to_limit: [300, 300]
process convert: 'jpg'
end
version :thumb, from_version: :small do
process resize_to_fill: [150, 150]
process convert: 'jpg'
end
def filename
if original_filename.present?
if model.respond_to?("#{mounted_as}_processing") && model.send("#{mounted_as}_processing")
@name ||= model.send("#{mounted_as}_identifier")
else
@name ||= "#{secure_token(8)}.jpg"
end
end
end
protected
def secure_token(length=16)
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end
end<file_sep>/app/models/references/body_part.rb
class References::BodyPart < ActiveRecord::Base
include Anatomic
has_and_belongs_to_many :muscles
has_and_belongs_to_many :exercises
scope :with_muscles, -> {
includes(:muscles).where.not(references_muscles: { id: nil })
}
end
<file_sep>/app/serializers/journal/item_serializer.rb
class Journal::ItemSerializer < ActiveModel::Serializer
attributes :id, :executed_at, :workout_attributes
def executed_at
object.executed_at.to_i
end
def workout_attributes
ActiveModelSerializers::SerializableResource.new(object.workout)
end
end
<file_sep>/app/models/picture_link.rb
class PictureLink < ActiveRecord::Base
self.primary_keys = :pictureable_id, :pictureable_type, :picture_id
belongs_to :picture
belongs_to :pictureable, polymorphic: true
validates_uniqueness_of :picture_id, scope: [:pictureable_id, :pictureable_type]
end
<file_sep>/lib/utils/o_auth.rb
module Utils
class OAuth
def self.normalize ( data )
data = OmniAuth::AuthHash.new(data) if data.kind_of? Hash
# for example:
# data.info.nickname = data.extra.raw_info.screen_name if (data.nickname.blank? && data.provider == 'vkontakte')
data
end
end
end<file_sep>/spec/models/picture_link_spec.rb
require 'rails_helper'
RSpec.describe PictureLink, type: :model do
let (:picture) { create :picture }
let (:pictureable) { create :muscle }
describe 'validation:' do
it { expect(PictureLink.create picture: picture, pictureable: pictureable).to be_valid }
describe 'should be invalid' do
it 'with duplicate PrimaryKey' do
PictureLink.create picture: picture, pictureable: pictureable
expect(PictureLink.create picture: picture, pictureable: pictureable).to be_invalid
end
end
end
end
<file_sep>/config/routes.rb
require 'sidekiq/web'
require 'sidekiq/cron/web'
Rails.application.routes.draw do
root 'welcome#index'
get 'welcome/index'
devise_for :users,
:controllers => {
:omniauth_callbacks => 'users/omniauth_callbacks',
:registrations => 'users/registrations'
}
resources :users
namespace :references do
concern :pictureable do
resources :pictures, only: [:index, :show, :create, :destroy]
end
resources :equipments
resources :muscles, concerns: :pictureable
resources :exercises
resources :body_parts
end
resources :pictures, only: [:index, :create, :update, :destroy]
namespace :journal do
resources :items
end
authenticate :user, lambda { |u| u.admin? } do
mount Sidekiq::Web => '/sidekiq'
end
end<file_sep>/app/controllers/references/exercises_controller.rb
class References::ExercisesController < AnatomicController
def index
@exercises = References::Exercise.all.eager_load(:equipments, :body_parts, :muscles)
respond_with @exercises,
each_serializer: request.format == :json && params[:short] ?
References::ExerciseShortSerializer :
References::ExerciseSerializer
end
private
def resource_params
accessible = [ :name, :alias, :description, :body_part_ids => [], :muscle_ids => [], :equipment_ids => [] ]
params.require(:exercise).permit(accessible)
end
end
<file_sep>/spec/factories/journal_items.rb
FactoryGirl.define do
factory :journal_item, class: 'Journal::Item' do
executed_at 1.days.ago
trait :with_journal do
journal factory: [ :journal, :with_user ]
end
trait :with_workout do
workout factory: [ :workout, :with_items ]
end
end
end
<file_sep>/spec/features/layout_spec.rb
require 'rails_helper'
describe 'Layout', type: :feature do
context 'when logged in as admin' do
login(admin: true)
it 'should have admin label' do
visit '/'
expect(page).to have_css 'strong.alert-danger', text: 'admin'
end
end
context 'when logged in as user' do
login(admin: false)
it 'should have no admin label' do
visit '/'
expect(page).to have_no_css 'strong.alert-danger', text: 'admin'
end
end
context 'responsive layout', js: true do
context 'when mobile' do
before do
resize_window_to_mobile
end
after do
resize_window_default
end
it '#sidebar should be hidden' do
visit '/'
page.execute_script File.read(File.join(Rails.root, %w(vendor assets javascripts jquery.visible.js)))
expect(page.evaluate_script('$(\'#sidebar\').visible()')).to eq false
end
it '#sidebar should be visible' do
visit '/'
page.find('.navbar-header').find('button.navbar-toggle').click
page.execute_script File.read(File.join(Rails.root, %w(vendor assets javascripts jquery.visible.js)))
expect(page.evaluate_script('$(\'#sidebar\').visible()')).to eq true
end
end
end
end<file_sep>/app/models/journal/item.rb
require 'validators/time_range_validator'
class Journal::Item < ActiveRecord::Base
belongs_to :journal
has_one :workout,
as: :workoutable,
autosave: true,
validate: true,
dependent: :destroy
accepts_nested_attributes_for :workout
validates :journal, :workout, :executed_at, presence: true
validates :executed_at, time_range: { maximum: -> { Time.now } }
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# Equipment
References::Equipment.create(alias: 'barbell', name: 'Штанга')
References::Equipment.create(alias: 'dumbbell', name: 'Гантели')
References::Equipment.create(alias: 'weight', name: 'Утяжелитель')
References::Equipment.create(alias: 'cable', name: 'Трос')
References::Equipment.create(alias: 'lever_plate', name: 'Рычаги с блинами')
References::Equipment.create(alias: 'lever_selectorized', name: 'Рачаги с наборными блоками')
References::Equipment.create(alias: 'sled', name: 'Салазки')
References::Equipment.create(alias: 'smith', name: '<NAME>')<file_sep>/app/controllers/journal/items_controller.rb
class Journal::ItemsController < ApplicationController
before_action :authenticate_user!
respond_to :html, only: [:index]
respond_to :json
def index
@items = current_user.journal.items.eager_load(workout: [items: [:exercise]]) if request.format == :json
respond_with @items
end
def show
@item = current_user.journal.items.eager_load(workout: [items: [:exercise]]).find(params[:id])
respond_with @item
end
def update
@item = current_user.journal.items.eager_load(workout: [items: [:exercise]]).find(params[:id])
@item.update(item_params)
@item.save
respond_with @item
end
def create
@item = current_user.journal.items.new(item_params)
@item.save
respond_with @item
end
def destroy
@item = current_user.journal.items.find(params[:id])
@item.destroy!
respond_with @item
end
private
def item_params
res = params.permit(
:executed_at,
workout_attributes: [
:name,
items_attributes: [
:exercise_id,
:pos,
sets: [:weight, :repeats]
]
]
)
res[:executed_at] = Time.at(res[:executed_at].to_i) if res[:executed_at]
res
end
end<file_sep>/db/migrate/20160706115531_rename_scoped_references.rb
class RenameScopedReferences < ActiveRecord::Migration
def change
rename_table 'body_parts', 'references_body_parts'
rename_table 'body_parts_exercises', 'references_body_parts_exercises'
rename_table 'body_parts_muscles', 'references_body_parts_muscles'
rename_table 'exercises', 'references_exercises'
rename_table 'exercises_muscles', 'references_exercises_muscles'
rename_table 'muscles', 'references_muscles'
reversible do |dir|
dir.up do
execute <<-SQL
UPDATE picture_links
SET pictureable_type = 'References::Muscle'
WHERE pictureable_type = 'Muscle'
SQL
end
dir.down do
execute <<-SQL
UPDATE picture_links
SET pictureable_type = 'Muscle'
WHERE pictureable_type = 'References::Muscle'
SQL
end
end
end
end
<file_sep>/spec/factories/references_equipment.rb
FactoryGirl.define do
factory :equipment, class: 'References::Equipment' do
sequence (:alias) { |n| "body_part#{n}" }
name "Equipment Test Name"
description "Equipment Test Description"
end
end
<file_sep>/spec/features/index_page_spec.rb
require 'rails_helper'
describe 'Index page', type: :feature do
it 'has welcome string' do
visit '/'
expect(page).to have_content 'Добро пожаловать на ресурс'
end
end<file_sep>/app/controllers/references/equipments_controller.rb
class References::EquipmentsController < ApplicationController
respond_to :json, only: [:index]
def index
@equipments = References::Equipment.all
respond_with @equipments
end
end
<file_sep>/spec/support/active_record/base.rb
# Use single connection, because SQLite not support concurrency connections
class ActiveRecord::Base
mattr_accessor :shared_connection
@@shared_connection = nil
def self.connection
@@shared_connection || retrieve_connection
end
end<file_sep>/app/helpers/users_helper.rb
module UsersHelper
def birthday(user)
if user.date_of_birth
user.date_of_birth.strftime("%d.%m.%Y")
else
''
end
end
end<file_sep>/app/serializers/workout_serializer.rb
class WorkoutSerializer < ActiveModel::Serializer
attributes :name, :items_attributes
def items_attributes
ActiveModelSerializers::SerializableResource.new(object.items)
end
end
<file_sep>/db/migrate/20150714065222_create_exercises_muscles.rb
class CreateExercisesMuscles < ActiveRecord::Migration
def change
create_table :exercises_muscles, :id => false do |t|
t.references :exercise, index: true, foreign_key: true
t.references :muscle, index: true, foreign_key: true
end
end
end
<file_sep>/lib/tasks/pictures.rake
namespace :pictures do
desc "Recreate all pictures"
task recreate: :environment do
pictures = Picture.all
puts 'Recreate started... ' + pictures.size.to_s + ' count'
pictures.each do |p|
begin
puts 'Process: ' + p.id.to_s
p.process_image_upload = true
p.image.cache_stored_file!
p.image.retrieve_from_cache!(p.image.cache_name)
p.image.recreate_versions!
p.save!
rescue => e
puts e.message
end
end
end
end<file_sep>/spec/models/references/body_part_spec.rb
require 'rails_helper'
RSpec.describe References::BodyPart, type: :model do
it_behaves_like 'anatomic'
it 'should create muscle' do
expect { create(:body_part_with_muscle) }.to change{References::Muscle.count}.by(1)
end
it 'should create exercise' do
expect { create(:body_part_with_exercise) }.to change{References::Exercise.count}.by(1)
end
end
<file_sep>/spec/support/devise.rb
require 'devise'
# Disable backgrounder proxy for tests
Devise.mailer = Devise::Mailer
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, :type => :controller
end
<file_sep>/spec/support/feature_macros.rb
module FeatureMacros
def login(options = {})
include Warden::Test::Helpers
before :each do
role = options[:admin]||false ? :admin : :user
user = FactoryGirl.create(role, confirmed_at: Time.zone.now)
Warden.test_mode!
login_as(user, scope: :user)
end
after :each do
logout(:user)
Warden.test_reset!
end
end
end<file_sep>/spec/models/workout_spec.rb
require 'rails_helper'
RSpec.describe Workout, type: :model do
let (:workout) { create :workout }
describe 'ordering items' do
describe 'should have asc ordering' do
it 'when created in random order' do
create :workout_item, workout: workout, exercise: create(:exercise), pos: 4
create :workout_item, workout: workout, exercise: create(:exercise), pos: 2
create :workout_item, workout: workout, exercise: create(:exercise), pos: 3
create :workout_item, workout: workout, exercise: create(:exercise), pos: 1
expect(workout.items.map(&:pos)).to be == (1..4).to_a
end
end
end
end
<file_sep>/config/deploy.rb
lock '3.6.1'
set :application, 'gym'
set :repo_url, '<EMAIL>:davydes/gym.git'
set :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }
set :deploy_to, "/var/www/apps/#{fetch :application}/#{fetch :stage}"
set :scm, :git
set :format, :airbrussh
set :format_options, command_output: true, log_file: 'log/capistrano.log', color: :auto, truncate: :auto
set :pty, true
set :keep_releases, 3
set :linked_files, fetch(:linked_files, []).push('config/application.yml', 'config/unicorn.rb', 'config/sidekiq.yml')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/sockets', 'tmp/cache', 'vendor/bundle', 'public/system', 'public/uploads')
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
# RVM
################################################################################
set :rvm_type, :user
set :rvm_ruby_version, '2.1.10'
set :rvm_custom_path, '~/.rvm'
################################################################################
namespace :app do
desc 'Stop Application'
task :stop do
on roles(:web) do
# Do stop
sudo "systemctl stop #{fetch :application}-web@#{fetch :stage}"
sudo "systemctl stop #{fetch :application}-worker@#{fetch :stage}"
end
end
desc 'Start Application'
task :start do
on roles(:web) do
sudo "systemctl start #{fetch :application}-web@#{fetch :stage}"
sudo "systemctl start #{fetch :application}-worker@#{fetch :stage}"
end
end
desc 'Restart Application'
task :restart
before :restart, :stop
before :restart, :start
end
namespace :deploy do
desc "Make sure local git is in sync with remote."
task :check_revision do
on roles(:web) do
unless `git rev-parse HEAD` == `git rev-parse origin/#{fetch :branch}`
puts "WARNING: HEAD is not the same as origin/#{fetch :branch}"
puts "Run `git push` to sync changes."
exit
end
end
end
before "deploy", "deploy:check_revision"
desc "Upload shared configs"
task :upload do
on roles(:web) do
execute "mkdir -p #{shared_path}/config"
upload! "shared/application.#{fetch :stage}.yml", "#{shared_path}/config/application.yml"
#upload! "shared/puma.#{fetch :stage}.rb", "#{shared_path}/config/puma.rb"
upload! "shared/unicorn.#{fetch :stage}.rb", "#{shared_path}/config/unicorn.rb"
upload! "shared/sidekiq.yml", "#{shared_path}/config/sidekiq.yml"
end
end
after :publishing, 'app:restart'
after :restart, :clear_cache do
on roles(:web), in: :groups, limit: 3, wait: 10 do
# Here we can do anything such as:
# within release_path do
# execute :rake, 'cache:clear'
# end
end
end
end
<file_sep>/spec/factories/workout_items.rb
FactoryGirl.define do
factory :workout_item, class: 'Workout::Item' do
sets { [ [160,2], [170,2] ] }
description 'Workout Item Description'
pos { workout.items.count + 1 }
end
end<file_sep>/app/helpers/devise_helper.rb
module DeviseHelper
def admin?
current_user and current_user.admin?
end
def devise_error_messages!
return '' if resource.errors.empty?
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
sentence = I18n.t("errors.messages.not_saved",
count: resource.errors.count)
html = <<-HTML
<div class="panel panel-danger">
<div class="panel-heading">
#{sentence}
<a class="pull-right btn btn-danger btn-xs" role="button" data-toggle="collapse" href="#error_explanation" aria-expanded="false" aria-controls="error_explanation">
<i id="error_explanation_chevron" class="fa fa-chevron-down"></i>
</a>
</div>
<div class="panel-body collapse" id="error_explanation">
<ul>#{messages}</ul>
</div>
</div>
<script>
(function() {
$('#error_explanation').on('shown.bs.collapse', function() {
$("#error_explanation_chevron").addClass('fa-chevron-up').removeClass('fa-chevron-down');
});
$('#error_explanation').on('hidden.bs.collapse', function() {
$("#error_explanation_chevron").addClass('fa-chevron-down').removeClass('fa-chevron-up');
});
}).call(this);
</script>
HTML
html.html_safe
end
end
<file_sep>/spec/models/picture_spec.rb
require 'rails_helper'
RSpec.describe Picture, type: :model do
describe 'validation:' do
let (:picture) do
build(:picture)
end
it { expect(picture).to be_valid }
describe 'should be invalid' do
context 'when attribute' do
it 'name is empty' do
picture.name = ''
expect(picture).to be_invalid
expect(picture.errors.messages.keys).to eq([:name])
end
describe :image do
it 'is empty' do
picture.remove_image!
expect(picture).to be_invalid
expect(picture.errors.messages.keys).to eq([:image])
end
it 'has wrong content type' do
picture.image.file.content_type = 'wrong/type'
expect(picture).to be_invalid
expect(picture.errors.messages.keys).to eq([:image])
end
end
end
end
end
describe '::pictureables' do
it 'should include pictureable' do
pictureable = create :muscle, pictures: [picture = create(:picture)]
expect(picture.pictureables).to include pictureable
end
end
describe 'scope lonely' do
it 'should be [picture]' do
picture = create :picture
create :muscle, pictures: [create(:picture)]
expect(Picture.count).to eq 2
expect(Picture.lonely).to eq [picture]
end
end
end
<file_sep>/spec/controllers/journal/items_controller_spec.rb
require 'rails_helper'
RSpec.describe Journal::ItemsController, type: :controller do
let (:journal) { create :journal, user: create(:user, confirmed_at: Time.zone.now) }
context 'HTTP' do
context 'when logged in as journal owner' do
before :each do
sign_in journal.user
end
context 'GET index' do
it 'assigns nil @items' do
item = create :journal_item, :with_workout, journal: journal
get :index
expect(assigns(:items)).to be_nil
end
it 'render template' do
get :index
expect(response).to render_template('journal/items/index')
end
end
end
context 'when logged out' do
context 'GET index' do
it 'should redirect to sign_in page' do
get :index
expect(response).to redirect_to('/users/sign_in')
end
end
end
end
context 'JSON' do
before :each do
request.env['HTTP_ACCEPT'] = 'application/json'
end
context 'when logged in as journal owner' do
before :each do
sign_in journal.user
end
context 'GET index' do
it 'assigns @items' do
item = create :journal_item, :with_workout, journal: journal
get :index
expect(assigns(:items)).to eq([item])
end
end
context 'GET show' do
it 'assigns @item' do
item = create :journal_item, :with_workout, journal: journal
get :show, id: item.id
expect(assigns(:item)).to eq(item)
end
end
context 'POST create' do
it 'should create valid item' do
params = {
executed_at: Time.now.to_i,
workout_attributes: {
name: 'Test',
items_attributes: [
{
exercise_id: create(:exercise).id,
pos: 1,
sets: [
{ repeats: 1, weight: 1 }
]
}
]
}
}
expect{ post :create, params }.to change{Journal::Item.count}.by(1)
expect(response.status).to eq(201)
end
end
context 'PUT update' do
it 'should update item' do
item = create :journal_item, :with_workout, journal: journal
params = {
id: item.id,
executed_at: Time.now.to_i,
workout_attributes: {
name: 'Test',
items_attributes: [
{
exercise_id: create(:exercise).id,
pos: 1,
sets: [
{ repeats: 1, weight: 1 }
]
}
]
}
}
put :update, params
expect(response.status).to eq(204)
end
end
context 'DELETE destroy' do
it 'should destroy item' do
item = create :journal_item, :with_workout, journal: journal
expect{ delete :destroy, id: item.id }.to change{Journal::Item.count}.by(-1)
expect(response.status).to eq(204)
end
end
end
context 'when logged out' do
let (:item) { create :journal_item, :with_workout, journal: journal}
context 'GET index' do
it 'should get error' do
get :index
expect(JSON.parse(response.body).keys).to eq(['error'])
expect(response.status).to eq(401)
end
end
context 'GET show' do
it 'should get error' do
get :show, id: item.id
expect(JSON.parse(response.body).keys).to eq(['error'])
expect(response.status).to eq(401)
end
end
context 'POST create' do
it 'should get error' do
post :create
expect(JSON.parse(response.body).keys).to eq(['error'])
expect(response.status).to eq(401)
end
end
context 'PUT update' do
it 'should get error' do
put :update, id: item.id
expect(JSON.parse(response.body).keys).to eq(['error'])
expect(response.status).to eq(401)
end
end
context 'DELETE destroy' do
it 'should get error' do
delete :destroy, id: item.id
expect(JSON.parse(response.body).keys).to eq(['error'])
expect(response.status).to eq(401)
end
end
end
end
end<file_sep>/spec/factories/references_exercises.rb
FactoryGirl.define do
factory :exercise, class: 'References::Exercise' do
sequence (:alias) { |n| "exercise#{n}" }
name 'Example Exercise'
description 'Exercise Description'
factory :exercise_with_muscle do
after(:create) do |exercise|
create(:muscle, exercises: [exercise])
end
end
factory :exercise_with_body_part do
after(:create) do |exercise|
create(:body_part, exercises: [exercise])
end
end
end
end<file_sep>/spec/support/capybara.rb
require 'capybara/rspec'<file_sep>/lib/muscles/shape.rb
module Muscles
class Shape < Utils::Enum
self.i18n_scope = 'muscles.shapes'
self.valid_values = %w(long short wide diamond square circle triangle)
end
end<file_sep>/spec/concern/anatomic_spec.rb
require 'spec_helper'
shared_examples_for 'anatomic' do
let(:model) { described_class.to_s.split('::').last.underscore.to_sym } # the class that includes the concern
let(:anatomic) { build(model) }
describe 'validation:' do
it 'should be valid by default' do
expect(anatomic).to be_valid
end
describe 'should be invalid' do
context 'when attribute' do
describe 'alias' do
it 'is empty' do
anatomic.alias = nil
expect(anatomic).to be_invalid
expect(anatomic.errors.messages.keys).to eq([:alias])
end
it 'has wrong format' do
anatomic.alias = 'wrong alias'
expect(anatomic).to be_invalid
expect(anatomic.errors.messages.keys).to eq([:alias])
end
it 'already exists' do
anatomic.alias = create(model, alias: 'example_alias').alias
expect(anatomic).to be_invalid
expect(anatomic.errors.messages.keys).to eq([:alias])
end
end
describe 'name' do
it 'is empty' do
anatomic.name = nil
expect(anatomic).to be_invalid
expect(anatomic.errors.messages.keys).to eq([:name])
end
it 'too long' do
anatomic.name = 'a'*251
expect(anatomic).to be_invalid
expect(anatomic.errors.messages.keys).to eq([:name])
end
end
it 'description too long' do
anatomic.description = 'a'*8001
expect(anatomic).to be_invalid
expect(anatomic.errors.messages.keys).to eq([:description])
end
end
end
end
describe '#before_save' do
it 'should be transform alias to lower' do
str = 'ExAmPle'
anatomic = create(model, alias: str)
expect(anatomic.alias).to be == str.downcase
end
end
end<file_sep>/app/models/references.rb
module References
def self.table_name_prefix
'references_'
end
end
<file_sep>/spec/validators/time_range_validator_spec.rb
require 'rails_helper'
require 'validators/time_range_validator'
class Validatable
include ActiveModel::Validations
attr_accessor :time
end
describe TimeRangeValidator do
describe '[:is]' do
before(:all) do
@validatable = Validatable.new
@validatable.class_eval { validates :time, time_range: { is: Time.parse('2015-01-01 01:12:12') } }
end
it 'should validate valid date' do
@validatable.time = Time.parse('2015-01-01 01:12:12')
expect(@validatable).to be_valid
end
it 'should validate invalid date' do
@validatable.time = Time.parse('2012-12-12 12:12:12')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
end
describe '[:maximum]' do
before(:all) do
@validatable = Validatable.new
@validatable.class_eval { validates :time, time_range: { maximum: Time.parse('2015-01-01 01:01:01') } }
end
it 'should validate valid date' do
@validatable.time = Time.parse('2015-01-01 01:01:01')
expect(@validatable).to be_valid
end
it 'should be invalid with later date' do
@validatable.time = Time.parse('2015-01-01 01:01:02')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
end
describe '[:minimum]' do
before(:all) do
@validatable = Validatable.new
@validatable.class_eval { validates :time, time_range: { minimum: Time.parse('2015-01-01 01:01:02') } }
end
it 'should validate valid date' do
@validatable.time = Time.parse('2015-01-01 01:01:02')
expect(@validatable).to be_valid
end
it 'should be invalid with early date' do
@validatable.time = Time.parse('2015-01-01 01:01:01')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
end
describe '[:minimum && :maximum]' do
before(:all) do
@validatable = Validatable.new
@validatable.class_eval { validates :time,
time_range: {
minimum: Time.parse('2015-01-01 01:01:02'),
maximum: Time.parse('2015-01-01 01:01:04')
}
}
end
it 'should validate valid date' do
@validatable.time = Time.parse('2015-01-01 01:01:03')
expect(@validatable).to be_valid
end
it 'should be invalid with early date' do
@validatable.time = Time.parse('2015-01-01 01:01:01')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
it 'should be invalid with later date' do
@validatable.time = Time.parse('2015-01-01 01:01:05')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
end
describe '[:in]' do
before(:all) do
@validatable = Validatable.new
@validatable.class_eval { validates :time,
time_range: {
in: Time.parse('2015-01-01 01:01:02')..Time.parse('2015-01-01 01:01:04')
}
}
end
it 'should validate valid date' do
@validatable.time = Time.parse('2015-01-01 01:01:03')
expect(@validatable).to be_valid
end
it 'should be invalid with early date' do
@validatable.time = Time.parse('2015-01-01 01:01:01')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
it 'should be invalid with later date' do
@validatable.time = Time.parse('2015-01-01 01:01:05')
expect(@validatable).not_to be_valid
expect(@validatable.errors.keys).to be == [:time]
end
end
end<file_sep>/app/models/concerns/anatomic.rb
module Anatomic
extend ActiveSupport::Concern
included do
# Validations
validates :alias, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[_a-z0-9]*\z/i }
validates :name, presence: true, length: { maximum: 250 }
validates :description, length: { maximum: 8000 }
# Callbacks
before_save { |anatomic| anatomic.alias = anatomic.alias.downcase }
end
end<file_sep>/app/serializers/references/body_part_short_serializer.rb
class References::BodyPartShortSerializer < ActiveModel::Serializer
attributes :id, :name, :alias
end<file_sep>/app/models/workout.rb
class Workout < ActiveRecord::Base
belongs_to :workoutable, polymorphic: true
has_many :items, -> { order(:pos) },
class_name: 'Workout::Item',
autosave: true,
validate: true,
dependent: :destroy
accepts_nested_attributes_for :items
validates :name, presence: true, length: { maximum: 250 }
validates :description, length: { maximum: 8000 }
end
<file_sep>/spec/models/references/equipment_join_spec.rb
require 'rails_helper'
RSpec.describe References::EquipmentJoin, type: :model do
let (:equipment) { create :equipment }
let (:equipmentable) { create :exercise }
describe 'validation:' do
it { expect(References::EquipmentJoin.create equipment: equipment, equipmentable: equipmentable).to be_valid }
describe 'should be invalid' do
it 'with duplicate PrimaryKey' do
References::EquipmentJoin.create equipment: equipment, equipmentable: equipmentable
expect(References::EquipmentJoin.create equipment: equipment, equipmentable: equipmentable).to be_invalid
end
end
end
end
<file_sep>/spec/controllers/references/pictures_controller_spec.rb
require 'rails_helper'
RSpec.describe References::PicturesController, type: :controller do
let (:pictureable) { create(:muscle, pictures: create_list(:picture, 5)) }
context 'JSON' do
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
context 'when logged in as admin' do
login(admin: true)
describe 'GET #index' do
it 'responds pictures as json' do
get :index, muscle_id: pictureable.id
json = JSON.parse(response.body)
expect(json.length).to eq(pictureable.pictures.count)
end
end
describe 'POST #create' do
it 'increase pictures count' do
picture = create(:picture)
params = { muscle_id: pictureable.id, l_id: picture.id }
expect{ post :create, params }.to change { pictureable.pictures.count }.by 1
expect(response).to be_success
end
end
describe 'DELETE #destroy' do
it 'decrease pictures count' do
picture = pictureable.pictures.first
params = { muscle_id: pictureable.id, id: picture.id }
expect{ delete :destroy, params }.to change { pictureable.pictures.count }.by -1
expect(response).to be_success
end
end
end
context 'when logged in as user' do
login(admin: false)
describe 'GET #index' do
it {
expect { get :index, muscle_id: pictureable.id }.to raise_error CanCan::AccessDenied
}
end
describe 'POST #create' do
it {
picture = create(:picture)
params = { muscle_id: pictureable.id, l_id: picture.id}
expect { post :create, params }.to raise_error CanCan::AccessDenied
}
end
describe 'DELETE #destroy' do
it {
picture = pictureable.pictures.first
params = { muscle_id: pictureable.id, id: picture.id }
expect { delete :destroy, params }.to raise_error CanCan::AccessDenied
}
end
end
end
context 'DEFAULT' do
context 'when user not logged in' do
describe 'GET #index' do
it {
get :index, muscle_id: pictureable.id
expect(response).to redirect_to '/users/sign_in'
}
end
end
context 'when logged in as user' do
login(admin: false)
describe 'GET #index' do
it { expect { get :index, muscle_id: pictureable.id }.to raise_error CanCan::AccessDenied }
end
describe 'POST #create' do
it {
params = { muscle_id: pictureable.id, picture: attributes_for(:picture) }
expect { post :create, params }.to raise_error CanCan::AccessDenied
}
end
describe 'DELETE #destroy' do
it {
params = { muscle_id: pictureable.id, id: pictureable.pictures.first.id }
expect { delete :destroy, params }.to raise_error CanCan::AccessDenied
}
end
end
context 'when logged in as admin' do
login(admin: true)
describe 'GET #index' do
it {
get :index, muscle_id: pictureable.id
expect(response).to render_template('index')
}
it 'assigns pictures' do
get :index, muscle_id: pictureable.id
expect(assigns(:pictures)).to eq(pictureable.pictures)
end
end
describe 'POST #create' do
it {
picture = create(:picture)
params = { muscle_id: pictureable.id, l_id: picture.id}
expect { post :create, params }.to raise_error ActionController::UnknownFormat
}
end
describe 'DELETE #destroy' do
it {
params = { muscle_id: pictureable.id, id: pictureable.pictures.first.id }
expect { delete :destroy, params }.to raise_error ActionController::UnknownFormat
}
end
end
end
end
<file_sep>/spec/models/references/equipment_spec.rb
require 'rails_helper'
RSpec.describe References::Equipment, type: :model do
it_behaves_like 'anatomic'
end
<file_sep>/spec/uploaders/picture_uploader_spec.rb
require 'carrierwave/test/matchers'
describe PictureUploader do
include CarrierWave::Test::Matchers
let(:picture) { create(:picture, process_image_upload: true) }
let(:uploader) { PictureUploader.new(picture, :image) }
before do
PictureUploader.enable_processing = true
end
after do
PictureUploader.enable_processing = false
uploader.remove!
end
describe '3000px image' do
before do
File.open(File.join(Rails.root, 'spec', 'support', 'pictures', '3000.png')) { |f| uploader.store!(f) }
end
describe 'the thumb version' do
it "scales down/up image to be exactly 150 by 150 pixels" do
expect(uploader.thumb).to have_dimensions(150, 150)
end
end
describe 'the small version' do
it "scales down image to fit within 300 by 300 pixels" do
expect(uploader.small).to be_no_larger_than(300, 300)
end
end
describe 'the original version' do
it "scales down image to fit within 2000 by 2000 pixels" do
expect(uploader).to be_no_larger_than(2000, 2000)
end
end
end
describe '1px image' do
before do
File.open(File.join(Rails.root, 'spec', 'support', 'pictures', 'test_image.jpg')) { |f| uploader.store!(f) }
end
describe 'the thumb version' do
it "scales down/up image to be exactly 150 by 150 pixels" do
expect(uploader.thumb).to have_dimensions(150, 150)
end
end
describe 'the small version' do
it "is 1 by 1 pixels" do
expect(uploader.small).to have_dimensions(1, 1)
end
end
describe 'the original version' do
it "is 1 by 1 pixels" do
expect(uploader).to have_dimensions(1, 1)
end
end
end
describe 'filename' do
before do
File.open(File.join(Rails.root, 'spec', 'support', 'pictures', 'test_image.jpg')) { |f| uploader.store!(f) }
end
it "has the correct file extension" do
expect(uploader.file.extension.downcase).to eq('jpg')
end
it "has the correct file basename" do
expect(uploader.file.basename.downcase).to match(/[0-9a-z]{8}/i)
end
end
end<file_sep>/spec/support/controller_macros.rb
module ControllerMacros
def login(options = {})
include Devise::Test::ControllerHelpers
before(:each) do
role = options[:admin]||false ? :admin : :user
user = FactoryGirl.create(role, confirmed_at: Time.zone.now)
@request.env['devise.mapping'] = Devise.mappings[:user]
sign_in user
end
end
end<file_sep>/app/models/references/exercise.rb
class References::Exercise < ActiveRecord::Base
include Anatomic
has_and_belongs_to_many :body_parts
has_and_belongs_to_many :muscles
has_many :equipment_joins, :class_name => 'References::EquipmentJoin', as: :equipmentable
has_many :equipments, :class_name => 'References::Equipment', through: :equipment_joins
end
<file_sep>/spec/mailers/previews/user_mailer_preview.rb
class UserMailerPreview < ActionMailer::Preview
def welcome
UserMailer.welcome(User.first.id, '<PASSWORD>')
end
end<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, :type => :model do
let (:user) { build :user }
describe 'validation:' do
describe 'should be valid' do
it 'by default' do
expect(user).to be_valid
end
context 'when attribute' do
it ' first_name and last_name is undefined' do
user.first_name = user.last_name = nil
expect(user).to be_valid
end
it 'age is undefined' do
user.date_of_birth = nil
expect(user).to be_valid
end
it 'gender is undefined' do
user.gender = nil
expect(user).to be_valid
end
end
end
describe 'should be invalid' do
context 'when attribute' do
describe :email do
it 'is empty' do
user.email = ''
expect(user).to be_invalid
end
it 'too long' do
user.email = "#{'a'*100}@<EMAIL>"
expect(user).to be_invalid
end
it 'has wrong format' do
user.email = 'user@<EMAIL>'
expect(user).to be_invalid
user.email = 'userexample.org'
expect(user).to be_invalid
end
it 'already exists' do
user.email = create(:user).email
expect(user).to be_invalid
end
end
describe :password do
it 'too short' do
user = build(:user, :password => '<PASSWORD>', :password_confirmation => '<PASSWORD>')
expect(user).to be_invalid
end
it 'too long' do
user = build(:user, :password => '<PASSWORD>'*10, :password_confirmation => '<PASSWORD>'*10)
expect(user).to be_invalid
end
it 'not matched with password_confirmation' do
user = build(:user, :password_confirmation => '')
expect(user).to be_invalid
end
end
describe :first_name do
it 'has wrong format' do
user.first_name = 'Wrong@Name'
expect(user).to be_invalid
end
it 'too long' do
user.first_name = 'N'*51
expect(user).to be_invalid
end
end
describe :last_name do
it 'has wrong format' do
user.last_name = 'Wrong@Name'
expect(user).to be_invalid
end
it 'too long' do
user.last_name = 'N'*51
expect(user).to be_invalid
end
end
it 'gender has invalid value' do
user = build(:user, :gender => 'i')
expect(user).to be_invalid
end
it 'age least 18' do
user = build(:user, :date_of_birth => 5.years.ago)
expect(user).to be_invalid
end
end
end
end
describe '#journal' do
before :all do
@user = create(:user)
end
it 'should create Journal model when it doesn\'t exists' do
expect{@user.journal}.to change{Journal.count}.by(1)
end
it 'should not create Journal model when it exists' do
expect{@user.journal}.to change{Journal.count}.by(0)
end
end
describe '::find_for_oauth' do
it 'find existing user by identity' do
user1 = create(:user)
identity1 = create(:identity, user: user1)
omniauth_hash = { 'provider' => identity1.provider,
'uid' => identity1.uid,
'info' => {
'name' => 'example',
'email' => identity1.email,
'nickname' => 'example'
},
'credentials' => {
'token' => Digest::SHA1.hexdigest([Time.now, rand].join),
'refresh_token' => Digest::SHA1.hexdigest([Time.now, rand].join)
}
}
user2 = User.find_for_oauth (Utils::OAuth.normalize omniauth_hash)
expect(user1.id).to be == user2.id
end
it 'find existing user by email' do
user1 = create(:user)
omniauth_hash = { 'provider' => 'provider_example',
'uid' => '12345',
'info' => {
'name' => 'example',
'email' => user1.email,
'nickname' => 'example'
},
'credentials' => {
'token' => Digest::SHA1.hexdigest([Time.now, rand].join),
'refresh_token' => Digest::SHA1.hexdigest([Time.now, rand].join)
}
}
user2 = User.find_for_oauth (Utils::OAuth.normalize omniauth_hash)
expect(user1.id).to be == user2.id
end
it 'link identity to signed in user' do
user1 = create(:user)
omniauth_hash = { 'provider' => 'provider_example',
'uid' => '12345',
'info' => {
'name' => 'example',
'email' => '<EMAIL>',
'nickname' => 'example'
},
'credentials' => {
'token' => Digest::SHA1.hexdigest([Time.now, rand].join),
'refresh_token' => Digest::SHA1.hexdigest([Time.now, rand].join)
}
}
expect{
User.find_for_oauth(Utils::OAuth.normalize(omniauth_hash), user1)
}.to change { Identity.count }.by(1)
expect(user1.identities.first.provider).to be == 'provider_example'
expect(user1.identities.first.uid).to be == '12345'
end
end
end
<file_sep>/app/serializers/references/exercise_serializer.rb
class References::ExerciseSerializer < ActiveModel::Serializer
attributes :id, :name, :alias, :description
has_many :equipments
has_many :muscles, serializer: References::MuscleShortSerializer
has_many :body_parts, serializer: References::BodyPartShortSerializer
end<file_sep>/README.rdoc
== README
Project based on Ruby on Rails.
Core:
- Ruby 2.1.10
- Rails 4.2
Softwares:
- Postgres SQL
- Redis (for Sidekiq)
- ImageMagick (for CarrierWave)
{<img src="https://codeclimate.com/github/davydes/gym/badges/gpa.svg" />}[https://codeclimate.com/github/davydes/gym]
{<img src="https://codeclimate.com/github/davydes/gym/badges/coverage.svg" />}[https://codeclimate.com/github/davydes/gym/coverage]
{<img src="https://travis-ci.org/davydes/gym.svg" alt="Build Status" />}[https://travis-ci.org/davydes/gym]
{<img src="https://gemnasium.com/davydes/gym.svg" alt="Dependency Status" />}[https://gemnasium.com/davydes/gym]<file_sep>/db/migrate/20150619123521_add_columns_to_users.rb
class AddColumnsToUsers < ActiveRecord::Migration
def change
add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :gender, :string, limit: 1
add_column :users, :country, :string
add_column :users, :city, :string
add_column :users, :date_of_birth, :datetime
add_index :users, :name, unique: true
end
end
<file_sep>/spec/controllers/references/equipments_controller_spec.rb
require 'rails_helper'
RSpec.describe References::EquipmentsController, type: :controller do
let (:equipments) { create_list(:equipment, 5) }
context 'JSON' do
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
describe 'GET #index' do
describe 'responds equipments as json with' do
it 'right count' do
count = equipments.count
get :index
json = JSON.parse(response.body)
expect(json.length).to eq(count)
end
it 'right format' do
create(:equipment)
get :index
json = JSON.parse(response.body)
expect(json.first.keys).to eq(%w(id name alias))
end
end
end
end
end
<file_sep>/db/migrate/20150703121304_create_muscles.rb
class CreateMuscles < ActiveRecord::Migration
def change
create_table :muscles do |t|
t.string :alias, null: false
t.string :name, null: false
t.text :description
t.string :shape
t.timestamps null: false
end
add_index :muscles, :alias, unique: true
end
end
<file_sep>/spec/factories/workouts.rb
FactoryGirl.define do
factory :workout do
name 'Example Workout'
description 'Workout Description'
trait :with_items do
after :create do |workout|
create_list :workout_item, 3,
:workout => workout,
:exercise => create(:exercise)
end
end
end
end
<file_sep>/app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def vkontakte
generic_callback 'vkontakte'
end
def google_oauth2
generic_callback 'google_oauth2'
end
def generic_callback( provider )
@user = User.find_for_oauth(Utils::OAuth.normalize(env['omniauth.auth']), current_user)
if @user.persisted?
sign_in_and_redirect @user, event: :authentication
set_flash_message(:notice, :success, kind: provider.capitalize) if is_navigational_format?
else
session['devise.auth_data'] = env['omniauth.auth']
redirect_to new_user_registration_url
end
end
end<file_sep>/app/controllers/references/muscles_controller.rb
class References::MusclesController < AnatomicController
def index
@body_parts = References::BodyPart.with_muscles.order(:name)
@muscles = References::Muscle.no_bodypart
respond_with References::Muscle.all
end
private
def resource_params
accessible = [ :name, :alias, :description, :shape, :body_part_ids => [], :exercise_ids => [], :pictures_attributes => [] ]
params.require(:muscle).permit(accessible)
end
end
<file_sep>/spec/mailers/statistics_mailer_spec.rb
require "rails_helper"
RSpec.describe StatisticsMailer, type: :mailer do
describe 'StatisticsMailer.common' do
before :context do
create_list(:admin, 3)
end
let(:mail) { described_class.common.deliver_now }
it 'renders the subject' do
expect(mail.subject).to eq('Common Stats')
end
it 'renders the receiver email' do
expect(mail.to).to eq(User.all.where(admin: true).pluck(:email))
end
end
end
<file_sep>/app/serializers/references/muscle_serializer.rb
class References::MuscleSerializer < ActiveModel::Serializer
attributes :id, :name, :alias, :description, :shape
has_many :exercises, serializer: References::ExerciseShortSerializer
has_many :body_parts, serializer: References::BodyPartShortSerializer
has_many :pictures
end<file_sep>/spec/models/identity_spec.rb
require 'rails_helper'
RSpec.describe Identity, :type => :model do
let (:identity) {build :identity}
describe 'validation' do
it { expect(identity).to be_valid }
describe 'should be invalid' do
it 'when attribute pair [provider, uid] already exists' do
identity_ = create(:identity)
identity.provider, identity.uid = identity_.provider, identity_.uid
expect(identity).to be_invalid
end
end
end
describe '::find_for_oauth' do
it 'when find exists identity by provider&uid' do
identity1 = create(:identity, email: '<EMAIL>')
omniauth_hash = { 'provider' => identity1.provider,
'uid' => identity1.uid,
'info' => {
'name' => 'example',
'email' => identity1.email,
'nickname' => 'example'
},
'credentials' => {
'token' => Digest::SHA1.hexdigest([Time.now, rand].join),
'refresh_token' => Digest::SHA1.hexdigest([Time.now, rand].join)
}
}
identity2 = Identity.find_for_oauth Utils::OAuth.normalize(omniauth_hash)
expect(identity1.id).to be == identity2.id
end
it 'when create new identity' do
identity1 = create(:identity, email: '<EMAIL>')
omniauth_hash = { 'provider' => identity1.provider,
'uid' => identity1.uid+rand(5..10).to_s,
'info' => {
'name' => 'example',
'email' => identity1.email,
'nickname' => 'example'
},
'credentials' => {
'token' => Digest::SHA1.hexdigest([Time.now, rand].join),
'refresh_token' => Digest::SHA1.hexdigest([Time.now, rand].join)
}
}
identity2 = Identity.find_for_oauth Utils::OAuth.normalize(omniauth_hash)
expect(identity1.id).not_to be == identity2.id
end
end
end
<file_sep>/spec/mailers/previews/statistics_mailer_preview.rb
class StatisticsMailerPreview < ActionMailer::Preview
# Preview all emails at http://localhost:3000/rails/mailers/statistics_mailer/common
def common
StatisticsMailer.common
end
end
<file_sep>/db/migrate/20160427064427_remove_name_from_users.rb
class RemoveNameFromUsers < ActiveRecord::Migration
def change
remove_index :users, column: :name, unique: true
remove_column :users, :name, :string
end
end
<file_sep>/spec/factories/identities.rb
FactoryGirl.define do
factory :identity do
sequence(:provider) { |n| "provider#{n}" }
sequence(:uid) { |n| n }
association :user, factory: :user
end
end<file_sep>/spec/models/journal_spec.rb
require 'rails_helper'
RSpec.describe Journal, type: :model do
let (:journal) { build :journal, :with_user }
describe 'validations' do
it { expect(journal).to be_valid }
describe 'should be invalid when attribute' do
describe 'user' do
it ' is nil' do
journal.user = nil
expect(journal).not_to be_valid
expect(journal.errors.keys).to be == [:user]
end
end
end
end
end<file_sep>/app/models/picture.rb
require 'validators/file_size_validator'
require 'validators/file_mime_type_validator'
class Picture < ActiveRecord::Base
scope :lonely, -> { where.not(:id => PictureLink.select(:picture_id).uniq) }
scope :for_obj, -> (type, id) {
where.not(:id => PictureLink.select(:picture_id)
.where(:pictureable_type => type, :pictureable_id => id).uniq)
}
has_many :picture_links, dependent: :destroy
mount_uploader :image, PictureUploader
process_in_background :image
validates :name, presence: true
validates :image,
presence: true,
file_size: { maximum: 1.megabytes.to_i },
file_mime_type: { content_type: /image/ }
def pictureables
picture_links.map {|x| x.pictureable}
end
end<file_sep>/app/models/workout/item.rb
class Workout::Item < ActiveRecord::Base
belongs_to :workout
belongs_to :exercise, class_name: 'References::Exercise'
serialize :sets, Array
validates :exercise, :sets, :pos, presence: true
validates :pos, numericality: { only_integer: true, greater_than: 0 },
uniqueness: { scope: :workout }
end<file_sep>/app/controllers/anatomic_controller.rb
class AnatomicController < ApplicationController
respond_to :html
respond_to :json, only: [:index]
before_action :authenticate_user!, except:[:show, :index]
load_resource except: [:create]
authorize_resource
def index
objects = model_class.constantize.all
instance_variable_set("@#{controller_name}", objects)
respond_with instance_variable_get("@#{controller_name}")
end
def show
respond_with instance_variable_get("@#{resource_name.underscore}")
end
def new
instance_variable_set "@#{resource_name.underscore}", model_class.constantize.new
end
def create
instance_variable_set "@#{resource_name.underscore}", model_class.constantize.create(resource_params)
respond_with instance_variable_get("@#{resource_name.underscore}")
end
def edit
end
def update
instance_variable_get("@#{resource_name.underscore}").update(resource_params)
respond_with instance_variable_get("@#{resource_name.underscore}")
end
def destroy
instance_variable_get("@#{resource_name.underscore}").destroy!
respond_with instance_variable_get("@#{resource_name.underscore}")
end
private
def model_class
params[:controller].classify
end
def resource_name
controller_name.classify
end
def resource_params
accessible = [ :name, :alias, :description ]
params.require(resource_name.underscore.to_sym).permit(accessible)
end
end
|
25853f7e0afc27871488d921d3707ff3cfee4494
|
[
"RDoc",
"Ruby"
] | 111 |
Ruby
|
davydes/gym
|
cc085b2f7e6cdb3b33d4ac4f49b71c9c34ef2756
|
b42c6c530a41a1d6c3dc185e46017e6ead9fbb2c
|
refs/heads/master
|
<repo_name>nasr98/myapp<file_sep>/index.py
print("another change made because of Essam")
print("extra blank line")
print("just like this")
=======
Shahad
Nasr
|
3bcf4fcc05e20345170f8f7f51117ccf42b4d064
|
[
"Python"
] | 1 |
Python
|
nasr98/myapp
|
4bdc240b972d9ce55ed488df74b6a1528e0f99a3
|
aebf796d6aab50a9cad9a5d38e006e00af237b56
|
refs/heads/master
|
<repo_name>Marcos-H/mpi4py<file_sep>/monte_carlo_pi.py
import math
import random
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
pi = 0
if rank == 0:
for i in range(1, size):
pi += comm.recv(source=i, tag=i)
pi = pi / (size-1)
print(pi)
else:
count = 0
count_inside = 0
for count in range(0, 100000):
d = math.hypot(random.random(), random.random())
if d < 1:
count_inside += 1
count += 1
pi = (4.0 * count_inside / count)
comm.send(pi, dest=0, tag=rank)
comm.Barrier()
|
5e729996a4cb93155135592a443c3076b9706fcc
|
[
"Python"
] | 1 |
Python
|
Marcos-H/mpi4py
|
2233c6854ef34cb1f6a868f088b92dc15c71ea3b
|
ad7926edc6b6a501b85e14d0dbe70e0d16da7104
|
refs/heads/master
|
<repo_name>zhouhua/bce-sdk-js<file_sep>/docs/Advanced-Topics-Server-Signature.md
---
id: advanced-topics-server-signature
title: 服务端签名
layout: docs
category: Advanced Topics
next: advanced-topics-sts
permalink: docs/advanced-topics-server-signature.html
---
主要的实现原理是把需要签名的数据发送给服务端,主要是 `httpMethod`, `path`, `queries`, `headers`。
收到服务器返回生成的签名之后,我们把签名和要上传的文件发送给 BOS 的服务器。
这种方案的优点是:因为签名的过程在服务端动态完成的,因此不需要把 AK 和 SK 放到页面上,而且可以添加
自己额外的验证逻辑,比如用户是否登录了,不允许 DELETE 这个 `httpMethod` 之类的。缺点是每次签名
都需要跟服务器交互一次。
### 实现代码
服务端返回内容的格式如下:
```js
{
statusCode: number,
signature: string,
xbceDate: string
}
```
正常情况下,`statusCode`应该是`200`
#### nodejs 后端示例
```js
var http = require('http');
var url = require('url');
var util = require('util');
var Auth = require('bce-sdk-js').Auth;
var kCredentials = {
ak: '<你的AK>'
sk: '<你的SK>'
};
function safeParse(text) {
try {
return JSON.parse(text);
}
catch (ex) {
return null;
}
}
http.createServer(function (req, res) {
console.log(req.url);
// query: { httpMethod: '$0', path: '$1', params: '$2', headers: '$3' },
var query = url.parse(req.url, true).query;
var statusCode = 200;
var policy = null;
var signature = null;
if (query.policy) {
var auth = new Auth(kCredentials.ak, kCredentials.sk);
policy = new Buffer(query.policy).toString('base64');
signature = auth.hash(policy, kCredentials.sk);
}
else if (query.httpMethod && query.path && query.params && query.headers) {
if (query.httpMethod !== 'PUT' && query.httpMethod !== 'POST' && query.httpMethod !== 'GET') {
// 只允许 PUT/POST/GET Method
statusCode = 403;
}
else {
var httpMethod = query.httpMethod;
var path = query.path;
var params = safeParse(query.params) || {};
var headers = safeParse(query.headers) || {};
var auth = new Auth(kCredentials.ak, kCredentials.sk);
signature = auth.generateAuthorization(httpMethod, path, params, headers);
}
}
else {
statusCode = 403;
}
// 最多10s的延迟
var delay = Math.min(query.delay || 0, 10);
setTimeout(function () {
var payload = query.policy
? {
accessKey: kCredentials.ak,
policy: policy,
signature: signature
}
: {
statusCode: statusCode,
signature: signature,
xbceDate: new Date().toISOString().replace(/\.\d+Z$/, 'Z')
};
res.writeHead(statusCode, {
'Content-Type': 'text/javascript; charset=utf-8',
'Access-Control-Allow-Origin': '*'
});
if (query.callback) {
res.end(util.format('%s(%s)', query.callback, JSON.stringify(payload)));
}
else {
res.end(JSON.stringify(payload));
}
}, delay * 1000);
}).listen(1337);
console.log('Server running at http://0.0.0.0:1337/');
```
#### C# 后端实现
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BaiduBce;
using BaiduBce.Auth;
using BaiduBce.Internal;
using Newtonsoft.Json;
using BaiduBce.Util;
using System.Text;
using System.Security.Cryptography;
namespace BaiduCloudEngine.Controllers
{
class SignatureResult
{
public int statusCode { get; set; }
public string signature { get; set; }
public string xbceDate { get; set; }
}
class PolicySignatureResult
{
public string policy { get; set; }
public string signature { get; set; }
public string accessKey { get; set; }
}
public class HomeController : Controller
{
private static string EncodeHex (byte[] data)
{
var sb = new StringBuilder ();
foreach (var b in data) {
sb.Append (BceV1Signer.HexTable [b]);
}
return sb.ToString ();
}
// http://127.0.0.1:8080/?httpMethod=PUT&path=%2Fv1%2Fbce-javascript-sdk-demo-test%2Fbce.png&delay=0&queries=%7B%7D&headers=%7B%22User-Agent%22%3A%22Mozilla%2F5.0+(Macintosh%3B+Intel+Mac+OS+X+10_11_2)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F48.0.2564.97+Safari%2F537.36%22%2C%22x-bce-date%22%3A%222016-02-22T08%3A03%3A13Z%22%2C%22Connection%22%3A%22close%22%2C%22Content-Type%22%3A%22image%2Fpng%3B+charset%3DUTF-8%22%2C%22Host%22%3A%22bos.bj.baidubce.com%22%2C%22Content-Length%22%3A4800%7D
public string Index (string httpMethod, string path, string queries, string headers, string policy, string callback)
{
BceClientConfiguration config = new BceClientConfiguration ();
string ak = "b92ea4a39f3645c8ae5f64ba5fc2a357";
string sk = "a4ce012968714958a21bb90dc180de17";
config.Credentials = new DefaultBceCredentials (ak, sk);
BceV1Signer bceV1Signer = new BceV1Signer ();
string result = null;
if (policy != null) {
string base64 = Convert.ToBase64String (Encoding.UTF8.GetBytes (policy));
var hash = new HMACSHA256 (Encoding.UTF8.GetBytes (sk));
string signature = EncodeHex (hash.ComputeHash (Encoding.UTF8.GetBytes (base64)));
result = JsonConvert.SerializeObject (new PolicySignatureResult () {
policy = base64,
signature = signature,
accessKey = ak,
});
} else {
InternalRequest internalRequest = new InternalRequest ();
internalRequest.Config = config;
internalRequest.Uri = new Uri ("http://www.baidu.com" + path);
internalRequest.HttpMethod = httpMethod;
if (headers != null) {
internalRequest.Headers = JsonConvert.DeserializeObject<Dictionary<string, string>> (headers);
}
if (queries != null) {
internalRequest.Parameters = JsonConvert.DeserializeObject<Dictionary<string, string>> (queries);
}
var sign = bceV1Signer.Sign (internalRequest);
var xbceDate = DateUtils.FormatAlternateIso8601Date (DateTime.Now);
result = JsonConvert.SerializeObject (new SignatureResult () {
statusCode = 200,
signature = sign,
xbceDate = xbceDate,
});
}
if (callback != null) {
result = callback + "(" + result + ")";
}
return result;
}
}
}
```
#### 浏览器前端实现
把签名的过程由后端完成,浏览器端需要更改签名过程。以下代码重写了sdk中签名的方式:
```js
var tokenUrl = '后端签名api';
var bosConfig = {
endpoint: 'http://bos.bj.baidubce.com'
};
var client = new baidubce.sdk.BosClient(bosConfig));
var bucket = 'bce-javascript-sdk-demo-test';
// 重写签名方法,改为从服务器获取签名
// 您的代码可以不与此相同,您可加入特定的控制逻辑,如是否允许删除?操作者是否已登录?
client.createSignature = function (_, httpMethod, path, params, headers) {
var deferred = baidubce.sdk.Q.defer();
$.ajax({
url: tokenUrl,
dataType: 'json',
data: {
httpMethod: httpMethod,
path: path,
params: JSON.stringify(params || {}),
headers: JSON.stringify(headers || {})
},
success: function (payload) {
if (payload.statusCode === 200 && payload.signature) {
deferred.resolve(payload.signature, payload.xbceDate);
}
else {
deferred.reject(new Error('createSignature failed, statusCode = ' + payload.statusCode));
}
}
});
return deferred.promise;
};
$('#upload').on('change', function (evt) {
var file = evt.target.files[0];
var key = file.name;
var blob = file;
var id = +new Date();
var ext = key.split(/\./g).pop();
var mimeType = sdk.MimeType.guess(ext);
if (/^text\//.test(mimeType)) {
mimeType += '; charset=UTF-8';
}
var options = {
'Content-Type': mimeType
};
// 以下逻辑与基本示例中的相同
var promise = client.putObjectFromBlob(bucket, key, blob, options);
client.on('progress', function (evt) {
// 上传中
});
promise.then(function (res) {
// 上传成功
})
.catch(function (err) {
// 上传失败
});
});
```
<file_sep>/website/src/bce-sdk-js/docs/advanced-topics-server-signature.js
/**
* @generated
*/
var React = require("React");
var Layout = require("DocsLayout");
var content = `
主要的实现原理是把需要签名的数据发送给服务端,主要是 \`httpMethod\`, \`path\`, \`queries\`, \`headers\`。
收到服务器返回生成的签名之后,我们把签名和要上传的文件发送给 BOS 的服务器。
这种方案的优点是:因为签名的过程在服务端动态完成的,因此不需要把 AK 和 SK 放到页面上,而且可以添加
自己额外的验证逻辑,比如用户是否登录了,不允许 DELETE 这个 \`httpMethod\` 之类的。缺点是每次签名
都需要跟服务器交互一次。
### 实现代码
服务端返回内容的格式如下:
\`\`\`js
{
statusCode: number,
signature: string,
xbceDate: string
}
\`\`\`
正常情况下,\`statusCode\`应该是\`200\`
#### nodejs 后端示例
\`\`\`js
var http = require\('http');
var url = require\('url');
var util = require\('util');
var Auth = require\('bce-sdk-js').Auth;
var kCredentials = {
ak: '<你的AK>'
sk: '<你的SK>'
};
function safeParse(text) {
try {
return JSON.parse(text);
}
catch (ex) {
return null;
}
}
http.createServer(function (req, res) {
console.log(req.url);
// query: { httpMethod: '$0', path: '$1', params: '$2', headers: '$3' },
var query = url.parse(req.url, true).query;
var statusCode = 200;
var policy = null;
var signature = null;
if (query.policy) {
var auth = new Auth(kCredentials.ak, kCredentials.sk);
policy = new Buffer(query.policy).toString('base64');
signature = auth.hash(policy, kCredentials.sk);
}
else if (query.httpMethod && query.path && query.params && query.headers) {
if (query.httpMethod !== 'PUT' && query.httpMethod !== 'POST' && query.httpMethod !== 'GET') {
// 只允许 PUT/POST/GET Method
statusCode = 403;
}
else {
var httpMethod = query.httpMethod;
var path = query.path;
var params = safeParse(query.params) || {};
var headers = safeParse(query.headers) || {};
var auth = new Auth(kCredentials.ak, kCredentials.sk);
signature = auth.generateAuthorization(httpMethod, path, params, headers);
}
}
else {
statusCode = 403;
}
// 最多10s的延迟
var delay = Math.min(query.delay || 0, 10);
setTimeout(function () {
var payload = query.policy
? {
accessKey: kCredentials.ak,
policy: policy,
signature: signature
}
: {
statusCode: statusCode,
signature: signature,
xbceDate: new Date().toISOString().replace(/\\.\\d+Z$/, 'Z')
};
res.writeHead(statusCode, {
'Content-Type': 'text/javascript; charset=utf-8',
'Access-Control-Allow-Origin': '*'
});
if (query.callback) {
res.end(util.format('%s(%s)', query.callback, JSON.stringify(payload)));
}
else {
res.end(JSON.stringify(payload));
}
}, delay * 1000);
}).listen(1337);
console.log('Server running at http://0.0.0.0:1337/');
\`\`\`
#### C# 后端实现
\`\`\`csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BaiduBce;
using BaiduBce.Auth;
using BaiduBce.Internal;
using Newtonsoft.Json;
using BaiduBce.Util;
using System.Text;
using System.Security.Cryptography;
namespace BaiduCloudEngine.Controllers
{
class SignatureResult
{
public int statusCode { get; set; }
public string signature { get; set; }
public string xbceDate { get; set; }
}
class PolicySignatureResult
{
public string policy { get; set; }
public string signature { get; set; }
public string accessKey { get; set; }
}
public class HomeController : Controller
{
private static string EncodeHex (byte[] data)
{
var sb = new StringBuilder ();
foreach (var b in data) {
sb.Append (BceV1Signer.HexTable [b]);
}
return sb.ToString ();
}
// http://127.0.0.1:8080/?httpMethod=PUT&path=%2Fv1%2Fbce-javascript-sdk-demo-test%2Fbce.png&delay=0&queries=%7B%7D&headers=%7B%22User-Agent%22%3A%22Mozilla%2F5.0+(Macintosh%3B+Intel+Mac+OS+X+10_11_2)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F48.0.2564.97+Safari%2F537.36%22%2C%22x-bce-date%22%3A%222016-02-22T08%3A03%3A13Z%22%2C%22Connection%22%3A%22close%22%2C%22Content-Type%22%3A%22image%2Fpng%3B+charset%3DUTF-8%22%2C%22Host%22%3A%22bos.bj.baidubce.com%22%2C%22Content-Length%22%3A4800%7D
public string Index (string httpMethod, string path, string queries, string headers, string policy, string callback)
{
BceClientConfiguration config = new BceClientConfiguration ();
string ak = "b92ea4a39f3645c8ae5f64ba5fc2a357";
string sk = "a4ce012968714958a21bb90dc180de17";
config.Credentials = new DefaultBceCredentials (ak, sk);
BceV1Signer bceV1Signer = new BceV1Signer ();
string result = null;
if (policy != null) {
string base64 = Convert.ToBase64String (Encoding.UTF8.GetBytes (policy));
var hash = new HMACSHA256 (Encoding.UTF8.GetBytes (sk));
string signature = EncodeHex (hash.ComputeHash (Encoding.UTF8.GetBytes (base64)));
result = JsonConvert.SerializeObject (new PolicySignatureResult () {
policy = base64,
signature = signature,
accessKey = ak,
});
} else {
InternalRequest internalRequest = new InternalRequest ();
internalRequest.Config = config;
internalRequest.Uri = new Uri ("http://www.baidu.com" + path);
internalRequest.HttpMethod = httpMethod;
if (headers != null) {
internalRequest.Headers = JsonConvert.DeserializeObject<Dictionary<string, string>> (headers);
}
if (queries != null) {
internalRequest.Parameters = JsonConvert.DeserializeObject<Dictionary<string, string>> (queries);
}
var sign = bceV1Signer.Sign (internalRequest);
var xbceDate = DateUtils.FormatAlternateIso8601Date (DateTime.Now);
result = JsonConvert.SerializeObject (new SignatureResult () {
statusCode = 200,
signature = sign,
xbceDate = xbceDate,
});
}
if (callback != null) {
result = callback + "(" + result + ")";
}
return result;
}
}
}
\`\`\`
#### 浏览器前端实现
把签名的过程由后端完成,浏览器端需要更改签名过程。以下代码重写了sdk中签名的方式:
\`\`\`js
var tokenUrl = '后端签名api';
var bosConfig = {
endpoint: 'http://bos.bj.baidubce.com'
};
var client = new baidubce.sdk.BosClient(bosConfig));
var bucket = 'bce-javascript-sdk-demo-test';
// 重写签名方法,改为从服务器获取签名
// 您的代码可以不与此相同,您可加入特定的控制逻辑,如是否允许删除?操作者是否已登录?
client.createSignature = function (_, httpMethod, path, params, headers) {
var deferred = baidubce.sdk.Q.defer();
$.ajax({
url: tokenUrl,
dataType: 'json',
data: {
httpMethod: httpMethod,
path: path,
params: JSON.stringify(params || {}),
headers: JSON.stringify(headers || {})
},
success: function (payload) {
if (payload.statusCode === 200 && payload.signature) {
deferred.resolve(payload.signature, payload.xbceDate);
}
else {
deferred.reject(new Error('createSignature failed, statusCode = ' + payload.statusCode));
}
}
});
return deferred.promise;
};
$('#upload').on('change', function (evt) {
var file = evt.target.files[0];
var key = file.name;
var blob = file;
var id = +new Date();
var ext = key.split(/\\./g).pop();
var mimeType = sdk.MimeType.guess(ext);
if (/^text\\//.test(mimeType)) {
mimeType += '; charset=UTF-8';
}
var options = {
'Content-Type': mimeType
};
// 以下逻辑与基本示例中的相同
var promise = client.putObjectFromBlob(bucket, key, blob, options);
client.on('progress', function (evt) {
// 上传中
});
promise.then(function (res) {
// 上传成功
})
.catch(function (err) {
// 上传失败
});
});
\`\`\`
`
var Post = React.createClass({
statics: {
content: content
},
render: function() {
return <Layout metadata={{"id":"advanced-topics-server-signature","title":"服务端签名","layout":"docs","category":"Advanced Topics","next":"advanced-topics-sts","permalink":"docs/advanced-topics-server-signature.html"}}>{content}</Layout>;
}
});
module.exports = Post;
|
f257f0248bb9bb533b43351d8b0a96a657a2960b
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
zhouhua/bce-sdk-js
|
e94574b6a928a5d2861182e460706af2b1317ecf
|
3c15933b46d5e0f50c75c1a4197eabaca6a6c77c
|
refs/heads/master
|
<repo_name>terrorizer1980/tensorpipe<file_sep>/tensorpipe/transport/uv/loop.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/uv/loop.h>
#include <tensorpipe/common/system.h>
#include <tensorpipe/transport/uv/macros.h>
#include <tensorpipe/transport/uv/uv.h>
namespace tensorpipe {
namespace transport {
namespace uv {
Loop::Loop()
: loop_(std::make_unique<uv_loop_t>()),
async_(std::make_unique<uv_async_t>()) {
int rv;
rv = uv_loop_init(loop_.get());
TP_THROW_UV_IF(rv < 0, rv);
rv = uv_async_init(loop_.get(), async_.get(), uv__async_cb);
TP_THROW_UV_IF(rv < 0, rv);
async_->data = this;
thread_ = std::thread(&Loop::loop, this);
}
void Loop::close() {
if (!closed_.exchange(true)) {
// It's fine to capture this because the loop won't be destroyed until join
// has completed, and join won't complete until this operation is performed.
deferToLoop(
[this]() { uv_unref(reinterpret_cast<uv_handle_t*>(async_.get())); });
}
}
void Loop::join() {
close();
if (!joined_.exchange(true)) {
// Wait for event loop thread to terminate.
thread_.join();
// There should not be any pending deferred work at this time.
TP_DCHECK(fns_.empty());
}
}
Loop::~Loop() noexcept {
join();
// Release resources associated with loop.
auto rv = uv_loop_close(loop_.get());
TP_THROW_UV_IF(rv < 0, rv);
}
void Loop::deferToLoop(std::function<void()> fn) {
{
std::unique_lock<std::mutex> lock(mutex_);
if (likely(isThreadConsumingDeferredFunctions_)) {
fns_.push_back(std::move(fn));
wakeup();
return;
}
}
// Must call it without holding the lock, as it could cause a reentrant call.
onDemandLoop_.deferToLoop(std::move(fn));
}
void Loop::wakeup() {
auto rv = uv_async_send(async_.get());
TP_THROW_UV_IF(rv < 0, rv);
}
void Loop::loop() {
setThreadName("TP_UV_loop");
int rv;
rv = uv_run(loop_.get(), UV_RUN_DEFAULT);
TP_THROW_ASSERT_IF(rv > 0)
<< ": uv_run returned with active handles or requests";
uv_ref(reinterpret_cast<uv_handle_t*>(async_.get()));
uv_close(reinterpret_cast<uv_handle_t*>(async_.get()), nullptr);
rv = uv_run(loop_.get(), UV_RUN_NOWAIT);
TP_THROW_ASSERT_IF(rv > 0)
<< ": uv_run returned with active handles or requests";
// The loop is winding down and "handing over" control to the on demand loop.
// But it can only do so safely once there are no pending deferred functions,
// as otherwise those may risk never being executed.
while (true) {
decltype(fns_) fns;
{
std::unique_lock<std::mutex> lock(mutex_);
if (fns_.empty()) {
isThreadConsumingDeferredFunctions_ = false;
break;
}
std::swap(fns, fns_);
}
for (auto& fn : fns) {
fn();
}
}
}
void Loop::uv__async_cb(uv_async_t* handle) {
auto& loop = *reinterpret_cast<Loop*>(handle->data);
loop.runFunctionsFromLoop();
}
void Loop::runFunctionsFromLoop() {
decltype(fns_) fns;
{
std::unique_lock<std::mutex> lock(mutex_);
std::swap(fns, fns_);
}
for (auto& fn : fns) {
fn();
}
}
} // namespace uv
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/test/util/ringbuffer/shm_ringbuffer_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/shm/socket.h>
#include <tensorpipe/util/ringbuffer/consumer.h>
#include <tensorpipe/util/ringbuffer/producer.h>
#include <tensorpipe/util/ringbuffer/ringbuffer.h>
#include <tensorpipe/util/ringbuffer/shm.h>
#include <tensorpipe/util/shm/segment.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <thread>
#include <gtest/gtest.h>
using namespace tensorpipe::util::ringbuffer;
using namespace tensorpipe::transport::shm;
// Same process produces and consumes share memory through different mappings.
TEST(ShmRingBuffer, SameProducerConsumer) {
// This must stay alive for the file descriptors to remain open.
std::shared_ptr<RingBuffer> producer_rb;
int header_fd = -1;
int data_fd = -1;
{
// Producer part.
// Buffer large enough to fit all data and persistent
// (needs to be unlinked up manually).
std::tie(header_fd, data_fd, producer_rb) = shm::create(256 * 1024);
Producer prod{producer_rb};
// Producer loop. It all fits in buffer.
int i = 0;
while (i < 2000) {
ssize_t ret = prod.write(&i, sizeof(i));
EXPECT_EQ(ret, sizeof(i));
++i;
}
}
{
// Consumer part.
// Map file again (to a different address) and consume it.
auto rb = shm::load(header_fd, data_fd);
Consumer cons{rb};
int i = 0;
while (i < 2000) {
int value;
ssize_t ret = cons.copy(sizeof(value), &value);
EXPECT_EQ(ret, sizeof(value));
EXPECT_EQ(value, i);
++i;
}
}
};
TEST(ShmRingBuffer, SingleProducer_SingleConsumer) {
int sock_fds[2];
{
int rv = socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds);
if (rv != 0) {
TP_THROW_SYSTEM(errno) << "Failed to create socket pair";
}
}
int event_fd = eventfd(0, 0);
if (event_fd < 0) {
TP_THROW_SYSTEM(errno) << "Failed to create event fd";
}
int pid = fork();
if (pid < 0) {
TP_THROW_SYSTEM(errno) << "Failed to fork";
}
if (pid == 0) {
// child, the producer
// Make a scope so shared_ptr's are released even on exit(0).
{
int header_fd;
int data_fd;
std::shared_ptr<RingBuffer> rb;
std::tie(header_fd, data_fd, rb) = shm::create(1024);
Producer prod{rb};
{
auto err = sendFdsToSocket(sock_fds[0], header_fd, data_fd);
if (err) {
TP_THROW_ASSERT() << err.what();
}
}
int i = 0;
while (i < 2000) {
ssize_t ret = prod.write(&i, sizeof(i));
if (ret == -ENOSPC) {
std::this_thread::yield();
continue;
}
EXPECT_EQ(ret, sizeof(i));
++i;
}
// Because of buffer size smaller than amount of data written,
// producer cannot have completed the loop before consumer
// started consuming the data.
{
uint64_t c;
::read(event_fd, &c, sizeof(uint64_t));
}
}
// Child exits. Careful when calling exit() directly, because
// it does not call destructors. We ensured shared_ptrs were
// destroyed before by calling exit(0).
exit(0);
}
// parent, the consumer
// Wait for other process to create buffer.
int header_fd;
int data_fd;
{
auto err = recvFdsFromSocket(sock_fds[1], header_fd, data_fd);
if (err) {
TP_THROW_ASSERT() << err.what();
}
}
auto rb = shm::load(header_fd, data_fd);
Consumer cons{rb};
int i = 0;
while (i < 2000) {
int value;
ssize_t ret = cons.copy(sizeof(value), &value);
if (ret == -ENODATA) {
std::this_thread::yield();
continue;
}
EXPECT_EQ(ret, sizeof(value));
EXPECT_EQ(value, i);
++i;
}
{
uint64_t c = 1;
::write(event_fd, &c, sizeof(uint64_t));
}
::close(event_fd);
::close(sock_fds[0]);
::close(sock_fds[1]);
// Wait for child to make gtest happy.
::wait(nullptr);
};
<file_sep>/tensorpipe/util/shm/segment.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <fcntl.h>
#include <cstring>
#include <memory>
#include <sstream>
#include <tensorpipe/common/defs.h>
#include <tensorpipe/common/optional.h>
//
// A C++17 version of shared memory segments handler inspired on boost
// interprocess.
//
// Handles lifetime through shared_ptr custom deleters and allows folders inside
// /dev/shm (Linux only).
//
namespace tensorpipe {
namespace util {
namespace shm {
/// PageType to suggest to Operative System.
/// The final page type depends on system configuration
/// and availability of pages of requested size.
/// HugeTLB pages often need to be reserved at boot time and
/// may none left by the time Segment that request one is cerated.
enum class PageType { Default, HugeTLB_2MB, HugeTLB_1GB };
/// Choose a reasonable page size for a given size.
/// This very opinionated choice of "reasonable" aims to
/// keep wasted memory low.
// XXX: Lots of memory could be wasted if size is slightly larger than
// page size, handle that case.
constexpr PageType getDefaultPageType(uint64_t size) {
constexpr uint64_t MB = 1024ull * 1024ull;
constexpr uint64_t GB = 1024ull * MB;
if (size >= (15ul * GB) / 16ul) {
// At least 15/16 of a 1GB page (at most 64 MB wasted).
return PageType::HugeTLB_1GB;
} else if (size >= ((2ul * MB) * 3ul) / 4ul) {
// At least 3/4 of a 2MB page (at most 512 KB wasteds)
return PageType::HugeTLB_2MB;
} else {
// No Huge TLB page, use Default (4KB for x86).
return PageType::Default;
}
}
class Segment {
public:
// Default base path for all segments created.
static constexpr char kBasePath[] = "/dev/shm";
Segment(const Segment&) = delete;
Segment(Segment&&) = delete;
Segment(size_t byte_size, bool perm_write, optional<PageType> page_type);
Segment(int fd, bool perm_write, optional<PageType> page_type);
/// Create read and size shared memory to contain an object of class T.
///
/// The created object's shared_ptr will own the lifetime of the
/// Segment and will call Segment destructor.
/// Caller can use the shared_ptr to the underlying Segment.
template <class T, class... Args>
static std::pair<std::shared_ptr<T>, std::shared_ptr<Segment>> create(
bool perm_write,
optional<PageType> page_type,
Args&&... args) {
static_assert(
!std::is_array<T>::value,
"Did you mean to use the array version of Segment::create");
static_assert(std::is_trivially_copyable<T>::value, "!");
const auto byte_size = sizeof(T);
auto segment = std::make_shared<Segment>(byte_size, perm_write, page_type);
TP_DCHECK_EQ(segment->getSize(), byte_size);
// Initialize in place. Forward T's constructor arguments.
T* ptr = new (segment->getPtr()) T(std::forward<Args>(args)...);
if (ptr != segment->getPtr()) {
TP_THROW_SYSTEM(EPERM)
<< "new's address cannot be different from segment->getPtr() "
<< " address. Some aligment assumption was incorrect";
}
return {std::shared_ptr<T>(segment, ptr), segment};
}
/// One-dimensional array version of create<T, ...Args>.
/// Caller can use the shared_ptr to the underlying Segment.
// XXX: Fuse all versions of create.
template <class T, typename TScalar = typename std::remove_extent<T>::type>
static std::pair<std::shared_ptr<TScalar>, std::shared_ptr<Segment>> create(
size_t num_elements,
bool perm_write,
optional<PageType> page_type) {
static_assert(
std::is_trivially_copyable<T>::value,
"Shared memory segments are restricted to only store objects that "
"are trivially copyable (i.e. no pointers and no heap allocation");
static_assert(
std::is_array<T>::value,
"Did you mean to use the non-array version, Segment::create<T, ...>");
static_assert(
std::rank<T>::value == 1,
"Currently, only one-dimensional arrays are supported. "
"You can use the non-template version of Segment::create");
static_assert(std::is_trivially_copyable<TScalar>::value, "!");
static_assert(!std::is_array<TScalar>::value, "!");
static_assert(std::is_same<TScalar[], T>::value, "Type mismatch");
size_t byte_size = sizeof(TScalar) * num_elements;
auto segment = std::make_shared<Segment>(byte_size, perm_write, page_type);
TP_DCHECK_EQ(segment->getSize(), byte_size);
// Initialize in place.
TScalar* ptr = new (segment->getPtr()) TScalar[num_elements]();
if (ptr != segment->getPtr()) {
TP_THROW_SYSTEM(EPERM)
<< "new's address cannot be different from segment->getPtr() "
<< " address. Some aligment assumption was incorrect";
}
return {std::shared_ptr<TScalar>(segment, ptr), segment};
}
/// Load an already created shared memory Segment that holds an
/// object of type T, where T is an array type.
///
/// Lifecycle of shared_ptr and Segment's reference_wrapper is
/// identical to create<>().
template <
class T,
typename TScalar = typename std::remove_extent<T>::type,
std::enable_if_t<std::is_array<T>::value, int> = 0>
static std::pair<std::shared_ptr<TScalar>, std::shared_ptr<Segment>> load(
int fd,
bool perm_write,
optional<PageType> page_type) {
auto segment = std::make_shared<Segment>(fd, perm_write, page_type);
const size_t size = segment->getSize();
static_assert(
std::rank<T>::value == 1,
"Currently only rank one arrays are supported");
static_assert(std::is_trivially_copyable<TScalar>::value, "!");
auto ptr = static_cast<TScalar*>(segment->getPtr());
return {std::shared_ptr<TScalar>(segment, ptr), segment};
}
/// Load an already created shared memory Segment that holds an
/// object of type T, where T is NOT an array type.
///
/// Lifecycle of shared_ptr and Segment's reference_wrapper is
/// identical to create<>().
template <class T, std::enable_if_t<!std::is_array<T>::value, int> = 0>
static std::pair<std::shared_ptr<T>, std::shared_ptr<Segment>> load(
int fd,
bool perm_write,
optional<PageType> page_type) {
auto segment = std::make_shared<Segment>(fd, perm_write, page_type);
const size_t size = segment->getSize();
// XXX: Do some checking other than the size that we are loading
// the right type.
if (size != sizeof(T)) {
TP_THROW_SYSTEM(EPERM)
<< "Shared memory file has unexpected size. "
<< "Got: " << size << " bytes, expected: " << sizeof(T) << ". "
<< "If there is a race between creation and loading of segments, "
<< "consider linking segment after it has been fully initialized.";
}
static_assert(std::is_trivially_copyable<T>::value, "!");
auto ptr = static_cast<T*>(segment->getPtr());
return {std::shared_ptr<T>(segment, ptr), segment};
}
const int getFd() const {
return fd_;
}
void* getPtr() {
return base_ptr_;
}
const void* getPtr() const {
return base_ptr_;
}
size_t getSize() const {
return byte_size_;
}
PageType getPageType() const {
return page_type_;
}
~Segment();
protected:
// The page used to mmap the segment.
PageType page_type_;
// The file descriptor of the shared memory file.
int fd_ = -1;
// Byte size of shared memory segment.
size_t byte_size_;
// Base pointer of mmmap'ed shared memory segment.
void* base_ptr_;
void mmap(bool perm_write, optional<PageType> page_type);
};
} // namespace shm
} // namespace util
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/shm/context.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/shm/context.h>
#include <tensorpipe/common/system.h>
#include <tensorpipe/transport/registry.h>
#include <tensorpipe/transport/shm/connection.h>
#include <tensorpipe/transport/shm/listener.h>
#include <tensorpipe/transport/shm/loop.h>
#include <tensorpipe/transport/shm/socket.h>
namespace tensorpipe {
namespace transport {
namespace shm {
namespace {
std::shared_ptr<Context> makeShmContext() {
return std::make_shared<Context>();
}
TP_REGISTER_CREATOR(TensorpipeTransportRegistry, shm, makeShmContext);
} // namespace
namespace {
// Prepend descriptor with transport name so it's easy to
// disambiguate descriptors when debugging.
const std::string kDomainDescriptorPrefix{"shm:"};
std::string generateDomainDescriptor() {
auto bootID = getBootID();
TP_THROW_ASSERT_IF(!bootID) << "Unable to read boot_id";
return kDomainDescriptorPrefix + bootID.value();
}
} // namespace
class Context::Impl : public Context::PrivateIface,
public std::enable_shared_from_this<Context::Impl> {
public:
Impl();
const std::string& domainDescriptor() const;
std::shared_ptr<transport::Connection> connect(address_t addr);
std::shared_ptr<transport::Listener> listen(address_t addr);
void setId(std::string id);
ClosingEmitter& getClosingEmitter() override;
bool inLoopThread() override;
void deferToLoop(std::function<void()> fn) override;
void runInLoop(std::function<void()> fn) override;
void registerDescriptor(int fd, int events, std::shared_ptr<EventHandler> h)
override;
void unregisterDescriptor(int fd) override;
TToken addReaction(TFunction fn) override;
void removeReaction(TToken token) override;
std::tuple<int, int> reactorFds() override;
void close();
void join();
~Impl() override = default;
private:
Reactor reactor_;
Loop loop_{this->reactor_};
std::atomic<bool> closed_{false};
std::atomic<bool> joined_{false};
ClosingEmitter closingEmitter_;
std::string domainDescriptor_;
// An identifier for the context, composed of the identifier for the context,
// combined with the transport's name. It will only be used for logging and
// debugging purposes.
std::string id_{"N/A"};
// Sequence numbers for the listeners and connections created by this context,
// used to create their identifiers based off this context's identifier. They
// will only be used for logging and debugging.
std::atomic<uint64_t> listenerCounter_{0};
std::atomic<uint64_t> connectionCounter_{0};
};
Context::Context() : impl_(std::make_shared<Impl>()) {}
Context::Impl::Impl() : domainDescriptor_(generateDomainDescriptor()) {}
void Context::close() {
impl_->close();
}
void Context::Impl::close() {
if (!closed_.exchange(true)) {
TP_VLOG(7) << "Transport context " << id_ << " is closing";
closingEmitter_.close();
loop_.close();
TP_VLOG(7) << "Transport context " << id_ << " done closing";
}
}
void Context::join() {
impl_->join();
}
void Context::Impl::join() {
close();
if (!joined_.exchange(true)) {
TP_VLOG(7) << "Transport context " << id_ << " is joining";
loop_.join();
TP_VLOG(7) << "Transport context " << id_ << " done joining";
}
}
Context::~Context() {
join();
}
std::shared_ptr<transport::Connection> Context::connect(std::string addr) {
return impl_->connect(std::move(addr));
}
std::shared_ptr<transport::Connection> Context::Impl::connect(
std::string addr) {
std::string connectionId = id_ + ".c" + std::to_string(connectionCounter_++);
TP_VLOG(7) << "Transport context " << id_ << " is opening connection "
<< connectionId << " to address " << addr;
return std::make_shared<Connection>(
Connection::ConstructorToken(),
std::static_pointer_cast<PrivateIface>(shared_from_this()),
std::move(addr),
std::move(connectionId));
}
std::shared_ptr<transport::Listener> Context::listen(std::string addr) {
return impl_->listen(std::move(addr));
}
std::shared_ptr<transport::Listener> Context::Impl::listen(std::string addr) {
std::string listenerId = id_ + ".l" + std::to_string(listenerCounter_++);
TP_VLOG(7) << "Transport context " << id_ << " is opening listener "
<< listenerId << " on address " << addr;
return std::make_shared<Listener>(
Listener::ConstructorToken(),
std::static_pointer_cast<PrivateIface>(shared_from_this()),
std::move(addr),
std::move(listenerId));
}
const std::string& Context::domainDescriptor() const {
return impl_->domainDescriptor();
}
const std::string& Context::Impl::domainDescriptor() const {
return domainDescriptor_;
}
void Context::setId(std::string id) {
impl_->setId(std::move(id));
}
void Context::Impl::setId(std::string id) {
TP_VLOG(7) << "Transport context " << id_ << " was renamed to " << id;
id_ = std::move(id);
}
ClosingEmitter& Context::Impl::getClosingEmitter() {
return closingEmitter_;
};
bool Context::Impl::inLoopThread() {
return reactor_.inReactorThread();
};
void Context::Impl::deferToLoop(std::function<void()> fn) {
reactor_.deferToLoop(std::move(fn));
};
void Context::Impl::runInLoop(std::function<void()> fn) {
reactor_.runInLoop(std::move(fn));
};
void Context::Impl::registerDescriptor(
int fd,
int events,
std::shared_ptr<EventHandler> h) {
loop_.registerDescriptor(fd, events, std::move(h));
}
void Context::Impl::unregisterDescriptor(int fd) {
loop_.unregisterDescriptor(fd);
}
Context::Impl::TToken Context::Impl::addReaction(TFunction fn) {
return reactor_.add(std::move(fn));
}
void Context::Impl::removeReaction(TToken token) {
reactor_.remove(token);
}
std::tuple<int, int> Context::Impl::reactorFds() {
return reactor_.fds();
}
} // namespace shm
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/util/ringbuffer/shm.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/util/ringbuffer/shm.h>
namespace tensorpipe {
namespace util {
namespace ringbuffer {
namespace shm {
std::tuple<int, int, std::shared_ptr<RingBuffer>> create(
size_t min_rb_byte_size,
optional<tensorpipe::util::shm::PageType> data_page_type,
bool perm_write) {
std::shared_ptr<RingBufferHeader> header;
std::shared_ptr<tensorpipe::util::shm::Segment> header_segment;
std::tie(header, header_segment) =
tensorpipe::util::shm::Segment::create<RingBufferHeader>(
perm_write,
tensorpipe::util::shm::PageType::Default,
min_rb_byte_size);
std::shared_ptr<uint8_t> data;
std::shared_ptr<tensorpipe::util::shm::Segment> data_segment;
std::tie(data, data_segment) =
tensorpipe::util::shm::Segment::create<uint8_t[]>(
header->kDataPoolByteSize, perm_write, data_page_type);
// Note: cannot use implicit construction from initializer list on GCC 5.5:
// "converting to XYZ from initializer list would use explicit constructor".
return std::make_tuple(
header_segment->getFd(),
data_segment->getFd(),
std::make_shared<RingBuffer>(std::move(header), std::move(data)));
}
std::shared_ptr<RingBuffer> load(
int header_fd,
int data_fd,
optional<tensorpipe::util::shm::PageType> data_page_type,
bool perm_write) {
std::shared_ptr<RingBufferHeader> header;
std::shared_ptr<tensorpipe::util::shm::Segment> header_segment;
std::tie(header, header_segment) =
tensorpipe::util::shm::Segment::load<RingBufferHeader>(
header_fd, perm_write, tensorpipe::util::shm::PageType::Default);
constexpr auto kHeaderSize = sizeof(RingBufferHeader);
if (unlikely(kHeaderSize != header_segment->getSize())) {
TP_THROW_SYSTEM(EPERM) << "Header segment of unexpected size";
}
std::shared_ptr<uint8_t> data;
std::shared_ptr<tensorpipe::util::shm::Segment> data_segment;
std::tie(data, data_segment) =
tensorpipe::util::shm::Segment::load<uint8_t[]>(
data_fd, perm_write, data_page_type);
if (unlikely(header->kDataPoolByteSize != data_segment->getSize())) {
TP_THROW_SYSTEM(EPERM) << "Data segment of unexpected size";
}
return std::make_shared<RingBuffer>(std::move(header), std::move(data));
}
} // namespace shm
} // namespace ringbuffer
} // namespace util
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/shm/socket.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/shm/socket.h>
#include <fcntl.h>
#include <sys/un.h>
#include <unistd.h>
#include <cstring>
#include <tensorpipe/common/defs.h>
namespace tensorpipe {
namespace transport {
namespace shm {
Sockaddr Sockaddr::createAbstractUnixAddr(const std::string& name) {
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
std::memset(&sun.sun_path, 0, sizeof(sun.sun_path));
constexpr size_t offset = 1;
const size_t len = std::min(sizeof(sun.sun_path) - offset, name.size());
std::strncpy(&sun.sun_path[offset], name.c_str(), len);
// Note: instead of using sizeof(sun) we compute the addrlen from
// the string length of the abstract socket name. If we use
// sizeof(sun), lsof shows all the trailing NUL characters.
return Sockaddr(
reinterpret_cast<struct sockaddr*>(&sun),
sizeof(sun.sun_family) + offset + len + 1);
};
Sockaddr::Sockaddr(struct sockaddr* addr, socklen_t addrlen) {
TP_ARG_CHECK_LE(addrlen, sizeof(addr_));
std::memcpy(&addr_, addr, addrlen);
addrlen_ = addrlen;
}
std::string Sockaddr::str() const {
const struct sockaddr_un* sun{
reinterpret_cast<const struct sockaddr_un*>(&addr_)};
constexpr size_t offset = 1;
const size_t len = addrlen_ - sizeof(sun->sun_family) - offset - 1;
return std::string(&sun->sun_path[offset], len);
}
std::tuple<Error, std::shared_ptr<Socket>> Socket::createForFamily(
sa_family_t ai_family) {
auto rv = socket(ai_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (rv == -1) {
return std::make_tuple(
TP_CREATE_ERROR(SystemError, "socket", errno),
std::shared_ptr<Socket>());
}
return std::make_tuple(Error::kSuccess, std::make_shared<Socket>(rv));
}
Error Socket::block(bool on) {
int rv;
rv = fcntl(fd_, F_GETFL);
if (rv == -1) {
return TP_CREATE_ERROR(SystemError, "fcntl", errno);
}
if (!on) {
// Set O_NONBLOCK
rv |= O_NONBLOCK;
} else {
// Clear O_NONBLOCK
rv &= ~O_NONBLOCK;
}
rv = fcntl(fd_, F_SETFL, rv);
if (rv == -1) {
return TP_CREATE_ERROR(SystemError, "fcntl", errno);
}
return Error::kSuccess;
}
Error Socket::bind(const Sockaddr& addr) {
auto rv = ::bind(fd_, addr.addr(), addr.addrlen());
if (rv == -1) {
return TP_CREATE_ERROR(SystemError, "bind", errno);
}
return Error::kSuccess;
}
Error Socket::listen(int backlog) {
auto rv = ::listen(fd_, backlog);
if (rv == -1) {
return TP_CREATE_ERROR(SystemError, "listen", errno);
}
return Error::kSuccess;
}
std::tuple<Error, std::shared_ptr<Socket>> Socket::accept() {
struct sockaddr_storage addr;
socklen_t addrlen = sizeof(addr);
int rv = -1;
for (;;) {
rv = ::accept(fd_, (struct sockaddr*)&addr, &addrlen);
if (rv == -1) {
if (errno == EINTR) {
continue;
}
return std::make_tuple(
TP_CREATE_ERROR(SystemError, "accept", errno),
std::shared_ptr<Socket>());
}
break;
}
return std::make_tuple(Error::kSuccess, std::make_shared<Socket>(rv));
}
Error Socket::connect(const Sockaddr& addr) {
for (;;) {
auto rv = ::connect(fd_, addr.addr(), addr.addrlen());
if (rv == -1) {
if (errno == EINTR) {
continue;
}
if (errno != EINPROGRESS) {
return TP_CREATE_ERROR(SystemError, "connect", errno);
}
}
break;
}
return Error::kSuccess;
}
} // namespace shm
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/test/transport/uv/sockaddr_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/uv/sockaddr.h>
#include <netinet/in.h>
#include <gtest/gtest.h>
using namespace tensorpipe::transport;
namespace {
int family(const uv::Sockaddr& addr) {
auto sockaddr = addr.addr();
return sockaddr->sa_family;
}
int port(const uv::Sockaddr& addr) {
auto sockaddr = addr.addr();
if (sockaddr->sa_family == AF_INET) {
auto in = reinterpret_cast<const struct sockaddr_in*>(sockaddr);
return in->sin_port;
}
if (sockaddr->sa_family == AF_INET6) {
auto in6 = reinterpret_cast<const struct sockaddr_in6*>(sockaddr);
return in6->sin6_port;
}
return -1;
}
} // namespace
TEST(Sockaddr, InetBadPort) {
ASSERT_THROW(
uv::Sockaddr::createInetSockAddr("1.2.3.4:-1"), std::invalid_argument);
ASSERT_THROW(
uv::Sockaddr::createInetSockAddr("1.2.3.4:65536"), std::invalid_argument);
}
TEST(Sockaddr, Inet) {
{
auto sa = uv::Sockaddr::createInetSockAddr("1.2.3.4:5");
ASSERT_EQ(family(sa), AF_INET);
ASSERT_EQ(port(sa), ntohs(5));
ASSERT_EQ(sa.str(), "1.2.3.4:5");
}
{
auto sa = uv::Sockaddr::createInetSockAddr("1.2.3.4:0");
ASSERT_EQ(family(sa), AF_INET);
ASSERT_EQ(port(sa), 0);
ASSERT_EQ(sa.str(), "1.2.3.4:0");
}
{
auto sa = uv::Sockaddr::createInetSockAddr("1.2.3.4");
ASSERT_EQ(family(sa), AF_INET);
ASSERT_EQ(port(sa), 0);
ASSERT_EQ(sa.str(), "1.2.3.4:0");
}
}
TEST(Sockaddr, Inet6BadPort) {
ASSERT_THROW(
uv::Sockaddr::createInetSockAddr("[::1]:-1"), std::invalid_argument);
ASSERT_THROW(
uv::Sockaddr::createInetSockAddr("[::1]:65536"), std::invalid_argument);
ASSERT_THROW(
uv::Sockaddr::createInetSockAddr("]::1["), std::invalid_argument);
}
TEST(Sockaddr, Inet6) {
{
auto sa = uv::Sockaddr::createInetSockAddr("[::1]:5");
ASSERT_EQ(family(sa), AF_INET6);
ASSERT_EQ(port(sa), ntohs(5));
ASSERT_EQ(sa.str(), "[::1]:5");
}
{
auto sa = uv::Sockaddr::createInetSockAddr("[::1]:0");
ASSERT_EQ(family(sa), AF_INET6);
ASSERT_EQ(port(sa), 0);
ASSERT_EQ(sa.str(), "[::1]:0");
}
{
auto sa = uv::Sockaddr::createInetSockAddr("::1");
ASSERT_EQ(family(sa), AF_INET6);
ASSERT_EQ(port(sa), 0);
ASSERT_EQ(sa.str(), "[::1]:0");
}
}
<file_sep>/tensorpipe/test/util/ringbuffer/ringbuffer_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <array>
#include <tensorpipe/util/ringbuffer/consumer.h>
#include <tensorpipe/util/ringbuffer/producer.h>
#include <tensorpipe/util/ringbuffer/ringbuffer.h>
#include <gtest/gtest.h>
using namespace tensorpipe::util::ringbuffer;
struct TestData {
uint16_t a;
uint16_t b;
uint16_t c;
bool operator==(const TestData& other) const {
return a == other.a && b == other.b && c == other.c;
}
};
std::shared_ptr<RingBuffer> makeRingBuffer(size_t size) {
auto header = std::make_shared<RingBufferHeader>(size);
// In C++20 use std::make_shared<uint8_t[]>(size)
auto data = std::shared_ptr<uint8_t>(
new uint8_t[header->kDataPoolByteSize], std::default_delete<uint8_t[]>());
return std::make_shared<RingBuffer>(std::move(header), std::move(data));
}
TEST(RingBuffer, WriteCopy) {
EXPECT_EQ(sizeof(TestData), 6);
// 16 bytes buffer. Fits two full TestData (each 6).
size_t size = 1u << 4;
auto rb = makeRingBuffer(size);
// Make a producer.
Producer p{rb};
// Make a consumer.
Consumer c{rb};
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
TestData d0{.a = 0xBA98, .b = 0x7654, .c = 0xA312};
TestData d1{.a = 0xA987, .b = 0x7777, .c = 0x2812};
TestData d2{.a = 0xFFFF, .b = 0x3333, .c = 0x1212};
{
ssize_t ret = p.write(&d0, sizeof(d0));
EXPECT_EQ(ret, sizeof(TestData));
}
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 6);
{
ssize_t ret = p.write(&d1, sizeof(d1));
EXPECT_EQ(ret, sizeof(TestData));
}
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 12);
{
ssize_t ret = p.write(&d2, sizeof(d2));
EXPECT_EQ(ret, -ENOSPC) << "Needs 2 more bytes to write the 6 required, "
"because 12 out of 16 are used.";
}
TestData r;
{
ssize_t ret = c.copy(sizeof(r), &r);
EXPECT_EQ(ret, sizeof(r));
EXPECT_EQ(r, d0);
}
{
ssize_t ret = c.copy(sizeof(r), &r);
EXPECT_EQ(ret, sizeof(r));
EXPECT_EQ(r, d1);
}
// It should be empty by now.
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
{
ssize_t ret = p.write(&d2, sizeof(d2));
EXPECT_EQ(ret, sizeof(TestData));
}
{
ssize_t ret = c.copy(sizeof(r), &r);
EXPECT_EQ(ret, sizeof(r));
EXPECT_EQ(r, d2);
}
// It should be empty by now.
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
}
TEST(RingBuffer, ReadMultipleElems) {
// 256 bytes buffer.
size_t size = 1u << 8u;
auto rb = makeRingBuffer(size);
// Make a producer.
Producer p{rb};
// Make a consumer.
Consumer c{rb};
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
uint16_t n = 0xACAC; // fits 128 times
{
for (int i = 0; i < 128; ++i) {
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
}
// It must be full by now.
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 256);
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, -ENOSPC);
}
{
uint8_t b = 0xEE;
ssize_t ret = p.write(&b, sizeof(b));
EXPECT_EQ(ret, -ENOSPC) << "Needs an extra byte";
}
{
// read the three bytes at once.
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
std::array<uint8_t, 3> r;
ret = c.copyInTx(sizeof(r), r.data());
EXPECT_EQ(ret, 3);
EXPECT_EQ(r[0], 0xAC);
EXPECT_EQ(r[1], 0xAC);
EXPECT_EQ(r[2], 0xAC);
ret = c.commitTx();
EXPECT_EQ(ret, 0);
}
{
// read 253 bytes at once.
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
std::array<uint8_t, 253> r;
ret = c.copyInTx(sizeof(r), r.data());
EXPECT_EQ(ret, 253);
for (int i = 0; i < 253; ++i) {
EXPECT_EQ(r[i], 0xAC);
}
ret = c.commitTx();
EXPECT_EQ(ret, 0);
}
{
// No more elements
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
uint8_t ch;
ret = c.copyInTx(sizeof(ch), &ch);
EXPECT_EQ(ret, -ENODATA);
ret = c.cancelTx();
EXPECT_EQ(ret, 0);
EXPECT_TRUE(!c.inTx()) << "Canceled transaction should've been canceled";
}
}
TEST(RingBuffer, CopyWrapping) {
// 8 bytes buffer.
size_t size = 1u << 3;
auto rb = makeRingBuffer(size);
// Make a producer.
Producer p{rb};
// Make a consumer.
Consumer c{rb};
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
uint8_t ch = 0xA7;
uint64_t n = 0xFFFFFFFFFFFFFFFF;
// Put one byte.
EXPECT_EQ(rb->getHeader().readHead(), 0);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
ssize_t ret = p.write(&ch, sizeof(ch));
EXPECT_EQ(ret, sizeof(ch));
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 1);
// Next 8 bytes won't fit.
ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, -ENOSPC)
<< "Needs an extra byte to write the 8 bytes element. "
"Capacity 8, used 1.";
// Remove the one byte in, now head is one off.
uint8_t cr;
uint64_t nr;
ret = c.copy(sizeof(cr), &cr);
EXPECT_EQ(ret, sizeof(cr));
EXPECT_EQ(cr, ch);
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 1);
// Next 8 bytes will fit, but wrap.
ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
EXPECT_EQ(rb->getHeader().readHead(), 9);
EXPECT_EQ(rb->getHeader().readTail(), 1);
ret = c.copy(sizeof(nr), &nr);
EXPECT_EQ(ret, sizeof(nr));
EXPECT_EQ(nr, n);
EXPECT_EQ(rb->getHeader().readHead(), 9);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
TEST(RingBuffer, ReadTxWrappingOneCons) {
// 8 bytes buffer.
size_t size = 1u << 3;
auto rb = makeRingBuffer(size);
// Make a producer.
Producer p{rb};
// Make a consumer.
Consumer c1{rb};
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
uint8_t ch = 0xA7;
uint64_t n = 0xFFFFFFFFFFFFFFFF;
// Put one byte.
{
EXPECT_EQ(rb->getHeader().readHead(), 0);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
ssize_t ret = p.write(&ch, sizeof(ch));
EXPECT_EQ(ret, sizeof(ch));
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 1);
}
// Next 8 bytes won't fit.
{
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, -ENOSPC)
<< "Needs an extra byte to write the 8 bytes element. "
"Capacity 8, used 1.";
}
// Remove the one byte in, now head is one off.
EXPECT_FALSE(c1.inTx());
{
// Start c1 read Tx
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint8_t rch;
ret = c1.copyInTx(sizeof(rch), &rch);
EXPECT_EQ(ret, sizeof(uint8_t));
EXPECT_EQ(rch, ch);
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_TRUE(c1.inTx());
}
{
// Complete c1's Tx.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 1);
}
{
// Retrying to commit should fail.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, -EINVAL);
}
{
// Next 8 bytes will fit, but wrap.
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
EXPECT_EQ(rb->getHeader().readHead(), 9);
EXPECT_EQ(rb->getHeader().readTail(), 1);
}
{
// Start c1 read Tx again.
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint64_t rn;
ret = c1.copyInTx(sizeof(rn), &rn);
EXPECT_EQ(ret, sizeof(uint64_t));
EXPECT_EQ(rn, n);
EXPECT_EQ(rb->getHeader().readHead(), 9);
EXPECT_EQ(rb->getHeader().readTail(), 1);
EXPECT_TRUE(c1.inTx());
}
{
// Complete c1.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, 0);
ret = c1.commitTx();
EXPECT_EQ(ret, -EINVAL);
}
{
// Next 8 bytes will fit, but wrap.
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
EXPECT_EQ(rb->getHeader().readHead(), 17);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
{
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint64_t rn;
ret = c1.copyInTx(sizeof(rn), &rn);
EXPECT_EQ(ret, sizeof(uint64_t));
EXPECT_EQ(rn, n);
EXPECT_EQ(rb->getHeader().readHead(), 17);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
{
// Cancel tx, data should be readable again.
ssize_t ret = c1.cancelTx();
EXPECT_EQ(ret, 0);
}
{
// Now c1 can read.
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint64_t rn;
ret = c1.copyInTx(sizeof(rn), &rn);
EXPECT_EQ(ret, sizeof(uint64_t));
EXPECT_EQ(rn, n);
EXPECT_EQ(rb->getHeader().readHead(), 17);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
{
// Commit succeds.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_FALSE(c1.inTx());
}
}
TEST(RingBuffer, ReadTxWrapping) {
// 8 bytes buffer.
size_t size = 1u << 3;
auto rb = makeRingBuffer(size);
// Make a producer.
Producer p{rb};
// Make consumers.
Consumer c1{rb};
Consumer c2{rb};
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
uint8_t ch = 0xA7;
uint64_t n = 0x3333333333333333;
// Put one byte.
{
EXPECT_EQ(rb->getHeader().readHead(), 0);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
ssize_t ret = p.write(&ch, sizeof(ch));
EXPECT_EQ(ret, sizeof(ch));
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 1);
}
// Next 8 bytes won't fit.
{
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, -ENOSPC)
<< "Needs an extra byte to write the 8 bytes element. "
"Capacity 8, used 1.";
}
// Remove the one byte in, now head is one off.
EXPECT_FALSE(c1.inTx());
EXPECT_FALSE(c2.inTx());
{
// Start c1 read Tx
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint8_t rch;
ret = c1.copyInTx(sizeof(rch), &rch);
EXPECT_EQ(ret, sizeof(uint8_t));
EXPECT_EQ(rch, ch);
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 0);
EXPECT_TRUE(c1.inTx());
}
{
// Complete c1's Tx.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().readHead(), 1);
EXPECT_EQ(rb->getHeader().readTail(), 1);
}
{
// Retrying to commit should fail.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, -EINVAL);
}
{
// Next 8 bytes will fit, but wrap.
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
EXPECT_EQ(rb->getHeader().readHead(), 9);
EXPECT_EQ(rb->getHeader().readTail(), 1);
}
{
// Start c1 read Tx again.
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint64_t rn;
ret = c1.copyInTx(sizeof(rn), &rn);
EXPECT_EQ(ret, sizeof(uint64_t));
EXPECT_EQ(rn, n);
EXPECT_EQ(rb->getHeader().readHead(), 9);
EXPECT_EQ(rb->getHeader().readTail(), 1);
EXPECT_TRUE(c1.inTx());
}
{
// Try to start read tx before c1 completing and get -EAGAIN.
ssize_t ret;
ret = c2.startTx();
EXPECT_EQ(ret, -EAGAIN);
}
{
// Complete c1.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, 0);
ret = c1.commitTx();
EXPECT_EQ(ret, -EINVAL);
}
{
// Next 8 bytes will fit, but wrap.
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
EXPECT_EQ(rb->getHeader().readHead(), 17);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
{
ssize_t ret;
ret = c2.startTx();
EXPECT_EQ(ret, 0);
uint64_t rn;
ret = c2.copyInTx(sizeof(rn), &rn);
EXPECT_EQ(ret, sizeof(uint64_t));
EXPECT_EQ(rn, n);
EXPECT_EQ(rb->getHeader().readHead(), 17);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
{
// Cancel tx, data should be readable again.
ssize_t ret = c2.cancelTx();
EXPECT_EQ(ret, 0);
}
{
// Now c1 can read.
ssize_t ret;
ret = c1.startTx();
EXPECT_EQ(ret, 0);
uint64_t rn;
ret = c1.copyInTx(sizeof(rn), &rn);
EXPECT_EQ(ret, sizeof(uint64_t));
EXPECT_EQ(rn, n);
EXPECT_EQ(rb->getHeader().readHead(), 17);
EXPECT_EQ(rb->getHeader().readTail(), 9);
}
{
// Commit succeds.
ssize_t ret = c1.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_FALSE(c1.inTx());
EXPECT_FALSE(c2.inTx());
}
}
TEST(RingBuffer, readContiguousAtMostInTx) {
// 256 bytes buffer.
size_t size = 1u << 8u;
auto rb = makeRingBuffer(size);
// Make a producer.
Producer p{rb};
// Make a consumer.
Consumer c{rb};
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
uint16_t n = 0xACAC; // fits 128 times
{
for (int i = 0; i < 128; ++i) {
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
}
// It must be full by now.
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 256);
uint8_t b = 0xEE;
ssize_t ret = p.write(&b, sizeof(b));
EXPECT_EQ(ret, -ENOSPC);
}
{
// Read the first 200 bytes at once.
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
const uint8_t* ptr;
std::tie(ret, ptr) = c.readContiguousAtMostInTx(200);
EXPECT_EQ(ret, 200);
for (int i = 0; i < 200; ++i) {
EXPECT_EQ(ptr[i], 0xAC);
}
ret = c.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 56);
}
{
for (int i = 0; i < 100; ++i) {
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
}
// It must be full again by now.
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 256);
}
{
// Attempt reading the next 200 bytes, but only 56 available contiguously.
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
const uint8_t* ptr;
std::tie(ret, ptr) = c.readContiguousAtMostInTx(200);
EXPECT_EQ(ret, 56);
for (int i = 0; i < 56; ++i) {
EXPECT_EQ(ptr[i], 0xAC);
}
ret = c.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 200);
}
{
for (int i = 0; i < 28; ++i) {
ssize_t ret = p.write(&n, sizeof(n));
EXPECT_EQ(ret, sizeof(n));
}
// It must be full again by now.
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 256);
}
{
// Reading the whole 256 bytes.
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
const uint8_t* ptr;
std::tie(ret, ptr) = c.readContiguousAtMostInTx(256);
EXPECT_EQ(ret, 256);
for (int i = 0; i < 256; ++i) {
EXPECT_EQ(ptr[i], 0xAC);
}
ret = c.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
}
{
// Attempt reading from empty buffer.
ssize_t ret;
ret = c.startTx();
EXPECT_EQ(ret, 0);
const uint8_t* ptr;
std::tie(ret, ptr) = c.readContiguousAtMostInTx(200);
EXPECT_EQ(ret, 0);
ret = c.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
}
}
<file_sep>/tensorpipe/channel/helpers.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/channel/helpers.h>
#include <tensorpipe/common/defs.h>
namespace tensorpipe {
namespace channel {
Channel::TDescriptor saveDescriptor(const google::protobuf::MessageLite& pb) {
Channel::TDescriptor out;
const auto success = pb.SerializeToString(&out);
TP_DCHECK(success) << "Failed to serialize protobuf message";
return out;
}
void loadDescriptor(
google::protobuf::MessageLite& pb,
const Channel::TDescriptor& in) {
const auto success = pb.ParseFromString(in);
TP_DCHECK(success) << "Failed to parse protobuf message";
}
} // namespace channel
} // namespace tensorpipe
<file_sep>/tensorpipe/test/util/shm/segment_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/shm/socket.h>
#include <tensorpipe/util/shm/segment.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <thread>
#include <gtest/gtest.h>
using namespace tensorpipe::util::shm;
using namespace tensorpipe::transport::shm;
// Same process produces and consumes share memory through different mappings.
TEST(Segment, SameProducerConsumer_Scalar) {
// Set affinity of producer to CPU zero so that consumer only has to read from
// that one CPU's buffer.
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
sched_setaffinity(0, sizeof(cpu_set_t), &cpuset);
// This must stay alive for the file descriptor to remain open.
std::shared_ptr<Segment> producer_segment;
{
// Producer part.
std::shared_ptr<int> my_int_ptr;
std::tie(my_int_ptr, producer_segment) =
Segment::create<int>(true, PageType::Default);
int& my_int = *my_int_ptr;
my_int = 1000;
}
{
// Consumer part.
// Map file again (to a different address) and consume it.
std::shared_ptr<int> my_int_ptr;
std::shared_ptr<Segment> segment;
std::tie(my_int_ptr, segment) =
Segment::load<int>(producer_segment->getFd(), true, PageType::Default);
EXPECT_EQ(segment->getSize(), sizeof(int));
EXPECT_EQ(*my_int_ptr, 1000);
}
};
TEST(SegmentManager, SingleProducer_SingleConsumer_Array) {
size_t num_floats = 330000;
int sock_fds[2];
{
int rv = socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds);
if (rv != 0) {
TP_THROW_SYSTEM(errno) << "Failed to create socket pair";
}
}
int event_fd = eventfd(0, 0);
if (event_fd < 0) {
TP_THROW_SYSTEM(errno) << "Failed to create event fd";
}
int pid = fork();
if (pid < 0) {
TP_THROW_SYSTEM(errno) << "Failed to fork";
}
if (pid == 0) {
// child, the producer
// Make a scope so shared_ptr's are released even on exit(0).
{
// use huge pages in creation and not in loading. This should only affects
// TLB overhead.
std::shared_ptr<float> my_floats;
std::shared_ptr<Segment> segment;
std::tie(my_floats, segment) =
Segment::create<float[]>(num_floats, true, PageType::HugeTLB_2MB);
for (int i = 0; i < num_floats; ++i) {
my_floats.get()[i] = i;
}
{
auto err = sendFdsToSocket(sock_fds[0], segment->getFd());
if (err) {
TP_THROW_ASSERT() << err.what();
}
}
{
uint64_t c;
::read(event_fd, &c, sizeof(uint64_t));
}
}
// Child exits. Careful when calling exit() directly, because
// it does not call destructors. We ensured shared_ptrs were
// destroyed before by calling exit(0).
exit(0);
}
// parent, the consumer
int segment_fd;
{
auto err = recvFdsFromSocket(sock_fds[1], segment_fd);
if (err) {
TP_THROW_ASSERT() << err.what();
}
}
std::shared_ptr<float> my_floats;
std::shared_ptr<Segment> segment;
std::tie(my_floats, segment) =
Segment::load<float[]>(segment_fd, false, PageType::Default);
EXPECT_EQ(num_floats * sizeof(float), segment->getSize());
for (int i = 0; i < num_floats; ++i) {
EXPECT_EQ(my_floats.get()[i], i);
}
{
uint64_t c = 1;
::write(event_fd, &c, sizeof(uint64_t));
}
::close(event_fd);
::close(sock_fds[0]);
::close(sock_fds[1]);
// Wait for child to make gtest happy.
::wait(nullptr);
};
<file_sep>/tensorpipe/util/ringbuffer/consumer.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <tensorpipe/util/ringbuffer/ringbuffer.h>
namespace tensorpipe {
namespace util {
namespace ringbuffer {
///
/// Consumer of data for a RingBuffer.
///
/// Provides method to read data ringbuffer.
///
class Consumer : public RingBufferWrapper {
public:
// Use base class constructor.
using RingBufferWrapper::RingBufferWrapper;
Consumer(const Consumer&) = delete;
Consumer(Consumer&&) = delete;
virtual ~Consumer() {
if (inTx()) {
auto r = this->cancelTx();
TP_DCHECK_EQ(r, 0);
}
}
//
// Transaction based API.
// Only one writer can have an active transaction at any time.
// *InTx* operations that fail do not cancel transaction.
//
bool inTx() const noexcept {
return this->inTx_;
}
[[nodiscard]] ssize_t startTx() noexcept {
if (unlikely(inTx())) {
return -EBUSY;
}
if (this->header_.in_read_tx.test_and_set(std::memory_order_acquire)) {
return -EAGAIN;
}
this->inTx_ = true;
TP_DCHECK_EQ(this->tx_size_, 0);
return 0;
}
[[nodiscard]] ssize_t commitTx() noexcept {
if (unlikely(!inTx())) {
return -EINVAL;
}
this->header_.incTail(this->tx_size_);
this->tx_size_ = 0;
this->inTx_ = false;
this->header_.in_read_tx.clear(std::memory_order_release);
return 0;
}
[[nodiscard]] ssize_t cancelTx() noexcept {
if (unlikely(!inTx())) {
return -EINVAL;
}
this->tx_size_ = 0;
// <in_read_tx> flags that we are in a transaction,
// so enforce no stores pass it.
this->inTx_ = false;
this->header_.in_read_tx.clear(std::memory_order_release);
return 0;
}
// Copy next <size> bytes to buffer.
[[nodiscard]] ssize_t copyInTx(const size_t size, void* buffer) noexcept {
if (unlikely(!inTx())) {
return -EINVAL;
}
if (size == 0) {
return 0;
}
if (unlikely(size > this->header_.kDataPoolByteSize)) {
return -EINVAL;
}
const uint8_t* ptr =
readFromRingBuffer_(size, static_cast<uint8_t*>(buffer));
if (ptr == nullptr) {
return -ENODATA;
}
return static_cast<ssize_t>(size);
}
// Copy up to the next <size> bytes to buffer.
[[nodiscard]] ssize_t copyAtMostInTx(
const size_t size,
uint8_t* buffer) noexcept {
if (unlikely(!inTx())) {
return -EINVAL;
}
// Single reader because we are in Tx, safe to read tail.
const size_t avail = this->header_.usedSizeWeak() - this->tx_size_;
return this->copyInTx(std::min(size, avail), buffer);
}
// Return the number of bytes (up to size) available as a contiguous segment,
// as well as a pointer to the first byte.
[[nodiscard]] std::pair<ssize_t, const uint8_t*> readContiguousAtMostInTx(
const size_t size) noexcept {
if (unlikely(!inTx())) {
return {-EINVAL, nullptr};
}
const uint64_t head = this->header_.readHead();
// Single reader because we are in Tx, safe to read tail.
const uint64_t tail = this->header_.readTail();
const uint64_t start = (this->tx_size_ + tail) & this->header_.kDataModMask;
const size_t avail = head - tail - this->tx_size_;
const uint64_t end = std::min(
start + std::min(size, avail), this->header_.kDataPoolByteSize);
this->tx_size_ += end - start;
return {end - start, &this->data_[start]};
}
//
// High-level atomic operations.
//
/// Makes a copy to <buffer>, buffer must be of size <size> or larger.
[[nodiscard]] ssize_t copy(const size_t size, void* buffer) noexcept {
auto ret = startTx();
if (0 > ret) {
return ret;
}
ret = copyInTx(size, static_cast<uint8_t*>(buffer));
if (0 > ret) {
auto r = cancelTx();
TP_DCHECK_EQ(r, 0);
return ret;
}
TP_DCHECK_EQ(ret, size);
ret = commitTx();
TP_DCHECK_EQ(ret, 0);
return static_cast<ssize_t>(size);
}
protected:
bool inTx_{false};
/// Returns a ptr to data (or null if no data available).
/// If succeeds, increases <tx_size_> by size.
const uint8_t* readFromRingBuffer_(
const size_t size,
uint8_t* copy_buffer) noexcept {
// Caller must have taken care of this.
TP_DCHECK_LE(size, this->header_.kDataPoolByteSize);
if (unlikely(0 >= size)) {
TP_LOG_ERROR() << "Cannot copy value of zero size";
return nullptr;
}
if (unlikely(size > this->header_.kDataPoolByteSize)) {
TP_LOG_ERROR() << "reads larger than buffer are not supported";
return nullptr;
}
const uint64_t head = this->header_.readHead();
// Single reader because we are in Tx, safe to read tail.
const uint64_t tail = this->header_.readTail();
TP_DCHECK_LE(head - tail, this->header_.kDataPoolByteSize);
// Check if there is enough data.
if (this->tx_size_ + size > head - tail) {
return nullptr;
}
// start and end are head and tail in module arithmetic.
const uint64_t start = (this->tx_size_ + tail) & this->header_.kDataModMask;
const uint64_t end = (start + size) & this->header_.kDataModMask;
const bool wrap = start >= end;
this->tx_size_ += size;
if (likely(!wrap)) {
std::memcpy(copy_buffer, &this->data_[start], size);
} else {
const size_t size0 = this->header_.kDataPoolByteSize - start;
std::memcpy(copy_buffer, &this->data_[start], size0);
std::memcpy(copy_buffer + size0, &this->data_[0], end);
}
return copy_buffer;
}
};
} // namespace ringbuffer
} // namespace util
} // namespace tensorpipe
<file_sep>/tensorpipe/util/shm/segment.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/util/shm/segment.h>
#include <fcntl.h>
#include <linux/mman.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <memory>
#include <sstream>
#include <thread>
#include <tuple>
namespace tensorpipe {
namespace util {
namespace shm {
namespace {
[[nodiscard]] int createShmFd() {
int flags = O_TMPFILE | O_EXCL | O_RDWR | O_CLOEXEC;
int fd = ::open(Segment::kBasePath, flags, 0);
if (fd == -1) {
TP_THROW_SYSTEM(errno) << "Failed to open shared memory file descriptor "
<< "at " << Segment::kBasePath;
}
return fd;
}
// if <byte_size> == 0, map the whole file.
void* mmapShmFd(int fd, size_t byte_size, bool perm_write, PageType page_type) {
#ifdef MAP_SHARED_VALIDATE
int flags = MAP_SHARED | MAP_SHARED_VALIDATE;
#else
#warning \
"this version of libc doesn't define MAP_SHARED_VALIDATE, \
update to obtain the latest correctness checks."
int flags = MAP_SHARED;
#endif
// Note that in x86 PROT_WRITE implies PROT_READ so there is no
// point on allowing read protection to be specified.
// Currently no handling PROT_EXEC because there is no use case for it.
int prot = PROT_READ;
if (perm_write) {
prot |= PROT_WRITE;
}
switch (page_type) {
case PageType::Default:
break;
case PageType::HugeTLB_2MB:
prot |= MAP_HUGETLB | MAP_HUGE_2MB;
break;
case PageType::HugeTLB_1GB:
prot |= MAP_HUGETLB | MAP_HUGE_1GB;
break;
}
void* shm = ::mmap(nullptr, byte_size, prot, flags, fd, 0);
if (shm == MAP_FAILED) {
TP_THROW_SYSTEM(errno) << "Failed to mmap memory of size: " << byte_size;
}
return shm;
}
} // namespace
// Mention static constexpr char to export the symbol.
constexpr char Segment::kBasePath[];
Segment::Segment(
size_t byte_size,
bool perm_write,
optional<PageType> page_type)
: fd_{createShmFd()}, byte_size_{byte_size}, base_ptr_{nullptr} {
// grow size to contain byte_size bytes.
off_t len = static_cast<off_t>(byte_size_);
int ret = ::fallocate(fd_, 0, 0, len);
if (ret == -1) {
TP_THROW_SYSTEM(errno) << "Error while allocating " << byte_size_
<< " bytes in shared memory";
}
mmap(perm_write, page_type);
}
Segment::Segment(int fd, bool perm_write, optional<PageType> page_type)
: fd_{fd}, base_ptr_{nullptr} {
// Load whole file. Use fstat to obtain size.
struct stat sb;
int ret = ::fstat(fd_, &sb);
if (ret == -1) {
TP_THROW_SYSTEM(errno) << "Error while fstat shared memory file.";
}
this->byte_size_ = static_cast<size_t>(sb.st_size);
mmap(perm_write, page_type);
}
void Segment::mmap(bool perm_write, optional<PageType> page_type) {
// If page_type is not set, use the default.
page_type_ = page_type.value_or(getDefaultPageType(this->byte_size_));
this->base_ptr_ = mmapShmFd(fd_, byte_size_, perm_write, page_type_);
}
Segment::~Segment() {
int ret = munmap(base_ptr_, byte_size_);
if (ret == -1) {
TP_LOG_ERROR() << "Error while munmapping shared memory segment. Error: "
<< toErrorCode(errno).message();
}
if (0 > fd_) {
TP_LOG_ERROR() << "Attempt to destroy segment with negative file "
<< "descriptor";
return;
}
::close(fd_);
}
} // namespace shm
} // namespace util
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/shm/listener.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/shm/listener.h>
#include <deque>
#include <functional>
#include <mutex>
#include <vector>
#include <tensorpipe/common/callback.h>
#include <tensorpipe/common/defs.h>
#include <tensorpipe/common/optional.h>
#include <tensorpipe/transport/error.h>
#include <tensorpipe/transport/shm/connection.h>
#include <tensorpipe/transport/shm/loop.h>
#include <tensorpipe/transport/shm/socket.h>
namespace tensorpipe {
namespace transport {
namespace shm {
class Listener::Impl : public std::enable_shared_from_this<Listener::Impl>,
public EventHandler {
public:
// Create a listener that listens on the specified address.
Impl(
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id);
// Initialize member fields that need `shared_from_this`.
void init();
// Queue a callback to be called when a connection comes in.
void accept(accept_callback_fn fn);
// Obtain the listener's address.
std::string addr() const;
// Tell the listener what its identifier is.
void setId(std::string id);
// Shut down the connection and its resources.
void close();
// Implementation of EventHandler.
void handleEventsFromLoop(int events) override;
private:
// Initialize member fields that need `shared_from_this`.
void initFromLoop();
// Queue a callback to be called when a connection comes in.
void acceptFromLoop(accept_callback_fn fn);
// Obtain the listener's address.
std::string addrFromLoop() const;
void setIdFromLoop_(std::string id);
// Shut down the connection and its resources.
void closeFromLoop();
void setError_(Error error);
// Deal with an error.
void handleError();
std::shared_ptr<Context::PrivateIface> context_;
std::shared_ptr<Socket> socket_;
Sockaddr sockaddr_;
Error error_{Error::kSuccess};
std::deque<accept_callback_fn> fns_;
ClosingReceiver closingReceiver_;
// A sequence number for the calls to accept.
uint64_t nextConnectionBeingAccepted_{0};
// A sequence number for the invocations of the callbacks of accept.
uint64_t nextAcceptCallbackToCall_{0};
// An identifier for the listener, composed of the identifier for the context,
// combined with an increasing sequence number. It will be used as a prefix
// for the identifiers of connections. All of them will only be used for
// logging and debugging purposes.
std::string id_;
// Sequence numbers for the connections created by this listener, used to
// create their identifiers based off this listener's identifier. They will
// only be used for logging and debugging.
std::atomic<uint64_t> connectionCounter_{0};
};
Listener::Impl::Impl(
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id)
: context_(std::move(context)),
sockaddr_(Sockaddr::createAbstractUnixAddr(addr)),
closingReceiver_(context_, context_->getClosingEmitter()),
id_(std::move(id)) {}
void Listener::Impl::initFromLoop() {
TP_DCHECK(context_->inLoopThread());
closingReceiver_.activate(*this);
Error error;
TP_DCHECK(socket_ == nullptr);
std::tie(error, socket_) = Socket::createForFamily(AF_UNIX);
if (error) {
setError_(std::move(error));
return;
}
error = socket_->bind(sockaddr_);
if (error) {
setError_(std::move(error));
return;
}
error = socket_->block(false);
if (error) {
setError_(std::move(error));
return;
}
error = socket_->listen(128);
if (error) {
setError_(std::move(error));
return;
}
}
Listener::Listener(
ConstructorToken /* unused */,
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id)
: impl_(std::make_shared<Impl>(
std::move(context),
std::move(addr),
std::move(id))) {
impl_->init();
}
void Listener::Impl::init() {
context_->deferToLoop([impl{shared_from_this()}]() { impl->initFromLoop(); });
}
void Listener::Impl::closeFromLoop() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(7) << "Listener " << id_ << " is closing";
setError_(TP_CREATE_ERROR(ListenerClosedError));
}
void Listener::Impl::setError_(Error error) {
// Don't overwrite an error that's already set.
if (error_ || !error) {
return;
}
error_ = std::move(error);
handleError();
}
void Listener::Impl::handleError() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(8) << "Listener " << id_ << " is handling error " << error_.what();
if (!fns_.empty()) {
context_->unregisterDescriptor(socket_->fd());
}
socket_.reset();
for (auto& fn : fns_) {
fn(error_, std::shared_ptr<Connection>());
}
fns_.clear();
}
void Listener::close() {
impl_->close();
}
void Listener::Impl::close() {
context_->deferToLoop(
[impl{shared_from_this()}]() { impl->closeFromLoop(); });
}
Listener::~Listener() {
close();
}
void Listener::accept(accept_callback_fn fn) {
impl_->accept(std::move(fn));
}
void Listener::Impl::accept(accept_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, fn{std::move(fn)}]() mutable {
impl->acceptFromLoop(std::move(fn));
});
}
void Listener::Impl::acceptFromLoop(accept_callback_fn fn) {
TP_DCHECK(context_->inLoopThread());
uint64_t sequenceNumber = nextConnectionBeingAccepted_++;
TP_VLOG(7) << "Listener " << id_ << " received an accept request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](
const Error& error,
std::shared_ptr<transport::Connection> connection) {
TP_DCHECK_EQ(sequenceNumber, nextAcceptCallbackToCall_++);
TP_VLOG(7) << "Listener " << id_ << " is calling an accept callback (#"
<< sequenceNumber << ")";
fn(error, std::move(connection));
TP_VLOG(7) << "Listener " << id_ << " done calling an accept callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_, std::shared_ptr<Connection>());
return;
}
fns_.push_back(std::move(fn));
// Only register if we go from 0 to 1 pending callbacks. In other cases we
// already had a pending callback and thus we were already registered.
if (fns_.size() == 1) {
// Register with loop for readability events.
context_->registerDescriptor(socket_->fd(), EPOLLIN, shared_from_this());
}
}
address_t Listener::addr() const {
return impl_->addr();
}
std::string Listener::Impl::addr() const {
std::string addr;
context_->runInLoop([this, &addr]() { addr = addrFromLoop(); });
return addr;
}
address_t Listener::Impl::addrFromLoop() const {
TP_DCHECK(context_->inLoopThread());
return sockaddr_.str();
}
void Listener::setId(std::string id) {
impl_->setId(std::move(id));
}
void Listener::Impl::setId(std::string id) {
context_->deferToLoop(
[impl{shared_from_this()}, id{std::move(id)}]() mutable {
impl->setIdFromLoop_(std::move(id));
});
}
void Listener::Impl::setIdFromLoop_(std::string id) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(7) << "Listener " << id_ << " was renamed to " << id;
id_ = std::move(id);
}
void Listener::Impl::handleEventsFromLoop(int events) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(9) << "Listener " << id_ << " is handling an event on its socket ("
<< Loop::formatEpollEvents(events) << ")";
if (events & EPOLLERR) {
int error;
socklen_t errorlen = sizeof(error);
int rv = getsockopt(
socket_->fd(),
SOL_SOCKET,
SO_ERROR,
reinterpret_cast<void*>(&error),
&errorlen);
if (rv == -1) {
setError_(TP_CREATE_ERROR(SystemError, "getsockopt", rv));
} else {
setError_(TP_CREATE_ERROR(SystemError, "async error on socket", error));
}
return;
}
if (events & EPOLLHUP) {
setError_(TP_CREATE_ERROR(EOFError));
return;
}
TP_ARG_CHECK_EQ(events, EPOLLIN);
Error error;
std::shared_ptr<Socket> socket;
std::tie(error, socket) = socket_->accept();
if (error) {
setError_(std::move(error));
return;
}
TP_DCHECK(!fns_.empty())
<< "when the callback is disarmed the listener's descriptor is supposed "
<< "to be unregistered";
auto fn = std::move(fns_.front());
fns_.pop_front();
if (fns_.empty()) {
context_->unregisterDescriptor(socket_->fd());
}
std::string connectionId = id_ + ".c" + std::to_string(connectionCounter_++);
TP_VLOG(7) << "Listener " << id_ << " is opening connection " << connectionId;
fn(Error::kSuccess,
std::make_shared<Connection>(
Connection::ConstructorToken(),
context_,
std::move(socket),
std::move(connectionId)));
}
} // namespace shm
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/uv/macros.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <tensorpipe/common/defs.h>
// Note: this file must only be included from source files!
#define TP_THROW_UV(err) TP_THROW(std::runtime_error)
#define TP_THROW_UV_IF(cond, err) \
if (unlikely(cond)) \
TP_THROW_UV(err) << TP_STRINGIFY(cond) << ": " << uv_strerror(err)
<file_sep>/tensorpipe/common/error.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/common/error.h>
#include <sstream>
#include <tensorpipe/common/defs.h>
namespace tensorpipe {
const Error Error::kSuccess = Error();
std::string Error::what() const {
TP_DCHECK(error_);
return error_->what();
}
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/connection.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/connection.h>
#include <google/protobuf/message_lite.h>
#include <tensorpipe/common/defs.h>
namespace tensorpipe {
namespace transport {
void Connection::read(
google::protobuf::MessageLite& message,
read_proto_callback_fn fn) {
read([&message, fn{std::move(fn)}](
const Error& error, const void* ptr, size_t len) {
if (!error) {
message.ParseFromArray(ptr, len);
}
fn(error);
});
}
void Connection::write(
const google::protobuf::MessageLite& message,
write_callback_fn fn) {
// FIXME use ByteSizeLong (introduced in a newer protobuf).
const auto len = message.ByteSize();
// Using a shared_ptr instead of unique_ptr because if the lambda captures a
// unique_ptr then it becomes non-copyable, which prevents it from being
// converted to a function. In C++20 use std::make_shared<uint8_t[]>(len).
//
// Note: this is a std::shared_ptr<uint8_t[]> semantically. A shared_ptr
// with array type is supported in C++17 and higher.
//
auto buf = std::shared_ptr<uint8_t>(
new uint8_t[len], std::default_delete<uint8_t[]>());
auto ptr = buf.get();
auto end = message.SerializeWithCachedSizesToArray(ptr);
TP_DCHECK_EQ(end, ptr + len) << "Failed to serialize protobuf message.";
// Perform write and forward callback.
write(
ptr,
len,
[buf{std::move(buf)}, fn{std::move(fn)}](const Error& error) mutable {
// The write has completed; destroy write buffer.
buf.reset();
fn(error);
});
}
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/context.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include <tensorpipe/transport/connection.h>
#include <tensorpipe/transport/defs.h>
#include <tensorpipe/transport/listener.h>
namespace tensorpipe {
namespace transport {
class Context {
public:
virtual std::shared_ptr<Connection> connect(address_t addr) = 0;
virtual std::shared_ptr<Listener> listen(address_t addr) = 0;
// Return string to describe the domain for this context.
//
// Two processes with a context of the same type whose domain
// descriptors are identical can connect to each other.
//
// For example, for a transport that leverages TCP/IP, this may be
// as simple as the address family (assuming we can route between
// any two processes). For a transport that leverages shared memory,
// this descriptor must uniquely identify the machine, such that
// only co-located processes generate the same domain descriptor.
//
virtual const std::string& domainDescriptor() const = 0;
// Tell the context what its identifier is.
//
// This is only supposed to be called from the high-level context or from
// channel contexts. It will only used for logging and debugging purposes.
virtual void setId(std::string id) = 0;
virtual void close() = 0;
virtual void join() = 0;
virtual ~Context() = default;
};
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/util/ringbuffer/ringbuffer.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <sys/types.h>
#include <atomic>
#include <cstring>
#include <memory>
#include <type_traits>
#include <tensorpipe/common/system.h>
///
/// C++17 implementation of shared-memory friendly perf_event style ringbuffer.
/// It's designed to avoid parallel access and provide (almost) zero-copy
///
///
/// A ringbuffer has a header and a data members that can be allocated
/// independently from the ringbuffer object, allowing the ringbuffer object
/// to be stored in process' exclusive memory while header and data
/// could be in shared memory.
///
/// Multiple ringbuffers can reference the same header + data.
///
/// Multiple producers (or consumers) can reference the same ringbuffer.
///
/// Synchronization between all producers/consumers of all ringbuffers that
/// reference the same header + pair pairs is done using atomic operations
/// care is taken to guarantee lock-free implementations, reduce the usage
/// of LOCK prefixes and the access to non-exclusive cache lines by CPUs.
///
/// Producers write data atomically at ringbuffer's head, while Consumers
/// write data atomically at ringbuffer's tail.
///
namespace tensorpipe {
namespace util {
namespace ringbuffer {
///
/// RingBufferHeader contains the head, tail and other control information
/// of the RingBuffer.
///
/// <kMinByteSize_> is the minimum byte size of the circular buffer. The actual
/// size is the smallest power of 2 larger than kMinByteSize_. Enforcing the
/// size to be a power of two avoids costly division/modulo operations.
///
class RingBufferHeader {
public:
const uint64_t kDataPoolByteSize;
const uint64_t kDataModMask;
RingBufferHeader(const RingBufferHeader&) = delete;
RingBufferHeader(RingBufferHeader&&) = delete;
// Implementation uses power of 2 arithmetic to avoid costly modulo.
// So build the largest RingBuffer with size of the smallest power of 2 >=
// <byte_size>.
RingBufferHeader(uint64_t min_data_byte_size)
: kDataPoolByteSize{nextPow2(min_data_byte_size)},
kDataModMask{kDataPoolByteSize - 1} {
// Minimum size where implementation of bit shift arithmetic works.
TP_DCHECK_GE(kDataPoolByteSize, 2)
<< "Minimum supported ringbuffer data size is 2 bytes";
TP_DCHECK(isPow2(kDataPoolByteSize))
<< kDataPoolByteSize << " is not a power of 2";
TP_DCHECK_LE(kDataPoolByteSize, std::numeric_limits<int>::max())
<< "Logic piggy-backs read/write size on ints, to be safe forbid"
" buffer to ever be larger than what an int can hold";
in_write_tx.clear();
in_read_tx.clear();
}
// Get size that is only guaranteed to be correct when producers and consumers
// are synchronized.
size_t usedSizeWeak() const {
return atomicHead_ - atomicTail_;
}
size_t freeSizeWeak() const {
return kDataPoolByteSize - usedSizeWeak();
}
uint64_t readHead() const {
return atomicHead_;
}
uint64_t readTail() const {
return atomicTail_;
}
void incHead(uint64_t inc) {
atomicHead_ += inc;
}
void incTail(uint64_t inc) {
atomicTail_ += inc;
}
void drop() {
atomicTail_.store(atomicHead_.load());
}
// acquired by producers.
std::atomic_flag in_write_tx;
// acquired by consumers.
std::atomic_flag in_read_tx;
protected:
// Written by producer.
std::atomic<uint64_t> atomicHead_{0};
// Written by consumer.
std::atomic<uint64_t> atomicTail_{0};
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html#atomics.lockfree
// static_assert(
// decltype(atomicHead_)::is_always_lock_free,
// "Only lock-free atomics are supported");
// static_assert(
// decltype(atomicTail_)::is_always_lock_free,
// "Only lock-free atomics are supported");
};
///
/// Process' view of a ring buffer.
/// This cannot reside in shared memory since it has pointers.
///
class RingBuffer final {
public:
RingBuffer(const RingBuffer&) = delete;
RingBuffer(RingBuffer&&) = delete;
RingBuffer(
std::shared_ptr<RingBufferHeader> header,
std::shared_ptr<uint8_t> data)
: header_{std::move(header)}, data_{std::move(data)} {
TP_THROW_IF_NULLPTR(header_) << "Header cannot be nullptr";
TP_THROW_IF_NULLPTR(data_) << "Data cannot be nullptr";
}
const RingBufferHeader& getHeader() const {
return *header_;
}
RingBufferHeader& getHeader() {
return *header_;
}
const uint8_t* getData() const {
return data_.get();
}
uint8_t* getData() {
return data_.get();
}
protected:
std::shared_ptr<RingBufferHeader> header_;
// Note: this is a std::shared_ptr<uint8_t[]> semantically.
// A shared_ptr with array type is supported in C++17 and higher.
std::shared_ptr<uint8_t> data_;
};
///
/// Ringbuffer wrapper
///
class RingBufferWrapper {
public:
RingBufferWrapper(const RingBufferWrapper&) = delete;
RingBufferWrapper(std::shared_ptr<RingBuffer> rb)
: rb_{rb}, header_{rb->getHeader()}, data_{rb->getData()} {
TP_THROW_IF_NULLPTR(rb);
TP_THROW_IF_NULLPTR(data_);
}
auto& getHeader() {
return header_;
}
const auto& getHeader() const {
return header_;
}
auto getRingBuffer() {
return rb_;
}
protected:
std::shared_ptr<RingBuffer> rb_;
RingBufferHeader& header_;
uint8_t* const data_;
unsigned tx_size_ = 0;
};
} // namespace ringbuffer
} // namespace util
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/shm/reactor.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <atomic>
#include <functional>
#include <future>
#include <list>
#include <mutex>
#include <set>
#include <thread>
#include <vector>
#include <tensorpipe/common/callback.h>
#include <tensorpipe/common/optional.h>
#include <tensorpipe/transport/shm/fd.h>
#include <tensorpipe/util/ringbuffer/consumer.h>
#include <tensorpipe/util/ringbuffer/producer.h>
namespace tensorpipe {
namespace transport {
namespace shm {
// Reactor loop.
//
// Companion class to the event loop in `loop.h` that executes
// functions on triggers. The triggers are posted to a shared memory
// ring buffer, so this can be done by other processes on the same
// machine. It uses extra data in the ring buffer header to store a
// mutex and condition variable to avoid a busy loop.
//
class Reactor final {
// This allows for buffering 1M triggers (at 4 bytes a piece).
static constexpr auto kSize = 4 * 1024 * 1024;
public:
using TFunction = std::function<void()>;
using TToken = uint32_t;
Reactor();
using TDeferredFunction = std::function<void()>;
// Run function on reactor thread.
// If the function throws, the thread crashes.
void deferToLoop(TDeferredFunction fn);
// Prefer using deferToLoop over runInLoop when you don't need to wait for the
// result.
template <typename F>
void runInLoop(F&& fn) {
// When called from the event loop thread itself (e.g., from a callback),
// deferring would cause a deadlock because the given callable can only be
// run when the loop is allowed to proceed. On the other hand, it means it
// is thread-safe to run it immediately. The danger here however is that it
// can lead to an inconsistent order between operations run from the event
// loop, from outside of it, and deferred.
if (inReactorThread()) {
fn();
} else {
// Must use a copyable wrapper around std::promise because
// we use it from a std::function which must be copyable.
auto promise = std::make_shared<std::promise<void>>();
auto future = promise->get_future();
deferToLoop([promise, fn{std::forward<F>(fn)}]() {
try {
fn();
promise->set_value();
} catch (...) {
promise->set_exception(std::current_exception());
}
});
future.get();
}
}
// Add function to the reactor.
// Returns token that can be used to trigger it.
TToken add(TFunction fn);
// Removes function associated with token from reactor.
void remove(TToken token);
// Trigger reactor with specified token.
void trigger(TToken token);
// Returns the file descriptors for the underlying ring buffer.
std::tuple<int, int> fds() const;
inline bool inReactorThread() {
{
std::unique_lock<std::mutex> lock(deferredFunctionMutex_);
if (likely(isThreadConsumingDeferredFunctions_)) {
return std::this_thread::get_id() == thread_.get_id();
}
}
return onDemandLoop_.inLoop();
}
void close();
void join();
~Reactor();
private:
Fd headerFd_;
Fd dataFd_;
optional<util::ringbuffer::Consumer> consumer_;
optional<util::ringbuffer::Producer> producer_;
std::mutex mutex_;
std::thread thread_;
std::atomic<bool> closed_{false};
std::atomic<bool> joined_{false};
std::mutex deferredFunctionMutex_;
std::list<TDeferredFunction> deferredFunctionList_;
std::atomic<int64_t> deferredFunctionCount_{0};
// Whether the thread is still taking care of running the deferred functions
//
// This is part of what can only be described as a hack. Sometimes, even when
// using the API as intended, objects try to defer tasks to the loop after
// that loop has been closed and joined. Since those tasks may be lambdas that
// captured shared_ptrs to the objects in their closures, this may lead to a
// reference cycle and thus a leak. Our hack is to have this flag to record
// when we can no longer defer tasks to the loop and in that case we just run
// those tasks inline. In order to keep ensuring the single-threadedness
// assumption of our model (which is what we rely on to be safe from race
// conditions) we use an on-demand loop.
bool isThreadConsumingDeferredFunctions_{true};
OnDemandLoop onDemandLoop_;
// Reactor thread entry point.
void run();
// Tokens are placed in this set if they can be reused.
std::set<TToken> reusableTokens_;
// Map reactor tokens to functions.
//
// The tokens are reused so we don't worry about unbounded growth
// and comfortably use a std::vector here.
//
std::vector<TFunction> functions_;
// Count how many functions are registered.
std::atomic<uint64_t> functionCount_{0};
public:
class Trigger {
public:
Trigger(Fd&& header, Fd&& data);
void run(TToken token);
private:
util::ringbuffer::Producer producer_;
};
};
} // namespace shm
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/uv/connection.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/uv/connection.h>
#include <array>
#include <deque>
#include <tensorpipe/common/callback.h>
#include <tensorpipe/common/defs.h>
#include <tensorpipe/common/error_macros.h>
#include <tensorpipe/common/optional.h>
#include <tensorpipe/transport/uv/error.h>
#include <tensorpipe/transport/uv/loop.h>
#include <tensorpipe/transport/uv/sockaddr.h>
#include <tensorpipe/transport/uv/uv.h>
namespace tensorpipe {
namespace transport {
namespace uv {
namespace {
// The read operation captures all state associated with reading a
// fixed length chunk of data from the underlying connection. All
// reads are required to include a word-sized header containing the
// number of bytes in the operation. This makes it possible for the
// read side of the connection to either 1) not know how many bytes
// to expected, and dynamically allocate, or 2) know how many bytes
// to expect, and preallocate the destination memory.
class ReadOperation {
enum Mode {
READ_LENGTH,
READ_PAYLOAD,
COMPLETE,
};
public:
using read_callback_fn = Connection::read_callback_fn;
explicit ReadOperation(read_callback_fn fn);
ReadOperation(void* ptr, size_t length, read_callback_fn fn);
// Called when libuv is about to read data from connection.
void allocFromLoop(uv_buf_t* buf);
// Called when libuv has read data from connection.
void readFromLoop(ssize_t nread, const uv_buf_t* buf);
// Returns if this read operation is complete.
inline bool completeFromLoop() const;
// Invoke user callback.
inline void callbackFromLoop(const Error& error);
private:
Mode mode_{READ_LENGTH};
char* ptr_{nullptr};
// Number of bytes as specified by the user (if applicable).
optional<size_t> givenLength_;
// Number of bytes to expect as read from the connection.
size_t readLength_{0};
// Number of bytes read from the connection.
// This is reset to 0 when we advance from READ_LENGTH to READ_PAYLOAD.
size_t bytesRead_{0};
// Holds temporary allocation if no length was specified.
std::unique_ptr<char[]> buffer_{nullptr};
// User callback.
read_callback_fn fn_;
};
ReadOperation::ReadOperation(read_callback_fn fn) : fn_(std::move(fn)) {}
ReadOperation::ReadOperation(void* ptr, size_t length, read_callback_fn fn)
: ptr_(static_cast<char*>(ptr)), givenLength_(length), fn_(std::move(fn)) {}
void ReadOperation::allocFromLoop(uv_buf_t* buf) {
if (mode_ == READ_LENGTH) {
TP_DCHECK_LT(bytesRead_, sizeof(readLength_));
buf->base = reinterpret_cast<char*>(&readLength_) + bytesRead_;
buf->len = sizeof(readLength_) - bytesRead_;
} else if (mode_ == READ_PAYLOAD) {
TP_DCHECK_LT(bytesRead_, readLength_);
TP_DCHECK(ptr_ != nullptr);
buf->base = ptr_ + bytesRead_;
buf->len = readLength_ - bytesRead_;
} else {
TP_THROW_ASSERT() << "invalid mode " << mode_;
}
}
void ReadOperation::readFromLoop(ssize_t nread, const uv_buf_t* buf) {
TP_DCHECK_GE(nread, 0);
bytesRead_ += nread;
if (mode_ == READ_LENGTH) {
TP_DCHECK_LE(bytesRead_, sizeof(readLength_));
if (bytesRead_ == sizeof(readLength_)) {
if (givenLength_.has_value()) {
TP_DCHECK(ptr_ != nullptr || givenLength_.value() == 0);
TP_DCHECK_EQ(readLength_, givenLength_.value());
} else {
TP_DCHECK(ptr_ == nullptr);
buffer_ = std::make_unique<char[]>(readLength_);
ptr_ = buffer_.get();
}
if (readLength_ == 0) {
mode_ = COMPLETE;
} else {
mode_ = READ_PAYLOAD;
}
bytesRead_ = 0;
}
} else if (mode_ == READ_PAYLOAD) {
TP_DCHECK_LE(bytesRead_, readLength_);
if (bytesRead_ == readLength_) {
mode_ = COMPLETE;
}
} else {
TP_THROW_ASSERT() << "invalid mode " << mode_;
}
}
bool ReadOperation::completeFromLoop() const {
return mode_ == COMPLETE;
}
void ReadOperation::callbackFromLoop(const Error& error) {
fn_(error, ptr_, readLength_);
}
// The write operation captures all state associated with writing a
// fixed length chunk of data from the underlying connection. The
// write includes a word-sized header containing the length of the
// write. This header is a member field on this class and therefore
// the instance must be kept alive and the reference to the instance
// must remain valid until the write callback has been called.
class WriteOperation {
public:
using write_callback_fn = Connection::write_callback_fn;
WriteOperation(const void* ptr, size_t length, write_callback_fn fn);
inline std::tuple<uv_buf_t*, unsigned int> getBufs();
// Invoke user callback.
inline void callbackFromLoop(const Error& error);
private:
const char* ptr_;
const size_t length_;
// Buffers (structs with pointers and lengths) we pass to uv_write.
std::array<uv_buf_t, 2> bufs_;
// User callback.
write_callback_fn fn_;
};
WriteOperation::WriteOperation(
const void* ptr,
size_t length,
write_callback_fn fn)
: ptr_(static_cast<const char*>(ptr)), length_(length), fn_(std::move(fn)) {
bufs_[0].base = const_cast<char*>(reinterpret_cast<const char*>(&length_));
bufs_[0].len = sizeof(length_);
bufs_[1].base = const_cast<char*>(ptr_);
bufs_[1].len = length_;
}
std::tuple<uv_buf_t*, unsigned int> WriteOperation::getBufs() {
// Libuv doesn't like when we pass it empty buffers (it fails with ENOBUFS),
// so if the second buffer is empty we only pass it the first one.
unsigned int numBuffers = length_ == 0 ? 1 : 2;
return std::make_tuple(bufs_.data(), numBuffers);
}
void WriteOperation::callbackFromLoop(const Error& error) {
fn_(error);
}
} // namespace
class Connection::Impl : public std::enable_shared_from_this<Connection::Impl> {
public:
// Create a connection that is already connected (e.g. from a listener).
Impl(
std::shared_ptr<Context::PrivateIface>,
std::shared_ptr<TCPHandle>,
std::string);
// Create a connection that connects to the specified address.
Impl(std::shared_ptr<Context::PrivateIface>, address_t, std::string);
// Initialize member fields that need `shared_from_this`.
void init();
// Queue a read operation.
void read(read_callback_fn fn);
void read(void* ptr, size_t length, read_callback_fn fn);
// Perform a write operation.
void write(const void* ptr, size_t length, write_callback_fn fn);
// Tell the connection what its identifier is.
void setId(std::string id);
// Shut down the connection and its resources.
void close();
private:
// Initialize member fields that need `shared_from_this`.
void initFromLoop();
// Queue a read operation.
void readFromLoop(read_callback_fn fn);
void readFromLoop(void* ptr, size_t length, read_callback_fn fn);
// Perform a write operation.
void writeFromLoop(const void* ptr, size_t length, write_callback_fn fn);
void setIdFromLoop_(std::string id);
// Shut down the connection and its resources.
void closeFromLoop();
// Called when libuv is about to read data from connection.
void allocCallbackFromLoop_(uv_buf_t* buf);
// Called when libuv has read data from connection.
void readCallbackFromLoop_(ssize_t nread, const uv_buf_t* buf);
// Called when libuv has written data to connection.
void writeCallbackFromLoop_(int status);
// Called when libuv has closed the handle.
void closeCallbackFromLoop_();
void setError_(Error error);
// Deal with an error.
void handleError_();
std::shared_ptr<Context::PrivateIface> context_;
std::shared_ptr<TCPHandle> handle_;
optional<Sockaddr> sockaddr_;
Error error_{Error::kSuccess};
ClosingReceiver closingReceiver_;
std::deque<ReadOperation> readOperations_;
std::deque<WriteOperation> writeOperations_;
// A sequence number for the calls to read and write.
uint64_t nextBufferBeingRead_{0};
uint64_t nextBufferBeingWritten_{0};
// A sequence number for the invocations of the callbacks of read and write.
uint64_t nextReadCallbackToCall_{0};
uint64_t nextWriteCallbackToCall_{0};
// An identifier for the connection, composed of the identifier for the
// context or listener, combined with an increasing sequence number. It will
// only be used for logging and debugging purposes.
std::string id_;
// By having the instance store a shared_ptr to itself we create a reference
// cycle which will "leak" the instance. This allows us to detach its
// lifetime from the connection and sync it with the TCPHandle's life cycle.
std::shared_ptr<Impl> leak_;
};
Connection::Impl::Impl(
std::shared_ptr<Context::PrivateIface> context,
std::shared_ptr<TCPHandle> handle,
std::string id)
: context_(std::move(context)),
handle_(std::move(handle)),
closingReceiver_(context_, context_->getClosingEmitter()),
id_(std::move(id)) {}
Connection::Impl::Impl(
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id)
: context_(std::move(context)),
handle_(context_->createHandle()),
sockaddr_(Sockaddr::createInetSockAddr(addr)),
closingReceiver_(context_, context_->getClosingEmitter()),
id_(std::move(id)) {}
void Connection::Impl::initFromLoop() {
leak_ = shared_from_this();
closingReceiver_.activate(*this);
if (sockaddr_.has_value()) {
handle_->initFromLoop();
handle_->connectFromLoop(sockaddr_.value(), [this](int status) {
if (status < 0) {
setError_(TP_CREATE_ERROR(UVError, status));
}
});
}
handle_->armCloseCallbackFromLoop(
[this]() { this->closeCallbackFromLoop_(); });
handle_->armAllocCallbackFromLoop(
[this](uv_buf_t* buf) { this->allocCallbackFromLoop_(buf); });
handle_->armReadCallbackFromLoop([this](ssize_t nread, const uv_buf_t* buf) {
this->readCallbackFromLoop_(nread, buf);
});
}
void Connection::Impl::readFromLoop(read_callback_fn fn) {
TP_DCHECK(context_->inLoopThread());
uint64_t sequenceNumber = nextBufferBeingRead_++;
TP_VLOG(7) << "Connection " << id_ << " received a read request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](
const Error& error, const void* ptr, size_t length) {
TP_DCHECK_EQ(sequenceNumber, nextReadCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_ << " is calling a read callback (#"
<< sequenceNumber << ")";
fn(error, ptr, length);
TP_VLOG(7) << "Connection " << id_ << " done calling a read callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_, nullptr, 0);
return;
}
readOperations_.emplace_back(std::move(fn));
// Start reading if this is the first read operation.
if (readOperations_.size() == 1) {
handle_->readStartFromLoop();
}
}
void Connection::Impl::readFromLoop(
void* ptr,
size_t length,
read_callback_fn fn) {
TP_DCHECK(context_->inLoopThread());
uint64_t sequenceNumber = nextBufferBeingRead_++;
TP_VLOG(7) << "Connection " << id_ << " received a read request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](
const Error& error, const void* ptr, size_t length) {
TP_DCHECK_EQ(sequenceNumber, nextReadCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_ << " is calling a read callback (#"
<< sequenceNumber << ")";
fn(error, ptr, length);
TP_VLOG(7) << "Connection " << id_ << " done calling a read callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_, ptr, length);
return;
}
readOperations_.emplace_back(ptr, length, std::move(fn));
// Start reading if this is the first read operation.
if (readOperations_.size() == 1) {
handle_->readStartFromLoop();
}
}
void Connection::Impl::writeFromLoop(
const void* ptr,
size_t length,
write_callback_fn fn) {
TP_DCHECK(context_->inLoopThread());
uint64_t sequenceNumber = nextBufferBeingWritten_++;
TP_VLOG(7) << "Connection " << id_ << " received a write request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](const Error& error) {
TP_DCHECK_EQ(sequenceNumber, nextWriteCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_ << " is calling a write callback (#"
<< sequenceNumber << ")";
fn(error);
TP_VLOG(7) << "Connection " << id_ << " done calling a write callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_);
return;
}
writeOperations_.emplace_back(ptr, length, std::move(fn));
auto& writeOperation = writeOperations_.back();
uv_buf_t* bufsPtr;
unsigned int bufsLen;
std::tie(bufsPtr, bufsLen) = writeOperation.getBufs();
handle_->writeFromLoop(bufsPtr, bufsLen, [this](int status) {
this->writeCallbackFromLoop_(status);
});
}
void Connection::Impl::setId(std::string id) {
context_->deferToLoop(
[impl{shared_from_this()}, id{std::move(id)}]() mutable {
impl->setIdFromLoop_(std::move(id));
});
}
void Connection::Impl::setIdFromLoop_(std::string id) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(7) << "Connection " << id_ << " was renamed to " << id;
id_ = std::move(id);
}
void Connection::Impl::close() {
context_->deferToLoop(
[impl{shared_from_this()}]() { impl->closeFromLoop(); });
}
void Connection::Impl::closeFromLoop() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(7) << "Connection " << id_ << " is closing";
setError_(TP_CREATE_ERROR(ConnectionClosedError));
}
void Connection::Impl::allocCallbackFromLoop_(uv_buf_t* buf) {
TP_DCHECK(context_->inLoopThread());
TP_THROW_ASSERT_IF(readOperations_.empty());
TP_VLOG(9) << "Connection " << id_
<< " has incoming data for which it needs to provide a buffer";
readOperations_.front().allocFromLoop(buf);
}
void Connection::Impl::readCallbackFromLoop_(
ssize_t nread,
const uv_buf_t* buf) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(9) << "Connection " << id_ << " has completed reading some data ("
<< (nread >= 0 ? std::to_string(nread) + " bytes"
: formatUvError(nread))
<< ")";
if (nread < 0) {
setError_(TP_CREATE_ERROR(UVError, nread));
return;
}
TP_THROW_ASSERT_IF(readOperations_.empty());
auto& readOperation = readOperations_.front();
readOperation.readFromLoop(nread, buf);
if (readOperation.completeFromLoop()) {
readOperation.callbackFromLoop(Error::kSuccess);
// Remove the completed operation.
// If this was the final pending operation, this instance should
// no longer receive allocation and read callbacks.
readOperations_.pop_front();
if (readOperations_.empty()) {
handle_->readStopFromLoop();
}
}
}
void Connection::Impl::writeCallbackFromLoop_(int status) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(9) << "Connection " << id_ << " has completed a write request ("
<< formatUvError(status) << ")";
if (status < 0) {
setError_(TP_CREATE_ERROR(UVError, status));
// Do NOT return, because the error handler method will only fire the
// callbacks of the read operations, because we can only fire the callbacks
// of the write operations after their corresponding UV requests complete
// (or else the user may deallocate the buffers while the loop is still
// processing them), therefore we must fire the write operation callbacks in
// this method, both in case of success and of error.
}
TP_THROW_ASSERT_IF(writeOperations_.empty());
auto& writeOperation = writeOperations_.front();
writeOperation.callbackFromLoop(error_);
writeOperations_.pop_front();
}
void Connection::Impl::closeCallbackFromLoop_() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(9) << "Connection " << id_ << " has finished closing its handle";
TP_DCHECK(writeOperations_.empty());
leak_.reset();
}
void Connection::Impl::setError_(Error error) {
// Don't overwrite an error that's already set.
if (error_ || !error) {
return;
}
error_ = std::move(error);
handleError_();
}
void Connection::Impl::handleError_() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(8) << "Connection " << id_ << " is handling error " << error_.what();
for (auto& readOperation : readOperations_) {
readOperation.callbackFromLoop(error_);
}
readOperations_.clear();
// Do NOT fire the callbacks of the write operations, because we must wait for
// their corresponding UV write requests to complete (or else the user may
// deallocate the buffers while the loop is still processing them).
handle_->closeFromLoop();
}
Connection::Connection(
ConstructorToken /* unused */,
std::shared_ptr<Context::PrivateIface> context,
std::shared_ptr<TCPHandle> handle,
std::string id)
: impl_(std::make_shared<Impl>(
std::move(context),
std::move(handle),
std::move(id))) {
impl_->init();
}
Connection::Connection(
ConstructorToken /* unused */,
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id)
: impl_(std::make_shared<Impl>(
std::move(context),
std::move(addr),
std::move(id))) {
impl_->init();
}
void Connection::Impl::init() {
context_->deferToLoop([impl{shared_from_this()}]() { impl->initFromLoop(); });
}
void Connection::read(read_callback_fn fn) {
impl_->read(std::move(fn));
}
void Connection::Impl::read(read_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, fn{std::move(fn)}]() mutable {
impl->readFromLoop(std::move(fn));
});
}
void Connection::read(void* ptr, size_t length, read_callback_fn fn) {
impl_->read(ptr, length, std::move(fn));
}
void Connection::Impl::read(void* ptr, size_t length, read_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, ptr, length, fn{std::move(fn)}]() mutable {
impl->readFromLoop(ptr, length, std::move(fn));
});
}
void Connection::write(const void* ptr, size_t length, write_callback_fn fn) {
impl_->write(ptr, length, std::move(fn));
}
void Connection::Impl::write(
const void* ptr,
size_t length,
write_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, ptr, length, fn{std::move(fn)}]() mutable {
impl->writeFromLoop(ptr, length, std::move(fn));
});
}
void Connection::setId(std::string id) {
impl_->setId(std::move(id));
}
void Connection::close() {
impl_->close();
}
Connection::~Connection() {
close();
}
} // namespace uv
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/shm/listener.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include <tensorpipe/transport/listener.h>
#include <tensorpipe/transport/shm/context.h>
namespace tensorpipe {
namespace transport {
namespace shm {
class Context;
class Loop;
class Sockaddr;
class Listener final : public transport::Listener {
// Use the passkey idiom to allow make_shared to call what should be a private
// constructor. See https://abseil.io/tips/134 for more information.
struct ConstructorToken {};
public:
// Create a listener that listens on the specified address.
Listener(
ConstructorToken,
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id);
// Queue a callback to be called when a connection comes in.
void accept(accept_callback_fn fn) override;
// Obtain the listener's address.
address_t addr() const override;
// Tell the listener what its identifier is.
void setId(std::string id) override;
// Shut down the connection and its resources.
void close() override;
~Listener() override;
private:
class Impl;
// Using a shared_ptr allows us to detach the lifetime of the implementation
// from the public object's one and perform the destruction asynchronously.
std::shared_ptr<Impl> impl_;
// Allow context to access constructor token.
friend class Context;
};
} // namespace shm
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/uv/listener.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/uv/listener.h>
#include <tensorpipe/common/callback.h>
#include <tensorpipe/common/error_macros.h>
#include <tensorpipe/transport/uv/connection.h>
#include <tensorpipe/transport/uv/error.h>
#include <tensorpipe/transport/uv/loop.h>
#include <tensorpipe/transport/uv/sockaddr.h>
#include <tensorpipe/transport/uv/uv.h>
namespace tensorpipe {
namespace transport {
namespace uv {
class Listener::Impl : public std::enable_shared_from_this<Listener::Impl> {
public:
// Create a listener that listens on the specified address.
Impl(std::shared_ptr<Context::PrivateIface>, address_t, std::string);
// Initialize member fields that need `shared_from_this`.
void init();
// Queue a callback to be called when a connection comes in.
void accept(accept_callback_fn fn);
// Obtain the listener's address.
std::string addr() const;
// Tell the listener what its identifier is.
void setId(std::string id);
// Shut down the connection and its resources.
void close();
private:
// Initialize member fields that need `shared_from_this`.
void initFromLoop();
// Queue a callback to be called when a connection comes in.
void acceptFromLoop(accept_callback_fn fn);
// Obtain the listener's address.
std::string addrFromLoop() const;
void setIdFromLoop_(std::string id);
// Shut down the connection and its resources.
void closeFromLoop();
// Called by libuv if the listening socket can accept a new connection. Status
// is 0 in case of success, < 0 otherwise. See `uv_connection_cb` for more
// information.
void connectionCallbackFromLoop_(int status);
// Called when libuv has closed the handle.
void closeCallbackFromLoop_();
void setError_(Error error);
// Deal with an error.
void handleError_();
std::shared_ptr<Context::PrivateIface> context_;
std::shared_ptr<TCPHandle> handle_;
Sockaddr sockaddr_;
Error error_{Error::kSuccess};
ClosingReceiver closingReceiver_;
// Once an accept callback fires, it becomes disarmed and must be rearmed.
// Any firings that occur while the callback is disarmed are stashed and
// triggered as soon as it's rearmed. With libuv we don't have the ability
// to disable the lower-level callback when the user callback is disarmed.
// So we'll keep getting notified of new connections even if we don't know
// what to do with them and don't want them. Thus we must store them
// somewhere. This is what RearmableCallback is for.
RearmableCallback<const Error&, std::shared_ptr<Connection>> callback_;
// A sequence number for the calls to accept.
uint64_t nextConnectionBeingAccepted_{0};
// A sequence number for the invocations of the callbacks of accept.
uint64_t nextAcceptCallbackToCall_{0};
// An identifier for the listener, composed of the identifier for the context,
// combined with an increasing sequence number. It will be used as a prefix
// for the identifiers of connections. All of them will only be used for
// logging and debugging purposes.
std::string id_;
// Sequence numbers for the connections created by this listener, used to
// create their identifiers based off this listener's identifier. They will
// only be used for logging and debugging.
std::atomic<uint64_t> connectionCounter_{0};
// By having the instance store a shared_ptr to itself we create a reference
// cycle which will "leak" the instance. This allows us to detach its
// lifetime from the connection and sync it with the TCPHandle's life cycle.
std::shared_ptr<Impl> leak_;
};
Listener::Impl::Impl(
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id)
: context_(std::move(context)),
handle_(context_->createHandle()),
sockaddr_(Sockaddr::createInetSockAddr(addr)),
closingReceiver_(context_, context_->getClosingEmitter()),
id_(std::move(id)) {}
void Listener::Impl::initFromLoop() {
leak_ = shared_from_this();
closingReceiver_.activate(*this);
handle_->initFromLoop();
auto rv = handle_->bindFromLoop(sockaddr_);
TP_THROW_UV_IF(rv < 0, rv);
handle_->armCloseCallbackFromLoop(
[this]() { this->closeCallbackFromLoop_(); });
handle_->listenFromLoop(
[this](int status) { this->connectionCallbackFromLoop_(status); });
}
void Listener::Impl::acceptFromLoop(accept_callback_fn fn) {
TP_DCHECK(context_->inLoopThread());
uint64_t sequenceNumber = nextConnectionBeingAccepted_++;
TP_VLOG(7) << "Listener " << id_ << " received an accept request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](
const Error& error,
std::shared_ptr<transport::Connection> connection) {
TP_DCHECK_EQ(sequenceNumber, nextAcceptCallbackToCall_++);
TP_VLOG(7) << "Listener " << id_ << " is calling an accept callback (#"
<< sequenceNumber << ")";
fn(error, std::move(connection));
TP_VLOG(7) << "Listener " << id_ << " done calling an accept callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_, std::shared_ptr<Connection>());
return;
}
callback_.arm(std::move(fn));
}
std::string Listener::Impl::addrFromLoop() const {
TP_DCHECK(context_->inLoopThread());
return handle_->sockNameFromLoop().str();
}
void Listener::Impl::setId(std::string id) {
context_->deferToLoop(
[impl{shared_from_this()}, id{std::move(id)}]() mutable {
impl->setIdFromLoop_(std::move(id));
});
}
void Listener::Impl::setIdFromLoop_(std::string id) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(7) << "Listener " << id_ << " was renamed to " << id;
id_ = std::move(id);
}
void Listener::Impl::close() {
context_->deferToLoop(
[impl{shared_from_this()}]() { impl->closeFromLoop(); });
}
void Listener::Impl::closeFromLoop() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(7) << "Listener " << id_ << " is closing";
setError_(TP_CREATE_ERROR(ListenerClosedError));
}
void Listener::Impl::connectionCallbackFromLoop_(int status) {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(9) << "Listener " << id_
<< " has an incoming connection ready to be accepted ("
<< formatUvError(status) << ")";
if (status != 0) {
setError_(TP_CREATE_ERROR(UVError, status));
return;
}
auto connection = context_->createHandle();
connection->initFromLoop();
handle_->acceptFromLoop(connection);
std::string connectionId = id_ + ".c" + std::to_string(connectionCounter_++);
TP_VLOG(7) << "Listener " << id_ << " is opening connection " << connectionId;
callback_.trigger(
Error::kSuccess,
std::make_shared<Connection>(
Connection::ConstructorToken(),
context_,
std::move(connection),
std::move(connectionId)));
}
void Listener::Impl::closeCallbackFromLoop_() {
TP_VLOG(9) << "Listener " << id_ << " has finished closing its handle";
leak_.reset();
}
void Listener::Impl::setError_(Error error) {
// Don't overwrite an error that's already set.
if (error_ || !error) {
return;
}
error_ = std::move(error);
handleError_();
}
void Listener::Impl::handleError_() {
TP_DCHECK(context_->inLoopThread());
TP_VLOG(8) << "Listener " << id_ << " is handling error " << error_.what();
callback_.triggerAll([&]() {
return std::make_tuple(std::cref(error_), std::shared_ptr<Connection>());
});
handle_->closeFromLoop();
}
Listener::Listener(
ConstructorToken /* unused */,
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id)
: impl_(std::make_shared<Impl>(
std::move(context),
std::move(addr),
std::move(id))) {
impl_->init();
}
void Listener::Impl::init() {
context_->deferToLoop([impl{shared_from_this()}]() { impl->initFromLoop(); });
}
void Listener::accept(accept_callback_fn fn) {
impl_->accept(std::move(fn));
}
void Listener::Impl::accept(accept_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, fn{std::move(fn)}]() mutable {
impl->acceptFromLoop(std::move(fn));
});
}
address_t Listener::addr() const {
return impl_->addr();
}
address_t Listener::Impl::addr() const {
std::string addr;
context_->runInLoop([this, &addr]() { addr = addrFromLoop(); });
return addr;
}
void Listener::setId(std::string id) {
impl_->setId(std::move(id));
}
void Listener::close() {
impl_->close();
}
Listener::~Listener() {
close();
}
} // namespace uv
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/shm/reactor.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/shm/reactor.h>
#include <tensorpipe/common/system.h>
#include <tensorpipe/util/ringbuffer/shm.h>
namespace tensorpipe {
namespace transport {
namespace shm {
namespace {
void writeToken(util::ringbuffer::Producer& producer, Reactor::TToken token) {
for (;;) {
auto rv = producer.write(&token, sizeof(token));
if (rv == -EAGAIN) {
// There's contention on the spin-lock, wait for it by retrying.
std::this_thread::yield();
continue;
}
if (rv == -ENOSPC) {
// The ringbuffer is full. Retrying should typically work, but might lead
// to a deadlock if, for example, a reactor thread is trying to write a
// token to its own ringbuffer, as then it would be stuck here and never
// proceed to consume data from the ringbuffer. This could also happen
// across multiple processes. This case seems remote enough, and a proper
// solution rather complicated, that we're going to take that risk...
std::this_thread::yield();
continue;
}
TP_DCHECK_EQ(rv, sizeof(token));
break;
}
}
} // namespace
Reactor::Reactor() {
int headerFd;
int dataFd;
std::shared_ptr<util::ringbuffer::RingBuffer> rb;
std::tie(headerFd, dataFd, rb) = util::ringbuffer::shm::create(kSize);
headerFd_ = Fd(headerFd);
dataFd_ = Fd(dataFd);
consumer_.emplace(rb);
producer_.emplace(rb);
thread_ = std::thread(&Reactor::run, this);
}
void Reactor::close() {
if (!closed_.exchange(true)) {
// No need to wake up the reactor, since it is busy-waiting.
}
}
void Reactor::join() {
close();
if (!joined_.exchange(true)) {
thread_.join();
}
}
Reactor::~Reactor() {
join();
}
Reactor::TToken Reactor::add(TFunction fn) {
std::unique_lock<std::mutex> lock(mutex_);
TToken token;
// Either reuse a token or generate a new one.
auto it = reusableTokens_.begin();
if (it != reusableTokens_.end()) {
token = *it;
reusableTokens_.erase(it);
} else {
// If there are no reusable tokens, the next token is always equal
// to the number of tokens in use + 1.
token = functions_.size();
}
// Ensure there is enough space in the functions vector.
if (functions_.size() <= token) {
functions_.resize(token + 1);
}
functions_[token] = std::move(fn);
functionCount_++;
return token;
}
void Reactor::remove(TToken token) {
std::unique_lock<std::mutex> lock(mutex_);
functions_[token] = nullptr;
reusableTokens_.insert(token);
functionCount_--;
}
void Reactor::trigger(TToken token) {
std::unique_lock<std::mutex> lock(mutex_);
writeToken(producer_.value(), token);
}
std::tuple<int, int> Reactor::fds() const {
return std::make_tuple(headerFd_.fd(), dataFd_.fd());
}
void Reactor::run() {
setThreadName("TP_SHM_reactor");
// Stop when another thread has asked the reactor the close and when
// all functions have been removed.
while (!closed_ || functionCount_ > 0) {
uint32_t token;
auto ret = consumer_->copy(sizeof(token), &token);
if (ret == -ENODATA) {
if (deferredFunctionCount_ > 0) {
decltype(deferredFunctionList_) fns;
{
std::unique_lock<std::mutex> lock(deferredFunctionMutex_);
std::swap(fns, deferredFunctionList_);
}
deferredFunctionCount_ -= fns.size();
for (auto& fn : fns) {
fn();
}
} else {
std::this_thread::yield();
}
continue;
}
TFunction fn;
// Make copy of std::function so we don't need
// to hold the lock while executing it.
{
std::unique_lock<std::mutex> lock(mutex_);
TP_DCHECK_LT(token, functions_.size());
fn = functions_[token];
}
if (fn) {
fn();
}
}
// The loop is winding down and "handing over" control to the on demand loop.
// But it can only do so safely once there are no pending deferred functions,
// as otherwise those may risk never being executed.
while (true) {
decltype(deferredFunctionList_) fns;
{
std::unique_lock<std::mutex> lock(deferredFunctionMutex_);
if (deferredFunctionList_.empty()) {
isThreadConsumingDeferredFunctions_ = false;
break;
}
std::swap(fns, deferredFunctionList_);
}
for (auto& fn : fns) {
fn();
}
}
}
Reactor::Trigger::Trigger(Fd&& headerFd, Fd&& dataFd)
: producer_(util::ringbuffer::shm::load(
// The header and data segment objects take over ownership
// of file descriptors. Release them to avoid double close.
headerFd.release(),
dataFd.release())) {}
void Reactor::Trigger::run(TToken token) {
writeToken(producer_, token);
}
void Reactor::deferToLoop(TDeferredFunction fn) {
{
std::unique_lock<std::mutex> lock(deferredFunctionMutex_);
if (likely(isThreadConsumingDeferredFunctions_)) {
deferredFunctionList_.push_back(std::move(fn));
++deferredFunctionCount_;
// No need to wake up the reactor, since it is busy-waiting.
return;
}
}
// Must call it without holding the lock, as it could cause a reentrant call.
onDemandLoop_.deferToLoop(std::move(fn));
}
} // namespace shm
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/uv/listener.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include <tensorpipe/transport/defs.h>
#include <tensorpipe/transport/listener.h>
#include <tensorpipe/transport/uv/context.h>
namespace tensorpipe {
namespace transport {
namespace uv {
class Loop;
class Sockaddr;
class TCPHandle;
class Listener : public transport::Listener {
// Use the passkey idiom to allow make_shared to call what should be a private
// constructor. See https://abseil.io/tips/134 for more information.
struct ConstructorToken {};
public:
// Create a listener that listens on the specified address.
Listener(
ConstructorToken,
std::shared_ptr<Context::PrivateIface> context,
address_t addr,
std::string id);
// Queue a callback to be called when a connection comes in.
void accept(accept_callback_fn fn) override;
// Obtain the listener's address.
address_t addr() const override;
// Tell the listener what its identifier is.
void setId(std::string id) override;
// Shut down the connection and its resources.
void close() override;
~Listener() override;
private:
// All the logic resides in an "implementation" class. The lifetime of these
// objects is detached from the lifetime of the listener, and is instead
// attached to the lifetime of the underlying libuv handle. Any operation on
// these implementation objects must be performed from within the libuv event
// loop thread, thus all the listeners's operations do is schedule the
// equivalent call on the implementation by deferring to the loop.
class Impl;
// Using a shared_ptr allows us to detach the lifetime of the implementation
// from the public object's one and perform the destruction asynchronously.
std::shared_ptr<Impl> impl_;
// Allow context to access constructor token.
friend class Context;
};
} // namespace uv
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/test/util/ringbuffer/protobuf_streams_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <array>
#include <tensorpipe/proto/core.pb.h>
#include <tensorpipe/util/ringbuffer/consumer.h>
#include <tensorpipe/util/ringbuffer/producer.h>
#include <tensorpipe/util/ringbuffer/protobuf_streams.h>
#include <tensorpipe/util/ringbuffer/ringbuffer.h>
#include <google/protobuf/util/message_differencer.h>
#include <gtest/gtest.h>
using namespace tensorpipe;
using namespace tensorpipe::util::ringbuffer;
namespace {
std::shared_ptr<RingBuffer> makeRingBuffer(size_t size) {
auto header = std::make_shared<RingBufferHeader>(size);
// In C++20 use std::make_shared<uint8_t[]>(size)
auto data = std::shared_ptr<uint8_t>(
new uint8_t[header->kDataPoolByteSize], std::default_delete<uint8_t[]>());
return std::make_shared<RingBuffer>(std::move(header), std::move(data));
}
proto::Brochure getMessage() {
proto::Brochure message;
const std::map<std::string, std::string> ta_map = {{"foo", "bar"},
{"foobar", "baz"}};
for (const auto& e : ta_map) {
proto::TransportAdvertisement ta;
ta.set_domain_descriptor(e.second);
(*message.mutable_transport_advertisement())[e.first] = ta;
}
const std::map<std::string, std::string> ca_map = {{"foo2", "bar2"},
{"foobar2", "baz2"}};
for (const auto& e : ca_map) {
proto::ChannelAdvertisement ca;
ca.set_domain_descriptor(e.second);
(*message.mutable_channel_advertisement())[e.first] = ca;
}
return message;
}
void test_serialize_parse(
std::shared_ptr<RingBuffer> rb,
const proto::Brochure message) {
uint32_t len = message.ByteSize();
EXPECT_LE(len, rb->getHeader().kDataPoolByteSize)
<< "Message larger than ring buffer.";
{
Producer p{rb};
ssize_t ret = p.startTx();
EXPECT_EQ(ret, 0);
ZeroCopyOutputStream os(&p, len);
ASSERT_TRUE(message.SerializeToZeroCopyStream(&os));
ret = p.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), len);
}
proto::Brochure parsed_message;
{
Consumer c{rb};
ssize_t ret = c.startTx();
EXPECT_EQ(ret, 0);
ZeroCopyInputStream is(&c, len);
ASSERT_TRUE(parsed_message.ParseFromZeroCopyStream(&is));
ret = c.commitTx();
EXPECT_EQ(ret, 0);
EXPECT_EQ(rb->getHeader().usedSizeWeak(), 0);
}
ASSERT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
message, parsed_message));
}
} // namespace
TEST(RingBuffer, NonWrappingZeroCopyStream) {
constexpr size_t kBufferSize = 2 * 1024 * 1024;
auto rb = makeRingBuffer(kBufferSize);
proto::Brochure message = getMessage();
test_serialize_parse(rb, message);
}
TEST(RingBuffer, WrappingZeroCopyStream) {
constexpr size_t kBufferSize = 2 * 1024 * 1024;
auto rb = makeRingBuffer(kBufferSize);
// Write and consume enough bytes to force the next write to wrap around.
{
Producer p{rb};
std::array<char, kBufferSize - 1> garbage;
EXPECT_EQ(p.write(garbage.data(), sizeof(garbage)), sizeof(garbage));
}
{
Consumer c{rb};
std::array<char, kBufferSize - 1> buf;
EXPECT_EQ(c.copy(sizeof(buf), buf.data()), sizeof(buf));
}
proto::Brochure message = getMessage();
test_serialize_parse(rb, message);
}
<file_sep>/tensorpipe/test/transport/uv/context_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/test/transport/uv/uv_test.h>
#include <gtest/gtest.h>
namespace {
class UVTransportContextTest : public TransportTest {};
UVTransportTestHelper helper;
} // namespace
using namespace tensorpipe;
// Disabled because on CircleCI the macOS machines cannot resolve their hostname
TEST_P(UVTransportContextTest, DISABLED_LookupHostnameAddress) {
auto context = std::dynamic_pointer_cast<transport::uv::Context>(
GetParam()->getContext());
ASSERT_TRUE(context);
Error error;
std::string addr;
std::tie(error, addr) = context->lookupAddrForHostname();
EXPECT_FALSE(error) << error.what();
EXPECT_NE(addr, "");
}
// Disabled because "lo" isn't a universal convention for the loopback interface
TEST_P(UVTransportContextTest, DISABLED_LookupInterfaceAddress) {
auto context = std::dynamic_pointer_cast<transport::uv::Context>(
GetParam()->getContext());
ASSERT_TRUE(context);
Error error;
std::string addr;
std::tie(error, addr) = context->lookupAddrForIface("lo");
EXPECT_FALSE(error) << error.what();
EXPECT_NE(addr, "");
}
INSTANTIATE_TEST_CASE_P(Uv, UVTransportContextTest, ::testing::Values(&helper));
<file_sep>/tensorpipe/util/ringbuffer/protobuf_streams.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <tensorpipe/util/ringbuffer/consumer.h>
#include <tensorpipe/util/ringbuffer/producer.h>
#include <google/protobuf/io/zero_copy_stream.h>
namespace tensorpipe {
namespace util {
namespace ringbuffer {
class ZeroCopyInputStream : public google::protobuf::io::ZeroCopyInputStream {
public:
ZeroCopyInputStream(Consumer* buffer, size_t payloadSize)
: buffer_(buffer), payloadSize_(payloadSize) {}
bool Next(const void** data, int* size) override {
if (bytesCount_ == payloadSize_) {
return false;
}
std::tie(*size, *data) =
buffer_->readContiguousAtMostInTx(payloadSize_ - bytesCount_);
TP_THROW_SYSTEM_IF(*size < 0, -*size);
bytesCount_ += *size;
return true;
}
void BackUp(int /* unused */) override {
// This should never be called as we know the size upfront.
TP_THROW_ASSERT() << "BackUp() called from ZeroCopyInputStream";
}
bool Skip(int /* unused */) override {
// This should never be called as we know the size upfront.
TP_THROW_ASSERT() << "Skip() called from ZeroCopyInputStream";
return false;
}
int64_t ByteCount() const override {
return bytesCount_;
}
private:
Consumer* buffer_{nullptr};
const size_t payloadSize_{0};
int64_t bytesCount_{0};
};
class ZeroCopyOutputStream : public google::protobuf::io::ZeroCopyOutputStream {
public:
ZeroCopyOutputStream(Producer* buffer, size_t payloadSize)
: buffer_(buffer), payloadSize_(payloadSize) {}
bool Next(void** data, int* size) override {
std::tie(*size, *data) =
buffer_->reserveContiguousInTx(payloadSize_ - bytesCount_);
if (*size == -ENOSPC) {
return false;
}
TP_THROW_SYSTEM_IF(*size < 0, -*size);
bytesCount_ += *size;
return true;
}
void BackUp(int /* unused */) override {
// This should never be called as we know the size upfront.
TP_THROW_ASSERT() << "BackUp() called from ZeroCopyOutputStream";
}
int64_t ByteCount() const override {
return bytesCount_;
}
private:
Producer* buffer_{nullptr};
const size_t payloadSize_{0};
int64_t bytesCount_{0};
};
} // namespace ringbuffer
} // namespace util
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/uv/context.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/uv/context.h>
#include <tensorpipe/common/error_macros.h>
#include <tensorpipe/transport/registry.h>
#include <tensorpipe/transport/uv/connection.h>
#include <tensorpipe/transport/uv/error.h>
#include <tensorpipe/transport/uv/listener.h>
#include <tensorpipe/transport/uv/loop.h>
#include <tensorpipe/transport/uv/sockaddr.h>
#include <tensorpipe/transport/uv/uv.h>
namespace tensorpipe {
namespace transport {
namespace uv {
namespace {
std::shared_ptr<Context> makeUvContext() {
return std::make_shared<Context>();
}
TP_REGISTER_CREATOR(TensorpipeTransportRegistry, uv, makeUvContext);
// Prepend descriptor with transport name so it's easy to
// disambiguate descriptors when debugging.
const std::string kDomainDescriptorPrefix{"uv:"};
std::string generateDomainDescriptor() {
return kDomainDescriptorPrefix + "*";
}
} // namespace
class Context::Impl : public Context::PrivateIface,
public std::enable_shared_from_this<Context::Impl> {
public:
Impl();
const std::string& domainDescriptor() const;
std::shared_ptr<transport::Connection> connect(address_t addr);
std::shared_ptr<transport::Listener> listen(address_t addr);
std::tuple<Error, address_t> lookupAddrForIface(std::string iface);
std::tuple<Error, address_t> lookupAddrForHostname();
void setId(std::string id);
ClosingEmitter& getClosingEmitter() override;
bool inLoopThread() override;
void deferToLoop(std::function<void()> fn) override;
void runInLoop(std::function<void()> fn) override;
std::shared_ptr<TCPHandle> createHandle() override;
void close();
void join();
~Impl() override = default;
private:
Loop loop_;
std::atomic<bool> closed_{false};
std::atomic<bool> joined_{false};
ClosingEmitter closingEmitter_;
std::string domainDescriptor_;
// An identifier for the context, composed of the identifier for the context,
// combined with the transport's name. It will only be used for logging and
// debugging purposes.
std::string id_{"N/A"};
// Sequence numbers for the listeners and connections created by this context,
// used to create their identifiers based off this context's identifier. They
// will only be used for logging and debugging.
std::atomic<uint64_t> listenerCounter_{0};
std::atomic<uint64_t> connectionCounter_{0};
std::tuple<Error, address_t> lookupAddrForHostnameFromLoop_();
};
Context::Context() : impl_(std::make_shared<Impl>()) {}
Context::Impl::Impl() : domainDescriptor_(generateDomainDescriptor()) {}
void Context::close() {
impl_->close();
}
void Context::Impl::close() {
if (!closed_.exchange(true)) {
TP_VLOG(7) << "Transport context " << id_ << " is closing";
closingEmitter_.close();
loop_.close();
TP_VLOG(7) << "Transport context " << id_ << " done closing";
}
}
void Context::join() {
impl_->join();
}
void Context::Impl::join() {
close();
if (!joined_.exchange(true)) {
TP_VLOG(7) << "Transport context " << id_ << " is joining";
loop_.join();
TP_VLOG(7) << "Transport context " << id_ << " done joining";
}
}
Context::~Context() {
join();
}
std::shared_ptr<transport::Connection> Context::connect(address_t addr) {
return impl_->connect(std::move(addr));
}
std::shared_ptr<transport::Connection> Context::Impl::connect(address_t addr) {
std::string connectionId = id_ + ".c" + std::to_string(connectionCounter_++);
TP_VLOG(7) << "Transport context " << id_ << " is opening connection "
<< connectionId << " to address " << addr;
return std::make_shared<Connection>(
Connection::ConstructorToken(),
std::static_pointer_cast<PrivateIface>(shared_from_this()),
std::move(addr),
std::move(connectionId));
}
std::shared_ptr<transport::Listener> Context::listen(address_t addr) {
return impl_->listen(std::move(addr));
}
std::shared_ptr<transport::Listener> Context::Impl::listen(address_t addr) {
std::string listenerId = id_ + ".l" + std::to_string(listenerCounter_++);
TP_VLOG(7) << "Transport context " << id_ << " is opening listener "
<< listenerId << " on address " << addr;
return std::make_shared<Listener>(
Listener::ConstructorToken(),
std::static_pointer_cast<PrivateIface>(shared_from_this()),
std::move(addr),
std::move(listenerId));
}
const std::string& Context::domainDescriptor() const {
return impl_->domainDescriptor();
}
const std::string& Context::Impl::domainDescriptor() const {
return domainDescriptor_;
}
std::tuple<Error, address_t> Context::lookupAddrForIface(std::string iface) {
return impl_->lookupAddrForIface(std::move(iface));
}
std::tuple<Error, address_t> Context::Impl::lookupAddrForIface(
std::string iface) {
int rv;
InterfaceAddresses addresses;
int count;
std::tie(rv, addresses, count) = getInterfaceAddresses();
if (rv < 0) {
return std::make_tuple(TP_CREATE_ERROR(UVError, rv), std::string());
}
for (auto i = 0; i < count; i++) {
const uv_interface_address_t& interface = addresses[i];
if (iface != interface.name) {
continue;
}
const auto& address = interface.address;
const struct sockaddr* sockaddr =
reinterpret_cast<const struct sockaddr*>(&address);
switch (sockaddr->sa_family) {
case AF_INET:
return std::make_tuple(
Error::kSuccess,
Sockaddr(sockaddr, sizeof(address.address4)).str());
case AF_INET6:
return std::make_tuple(
Error::kSuccess,
Sockaddr(sockaddr, sizeof(address.address6)).str());
}
}
return std::make_tuple(TP_CREATE_ERROR(NoAddrFoundError), std::string());
}
std::tuple<Error, address_t> Context::lookupAddrForHostname() {
return impl_->lookupAddrForHostname();
}
std::tuple<Error, address_t> Context::Impl::lookupAddrForHostname() {
Error error;
std::string addr;
runInLoop([this, &error, &addr]() {
std::tie(error, addr) = lookupAddrForHostnameFromLoop_();
});
return std::make_tuple(std::move(error), std::move(addr));
}
std::tuple<Error, address_t> Context::Impl::lookupAddrForHostnameFromLoop_() {
int rv;
std::string hostname;
std::tie(rv, hostname) = getHostname();
if (rv < 0) {
return std::make_tuple(TP_CREATE_ERROR(UVError, rv), std::string());
}
Addrinfo info;
std::tie(rv, info) = getAddrinfoFromLoop(loop_, std::move(hostname));
if (rv < 0) {
return std::make_tuple(TP_CREATE_ERROR(UVError, rv), std::string());
}
Error error;
for (struct addrinfo* rp = info.get(); rp != nullptr; rp = rp->ai_next) {
TP_DCHECK(rp->ai_family == AF_INET || rp->ai_family == AF_INET6);
TP_DCHECK_EQ(rp->ai_socktype, SOCK_STREAM);
TP_DCHECK_EQ(rp->ai_protocol, IPPROTO_TCP);
Sockaddr addr = Sockaddr(rp->ai_addr, rp->ai_addrlen);
std::shared_ptr<TCPHandle> handle = createHandle();
handle->initFromLoop();
rv = handle->bindFromLoop(addr);
handle->closeFromLoop();
if (rv < 0) {
// Record the first binding error we encounter and return that in the end
// if no working address is found, in order to help with debugging.
if (!error) {
error = TP_CREATE_ERROR(UVError, rv);
}
continue;
}
return std::make_tuple(Error::kSuccess, addr.str());
}
if (error) {
return std::make_tuple(std::move(error), std::string());
} else {
return std::make_tuple(TP_CREATE_ERROR(NoAddrFoundError), std::string());
}
}
void Context::setId(std::string id) {
impl_->setId(std::move(id));
}
void Context::Impl::setId(std::string id) {
TP_VLOG(7) << "Transport context " << id_ << " was renamed to " << id;
id_ = std::move(id);
}
ClosingEmitter& Context::Impl::getClosingEmitter() {
return closingEmitter_;
};
bool Context::Impl::inLoopThread() {
return loop_.inLoopThread();
};
void Context::Impl::deferToLoop(std::function<void()> fn) {
loop_.deferToLoop(std::move(fn));
};
void Context::Impl::runInLoop(std::function<void()> fn) {
loop_.runInLoop(std::move(fn));
};
std::shared_ptr<TCPHandle> Context::Impl::createHandle() {
return TCPHandle::create(loop_);
};
} // namespace uv
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/channel/helpers.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
// Note: never include this file from headers!
#include <google/protobuf/message_lite.h>
#include <tensorpipe/channel/channel.h>
namespace tensorpipe {
namespace channel {
Channel::TDescriptor saveDescriptor(const google::protobuf::MessageLite& pb);
void loadDescriptor(
google::protobuf::MessageLite& pb,
const Channel::TDescriptor& in);
} // namespace channel
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/uv/loop.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#include <uv.h>
#include <tensorpipe/common/callback.h>
#include <tensorpipe/common/defs.h>
namespace tensorpipe {
namespace transport {
namespace uv {
class Loop final {
public:
Loop();
// Prefer using deferToLoop over runInLoop when you don't need to wait for the
// result.
template <typename F>
void runInLoop(F&& fn) {
// When called from the event loop thread itself (e.g., from a callback),
// deferring would cause a deadlock because the given callable can only be
// run when the loop is allowed to proceed. On the other hand, it means it
// is thread-safe to run it immediately. The danger here however is that it
// can lead to an inconsistent order between operations run from the event
// loop, from outside of it, and deferred.
if (std::this_thread::get_id() == thread_.get_id()) {
fn();
} else {
// Must use a copyable wrapper around std::promise because
// we use it from a std::function which must be copyable.
auto promise = std::make_shared<std::promise<void>>();
auto future = promise->get_future();
deferToLoop([promise, fn{std::forward<F>(fn)}]() {
try {
fn();
promise->set_value();
} catch (...) {
promise->set_exception(std::current_exception());
}
});
future.get();
}
}
void deferToLoop(std::function<void()> fn);
inline bool inLoopThread() {
{
std::unique_lock<std::mutex> lock(mutex_);
if (likely(isThreadConsumingDeferredFunctions_)) {
return std::this_thread::get_id() == thread_.get_id();
}
}
return onDemandLoop_.inLoop();
}
uv_loop_t* ptr() {
return loop_.get();
}
void close();
void join();
~Loop() noexcept;
private:
std::mutex mutex_;
std::thread thread_;
std::unique_ptr<uv_loop_t> loop_;
std::unique_ptr<uv_async_t> async_;
std::atomic<bool> closed_{false};
std::atomic<bool> joined_{false};
// Wake up the event loop.
void wakeup();
// Event loop thread entry function.
void loop();
// List of deferred functions to run when the loop is ready.
std::vector<std::function<void()>> fns_;
// Whether the thread is still taking care of running the deferred functions
//
// This is part of what can only be described as a hack. Sometimes, even when
// using the API as intended, objects try to defer tasks to the loop after
// that loop has been closed and joined. Since those tasks may be lambdas that
// captured shared_ptrs to the objects in their closures, this may lead to a
// reference cycle and thus a leak. Our hack is to have this flag to record
// when we can no longer defer tasks to the loop and in that case we just run
// those tasks inline. In order to keep ensuring the single-threadedness
// assumption of our model (which is what we rely on to be safe from race
// conditions) we use an on-demand loop.
bool isThreadConsumingDeferredFunctions_{true};
OnDemandLoop onDemandLoop_;
// This function is called by the event loop thread whenever
// we have to run a number of deferred functions.
static void uv__async_cb(uv_async_t* handle);
// Companion function to uv__async_cb as member function
// on the loop class.
void runFunctionsFromLoop();
};
} // namespace uv
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/transport/error.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <string>
#include <tensorpipe/common/error.h>
namespace tensorpipe {
namespace transport {
class SystemError final : public BaseError {
public:
explicit SystemError(const char* syscall, int error)
: syscall_(syscall), error_(error) {}
std::string what() const override;
private:
const char* syscall_;
const int error_;
};
class ShortReadError final : public BaseError {
public:
ShortReadError(ssize_t expected, ssize_t actual)
: expected_(expected), actual_(actual) {}
std::string what() const override;
private:
const ssize_t expected_;
const ssize_t actual_;
};
class ShortWriteError final : public BaseError {
public:
ShortWriteError(ssize_t expected, ssize_t actual)
: expected_(expected), actual_(actual) {}
std::string what() const override;
private:
const ssize_t expected_;
const ssize_t actual_;
};
class EOFError final : public BaseError {
public:
EOFError() {}
std::string what() const override;
};
class ListenerClosedError final : public BaseError {
public:
ListenerClosedError() {}
std::string what() const override;
};
class ConnectionClosedError final : public BaseError {
public:
ConnectionClosedError() {}
std::string what() const override;
};
} // namespace transport
} // namespace tensorpipe
<file_sep>/tensorpipe/test/proto/core_test.cc
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/proto/core.pb.h>
#include <gtest/gtest.h>
TEST(Proto, MessageDescriptor) {
tensorpipe::proto::MessageDescriptor::PayloadDescriptor d;
d.set_size_in_bytes(10);
EXPECT_EQ(d.size_in_bytes(), 10);
}
|
f64c775d551e88969fed6971eaecf85fd5b64faf
|
[
"C++"
] | 32 |
C++
|
terrorizer1980/tensorpipe
|
42033c5437fc9c181dc9d0a32df600484e2b0685
|
d65576c5083b28e47d8d17ea09808b0aaf293e38
|
refs/heads/master
|
<repo_name>gfx/ORM-APK-Size-Example<file_sep>/settings.gradle
include ':app', ':realmapp', ':ormaapp', ':requeryapp'
<file_sep>/build.gradle
buildscript {
repositories {
jcenter()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
classpath "gradle.plugin.com.vanniktech:gradle-android-apk-size-plugin:0.2.0"
classpath 'io.realm:realm-gradle-plugin:0.88.3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
<file_sep>/realmapp/src/main/java/com/github/gfx/android/realmapp/Item.java
package com.github.gfx.android.realmapp;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Item extends RealmObject {
@PrimaryKey
public long id;
}
<file_sep>/README.md
# ORM-APK-Size-Example
Simple apps + ORM libraries with proguard dead-code-elimination.
```
./gradlew assembleRelease -q
Total APK Size in app-release-unsigned.apk in bytes: 894466 # 874kb
Total APK Size in ormaapp-release-unsigned.apk in bytes: 1014550 # diff: 117kb
Total APK Size in realmapp-release-unsigned.apk in bytes: 4876247 # diff: 3888kb
Total APK Size in requeryapp-release-unsigned.apk in bytes: 938766 # diff: 43kb
```
* Orma v2.4.1
* Realm v0.88.3<file_sep>/ormaapp/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: "com.vanniktech.android.apk.size"
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.github.gfx.android.ormaapp"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
apt 'com.github.gfx.android.orma:orma-processor:2.4.1'
compile 'com.github.gfx.android.orma:orma:2.4.1'
}
|
f1a3b8f54e83b3629a87699961ac7022ec6fc33a
|
[
"Markdown",
"Java",
"Gradle"
] | 5 |
Gradle
|
gfx/ORM-APK-Size-Example
|
74e0da9370125d1e61c84ef5f2b29c4737af3d7c
|
83d77d6d2dda8da00e2db6db93369b580e2b33a0
|
refs/heads/master
|
<file_sep>from .curves import *
from .formulas import *
from .lex import *
<file_sep>from curve_analysis.osu_dump import *
from curve_analysis.curve_analysis import *
import numpy as np
from tqdm import tqdm, trange
# Converts sql scores db to 2d numpy table
def to_scores_table(sql_db):
cursor = sql_db.cursor(buffered=True)
cnt = 0
cursor.execute('select * from osu_scores_high')
scores_high = cursor.fetchall()
scores_np = np.empty((len(scores_high), len(scores_high[0])), dtype='uint32')
for i in range(len(scores_high)):
np_score = row_to_np(scores_high[i])
if np_score is not None:
scores_np[cnt] = np_score
cnt += 1
return scores_np[:cnt, :]
# Appends 3 columns to a standard scores_table:
# counts: Weighted accuracy score
# max_counts: Maximum possible accuracy score
# acc: Accuracy
def stack_acc_columns(scores_table):
# calculating accuracy statistics
max_counts = (scores_table[:, 6] + scores_table[:, 7] + scores_table[:, 8] + scores_table[:, 9]) * 300
counts = scores_table[:, 6] * 50 + scores_table[:, 7] * 100 + scores_table[:, 8] * 300
acc = ((counts / max_counts) * 1000000).astype('uint32')
# adding accuracy columns to table
return np.hstack((scores_table, np.column_stack((counts, max_counts, acc))))
# Computes all user's pp given a table of scores
# scores_lex: user_id, bm_id, pp, ...
def calc_user_pp(scores_lex):
score_iter = lex_iterator(scores_lex, 0)
num_users = len(score_iter) - 1
pp_table = np.empty((num_users, 2), dtype="uint32")
for i in trange(num_users):
low = score_iter[i]
high = score_iter[i + 1]
pp_table[i] = [int(scores_lex[low][0]), pp_rank(scores_lex, low, high)]
return pp_table
# Revises pp table from dump by replacing with recomputed user pp
# scores_lex: user_id, bm_id, pp, ...
# user_lex: user_id, rank_pp, ...
def revise_user_pp(scores_lex, user_lex):
user_iter = lex_iterator(user_lex, 0)
pp_dict = {}
for i in range(len(user_iter) - 1):
low = user_iter[i]
high = user_iter[i + 1]
pp_dict[int(user_lex[low][0])] = user_lex[high - 1][1]
print('- Recalculating user PP')
revised_pp_table = calc_user_pp(scores_lex)
revised_dict = {row[0]: row[1] for row in revised_pp_table}
# Filling in missing users from user_lex
print('- Replacing missing users from user_lex')
for user_id, pp in pp_dict.items():
if user_id not in revised_dict:
revised_dict[user_id] = pp
return np.array([[key, value] for key, value in revised_dict.items()], dtype='uint32')
def permit_save(subject, path, importance=None):
prefix = '({})'.format(importance) if importance is not None else ''
print('* {} Save {} in {}? [y/n]:'.format(prefix, subject, path), end=' ')
return input() == 'y'
if __name__ == '__main__':
print('CONNECTING TO SQL')
dump = OsuDB(SQL_DB_NAMES.remove('top_2020_04_01'))
print('\nCONSTRUCTING AGGREGATED SCORE TABLE')
print('- Converting ({}) dumps to numpy (This may take a while):'.format(len(dump.dbs)))
score_tables = []
for db in tqdm(dump.dbs):
score_tables.append(to_scores_table(db))
if permit_save('numpy-converted dumps', SCORES_PATH, 'RECOMMENDED'):
for i in range(len(score_tables)):
np.save(SCORES_PATH + dump.names[i] + '.npy', score_tables[i])
#
score_tables = []
for name in dump.names:
score_tables.append(np.load(SCORES_PATH + name + '.npy'))
print('- Combining score tables')
all_scores = np.vstack(tuple(score_tables))
print('- Appending columns: counts, max_counts, accuracy...')
all_scores = stack_acc_columns(all_scores)
if permit_save('aggregated score table', 'SCORES_PATH', 'REQUIRED'):
np.save(SCORES_PATH + 'all_scores.npy', all_scores)
print('\nREVISING USER PP VALUES')
user_stats = np.array(dump.fetch_all('osu_user_stats', ['user_id', 'rank_score']))
user_lex = lex(user_stats)
print('- Constructing scores_lex WITH [cols: user_id, bm_id, pp] FROM all_scores')
scores_lex = all_scores[:, [2, 1, -7]]
scores_lex = scores_lex.astype('float32')
scores_lex[:, 2] /= 1000000
scores_lex = lex(scores_lex)
u_pp = revise_user_pp(scores_lex, user_lex)
if permit_save('revised user pp table', 'DATA_PATH', 'REQUIRED'):
np.save(DATA_PATH + 'u_pp_revised.npy', u_pp)
<file_sep>
CREATE TABLE user_filter(user_id int(11) UNSIGNED PRIMARY KEY NOT NULL);
INSERT INTO user_filter SELECT user_id FROM osu_user_stats WHERE rank_score!=0;
INSERT IGNORE INTO osu_random.osu_beatmap_difficulty SELECT * FROM osu_beatmap_difficulty;
INSERT IGNORE INTO osu_random.osu_beatmap_difficulty_attribs SELECT * FROM osu_beatmap_difficulty_attribs;
INSERT IGNORE INTO osu_random.osu_beatmap_failtimes SELECT * FROM osu_beatmap_failtimes;
INSERT IGNORE INTO osu_random.osu_beatmaps SELECT * FROM osu_beatmaps;
-- if BPM is not in the dump :
-- INSERT IGNORE INTO osu_random.osu_beatmaps SELECT *,NULL FROM osu_beatmaps;
INSERT IGNORE INTO osu_random.osu_beatmapsets SELECT * FROM osu_beatmapsets;
INSERT IGNORE INTO osu_random.osu_scores_high SELECT A.* FROM osu_scores_high as A WHERE EXISTS (SELECT * FROM user_filter AS B WHERE A.user_id=B.user_id);
INSERT IGNORE INTO osu_random.osu_user_beatmap_playcount SELECT A.* FROM osu_user_beatmap_playcount as A WHERE EXISTS (SELECT * FROM user_filter AS B WHERE A.user_id=B.user_id);
INSERT IGNORE INTO osu_random.osu_user_stats SELECT A.* FROM osu_user_stats as A WHERE EXISTS (SELECT * FROM user_filter AS B WHERE A.user_id=B.user_id);
INSERT IGNORE INTO osu_random.sample_users SELECT A.* FROM sample_users as A WHERE EXISTS (SELECT * FROM user_filter AS B WHERE A.user_id=B.user_id);<file_sep>import numpy as np
# lex_table: user_id, bm_id, pp, ...
def pp_rank(lex_table, bound_low, bound_high):
unique_bms = 0
top_pps = []
for i in range(bound_low, bound_high):
if i == bound_high - 1 or lex_table[i][1] != lex_table[i + 1][1]:
top_pps.append(lex_table[i][2])
unique_bms += 1
top_pps.sort(reverse=True)
performance_score = 0
multiplier = 1
for i in range(min(len(top_pps), 100)):
performance_score += multiplier * top_pps[i]
multiplier *= .95
bonus_score = 416.6667 * (1 - (0.9994 ** unique_bms))
return performance_score + bonus_score
def sigmoid(x, a, b, k):
j = k * ((1 / (1 + np.exp(-(a * x + b)))) - (1 / (1 + np.exp(-b))))
return j
<file_sep>from .dump_compression import row_to_np
from .osu_db import *
<file_sep># Go ahead and replace db_names with how you named your dumps. Make sure it's in the same order
# Each dump should still start with osu_ ex. osu_random_2019_11_01
from curve_analysis.bin.config import *
import mysql.connector
from tqdm import tqdm
class OsuDB:
password = <PASSWORD>
host = SQL_HOST
user = SQL_USER
def __init__(self, names=None):
self.dbs = []
if names is None:
self.names = SQL_DB_NAMES
else:
self.names = names
for db_name in self.names:
self.dbs.append(self.connect_db('osu_' + db_name))
def connect_db(self, name):
return mysql.connector.connect(
host=self.host,
user=self.user,
passwd=<PASSWORD>,
database=name
)
# Creates a 'super' table by combining calls on OsuDB.fetch for all dbs
def fetch_all(self, table_name, columns=None):
ret = []
print('- Fetching {} from ({}) dumps'.format(columns, len(self.dbs)))
for db in tqdm(self.dbs):
table = OsuDB.fetch(db, table_name, columns)
ret.extend(table)
return ret
# Takes a subset of columns from a table in db
@staticmethod
def fetch(db, table_name, columns=None):
selection = '* '
if columns is not None:
selection = ''
for i in range(len(columns)):
selection += columns[i] + (', ' if i + 1 != len(columns) else ' ')
cur = db.cursor(buffered=True)
cur.execute('select ' + selection + 'from ' + table_name)
return cur.fetchall()
<file_sep>DELETE FROM osu_scores_high WHERE hidden!=0;
-- Saving the id of the scores we delete :
CREATE TABLE duplicate_scores(score_id int(9) UNSIGNED PRIMARY KEY NOT NULL);
INSERT INTO duplicate_scores SELECT A.score_id FROM osu_scores_high AS A WHERE EXISTS (
SELECT * FROM osu_scores_high AS B WHERE (
A.score_id!=B.score_id AND A.beatmap_id=B.beatmap_id AND A.enabled_mods=B.enabled_mods AND A.user_id=B.user_id
) AND (
A.score<B.score OR (A.score=B.score AND A.score_id<B.score_id)
)
);
-- Deleting the score
DELETE FROM osu_scores_high WHERE score_id IN (SELECT * FROM duplicate_scores);
-- Alternative :
-- DELETE FROM osu_scores_high WHERE score_id IN (
-- SELECT A.score_id FROM (SELECT * FROM osu_scores_high) AS A WHERE EXISTS (
-- SELECT * FROM (SELECT * FROM osu_scores_high) AS B WHERE (
-- A.score_id!=B.score_id AND A.beatmap_id=B.beatmap_id AND A.enabled_mods=B.enabled_mods AND A.user_id=B.user_id
-- ) AND (
-- A.score<B.score OR (A.score=B.score AND A.score_id<B.score_id))
-- )
-- );
<file_sep>'''
INSTRUCTIONS
1. Download dumps, and create a database for each in mysql
2. Replace sql information below, and set paths for storage (minimum 5 GB)
3. Run process_dump.py. REQUIRED files must be saved to continue
4. Run sandbox.py, then feel free to mess around
'''
# Information about your sql database
SQL_PASSWORD = "<PASSWORD>"
SQL_HOST = "localhost"
SQL_USER = "root"
SQL_DB_NAMES = ['random_2019_11_01', 'random_2019_12_01', 'random_2020_01_01', 'random_2020_02_01',
'random_2020_03_01', 'random_2020_04_01', 'top_2020_04_01'] # Replace with your own db names
# Path where you would like to store data on scores
SCORES_PATH = "./scores/"
# Path where you would like to store processed data
DATA_PATH = "./data/"
<file_sep>import numpy as np
import pandas as pd
from curve_analysis.curve_analysis.lex import lex_bounds
# Generates a list of (pp, score) data points from plays on a beatmap
# score_col: column in lex_table to be used as score
def bm_data(lex_table, user_lex, bm_id, score_col):
data = []
bm_bounds = lex_bounds(lex_table, [bm_id])
for i in range(bm_bounds[0], bm_bounds[1]):
play = lex_table[i]
user_ix = lex_bounds(user_lex, [play[1]])[0]
user_pp = user_lex[user_ix][1]
score = play[score_col]
data.append([user_pp, score])
data.sort(key=lambda x: x[0])
data = np.array(data)
return data
# Bin beatmap data points by non-overlapping pp ranges
def bin_by_pp(data, minimum, maximum, step):
bins = np.arange(minimum, maximum + step, step)
intervals = pd.cut(data[:, 0], bins)
ret = [[] for i in range(len(bins) - 1)]
for i in range(len(data)):
if str(intervals[i]) != 'nan':
ix = int(intervals[i].left / step)
ret[ix].append(data[i][1])
return ret, bins
# Efficiently computes proportion of successful plays (score > min_score) in each pp range
# Complexity - O(N + 2M) [N: len(data), M: len(pp_ranges)]
def proportion_curve(data, pp_ranges, min_score):
pp = data[:, 0]
scores = data[:, 1]
cuts = np.empty((len(pp_ranges) * 2, 2))
for i in range(len(pp_ranges)):
cuts[i * 2] = [pp_ranges[i][0], i]
cuts[i * 2 + 1] = [pp_ranges[i][1], - (i + 1)]
cuts = cuts[cuts[:, 0].argsort()]
cuts = np.vstack([cuts, [0, 0]])
ret = np.zeros((len(pp_ranges), 2))
starts = set()
score_i = 0
passes = 0
total = 0
for i in range(len(cuts) - 1):
range_i = int(cuts[i][1])
pp_next = cuts[i + 1][0]
if range_i < 0:
range_i = - (range_i + 1)
starts.remove(range_i)
ret[range_i] += [passes, total]
else:
starts.add(range_i)
ret[range_i] = -np.array([passes, total])
while score_i < len(pp) and pp[score_i] < pp_next:
if scores[score_i] >= min_score:
passes += 1
total += 1
score_i += 1
return ret
<file_sep>#!/bin/bash
# Change the utf8mb4_0900_ai_ci COLLATE in sql files to utf8mb4_general_ci, to make it compatible with MariaDB
sed -i -e 's/utf8mb4_0900_ai_ci/utf8mb4_general_ci/g' **/*.sql<file_sep># mlpp-playground
Messy repository that is used to try things up in the process of making MLpp
<file_sep>import numpy as np
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
# datetime to unix seconds
def unix_time_seconds(dt):
return (dt - epoch).total_seconds()
# converts osu score sql row into uint32 numpy
def row_to_np(sql_row):
try:
ret = np.asarray(sql_row)
ret[5] = ord(ret[5][0]) - ord('A') # score rank to numeric
ret[14] = unix_time_seconds(ret[14]) # datetime to unix seconds
country = ret[-1].decode() # from byte to country initials
ret[-1] = (ord(country[0]) - ord('A')) * 26 + ord(country[1]) - ord('A') # country to numeric
ret[-4] = ret[-4] * 1000000 # Keeping 6 decimal accuracy of float pp by storing pp * 10^6
return ret.astype('uint32')
except:
return None # row format didn't match
<file_sep>from curve_analysis.curve_analysis import *
from curve_analysis.osu_dump import OsuDB
from curve_analysis.bin.config import DATA_PATH, SCORES_PATH
import numpy as np
import matplotlib.pyplot as plt
from pygam import PoissonGAM, LinearGAM, s, f
from scipy.optimize import curve_fit
if __name__ == '__main__':
dump = OsuDB()
print('EXTRACTING FROM DATA SETS')
beatmaps = lex(np.array(dump.fetch_all('osu_beatmaps', ['beatmap_id', 'difficultyrating'])))
print('- Generating lex tables for user scores & user pp')
all_scores = np.load(SCORES_PATH + 'all_scores.npy')
u_pp_lex = lex(np.load(DATA_PATH + 'u_pp_revised.npy'))
acc_scores = all_scores[:, [-9, 1, 2, -1]] # cols: mods, bm_id, user_id, acc
acc_scores = lex(acc_scores)
print('- Subsetting NM scores')
acc_scores_subset = np.concatenate((lex_2d(lex_bounds(acc_scores, [0], get="all")),
lex_2d(lex_bounds(acc_scores, [1], get="all"))), axis=0)
acc_scores_subset = acc_scores_subset[:, 1:4]
acc_scores_subset = acc_scores_subset.astype('float32')
acc_scores_subset[:, 2] /= 1000000 # converting pp * 10^6 back to float pp
acc_scores_subset = lex(acc_scores_subset)
print('- Finding beatmaps w/ most samples')
bm_samples = freq_keys(acc_scores_subset)[:100]
N = 1000
x = np.arange(0, 16000 - N)
print('\nPLOTTING BEATMAPS')
for bm_id in bm_samples[:10, 0]:
stars = lex_bounds(beatmaps, [bm_id], get="one")[1]
ranges = [[i, i + N] for i in range(0, 16000 - N)]
data = bm_data(acc_scores_subset, u_pp_lex, bm_id, 2)
prop_curve = proportion_curve(data, ranges, .95)
plt.figure(figsize=(15, 6))
plt.plot(np.arange(0, 16000 - N), prop_curve[:, 1])
plt.show(block=False)
prop_curve[prop_curve[:, 1] == 0] = -1
props = prop_curve[:, 0] / prop_curve[:, 1]
props = np.column_stack((x, props))
props = props[prop_curve[:, 1] > 20].T
plt.figure(figsize=(15, 6))
plt.plot(props[0], props[1])
# Choose a curve fitting method (Sigmoid only works on > 5* maps):
# Curve fitting with pyGAM
gam = LinearGAM(s(0, n_splines=13, constraints='monotonic_inc')).fit(props[0], props[1])
plt.plot(x, gam.predict(x))
# Curve fitting with sigmoid
# popt, pcov = curve_fit(sigmoid, props[0], props[1], p0=[-.001, 1, -1])
# a, b, k = popt
# median = - b / a
# plt.plot(x, sigmoid(x, *popt))
# print('{} - Median: {}'.format(int(bm_id), median))
plt.xlabel('Total PP')
plt.ylabel('% Players')
plt.title('{} ({:.1f}*): Proportion of players w/ 90% acc'.format(int(bm_id), stars))
plt.show()
<file_sep>import numpy as np
"""
Make sure you understand this section well, otherwise you won't be able to efficiently access the
score data from the numpy files generated. The idea is to lexicographically sort
the rows of the numpy scores table like how a dictionary works. This enables quick lookups
for specific subsets or single scores.
"""
# converts 2d table to lex table (1d array of sortable tuples, with each tuple being a score)
def lex(np_table):
data = np_table[np.lexsort(np.rot90(np_table, 1))]
dt = [('', data.dtype) for i in range(data.shape[1])]
return np.ascontiguousarray(data).view(dt).squeeze(-1)
# reverts from lex table to 2d table
def lex_2d(lex_table):
return lex_table.view(dtype=lex_table.dtype[0]).reshape(-1, len(lex_table.dtype))
# Lexicographic binary searches a subset of rows from a lex table
# get = 'all': copies all rows in subset to a new lex table
# get = 'one': returns first row in subset
def lex_bounds(lex_table, dmin, dmax=None, get=None):
if dmax is None:
dmax = dmin.copy()
dmax[-1] += 1
cols = len(lex_table[0])
low = np.zeros((cols,))
low[:len(dmin)] = dmin
high = np.zeros((cols,))
high[:len(dmax)] = dmax
low = np.searchsorted(lex_table, np.array(tuple(low), lex_table.dtype))
high = np.searchsorted(lex_table, np.array(tuple(high), lex_table.dtype))
if get:
if lex_2d(lex_table[low:low + 1])[0, 0:len(dmin)] == dmin:
if get == "all":
return lex_table[low:high]
elif get == "one":
return lex_table[low]
else:
return low, high
return None
# Iterates across all unique keys in column (col) of a lex table
def lex_iterator(lex_table, col):
ret = []
i = 0
while i != lex_table.shape[0]:
bound_low, bound_high = lex_bounds(lex_table, [lex_table[i][col]])
ret.append(bound_low)
i = bound_high
ret.append(lex_table.shape[0])
return np.array(ret)
# Returns unique keys in first column of lex table, sorted by frequency
def freq_keys(lex_table):
score_iterator = lex_iterator(lex_table, 0)
ret = np.zeros((len(score_iterator) - 1, 2))
for i in range(len(ret)):
low = score_iterator[i]
high = score_iterator[i + 1]
ret[i] = [lex_table[int(low)][0], high - low]
return ret[ret[:, 1].argsort()[::-1]]
|
bca538f157696abd19aedb43316cc0c051a8ab35
|
[
"Markdown",
"SQL",
"Python",
"Shell"
] | 14 |
Python
|
osu-mlpp/mlpp-playground
|
56439a6da2739b19b0b9820443d1eed58c7989f8
|
8de9d6dd7dc820dea6a8baa965e5f2cc7625b8b3
|
refs/heads/master
|
<repo_name>nicolehappy/kaggle<file_sep>/Python-Graph.py
import pandas as pd
from pandas import Series, DataFrame
import pylab
pylab.show()
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
## machine learning
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
train = pd.read_csv('./kaggle/train.csv')
test = pd.read_csv('./kaggle/test.csv')
### Embarked cities
train['Embarked'] = train['Embarked'].fillna('S')
#### plot
sns.factorplot('Embarked', 'Survived',kind ='point', color = 'red', data = train, size = 4, aspect = 3)
pclass = sns.factorplot(x = 'Sex', y = 'Survived', col = 'Pclass',
data = train, saturation = .5, kind = 'bar', ci = None, aspect = .6)
sns.barplot(x="Sex", y="Survived", hue="Pclass", data=train)
#sns.pointplot(x="Pclass", y="Survived", hue="Sex", data=train,
palette={"male": "g", "female": "m"},)
pylab.show()
#### References
#### https://stanford.edu/~mwaskom/software/seaborn/tutorial/categorical.html<file_sep>/DataCleaning.R
library(plyr)
library(foreign)
train <- read.csv('./train.csv', stringsAsFactors = FALSE)
test <- read.csv('./test.csv', stringsAsFactors = FALSE)
# Create Survived column in Test
test$Survived <- 0
#Convert cateogrical Varaibles to factors
train$Survived <- factor(train$Survived)
train$Sex <- factor(train$Sex)
train$Pclass <- factor(train$Pclass)
test$Survived <- factor(test$Survived)
test$Sex <- factor(test$Sex)
test$Pclass <- factor(test$Pclass)
test$Embarked <- factor(test$Embarked)
# Fixing missing values
# combining the data sets for age/fate modeling
full <- join(test, train, type = 'full')
# Create LM models for predicting missing values in Age and Fare
age.mod <- lm(Age ~ Pclass + Sex + SibSp + Parch + Fare, data = full)
fare.mod <- lm(Fare ~ Pclass + Sex + SibSp + Parch + Age, data =full)
# Replacing missing values in Age and Fare with prediction
train$Age[is.na(train$Age)] <- predict(age.mod, train)[is.na(train$Age)]
test$Age[is.na(test$Age)] <- predict(age.mod, test)[is.na(test$Age)]
test$Fare[is.na(test$Fare)] <- predict(fare.mod, test)[is.na(test$Fare)]
# Replace missing values in Embarekd with most popular
train$Embarked[train$Embarked == ''] <-'S'
train$Embarked <- factor(train$Embarked)
###### Create 'Sex.name" variable
library(stringr)
train$sex.name <- 0
test$sex.name <- 0
train$sex.name[!is.na(str_extract(train$Name, "Mr"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Mrs"))] <- "Mrs"
train$sex.name[!is.na(str_extract(train$Name, "Mme"))] <- "Mrs"
train$sex.name[!is.na(str_extract(train$Name, "Miss"))] <- "Miss"
train$sex.name[!is.na(str_extract(train$Name, "Ms"))] <- "Miss"
train$sex.name[!is.na(str_extract(train$Name, "Mlle"))] <- "Miss"
train$sex.name[!is.na(str_extract(train$Name, "Capt"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Major"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Col"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Master"))] <- "Mast"
train$sex.name[!is.na(str_extract(train$Name, "Rev"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Dr"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Don"))] <- "Mr"
train$sex.name[!is.na(str_extract(train$Name, "Countess"))] <- "Mrs"
train$sex.name[!is.na(str_extract(train$Name, "Jonkheer"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Mr"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Mrs"))] <- "Mrs"
test$sex.name[!is.na(str_extract(test$Name, "Mme"))] <- "Mrs"
test$sex.name[!is.na(str_extract(test$Name, "Miss"))] <- "Miss"
test$sex.name[!is.na(str_extract(test$Name, "Ms"))] <- "Miss"
test$sex.name[!is.na(str_extract(test$Name, "Mlle"))] <- "Miss"
test$sex.name[!is.na(str_extract(test$Name, "Capt"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Major"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Col"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Master"))] <- "Mast"
test$sex.name[!is.na(str_extract(test$Name, "Rev"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Dr"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Don"))] <- "Mr"
test$sex.name[!is.na(str_extract(test$Name, "Countess"))] <- "Mrs"
test$sex.name[!is.na(str_extract(test$Name, "Jonkheer"))] <- "Mr"
test$Name[test$sex.name == 0]
train$Name[train$sex.name == 0]
train$sex.name <- factor(train$sex.name)
test$sex.name <- factor(test$sex.name)
# Create 'Fare Distance ' varaibel
# Find the mean fare for each Pclass
class1 <- subset(full, Pclass == 1)
class2 <- subset(full, Pclass == 2)
class3 <- subset(full, Pclass == 3)
fare1 <- mean(class1$Fare, na.rm = TRUE)
fare2 <- mean(class2$Fare, na.rm = TRUE)
fare3 <- mean(class3$Fare, na.rm = TRUE)
# Create fare_Avg column
train$fare_avg[train$Pclass == 1] <- fare1
train$fare_avg[train$Pclass == 2] <- fare2
train$fare_avg[train$Pclass == 3] <- fare3
test$fare_avg[test$Pclass == 1] <- fare1
test$fare_avg[test$Pclass == 2] <- fare2
test$fare_avg[test$Pclass == 3] <- fare3
# Create fare-distance metric for trian
train <- transform(train, fare.distance = Fare - fare_avg)
train <- train[, !names(train) %in% c("fare_avg")]
# Create fare-distance metric for Test
test <- transform(test, fare.distance = Fare - fare_avg)
test <- test[, !names(test) %in% c("fare_avg")]
### Add family column
train$family <- NA
test$family <- NA
train$family[which(train$SibSp != 0 | train$Parch != 0)] <- 1
train$family[which(train$SibSp == 0 & train$Parch == 0)] <- 0
test$family[which(test$SibSp != 0 | test$Parch != 0)] <- 1
test$family[which(test$SibSp == 0 & test$Parch == 0)] <- 0
test$family <- factor(test$family)
train$family <- factor(train$family)
test$familySize <- test$SibSp + test$Parch + 1
train$familySize <- train$SibSp + train$Parch + 1
### Scale the non factors
train$age_scale <- (train$Age-min(train$Age)) / (max(train$Age - min(train$Age)))
train$fare_scale <- (train$Fare - min(train$Fare)) / (max(train$Fare - min(train$Fare)))
test$age_scale <- (test$Age-min(test$Age)) / (max(test$Age - min(test$Age)))
test$fare_scale <- (test$Fare-min(test$Fare)) / (max(test$Fare - min(test$Fare)))
# Saving the new Data Sets
# save files as RData in order to preserve data structures
# open .RDdata with load()
save("test", file = "./Data/test_clean.RData")
save("train", file = "./Data/train_clean.RData")
# save the empty age data
save('test', file = './Data/test_clean_age.RData')
save('train', file = './Data/train_clean_age.RData')
# Save as ARFF for WEKA using foreign
write.arff(test, file = "./Data/test_clean.ARFF")
write.arff(train, file = "./Data/train_clean.ARFF")
# Also save .csv's just in case. These do not preserve data structures,
# so don't use them in the analysis!
write.csv(test, "./Data/CSV/test_clean.csv", row.names = FALSE)
write.csv(train, "./Data/CSV/train_clean.csv", row.names = FALSE)
write.csv(full, './Data/CSV/full.csv', row.names = FALSE)
|
881891331a75c1f36ead7495a386f8705ba4f189
|
[
"Python",
"R"
] | 2 |
Python
|
nicolehappy/kaggle
|
eea994adc34caa94ed7e7b75b339fb4f491ec924
|
5fbb2619dcffed37d64afe76644a95ac6a8aed20
|
refs/heads/master
|
<file_sep> // Funciones
function mostrar_emp(i){
$.ajax({
type:"POST",
url:"datos_empresa.php",
success:function(r){
$(i).html(r);
}
});
}
function mostrar_emp2(i){
$.ajax({
type:"POST",
url:"datos_empresa_2.php",
success:function(r){
$(i).html(r);
}
});
}
// Funcion que Limpia cualquier cantidad de Elementos
function limpiar(...elementos){
for (let elemento of elementos) {
$(elemento).val("");
}
}
function ir_a_menuCFT(){
//window.location="menu_CFT.php";
alert("Hola");
}
function get_fecha(){
var meses = new Array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
var f=new Date();
var fecha = f.getDate() + " de " + meses[f.getMonth()] + " de " + f.getFullYear();
return fecha;
}
function get_hora(){
var h=new Date();
var hora = h.getHours()+ ':'+ h.getMinutes();
return hora;
}
|
c82b8eb5fdf50d238acff3d34caaaf28e9b31f6a
|
[
"JavaScript"
] | 1 |
JavaScript
|
Zjavier29/login
|
7e2c12b6bf248a6bc5a3fb162dc84e7381e53bce
|
66fea8280ab1fa93bb36d40840a7db6da2d51cd7
|
refs/heads/master
|
<file_sep><?php
namespace DevStrefa\Esemeser;
/**
* MessageType class
*
* MessageType class is helper class in library, it contains constants for message Types and static function for validation type
*
* @license https://opensource.org/licenses/MIT MIT
* @author Cichy <<EMAIL>>
* @version 1.1.0
*
*/
class MessageType
{
const ECO='eco';
const STANDARD='standard';
const PLUS='plus';
const PLUS2='plus2';
/**
* @param string $type Message type
* @return bool
*/
public static function typeIsValid($type)
{
if (!in_array($type,array(self::ECO,self::PLUS,self::PLUS2,self::STANDARD)) && $type !== null){
return false;
}
return true;
}
}<file_sep><?php
namespace DevStrefa\Esemeser;
/**
* Message class
*
* Message class is simple class to store basic message information such as phone number, content and name of recipient
*
* @license https://opensource.org/licenses/MIT MIT
* @author Cichy <<EMAIL>>
* @version 1.1.0
*
*/
class Message
{
private $clientName;
private $phoneNumber;
private $message;
private $messageType;
/**
* Message constructor.
*
* @param string $clientName Client name
* @param string $phoneNumber Recipient phone number
* @param string $message Message content
* @param string $messageType Message type
*/
public function __construct($clientName=null,$phoneNumber=null,$message=null,$messageType=null)
{
if ($clientName!=null){
$this->setClientName($clientName);
}
if ($phoneNumber!=null){
$this->setPhoneNumber($phoneNumber);
}
if ($message!=null){
$this->setMessage($message);
}
if ($messageType!=null){
$this->setMessageType($messageType);
}
}
/**
* @param string $clientName
* @return Message
*/
public function setClientName($clientName)
{
$this->clientName = $clientName;
return $this;
}
/**
* @param string $phoneNumber
* @return Message
*/
public function setPhoneNumber($phoneNumber)
{
if (preg_match('/^[0-9]{9}$/',$phoneNumber)){
$this->phoneNumber = $phoneNumber;
return $this;
}
throw new \InvalidArgumentException('Incorrect Phone Number');
}
/**
* @param string $message
* @return Message
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* @param string $messageType
* @return Message
*/
public function setMessageType($messageType)
{
if (!MessageType::typeIsValid($messageType)){
throw new \InvalidArgumentException('Incorrect Message Type');
}
$this->messageType = $messageType;
return $this;
}
/**
* @return mixed
*/
public function getClientName()
{
return $this->clientName;
}
/**
* @return mixed
*/
public function getPhoneNumber()
{
return $this->phoneNumber;
}
/**
* @return mixed
*/
public function getMessage()
{
return $this->message;
}
/**
* @return mixed
*/
public function getMessageType()
{
return $this->messageType;
}
}<file_sep><?php
namespace DevStrefa\Esemeser;
/**
* Library main class
*
* Esemeser is a simple library for sending Mobile Text messages through esemeser.pl official API
*
* @license https://opensource.org/licenses/MIT MIT
* @author Cichy <<EMAIL>>
* @version 1.1.0
*
*/
class Esemeser
{
/**
* @var string Sending messages API endpoint
*/
const SEND_URL='https://esemeser.pl/0api/wyslij.php';
/**
* @var string Checking balance API endpoint
*/
const CHECK_URL='https://esemeser.pl/0api/sprawdz.php';
private $account;
private $login;
private $password;
private $requestMethod;
/**
* Class Constructor
*
* @param string $account Account name
* @param string $login Account login
* @param string $password Account password
*/
public function __construct($account=null,$login=null,$password=null)
{
if ($account != null){
$this->setAccount($account);
}
if ($login!=null){
$this->setLogin($login);
}
if ($password!=null){
$this->setPassword($password);
}
//default request method is set to file_get_contents
$this->requestMethod='fgc';
}
/**
* Set mechanism used to make requests to API (Allowed values: fgc OR curl) file_get_contents is default
*
* @param $requestMethod
* @throws \InvalidArgumentException *Exception is thrown when invalud request method is provided as argument*
*/
public function setRequestMethod($requestMethod){
if ($requestMethod != 'fgc' && $requestMethod !='curl'){
throw new \InvalidArgumentException('Invalid Request Method');
}
}
/**
* @param string $url
* @return mixed | string
*/
private function makeRequest($url)
{
if ($this->requestMethod == 'fgc'){
return file_get_contents($url);
} elseif ($this->requestMethod == 'curl'){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
return curl_exec($curl);
}
}
/**
* Method returns number of possible to send messages of given type
*
* @param string $messageType Type of message
* @return int Number of messages possible to send
* @throws \InvalidArgumentException *Exception is thrown when provided type is incorrect*
* @throws \Exception *Exception is thrown when library wasn't able to get number of messages (ie. credentials was wrong)*
*/
public function checkBalance($messageType=null)
{
$query=array(
'konto'=>$this->getAccount(),
'login'=>$this->getLogin(),
'haslo'=>$this->getPassword()
);
if ($messageType!==null){
if (MessageType::typeIsValid($messageType)) {
$query['rodzaj'] =$messageType;
} else{
throw new \InvalidArgumentException('Incorrect Message Type');
}
}
$queryString=http_build_query($query);
$result=$this->makeRequest(self::CHECK_URL.'?'.$queryString);
if ($result < 0){
switch ($result){
case '-1':
throw new \Exception('Incorrect Account name');
break;
case '-2':
throw new \Exception('Incorrect login or password');
break;
default:
throw new \Exception('Unknown Error');
break;
}
} else {
return $result;
}
}
/**
* Method will send given message
*
* @param Message $message instance of message object
* @return bool Function return **true** if message was sent
* @throws \Exception *Exception is thrown when message wasn't send*
*/
public function send(Message $message)
{
$query=array(
'konto'=>$this->getAccount(),
'login'=>$this->getLogin(),
'haslo'=>$this->getPassword(),
'nazwa'=>$message->getClientName(),
'telefon'=>$message->getPhoneNumber(),
'tresc'=>$message->getMessage()
);
if ($message->getMessageType() !== null){
$query['rodzaj']=$message->getMessageType();
}
$queryString=http_build_query($query);
$result=$this->makeRequest(self::SEND_URL.'?'.$queryString);
if ($result !='OK'){
switch ($result){
case '-1':
throw new \Exception('Incorrect Account name');
break;
case '-2':
throw new \Exception('Incorrect login or password');
break;
case '-3':
throw new \Exception('Incorrect phone number');
break;
case 'NIE':
throw new \Exception('Message wasn\'t sent');
break;
default:
throw new \Exception('Unknown Error');
break;
}
} else {
return true;
}
}
/**
* Method returns account name
* @return string
*/
public function getAccount()
{
return $this->account;
}
/**
* Method for setting account name
* @param string $account Account name
* @return Esemeser
*/
public function setAccount($account)
{
$this->account = $account;
return $this;
}
/**
* Method returns account login
* @return string
*/
public function getLogin()
{
return $this->login;
}
/**
* Method for setting login to account
* @param string $login
* @return Esemeser
*/
public function setLogin($login)
{
$this->login = $login;
return $this;
}
/**
* Method return password
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Method for setting password to account
* @param string $password
* @return Esemeser
*/
public function setPassword($password)
{
$this->password = $<PASSWORD>;
return $this;
}
}<file_sep># Esemeser 1.1.0
PHP Library designed to sending SMS messages through esemeser.pl API
### Before you use it!
Esemeser.pl is a Polish service for sending SMS messages, so remember that You can send messages only to Polish phone numbers
those numbers must be in format: xxxxxxxxx (9 digits), other numbers probably will not work.
This library is using [file_get_contents](http://php.net/manual/en/function.file-get-contents.php) as default mechanism to send requests, so before You start using it, make sure you have properly configured environment. Check if your [allow_url_fopen](http://php.net/manual/en/filesystem.configuration.php) is set to "1". You can use [CURL](http://php.net/manual/en/book.curl.php) instead of [file_get_contents](http://php.net/manual/en/function.file-get-contents.php) please read below to get more information.
### How to install
Library is compatible with [composer](https://getcomposer.org/) so You can install it by adding:
```code
"require": {
"devstrefa/esemeser": "1.0.x-dev"
}
```
to Your composer.json file
You can also download zip file and include all necessary files by yourself
### How to use
Library is designed for 2 main tasks:
**1. Sending Messages**
Below you can see example of code sending some message:
```php
<?php
use DevStrefa\Esemeser\Esemeser;
use DevStrefa\Esemeser\Message;
use DevStrefa\Esemeser\MessageType;
require_once ('../vendor/autoload.php');
try {
$esemeser = new Esemeser();
$esemeser->setLogin('login')->setAccount('account_name')->setPassword('<PASSWORD>');
$message = new Message();
$message->setClientName('client_name')->setPhoneNumber('123456789')->setMessage('test')->setMessageType(MessageType::ECO);
$esemeser->send($message);
} catch (\Exception $e){
var_dump($e);
}
```
**2. Checking Balance**
Second function of library is checking how many messages of given type You can still send with Your current balance. To do this use library like in code below:
```php
<?php
use DevStrefa\Esemeser\Esemeser;
use DevStrefa\Esemeser\MessageType;
require_once ('../vendor/autoload.php');
try {
$esemeser = new Esemeser();
$esemeser->setLogin('login')->setAccount('account_name')->setPassword('<PASSWORD>');
$balance=$esemeser->checkBalance(MessageType::ECO);
echo $balance;
} catch (\Exception $e){
var_dump($e);
}
```
### How to use CURL instead of file_get_contents
Since version 1.1.0 of library, You can choose mechanism which is used to make requests to API, if you want to do this add this line to Your code:
```php
$esemeser->setRequestMethod('fgc');
```
available values for setRequestMethod are:
* ***fgc*** - for file_get_contents
* ***curl*** - for curl library
For more information about library please read generated [documentation](http://devstrefa.github.io/esemeserDoc/).
## Changelog
You can see Changelog for this project [here](https://github.com/DevStrefa/esemeser/blob/master/CHANGELOG.md)
### License
Whole code in this repository is Under [MIT license](https://github.com/DevStrefa/esemeser/blob/master/LICENSE)<file_sep>## 1.1.0 (05.09.2016)
Added support for CURL
## 1.0.0 (15.08.2016)
Initial release of library.
|
03fc20a1d4dec3bf68f0d83b213bcdd6eea5dfb2
|
[
"Markdown",
"PHP"
] | 5 |
PHP
|
DevStrefa/esemeser
|
e216ddd6579b266d325ff54cde0b57ec98817402
|
6c48b4e55da9f25728470afafea5dab94e1e6976
|
refs/heads/master
|
<file_sep>package com.phuong.demoroomdatabase.activity;
public class AddStory {
}
<file_sep>package com.phuong.demoroomdatabase.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import com.phuong.demoroomdatabase.model.Topic;
import java.util.List;
@Dao
public interface TopicDao {
@Query("SELECT * FROM topic")
List<Topic> getAll();
@Insert
void insert(Topic task);
@Delete
void delete(Topic task);
@Update
void update(Topic task);
}
<file_sep>package com.phuong.demoroomdatabase.activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.phuong.demoroomdatabase.R;
public class ContentActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story);
}
}
<file_sep>package com.phuong.demoroomdatabase.model;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.io.Serializable;
@Entity
public class Topic implements Serializable {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "title")
private String name;
@ColumnInfo(name = "finished")
private boolean finished;
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>package com.phuong.demoroomdatabase.activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.phuong.demoroomdatabase.R;
import com.phuong.demoroomdatabase.model.Topic;
import com.phuong.demoroomdatabase.db.DatabaseClient;
public class AddTopic extends AppCompatActivity {
private EditText editTitle;
private ImageButton back;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_topic);
editTitle=findViewById(R.id.et_topic);
findViewById(R.id.btn_save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveTopic();
}
});
back=findViewById(R.id.btn_back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
}
private void saveTopic() {
final String title = editTitle.getText().toString().trim();
if (title.isEmpty()) {
editTitle.setError("Topic required");
editTitle.requestFocus();
return;
}
class SaveTopic extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
//creating a task
Topic topic=new Topic();
topic.setName(title);
//adding to database
DatabaseClient.getInstance(getApplicationContext()).getAppDatabase()
.topicDao().insert(topic);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
}
}
SaveTopic st = new SaveTopic();
st.execute();
}
}
<file_sep>package com.phuong.demoroomdatabase.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import com.phuong.demoroomdatabase.model.Story;
import java.util.List;
@Dao
public interface StoriesDao {
@Query("SELECT * FROM story WHERE idStory=idTopic")
List<Story> getAllStory();
@Insert
void insert(Story story);
@Delete
void delete(Story story);
@Update
void update(Story story);
}
|
d8b6ab6330ea8e826e23d0b7f99c9c2f7a8a92a7
|
[
"Java"
] | 6 |
Java
|
gnouhpuht/DemoRoomDatabase
|
e4f69b8fc787ff6ea4cbeef0c61475c1510a9fad
|
c5f595d3682cbfbd87ec92b83e73e94372a80ab8
|
refs/heads/master
|
<file_sep>
package main
import (
"fmt"
"log"
"encoding/json"
"bytes"
"crypto/tls"
"net/http"
)
type PodDetails struct{
Services []NamespaceDetails
}
func main() {
Namespacedetails := NamespaceDetails{}
NamespaceList := []NamespaceDetails{}
for{
NamespaceList = Namespacedetails.GetNamespaceDetails()
podDetails := PodDetails{}
podDetails.Services = NamespaceList
jsonData, err := json.Marshal(podDetails)
if err != nil { log.Println(err) }
fmt.Println(string(jsonData))
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
clientIngestion := &http.Client{Transport: tr}
var byteR = bytes.NewReader(jsonData)
req1, _ := http.NewRequest("POST", "http://localhost:8082/api/v1/ingest/analytics", byteR)
req1.Header.Set("content-type", "application/json")
req1.Header.Set("topic-name", "ServicePodMetric")
req1.Header.Set("x-auth-header", "abc")
res, _ := clientIngestion.Do(req1)
fmt.Println("***************Result from Ingestion API*******\n", res)
}
}
<file_sep>FROM scratch
EXPOSE 8080
ENTRYPOINT ["/serviceslist"]
COPY ./bin/ /<file_sep>package main
import (
"bufio"
"strings"
"os/exec"
)
type Services struct {
Namespace string
ServiceName string
}
type NamespaceDetails struct {
Namespace string
ServiceName string
PodList map[string][]string
}
func (n *NamespaceDetails) GetNamespaceDetails() []NamespaceDetails {
var npvarArray []string
var services []Services
var podlist []NamespaceDetails
out1, _ := exec.Command("sh", "-c", "kubectl get namespaces").Output()
inputstr1 := string(out1)
scanner := bufio.NewScanner(strings.NewReader(inputstr1))
for scanner.Scan() {
tempStr := scanner.Text()
if !strings.Contains(tempStr, "NAME") {
tempArr := strings.Fields(tempStr)
npvarArray = append(npvarArray, strings.TrimSpace(tempArr[0]))
}
}
for _,v3 := range npvarArray{
serviceObj := Services{}
out2, _ := exec.Command("sh", "-c", "kubectl get svc -n " + v3 +"").Output()
inputstr2 := string(out2)
scanner = bufio.NewScanner(strings.NewReader(inputstr2))
for scanner.Scan() {
tempStr := scanner.Text()
if !strings.Contains(tempStr, "NAME") {
tempArr := strings.Fields(tempStr)
serviceObj.Namespace = v3
serviceObj.ServiceName = strings.TrimSpace(tempArr[0])
services = append(services,serviceObj)
}
}
}
for _,i := range services{
namespace := NamespaceDetails{}
namespace.Namespace = i.Namespace
namespace.ServiceName = i.ServiceName
namespace.PodList = make(map[string][]string)
kubectlCommand := "kubectl get pods -n " + i.Namespace + " -l $(kubectl describe svc " + i.ServiceName + " -n " + i.Namespace + " | grep -e Selector |awk '{print $2}')"
out3, _ := exec.Command("sh", "-c", kubectlCommand).Output()
inputstr3 := string(out3)
scanner = bufio.NewScanner(strings.NewReader(inputstr3))
var PodArray []string
for scanner.Scan() {
tempStr := scanner.Text()
if !strings.Contains(tempStr, "NAME") {
tempArr3 := strings.Fields(tempStr)
PodArray = append(PodArray,(strings.TrimSpace(tempArr3[0])))
}
}
namespace.PodList["Pods"]= PodArray
podlist = append(podlist,namespace)
}
return podlist
}
|
50b35cf1167b68a593bb8f637df28a88a8f38656
|
[
"Go",
"Dockerfile"
] | 3 |
Go
|
navnitkum/go
|
1c0f3f05a464d956d01e0f6df2116ae8cba91a7e
|
bf588880028ff93ce6ddb04d6ade0ff9ca5e51a2
|
refs/heads/master
|
<file_sep># recipe_demo
- Stack
- Tab
- GridView
- Navigation
- Drawer
## TODO
- [ ] Cache Image
- [ ] State Management
<div>
<img src='screenshots/recipe.gif' width="30%" alt='main'>
<img src='screenshots/favorite.gif' width="30%" alt='favorite'>
<img src='screenshots/filter.gif' width="30%" alt='filter'>
</div><file_sep># layout_demo
This project is tutorial work from [building layouts in Flutter](https://flutter.dev/docs/development/ui/layout/tutorial).
- lake_demo.dart build the layout for the following:
<img src='look/lake_final_look.png' width="30%" alt='lake'>
- basic_layout_demo.dart play the layout for the following:
<img src='look/basic_layout.png' width="30%" alt='lake'>
- avatar_demo.dart (use `Card, ListTitle class`) build the layout for the following:
<img src='look/avatar_final_look.png' width="30%" alt='lake'><file_sep>package com.example.bloc_api_demo
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
<file_sep># pl_players
This is simple flutter project.
Used ChangeNotifierProvider for state management.
```
dependencies:
provider: ^4.0.2
```
<div>
<img src='screenshot/pl_provider.gif' width="15%" alt='pl_players'>
</div><file_sep># shop_demo
## Todo
- [x] List of colors (Display Only)
- [ ] List of size (Not implemented)
- [ ] Selectable Color
- [ ] Selectable Size
- [ ] Selectable QTY
- loading
- pull to refresh
- error handling <file_sep># code-flutter
# 🎨 Layout and Design
## layout_demo [Basic Layout Learning]
layout_demo project is tutorial work of layout. In the project, build the layout for the following:
<div>
<img src='flutter/layout_demo/look/lake_final_look.png' width="15%" alt='lake'>
<img src='flutter/layout_demo/look/basic_layout.png' width="15%" alt='lake'> <img src='flutter/layout_demo/look/avatar_final_look.png' width="15%" alt='lake'>
</div>
## 🧩ui_building
In this project, tried out following widgets.
- buttons
- pull down
- radio
- checkbox
- input
- alert box
- app bar
- Your Wallet Design (inspired from google search result, hope they won't mind for using their design)
```
dependencies:
backdrop: ^0.2.8
widget_with_codeview: ^1.0.3
```
<div>
<img src='flutter/ui_building/screenshot/ui_building.gif' width="20%" alt='ui'>
</div>
# 🤹🏻♂️ State Management
- provider
## pl_players
This is simple flutter project.
Used ChangeNotifierProvider for state management.
```
dependencies:
provider: ^4.0.2
```
<div>
<img src='flutter/provider_demo/pl_players/screenshot/pl_provider.gif' width="20%" alt='pl_players'>
</div>
# 🗄 Database
## Local DB
- sqflite
- moor
## book_moor
Used Moor as persistence library.
Simple CRUD operation done on Category Model.
```
dependencies:
moor_flutter: ^2.0.0
```
<div>
<img src='flutter/database_demo/moor/book_moor/screenshot/category_moor.gif' width="20%" alt='category'>
</div>
# 💭 Demo
## expenses_demo
Weekly spend tracking demo with in memory data storage.
<div>
<img src='flutter/expenses_demo/screenshots/main.png' width="15%" alt='main'>
<img src='flutter/expenses_demo/screenshots/modal.png' width="15%" alt='main'>
<img src='flutter/expenses_demo/screenshots/landscape1.png' width="50%" alt='main'>
</div>
## recipe_demo
Recipe browsing app.
<div>
<img src='flutter/recipe_demo/screenshots/recipe.gif' width="20%" alt='main'>
<img src='flutter/recipe_demo/screenshots/favorite.gif' width="20%" alt='favorite'>
<img src='flutter/recipe_demo/screenshots/filter.gif' width="20%" alt='filter'>
</div>
<file_sep># bloc_api_demo
Implement BLoc design.
```
dependencies:
flutter_bloc: ^4.0.0
```
<file_sep># book_moor
Used Moor as persistence library.
Simple CRUD operation done on Category Model.
* DrawerWidget
* Form
* Form Validation with RegExp
```
dependencies:
flutter:
moor: ^2.3.0
moor_flutter: ^2.0.0
path_provider: ^1.6.0
dev_dependencies:
flutter_test:
sdk: flutter
moor_generator: ^2.3.1
```
<div>
<img src='screenshot/category_moor.gif' width="15%" alt='category'>
</div>
<file_sep># ui_building
Tried the taste of flutter.
In this project, tried out following widgets.
* buttons
* pull down
* radio
* checkbox
* input
* alert box
* app bar
* Your Wallet Design (inspired from google search result, hope they won't mind for using their design)
```
dependencies:
flutter:
backdrop: ^0.2.8
widget_with_codeview: ^1.0.3
```
```
fonts:
- family: MyanmarNayone
fonts:
- asset: assets/fonts/MyanmarNayone.ttf
- family: Bebas Neue
fonts:
- asset: assets/fonts/BebasNeue-Regular.ttf
```
<div>
<img src='screenshot/ui_building.gif' width="15%" alt='ui'>
</div><file_sep>package com.example.bloc_weather_demo
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
<file_sep># api_demo
Fetch data from [https://jsonplaceholder.typicode.com] api.
Used [Retrofit] package and fllowing:
```
dependencies:
json_serializable: ^3.2.5
dio: ^3.0.8
retrofit: ^1.3.0
logger: ^0.8.3
pretty_dio_logger ^1.1.0
provider: ^4.0.4
dev_dependencies:
build_runner: ^1.7.4
retrofit_generator: ^1.3.0
```
<file_sep># expenses_demo
Weekly expense tracking demo project.
- Responsive (MediaQuery, LayoutBuilder) apply
- Landscape / Portrait mode control
- Device platform control
## UI
> Android Look
<div>
<img src='./screenshots/main.png' width="20%" alt='main'>
<img src='./screenshots/modal.png' width="20%" alt='modal'>
</div>
> IOS Look
<div>
<img src='./screenshots/ios.png' width="20%" alt='main'>
</div>
> Landscape
<div>
<img src='./screenshots/landscape1.png' width="50%" alt='main'>
<img src='./screenshots/landscape2.png' width="50%" alt='modal'>
</div>
---
TODO
1. [ ] State management with provider
2. [ ] Local db
3. [ ] Update ?
4. [ ] Monthly usage pie chart
<file_sep># bloc_weather_demo
Implemented Bloc pattern.
<div>
<img src='screenshots/screen.gif' width="30%" alt='main'>
</div>
|
97f262b3cbbc0610e4bd8078f00463c1ae12d2a5
|
[
"Markdown",
"Kotlin"
] | 13 |
Markdown
|
sumyathtarwai/code-flutter
|
23194a69eaf5377ab543589317937352cc97c2d5
|
aa7a2c3f86ac11074e45f1b3f9a2016124442585
|
refs/heads/master
|
<repo_name>croizat/shores_PA3<file_sep>/shores_p2/src/Application.java
public class Application extends SavingsAccount {
Application(double amt) {
super(amt);
}
public static void main(String[] args){
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(4.0);
System.out.println("\n\033[3mAccount balance with interest rate of 4.0%\033[0m");
System.out.println("Month \t saver1 \t saver2");
//print 12 months of interest
for(int i = 1; i <= 12; ++i){
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.printf("%3d\t\t", i);
saver1.printBalance();
System.out.print("\t");
saver2.printBalance();
System.out.println();
}
System.out.println("\n\033[3mAccount balance with new interest rate of 5.0%\033[0m");
SavingsAccount.modifyInterestRate(5.0);
// get new balance with new interest
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
// print last month
System.out.println("Month \t saver1 \t saver2");
System.out.printf("%3d\t\t", 13);
saver1.printBalance();
System.out.print("\t");
saver2.printBalance();
System.out.println();
}
}
<file_sep>/shores_p1/src/ArithmeticTutor.java
import java.security.SecureRandom;
import java.util.Scanner;
import java.util.ArrayList;
public class ArithmeticTutor {
private SecureRandom randGen = new SecureRandom();
private Scanner sc = new Scanner(System.in);
private int[] nums = new int[2];
private int amountCorrect = 0;
private int level = 1;
private int operatorChoice = 1;
private char currentOperator = '+';
public static void main(String[] args) {
System.out.println("Welcome to the Arithmetic Computer-Assisted Instruction Program.");
System.out.println("If at any point you would like to exit the program, enter q.\n\n");
ArithmeticTutor program = new ArithmeticTutor();
while(true) {
program.run();
System.out.print("Would you like to continue (Y/N)? ");
String persistInput = program.sc.next().toLowerCase();
while(persistInput.matches("[^yn]"))
{
System.out.print("Sorry, you didn't answer with either a Y or N. Try again: ");
persistInput = program.sc.next().toLowerCase();
}
if(persistInput.matches("([y])")) {
System.out.println("Program reset! New round begins now.\n");
program.reset();
}
else if(persistInput.matches("([n])")) {
System.out.println("Thanks for participating!");
System.exit(0);
}
}
}
private void run(){
int counter = 0;
printLevelMenu();
printOperationSelection();
while(counter != 10){
getQuestion();
String temp = sc.next().toLowerCase();
while(!(temp.matches("(-?\\d+)?(\\.?\\d+)?|([q])"))) {
System.out.print("Sorry, you didn't answer with an integer or formatted your answer incorrectly. Try again: ");
temp = sc.next();
}
if(temp.charAt(0) == 'q') {
System.out.println("Thanks for participating!");
System.exit(0);
}
float answer = Float.parseFloat(temp);
printAnswerResponse(checkAnswer(answer));
++counter;
}
getResults();
}
private void printLevelMenu(){
System.out.println("Level Selection");
System.out.println("1) Level 1, single digit arithmetic");
System.out.println("2) Level 2, double digit arithmetic");
System.out.println("3) Level 3, triple digit arithmetic");
System.out.println("4) Level 4, quadruple digit arithmetic");
System.out.print("Choose a level to begin with: ");
String temp = sc.next().toLowerCase();
while(!(temp.matches("(\\d+)|([q])"))) {
System.out.print("Sorry, you didn't answer with an integer. Try again: ");
temp = sc.next();
}
if(temp.charAt(0) == 'q') {
System.out.println("Thanks for participating!");
System.exit(0);
}
int level = Integer.parseInt(temp);
setLevel(level);
if((level < 1 || level > 4)) {
printLevelMenu();
}
}
private void setLevel(int level){
this.level = level;
}
private void getQuestion(){
if(nums[0] == 0 && nums[1] == 0) {
setQuestion();
}
System.out.printf("How much is %d %c %d? ", nums[0], currentOperator, nums[1]);
}
private void setQuestion(){
int[] levels = {9, 90, 900, 9000};
if(level == 1) {
nums[0] = randGen.nextInt(levels[level - 1]);
nums[1] = randGen.nextInt(levels[level - 1]);
}
else {
nums[0] = randGen.nextInt(levels[level - 1]) + (int) Math.pow(10, level - 1);
nums[1] = randGen.nextInt(levels[level - 1]) + (int) Math.pow(10, level - 1);
}
setOperator();
}
private void printOperationSelection(){
System.out.println("Arithmetic Selection");
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Mixed mode");
System.out.print("Choose an arithmetic to practice with: ");
String temp = sc.next().toLowerCase();
while(!(temp.matches("(\\d+)|([q])"))) {
System.out.print("Sorry, you didn't answer with an integer. Try again: ");
temp = sc.next();
}
if(temp.charAt(0) == 'q') {
System.out.println("Thanks for participating!");
System.exit(0);
}
int operatorChoice = Integer.parseInt(temp);
setOperatorChoice(operatorChoice);
if(operatorChoice == 4 | operatorChoice == 5) {
System.out.println("For division problems, please round your answer to at least two decimal places.");
}
if((operatorChoice < 1 || operatorChoice > 5) && operatorChoice != -1) {
printOperationSelection();
}
}
private void setOperatorChoice(int operatorChoice){
this.operatorChoice = operatorChoice;
}
private void setOperator(){
char[] operatorsArray = {'+', '-', '*', '/'};
if(operatorChoice == 5) {
currentOperator = operatorsArray[randGen.nextInt(4)];
}
else {
currentOperator = operatorsArray[operatorChoice - 1];
}
if((nums[0] == 0 || nums[1] == 0) && currentOperator == '/') {
setQuestion();
}
}
private void printAnswerResponse(boolean result){
ArrayList<String> responses = new ArrayList<String>();
int fakeBoolean;
if(result) {
fakeBoolean = 0;
}
else {
fakeBoolean = 1;
}
switch(fakeBoolean) {
case 0:
responses.add("Very Good!");
responses.add("Excellent!");
responses.add("Nice Work!");
responses.add("Keep up the good work!");
setQuestion();
++amountCorrect;
break;
case 1:
responses.add("No. Please try again.");
responses.add("Wrong. Try once more.");
responses.add("Don't give up.");
responses.add("No. Keep trying.");
break;
}
System.out.println(responses.get(randGen.nextInt(responses.size())));
}
private boolean checkAnswer(float answer){
float tempDiv = (float)nums[0] / (float)nums[1];
double EPSILON = 0.01;
switch(currentOperator) {
case '+':
return (answer == nums[0] + nums[1]);
case '-':
return (answer == nums[0] - nums[1]);
case '*':
return (answer == nums[0] * nums[1]);
case '/':
return (Math.abs(tempDiv - answer) < EPSILON);
default:
return false;
}
}
private void getResults(){
System.out.printf("\nYou scored %d out of 10.\n", amountCorrect);
if(amountCorrect >= (10 * 0.75)) {
System.out.println("Congratulations, you are ready to go the next level!\n");
}
else {
System.out.println("Please ask your teacher for extra help.\n");
}
}
private void reset(){
amountCorrect = 0;
nums[0] = 0;
nums[1] = 0;
}
}
|
beaf7697d2008c95b6aa9c11691d14a190547637
|
[
"Java"
] | 2 |
Java
|
croizat/shores_PA3
|
d6eafe45729a5e19fd69f24ef62d61f7105924c0
|
137bdb7dd6932e604dd0ec7e9eee2b97e9957f8f
|
refs/heads/master
|
<repo_name>wahyono17/tpb_backEnd<file_sep>/application/controllers/api/header.php
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Header extends REST_Controller {
public function __construct(){
parent::__construct();
$this->load->model('Header_model','header');
}
public function index_get() {
$nomor_peb = $this->get('NOMOR_DAFTAR');
$tahun = $this->get('YEAR(TANGGAL_DAFTAR)');
$bulan = $this->get('MONTH(TANGGAL_DAFTAR)');
if ($nomor_peb === null && $tahun === null && $bulan === null){
$header = $this->header->getHeader($nomor_peb = null,$tahun, $bulan = null);
} else if ($nomor_peb === null && $tahun != null && $bulan === null){
$header = $this->header->getHeader($nomor_peb = null,$tahun, $bulan = null);
} else if ($nomor_peb != null && $tahun === null && $bulan === null ){
$header = $this->header->getHeader($nomor_peb, $tahun = null, $bulan = null) ;
} else if ($nomor_peb != null && $tahun != null && $bulan === null){
$header = $this->header->getHeader($nomor_peb, $tahun, $bulan = null);
} else if ($nomor_peb === null && $tahun != null && $bulan != null){
$header = $this->header->getHeader($nomor_peb = null, $tahun, $bulan);
} else if ($nomor_peb != null && $tahun != null && $bulan != null){
$header = $this->header->getHeader($nomor_peb, $tahun, $bulan);
}
// jika ketemu $header maka confer to json
if ($header){
$this->response([
'status' => true,'data' => $header
], REST_Controller::HTTP_OK);
} else{
$this->response([
'status' => false,'message' => 'data not found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
}
?><file_sep>/application/models/Header_model.php
<?php
class Header_model extends CI_Model {
public function getHeader ($nomor_peb = null, $tahun = null, $bulan = null)
{
$this->db->select('NOMOR_AJU,TANGGAL_DAFTAR,YEAR(TANGGAL_DAFTAR) as TAHUN, MONTH(TANGGAL_DAFTAR) as BULAN, NOMOR_DAFTAR,KODE_DOKUMEN_PABEAN,CIF, HARGA_PENYERAHAN');
if ($nomor_peb === null && $tahun === null && $bulan === null){
$tahun = date('Y-m-d');
return $hasil = $this->db->get_where('tpb_header',['TANGGAL_DAFTAR'=> $tahun])->result_array();
} else if($nomor_peb === null && $tahun != null && $bulan === null) {
return $this->db->get_where('tpb_header',['YEAR(TANGGAL_DAFTAR)'=> $tahun])->result_array();
} else if ($nomor_peb != null && $tahun === null && $bulan === null){
return $this->db->get_where('tpb_header',['NOMOR_DAFTAR'=> $nomor_peb])->result_array();
} else if($nomor_peb != null && $tahun != null && $bulan === null){
$multiwhere = ['NOMOR_DAFTAR' => $nomor_peb, 'YEAR(TANGGAL_DAFTAR)' => $tahun];
return $this->db->get_where('tpb_header',$multiwhere)->result_array();
} else if($nomor_peb === null && $tahun != null && $bulan != null){
$multiwhere = ['YEAR(TANGGAL_DAFTAR)' => $tahun, 'MONTH(TANGGAL_DAFTAR)'=> $bulan];
return $this->db->get_where('tpb_header',$multiwhere)->result_array();
} else if ($nomor_peb != null && $tahun != null && $bulan != null){
$multiwhere = ['NOMOR_DAFTAR' => $nomor_peb,'YEAR(TANGGAL_DAFTAR)' => $tahun, 'MONTH(TANGGAL_DAFTAR)'=> $bulan];
return $this->db->get_where('tpb_header',$multiwhere)->result_array();
}
}
}
?>
|
0ccd4cdf85038441a79dc667f965419167b7ea81
|
[
"PHP"
] | 2 |
PHP
|
wahyono17/tpb_backEnd
|
63e1441766b9435b16a15b25fccc8211d15e36b2
|
df7d6cc7ab755a87de5f97f67a485fb91a28c975
|
refs/heads/orbitai
|
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include "data.h"
void DataSet::findFeatRange() {
m_minFeatRange = VectorXd(m_numFeatures);
m_maxFeatRange = VectorXd(m_numFeatures);
double minVal, maxVal;
for (int nFeat = 0; nFeat < m_numFeatures; nFeat++) {
minVal = m_samples[0].x(nFeat);
maxVal = m_samples[0].x(nFeat);
for (int nSamp = 1; nSamp < m_numSamples; nSamp++) {
if (m_samples[nSamp].x(nFeat) < minVal) {
minVal = m_samples[nSamp].x(nFeat);
}
if (m_samples[nSamp].x(nFeat) > maxVal) {
maxVal = m_samples[nSamp].x(nFeat);
}
}
m_minFeatRange(nFeat) = minVal;
m_maxFeatRange(nFeat) = maxVal;
}
}
void DataSet::load(const string& x_filename, const string& y_filename) {
ifstream xfp(x_filename.c_str(), ios::binary);
if (!xfp) {
cout << "Could not open input file " << x_filename << endl;
exit(EXIT_FAILURE);
}
ifstream yfp(y_filename.c_str(), ios::binary);
if (!yfp) {
cout << "Could not open input file " << y_filename << endl;
exit(EXIT_FAILURE);
}
cout << "Loading data file: " << x_filename << " ... " << endl;
// Reading the header
int tmp;
xfp >> m_numSamples;
xfp >> m_numFeatures;
yfp >> tmp;
if (tmp != m_numSamples) {
cout << "Number of samples in data and labels file is different" << endl;
exit(EXIT_FAILURE);
}
yfp >> tmp;
m_samples.clear();
set<int> labels;
for (int nSamp = 0; nSamp < m_numSamples; nSamp++) {
Sample sample;
sample.x = VectorXd(m_numFeatures);
sample.id = nSamp;
sample.w = 1.0;
yfp >> sample.y;
labels.insert(sample.y);
for (int nFeat = 0; nFeat < m_numFeatures; nFeat++) {
xfp >> sample.x(nFeat);
}
m_samples.push_back(sample); // push sample into dataset
}
xfp.close();
yfp.close();
m_numClasses = labels.size();
// Find the data range
findFeatRange();
cout << "Loaded " << m_numSamples << " samples with " << m_numFeatures;
cout << " features and " << m_numClasses << " classes." << endl;
}
Result::Result() {
}
Result::Result(const int& numClasses) : confidence(VectorXd::Zero(numClasses)) {
}
Cache::Cache() : margin(-1.0), yPrime(-1) {
}
Cache::Cache(const Sample& sample, const int& numBases, const int& numClasses) : margin(-1.0), yPrime(-1) {
cacheSample.x = sample.x;
cacheSample.y = sample.y;
cacheSample.w = sample.w;
cacheSample.id = sample.id;
}
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef BOOSTER_H
#define BOOSTER_H
#include "classifier.h"
class Booster : public Classifier {
public:
Booster(const Hyperparameters& hp, const int& numClasses, const int& numFeatures,
const VectorXd& minFeatRange, const VectorXd& maxFeatRange);
~Booster();
virtual void eval(Sample& sample, Result& result);
protected:
vector<Classifier*> m_bases;
VectorXd m_w;
vector<Cache> m_cache;
};
#endif // BOOSTER_H
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include "online_rf.h"
RandomTest::RandomTest(const int& numClasses, const int& numFeatures, const VectorXd &minFeatRange, const VectorXd &maxFeatRange) :
m_numClasses(&numClasses), m_trueCount(0.0), m_falseCount(0.0),
m_trueStats(VectorXd::Zero(numClasses)), m_falseStats(VectorXd::Zero(numClasses)) {
m_feature = randDouble(0, numFeatures + 1);
m_threshold = randDouble(minFeatRange(m_feature), maxFeatRange(m_feature));
}
void RandomTest::update(const Sample& sample) {
updateStats(sample, eval(sample));
}
bool RandomTest::eval(const Sample& sample) const {
return (sample.x(m_feature) > m_threshold) ? true : false;
}
double RandomTest::score() const {
double trueScore = 0.0, falseScore = 0.0, p;
if (m_trueCount) {
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
p = m_trueStats[nClass] / m_trueCount;
trueScore += p * (1 - p);
}
}
if (m_falseCount) {
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
p = m_falseStats[nClass] / m_falseCount;
falseScore += p * (1 - p);
}
}
return (m_trueCount * trueScore + m_falseCount * falseScore) / (m_trueCount + m_falseCount + 1e-16);
}
pair<VectorXd, VectorXd > RandomTest::getStats() const {
return pair<VectorXd, VectorXd> (m_trueStats, m_falseStats);
}
void RandomTest::updateStats(const Sample& sample, const bool& decision) {
if (decision) {
m_trueCount += sample.w;
m_trueStats(sample.y) += sample.w;
} else {
m_falseCount += sample.w;
m_falseStats(sample.y) += sample.w;
}
}
OnlineNode::OnlineNode(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange,
const int& depth) :
m_numClasses(&numClasses), m_depth(depth), m_isLeaf(true), m_hp(&hp), m_label(-1),
m_counter(0.0), m_parentCounter(0.0), m_labelStats(VectorXd::Zero(numClasses)),
m_minFeatRange(&minFeatRange), m_maxFeatRange(&maxFeatRange) {
// Creating random tests
for (int nTest = 0; nTest < hp.numRandomTests; nTest++) {
m_onlineTests.push_back(new RandomTest(numClasses, numFeatures, minFeatRange, maxFeatRange));
}
}
OnlineNode::OnlineNode(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange,
const int& depth, const VectorXd& parentStats) :
m_numClasses(&numClasses), m_depth(depth), m_isLeaf(true), m_hp(&hp), m_label(-1),
m_counter(0.0), m_parentCounter(parentStats.sum()), m_labelStats(parentStats),
m_minFeatRange(&minFeatRange), m_maxFeatRange(&maxFeatRange) {
m_labelStats.maxCoeff(&m_label);
// Creating random tests
for (int nTest = 0; nTest < hp.numRandomTests; nTest++) {
m_onlineTests.push_back(new RandomTest(numClasses, numFeatures, minFeatRange, maxFeatRange));
}
}
OnlineNode::~OnlineNode() {
if (!m_isLeaf) {
delete m_leftChildNode;
delete m_rightChildNode;
delete m_bestTest;
} else {
for (int nTest = 0; nTest < m_hp->numRandomTests; nTest++) {
delete m_onlineTests[nTest];
}
}
}
void OnlineNode::update(const Sample& sample) {
m_counter += sample.w;
m_labelStats(sample.y) += sample.w;
if (m_isLeaf) {
// Update online tests
for (vector<RandomTest*>::iterator itr = m_onlineTests.begin(); itr != m_onlineTests.end(); ++itr) {
(*itr)->update(sample);
}
// Update the label
m_labelStats.maxCoeff(&m_label);
// Decide for split
if (shouldISplit()) {
m_isLeaf = false;
// Find the best online test
int nTest = 0, minIndex = 0;
double minScore = 1, score;
for (vector<RandomTest*>::const_iterator itr(m_onlineTests.begin()); itr != m_onlineTests.end(); ++itr, nTest++) {
score = (*itr)->score();
if (score < minScore) {
minScore = score;
minIndex = nTest;
}
}
m_bestTest = m_onlineTests[minIndex];
for (int nTest = 0; nTest < m_hp->numRandomTests; nTest++) {
if (minIndex != nTest) {
delete m_onlineTests[nTest];
}
}
// Split
pair<VectorXd, VectorXd> parentStats = m_bestTest->getStats();
m_rightChildNode = new OnlineNode(*m_hp, *m_numClasses, m_minFeatRange->rows(), *m_minFeatRange, *m_maxFeatRange, m_depth + 1,
parentStats.first);
m_leftChildNode = new OnlineNode(*m_hp, *m_numClasses, m_minFeatRange->rows(), *m_minFeatRange, *m_maxFeatRange, m_depth + 1,
parentStats.second);
}
} else {
if (m_bestTest->eval(sample)) {
m_rightChildNode->update(sample);
} else {
m_leftChildNode->update(sample);
}
}
}
void OnlineNode::eval(const Sample& sample, Result& result) {
if (m_isLeaf) {
if (m_counter + m_parentCounter) {
result.confidence = m_labelStats / (m_counter + m_parentCounter);
result.prediction = m_label;
} else {
result.confidence = VectorXd::Constant(m_labelStats.rows(), 1.0 / *m_numClasses);
result.prediction = 0;
}
} else {
if (m_bestTest->eval(sample)) {
m_rightChildNode->eval(sample, result);
} else {
m_leftChildNode->eval(sample, result);
}
}
}
bool OnlineNode::shouldISplit() const {
bool isPure = false;
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
if (m_labelStats(nClass) == m_counter + m_parentCounter) {
isPure = true;
break;
}
}
if ((isPure) || (m_depth >= m_hp->maxDepth) || (m_counter < m_hp->counterThreshold)) {
return false;
} else {
return true;
}
}
OnlineTree::OnlineTree(const Hyperparameters& hp, const int& numClasses, const int& numFeatures,
const VectorXd& minFeatRange, const VectorXd& maxFeatRange) :
Classifier(hp, numClasses) {
m_rootNode = new OnlineNode(hp, numClasses, numFeatures, minFeatRange, maxFeatRange, 0);
m_name = "OnlineTree";
}
OnlineTree::~OnlineTree() {
delete m_rootNode;
}
void OnlineTree::update(Sample& sample) {
m_rootNode->update(sample);
}
void OnlineTree::eval(Sample& sample, Result& result) {
m_rootNode->eval(sample, result);
}
OnlineRF::OnlineRF(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange) :
Classifier(hp, numClasses), m_counter(0.0), m_oobe(0.0) {
OnlineTree *tree;
for (int nTree = 0; nTree < hp.numTrees; nTree++) {
tree = new OnlineTree(hp, numClasses, numFeatures, minFeatRange, maxFeatRange);
m_trees.push_back(tree);
}
m_name = "OnlineRF";
}
OnlineRF::~OnlineRF() {
for (int nTree = 0; nTree < m_hp->numTrees; nTree++) {
delete m_trees[nTree];
}
}
void OnlineRF::update(Sample& sample) {
m_counter += sample.w;
Result result(*m_numClasses), treeResult;
int numTries;
for (int nTree = 0; nTree < m_hp->numTrees; nTree++) {
numTries = poisson(1.0);
if (numTries) {
for (int nTry = 0; nTry < numTries; nTry++) {
m_trees[nTree]->update(sample);
}
} else {
m_trees[nTree]->eval(sample, treeResult);
result.confidence += treeResult.confidence;
}
}
int pre;
result.confidence.maxCoeff(&pre);
if (pre != sample.y) {
m_oobe += sample.w;
}
}
void OnlineRF::eval(Sample& sample, Result& result) {
Result treeResult;
for (int nTree = 0; nTree < m_hp->numTrees; nTree++) {
m_trees[nTree]->eval(sample, treeResult);
result.confidence += treeResult.confidence;
}
result.confidence /= m_hp->numTrees;
result.confidence.maxCoeff(&result.prediction);
}
<file_sep>// -*- C++ -*-
// Copyright (C) 2008- <NAME>
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA
#include <cstdlib>
#include <sys/time.h>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <cfloat>
#include <cassert>
#include "vectors.h"
#include "LaRank.h"
/////////////////////
void exit_with_help()
{
fprintf(stdout,
"\nLA_RANK_LEARN: learns models for multiclass classification with the 'LaRank algorithm'.\n"
"!!! Implementation optimized for the use of LINEAR kernel only !!!\n"
"\nUsage: la_rank_learn [options] training_set_file model_file\n"
"options:\n"
"-c cost : set the parameter C (default 1)\n"
"-t tau : threshold determining tau-violating pairs of coordinates (default 1e-4) \n"
"-m mode : set the learning mode (default 0)\n"
"\t 0: online learning\n"
"\t 1: batch learning (stopping criteria: duality gap < C)\n"
"-v verbosity degree : display informations every v %% of the training set size (default 10)\n"
);
exit(1);
}
void training(Machine* svm, Exampler train, int step, int mode)
{
int n_it = 0;
double initime = getTime(), gap = DBL_MAX;
std::cout << "\n--> Training on " << train.nb_ex << "ex" << std::endl;
while (gap > svm->C) {
n_it++;
double tr_err = 0;
int ind = step;
for (int i = 0; i < train.nb_ex; i++) {
int lab = train.data[i].cls;
if (svm->add(train.data[i].inpt, lab, i) != lab)
tr_err++;
if (i / ind) {
std::cout << "Done: " << (int) (((double) i) / train.nb_ex * 100) << "%, Train error (online): " << (tr_err / ((double) i + 1)) *100 << "%" << std::endl;
svm->printStuff(initime, false);
ind += step;
}
}
std::cout << "---- End of iteration " << n_it << " ----" << std::endl;
gap = svm->computeGap();
std::cout << "Duality gap: " << gap << std::endl;
std::cout << "Train error (online): " << (tr_err / train.nb_ex) *100 << "%" << std::endl;
svm->printStuff(initime, true);
if (mode == 0)
gap = 0;
}
std::cout << "---- End of training ----" << std::endl;
}
void save_model(Machine* svm, const char* file)
{
std::cout << "\n--> Saving Model in \"" << file << "\"" << std::endl;
std::ofstream ostr(file);
svm->save_outputs(ostr);
}
int main(int argc, char* argv[])
{
Exampler train;
int i, mode = 0;
double C = 1, verb = 10, tau = 0.0001;
// parse options
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') break;
++i;
switch (argv[i - 1][1]) {
case 'c':
C = atof(argv[i]);
break;
case 't':
tau = atof(argv[i]);
break;
case 'm':
mode = atoi(argv[i]);
break;
case 'v':
verb = atof(argv[i]);
break;
default:
fprintf(stderr, "unknown option\n");
}
}
// determine filenames
if (i >= (argc - 1))
exit_with_help();
std::cout << "Loading Train Data " << std::endl;
train.libsvm_load_data(argv[i], false);
char* save_file = argv[i + 1];
// CREATE
int step = (int) ((double) train.nb_ex / (100 / verb));
std::cout << "\n--> Building with C = " << C << std::endl;
if (mode)
std::cout << " BATCH Learning" << std::endl;
else
std::cout << " ONLINE Learning" << std::endl;
Machine* svm = create_larank();
svm->C = C;
svm->tau = tau;
training(svm, train, step, mode);
save_model(svm, save_file);
delete svm;
return 0;
}
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef ONLINERF_H_
#define ONLINERF_H_
#include "classifier.h"
#include "data.h"
#include "hyperparameters.h"
#include "utilities.h"
class RandomTest {
public:
RandomTest(const int& numClasses, const int& numFeatures, const VectorXd &minFeatRange, const VectorXd &maxFeatRange);
void update(const Sample& sample);
bool eval(const Sample& sample) const;
double score() const;
pair<VectorXd, VectorXd > getStats() const;
protected:
const int* m_numClasses;
int m_feature;
double m_threshold;
double m_trueCount;
double m_falseCount;
VectorXd m_trueStats;
VectorXd m_falseStats;
void updateStats(const Sample& sample, const bool& decision);
};
class OnlineNode {
public:
OnlineNode(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange,
const int& depth);
OnlineNode(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange,
const int& depth, const VectorXd& parentStats);
~OnlineNode();
void update(const Sample& sample);
void eval(const Sample& sample, Result& result);
private:
const int* m_numClasses;
int m_depth;
bool m_isLeaf;
const Hyperparameters* m_hp;
int m_label;
double m_counter;
double m_parentCounter;
VectorXd m_labelStats;
const VectorXd* m_minFeatRange;
const VectorXd* m_maxFeatRange;
OnlineNode* m_leftChildNode;
OnlineNode* m_rightChildNode;
vector<RandomTest*> m_onlineTests;
RandomTest* m_bestTest;
bool shouldISplit() const;
};
class OnlineTree: public Classifier {
public:
OnlineTree(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange);
~OnlineTree();
virtual void update(Sample& sample);
virtual void eval(Sample& sample, Result& result);
private:
OnlineNode* m_rootNode;
};
class OnlineRF: public Classifier {
public:
OnlineRF(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange);
~OnlineRF();
virtual void update(Sample& sample);
virtual void eval(Sample& sample, Result& result);
protected:
double m_counter;
double m_oobe;
vector<OnlineTree*> m_trees;
};
#endif /* ONLINERF_H_ */
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include <fstream>
#include <sys/time.h>
#include "experimenter.h"
void train(Classifier* model, DataSet& dataset, Hyperparameters& hp) {
timeval startTime;
gettimeofday(&startTime, NULL);
vector<int> randIndex;
int sampRatio = dataset.m_numSamples / 10;
vector<double> trainError(hp.numEpochs, 0.0);
for (int nEpoch = 0; nEpoch < hp.numEpochs; nEpoch++) {
randPerm(dataset.m_numSamples, randIndex);
for (int nSamp = 0; nSamp < dataset.m_numSamples; nSamp++) {
if (hp.findTrainError) {
Result result(dataset.m_numClasses);
model->eval(dataset.m_samples[randIndex[nSamp]], result);
if (result.prediction != dataset.m_samples[randIndex[nSamp]].y) {
trainError[nEpoch]++;
}
}
model->update(dataset.m_samples[randIndex[nSamp]]);
if (hp.verbose && (nSamp % sampRatio) == 0) {
cout << "--- " << model->name() << " training --- Epoch: " << nEpoch + 1 << " --- ";
cout << (10 * nSamp) / sampRatio << "%";
cout << " --- Training error = " << trainError[nEpoch] << "/" << nSamp << endl;
}
}
}
timeval endTime;
gettimeofday(&endTime, NULL);
cout << "--- " << model->name() << " training time = ";
cout << (endTime.tv_sec - startTime.tv_sec + (endTime.tv_usec - startTime.tv_usec) / 1e6) << " seconds." << endl;
}
vector<Result> test(Classifier* model, DataSet& dataset, Hyperparameters& hp) {
timeval startTime;
gettimeofday(&startTime, NULL);
vector<Result> results;
for (int nSamp = 0; nSamp < dataset.m_numSamples; nSamp++) {
Result result(dataset.m_numClasses);
model->eval(dataset.m_samples[nSamp], result);
results.push_back(result);
}
double error = compError(results, dataset);
if (hp.verbose) {
cout << "--- " << model->name() << " test error: " << error << endl;
}
timeval endTime;
gettimeofday(&endTime, NULL);
cout << "--- " << model->name() << " testing time = ";
cout << (endTime.tv_sec - startTime.tv_sec + (endTime.tv_usec - startTime.tv_usec) / 1e6) << " seconds." << endl;
return results;
}
vector<Result> trainAndTest(Classifier* model, DataSet& dataset_tr, DataSet& dataset_ts, Hyperparameters& hp) {
timeval startTime;
gettimeofday(&startTime, NULL);
vector<Result> results;
vector<int> randIndex;
int sampRatio = dataset_tr.m_numSamples / 10;
vector<double> trainError(hp.numEpochs, 0.0);
vector<double> testError;
for (int nEpoch = 0; nEpoch < hp.numEpochs; nEpoch++) {
randPerm(dataset_tr.m_numSamples, randIndex);
for (int nSamp = 0; nSamp < dataset_tr.m_numSamples; nSamp++) {
if (hp.findTrainError) {
Result result(dataset_tr.m_numClasses);
model->eval(dataset_tr.m_samples[randIndex[nSamp]], result);
if (result.prediction != dataset_tr.m_samples[randIndex[nSamp]].y) {
trainError[nEpoch]++;
}
}
model->update(dataset_tr.m_samples[randIndex[nSamp]]);
if (hp.verbose && (nSamp % sampRatio) == 0) {
cout << "--- " << model->name() << " training --- Epoch: " << nEpoch + 1 << " --- ";
cout << (10 * nSamp) / sampRatio << "%";
cout << " --- Training error = " << trainError[nEpoch] << "/" << nSamp << endl;
}
}
results = test(model, dataset_ts, hp);
testError.push_back(compError(results, dataset_ts));
}
timeval endTime;
gettimeofday(&endTime, NULL);
cout << "--- Total training and testing time = ";
cout << (endTime.tv_sec - startTime.tv_sec + (endTime.tv_usec - startTime.tv_usec) / 1e6) << " seconds." << endl;
if (hp.verbose) {
cout << endl << "--- " << model->name() << " test error over epochs: ";
dispErrors(testError);
}
// Write the results
string saveFile = hp.savePath + ".errors";
ofstream file(saveFile.c_str(), ios::binary);
if (!file) {
cout << "Could not access " << saveFile << endl;
exit(EXIT_FAILURE);
}
file << hp.numEpochs << " 1" << endl;
for (int nEpoch = 0; nEpoch < hp.numEpochs; nEpoch++) {
file << testError[nEpoch] << endl;
}
file.close();
return results;
}
double compError(const vector<Result>& results, const DataSet& dataset) {
double error = 0.0;
for (int nSamp = 0; nSamp < dataset.m_numSamples; nSamp++) {
if (results[nSamp].prediction != dataset.m_samples[nSamp].y) {
error++;
}
}
return error / dataset.m_numSamples;
}
void dispErrors(const vector<double>& errors) {
for (int nSamp = 0; nSamp < (int) errors.size(); nSamp++) {
cout << nSamp + 1 << ": " << errors[nSamp] << " --- ";
}
cout << endl;
}
<file_sep>// -*- C++ -*-
// Copyright (C) 2008- <NAME>
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA
#include <cstdlib>
#include <sys/time.h>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <cfloat>
#include <cassert>
#include "vectors.h"
#include "LaRank.h"
/////////////////////
void exit_with_help()
{
fprintf(stdout,
"\nLA_RANK_CLASSIFY: uses models learned with the 'LaRank algorithm' for multiclass classification to make prediction.\n"
"!!! Only for models learned with the special implementation of LaRank for LINEAR kernel !!!\n"
"\nUsage: la_rank_classify testing_set_file model_file prediction_file\n"
);
exit(1);
}
void testing(Machine* svm, Exampler test, char* pred_file)
{
double err = 0;
FILE* fp = fopen(pred_file, "w");
std::cout << "\n--> Testing on " << test.nb_ex << "ex" << std::endl;
for (int i = 0; i < test.nb_ex; i++) {
int lab = test.data[i].cls;
int predlab = svm->predict(test.data[i].inpt);
if (predlab != lab)
err++;
fprintf(fp, "%d %d \n", lab, predlab);
}
fprintf(fp, "\n");
fclose(fp);
std::cout << "Test Error:" << 100 * (err / test.nb_ex) << "%" << std::endl;
}
Machine* load_model(char* file)
{
Exampler model;
model.libsvm_load_data(file, true);
Machine* svm = create_larank();
for (int i = 0; i < model.nb_ex; i++)
svm->add_output(model.data[i].cls, LaFVector(model.data[i].inpt));
return svm;
}
int main(int argc, char* argv[])
{
Exampler test;
int i;
// parse options -- no option so far
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') break;
++i;
switch (argv[i - 1][1]) {
default:
fprintf(stderr, "unknown option\n");
}
}
// determine filenames
if (i >= (argc - 2))
exit_with_help();
std::cout << "Loading Test Data" << std::endl;
test.libsvm_load_data(argv[i], false);
std::cout << "\nLoading Model" << std::endl;
char* model_file = argv[i + 1];
Machine* svm_load = load_model(model_file);
char* pred_file = argv[i + 2];
testing(svm_load, test, pred_file);
delete svm_load;
return 0;
}
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include "linear_larank.h"
LinearLaRank::LinearLaRank(const Hyperparameters& hp, const int& numClasses, const int& numFeatures,
const VectorXd& minFeatRange, const VectorXd& maxFeatRange) :
Classifier(hp, numClasses), m_sampleCount(0), m_numFeatures(&numFeatures) {
m_svm = new LaRank();
m_svm->tau = 0.0001;
m_svm->C = hp.larankC;
m_name = "LinearLaRank";
}
LinearLaRank::~LinearLaRank() {
delete m_svm;
}
void LinearLaRank::update(Sample& sample) {
// Convert the Sample to LaRank form
SVector laX;
for (int nFeat = 0; nFeat < sample.x.rows(); nFeat++) {
laX.set(nFeat, sample.x(nFeat));
}
// Add the sample to svm
m_sampleCount++;
m_svm->add(laX, sample.y, m_sampleCount, sample.w);
}
void LinearLaRank::eval(Sample& sample, Result& result) {
// Evaluate the sample
if (m_sampleCount) {
// Convert the Sample to LaRank form
SVector laX;
for (int nFeat = 0; nFeat < sample.x.rows(); nFeat++) {
laX.set(nFeat, sample.x(nFeat));
}
m_svm->predict_with_scores(laX, result);
// Convert the scores to probabilities
double totalProb = 0.0;
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
result.confidence[nClass] = exp(result.confidence[nClass]);
totalProb += result.confidence[nClass];
}
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
result.confidence[nClass] /= (totalProb + 1e-16);
}
} else {
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
result.confidence[nClass] = 1.0 / *m_numClasses;
}
result.prediction = 0;
}
}
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef ONLINE_MCLPBOOST_H
#define ONLINE_MCLPBOOST_H
#include "classifier.h"
#include "booster.h"
#include "data.h"
#include "hyperparameters.h"
#include "utilities.h"
class OnlineMCLPBoost : public Booster {
public:
OnlineMCLPBoost(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange);
virtual void update(Sample& sample);
private:
double m_nuD;
double m_nuP;
int findYPrime(const Sample& sample, const Result& result);
};
#endif // ONLINE_MCLPBOOST_H
<file_sep>// -*- C++ -*-
// Little library of copy-on-write wrappers
// Copyright (C) 2007- <NAME>
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA
// $Id: wrapper.h,v 1.8 2007/10/02 20:40:06 cvs Exp $
#ifndef WRAPPER_H
#define WRAPPER_H 1
template <class Rep>
class Wrapper {
private:
Rep *q;
Rep *ref(Rep *q)
{
q->refcount++;
return q;
}
void deref(Rep *q)
{
if (! --(q->refcount)) delete q;
}
public:
Wrapper()
: q(new Rep)
{
q->refcount = 1;
}
Wrapper(Rep *rep)
: q(rep)
{
q->refcount = 1;
}
Wrapper(const Wrapper<Rep> &other)
: q(ref(other.q))
{
}
~Wrapper()
{
deref(q);
}
Wrapper & operator=(const Wrapper<Rep> &other)
{
Rep *p = q;
q = ref(other.q);
deref(p);
return *this;
}
void detach()
{
if (q->refcount > 1) {
deref(q);
q = q->copy();
q->refcount = 1;
}
}
Rep *rep() const
{
return q;
}
};
// Recommended usage
//
// #include <cstdlib>
// #include <cstring>
//
// class String
// {
// private:
//
// struct Rep
// {
// int refcount;
// int length;
// char *data;
// Rep(const char *s, int l)
// : length(len), data(new char[l+1])
// { ::memcpy(data, s, l); data[len] = 0; }
// Rep *copy()
// { return new StringRep(data, length); }
// };
//
// Wrapper<Rep> w;
// Rep *rep() { return w.rep(); }
// const Rep *rep() const { return w.rep(); }
//
// public:
// String(const char *s, int l)
// : w(new Rep(s,l)) {}
// String(const char *s)
// : w(new Rep(s,::strlen(s))) {}
//
// // function that do not mutate
// int size() const { return rep()->length; }
// operator const char*() const { return rep()->data; }
// char operator[](int i) const { return rep()->data[i]; }
//
// // functions that perform a mutation
// void set(int i, char c) { w.detach(); rep()->data[i] = c; }
// }
//
#endif
/* -------------------------------------------------------------
Local Variables:
c++-font-lock-extra-types: ( "\\sw+_t" "[A-Z]\\sw*[a-z]\\sw*" )
End:
------------------------------------------------------------- */
<file_sep>// -*- C++ -*-
// Copyright (C) 2008- <NAME>
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA
#ifndef LARANK_H_
#define LARANK_H_
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <ctime>
#include <sys/time.h>
#include <ext/hash_map>
#include <ext/hash_set>
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <cfloat>
#include <cassert>
#define STDEXT_NAMESPACE __gnu_cxx
#define std_hash_map STDEXT_NAMESPACE::hash_map
#define std_hash_set STDEXT_NAMESPACE::hash_set
#define VERBOSE_LEVEL 0
#include "vectors.h"
#include "../data.h"
#define jmin(a,b) (((a)<(b))?(a):(b))
#define jmax(a,b) (((a)>(b))?(a):(b))
// EXAMPLER: to read and store data and model files.
class Exampler {
public:
struct example_t {
// AMIR BEGINS
// Added the sample weight
example_t(SVector x, int y)
: inpt(x), cls(y), w(1.0)
{
}
example_t(SVector x, int y, double w)
: inpt(x), cls(y), w(w)
{
}
// AMIR ENDS
example_t()
{
}
SVector inpt;
int cls;
// AMIR BEGINS
double w; // sample weight
// AMIR ENDS
};
typedef std::vector< example_t> examples_t;
// int libsvm_load_data(char *filename, bool model_file)
// {
// int index;
// double value;
// int elements, i;
// FILE *fp = fopen(filename, "r");
// if (fp == NULL) {
// fprintf(stderr, "Can't open input file \"%s\"\n", filename);
// exit(1);
// } else {
// printf("loading \"%s\".. \n", filename);
// }
// int msz = 0;
// elements = 0;
// while (1) {
// int c = fgetc(fp);
// switch (c) {
// case '\n':
// ++msz;
// elements = 0;
// break;
// case ':':
// ++elements;
// break;
// case EOF:
// goto out;
// default:
// ;
// }
// }
// out:
// rewind(fp);
// max_index = 0;
// nb_labels = 0;
// for (i = 0; i < msz; i++) {
// int label;
// SVector v;
// fscanf(fp, "%d", &label);
// if ((int) label >= nb_labels) nb_labels = label;
// while (1) {
// int c;
// do {
// c = getc(fp);
// if (c == '\n') goto out2;
// } while (isspace(c));
// ungetc(c, fp);
// fscanf(fp, "%d:%lf", &index, &value);
// v.set(index, value);
// if (index > max_index) max_index = index;
// }
// out2:
// data.push_back(example_t(v, label));
// }
// fclose(fp);
// if (model_file)
// printf("-> classes: %d\n", msz);
// else
// printf("-> examples: %d features: %d labels: %d\n", msz, max_index, nb_labels);
// nb_ex = msz;
// return msz;
// }
// AMIR BEGINS
// Loads data from Python Numpy
void load_data(const double *inSamples, const int *inLabels, const double *inWeights,
const int& inNumSamples, const int& inNumFeatures, const int& inNumClasses)
{
data.clear();
for (int nSamp = 0; nSamp < inNumSamples; nSamp++) {
SVector dataVec;
for (int nFeat = 0; nFeat < inNumFeatures; nFeat++) {
dataVec.set(nFeat, inSamples[nSamp * inNumFeatures + nFeat]);
}
data.push_back(example_t(dataVec, inLabels[nSamp], inWeights[nSamp]));
}
nb_ex = inNumSamples;
max_index = inNumFeatures;
nb_labels = inNumClasses;
}
void load_data(const double *inSamples, const int *inLabels,
const int& inNumSamples, const int& inNumFeatures, const int& inNumClasses)
{
data.clear();
for (int nSamp = 0; nSamp < inNumSamples; nSamp++) {
SVector dataVec;
for (int nFeat = 0; nFeat < inNumFeatures; nFeat++) {
dataVec.set(nFeat, inSamples[nSamp * inNumFeatures + nFeat]);
}
data.push_back(example_t(dataVec, inLabels[nSamp]));
}
nb_ex = inNumSamples;
max_index = inNumFeatures;
nb_labels = inNumClasses;
}
// Loads SVM weight vector from Python Numpy
void load_weights(const double *inW, const int& inNumFeatures, const int& inNumClasses)
{
data.clear();
for (int nClass = 0; nClass < inNumClasses; nClass++) {
SVector dataVec;
for (int nFeat = 0; nFeat < inNumFeatures; nFeat++) {
dataVec.set(nFeat, inW[nClass * inNumFeatures + nFeat]);
}
data.push_back(example_t(dataVec, nClass));
}
nb_ex = inNumClasses;
max_index = inNumFeatures;
nb_labels = inNumClasses;
}
// AMIR ENDS
// ...
examples_t data;
int nb_ex;
int max_index;
int nb_labels;
};
// LARANKPATTERN: to keep track of the support patterns
class LaRankPattern {
public:
// AMIR BEGINS
// Added the sample weight
LaRankPattern(int x_id, const SVector& x, int y, double w)
: x_id(x_id), x(x), y(y), w(w)
{
}
LaRankPattern(int x_id, const SVector& x, int y)
: x_id(x_id), x(x), y(y), w(1.0)
{
}
// AMIR ENDS
LaRankPattern()
: x_id(0)
{
}
bool exists() const
{
return x_id >= 0;
}
void clear()
{
x_id = -1;
}
int x_id;
SVector x;
int y;
// AMIR BEGINS
double w; // sample weight
// AMIR ENDS
};
// LARANKPATTERNS: the collection of support patterns
class LaRankPatterns {
public:
LaRankPatterns()
{
}
~LaRankPatterns()
{
}
void insert(const LaRankPattern& pattern)
{
if (!isPattern(pattern.x_id)) {
if (freeidx.size()) {
std_hash_set<unsigned>::iterator it = freeidx.begin();
patterns[*it] = pattern;
x_id2rank[pattern.x_id] = *it;
freeidx.erase(it);
} else {
patterns.push_back(pattern);
x_id2rank[pattern.x_id] = patterns.size() - 1;
}
} else {
int rank = getPatternRank(pattern.x_id);
patterns[rank] = pattern;
}
}
void remove(unsigned i)
{
x_id2rank[patterns[i].x_id] = 0;
patterns[i].clear();
freeidx.insert(i);
}
bool empty() const
{
return patterns.size() == freeidx.size();
}
unsigned size() const
{
return patterns.size() - freeidx.size();
}
LaRankPattern& sample()
{
assert(!empty());
while (true) {
unsigned r = rand() % patterns.size();
if (patterns[r].exists())
return patterns[r];
}
return patterns[0];
}
unsigned getPatternRank(int x_id)
{
return x_id2rank[x_id];
}
bool isPattern(int x_id)
{
return x_id2rank[x_id] != 0;
}
LaRankPattern& getPattern(int x_id)
{
unsigned rank = x_id2rank[x_id];
return patterns[rank];
}
unsigned maxcount() const
{
return patterns.size();
}
LaRankPattern & operator [](unsigned i)
{
return patterns[i];
}
const LaRankPattern & operator [](unsigned i) const
{
return patterns[i];
}
private:
std_hash_set<unsigned> freeidx;
std::vector<LaRankPattern> patterns;
std_hash_map<int, unsigned> x_id2rank;
};
// MACHINE: the thing we learn
class Machine {
public:
virtual ~Machine()
{
};
//MAIN functions for training and testing
virtual int add(const SVector& x, int classnumber, int x_id) = 0;
// AMIR BEGINS
// Added sample weight for learning phase
virtual int add(const SVector& x, int classnumber, int x_id, double w) = 0;
// AMIR ENDS
virtual int predict(const SVector& x) = 0;
virtual void predict_with_scores(const SVector& x, Result& result) = 0;
// Functions for saving and loading model
virtual void save_outputs(std::ostream& ostr) = 0;
// AMIR BEGINS
// Used for saving the SVM weights back to Python Numpy
virtual void get_weights(double* outW, const int inNumFeatures) = 0;
// AMIR ENDS
virtual void add_output(int y, LaFVector wy) = 0;
// Information functions
virtual void printStuff(double initime, bool dual) = 0;
virtual double computeGap() = 0;
std_hash_set<int> classes;
unsigned class_count() const
{
return classes.size();
}
double C;
double tau;
};
class LaRankOutput {
public:
LaRankOutput()
{
}
LaRankOutput(LaFVector& w)
: wy(w)
{
}
~LaRankOutput()
{
}
double computeGradient(const SVector& xi, int yi, int ythis)
{
return (yi == ythis ? 1 : 0) -computeScore(xi);
}
double computeScore(const SVector& x)
{
return dot(wy, x);
}
void update(const SVector& xi, double lambda, int xi_id)
{
wy.add(xi, lambda);
double oldb = beta.get(xi_id);
beta.set(xi_id, oldb + lambda);
}
void save_output(std::ostream& ostr, int ythis) const
{
ostr << ythis << " " << wy;
}
// AMIR BEGINS
// Used for saving the SVM weights back to Python Numpy
void get_weights(double* outW, int inNumFeatures, int ythis) const
{
for (int nFeat = 0; nFeat < inNumFeatures; nFeat++) {
outW[ythis * inNumFeatures + nFeat] = wy.get(nFeat);
}
}
// AMIR ENDS
double getBeta(int x_id) const
{
return beta.get(x_id);
}
bool isSupportVector(int x_id) const
{
return beta.get(x_id) != 0;
}
int getNSV() const
{
int res = 0;
for (int i = 0; i < beta.size(); i++)
if (beta.get(i) != 0)
res++;
return res;
}
double getW2() const
{
return dot(wy, wy);
}
private:
// BETA: keep track of the bea value of each support vector (indicator)
SVector beta;
// WY: conains the prediction information
LaFVector wy;
};
inline double getTime()
{
struct timeval tv;
struct timezone tz;
long int sec;
long int usec;
double mytime;
gettimeofday(&tv, &tz);
sec = (long int) tv.tv_sec;
usec = (long int) tv.tv_usec;
mytime = (double) sec + usec * 0.000001;
return mytime;
}
class LaRank : public Machine {
public:
LaRank() : nb_seen_examples(0), nb_removed(0),
n_pro(0), n_rep(0), n_opt(0),
w_pro(1), w_rep(1), w_opt(1), dual(0)
{
}
~LaRank()
{
}
// LEARNING FUNCTION: add new patterns and run optimization steps selected with dapatative schedule
virtual int add(const SVector& xi, int yi, int x_id)
{
++nb_seen_examples;
// create a new output object if never seen this one before
if (!getOutput(yi))
outputs.insert(std::make_pair(yi, LaRankOutput()));
LaRankPattern tpattern(x_id, xi, yi);
LaRankPattern &pattern = (patterns.isPattern(x_id)) ? patterns.getPattern(x_id) : tpattern;
// ProcessNew with the "fresh" pattern
double time1 = getTime();
process_return_t pro_ret = process(pattern, processNew);
double dual_increase = pro_ret.dual_increase;
dual += dual_increase;
double duration = (getTime() - time1);
double coeff = dual_increase / (10 * (0.00001 + duration));
n_pro++;
w_pro = 0.05 * coeff + (1 - 0.05) * w_pro;
// ProcessOld & Optimize until ready for a new processnew
// (Adaptative schedule here)
for (;;) {
double w_sum = w_pro + w_rep + w_opt;
double prop_min = w_sum / 20;
if (w_pro < prop_min)
w_pro = prop_min;
if (w_rep < prop_min)
w_rep = prop_min;
if (w_opt < prop_min)
w_opt = prop_min;
w_sum = w_pro + w_rep + w_opt;
double r = rand() / (double) RAND_MAX * w_sum;
if (r <= w_pro) {
break;
} else if ((r > w_pro) && (r <= w_pro + w_rep)) {
double time1 = getTime();
double dual_increase = reprocess();
dual += dual_increase;
double duration = (getTime() - time1);
double coeff = dual_increase / (0.00001 + duration);
n_rep++;
w_rep = 0.05 * coeff + (1 - 0.05) * w_rep;
} else {
double time1 = getTime();
double dual_increase = optimize();
dual += dual_increase;
double duration = (getTime() - time1);
double coeff = dual_increase / (0.00001 + duration);
n_opt++;
w_opt = 0.05 * coeff + (1 - 0.05) * w_opt;
}
}
if (nb_seen_examples % 100 == 0)
nb_removed += cleanup();
return pro_ret.ypred;
}
// AMIR BEGINS
virtual int add(const SVector& xi, int yi, int x_id, double w)
{
++nb_seen_examples;
// create a new output object if never seen this one before
if (!getOutput(yi))
outputs.insert(std::make_pair(yi, LaRankOutput()));
LaRankPattern tpattern(x_id, xi, yi, w);
LaRankPattern &pattern = (patterns.isPattern(x_id)) ? patterns.getPattern(x_id) : tpattern;
// ProcessNew with the "fresh" pattern
double time1 = getTime();
process_return_t pro_ret = process_w(pattern, processNew);
double dual_increase = pro_ret.dual_increase;
dual += dual_increase;
double duration = (getTime() - time1);
double coeff = dual_increase / (10 * (0.00001 + duration));
n_pro++;
w_pro = 0.05 * coeff + (1 - 0.05) * w_pro;
// ProcessOld & Optimize until ready for a new processnew
// (Adaptative schedule here)
for (;;) {
double w_sum = w_pro + w_rep + w_opt;
double prop_min = w_sum / 20;
if (w_pro < prop_min)
w_pro = prop_min;
if (w_rep < prop_min)
w_rep = prop_min;
if (w_opt < prop_min)
w_opt = prop_min;
w_sum = w_pro + w_rep + w_opt;
double r = rand() / (double) RAND_MAX * w_sum;
if (r <= w_pro) {
break;
} else if ((r > w_pro) && (r <= w_pro + w_rep)) {
double time1 = getTime();
double dual_increase = reprocess();
dual += dual_increase;
double duration = (getTime() - time1);
double coeff = dual_increase / (0.00001 + duration);
n_rep++;
w_rep = 0.05 * coeff + (1 - 0.05) * w_rep;
} else {
double time1 = getTime();
double dual_increase = optimize();
dual += dual_increase;
double duration = (getTime() - time1);
double coeff = dual_increase / (0.00001 + duration);
n_opt++;
w_opt = 0.05 * coeff + (1 - 0.05) * w_opt;
}
}
if (nb_seen_examples % 100 == 0)
nb_removed += cleanup();
return pro_ret.ypred;
}
// AMIR ENDS
// PREDICTION FUNCTION: main function in la_rank_classify
virtual int predict(const SVector& x)
{
int res = -1;
double score_max = -DBL_MAX;
for (outputhash_t::iterator it = outputs.begin(); it != outputs.end(); ++it) {
double score = it->second.computeScore(x);
if (score > score_max) {
score_max = score;
res = it->first;
}
}
return res;
}
// AMIR BEGINS
// Returns the confidence/label pair back
virtual void predict_with_scores(const SVector& x, Result& result)
{
int res = -1, nClass = 0;
double score_max = -DBL_MAX;
for (outputhash_t::iterator it = outputs.begin(); it != outputs.end(); ++it, nClass++) {
double score = it->second.computeScore(x);
result.confidence[nClass] = score;
if (score > score_max) {
score_max = score;
res = it->first;
}
}
result.prediction = res;
}
// AMIR ENDS
// Used for saving a model file
virtual void save_outputs(std::ostream& ostr)
{
for (outputhash_t::const_iterator it = outputs.begin(); it != outputs.end(); ++it)
it->second.save_output(ostr, it->first);
}
// AMIR BEGINS
// Used for saving the SVM weights back to Python Numpy
virtual void get_weights(double* outW, const int inNumFeatures)
{
for (outputhash_t::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
it->second.get_weights(outW, inNumFeatures, it->first);
}
}
// AMIR ENDS
// Used for loading a model file
virtual void add_output(int y, LaFVector wy)
{
outputs.insert(std::make_pair(y, LaRankOutput(wy)));
}
// Compute Duality gap (costly but used in stopping criteria in batch mode)
virtual double computeGap()
{
double sum_sl = 0;
double sum_bi = 0;
for (unsigned i = 0; i < patterns.maxcount(); ++i) {
const LaRankPattern& p = patterns[i];
if (!p.exists())
continue;
LaRankOutput* out = getOutput(p.y);
if (!out)
continue;
sum_bi += out->getBeta(p.x_id);
double gi = out->computeGradient(p.x, p.y, p.y);
double gmin = DBL_MAX;
for (outputhash_t::iterator it = outputs.begin(); it != outputs.end(); ++it) {
if (it->first != p.y && it->second.isSupportVector(p.x_id)) {
double g = it->second.computeGradient(p.x, p.y, it->first);
if (g < gmin)
gmin = g;
}
}
sum_sl += jmax(0, gi - gmin);
}
return jmax(0, getW2() + C * sum_sl - sum_bi);
}
// Display stuffs along learning
virtual void printStuff(double initime, bool dual)
{
std::cout << "Current duration (CPUs): " << getTime() - initime << std::endl;
if (dual)
std::cout << "Dual: " << getDual() << " (w2: " << getW2() << ")" << std::endl;
std::cout << "Number of Support Patterns: " << patterns.size() << " / " << nb_seen_examples << " (removed:" << nb_removed << ")" << std::endl;
double w_sum = w_pro + w_rep + w_opt;
std::cout << "ProcessNew:" << n_pro << " (" << w_pro / w_sum << ") ProcessOld:" << n_rep << " (" << w_rep / w_sum << ") Optimize:" << n_opt << " (" << w_opt / w_sum << ")" << std::endl;
std::cout << "\t......" << std::endl;
}
virtual unsigned getNumOutputs() const
{
return outputs.size();
}
private:
/*
MAIN DARK OPTIMIZATION PROCESSES
*/
typedef std_hash_map<int, LaRankOutput> outputhash_t; // class index -> LaRankOutput
outputhash_t outputs;
LaRankOutput* getOutput(int index)
{
outputhash_t::iterator it = outputs.find(index);
return it == outputs.end() ? NULL : &it->second;
}
const LaRankOutput* getOutput(int index) const
{
outputhash_t::const_iterator it = outputs.find(index);
return it == outputs.end() ? NULL : &it->second;
}
LaRankPatterns patterns;
int nb_seen_examples;
int nb_removed;
int n_pro;
int n_rep;
int n_opt;
double w_pro;
double w_rep;
double w_opt;
double dual;
struct outputgradient_t {
outputgradient_t(int output, double gradient)
: output(output), gradient(gradient)
{
}
outputgradient_t()
: output(0), gradient(0)
{
}
int output;
double gradient;
bool operator<(const outputgradient_t & og) const
{
return gradient > og.gradient;
}
};
//3 types of operations in LaRank
enum process_type {
processNew,
processOld,
processOptimize
};
struct process_return_t {
process_return_t(double dual, int ypred)
: dual_increase(dual), ypred(ypred)
{
}
process_return_t()
{
}
double dual_increase;
int ypred;
};
//Main optimization step
process_return_t process(const LaRankPattern& pattern, process_type ptype)
{
process_return_t pro_ret = process_return_t(0, 0);
std::vector<outputgradient_t> outputgradients;
outputgradients.reserve(getNumOutputs());
std::vector<outputgradient_t> outputscores;
outputscores.reserve(getNumOutputs());
//Compute gradient and sort
for (outputhash_t::iterator it = outputs.begin(); it != outputs.end(); ++it)
if (ptype != processOptimize || it->second.isSupportVector(pattern.x_id)) {
double g = it->second.computeGradient(pattern.x, pattern.y, it->first);
outputgradients.push_back(outputgradient_t(it->first, g));
if (it->first == pattern.y)
outputscores.push_back(outputgradient_t(it->first, (1 - g)));
else
outputscores.push_back(outputgradient_t(it->first, -g));
}
std::sort(outputgradients.begin(), outputgradients.end());
//Determine the prediction and its confidence
std::sort(outputscores.begin(), outputscores.end());
pro_ret.ypred = outputscores[0].output;
//Find yp
outputgradient_t ygp;
LaRankOutput* outp = NULL;
unsigned p;
for (p = 0; p < outputgradients.size(); ++p) {
outputgradient_t& current = outputgradients[p];
LaRankOutput* output = getOutput(current.output);
bool support = ptype == processOptimize || output->isSupportVector(pattern.x_id);
bool goodclass = current.output == pattern.y;
if ((!support && goodclass) || (support && output->getBeta(pattern.x_id) < (goodclass ? C : 0))) {
ygp = current;
outp = output;
break;
}
}
if (p == outputgradients.size())
return pro_ret;
//Find ym
outputgradient_t ygm;
LaRankOutput* outm = NULL;
int m;
for (m = outputgradients.size() - 1; m >= 0; --m) {
outputgradient_t& current = outputgradients[m];
LaRankOutput* output = getOutput(current.output);
bool support = ptype == processOptimize || output->isSupportVector(pattern.x_id);
bool goodclass = current.output == pattern.y;
if (!goodclass || (support && output->getBeta(pattern.x_id) > 0)) {
ygm = current;
outm = output;
break;
}
}
if (m < 0)
return pro_ret;
//Throw or insert pattern
if ((ygp.gradient - ygm.gradient) < tau)
return pro_ret;
if (ptype == processNew)
patterns.insert(pattern);
//Compute lambda and clippe it
double kii = dot(pattern.x, pattern.x);
double lambda = (ygp.gradient - ygm.gradient) / (2 * kii);
if (ptype == processOptimize || outp->isSupportVector(pattern.x_id)) {
double beta = outp->getBeta(pattern.x_id);
if (ygp.output == pattern.y)
lambda = jmin(lambda, C - beta);
else
lambda = jmin(lambda, fabs(beta));
} else
lambda = jmin(lambda, C);
//Update parameters
outp->update(pattern.x, lambda, pattern.x_id);
outm->update(pattern.x, -lambda, pattern.x_id);
pro_ret.dual_increase = lambda * ((ygp.gradient - ygm.gradient) - lambda * kii);
return pro_ret;
}
// AMIR BEGINS
process_return_t process_w(const LaRankPattern& pattern, process_type ptype)
{
process_return_t pro_ret = process_return_t(0, 0);
std::vector<outputgradient_t> outputgradients;
outputgradients.reserve(getNumOutputs());
std::vector<outputgradient_t> outputscores;
outputscores.reserve(getNumOutputs());
//Compute gradient and sort
for (outputhash_t::iterator it = outputs.begin(); it != outputs.end(); ++it)
if (ptype != processOptimize || it->second.isSupportVector(pattern.x_id)) {
double g = it->second.computeGradient(pattern.x, pattern.y, it->first);
outputgradients.push_back(outputgradient_t(it->first, g));
if (it->first == pattern.y)
outputscores.push_back(outputgradient_t(it->first, (1 - g)));
else
outputscores.push_back(outputgradient_t(it->first, -g));
}
std::sort(outputgradients.begin(), outputgradients.end());
//Determine the prediction and its confidence
std::sort(outputscores.begin(), outputscores.end());
pro_ret.ypred = outputscores[0].output;
//Find yp
outputgradient_t ygp;
LaRankOutput* outp = NULL;
unsigned p;
for (p = 0; p < outputgradients.size(); ++p) {
outputgradient_t& current = outputgradients[p];
LaRankOutput* output = getOutput(current.output);
bool support = ptype == processOptimize || output->isSupportVector(pattern.x_id);
bool goodclass = current.output == pattern.y;
if ((!support && goodclass) || (support && output->getBeta(pattern.x_id) < (goodclass ? C * pattern.w : 0))) {
ygp = current;
outp = output;
break;
}
}
if (p == outputgradients.size())
return pro_ret;
//Find ym
outputgradient_t ygm;
LaRankOutput* outm = NULL;
int m;
for (m = outputgradients.size() - 1; m >= 0; --m) {
outputgradient_t& current = outputgradients[m];
LaRankOutput* output = getOutput(current.output);
bool support = ptype == processOptimize || output->isSupportVector(pattern.x_id);
bool goodclass = current.output == pattern.y;
if (!goodclass || (support && output->getBeta(pattern.x_id) > 0)) {
ygm = current;
outm = output;
break;
}
}
if (m < 0)
return pro_ret;
//Throw or insert pattern
if ((ygp.gradient - ygm.gradient) < tau)
return pro_ret;
if (ptype == processNew)
patterns.insert(pattern);
//Compute lambda and clippe it
double kii = dot(pattern.x, pattern.x);
double lambda = (ygp.gradient - ygm.gradient) / (2 * kii);
if (ptype == processOptimize || outp->isSupportVector(pattern.x_id)) {
double beta = outp->getBeta(pattern.x_id);
if (ygp.output == pattern.y)
lambda = jmin(lambda, C * pattern.w - beta);
else
lambda = jmin(lambda, fabs(beta));
} else
lambda = jmin(lambda, C * pattern.w);
//Update parameters
outp->update(pattern.x, lambda, pattern.x_id);
outm->update(pattern.x, -lambda, pattern.x_id);
pro_ret.dual_increase = lambda * ((ygp.gradient - ygm.gradient) - lambda * kii);
return pro_ret;
}
// AMIR ENDS
// 2nd optimization fiunction of LaRank (= ProcessOld in the paper)
double reprocess()
{
if (patterns.size())
for (int n = 0; n < 10; ++n) {
process_return_t pro_ret = process(patterns.sample(), processOld);
if (pro_ret.dual_increase)
return pro_ret.dual_increase;
}
return 0;
}
// 3rd optimization function of LaRank
double optimize()
{
double dual_increase = 0;
if (patterns.size())
for (int n = 0; n < 10; ++n) {
process_return_t pro_ret = process(patterns.sample(), processOptimize);
dual_increase += pro_ret.dual_increase;
}
return dual_increase;
}
// remove patterns and return the number of patterns that were removed
unsigned cleanup()
{
unsigned res = 0;
for (unsigned i = 0; i < patterns.size(); ++i) {
LaRankPattern& p = patterns[i];
if (p.exists() && !outputs[p.y].isSupportVector(p.x_id)) {
patterns.remove(i);
++res;
}
}
return res;
}
/*
INFORMATION FUNCTIONS: display/compute parameter values of the algorithm
*/
// Number of Support Vectors
int getNSV() const
{
int res = 0;
for (outputhash_t::const_iterator it = outputs.begin(); it != outputs.end(); ++it)
res += it->second.getNSV();
return res;
}
// Square-norm of the weight vector w
double getW2() const
{
double res = 0;
for (outputhash_t::const_iterator it = outputs.begin(); it != outputs.end(); ++it)
res += it->second.getW2();
return res;
}
// Square-norm of the weight vector w (another way of computing it, very costly)
double computeW2()
{
double res = 0;
for (unsigned i = 0; i < patterns.maxcount(); ++i) {
const LaRankPattern& p = patterns[i];
if (!p.exists())
continue;
for (outputhash_t::iterator it = outputs.begin(); it != outputs.end(); ++it)
if (it->second.getBeta(p.x_id))
res += it->second.getBeta(p.x_id) * it->second.computeScore(p.x);
}
return res;
}
// DUAL objective value
double getDual()
{
double res = 0;
for (unsigned i = 0; i < patterns.maxcount(); ++i) {
const LaRankPattern& p = patterns[i];
if (!p.exists())
continue;
const LaRankOutput* out = getOutput(p.y);
if (!out)
continue;
res += out->getBeta(p.x_id);
}
return res - getW2() / 2;
}
};
#endif // !LARANK_H_
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef ONLINEMCBOOST_H_
#define ONLINEMCBOOST_H_
#include <cmath>
#include "classifier.h"
#include "booster.h"
#include "data.h"
#include "hyperparameters.h"
#include "utilities.h"
class OnlineMCBoost: public Booster {
public:
OnlineMCBoost(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange);
virtual void update(Sample& sample);
private:
inline double d_exp(const double& fy) {
return exp(-fy);
}
inline double d_logit(const double& fy) {
return 1.0 / (1.0 + exp(fy));
}
};
#endif /* ONLINEMCBOOST_H_ */
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include "online_mcboost.h"
OnlineMCBoost::OnlineMCBoost(const Hyperparameters& hp, const int& numClasses, const int& numFeatures,
const VectorXd& minFeatRange, const VectorXd& maxFeatRange) :
Booster(hp, numClasses, numFeatures, minFeatRange, maxFeatRange) {
m_name = "OnlineMCBoost";
}
void OnlineMCBoost::update(Sample& sample) {
sample.w = 1.0;
double fy = 0.0;
for (int nBase = 0; nBase < m_hp->numBases; nBase++) {
Result baseResult(*m_numClasses);
m_bases[nBase]->update(sample);
m_bases[nBase]->eval(sample, baseResult);
fy += m_hp->shrinkage * (baseResult.confidence(sample.y) - 1.0 / (*m_numClasses));
switch (m_hp->lossFunction) {
case EXPONENTIAL: {
sample.w = d_exp(fy);
break;
}
case LOGIT: {
sample.w = d_logit(fy);
break;
}
}
}
}
<file_sep># This is a make file for OMCBoost package
# <NAME>, <EMAIL>
#
# Modified for the OPS-SAT spacecraft's OrbitAI experiment
# <NAME>, <EMAIL>
#-----------------------------------------
TARGET = dev
# Compiler options
CC_DEV = g++
CC_ARM = /usr/bin/arm-linux-gnueabihf-g++
INCLUDEPATH = -I/usr/local/include -I../eigen -I$(HOME)/local/include
LINKPATH = -L/usr/local/lib -L$(HOME)/local/lib
# OPTIMIZED
# Compile for gcc development environment:
CFLAGS_DEV = -c -O3 -Wall -march=native -mtune=native -DNDEBUG -Wno-deprecated
# Compile for ARM gcc target environment:
CFLAGS_ARM = -c -O3 -Wall -DNDEBUG -Wno-deprecated
# libconfig++ depedency.
LDFLAGS = -lconfig++ -lboost_serialization
# Source directory and files
SOURCEDIR = src
HEADERS := $(wildcard $(SOURCEDIR)/*.h)
SOURCES := $(wildcard $(SOURCEDIR)/*.cpp)
OBJECTS := $(SOURCES:.cpp=.o)
LIBLARANKDIR := $(SOURCEDIR)/linear_larank
# Target output
BUILDTARGET = OrbitAI_OMCBoost
# Target compiler environment.
ifeq ($(TARGET),arm)
CC = $(CC_ARM)
CFLAGS = $(CFLAGS_ARM)
else
CC = $(CC_DEV)
CFLAGS = $(CFLAGS_DEV)
endif
# Build
all: $(BUILDTARGET)
$(BUILDTARGET): $(OBJECTS) $(SOURCES) $(HEADERS) $(LIBLARANKDIR)/LaRank.o $(LIBLARANKDIR)/vectors.o
$(CC) $(LINKPATH) $(OBJECTS) $(LIBLARANKDIR)/LaRank.o $(LIBLARANKDIR)/vectors.o -o $@ $(LDFLAGS)
.cpp.o:
$(CC) $(CFLAGS) $(INCLUDEPATH) $< -o $@
$(LIBLARANKDIR)/LaRank.o: $(LIBLARANKDIR)/LaRank.cpp $(LIBLARANKDIR)/LaRank.h $(LIBLARANKDIR)/vectors.o
$(CC) $(CFLAGS) $(INCLUDEPATH) -o $(LIBLARANKDIR)/LaRank.o $(LIBLARANKDIR)/LaRank.cpp
$(LIBLARANKDIR)/vectors.o: $(LIBLARANKDIR)/vectors.h $(LIBLARANKDIR)/wrapper.h
$(CC) $(CFLAGS) $(INCLUDEPATH) -o $(LIBLARANKDIR)/vectors.o $(LIBLARANKDIR)/vectors.cpp
clean:
rm -f $(SOURCEDIR)/*~ $(SOURCEDIR)/*.o
rm -f $(LIBLARANKDIR)/*.o
rm -f $(BUILDTARGET)<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef LINEARLARANK_H_
#define LINEARLARANK_H_
#include "classifier.h"
#include "data.h"
#include "hyperparameters.h"
#include "utilities.h"
#include "linear_larank/LaRank.h"
#include "linear_larank/vectors.h"
class LinearLaRank: public Classifier {
public:
LinearLaRank(const Hyperparameters& hp, const int& numClasses, const int& numFeatures, const VectorXd& minFeatRange, const VectorXd& maxFeatRange);
~LinearLaRank();
virtual void update(Sample& sample);
virtual void eval(Sample& sample, Result& result);
protected:
Machine* m_svm;
int m_sampleCount;
const int* m_numFeatures;
};
#endif /* LINEARLARANK_H_ */
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include "booster.h"
#include "online_rf.h"
#include "linear_larank.h"
Booster::Booster(const Hyperparameters& hp, const int& numClasses, const int& numFeatures,
const VectorXd& minFeatRange, const VectorXd& maxFeatRange) :
Classifier(hp, numClasses), m_w(VectorXd::Constant(hp.numBases, hp.shrinkage)) {
switch (hp.weakLearner) {
case WEAK_ORF: {
OnlineRF *weakLearner;
for (int nBase = 0; nBase < hp.numBases; nBase++) {
weakLearner = new OnlineRF(hp, numClasses, numFeatures, minFeatRange, maxFeatRange);
m_bases.push_back(weakLearner);
}
break;
}
case WEAK_LARANK: {
LinearLaRank *weakLearner;
for (int nBase = 0; nBase < hp.numBases; nBase++) {
weakLearner = new LinearLaRank(hp, numClasses, numFeatures, minFeatRange, maxFeatRange);
m_bases.push_back(weakLearner);
}
break;
}
}
}
Booster::~Booster() {
for (int nBase = 0; nBase < m_hp->numBases; nBase++) {
delete m_bases[nBase];
}
}
void Booster::eval(Sample& sample, Result& result) {
for (int nBase = 0; nBase < m_hp->numBases; nBase++) {
Result baseResult(*m_numClasses);
m_bases[nBase]->eval(sample, baseResult);
baseResult.confidence *= m_w(nBase);
result.confidence += baseResult.confidence;
}
result.confidence.maxCoeff(&result.prediction);
}
<file_sep>SHELL=/bin/sh
CFLAGS= -O3 -march=native -mtune=native -Wall
TOOLS= LaRank.cpp vectors.cpp
TOOLSINCL= LaRank.h vectors.h wrapper.h
LARANKSRC= LaRankLearn.cpp
LARANKTESTSRC= LaRankClassify.cpp
all: la_rank_learn la_rank_classify
la_rank_learn: $(LARANKSRC) $(TOOLS) $(TOOLSINCL)
$(CXX) $(CFLAGS) -o la_rank_learn $(LARANKSRC) $(TOOLS) -lm
la_rank_classify: $(LARANKTESTSRC) $(TOOLS) $(TOOLSINCL)
$(CXX) $(CFLAGS) -o la_rank_classify $(LARANKTESTSRC) $(TOOLS) -lm
clean: FORCE
rm 2>/dev/null la_rank_learn la_rank_classify
FORCE:
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#include "online_mclpboost.h"
OnlineMCLPBoost::OnlineMCLPBoost(const Hyperparameters& hp, const int& numClasses, const int& numFeatures,
const VectorXd& minFeatRange, const VectorXd& maxFeatRange) :
Booster(hp, numClasses, numFeatures, minFeatRange, maxFeatRange), m_nuD(hp.nuD), m_nuP(hp.nuP) {
m_name = "OnlineMCLPBoost";
}
void OnlineMCLPBoost::update(Sample& sample) {
// Update the cache
if ((int) m_cache.size() == m_hp->cacheSize) {
m_cache.erase(m_cache.begin());
}
m_cache.push_back(Cache(sample, m_hp->numBases, *m_numClasses));
// Evaluate the samples in cache
for (int nCache = 0; nCache < (int) m_cache.size(); nCache++) {
m_cache[nCache].cacheSample.w = m_hp->C;
// Evaluate this sample and find yPrime
Result yPrimeResults(*m_numClasses);
eval(m_cache[nCache].cacheSample, yPrimeResults);
m_cache[nCache].yPrime = findYPrime(m_cache[nCache].cacheSample, yPrimeResults);
m_cache[nCache].margin = yPrimeResults.confidence(m_cache[nCache].cacheSample.y) - yPrimeResults.confidence(m_cache[nCache].yPrime);
}
// Annealing
m_nuP *= m_hp->annealingRate;
m_nuD *= m_hp->annealingRate;
// Primal/Dual gradient descent/ascent
VectorXd q = VectorXd::Ones(m_hp->numBases, 1.0);
vector<vector<double> > dG(m_hp->numBases);
double e, z, nuThetaInv = m_nuD / m_hp->theta;
for (int nBase = 0; nBase < m_hp->numBases; nBase++) {
// Dual
VectorXd sampleW(m_cache.size());
for (int nCache = 0; nCache < (int) m_cache.size(); nCache++) {
Result baseResult(*m_numClasses);
m_bases[nBase]->update(m_cache[nCache].cacheSample);
m_bases[nBase]->eval(m_cache[nCache].cacheSample, baseResult);
dG[nBase].push_back(baseResult.confidence(m_cache[nCache].cacheSample.y) -
baseResult.confidence(m_cache[nCache].yPrime));
sampleW(nCache) = m_cache[nCache].cacheSample.w;
e = 0.0;
for (int nBase1 = 0; nBase1 < nBase; nBase1++) {
if (q(nBase1) < 0.0) {
e += nuThetaInv * q(nBase1) * dG[nBase1][nCache];
}
}
sampleW(nCache) = max(0.0, min(m_hp->C, sampleW(nCache) + m_nuD + e));
}
// Primal
z = 0.0;
for (int nCache = 0; nCache < (int) m_cache.size(); nCache++) {
z += m_cache[nCache].cacheSample.w * dG[nBase][nCache];
}
z = m_w(nBase) - m_nuP * (1.0 - z);
m_w(nBase) = max(0.0, z);
// Slack update
q(nBase) = 1.0 - m_hp->theta * m_w(nBase);
for (int nCache = 0; nCache < (int) m_cache.size(); nCache++) {
m_cache[nCache].cacheSample.w = sampleW(nCache);
q(nBase) -= m_cache[nCache].cacheSample.w * dG[nBase][nCache];
}
}
}
int OnlineMCLPBoost::findYPrime(const Sample& sample, const Result& result) {
int yPrime = 0;
double maxF = -1e6;
for (int nClass = 0; nClass < *m_numClasses; nClass++) {
if (nClass != sample.y && result.confidence(nClass) > maxF) {
maxF = result.confidence(nClass);
yPrime = nClass;
}
}
return yPrime;
}
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef DATA_H_
#define DATA_H_
#include <fstream>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <Eigen/Core>
#include <Eigen/Array>
using namespace std;
using namespace Eigen;
// DATA CLASSES
class Sample {
public:
VectorXd x;
int y;
double w;
int id;
};
class DataSet {
public:
void findFeatRange();
void load(const string& x_filename, const string& y_filename);
vector<Sample> m_samples;
int m_numSamples;
int m_numFeatures;
int m_numClasses;
VectorXd m_minFeatRange;
VectorXd m_maxFeatRange;
};
class Result {
public:
Result();
Result(const int& numClasses);
VectorXd confidence;
int prediction;
};
class Cache {
public:
Cache();
Cache(const Sample& sample, const int& numBases, const int& numClasses);
Sample cacheSample;
double margin;
int yPrime; // Class with closest margin to the sample
};
#endif /* DATA_H_ */
<file_sep>// -*- C++ -*-
/*
* 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.
*
* Written (W) 2010 <NAME>, <EMAIL>
* Copyright (C) 2010 <NAME>,
* Institute for Computer Graphics and Vision,
* Graz University of Technology, Austria
*/
#ifndef EXPERIMENTER_H
#define EXPERIMENTER_H
#include "classifier.h"
#include "data.h"
#include "utilities.h"
void train(Classifier* model, DataSet& dataset, Hyperparameters& hp);
vector<Result> test(Classifier* model, DataSet& dataset, Hyperparameters& hp);
vector<Result> trainAndTest(Classifier* model, DataSet& dataset_tr, DataSet& dataset_ts, Hyperparameters& hp);
double compError(const vector<Result>& results, const DataSet& dataset);
void dispErrors(const vector<double>& errors);
#endif // EXPERIMENTER_H
|
f7052b44013b4d931268fbc548b9dd339c751c36
|
[
"Makefile",
"C++"
] | 20 |
C++
|
georgeslabreche/online-multiclass-lpboost
|
7c14d6f3102b8b7e432796bdf0d48ee2af2eeffb
|
c11c4eeb45492781e29753e58ed86f32e125f51b
|
refs/heads/master
|
<repo_name>mre/twox-hash<file_sep>/comparison/Cargo.toml
[package]
authors = ["<NAME> <<EMAIL>>"]
name = "comparison"
version = "0.1.0"
[dependencies]
fnv = "1.0"
quickcheck = "0.4.1"
rand = "0.3.15"
xxhash2 = "0.1.0"
[dependencies.twox-hash]
path = ".."
[features]
bench = []
<file_sep>/Cargo.toml
[package]
name = "twox-hash"
version = "1.1.2"
authors = ["<NAME> <<EMAIL>>"]
description = "A Rust implementation of the XXHash algorithm"
readme = "README.md"
keywords = ["hash"]
categories = ["algorithms"]
repository = "https://github.com/shepmaster/twox-hash"
documentation = "https://docs.rs/twox-hash/"
license = "MIT"
[dependencies]
rand = ">= 0.3.10, < 0.7"
<file_sep>/comparison/src/bench.rs
use std::hash::{Hasher,SipHasher};
use test;
use fnv;
use twox_hash::{XxHash, XxHash32};
fn hasher_bench<H>(b: &mut test::Bencher, mut hasher: H, len: usize)
where H: Hasher
{
let bytes: Vec<_> = (0..100).cycle().take(len).collect();
b.bytes = bytes.len() as u64;
b.iter(|| {
hasher.write(&bytes);
hasher.finish()
});
}
fn xxhash_bench(b: &mut test::Bencher, len: usize) {
hasher_bench(b, XxHash::with_seed(0), len)
}
fn xxhash32_bench(b: &mut test::Bencher, len: usize) {
hasher_bench(b, XxHash32::with_seed(0), len)
}
fn siphash_bench(b: &mut test::Bencher, len: usize) {
hasher_bench(b, SipHasher::new(), len)
}
fn fnvhash_bench(b: &mut test::Bencher, len: usize) {
hasher_bench(b, <fnv::FnvHasher as Default>::default(), len)
}
#[bench]
fn siphash_megabyte(b: &mut test::Bencher) { siphash_bench(b, 1024*1024) }
#[bench]
fn siphash_1024_byte(b: &mut test::Bencher) { siphash_bench(b, 1024) }
#[bench]
fn siphash_512_byte(b: &mut test::Bencher) { siphash_bench(b, 512) }
#[bench]
fn siphash_256_byte(b: &mut test::Bencher) { siphash_bench(b, 256) }
#[bench]
fn siphash_128_byte(b: &mut test::Bencher) { siphash_bench(b, 128) }
#[bench]
fn siphash_32_byte(b: &mut test::Bencher) { siphash_bench(b, 32) }
#[bench]
fn siphash_16_byte(b: &mut test::Bencher) { siphash_bench(b, 16) }
#[bench]
fn siphash_4_byte(b: &mut test::Bencher) { siphash_bench(b, 4) }
#[bench]
fn siphash_1_byte(b: &mut test::Bencher) { siphash_bench(b, 1) }
#[bench]
fn siphash_0_byte(b: &mut test::Bencher) { siphash_bench(b, 0) }
#[bench]
fn fnvhash_megabyte(b: &mut test::Bencher) { fnvhash_bench(b, 1024*1024) }
#[bench]
fn fnvhash_1024_byte(b: &mut test::Bencher) { fnvhash_bench(b, 1024) }
#[bench]
fn fnvhash_512_byte(b: &mut test::Bencher) { fnvhash_bench(b, 512) }
#[bench]
fn fnvhash_256_byte(b: &mut test::Bencher) { fnvhash_bench(b, 256) }
#[bench]
fn fnvhash_128_byte(b: &mut test::Bencher) { fnvhash_bench(b, 128) }
#[bench]
fn fnvhash_32_byte(b: &mut test::Bencher) { fnvhash_bench(b, 32) }
#[bench]
fn fnvhash_16_byte(b: &mut test::Bencher) { fnvhash_bench(b, 16) }
#[bench]
fn fnvhash_4_byte(b: &mut test::Bencher) { fnvhash_bench(b, 4) }
#[bench]
fn fnvhash_1_byte(b: &mut test::Bencher) { fnvhash_bench(b, 1) }
#[bench]
fn fnvhash_0_byte(b: &mut test::Bencher) { fnvhash_bench(b, 0) }
#[bench]
fn xxhash_megabyte(b: &mut test::Bencher) { xxhash_bench(b, 1024*1024) }
#[bench]
fn xxhash_1024_byte(b: &mut test::Bencher) { xxhash_bench(b, 1024) }
#[bench]
fn xxhash_512_byte(b: &mut test::Bencher) { xxhash_bench(b, 512) }
#[bench]
fn xxhash_256_byte(b: &mut test::Bencher) { xxhash_bench(b, 256) }
#[bench]
fn xxhash_128_byte(b: &mut test::Bencher) { xxhash_bench(b, 128) }
#[bench]
fn xxhash_32_byte(b: &mut test::Bencher) { xxhash_bench(b, 32) }
#[bench]
fn xxhash_16_byte(b: &mut test::Bencher) { xxhash_bench(b, 16) }
#[bench]
fn xxhash_4_byte(b: &mut test::Bencher) { xxhash_bench(b, 4) }
#[bench]
fn xxhash_1_byte(b: &mut test::Bencher) { xxhash_bench(b, 1) }
#[bench]
fn xxhash_0_byte(b: &mut test::Bencher) { xxhash_bench(b, 0) }
#[bench]
fn xxhash32_megabyte(b: &mut test::Bencher) { xxhash32_bench(b, 1024*1024) }
#[bench]
fn xxhash32_1024_byte(b: &mut test::Bencher) { xxhash32_bench(b, 1024) }
#[bench]
fn xxhash32_512_byte(b: &mut test::Bencher) { xxhash32_bench(b, 512) }
#[bench]
fn xxhash32_256_byte(b: &mut test::Bencher) { xxhash32_bench(b, 256) }
#[bench]
fn xxhash32_128_byte(b: &mut test::Bencher) { xxhash32_bench(b, 128) }
#[bench]
fn xxhash32_32_byte(b: &mut test::Bencher) { xxhash32_bench(b, 32) }
#[bench]
fn xxhash32_16_byte(b: &mut test::Bencher) { xxhash32_bench(b, 16) }
#[bench]
fn xxhash32_4_byte(b: &mut test::Bencher) { xxhash32_bench(b, 4) }
#[bench]
fn xxhash32_1_byte(b: &mut test::Bencher) { xxhash32_bench(b, 1) }
#[bench]
fn xxhash32_0_byte(b: &mut test::Bencher) { xxhash32_bench(b, 0) }
<file_sep>/comparison/src/same.rs
use std::hash::Hasher;
use quickcheck::{QuickCheck, StdGen};
use rand::ThreadRng;
use twox_hash::{XxHash, XxHash32};
use xxhash2;
fn qc() -> QuickCheck<StdGen<ThreadRng>> {
QuickCheck::new()
.tests(100_000)
.max_tests(10_000_000)
}
#[test]
fn same_results_as_c_for_64_bit() {
fn prop(seed: u64, data: Vec<u8>) -> bool {
let mut hasher = XxHash::with_seed(seed);
hasher.write(&data);
let our_result = hasher.finish();
let their_result = xxhash2::hash64(&data, seed);
our_result == their_result
}
qc().quickcheck(prop as fn(_, _) -> _);
}
#[test]
fn same_results_as_c_for_32_bit() {
fn prop(seed: u32, data: Vec<u8>) -> bool {
let mut hasher = XxHash32::with_seed(seed);
hasher.write(&data);
let our_result = hasher.finish();
let their_result = xxhash2::hash32(&data, seed);
our_result == their_result as u64
}
qc().quickcheck(prop as fn(_, _) -> _);
}
|
b880cf0617d66269e5a0cfc0dc85ca53588b94e3
|
[
"TOML",
"Rust"
] | 4 |
TOML
|
mre/twox-hash
|
c80d6937b868f46e463d9d88a84812b4d5dd3c91
|
6bbab2c96c3de2b7bef2d763fe9dc75d15aa014c
|
refs/heads/master
|
<repo_name>webmsgr/OneLifeMapper<file_sep>/interactive_map.py
import pygame
import math
import glob
import os
tilesize = 128 # pixels per tile
def tiletosurface(tile):
pass
def maptosurface(sx,sy,ex,ey,oholmap):
pass
def main(windowsize,tilepipe,OHOLMap):
wt = math.floor(windowsize/tilesize)
cx,cy,first = 0,0,True
if OHOLMap.data != {}:
for x in OHOLMap.data:
for y in OHOLMap.data[x]:
if not first:
break
cx,cy = x,y
first = False
print("Loading sprites")
sprites = glob.glob("./OneLifeData/sprites/*.tga")
loadedsprites = {}
print("Found {} sprites, loading...".format(len(sprites)))
for sprite in sprites:
spriteid = os.path.basename(sprite).split(".")[0]
loadedsprites[spriteid] = pygame.image.load(sprite)
# do other loading things...
tilepipe.send("READY")
# main loop goes here
<file_sep>/mitm.py
# @todo add mitm proxy
import select
import socket
import multiprocessing as mp
import threading
def main(saddr,cport,outpipe): # receves packets and sends them to the caller
wk,data = mp.Pipe()
sname,sport = saddr.split(":")
server_worker_thread = threading.Thread(target=server_worker,args=(sname,sport,cport,wk))
server_worker_thread.start()
while server_worker_thread.is_alive():
if data.poll():
outpipe.send(data.recv())
def server_worker(sname,sport,cport,outpipe): # communicates with server/client
pass
def Server(pipe,msocket): # copied from bot, communicates
msocket.setblocking(0)
while True:
try:
read,write,error = select.select([msocket],[msocket],[msocket],60)
if msocket in read:
buf = msocket.recv(2048)
pipe.send(buf)
if pipe.poll() and msocket in write:
msocket.send(pipe.recv())
if msocket in error:
break
except:
break
<file_sep>/mapper.py
import mitm
import multiprocessing as mp
import zlib
import argparse
class Tile:
def __init__(self,data="0 0 0 0 0",dovis=1):
self.data = data
self.dovis = dovis
parsed = data.split(" ")
self.x = parsed[0]
self.y = parsed[1]
self.biome = parsed[2]
self.floor = parsed[3]
self.contained = []
on = parsed[4]
out = []
if "," in on:
temp = []
inside = on.split(",")
container = inside.pop(0)
for item in inside:
if ";" in item:
temp2 = []
inside2 = item.split(";")
container2 = inside2.pop(0)
for item2 in inside2:
temp2.append(item2)
temp.append((container2,temp2))
else:
temp.append(item)
out = (container,temp)
else:
out = (on,[])
self.contained = out
def read_tutorial():
tiles = {}
lines = open("OneLifeData/tutorialMaps/tutorial1.txt").read().split("\n")
for line in lines:
if line.strip() == "":
continue
temp = Tile(line)
if temp.x in tiles:
tiles[temp.x][temp.y] = temp
else:
tiles[temp.x] = {}
tiles[temp.x][temp.y] = temp
return OHOLMap(tiles)
class OHOLMap:
def __init__(self,data={}):
self.data = data
def settile(self,x,y,tile):
if x in self.data:
self.data[x][y] = tile
else:
self.data[x] = {}
self.data[x][y] = tile
def blanktile(self,x,y):
return Tile("{0} {1} 0 0 0".format(x,y),0)
def gettile(self,x,y):
if x in self.data:
if y in self.data[x]:
return self.data[x][y]
return self.blanktile(x,y)
def applytile(self,tile):
self.settile(tile.x,tile.y,tile)
class MapChunk:
def __init__(self,data=[[]],x=0,y=0):
self.data = data
self.x = x
self.y = y
self.ly = len(data)
self.lx = len(data[0])
def get(self,x,y):
return self.data[y][x]
def setitem(self,x,y,data):
self.data[y][x] = data
def setrow(self,y,data):
self.data[y] = data
def setcol(self,x,data):
for n,data in enumerate(data):
self.set(x,n,data)
def __iter__(self):
return iter(self.data)
def main():
pass
def worker(): # takes packets from server, parses map chunks, converts to Tiles and sends them to caller
pass
def zlib_decompress(data):
return zlib.decompress(data)
def parser_worker(data): # parses map chunks
pass
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--server",help = "The address of the server in hostname:port format",default="server1.onehouronelife.com:8006")
parser.add_argument("--port",help= "The port to host the server on",default="8007")
parser.add_argument("-o",help="Where to output map chunks to")
parser.add_argument("-i",help="Where to output a image of the map")
parser.add_argument("--interactive",help="Allow for viewing of map in a pygame window",action="store_true")
data = parser.parse_args()
# flow
# func name in []
# -> [worker]packet from mitm
# -> [worker]check if map
# -> [zlib_decompress]decompress
# -> [worker]send over to parser
# -> [parser_worker]parse
# -> [worker]return
<file_sep>/mapfile.py
def test_mapfile():
biomes = open("biomes.txt")
biomes = biomes.read().split("\n")
fl = open("OneLifeData/tutorialMaps/tutorial1.txt")
data = fl.read().split("\n")
fl.close()
cache = {}
for line,loc in enumerate(data):
if loc.strip() == "":
continue
x,y,biome,floor,ontop = loc.split(" ")
print("location : ({},{}) ".format(x,y))
print("biome: {} ({})".format(biomes[int(biome)],biome))
if "," in ontop:
things = ontop.split(",")
print("container: {}".format(things.pop(0)))
for item in things:
if ";" in item:
items = item.split(";")
print(" container: {}".format(items.pop(0)))
for citem in items:
print(" has: {}".format(citem))
else:
print(" has: {}".format(item))
else:
print("item:{}".format(ontop))
test_mapfile()
<file_sep>/README.md
# OneLifeMapper
Maps the world as you walk around.
|
83d50fa4a7beb13733cdcc268faed95391c1d9a3
|
[
"Markdown",
"Python"
] | 5 |
Python
|
webmsgr/OneLifeMapper
|
9c94f2820c8605372ff4127f8fb2dfd411db3388
|
74e4f27c002f048a9b4f75e7161a8fccc79ed6d2
|
refs/heads/master
|
<repo_name>jpsalvadorm63/rfs_02_time_tracking_app<file_sep>/README.md
Fallowing the book
# Fullstack React (R29)
*The Complete Guide to ReactJS and Friends*
02 - Components
This code comes from the book
[Fullstack React](https://www.fullstackreact.com/),
*Components*,
some modifications. For example, I created
the project using the command `create-react-app`
from the OS command line; to create components I avoid using `React.createClass`, instead I use
the `React.Component`; I got a better organized structure
of components: each one in one file, etc.
## Links
* [React.createClass vs React.Component](https://toddmotto.com/react-create-class-versus-component)
**_Facebook does suggest the future
[removal of React.createClass](https://facebook.github.io/react/blog/2015/03/10/react-v0.13.html) completely in favour of ES6 classes_**
* [Keys](https://facebook.github.io/react/docs/lists-and-keys.html#keys)
* [State and Lifecycle](https://facebook.github.io/react/docs/state-and-lifecycle.html)
* [Forms in React](https://facebook.github.io/react/docs/forms.html)
* [communication between Components](https://www.ctheu.com/2015/02/12/how-to-communicate-between-react-components/#comp_to_comp)
<file_sep>/src/js/timer.js
import React, { Component } from "react" ;
import helpers from "./helpers" ;
class Timer extends Component {
componentDidMount = () => {
this.forceUpdateInterval = setInterval(() => this.forceUpdate(), 500);
};
componentWillUnmount = () => {
clearInterval(this.forceUpdateInterval);
};
startClick = () => {
this.props.onStartTimer(this.props.id);
};
stopClick = () => {
this.props.onStopTimer(this.props.id);
};
handleTrashClick = () => {
this.props.onTrashClick(this.props.id);
};
render() {
const elapsedString = helpers.renderElapsedString(
this.props.elapsed, this.props.runningSince
);
return (
<div className='ui centered card'>
<div className='content'>
<div className='header'>
{this.props.title}
</div>
<div className='meta'>
{this.props.project}
</div>
<div className='center aligned description'>
<h2>
{elapsedString}
</h2>
</div>
<div className='extra content'>
<span
className='right floated edit icon'
onClick={this.props.onEditClick}>
<i className='edit icon' />
</span>
<span
className='right floated trash icon'
onClick={this.props.onDeleteClick}>
<i className='trash icon' />
</span>
</div>
</div>
<TimerActionButton
timerIsRunning={!!this.props.runningSince}
onStartClick={this.startClick}
onStopClick={this.stopClick}
/>
</div>
);
}
}
class TimerActionButton extends Component {
render() {
const stopText = "Stop" ;
const startText = "Start" ;
if (this.props.timerIsRunning) {
return (
<div
className='ui bottom attached red basic button'
onClick={this.props.onStopClick}
>
{stopText}
</div>
);
} else {
return (
<div
className='ui bottom attached green basic button'
onClick={this.props.onStartClick}
>
{startText}
</div>
);
}
}
}
export default Timer ;
<file_sep>/src/js/timer_form.js
import React, {Component} from "react" ;
class TimerForm extends Component {
constructor(props) {
super(props) ;
this.state = {
id : props.id,
title : props.title,
project : props.project,
elapsed : props.elapsed,
runningSince : props.runningSince,
} ;
};
handleChange = (event) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({ [name]: value });
} ;
formSubmit = () => {
if(this.props.onFormSubmit) {
this.props.onFormSubmit({
id: this.props.id,
title: this.state.title,
project: this.state.project,
});
}
} ;
render() {
const submitText = this.props.title ? 'Update' : 'Create';
const cancelText = 'Cancel' ;
return (
<div className='ui centered card'>
<div className='content'>
<div className='ui form'>
<div className='field'>
<label>Title</label>
<input name="title" type='text'
defaultValue={this.state.title}
onChange={this.handleChange}/>
</div>
<div className='field'>
<label>Project</label>
<input name="project" type='text'
defaultValue={this.state.project}
onChange={this.handleChange}/>
</div>
<div className='ui two bottom attached buttons'>
<button
className='ui basic blue button'
onClick={this.formSubmit}>
{submitText}
</button>
<button
className='ui basic red button'
onClick={this.props.onFormCancel}>
{cancelText}
</button>
</div>
</div>
</div>
</div>
);
}
}
export default TimerForm ;
<file_sep>/src/js/editable_timer.js
import React, { Component} from "react" ;
import helpers from "./helpers.js" ;
import TimerForm from "./timer_form.js" ;
import Timer from "./timer.js" ;
class EditableTimer extends Component {
constructor(props) {
super(props);
this.state = { editFormOpen: false } ;
}
hello = () => {
console.log("hello from [EditableTimer] ...") ;
};
message = (res) => {if(res) {
const tof = !res.ok ;
this.setState({ editFormOpen: tof });
}};
componentDidMount = () => {
if(this.props.onMount)
this.props.onMount(this);
};
componentWillUnmount = () => {
if(this.props.onMount)
this.props.onMount(null);
};
formEdit = () => {
this.formOpen();
};
formOpen = () => {
this.setState({ editFormOpen: true });
};
formUpdate = (timer) => {
if(this.props.onFormSubmit) {
if(helpers.validateTimer(timer)) {
this.props.onFormSubmit(timer);
this.formClose();
} else {
console.log("[EditableTimer.formSubmit] ERROR: No valid timer data");
}
}
};
formDelete = () => {
if(this.props.onFormDelete) {
this.props.onFormDelete({
id:this.props.id,
title:this.props.title,
project:this.props.project
});
} else {
console.log("[EditableTimer.formDelete] ERROR");
}
};
formCancel = () => { this.formClose(); };
formClose = () => {
this.setState({editFormOpen : false});
};
render() {
if (this.state.editFormOpen) {
return (
<TimerForm
key={this.props.id}
id={this.props.id}
title={this.props.title}
project={this.props.project}
onFormSubmit={this.formUpdate}
onFormCancel={this.formCancel}
/>
);
} else {
return (
<Timer
key={this.props.id}
id={this.props.id}
title={this.props.title}
project={this.props.project}
elapsed={this.props.elapsed}
runningSince={this.props.runningSince}
onEditClick={this.formEdit}
onDeleteClick={this.formDelete}
onStartTimer={this.props.onStartTimer}
onStopTimer={this.props.onStopTimer}
/>
);
}
}
};
export default EditableTimer ;
<file_sep>/src/js/timer_list.js
import React, { Component } from "react" ;
import uuid from "uuid" ;
import helpers from "./helpers" ;
import EditableTimer from "./editable_timer.js" ;
class TimerList extends Component {
constructor(props) {
super(props) ;
this.state = {
timers: [
{ id: uuid.v4(),
title: 'Practice squat',
project: 'Gym Chores',
elapsed: 5456099,
runningSince: Date.now(),
},
{ id: uuid.v4(),
title: 'Bake squash',
project: 'Kitchen Chores',
elapsed: 1273998,
runningSince: null,
},
]
};
};
hello = () => { console.log("hello from [TimerList]"); };
message = (msg) => {if(msg) {} };
componentDidMount = () => {
if(this.props.onMount)
this.props.onMount(this);
};
componentWillUnmount = () => {
if(this.props.onMount)
this.props.onMount(null);
};
timerAdd2list = (timer) => {
let ok = false ;
const from = 'TimerList.addTimer2list' ;
let msg = null ;
if(helpers.validateTimer(timer)) {
const t = helpers.newTimer(timer);
this.setState({
timers: [...this.state.timers, t],
});
ok = true ;
msg = 'TIMER INSERTED IN LIST !' ;
} else
msg = 'WRONG INPUT DATA';
const result = {
ok: ok,
from: from,
data: timer,
msg: msg,
} ;
return result ;
} ;
timerUpdate = (timer) => {
this.setState({
timers: this.state.timers.map((t) => {
if (t.id === timer.id) {
return Object.assign({}, t, {
title: timer.title,
project: timer.project,
});
} else {
return t;
}
}),
});
} ;
timerDelete = (timer) => {
if(timer) {
this.setState({
timers: this.state.timers.filter((t => t.id !== timer.id)),
});
}
} ;
startTimer = (timerId) => {
const now = Date.now();
this.setState({
timers: this.state.timers.map((timer) => {
if (timer.id === timerId) {
return Object.assign({}, timer, { runningSince: now });
} else {
return timer;
}
}),
});
};
stopTimer = (timerId) => {
const now = Date.now();
this.setState({
timers: this.state.timers.map((timer) => {
if (timer.id === timerId) {
const lastElapsed = now - timer.runningSince;
return Object.assign({}, timer, {
elapsed: timer.elapsed + lastElapsed,
runningSince: null,
});
} else {
return timer;
}
}),
});
};
render() {
const timers = this.state.timers.map((timer) => {
return (
<EditableTimer
key={timer.id}
id={timer.id}
title={timer.title}
project={timer.project}
elapsed={timer.elapsed}
runningSince={timer.runningSince}
onFormSubmit={this.timerUpdate}
onFormDelete={this.timerDelete}
onStartTimer={this.startTimer}
onStopTimer={this.stopTimer}
/>
);
});
return (
<div id='timers'>
{timers}
</div>
);
}
}
export default TimerList ;
|
a38abcabc8990d51456d3ea6f2f37109565d4940
|
[
"Markdown",
"JavaScript"
] | 5 |
Markdown
|
jpsalvadorm63/rfs_02_time_tracking_app
|
7fe6bd342caff9c947f5762070f8e7196fbea98c
|
2242932fa889a97e1f17cfd6dfee09ee777ebffb
|
refs/heads/main
|
<file_sep># Changelog:
# v0.2.6
### Bug Fixes:
* getting "failed to build bootstrap manifests" since v0.2.5 [#106](https://github.com/argoproj-labs/argocd-autopilot/issues/106)
### Breaking Changes:
* ~when sending `--app` flag value, use either `?sha=<sha_value>`, `?tag=<tag_name>` or `?ref=<branch_name>` to specificy sha|tag|branch to clone from ~ [#98](https://github.com/argoproj-labs/argocd-autopilot/pull/98)~ - REVERTED in [#107](https://github.com/argoproj-labs/argocd-autopilot/pull/107)
### Additional Changes:
* fixed help text typos [#105](https://github.com/argoproj-labs/argocd-autopilot/pull/105)
# v0.2.2
### Bug fixes:
* App type infer fails when --app value references a tag [#97](https://github.com/argoproj-labs/argocd-autopilot/issues/97)
* Deleting the bootstrap app hangs while deleting the entire hierarchy [#99](https://github.com/argoproj-labs/argocd-autopilot/issues/99)
### Breaking Changes:
* when sending `--app` flag value, use either `?sha=<sha_value>`, `?tag=<tag_name>` or `?ref=<branch_name>` to specificy sha|tag|branch to clone from [#98](https://github.com/argoproj-labs/argocd-autopilot/pull/98)
### Additional changes:
* update docs about secrets not yet supported [#93](https://github.com/argoproj-labs/argocd-autopilot/pull/93)
* Support using 2 repos for Kustomize apps [#97](https://github.com/argoproj-labs/argocd-autopilot/issues/97)
# v0.2.1
### Bug fixes:
* app create does not work with local path (tries to infer application type by cloning) [#87](https://github.com/argoproj-labs/argocd-autopilot/issues/87)
* Clone logs not displaying correct values
* Debug logs not showing
### Additional changes:
* Updated k8s dependencies from v0.20.4 to v0.21.1
* Added `--progress` flag to redirect the git operations
* `CloneOptions.FS` is now `fs.FS` instead of `billy.Filesystem`
# v0.2.0
### Breaking Changes:
* Combined `--repo`, `--installation-path` and `--revision` into a single url, set by `--repo` with the following syntax:
```
argocd-autopilot <command> --repo https://github.com/owner/name/path/to/installation_path?ref=branch
```
The `REPO_URL` environment variable also uses the new syntax
### Bug fixes:
* failed to build bootstrap manifests [#82](https://github.com/argoproj-labs/argocd-autopilot/issues/82)
* Adding two applications with the same ns causes sync ping-pong [#23](https://github.com/argoproj-labs/argocd-autopilot/issues/23)
### Additional changes:
* The `RunRepoCreate` func now returns `(*git.CloneOptions, error)`
# v0.1.10
### Bug fixes:
* removed dependency on `packr` for compiling source with additional assets required by argo-cd dependency.
# v0.1.9
### Bug fixes:
* `--project` flag shows in unrelated commands and not marked as required where it should be.
### Additional changes
* Added `brew` formula for `argocd-autopilot` [#31](https://github.com/argoproj-labs/argocd-autopilot/issues/31)
# v0.1.8
* Fix -p option in README.md
* renamed module from `argoproj/argocd-autopilot` to `argoproj-labs/argocd-autopilot`
# v0.1.7
* Fixed `--namespaced` bootstrap
* fix typo in auth error message
* Support for directory type application
* Renamed the binary archive from just .gz zo .tar.gz
# v0.1.6
* new logo!
* updated docs
# v0.1.5
* doc fixes
* you no longer need to run `argocd login` after running `repo bootstrap`
* added `app delete` command
# v0.1.4
* doc fixes
* fixed adding application on a remote cluster
# v0.1.3
* fixed docker image creation
# v0.1.2
* added documentation
* improved CI-CD flow
# v0.1.0
This is the first release of the `argocd-autopilot` tool.
<file_sep>package commands
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/argoproj-labs/argocd-autopilot/pkg/application"
"github.com/argoproj-labs/argocd-autopilot/pkg/argocd"
"github.com/argoproj-labs/argocd-autopilot/pkg/fs"
fsutils "github.com/argoproj-labs/argocd-autopilot/pkg/fs/utils"
"github.com/argoproj-labs/argocd-autopilot/pkg/git"
"github.com/argoproj-labs/argocd-autopilot/pkg/kube"
"github.com/argoproj-labs/argocd-autopilot/pkg/log"
"github.com/argoproj-labs/argocd-autopilot/pkg/store"
"github.com/argoproj-labs/argocd-autopilot/pkg/util"
appset "github.com/argoproj-labs/applicationset/api/v1alpha1"
argocdsettings "github.com/argoproj/argo-cd/v2/util/settings"
"github.com/ghodss/yaml"
"github.com/go-git/go-billy/v5/memfs"
"github.com/spf13/cobra"
"github.com/spf13/viper"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kusttypes "sigs.k8s.io/kustomize/api/types"
)
const (
installationModeFlat = "flat"
installationModeNormal = "normal"
)
// used for mocking
var (
argocdLogin = argocd.Login
getGitProvider = git.NewProvider
currentKubeContext = kube.CurrentContext
runKustomizeBuild = application.GenerateManifests
)
type (
RepoCreateOptions struct {
Provider string
Owner string
Repo string
Token string
Public bool
Host string
}
RepoBootstrapOptions struct {
AppSpecifier string
InstallationMode string
Namespace string
KubeContext string
Namespaced bool
DryRun bool
HidePassword bool
Timeout time.Duration
// FS fs.FS
KubeFactory kube.Factory
CloneOptions *git.CloneOptions
}
bootstrapManifests struct {
bootstrapApp []byte
rootApp []byte
clusterResAppSet []byte
clusterResConfig []byte
argocdApp []byte
repoCreds []byte
applyManifests []byte
bootstrapKustomization []byte
namespace []byte
}
)
func NewRepoCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "repo",
Short: "Manage gitops repositories",
Run: func(cmd *cobra.Command, args []string) {
cmd.HelpFunc()(cmd, args)
exit(1)
},
}
cmd.AddCommand(NewRepoCreateCommand())
cmd.AddCommand(NewRepoBootstrapCommand())
return cmd
}
func NewRepoCreateCommand() *cobra.Command {
var opts *RepoCreateOptions
cmd := &cobra.Command{
Use: "create",
Short: "Create a new gitops repository",
Example: util.Doc(`
# To run this command you need to create a personal access token for your git provider
# and provide it using:
export GIT_TOKEN=<token>
# or with the flag:
--git-token <token>
# Create a new gitops repository on github
<BIN> repo create --owner foo --name bar --git-token <PASSWORD>
# Create a public gitops repository on github
<BIN> repo create --owner foo --name bar --git-token <PASSWORD> --public
`),
RunE: func(cmd *cobra.Command, _ []string) error {
_, err := RunRepoCreate(cmd.Context(), opts)
return err
},
}
opts = AddRepoCreateFlags(cmd, "")
return cmd
}
func NewRepoBootstrapCommand() *cobra.Command {
var (
appSpecifier string
namespaced bool
dryRun bool
hidePassword bool
installationMode string
cloneOpts *git.CloneOptions
f kube.Factory
)
cmd := &cobra.Command{
Use: "bootstrap",
Short: "Bootstrap a new installation",
Example: util.Doc(`
# To run this command you need to create a personal access token for your git provider
# and provide it using:
export GIT_TOKEN=<token>
# or with the flag:
--git-token <token>
# Install argo-cd on the current kubernetes context in the argocd namespace
# and persists the bootstrap manifests to the root of gitops repository
<BIN> repo bootstrap --repo https://github.com/example/repo
# Install argo-cd on the current kubernetes context in the argocd namespace
# and persists the bootstrap manifests to a specific folder in the gitops repository
<BIN> repo bootstrap --repo https://github.com/example/repo/path/to/installation_root
`),
PreRun: func(_ *cobra.Command, _ []string) { cloneOpts.Parse() },
RunE: func(cmd *cobra.Command, args []string) error {
return RunRepoBootstrap(cmd.Context(), &RepoBootstrapOptions{
AppSpecifier: appSpecifier,
InstallationMode: installationMode,
Namespace: cmd.Flag("namespace").Value.String(),
KubeContext: cmd.Flag("context").Value.String(),
Namespaced: namespaced,
DryRun: dryRun,
HidePassword: hidePassword,
Timeout: util.MustParseDuration(cmd.Flag("request-timeout").Value.String()),
KubeFactory: f,
CloneOptions: cloneOpts,
})
},
}
cmd.Flags().StringVar(&appSpecifier, "app", "", "The application specifier (e.g. github.com/argoproj-labs/argocd-autopilot/manifests?ref=v0.2.5), overrides the default installation argo-cd manifests")
cmd.Flags().BoolVar(&namespaced, "namespaced", false, "If true, install a namespaced version of argo-cd (no need for cluster-role)")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "If true, print manifests instead of applying them to the cluster (nothing will be commited to git)")
cmd.Flags().BoolVar(&hidePassword, "hide-password", false, "If true, will not print initial argo cd password")
cmd.Flags().StringVar(&installationMode, "installation-mode", "normal", "One of: normal|flat. "+
"If flat, will commit the bootstrap manifests, otherwise will commit the bootstrap kustomization.yaml")
cloneOpts = git.AddFlags(cmd, memfs.New(), "")
// add kubernetes flags
f = kube.AddFlags(cmd.Flags())
return cmd
}
func AddRepoCreateFlags(cmd *cobra.Command, prefix string) *RepoCreateOptions {
opts := &RepoCreateOptions{}
if prefix != "" {
if !strings.HasSuffix(prefix, "-") {
prefix += "-"
}
envPrefix := strings.ReplaceAll(strings.ToUpper(prefix), "-", "_")
cmd.Flags().StringVar(&opts.Owner, prefix+"owner", "", "The name of the owner or organization")
cmd.Flags().StringVar(&opts.Repo, prefix+"name", "", "The name of the repository")
cmd.Flags().StringVar(&opts.Token, prefix+"git-token", "", fmt.Sprintf("Your git provider api token [%sGIT_TOKEN]", envPrefix))
cmd.Flags().StringVar(&opts.Provider, prefix+"provider", "github", fmt.Sprintf("The git provider, one of: %v", strings.Join(git.Providers(), "|")))
cmd.Flags().StringVar(&opts.Host, prefix+"host", "", "The git provider address (for on-premise git providers)")
cmd.Flags().BoolVar(&opts.Public, prefix+"public", false, "If true, will create the repository as public (default is false)")
die(viper.BindEnv(prefix+"git-token", envPrefix+"GIT_TOKEN"))
} else {
cmd.Flags().StringVarP(&opts.Owner, "owner", "o", "", "The name of the owner or organization")
cmd.Flags().StringVarP(&opts.Repo, "name", "n", "", "The name of the repository")
cmd.Flags().StringVarP(&opts.Token, "git-token", "t", "", "Your git provider api token [GIT_TOKEN]")
cmd.Flags().StringVarP(&opts.Provider, "provider", "p", "github", fmt.Sprintf("The git provider, one of: %v", strings.Join(git.Providers(), "|")))
cmd.Flags().StringVar(&opts.Host, "host", "", "The git provider address (for on-premise git providers)")
cmd.Flags().BoolVar(&opts.Public, "public", false, "If true, will create the repository as public (default is false)")
die(viper.BindEnv("git-token", "GIT_TOKEN"))
die(cmd.MarkFlagRequired("owner"))
die(cmd.MarkFlagRequired("name"))
die(cmd.MarkFlagRequired("git-token"))
}
return opts
}
func RunRepoCreate(ctx context.Context, opts *RepoCreateOptions) (*git.CloneOptions, error) {
p, err := getGitProvider(&git.ProviderOptions{
Type: opts.Provider,
Auth: &git.Auth{
Username: "git",
Password: opts.Token,
},
Host: opts.Host,
})
if err != nil {
return nil, err
}
log.G().Infof("creating repo: %s/%s", opts.Owner, opts.Repo)
repoUrl, err := p.CreateRepository(ctx, &git.CreateRepoOptions{
Owner: opts.Owner,
Name: opts.Repo,
Private: !opts.Public,
})
if err != nil {
return nil, err
}
log.G().Infof("repo created at: %s", repoUrl)
co := &git.CloneOptions{
Repo: repoUrl,
FS: fs.Create(memfs.New()),
Auth: git.Auth{
Password: opts.Token,
},
}
co.Parse()
return co, nil
}
func RunRepoBootstrap(ctx context.Context, opts *RepoBootstrapOptions) error {
var err error
if opts, err = setBootstrapOptsDefaults(*opts); err != nil {
return err
}
log.G().WithFields(log.Fields{
"repo-url": opts.CloneOptions.URL(),
"revision": opts.CloneOptions.Revision(),
"namespace": opts.Namespace,
"kube-context": opts.KubeContext,
}).Debug("starting with options: ")
manifests, err := buildBootstrapManifests(
opts.Namespace,
opts.AppSpecifier,
opts.CloneOptions,
)
if err != nil {
return fmt.Errorf("failed to build bootstrap manifests: %w", err)
}
// Dry Run check
if opts.DryRun {
fmt.Printf("%s", util.JoinManifests(
manifests.namespace,
manifests.applyManifests,
manifests.repoCreds,
manifests.bootstrapApp,
manifests.argocdApp,
manifests.rootApp,
))
exit(0)
return nil
}
log.G().Infof("cloning repo: %s", opts.CloneOptions.URL())
// clone GitOps repo
r, repofs, err := clone(ctx, opts.CloneOptions)
if err != nil {
return err
}
log.G().Infof("using revision: \"%s\", installation path: \"%s\"", opts.CloneOptions.Revision(), opts.CloneOptions.Path())
if err = validateRepo(repofs); err != nil {
return err
}
log.G().Debug("repository is ok")
// apply built manifest to k8s cluster
log.G().Infof("using context: \"%s\", namespace: \"%s\"", opts.KubeContext, opts.Namespace)
log.G().Infof("applying bootstrap manifests to cluster...")
if err = opts.KubeFactory.Apply(ctx, opts.Namespace, util.JoinManifests(manifests.namespace, manifests.applyManifests, manifests.repoCreds)); err != nil {
return fmt.Errorf("failed to apply bootstrap manifests to cluster: %w", err)
}
// write argocd manifests
if err = writeManifestsToRepo(repofs, manifests, opts.InstallationMode, opts.Namespace); err != nil {
return fmt.Errorf("failed to write manifests to repo: %w", err)
}
// wait for argocd to be ready before applying argocd-apps
stop := util.WithSpinner(ctx, "waiting for argo-cd to be ready")
if err = waitClusterReady(ctx, opts.KubeFactory, opts.Timeout, opts.Namespace); err != nil {
return err
}
stop()
// push results to repo
log.G().Infof("pushing bootstrap manifests to repo")
commitMsg := "Autopilot Bootstrap"
if opts.CloneOptions.Path() != "" {
commitMsg = "Autopilot Bootstrap at " + opts.CloneOptions.Path()
}
if err = r.Persist(ctx, &git.PushOptions{CommitMsg: commitMsg}); err != nil {
return err
}
// apply "Argo-CD" Application that references "bootstrap/argo-cd"
log.G().Infof("applying argo-cd bootstrap application")
if err = opts.KubeFactory.Apply(ctx, opts.Namespace, manifests.bootstrapApp); err != nil {
return err
}
passwd, err := getInitialPassword(ctx, opts.KubeFactory, opts.Namespace)
if err != nil {
return err
}
log.G().Infof("running argocd login to initialize argocd config")
err = argocdLogin(&argocd.LoginOptions{
Namespace: opts.Namespace,
Username: "admin",
Password: <PASSWORD>,
})
if err != nil {
return err
}
if !opts.HidePassword {
log.G(ctx).Printf("")
log.G(ctx).Infof("argocd initialized. password: %s", passwd)
log.G(ctx).Infof("run:\n\n kubectl port-forward -n %s svc/argocd-server 8080:80\n\n", opts.Namespace)
}
return nil
}
func setBootstrapOptsDefaults(opts RepoBootstrapOptions) (*RepoBootstrapOptions, error) {
var err error
switch opts.InstallationMode {
case installationModeFlat, installationModeNormal:
case "":
opts.InstallationMode = installationModeNormal
default:
return nil, fmt.Errorf("unknown installation mode: %s", opts.InstallationMode)
}
if opts.Namespace == "" {
opts.Namespace = store.Default.ArgoCDNamespace
}
if opts.AppSpecifier == "" {
opts.AppSpecifier = getBootstrapAppSpecifier(opts.Namespaced)
}
if _, err := os.Stat(opts.AppSpecifier); err == nil {
log.G().Warnf("detected local bootstrap manifests, using 'flat' installation mode")
opts.InstallationMode = installationModeFlat
}
if opts.KubeContext == "" {
if opts.KubeContext, err = currentKubeContext(); err != nil {
return nil, err
}
}
return &opts, nil
}
func validateRepo(repofs fs.FS) error {
folders := []string{store.Default.BootsrtrapDir, store.Default.ProjectsDir}
for _, folder := range folders {
if repofs.ExistsOrDie(folder) {
return fmt.Errorf("folder %s already exist in: %s", folder, repofs.Join(repofs.Root(), folder))
}
}
return nil
}
func waitClusterReady(ctx context.Context, f kube.Factory, timeout time.Duration, namespace string) error {
return f.Wait(ctx, &kube.WaitOptions{
Interval: store.Default.WaitInterval,
Timeout: timeout,
Resources: []kube.Resource{
{
Name: "argocd-server",
Namespace: namespace,
WaitFunc: kube.WaitDeploymentReady,
},
},
})
}
func getRepoCredsSecret(token, namespace string) ([]byte, error) {
return yaml.Marshal(&v1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: store.Default.RepoCredsSecretName,
Namespace: namespace,
},
Data: map[string][]byte{
"git_username": []byte(store.Default.GitUsername),
"git_token": []byte(token),
},
})
}
func getInitialPassword(ctx context.Context, f kube.Factory, namespace string) (string, error) {
cs := f.KubernetesClientSetOrDie()
secret, err := cs.CoreV1().Secrets(namespace).Get(ctx, "argocd-initial-admin-secret", metav1.GetOptions{})
if err != nil {
return "", err
}
passwd, ok := secret.Data["password"]
if !ok {
return "", fmt.Errorf("argocd initial password not found")
}
return string(passwd), nil
}
func getBootstrapAppSpecifier(namespaced bool) string {
if namespaced {
return store.Get().InstallationManifestsNamespacedURL
}
return store.Get().InstallationManifestsURL
}
func buildBootstrapManifests(namespace, appSpecifier string, cloneOpts *git.CloneOptions) (*bootstrapManifests, error) {
var err error
manifests := &bootstrapManifests{}
manifests.bootstrapApp, err = createApp(&createAppOptions{
name: store.Default.BootsrtrapAppName,
namespace: namespace,
repoURL: cloneOpts.URL(),
revision: cloneOpts.Revision(),
srcPath: filepath.Join(cloneOpts.Path(), store.Default.BootsrtrapDir),
})
if err != nil {
return nil, err
}
manifests.rootApp, err = createApp(&createAppOptions{
name: store.Default.RootAppName,
namespace: namespace,
repoURL: cloneOpts.URL(),
revision: cloneOpts.Revision(),
srcPath: filepath.Join(cloneOpts.Path(), store.Default.ProjectsDir),
})
if err != nil {
return nil, err
}
manifests.argocdApp, err = createApp(&createAppOptions{
name: store.Default.ArgoCDName,
namespace: namespace,
repoURL: cloneOpts.URL(),
revision: cloneOpts.Revision(),
srcPath: filepath.Join(cloneOpts.Path(), store.Default.BootsrtrapDir, store.Default.ArgoCDName),
noFinalizer: true,
})
if err != nil {
return nil, err
}
manifests.clusterResAppSet, err = createAppSet(&createAppSetOptions{
name: store.Default.ClusterResourcesDir,
namespace: namespace,
repoURL: cloneOpts.URL(),
revision: cloneOpts.Revision(),
appName: store.Default.ClusterResourcesDir + "-{{name}}",
appNamespace: namespace,
destServer: "{{server}}",
prune: false,
preserveResourcesOnDeletion: true,
srcPath: filepath.Join(cloneOpts.Path(), store.Default.BootsrtrapDir, store.Default.ClusterResourcesDir, "{{name}}"),
generators: []appset.ApplicationSetGenerator{
{
Git: &appset.GitGenerator{
RepoURL: cloneOpts.URL(),
Revision: cloneOpts.Revision(),
Files: []appset.GitFileGeneratorItem{
{
Path: filepath.Join(
cloneOpts.Path(),
store.Default.BootsrtrapDir,
store.Default.ClusterResourcesDir,
"*.json",
),
},
},
RequeueAfterSeconds: &DefaultApplicationSetGeneratorInterval,
},
},
},
})
if err != nil {
return nil, err
}
manifests.clusterResConfig, err = json.Marshal(&application.ClusterResConfig{Name: store.Default.ClusterContextName, Server: store.Default.DestServer})
if err != nil {
return nil, err
}
k, err := createBootstrapKustomization(namespace, cloneOpts.URL(), appSpecifier)
if err != nil {
return nil, err
}
if namespace != "" && namespace != "default" {
ns := kube.GenerateNamespace(namespace)
manifests.namespace, err = yaml.Marshal(ns)
if err != nil {
return nil, err
}
}
manifests.applyManifests, err = runKustomizeBuild(k)
if err != nil {
return nil, err
}
manifests.repoCreds, err = getRepoCredsSecret(cloneOpts.Auth.Password, namespace)
if err != nil {
return nil, err
}
manifests.bootstrapKustomization, err = yaml.Marshal(k)
if err != nil {
return nil, err
}
return manifests, nil
}
func writeManifestsToRepo(repoFS fs.FS, manifests *bootstrapManifests, installationMode, namespace string) error {
var bulkWrites []fsutils.BulkWriteRequest
argocdPath := repoFS.Join(store.Default.BootsrtrapDir, store.Default.ArgoCDName)
clusterResReadme := []byte(strings.ReplaceAll(string(clusterResReadmeTpl), "{CLUSTER}", store.Default.ClusterContextName))
if installationMode == installationModeNormal {
bulkWrites = []fsutils.BulkWriteRequest{
{Filename: repoFS.Join(argocdPath, "kustomization.yaml"), Data: manifests.bootstrapKustomization},
}
} else {
bulkWrites = []fsutils.BulkWriteRequest{
{Filename: repoFS.Join(argocdPath, "install.yaml"), Data: manifests.applyManifests},
}
}
bulkWrites = append(bulkWrites, []fsutils.BulkWriteRequest{
{Filename: repoFS.Join(store.Default.BootsrtrapDir, store.Default.RootAppName+".yaml"), Data: manifests.rootApp}, // write projects root app
{Filename: repoFS.Join(store.Default.BootsrtrapDir, store.Default.ArgoCDName+".yaml"), Data: manifests.argocdApp}, // write argocd app
{Filename: repoFS.Join(store.Default.BootsrtrapDir, store.Default.ClusterResourcesDir+".yaml"), Data: manifests.clusterResAppSet}, // write cluster-resources appset
{Filename: repoFS.Join(store.Default.BootsrtrapDir, store.Default.ClusterResourcesDir, store.Default.ClusterContextName, "README.md"), Data: clusterResReadme}, // write ./bootstrap/cluster-resources/in-cluster/README.md
{Filename: repoFS.Join(store.Default.BootsrtrapDir, store.Default.ClusterResourcesDir, store.Default.ClusterContextName+".json"), Data: manifests.clusterResConfig}, // write ./bootstrap/cluster-resources/in-cluster.json
{Filename: repoFS.Join(store.Default.ProjectsDir, "README.md"), Data: projectReadme}, // write ./projects/README.md
{Filename: repoFS.Join(store.Default.AppsDir, "README.md"), Data: appsReadme}, // write ./apps/README.md
}...)
if manifests.namespace != nil {
// write ./bootstrap/cluster-resources/in-cluster/...-ns.yaml
bulkWrites = append(
bulkWrites,
fsutils.BulkWriteRequest{Filename: repoFS.Join(store.Default.BootsrtrapDir, store.Default.ClusterResourcesDir, store.Default.ClusterContextName, namespace+"-ns.yaml"), Data: manifests.namespace},
)
}
return fsutils.BulkWrite(repoFS, bulkWrites...)
}
func createBootstrapKustomization(namespace, repoURL, appSpecifier string) (*kusttypes.Kustomization, error) {
credsYAML, err := createCreds(repoURL)
if err != nil {
return nil, err
}
k := &kusttypes.Kustomization{
Resources: []string{
appSpecifier,
},
TypeMeta: kusttypes.TypeMeta{
APIVersion: kusttypes.KustomizationVersion,
Kind: kusttypes.KustomizationKind,
},
ConfigMapGenerator: []kusttypes.ConfigMapArgs{
{
GeneratorArgs: kusttypes.GeneratorArgs{
Name: "argocd-cm",
Behavior: kusttypes.BehaviorMerge.String(),
KvPairSources: kusttypes.KvPairSources{
LiteralSources: []string{
"repository.credentials=" + string(credsYAML),
},
},
},
},
},
Namespace: namespace,
}
k.FixKustomizationPostUnmarshalling()
errs := k.EnforceFields()
if len(errs) > 0 {
return nil, fmt.Errorf("kustomization errors: %s", strings.Join(errs, "\n"))
}
return k, k.FixKustomizationPreMarshalling()
}
func createCreds(repoUrl string) ([]byte, error) {
host, _, _, _, _, _, _ := util.ParseGitUrl(repoUrl)
creds := []argocdsettings.RepositoryCredentials{
{
URL: host,
UsernameSecret: &v1.SecretKeySelector{
LocalObjectReference: v1.LocalObjectReference{
Name: "autopilot-secret",
},
Key: "git_username",
},
PasswordSecret: &v1.SecretKeySelector{
LocalObjectReference: v1.LocalObjectReference{
Name: "autopilot-secret",
},
Key: "git_token",
},
},
}
return yaml.Marshal(creds)
}
<file_sep>### Bug Fixes:
* getting "failed to build bootstrap manifests" since v0.2.5 [#106](https://github.com/argoproj-labs/argocd-autopilot/issues/106)
### Breaking Changes:
* ~when sending `--app` flag value, use either `?sha=<sha_value>`, `?tag=<tag_name>` or `?ref=<branch_name>` to specificy sha|tag|branch to clone from ~ [#98](https://github.com/argoproj-labs/argocd-autopilot/pull/98)~ - REVERTED in [#107](https://github.com/argoproj-labs/argocd-autopilot/pull/107)
### Additional Changes:
* fixed help text typos [#105](https://github.com/argoproj-labs/argocd-autopilot/pull/105)
### Contributors:
- <NAME> ([@mosheavni](https://github.com/mosheavni))
- <NAME> ([@roi-codefresh](https://github.com/roi-codefresh))
- <NAME> ([@noam-codefresh](https://github.com/noam-codefresh))
## Installation:
To use the `argocd-autopilot` CLI you need to download the latest binary from the [git release page](https://github.com/argoproj-labs/argocd-autopilot/releases).
### Using brew:
```bash
# install
brew install argocd-autopilot
# check the installation
argocd-autopilot version
```
### Linux and WSL (using curl):
```bash
# get the latest version or change to a specific version
VERSION=$(curl --silent "https://api.github.com/repos/argoproj-labs/argocd-autopilot/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
# download and extract the binary
curl -L --output - https://github.com/argoproj-labs/argocd-autopilot/releases/download/$VERSION/argocd-autopilot-linux-amd64.tar.gz | tar zx
# move the binary to your $PATH
mv ./argocd-autopilot-* /usr/local/bin/argocd-autopilot
# check the installation
argocd-autopilot version
```
### Mac (using curl):
```bash
# get the latest version or change to a specific version
VERSION=$(curl --silent "https://api.github.com/repos/argoproj-labs/argocd-autopilot/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
# download and extract the binary
curl -L --output - https://github.com/argoproj-labs/argocd-autopilot/releases/download/$VERSION/argocd-autopilot-darwin-amd64.tar.gz | tar zx
# move the binary to your $PATH
mv ./argocd-autopilot-* /usr/local/bin/argocd-autopilot
# check the installation
argocd-autopilot version
```
### Docker:
When using the Docker image, you have to provide the `.kube` and `.gitconfig` directories as mounts to the running container:
```
docker run \
-v ~/.kube:/home/autopilot/.kube \
-v ~/.gitconfig:/home/autopilot/.gitconfig \
-it quay.io/argoprojlabs/argocd-autopilot <cmd> <flags>
```
|
01061ddc69e4b828efc1819512e72f384515876d
|
[
"Markdown",
"Go"
] | 3 |
Markdown
|
ndrpnt/argocd-autopilot
|
5f6ebc8b9bd4b9b91d0044a060be1f8b0307c221
|
81720b91dd8bca72e0b9543300c9a014dece8146
|
refs/heads/main
|
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.game;
import com.ahli.galaxy.ui.interfaces.UICatalog;
import lombok.Data;
/**
* Class containing the data of a game (Sc2/Heroes/...).
*
* @author Ahli
*/
@Data
public class GameData {
private final GameDef gameDef;
private UICatalog uiCatalog;
public GameData(final GameDef gameDef) {
this.gameDef = gameDef;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
import com.ahli.galaxy.ui.abstracts.UIElementAbstract;
import com.ahli.galaxy.ui.interfaces.UIAttribute;
import com.ahli.galaxy.ui.interfaces.UIController;
import com.ahli.galaxy.ui.interfaces.UIElement;
import com.ahli.util.StringInterner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* @author Ahli
*/
public class UIControllerMutable extends UIElementAbstract implements UIController {
private final List<String> attributesKeyValueList;
private List<UIAttribute> keys;
private boolean nextAdditionShouldOverride;
private boolean nameIsImplicit = true;
public UIControllerMutable() {
super(null);
attributesKeyValueList = new ArrayList<>(0);
keys = new ArrayList<>(0);
}
/**
* @param name
*/
public UIControllerMutable(final String name) {
super(name);
attributesKeyValueList = new ArrayList<>(0);
keys = new ArrayList<>(0);
}
/**
* @param name
* @param attributesCapacity
* @param keysCapacity
*/
public UIControllerMutable(final String name, final int attributesCapacity, final int keysCapacity) {
super(name);
attributesKeyValueList = new ArrayList<>(attributesCapacity);
keys = new ArrayList<>(keysCapacity);
}
/**
* Returns a deep clone of this.
*/
@Override
public Object deepCopy() {
final UIControllerMutable clone =
new UIControllerMutable(getName(), attributesKeyValueList.size(), keys.size());
for (int i = 0, len = keys.size(); i < len; ++i) {
clone.keys.add((UIAttribute) keys.get(i).deepCopy());
}
for (int i = 0, len = attributesKeyValueList.size(); i < len; ++i) {
clone.attributesKeyValueList.add(attributesKeyValueList.get(i));
}
clone.nextAdditionShouldOverride = nextAdditionShouldOverride;
clone.nameIsImplicit = nameIsImplicit;
return clone;
}
/**
* @return the keys
*/
@Override
public List<UIAttribute> getKeys() {
return keys;
}
/**
* @param keys
* the keys to set
*/
@Override
public void setKeys(final List<UIAttribute> keys) {
this.keys = keys;
}
/**
* @return the nextAdditionShouldOverride
*/
@Override
public boolean isNextAdditionShouldOverride() {
return nextAdditionShouldOverride;
}
/**
* @param nextAdditionShouldOverride
* the nextAdditionShouldOverride to set
*/
@Override
public void setNextAdditionShouldOverride(final boolean nextAdditionShouldOverride) {
this.nextAdditionShouldOverride = nextAdditionShouldOverride;
}
/**
* Adds a value for the key and returns any overridden value.
*
* @param key
* @param value
*/
@Override
public void addValue(final String key, final String value) {
int i = 0;
final int len = attributesKeyValueList.size();
for (; i < len; i += 2) {
if (attributesKeyValueList.get(i).equals(key)) {
break;
}
}
if (i >= len) {
// not found
attributesKeyValueList.add(StringInterner.intern(key));
attributesKeyValueList.add(StringInterner.intern(value));
} else {
attributesKeyValueList.set(i, StringInterner.intern(value));
}
}
/**
* @param key
* @return
*/
@Override
public String getValue(final String key) {
int i = 0;
for (final int len = attributesKeyValueList.size(); i < len; i += 2) {
if (attributesKeyValueList.get(i).equals(key)) {
return attributesKeyValueList.get(i + 1);
}
}
return null;
}
/**
* @return the nameIsImplicit
*/
@Override
public boolean isNameIsImplicit() {
return nameIsImplicit;
}
/**
* @param nameIsImplicit
* the nameIsImplicit to set
*/
@Override
public void setNameIsImplicit(final boolean nameIsImplicit) {
this.nameIsImplicit = nameIsImplicit;
}
/**
* @param path
* @return
*/
@Override
public UIElement receiveFrameFromPath(final String path) {
return (path == null || path.isEmpty()) ? this : null;
}
@Override
public String toString() {
return "<Controller name='" + getName() + "'>";
}
@Override
public List<UIElement> getChildren() {
return Collections.emptyList();
}
@Override
@SuppressWarnings("java:S1168")
public List<UIElement> getChildrenRaw() {
return null; // returning null is desired here
}
@Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof final UIControllerMutable that)) {
return false;
}
if (!super.equals(o)) {
return false;
}
return that.canEqual(this) && nextAdditionShouldOverride == that.nextAdditionShouldOverride &&
nameIsImplicit == that.nameIsImplicit &&
Objects.equals(attributesKeyValueList, that.attributesKeyValueList) && Objects.equals(keys, that.keys);
}
@Override
public boolean canEqual(final Object other) {
return (other instanceof UIControllerMutable);
}
@Override
public final int hashCode() {
//noinspection ObjectInstantiationInEqualsHashCode
return Objects.hash(super.hashCode(), attributesKeyValueList, keys, nextAdditionShouldOverride, nameIsImplicit);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.threads;
public interface CleaningForkJoinTaskCleaner {
void tryCleanUp();
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
import com.ahli.util.XmlDomHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Reads a Desc Index File.
*
* @author Ahli
*/
public final class DescIndexReader {
private static final Logger logger = LoggerFactory.getLogger(DescIndexReader.class);
/**
*
*/
private DescIndexReader() {
}
/**
* Grabs all layout file paths from a given descIndex file.
*
* @param f
* descIndex file
* @return
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static List<String> getLayoutPathList(final File f, final Mode mode)
throws SAXException, IOException, ParserConfigurationException {
final DocumentBuilder dBuilder = XmlDomHelper.buildSecureDocumentBuilder();
logger.trace("reading layouts from descIndexFile: {}", f);
final Document doc = dBuilder.parse(f);
// must be in a DataComponent node
final NodeList nodeList = doc.getElementsByTagName("*");
final ArrayList<String> list = new ArrayList<>(nodeList.getLength());
for (int i = 0, len = nodeList.getLength(); i < len; ++i) {
final Node node = nodeList.item(i);
if ("Include".equalsIgnoreCase(node.getNodeName())) {
final NamedNodeMap attributes = node.getAttributes();
// ignore requiredtoload if desired
if ((mode == Mode.ONLY_LOADABLE && XmlDomHelper.isFailingRequiredToLoad(attributes)) ||
(mode == Mode.ONLY_UNLOADABLE && !XmlDomHelper.isFailingRequiredToLoad(attributes))) {
continue;
}
final String path = attributes.item(0).getNodeValue();
list.add(path);
logger.trace("Adding layout path to layoutPathList: {}", path);
}
}
return list;
}
public enum Mode {
ONLY_LOADABLE, ONLY_UNLOADABLE, ALL
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.hotkey_ui.application.model;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import java.util.Locale;
import java.util.Objects;
/**
* Class that defines a Hotkey or Settings value to be used in UI.
*
* @author Ahli
*/
public class ValueDef {
private final SimpleStringProperty id;
private final SimpleStringProperty value;
private final SimpleStringProperty description;
private final SimpleStringProperty defaultValue;
private final SimpleStringProperty oldValue;
private final SimpleBooleanProperty hasChanged;
private final String[] allowedValues;
private final ValueType type;
private final String gamestringsAdd;
/**
* Constructor.
*
* @param id
* @param description
* @param defaultValue
*/
public ValueDef(final String id, final String description, final String defaultValue) {
this.id = new SimpleStringProperty(id);
value = new SimpleStringProperty("");
this.description = new SimpleStringProperty(description);
this.defaultValue = new SimpleStringProperty(defaultValue);
allowedValues = null;
gamestringsAdd = "";
type = ValueType.TEXT;
oldValue = new SimpleStringProperty("");
hasChanged = new SimpleBooleanProperty(false);
initHasChangedBinding();
}
private void initHasChangedBinding() {
hasChanged.bind(value.isNotEqualTo(oldValue));
}
/**
* @param id
* @param description
* @param defaultValue
* @param type
* @param allowedValues
* @param gamestringsAdd
*/
public ValueDef(
final String id,
final String description,
final String defaultValue,
final String type,
final String[] allowedValues,
final String gamestringsAdd) {
this.id = new SimpleStringProperty(id);
value = new SimpleStringProperty("");
this.description = new SimpleStringProperty(description);
this.defaultValue = new SimpleStringProperty(defaultValue);
this.allowedValues = allowedValues;
this.gamestringsAdd = gamestringsAdd;
this.type = determineType(type);
oldValue = new SimpleStringProperty("");
hasChanged = new SimpleBooleanProperty(false);
initHasChangedBinding();
initDefaultValue(defaultValue);
}
private ValueType determineType(final String typeStr) {
try {
return ValueType.valueOf(typeStr.toUpperCase(Locale.ROOT));
} catch (final IllegalArgumentException ignored) {
return ValueType.TEXT;
}
}
private void initDefaultValue(final String defaultValue) {
if (type == ValueType.BOOLEAN && defaultValue.isEmpty()) {
setDefaultValue(Constants.FALSE);
}
}
public String getOldValue() {
return oldValue.get();
}
public void setOldValue(final String oldValue) {
this.oldValue.set(oldValue);
}
/**
* @return
*/
public String getGamestringsAdd() {
return gamestringsAdd;
}
/**
* @return
*/
public String getId() {
return id.get();
}
/**
* @param id
*/
public void setId(final String id) {
this.id.set(id);
}
/**
* @return
*/
public String getValue() {
return value.get();
}
/**
* @param value
*/
public void setValue(final String value) {
this.value.set(value);
}
/**
* @return
*/
public String getDescription() {
return description.get();
}
/**
* @param description
*/
public void setDescription(final String description) {
this.description.set(description);
}
/**
* @return
*/
public String getDefaultValue() {
return defaultValue.get();
}
/**
* @return
*/
// required to make UI track changes
public SimpleStringProperty valueProperty() {
return value;
}
/**
* @return
*/
// required to make UI track changes
public SimpleStringProperty defaultValueProperty() {
return defaultValue;
}
/**
* @return
*/
// required to make UI track changes
public SimpleStringProperty descriptionProperty() {
return description;
}
/**
* @return
*/
// required to make UI track changes
public SimpleStringProperty idProperty() {
return id;
}
/**
* @return
*/
// required to make UI track changes
public SimpleBooleanProperty hasChangedProperty() {
return hasChanged;
}
/**
* @return
*/
// required to make UI track changes
public SimpleStringProperty oldValueProperty() {
return oldValue;
}
/**
* @return
*/
public ValueType getType() {
return type;
}
/**
* @return
*/
public String[] getAllowedValues() {
return allowedValues;
}
/**
* Returns whether the value has changed.
*
* @return true if the value changed; false if the old value is still current
*/
public boolean hasChanged() {
return hasChanged.get();
}
/**
* Returns whether the value is the default value.
*
* @return true if the value is the default value
*/
public boolean isDefaultValue() {
return Objects.equals(defaultValue.get(), value.get());
}
/**
* @param defaultValue
*/
public void setDefaultValue(final String defaultValue) {
this.defaultValue.set(defaultValue);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.config;
import com.ahli.galaxy.game.GameData;
import com.ahli.galaxy.game.GameDef;
import com.ahli.mpq.MpqEditorInterface;
import interfacebuilder.SpringBootApplication;
import interfacebuilder.base_ui.BaseUiService;
import interfacebuilder.base_ui.DiscCacheService;
import interfacebuilder.build.MpqBuilderService;
import interfacebuilder.compile.CompileService;
import interfacebuilder.compress.GameService;
import interfacebuilder.compress.RuleSet;
import interfacebuilder.integration.FileService;
import interfacebuilder.integration.JarHelper;
import interfacebuilder.integration.ReplayService;
import interfacebuilder.integration.SettingsIniInterface;
import interfacebuilder.integration.kryo.KryoService;
import interfacebuilder.projects.ProjectEntity;
import interfacebuilder.projects.ProjectJpaRepository;
import interfacebuilder.projects.ProjectService;
import interfacebuilder.threads.CleaningForkJoinPool;
import interfacebuilder.threads.CleaningForkJoinTaskCleaner;
import interfacebuilder.threads.SpringForkJoinWorkerThreadFactory;
import interfacebuilder.ui.AppController;
import interfacebuilder.ui.navigation.NavigationController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.nio.file.Path;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
@Configuration
@EntityScan(basePackageClasses = { ProjectEntity.class, RuleSet.class })
@EnableJpaRepositories(basePackageClasses = ProjectJpaRepository.class)
public class AppConfiguration {
private static final Logger logger = LogManager.getLogger(AppConfiguration.class);
protected AppConfiguration() {
}
@Bean
protected GameData sc2BaseGameData() {
logger.debug("init bean: sc2BaseGameData");
return new GameData(GameDef.buildSc2GameDef());
}
@Bean
protected GameData heroesBaseGameData() {
logger.debug("init bean: heroesBaseGameData");
return new GameData(GameDef.buildHeroesGameDef());
}
@Bean
protected MpqEditorInterface mpqEditorInterface() {
logger.debug("init bean: mpqEditorInterface");
return new MpqEditorInterface(mpqCachePath(tempDirectory()), mpqEditorPath(basePath()));
}
protected Path mpqCachePath(final Path tempDirectory) {
return Path.of(tempDirectory.toString(), "ObserverInterfaceBuilder", "_ExtractedMpq");
}
protected Path tempDirectory() {
return Path.of(System.getProperty("java.io.tmpdir"));
}
protected Path mpqEditorPath(final Path basePath) {
return Path.of(
basePath.getParent() + File.separator + "tools" + File.separator + "plugins" + File.separator + "mpq" +
File.separator + "MPQEditor.exe");
}
protected Path basePath() {
return JarHelper.getJarDir(SpringBootApplication.class);
}
@Bean
protected ReplayService replayService() {
logger.debug("init bean replayService");
return new ReplayService();
}
@Bean
protected CompileService compileService(final GameService gameService) {
logger.debug("init bean: compileService");
return new CompileService(gameService);
}
@Bean
protected ProjectService projectService(
final ProjectJpaRepository projectJpaRepository,
@Lazy final MpqBuilderService mpqBuilderService,
final NavigationController navigationController) {
logger.debug("init bean: projectService");
return new ProjectService(projectJpaRepository, mpqBuilderService, navigationController);
}
@Bean
protected MpqBuilderService mpqBuilderService(
final ConfigService configService,
final CompileService compileService,
final FileService fileService,
final ProjectService projectService,
final BaseUiService baseUiService,
final GameData sc2BaseGameData,
final GameData heroesBaseGameData,
final ForkJoinPool forkJoinPool,
final AppController appController) {
logger.debug("init bean: mpqBuilderService");
return new MpqBuilderService(
configService,
compileService,
fileService,
projectService,
baseUiService,
sc2BaseGameData,
heroesBaseGameData,
forkJoinPool,
appController);
}
@Bean
protected ForkJoinPool forkJoinPool(final CleaningForkJoinTaskCleaner cleaner) {
logger.debug("init bean: forkJoinPool");
final int maxThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
return new CleaningForkJoinPool(
maxThreads,
new SpringForkJoinWorkerThreadFactory(),
null,
true,
maxThreads,
256,
1,
null,
5_000L,
TimeUnit.MILLISECONDS,
cleaner);
}
@Bean
protected AppController appController() {
logger.debug("init bean: appController");
return new AppController();
}
@Bean
protected BaseUiService baseUiService(
final ConfigService configService,
final FileService fileService,
final DiscCacheService discCacheService,
final KryoService kryoService,
final AppController appController,
final GameService gameService) {
logger.debug("init bean: baseUiService");
return new BaseUiService(configService, gameService, fileService, discCacheService, kryoService, appController);
}
@Bean
protected GameService gameService(final ConfigService configService) {
logger.debug("init bean: gameService");
return new GameService(configService);
}
@Bean
protected FileService fileService() {
logger.debug("init bean: fileService");
return new FileService();
}
@Bean
protected DiscCacheService discCacheService(final ConfigService configService, final KryoService kryoService) {
logger.debug("init bean: discCacheService");
return new DiscCacheService(configService, kryoService);
}
@Bean
protected KryoService kryoService() {
logger.debug("init bean: kryoService");
return new KryoService();
}
@Bean
protected ConfigService configService(
final SettingsIniInterface settingsIniInterface) {
logger.debug("init bean: configService");
final Path tmpPath = tempDirectory();
final Path basePath = basePath();
return new ConfigService(
mpqCachePath(tmpPath),
basePath,
documentsPath(),
mpqEditorPath(basePath),
settingsIniInterface,
raceId(),
consoleSkinId(),
baseUiPath(basePath),
cascExtractorExeFile(),
cachePath(),
miningTempPath(tmpPath));
}
protected Path documentsPath() {
return FileSystemView.getFileSystemView().getDefaultDirectory().toPath();
}
protected String raceId() {
return "Terr";
}
protected String consoleSkinId() {
return "ClassicTerran";
}
protected Path baseUiPath(final Path basePath) {
return basePath.getParent().resolve("baseUI");
}
protected File cascExtractorExeFile() {
return new File(
basePath().getParent() + File.separator + "tools" + File.separator + "plugins" + File.separator +
"casc" + File.separator + "CascExtractor.exe");
}
protected Path cachePath() {
return Path.of(System.getProperty("user.home") + File.separator + ".GalaxyObsUI" + File.separator + "cache");
}
protected Path miningTempPath(final Path tempDirectory) {
return tempDirectory.resolve("ObserverInterfaceBuilder" + File.separator + "_Mining");
}
@Bean
protected SettingsIniInterface settingsIniInterface() {
logger.debug("init bean: settingsIniInterface");
return new SettingsIniInterface(iniSettingsPath(basePath()));
}
protected Path iniSettingsPath(final Path basePath) {
return basePath.getParent().resolve("settings.ini");
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.projects;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProjectJpaRepository extends JpaRepository<ProjectEntity, Integer> {
// automatically implements common methods
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
import com.ahli.galaxy.game.GameDef;
import com.ahli.galaxy.parser.DeduplicationIntensity;
import com.ahli.galaxy.parser.UICatalogParser;
import com.ahli.galaxy.parser.XmlParserVtd;
import com.ahli.galaxy.parser.interfaces.ParsedXmlConsumer;
import com.ahli.galaxy.parser.interfaces.XmlParser;
import com.ahli.galaxy.ui.exception.UIException;
import com.ahli.galaxy.ui.interfaces.UICatalog;
import com.ahli.galaxy.ui.interfaces.UIConstant;
import com.ahli.galaxy.ui.interfaces.UIElement;
import com.ahli.galaxy.ui.interfaces.UIFrame;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/***
* Represents a container for UI frame.**
*
* @author Ahli
*/
public class UICatalogImpl implements UICatalog {
private static final String UNDERSCORE = "_";
private static final Logger logger = LoggerFactory.getLogger(UICatalogImpl.class);
// members
private final List<UITemplate> templates;
private final List<UITemplate> blizzOnlyTemplates;
private final List<UIConstant> constants;
private final List<UIConstant> blizzOnlyConstants;
private final Map<String, UIFrame> handles;
private List<String> blizzOnlyLayouts;
private ParsedXmlConsumer parser;
// internal, used during processing
private String curBasePath;
public UICatalogImpl() {
templates = new ArrayList<>(2500);
blizzOnlyTemplates = new ArrayList<>(10);
constants = new ArrayList<>(800);
blizzOnlyConstants = new ArrayList<>(10);
blizzOnlyLayouts = new ArrayList<>(25);
handles = new UnifiedMap<>(650 * 5 / 4);
}
public UICatalogImpl(final GameDef gameDef) {
if (gameDef != null) {
if ("sc2".equals(gameDef.nameHandle())) {
templates = new ArrayList<>(2365);
blizzOnlyTemplates = new ArrayList<>(17);
constants = new ArrayList<>(1241);
blizzOnlyConstants = new ArrayList<>(0);
blizzOnlyLayouts = new ArrayList<>(14);
handles = new UnifiedMap<>(242 * 5 / 4);
return;
} else if ("heroes".equals(gameDef.nameHandle())) {
templates = new ArrayList<>(2088);
blizzOnlyTemplates = new ArrayList<>(6);
constants = new ArrayList<>(449);
blizzOnlyConstants = new ArrayList<>(0);
blizzOnlyLayouts = new ArrayList<>(11);
handles = new UnifiedMap<>(367 * 5 / 4);
return;
}
}
templates = new ArrayList<>(2500);
blizzOnlyTemplates = new ArrayList<>(10);
constants = new ArrayList<>(800);
blizzOnlyConstants = new ArrayList<>(10);
blizzOnlyLayouts = new ArrayList<>(25);
handles = new UnifiedMap<>(650 * 5 / 4);
}
/**
* Constructor.
*
* @throws ParserConfigurationException
*/
public UICatalogImpl(
final int templatesCapacity,
final int blizzOnlyTemplatesCapacity,
final int constantsCapacity,
final int blizzOnlyConstantsCapacity,
final int blizzOnlyLayoutsCapacity,
final int handlesCapacity) {
templates = new ArrayList<>(templatesCapacity);
blizzOnlyTemplates = new ArrayList<>(blizzOnlyTemplatesCapacity);
constants = new ArrayList<>(constantsCapacity);
blizzOnlyConstants = new ArrayList<>(blizzOnlyConstantsCapacity);
blizzOnlyLayouts = new ArrayList<>(blizzOnlyLayoutsCapacity);
handles = new UnifiedMap<>(handlesCapacity);
}
/**
* Returns a deep clone of this.
*/
@Override
public Object deepCopy() {
// clone with additional space for templates, constants, handles
final UICatalogImpl clone = new UICatalogImpl(templates.size() + 550,
blizzOnlyTemplates.size(),
constants.size() + 150,
blizzOnlyConstants.size(),
blizzOnlyLayouts.size(),
handles.size() + 300);
// testing shows that iterators are not faster and are not thread safe
int i;
int len;
for (i = 0, len = templates.size(); i < len; ++i) {
clone.templates.add((UITemplate) templates.get(i).deepCopy());
}
for (i = 0, len = blizzOnlyTemplates.size(); i < len; ++i) {
clone.blizzOnlyTemplates.add((UITemplate) blizzOnlyTemplates.get(i).deepCopy());
}
for (i = 0, len = constants.size(); i < len; ++i) {
clone.constants.add((UIConstant) constants.get(i).deepCopy());
}
for (i = 0, len = blizzOnlyConstants.size(); i < len; ++i) {
clone.blizzOnlyConstants.add((UIConstant) blizzOnlyConstants.get(i).deepCopy());
}
clone.blizzOnlyLayouts = blizzOnlyLayouts;
for (final var handleEntry : handles.entrySet()) {
clone.handles.put(handleEntry.getKey(), handleEntry.getValue());
}
clone.curBasePath = curBasePath;
return clone;
}
@Override
public void setParser(final ParsedXmlConsumer parser) {
this.parser = parser;
}
@Override
public void processDescIndex(final File f, final String raceId, final String consoleSkinId)
throws SAXException, IOException, ParserConfigurationException, InterruptedException {
// TODO inefficient code, parses twice
List<String> blizzLayouts = DescIndexReader.getLayoutPathList(f, DescIndexReader.Mode.ONLY_UNLOADABLE);
blizzOnlyLayouts.addAll(blizzLayouts);
blizzLayouts = null;
final String descIndexPath = f.getAbsolutePath();
final String basePath = descIndexPath.substring(0, descIndexPath.length() - f.getName().length());
logger.trace("descIndexPath={}\nbasePath={}", descIndexPath, basePath);
final List<String> combinedList = DescIndexReader.getLayoutPathList(f, DescIndexReader.Mode.ALL);
processLayouts(combinedList, basePath, raceId, consoleSkinId);
logger.trace(
"UICatalogSizes: templates={}, blizzTemplates={}, constants={}, blizzConstants={}, blizzLayouts={}",
templates.size(),
blizzOnlyTemplates.size(),
constants.size(),
blizzOnlyConstants.size(),
blizzOnlyLayouts.size());
}
/**
* @param toProcessList
* @param basePath
* @param raceId
* @param consoleSkinId
* @throws InterruptedException
* if the current thread was interrupted
*/
private void processLayouts(
final List<String> toProcessList, final String basePath, final String raceId, final String consoleSkinId)
throws InterruptedException {
String basePathTemp;
for (final String intPath : toProcessList) {
final boolean isDevLayout = blizzOnlyLayouts.contains(intPath);
logger.trace("intPath={}\nisDevLayout={}", intPath, isDevLayout);
basePathTemp = basePath;
int lastIndex = 0;
while (!new File(basePathTemp + File.separator + intPath).exists() && lastIndex != -1) {
lastIndex = basePathTemp.lastIndexOf(File.separatorChar);
if (lastIndex != -1) {
basePathTemp = basePathTemp.substring(0, lastIndex);
logger.trace("basePathTemp={}", basePathTemp);
} else {
if (!isDevLayout) {
logger.error("ERROR: Cannot find layout file: {}", intPath);
} else {
logger.warn("WARNING: Cannot find Blizz-only layout file: {}, so this is fine.", intPath);
}
}
}
if (lastIndex != -1) {
curBasePath = basePathTemp;
final Path layoutFilePath = Path.of(basePathTemp, intPath);
try {
processLayoutFile(layoutFilePath, raceId, isDevLayout, consoleSkinId, parser);
} catch (final IOException e) {
final String msg = String.format(
"ERROR: encountered an Exception while processing the layout file '%s'.",
layoutFilePath);
logger.error(msg, e);
}
if (Thread.interrupted()) {
//noinspection NewExceptionWithoutArguments
throw new InterruptedException();
}
}
}
}
@Override
public void processLayoutFile(
final Path p,
final String raceId,
final boolean isDevLayout,
final String consoleSkinId,
final ParsedXmlConsumer parser) throws IOException {
parser.parseFile(p, raceId, isDevLayout, consoleSkinId);
}
@Override
public void processInclude(
final String path,
final boolean isDevLayout,
final String raceId,
final String consoleSkinId,
final DeduplicationIntensity deduplicationAllowed) {
logger.trace("processing Include appearing within a real layout");
String basePathTemp = getCurBasePath();
while (!Files.exists(Path.of(basePathTemp, path))) {
final int lastIndex = basePathTemp.lastIndexOf(File.separatorChar);
if (lastIndex != -1) {
basePathTemp = basePathTemp.substring(0, lastIndex);
logger.trace("basePathTemp={}", basePathTemp);
} else {
if (!isDevLayout) {
logger.error("ERROR: Cannot find layout file: {}", path);
} else {
logger.warn("WARNING: Cannot find Blizz-only layout file: {}, so this is fine.", path);
}
return;
}
}
final Path filePath = Path.of(basePathTemp, path);
final XmlParser xmlParser = new XmlParserVtd();
final UICatalogParser parserTemp = new UICatalogParser(this, xmlParser, deduplicationAllowed);
try {
parserTemp.parseFile(filePath, raceId, isDevLayout, consoleSkinId);
} catch (final IOException e) {
logger.error("ERROR: while parsing include appearing within usual layouts.", e);
}
xmlParser.clear();
}
@Override
public String getCurBasePath() {
return curBasePath;
}
@Override
public UITemplate[] getTemplatesOfPath(final String file) {
final List<UITemplate> foundTemplates = new ArrayList<>(1);
for (final var template : templates) {
if (template.getFileName().equalsIgnoreCase(file)) {
foundTemplates.add(template);
}
}
for (final var template : blizzOnlyTemplates) {
if (template.getFileName().equalsIgnoreCase(file)) {
logger.error("ERROR: cannot modify Blizzard-only Template: {}", template.getFileName());
break;
}
}
if (foundTemplates.isEmpty()) {
logger.warn("WARN: cannot find Layout file: {}", file);
}
return foundTemplates.toArray(new UITemplate[foundTemplates.size()]);
}
@Override
public void postProcessParsing() {
if (parser != null) {
parser.deduplicate();
}
}
/**
* @param fileName
* @param thisElem
* @param isDevLayout
* @return
* @throws UIException
*/
@Override
public UITemplate addTemplate(final String fileName, final UIElement thisElem, final boolean isDevLayout)
throws UIException {
if (thisElem == null) {
throw new UIException("Cannot create Template definition for a 'null' UIElement.");
}
final List<UITemplate> list = isDevLayout ? blizzOnlyTemplates : templates;
final UITemplate template = new UITemplate(fileName, thisElem);
list.add(template);
return template;
}
/**
* Adds a Constant to the correct list. It removes other values and loggs warnings, if problems arise.
*
* @param constant
* @param isDevLayout
*/
@Override
public void addConstant(final UIConstant constant, final boolean isDevLayout) {
final String name = constant.getName();
// register with parent/templates overriding previous constant values
if (!isDevLayout) {
// is general layout
final boolean removedBlizzOnly = removeConstantFromList(name, blizzOnlyConstants);
removeConstantFromList(name, constants);
constants.add(constant);
if (removedBlizzOnly) {
logger.warn("WARNING: constant '{}' overrides value from Blizz-only constant, so this might be fine.",
name);
}
} else {
// is blizz-only layout
removeConstantFromList(name, blizzOnlyConstants);
final boolean removedGeneral = removeConstantFromList(name, constants);
blizzOnlyConstants.add(constant);
if (removedGeneral) {
logger.warn(
"WARNING: constant '{}' from Blizz-only layout overrides a general constant, so this might be fine.",
name);
}
}
}
/**
* @param name
* @param listOfConstants
* @return
*/
private static boolean removeConstantFromList(final String name, final List<UIConstant> listOfConstants) {
boolean result = false;
for (int i = listOfConstants.size() - 1; i >= 0; --i) {
final UIConstant curConst = listOfConstants.get(i);
if (curConst.getName().compareToIgnoreCase(name) == 0) {
listOfConstants.remove(i);
result = true;
}
}
return result;
}
@Override
public String getConstantValue(
final String constantRef, final String raceId, final boolean isDevLayout, final String consoleSkinId) {
int i = 0;
if (!constantRef.isEmpty()) {
while (constantRef.charAt(i) == '#') {
++i;
}
}
// no constant tag
if (i <= 0) {
return constantRef;
}
final String prefix = constantRef.substring(0, i);
final String constantName = constantRef.substring(i);
logger.trace("Encountered Constant: prefix='{}', constantName='{}'", prefix, constantName);
for (final UIConstant c : constants) {
if (c.getName().equalsIgnoreCase(constantName)) {
return c.getValue();
}
}
// constant tag with race suffix
if (i == 2) {
final String constantNameWithRacePostFix = constantName + UNDERSCORE + raceId;
for (final UIConstant c : constants) {
if (c.getName().equalsIgnoreCase(constantNameWithRacePostFix)) {
return c.getValue();
}
}
} else if (i == 3) {
final String constantNameWithConsolePostFix = constantName + UNDERSCORE + consoleSkinId;
for (final UIConstant c : constants) {
if (c.getName().equalsIgnoreCase(constantNameWithConsolePostFix)) {
return c.getValue();
}
}
} else if (i >= 4) {
logger.error(
"ERROR: Encountered a constant definition with three #'{}' when its maximum is two '#'.",
constantRef);
}
if (!isDevLayout) {
logger.warn("WARNING: Did not find a constant definition for '{}', so '{}' is used instead.",
constantRef,
constantName);
} else {
// inside blizz-only
for (final UIConstant c : blizzOnlyConstants) {
if (c.getName().equalsIgnoreCase(constantName)) {
return c.getValue();
}
}
logger.warn(
"WARNING: Did not find a constant definition for '{}', but it is a Blizz-only layout, so this is fine.",
constantRef);
}
return constantName;
}
@Override
public List<UITemplate> getTemplates() {
return templates;
}
@Override
public List<UITemplate> getBlizzOnlyTemplates() {
return blizzOnlyTemplates;
}
@Override
public List<UIConstant> getConstants() {
return constants;
}
@Override
public List<UIConstant> getBlizzOnlyConstants() {
return blizzOnlyConstants;
}
@Override
public Map<String, UIFrame> getHandles() {
return handles;
}
@Override
public List<String> getDevLayouts() {
return blizzOnlyLayouts;
}
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof final UICatalogImpl uiCatalog)) {
return false;
}
return Objects.equals(parser, uiCatalog.parser) && Objects.equals(templates, uiCatalog.templates) &&
Objects.equals(blizzOnlyTemplates, uiCatalog.blizzOnlyTemplates) &&
Objects.equals(constants, uiCatalog.constants) &&
Objects.equals(blizzOnlyConstants, uiCatalog.blizzOnlyConstants) &&
Objects.equals(blizzOnlyLayouts, uiCatalog.blizzOnlyLayouts) &&
Objects.equals(handles, uiCatalog.handles) && Objects.equals(curBasePath, uiCatalog.curBasePath);
}
@Override
public final int hashCode() {
//noinspection ObjectInstantiationInEqualsHashCode
return Objects.hash(parser,
templates,
blizzOnlyTemplates,
constants,
blizzOnlyConstants,
blizzOnlyLayouts,
handles,
curBasePath);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.parser;
import com.ahli.galaxy.parser.abstracts.XmlParserAbstract;
import com.ahli.galaxy.parser.interfaces.ParsedXmlConsumer;
import com.ahli.galaxy.ui.exception.UIException;
import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class XmlParserVtd extends XmlParserAbstract {
private static final String ANY_TAG = "*";
private static final Logger logger = LoggerFactory.getLogger(XmlParserVtd.class);
private VTDGen vtd;
private List<String> attrTypes;
private List<String> attrValues;
/**
*
*/
public XmlParserVtd() {
super(null);
}
/**
* @param consumer
*/
public XmlParserVtd(final ParsedXmlConsumer consumer) {
super(consumer);
init();
}
private void init() {
if (vtd == null) {
vtd = new VTDGen();
}
attrTypes = new ArrayList<>(3);
attrValues = new ArrayList<>(3);
}
@Override
public void setConsumer(final ParsedXmlConsumer consumer) {
this.consumer = consumer;
init();
}
@Override
public void clear() {
vtd = null;
attrTypes = null;
attrValues = null;
consumer = null;
}
@Override
public void parseFile(final Path p) throws IOException {
if (logger.isTraceEnabled()) {
logger.trace("parsing layout file: {}", p.getFileName());
}
try {
// setdoc causes a nullpointer error due to an internal bug => use byte array
vtd.setDoc_BR(Files.readAllBytes(p));
vtd.parse(false);
final VTDNav nav = vtd.getNav();
final AutoPilot ap = new AutoPilot(nav);
ap.selectElement(ANY_TAG);
final AutoPilot ap2 = new AutoPilot(nav);
int i;
while (ap.iterate()) {
ap2.selectAttr(ANY_TAG);
while ((i = ap2.iterateAttr()) != -1) {
// i will be attr name, i+1 will be attribute value
attrTypes.add(nav.toRawStringLowerCase(i));
attrValues.add(nav.toRawString(i + 1));
}
consumer.parse(
nav.getCurrentDepth() + 1,
nav.toRawStringLowerCase(nav.getCurrentIndex()),
attrTypes,
attrValues);
attrTypes.clear();
attrValues.clear();
}
} catch (final IOException | UIException | ParseException | NavException e) {
throw new IOException("ERROR during XML parsing.", e);
}
consumer.endLayoutFile();
}
}
<file_sep>MpqInterface.CouldNotOverwriteFile=Can not overwrite file '%1$s'.
MpqInterface.MpqEditorNotFound=MPQEditor not found under: %1$s.
MpqInterface.NoFilesExtracted=No files could be extracted from '%1$s'.
MpqInterface.CouldNotCreatePath=Could not create directories for path '%1$s'.
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.projects;
import interfacebuilder.compress.RuleSet;
import interfacebuilder.projects.enums.Game;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import java.time.LocalDateTime;
import java.util.Objects;
@Data
@ToString
@Builder
@AllArgsConstructor
public class Project {
private final int id;
private String name;
private String projectPath;
private Game game;
private LocalDateTime lastBuildDateTime;
private long lastBuildSize;
private RuleSet bestCompressionRuleSet;
public Project(final String name, final String projectPath, final Game game) {
this.name = name;
this.projectPath = projectPath;
this.game = game;
id = 0;
}
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof final Project project)) {
return false;
}
return id == project.id && lastBuildSize == project.lastBuildSize && Objects.equals(name, project.name) &&
Objects.equals(projectPath, project.projectPath) && game == project.game &&
Objects.equals(lastBuildDateTime, project.lastBuildDateTime) &&
Objects.equals(bestCompressionRuleSet, project.bestCompressionRuleSet);
}
@Override
public final int hashCode() {
return Objects.hash(id, name, projectPath, game, lastBuildDateTime, lastBuildSize, bestCompressionRuleSet);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.progress.appender;
import javafx.beans.property.SimpleBooleanProperty;
public interface Appender {
/**
* Appends the specified line to configured thing.
*
* @param line
* line that is added
*/
void append(String line);
/**
* Signals that the appending is now stopping.
*/
void end();
/**
* @return
*/
SimpleBooleanProperty endedProperty();
}
<file_sep>Main.allFilesFilter=Alle Dateien
Main.anErrorOccured=Ein Fehler ist aufgetreten
Main.hasUnsavedChanges='%1$s' hat ungespeicherte Änderungen. Speichern?
Main.heroesInterfaceFilter=Heroes Interface
Main.observerUiSettingsEditorTitle=Observer UI Settings Editor - DE
Main.warningAlertTitle=Achtung
Main.couldNotFindMpqEditor=Konnte die 'MPQEditor.exe' nicht im folgenden Verzeichnis finden: '%1$s'.
General.OkButton=OK
General.YesButton=Ja
General.NoButton=Nein
General.CancelButton=Abbrechen
General.ExceptionStackTrace=Details dieses Ausnahmefehlers:
Main.OpenedFileNoComponentList=Geöffnete Datei enthielt keine 'ComponentList'-Datei.
Main.openObserverInterfaceTitle=Öffne Observer Interface...
Main.saveUiTitle=Speicher Observer Interface...
Main.sc2InterfaceFilter=SC2 Interface
Main.unsavedChangesTitle=Ungespeicherte Änderungen
MenuBarController.About=Über
MenuBarController.AboutText=Version: \t\t\t%1$s%n%nAuthor:\t\t\tChristoph "Ahli" Ahlers (Twitter: @AhliSC2)
MenuBarController.AboutText2=Übersetzung:\n\tChinesisch, Taiwanisch:\t\ttinkoliu (twitter: @tinkoliu)\n\ntools:\n\tMPQ Editor:\t\t\t\tLadislav \"Ladik\" Zezula (http://www.zezula.net)
MenuBarController.ObserverUISettingsEditor=Observer UI Settings Editor
rootLayout.Open=Öffnen
rootLayout.Save=Spechern
rootLayout.SaveAs=Speichern Unter
rootLayout.CloseFile=Datei schließen
rootLayout.Exit=Beenden
rootLayout.About=Über
rootLayout.?=?
rootLayout.File=Datei
TabsController.ResetDefault=Standardwert
TabsController.ResetOldValue=Rückgängig
tabsLayout.Hotkeys=Hotkeys
tabsLayout.Name=Name
tabsLayout.Description=Beschreibung
tabsLayout.Default=Standardwert
tabsLayout.Key=Taste
tabsLayout.Value=Wert
tabsLayout.Settings=Einstellungen
tabsLayout.NoHotkeysFound=Keine Hotkeys gefunden.
tabsLayout.NoSettingsFound=Keine Einstellungen gefunden.
tabsLayout.Actions=Aktionen
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui.abstracts;
import com.ahli.galaxy.ui.interfaces.UIElement;
import com.ahli.util.StringInterner;
/**
* @author Ahli
*/
public abstract class UIElementAbstract implements UIElement {
// for hashcode caching
protected boolean hashIsDirty;
protected boolean hashIsZero;
protected int hash;
private String name;
/**
* Constructor.
*
* @param name
* element's name
*/
protected UIElementAbstract(final String name) {
this.name = name != null ? StringInterner.intern(name) : null;
}
@Override
public String toString() {
return "<UIElement name='" + name + "'>";
}
@Override
public boolean equals(final Object obj) {
// based on lombok
if (obj == this) {
return true;
}
if (!(obj instanceof final UIElementAbstract other)) {
return false;
}
if (!other.canEqual(this)) {
return false;
}
return name == null ? other.name == null : name.equals(other.name);
}
@Override
public boolean canEqual(final Object other) {
return other instanceof UIElementAbstract;
}
/**
* @return the name
*/
@Override
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
@Override
public void setName(final String name) {
this.name = name != null ? StringInterner.intern(name) : null;
}
@Override
public int hashCode() {
// based on lombok
return 59 + (name == null ? 43 : name.hashCode());
}
@Override
public void invalidateHashcode() {
hashIsDirty = true;
}
}
<file_sep>Main.allFilesFilter=All Files
Main.anErrorOccured=An error occurred
Main.hasUnsavedChanges='%1$s' has unsaved changes. Save them?
Main.heroesInterfaceFilter=Heroes Interface
Main.observerUiSettingsEditorTitle=Observer UI Settings Editor - EN
Main.warningAlertTitle=Warning
Main.couldNotFindMpqEditor=Could not find the 'MPQEditor.exe' under '%1$s'.
General.OkButton=OK
General.YesButton=Yes
General.NoButton=No
General.CancelButton=Cancel
General.ExceptionStackTrace=The exception stacktrace was:
Main.OpenedFileNoComponentList=Opened file does not contain a 'ComponentList' file.
Main.openObserverInterfaceTitle=Open Observer Interface...
Main.saveUiTitle=Save Observer Interface...
Main.sc2InterfaceFilter=SC2 Interface
Main.unsavedChangesTitle=Unsaved changes
MenuBarController.About=About
MenuBarController.AboutText=version: \t\t\t%1$s%n%ncreated by:\t\tChristoph "Ahli" Ahlers (twitter: @AhliSC2)
MenuBarController.AboutText2=translation:\n\tChinese, Taiwanese:\t\t\ttinkoliu (twitter: @tinkoliu)\n\ntools:\n\tMPQ Editor:\t\t\t\tLadislav \"Ladik\" Zezula (http://www.zezula.net)
MenuBarController.ObserverUISettingsEditor=Observer UI Settings Editor
rootLayout.Open=Open
rootLayout.Save=Save
rootLayout.SaveAs=Save As
rootLayout.CloseFile=Close File
rootLayout.Exit=Exit
rootLayout.About=About
rootLayout.?=?
rootLayout.File=File
TabsController.ResetDefault=Default
TabsController.ResetOldValue=Undo
tabsLayout.Hotkeys=Hotkeys
tabsLayout.Name=Name
tabsLayout.Description=Description
tabsLayout.Default=Default
tabsLayout.Key=Shortcut
tabsLayout.Value=Value
tabsLayout.Settings=Settings
tabsLayout.NoHotkeysFound=No Hotkey found.
tabsLayout.NoSettingsFound=No Settings found.
tabsLayout.Actions=Actions
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.progress;
import com.ahli.galaxy.game.GameDef;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import interfacebuilder.base_ui.BaseUiService;
import interfacebuilder.base_ui.ExtractBaseUiTask;
import interfacebuilder.compress.GameService;
import interfacebuilder.projects.enums.Game;
import interfacebuilder.ui.AppController;
import interfacebuilder.ui.Updateable;
import interfacebuilder.ui.navigation.NavigationController;
import interfacebuilder.ui.progress.appender.Appender;
import interfacebuilder.ui.progress.appender.TextFlowAppender;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import java.util.concurrent.ForkJoinPool;
public class BaseUiExtractionController implements Updateable {
private static int threadCount;
private final String[] threadNames;
private final BaseUiService baseUiService;
private final GameService gameService;
private final NavigationController navigationController;
private final ForkJoinPool executor;
private final AppController appController;
@FXML
private FontAwesomeIconView stateImage1;
@FXML
private FontAwesomeIconView stateImage2;
@FXML
private FontAwesomeIconView stateImage3;
@FXML
private ScrollPane scrollPane1;
@FXML
private ScrollPane scrollPane2;
@FXML
private ScrollPane scrollPane3;
@FXML
private VBox loggingArea;
@FXML
private Label titleLabel;
@FXML
private TextFlow txtArea1;
@FXML
private Label areaLabel1;
@FXML
private TextFlow txtArea2;
@FXML
private Label areaLabel2;
@FXML
private TextFlow txtArea3;
@FXML
private Label areaLabel3;
private ErrorTabController errorTabController;
public BaseUiExtractionController(
final BaseUiService baseUiService,
final GameService gameServic,
final NavigationController navigationController,
final ForkJoinPool executor,
final AppController appController) {
this.baseUiService = baseUiService;
gameService = gameServic;
this.navigationController = navigationController;
this.executor = executor;
this.appController = appController;
final String threadName = "extractThread_";
threadNames = new String[3];
threadNames[0] = threadName + ++threadCount;
threadNames[1] = threadName + ++threadCount;
threadNames[2] = threadName + ++threadCount;
}
public VBox getLoggingArea() {
return loggingArea;
}
/**
* Automatically called by FxmlLoader
*/
public void initialize() {
// auto-downscrolling
scrollPane1.vvalueProperty().bind(txtArea1.heightProperty());
scrollPane2.vvalueProperty().bind(txtArea2.heightProperty());
scrollPane3.vvalueProperty().bind(txtArea3.heightProperty());
stateImage1.setVisible(false);
stateImage2.setVisible(false);
stateImage3.setVisible(false);
}
@Override
public void update() {
// nothing to do
}
public void start(final Game game, final boolean usePtr) {
errorTabController.setRunning(true);
final GameDef exportedGameDef = gameService.getGameDef(game);
final String ptrString = usePtr ? " PTR" : "";
titleLabel.setText(String.format("Extract %s's Base UI", exportedGameDef.name() + ptrString));
txtArea1.getChildren().clear();
txtArea2.getChildren().clear();
txtArea3.getChildren().clear();
final Appender[] appenders = new Appender[3];
appenders[0] = new TextFlowAppender(txtArea1);
appenders[1] = new TextFlowAppender(txtArea2);
appenders[2] = new TextFlowAppender(txtArea3);
appenders[0].endedProperty().addListener(new EndedListener(stateImage1, txtArea1));
appenders[1].endedProperty().addListener(new EndedListener(stateImage2, txtArea2));
appenders[2].endedProperty().addListener(new EndedListener(stateImage3, txtArea3));
final String[] queryMasks = BaseUiService.getQueryMasks(game);
final String msg = "Extracting %s files";
areaLabel1.setText(String.format(msg, queryMasks[0]));
areaLabel2.setText(String.format(msg, queryMasks[1]));
areaLabel3.setText(String.format(msg, queryMasks[2]));
stateImage1.setIcon(FontAwesomeIcon.SPINNER);
stateImage2.setIcon(FontAwesomeIcon.SPINNER);
stateImage3.setIcon(FontAwesomeIcon.SPINNER);
stateImage1.setFill(Color.GAINSBORO);
stateImage2.setFill(Color.GAINSBORO);
stateImage3.setFill(Color.GAINSBORO);
stateImage1.setVisible(true);
stateImage2.setVisible(true);
stateImage3.setVisible(true);
final ExtractBaseUiTask task = new ExtractBaseUiTask(appController,
baseUiService,
game,
usePtr,
appenders,
errorTabController,
navigationController);
executor.execute(task);
}
public String[] getThreadNames() {
return threadNames;
}
public void setErrorTabControl(final ErrorTabController errorTabCtrl) {
errorTabController = errorTabCtrl;
}
public ErrorTabController getErrorTabController() {
return errorTabController;
}
private static final class EndedListener implements ChangeListener<Boolean> {
private static final String ERROR = "ERROR:";
private static final String WARNING = "WARNING:";
private final FontAwesomeIconView stateImage;
private final TextFlow txtArea;
private EndedListener(final FontAwesomeIconView stateImage, final TextFlow txtArea) {
this.stateImage = stateImage;
this.txtArea = txtArea;
}
@Override
public void changed(
final ObservableValue<? extends Boolean> observable, final Boolean oldValue, final Boolean newValue) {
// the text children are added after the UI updates
Platform.runLater(() -> {
boolean isError = false;
boolean isWarning = false;
final ObservableList<Node> children = txtArea.getChildren();
if (children != null && !children.isEmpty()) {
for (final Node child : children) {
if (child instanceof final Text text) {
if (text.getText().contains(ERROR)) {
isError = true;
break;
}
if (text.getText().contains(WARNING)) {
isWarning = true;
break;
}
}
}
} else {
isError = true;
}
if (isError) {
stateImage.setIcon(FontAwesomeIcon.EXCLAMATION_TRIANGLE);
stateImage.setFill(Color.RED);
} else if (isWarning) {
stateImage.setIcon(FontAwesomeIcon.EXCLAMATION_TRIANGLE);
stateImage.setFill(Color.YELLOW);
} else {
stateImage.setIcon(FontAwesomeIcon.CHECK);
stateImage.setFill(Color.LAWNGREEN);
}
});
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.browse;
import com.ahli.galaxy.ui.interfaces.UIElement;
import javafx.scene.control.TreeCell;
public class CustomTreeCell extends TreeCell<UIElement> {
private final TextFlowFactory flowFactory;
public CustomTreeCell(final TextFlowFactory flowFactory) {
this.flowFactory = flowFactory;
}
@Override
protected void updateItem(final UIElement item, final boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(flowFactory.getFlow(item));
}
setText(null);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.integration.kryo;
import java.util.Arrays;
import java.util.Objects;
public class KryoGameInfo {
private final int[] version;
private final String gameName;
private final boolean isPtr;
public KryoGameInfo(final int[] version, final String gameName, final boolean isPtr) {
this.version = version;
this.gameName = gameName;
this.isPtr = isPtr;
}
public String getGameName() {
return gameName;
}
public boolean isPtr() {
return isPtr;
}
public int[] getVersion() {
return version;
}
@Override
public String toString() {
return "KryoGameInfo{gameName=" + gameName + ", isPtr=" + isPtr + ", version=" + Arrays.toString(version) + "}";
}
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof final KryoGameInfo that)) {
return false;
}
return isPtr == that.isPtr && Arrays.equals(version, that.version) && Objects.equals(gameName, that.gameName);
}
@Override
public final int hashCode() {
@SuppressWarnings("ObjectInstantiationInEqualsHashCode")
int result = Objects.hash(gameName, isPtr);
result = 31 * result + Arrays.hashCode(version);
return result;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui.interfaces;
import com.ahli.galaxy.ui.UIAnchorSide;
import java.util.List;
public interface UIFrame extends UIElement {
@Override
Object deepCopy();
String getType();
void setType(String type);
@Override
List<UIElement> getChildren();
@Override
List<UIElement> getChildrenRaw();
void addAttribute(UIAttribute value);
UIAttribute getValue(String key);
List<UIAttribute> getAttributes();
List<UIAttribute> getAttributesRaw();
String getAnchorRelative(UIAnchorSide side);
String getAnchorOffset(UIAnchorSide side);
String getAnchorPos(UIAnchorSide side);
void setAnchor(String relative, String offset);
void setAnchor(UIAnchorSide side, String relative, String pos, String offset);
void setAnchorRelative(UIAnchorSide side, String relative);
void setAnchorPos(UIAnchorSide side, String pos);
void setAnchorOffset(UIAnchorSide side, String offset);
@Override
UIElement receiveFrameFromPath(String path);
@Override
String toString();
@Override
boolean equals(Object obj);
@Override
boolean canEqual(Object other);
@Override
int hashCode();
}
<file_sep>Main.allFilesFilter=所有文件
Main.anErrorOccured=發生錯誤
Main.hasUnsavedChanges='%1$s' 的更改尚未保存。是否保存更改?
Main.heroesInterfaceFilter=暴雪英霸UI文件
Main.observerUiSettingsEditorTitle=觀戰界面設置編輯器
Main.warningAlertTitle=Warning
Main.couldNotFindMpqEditor=Could not find the 'MPQEditor.exe' under '%1$s'.
General.OkButton=確定
General.YesButton=是
General.NoButton=否
General.CancelButton=取消
General.ExceptionStackTrace=異常堆棧:
Main.OpenedFileNoComponentList=無法在指定的文件中找到組建列表。
Main.openObserverInterfaceTitle=打開觀戰界面文件...
Main.saveUiTitle=保存觀戰界面文件...
Main.sc2HeroesObserverInterfaceExtFilter=星海爭霸2 / 暴雪英霸 觀戰界面
Main.sc2InterfaceFilter=星海爭霸2 UI文件
Main.unsavedChangesTitle=有未保存的更改
MenuBarController.About=關於
MenuBarController.AboutText=版本: \t\t%1$s%n%n開發:\t\tChristoph "Ahli" Ahlers (twitter: @AhliSC2)
MenuBarController.AboutText2=本地化支持:\n\t簡、繁體中文:\t\t\ttinkoliu (twitter: @tinkoliu)\n\n工具:\n\tMPQ Editor:\t\t\t\tLadislav \"Ladik\" Zezula (http://www.zezula.net)
MenuBarController.ObserverUISettingsEditor=觀戰界面設置編輯器
rootLayout.Open=打開
rootLayout.Save=保存
rootLayout.SaveAs=另存爲
rootLayout.CloseFile=關閉文件
rootLayout.Exit=退出
rootLayout.About=關於
rootLayout.?=?
rootLayout.File=文件
TabsController.ResetDefault=默認
TabsController.ResetOldValue=撤消
tabsLayout.Hotkeys=快捷鍵
tabsLayout.Name=名稱
tabsLayout.Description=描述
tabsLayout.Default=默認
tabsLayout.Key=快捷鍵
tabsLayout.Value=值
tabsLayout.Settings=設置
tabsLayout.NoHotkeysFound=找不到快捷鍵。
tabsLayout.NoSettingsFound=找不到設置項
tabsLayout.Actions=操作
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder;
import interfacebuilder.config.AppConfiguration;
import interfacebuilder.config.FxmlConfiguration;
import interfacebuilder.integration.CommandLineParams;
import interfacebuilder.integration.InterProcessCommunication;
import javafx.application.Application;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Import;
import java.io.IOException;
import java.util.Arrays;
import static interfacebuilder.ui.AppController.FATAL_ERROR;
// start with VM parameter: -add-opens=javafx.controls/javafx.scene.control=interfacex.builder
@EnableAutoConfiguration(excludeName = { // exclude based on beans in context on runtime
"org.springframework.boot.autoconfigure.aop.AopAutoConfiguration", // not required
//"org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", // required for Resources
//"org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration", // req for Resources
"org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration",
"org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration",
//"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration", // required for JPA Repository
"org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration",
//"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration", // req
"org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration",
"org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration",
//"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration", // req
"org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration",
"org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration",
//"org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration", // req
"org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration" })
@Import({ AppConfiguration.class, FxmlConfiguration.class })
public final class SpringBootApplication {
public static final int INTER_PROCESS_COMMUNICATION_PORT = 12317;
private static final Logger logger = LogManager.getLogger(SpringBootApplication.class);
public static void main(final String[] args) {
try {
// TODO app mode without GUI
if (InterProcessCommunication.isPortFree(INTER_PROCESS_COMMUNICATION_PORT)) {
if (!actAsServer(args)) {
logger.warn("Failed to create Server Thread. Starting App without it...");
launch(args, null);
}
} else {
logger.info("App already running. Passing over command line arguments.");
actAsClient(args);
}
} catch (final Exception e) {
logger.error(FATAL_ERROR, e);
}
}
private static boolean actAsClient(final String[] args) {
if (InterProcessCommunication.sendToServer(args, INTER_PROCESS_COMMUNICATION_PORT)) {
return true;
} else {
logger.error("InterProcessCommunication as Client failed. The port might not be free anymore.");
}
return false;
}
private static boolean actAsServer(final String[] args) {
try (final InterProcessCommunication interProcessCommunication = new InterProcessCommunication()) {
final Thread serverThread = interProcessCommunication.actAsServer(INTER_PROCESS_COMMUNICATION_PORT);
if (serverThread != null) {
launch(args, serverThread);
return true;
} else {
logger.error("InterProcessCommunication failed");
}
} catch (final IOException e) {
logger.error("Closing InterProcessCommunication failed", e);
}
return false;
}
private static void launch(final String[] args, final Thread serverThread) {
logger.trace("System's Log4j2 Configuration File: {}", () -> System.getProperty("log4j.configurationFile"));
logger.info(
"Launch arguments: {}\nMax Heap Space: {}mb.",
() -> Arrays.toString(args),
() -> Runtime.getRuntime().maxMemory() / 1_048_576L);
boolean noGui = false;
for (final String arg : args) {
if ("--noGUI".equalsIgnoreCase(arg)) {
noGui = true;
break;
}
}
if (noGui) {
launchNoGui(args, serverThread);
} else {
launchGui(args, serverThread);
}
}
private static void launchNoGui(final String[] args, final Thread serverThread) {
final NoGuiApplication app = new NoGuiApplication(args, serverThread);
app.start();
}
private static void launchGui(final String[] args, final Thread serverThread) {
setJavaFxPreloader(AppPreloader.class.getCanonicalName());
Application.launch(JavafxApplication.class, argsWithServerThread(args, serverThread));
}
private static void setJavaFxPreloader(final String canonicalPath) {
System.setProperty("javafx.preloader", canonicalPath);
}
private static String[] argsWithServerThread(final String[] args, final Thread serverThread) {
if (serverThread != null) {
final String[] destArray = Arrays.copyOf(args, args.length + 1);
destArray[destArray.length - 1] =
CommandLineParams.PARAM_PREFIX + CommandLineParams.SERVER + CommandLineParams.EQUAL +
serverThread.getId();
return destArray;
}
return args;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.base_ui;
import com.ahli.galaxy.ui.UICatalogImpl;
import com.ahli.galaxy.ui.interfaces.UICatalog;
import com.esotericsoftware.kryo.Kryo;
import interfacebuilder.config.ConfigService;
import interfacebuilder.integration.kryo.KryoGameInfo;
import interfacebuilder.integration.kryo.KryoService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class DiscCacheService {
private static final Logger logger = LogManager.getLogger(DiscCacheService.class);
private final ConfigService configService;
private final KryoService kryoService;
public DiscCacheService(final ConfigService configService, final KryoService kryoService) {
this.configService = configService;
this.kryoService = kryoService;
}
/**
* @param catalog
* @param gameDefName
* @throws IOException
*/
public void put(final UICatalog catalog, final String gameDefName, final boolean isPtr, final int[] version)
throws IOException {
final Path p = getCacheFilePath(gameDefName, isPtr);
Files.deleteIfExists(p);
final KryoGameInfo metaInfo = new KryoGameInfo(version, gameDefName, isPtr);
final List<Object> payload = new ArrayList<>(2);
payload.add(metaInfo);
payload.add(catalog);
final Kryo kryo = kryoService.getKryoForUICatalog();
kryoService.put(p, payload, kryo);
logger.info(
"Cached UI for {} - templates={}, blizzOnlyTemplates={}, constants={}, blizzOnlyConstants={}, devLayouts={}",
gameDefName,
catalog.getTemplates().size(),
catalog.getBlizzOnlyTemplates().size(),
catalog.getConstants().size(),
catalog.getBlizzOnlyConstants().size(),
catalog.getDevLayouts().size());
}
/**
* @param gameDefName
* @return
*/
public Path getCacheFilePath(final String gameDefName, final boolean isPtr) {
return configService.getCachePath().resolve(gameDefName + (isPtr ? " PTR" : "") + ".kryo");
}
/**
* @param gameDefName
* @param isPtr
* @return
* @throws IOException
*/
public UICatalog getCachedBaseUi(final String gameDefName, final boolean isPtr) throws IOException {
return getCachedBaseUi(getCacheFilePath(gameDefName, isPtr));
}
public UICatalog getCachedBaseUi(final Path path) throws IOException {
final Kryo kryo = kryoService.getKryoForUICatalog();
final List<Class<?>> payloadClasses = new ArrayList<>(2);
payloadClasses.add(KryoGameInfo.class);
payloadClasses.add(UICatalogImpl.class);
return (UICatalog) kryoService.get(path, payloadClasses, kryo).get(1);
}
public KryoGameInfo getCachedBaseUiInfo(final Path path) throws IOException {
final Kryo kryo = kryoService.getKryoForUICatalog();
final List<Class<?>> payloadClasses = new ArrayList<>(2);
payloadClasses.add(KryoGameInfo.class);
payloadClasses.add(UICatalogImpl.class);
return (KryoGameInfo) kryoService.get(path, payloadClasses, kryo, 0).get(0);
}
/**
* @param gameDefName
* @param isPtr
* @throws IOException
*/
public void remove(final String gameDefName, final boolean isPtr) throws IOException {
final Path p = getCacheFilePath(gameDefName, isPtr);
if (Files.exists(p)) {
Files.delete(p);
logger.trace("Cleaning cache of {} in {}", () -> gameDefName, p::toAbsolutePath);
} else {
logger.trace("Could not find cache of {} in {} to clean it", () -> gameDefName, p::toAbsolutePath);
}
}
/**
* @param gameDefName
* @param isPtr
* @return
*/
public boolean exists(final String gameDefName, final boolean isPtr) {
return Files.exists(getCacheFilePath(gameDefName, isPtr));
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui.exception;
import java.io.Serial;
/**
* Exception of the UI Parsing/Validation.
*
* @author Ahli
*/
public class UIException extends Exception {
@Serial
private static final long serialVersionUID = -4719408127547238653L;
/**
* Constructor.
*
* @param message
* the message
*/
public UIException(final String message) {
super(message);
}
/**
* Constructor.
*
* @param message
* the message
* @param e
* the contained Exception
*/
public UIException(final String message, final Exception e) {
super(message, e);
}
/**
* Constructor.
*
* @param e
* the contained Exception
*/
public UIException(final Exception e) {
super(e);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.hotkey_ui.application.controller;
import com.ahli.hotkey_ui.application.i18n.Messages;
import com.ahli.hotkey_ui.application.model.ValueDef;
import com.ahli.hotkey_ui.application.ui.DynamicValueDefEditingTableCell;
import com.ahli.hotkey_ui.application.ui.ResetDefaultButtonTableCell;
import com.ahli.hotkey_ui.application.ui.WrappingTextTableCell;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author Ahli
*/
public class TabsController {
private static final Logger logger = LogManager.getLogger(TabsController.class);
private static final Callback<TableColumn<ValueDef, Boolean>, TableCell<ValueDef, Boolean>>
ActionColumnCellFactoryReset =
tableColumn -> new ResetDefaultButtonTableCell(Messages.getString("TabsController.ResetDefault"),
Messages.getString("TabsController.ResetOldValue"));
private static final Callback<TableColumn<ValueDef, String>, TableCell<ValueDef, String>> WRAPPING_CELL_FACTORY =
tableColumn -> new WrappingTextTableCell();
private static final Callback<TableColumn<ValueDef, String>, TableCell<ValueDef, String>>
VALUEDEF_EDIT_CELL_FACTORY = tableColumn -> new DynamicValueDefEditingTableCell();
private final ObservableList<ValueDef> hotkeysData = FXCollections.observableArrayList();
private final ObservableList<ValueDef> settingsData = FXCollections.observableArrayList();
@FXML
private TableView<ValueDef> hotkeysTable;
@FXML
private TableColumn<ValueDef, String> hotkeysNameCol;
@FXML
private TableColumn<ValueDef, String> hotkeysDescriptionCol;
@FXML
private TableColumn<ValueDef, String> hotkeysDefaultCol;
@FXML
private TableColumn<ValueDef, String> hotkeysKeyCol;
@FXML
private TableColumn<ValueDef, Boolean> hotkeysActionsCol;
@FXML
private TableView<ValueDef> settingsTable;
@FXML
private TableColumn<ValueDef, String> settingsNameCol;
@FXML
private TableColumn<ValueDef, String> settingsDescriptionCol;
@FXML
private TableColumn<ValueDef, String> settingsDefaultCol;
@FXML
private TableColumn<ValueDef, String> settingsValueCol;
@FXML
private TableColumn<ValueDef, Boolean> settingsActionsCol;
/**
* On Controller initialization.
*/
@FXML
public void initialize() {
logger.trace("initializing");
final Callback<CellDataFeatures<ValueDef, String>, ObservableValue<String>> idFac =
new PropertyValueFactory<>("id");
final Callback<CellDataFeatures<ValueDef, String>, ObservableValue<String>> descFac =
new PropertyValueFactory<>("description");
final Callback<CellDataFeatures<ValueDef, String>, ObservableValue<String>> defaultValueFac =
new PropertyValueFactory<>("defaultValue");
final Callback<CellDataFeatures<ValueDef, String>, ObservableValue<String>> valueFac =
new PropertyValueFactory<>("value");
final Callback<CellDataFeatures<ValueDef, Boolean>, ObservableValue<Boolean>> hasChangedFac =
new PropertyValueFactory<>("hasChanged");
hotkeysNameCol.setCellValueFactory(idFac);
hotkeysDescriptionCol.setCellValueFactory(descFac);
hotkeysDescriptionCol.setCellFactory(WRAPPING_CELL_FACTORY);
hotkeysDefaultCol.setCellValueFactory(defaultValueFac);
hotkeysKeyCol.setCellValueFactory(valueFac);
hotkeysKeyCol.setCellFactory(VALUEDEF_EDIT_CELL_FACTORY);
hotkeysKeyCol.setSortable(false);
hotkeysActionsCol.setSortable(false);
hotkeysActionsCol.setCellValueFactory(hasChangedFac);
hotkeysActionsCol.setCellFactory(ActionColumnCellFactoryReset);
settingsNameCol.setCellValueFactory(idFac);
settingsDescriptionCol.setCellValueFactory(descFac);
settingsDescriptionCol.setCellFactory(WRAPPING_CELL_FACTORY);
settingsDefaultCol.setCellValueFactory(defaultValueFac);
settingsValueCol.setCellValueFactory(valueFac);
settingsValueCol.setCellFactory(VALUEDEF_EDIT_CELL_FACTORY);
settingsValueCol.setSortable(false);
settingsActionsCol.setSortable(false);
settingsActionsCol.setCellValueFactory(hasChangedFac);
settingsActionsCol.setCellFactory(ActionColumnCellFactoryReset);
hotkeysTable.setItems(hotkeysData);
settingsTable.setItems(settingsData);
}
/**
* @return the hotkeysData
*/
public ObservableList<ValueDef> getHotkeysData() {
return hotkeysData;
}
/**
* @return the settingsData
*/
public ObservableList<ValueDef> getSettingsData() {
return settingsData;
}
/**
* Clears the data.
*/
public void clearData() {
hotkeysData.clear();
settingsData.clear();
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui.interfaces;
import java.util.List;
public interface UIAnimation extends UIElement {
/**
* Returns a deep clone of this.
*/
@Override
Object deepCopy();
/**
* @return the controllers
*/
List<UIElement> getControllers();
/**
* @return the events
*/
List<UIAttribute> getEvents();
/**
* @param newEvent
*/
void addEvent(UIAttribute newEvent);
/**
* @return
*/
boolean isNextEventsAdditionShouldOverride();
/**
* @param nextEventsAdditionShouldOverride
*/
void setNextEventsAdditionShouldOverride(boolean nextEventsAdditionShouldOverride);
/**
* @return the driver
*/
UIAttribute getDriver();
/**
* @param driver
* the driver to set
*/
void setDriver(UIAttribute driver);
/**
* @param path
* @return
*/
@Override
UIElement receiveFrameFromPath(String path);
@Override
String toString();
@Override
@SuppressWarnings("java:S4144")
List<UIElement> getChildren();
@Override
@SuppressWarnings("java:S4144")
List<UIElement> getChildrenRaw();
@Override
boolean equals(Object o);
@Override
boolean canEqual(Object other);
@Override
int hashCode();
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.mpq;
import com.ahli.mpq.i18n.Messages;
import com.ahli.mpq.mpqeditor.MpqEditorCompression;
import com.ahli.mpq.mpqeditor.MpqEditorCompressionRule;
import com.ahli.mpq.mpqeditor.MpqEditorSettingsInterface;
import com.ahli.util.DeepCopyable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Stream;
/**
* Implements a MpqInterface for <NAME>'s MpqEditor.exe.
*
* @author Ahli
*/
public class MpqEditorInterface implements MpqInterface, DeepCopyable {
private static final String EXECUTING = "executing: {}";
private static final String EXECUTION_FINISHED = "execution finished";
private static final char QUOTE = '\"';
private static final String QUOTESTR = "\"";
private static final Logger logger = LoggerFactory.getLogger(MpqEditorInterface.class);
private static final String MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND = "MpqInterface.MpqEditorNotFound";
private static final String CMD = "cmd";
private static final String SLASH_C = "/C";
private static final Object classWideLock = new Object();
private MpqEditorSettingsInterface settings;
private Path mpqEditorPath;
private Path mpqCachePath;
/**
* Constructor.
*
* @param mpqCachePath
* path of the directory that will temporarily contain the extracted mpq
* @param mpqEditorPath
* the path of the MpqEditor.exe
*/
public MpqEditorInterface(final Path mpqCachePath, final Path mpqEditorPath) {
this.mpqCachePath = mpqCachePath;
this.mpqEditorPath = mpqEditorPath;
settings = new MpqEditorSettingsInterface();
}
/**
* Returns a cloned instance of this.
*/
@Override
public Object deepCopy() {
final MpqEditorInterface clone = new MpqEditorInterface(mpqCachePath, mpqEditorPath);
clone.settings = (MpqEditorSettingsInterface) settings.deepCopy();
return clone;
}
/**
* Build MPQ from cache.
*
* @param buildPath
* @param buildFileName
* @param compressXml
* @param compressMpq
* @param buildUnprotectedToo
* if protectMPQ, then this controls if an unprotected version is build, too
* @throws IOException
* @throws InterruptedException
* @throws MpqException
*/
public void buildMpq(
final Path buildPath,
final String buildFileName,
final boolean compressXml,
final MpqEditorCompression compressMpq,
final boolean buildUnprotectedToo) throws IOException, InterruptedException, MpqException {
final Path absolutePath = buildPath.resolve(buildFileName);
buildMpq(absolutePath, compressXml, compressMpq, buildUnprotectedToo);
}
/**
* Build MPQ from cache.
*
* @param targetFile
* @param compressXml
* @param compressMpq
* @param buildUnprotectedToo
* if compressXml, then this controls if an unprotected version is build, too
* @throws IOException
* @throws InterruptedException
* @throws MpqException
*/
public void buildMpq(
final Path targetFile,
final boolean compressXml,
final MpqEditorCompression compressMpq,
final boolean buildUnprotectedToo) throws IOException, InterruptedException, MpqException {
// create parent directory
final Path parentFolder = targetFile.getParent();
if (parentFolder == null) {
logger.error("ERROR: Could not receive parent directory of path: {}", targetFile);
throw new MpqException(String.format(Messages.getString("MpqInterface.CouldNotCreatePath"), targetFile));
}
if (!Files.exists(parentFolder)) {
Files.createDirectories(parentFolder);
}
// add 2 to be sure to have enough space for listfile and attributes
final long fileCount = 2L + getFileCountInFolder(mpqCachePath);
if (compressXml) {
if (buildUnprotectedToo) {
// special unprotected file path
final Path unprotectedPath = getPathWithUnprotectedSuffix(targetFile);
// make way for unprotected file
deleteFile(unprotectedPath);
// build unprotected file
buildMpqWithCompression(MpqEditorCompression.NONE, unprotectedPath.toString(), fileCount);
}
// make way for protected file
deleteFile(targetFile);
// extra file compression
try {
XmlCompressorDom.processCache(mpqCachePath, 1);
} catch (final ParserConfigurationException | TransformerConfigurationException e) {
logger.error("Error while compressing files in the cache", e);
}
} else {
// NO CONTENT COMPRESSION/PROTECTION OPTIONS
// make way for file
deleteFile(targetFile);
}
buildMpqWithCompression(compressMpq, targetFile.toString(), fileCount);
}
/**
* Returns the file count in a folder including all subfolders.
*
* @param path
* @return
*/
public static long getFileCountInFolder(final Path path) throws IOException {
try (final Stream<Path> walk = Files.walk(path)) {
return walk.parallel().map(Path::toFile).filter(p -> !p.isDirectory()).count();
}
}
/**
* Returns path with suffix via changing file name.
*
* @param targetFile
* @return
*/
private static Path getPathWithUnprotectedSuffix(final Path targetFile) {
final String path = targetFile.toString();
final int i = path.lastIndexOf('.');
return Path.of(path.substring(0, i < 0 ? path.length() : i) + "_unprtctd" + (i < 0 ? "" : path.substring(i)));
}
/**
* Deletes a file of the specified path.
*
* @param path
* file path
* @throws MpqException
* if file does not exist, is not a file or the file could not be deleted
*/
private static void deleteFile(final Path path) throws MpqException {
if (Files.exists(path)) {
if (Files.isRegularFile(path)) {
if (Files.isWritable(path)) {
try {
Files.delete(path);
} catch (final IOException e) {
logger.error(String.format("ERROR: Could not delete file '%s'.", path), e);
throw new MpqException(String.format(Messages.getString("MpqInterface.CouldNotOverwriteFile"),
path), e);
}
} else {
throw new MpqException(String.format("ERROR: Could not delete file '%s'. It might be used by another process.",
path));
}
} else {
throw new MpqException(String.format("ERROR: Could not delete file '%s'. A directory with the same name exists.",
path));
}
}
}
/**
* @param compressMpq
* @param absolutePath
* @param fileCount
* @throws IOException
* @throws MpqException
* @throws InterruptedException
*/
private void buildMpqWithCompression(
final MpqEditorCompression compressMpq, final String absolutePath, final long fileCount)
throws IOException, MpqException, InterruptedException {
// mpq compression
settings.setCompression(compressMpq);
/* MpqEditor reads its settings from ini files in a specific location.
Multiple different compression settings would cause race conditions and problems. */
final MpqEditorSettingsInterface settingsInterface = settings;
final String cachePath = mpqCachePath.toString();
synchronized (classWideLock) {
settingsInterface.applyCompression();
try {
// build protected file
newMpq(absolutePath, fileCount);
addToMpq(absolutePath, cachePath, "");
compactMpq(absolutePath);
} finally {
settingsInterface.restoreOriginalSettingFiles();
}
}
}
/**
* @param mpqPath
* @param maxFileCount
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void newMpq(final String mpqPath, final long maxFileCount)
throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " n " + QUOTE + mpqPath + QUOTE + " " + maxFileCount +
QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* @param mpqPath
* @param sourceFilePath
* @param targetName
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void addToMpq(final String mpqPath, final String sourceFilePath, final String targetName)
throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " a " + QUOTE + mpqPath + QUOTE + " " + QUOTE +
sourceFilePath + QUOTE + " " + QUOTE + targetName + QUOTE + " /r" + QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* @param mpqPath
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void compactMpq(final String mpqPath) throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " compact " + QUOTE + mpqPath + QUOTE + QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* Verifies the existence of the MPQEditor.exe at the stored file path.
*
* @return
*/
private boolean isMissingMpqEditor() {
return !Files.isExecutable(mpqEditorPath);
}
/**
* @param mpqSourcePath
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void extractEntireMPQ(final String mpqSourcePath) throws InterruptedException, IOException, MpqException {
logger.trace("mpqCachePath: {}\nmpqSourcePath: {}", mpqCachePath, mpqSourcePath);
clearCacheExtractedMpq();
extractFromMpq(mpqSourcePath, "*", mpqCachePath.toString(), true);
clearCacheListFile();
clearCacheAttributesFile();
if (getFileCountInFolder(mpqCachePath) <= 0L) {
throw new MpqException(String.format(Messages.getString("MpqInterface.NoFilesExtracted"), mpqSourcePath));
}
}
/**
* Removes all files in the cache.
*/
public boolean clearCacheExtractedMpq() {
final Path path = mpqCachePath;
if (Files.exists(path)) {
try {
deleteDir(path);
} catch (final IOException e) {
logger.error("clearing Cache FAILED", e);
return false;
}
}
return true;
}
/**
* @param mpqPath
* @param fileName
* @param targetPath
* @param inclSubFolders
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void extractFromMpq(
final String mpqPath, final String fileName, final String targetPath, final boolean inclSubFolders)
throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " e " + QUOTE + mpqPath + QUOTE + " " + QUOTE + fileName +
QUOTE + " " + QUOTE + targetPath + QUOTE + (inclSubFolders ? " /fp" : "") + QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* Removes the "(listfile)" file from the cache.
*/
private void clearCacheListFile() throws IOException {
final Path path = mpqCachePath.resolve("(listfile)");
if (!Files.isDirectory(path)) {
Files.deleteIfExists(path);
}
}
/**
* Removes the "(attributes)" file from the cache.
*/
private void clearCacheAttributesFile() throws IOException {
final Path path = mpqCachePath.resolve("(attributes)");
if (!Files.isDirectory(path)) {
Files.deleteIfExists(path);
}
}
/**
* @param path
* @return
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void deleteDir(final Path path) throws IOException {
if (Files.isDirectory(path)) {
try (final Stream<Path> walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
}
} else {
Files.delete(path);
}
}
/**
* @param mpqPath
* @param scriptPath
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void scriptMpq(final String mpqPath, final String scriptPath)
throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " s " + QUOTE + mpqPath + QUOTE + " " + QUOTE + scriptPath +
QUOTE + QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* @param mpqPath
* @param filePath
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void deleteFileInMpq(final String mpqPath, final String filePath)
throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " d " + QUOTE + mpqPath + QUOTE + " " + QUOTE + filePath +
QUOTE + QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* @param mpqPath
* @param oldfilePath
* @param newFilePath
* @throws InterruptedException
* @throws IOException
* @throws MpqException
*/
public void renameFileInMpq(final String mpqPath, final String oldfilePath, final String newFilePath)
throws InterruptedException, IOException, MpqException {
if (isMissingMpqEditor()) {
throw new MpqException(String.format(Messages.getString(MPQ_INTERFACE_MPQ_EDITOR_NOT_FOUND),
mpqEditorPath));
}
final String[] cmd = new String[] { CMD, SLASH_C,
QUOTESTR + QUOTE + mpqEditorPath + QUOTE + " r " + QUOTE + mpqPath + QUOTE + " " + QUOTE + oldfilePath +
QUOTE + " " + QUOTE + newFilePath + QUOTE + QUOTE };
if (logger.isTraceEnabled()) {
logger.trace(EXECUTING, Arrays.toString(cmd));
}
Runtime.getRuntime().exec(cmd).waitFor();
logger.trace(EXECUTION_FINISHED);
}
/**
* Returns the path to a file from the cache with the specified internal path.
*
* @param internalPath
* internal path
* @return path
*/
@Override
public Path getFilePathFromMpq(final String internalPath) {
return mpqCachePath.resolve(internalPath);
}
/**
* Returns the componentList file.
*
* @return
*/
public Path getComponentListFile() {
Path path = mpqCachePath.resolve("ComponentList.StormComponents");
if (!Files.isRegularFile(path)) {
path = mpqCachePath.resolve("ComponentList.SC2Components");
if (!Files.isRegularFile(path)) {
return null;
}
}
return path;
}
/**
*
*/
@Override
public boolean isHeroesMpq() throws MpqException {
Path path = mpqCachePath.resolve("ComponentList.StormComponents");
if (!Files.isRegularFile(path)) {
path = mpqCachePath.resolve("ComponentList.SC2Components");
if (!Files.isRegularFile(path)) {
logger.error("ERROR: archive has no ComponentList file.");
throw new MpqException("ERROR: Cannot identify if file belongs to Heroes or SC2.");
}
return false;
}
return true;
}
@Override
public Path getCache() {
return mpqCachePath;
}
@Override
public void setCache(final Path cache) {
mpqCachePath = cache;
}
/**
* Returns the custom ruleset for the file attributes and compression.
*
* @return
*/
public MpqEditorCompressionRule[] getCustomRuleSet() {
return settings.getCustomRuleSet();
}
/**
* Sets custom rules for the file attributes and compression. To use it, the archive needs to use
* MpqEditorCompression.CUSTOM.
*
* @param rules
*/
public void setCustomCompressionRules(final MpqEditorCompressionRule... rules) {
settings.setCustomRules(rules);
}
/**
* @return
*/
public Path getMpqEditorPath() {
return mpqEditorPath;
}
/**
* Sets the MpqEditor path.
*
* @param editorPath
* new editor path as String
*/
public void setMpqEditorPath(final Path editorPath) {
mpqEditorPath = editorPath;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.validator;
import com.ahli.galaxy.ModData;
import com.ahli.galaxy.ui.UIAnchorSide;
import com.ahli.galaxy.ui.UITemplate;
import com.ahli.galaxy.ui.interfaces.UIAnimation;
import com.ahli.galaxy.ui.interfaces.UIAttribute;
import com.ahli.galaxy.ui.interfaces.UICatalog;
import com.ahli.galaxy.ui.interfaces.UIController;
import com.ahli.galaxy.ui.interfaces.UIElement;
import com.ahli.galaxy.ui.interfaces.UIFrame;
import com.ahli.galaxy.ui.interfaces.UIStateGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayDeque;
import java.util.List;
public class ReferenceValidator {
private static final Logger logger = LoggerFactory.getLogger(ReferenceValidator.class);
private final UICatalog uiCatalog;
public ReferenceValidator(final ModData mod) {
uiCatalog = mod.getUiCatalog();
}
private static void validate(final UIAnimation element, final ValidatorData data) {
for (final UIAttribute event : element.getEvents()) {
validate(element, event.getValue("frame"), data);
}
for (final UIElement c : element.getControllers()) {
final UIController controller = (UIController) c;
validate(element, controller, controller.getValue("frame"), data);
}
}
private static void validate(
final UIAnimation element, final UIController controller, final String frame, final ValidatorData data) {
}
private static void validate(
final UIFrame element, final UIAnchorSide anchorSide, final ValidatorData data) {
validate(element, element.getAnchorRelative(anchorSide), data);
}
private static void validate(final UIElement element, final String relative, final ValidatorData data) {
// TODO $this
// TODO $parent
// TODO $ancestor[@type=...]
// TODO $root // used to create elements in a few special tags, e.g. <NormalImage val="NormalImage"/> or <HoverImage val="HoverImage"/>
// TODO $layer
// TODO $sibling
// TODO $handle
}
public void validate() {
if (uiCatalog != null) {
final ValidatorData data = new ValidatorData(20);
for (final UITemplate template : uiCatalog.getTemplates()) {
// TODO ideally only templates that are directly instanciated are used... so maybe the ones that were not referenced somewhere else and have no file-attribute
if ("GameUI".equalsIgnoreCase(template.getFileName()) &&
"GameUI".equalsIgnoreCase(template.getElement().getName())) {
// TODO atm only GameUI/GameUI
validate(template.getElement(), data);
break;
}
}
}
}
// TODO validate bindings
private void validate(final UIElement element, final ValidatorData data) {
if (element instanceof UIFrame) {
validate((UIFrame) element, data);
} else if (element instanceof UIAnimation) {
validate((UIAnimation) element, data);
} else if (element instanceof UIStateGroup) {
validate((UIStateGroup) element, data);
} else {
logger.error("ERROR: UIElement not handled in ReferenceValidator");
}
}
private void validate(final UIFrame element, final ValidatorData data) {
validate(element, UIAnchorSide.TOP, data);
validate(element, UIAnchorSide.LEFT, data);
validate(element, UIAnchorSide.RIGHT, data);
validate(element, UIAnchorSide.BOTTOM, data);
final List<UIElement> children = element.getChildrenRaw();
if (children != null && !children.isEmpty()) {
data.parents.addFirst(element);
for (final UIElement child : children) {
validate(child, data);
}
data.parents.removeFirst();
}
}
private void validate(final UIStateGroup element, final ValidatorData data) {
final List<UIElement> states = element.getChildrenRaw();
if (states != null) {
}
}
private static class ValidatorData {
private final ArrayDeque<UIFrame> parents;
//private boolean isDevLayout = false;
private ValidatorData(final int parentStackCapacity) {
parents = new ArrayDeque<>(parentStackCapacity);
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.hotkey_ui.application.ui;
import com.ahli.hotkey_ui.application.model.ValueDef;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.layout.HBox;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A table cell for ValueDef model data to reset its value to the default or the old value.
*
* @author Ahli
*/
public class ResetDefaultButtonTableCell extends TableCell<ValueDef, Boolean> {
private static final Logger logger = LogManager.getLogger(ResetDefaultButtonTableCell.class);
private final Button resetToDefaultButton = new Button();
private final Button resetToOldValueButton = new Button();
/**
* @param resetToDefaultText
* @param resetToOldValueText
*/
public ResetDefaultButtonTableCell(final String resetToDefaultText, final String resetToOldValueText) {
resetToDefaultButton.setText(resetToDefaultText);
resetToOldValueButton.setText(resetToOldValueText);
resetToDefaultButton.setOnAction(this::resetToDefault);
resetToOldValueButton.setOnAction(this::resetToOldValue);
}
private void resetToDefault(final ActionEvent event) {
logger.trace("reset value to default value button clicked");
final ValueDef data = getTableRow().getItem();
data.setValue(data.getDefaultValue());
}
private void resetToOldValue(final ActionEvent event) {
logger.trace("reset value to old value button clicked");
final ValueDef data = getTableRow().getItem();
data.setValue(data.getOldValue());
}
// Display button if the row is not empty
@Override
protected void updateItem(final Boolean value, final boolean empty) {
super.updateItem(value, empty);
if (!empty && getTableRow().getItem() != null) {
if (value != null && value) {
if (getTableRow().getItem().isDefaultValue()) {
setGraphic(resetToOldValueButton);
} else {
setGraphic(new HBox(resetToDefaultButton, resetToOldValueButton));
}
} else {
if (getTableRow().getItem().isDefaultValue()) {
setGraphic(null);
} else {
setGraphic(resetToDefaultButton);
}
}
} else {
setGraphic(null);
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder;
import javafx.application.Preloader;
import javafx.scene.Scene;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
public class AppPreloader extends Preloader {
private static final Logger logger = LogManager.getLogger(AppPreloader.class);
private Stage stage;
@Override
public void start(final Stage primaryStage) {
stage = primaryStage;
final ProgressIndicator progressIndicator = new ProgressIndicator(-1);
final Scene scene = new Scene(progressIndicator, 90, 90);
primaryStage.initStyle(StageStyle.TRANSPARENT);
scene.setFill(Color.TRANSPARENT);
try {
final URL cssFile = getClass().getResource("/view/preload.css");
if (cssFile != null) {
scene.getStylesheets().add(cssFile.toURI().toString());
} else {
logger.warn("preloader stylesheet not found");
}
} catch (final URISyntaxException e) {
logger.error("preloader stylesheet loading error", e);
}
primaryStage.setScene(scene);
primaryStage.setTitle("Interface Builder");
final InputStream iconStream = getClass().getResourceAsStream("/res/ahli.png");
if (iconStream != null) {
primaryStage.getIcons().add(new Image(iconStream));
} else {
logger.warn("preloader icon not found");
}
primaryStage.show();
}
@Override
public void handleStateChangeNotification(final StateChangeNotification info) {
if (info.getType() == StateChangeNotification.Type.BEFORE_START) {
stage.hide();
}
}
}
<file_sep>Main.allFilesFilter=所有文件
Main.anErrorOccured=发生错误
Main.hasUnsavedChanges='%1$s' 的更改尚未保存。是否保存更改?
Main.heroesInterfaceFilter=风暴英雄UI文件
Main.observerUiSettingsEditorTitle=观战界面设置编辑器
Main.warningAlertTitle=Warning
Main.couldNotFindMpqEditor=Could not find the 'MPQEditor.exe' under '%1$s'.
General.OkButton=确定
General.YesButton=是
General.NoButton=否
General.CancelButton=取消
General.ExceptionStackTrace=异常堆栈:
Main.OpenedFileNoComponentList=无法在指定的文件中找到组建列表。
Main.openObserverInterfaceTitle=打开观战界面文件...
Main.saveUiTitle=保存观战界面文件...
Main.sc2HeroesObserverInterfaceExtFilter=星际争霸2 / 风暴英雄 观战界面
Main.sc2InterfaceFilter=星际争霸2 UI文件
Main.unsavedChangesTitle=有未保存的更改
MenuBarController.About=关于
MenuBarController.AboutText=版本: \t\t%1$s%n%n开发:\t\tChristoph "Ahli" Ahlers (twitter: @AhliSC2)
MenuBarController.AboutText2=本地化支持:\n\t简、繁体中文:\t\t\ttinkoliu (twitter: @tinkoliu)\n\n工具:\n\tMPQ Editor:\t\t\tLadislav \"Ladik\" Zezula (http://www.zezula.net)
MenuBarController.ObserverUISettingsEditor=观战界面设置编辑器
rootLayout.Open=打开
rootLayout.Save=保存
rootLayout.SaveAs=另存为
rootLayout.CloseFile=关闭文件
rootLayout.Exit=退出
rootLayout.About=关于
rootLayout.?=?
rootLayout.File=文件
TabsController.ResetDefault=默认
TabsController.ResetOldValue=撤消
tabsLayout.Hotkeys=快捷键
tabsLayout.Name=名称
tabsLayout.Description=描述
tabsLayout.Default=默认
tabsLayout.Key=快捷键
tabsLayout.Value=值
tabsLayout.Settings=设置
tabsLayout.NoHotkeysFound=找不到快捷键。
tabsLayout.NoSettingsFound=找不到设置项。
tabsLayout.Actions=操作
<file_sep>
Bootstrap test page
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.integration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.system.ApplicationHome;
import java.io.File;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Helper class for the executable jar file. It is capable of determining the position.
*
* @author Ahli
*/
public final class JarHelper {
private static final Logger logger = LogManager.getLogger(JarHelper.class);
/**
* Disabled Constructor.
*/
private JarHelper() {
}
/**
* from stackoverflow because why doesn't java have this functionality? It's not like nobody would need that or it
* is trivial to create...
*
* @param aclass
* @return File at base path
*/
public static Path getJarDir(final Class<?> aclass) {
logger.trace("_FINDING JAR'S PATH");
// ATTEMPT #1
final File dir = new ApplicationHome(aclass).getDir();
String str = dir.toString();
logger.trace("Attempt#1 java.class.path: {}", dir::toString);
// check if started in eclipse
final int i = str.indexOf(File.separator + "target" + File.separator + "classes");
if (i > 0) {
final String check = str.substring(0, i);
logger.trace("target/classes location: {}", check);
if (check.indexOf(';') < 0) {
final Path p = Path.of(check).getParent().getParent();
if (Files.exists(p)) {
return p.resolve("dev");
}
}
// get current working directory
final URI uri = new File(".").toURI();
// results in: "file:/D:/GalaxyObsUI/dev/./"
// but maybe results in something completely different like
// notepad++'s directory...
str = uri.getPath();
logger.trace("_URI path: {}", uri::getPath);
// fix for intellij
if (str.endsWith("/tools/./")) {
str = str.substring(0, str.length() - 2);
final String dirStr = dir.toString();
final String tools = "\\tools\\";
final int targetIndex = dirStr.indexOf("\\target\\");
if (targetIndex >= 0) {
str += dirStr.substring(dirStr.indexOf(tools) + tools.length(), targetIndex);
str = str.replace('\\', '/');
}
}
if (str.startsWith("file:/")) {
str = str.substring(6);
}
if (str.charAt(0) == '/') {
str = str.substring(1);
}
if (str.endsWith("/./")) {
str = str.substring(0, str.length() - 3);
}
} else {
if (str.contains(".jar;")) {
str = str.substring(0, str.indexOf(".jar"));
logger.trace("path before .jar: {}", str);
final int lastFileSepIndex = str.lastIndexOf(File.separator);
if (lastFileSepIndex >= 0) {
str = str.substring(0, lastFileSepIndex);
}
}
}
logger.trace("_RESULT PATH: {}", str);
return Path.of(str);
}
}
<file_sep>MpqInterface.CouldNotOverwriteFile=Kann Datei '%1$s' nicht überschreiben.
MpqInterface.MpqEditorNotFound=MPQEditor nicht unter '%1$s' gefunden.
MpqInterface.NoFilesExtracted=Es konnten keine Dateien aus '%1$s' extrahiert werden.
MpqInterface.CouldNotCreatePath=Ordner des Pfades '%1$s' konnten nicht erstellt werden.
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui;
/**
* Interface for Updateable classes providing a method to update.
*/
public interface Updateable {
/**
* Notifies this class that it should update.
*/
void update();
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.projects;
import interfacebuilder.SpringBootApplication;
import interfacebuilder.projects.enums.Game;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@DataJpaTest
@ContextConfiguration(classes = SpringBootApplication.class)
@TestExecutionListeners(
listeners = { MockitoTestExecutionListener.class, SpringBootDependencyInjectionTestExecutionListener.class },
mergeMode = TestExecutionListeners.MergeMode.REPLACE_DEFAULTS)
final class ProjectServiceTest {
@MockBean
private ProjectJpaRepository projectRepoMock;
@Autowired
private ProjectService projectService;
@Test
void testGetAllProjects() {
final ProjectEntity project1 =
ProjectEntity.builder().id(1).name("name1").projectPath("path1").game(Game.SC2).build();
final ProjectEntity project2 =
ProjectEntity.builder().id(2).name("name2").projectPath("path2").game(Game.HEROES).build();
when(projectRepoMock.findAll()).thenReturn(Arrays.asList(project1, project2));
final int numberOfProjects = projectService.getAllProjects().size();
assertEquals(2, numberOfProjects, "not fetching all existing projects");
}
@Test
void testSaveProject() {
final Project project = Project.builder().id(1).name("name").projectPath("path").game(Game.SC2).build();
final ProjectEntity projectEntity = ProjectEntity.fromProject(project);
when(projectRepoMock.save(projectEntity)).thenReturn(projectEntity);
final Project savedProject = projectService.saveProject(project);
assertEquals(project, savedProject, "saving altered project");
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
import com.ahli.galaxy.ui.abstracts.UIElementAbstract;
import com.ahli.galaxy.ui.interfaces.UIAnimation;
import com.ahli.galaxy.ui.interfaces.UIAttribute;
import com.ahli.galaxy.ui.interfaces.UIController;
import com.ahli.galaxy.ui.interfaces.UIElement;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author Ahli
*/
public class UIAnimationMutable extends UIElementAbstract implements UIAnimation {
private final List<UIElement> controllers;
private final List<UIAttribute> events;
private boolean nextEventsAdditionShouldOverride;
private UIAttribute driver;
public UIAnimationMutable() {
super(null);
events = new ArrayList<>(0);
controllers = new ArrayList<>(0);
}
/**
* @param name
*/
public UIAnimationMutable(final String name) {
super(name);
events = new ArrayList<>(0);
controllers = new ArrayList<>(0);
}
/**
* Constructor.
*
* @param name
* Element's name
* @param eventsCapacity
* @param controllerCapacity
*/
public UIAnimationMutable(final String name, final int eventsCapacity, final int controllerCapacity) {
super(name);
events = new ArrayList<>(eventsCapacity);
controllers = new ArrayList<>(controllerCapacity);
}
/**
* Returns a deep clone of this.
*/
@Override
public Object deepCopy() {
final UIAnimationMutable clone = new UIAnimationMutable(getName(), events.size(), controllers.size());
for (int i = 0, len = controllers.size(); i < len; ++i) {
clone.controllers.add((UIController) controllers.get(i).deepCopy());
}
for (int i = 0, len = events.size(); i < len; ++i) {
final UIAttribute p = events.get(i);
clone.events.add((UIAttribute) p.deepCopy());
}
clone.nextEventsAdditionShouldOverride = nextEventsAdditionShouldOverride;
if (driver != null) {
clone.driver = (UIAttribute) driver.deepCopy();
}
return clone;
}
/**
* @return the controllers
*/
@Override
public List<UIElement> getControllers() {
return controllers;
}
/**
* @return the events
*/
@Override
public List<UIAttribute> getEvents() {
return events;
}
/**
* @param newEvent
*/
@Override
public void addEvent(final UIAttribute newEvent) {
events.add(newEvent);
}
/**
* @return
*/
@Override
public boolean isNextEventsAdditionShouldOverride() {
return nextEventsAdditionShouldOverride;
}
/**
* @param nextEventsAdditionShouldOverride
*/
@Override
public void setNextEventsAdditionShouldOverride(final boolean nextEventsAdditionShouldOverride) {
this.nextEventsAdditionShouldOverride = nextEventsAdditionShouldOverride;
}
/**
* @return the driver
*/
@Override
public UIAttribute getDriver() {
return driver;
}
/**
* @param driver
* the driver to set
*/
@Override
public void setDriver(final UIAttribute driver) {
this.driver = driver;
}
/**
* @param path
* @return
*/
@Override
public UIElement receiveFrameFromPath(final String path) {
if (path == null || path.isEmpty()) {
// end here
return this;
} else {
// go deeper
final String curName = UIElement.getLeftPathLevel(path);
for (final UIElement curElem : controllers) {
if (curName.equalsIgnoreCase(curElem.getName())) {
// found right frame -> cut path
final String newPath = UIElement.removeLeftPathLevel(path);
return curElem.receiveFrameFromPath(newPath);
}
}
return null;
}
}
@Override
public String toString() {
return "<Animation name='" + getName() + "'>";
}
@Override
@SuppressWarnings("java:S4144")
public List<UIElement> getChildren() {
return controllers;
}
@Override
@SuppressWarnings("java:S4144")
public List<UIElement> getChildrenRaw() {
return controllers;
}
@Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof final UIAnimationMutable that)) {
return false;
}
if (!super.equals(o)) {
return false;
}
return that.canEqual(this) && nextEventsAdditionShouldOverride == that.nextEventsAdditionShouldOverride &&
Objects.equals(controllers, that.controllers) && Objects.equals(events, that.events) &&
Objects.equals(driver, that.driver);
}
@Override
public boolean canEqual(final Object other) {
return (other instanceof UIAnimationMutable);
}
@Override
public final int hashCode() {
//noinspection ObjectInstantiationInEqualsHashCode
return Objects.hash(super.hashCode(), controllers, events, nextEventsAdditionShouldOverride, driver);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.util;
/*
* Copyright Terracotta, 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 java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractMap.SimpleEntry;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Source: https://github.com/ehcache/ehcache3/blob/master/core/src/main/java/org/ehcache/core/collections/ConcurrentWeakIdentityHashMap.java
*
* @author <NAME>, modified by Ahli
*/
public class ConcurrentWeakWeakHashMap<K> implements ConcurrentMap<K, K> {
private final ConcurrentMap<WeakReferenceWithHash<K>, WeakReferenceWithHash<K>> map;
private final ReferenceQueue<K> queue = new ReferenceQueue<>();
public ConcurrentWeakWeakHashMap() {
this(8, 0.9F, 1);
}
public ConcurrentWeakWeakHashMap(final int initialCapacity, final float loadFactor, final int concurrencyLevel) {
map = new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel);
}
@Override
public K putIfAbsent(final K key, final K value) {
purgeKeys();
final var weakRef = newKey(key);
final var result = map.putIfAbsent(weakRef, weakRef);
return result == null ? null : result.get();
}
/**
* Removes GC-collected keys.
*/
public void purgeKeys() {
Reference<? extends K> reference;
while ((reference = queue.poll()) != null) {
//noinspection SuspiciousMethodCalls
map.remove(reference);
}
}
private WeakReferenceWithHash<K> newKey(final K key) {
return new WeakReferenceWithHash<>(key, queue);
}
@Override
public boolean remove(final Object key, final Object value) {
purgeKeys();
return map.remove(new WeakReferenceWithHash<>(key, null), key);
}
@Override
public boolean replace(final K key, final K oldValue, final K newValue) {
purgeKeys();
final var weakKeyRefKey = newKey(key);
// TODO I guess this is wrong, but I don't use it...
return map.replace(weakKeyRefKey, weakKeyRefKey, weakKeyRefKey);
}
@Override
public K replace(final K key, final K value) {
purgeKeys();
final var weakKeyRef = newKey(key);
final var result = map.replace(weakKeyRef, weakKeyRef);
return result == null ? null : result.get();
}
@Override
public int size() {
purgeKeys();
return map.size();
}
@Override
public boolean isEmpty() {
purgeKeys();
return map.isEmpty();
}
@Override
public boolean containsValue(final Object value) {
purgeKeys();
return map.containsValue(newKeyByObj(value));
}
private WeakReferenceWithHash<?> newKeyByObj(final Object obj) {
//noinspection rawtypes,unchecked
return new WeakReferenceWithHash(obj, queue);
}
@Override
public K get(final Object key) {
purgeKeys();
final var result = map.get(new WeakReferenceWithHash<>(key, null));
return result == null ? null : result.get();
}
@Override
public K put(final K key, final K value) {
purgeKeys();
final var keyWeakRef = newKey(key);
final var result = map.put(keyWeakRef, keyWeakRef);
return result == null ? null : result.get();
}
@Override
public K remove(final Object key) {
purgeKeys();
final var result = map.remove(new WeakReferenceWithHash<>(key, null));
return result == null ? null : result.get();
}
@Override
public void putAll(final Map<? extends K, ? extends K> m) {
purgeKeys();
for (final Entry<? extends K, ? extends K> entry : m.entrySet()) {
@SuppressWarnings("ObjectAllocationInLoop")
final var keyWeakRef = newKey(entry.getKey());
map.put(keyWeakRef, keyWeakRef);
}
}
@Override
public void clear() {
purgeKeys();
map.clear();
}
@Override
public Set<K> keySet() {
return new WeakHashMapKeySet<>(this);
}
@Override
public boolean containsKey(final Object key) {
purgeKeys();
return map.containsKey(new WeakReferenceWithHash<>(key, null));
}
@Override
public Collection<K> values() {
purgeKeys();
final var values = map.values();
final Collection<K> coll = new ArrayList<>(values.size());
for (final var value : values) {
coll.add(value.get());
}
return coll;
}
@Override
public Set<Entry<K, K>> entrySet() {
return new WeakHashMapEntrySet<>(this);
}
private static final class WeakReferenceWithHash<T> extends WeakReference<T> {
private final int hashCode;
private WeakReferenceWithHash(final T referent, final ReferenceQueue<? super T> q) {
super(referent, q);
hashCode = referent.hashCode();
}
@Override
public boolean equals(final Object obj) {
return obj != null && obj.getClass() == getClass() &&
((this == obj || super.get() == ((WeakReferenceWithHash<?>) obj).get()) ||
(hashCode == ((WeakReferenceWithHash<?>) obj).hashCode &&
Objects.equals(super.get(), ((WeakReferenceWithHash<?>) obj).get())));
}
@Override
public int hashCode() {
return hashCode;
}
}
private abstract static class WeakSafeIterator<T, U> implements Iterator<T> {
private final Iterator<U> weakIterator;
protected T strongNext;
private WeakSafeIterator(final Iterator<U> weakIterator) {
this.weakIterator = weakIterator;
advance();
}
private void advance() {
while (weakIterator.hasNext()) {
final U nextU = weakIterator.next();
if ((strongNext = extract(nextU)) != null) {
return;
}
}
strongNext = null;
}
protected abstract T extract(U u);
@Override
public boolean hasNext() {
return strongNext != null;
}
@Override
@SuppressWarnings({ "squid:S2272", "IteratorNextCanNotThrowNoSuchElementException" })
public final T next() {
final T next = strongNext;
advance();
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
}
private static final class WeakHashMapKeySet<K> extends AbstractSet<K> {
private final ConcurrentWeakWeakHashMap<K> weakHashMap;
private WeakHashMapKeySet(final ConcurrentWeakWeakHashMap<K> weakHashMap) {
this.weakHashMap = weakHashMap;
}
@Override
public Iterator<K> iterator() {
weakHashMap.purgeKeys();
return new WeakHashMapKeySetIterator<>(weakHashMap.map.keySet().iterator());
}
@Override
public boolean contains(final Object o) {
//noinspection SuspiciousMethodCalls
return weakHashMap.containsKey(o);
}
@Override
public int size() {
return weakHashMap.map.size();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final WeakHashMapKeySet<?> that = (WeakHashMapKeySet<?>) o;
return Objects.equals(weakHashMap, that.weakHashMap);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), weakHashMap);
}
}
private static final class WeakHashMapKeySetIterator<K> extends WeakSafeIterator<K, WeakReferenceWithHash<K>> {
private WeakHashMapKeySetIterator(final Iterator<WeakReferenceWithHash<K>> iterator) {
super(iterator);
}
@Override
protected K extract(final WeakReferenceWithHash<K> u) {
return u.get();
}
}
private static final class WeakHashMapEntrySet<K> extends AbstractSet<Entry<K, K>> {
private final ConcurrentWeakWeakHashMap<K> weakHashMap;
private WeakHashMapEntrySet(final ConcurrentWeakWeakHashMap<K> weakHashMap) {
this.weakHashMap = weakHashMap;
}
@Override
public Iterator<Entry<K, K>> iterator() {
weakHashMap.purgeKeys();
return new WeakHashMapEntrySetIterator<>(weakHashMap.map.entrySet().iterator());
}
@Override
public int size() {
return weakHashMap.map.size();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final WeakHashMapEntrySet<?> that = (WeakHashMapEntrySet<?>) o;
return Objects.equals(weakHashMap, that.weakHashMap);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), weakHashMap);
}
private static final class WeakHashMapEntrySetIterator<K>
extends WeakSafeIterator<Entry<K, K>, Entry<WeakReferenceWithHash<K>, WeakReferenceWithHash<K>>> {
private WeakHashMapEntrySetIterator(final Iterator<Entry<WeakReferenceWithHash<K>, WeakReferenceWithHash<K>>> weakIterator) {
super(weakIterator);
}
@Override
protected Entry<K, K> extract(final Entry<WeakReferenceWithHash<K>, WeakReferenceWithHash<K>> u) {
final K key = u.getKey().get();
if (key == null) {
return null;
} else {
return new SimpleEntry<>(key, u.getValue().get());
}
}
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.util;
public interface DeepCopyable {
/**
* Returns a deep copy of the Object.
*
* @return
*/
Object deepCopy();
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.base_ui;
import interfacebuilder.projects.enums.Game;
import interfacebuilder.threads.CleaningForkJoinTask;
import interfacebuilder.threads.CleaningForkJoinTaskCleaner;
import interfacebuilder.ui.navigation.NavigationController;
import interfacebuilder.ui.progress.ErrorTabController;
import interfacebuilder.ui.progress.appender.Appender;
import javafx.application.Platform;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
public class ExtractBaseUiTask extends CleaningForkJoinTask {
private final Game game;
private final boolean usePtr;
private final Appender[] output;
private final BaseUiService baseUiService;
private final ErrorTabController errorTabController;
private final NavigationController navigationController;
public ExtractBaseUiTask(
final CleaningForkJoinTaskCleaner cleaner,
final BaseUiService baseUiService,
final Game game,
final boolean usePtr,
final Appender[] output,
final ErrorTabController errorTabController,
final NavigationController navigationController) {
super(cleaner);
this.baseUiService = baseUiService;
this.game = game;
this.usePtr = usePtr;
this.output = output;
this.errorTabController = errorTabController;
this.navigationController = navigationController;
}
@Override
protected boolean work() {
final List<ForkJoinTask<Void>> tasks = baseUiService.createExtractionTasks(game, usePtr, output);
Platform.runLater(() -> {
final String notificationId;
if (game == Game.SC2) {
notificationId = "sc2OutOfDate";
} else if (usePtr && game == Game.HEROES) {
notificationId = "heroesPtrOutOfDate";
} else if (game == Game.HEROES) {
notificationId = "heroesOutOfDate";
} else {
return;
}
navigationController.closeNotification(notificationId);
});
for (final var task : tasks) {
task.fork();
}
for (final var task : tasks) {
task.join();
}
Platform.runLater(() -> errorTabController.setRunning(false));
return true;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui.abstracts;
import com.ahli.galaxy.ui.UIAnimationMutable;
import com.ahli.galaxy.ui.UIAttributeImmutable;
import com.ahli.galaxy.ui.UIConstantImmutable;
import com.ahli.galaxy.ui.UIControllerMutable;
import com.ahli.galaxy.ui.UIFrameMutable;
import com.ahli.galaxy.ui.UIStateGroupMutable;
import com.ahli.galaxy.ui.UIStateMutable;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.jupiter.api.Test;
class UIElementTest {
@Test
void equalsContract() {
EqualsVerifier.forClass(UIElementAbstract.class)
.withRedefinedSubclass(UIFrameMutable.class)
.withRedefinedSubclass(UIStateGroupMutable.class)
.withRedefinedSubclass(UIStateMutable.class)
.withRedefinedSubclass(UIAttributeImmutable.class)
.withRedefinedSubclass(UIAnimationMutable.class)
.withRedefinedSubclass(UIConstantImmutable.class)
.withRedefinedSubclass(UIControllerMutable.class)
.withIgnoredFields("hash", "hashIsZero", "hashIsDirty")
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.mpq.mpqeditor;
import java.util.Arrays;
import java.util.Objects;
public class MpqEditorCompressionRuleMask extends MpqEditorCompressionRule {
private String mask;
public MpqEditorCompressionRuleMask(final String mask) {
this.mask = mask;
}
/**
* Copy Constructor
*
* @param original
*/
public MpqEditorCompressionRuleMask(final MpqEditorCompressionRuleMask original) {
super(original);
mask = original.mask;
}
@Override
public String toString() {
return "Mask:" + getMask() + "=" + getAttributeString() + ", " + getCompressionMethodString() + ", 0xFFFFFFFF";
}
public String getMask() {
return mask;
}
/**
* Sets the mask to match file names. Use '*' as a wildcard.
*
* @param mask
*/
public void setMask(final String mask) {
this.mask = mask;
}
@Override
public Object deepCopy() {
return new MpqEditorCompressionRuleMask(this);
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
if (obj == this) {
return true;
}
final Object[] signatureFields = getSignatureFields();
final Object[] thatSignatureFields = ((MpqEditorCompressionRuleMask) obj).getSignatureFields();
for (int i = 0; i < signatureFields.length; ++i) {
if (!(signatureFields[i] instanceof Object[])) {
if (!Objects.equals(signatureFields[i], thatSignatureFields[i])) {
return false;
}
} else {
if (!Arrays.deepEquals((Object[]) signatureFields[i], (Object[]) thatSignatureFields[i])) {
return false;
}
}
}
return true;
}
private Object[] getSignatureFields() {
return new Object[] { mask, getCompressionMethod(), getAttributeString() };
}
@Override
public int hashCode() {
return Objects.hash(getSignatureFields());
}
}
<file_sep>MpqInterface.CouldNotOverwriteFile=无法覆盖文件 '%1$s'.
MpqInterface.MpqEditorNotFound=无法在以下文件夹中找到MPQEditor: %1$s.
MpqInterface.NoFilesExtracted=没有文件从下列包中解压出来 '%1$s'.
MpqInterface.CouldNotCreatePath=Could not create directories for path '%1$s'.
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.compress;
import com.ahli.galaxy.ModData;
import com.ahli.galaxy.game.GameData;
import com.ahli.galaxy.game.GameDef;
import interfacebuilder.config.ConfigService;
import interfacebuilder.integration.SettingsIniInterface;
import interfacebuilder.projects.enums.Game;
public class GameService {
private final ConfigService configService;
public GameService(final ConfigService configService) {
this.configService = configService;
}
/**
* Returns a ModData instance containing the specified game definition.
*
* @param game
* @return
*/
public ModData getModData(final Game game) {
return new ModData(new GameData(getGameDef(game)));
}
/**
* Returns a GameDef instance containing the specified game definition.
*
* @param game
* @return
*/
public GameDef getGameDef(final Game game) {
return switch (game) {
case SC2 -> GameDef.buildSc2GameDef();
case HEROES -> GameDef.buildHeroesGameDef();
};
}
/**
* Returns the path of the image that reflects the specified game.
*
* @param game
* @return
*/
public String getGameItemPath(final Game game) {
return switch (game) {
case SC2 -> "classpath:res/sc2.png";
case HEROES -> "classpath:res/heroes.png";
};
}
/**
* Returns the Game Directory of a specified game Def.
*
* @param gameDef
* @param isPtr
* @return Path to the game's directory
*/
public String getGameDirPath(final GameDef gameDef, final boolean isPtr) {
final SettingsIniInterface iniSettings = configService.getIniSettings();
if (GameDef.isSc2(gameDef)) {
return iniSettings.getSc2Path();
}
if (GameDef.isHeroes(gameDef)) {
return isPtr ? iniSettings.getHeroesPtrPath() : iniSettings.getHeroesPath();
}
return null;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.mpq.mpqeditor;
import java.util.Arrays;
import java.util.Objects;
public class MpqEditorCompressionRuleSize extends MpqEditorCompressionRule {
private int minSize;
private int maxSize;
public MpqEditorCompressionRuleSize(final int minSize, final int maxSize) {
this.minSize = minSize;
this.maxSize = maxSize;
}
/**
* Copy Constructor
*
* @param original
*/
public MpqEditorCompressionRuleSize(final MpqEditorCompressionRuleSize original) {
super(original);
minSize = original.minSize;
maxSize = original.maxSize;
}
@Override
public boolean isValidRule() {
return super.isValidRule() && minSize >= 0 && maxSize >= minSize;
}
@Override
public String toString() {
return "Size:" + minSize + "-" + maxSize + "=" + getAttributeString() + ", " + getCompressionMethodString() +
", 0xFFFFFFFF";
}
public int getMinSize() {
return minSize;
}
/**
* Sets the minimum file size for this rule. Must be greater or equal zero.
*
* @param minSize
*/
public void setMinSize(final int minSize) {
this.minSize = minSize;
}
public int getMaxSize() {
return maxSize;
}
/**
* Sets the maximum file size for this rule. Must be greater or equal to minSize (and zero).
*
* @param maxSize
*/
public void setMaxSize(final int maxSize) {
this.maxSize = maxSize;
}
@Override
public Object deepCopy() {
return new MpqEditorCompressionRuleSize(this);
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
if (obj == this) {
return true;
}
final Object[] signatureFields = getSignatureFields();
final Object[] thatSignatureFields = ((MpqEditorCompressionRuleSize) obj).getSignatureFields();
for (int i = 0; i < signatureFields.length; ++i) {
if (!(signatureFields[i] instanceof Object[])) {
if (!Objects.equals(signatureFields[i], thatSignatureFields[i])) {
return false;
}
} else {
if (!Arrays.deepEquals((Object[]) signatureFields[i], (Object[]) thatSignatureFields[i])) {
return false;
}
}
}
return true;
}
private Object[] getSignatureFields() {
return new Object[] { maxSize, minSize, getCompressionMethod(), getAttributeString() };
}
@Override
public int hashCode() {
return Objects.hash(getSignatureFields());
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.compress;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Converter that is automatically loaded by Hibernate without any references.
*/
@Converter
public class StringArrayToListConverter implements AttributeConverter<String[], List<String>> {
@Override
public List<String> convertToDatabaseColumn(final String[] attribute) {
if (attribute == null || attribute.length <= 0) {
return new ArrayList<>(10);
}
return Arrays.asList(attribute);
}
@Override
public String[] convertToEntityAttribute(final List<String> dbData) {
if (dbData == null || dbData.isEmpty()) {
//noinspection ZeroLengthArrayAllocation
return new String[0];
}
return dbData.toArray(new String[dbData.size()]);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.integration.kryo.serializer;
import com.ahli.util.StringInterner;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers;
public class KryoInternStringArraySerializer extends DefaultArraySerializers.StringArraySerializer {
@Override
public String[] read(final Kryo kryo, final Input input, final Class type) {
final String[] array = super.read(kryo, input, type);
for (int i = array.length - 1; i >= 0; --i) {
if (array[i] != null) {
array[i] = StringInterner.intern(array[i]);
}
}
return array;
}
}<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
/**
* Sides of an Anchor.
*
* @author Ahli
*/
public enum UIAnchorSide {TOP, LEFT, BOTTOM, RIGHT}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
import com.ahli.galaxy.ui.abstracts.UIElementAbstract;
import com.ahli.galaxy.ui.interfaces.UIAttribute;
import com.ahli.galaxy.ui.interfaces.UIElement;
import com.ahli.galaxy.ui.interfaces.UIState;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* @author Ahli
*/
public class UIStateMutable extends UIElementAbstract implements UIState {
private List<UIAttribute> whens;
private List<UIAttribute> actions;
private boolean nextAdditionShouldOverrideWhens;
private boolean nextAdditionShouldOverrideActions;
public UIStateMutable() {
super(null);
whens = new ArrayList<>(0);
actions = new ArrayList<>(0);
}
/**
* @param name
*/
public UIStateMutable(final String name) {
super(name);
whens = new ArrayList<>(0);
actions = new ArrayList<>(0);
}
/**
* @param name
* @param whensCapacity
* @param actionsCapacity
*/
public UIStateMutable(final String name, final int whensCapacity, final int actionsCapacity) {
super(name);
whens = new ArrayList<>(whensCapacity);
actions = new ArrayList<>(actionsCapacity);
}
/**
* Returns a deep clone of this.
*/
@Override
public Object deepCopy() {
final UIStateMutable clone = new UIStateMutable(getName(), whens.size(), actions.size());
final List<UIAttribute> whensClone = clone.whens;
for (final UIAttribute when : whens) {
whensClone.add((UIAttribute) when.deepCopy());
}
final List<UIAttribute> actionsClone = clone.actions;
for (final UIAttribute action : actions) {
actionsClone.add((UIAttribute) action.deepCopy());
}
clone.nextAdditionShouldOverrideActions = nextAdditionShouldOverrideActions;
clone.nextAdditionShouldOverrideWhens = nextAdditionShouldOverrideWhens;
return clone;
}
/**
* @return the whens
*/
@Override
public List<UIAttribute> getWhens() {
return whens;
}
/**
* @param whens
* the whens to set
*/
@Override
public void setWhens(final List<UIAttribute> whens) {
this.whens = whens;
}
/**
* @return the actions
*/
@Override
public List<UIAttribute> getActions() {
return actions;
}
/**
* @param actions
* the actions to set
*/
@Override
public void setActions(final List<UIAttribute> actions) {
this.actions = actions;
}
/**
* @return the nextAdditionShouldOverrideWhens
*/
@Override
public boolean isNextAdditionShouldOverrideWhens() {
return nextAdditionShouldOverrideWhens;
}
/**
* @param nextAdditionShouldOverrideWhens
* the nextAdditionShouldOverrideWhens to set
*/
@Override
public void setNextAdditionShouldOverrideWhens(final boolean nextAdditionShouldOverrideWhens) {
this.nextAdditionShouldOverrideWhens = nextAdditionShouldOverrideWhens;
}
/**
* @return the nextAdditionShouldOverrideActions
*/
@Override
public boolean isNextAdditionShouldOverrideActions() {
return nextAdditionShouldOverrideActions;
}
/**
* @param nextAdditionShouldOverrideActions
* the nextAdditionShouldOverrideActions to set
*/
@Override
public void setNextAdditionShouldOverrideActions(final boolean nextAdditionShouldOverrideActions) {
this.nextAdditionShouldOverrideActions = nextAdditionShouldOverrideActions;
}
/**
* @param path
* @return
*/
@Override
public UIElement receiveFrameFromPath(final String path) {
return (path == null || path.isEmpty()) ? this : null;
}
@Override
public String toString() {
return "<State name='" + getName() + "'>";
}
@Override
public List<UIElement> getChildren() {
return Collections.emptyList();
}
@Override
@SuppressWarnings("java:S1168")
public List<UIElement> getChildrenRaw() {
return null; // returning null is desired here
}
@Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof final UIStateMutable uiState)) {
return false;
}
if (!super.equals(o)) {
return false;
}
return uiState.canEqual(this) && nextAdditionShouldOverrideWhens == uiState.nextAdditionShouldOverrideWhens &&
nextAdditionShouldOverrideActions == uiState.nextAdditionShouldOverrideActions &&
Objects.equals(whens, uiState.whens) && Objects.equals(actions, uiState.actions);
}
@Override
public boolean canEqual(final Object other) {
return (other instanceof UIStateMutable);
}
@Override
public final int hashCode() {
//noinspection ObjectInstantiationInEqualsHashCode
return Objects.hash(super.hashCode(),
whens,
actions,
nextAdditionShouldOverrideWhens,
nextAdditionShouldOverrideActions);
}
}
<file_sep><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.ahli</groupId>
<artifactId>observer-ui-settings-editor</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Observer UI Settings Editor</name>
<!-- goal to execute to check for plugins and dependency updates:
versions:display-plugin-updates versions:display-parent-updates versions:display-dependency-updates versions:display-property-updates
-->
<!-- QUICK SETTINGS -->
<properties>
<java.version>16</java.version>
<jarName>Observer UI Settings Editor App</jarName>
<executableJavaClass>com.ahli.hotkey_ui.application.Main</executableJavaClass>
<jarTargetPath>../../release/Observer UI Settings Editor</jarTargetPath>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<moduleName>ObserverUiSettingsEditor</moduleName>
<javafx.version>18-ea+1</javafx.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<log4j2.version>2.14.1</log4j2.version>
<commons-io.version>2.11.0</commons-io.version>
<commons-configuration2.version>2.7</commons-configuration2.version>
<commons-text.version>1.9</commons-text.version>
<commons-logging.version>1.2</commons-logging.version>
<lmax-disruptor.version>3.4.4</lmax-disruptor.version>
<commons-collection.version>3.2.2</commons-collection.version>
<commons-beanutils.version>1.9.4</commons-beanutils.version>
<vtd-xml.version>2.13.4</vtd-xml.version>
<asm.version>9.2</asm.version>
<eclipse-collection.version>10.4.0</eclipse-collection.version>
<slf4j.version>1.8.0-beta4</slf4j.version>
</properties>
<build>
<!-- name of the generated jar -->
<!--<finalName>${jarName}</finalName>-->
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<!-- copy res folder to res folder in jar -->
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<!-- Force requirement of Maven version 3.0+ -->
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-enforcer-plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>[3.1.1,)</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<release>${java.version}</release>
<excludes>
<!-- excludes files from being put into same path as classes -->
<exclude>**/*.txt</exclude>
</excludes>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
<!--<compilerArgs>--enable-preview</compilerArgs>-->
<compilerArgs>
<compilerArg>-Xlint:all</compilerArg>
</compilerArgs>
</configuration>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-jar-plugin -->
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<!-- create executable jar -->
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${executableJavaClass}</mainClass>
</manifest>
</archive>
<!-- for moditect -->
<outputDirectory>
${project.build.directory}/modules
</outputDirectory>
</configuration>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-site-plugin -->
<artifactId>maven-site-plugin</artifactId>
<version>3.9.1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-deploy-plugin -->
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-install-plugin -->
<artifactId>maven-install-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-antrun-plugin -->
<artifactId>maven-antrun-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-release-plugin -->
<artifactId>maven-release-plugin</artifactId>
<version>3.0.0-M4</version>
</plugin>
<!-- https://mvnrepository.com/artifact/org.codehaus.mojo/versions-maven-plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.8.1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<!--<argLine>--enable-preview</argLine>-->
</configuration>
<dependencies>
<dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin -->
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-clean-plugin -->
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>6.2.2</version>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<failOnError>false</failOnError>
<assemblyAnalyzerEnabled>false</assemblyAnalyzerEnabled>
</configuration>
</plugin>
<plugin>
<groupId>org.moditect</groupId>
<artifactId>moditect-maven-plugin</artifactId>
<version>1.0.0.RC1</version>
<dependencies>
<dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>add-module-infos</id>
<phase>generate-resources</phase>
<goals>
<goal>add-module-info</goal>
</goals>
<configuration>
<overwriteExistingFiles>true</overwriteExistingFiles>
<outputDirectory>${project.build.directory}/modules</outputDirectory>
<modules>
<module>
<artifact>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.io {
exports org.apache.commons.io;
exports org.apache.commons.io.filefilter;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.text {
exports org.apache.commons.text;
exports org.apache.commons.text.lookup;
requires org.apache.commons.lang3;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</artifact>
<moduleInfoSource>
module javafx.controlsEmpty {
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${lmax-disruptor.version}</version>
</artifact>
<moduleInfoSource>
module com.lmax.disruptor {
exports com.lmax.disruptor;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.logging {
exports org.apache.commons.logging;
exports org.apache.commons.logging.impl;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</artifact>
<!-- opens might not be needed -->
<moduleInfoSource>
module org.apache.logging.log4j.core {
requires org.apache.logging.log4j;
exports org.apache.logging.log4j.core;
opens org.apache.logging.log4j.core;
exports org.apache.logging.log4j.core.util;
opens org.apache.logging.log4j.core.util;
exports org.apache.logging.log4j.core.util.datetime;
opens org.apache.logging.log4j.core.util.datetime;
exports org.apache.logging.log4j.core.tools;
opens org.apache.logging.log4j.core.tools;
exports org.apache.logging.log4j.core.tools.picocli;
opens org.apache.logging.log4j.core.tools.picocli;
exports org.apache.logging.log4j.core.time;
opens org.apache.logging.log4j.core.time;
exports org.apache.logging.log4j.core.time.internal;
opens org.apache.logging.log4j.core.time.internal;
exports org.apache.logging.log4j.core.selector;
opens org.apache.logging.log4j.core.selector;
exports org.apache.logging.log4j.core.script;
opens org.apache.logging.log4j.core.script;
exports org.apache.logging.log4j.core.pattern;
opens org.apache.logging.log4j.core.pattern;
exports org.apache.logging.log4j.core.parser;
opens org.apache.logging.log4j.core.parser;
exports org.apache.logging.log4j.core.osgi;
opens org.apache.logging.log4j.core.osgi;
exports org.apache.logging.log4j.core.net;
opens org.apache.logging.log4j.core.net;
exports org.apache.logging.log4j.core.net.ssl;
opens org.apache.logging.log4j.core.net.ssl;
exports org.apache.logging.log4j.core.message;
opens org.apache.logging.log4j.core.message;
exports org.apache.logging.log4j.core.lookup;
opens org.apache.logging.log4j.core.lookup;
exports org.apache.logging.log4j.core.layout;
opens org.apache.logging.log4j.core.layout;
exports org.apache.logging.log4j.core.layout.internal;
opens org.apache.logging.log4j.core.layout.internal;
exports org.apache.logging.log4j.core.jmx;
opens org.apache.logging.log4j.core.jmx;
exports org.apache.logging.log4j.core.impl;
opens org.apache.logging.log4j.core.impl;
exports org.apache.logging.log4j.core.jackson;
opens org.apache.logging.log4j.core.jackson;
exports org.apache.logging.log4j.core.filter;
opens org.apache.logging.log4j.core.filter;
exports org.apache.logging.log4j.core.config;
opens org.apache.logging.log4j.core.config;
//exports org.apache.logging.log4j.core.config.builder;
//opens org.apache.logging.log4j.core.config.builder;
//exports org.apache.logging.log4j.core.config.builder.api;
//opens org.apache.logging.log4j.core.config.builder.api;
//exports org.apache.logging.log4j.core.config.builder.impl;
//opens org.apache.logging.log4j.core.config.builder.impl;
exports org.apache.logging.log4j.core.config.composite;
opens org.apache.logging.log4j.core.config.composite;
exports org.apache.logging.log4j.core.config.json;
opens org.apache.logging.log4j.core.config.json;
exports org.apache.logging.log4j.core.config.plugins;
opens org.apache.logging.log4j.core.config.plugins;
exports org.apache.logging.log4j.core.config.plugins.convert;
opens org.apache.logging.log4j.core.config.plugins.convert;
exports org.apache.logging.log4j.core.config.plugins.processor;
opens org.apache.logging.log4j.core.config.plugins.processor;
exports org.apache.logging.log4j.core.config.plugins.util;
opens org.apache.logging.log4j.core.config.plugins.util;
exports org.apache.logging.log4j.core.config.plugins.validation;
opens org.apache.logging.log4j.core.config.plugins.validation;
exports org.apache.logging.log4j.core.config.plugins.validation.constraints;
opens org.apache.logging.log4j.core.config.plugins.validation.constraints;
exports org.apache.logging.log4j.core.config.plugins.validation.validators;
opens org.apache.logging.log4j.core.config.plugins.validation.validators;
//exports org.apache.logging.log4j.core.config.plugins.validation.visitors;
//opens org.apache.logging.log4j.core.config.plugins.validation.visitors;
exports org.apache.logging.log4j.core.async;
opens org.apache.logging.log4j.core.async;
exports org.apache.logging.log4j.core.appender;
opens org.apache.logging.log4j.core.appender;
exports org.apache.logging.log4j.core.appender.db;
opens org.apache.logging.log4j.core.appender.db;
exports org.apache.logging.log4j.core.appender.db.jdbc;
opens org.apache.logging.log4j.core.appender.db.jdbc;
exports org.apache.logging.log4j.core.appender.mom;
opens org.apache.logging.log4j.core.appender.mom;
exports org.apache.logging.log4j.core.appender.mom.jeromq;
opens org.apache.logging.log4j.core.appender.mom.jeromq;
exports org.apache.logging.log4j.core.appender.mom.kafka;
opens org.apache.logging.log4j.core.appender.mom.kafka;
exports org.apache.logging.log4j.core.appender.nosql;
opens org.apache.logging.log4j.core.appender.nosql;
exports org.apache.logging.log4j.core.appender.rewrite;
opens org.apache.logging.log4j.core.appender.rewrite;
exports org.apache.logging.log4j.core.appender.rolling;
opens org.apache.logging.log4j.core.appender.rolling;
exports org.apache.logging.log4j.core.appender.rolling.action;
opens org.apache.logging.log4j.core.appender.rolling.action;
exports org.apache.logging.log4j.core.appender.routing;
opens org.apache.logging.log4j.core.appender.routing;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.lang3 {
exports org.apache.commons.lang3;
exports org.apache.commons.lang3.builder;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>${commons-configuration2.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.configuration2 {
exports org.apache.commons.configuration2;
exports org.apache.commons.configuration2.ex;
exports org.apache.commons.configuration2.builder.fluent;
requires org.apache.commons.logging;
requires org.apache.commons.beanutils;
requires org.apache.commons.text;
exports org.apache.commons.configuration2.builder;
requires org.apache.commons.lang3;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>com.ximpleware</groupId>
<artifactId>vtd-xml</artifactId>
<version>${vtd-xml.version}</version>
</artifact>
<moduleInfoSource>
module vtd.xml {
exports com.ximpleware;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>${javafx.version}</version>
</artifact>
<moduleInfoSource>
module javafx.graphicsEmpty {
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>${javafx.version}</version>
</artifact>
<moduleInfoSource>
module javafx.mediaEmpty {
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>${javafx.version}</version>
</artifact>
<moduleInfoSource>
module javafx.mediaEmpty {
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>${javafx.version}</version>
</artifact>
<moduleInfoSource>
module javafx.fxmlEmpty {
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>${javafx.version}</version>
</artifact>
<moduleInfoSource>
module javafx.baseEmpty {
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.beanutils {
exports org.apache.commons.beanutils;
requires java.desktop;
requires org.apache.commons.logging;
requires java.sql;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons-collection.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.commons.collections {
exports org.apache.commons.collections;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collection.version}</version>
</artifact>
<moduleInfoSource>
module org.eclipse.collections.impl {
exports org.eclipse.collections.impl.tuple;
requires org.eclipse.collections.api;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections-api</artifactId>
<version>${eclipse-collection.version}</version>
</artifact>
<moduleInfoSource>
module org.eclipse.collections.api {
exports org.eclipse.collections.api.tuple;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</artifact>
<moduleInfoSource>
module org.slf4j {
exports org.slf4j;
opens org.slf4j;
exports org.slf4j.spi;
opens org.slf4j.spi;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.logging.log4j {
exports org.apache.logging.log4j;
opens org.apache.logging.log4j;
exports org.apache.logging.log4j.internal;
opens org.apache.logging.log4j.internal;
exports org.apache.logging.log4j.message;
opens org.apache.logging.log4j.message;
exports org.apache.logging.log4j.simple;
opens org.apache.logging.log4j.simple;
exports org.apache.logging.log4j.spi;
opens org.apache.logging.log4j.spi;
exports org.apache.logging.log4j.status;
opens org.apache.logging.log4j.status;
exports org.apache.logging.log4j.util;
opens org.apache.logging.log4j.util;
}
</moduleInfoSource>
</module>
<module>
<artifact>
<groupId>org.apache.logging.log4j</groupId>
<!-- <artifactId>log4j-slf4j-impl</artifactId>--><!-- for version 1.7.x -->
<artifactId>log4j-slf4j18-impl</artifactId><!-- for 1.8.x+ -->
<version>${log4j2.version}</version>
</artifact>
<moduleInfoSource>
module org.apache.logging.log4j.slf4j {
requires org.slf4j;
requires org.apache.logging.log4j;
exports org.apache.logging.slf4j;
opens org.apache.logging.slf4j;
}
</moduleInfoSource>
</module>
</modules>
</configuration>
</execution>
<execution>
<id>create-runtime-image</id>
<phase>package</phase>
<goals>
<goal>create-runtime-image</goal>
</goals>
<configuration>
<modulePath>
<path>${project.build.directory}/modules</path>
</modulePath>
<modules>
<module>${moduleName}</module>
</modules>
<!-- references toolchains.xml in ".m2" directory of the user -->
<baseJdk>version=16,vendor=openjdk</baseJdk>
<outputDirectory>
${project.build.directory}/jlink-image
</outputDirectory>
<stripDebug>true</stripDebug>
<compression>2</compression>
<ignoreSigningInformation>true</ignoreSigningInformation>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/modules</outputDirectory>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- file IO stuff -->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- log4j2 -->
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!-- used in async logging -->
<!-- https://mvnrepository.com/artifact/com.lmax/disruptor -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${lmax-disruptor.version}</version>
</dependency>
<!-- library's slf4j support for log4j2 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j18-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!-- to get stack trace as String -->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- dependency to GalaxyLib -->
<dependency>
<groupId>io.github.ahli</groupId>
<artifactId>galaxy-lib</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!-- JavaFX -->
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-graphics -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-base -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-fxml -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-media -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>${javafx.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- update dependency within configuration2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project><file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include <iostream>
#include <filesystem>
#include <atlbase.h>
#include "CascLib.h"
static bool ExtractFile(HANDLE hStorage, const CASC_FIND_DATA& findData, const char* targetDirPath, const char* targetFilePath);
static int CleanUp(int exitCode, HANDLE hStorage, HANDLE hFind) noexcept;
static bool CleanUpStorage(HANDLE hStorage) noexcept;
static bool CleanUpFind(HANDLE hFind) noexcept;
static FILE* OpenExtractedFile(const char* filePath);
/// <summary>
///
/// </summary>
/// <param name="argc"></param>
/// <param name="argv"></param>
/// <returns></returns>
int main(const int argc, const char* const argv[])
{
try {
LPCTSTR path = nullptr;
LPCSTR mask = nullptr;
LPCSTR targetPath = nullptr;
#ifndef _DEBUG
if (argc != 4) {
std::cout << "ERROR: Please provide 3 arguments: CascExtractor.exe [\"Path\\to\\the\\CASC storage\"] [\"*mask.txt\"] [\"Path\\to\\the\\output Directory\"]." << std::endl;
return EXIT_FAILURE;
}
std::string str = argv[1];
std::replace(str.begin(), str.end(), '/', '\\');
path = CA2CT(str.c_str());
mask = argv[2];
str = argv[3];
std::replace(str.begin(), str.end(), '/', '\\');
targetPath = str.c_str();
#else
path = L"C:\\Spiele\\StarCraft II\\";
mask = "*.sc2style";
targetPath = "Debug\\out";
#endif
std::wcout << "casc path: " << path << std::endl;
std::cout << "mask: " << mask << std::endl;
std::cout << "target path: " << targetPath << std::endl;
std::wcout << "Opening CASC Storage: " << path << std::endl;
HANDLE hStorage;
if (!CascOpenStorage(path, 0, &hStorage)) {
std::cerr << "ERROR: opening storage: " << GetCascError() << std::endl;
return EXIT_FAILURE;
}
std::cout << "Finding files with mask: " << mask << std::endl;
const LPCTSTR listFile = NULL;
CASC_FIND_DATA findData = {};
const PCASC_FIND_DATA pFindData = &findData;
HANDLE hFind = CascFindFirstFile(hStorage, mask, pFindData, listFile);
if (hFind == INVALID_HANDLE_VALUE) {
if (GetCascError() == ERROR_SUCCESS) {
std::cout << "Found 0 files for mask: " << mask << std::endl;
CascFindClose(hFind);
CleanUpStorage(hStorage);
return EXIT_SUCCESS;
}
else {
std::cerr << "ERROR: Unknown error, mask: " << mask << std::endl;
CascFindClose(hFind);
CleanUpStorage(hStorage);
return EXIT_FAILURE;
}
}
int results = 0;
do {
std::cout << pFindData->szFileName << std::endl;
std::string targetFilePath = std::string(targetPath).append("\\").append(pFindData->szFileName);
// get the path from file
std::string targetDirPath;
const std::size_t pos = targetFilePath.find_last_of('\\');
if (pos != std::string::npos) {
targetDirPath = targetFilePath.substr(0, pos);
if (ExtractFile(hStorage, *pFindData, targetDirPath.c_str(), targetFilePath.c_str()) == ERROR_SUCCESS) {
++results;
}
}
else {
std::cerr << " ERROR: Unexpected file path: " << targetFilePath << std::endl;
}
} while (CascFindNextFile(hFind, pFindData));
std::cout << "Extracted " << results << " file" << (results == 1 ? "" : "s") << " for mask: " << mask << std::endl;
// clean up
const bool findFailed = (GetCascError() != ERROR_NO_MORE_FILES && GetCascError() != ERROR_SUCCESS);
const int exitCode = findFailed ? EXIT_FAILURE : EXIT_SUCCESS;
return CleanUp(exitCode, hStorage, hFind);
}
catch (const std::exception& e) {
std::cout << "ERROR: " << e.what() << std::endl;
}
catch (...) {
std::cout << "ERROR: An unknown fatal error occurred." << std::endl;
}
return 0;
}
/// <summary>
/// Cleans up the Storage and the Find. Returns the specified EXIT_code.
/// </summary>
/// <param name="exitCode">EXIT_code when cleaning up was successful</param>
/// <param name="hStorage">HANDLE of the Storage</param>
/// <param name="hFind">HANDLE of the Find</param>
/// <returns>EXIT_FAILURE code when cleaning up encountered a problem. Else the specified exitCode is returned.</returns>
static int CleanUp(int exitCode, HANDLE hStorage, HANDLE hFind) noexcept {
bool result = CleanUpFind(hFind);
result = CleanUpStorage(hStorage) || result;
return !result ? EXIT_FAILURE : exitCode;
}
/// <summary>
///
/// </summary>
/// <param name="hStorage">HANDLE of the Storage</param>
static bool CleanUpStorage(HANDLE hStorage) noexcept {
if (hStorage) {
return CascCloseStorage(hStorage);
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="hFind">HANDLE of the Find</param>
static bool CleanUpFind(HANDLE hFind) noexcept {
if (hFind) {
return CascFindClose(hFind);
}
return true;
}
// -----------------------------------------------
// BASED ON THE CODE FROM CASCLIB's TEST PROJECT
// -----------------------------------------------
template <typename T> T* CASC_ALLOC(size_t nCount) noexcept
{
return static_cast<T*>(malloc(nCount * sizeof(T)));
}
template <typename T> void CASC_FREE(T*& ptr) noexcept
{
free(ptr);
ptr = nullptr;
}
// Retrieves the pointer to plain name
template <typename XCHAR> const XCHAR* GetPlainFileName(const XCHAR* szFileName)
{
const XCHAR* szPlainName = szFileName;
while (*szFileName != 0)
{
if (*szFileName == '\\' || *szFileName == '/')
szPlainName = szFileName + 1;
szFileName++;
}
return szPlainName;
}
static PCASC_FILE_SPAN_INFO GetFileInfo(HANDLE hFile, CASC_FILE_FULL_INFO& FileInfo) noexcept
{
PCASC_FILE_SPAN_INFO pSpans = nullptr;
// Retrieve the full file info
if (CascGetFileInfo(hFile, CascFileFullInfo, &FileInfo, sizeof(CASC_FILE_FULL_INFO), nullptr))
{
if ((pSpans = CASC_ALLOC<CASC_FILE_SPAN_INFO>(FileInfo.SpanCount)) != nullptr)
{
if (!CascGetFileInfo(hFile, CascFileSpanInfo, pSpans, FileInfo.SpanCount * sizeof(CASC_FILE_SPAN_INFO), nullptr))
{
CASC_FREE(pSpans);
pSpans = nullptr;
}
}
}
return pSpans;
}
static bool ExtractFile(HANDLE hStorage, const CASC_FIND_DATA& findData, const char* targetDirPath, const char* targetFilePath) {
namespace fs = std::filesystem;
PCASC_FILE_SPAN_INFO pSpans = nullptr;
CASC_FILE_FULL_INFO fileInfo{};
LPCSTR szOpenName = findData.szFileName;
DWORD dwErrCode = ERROR_SUCCESS;
HANDLE hFile = NULL;
if (CascOpenFile(hStorage, szOpenName, NULL /*dwLocaleFlags*/, CASC_STRICT_DATA_CHECK, &hFile))
{
// Retrieve the information about file spans.
if ((pSpans = GetFileInfo(hFile, fileInfo)) != nullptr && fileInfo.ContentSize > 0)
{
DWORD dwBytesRead = 0;
ULONGLONG totalWritten = 0;
FILE* pOutFile = nullptr;
// Load the entire file, one read request per span.
// Using span-aligned reads will cause CascReadFile not to do any caching,
// and the amount of memcpys will be almost zero
for (DWORD i = 0; i < fileInfo.SpanCount && dwErrCode == ERROR_SUCCESS; i++)
{
const PCASC_FILE_SPAN_INFO pFileSpan = pSpans + i;
LPBYTE pbFileSpan = nullptr;
const DWORD cbFileSpan = static_cast<DWORD>(pFileSpan->EndOffset - pFileSpan->StartOffset);
// Do not read empty spans.
if (cbFileSpan == 0)
continue;
// Allocate span buffer
pbFileSpan = CASC_ALLOC<BYTE>(cbFileSpan);
if (pbFileSpan == NULL)
{
std::cerr << " ERROR: Not enough memory to allocate " << cbFileSpan << " bytes" << std::endl;
dwErrCode = ERROR_NOT_ENOUGH_MEMORY;
break;
}
// CascReadFile will read as much as possible. If there is a frame error
// (e.g. MD5 mismatch, missing encryption key or disc error),
// CascReadFile only returns frames that are loaded entirely.
if (!CascReadFile(hFile, pbFileSpan, cbFileSpan, &dwBytesRead))
{
// Do not report some errors; for example, when the file is encrypted,
// we can't do much about it. Only report it if we are going to extract one file
switch (dwErrCode = GetCascError())
{
case ERROR_SUCCESS: {
} break;
case ERROR_FILE_ENCRYPTED: {
std::cout << " WARNING: File is encrypted: " << szOpenName << std::endl;
} break;
default: {
std::cout << " WARNING: Could not read file: " << szOpenName << std::endl;
}break;
}
}
if (dwBytesRead > 0) {
// prepare file stream
if (!pOutFile) {
if (fs::exists(targetDirPath) || fs::create_directories(targetDirPath)) {
// create filestream and empty file
if ((pOutFile = OpenExtractedFile(targetFilePath)) == nullptr) {
std::cerr << " ERROR: Could not create file: " << targetFilePath << std::endl;
}
}
else {
std::cerr << " ERROR: Could not create directories: " << targetDirPath << std::endl;
}
}
// write span's content to the file
if (pOutFile) {
//std::cout << " bytes read: " << dwBytesRead << std::endl;
fwrite(pbFileSpan, 1, dwBytesRead, pOutFile);
}
totalWritten += dwBytesRead;
}
// Free the memory occupied by the file span
CASC_FREE(pbFileSpan);
}
if (pOutFile) {
fclose(pOutFile);
}
// Check whether the total size matches
if (dwErrCode == ERROR_SUCCESS && totalWritten != fileInfo.ContentSize)
{
std::cerr << " WARNING: exported file is corrupted: " << szOpenName << std::endl;
dwErrCode = ERROR_FILE_CORRUPT;
}
//std::cout << "totalWritten: " << totalWritten << std::endl;
}
else if (dwErrCode == ERROR_SUCCESS) {
std::cerr << " WARNING: file had no content: " << szOpenName << std::endl;
dwErrCode = ERROR_NO_DATA;
}
// Free the span array
if (pSpans) {
CASC_FREE(pSpans);
}
// Close the handle
CascCloseFile(hFile);
}
else
{
std::cout << " WARNING: could not open file: " << szOpenName << std::endl;
dwErrCode = GetCascError();
}
//std::cout << " returning error code: " << dwErrCode << std::endl;
return dwErrCode;
}
// this is pretty much a new function
static FILE* OpenExtractedFile(const char* filePath)
{
FILE* pFile;
errno_t err;
//std::cout << "outFile: " << filePath << std::endl;
if ((err = fopen_s(&pFile, filePath, "wb")) != 0) {
char buf[1024];
strerror_s(buf, sizeof buf, err);
std::cout << "ERROR: could not write file: " << filePath << ". Reason: " << buf << std::endl;
return nullptr;
}
return pFile;
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui;
import javafx.fxml.FXMLLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceResourceBundle;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Objects;
/**
* A FXMLLoader with its ControllerFactory set to be the ApplicationContext's Bean. Controllers are required to be jpa
* now.
*/
public class FXMLSpringLoader extends FXMLLoader implements ApplicationContextAware {
private ApplicationContext context;
public FXMLSpringLoader(final ApplicationContext applicationContext) {
setApplicationContextPrivate(applicationContext);
}
private void setApplicationContextPrivate(final ApplicationContext applicationContext) {
context = applicationContext;
setControllerFactory(applicationContext::getBean);
setResources(new MessageSourceResourceBundle(applicationContext.getBean(MessageSource.class),
Locale.getDefault()));
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
setApplicationContextPrivate(applicationContext);
}
public <T> T load(final String resourceLocation) throws IOException {
if (context != null) {
final var res = context.getResource(resourceLocation);
setLocation(res.getURL());
try (final InputStream is = res.getInputStream()) {
return load(is);
}
} else {
throw new IllegalStateException(
"Spring context was not set. Use 'new FXMLLoader', if no Spring Bean is desired.");
}
}
@Override
public <T> T load(final InputStream inputStream) throws IOException {
if (context != null) {
return super.load(inputStream);
} else {
throw new IllegalStateException(
"Spring context was not set. Use 'new FXMLLoader', if no Spring Bean is desired.");
}
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
if (!super.equals(obj)) {
return false;
}
final FXMLSpringLoader that = (FXMLSpringLoader) obj;
return Objects.equals(context, that.context);
}
@Override
public int hashCode() {
return Objects.hash(context);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.base_ui;
import com.ahli.galaxy.game.GameData;
import com.ahli.galaxy.game.GameDef;
import com.ahli.galaxy.parser.DeduplicationIntensity;
import com.ahli.galaxy.parser.UICatalogParser;
import com.ahli.galaxy.parser.XmlParserVtd;
import com.ahli.galaxy.ui.UICatalogImpl;
import com.ahli.galaxy.ui.interfaces.UICatalog;
import com.esotericsoftware.kryo.Kryo;
import com.kichik.pecoff4j.PE;
import com.kichik.pecoff4j.ResourceDirectory;
import com.kichik.pecoff4j.ResourceEntry;
import com.kichik.pecoff4j.constant.ResourceType;
import com.kichik.pecoff4j.io.PEParser;
import com.kichik.pecoff4j.io.ResourceParser;
import com.kichik.pecoff4j.resources.StringFileInfo;
import com.kichik.pecoff4j.resources.StringTable;
import com.kichik.pecoff4j.resources.VersionInfo;
import com.kichik.pecoff4j.util.ResourceHelper;
import interfacebuilder.compress.GameService;
import interfacebuilder.config.ConfigService;
import interfacebuilder.integration.FileService;
import interfacebuilder.integration.SettingsIniInterface;
import interfacebuilder.integration.kryo.KryoGameInfo;
import interfacebuilder.integration.kryo.KryoService;
import interfacebuilder.integration.log4j.StylizedTextAreaAppender;
import interfacebuilder.projects.enums.Game;
import interfacebuilder.ui.AppController;
import interfacebuilder.ui.progress.appender.Appender;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serial;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
public class BaseUiService {
private static final Logger logger = LogManager.getLogger(BaseUiService.class);
private static final String META_FILE_NAME = ".meta";
private final ConfigService configService;
private final GameService gameService;
private final FileService fileService;
private final DiscCacheService discCacheService;
private final KryoService kryoService;
private final AppController appController;
public BaseUiService(
final ConfigService configService,
final GameService gameService,
final FileService fileService,
final DiscCacheService discCacheService,
final KryoService kryoService,
final AppController appController) {
this.configService = configService;
this.gameService = gameService;
this.fileService = fileService;
this.discCacheService = discCacheService;
this.kryoService = kryoService;
this.appController = appController;
}
/**
* Checks if the specified game's baseUI is older than the game files.
*
* @param game
* @param usePtr
* @return true, if outdated
*/
public boolean isOutdated(final Game game, final boolean usePtr) throws IOException {
final GameDef gameDef = gameService.getGameDef(game);
final Path gameBaseUI = configService.getBaseUiPath(gameDef);
if (!Files.exists(gameBaseUI) || fileService.isEmptyDirectory(gameBaseUI)) {
return true;
}
final Path baseUiMetaFileDir = configService.getBaseUiPath(gameDef);
final KryoGameInfo baseUiInfo;
try {
baseUiInfo = readMetaFile(baseUiMetaFileDir);
if (baseUiInfo == null) {
return true;
}
} catch (final IOException e) {
final String msg = "Failed to read Game Info from extracted base UI.";
logger.warn(msg);
logger.trace(msg, e);
return true;
}
final int[] versionBaseUi = baseUiInfo.getVersion();
final int[] versionExe = getVersion(gameDef, usePtr);
boolean isUpToDate = true;
for (int i = 0; i < versionExe.length && isUpToDate; ++i) {
isUpToDate = versionExe[i] <= versionBaseUi[i];
}
if (logger.isTraceEnabled()) {
logger.trace("Exe version check - exe={} - {} - upToDate={}",
Arrays.toString(versionExe),
Arrays.toString(versionBaseUi),
isUpToDate);
}
return !isUpToDate;
}
private KryoGameInfo readMetaFile(final Path directory) throws IOException {
final Path path = directory.resolve(META_FILE_NAME);
if (Files.exists(path)) {
final Kryo kryo = kryoService.getKryoForBaseUiMetaFile();
final List<Class<?>> payloadClasses = new ArrayList<>(1);
payloadClasses.add(KryoGameInfo.class);
return (KryoGameInfo) kryoService.get(path, payloadClasses, kryo).get(0);
}
return null;
}
public int[] getVersion(final GameDef gameDef, final boolean isPtr) {
final int[] versions = new int[4];
final Path path = Path.of(gameService.getGameDirPath(gameDef, isPtr),
gameDef.supportDirectoryX64(),
gameDef.switcherExeNameX64());
try {
final PE pe = PEParser.parse(path.toFile());
final ResourceDirectory rd = pe.getImageData().getResourceTable();
final ResourceEntry[] entries = ResourceHelper.findResources(rd, ResourceType.VERSION_INFO);
for (final ResourceEntry entry : entries) {
final byte[] data = entry.getData();
@SuppressWarnings("ObjectAllocationInLoop")
final VersionInfo version = ResourceParser.readVersionInfo(data);
final StringFileInfo strings = version.getStringFileInfo();
final StringTable table = strings.getTable(0);
for (int j = 0; j < table.getCount(); j++) {
final String key = table.getString(j).getKey();
if ("FileVersion".equals(key)) {
final String value = table.getString(j).getValue();
logger.trace("found FileVersion={}", value);
final String[] parts = value.split("\\.");
for (int k = 0; k < 4; k++) {
versions[k] = Integer.parseInt(parts[k]);
}
return versions;
}
}
}
} catch (final IOException e) {
logger.error("Error attempting to parse FileVersion from game's exe: ", e);
}
return versions;
}
/**
* Creates Tasks that will extract the base UI for a specified game.
*
* @param game
* @param usePtr
* @param outputs
* @return list of executable tasks
*/
public List<ForkJoinTask<Void>> createExtractionTasks(
final Game game, final boolean usePtr, final Appender[] outputs) {
logger.info("Extracting baseUI for {}", game);
final GameDef gameDef = gameService.getGameDef(game);
final Path destination = configService.getBaseUiPath(gameDef);
try {
if (!Files.exists(destination)) {
Files.createDirectories(destination);
}
fileService.cleanDirectory(destination);
discCacheService.remove(gameDef.name(), usePtr);
} catch (final IOException e) {
logger.error(String.format("Directory %s could not be cleaned.", destination), e);
return Collections.emptyList();
}
final List<ForkJoinTask<Void>> tasks = new ArrayList<>(4);
final File extractorExe = configService.getCascExtractorExeFile();
final String gamePath = gameService.getGameDirPath(gameDef, usePtr);
final String[] queryMasks = getQueryMasks(game);
int i = 0;
for (final String mask : queryMasks) {
final Appender outputAppender = outputs[i++];
//noinspection ObjectAllocationInLoop
tasks.add(new CascFileExtractionTask(extractorExe, gamePath, mask, destination, outputAppender));
}
final ForkJoinTask<Void> task = new ExtractVersionTask(gameDef, usePtr, destination, this);
tasks.add(task);
return tasks;
}
/**
* @param game
* @return
*/
public static String[] getQueryMasks(final Game game) {
return switch (game) {
case SC2 -> new String[] { "*.SC2Layout", "*Assets.txt", "*.SC2Style" };
case HEROES -> new String[] { "*.StormLayout", "*Assets.txt", "*.StormStyle" };
};
}
private void writeToMetaFile(final Path directory, final String gameName, final int[] version, final boolean isPtr)
throws IOException {
final Path path = directory.resolve(META_FILE_NAME);
final KryoGameInfo metaInfo = new KryoGameInfo(version, gameName, isPtr);
final List<Object> payload = new ArrayList<>(1);
payload.add(metaInfo);
final Kryo kryo = kryoService.getKryoForBaseUiMetaFile();
kryoService.put(path, payload, kryo);
}
/**
* Parses the baseUI of the GameData, if that is required for the settings.
*
* @param gameData
* @param useCmdLineSettings
*/
public void parseBaseUiIfNecessary(final GameData gameData, final boolean useCmdLineSettings) {
final boolean verifyLayout;
final SettingsIniInterface settings = configService.getIniSettings();
if (useCmdLineSettings) {
verifyLayout = settings.isCmdLineVerifyLayout();
} else {
verifyLayout = settings.isGuiVerifyLayout();
}
if (gameData.getUiCatalog() == null && verifyLayout) {
parseBaseUI(gameData);
}
}
/**
* Parses the baseUI of the specified game. The parsing of the baseUI is synchronized.
*
* @param gameData
* game whose default UI is parsed
*/
public void parseBaseUI(final GameData gameData) {
// lock per game
final String gameName = gameData.getGameDef().name();
synchronized (gameName) {
UICatalog uiCatalog = gameData.getUiCatalog();
if (uiCatalog != null) {
logger.trace("Aborting parsing baseUI for '{}' as was already parsed.", gameName);
} else {
final long startTime = System.currentTimeMillis();
logger.info("Loading baseUI for {}", gameName);
boolean needToParseAgain = true;
final Path baseUiPath = configService.getBaseUiPath(gameData.getGameDef());
boolean isPtr = false;
try {
isPtr = isPtr(baseUiPath);
} catch (final IOException e) {
// do nothing
logger.trace("Ignoring error in isPtr() check on baseUiPath.", e);
}
try {
if (cacheIsUpToDateCheckException(gameData.getGameDef(), isPtr)) {
// load from cache
uiCatalog = discCacheService.getCachedBaseUi(gameName, isPtr);
gameData.setUiCatalog(uiCatalog);
needToParseAgain = false;
logger.trace("Loaded baseUI for '{}' from cache", gameName);
}
} catch (final IOException e) {
logger.warn("ERROR: loading cached base UI failed.", e);
}
if (needToParseAgain) {
// parse baseUI
uiCatalog = new UICatalogImpl(gameData.getGameDef());
uiCatalog.setParser(new UICatalogParser(uiCatalog,
new XmlParserVtd(),
DeduplicationIntensity.FULL));
appController.printInfoLogMessageToGeneral("Starting to parse base " + gameName + " UI.");
appController.addThreadLoggerTab(Thread.currentThread().getName(),
gameData.getGameDef().nameHandle() + "UI",
false);
final String gameDir = configService.getBaseUiPath(gameData.getGameDef()) + File.separator +
gameData.getGameDef().modsSubDirectory();
try {
final WildcardFileFilter fileFilter =
new WildcardFileFilter("descindex.*layout", IOCase.INSENSITIVE);
for (final String modOrDir : gameData.getGameDef().coreModsOrDirectories()) {
@SuppressWarnings("ObjectAllocationInLoop")
final File directory = new File(gameDir + File.separator + modOrDir);
if (!directory.exists() || !directory.isDirectory()) {
throw new IOException("BaseUI does not exist.");
}
@SuppressWarnings("ObjectAllocationInLoop")
final Collection<File> descIndexFiles =
FileUtils.listFiles(directory, fileFilter, TrueFileFilter.INSTANCE);
logger.info("number of descIndexFiles found: {}", descIndexFiles.size());
for (final File descIndexFile : descIndexFiles) {
logger.info("parsing descIndexFile '{}'", descIndexFile.getPath());
uiCatalog.processDescIndex(descIndexFile,
gameData.getGameDef().defaultRaceId(),
gameData.getGameDef().defaultConsoleSkinId());
}
}
uiCatalog.postProcessParsing();
gameData.setUiCatalog(uiCatalog);
logger.trace("Parsed BaseUI for {}", gameName);
} catch (final SAXException | IOException | ParserConfigurationException e) {
logger.error(String.format("ERROR parsing base UI catalog for '%s'.", gameName), e);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
uiCatalog.setParser(null);
}
final String msg = "Finished parsing base UI for " + gameName + ".";
logger.info(msg);
appController.printInfoLogMessageToGeneral(msg);
try {
discCacheService.put(uiCatalog, gameName, isPtr, getVersion(gameData.getGameDef(), isPtr));
} catch (final IOException e) {
logger.error("ERROR when creating cache file of UI", e);
}
}
final long executionTime = (System.currentTimeMillis() - startTime);
logger.info("Loading BaseUI for {} took {}ms.", gameName, executionTime);
if (needToParseAgain) {
// set result in UI
StylizedTextAreaAppender.finishedWork(Thread.currentThread().getName(), true, 50);
}
}
}
}
/**
* Checks if the baseUiDirectory is PTR.
*
* @param baseUiDirectory
* @return true if PTR; false if not or no file is existing
* @throws IOException
*/
public boolean isPtr(final Path baseUiDirectory) throws IOException {
final KryoGameInfo kryoGameInfo = readMetaFile(baseUiDirectory);
return kryoGameInfo != null && kryoGameInfo.isPtr();
}
public boolean cacheIsUpToDateCheckException(final GameDef gameDef, final boolean usePtr) {
try {
return cacheIsUpToDate(gameDef, usePtr);
} catch (final NoSuchFileException e) {
logger.trace(String.format("No cache exists for %s", gameDef.name()), e);
} catch (final IOException e) {
logger.info(String.format("Failed to check cache status of %s:", gameDef.name()), e);
}
return false;
}
public boolean cacheIsUpToDate(final GameDef gameDef, final boolean usePtr) throws IOException {
final Path baseUiMetaFileDir = configService.getBaseUiPath(gameDef);
final Path cacheFilePath = discCacheService.getCacheFilePath(gameDef.name(), usePtr);
return cacheIsUpToDate(cacheFilePath, baseUiMetaFileDir);
}
/**
* @param cacheFile
* @param metaFileDir
* @return
*/
public boolean cacheIsUpToDate(final Path cacheFile, final Path metaFileDir) throws IOException {
// no cache -> not up to date
if (!Files.exists(cacheFile)) {
return false;
}
final KryoGameInfo cacheInfo = discCacheService.getCachedBaseUiInfo(cacheFile);
final int[] versionCache = cacheInfo.getVersion();
final KryoGameInfo baseUiInfo = readMetaFile(metaFileDir);
if (baseUiInfo == null) {
return false;
}
final int[] versionBaseUi = baseUiInfo.getVersion();
boolean isUpToDate = true;
for (int i = 0; i < versionCache.length && isUpToDate; ++i) {
isUpToDate = versionCache[i] == versionBaseUi[i];
}
logger.trace("Cache and baseUI versions match: {}", isUpToDate);
return isUpToDate;
}
public boolean isHeroesPtrActive() {
final Path baseUiMetaFileDir = configService.getBaseUiPath(gameService.getGameDef(Game.HEROES));
try {
final KryoGameInfo baseUiInfo = readMetaFile(baseUiMetaFileDir);
if (baseUiInfo != null) {
return baseUiInfo.isPtr();
}
} catch (final IOException e) {
logger.error("ERROR while checking if ptr is active via baseUI cache file", e);
}
return false;
}
private static final class CascFileExtractionTask extends RecursiveAction {
@Serial
private static final long serialVersionUID = -775938058915435006L;
private final File extractorExe;
private final String gamePath;
private final String mask;
private final Path destination;
private final Appender outputAppender;
private CascFileExtractionTask(
final File extractorExe,
final String gamePath,
final String mask,
final Path destination,
final Appender outputAppender) {
this.extractorExe = extractorExe;
this.gamePath = gamePath;
this.mask = mask;
this.destination = destination;
this.outputAppender = outputAppender;
}
@Override
protected void compute() {
try {
if (extract(extractorExe, gamePath, mask, destination, outputAppender)) {
Thread.sleep(50);
if (extract(extractorExe, gamePath, mask, destination, outputAppender)) {
logger.warn(
"Extraction failed due to a file access. Try closing the Battle.net App, if it is running and this fails to extract all files.");
}
}
} catch (final IOException e) {
logger.error("Extracting files from CASC via CascExtractor failed.", e);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
if (outputAppender != null) {
outputAppender.end();
}
}
}
/**
* @param extractorExe
* @param gamePath
* @param mask
* @param destination
* @param out
* @return
* @throws IOException
* @throws InterruptedException
*/
private static boolean extract(
final File extractorExe,
final String gamePath,
final String mask,
final Path destination,
final Appender out) throws IOException, InterruptedException {
final ProcessBuilder pb = new ProcessBuilder(extractorExe.getAbsolutePath(),
gamePath + File.separator,
mask,
destination + File.separator);
// put error and normal output into the same stream
pb.redirectErrorStream(true);
boolean retry = false;
final Process process = pb.start();
// empty output buffers and print to console
try (final InputStream is = process.getInputStream()) {
do {
//noinspection BusyWait
Thread.sleep(50);
final String log = IOUtils.toString(is, Charset.defaultCharset());
if (log.contains("Unhandled Exception: System.IO.IOException: The process cannot access the file")) {
retry = true;
} else {
if (out != null) {
out.append(log);
} else {
logger.info(log);
}
}
} while (process.isAlive());
}
return retry;
}
}
private static final class ExtractVersionTask extends RecursiveAction {
@Serial
private static final long serialVersionUID = 3071926102876787289L;
private final GameDef gameDef;
private final boolean usePtr;
private final Path destination;
private final BaseUiService baseUiService;
private ExtractVersionTask(
final GameDef gameDef,
final boolean usePtr,
final Path destination,
final BaseUiService baseUiService) {
this.gameDef = gameDef;
this.usePtr = usePtr;
this.destination = destination;
this.baseUiService = baseUiService;
}
@Override
protected void compute() {
final int[] version = baseUiService.getVersion(gameDef, usePtr);
try {
baseUiService.writeToMetaFile(destination, gameDef.name(), version, usePtr);
} catch (final IOException e) {
logger.error("Failed to write metafile: ", e);
}
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.browse;
import com.ahli.galaxy.ui.interfaces.UIAnimation;
import com.ahli.galaxy.ui.interfaces.UIController;
import com.ahli.galaxy.ui.interfaces.UIElement;
import com.ahli.galaxy.ui.interfaces.UIFrame;
import com.ahli.galaxy.ui.interfaces.UIState;
import com.ahli.galaxy.ui.interfaces.UIStateGroup;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.apache.commons.lang3.StringUtils;
public class TextFlowFactory {
public static final String STYLE_DFLT = "-fx-fill: white; -fx-font-smoothing-type: lcd;";
public static final String STYLE_HIGHLIGHTED = "-fx-fill: orange; -fx-font-smoothing-type: lcd;";
private String query;
public TextFlowFactory() {
// explicit default constructor
}
public void setHighlight(final String query) {
this.query = query;
}
public TextFlow getFlow(final UIElement item) {
final TextFlow flow = new TextFlow();
if (item instanceof final UIFrame frame) {
append(flow, textUnimportant("<Frame type=\""));
append(flow, textQueried(frame.getType()));
append(flow, textUnimportant("\" name=\""));
append(flow, textQueried(frame.getName()));
append(flow, textUnimportant("\">"));
} else if (item instanceof final UIAnimation anim) {
append(flow, textUnimportant("<Animation name=\""));
append(flow, textQueried(anim.getName()));
append(flow, textUnimportant("\">"));
} else if (item instanceof final UIState state) {
append(flow, textUnimportant("<State name=\""));
append(flow, textQueried(state.getName()));
append(flow, textUnimportant("\">"));
} else if (item instanceof final UIController ctrl) {
append(flow, textUnimportant("<Controller name=\""));
append(flow, textQueried(ctrl.getName()));
append(flow, textUnimportant("\">"));
} else if (item instanceof final UIStateGroup stateGroup) {
append(flow, textUnimportant("<StateGroup name=\""));
append(flow, textQueried(stateGroup.getName()));
append(flow, textUnimportant("\">"));
} else {
append(flow, textQueried(item.toString()));
}
return flow;
}
private static void append(final TextFlow flow, final Text text) {
flow.getChildren().add(text);
}
private static Text textUnimportant(final String label) {
final Text text = new Text(label);
text.setStyle("-fx-fill: grey; -fx-font-smoothing-type: lcd;");
return text;
}
private static void append(final TextFlow flow, final Text[] text) {
flow.getChildren().addAll(text);
}
private Text[] textQueried(final String label) {
int count = 1;
int index = -1;
if (query != null && !query.isEmpty()) {
index = StringUtils.indexOfIgnoreCase(label, query);
if (index > -1) {
// match in the front = 2 segments; match in the middle = 3 segments
count += (index > 0 ? 2 : 1);
}
}
final Text[] text = new Text[count];
if (count > 2) {
text[0] = new Text(label.substring(0, index));
text[1] = new Text(label.substring(index, index + query.length()));
text[2] = new Text(label.substring(index + query.length()));
text[0].setStyle(STYLE_DFLT);
text[1].setStyle(STYLE_HIGHLIGHTED);
text[2].setStyle(STYLE_DFLT);
applyVisualHighlight(text[1]);
} else if (count > 1) {
text[0] = new Text(label.substring(0, index + query.length()));
text[1] = new Text(label.substring(index + query.length()));
text[0].setStyle(STYLE_HIGHLIGHTED);
text[1].setStyle(STYLE_DFLT);
applyVisualHighlight(text[0]);
} else {
text[0] = new Text(label);
text[0].setStyle(STYLE_DFLT);
}
return text;
}
private static void applyVisualHighlight(final Text text) {
final Blend blend = new Blend();
blend.setMode(BlendMode.MULTIPLY);
final DropShadow ds = new DropShadow();
ds.setColor(Color.rgb(188, 254, 66, 0.1));
ds.setOffsetX(0);
ds.setOffsetY(0);
ds.setRadius(13);
ds.setSpread(0.8);
ds.setBlurType(BlurType.TWO_PASS_BOX);
blend.setBottomInput(ds);
text.setEffect(blend);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.browse;
import javafx.scene.control.TreeItem;
import java.util.function.Predicate;
@FunctionalInterface
public interface TreeItemPredicate<T> {
/**
* Utility method to create a TreeItemPredicate from a given {@link Predicate}
*/
static <T> TreeItemPredicate<T> create(final Predicate<T> predicate) {
return new TestingTreeItemPredicate<>(predicate);
}
/**
* Evaluates this predicate on the given argument.
*
* @param parent
* the parent tree item of the element or null if there is no parent
* @param value
* the value to be tested
* @return {@code true} if the input argument matches the predicate,otherwise {@code false}
*/
boolean test(TreeItem<T> parent, T value);
/**
* TreeItemPredicate implementation for Utility method
*
* @param <T>
*/
final class TestingTreeItemPredicate<T> implements TreeItemPredicate<T> {
private final Predicate<T> predicate;
public TestingTreeItemPredicate(final Predicate<T> predicate) {
this.predicate = predicate;
}
@Override
public boolean test(final TreeItem<T> parent, final T value) {
return predicate.test(value);
}
}
}<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.archive;
import com.ahli.mpq.MpqException;
import com.ahli.mpq.MpqInterface;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.tuple.Tuples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Stores the Data of a Desc Index File.
*
* @author Ahli
*/
// TODO rebuild to use the UI object model instead of parsing all layout files
// another time
public class DescIndexData {
private static final String STRING2 = "#";
private static final String DESC = "</Desc>\r\n";
private static final String STRING = "\"/>\r\n";
private static final String INCLUDE_PATH = " <Include path=\"";
private static final String XML_VERSION_1_0_ENCODING_UTF_8_STANDALONE_YES_DESC =
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n<Desc>\r\n";
private static final Logger logger = LoggerFactory.getLogger(DescIndexData.class);
private static final String CHECKED_WITH_DEPENDENCY_AND_I_J_I2 =
"checked {} with dependency {} and {} i={} j={} i2={}";
private static final String FILE_INT_PATH_LIST = "fileIntPathList: {}";
private final MpqInterface mpqi;
private final List<Pair<Path, String>> fileIntPathList;
private String descIndexIntPath;
/**
* Constructor.
*
* @param mpqi
* MpqInterface
*/
public DescIndexData(final MpqInterface mpqi) {
this.mpqi = mpqi;
fileIntPathList = new ArrayList<>(10);
}
/**
* @return
*/
public String getDescIndexIntPath() {
return descIndexIntPath;
}
/**
* @param descIndexIntPath
*/
public void setDescIndexIntPath(final String descIndexIntPath) {
this.descIndexIntPath = descIndexIntPath;
}
/**
* @param i
* @return
*/
public String getLayoutIntPath(final int i) {
return fileIntPathList.get(i).getTwo();
}
/**
* @param intPath
* @return
*/
public boolean removeLayoutIntPath(final String intPath) {
for (int i = 0, len = fileIntPathList.size(); i < len; ++i) {
final Pair<Path, String> p = fileIntPathList.get(i);
if (p.getTwo().equals(intPath)) {
fileIntPathList.remove(i);
return true;
}
}
return false;
}
/**
* @param descIndexPath
*/
public void setDescIndexPathAndClear(final String descIndexPath) {
clear();
setDescIndexIntPath(descIndexPath);
}
/**
*
*/
public void clear() {
fileIntPathList.clear();
}
/**
* @param layoutPathList
* @throws MpqException
*/
public void addLayoutIntPath(final Iterable<String> layoutPathList) throws MpqException {
for (final String aLayoutPathList : layoutPathList) {
addLayoutIntPath(aLayoutPathList);
}
}
/**
* @param intPath
* @throws MpqException
*/
public void addLayoutIntPath(final String intPath) throws MpqException {
String intPath2 = intPath;
Path p = mpqi.getFilePathFromMpq(intPath);
if (!Files.exists(p)) {
// add base folder to the path
intPath2 = (mpqi.isHeroesMpq() ? "base.stormdata" : "Base.SC2Data") + File.separator + intPath;
p = mpqi.getFilePathFromMpq(intPath2);
if (!Files.exists(p)) {
return;
}
}
fileIntPathList.add(Tuples.pair(p, intPath2));
logger.trace("added Layout path: {}\nadded File path: {}", intPath2, p);
}
/**
* @return
*/
public int getLayoutCount() {
return fileIntPathList.size();
}
/**
* @param intPath
* @return
*/
public Path getLayoutFilePath(final String intPath) {
for (final Pair<Path, String> p : fileIntPathList) {
if (p.getTwo().equals(intPath)) {
return p.getOne();
}
}
return null;
}
/**
* @throws IOException
*/
public void persistDescIndexFile() throws IOException {
final Path p = mpqi.getFilePathFromMpq(descIndexIntPath);
try (final BufferedWriter bw = Files.newBufferedWriter(p)) {
bw.write(XML_VERSION_1_0_ENCODING_UTF_8_STANDALONE_YES_DESC);
for (final Pair<Path, String> curPair : fileIntPathList) {
bw.write(INCLUDE_PATH);
bw.write(curPair.getTwo());
bw.write(STRING);
}
bw.write(DESC);
} catch (final IOException e) {
logger.error("ERROR writing DescIndex to disc.", e);
throw e;
}
}
/**
* Orders layout files in DescIndex.
*
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public void orderLayoutFiles() throws ParserConfigurationException, SAXException, IOException {
final List<List<String>> dependencies = new ArrayList<>(10);
final List<List<String>> ownConstants = new ArrayList<>(10);
// grab dependencies and constant definitions for every layout file
List<String> layoutDeps;
List<String> curConstants;
for (final Pair<Path, String> pair : fileIntPathList) {
final File f = pair.getOne().toFile();
curConstants = LayoutReaderDom.getLayoutsConstantDefinitions(f);
// add calculated list of dependencies from layout file
layoutDeps = LayoutReaderDom.getDependencyLayouts(f, curConstants);
logger.trace("Dependencies found: {}", layoutDeps);
ownConstants.add(curConstants);
dependencies.add(layoutDeps);
}
boolean insertOccurred = true;
for (int counter = 0; insertOccurred && counter < Math.pow(fileIntPathList.size(), 4); ++counter) {
logger.trace("counter={}", counter);
insertOccurred = false;
for (int i = 0, len = dependencies.size(); i < len; ++i) {
final List<String> curLayoutDepList = dependencies.get(i);
final Pair<Path, String> pair = fileIntPathList.get(i);
for (int j = 0, len2 = curLayoutDepList.size(); j < len2; ++j) {
String curDependencyTo = curLayoutDepList.get(j);
if (curDependencyTo.startsWith(STRING2)) {
logger.trace("DEPENDENCY: {}", curDependencyTo);
while (curDependencyTo.startsWith(STRING2)) {
curDependencyTo = curDependencyTo.substring(1);
}
boolean constantNotDefinedBefore = true;
// check if it appears before the template
if (i > 0) {
y:
for (int i2 = 0; i2 < i; ++i2) {
// Pair<File, String> otherPair =
// fileIntPathList.get(i2);
// String fileName =
// otherPair.getKey().getName();
// fileName = fileName.substring(0,
// fileName.lastIndexOf('.'));
for (final String constant : ownConstants.get(i2)) {
if (constant.equals(curDependencyTo)) {
constantNotDefinedBefore = false;
break y;
}
}
}
}
if (constantNotDefinedBefore) {
y:
for (int i2 = i + 1, len3 = dependencies.size(); i2 < len3; ++i2) {
final Pair<Path, String> otherPair = fileIntPathList.get(i2);
String fileName = otherPair.getOne().getFileName().toString();
final int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0) {
fileName = fileName.substring(0, dotIndex);
}
for (final String constant : ownConstants.get(i2)) {
if (constant.equals(curDependencyTo)) {
if (logger.isTraceEnabled()) {
logger.trace(
CHECKED_WITH_DEPENDENCY_AND_I_J_I2,
fileIntPathList.get(i).getOne().getFileName(),
curDependencyTo,
constant,
i,
j,
i2);
logger.trace(FILE_INT_PATH_LIST, fileIntPathList);
}
// i's needs to be inserted after i2
dependencies.remove(i);
fileIntPathList.remove(i);
i = i2;
dependencies.add(i, curLayoutDepList);
fileIntPathList.add(i, pair);
//constantDefinedBefore = true;
if (logger.isTraceEnabled()) {
logger.trace(
"inserted {} after {}",
fileIntPathList.get(i).getOne().getFileName(),
fileName);
logger.trace(FILE_INT_PATH_LIST, fileIntPathList);
}
break y;
} else {
if (logger.isTraceEnabled()) {
logger.trace(
CHECKED_WITH_DEPENDENCY_AND_I_J_I2,
fileIntPathList.get(i).getOne().getFileName(),
curDependencyTo,
constant,
i,
j,
i2);
}
}
}
}
}
}
// else {
// // templates
// }
}
}
}
// change order according to templates
insertOccurred = true;
for (int counter = 0; insertOccurred && counter < Math.pow(fileIntPathList.size(), 4); ++counter) {
logger.trace("counter={}", counter);
insertOccurred = false;
x:
for (int i = 0; i < dependencies.size(); ++i) {
final List<String> curLayoutDepList = dependencies.get(i);
final Pair<Path, String> pair = fileIntPathList.get(i);
for (int j = 0; j < curLayoutDepList.size(); ++j) {
final String curDependencyTo = curLayoutDepList.get(j);
if (!curDependencyTo.startsWith(STRING2)) {
// check if it appears after the template
for (int i2 = i + 1; i2 < dependencies.size(); ++i2) {
final Pair<Path, String> otherPair = fileIntPathList.get(i2);
String fileName = otherPair.getOne().getFileName().toString();
final int dotIndex = fileName.lastIndexOf('.');
if (dotIndex >= 0) {
fileName = fileName.substring(0, dotIndex);
}
if (fileName.equals(curDependencyTo)) {
if (logger.isTraceEnabled()) {
logger.trace(
CHECKED_WITH_DEPENDENCY_AND_I_J_I2,
fileIntPathList.get(i).getOne().getFileName(),
curDependencyTo,
fileName,
i,
j,
i2);
logger.trace(FILE_INT_PATH_LIST, fileIntPathList);
}
// i's needs to be inserted after i2
dependencies.remove(i);
fileIntPathList.remove(i);
i = i2;
dependencies.add(i, curLayoutDepList);
fileIntPathList.add(i, pair);
insertOccurred = true;
if (logger.isTraceEnabled()) {
logger.trace(
"inserted {} after {}",
fileIntPathList.get(i).getOne().getFileName(),
fileName);
logger.trace(FILE_INT_PATH_LIST, fileIntPathList);
}
break x;
} else {
if (logger.isTraceEnabled()) {
logger.trace(
CHECKED_WITH_DEPENDENCY_AND_I_J_I2,
fileIntPathList.get(i).getOne().getFileName(),
curDependencyTo,
fileName,
i,
j,
i2);
}
}
}
}
// else {
// // constants
// }
}
}
}
// 1. layouts durchgehen und Abhaengigkeiten speichern
// Abhaengigkeit:
// - template aus anderem layout aus dieser Liste benutzen
// (template="filename/...")
// - constant benutzen, die in anderem layout definiert wird und nicht
// im eigenen (#abc oder ##abc)
// 2. layouts anordnen, sodass keine Abhaengigkeit mehr vorhanden sind
}
}
<file_sep>Observer Interface Settings Editor
----------------------------------
Author: Christoph "Ahli" Ahlers (twitter: @AhliSC2)
version: alpha
Legal Information
-----------------
Use at your own risk. This software is free to use.
Do not duplicate, copy, steal, sell, eat, etc.
Copyright 2019 <<NAME>>
What does it do?
----------------
This program is a simple editor to load and edit hotkeys and settings within Observer Interface files which use the file types .SC2Interface and .StormInterface.
These Observer Interface files can be loaded in the game options of Blizzard Entertainment's games StarCraft II and Heroes of the Storm to adjust the UI of an observer.
The interfaces are required to define adjustable constants within a layout file with the syntax described at the end of this document.
Contained Files:
----------------
The files installed into your install directory.
Other Files that are created and persist:
-----------------------------------
- %AppData%\Roaming\MPQEditor.ini Ladik's MpqEditor settings file.
- %AppData%\Roaming\MPQEditor_Ruleset.ini Ladik's MpqEditor settings file for custom file compression.
- %UserHome%\.GalaxyObsUiSettingsEditor\logs\settingsEditor_lastRun.log Log file of the last settings editor execution for debugging.
Credits:
--------
- @tinkoliu for translating the editor to Chinese and Taiwanese
- Ladislav "Ladik" Zezula for creating his MpqEditor. It is used to open and create the Observer Interface files.
How to add Hotkeys and Settings to your Observer Interface?
-----------------------------------------------------------
The editor will scan all layout files for special texts in comments that define hotkeys and settings.
Here is an example hotkey and setting definition:
<!-- @Hotkey ( constant = "Hotkey - Toggle Talents",
default = "Control+1",
description = "Toggle bottom panel's talent tab."
) -->
<!-- @Setting ( constant = "LeaderPanelBottom_VerticalOffset",
default = "0",
description = "Controls the offset of the bottom panel. Use values like '-75' to move it upwards."
) -->
<Frame type="Frame" name="ObserverUiSettingsDefinitions">
</Frame>
<Constant name="Hotkey - Toggle Talents" val="Control+1"/>
<Constant name="LeaderPanelBottom_VerticalOffset" val="0"/>
A definition has to be in a comment as shown above. The minimal definition requires only the name of the constant:
@Hotkey ( constant = "name of the constant you want to modify" )
All settings you wish to edit has to use constants, so your actual control frames need to define a shortcut with a constant:
<Frame type="ToggleControl" name="ToggleTalentOverview">
<Anchor relative="$parent"/>
<Shortcut val="#Hotkey - Toggle Talents"/>
</Frame>
Furthermore, you should define a default value and a description for your settings and hotkeys. These information are not required, but help the user.
<file_sep>MpqInterface.CouldNotOverwriteFile=無法覆蓋文件 '%1$s'.
MpqInterface.MpqEditorNotFound=無法在以下文件夾中找到MPQEditor: %1$s.
MpqInterface.NoFilesExtracted=沒有文件從下列包中解壓出來 '%1$s'.
MpqInterface.CouldNotCreatePath=Could not create directories for path '%1$s'.
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.browse;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import lombok.extern.log4j.Log4j2;
import java.util.ArrayList;
import java.util.List;
/**
* This class is a ComboBox which implements a search functionality which appears in a context menu.
* <p>
* This implementation is based on <NAME>'s AutoCompleteTextField.
*/
@Log4j2
public class AutoCompleteComboBox extends ComboBox<String> {
/** The popup used to select an entry. */
private final ContextMenu entriesPopup;
/** Construct a new AutoCompleteTextField. */
public AutoCompleteComboBox() {
setEditable(true);
entriesPopup = new ContextMenu();
final TextField editor = getEditor();
if (editor != null) {
editor.textProperty().addListener(new TextChangeListener());
}
focusedProperty().addListener((observableValue, aBoolean, aBoolean2) -> entriesPopup.hide());
}
/**
* Code by Icza from https://stackoverflow.com/a/25379180/12849006
*
* @param src
* @param what
* @return
*/
public static boolean containsIgnoreCase(final String src, final String what) {
final int length = what.length();
if (length == 0) {
return true; // Empty string is contained
}
final char firstLo = Character.toLowerCase(what.charAt(0));
final char firstUp = Character.toUpperCase(what.charAt(0));
for (int i = src.length() - length; i >= 0; --i) {
// Quick check before calling the more expensive regionMatches() method:
final char ch = src.charAt(i);
if (ch != firstLo && ch != firstUp) {
continue;
}
if (src.regionMatches(true, i, what, 0, length)) {
return true;
}
}
return false;
}
private class TextChangeListener implements ChangeListener<String> {
@Override
public void changed(
final ObservableValue<? extends String> observableValue, final String oldVal, final String newVal) {
if (newVal.isEmpty() || !isFocused()) {
entriesPopup.hide();
} else {
// TODO visually show the matching area in contextmenu's texts
final int maxEntries = 20;
final List<CustomMenuItem> menuItems = new ArrayList<>(maxEntries);
int curEntries = 0;
for (final String item : getItems()) {
if (containsIgnoreCase(item, newVal)) {
@SuppressWarnings("ObjectAllocationInLoop")
final Label entryLabel = new Label(item);
@SuppressWarnings("ObjectAllocationInLoop")
final CustomMenuItem menuItem = new CustomMenuItem(entryLabel, true);
//noinspection ObjectAllocationInLoop
menuItem.setOnAction(new MenuItemEventHandler(AutoCompleteComboBox.this, item, entriesPopup));
menuItems.add(menuItem);
++curEntries;
if (curEntries >= maxEntries) {
break;
}
}
}
if (!menuItems.isEmpty()) {
entriesPopup.getItems().clear();
entriesPopup.getItems().addAll(menuItems);
entriesPopup.show(AutoCompleteComboBox.this, Side.BOTTOM, 0, 0);
} else {
entriesPopup.hide();
entriesPopup.getItems().clear();
}
}
}
private static class MenuItemEventHandler implements EventHandler<ActionEvent> {
private final AutoCompleteComboBox autoCompleteComboBox;
private final String item;
private final ContextMenu entriesPopup;
public MenuItemEventHandler(
final AutoCompleteComboBox autoCompleteComboBox,
final String item,
final ContextMenu entriesPopup) {
this.autoCompleteComboBox = autoCompleteComboBox;
this.item = item;
this.entriesPopup = entriesPopup;
}
@Override
public void handle(final ActionEvent event) {
autoCompleteComboBox.getSelectionModel().select(item);
entriesPopup.hide();
}
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
class UIConstantTest {
// @Test
// @SuppressWarnings("JUnitTestMethodWithNoAssertions")
// void equalsContract() {
// EqualsVerifier.forClass(UIConstant.class)
// .withRedefinedSuperclass()
// .withIgnoredFields("hash", "hashIsZero", "hashIsDirty")
// .suppress(Warning.NONFINAL_FIELDS)
// .verify();
// }
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.util;
public final class StringInterner {
private static final ConcurrentWeakWeakHashMap<String> map = new ConcurrentWeakWeakHashMap<>(8, 0.9F, 1);
private StringInterner() {
// no instances allowed
}
public static String intern(final String s) {
final String exists = map.putIfAbsent(s, s);
return (exists == null) ? s : exists;
}
public static void clear() {
map.clear();
}
/**
* Removes obsolete WeakReference-Instances that remain after the VM garbage was collected.
*/
public static void cleanUpGarbage() {
map.purgeKeys();
}
/**
* Returns the number of interned strings stored.
*
* @return the number of stored strings
*/
public static int size() {
return map.size();
}
public static StringBuilder print() {
final StringBuilder sb = new StringBuilder(32);
for (final String key : map.keySet()) {
sb.append(key).append('\n');
}
return sb;
}
}
<file_sep># Galaxy-Observer-UI
This is a toolset to create Observer Interface files for StarCraft II and Heroes of the Storm.
## User Guide:
### User Installation:
Required Software (for Windows):
* [Java 16 or higher](https://adoptopenjdk.net)
* A text editor preferably with XML syntax support, e.g. [Notepad++](https://notepad-plus-plus.org/) with the [NppExec plugin](https://sourceforge.net/projects/npp-plugins/files/NppExec/)
### Using the Builder:
To compile all archives, just start 'compile-spring-boot.jar' within the 'dev' folder via the .bat file.
To compile a selected archive and start a replay, consult the 'ReadMe.txt' in the same folder.
#### Installation Steps:
1. Install the Java SDK.
2. Download and place this development environment somewhere.
3. Start the Builder via the .bat file located in the dev directory. Add your projects or create new ones in the home screen.
4. Open the Settings screen and set your game paths.
5. In the Browse screen's Manage tab, extract the base UI of your games.
### Tools-Developer Installation:
Required Software (for Windows):
* [Java 16 or higher](https://adoptopenjdk.net)
* Java IDE, for example [IntelliJ](https://www.jetbrains.com/idea/download/#section=windows) or [Eclipse for Java Developers](https://www.eclipse.org/downloads/eclipse-packages/)
* A text editor preferably with XML syntax support, e.g. [Notepad++](https://notepad-plus-plus.org/) with optionally the [NppExec plugin](https://sourceforge.net/projects/npp-plugins/files/NppExec/) or alternatively [VSCode](https://code.visualstudio.com) with [Talv's SC2Layout plugin](https://github.com/Talv/sc2-layouts)
* Git or some of its GUI software like [Sourcetree](https://www.sourcetreeapp.com/).
* [NSIS](https://nsis.sourceforge.io/Main_Page) to create installers for Settings Editor
#### Tools-Developer Installation Steps:
1. Install Java.
2. Install Git and clone this repository.
3. Install Notepad++ and its NppExec plugin.
To install the plugin via Notepad's Plugin Admin dialog. Then configure the plugin with the parameters suggested in dev/ReadMe.txt.
Alternatively, use [VSCode](https://code.visualstudio.com) and install [Talv's plugin for SC2Layout files](https://github.com/Talv/sc2-layouts)
4. Install your Java IDE
5. Install NSIS
## Further Software already included:
* [MPQ Editor by <NAME>](http://www.zezula.net/en/mpq/download.html). It is used to open and create MPQ files.
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.projects;
import com.ahli.galaxy.game.GameData;
import interfacebuilder.build.MpqBuilderService;
import interfacebuilder.compress.RuleSet;
import interfacebuilder.projects.enums.Game;
import interfacebuilder.ui.navigation.NavigationController;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.transaction.annotation.Transactional;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Iterator;
import java.util.List;
/**
* ProjectService manages Observer Interface project related tasks.
*/
public class ProjectService {
private static final String DIRECTORY_SYMBOL = "/";
private static final Logger logger = LogManager.getLogger(ProjectService.class);
private final ProjectJpaRepository projectRepo;
private final MpqBuilderService mpqBuilderService;
private final NavigationController navigationController;
public ProjectService(
final ProjectJpaRepository projectRepo,
final MpqBuilderService mpqBuilderService,
final NavigationController navigationController) {
this.projectRepo = projectRepo;
this.mpqBuilderService = mpqBuilderService;
this.navigationController = navigationController;
}
/**
* @param project
* @throws IOException
*/
public void createTemplateProjectFiles(final Project project) throws IOException {
final String jarIntPath;
if (project.getGame() == Game.SC2) {
jarIntPath = "templates/sc2/interface/";
} else {
jarIntPath = "templates/heroes/interface/";
}
final Path projPath = Path.of(project.getProjectPath());
final var resolver = new PathMatchingResourcePatternResolver();
logger.trace("creating template");
final int jarIntPathLen = jarIntPath.length();
for (final Resource res : resolver.getResources("classpath*:" + jarIntPath + "**")) {
final String uri = res.getURI().toString();
logger.trace("extracting file {}", uri);
final int i = uri.indexOf(jarIntPath);
final String intPath = uri.substring(i + jarIntPathLen);
final Path path = projPath.resolve(intPath);
logger.trace("writing file {}", path);
if (!uri.endsWith(DIRECTORY_SYMBOL)) {
Files.createDirectories(path.getParent());
//noinspection ObjectAllocationInLoop
try (final InputStream in = new BufferedInputStream(res.getInputStream(), 1_024)) {
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
}
} else {
Files.createDirectories(path);
}
}
logger.trace("create template finished");
}
/**
* Returns whether the specified path contains a compilable file for the specified game.
*
* @param path
* @param game
* @return
*/
public boolean pathContainsCompileableForGame(final String path, final GameData game) {
// detection via layout file ending as defined in the GameData's GameDef
final String[] extensions = new String[1];
extensions[0] = game.getGameDef().layoutFileEnding();
final IOFileFilter filter = new SuffixFileFilter(extensions, IOCase.INSENSITIVE);
final Iterator<File> iter = FileUtils.iterateFiles(new File(path), filter, TrueFileFilter.INSTANCE);
while (iter.hasNext()) {
if (iter.next().isFile()) {
return true;
}
}
return false;
}
/**
* Returns all Projects.
*
* @return
*/
public List<Project> getAllProjects() {
return ProjectEntity.toProjects(projectRepo.findAll());
}
/**
* Saves the specified project to the database.
*
* @param project
* @return updated instance
* @throws DataAccessException
*/
public Project saveProject(final Project project) {
try {
return ProjectEntity.toProject(projectRepo.save(ProjectEntity.fromProject(project)));
} catch (final DataAccessException e) {
logger.error("Saving project failed", e);
throw e;
}
}
/**
* Builds the specified projects.
*
* @param projects
* @param useCmdLineSettings
*/
public void build(final Iterable<Project> projects, final boolean useCmdLineSettings) {
boolean building = false;
for (final Project project : projects) {
building = true;
mpqBuilderService.build(project, useCmdLineSettings);
}
if (building) {
// switch to progress
navigationController.clickProgress();
}
}
/**
* Removes the specified Project from the database.
*
* @param project
*/
public void deleteProject(final Project project) {
projectRepo.delete(ProjectEntity.fromProject(project));
}
/**
* Returns a list of Projects using the specified path.
*
* @param path
* @return list of Projects with matching path
*/
public List<Project> getProjectsOfPath(final String path) {
return ProjectEntity.toProjects(projectRepo.findAll(new ProjectsPathMatcher(path)));
}
/**
* Initializes the BestCompressionRuleSet field of the specified project and returns it.
*
* @param project
* @return
*/
@Transactional
public RuleSet fetchBestCompressionRuleSet(final Project project) {
if (!Hibernate.isInitialized(project.getBestCompressionRuleSet())) {
// grab from DB wire compression rules to old instance
final ProjectEntity project2 = projectRepo.getById(project.getId());
try {
Hibernate.initialize(project2.getBestCompressionRuleSet());
} catch (final HibernateException e) {
logger.error("Error while fetching compression rule set from DB.", e);
}
project.setBestCompressionRuleSet(project2.getBestCompressionRuleSet());
}
return project.getBestCompressionRuleSet();
}
private static final class ProjectsPathMatcher implements Example<ProjectEntity> {
private final String path;
private ProjectsPathMatcher(final String path) {
this.path = path;
}
@Override
public ProjectEntity getProbe() {
return new ProjectEntity(null, path, null);
}
@Override
public ExampleMatcher getMatcher() {
return ExampleMatcher.matchingAll().withIgnoreNullValues();
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.mpq.mpqeditor;
import com.ahli.util.DeepCopyable;
import org.apache.commons.configuration2.INIConfiguration;
import org.apache.commons.configuration2.SubnodeConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.INIBuilderParameters;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Class to manage the settings of Ladik's MpqEditor.
*/
public class MpqEditorSettingsInterface implements DeepCopyable {
private static final String MPQEDITOR_RULESET_INI = "MPQEditor_Ruleset.ini";
private static final String CUSTOM_RULE_PROPERTY_KEY = "CustomRules. ";
private static final String MPQEDITOR_INI = "MPQEditor.ini";
private static final Logger logger = LoggerFactory.getLogger(MpqEditorSettingsInterface.class);
private static final String APPDATA = "APPDATA";
private static final String NO_COMPRESSION_CUSTOM_RULE = "0x01000000, 0x00000002, 0xFFFFFFFF";
private static final String DEFAULT = "Default";
private static final String MPQ_VERSION = "MpqVersion";
private static final String ATTR_FLAGS = "AttrFlags";
private static final String SECTOR_SIZE = "SectorSize";
private static final String RAW_CHUNK_SIZE = "RawChunkSize";
private static final String CUSTOM_RULES = "CustomRules";
private static final String SPACESPACEEQUALSSPACE = " = ";
private static final String GAME_ID = "GameId";
private static final String OPTIONS = "Options";
private static final String UTF_8 = "UTF-8";
private final Path iniFile;
private final Path rulesetFile;
private Path iniFileBackUp;
private Path rulesetFileBackUp;
private boolean backupActive;
private MpqEditorCompressionRule[] customRules;
private MpqEditorCompression compression = MpqEditorCompression.BLIZZARD_SC2_HEROES;
public MpqEditorSettingsInterface() {
iniFile = Path.of(System.getenv(APPDATA) + File.separator + MPQEDITOR_INI);
rulesetFile = Path.of(System.getenv(APPDATA) + File.separator + MPQEDITOR_RULESET_INI);
}
/**
* Restored the original settings files that were backed up.
*
* @throws IOException
*/
public void restoreOriginalSettingFiles() throws IOException {
if (!backupActive) {
return;
}
restoreFileFromBackUp(rulesetFileBackUp, rulesetFile);
rulesetFileBackUp = null;
restoreFileFromBackUp(iniFileBackUp, iniFile);
iniFileBackUp = null;
backupActive = false;
}
/**
* Restores a file that was backed up.
*
* @param backUpFileName
* @param originalFileName
* @throws IOException
*/
private static void restoreFileFromBackUp(final Path backUpFileName, final Path originalFileName)
throws IOException {
if (backUpFileName != null && Files.exists(backUpFileName)) {
if (Files.exists(originalFileName)) {
Files.delete(originalFileName);
}
Files.move(backUpFileName, originalFileName);
}
}
/**
* Returns the state of file backups.
*
* @return
*/
public boolean isBackupActive() {
return backupActive;
}
/**
* Returns the currently active compression method.
*
* @return
*/
public MpqEditorCompression getCompression() {
return compression;
}
/**
* Sets the compression method.
*
* @param compression
*/
public void setCompression(final MpqEditorCompression compression) {
this.compression = compression;
}
/**
* Applies the compression. Make sure to call <code>restoreOriginalSettingFiles()</code> afterwards to restore these
* files.
*/
public void applyCompression() throws IOException {
switch (compression) {
// custom, blizz & none use custom ruleset
case CUSTOM, BLIZZARD_SC2_HEROES, NONE:
backUpOriginalSettingsFiles();
applyChangesToFiles();
break;
case SYSTEM_DEFAULT:
break;
default:
throw new IOException("unknown compression setting");
}
}
/**
* Backs up the original settings files
*
* @throws IOException
*/
private void backUpOriginalSettingsFiles() throws IOException {
if (backupActive) {
return;
}
final Path directoryPath = iniFile.getParent();
int i = 0;
Path backupFile;
// ruleset file
if (Files.exists(rulesetFile)) {
do {
//noinspection ObjectAllocationInLoop
backupFile = directoryPath.resolve("MPQEditor_Ruleset_" + i + ".tmp");
++i;
if (i > 999) {
throw new IOException("Could not find unique name for MPQEditor_Ruleset.ini's backup copy.");
}
} while (Files.exists(backupFile));
Files.copy(rulesetFile, backupFile, StandardCopyOption.REPLACE_EXISTING);
rulesetFileBackUp = backupFile;
}
// ini file
if (Files.exists(iniFile)) {
i = 0;
do {
//noinspection ObjectAllocationInLoop
backupFile = directoryPath.resolve("MPQEditor_" + i + ".tmp");
++i;
if (i > 999) {
throw new IOException("Could not find unique name for MPQEditor.ini's backup copy.");
}
} while (Files.exists(backupFile));
Files.copy(iniFile, backupFile, StandardCopyOption.REPLACE_EXISTING);
iniFileBackUp = backupFile;
}
backupActive = true;
}
/**
* Applies the necessary changes to the ini files.
*/
private void applyChangesToFiles() throws IOException {
if (!Files.exists(iniFile)) {
logger.error(
"MpqEditor's ini file does not exist. It would be located at '{}'. The editor will run with its factory settings.",
iniFile.toAbsolutePath());
return;
}
int gameId = 6;
try {
final INIBuilderParameters params = new Parameters().ini().setFile(iniFile.toFile()).setEncoding(UTF_8);
final FileBasedConfigurationBuilder<INIConfiguration> b =
new FileBasedConfigurationBuilder<>(INIConfiguration.class).configure(params);
final INIConfiguration ini = b.getConfiguration();
final SubnodeConfiguration options = ini.getSection(OPTIONS);
gameId = getGameIdPropertyValue(compression);
options.setProperty(GAME_ID, gameId);
b.save();
} catch (final ConfigurationException e) {
logger.error("Error while applying custom ruleset usage entry.", e);
}
if (gameId == 13) {
writeMpqRuleset();
}
}
/**
* @param compression
* @return
*/
private static int getGameIdPropertyValue(final MpqEditorCompression compression) {
if (compression == MpqEditorCompression.BLIZZARD_SC2_HEROES) {
return 11;
}
return 13;
}
/**
*
*/
private void writeMpqRuleset() throws IOException {
INIConfiguration ini = null;
if (Files.exists(rulesetFile)) {
try {
final INIBuilderParameters params =
new Parameters().ini().setFile(rulesetFile.toFile()).setEncoding(UTF_8);
final FileBasedConfigurationBuilder<INIConfiguration> b =
new FileBasedConfigurationBuilder<>(INIConfiguration.class).configure(params);
ini = b.getConfiguration();
ini.clear();
} catch (final ConfigurationException e) {
logger.error("Error while editing custom ruleset file.", e);
ini = null;
}
}
if (ini == null) {
ini = new INIConfiguration();
}
final SubnodeConfiguration section = ini.getSection(CUSTOM_RULES);
section.setProperty(MPQ_VERSION, 3); // possible: 0,1,2,3 (higher has bigger header); sc2 maps use 3
// 1 adds longer archives, 2 adds replacement that is supposed to be more effective, 3 adds more like md5
section.setProperty(ATTR_FLAGS, 0); // default 5 "(attributes)" file becomes shorter, 0 = no file
// (Attributes) file is not required for at least Obs UI
section.setProperty(SECTOR_SIZE, 16_384); // default 16384, 1024-4096 made AhliObs bigger, SC2 maps use 16384
section.setProperty(RAW_CHUNK_SIZE, 0); // default 0
switch (compression) {
case CUSTOM:
if (customRules != null) {
for (final MpqEditorCompressionRule customRule : customRules) {
if (customRule != null) {
ini.addProperty(CUSTOM_RULE_PROPERTY_KEY, customRule.toString());
} else {
throw new IllegalArgumentException(
"Compression Rules in MpqEditorSettingsInterface has null entry");
}
}
} else {
section.addProperty(DEFAULT, NO_COMPRESSION_CUSTOM_RULE);
}
break;
case NONE:
section.addProperty(DEFAULT, NO_COMPRESSION_CUSTOM_RULE);
break;
case SYSTEM_DEFAULT, BLIZZARD_SC2_HEROES:
default:
break;
}
try (final BufferedWriter bw = Files.newBufferedWriter(rulesetFile)) {
ini.write(bw);
} catch (final ConfigurationException | IOException e) {
throw new IOException("Could not write '" + rulesetFile.toAbsolutePath() + "'.", e);
}
// remove custom ruleset line beginnings
if (compression == MpqEditorCompression.CUSTOM) {
final List<String> editedLines;
try (final Stream<String> lineStream = Files.lines(rulesetFile)) {
editedLines =
lineStream.map(line -> line.replace(SPACESPACEEQUALSSPACE, "")).collect(Collectors.toList());
}
try (final BufferedWriter bw = Files.newBufferedWriter(rulesetFile)) {
final String separator = System.lineSeparator();
for (final String line : editedLines) {
bw.write(line);
bw.write(separator);
}
}
}
}
/**
* Returns the ruleset array used by this class.
*
* @return
*/
public MpqEditorCompressionRule[] getCustomRuleSet() {
return customRules;
}
/**
* @param customRules
*/
public void setCustomRules(final MpqEditorCompressionRule... customRules) {
this.customRules = customRules;
}
@Override
public Object deepCopy() {
final MpqEditorSettingsInterface clone = new MpqEditorSettingsInterface();
if (customRules != null) {
clone.customRules = new MpqEditorCompressionRule[customRules.length];
for (int i = 0, len = customRules.length; i < len; ++i) {
customRules[i] = customRules[i] == null ? null : (MpqEditorCompressionRule) customRules[i].deepCopy();
}
}
clone.compression = compression;
clone.iniFileBackUp = iniFileBackUp;
clone.rulesetFileBackUp = rulesetFileBackUp;
clone.backupActive = backupActive;
return clone;
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.compile;
import com.ahli.galaxy.ModData;
import com.ahli.galaxy.archive.DescIndexData;
import com.ahli.galaxy.game.GameDef;
import com.ahli.galaxy.parser.DeduplicationIntensity;
import com.ahli.galaxy.parser.UICatalogParser;
import com.ahli.galaxy.parser.XmlParserVtd;
import com.ahli.galaxy.ui.interfaces.UICatalog;
import com.ahli.util.XmlDomHelper;
import interfacebuilder.compress.GameService;
import interfacebuilder.projects.enums.Game;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* Compiles MPQ stuff.
*
* @author Ahli
*/
public class CompileService {
private static final Logger logger = LogManager.getLogger(CompileService.class);
private final GameService gameService;
public CompileService(final GameService gameService) {
this.gameService = gameService;
}
/**
* Compiles and updates the data in the cache.
*
* @param mod
* the mod
* @param raceId
* the raceId used
* @param repairLayoutOrder
* @param verifyLayout
* @param verifyXml
* @return UICatalog describing the UI when verifyLayout was enabled; else null
* @throws InterruptedException
*/
public UICatalog compile(
final ModData mod,
final String raceId,
final boolean repairLayoutOrder,
final boolean verifyLayout,
final boolean verifyXml,
final String consoleSkinId) throws InterruptedException {
UICatalog catalogClone = null;
try {
long startTime;
long executionTime;
// manage descIndexData
final DescIndexData descIndex = mod.getDescIndexData();
if (repairLayoutOrder) {
startTime = System.currentTimeMillis();
manageOrderOfLayoutFiles(descIndex);
executionTime = (System.currentTimeMillis() - startTime);
logger.info("Checking and repairing the Layout order took {}ms.", executionTime);
}
if (verifyLayout) {
startTime = System.currentTimeMillis();
// validate catalog
catalogClone = getClonedUICatalog(mod.getGameData().getUiCatalog());
executionTime = (System.currentTimeMillis() - startTime);
logger.info("BaseUI Cloning took {}ms.", executionTime);
startTime = System.currentTimeMillis();
if (catalogClone == null) {
return null;
}
catalogClone.setParser(new UICatalogParser(catalogClone,
new XmlParserVtd(),
DeduplicationIntensity.SIMPLE));
// apply mod's UI
final File descIndexFile = new File(
mod.getMpqCacheDirectory() + File.separator + mod.getDescIndexData().getDescIndexIntPath());
catalogClone.processDescIndex(descIndexFile, raceId, consoleSkinId);
catalogClone.postProcessParsing();
catalogClone.setParser(null);
executionTime = (System.currentTimeMillis() - startTime);
logger.info("Validating Layouts took {}ms.", executionTime);
} else {
if (!repairLayoutOrder && verifyXml) {
// only verify XML and nothing else
final DocumentBuilder dBuilder = XmlDomHelper.buildSecureDocumentBuilder(true, false);
final GameDef sc2GameDef = gameService.getGameDef(Game.SC2);
final GameDef heroesGameDef = gameService.getGameDef(Game.HEROES);
final String[] extensions = { heroesGameDef.layoutFileEnding(), sc2GameDef.layoutFileEnding(),
heroesGameDef.componentsFileEnding(), sc2GameDef.componentsFileEnding(),
heroesGameDef.cutsceneFileEnding(), sc2GameDef.cutsceneFileEnding(),
heroesGameDef.styleFileEnding(), sc2GameDef.styleFileEnding(), "xml" };
final FileVisitor<Path> visitor = new XmlVerifier(dBuilder, extensions);
Files.walkFileTree(mod.getMpqCacheDirectory(), visitor);
}
}
} catch (final ParserConfigurationException | SAXException | IOException e) {
logger.error("ERROR: encountered error while compiling.", e);
}
return catalogClone;
}
/**
* Creates a correct ordering of the layout files based on their internal dependencies.
*
* @param descIndex
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
private static void manageOrderOfLayoutFiles(final DescIndexData descIndex)
throws ParserConfigurationException, SAXException, IOException {
// manage order of layout files in DescIndex
descIndex.orderLayoutFiles();
descIndex.persistDescIndexFile();
}
/**
* Clones the specified UICatalog.
*
* @param uiCatalog
* @return clone of the CatalogUI
*/
private static UICatalog getClonedUICatalog(final UICatalog uiCatalog) {
return uiCatalog != null ? (UICatalog) uiCatalog.deepCopy() : null;
}
private static final class XmlVerifier extends SimpleFileVisitor<Path> {
private final DocumentBuilder dBuilder;
private final String[] extensions;
private XmlVerifier(final DocumentBuilder dBuilder, final String[] extensions) {
this.dBuilder = dBuilder;
this.extensions = extensions;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
final String fileName = file.getFileName().toString();
final int i = fileName.lastIndexOf('.');
if (i >= 0) {
final String curExt = fileName.substring(i + 1);
boolean found = false;
for (final String ext : extensions) {
if (ext.equalsIgnoreCase(curExt)) {
found = true;
break;
}
}
if (found) {
try (final InputStream is = new BufferedInputStream(Files.newInputStream(file))) {
dBuilder.parse(is);
} catch (final SAXException e) {
logger.trace("Error while verifying XML.", e);
throw new IOException("XML verification failed.", e);
}
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
logger.error("Failed to access file: {}", file);
throw exc;
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.home;
import interfacebuilder.compress.GameService;
import interfacebuilder.i18n.Messages;
import interfacebuilder.integration.FileService;
import interfacebuilder.projects.Project;
import interfacebuilder.projects.ProjectService;
import interfacebuilder.ui.FXMLSpringLoader;
import interfacebuilder.ui.Updateable;
import interfacebuilder.ui.navigation.NavigationController;
import interfacebuilder.ui.progress.CompressionMiningController;
import interfacebuilder.ui.progress.TabPaneController;
import javafx.beans.InvalidationListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.Window;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
public class HomeController implements Updateable {
private static final Logger logger = LogManager.getLogger(HomeController.class);
private final ApplicationContext appContext;
private final ProjectService projectService;
private final FileService fileService;
private final GameService gameService;
private final TabPaneController tabPaneController;
private final NavigationController navigationController;
@FXML
private Pane selectedPanel;
@FXML
private Label selectedName;
@FXML
private ImageView selectedImage;
@FXML
private Label selectedPath;
@FXML
private Label selectedDirSize;
@FXML
private Label selectedDirFiles;
@FXML
private Label selectedBuildDate;
@FXML
private Label selectedBuildSize;
@FXML
private Button newProject;
@FXML
private Button addProject;
@FXML
private ListView<Project> selectionList;
@FXML
private Button removeProject;
@FXML
private Button editProject;
@FXML
private Button buildSelection;
private ObservableList<Project> projectsObservable;
public HomeController(
final ApplicationContext appContext,
final ProjectService projectService,
final FileService fileService,
final GameService gameService,
final TabPaneController tabPaneController,
final NavigationController navigationController) {
this.appContext = appContext;
this.projectService = projectService;
this.fileService = fileService;
this.gameService = gameService;
this.tabPaneController = tabPaneController;
this.navigationController = navigationController;
}
/**
* Automatically called by FxmlLoader
*/
@SuppressWarnings("java:S1905") // unnecessary cast warning (cast is necessary here)
public void initialize() {
// grab list of projects per game
projectsObservable = FXCollections.observableList(projectService.getAllProjects());
selectionList.setItems(projectsObservable);
selectionList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
selectionList.setCellFactory(listViewProject -> new ListCell<>() {
@Override
protected void updateItem(final Project project, final boolean empty) {
super.updateItem(project, empty);
if (empty || project == null) {
setText(null);
setGraphic(null);
} else {
setText(project.getName());
try {
setGraphic(getListItemGameImage(project));
} catch (final IOException e) {
logger.error("Failed to find image resource.", e);
}
}
}
});
selectionList.getSelectionModel().selectAll();
selectionList.getSelectionModel()
.getSelectedItems()
.addListener((InvalidationListener) observable -> updateSelectedDetailsPanel());
}
/**
* Returns an image reflecting the game with proper size for the project list.
*
* @param project
* @return
* @throws IOException
*/
private ImageView getListItemGameImage(final Project project) throws IOException {
final ImageView iv = new ImageView(getResourceAsUrl(gameService.getGameItemPath(project.getGame())).toString());
iv.setFitHeight(32);
iv.setFitWidth(32);
return iv;
}
/**
* Updates the panel showing info about the selected projects.
*/
private void updateSelectedDetailsPanel() {
final ObservableList<Project> selectedItems = selectionList.getSelectionModel().getSelectedItems();
if (selectedItems.size() == 1) {
selectedPanel.setVisible(true);
final Project p = selectedItems.get(0);
selectedName.setText(p.getName());
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
selectedBuildDate.setText(
p.getLastBuildDateTime() == null ? "-" : p.getLastBuildDateTime().format(formatter));
selectedBuildSize.setText(
p.getLastBuildSize() == 0 ? "-" : (String.format("%,d", p.getLastBuildSize() / 1024) + " kb"));
try {
final Path path = Path.of(p.getProjectPath());
selectedDirFiles.setText(String.format("%,d", fileService.getFileCountOfDirectory(path)) + " files");
selectedDirSize.setText(String.format("%,d", fileService.getDirectorySize(path) / 1024) + " kb");
} catch (final IOException e) {
selectedDirSize.setText("-");
selectedDirFiles.setText("-");
logger.trace("Error updating selected details panel.", e);
}
selectedPath.setText(p.getProjectPath());
try {
selectedImage.setImage(new Image(getResourceAsUrl(gameService.getGameItemPath(p.getGame())).toString()));
} catch (final IOException e) {
logger.error("Failed to load image from project's game setting.", e);
}
} else {
selectedPanel.setVisible(false);
}
}
/**
* Returns a resource as a URL.
*
* @param path
* @return
* @throws IOException
*/
private URL getResourceAsUrl(final String path) throws IOException {
return appContext.getResource(path).getURL();
}
@Override
public void update() {
updateSelectedDetailsPanel();
}
/**
* Add a Project to the list.
*
* @throws IOException
*/
public void addProjectAction() throws IOException {
final FXMLSpringLoader loader = new FXMLSpringLoader(appContext);
final Dialog<Project> dialog = loader.load("classpath:view/Home_AddProjectDialog.fxml");
dialog.initOwner(addProject.getScene().getWindow());
final Optional<Project> result = dialog.showAndWait();
if (result.isPresent()) {
logger.trace("dialog 'add project' result: {}", result::get);
projectsObservable.add(result.get());
}
}
/**
* Create a new Project from a template and add it to the list.
*
* @throws IOException
*/
public void newProjectAction() throws IOException {
final FXMLSpringLoader loader = new FXMLSpringLoader(appContext);
final Dialog<Project> dialog = loader.load("classpath:view/Home_NewProjectDialog.fxml");
dialog.initOwner(newProject.getScene().getWindow());
final Optional<Project> result = dialog.showAndWait();
if (result.isPresent()) {
logger.trace("dialog 'new project' result: {}", result::get);
projectsObservable.add(result.get());
}
}
/**
* Edit a single selected project.
*
* @throws IOException
*/
public void editProjectAction() throws IOException {
final List<Project> projects = selectionList.getSelectionModel().getSelectedItems();
if (projects.size() == 1) {
final Project project = projects.get(0);
final FXMLSpringLoader loader = new FXMLSpringLoader(appContext);
final Dialog<Project> dialog = loader.load("classpath:view/Home_AddProjectDialog.fxml");
dialog.initOwner(addProject.getScene().getWindow());
((AddProjectDialogController) loader.getController()).getContentController().setProjectToEdit(project);
final Optional<Project> result = dialog.showAndWait();
if (result.isPresent()) {
logger.trace("dialog 'edit project' result: {}", result::get);
updateProjectList();
}
}
}
/**
* Update the project list to reflect name/game changes.
*/
private void updateProjectList() {
final MultipleSelectionModel<Project> selectionModel = selectionList.getSelectionModel();
final Object[] selectedIndices = selectionModel.getSelectedIndices().toArray();
selectionModel.clearSelection();
for (final Object i : selectedIndices) {
selectionModel.select((int) i);
}
}
/**
* Builds the selected projects.
*/
public void buildSelectedAction() {
final List<Project> selectedItems = selectionList.getSelectionModel().getSelectedItems();
if (!selectedItems.isEmpty()) {
navigationController.clickProgress();
projectService.build(selectedItems, false);
}
}
/**
* Removes the selected projects.
*/
public void removeSelectedAction() {
final List<Project> selectedItems = selectionList.getSelectionModel().getSelectedItems();
if (!selectedItems.isEmpty()) {
final Project[] items = selectedItems.toArray(new Project[selectedItems.size()]);
final Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.initOwner(getWindow());
if (selectedItems.size() > 1) {
alert.setTitle(String.format("Remove selected Projects from list? - %s items selected",
selectedItems.size()));
} else {
alert.setTitle("Remove selected Project from list? - 1 item selected");
}
alert.setHeaderText("""
Are you sure you want to remove the selected projects?
This will not remove any files from the project.
""");
final Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK) {
for (final Project p : items) {
projectService.deleteProject(p);
projectsObservable.remove(p);
}
}
}
}
/**
* Returns this UI's window.
*
* @return
*/
public Window getWindow() {
return selectionList.getScene().getWindow();
}
/**
* Action to view the best compression ruleset for the selected project.
*
* @throws IOException
*/
public void viewBestCompressionForSelected() throws IOException {
final List<Project> selectedItems = selectionList.getSelectionModel().getSelectedItems();
if (selectedItems.size() == 1) {
final Project project = selectedItems.get(0);
final FXMLSpringLoader loader = new FXMLSpringLoader(appContext);
final Dialog<Project> dialog = loader.load("classpath:view/Home_ViewRuleSet.fxml");
((ViewRuleSetController) loader.getController()).setProject(project);
dialog.initOwner(addProject.getScene().getWindow());
dialog.showAndWait();
}
}
/**
* Action to mine a better compression for the selected project.
*/
public void mineBetterCompressionForSelected() throws IOException {
final List<Project> selectedItems = selectionList.getSelectionModel().getSelectedItems();
if (selectedItems.size() == 1) {
final Project project = selectedItems.get(0);
// init UI as Tab in Progress
final FXMLSpringLoader loader = new FXMLSpringLoader(appContext);
final Parent content = loader.load("classpath:view/Progress_CompressionMining.fxml");
final String tabName = String.format("%s Compression Mining", project.getName());
final TabPane tabPane = tabPaneController.getTabPane();
final ObservableList<Tab> tabs = tabPane.getTabs();
Tab newTab = null;
// re-use existing tab with that name
for (final Tab tab : tabs) {
if (tab.getText().equals(tabName)) {
newTab = tab;
break;
}
}
if (newTab == null) {
// CASE: new tab
newTab = new Tab(tabName, content);
final CompressionMiningController controller = loader.getController();
// context menu with close option
final ContextMenu contextMenu = new ContextMenu();
final MenuItem closeItem = new MenuItem(Messages.getString("contextmenu.close"));
closeItem.setOnAction(new CloseMiningTabAction(newTab, controller));
contextMenu.getItems().addAll(closeItem);
newTab.setContextMenu(contextMenu);
tabs.add(newTab);
controller.setProject(project);
// switch to progress and the new tab
navigationController.clickProgress();
tabPane.getSelectionModel().select(newTab);
// start mining
controller.startMining();
} else {
// CASE: recycle existing Tab
// switch to progress and the new tab
navigationController.clickProgress();
tabPane.getSelectionModel().select(newTab);
}
}
}
private static final class CloseMiningTabAction implements EventHandler<ActionEvent> {
private final Tab tab;
private final CompressionMiningController controller;
private CloseMiningTabAction(final Tab tab, final CompressionMiningController controller) {
this.tab = tab;
this.controller = controller;
}
@Override
public void handle(final ActionEvent event) {
tab.getTabPane().getTabs().remove(tab);
tab.setContextMenu(null);
controller.stopMining();
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.home;
import com.ahli.mpq.mpqeditor.MpqEditorCompressionRule;
import com.ahli.mpq.mpqeditor.MpqEditorCompressionRuleMask;
import com.ahli.mpq.mpqeditor.MpqEditorCompressionRuleSize;
import interfacebuilder.compress.RuleSet;
import interfacebuilder.projects.Project;
import interfacebuilder.projects.ProjectService;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.io.IOException;
public class ViewRuleSetController {
private final ProjectService projectService;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnMarkedForDeletion;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnIncludeSectorChecksum;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnEncryptAdjusted;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnEncrypt;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnCompress;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnSingleFile;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnCompressionAlgo;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnMaskSize;
@FXML
private TableColumn<MpqEditorCompressionRule, String> columnType;
@FXML
private TableView<MpqEditorCompressionRule> ruleSetTable;
@FXML
private Dialog<Void> dialog;
public ViewRuleSetController(final ProjectService projectService) {
this.projectService = projectService;
}
/**
* Automatically called by FxmlLoader
*/
public void initialize() {
final DialogPane dialogPane = dialog.getDialogPane();
dialogPane.getButtonTypes().addAll(ButtonType.OK);
columnCompress.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue()
.isCompress()).asString());
columnEncrypt.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue()
.isEncrypt()).asString());
columnEncryptAdjusted.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue()
.isEncryptAdjusted()).asString());
columnIncludeSectorChecksum.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue()
.isIncludeSectorChecksum()).asString());
columnMarkedForDeletion.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue()
.isMarkedForDeletion()).asString());
columnSingleFile.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue()
.isSingleUnit()).asString());
columnMaskSize.setCellValueFactory(cellData -> {
final MpqEditorCompressionRule rule = cellData.getValue();
if (rule instanceof final MpqEditorCompressionRuleMask ruleMask) {
return new SimpleStringProperty(ruleMask.getMask());
} else if (rule instanceof final MpqEditorCompressionRuleSize ruleSize) {
return new SimpleStringProperty(ruleSize.getMinSize() + " - " + ruleSize.getMaxSize());
} else {
return new SimpleStringProperty("");
}
});
columnCompressionAlgo.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue()
.getCompressionMethod()
.toString()));
columnType.setCellValueFactory(cellData -> {
final MpqEditorCompressionRule rule = cellData.getValue();
if (rule instanceof MpqEditorCompressionRuleMask) {
return new SimpleStringProperty("Mask");
} else if (rule instanceof MpqEditorCompressionRuleSize) {
return new SimpleStringProperty("Size");
} else {
return new SimpleStringProperty("Default");
}
});
}
/**
* Inject a project whose best compression ruleset is shown.
*
* @param project
*/
public void setProject(final Project project) throws IOException {
dialog.setTitle(String.format("Best Compression Ruleset for %s", project.getName()));
showProjectsRuleSet(project);
}
/**
* Shows the compression ruleset of a specified project.
*
* @param project
*/
public void showProjectsRuleSet(final Project project) throws IOException {
final ObservableList<MpqEditorCompressionRule> ruleSetObservableItems = FXCollections.observableArrayList();
final RuleSet bestCompressionRuleSet = projectService.fetchBestCompressionRuleSet(project);
if (bestCompressionRuleSet != null) {
final MpqEditorCompressionRule[] rules = bestCompressionRuleSet.getCompressionRules();
if (rules != null) {
ruleSetObservableItems.setAll(rules);
}
}
ruleSetTable.setItems(ruleSetObservableItems);
ruleSetTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// columns are properly resized for content, if no prefWidth was defined!
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.hotkey_ui.application.model;
public enum ValueType {
TEXT, BOOLEAN, NUMBER
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.util;
import org.junit.jupiter.api.Test;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
final class StringInternerTest {
@SuppressWarnings("UnusedAssignment")
@Test
void testWeakRefStringInterner() {
@SuppressWarnings("UnsecureRandomNumberGeneration")
final double value = Math.random();
final String text = "HELLO WORLD! ";
String firstToBeInterned = text + value;
// first intern
String firstInterned = StringInterner.intern(firstToBeInterned);
assertSame(firstInterned, firstToBeInterned, "first interned received different reference");
// second intern
final String secondToBeInterned = text + value;
assertNotSame(
firstToBeInterned,
secondToBeInterned,
"first and second interned are same reference - VM is breaking this test with optimizations");
String secondInterned = StringInterner.intern(secondToBeInterned);
assertEquals(secondInterned, firstInterned, "second interned changed value during interning - first vs second");
assertEquals(
secondInterned,
secondToBeInterned,
"second interned changed value during interning - second input vs output");
assertNotSame(secondInterned, secondToBeInterned, "second interned delivered same reference back");
assertSame(firstInterned, secondInterned, "first interned received different reference");
// test garbage collection
final var referenceQueue = new ReferenceQueue<String>();
@SuppressWarnings("unused")
final var weakRef = new WeakReference<>(firstInterned, referenceQueue);
firstToBeInterned = null;
firstInterned = null;
secondInterned = null;
int i = 0;
final int maxAttempts = 3;
while (referenceQueue.poll() == null && i < maxAttempts) {
++i;
System.gc();
System.runFinalization();
}
// fails on J9 JDK
assertTrue(i < maxAttempts, "GC did not remove the WeakReference within " + maxAttempts + " attempts");
}
}<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.archive;
import com.ahli.galaxy.game.GameDef;
import com.ahli.util.XmlDomHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Reads the Components List file within the MPQ Archive.
*
* @author Ahli
*/
public final class ComponentsListReaderDom {
private static final String TYPE = "Type";
private static final String DATA_COMPONENT = "DataComponent";
private static final String UIUI = "uiui";
private static final Logger logger = LoggerFactory.getLogger(ComponentsListReaderDom.class);
/**
*
*/
private ComponentsListReaderDom() {
}
/**
* Returns the internal path of DescIndex of the mpq file.
*
* @param compListFile
* components list file
* @return
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static String getDescIndexPath(final Path compListFile, final GameDef game)
throws ParserConfigurationException, SAXException, IOException {
final String str = game.baseDataFolderName() + File.separator + getComponentsListValue(compListFile, UIUI);
logger.trace("DescIndexPath: {}", str);
return str;
}
/**
* Returns the path information of a given type value, e.g. "uiui" or "font". Locales are not supported here.
*
* @param compListFile
* components list file
* @param typeVal
* value of the type, e.g. "uiui"
* @return path information of the specified type value
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static String getComponentsListValue(final Path compListFile, final String typeVal)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilder dBuilder = XmlDomHelper.buildSecureDocumentBuilder(false, true);
final Document doc = dBuilder.parse(compListFile.toString());
// must be in a DataComponent node
final NodeList nodeList = doc.getElementsByTagName(DATA_COMPONENT);
for (int i = 0, len = nodeList.getLength(); i < len; ++i) {
final Node node = nodeList.item(i);
final Node attrZero = node.getAttributes().item(0);
// first attribute's name is Type & value must be as specified
if (TYPE.equals(attrZero.getNodeName()) && attrZero.getNodeValue().equals(typeVal)) {
// the text is the value between the tags
return node.getTextContent();
}
}
return null;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.ahli</groupId>
<artifactId>interface-builder</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>InterfaceBuilder</name>
<description>Application to build Observer Interface files for StarCraft II and Heroes of the Storm.</description>
<!-- for IntelliJ's configuration: add to VM options: -->
<!-- - a fix for JavaFX's poor extensibility to add filter possibility to TreeItem via reflection; remove the # -->
<!-- -#-add-opens=javafx.controls/javafx.scene.control=interfacex.builder -->
<!-- -#-illegal-access=permit -->
<!--
goals:
- list all dependencies:
compile org.apache.maven.plugins:maven-dependency-plugin:3.2.0:resolve
-->
<parent>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.0-M2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>16</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<jarName>compile</jarName>
<mainClass>interfacebuilder.SpringBootApplication</mainClass>
<!-- override spring versions -->
<lombok.version>1.18.20</lombok.version>
<byte-buddy.version>1.11.13</byte-buddy.version>
<jakarta-xml-bind.version>2.3.3</jakarta-xml-bind.version><!-- 2.3.3 -> 3.0.0 -->
<jakarta-transaction.version>1.3.3</jakarta-transaction.version><!-- 1.3.3 -> 2.0.0 -->
<jakarta-persistence.version>2.2.3</jakarta-persistence.version><!-- 2.2.3 -> 3.0.0 -->
<jakarta-annotation.version>2.0.0</jakarta-annotation.version>
<jakarta-activation.version>2.0.1</jakarta-activation.version>
<glassfish-jaxb.version>3.0.2</glassfish-jaxb.version>
<hibernate.version>5.5.6.Final</hibernate.version><!-- 5.4.28.Final -> 6.0.0.Alpha6;
still depends on javax.persistence -->
<hibernate-validator.version>6.2.0.Final</hibernate-validator.version>
<h2.version>1.4.200</h2.version>
<junit-jupiter.version>5.8.0-RC1</junit-jupiter.version>
<slf4j.version>1.7.32</slf4j.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<hikaricp.version>5.0.0</hikaricp.version>
<jboss-logging.version>3.4.2.Final</jboss-logging.version>
<aspectj.version>1.9.7</aspectj.version>
<mockito.version>3.12.1</mockito.version>
<!-- local versions -->
<mockito-junit-jupiter.version>3.11.2</mockito-junit-jupiter.version>
<javafx.version>18-ea+1</javafx.version>
<kryo.version>5.2.0</kryo.version>
<pecoff4j.version>0.3.2</pecoff4j.version>
<asm.version>9.2</asm.version>
<log4j2.version>2.14.1</log4j2.version>
<lmax-disruptor.version>3.4.4</lmax-disruptor.version>
<fontawesomefx-fontawesome.version>4.7.0-9.1.2</fontawesomefx-fontawesome.version>
<fontawesomefx-commons.version>9.1.2</fontawesomefx-commons.version>
<eclipse-collection.version>10.4.0</eclipse-collection.version>
<commons-io.version>2.11.0</commons-io.version>
<commons-text.version>1.9</commons-text.version>
<equalsverifier.version>3.7.1</equalsverifier.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<!-- exclude junit4 as junit5 is used -->
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<!-- exclude junit4 as junit5 is used -->
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
<!-- exclusions to make module-info happy -->
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-jcl</artifactId>
</exclusion>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-bom</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<!-- Exclude Spring Boot's Default Logging to use log4j instead -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
<!-- remove dependencies that are not required -->
<exclusion>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Add Log4j2 Dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- Spring Development helpers
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>runtime</scope>
</dependency> -->
<!-- Spring Actuator for Debugging
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> -->
<!-- Spring's package with jpa, hibernate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>com.sun.activation</groupId>
<artifactId>jakarta.activation</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>${jakarta-xml-bind.version}</version>
</dependency>-->
<!-- indexer for spring component scan -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<optional>true</optional>
</dependency>
<!-- file IO -->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- log4j2 -->
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!-- async logging in log4j -->
<!-- https://mvnrepository.com/artifact/com.lmax/disruptor -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${lmax-disruptor.version}</version>
</dependency>
<!-- dependency to GalaxyLib -->
<dependency>
<groupId>io.github.ahli</groupId>
<artifactId>galaxy-lib</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!-- JavaFX Font Awesome -->
<!-- https://mvnrepository.com/artifact/de.jensd/fontawesomefx-fontawesome -->
<dependency>
<groupId>de.jensd</groupId>
<artifactId>fontawesomefx-fontawesome</artifactId>
<version>${fontawesomefx-fontawesome.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/de.jensd/fontawesomefx-commons -->
<dependency>
<groupId>de.jensd</groupId>
<artifactId>fontawesomefx-commons</artifactId>
<version>${fontawesomefx-commons.version}</version>
</dependency>
<!-- Embedded DB -->
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Mockito to assist unit tests with fake-environments like fake DB info -->
<dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter -->
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito-junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
<version>${equalsverifier.version}</version>
<scope>test</scope>
</dependency>
<!-- JDK11 JavaFX -->
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-graphics -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-base -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-fxml -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-media -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>${javafx.version}</version>
</dependency>
<!-- serialization -->
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>${kryo.version}</version>
</dependency>
<!-- high performance collections -->
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections-api</artifactId>
<version>${eclipse-collection.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collection.version}</version>
</dependency>
<!-- read version from exe file -->
<!-- https://mvnrepository.com/artifact/com.kichik.pecoff4j/pecoff4j -->
<dependency>
<groupId>com.kichik.pecoff4j</groupId>
<artifactId>pecoff4j</artifactId>
<version>${pecoff4j.version}</version>
</dependency>
<!-- less boilerplate code -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/eu.mihosoft.jfx.scaledfx/scaledfx -->
<dependency>
<groupId>eu.mihosoft.jfx.scaledfx</groupId>
<artifactId>scaledfx</artifactId>
<version>0.6</version>
<exclusions>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
</exclusion>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
</exclusion>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
</exclusion>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- TO UPDATE DEPENDENCIES within other dependencies -->
<!-- https://mvnrepository.com/artifact/org.jboss/jandex -->
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.3.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.28.0-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.objenesis/objenesis for kryo & mockito -->
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.esotericsoftware/reflectasm -->
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>reflectasm</artifactId>
<version>1.11.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.istack/istack-commons-runtime for hibernate core -> jaxb-runtime
-->
<dependency>
<groupId>com.sun.istack</groupId>
<artifactId>istack-commons-runtime</artifactId>
<version>4.1.0-M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j for hibernate core -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<!-- update dependency within configuration2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<!-- name of the generated jar -->
<finalName>${jarName}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.0-M2</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<!--<finalName>${jarName}</finalName>-->
<layout>JAR</layout>
<classifier>spring-boot</classifier>
<mainClass>${mainClass}</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<release>${java.version}</release>
<excludes>
<!-- excludes files from being put into same path as classes -->
<exclude>**/*.txt</exclude>
</excludes>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
<!--<compilerArgs>-->
<!-- when testing java preview features -->
<!----enable-preview-->
<!--</compilerArgs>-->
<annotationProcessorPaths>
<path>
<!-- Creates .dat file for log4j custom appenders -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<compilerArg>-Xlint:all</compilerArg>
</compilerArgs>
</configuration>
<dependencies>
<dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>log4j-plugin-processor</id>
<goals>
<goal>compile</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<proc>only</proc>
<annotationProcessors>
<annotationProcessor>
org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor
</annotationProcessor>
</annotationProcessors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-jar-plugin -->
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifestEntries>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-site-plugin -->
<artifactId>maven-site-plugin</artifactId>
<version>3.9.1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-deploy-plugin -->
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-install-plugin -->
<artifactId>maven-install-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<!--<argLine>--enable-preview</argLine>-->
</configuration>
<dependencies>
<dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin -->
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-clean-plugin -->
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- Force requirement of Maven version 3.0+ -->
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-enforcer-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>[3.1.1,)</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${mainClass}</mainClass>
</configuration>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin -->
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-release-plugin -->
<artifactId>maven-release-plugin</artifactId>
<version>3.0.0-M4</version>
</plugin>
<!-- goal to execute to check for plugins and dependency updates:
versions:display-plugin-updates versions:display-parent-updates versions:display-dependency-updates versions:display-property-updates
-->
<!-- https://mvnrepository.com/artifact/org.codehaus.mojo/versions-maven-plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.8.1</version>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>6.2.2</version>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<failOnError>false</failOnError>
<assemblyAnalyzerEnabled>false</assemblyAnalyzerEnabled>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<!--<repository>-->
<!--<id>spring-snapshots</id>-->
<!--<name>Spring Snapshots</name>-->
<!--<url>https://repo.spring.io/snapshot</url>-->
<!--<snapshots>-->
<!--<enabled>true</enabled>-->
<!--</snapshots>-->
<!--</repository>-->
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<!--<repository>
<id>mockito-repository</id>
<name>Mockito Repository</name>
<url>https://dl.bintray.com/mockito/maven/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>-->
<!-- Kryo snapshot repository -->
<repository>
<id>sonatype-snapshots</id>
<name>sonatype snapshots repo</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
<pluginRepositories>
<!--<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>-->
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</pluginRepository>
</pluginRepositories>
</project>
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.integration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
final class CommandLineParametersTest {
@Test
void testStringParamCompileRun() {
// TODO improve test with freshly created directory
final CommandLineParams param = new CommandLineParams(
true,
"--compileRun=D:\\Galaxy-Observer-UI\\dev\\heroes\\AhliObs.StormInterface\\Base.StormData\\UI\\Layout");
assertEquals(
"D:\\Galaxy-Observer-UI\\dev\\heroes\\AhliObs.StormInterface",
param.getParamCompilePath(),
"compileRun's path is wrong");
assertTrue(param.isHasParamCompilePath(), "hasParamCompilePath is wrong");
assertNull(param.getParamRunPath(), "run path wrongfully set when command is: --compileRun");
}
@Test
void testStringParamCompile() {
// TODO improve test with freshly created directory
final CommandLineParams param = new CommandLineParams(
true,
"--compile=D:\\Galaxy-Observer-UI\\dev\\heroes\\AhliObs.StormInterface\\Base.StormData\\UI\\Layout");
assertEquals(
"D:\\Galaxy-Observer-UI\\dev\\heroes\\AhliObs.StormInterface",
param.getParamCompilePath(),
"compile's path is wrong");
assertTrue(param.isHasParamCompilePath(), "hasParamCompilePath is wrong");
assertNull(param.getParamRunPath(), "run path wrongfully set when command is: --compile");
}
@Test
void testStringParamRun() {
// TODO improve test with freshly created directory
final CommandLineParams param = new CommandLineParams(true, "--run=D:\\Path\\To\\Some\\replayFile.SC2Replay");
assertEquals("D:\\Path\\To\\Some\\replayFile.SC2Replay", param.getParamRunPath(), "run's path is wrong");
assertFalse(param.isHasParamCompilePath(), "hasParamCompilePath is wrong");
assertNull(param.getParamCompilePath(), "compile path wrongfully set when command is: --run");
}
@Test
void testStringEmpty() {
final CommandLineParams param = new CommandLineParams(true, "");
assertNull(param.getParamRunPath(), "run's path is wrong");
assertFalse(param.isHasParamCompilePath(), "hasParamCompilePath is wrong");
assertNull(param.getParamCompilePath(), "compile path is wrong");
}
// TODO test with the named params map, too
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.settings;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import interfacebuilder.config.ConfigService;
import interfacebuilder.integration.FileService;
import interfacebuilder.integration.SettingsIniInterface;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.stage.DirectoryChooser;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
public class SettingsGamesPathsController extends SettingsAutoSaveController {
public static final String HEROES_SWITCHER_EXE = "HeroesSwitcher.exe";
public static final String SC2_SWITCHER_EXE = "SC2Switcher.exe";
@FXML
private TextField sc2Path;
@FXML
private CheckBox sc2Architecture;
@FXML
private TextField heroesPath;
@FXML
private TextField heroesPtrPath;
@FXML
private Label sc2PathLabel;
@FXML
private Label heroesPathLabel;
@FXML
private Label heroesPtrPathLabel;
@Autowired
private FileService fileService;
public SettingsGamesPathsController(final ConfigService configService) {
super(configService);
}
/**
* Automatically called by FxmlLoader
*/
@Override
public void initialize() {
super.initialize();
sc2PathLabel.setTextFill(Color.YELLOW);
heroesPathLabel.setTextFill(Color.YELLOW);
heroesPtrPathLabel.setTextFill(Color.YELLOW);
FontAwesomeIconView icon = new FontAwesomeIconView(FontAwesomeIcon.EXCLAMATION_TRIANGLE);
icon.setFill(Color.YELLOW);
sc2PathLabel.setGraphic(icon);
icon = new FontAwesomeIconView(FontAwesomeIcon.EXCLAMATION_TRIANGLE);
icon.setFill(Color.YELLOW);
heroesPathLabel.setGraphic(icon);
icon = new FontAwesomeIconView(FontAwesomeIcon.EXCLAMATION_TRIANGLE);
icon.setFill(Color.YELLOW);
heroesPtrPathLabel.setGraphic(icon);
}
@Override
public void update() {
super.update();
// load values from ini
final SettingsIniInterface settings = configService.getIniSettings();
heroesPath.setText(settings.getHeroesPath());
heroesPtrPath.setText(settings.getHeroesPtrPath());
sc2Path.setText(settings.getSc2Path());
sc2Architecture.setSelected(settings.isSc64bit());
// change listener for editable text fields
sc2Path.textProperty().addListener((observable, oldVal, newVal) -> {
if (!oldVal.equals(newVal)) {
setSc2Path(newVal);
}
});
heroesPath.textProperty().addListener((observable, oldVal, newVal) -> {
if (!oldVal.equals(newVal)) {
setHeroesPath(newVal);
}
});
heroesPtrPath.textProperty().addListener((observable, oldVal, newVal) -> {
if (!oldVal.equals(newVal)) {
setHeroesPtrPath(newVal);
}
});
validatePath(sc2Path.getText(), SC2_SWITCHER_EXE, sc2PathLabel);
validatePath(heroesPath.getText(), HEROES_SWITCHER_EXE, heroesPathLabel);
validatePath(heroesPtrPath.getText(), HEROES_SWITCHER_EXE, heroesPtrPathLabel);
}
@FXML
public void onSc2ArchitectureChange(final ActionEvent actionEvent) {
final boolean val = ((CheckBox) actionEvent.getSource()).selectedProperty().getValue();
configService.getIniSettings().setSc2Is64Bit(val);
persistSettingsIni();
}
@FXML
public void onSc2PathButtonClick() {
final File selectedFile =
showDirectoryChooser("Select StarCraft II's installation directory", sc2Path.getText());
if (selectedFile != null) {
setSc2Path(selectedFile.getAbsolutePath());
}
}
/**
* Shows a new directory selection dialog. The method doesn't return until the displayed dialog is dismissed. The
* return value specifies the directory chosen by the user or null if no selection has been made. If the owner
* window for the directory selection dialog is set, input to all windows in the dialog's owner chain is blocked
* while the dialog is being shown.
*
* @param title
* @param initialPath
* @return the selected directory or null if no directory has been selected
*/
private File showDirectoryChooser(final String title, final String initialPath) {
final DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle(title);
final File f = fileService.cutTillValidDirectory(initialPath);
if (f != null) {
directoryChooser.setInitialDirectory(f);
}
return directoryChooser.showDialog(getWindow());
}
private void setSc2Path(final String path) {
sc2Path.setText(path);
configService.getIniSettings().setSc2Path(path);
validatePath(path, SC2_SWITCHER_EXE, sc2PathLabel);
persistSettingsIni();
}
/**
* Validates a path leading to a game directory and adjusts the UI's error label.
*
* @param path
* installation path to validate
* @param switcher
* name of the Switcher.exe file found in the "Support" folder
* @param invalidLabel
* label set visible if invalid, can be null
*/
private static void validatePath(final String path, final String switcher, final Label invalidLabel) {
@SuppressWarnings("BooleanVariableAlwaysNegated")
boolean valid = false;
if (path != null) {
valid = switcherExists(path, switcher, false) ||
switcherExists(path, switcher.replace(".exe", "_x64.exe"), true);
}
if (invalidLabel != null) {
invalidLabel.setVisible(!valid);
}
}
/**
* @param gameDirectoryPath
* @param switcherName
* @param is64bit
* @return
*/
private static boolean switcherExists(
final String gameDirectoryPath, final String switcherName, final boolean is64bit) {
return new File(gameDirectoryPath + File.separator + "Support" + (is64bit ? "64" : "") + File.separator +
switcherName).exists();
}
@FXML
public void onHeroesPathButtonClick() {
final File selectedFile =
showDirectoryChooser("Select Heroes of the Storm's installation directory", heroesPath.getText());
if (selectedFile != null) {
setHeroesPath(selectedFile.getAbsolutePath());
}
}
private void setHeroesPath(final String path) {
heroesPath.setText(path);
configService.getIniSettings().setHeroesPath(path);
validatePath(path, HEROES_SWITCHER_EXE, heroesPathLabel);
persistSettingsIni();
}
@FXML
public void onHeroesPtrPathButtonClick() {
final File selectedFile = showDirectoryChooser("Select Heroes of the Storm's PTR installation directory",
heroesPtrPath.getText());
if (selectedFile != null) {
setHeroesPtrPath(selectedFile.getAbsolutePath());
}
}
private void setHeroesPtrPath(final String path) {
heroesPtrPath.setText(path);
configService.getIniSettings().setHeroesPtrPath(path);
validatePath(path, HEROES_SWITCHER_EXE, heroesPtrPathLabel);
persistSettingsIni();
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.ui;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.jupiter.api.Test;
class UIControllerTest {
@Test
@SuppressWarnings("JUnitTestMethodWithNoAssertions")
void equalsContract() {
EqualsVerifier.forClass(UIControllerMutable.class)
.withRedefinedSuperclass()
.withIgnoredFields("hash", "hashIsZero", "hashIsDirty")
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}
<file_sep>general.okButton=OK
general.yesButton=Yes
general.noButton=No
general.cancelButton=Cancel
general.exceptionStackTrace=The exception stacktrace was:
nav.progress=Progress
nav.home=Home
nav.settings=Settings
settings.cmdLineTool.compressBuildUnprotectedToo=build unprotected version, too
settings.cmdLineTool.compressMpq=MPQ compression:
settings.cmdLineTool.compressMpqBest=apply best experimental compression
settings.cmdLineTool.compressMpqBlizz=Blizzard's SC2/Heroes compression
settings.cmdLineTool.compressMpqNone=none (fast)
settings.cmdLineTool.compressMpqSystemDefault=System default
settings.cmdLineTool.compressXml=compress XML
settings.cmdLineTool.compressionTitle=Compression / Protection:
settings.cmdLineTool.repairLayoutOrder=repair order of Layout files
settings.cmdLineTool.validateLayoutFiles=check Layout files
settings.cmdLineTool.validateXml=check XML
settings.cmdLineTool.validationTitle=Verification:
settings.guitool.compressBuildUnprotectedToo=build unprotected version, too
settings.guitool.compressMpq=MPQ compression:
settings.guitool.compressMpqBest=apply best experimental compression
settings.guitool.compressMpqBlizz=Blizzard's SC2/Heroes compression
settings.guitool.compressMpqNone=none (fast)
settings.guitool.compressMpqSystemDefault=System default
settings.guitool.compressXml=compress XML
settings.guitool.compressionTitle=Compression / Protection:
settings.guitool.repairLayoutOrder=repair order of Layout files
settings.guitool.validateLayoutFiles=check Layout files
settings.guitool.validateXml=check XML
settings.guitool.validationTitle=Verification:
settings.paths.directoryNotValid=directory not valid
settings.paths.installDirectory=Installation directory:
settings.paths.pathPromptHeeroes=e.g.: C:\\Program Files\\Heroes of the Storm
settings.paths.pathPromptHeroesPtr=e.g.: C:\\Program Files\\Heroes of the Storm Public Test
settings.paths.pathPromptSc2=e.g.: C:\\Program Files\\StarCraft II
settings.paths.titleHeroes=Heroes of the Storm
settings.paths.titlePtr=PTR:
settings.paths.titleSc2=StarCraft II
settings.paths.use64bit=Use 64bit
settings.savedNotification=Settings saved!
settings.settings=Settings
progress.compressionMining.title=Compression Mining
progress.compressionMining.type=Type
progress.compressionMining.maskSize=Mask/Size
progress.compressionMining.compressionMethod=Compression
progress.compressionMining.singleFile=singleFile?
progress.compressionMining.compress=compress?
progress.compressionMining.encrypt=encrypt?
progress.compressionMining.encryptAdjusted=encryptAdjusted?
progress.compressionMining.includeSectorChecksum=includeSectorChecksum?
progress.compressionMining.markedForDeletion=markedForDeletion?
progress.compressionMining.testsPerformed=Tests performed:
progress.compressionMining.lastSize=Last size:
progress.compressionMining.sizeToBeat=Size to beat:
progress.compressionMining.stopMining=Stop Mining
progress.compressionMining.startMining=Start Mining
home.viewRuleset.type=Type
home.viewRuleset.maskSize=Mask/Size
home.viewRuleset.compressionMethod=Compression
home.viewRuleset.singleFile=singleFile?
home.viewRuleset.compress=compress?
home.viewRuleset.encrypt=encrypt?
home.viewRuleset.encryptAdjusted=encryptAdjusted?
home.viewRuleset.includeSectorChecksum=includeSectorChecksum?
home.viewRuleset.markedForDeletion=markedForDeletion?
home.addProject.name=Name:
home.addProject.path=Path:
home.addProject.game=Game:
home.newProject.name=Name:
home.newProject.path=Path:
home.title=Interface Builder
home.new=New
home.add=Add
home.remove=Remove
home.edit=Edit
home.build=Build
home.project.name=Project Name:
home.project.path=Path:
home.project.directorySize=Directory Size:
home.project.filesInArchive=Files in Archive:
home.project.lastBuildDate=Last build Date:
home.project.lastBuildSize=Last build Size:
home.project.viewBestCompressionRuleSet=View Best Compression Ruleset
home.project.mineBetterCompression=Mine Better Compression
app.title=Interface Builder
browse.title=Browse UI
nav.browse=Browse UI
browse.ptrActive=PTR is currently active.
browse.live=Live
browse.ptr=PTR
browse.extractBaseUi=Extract BaseUI
browse.notification.sc2OutOfDate=Base UI of SC2 might be out of date.
browse.notification.heroesOutOfDate=Base UI of Heroes might be out of date.
browse.notification.heroesPtrOutOfDate=Base UI of Heroes PTR might be out of date.
browse.viewSc2=Browse UI
browse.viewHeroes=Browse UI
browse.viewSelected=Browse Selected Project
browse.manageTabTitle=Manage
browse.projectTitle=Projects:
browse.sc2Title=StarCraft II:
browse.heroesTitle=Heroes of the Storm:
contextmenu.close=Close<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.progress;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import javafx.scene.control.Tab;
import javafx.scene.paint.Color;
import javafx.scene.text.TextFlow;
/**
* Tracks occurrence of an error.
*
* @author Ahli
*/
public final class ErrorTabController {
private static final String TAB_TEXT_COLOR_YELLOW = "-tab-text-color: yellow;";
private static final String TAB_TEXT_COLOR_RED = "-tab-text-color: red;";
private static final String TAB_TEXT_COLOR_WHITE = "-tab-text-color: white;";
private final boolean colorizeTitle;
private final boolean showResultIcon;
private final Tab tab;
private final TextFlow textArea;
private boolean encounteredError;
private boolean running;
private boolean encounteredWarning;
private State state = State.NOT_STARTED;
private boolean errorPreventsExit;
/**
* Constructor
*
* @param tab
* @param textArea
* @param colorizeTitle
* @param noResultIcon
*/
public ErrorTabController(
final Tab tab,
final TextFlow textArea,
final boolean colorizeTitle,
final boolean noResultIcon,
final boolean errorPreventsExit) {
this.tab = tab;
this.textArea = textArea;
this.colorizeTitle = colorizeTitle;
showResultIcon = !noResultIcon;
this.errorPreventsExit = errorPreventsExit;
}
/**
* @return
*/
public boolean hasEncounteredError() {
return encounteredError;
}
/**
* @return
*/
public boolean hasEncounteredWarning() {
return encounteredWarning;
}
public void clearError(final boolean updateTabHeader) {
encounteredError = false;
if (updateTabHeader) {
updateIcon();
updateLabel();
}
}
/**
*
*/
private void updateIcon() {
if (running) {
setIconAppearance(State.RUNNING, FontAwesomeIcon.SPINNER, Color.GAINSBORO);
} else if (encounteredError) {
setIconAppearance(State.ERROR, FontAwesomeIcon.EXCLAMATION_TRIANGLE, Color.RED);
} else if (encounteredWarning) {
setIconAppearance(State.WARNING, FontAwesomeIcon.EXCLAMATION_TRIANGLE, Color.YELLOW);
} else {
setIconAppearance(State.GOOD, FontAwesomeIcon.CHECK, Color.LAWNGREEN);
}
}
private void updateLabel() {
if (!encounteredError && !encounteredWarning) {
tab.setStyle(TAB_TEXT_COLOR_WHITE);
}
}
private void setIconAppearance(final State newState, final FontAwesomeIcon icon, final Color color) {
if (state != newState) {
state = newState;
if (newState == State.RUNNING || newState == State.NOT_STARTED || showResultIcon) {
final FontAwesomeIconView iconView = new FontAwesomeIconView(icon);
iconView.setFill(color);
tab.setGraphic(iconView);
} else {
tab.setGraphic(null);
}
}
}
public void clearWarning(final boolean updateTabHeader) {
encounteredWarning = false;
if (updateTabHeader) {
updateIcon();
updateLabel();
}
}
/**
* @return the tab
*/
public Tab getTab() {
return tab;
}
/**
* @return the running
*/
public boolean isRunning() {
return running;
}
/**
* @param running
* the running to set
*/
public void setRunning(final boolean running) {
this.running = running;
updateIcon();
}
/**
* @return
*/
public TextFlow getTextArea() {
return textArea;
}
/**
*
*/
public void reportError() {
if (!encounteredError) {
encounteredError = true;
if (colorizeTitle) {
tab.setStyle(TAB_TEXT_COLOR_RED);
}
updateIcon();
}
}
/**
*
*/
public void reportWarning() {
if (!encounteredWarning) {
encounteredWarning = true;
if (colorizeTitle && !encounteredError) {
tab.setStyle(TAB_TEXT_COLOR_YELLOW);
}
updateIcon();
}
}
public boolean isErrorPreventsExit() {
return errorPreventsExit;
}
public void setErrorPreventsExit(final boolean errorPreventsExit) {
this.errorPreventsExit = errorPreventsExit;
}
private enum State {NOT_STARTED, RUNNING, WARNING, ERROR, GOOD}
}
<file_sep>READ ME - compile-spring-boot.jar
=============================================================================================================================================
Author: Ahli
=============================================================================================================================================
A log file is created in your system's user.home path. For example: C:\Users\Ahli\.GalaxyObsUI\logs
=============================================================================================================================================
Parameters:
--compile="pathToInterfaceSourceFolder"
This will compile a specific Interface
--compileRun="pathToInterfaceSourceFolder"
This will compile a specific Interface and launch the appropriate game based on the settings.ini with the most recent replay.
--run="pathToGamesSwitcher.exe"
This will launch the game's specified Switcher.exe with the most recent replay.
See the following example:
=============================================================================================================================================
Example code for Notepad++'s NppExec plugin:
javaw -jar D:\GalaxyObsUI\dev\compile-spring-boot.jar --compileRun="$(CURRENT_DIRECTORY)"
(You might have to enable NppExec's Follow $(CURRENT_DIRECTORY) setting inside the dropdown.)
(Suggested highlight for NppExec: "*ERROR:*%FILE%*" and " at*".)
=============================================================================================================================================
There are two modes supported:
- If the Builder is already running, the commands are transferred. The output is send back and shown in the console.
- If the Builder is not running, the Builder is booting, performs the task and exits itself again, if there was no error.
- add "--noGUI" to run without UI
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.mpq;
import java.nio.file.Path;
/**
* Interface for the interaction of MPQ files.
*
* @author Ahli
*/
public interface MpqInterface {
/**
* Returns a File from a mpq with the specified internal path.
*
* @param internalPath
* @return File from the mpq with specified internal Path
*/
Path getFilePathFromMpq(String internalPath);
/**
* @return
* @throws MpqException
*/
boolean isHeroesMpq() throws MpqException;
/**
* Returns the cache folder of the opened mpq.
*
* @return cache folder as a Path
*/
Path getCache();
/**
* Sets the cache folder.
*
* @param cache
* Cache folder to temporarily store mpq content within
*/
void setCache(Path cache);
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.integration.kryo;
import com.ahli.galaxy.ui.UIAnimationMutable;
import com.ahli.galaxy.ui.UIAttributeImmutable;
import com.ahli.galaxy.ui.UICatalogImpl;
import com.ahli.galaxy.ui.UIConstantImmutable;
import com.ahli.galaxy.ui.UIControllerMutable;
import com.ahli.galaxy.ui.UIFrameMutable;
import com.ahli.galaxy.ui.UIStateGroupMutable;
import com.ahli.galaxy.ui.UIStateMutable;
import com.ahli.galaxy.ui.UITemplate;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.util.HashMapReferenceResolver;
import com.esotericsoftware.kryo.util.ListReferenceResolver;
import interfacebuilder.integration.kryo.serializer.KryoGameInfoSerializer;
import interfacebuilder.integration.kryo.serializer.KryoInternStringArraySerializer;
import interfacebuilder.integration.kryo.serializer.KryoInternStringSerializer;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
public class KryoService {
public KryoService() {
// explicit default constructor
}
public Kryo getKryoForUICatalog() {
// Kryo logging
// Log.ERROR = true;
// Log.WARN = true;
// Log.INFO = true;
// Log.DEBUG = true;
// Log.TRACE = false;
final Kryo kryo = new Kryo(new HashMapReferenceResolver());
kryo.register(ArrayList.class, 9);
kryo.register(UIAttributeImmutable.class, 10);
kryo.register(String[].class, new KryoInternStringArraySerializer(), 11);
kryo.register(UIFrameMutable.class, 12);
kryo.register(UITemplate.class, 13);
kryo.register(UIConstantImmutable.class, 14);
kryo.register(UIStateMutable.class, 15);
kryo.register(UIControllerMutable.class, 16);
kryo.register(UIAnimationMutable.class, 17);
kryo.register(UIStateGroupMutable.class, 18);
kryo.register(UICatalogImpl.class, 19);
kryo.register(KryoGameInfo.class, new KryoGameInfoSerializer(), 20);
kryo.register(int[].class, 21);
kryo.register(byte[].class, 22);
kryo.register(UnifiedMap.class, 23);
kryo.register(String.class, new KryoInternStringSerializer(), 24);
kryo.setRegistrationRequired(true);
return kryo;
}
public Kryo getKryoForBaseUiMetaFile() {
final Kryo kryo = new Kryo(new ListReferenceResolver());
kryo.register(KryoGameInfo.class, new KryoGameInfoSerializer(), 9);
kryo.register(int[].class, 10);
kryo.setRegistrationRequired(true);
return kryo;
}
public List<Object> get(final Path path, final List<Class<?>> payloadClasses, final Kryo kryo) throws IOException {
try (final InflaterInputStream in = new InflaterInputStream(Files.newInputStream(path))) {
try (final Input input = new Input(in)) {
final List<Object> result = new ArrayList<>(payloadClasses.size());
for (final var clazz : payloadClasses) {
result.add(kryo.readObject(input, clazz));
}
return result;
} catch (final KryoException e) {
Files.deleteIfExists(path);
throw new IOException(e);
}
}
}
public List<Object> get(
final Path path, final List<Class<?>> payloadClasses, final Kryo kryo, final int stopAfterIndex)
throws IOException {
try (final InflaterInputStream in = new InflaterInputStream(Files.newInputStream(path))) {
try (final Input input = new Input(in)) {
final List<Object> result = new ArrayList<>(payloadClasses.size());
int i = 0;
for (final var clazz : payloadClasses) {
result.add(kryo.readObject(input, clazz));
if (i == stopAfterIndex) {
break;
}
++i;
}
return result;
} catch (final KryoException e) {
Files.deleteIfExists(path);
throw new IOException(e);
}
}
}
public void put(final Path path, final Iterable<Object> payload, final Kryo kryo) throws IOException {
Files.createDirectories(path.getParent());
try (final DeflaterOutputStream out = new DeflaterOutputStream(Files.newOutputStream(path))) {
try (final Output output = new Output(out)) {
for (final var obj : payload) {
kryo.writeObject(output, obj);
}
}
} catch (final KryoException e) {
throw new IOException(e);
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.integration;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.Serial;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
public class FileService {
public FileService() {
// explicit default constructor
}
/**
* Copies a file or directory.
*
* @param source
* source location
* @param target
* target location
* @throws IOException
* when something goes wrong
*/
public void copyFileOrDirectory(final Path source, final Path target) throws IOException {
if (Files.isDirectory(source)) {
// create folder if not existing
if (!Files.exists(target)) {
Files.createDirectories(target);
}
// copy all contained files recursively
try (final Stream<Path> stream = Files.walk(source)) {
stream.forEach(file -> {
try {
Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException e) {
throw new FileServiceException(e.getMessage(), e);
}
});
}
} else {
// copy a file
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
}
/**
* Shortens the path to become a valid directory. Returns null if no valid directory exists.
*
* @param path
* @return
*/
public File cutTillValidDirectory(final String path) {
File f = new File(path);
if (!f.isDirectory()) {
final char sep = File.separatorChar;
int i;
String pathTmp = path;
do {
i = pathTmp.lastIndexOf(sep);
if (i != -1) {
pathTmp = pathTmp.substring(0, i);
//noinspection ObjectAllocationInLoop
f = new File(pathTmp);
} else {
f = null;
break;
}
} while (!f.isDirectory());
}
return f;
}
/**
* Returns the size of the specified directory in bytes.
*
* @param path
* @return size of all contained files in bytes
* @throws IOException
*/
public long getDirectorySize(final Path path) throws IOException {
final long size;
try (final Stream<Path> walk = Files.walk(path)) {
size = walk.filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
}
return size;
}
/**
* Cleans a directory without deleting it.
*
* @param directory
* @throws IOException
*/
public void cleanDirectory(final Path directory) throws IOException {
for (int i = 500; i > 0; --i) {
try {
// TODO check if it can be rewritten using nio streams
FileUtils.cleanDirectory(directory.toFile());
return;
} catch (final IOException e) {
if (i <= 1) {
throw e;
} else {
try {
Thread.sleep(5);
} catch (final InterruptedException e1) {
e1.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
}
}
/**
* Checks if a directory is empty or not.
*
* @param directory
* @return true, if the directory is empty
* @throws IOException
* if it is not a directory or another problem occurred
*/
public boolean isEmptyDirectory(final Path directory) throws IOException {
return getFileCountOfDirectory(directory) <= 0;
}
/**
* Returns the count of files within the specified directory.
*
* @param path
* @return count of files in directory and subdirectories
* @throws IOException
*/
public long getFileCountOfDirectory(final Path path) throws IOException {
if (!Files.exists(path)) {
return 0;
}
final long count;
try (final Stream<Path> walk = Files.walk(path)) {
count = walk.filter(p -> p.toFile().isFile()).count();
}
return count;
}
private static class FileServiceException extends RuntimeException {
@Serial
private static final long serialVersionUID = -5030478360016607662L;
public FileServiceException(final String message, final IOException e) {
super(message, e);
}
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder;
import interfacebuilder.integration.CommandLineParams;
import interfacebuilder.integration.InterProcessCommunication;
import interfacebuilder.ui.AppController;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
public class NoGuiApplication {
private final InterProcessCommunication.IpcServerThread serverThread;
private final ConfigurableApplicationContext context;
private final CommandLineParams startingParams;
public NoGuiApplication(final String[] args, final Thread serverThread) {
this.serverThread = (InterProcessCommunication.IpcServerThread) serverThread;
context = new SpringApplicationBuilder(SpringBootApplication.class).build().run(args);
if (serverThread != null && serverThread.isAlive()) {
this.serverThread.setAppController(context.getBean(AppController.class));
}
startingParams = new CommandLineParams(false, args);
}
public void start() {
context.publishEvent(new PrimaryStageReadyEvent(this, startingParams));
}
public void stop() {
if (serverThread != null && serverThread.isAlive()) {
serverThread.interrupt();
}
context.publishEvent(new AppClosingEvent(this));
context.close();
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.home;
import interfacebuilder.projects.Project;
import javafx.fxml.FXML;
import javafx.scene.control.Dialog;
import javafx.scene.layout.Pane;
public class NewProjectDialogController {
@FXML
private Pane contentPane;
@FXML
private NewProjectController contentPaneController;
@FXML
private Dialog<Project> dialog;
public NewProjectDialogController() {
// explicit default constructor
}
public NewProjectController getContentController() {
return contentPaneController;
}
/**
* Automatically called by FxmlLoader
*/
public void initialize() {
contentPaneController.initialize(dialog);
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.build;
import com.ahli.galaxy.ModData;
import com.ahli.galaxy.archive.ComponentsListReaderDom;
import com.ahli.galaxy.archive.DescIndexData;
import com.ahli.galaxy.game.GameData;
import com.ahli.galaxy.game.GameDef;
import com.ahli.galaxy.ui.DescIndexReader;
import com.ahli.mpq.MpqEditorInterface;
import com.ahli.mpq.MpqException;
import com.ahli.mpq.mpqeditor.MpqEditorCompression;
import interfacebuilder.base_ui.BaseUiService;
import interfacebuilder.compile.CompileService;
import interfacebuilder.compress.RuleSet;
import interfacebuilder.config.ConfigService;
import interfacebuilder.integration.FileService;
import interfacebuilder.integration.SettingsIniInterface;
import interfacebuilder.projects.Project;
import interfacebuilder.projects.ProjectService;
import interfacebuilder.projects.enums.Game;
import interfacebuilder.ui.AppController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
public class MpqBuilderService {
private static final Logger logger = LogManager.getLogger(MpqBuilderService.class);
private final ConfigService configService;
private final CompileService compileService;
private final FileService fileService;
private final ProjectService projectService;
private final BaseUiService baseUiService;
private final GameData sc2BaseGameData;
private final GameData heroesBaseGameData;
private final ForkJoinPool executor;
private final AppController appController;
public MpqBuilderService(
final ConfigService configService,
final CompileService compileService,
final FileService fileService,
final ProjectService projectService,
final BaseUiService baseUiService,
final GameData sc2BaseGameData,
final GameData heroesBaseGameData,
final ForkJoinPool executor,
final AppController appController) {
this.configService = configService;
this.compileService = compileService;
this.fileService = fileService;
this.projectService = projectService;
this.baseUiService = baseUiService;
this.sc2BaseGameData = sc2BaseGameData;
this.heroesBaseGameData = heroesBaseGameData;
this.executor = executor;
this.appController = appController;
}
/**
* Schedules a task to find and build a project based on the specified path.
*
* @param path
*/
public void build(final String path) {
final File f = new File(path);
final Project project;
final List<Project> projectsOfPath = projectService.getProjectsOfPath(path);
if (projectsOfPath.isEmpty()) {
final Game game;
if (projectService.pathContainsCompileableForGame(path, heroesBaseGameData)) {
game = Game.HEROES;
} else if (projectService.pathContainsCompileableForGame(path, sc2BaseGameData)) {
game = Game.SC2;
} else {
throw new IllegalArgumentException("Specified path '" + path + "' did not contain any project.");
}
project = new Project(f.getName(), f.getAbsolutePath(), game);
} else {
project = projectsOfPath.get(0);
}
build(project, true);
}
/**
* Schedules a task to build the mpq archive file for a project.
*
* @param project
*/
public void build(final Project project, final boolean useCmdLineSettings) {
final BuildTask task = new BuildTask(appController, project, useCmdLineSettings, this, baseUiService);
executor.execute(task);
}
/**
* Returns the GameData definition for the specified game.
*
* @param game
* @return
*/
public GameData getGameData(final Game game) {
return switch (game) {
case SC2 -> sc2BaseGameData;
case HEROES -> heroesBaseGameData;
};
}
/**
* Builds a specific Interface in a Build Thread.
*
* @param interfaceDirectory
* folder of the interface file to be built
* @param game
* @param useCmdLineSettings
*/
void buildSpecificUI(
final Path interfaceDirectory,
final GameData game,
final boolean useCmdLineSettings,
final Project project) {
if (executor.isShutdown()) {
logger.error("ERROR: Executor shut down. Skipping building a UI...");
return;
}
if (!Files.exists(interfaceDirectory) || !Files.isDirectory(interfaceDirectory)) {
logger.error("ERROR: Can't build UI from file '{}', expected an existing directory.", interfaceDirectory);
return;
}
final boolean verifyLayout;
final SettingsIniInterface settings = configService.getIniSettings();
if (useCmdLineSettings) {
verifyLayout = settings.isCmdLineVerifyLayout();
} else {
verifyLayout = settings.isGuiVerifyLayout();
}
if (game.getUiCatalog() == null && verifyLayout) {
// parse default UI
throw new IllegalStateException(String.format("Base UI of game '%s' has not been parsed.",
game.getGameDef().name()));
}
// create tasks for the worker pool
try {
appController.addThreadLoggerTab(Thread.currentThread().getName(),
interfaceDirectory.getFileName().toString(),
true);
// create unique cache path
final MpqEditorInterface threadsMpqInterface = new MpqEditorInterface(configService.getMpqCachePath()
.resolve(Long.toString(Thread.currentThread().getId())), configService.getMpqEditorPath());
// work
final boolean compressXml;
final int compressMpqSetting;
final boolean buildUnprotectedToo;
final boolean repairLayoutOrder;
final boolean verifyXml;
if (useCmdLineSettings) {
compressXml = settings.isCmdLineCompressXml();
compressMpqSetting = settings.getCmdLineCompressMpq();
buildUnprotectedToo = settings.isCmdLineBuildUnprotectedToo();
repairLayoutOrder = settings.isCmdLineRepairLayoutOrder();
verifyXml = settings.isCmdLineVerifyXml();
} else {
compressXml = settings.isGuiCompressXml();
compressMpqSetting = settings.getGuiCompressMpq();
buildUnprotectedToo = settings.isGuiBuildUnprotectedToo();
repairLayoutOrder = settings.isGuiRepairLayoutOrder();
verifyXml = settings.isGuiVerifyXml();
}
// load best compression ruleset
if (compressXml && compressMpqSetting == 2) {
final RuleSet ruleSet = projectService.fetchBestCompressionRuleSet(project);
if (ruleSet != null) {
// TODO verify/expand ruleset
threadsMpqInterface.setCustomCompressionRules(ruleSet.getCompressionRules());
}
}
threadsMpqInterface.clearCacheExtractedMpq();
buildFile(interfaceDirectory,
game,
threadsMpqInterface,
compressXml,
compressMpqSetting,
buildUnprotectedToo,
repairLayoutOrder,
verifyLayout,
verifyXml,
project);
threadsMpqInterface.clearCacheExtractedMpq();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
} catch (final IOException e) {
logger.error("ERROR: Exception while building UIs.", e);
} catch (final Exception e) {
logger.fatal("FATAL ERROR: ", e);
}
}
/**
* Builds MPQ Archive File. Run this in its own thread! Conditions: - Specified MpqInterface requires a unique cache
* path for multithreading.
*
* @param sourceFile
* folder location
* @param game
* the game data with game definition
* @param mpqi
* MpqInterface with unique cache path
* @param compressXml
* @param compressMpq
* @param buildUnprotectedToo
* @param repairLayoutOrder
* @param verifyLayout
* @param verifyXml
* @param project
* @throws IOException
* when something goes wrong
* @throws InterruptedException
*/
private void buildFile(
final Path sourceFile,
final GameData game,
final MpqEditorInterface mpqi,
final boolean compressXml,
final int compressMpq,
final boolean buildUnprotectedToo,
final boolean repairLayoutOrder,
final boolean verifyLayout,
final boolean verifyXml,
final Project project) throws IOException, InterruptedException {
appController.printInfoLogMessageToGeneral(sourceFile.getFileName() + " started construction.");
final GameDef gameDef = game.getGameDef();
final Path targetFile =
Path.of(configService.getDocumentsPath() + File.separator + gameDef.documentsGameDirectoryName() +
File.separator + gameDef.documentsInterfaceSubdirectoryName());
// init mod data
final ModData mod = new ModData(game);
mod.setSourceDirectory(sourceFile);
mod.setTargetFile(targetFile);
// get and create cache
final Path cache = mpqi.getCache();
if (!Files.exists(cache)) {
Files.createDirectories(cache);
}
int cacheClearAttempts;
for (cacheClearAttempts = 0; cacheClearAttempts <= 100; ++cacheClearAttempts) {
if (!mpqi.clearCacheExtractedMpq()) {
// sleep and hope the file gets released soon
Thread.sleep(500);
} else {
// success
break;
}
}
if (cacheClearAttempts > 100) {
final String msg = "ERROR: Cache could not be cleared";
logger.error(msg);
return;
}
mod.setMpqCacheDirectory(cache);
// put files into cache
int copyAttempts;
for (copyAttempts = 0; copyAttempts <= 100; ++copyAttempts) {
try {
fileService.copyFileOrDirectory(sourceFile, cache);
break;
} catch (final FileSystemException e) {
if (copyAttempts == 0) {
logger.warn("Attempt to copy directory failed.", e);
} else if (copyAttempts >= 100) {
final String msg = "Unable to copy directory after 100 copy attempts: " + e.getMessage();
logger.error(msg, e);
throw new FileSystemException(msg);
}
// sleep and hope the file gets released soon
Thread.sleep(500);
} catch (final IOException e) {
final String msg = "Unable to copy directory";
logger.error(msg, e);
}
}
if (copyAttempts > 100) {
// copy keeps failing -> abort
final String msg = "Failed to copy files to: " + cache;
logger.error(msg);
throw new IOException(msg);
}
final Path componentListFile = mpqi.getComponentListFile();
if (componentListFile == null) {
final String msg = "ERROR: did not find the ComponentList file.";
logger.error(msg);
throw new IOException(msg);
}
mod.setComponentListFile(componentListFile);
final DescIndexData descIndexData = new DescIndexData(mpqi);
mod.setDescIndexData(descIndexData);
try {
descIndexData.setDescIndexPathAndClear(ComponentsListReaderDom.getDescIndexPath(componentListFile,
gameDef));
} catch (final ParserConfigurationException | SAXException | IOException e) {
final String msg = "ERROR: unable to read DescIndex path.";
logger.error(msg, e);
throw new IOException(msg, e);
}
final File descIndexFile = mpqi.getFilePathFromMpq(descIndexData.getDescIndexIntPath()).toFile();
try {
descIndexData.addLayoutIntPath(DescIndexReader.getLayoutPathList(descIndexFile, DescIndexReader.Mode.ALL));
} catch (final SAXException | ParserConfigurationException | IOException | MpqException e) {
logger.error("unable to read Layout paths", e);
}
logger.info("Compiling... {}", sourceFile.getFileName());
// perform checks/improvements on code
compileService.compile(mod,
configService.getRaceId(),
repairLayoutOrder,
verifyLayout,
verifyXml,
configService.getConsoleSkinId());
logger.info("Building... {}", sourceFile.getFileName());
final String sourceFileName = sourceFile.getFileName().toString();
try {
mpqi.buildMpq(targetFile,
sourceFileName,
compressXml,
getCompressionModeOfSetting(compressMpq),
buildUnprotectedToo);
project.setLastBuildDateTime(LocalDateTime.now());
final long size = Files.size(targetFile.resolve(sourceFileName));
project.setLastBuildSize(size);
logger.info("Finished building... {}. Size: {}kb", sourceFileName, size / 1024);
projectService.saveProject(project);
appController.printInfoLogMessageToGeneral(sourceFileName + " finished construction.");
} catch (final IOException | MpqException e) {
logger.error("ERROR: unable to construct final Interface file.", e);
AppController.printErrorLogMessageToGeneral(sourceFileName + " could not be created.");
}
}
/**
* @param compressMpqSetting
* @return
*/
private static MpqEditorCompression getCompressionModeOfSetting(final int compressMpqSetting) {
return switch (compressMpqSetting) {
case 0 -> MpqEditorCompression.NONE;
case 1 -> MpqEditorCompression.BLIZZARD_SC2_HEROES;
case 2 -> MpqEditorCompression.CUSTOM;
case 3 -> MpqEditorCompression.SYSTEM_DEFAULT;
default -> throw new IllegalArgumentException("Unsupported mpq compression mode.");
};
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui.progress;
import interfacebuilder.integration.log4j.StylizedTextAreaAppender;
import interfacebuilder.ui.AppController;
import interfacebuilder.ui.Updateable;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.text.TextFlow;
public class TabPaneController implements Updateable {
private final AppController appController;
@FXML
private TabPane tabPane;
public TabPaneController(final AppController appController) {
this.appController = appController;
}
/**
* Automatically called by FxmlLoader
*/
public void initialize() {
// log4j2 prints into txtArea
final TextFlow txtArea = new TextFlow();
final ScrollPane scrollPane = new ScrollPane(txtArea);
scrollPane.setPannable(true);
// auto-downscrolling
scrollPane.vvalueProperty().bind(txtArea.heightProperty());
// special ScrollPane within first Tab of tabPane
final ObservableList<Tab> tabs = tabPane.getTabs();
final Tab tab = tabs.get(0);
tab.setContent(scrollPane);
final ErrorTabController errorTabCtrl = new ErrorTabController(tab, txtArea, false, true, true);
appController.addErrorTabController(errorTabCtrl);
StylizedTextAreaAppender.setGeneralController(errorTabCtrl);
}
/**
* Returns the TabPane.
*
* @return
*/
public TabPane getTabPane() {
return tabPane;
}
@Override
public void update() {
// nothing to do
}
}
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package interfacebuilder.ui;
import interfacebuilder.i18n.Messages;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Window;
import org.apache.commons.lang3.exception.ExceptionUtils;
public final class Alerts {
private Alerts() {
// disallow class instances
}
/**
* @param owner
* @param title
* @param header
* @param content
* @return
*/
public static Alert buildYesNoCancelAlert(
final Window owner, final String title, final String header, final String content) {
final ButtonType yesButton = new ButtonType(Messages.getString("general.yesButton"), ButtonData.YES);
final ButtonType noButton = new ButtonType(Messages.getString("general.noButton"), ButtonData.NO);
final ButtonType cancelButton =
new ButtonType(Messages.getString("general.cancelButton"), ButtonData.CANCEL_CLOSE);
final Alert alert = new Alert(AlertType.INFORMATION, content, yesButton, noButton, cancelButton);
alert.initOwner(owner);
alert.setTitle(title);
alert.setHeaderText(header);
return alert;
}
/**
* @param owner
* @param title
* @param header
* @param content
* @return
*/
public static Alert buildErrorAlert(
final Window owner, final String title, final String header, final String content) {
final ButtonType okButton = createOkButton();
final Alert alert = new Alert(AlertType.ERROR, content, okButton);
alert.initOwner(owner);
alert.setTitle(title);
alert.setHeaderText(header);
return alert;
}
private static ButtonType createOkButton() {
return new ButtonType(Messages.getString("general.okButton"), ButtonData.OK_DONE);
}
/**
* @param owner
* @param title
* @param header
* @param content
* @return
*/
public static Alert buildWarningAlert(
final Window owner, final String title, final String header, final String content) {
final ButtonType okButton = createOkButton();
final Alert alert = new Alert(AlertType.WARNING, content, okButton);
alert.initOwner(owner);
alert.setTitle(title);
alert.setHeaderText(header);
return alert;
}
/**
* @param owner
* @param title
* @param header
* @param content
* @param imageUrl
* @return
*/
public static Alert buildAboutAlert(
final Window owner, final String title, final String header, final String content, final String imageUrl) {
final ButtonType okButton = createOkButton();
final Alert alert = new Alert(AlertType.INFORMATION, content, okButton);
alert.initOwner(owner);
alert.setTitle(title);
alert.setHeaderText(header);
if (imageUrl != null) {
alert.setGraphic(new ImageView(imageUrl));
}
alert.getDialogPane().setPrefSize(480, 360);
return alert;
}
/**
* @param owner
* @param e
* @return
*/
public static Alert buildExceptionAlert(final Window owner, final Throwable e) {
final ButtonType okButton = createOkButton();
final String localizedMsg = e.getLocalizedMessage();
final Alert alert = new Alert(AlertType.ERROR, localizedMsg, okButton);
alert.initOwner(owner);
final Label label = new Label(Messages.getString("general.exceptionStackTrace"));
final String stackTrace = ExceptionUtils.getStackTrace(e);
final TextArea textArea = new TextArea(stackTrace);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
final GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
// Set expandable Exception into the dialog pane.
alert.getDialogPane().setExpandableContent(expContent);
return alert;
}
}
<file_sep><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.ahli</groupId>
<artifactId>galaxy-lib</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<java.version>16</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- version definitions -->
<lombok.version>1.18.20</lombok.version>
<asm.version>9.2</asm.version>
<log4j2.version>2.14.1</log4j2.version>
<lmax-disruptor.version>3.4.4</lmax-disruptor.version>
<eclipse-collection.version>10.4.0</eclipse-collection.version>
<commons-io.version>2.11.0</commons-io.version>
<commons-beanutils.version>1.9.4</commons-beanutils.version>
<commons-configuration2.version>2.7</commons-configuration2.version>
<commons-text.version>1.9</commons-text.version><!-- dependency of configuration2 -->
<commons-lang3.version>3.12.0</commons-lang3.version><!-- dependency of configuration2 -->
<vtd-xml.version>2.13.4</vtd-xml.version>
<junit-jupiter.version>5.8.0-RC1</junit-jupiter.version>
<equalsverifier.version>3.7.1</equalsverifier.version>
<slf4j.version>1.8.0-beta4</slf4j.version>
<!-- <slf4j.version>1.7.31</slf4j.version>-->
</properties>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<release>${java.version}</release>
<excludes>
<!-- excludes files from being put into same path as classes -->
<exclude>**/*.txt</exclude>
</excludes>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
<!--<compilerArgs>- -enable-preview</compilerArgs>-->
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<compilerArg>-Xlint:all</compilerArg>
</compilerArgs>
</configuration>
</plugin>
<!-- Force requirement of Maven version 3.1.0+ -->
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-enforcer-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>[3.1.1,)</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<!-- goal to execute to check for plugins and dependency updates:
versions:display-plugin-updates versions:display-parent-updates versions:display-dependency-updates versions:display-property-updates
-->
<!-- https://mvnrepository.com/artifact/org.codehaus.mojo/versions-maven-plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.8.1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-clean-plugin -->
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-deploy-plugin -->
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-install-plugin -->
<artifactId>maven-install-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<!--<argLine>--enable-preview</argLine>-->
</configuration>
<dependencies>
<dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin -->
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-site-plugin -->
<artifactId>maven-site-plugin</artifactId>
<version>3.9.1</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-jar-plugin -->
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin -->
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>6.2.2</version>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<failOnError>false</failOnError>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- file IO stuff -->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- logging facade -->
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- logging implementation (during tests) -->
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
<!-- high performance xml parser -->
<!-- https://mvnrepository.com/artifact/com.ximpleware/vtd-xml -->
<dependency>
<groupId>com.ximpleware</groupId>
<artifactId>vtd-xml</artifactId>
<version>${vtd-xml.version}</version>
</dependency>
<!-- read ini files -->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-configuration2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>${commons-configuration2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections-api</artifactId>
<version>${eclipse-collection.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collection.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
<version>${equalsverifier.version}</version>
<scope>test</scope>
</dependency>
<!-- less boilerplate code -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- update dependencies within configuration2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project><file_sep>[GamePaths]
Heroes_Path = F:\Spiele\Heroes of the Storm
HeroesPTR_Path = F:\Spiele\Heroes of the Storm Public Test
StarCraft2_Path = F:\Spiele\StarCraft II
StarCraft2_use64bit = true
[CommandLineExecution]
verifyXml = true
verifyLayout = true
repairLayoutOrder = true
compressXml = false
compressMPQ = 0
buildUnprotectedToo = false
[GuiExecution]
verifyXml = true
verifyLayout = true
repairLayoutOrder = true
compressXml = true
compressMPQ = 2
buildUnprotectedToo = false
<file_sep>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package com.ahli.galaxy.parser.abstracts;
import com.ahli.galaxy.parser.interfaces.ParsedXmlConsumer;
import com.ahli.galaxy.parser.interfaces.XmlParser;
public abstract class XmlParserAbstract implements XmlParser {
protected ParsedXmlConsumer consumer;
protected XmlParserAbstract(final ParsedXmlConsumer consumer) {
this.consumer = consumer;
}
}
|
59dd670b4b4fcf28083def694eae6491964f1f7b
|
[
"Markdown",
"Maven POM",
"INI",
"Java",
"Text",
"C++"
] | 87 |
Java
|
0x00FF00FF/Galaxy-Observer-UI
|
d47e21ff54b1e3b4cb026b740eba61c86a028280
|
a8ea8cf90cb36287657e6ab41273088b7a27dbfe
|
refs/heads/master
|
<repo_name>YektaAnilAksoy/Compatitive-Programming-Helpfull-Templates<file_sep>/PrimsAlgorithm.java
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class PrimsAlgorithm {
// Dügümleri temsil eden class yapimiz
static class Vertex{
List<Edge> neighbours;
public Vertex() {
neighbours = new ArrayList<>();
}
}
// Kenarlari temsil eden class yapimiz
static class Edge implements Comparable<Edge>{
//Edge in nereye gittigini temsil ediyor
int to;
//Edge in agirligini temsil ediyor
int weight;
public Edge(int to,int weight) {
this.to = to;
this.weight = weight;
}
/**
* Oncelikli Sirada(PriorityQueue) agirligi dusuk olani vermesi icin
* Comparable arayuzu implement edildi ve compareTo methodu Override edildi.
*/
@Override
public int compareTo(Edge o) {
return this.weight - o.weight;
}
}
public static int runPrimsAlgorithm(Vertex[] graph, int numOfVertex, int source) {
boolean[] visited = new boolean[numOfVertex];
//baslangic noktasi visited olarak isaretlendi
visited[source] = true;
PriorityQueue<Edge> priorityQueue = new PriorityQueue<Edge>();
// Baslangic dugumun kenarlari(edgeleri) priority queue ya eklenir
for(Edge e : graph[source].neighbours)
priorityQueue.add(e);
// minimumCost degiskenimiz tum dugumleri gezmemiz icin gereken minimum agirligi tutacak
int minimumCost = 0;
while(!priorityQueue.isEmpty()) {
//priorityqueue dan agirligi en dusuk olan kenar alinir
Edge edge = priorityQueue.poll();
/**
* eger bu aldigimiz kenarin gittigi dugum onceden ziyaret edildiyse,
* bu dugum icin herhangi bir islem yapmamize gerek yok.
*/
if(visited[edge.to])
continue;
// eger ziyaret edilmediyse,bu kenar ziyaret edildi olarak isaretlenir.
visited[edge.to] = true;
// bu kenar ilk defa ziyaret edildigi icin agirligi minimumCost degiskenine eklenir
minimumCost += edge.weight;
// bu kenarin gittigi dugumun kenarlari priorityqueue ya eklenir
for(Edge childEdge : graph[edge.to].neighbours)
priorityQueue.add(childEdge);
}
return minimumCost;
}
// ORNEK INPUT EKLENDI
public static void main(String[] args) {
final int numOfVertex = 5;
final int source = 0;
Vertex[] graph = new Vertex[numOfVertex];
// Dugumler yaratildi
for(int i = 0; i<numOfVertex;i++)
graph[i] = new Vertex();
// Ornek kenarlar(edges) eklendi
graph[0].neighbours.add(new Edge(1, 3));
graph[1].neighbours.add(new Edge(0,3));
graph[0].neighbours.add(new Edge(2,4));
graph[2].neighbours.add(new Edge(0,4));
graph[3].neighbours.add(new Edge(1,6));
graph[1].neighbours.add(new Edge(3,6));
graph[4].neighbours.add(new Edge(1,2));
graph[1].neighbours.add(new Edge(4,2));
graph[1].neighbours.add(new Edge(2,5));
graph[2].neighbours.add(new Edge(1,5));
graph[2].neighbours.add(new Edge(4,7));
graph[4].neighbours.add(new Edge(2,7));
System.out.println(runPrimsAlgorithm(graph, numOfVertex, source));
}
}
<file_sep>/README.md
# Compatitive-Programming-Helpfull-Templates
There are useful algorithms,data structures and templates in this repository for using at Competitive Programming
|
9518cac79685bc5e3071558c73f603bf0284b3fc
|
[
"Markdown",
"Java"
] | 2 |
Java
|
YektaAnilAksoy/Compatitive-Programming-Helpfull-Templates
|
691fff7bee6002d58fb96d43d7c34030e8c3244e
|
cab4384f9fdf5484683b2a9f2fbef38c7508944f
|
refs/heads/master
|
<file_sep>//
// Balloon.swift
// 99RedBalloons
//
// Created by <NAME> on 2/7/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
|
803541bad285667c143b8e1bbd5dc6b3baf2cab8
|
[
"Swift"
] | 1 |
Swift
|
rnoriega31/99RedBalloons
|
8a634c535ee39f62bda8f7265208670569249de3
|
637bcb96687efe1b1421d48497b889d7b55a477f
|
refs/heads/master
|
<repo_name>josebur86/scaling<file_sep>/provision/loadBalancer.sh
#!/bin/bash
echo "Installing Nginx"
sudo apt-get update > /dev/null
sudo apt-get install nginx -y > /dev/null
echo "Configuring Nginx"
sudo cp /vagrant/provision/config/nginx.conf /etc/nginx.conf
sudo cp /vagrant/provision/config/default /etc/nginx/sites-enabled/default
echo "Reloading Nginx"
sudo service nginx restart > /dev/null
<file_sep>/provision/app.sh
#!/bin/bash
echo "Installing NodeJS and NPM"
sudo apt-get update > /dev/null
sudo apt-get install nodejs -y > /dev/null
sudo apt-get install nodejs-legacy -y > /dev/null
sudo apt-get install npm -y > /dev/null
<file_sep>/README.md
Configuration
=============
* [Nginx Tutorial](https://www.youtube.com/watch?v=FJrs0Ar9asY)
* 4 Boxes Running Precise64
* Node Express App Running on Port 3000 (.2 box)
* Nginx (.4 box) - this is where the domain will resolve
* Install thru apt-get
* /etc/nginx/nginx.conf
* One worker process per CPU
* sites-enabled
* ab - [Apache Bench](httpd.apache.org/docs/2.2/programs/ab.html)
<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANT_CONFIG_VERSION = 2
Vagrant.configure(VAGRANT_CONFIG_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.define "app1" do |app|
app.vm.network "private_network", ip: "192.168.33.2"
app.vm.provision "shell", path: "provision/app.sh"
end
config.vm.define "app2" do |app|
app.vm.network "private_network", ip: "192.168.33.3"
app.vm.provision "shell", path: "provision/app.sh"
end
config.vm.define "app3" do |app|
app.vm.network "private_network", ip: "192.168.33.5"
app.vm.provision "shell", path: "provision/app.sh"
end
config.vm.define "load_balancer" do |load_balancer|
load_balancer.vm.network "private_network", ip: "192.168.33.4"
load_balancer.vm.provision "shell", path: "provision/loadBalancer.sh"
end
end
|
cc64b77e59c73d0320b460bc83ee9c2b87a3de2e
|
[
"Markdown",
"Ruby",
"Shell"
] | 4 |
Shell
|
josebur86/scaling
|
1bf8ace06b374982f75201f67784981763fe77ca
|
2aec1b97d5f0c3d0891d24a7018e5235ec90271f
|
refs/heads/master
|
<repo_name>spikeeSakshu/CFG<file_sep>/sfile.c
#import<stdio.h>
int main ( )
{
int x = 10 ;
int y = 20 ;
int greater ;
if ( x < y )
{
greater = y ;
}
else
{
greater = x ;
}
printf ( "%d" , greater ) ;
}
<file_sep>/test_while.c
int evensum(int i)
{
int sum=0;
while (i<=10)
{
if (i/2==0)
{
sum=sum+i;
}
i++;
}
return sum;
}
<file_sep>/try.c
int main() {
int i, grade = 0;
printf (" Enter points: \n");
scanf ("%d", &i);
if (i >= 50 && i <= 60)
grade = 5;
else if (i > 50 && i <= 60)
grade = 6;
else if (i > 60 && i <= 70)
grade = 7;
else if (i > 70 && i <= 80)
grade = 8;
else if (i > 80 && i <= 90)
grade = 9;
else if (i > 90 && i <= 100)
grade = 10;
char sign = ' ';
if (grade) {
int p = i % 10;
if (grade != 5) {
if (p >= 1 && p <= 3)
sign = '-';
else if (grade != 10 && (p >= 8 || p == 0))
sign = '+';
}
printf (" The grade is %d%c. \n", grade, sign);
}
return 0;
}
<file_sep>/CFG.py
"""
Created on Mon Nov 24 13:16:00 2018
@author: Spikee
"""
import re
from pythonds.basic.stack import Stack
read_lines=list()
lines=list()
stack=Stack()
num=Stack()
breakFlags=Stack()
continueFlags=Stack()
ifFlag=Stack()
def parseData():
for line in file.readlines():
read_lines.append(line)
file.close()
removeSpace()
# preprocessing of the file to remove extra spaces
def removeSpace():
lines.clear() #To clear the initial Lines list
for line in read_lines:
if len(line)==0:
continue
lines.append(re.sub(r'\s+',' ',line).strip())
CheckLines()
def CheckLines():
line_num=0
endif=0
endelse=0
size=len(lines)
matrix=[[0 for x in range(size)]for x in range(size)]
while (line_num<size):
if "#" in lines[line_num]:
matrix[line_num][line_num+1]=1
elif "if" in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('if')
num.push(line_num)
ifFlag.push(line_num)
elif 'else if' in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('else if')
num.push(line_num)
ifFlag.push(line_num)
elif "else" in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('else')
num.push(line_num)
elif "while" in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('while')
num.push(line_num)
elif "do" in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('do')
num.push(line_num)
elif "for" in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('for')
num.push(line_num)
elif "switch" in lines[line_num]:
matrix[line_num][line_num+1]=1
stack.push('switch')
num.push(line_num)
elif "case" in lines[line_num]:
matrix[line_num][line_num+1]=1
matrix[num.peek()][line_num]=1
elif "default " in lines[line_num] or 'default:' in lines[line_num] :
matrix[line_num][line_num+1]=1
matrix[num.peek()][line_num]=1
elif "break" in lines[line_num]:
breakFlags.push(line_num)
elif "continue" in lines[line_num]:
continueFlags.push(line_num)
elif "{" in lines[line_num]:
matrix[line_num][line_num+1]=1
elif "}" in lines[line_num]:
if line_num==size-1 :
break
s=stack.peek()
if breakFlags.isEmpty()== False:
if s is not 'if' and s is not 'else' and s is not 'else if':
matrix[breakFlags.pop()][num.peek()]=1
if continueFlags.isEmpty()== False:
if s is not 'if' and s is not 'else' and s is not 'else if':
matrix[continueFlags.pop()][num.peek()]=1
if stack.isEmpty()== False:
if s is 'else':
num.pop()
stack.pop()
else:
matrix[num.pop()][line_num+1]=1
stack.pop()
if s=='if':
endif=line_num
if s=='else':
endelse=line_num+1
matrix[endif][endelse]=1
matrix[line_num][line_num+1]=1
#if '}while' and stack.peek() is 'do':
# matrix[line_num][num.pop()]=1
# stack.pop()
elif ')' in lines[line_num]:
matrix[line_num][line_num+1]=1
elif ';' in lines[line_num]:
matrix[line_num][line_num+1]=1
line_num+=1
printMatrix(matrix)
# To Print the Adjacency
def printMatrix(matrix):
print("PRINTING...")
i=1
size=len(matrix)
for k in range(1,size+1):
print(k,end=" ")
print()
for row in matrix:
out.write(str(row)+"\n")
for j in row:
print(j,end=" " )
print(i)
i+=1
out.close()
file=open("test_while.c","r")
out=open("output_while.txt","w")
parseData()
<file_sep>/README.md
# CFG
Python Code to compute the Control Flow Graph and store the result in a Adjacency Matrix
|
07dc215e8084729e4ec6b2f4e01082f52b55dc79
|
[
"Markdown",
"C",
"Python"
] | 5 |
C
|
spikeeSakshu/CFG
|
fb1583c04a979bb4db9ef498ee6d5b2010c30a2e
|
171786c36898d69e6eadeb41f2609de0ef39f92d
|
refs/heads/master
|
<repo_name>swnesbitt/pyrect<file_sep>/README.md
Radar echo classification toolkit
=================================
This is a cloud and weather radar echo classification toolkit, primarily written in the Python programming language.
Dependencies
------------
* [pyart](https://github.com/ARM-DOE/pyart)
<file_sep>/pyrect/util/__init__.py
"""
"""
from .textures import add_textures
<file_sep>/pyrect/util/texture.py
"""
echo.util.texture
=================
A submodule for computing texture fields from radar fields. A texture field is
defined as the standard deviation of a radar measurement within a 1-D or 2-D
window centered around a radar gate.
"""
import time
import numpy as np
from pyart.config import get_fillvalue, get_field_name
from ._texture import compute_texture
def add_textures(
radar, fields=None, gatefilter=None, window=(3, 3), min_sample=5,
min_sweep=None, max_sweep=None, min_range=None, max_range=None,
rays_wrap_around=False, fill_value=None, debug=False, verbose=False):
"""
Add texture fields to radar.
Parameters
----------
radar : Radar
Py-ART Radar containing specified field.
fields : str or list or tuple, optional
Radar field(s) to compute texture field(s). If None, texture fields
for all available radar fields will be computed and added.
gatefilter : GateFilter, optional
Py-ART GateFilter specifying radar gates which should be included when
computing the texture field.
window : list or tuple, optional
The 2-D (ray, gate) texture window used to compute texture fields.
min_sample : int, optional
Minimum sample size within texture window required to define a valid
texture. Note that a minimum of 2 radar gates are required to compute
the texture field.
min_sweep : int, optional
Minimum sweep number to compute texture field.
max_sweep : int, optional
Maximum sweep number to compute texture field.
min_range : float, optional
Minimum range in meters from radar to compute texture field.
max_range : float, optional
Maximum range in meters from radar to compute texture field.
fill_value : float, optional
Value indicating missing or bad data in radar field data. If None,
default value in Py-ART configuration file is used.
debug : bool, optional
True to print debugging information, False to suppress.
verbose : bool, optional
True to print progress and identification information, False to
suppress.
"""
# Parse fill value
if fill_value is None:
fill_value = get_fillvalue()
# Parse fields to compute textures
# If no fields are specified then the texture field of all available radar
# fields are computed
if fields is None:
fields = radar.fields.keys()
if isinstance(fields, str):
fields = [fields]
# Parse texture window parameters
ray_window, gate_window = window
if verbose:
print 'Number of rays in window: {}'.format(ray_window)
print 'Number of gates in window: {}'.format(gate_window)
for field in fields:
if verbose:
print 'Computing texture field: {}'.format(field)
_add_texture(
radar, field, gatefilter=gatefilter, ray_window=ray_window,
gate_window=gate_window, min_sample=min_sample,
min_sweep=min_sweep, max_sweep=max_sweep, min_range=min_range,
max_range=max_range, rays_wrap_around=rays_wrap_around,
fill_value=fill_value, debug=debug, verbose=verbose)
return
def _add_texture(
radar, field, gatefilter=None, ray_window=3, gate_window=3,
min_sample=5, min_sweep=None, max_sweep=None, min_range=None,
max_range=None, rays_wrap_around=False, fill_value=None,
text_field=None, debug=False, verbose=False):
"""
Compute the texture field (standard deviation) of the input radar field
within a 1-D or 2-D window.
Parameters
----------
radar : Radar
Py-ART Radar containing specified field.
field : str
Radar field to compute texture field.
gatefilter : GateFilter, optional
Py-ART GateFilter specifying radar gates which should be included when
computing the texture field.
ray_window : int, optional
Number of rays in texture window.
gate_window : int, optional
Number of range gates in texture window.
min_sample : int, optional
Minimum sample size within texture window required to define a valid
texture. Note that a minimum of 2 radar gates are required to compute
the texture field.
min_sweep : int, optional
Minimum sweep number to compute texture field.
max_sweep : int, optional
Maximum sweep number to compute texture field.
min_range : float, optional
Minimum range in meters from radar to compute texture field.
max_range : float, optional
Maximum range in meters from radar to compute texture field.
fill_value : float, optional
Value indicating missing or bad data in radar field data. If None,
default value in Py-ART configuration file is used.
debug : bool, optional
True to print debugging information, False to suppress.
verbose : bool, optional
True to print relevant information, False to suppress.
"""
# Parse fill value
if fill_value is None:
fill_value = get_fillvalue()
# Parse field names
if text_field is None:
text_field = '{}_texture'.format(field)
# Parse radar data
data = radar.fields[field]['data'].copy()
# Mask sweeps outside of specified sweep range
for sweep, slc in enumerate(radar.iter_slice()):
if min_sweep is not None and sweep < min_sweep:
data[slc] = np.ma.masked
if max_sweep is not None and sweep > max_sweep:
data[slc] = np.ma.masked
# Mask radar range gates outside specified gate range
if min_range is not None:
idx = np.abs(radar.range['data'] - min_range).argmin()
data[:,:idx+1] = np.ma.masked
if max_range is not None:
idx = np.abs(radar.range['data'] - max_range).argmin()
data[:,idx+1:] = np.ma.masked
# Parse gate filter information
if gatefilter is not None:
data = np.ma.masked_where(gatefilter.gate_excluded, data)
if debug:
N = np.ma.count(data)
print 'Sample size of data field: {}'.format(N)
# Parse sweep start and end indices
sweep_start = radar.sweep_start_ray_index['data']
sweep_end = radar.sweep_end_ray_index['data']
# Record starting time
start = time.time()
# Compute texture field
sigma, sample_size = compute_texture(
np.ma.filled(data, fill_value), sweep_start, sweep_end,
ray_window=ray_window, gate_window=gate_window,
rays_wrap_around=rays_wrap_around, fill_value=fill_value,
debug=debug, verbose=verbose)
# Record elapsed time to compute texture
elapsed = time.time() - start
if debug:
print('Elapsed time to compute texture: {:.2f} sec'.format(elapsed))
if min_sample is not None:
sigma = np.ma.masked_where(sample_size < min_sample, sigma)
sigma = np.ma.masked_invalid(sigma)
sigma = np.ma.masked_values(sigma, fill_value, atol=1.0e-5)
if debug:
N = np.ma.count(sigma)
print 'Sample size of texture field: {}'.format(N)
sigma_dict = {
'data': sigma,
'units': '',
'valid_min': 0.0,
'number_of_rays': ray_window,
'number_of_gates': gate_window,
}
radar.add_field(text_field, sigma_dict, replace_existing=True)
return
|
67c9c94ebfd876449be3ba1411d3055e04bfed5c
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
swnesbitt/pyrect
|
bf9880661a02535cf1a8df66b3d3ec270b158186
|
eab5ef3bc4dd4dedcc71bf926be1b10dd6c8d366
|
refs/heads/master
|
<file_sep><?php
include "signin.html";
?><file_sep>---------open source-------
# signin
a simple signin for webapps
-------open source------
requirements
--must have a database
--upload the table sql file pack
--php7 is required
--HTML5 is required
<file_sep><?php
$localhost = "localhost";
$username = "root";
$pass = "";
$dbname = "weets";
$con = mysqli_connect($localhost, $username, $pass, $dbname);
if($con){
}
else{
echo "connection error";
}
?><file_sep><?php
include '../config.php';
$username = $_POST['username'];
$pasword = $_POST['<PASSWORD>'];
$u = "SELECT * FROM `signin` WHERE `username` = '$username' AND `pasword` = '$<PASSWORD>'";
$u1 = mysqli_query($con, $u);
$u2 = mysqli_num_rows($u1);
if($u2>0){
while ($info = mysqli_fetch_assoc($u1)){
$firstname = $info['firstname'];
echo $firstname;
}
}
else{
echo "incorrect username or password";
}
<file_sep>create table `signin` (
`signID` int(30) auto_increment,
`firstname` text not null,
`surname` text not null,
`country` text not null,
`dateb` text not null,
`monthb` text not null,
`yearb` text not null,
`username` text not null,
`pasword` text not null,
`acctype` text not null,
primary key(`signID`)
)
engine=myisam character set utf8 collate=utf8_general_ci;
|
b218510bba5b485f28a5cbbc6b3c289512f6a948
|
[
"Markdown",
"SQL",
"PHP"
] | 5 |
PHP
|
weetsapp/signin
|
557733af72e21686dbfbafecbd875a2b965f92fc
|
e0813743fa9a33b26da70e03a341c65b4cbe07b3
|
refs/heads/master
|
<repo_name>ThaboMatlenana/Get_Next_Line<file_sep>/get_next_line.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmatlena <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/21 11:09:36 by tmatlena #+# #+# */
/* Updated: 2018/06/29 10:40:57 by tmatlena ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static int stoping_point(char *buff)
{
int i;
i = 0;
while (buff[i] != '\n' && buff[i])
i++;
if (buff[i] == '\n')
{
buff[i] = '\0';
return (i);
}
else
return (-1);
}
static char *add(char *buff, char *buz)
{
size_t len1;
size_t len2;
char *ptr;
len1 = 0;
len2 = 0;
if (buff)
len1 = ft_strlen(buff);
if (buz)
len2 = ft_strlen(buz);
ptr = (char *)malloc(sizeof(*ptr) * (len1 + len2 + 1));
ft_memcpy(ptr, buff, len1);
ft_memcpy(ptr + len1, buz, len2);
ptr[len1 + len2] = '\0';
free(buff);
ft_bzero(buz, BUFF_SIZE + 1);
return (ptr);
}
static int check(char **buff, char **buz, char **line)
{
char *ptr;
int final;
*buff = add(*buff, *buz);
final = stoping_point(*buff);
if (final > -1)
{
*line = ft_strdup(*buff);
ptr = *buff;
*buff = ft_strdup(*buff + final + 1);
free(ptr);
return (1);
}
return (0);
}
int get_next_line(int const fd, char **line)
{
static char *buff[12000];
char *tmp;
int ret;
int result;
tmp = ft_strnew(BUFF_SIZE);
if (!line || BUFF_SIZE <= 0 || fd < 0 || (ret = read(fd, tmp, 0)) < 0)
return (-1);
while ((ret = read(fd, tmp, BUFF_SIZE)) > 0)
{
result = check(&buff[fd], &tmp, line);
free(tmp);
if (result == 1)
return (1);
tmp = ft_strnew(BUFF_SIZE);
}
if ((result = check(&buff[fd], &tmp, line)))
return (1);
else if (ft_strlen(buff[fd]) > 0)
{
*line = ft_strdup(buff[fd]);
ft_strdel(&buff[fd]);
return (1);
}
return (result);
}
<file_sep>/libft/Makefile
# **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: tmatlena <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/05/30 14:28:25 by tmatlena #+# #+# #
# Updated: 2018/06/14 14:29:12 by tmatlena ### ########.fr #
# #
# **************************************************************************** #
NAME = libft.a
INCLUDE = ./libft.h
SRC = ft_memccpy.c ft_putnbr.c ft_strequ.c ft_strnequ.c ft_memchr.c \
ft_putnbr_fd.c ft_striter.c ft_strnew.c ft_atoi.c \
ft_memcmp.c ft_putstr.c ft_striteri.c ft_strnstr.c \
ft_bzero.c ft_memcpy.c ft_putstr_fd.c ft_strjoin.c \
ft_strrchr.c ft_isalnum.c ft_memdel.c ft_strcat.c ft_strlcat.c \
ft_strsplit.c ft_isalpha.c ft_memmove.c ft_strchr.c ft_strlen.c \
ft_strstr.c ft_isascii.c ft_memset.c ft_strclr.c ft_strmap.c ft_strsub.c \
ft_isdigit.c ft_putchar.c ft_strcmp.c ft_strmapi.c ft_strtrim.c \
ft_isprint.c ft_putchar_fd.c ft_strcpy.c ft_strncat.c ft_tolower.c \
ft_itoa.c ft_putendl.c ft_strdel.c ft_strncmp.c ft_toupper.c \
ft_memalloc.c ft_putendl_fd.c ft_strdup.c ft_strncpy.c \
OBJ = ft_memccpy.o ft_putnbr.o ft_strequ.o ft_strnequ.o ft_memchr.o \
ft_putnbr_fd.o ft_striter.o ft_strnew.o ft_atoi.o \
ft_memcmp.o ft_putstr.o ft_striteri.o ft_strnstr.o \
ft_bzero.o ft_memcpy.o ft_putstr_fd.o ft_strjoin.o \
ft_strrchr.o ft_isalnum.o ft_memdel.o ft_strcat.o ft_strlcat.o \
ft_strsplit.o ft_isalpha.o ft_memmove.o ft_strchr.o ft_strlen.o \
ft_strstr.o ft_isascii.o ft_memset.o ft_strclr.o ft_strmap.o ft_strsub.o \
ft_isdigit.o ft_putchar.o ft_strcmp.o ft_strmapi.o ft_strtrim.o \
ft_isprint.o ft_putchar_fd.o ft_strcpy.o ft_strncat.o ft_tolower.o \
ft_itoa.o ft_putendl.o ft_strdel.o ft_strncmp.o ft_toupper.o \
ft_memalloc.o ft_putendl_fd.o ft_strdup.o ft_strncpy.o \
all: $(NAME)
$(NAME): $(OBJ)
ar rc $(NAME) $(OBJ)
ranlib $(NAME)
$(OBJ): $(SRC)
gcc -Wall -Werror -Wextra -c -I$(INCLUDE) $(SRC)
clean:
rm -f $(OBJ)
fclean:
rm -f $(NAME) $(OBJ)
re: fclean all
|
01b7f59e682c8d655446609a82d7bc1e5dcf0d1b
|
[
"C",
"Makefile"
] | 2 |
C
|
ThaboMatlenana/Get_Next_Line
|
eaf172ad3f4b907c7725580766cf27494a9f6050
|
7601f81c8e20fb56d45e34d0cca87be692066d1e
|
refs/heads/master
|
<file_sep>/**
* Created by 罗志伟 on 2016/10/25.
*/
//console.log("node.js 是前端使用的最好的后端语言");
'use strict';//javaScript 严格模式
var http = require('http');//request 表示引入 http是node.js 的负责网络请求的模块
//https 是加密的http请求协议
var https = require('https');
//引入文件处理模块
var fs = require('fs');
//创建文件,将helloworld写入文件
fs.writeFile('a.text','hello world',function(err){
console.log("保存成功");
});
//引入路径模块
var path = require('path');
//cheerio 可以将一个html(dom)片段在服务器端环境运行起来一个jquery的效果,直接使用 jquery获得元素的方法获得内容
var cheerio = require('cheerio');
//请求某个网页
https.get('https://movie.douban.com/top250?start=0',function(res){
//console.log(res);
var html = '';
var movies = [];
//设置返回结果的字符集
res.setEncoding('utf-8');
//data发生在有数据到达的时候 执行回调 chunk 里面就是到达的数据
res.on('data',function(chunk){
html = html + chunk;
});
res.on('end',function(){
//cheerio 将 load方法 ,将html变成dom可查询状态
var $ = cheerio.load(html);
//获取所有的item each方法
$('.item').each(function(index,object){
var picUrl = $('.pic img',this).attr('src');
console.log(picUrl);
downloadImg('./img/',picUrl);
});
//fs.writeFile('a.text',html,function(err){
// console.log('保存成功');
//});
})
});
//下载图片保存到img的目录下
function downloadImg(imgDir,url){
https.get(url,function(res){
var data = '';
res.setEncoding('binary');
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
fs.writeFile(imgDir+path.basename(url),data,'binary',function(err){
if(err){
console.log('下载失败');
}else{
console.log('下载成功');
}
})
})
})
}
//生成器函数
//function *doSpider(x){
//
//}<file_sep># spider
爬虫
|
403542aa0f35efee94bf58e3f54f4f3a52bc7b06
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
jeft224/spider
|
2d4daed3cebea9a058e7bfa2826f81668003f515
|
c287e3a661e0076059bec40c919d18ba6868b90c
|
refs/heads/master
|
<file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>User Login</title>
</head>
<link rel="stylesheet" type="text/css" href="../libs/css/style.css"/>
<body>
<form id="frmTest" action="Login.php" method="POST">
<h2>LOGIN PAGE</h2>
<label class="label-text">Username</label></br>
<input class="input-text" name="username" type="text" maxlength="50" value="<?php echo
isset($_POST['username']) ? $_POST['username'] : "" ?>" /></br>
<label class="label-text">Password</label></br>
<input class="input-text" name="password" type="password" maxlength="50" value="<?php echo
isset($_POST['password']) ? $_POST['password'] : "" ?>" /></br>
<div class="div_button">
<input class="input-button" name="btnLogin" type="submit" value="Login"/>
<input class="input-button" name="btnSignUp" type="button" onclick="clickSignUp()" value="Sign Up"/>
<input class="input-button" name="btnChangePass" type="button" onclick="clickChangePass()" value="Change Pass"/>
</div>
</form>
</body>
<?php
require (dirname(__file__) . "/../controller/LoginController.php");
$login=new LoginController();
$login->checkAuthen();
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
session_destroy();
}
?>
<script type="text/javascript">
clickSignUp = function(){
window.location.href='signup.php';
}
clickChangePass=function(){
window.location.href='changepass.php';
}
</script>
</html><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../common/Db_helper.php");
class LocationBussiness extends Db_helper
{
function selectCatLocation()
{
$sql = "select a.*,b.location_name parentName from cat_location a left join cat_location b on a.parent_id=b.location_id";
return parent::getDataBySQL($sql);
}
function selectCatParentLocation()
{
$sql = "select * from cat_location where parent_id is null";
return parent::getDataBySQL($sql);
}
function selectCatChildLocation()
{
$sql = "select * from cat_location where parent_id is not null";
return parent::getDataBySQL($sql);
}
function selectChildLocationByParent($parentId)
{
$sql = "select * from cat_location where parent_id ='".$parentId."'";
return parent::getDataBySQL($sql);
}
function insertLocation($table, $array)
{
return parent::insertDB($table, $array);
}
function deleteLocation($location_id){
$clause=' location_id="'.$location_id.'" or parent_id ="'.$location_id.'"';
return parent::deleteDB('cat_location',$clause);
}
function selectLocationById($locationId){
$sql = "select * from cat_location where location_id='".$locationId."'";
return parent::getDataBySQL($sql);
}
function updateLocation($array,$location_id){
$clause='location_id='.$location_id;
return parent::updateDB('cat_location',$array,$clause);
}
}
?><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
class Alert_Common
{
function alertNotReturn($message)
{
return '<script type="text/javascript">alert("' . $message . '");</script>';
}
function alertReturn($message, $url)
{
return '<script type="text/javascript">alert("' . $message .
'");window.location.href="' . $url . '";</script>';
}
function AlertConfirm($msg) {
return '<script type="text/javascript">confirm("' . $msg . '");</script>';
}
}
?><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../model/LoginBussiness.php");
require_once (dirname(__file__) . "/../common/Alert_Common.php");
class LoginController
{
//Kiem tra dang nhap
function checkAuthen(){
session_start();
$bussiness=new LoginBussiness();
$alert=new Alert_Common();
if (isset($_REQUEST['btnLogin'])) {
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
if (empty($username)) {
echo $alert->alertNotReturn("Username must requied");
} else
if (empty($password)) {
echo $alert->alertNotReturn("Password must requied");
} else {
$rs = $bussiness->getDataByUsernameAndPassword($username, $password);
if (count($rs)>0) {
$_SESSION['username'] = $username;
$_SESSION['role'] = $rs[0]['role'];
header('Location: /hungnd/demo-mvc/index.php');
exit;
} else {
echo $alert->alertNotReturn('Wrong username or password. Please try again!');
}
}
}
}
//Doi mat khau
function changePass(){
$bussiness=new LoginBussiness();
$alert=new Alert_Common();
if (isset($_REQUEST['btnChangePass'])) {
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$passwordOld = isset($_POST['passwordOld']) ? $_POST['passwordOld'] : "";
$passwordRetype = isset($_POST['passwordRetype']) ? $_POST['passwordRetype'] : "";
if (empty($username)) {
echo $alert->alertNotReturn("Username must requied");
} else if (empty($password)) {
echo $alert->alertNotReturn("Password New must requied");
} else if (empty($passwordOld)) {
echo $alert->alertNotReturn("Password Old must requied");
}else if (empty($passwordRetype)) {
echo $alert->alertNotReturn("Password New Retype must requied");
}else if ($password != $passwordRetype) {
echo $alert->alertNotReturn("Password New not match");
}else{
$data=$bussiness->selectByUsername($username);
if (count($data) < 1) {
echo $alert->alertNotReturn("Username is not found");
}else if (count($bussiness->selectByPassword($username,md5($passwordOld))) < 1) {
echo $alert->alertNotReturn("Password Old is wrong");
} else {
$arrayData = array();
$arrayData['password'] = md5($password);
$rs = $bussiness->updateUser($arrayData,$data[0]['user_id']);
if ($rs) {
echo $alert->alertReturn('Change password success', 'Login.php');
} else {
echo $alert->alertNotReturn($rs);
}
}
}
}
}
//dang ky account dang nhap
function signUpAccount(){
$bussiness=new LoginBussiness();
$alert=new Alert_Common();
if (isset($_REQUEST['btnSignUp'])) {
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$passwordRetype = isset($_POST['passwordRetype']) ? $_POST['passwordRetype'] : "";
if (empty($username)) {
echo $alert->alertNotReturn("Username must requied");
} else
if (empty($password)) {
echo $alert->alertNotReturn("Password must requied");
} else if (empty($passwordRetype)) {
echo $alert->alertNotReturn("Password Retype must requied");
} else if ($password != $passwordRetype) {
echo $alert->alertNotReturn("Password not match");
} else if (count($bussiness->selectByUsername($username)) > 0) {
echo $alert->alertNotReturn("Username is duplicate");
} else {
$arrayData = array();
$arrayData['username'] = $username;
$arrayData['password'] = md5($<PASSWORD>);
if(count($bussiness->selectData())<1){
$arrayData['role'] = '1';
}
$rs = $bussiness->insertReturnId('sys_users',$arrayData);
$arr=array();
$arr['user_id']=$rs;
$bussiness->insertDB('users_info',$arr);
if ($rs) {
echo $alert->alertReturn('Create account success', 'Login.php');
} else {
echo $alert->alertNotReturn($rs);
}
}
}
}
}
?><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>User Manager</title>
<link rel="stylesheet" type="text/css" href="libs/css/style.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: /hungnd/demo-mvc/view/Login.php');
exit;
}
?>
<body>
<div id="divLeft"></div>
<div id="divCenter">
<?php include 'view/headerPages.php' ?>
<table>
<tr>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>Zip Code</th>
<th>About</th>
<th>Website</th>
<th>Facebook</th>
<th>Twitter</th>
<th>Other</th>
<th>Action</th>
</tr>
<?php
require (dirname(__file__) . "/../controller/UsersController.php");
$users = new UsersController();
$arr=$users->onSearchAllUsers();
for($i=0;$i< count($arr);$i++){
echo '<tr>';
echo '<td>'.$arr[$i]['username'].'</td>';
echo '<td>'.$arr[$i]['first_name'].'</td>';
echo '<td>'.$arr[$i]['last_name'].'</td>';
echo '<td>'.$arr[$i]['email'].'</td>';
echo '<td>'.$arr[$i]['nationalName'].' - '.$arr[$i]['provinceName'].' - '.$arr[$i]['home_address'].'</td>';
echo '<td>'.$arr[$i]['zip_code'].'</td>';
echo '<td>'.$arr[$i]['about'].'</td>';
echo '<td>'.$arr[$i]['website'].'</td>';
echo '<td>'.$arr[$i]['facebook'].'</td>';
echo '<td>'.$arr[$i]['twitter'].'</td>';
echo '<td>'.$arr[$i]['other'].'</td>';
echo '<td><a onclick="onPreUpdate('.$arr[$i]['userId'].')" ><img width="70px" height="30px" src="http://www.clker.com/cliparts/e/0/H/N/J/2/edit-button-blue-md.png"/></a>
<a onclick="confirmAlert('.$arr[$i]['userId'].')" ><img width="70px" height="30px" src="http://www.clker.com/cliparts/L/8/M/t/O/G/delete-button-blue-md.png"/></a></td>';
echo '</tr>';
}
?>
</table>
<div id="divFooter">
</div>
<div id="divRight">
</div>
</body>
<script type="text/javascript">
confirmAlert=function(id){
if(confirm('Do you want to delete record?')){
//window.location.href='?action=deleteLocation&id='+id;
}
}
onPreUpdate=function(id){
window.location.href='?action=updateUser&user_id='+id;
}
</script>
</html>
<file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
class Db_helper
{
private $conn;
function getConnect()
{
error_reporting(E_ALL ^ E_DEPRECATED);
if ($this->conn == null) {
$this->conn = mysql_connect('localhost', 'root', '') or die("can't connect this database");
mysql_select_db('hungnd_test', $this->conn);
mysql_query('CREATE TABLE IF NOT EXISTS sys_users (
user_id int(10) NOT NULL AUTO_INCREMENT,
username varchar(100) NOT NULL,
password varchar(100) NOT NULL,
role int(1) NOT null DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id)
) ') or die('Create table sys_users false');
mysql_query('CREATE TABLE IF NOT EXISTS users_info(
first_name varchar(50),
last_name varchar(50),
email varchar(100),
national int(10),
province int(10),
home_address varchar(200),
zip_code varchar(20),
about text,
website varchar(100),
facebook varchar(100),
twitter varchar(100),
other varchar(100),
user_id int(10),
PRIMARY KEY(user_id)
)') or die('Create table users_info false');
mysql_query('CREATE TABLE IF NOT EXISTS cat_location(
location_id int(10) NOT null AUTO_INCREMENT,
location_name varchar(200),
parent_id int(10),
PRIMARY KEY (location_id)
)')or die('Create table cat_location false');
}
}
function getDataBySQL($query)
{
$this->getConnect();
$data = mysql_query($query) or die("Can not query");
$array_result = array();
while ($row = mysql_fetch_array($data)) {
$array_result[] = $row;
}
return $array_result;
}
function insertDB($table, $data)
{
$this->getConnect();
$field_list = '';
$value_list = '';
// Lặp qua data
foreach ($data as $key => $value) {
$field_list .= $key . ",";
$value_list .= "'" . $value . "',";
}
$sql = 'INSERT INTO ' . $table . '(' . rtrim($field_list, ',') . ') VALUES (' .
rtrim($value_list, ',') . ')';
$rs = mysql_query($sql);
return $rs;
}
function insertReturnId($table, $data)
{
$this->getConnect();
$field_list = '';
$value_list = '';
// Lặp qua data
foreach ($data as $key => $value) {
$field_list .= $key . ",";
$value_list .= "'" . $value . "',";
}
$sql = 'INSERT INTO ' . $table . '(' . rtrim($field_list, ',') . ') VALUES (' .
rtrim($value_list, ',') . ')';
$rs = mysql_query($sql);
return mysql_insert_id();
}
function updateDB($table, $data,$clause)
{
$this->getConnect();
$field_list = '';
// Lặp qua data
foreach ($data as $key => $value) {
$field_list .= $key . "='" . $value . "',";
}
$sql = 'UPDATE '.$table.' SET '.rtrim($field_list,',').' WHERE '.$clause;
$rs = mysql_query($sql);
return $rs;
}
function deleteDB($table,$clause)
{
$this->getConnect();
$sql = 'DELETE FROM '.$table.' WHERE '.$clause;
$rs = mysql_query($sql);
return $rs;
}
}
?><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../controller/LocationController.php");
$location=new LocationController();
$location->deleteLocation();
?><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>User Manager</title>
<link rel="stylesheet" type="text/css" href="libs/css/style.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: /hungnd/demo-mvc/view/Login.php');
exit;
}
require_once (dirname(__file__) . "/../controller/LocationController.php");
$location=new LocationController();
$row=$location->getLocationById();
?>
<body>
<div id="divLeft"></div>
<div id="divCenter">
<?php include 'view/headerPages.php' ?>
<form method="POST" style="float: left;width: 100%;">
<h2>Update location form</h2>
<label class="label-text">Location Name</label></br>
<input class="input-text" name="locationName" value="<?php if (isset($row[0]['location_name'])){echo $row[0]['location_name'];}
else if (isset($_POST['locationName'])){echo $_POST['locationName'];}?>" type="text" maxlength="50" /></br>
<label class="label-text">Location Parent</label></br>
<select id="cbRole" class="input-text" name="locationParent" size=1>
<option value="-1" >--Choose--</option>
<?php
require_once (dirname(__file__) . "/../controller/LocationController.php");
$location=new LocationController();
$arrData=$location->onSearchParentCatLocation();
for($i=0;$i<count($arrData);$i++){
if(isset($row[0]['parent_id']) && $row[0]['parent_id'] == $arrData[$i]['location_id']){
echo '<option value="'.$arrData[$i]['location_id'].'" selected="selected">'.$arrData[$i]['location_name'].'</option>';
}else{
echo '<option value="'.$arrData[$i]['location_id'].'">'.$arrData[$i]['location_name'].'</option>';
}
}
?>
</select>
</br></br>
<div class="div_button">
<input class="input-button" name="btnUpdateLocation" type="submit" value="Save"/>
<input class="input-button" name="btnBack" type="button" onclick="onBack()" value="Back"/>
</div>
</form>
<div id="divFooter">
</div>
<div id="divRight">
<?php
require_once (dirname(__file__) . "/../controller/LocationController.php");
$location=new LocationController();
$location->updateLocation();
?>
</div>
</body>
<script type="text/javascript">
onBack=function(){
window.location.href='?action=manageLocation';
}
</script>
</html><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../model/LocationBussiness.php");
require_once (dirname(__file__) . "/../common/Alert_Common.php");
class LocationController{
//Lay danh sach du lieu trong bang cat location
function onSearchAllCatLocation(){
$bussiness=new LocationBussiness();
$data=$bussiness->selectCatLocation();
return $data;
}
//Lay danh sach du lieu cha trong bang cat location
function onSearchParentCatLocation(){
$bussiness=new LocationBussiness();
$data=$bussiness->selectCatParentLocation();
return $data;
}
//Lay danh sach du lieu con trong bang cat location
function onSearchChildCatLocation(){
$bussiness=new LocationBussiness();
$data=$bussiness->selectCatChildLocation();
return $data;
}
//Lay danh sach du lieu con ttheo parent id
function onSearchChildCatLocationByParent($parentId){
$bussiness=new LocationBussiness();
$data=$bussiness->selectChildLocationByParent($parentId);
return $data;
}
//Them danh sach dia ban
function insertLocation(){
$bussiness=new LocationBussiness();
$alert=new Alert_Common();
if (isset($_REQUEST['btnInsertLocation'])) {
$locationName = isset($_POST['locationName']) ? $_POST['locationName'] : "";
$locationParent = isset($_POST['locationParent']) ? $_POST['locationParent'] : "-1";
if (empty($locationName)) {
echo $alert->alertNotReturn("Location Name must requied");
} else{
$dt = array();
$dt['location_name'] = $locationName;
if($locationParent!='-1'){
$dt['parent_id'] = $locationParent;
}
$rs = $bussiness->insertLocation('cat_location',$dt);
if ($rs) {
echo $alert->alertReturn('Insert location success', '?action=manageLocation');
} else {
echo $alert->alertNotReturn($rs);
}
}
}
}
//Xoa dia ban
function deleteLocation(){
$bussiness=new LocationBussiness();
$alert=new Alert_Common();
if (isset($_GET['id'])) {
$rs = $bussiness->deleteLocation($_GET['id']);
echo $alert->alertReturn('Delete location success', '?action=manageLocation');
}
}
function getLocationById(){
$bussiness=new LocationBussiness();
if (isset($_GET['id'])) {
$rs = $bussiness->selectLocationById($_GET['id']);
return $rs;
}else{
echo $alert->alertReturn('Not found records', '?action=manageLocation');
}
}
function updateLocation(){
$bussiness=new LocationBussiness();
$alert=new Alert_Common();
if (isset($_REQUEST['btnUpdateLocation'])) {
if(isset($_GET['id'])){
$locationName = isset($_POST['locationName']) ? $_POST['locationName'] : "";
$locationParent = isset($_POST['locationParent']) ? $_POST['locationParent'] : "-1";
if (empty($locationName)) {
echo $alert->alertNotReturn("Location Name must requied");
} else{
$dt = array();
$dt['location_name'] = $locationName;
if($locationParent!='-1'){
$dt['parent_id'] = $locationParent;
}
$rs = $bussiness->updateLocation($dt,$_GET['id']);
if ($rs) {
echo $alert->alertReturn('Update location success', '?action=manageLocation');
} else {
echo $alert->alertNotReturn($rs);
}
}
}else{
echo $alert->alertReturn('Not found record', '?action=manageLocation');
}
}
}
}
?><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>User Manager</title>
<link rel="stylesheet" type="text/css" href="libs/css/style.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: /hungnd/demo-mvc/view/Login.php');
exit;
}
?>
<body>
<div id="divLeft"></div>
<div id="divCenter">
<?php include 'view/headerPages.php' ?>
<div id="divFooter">
</div>
<div id="divRight">
</div>
</body>
</html><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../model/UsersBussiness.php");
require_once (dirname(__file__) . "/../common/Alert_Common.php");
class UsersController{
//Lay danh sach du lieu trong bang sys_users va users_info
function onSearchAllUsers(){
$user=new UsersBussiness();
$data=$user->selectUsers();
return $data;
}
//Xoa users
function deleteUser(){
$user=new UsersBussiness();
$alert=new Alert_Common();
if (isset($_GET['id'])) {
$rs = $bussiness->deleteLocation($_GET['id']);
echo $alert->alertReturn('Delete user success', '?action=manageUser');
}
}
function getUsersByUserId(){
$user=new UsersBussiness();
if (isset($_GET['user_id'])) {
$rs = $user->selectUsersById($_GET['user_id']);
return $rs;
}else{
echo $alert->alertReturn('Not found records', '?action=manageUser');
}
}
function updateUsers(){
$user=new UsersBussiness();
$alert=new Alert_Common();
if (isset($_REQUEST['btnUpdateUsers'])) {
if(isset($_GET['user_id'])){
$firstName = isset($_POST['firstName']) ? $_POST['firstName'] : "";
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$national = isset($_POST['national']) ? $_POST['national'] : "-1";
$province = isset($_POST['province']) ? $_POST['province'] : "-1";
$home_address = isset($_POST['homeAddress']) ? $_POST['homeAddress'] : "";
$zip_code = isset($_POST['zipCode']) ? $_POST['zipCode'] : "";
$about = isset($_POST['about']) ? $_POST['about'] : "";
$website = isset($_POST['website']) ? $_POST['website'] : "";
$facebook = isset($_POST['facebook']) ? $_POST['facebook'] : "";
$twitter = isset($_POST['twitter']) ? $_POST['twitter'] : "";
$other = isset($_POST['other']) ? $_POST['other'] : "";
$dt = array();
$dt['first_name'] = $firstName;
$dt['last_name'] = $lastName;
$dt['email'] = $email;
if($national!='-1'){
$dt['national'] = $national;
}
if($province!='-1'){
$dt['province'] = $province;
}
$dt['home_address'] = $home_address;
$dt['zip_code'] = $zip_code;
$dt['about'] = $about;
$dt['website'] = $website;
$dt['facebook'] = $facebook;
$dt['twitter'] = $twitter;
$dt['other'] = $other;
$rs = $user->updateUser($dt,$_GET['user_id']);
if ($rs) {
echo $alert->alertReturn('Update User success', '?action=manageUser');
} else {
echo $alert->alertNotReturn($rs);
}
}else{
echo $alert->alertReturn('Not found record', '?action=manageUser');
}
}
}
}
?><file_sep><div id="divBanner"></div>
<ul id="menu">
<li><a href="?action=index">Home</a></li>
<li><a href="?action=manageLocation">Cat Location</a></li>
<li><a href="?action=manageUser">User Manager</a></li>
</ul>
<div id="divUser">
<label>Hello <?php echo "hung" ?>!</label>
|<a href='/hungnd/demo-mvc/view/Login.php?action=logout'>Log out</a>
</div><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>Change Pass</title>
</head>
<link rel="stylesheet" type="text/css" href="../libs/css/style.css"/>
<body>
<form id="frmTest" action="changepass.php" method="POST">
<h2>CHANGE PASS PAGE</h2>
<label class="label-text">Username</label></br>
<input class="input-text" name="username" type="text" maxlength="50" value="<?php echo
isset($_POST['username']) ? $_POST['username'] : "" ?>" /></br>
<label class="label-text">Old Password</label></br>
<input class="input-text" name="passwordOld" type="password" maxlength="50" value="<?php echo
isset($_POST['passwordOld']) ? $_POST['passwordOld'] : "" ?>" /></br>
<label class="label-text">New Password</label></br>
<input class="input-text" name="password" type="password" maxlength="50" value="<?php echo
isset($_POST['password']) ? $_POST['password'] : "" ?>" /></br>
<label class="label-text">Re-type New Password</label></br>
<input class="input-text" name="passwordRetype" type="password" maxlength="50" value="<?php echo
isset($_POST['passwordRetype']) ? $_POST['passwordRetype'] : "" ?>" /></br>
<div class="div_button">
<input class="input-button" name="btnChangePass" type="submit" value="Change"/>
<input class="input-button" name="btnBack" type="button" onclick="clickBack()" value="Back"/>
</div>
</form>
</body>
<?php
require (dirname(__file__) . "/../controller/LoginController.php");
$login=new LoginController();
$login->changePass();
?>
<script type="text/javascript">
clickBack = function(){
window.location.href='Login.php';
}
</script>
</html><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
$nation = $_GET['nation'];
$province=$_GET['province'];
require_once (dirname(__file__) . "/../controller/LocationController.php");
$location=new LocationController();
$rs=$location->onSearchChildCatLocationByParent($nation);
echo '<select class="input-text" name="province" size=1>';
echo '<option value="-1" >--Choose--</option>';
for($i=0; $i < count($rs);$i++){
if(isset($province) && $province == $rs[$i]['location_id']){
echo "<option value=" .$rs[$i]['location_id'] . " selected='selected' >" . $rs[$i]['location_name'] . "</option>";
}else{
echo "<option value=" .$rs[$i]['location_id'] . ">" . $rs[$i]['location_name'] . "</option>";
}
}
echo '</select>';
?><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>User Manager</title>
<link rel="stylesheet" type="text/css" href="libs/css/style.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: /hungnd/demo-mvc/view/Login.php');
exit;
}
require_once (dirname(__file__) . "/../controller/UsersController.php");
$users=new UsersController();
$row=$users->getUsersByUserId();
?>
<body>
<div id="divLeft"></div>
<div id="divCenter">
<?php include 'view/headerPages.php' ?>
<form method="POST" style="float: left;width: 100%;">
<h2>Update user form</h2>
<label class="label-text">Username</label></br>
<input class="input-text" name="username" readonly="true" value="<?php if (isset($row[0]['username'])){echo $row[0]['username'];}
else if (isset($_POST['username'])){echo $_POST['username'];}?>" type="text" maxlength="50" /></br>
<label class="label-text">First Name</label></br>
<input class="input-text" name="firstName" value="<?php if (isset($row[0]['first_name'])){echo $row[0]['first_name'];}
else if (isset($_POST['firstName'])){echo $_POST['firstName'];}?>" type="text" maxlength="50" /></br>
<label class="label-text">Last Name</label></br>
<input class="input-text" name="lastName" value="<?php if (isset($row[0]['last_name'])){echo $row[0]['last_name'];}
else if (isset($_POST['lastName'])){echo $_POST['lastName'];}?>" type="text" maxlength="50" /></br>
<label class="label-text">Email</label></br>
<input class="input-text" name="email" value="<?php if (isset($row[0]['email'])){echo $row[0]['email'];}
else if (isset($_POST['email'])){echo $_POST['email'];}?>" type="text" maxlength="50" /></br>
<label class="label-text">National</label></br>
<select id="cbNation" class="input-text" name="national" size=1 onchange="loadProvince(this.value,
<?php if (isset( $row[0]['province'])){echo $row[0]['province'];}else if(isset($_POST['province'])){echo $_POST['province'];}else{echo -1;};?>)">
<option value="-1" >--Choose--</option>
<?php
require_once (dirname(__file__) . "/../controller/LocationController.php");
$location=new LocationController();
$arrData=$location->onSearchParentCatLocation();
for($i=0;$i<count($arrData);$i++){
if(isset($row[0]['national']) && $row[0]['national'] == $arrData[$i]['location_id']){
echo '<option value="'.$arrData[$i]['location_id'].'" selected="selected">'.$arrData[$i]['location_name'].'</option>';
}else{
echo '<option value="'.$arrData[$i]['location_id'].'">'.$arrData[$i]['location_name'].'</option>';
}
}
?>
</select>
<label class="label-text">Province</label></br>
<div id="divProvince">
<select class="input-text" name="province" size=1>
<option value="-1" >--Choose--</option>
</select>
</div>
<label class="label-text">Home Address</label></br>
<input class="input-text" name="homeAddress" value="<?php if (isset($row[0]['home_address'])){echo $row[0]['home_address'];}
else if (isset($_POST['homeAddress'])){echo $_POST['homeAddress'];}?>" type="text" maxlength="200" /></br>
<label class="label-text">Zip code</label></br>
<input class="input-text" name="zipCode" value="<?php if (isset($row[0]['zip_code'])){echo $row[0]['zip_code'];}
else if (isset($_POST['zipCode'])){echo $_POST['zipCode'];}?>" type="text" maxlength="20" /></br>
<label class="label-text">About</label></br>
<input class="input-text" name="about" value="<?php if (isset($row[0]['about'])){echo $row[0]['about'];}
else if (isset($_POST['about'])){echo $_POST['about'];}?>" type="text" maxlength="2000" /></br>
<label class="label-text">Website</label></br>
<input class="input-text" name="website" value="<?php if (isset($row[0]['website'])){echo $row[0]['website'];}
else if (isset($_POST['website'])){echo $_POST['website'];}?>" type="text" maxlength="100" /></br>
<label class="label-text">Facebook</label></br>
<input class="input-text" name="facebook" value="<?php if (isset($row[0]['facebook'])){echo $row[0]['facebook'];}
else if (isset($_POST['facebook'])){echo $_POST['facebook'];}?>" type="text" maxlength="100" /></br>
<label class="label-text">Twitter</label></br>
<input class="input-text" name="twitter" value="<?php if (isset($row[0]['twitter'])){echo $row[0]['twitter'];}
else if (isset($_POST['twitter'])){echo $_POST['twitter'];}?>" type="text" maxlength="100" /></br>
<label class="label-text">Other</label></br>
<input class="input-text" name="other" value="<?php if (isset($row[0]['other'])){echo $row[0]['other'];}
else if (isset($_POST['other'])){echo $_POST['other'];}?>" type="text" maxlength="100" /></br>
</br></br>
<div class="div_button">
<input class="input-button" name="btnUpdateUsers" type="submit" value="Save"/>
<input class="input-button" name="btnBack" type="button" onclick="onBack()" value="Back"/>
</div>
</form>
<div id="divFooter">
</div>
<div id="divRight">
<?php
require_once (dirname(__file__) . "/../controller/UsersController.php");
$users=new UsersController();
$users->updateUsers();
?>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(e) {
$("#cbNation").change();
});
onBack=function(){
window.location.href='?action=manageUser';
}
loadProvince= function(national,province) {
document.getElementById("divProvince").innerHTML=httpGet("view/loadProvince.php?nation="+national+"&province="+province);
}
httpGet=function(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET",theUrl,false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
</script>
</html><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../common/Db_helper.php");
class LoginBussiness extends Db_helper
{
public function getDataByUsernameAndPassword($username, $password)
{
$sql = "select * from sys_users where password='" . md5($password) .
"' and username='" . $username . "'";
return parent::getDataBySQL($sql);
}
public function selectByUsername($username)
{
$sql = 'select * from sys_users where username = "' . $username . '"';
return parent::getDataBySQL($sql);
}
public function selectByPassword($username,$password)
{
$sql = 'select * from sys_users where username = "' . $username . '" and password="'.$password.'"';
return parent::getDataBySQL($sql);
}
function updateUser($data,$id){
$clause='user_id='.$id;
return parent::updateDB('sys_users',$data,$clause);
}
function selectData()
{
$sql = "select username,CASE role
WHEN '1' THEN 'admin'
ELSE 'User'
END AS role,create_time from sys_users";
return parent::getDataBySQL($sql);
}
function insertDB($table, $array)
{
return parent::insertReturnId($table, $array);
}
}
?><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>Sign Up</title>
</head>
<link rel="stylesheet" type="text/css" href="../libs/css/style.css"/>
<body>
<form id="frmTest" action="signup.php" method="POST">
<h2>SIGN UP PAGE</h2>
<label class="label-text">Username</label></br>
<input class="input-text" name="username" type="text" maxlength="50" value="<?php echo
isset($_POST['username']) ? $_POST['username'] : "" ?>" /></br>
<label class="label-text">Password</label></br>
<input class="input-text" name="password" type="password" maxlength="50" value="<?php echo
isset($_POST['password']) ? $_POST['password'] : "" ?>" /></br>
<label class="label-text">Re-type Password</label></br>
<input class="input-text" name="passwordRetype" type="password" maxlength="50" value="<?php echo
isset($_POST['passwordRetype']) ? $_POST['passwordRetype'] : "" ?>" /></br>
<div class="div_button">
<input class="input-button" name="btnSignUp" type="submit" value="Create"/>
<input class="input-button" name="btnBack" type="button" onclick="clickBack()" value="Back"/>
</div>
</form>
<?php
require (dirname(__file__) . "/../controller/LoginController.php");
$login=new LoginController();
$login->signUpAccount();
?>
</body>
<script type="text/javascript">
clickBack = function(){
window.location.href='Login.php';
}
</script>
</html><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
require_once (dirname(__file__) . "/../common/Db_helper.php");
class UsersBussiness extends Db_helper
{
function selectUsers()
{
$sql = "select a.user_id userId,a.username,b.*,c.location_name nationalName,d.location_name provinceName from sys_users a
left join users_info b on a.user_id=b.user_id
left join cat_location c on b.national=c.location_id
left join cat_location d on b.province=d.location_id";
return parent::getDataBySQL($sql);
}
function deleteLocation($location_id){
$clause=' location_id="'.$location_id.'" or parent_id ="'.$location_id.'"';
return parent::deleteDB('cat_location',$clause);
}
function selectUsersById($userId){
$sql = "select a.user_id userId,a.username,b.*,c.location_name nationalName,d.location_name provinceName from sys_users a
left join users_info b on a.user_id=b.user_id
left join cat_location c on b.national=c.location_id
left join cat_location d on b.province=d.location_id where a.user_id='".$userId."'";
return parent::getDataBySQL($sql);
}
function updateUser($array,$userId){
$clause='user_id='.$userId;
return parent::updateDB('users_info',$array,$clause);
}
}
?><file_sep><?php
/**
* @author hungnd
* @copyright 2016
*/
if(isset($_GET['action'])){
$action=$_GET['action'];
}else if(isset($_POST['action'])){
$action=$_POST['action'];
}else{
$action='index';
}
switch($action){
case 'index':
include '/view/HomePage.php';
break;
case 'manageLocation':
include '/view/viewLocation.php';
break;
case 'insertLocation':
include '/view/insertLocation.php';
break;
case 'updateLocation':
include '/view/updateLocation.php';
break;
case 'deleteLocation':
include '/view/deleteLocation.php';
break;
case 'manageUser':
include '/view/viewUsers.php';
break;
case 'updateUser':
include '/view/updateUsers.php';
break;
}
?><file_sep><!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="hungnd" />
<title>User Manager</title>
<link rel="stylesheet" type="text/css" href="libs/css/style.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: /hungnd/demo-mvc/view/Login.php');
exit;
}
?>
<body>
<div id="divLeft"></div>
<div id="divCenter">
<?php include 'view/headerPages.php' ?>
<div class="div_button">
<input class="input-button" name="btnInsert" type="submit" onclick="onPreInsertLocation()" value="Insert"/>
</div>
<table>
<tr>
<th>Location Name</th>
<th>Location Parent</th>
<th>Action</th>
</tr>
<?php
require (dirname(__file__) . "/../controller/LocationController.php");
$location = new LocationController();
$arr=$location->onSearchAllCatLocation();
for($i=0;$i< count($arr);$i++){
echo '<tr>';
echo '<td>'.$arr[$i]['location_name'].'</td>';
echo '<td>'.$arr[$i]['parentName'].'</td>';
echo '<td><a onclick="onPreUpdate('.$arr[$i]['location_id'].')" ><img width="70px" height="30px" src="http://www.clker.com/cliparts/e/0/H/N/J/2/edit-button-blue-md.png"/></a>
<a onclick="confirmAlert('.$arr[$i]['location_id'].')" ><img width="70px" height="30px" src="http://www.clker.com/cliparts/L/8/M/t/O/G/delete-button-blue-md.png"/></a></td>';
echo '</tr>';
}
?>
</table>
<div id="divFooter">
</div>
<div id="divRight">
</div>
</body>
<script type="text/javascript">
onPreInsertLocation=function(){
window.location.href='?action=insertLocation';
}
confirmAlert=function(id){
if(confirm('Do you want to delete record?')){
window.location.href='?action=deleteLocation&id='+id;
}
}
onPreUpdate=function(id){
window.location.href='?action=updateLocation&id='+id;
}
</script>
</html>
|
0144c9128ef6963bdffb309c6c9fecb8cdf6d4f2
|
[
"PHP"
] | 20 |
PHP
|
storevan/-PHP-demo-mvc
|
17d12f20da43e2faa00b085e09bf6b6c4099ed5a
|
a8d9473c733aaffd4c97b5bb65786198f7e4a3d7
|
refs/heads/master
|
<file_sep>/* eslint-env node */
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'sinon-chai'],
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
type: 'html',
dir: 'coverage/'
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
});
};
|
02415c1a03ab59858449c33857ac3c21f6e7b171
|
[
"JavaScript"
] | 1 |
JavaScript
|
vigetlabs/taggle.js
|
dde4d53f841d39aae8cdaaccc7305990e15fdd61
|
31cc0cc3b59986a9aff5f5c8a7a7550b4eb71e74
|
refs/heads/main
|
<repo_name>wjcarey/wordpress-move-install<file_sep>/README.md
# wordpress-move-install
move a wordpress install and modify the default virtual host file. the script will prompt you for old and new install locations. not for use in multisite wordpress configurations.
### run this code from the commandline. The script will ask you where to install wordpress files. You can also pass in old and new directories as arguments
~~~
sudo curl -o wordpress-move-install.sh https://raw.githubusercontent.com/wjcarey/wordpress-move-install/main/wordpress-move-install.sh && sudo chmod 777 wordpress-move-install.sh && sudo ./wordpress-move-install.sh
~~~<file_sep>/wordpress-move-install.sh
#! /bin/bash
if [ -z "$1" ]
then
echo -e "\e[32menter the current install path ... \e[39m"
read OLD_INSTALL_PATH
echo -e "\e[32menter the location for your new install path ... \e[39m"
read NEW_INSTALL_PATH
echo -e "\e[32mconfirm wordpress move from ${OLD_INSTALL_PATH} to ${NEW_INSTALL_PATH}, Do you want to continue? [Y/n] \e[39m"
read CONFIRM_WORDPRESS_MOVE
else
OLD_INSTALL_PATH=${1}
NEW_INSTALL_PATH=${2}
CONFIRM_WORDPRESS_MOVE="Y"
fi
OLD_INSTALL_PATH=$(realpath -s --canonicalize-existing $OLD_INSTALL_PATH)
NEW_INSTALL_PATH=$(realpath -s --canonicalize-missing $NEW_INSTALL_PATH)
if [ "$CONFIRM_WORDPRESS_MOVE" != "${CONFIRM_WORDPRESS_MOVE#[Yy]}" ] ;then
mkdir ${NEW_INSTALL_PATH}
chmod 775 -R ${NEW_INSTALL_PATH} && chown www-data:www-data ${NEW_INSTALL_PATH}
shopt -s dotglob
mv ${OLD_INSTALL_PATH}/* ${NEW_INSTALL_PATH}
rm -R ${OLD_INSTALL_PATH}
echo "updating apache2 default virtual host for directory ${NEW_INSTALL_PATH} ..."
sed -i "s#${OLD_INSTALL_PATH}#${NEW_INSTALL_PATH}#" /etc/apache2/sites-available/000-default.conf
echo "restarting apache2 ..."
systemctl restart apache2
else
echo "notice: the wordpress installer was skipped by user..."
fi
#SELF DELETE AND EXIT
rm -- "$0"
exit
|
5c6c1392d126c20db9fd2b9161a5cd3db61bc86f
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
wjcarey/wordpress-move-install
|
623119909f5ce7266737736e0c705ed68227edbc
|
3f42f7d546993fbd4ccf04d8fe22bc8cc2ec84e4
|
refs/heads/master
|
<file_sep>package com.shu.merchants.service.impl;
import com.alibaba.fastjson.JSON;
import com.shu.merchants.constant.Constants;
import com.shu.merchants.constant.ErrorCode;
import com.shu.merchants.dao.MerchantsDao;
import com.shu.merchants.entity.Merchants;
import com.shu.merchants.service.IMerchantsService;
import com.shu.merchants.vo.CreateMerchantsRequest;
import com.shu.merchants.vo.CreateMerchantsResponse;
import com.shu.merchants.vo.PassTemplate;
import com.shu.merchants.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <h1>商户服务接口实现</h1>
*
* @author yang
* @date 2019/6/10 15:29
*/
@Slf4j
@Service
public class MerchantsServiceImpl implements IMerchantsService {
private final MerchantsDao merchantsDao;
private final KafkaTemplate<String, String> kafkaTemplate;
@Autowired
public MerchantsServiceImpl(MerchantsDao merchantsDao, KafkaTemplate<String, String> kafkaTemplate) {
this.merchantsDao = merchantsDao;
this.kafkaTemplate = kafkaTemplate;
}
@Override
@Transactional
public Response createMerchants(CreateMerchantsRequest request) {
Response response = new Response();
CreateMerchantsResponse createMerchantsResponse = new CreateMerchantsResponse();
ErrorCode errorCode = request.validate(merchantsDao);
if (errorCode != ErrorCode.SUCCESS) {
createMerchantsResponse.setId(-1);
response.setErrorCode(errorCode.getCode());
response.setErrorMsg(errorCode.getDesc());
} else {
createMerchantsResponse.setId(merchantsDao.save(request.toMerchants()).getId());
}
response.setData(createMerchantsResponse);
return response;
}
@Override
public Response buildMerchantsInfoById(Integer id) {
Response response = new Response();
Merchants merchants = merchantsDao.findById(id);
if (null == merchants) {
response.setErrorCode(ErrorCode.MERCHANTS_NOT_EXIST.getCode());
response.setErrorMsg(ErrorCode.MERCHANTS_NOT_EXIST.getDesc());
}
response.setData(merchants);
return response;
}
@Override
public Response dropPassTemplate(PassTemplate passTemplate) {
Response response = new Response();
ErrorCode errorCode = passTemplate.validate(merchantsDao);
response.setErrorCode(errorCode.getCode());
response.setErrorMsg(errorCode.getDesc());
if (errorCode == ErrorCode.SUCCESS) {
String s = JSON.toJSONString(passTemplate);
kafkaTemplate.send(Constants.TEMPLATE_TOPIC, Constants.TEMPLATE_TOPIC, s);
log.info("DropPassTemplate:{}", s);
}
return response;
}
}
<file_sep># merchants
卡包商家端
<file_sep>package com.shu.merchants.constant;
/**
* <h2>错误码枚举定义</h2>
*
* @author yang
* @date 2019/6/10 13:18
*/
public enum ErrorCode {
/**
* 错误码及描述
*/
SUCCESS(0, ""),
DUPLICATE_NAME(1, "商户名称重复"),
EMPTY_LOGO(2, "商户logo为空"),
EMPTY_BUSINESS_LICENSE(3, "商户营业执照为空"),
ERROR_PHONE(4, "商户联系电话错误"),
EMPTY_ADDRESS(5, "商户地址为空"),
MERCHANTS_NOT_EXIST(6, "商户不存在");
private Integer code;
private String desc;
/**
* 错误码
*/
public Integer getCode() {
return code;
}
/**
* 描述
*/
public String getDesc() {
return desc;
}
ErrorCode(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
}
<file_sep>package com.shu.merchants.vo;
import com.shu.merchants.constant.ErrorCode;
import com.shu.merchants.dao.MerchantsDao;
import com.shu.merchants.entity.Merchants;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
/**
* <h2>创建商户请求对象</h2>
*
* @author yang
* @date 2019/6/10 15:04
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CreateMerchantsRequest {
/**
* 商户名称
*/
private String name;
/**
* 商户logo
*/
private String logoUrl;
/**
* 商户营业执照
*/
private String businessLicenseUrl;
/**
* 商户联系电话
*/
private String phone;
/**
* 商户地址
*/
private String address;
/**
* 验证请求有效性
*
* @param merchantsDao {@link MerchantsDao}
* @return {@link ErrorCode}
*/
public ErrorCode validate(MerchantsDao merchantsDao) {
if (merchantsDao.findByName(this.name) != null) {
return ErrorCode.DUPLICATE_NAME;
}
if (StringUtils.isEmpty(this.logoUrl)) {
return ErrorCode.EMPTY_LOGO;
}
if (StringUtils.isEmpty(this.businessLicenseUrl)) {
return ErrorCode.EMPTY_BUSINESS_LICENSE;
}
if (StringUtils.isEmpty(this.address)) {
return ErrorCode.EMPTY_ADDRESS;
}
if (StringUtils.isEmpty(this.phone)) {
return ErrorCode.ERROR_PHONE;
}
return ErrorCode.SUCCESS;
}
/**
* <h2>将请求对象转换为商户对象</h2>
*
* @return {@link Merchants}
*/
public Merchants toMerchants() {
Merchants merchants = new Merchants();
merchants.setName(name);
merchants.setLogoUrl(logoUrl);
merchants.setAddress(address);
merchants.setBusinessLicenseUrl(businessLicenseUrl);
merchants.setPhone(phone);
return merchants;
}
}
<file_sep>package com.shu.merchants.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <h1>通用响应对象</h1>
*
* @author yang
* @date 2019/6/10 14:58
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Response {
/**
* 错误码,正确返回0
*/
private Integer errorCode;
/**
* 错误信息
*/
private String errorMsg;
/**
* 返回值对象
*/
private Object data;
/**
* <h2>正确的响应构造函数</h2>
*
* @param data 返回对象
*/
public Response(Object data) {
this.data = data;
}
// public Response() {
// }
}
<file_sep>package com.shu.merchants.constant;
/**
* <h1>通用常量</h1>
*
* @author yang
* @date 2019/6/10 13:08
*/
public class Constants {
/**
* 商户优惠券kafka topic
*/
public static final String TEMPLATE_TOPIC = "merchants-template";
/**
* token string
*/
public static final String TOKEN_STRING = "token";
/**
* token info
*/
public static final String TOKEN = "<PASSWORD>";
}
<file_sep>package com.shu.merchants.dao;
import com.shu.merchants.entity.Merchants;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* <h1>Merchants Dao 接口</h1>
*
* @author yang
* @date 2019/6/10 14:17
*/
public interface MerchantsDao extends JpaRepository<Merchants, Integer> {
/**
* <h2>根据商户id获取商户</h2>
*
* @param id 商户id
* @return {@link Merchants}
*/
Merchants findById(Integer id);
/**
* <h2>根据商户名称获取商户对象</h2>
*
* @param name 商户名称
* @return {@link Merchants}
*/
Merchants findByName(String name);
}
<file_sep>package com.shu.merchants.vo;
import com.shu.merchants.constant.ErrorCode;
import com.shu.merchants.dao.MerchantsDao;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* <h1>投放优惠券对象定义</h1>
*
* @author yang
* @date 2019/6/10 14:50
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PassTemplate {
/**
* 所属商户id
*/
private Integer id;
/**
* 优惠券标题
*/
private String title;
/**
* 优惠券详细信息
*/
private String summary;
/**
* 最大个数限制
*/
private Long limit;
/**
* 优惠券是否有token用于商户核销
* redis中获取
*/
private Boolean hasToken;
/**
* 优惠券背景颜色
*/
private Integer background;
/**
* 优惠券开始时间
*/
private Date start;
/**
* 优惠券结束时间
*/
private Date end;
/**
* 描述
*/
private String Desc;
/**
* 校验优惠券对象有效性
*
* @param merchantsDao {@link MerchantsDao}
* @return {@link ErrorCode}
*/
public ErrorCode validate(MerchantsDao merchantsDao) {
if (null == merchantsDao.findById(id)) {
return ErrorCode.MERCHANTS_NOT_EXIST;
}
return ErrorCode.SUCCESS;
}
}
|
4f2e6502082af98a9cbe58f1aa443891902b8fc6
|
[
"Markdown",
"Java"
] | 8 |
Java
|
jianlinyang/merchants
|
bd038b2ee48d910506c3073c800793cd00b6c89f
|
2473c1fec014f5b78d377eb966df82a4db8f9654
|
refs/heads/master
|
<file_sep># Tasks API
## Description
This Directory contains API files and documenation
## Environment
* __OS:__ Ubuntu 14.04 LTS
* __language:__ Ruby 2.6.5
* __database:__ postgresql
`
## SETUP PROJECT
### Install app dependencies:
```
bundle install
```
### Setup pre-commit gem
```
pre-commit install
```
### Create Database
```
rake db:create
```
### Migrate
```
rake db:migrate
```
## Testing API
* Execute program:
```
bundle exec rails s
```
* Testing from CLI:
```
curl -X GET http://0.0.0.0:3000/api/v1/[YOUR API REQUEST]
```
example:
```
curl -X GET http://0.0.0.0:3000/api/v1/tasks/:user_id
``<file_sep>class Task < ApplicationRecord
enum state: [:to_do, :done]
end
<file_sep>version: "2"
volumes:
db-data:
external: false
services:
db:
build: .
image: postgres
environment:
POSTGRES_HOST: db
volumes:
- db-data:/var/lib/postgresql/db-data
ports:
- 5432
app:
build: .
command: 'bash -c ''bundle exec puma -C config/puma.rb'''
environment:
POSTGRES_HOST: db
volumes:
- .:/usr/src/app
depends_on:
- db
ports:
- 3000
<file_sep>class Api::V1::TasksController < ApplicationController
before_action :set_task, only: [:update, :destroy]
# GET /tasks/user_id
def index
@tasks = Task.where(user_id: params[:user_id])
render json: @tasks
end
# POST /tasks
def create
@task = Task.create!(create_params)
json_response(@task, :created)
end
# PUT /tasks/:id
def update
@task.update!(update_params)
json_response(@task, :no_content)
end
# DELETE /todos/:id
def destroy
@task.destroy!
json_response({}, :ok)
end
private
def create_params
params.require(:task).permit(:description, :state, :user_id)
end
def update_params
params.require(:task).permit(:description, :state)
end
def set_task
@task = Task.find(params[:id])
end
end
|
43c4d338adc231fa5fd8699f94abfe15978fc4a7
|
[
"Markdown",
"Ruby",
"YAML"
] | 4 |
Markdown
|
Jhon112/tasks-microservice
|
9dca44276a114ad48f09865d9409b32d265d6f8d
|
3fb5e863c18cfd993100942fe3c782d5e04cbb80
|
refs/heads/master
|
<repo_name>warkop/pertagas-qrtg-api<file_sep>/application/app/Http/Models/StockMovement.php
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class StockMovement extends Model
{
use SoftDeletes;
protected $table = 'stock_movement';
protected $primaryKey = 'stock_movement_id';
protected $guarded = [
'stock_movement_id',
];
protected $dateFormat = 'd-m-Y';
protected $dates = [
'start_date',
'end_date',
];
protected $hidden = [
'asset_id',
'report_type_id',
'station_id',
'destination_station_id',
'document_number',
'ref_doc_number',
'start_date',
'end_date',
'created_at',
'created_by',
'updated_at',
'updated_by',
'deleted_at',
'deleted_by',
];
public $timestamps = false;
public function ReportType()
{
return $this->belongsToMany('App\Http\Models\ReportType', '', '');
}
public function getAll()
{
$query = DB::table('stock_movement as sm')
->select(['stock_movement_id', 'document_number', 's.station_name as station', 'ss.station_name as destination_station'])
->join('stations as s', 's.station_id', '=', 'sm.station_id')
->join('stations as ss', 'ss.station_id', '=', 'sm.destination_station_id')->get();
return $query;
}
public static function jsonGrid($start, $length, $search = '', $count = false, $sort, $field)
{
$result = DB::table('document as d')
->select([
'document_id',
DB::raw('(CASE
WHEN d.document_status = 1 AND rt.can_be_ref IS NULL THEN document_number
WHEN d.document_status = 2 AND rt.can_be_ref IS NULL THEN document_number
WHEN d.document_status = 3 AND rt.can_be_ref IS NOT NULL THEN ref_doc_number
WHEN d.document_status = 4 AND rt.can_be_ref IS NOT NULL THEN ref_doc_number
END) as document_number'),
// 'document_number',
// 'ref_doc_number',
's.station_id',
's.station_name as station',
'ss.station_id as destination_id',
'ss.station_name as destination_station',
'rt.report_type_id',
'rt.report_name',
'd.document_status',
DB::raw('(CASE
WHEN d.document_status = 1 AND rt.can_be_ref IS NULL THEN \'Draft\'
WHEN d.document_status = 2 AND rt.can_be_ref IS NULL THEN \'Approve\'
WHEN d.document_status = 3 AND rt.can_be_ref IS NOT NULL THEN \'GR Draft\'
WHEN d.document_status = 4 AND rt.can_be_ref IS NOT NULL THEN \'GR Approve\'
END) as status
'),
])
->leftJoin('stations as s', 's.station_id', '=', 'd.station_id')
->leftJoin('stations as ss', 'ss.station_id', '=', 'd.destination_station_id')
->leftJoin('report_type as rt', 'rt.report_type_id', '=', 'd.report_type_id')
->whereNull('d.deleted_at');
if (!empty($search)) {
$result = $result->where(function ($where) use ($search) {
$where->where('document_number', 'ILIKE', '%' . $search . '%')
->orWhere('s.station_name', 'ILIKE', '%' . $search . '%')
->orWhere('ss.station_name', 'ILIKE', '%' . $search . '%');
});
}
$result = $result->offset($start)->limit($length)->orderBy($field, $sort)->get();
if ($count == false) {
return $result;
} else {
return $result->count();
}
}
public function assetOfStockMovement($id_document='', $id_asset='')
{
$query = DB::table('stock_movement as sm')
->select([
'd.document_id',
'sm.stock_movement_id',
'sm.asset_id',
'd.document_number',
'a.qr_code',
'a.serial_number',
'at.asset_name',
])
->join('document as d', 'd.document_id', '=', 'sm.document_id')
->join('assets as a', 'a.asset_id', '=', 'sm.asset_id')
->join('asset_type as at', 'at.asset_type_id', '=', 'a.asset_type_id')
->where('sm.document_id', $id_document)
->whereNull('sm.deleted_at')
->get();
return $query;
}
public function getDetail($id_document)
{
$query = DB::table('document as d')
->selectRaw('
d.document_id,
d.report_type_id,
d.station_id,
d.destination_station_id,
(select station_name from stations where station_id = d.destination_station_id) destination_name,
document_number,
ref_doc_number,
s.station_name,
s.abbreviation,
rt.report_name,
rt.report_desc,
TO_CHAR(d.start_date, \'dd-mm-yyyy\') AS start_date,
TO_CHAR(d.end_date, \'dd-mm-yyyy\') AS end_date
')
->leftJoin('stations as s', 's.station_id', '=', 'd.station_id')
->leftJoin('report_type as rt', 'd.report_type_id', '=', 'rt.report_type_id')
->where('d.document_id', $id_document)
->whereNull('d.deleted_at')
->whereNull('s.deleted_at')
->whereNull('rt.deleted_at')
->first();
return $query;
}
public function getStationRole($id_user)
{
$query = DB::table('users as u')
->select('user_id',
'role_id',
'username',
'station_name',
'abbreviation')
->join('stations as s', 'u.station_id', '=', 's.station_id')
->where('u.user_id', $id_user)
->first();
return $query;
}
public function getAssets($start, $length, $search = '', $count = false, $sort, $field, $id_station)
{
$result = DB::table('transactions as t')
->select('*')
->join('assets as a', 't.asset_id', '=', 'a.asset_id')
->join('asset_type as at', 'at.asset_type_id', '=', 'a.asset_type_id')
->where('t.station_id', $id_station)
->whereNull('t.deleted_at')
->whereNull('a.deleted_at')
->get();
if (!empty($search)) {
$result = $result->where(function ($where) use ($search) {
$where->where('serial_number', 'ILIKE', '%' . $search . '%')
->orWhere('qr_code', 'ILIKE', '%' . $search . '%')
->orWhere('at.asset_name', 'ILIKE', '%' . $search . '%');
});
}
$result = $result->offset($start)->limit($length)->orderBy($field, $sort);
if ($count == false) {
return $result->get();
} else {
return $result->count();
}
}
public function listDestination($id_role)
{
$query = DB::table('station_role as sr')
->select(
'station_role_id',
's.station_id',
'station_name'
)
->join('stations as s', 'sr.station_id', '=', 's.station_id')
->where('role_id', $id_role)
->get();
return $query;
}
public function listScan($id_document, $status='')
{
$query = DB::table('stock_movement as sm')
->select([
'd.document_id',
'sm.asset_id',
'd.ref_doc_number',
'a.serial_number',
'at.asset_name',
])
->join('document as d', 'd.document_id', '=', 'sm.document_id')
->join('assets as a', 'a.asset_id', '=', 'sm.asset_id')
->join('asset_type as at', 'at.asset_type_id', '=', 'a.asset_type_id')
->where('sm.document_id', $id_document)
->where('sm.stock_move_status', $status)
->whereNull('sm.deleted_at')
->get();
return $query;
}
}
<file_sep>/application/helpers/public.php
<?php
/**
* Function helpNumeric
* Fungsi ini digunakan untuk mengecek apakah sebuah variabel berisi nilai
yang bersifat numeric (int, float, double).
* @access public
* @param (any) $var
* @param (int) $res
* @return (int) {0}
*/
function helpNumeric($var, $res = 0)
{
return is_numeric($var) ? $var : $res;
}
/**
* Function helpRoman
* Fungsi ini digunakan untuk merubah angka menjadi bilangan romawi
* @access public
* @param (int) $var
* @return (string) {''}
*/
function helpRoman($var)
{
$n = intval($var);
$result = '';
$lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
foreach ($lookup as $roman => $value) {
$matches = intval($n / $value);
$result .= str_repeat($roman, $matches);
$n = $n % $value;
}
return $result;
}
/**
* Function helpSecSql
* Fungsi ini digunakan untuk merubah variabel menjadi aman sebelum dimasukkan ke dalam database
* @access public
* @param (string) $var
* @return (string)
*/
function helpSecSql($var)
{
return addslashes(strtolower($var));
}
/**
* Function helpTerbilang
* Fungsi ini digunakan untuk merubah angka yang dimasukkan menjadi ejaan
* @access public
* @param (int) $var
* @return (string)
*/
function helpTerbilang($num)
{
$digits = array(
0 => "nol",
1 => "satu",
2 => "dua",
3 => "tiga",
4 => "empat",
5 => "lima",
6 => "enam",
7 => "tujuh",
8 => "delapan",
9 => "sembilan");
$orders = array(
0 => "",
1 => "puluh",
2 => "ratus",
3 => "ribu",
6 => "juta",
9 => "miliar",
12 => "triliun",
15 => "kuadriliun");
$is_neg = $num < 0; $num = "$num";
$int = ""; if (preg_match("/^[+-]?(\d+)/", $num, $m)) $int = $m[1];
$mult = 0; $wint = "";
while (preg_match('/(\d{1,3})$/', $int, $m)) {
$s = $m[1] % 10;
$p = ($m[1] % 100 - $s)/10;
$r = ($m[1] - $p*10 - $s)/100;
if ($r==0) $g = "";
elseif ($r==1) $g = "se$orders[2]";
else $g = $digits[$r]." $orders[2]";
if ($p==0) {
if ($s==0);
elseif ($s==1) $g = ($g ? "$g ".$digits[$s] :
($mult==0 ? $digits[1] : "se"));
else $g = ($g ? "$g ":"") . $digits[$s];
} elseif ($p==1) {
if ($s==0) $g = ($g ? "$g ":"") . "se$orders[1]";
elseif ($s==1) $g = ($g ? "$g ":"") . "sebelas";
else $g = ($g ? "$g ":"") . $digits[$s] . " belas";
} else {
$g = ($g ? "$g ":"").$digits[$p]." puluh".
($s > 0 ? " ".$digits[$s] : "");
}
$wint = ($g ? $g.($g=="se" ? "":" ").$orders[$mult]:"").
($wint ? " $wint":"");
$int = preg_replace('/\d{1,3}$/', '', $int);
$mult+=3;
}
if (!$wint) $wint = $digits[0];
$frac = ""; if (preg_match("/\.(\d+)/", $num, $m)) $frac = $m[1];
$wfrac = "";
for ($i=0; $i<strlen($frac); $i++) {
$wfrac .= ($wfrac ? " ":"").$digits[substr($frac,$i,1)];
}
$hasil= ($is_neg ? "minus ":"").$wint.($wfrac ? " koma $wfrac":"");
$hasil=str_replace("sejuta","satu juta",$hasil);
return $hasil;
}
/**
* Function helpResponse
* Fungsi ini digunakan untuk mengambil response restful
* @access public
* @param (string) $code
* @param (array) $data
* @param (string) $msg
* @param (string) $status
* @return (array)
*/
function helpResponse($code, $data = NULL, $msg = '', $status = '', $note=NULL)
{
switch($code){
case '200':
$s = 'OK';
$m = 'Sukses';
break;
case '201':
case '202':
$s = 'Saved';
$m = 'Data berhasil disimpan';
break;
case '204':
$s = 'No Content';
$m = 'Data tidak ditemukan';
break;
case '304':
$s = 'Not Modified';
$m = 'Data gagal disimpan';
break;
case '400':
$s = 'Bad Request';
$m = 'Fungsi tidak ditemukan';
break;
case '401':
$s = 'Unauthorized';
$m = 'Silahkan login terlebih dahulu';
break;
case '403':
$s = 'Forbidden';
$m = 'Sesi anda telah berakhir';
break;
case '404':
$s = 'Not Found';
$m = 'Halaman tidak ditemukan';
break;
case '414':
$s = 'Request URI Too Long';
$m = 'Data yang dikirim terlalu panjang';
break;
case '500':
$s = 'Internal Server Error';
$m = 'Maaf, terjadi kesalahan dalam mengolah data';
break;
case '502':
$s = 'Bad Gateway';
$m = 'Tidak dapat terhubung ke server';
break;
case '503':
$s = 'Service Unavailable';
$m = 'Server tidak dapat diakses';
break;
default:
$s = 'Undefined';
$m = 'Undefined';
break;
}
$status = ($status != '') ? $status : $s;
$msg = ($msg != '') ? $msg : $m;
$result=array(
"status"=>$status,
"code"=>$code,
"message"=>$msg,
"data"=>$data,
"note"=>$note
);
setHeader($code, $status);
return $result;
}
function dump($var=""){
if($var == ""){
echo "No value to return.";
} else {
echo "<pre>";
print_r($var);
echo "</pre>";
}
}
function rand_str($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// start by: dimas
function helpCurrency($nominal='', $start='', $pemisah='.', $cent=true) {
if(empty($nominal)){
$hasil = '-';
}else{
$nominal = empty($nominal)? 0: $nominal;
$angka_belakang =',00';
$temp_rp = explode('.', $nominal);
if(count($temp_rp) > 1){
$nominal = $temp_rp[0];
$angka_belakang = ','.$temp_rp[1];
}
if($cent == false){
$angka_belakang = '';
}
$hasil = $start.number_format($nominal, 0, "", $pemisah) . $angka_belakang;
}
return $hasil;
}
function setHeader($code='200', $status='')
{
header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$status);
}
function helpToNum($data) {
$alphabet = array( 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z'
);
$alpha_flip = array_flip($alphabet);
$return_value = -1;
$length = strlen($data);
for ($i = 0; $i < $length; $i++) {
$return_value +=
($alpha_flip[$data[$i]] + 1) * pow(26, ($length - $i - 1));
}
return $return_value;
}
function toNum($data) {
$alphabet = array( 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z'
);
$alpha_flip = array_flip($alphabet);
$return_value = -1;
$length = strlen($data);
for ($i = 0; $i < $length; $i++) {
$return_value +=
($alpha_flip[$data[$i]] + 1) * pow(26, ($length - $i - 1));
}
return $return_value;
}
function toAlpha($data){
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alpha_flip = array_flip($alphabet);
if($data <= 25){
return $alphabet[$data];
}
elseif($data > 25){
$dividend = ($data + 1);
$alpha = '';
$modulo;
while ($dividend > 0){
$modulo = ($dividend - 1) % 26;
$alpha = $alphabet[$modulo] . $alpha;
$dividend = floor((($dividend - $modulo) / 26));
}
return $alpha;
}
}
function helpRename($value='', $replace_with='')
{
$pattern = '/[^a-zA-Z0-9 &.,-_]/u';
$value = preg_replace($pattern, $replace_with, $value);
return $value;
}
function help_forbidden_char($value='', $replace_with='')
{
$forbidden_char = array('[', ']', '(', ')', '?', '\'', '′', '%');
$value = str_replace($forbidden_char, $replace_with, $value);
return $value;
}
function help_filename($value='', $replace_with='', $timestamp=true)
{
$forbidden_char = array('[', ']', '(', ')', '?', '\'', '′', '%', ' ');
$value = str_replace($forbidden_char, $replace_with, $value);
$value = ($timestamp == true)? date('YmdHis').'_'.$value : $value;
return $value;
}
function helpUsername($value='', $replace_with='', $lower=true)
{
$pattern = '/[^a-zA-Z0-9.-_]/u';
$arr_temp = explode(' ', $value);
$result = preg_replace($pattern, $replace_with, $arr_temp[0]);
$result = (strlen($result) >= 5)? $result : ( isset($arr_temp[1])? $result.preg_replace($pattern, $replace_with, $arr_temp[1]) : $result.rand_str(2, true));
$result = ($lower == true)? strtolower($result) : $result;
return $result;
}
function helpEmpty($value='', $replace_with='-', $null=false)
{
if($null == false){
$result = (empty($value) && $value != '0')? $replace_with : $value;
}else{
$result = (empty($value) && $value != '0')? '' : $value;
}
return $result;
}
function helpText($value, $tags=true, $zalgo=true){
$result = $value;
if($tags == true){
$result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
}
if($zalgo == true){
// $pattern = "~(?:[\p{M}]{1})([\p{M}])+?~uis";
$pattern = "~[\p{M}]~uis";
$result = preg_replace($pattern,"", $result);
}
return $result;
}
function slug($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\pL\d]+~u', '-', $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('[^-\w]+', '', $text);
// trim
$text = trim($text, '-');
// remove duplicate -
$text = preg_replace('-+', '-', $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
// end by: dimas<file_sep>/application/app/Http/Controllers/AssetsController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\Assets;
use App\Http\Models\Transactions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class AssetsController extends Controller
{
private $responseCode = 403;
private $responseStatus = '';
private $responseMessage = '';
private $responseData = [];
private $responseNote = null;
public function __construct()
{
//
}
public function index(Request $req)
{
$rules['start'] = 'required|integer|min:0';
$rules['perpage'] = 'required|integer|min:1';
$validator = Validator::make($req->all(), $rules);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseStatus = 'Missing Param';
$this->responseMessage = 'Silahkan isi form dengan benar terlebih dahulu';
$this->responseData = $validator->errors();
} else {
$res = new Assets();
$start = $req->input('start');
$perpage = $req->input('perpage');
$search = $req->input('search');
$order = $req->input('order');
$pattern = '/[^a-zA-Z0-9 !@#$%^&*\/\.\,\(\)-_:;?\+=]/u';
$search = preg_replace($pattern, '', $search);
$sort = $order ?? 'desc';
$field = 'a.created_at';
$total = $res->jsonGrid($start, $perpage, $search, true, $sort, $field);
$resource = $res->jsonGrid($start, $perpage, $search, false, $sort, $field);
$this->responseCode = 200;
$this->responseData = $resource;
$pagination = ['row' => count($resource), 'rowStart' => ((count($resource) > 0) ? ($start + 1) : 0), 'rowEnd' => ($start + count($resource))];
$this->responseData['meta'] = ['start' => $start, 'perpage' => $perpage, 'search' => $search, 'total' => $total, 'pagination' => $pagination];
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
public function testDetail($id_asset)
{
$res = Assets::find($id_asset)->assetType()->get();
return $res;
}
public function detail(Request $req)
{
$validator = Validator::make($req->all(), [
'qr_code' => 'required',
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$assets = new Assets;
$qr_code = $req->input('qr_code');
$res = $assets->getDetail($qr_code);
if (empty($res)) {
$this->responseCode = 400;
$this->responseMessage = 'Asset tidak ditemukan';
} else {
$this->responseCode = 200;
$this->responseData = $res;
$this->responseNote['pics_url'] = [
'url' => '{base_url}/watch/{pics_url}?token={access_token}&un={asset_id}&ctg=assets&src={pics_url}'
];
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus, $this->responseNote);
return response()->json($response, $this->responseCode);
}
}
public function store(Request $req)
{
$id_manufacturer = $req->input('manufacturer_id');
$id_type_asset = $req->input('asset_type_id');
$id_seq_scheme_group = $req->input('seq_scheme_group_id');
$validator = Validator::make($req->all(), [
'asset_type_id' => [
'required',
Rule::exists('asset_type')->where(function ($query) use ($id_type_asset) {
$query->where('asset_type_id', $id_type_asset);
})
],
'manufacturer_id' => [
'required',
Rule::exists('manufacturer')->where(function ($query) use ($id_manufacturer) {
$query->where('manufacturer_id', $id_manufacturer);
})
],
'seq_scheme_group_id' => [
'required',
Rule::exists('seq_scheme_group')->where(function ($query) use ($id_seq_scheme_group) {
$query->where('seq_scheme_group_id', $id_seq_scheme_group);
})
],
'qr_code' => 'required|unique:assets,qr_code',
'serial_number' => 'required|unique:assets,serial_number',
'manufacturer_date' => 'date_format:d-m-Y',
'expiry_date' => 'date_format:d-m-Y',
'pics_url' => 'file',
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$asset_desc = $req->input('asset_desc');
$gross_weight = $req->input('gross_weight');
$net_weight = $req->input('net_weight');
$pics_url = $req->input('pics_url');
$qr_code = $req->input('qr_code');
$serial_number = $req->input('serial_number');
$manufacture_date = $req->input('manufacture_date');
$expiry_date = $req->input('expiry_date');
$height = $req->input('height');
$width = $req->input('width');
$from_date = $req->input('from_date');
$end_date = $req->input('end_date');
$temp = Assets::where('serial_number',$serial_number)->get();
if ($temp->isEmpty()) {
$user = $req->get('my_auth');
$res = new Assets;
$res->asset_type_id = $id_type_asset;
$res->manufacturer_id = $id_manufacturer;
$res->seq_scheme_group_id = $id_seq_scheme_group;
$res->asset_desc = $asset_desc;
$res->gross_weight = $gross_weight;
$res->net_weight = $net_weight;
$res->qr_code = $qr_code;
$res->serial_number = $serial_number;
$res->manufacture_date = date('Y-m-d', strtotime($manufacture_date));
$res->expiry_date = date('Y-m-d', strtotime($expiry_date));
$res->height = $height;
$res->width = $width;
$res->from_date = date('Y-m-d',strtotime($from_date));
$res->end_date = date('Y-m-d', strtotime($end_date));
$res->created_at = date('Y-m-d H:i:s');
$res->created_by = $user->id_user;
$saved = $res->save();
if (!$saved) {
$this->responseCode = 502;
$this->responseMessage = 'Data gagal disimpan!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$pics_url = $req->file('pics_url')->getClientOriginalName();
if ($req->file('pics_url')->isValid()) {
$destinationPath = storage_path('app/public') . '/assets/' . $res->asset_id;
$req->file('pics_url')->move($destinationPath, $pics_url);
$resource = Assets::find($res->asset_id);
$resource->pics_url = $pics_url;
$resource->save();
}
$arr_store = [
'asset_id' => $res->asset_id,
'station_id' => 2,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => $user->id_user,
];
$saved = Transactions::create($arr_store);
$this->responseCode = 201;
$this->responseMessage = 'Asset berhasil disimpan!';
$this->responseData = $req->all();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
} else {
$this->responseCode = 400;
$this->responseData = $req->input('serial_number');
$this->responseMessage = 'Serial Number sudah ada!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
public function delete($id_asset)
{
$id_asset = strip_tags($id_asset);
$destroy = Assets::destroy($id_asset);
if ($destroy) {
$this->responseCode = 202;
$this->responseMessage = 'Asset berhasil dihapus!';
$this->responseData = $destroy;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$this->responseCode = 500;
$this->responseMessage = 'Asset gagal dihapus!';
$this->responseData = $destroy;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
public function deleteAll()
{
$responseCode = 403;
$responseStatus = '';
$responseMessage = '';
$responseData = [];
$res = Assets::whereNotNull('asset_id');
$destroy = $res->forceDelete();
if ($destroy) {
$responseCode = 202;
$responseMessage = 'Asset berhasil dihapus semua!';
$responseData = $destroy;
$responseStatus = 'Accepted';
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
} else {
$responseCode = 500;
$responseMessage = 'Asset gagal dihapus!';
$responseData = $destroy;
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
}
return response()->json($response, $responseCode);
}
}
<file_sep>/application/database/seeds/StationsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class StationsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('stations')->insert([
'station_name' => 'Manufacturer',
'abbreviation' => 'MF',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('stations')->insert([
'station_name' => 'Material Warehouse',
'abbreviation' => 'MWH',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('stations')->insert([
'station_name' => 'Pre-Filling Checking Plant',
'abbreviation' => 'PFCP',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('stations')->insert([
'station_name' => 'Filling Plant',
'abbreviation' => 'FP',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('stations')->insert([
'station_name' => 'Shipping Plant',
'abbreviation' => 'SP',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('stations')->insert([
'station_name' => 'Repair Plant',
'abbreviation' => 'RP',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('stations')->insert([
'station_name' => 'Agents',
'abbreviation' => 'AG',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
}
}
<file_sep>/application/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call('UsersTableSeeder');
$this->call('RolesTableSeeder');
$this->call('AssetTypeTableSeeder');
$this->call('ManufacturerTableSeeder');
$this->call('ResultsTableSeeder');
$this->call('SeqSchemeGroupTableSeeder');
$this->call('SeqSchemeTableSeeder');
$this->call('StationsTableSeeder');
$this->call('ReportTypeTableSeeder');
}
}
<file_sep>/application/app/Http/Models/Document.php
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class Document extends Model
{
use SoftDeletes;
protected $table = 'document';
protected $primaryKey = 'document_id';
protected $guarded = [
'document_id',
];
protected $hidden = [
'created_at',
'created_by',
'updated_at',
'updated_by',
'deleted_at',
'deleted_by',
];
public $timestamps = false;
}
<file_sep>/application/app/Http/Models/SeqScheme.php
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class SeqScheme extends Model
{
use SoftDeletes;
protected $table = 'seq_scheme';
protected $primaryKey = 'seq_scheme_id';
protected $guarded = [
'seq_scheme_id',
];
protected $hidden = [
'from_date',
'end_date',
'created_at',
'created_by',
'updated_at',
'updated_by',
'deleted_at',
'deleted_by',
];
public $timestamps = false;
public function showFlow()
{
$query = DB::table(DB::raw('seq_scheme ss'))->select(DB::raw('seq_scheme_id,
scheme_name,
(SELECT
station_name FROM stations WHERE stations.station_id = predecessor_station_id)as predecessor_station,
s.station_name,
r.result_name,
ssg.group_name'))
->leftJoin(DB::raw('stations s'), 'ss.station_id', '=', 's.station_id')
->leftJoin(DB::raw('results r'), 'r.result_id', '=', 'ss.result_id')
->leftJoin(DB::raw('seq_scheme_group ssg'), 'ss.seq_scheme_group_id', '=', 'ssg.seq_scheme_group_id')
->orderBy('seq_scheme_id')
->get();
return $query;
}
public function checkPosition($id_asset)
{
$query = DB::table('assets as a')
->select(
't.transaction_id',
'a.asset_id',
'at.asset_name',
's.station_id',
't.result_id',
'r.result_name',
'r.result_desc',
'at.asset_desc',
's.station_name',
'a.serial_number',
'a.gross_weight',
'a.net_weight',
'a.pics_url',
'a.from_date',
'a.end_date',
'a.height',
'a.width'
)
->leftJoin('transactions as t', 't.asset_id', '=', 'a.asset_id')
->leftJoin('stations as s', 's.station_id', '=', 't.station_id')
->leftJoin('asset_type as at', 'a.asset_type_id', '=', 'at.asset_type_id')
->leftJoin('results as r', 't.result_id', '=', 'r.result_id')
->leftJoin('manufacturer as m', 'm.manufacturer_id', '=', 'a.manufacturer_id')
->leftJoin('seq_scheme_group as ssg', 'a.seq_scheme_group_id', '=', 'ssg.seq_scheme_group_id')
->where('a.asset_id', $id_asset)
->orderBy('transaction_id', 'desc')
->take(1)
->first();
return $query;
}
public function getResultByStation($id_station)
{
$query = DB::table('seq_scheme as ss')
->select('r.result_id', 'r.result_name', 'r.result_desc')
->join('results as r', 'ss.result_id', '=', 'r.result_id')
->where('predecessor_station_id', $id_station)
->groupBy('r.result_id')
->get();
return $query;
}
}
<file_sep>/application/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Models\Users;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
public function index(Request $request)
{
$responseCode = 403;
$responseStatus = '';
$responseMessage = '';
$responseData = [];
$rules['username'] = 'required';
$rules['password'] = '<PASSWORD>';
// $rules['device_id'] = 'required';
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$responseCode = 400;
$responseStatus = 'Missing Param';
$responseMessage = 'Silahkan isi form dengan benar terlebih dahulu';
$responseData['error_log'] = $validator->errors();
} else {
$username = $request->input('username');
$password = $request->input('<PASSWORD>');
$device_id = $request->input('device');
$cek_user = Users::where('username', $username)->whereNull('deleted_at')->first();
if ($cek_user) {
if (Hash::check($password, $cek_user['password'])) {
$m_user = Users::find($cek_user['user_id']);
if (empty($cek_user['token'])) {
$access_token = 'QrTg-' . rand_str(10) . date('Y') . rand_str(6) . date('m') . rand_str(6) . date('d') . rand_str(6) . date('H') . rand_str(6) . date('i') . rand_str(6) . date('s');
$m_user->token = $access_token;
} else {
$access_token = $cek_user['token'];
}
$m_user->device = $device_id;
$m_user->save();
$responseCode = 200;
$responseData['access_token'] = $access_token;
$responseData['role'] = $m_user->role_id;
$responseData['username'] = $m_user->username;
$responseData['email'] = $m_user->email;
$responseData['id_user'] = $m_user->user_id;
$responseData['id_station'] = $m_user->station_id;
$responseData['gcid'] = $m_user->user_gcid;
$responseMessage = 'Anda berhasil login';
} else {
$responseCode = 401;
$responseMessage = 'Username atau Password Anda salah';
}
} else {
$responseCode = 401;
$responseMessage = 'Username atau Password Anda salah';
}
}
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
return response()->json($response, $responseCode);
}
public function logout(Request $req)
{
$responseCode = 403;
$responseStatus = '';
$responseMessage = '';
$responseData = [];
$this->validate($req, [
'token' => 'required',
]);
$user = new Users;
$data = $user->where([["token", "=", $req->get("token")]])->first();
if (is_null($data)) {
$responseCode = 400;
$responseMessage = "User tidak ditemukan.";
} else {
$user->where("user_id", $data["user_id"])->update(["token" => null]);
$responseCode = 200;
$responseMessage = "Berhasil melakukan logout.";
}
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
return response()->json($response, $responseCode);
}
public function listUser()
{
}
}
<file_sep>/application/app/Http/Models/Transactions.php
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class Transactions extends Model
{
use SoftDeletes;
protected $table = 'transactions';
protected $primaryKey = 'transaction_id';
protected $guarded = [
'transaction_id',
];
protected $hidden = [
'from_date',
'end_date',
'created_at',
'created_by',
'updated_at',
'updated_by',
'deleted_at',
'deleted_by',
];
public $timestamps = false;
public function getTransactionAsset($id_asset)
{
$result = DB::table(DB::raw('transactions'))
->select(DB::raw('*'))
->where(DB::raw('asset_id'), '=', $id_asset)
->orderBy('created_at', 'desc')
->take(1)
->get();
return $result;
}
public function listTransaction($id_asset)
{
$query = DB::table('transactions as t')
->select(
't.transaction_id',
't.asset_id',
't.result_id',
'asset_name',
'at.asset_desc as asset_type_desc',
'a.asset_desc as asset_desc',
'station_name',
'result_name',
'result_desc',
'snapshot_url'
)
->leftJoin('assets as a', 't.asset_id', '=', 'a.asset_id')
->leftJoin('asset_type as at', 'at.asset_type_id', '=', 'a.asset_type_id')
->leftJoin('results as r', 't.result_id', '=', 'r.result_id')
->leftJoin('stations as s', 't.station_id', '=', 's.station_id')
->where('t.asset_id', $id_asset)
->orderBy('t.created_at', 'desc')
->get();
return $query;
}
}
<file_sep>/application/database/migrations/2019_09_09_113221_create_table_seq_scheme.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableSeqScheme extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('seq_scheme', function (Blueprint $table) {
$table->bigIncrements('seq_scheme_id');
$table->integer('station_id')->nullable();
$table->integer('predecessor_station_id')->nullable();
$table->integer('result_id')->nullable();
$table->integer('seq_scheme_group_id')->nullable();
$table->string('scheme_name')->nullable();
$table->date('from_date')->nullable();
$table->date('end_date')->nullable();
$table->string('created_by')->nullable();
$table->string('updated_by')->nullable();
$table->string('deleted_by')->nullable();
$table->timestamps();
$table->softDeletes()->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('seq_scheme');
}
}
<file_sep>/application/app/Http/Controllers/AssetTypeController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\AssetType;
class AssetTypeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
public function index()
{
$res = new AssetType;
return $res->all();
}
}
<file_sep>/application/helpers/directory.php
<?php
function base_url($value='')
{
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://".$_SERVER['HTTP_HOST'];
$base_url .= preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME'])).'/';
return $base_url;
}
function myBasePath($replace='', $to=''){
$root = $_SERVER['DOCUMENT_ROOT'];
$root .= preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME'])).'/';
if(!empty($replace)){
$root = str_replace($replace, $to, $root);
}
return $root;
}
function myStorage($url_path='')
{
$dir = 'jkhbvfds/'.$url_path;
return $dir;
}
function aset_tema($url_source='', $tema='metronic')
{
$dir = base_url().'assets/main/'.$tema.'/'.$url_source;
return $dir;
}
function aset_extends($url_source='')
{
$dir = base_url().'assets/extends/'.$url_source;
return $dir;
}
function zip_directory($path='', $zip_name='', $target_dir='')
{
$zip_name = empty($zip_name)? date('YmdHis').'.zip' : $zip_name.'.zip';
// if(file_exists($target_dir.$zip_name) and !is_dir($target_dir.$zip_name)){
// unlink($target_dir.$zip_name);
// echo 'a';
// }
// Get real path for our folder
$rootPath = realpath($path);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($target_dir.$zip_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
}
function helpCreateDirectory($directory='', $akses=0755){
if(!empty($directory)){
$explode_dir = explode('/', $directory);
if(count($explode_dir) > 0){
$temp_directory = '';
for ($i=0; $i < count($explode_dir); $i++) {
if(!empty($explode_dir[$i]) && $explode_dir[$i] != '.'){
$temp_directory .= $explode_dir[$i];
if(!is_dir($temp_directory)){
mkdir($temp_directory, $akses);
}
}
$temp_directory .= '/';
}
}else{
if(!is_dir($directory)){
mkdir($directory, $akses);
}
}
}
return true;
}
function protectPath($value='')
{
$arr_forbidden = ['../', '..'];
return str_replace($arr_forbidden, '', $value);
}
?><file_sep>/application/app/Http/Models/Results.php
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class Results extends Model
{
use SoftDeletes;
protected $table = 'results';
protected $primaryKey = 'result_id';
protected $guarded = [
'result_id',
];
protected $hidden = [
'from_date',
'end_date',
'created_at',
'created_by',
'updated_at',
'updated_by',
'deleted_at',
'deleted_by',
];
public $timestamps = false;
}
<file_sep>/application/app/Http/Controllers/RolesController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\Roles;
use App\Http\Models\Users;
use Illuminate\Http\Request;
class RolesController extends Controller
{
private $responseCode = 403;
private $responseStatus = '';
private $responseMessage = '';
private $responseData = [];
public function __construct()
{
//
}
public function index()
{
$res = new Roles;
$this->responseData = $res->all();
$this->responseCode = 200;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
public function getUsers($user_id='')
{
if (!empty($user_id)) {
$res = Users::find($user_id)->first();
$this->responseData = $res;
$this->responseCode = 200;
} else {
$res = new Users();
$this->responseData = $res->all();
$this->responseCode = 200;
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
<file_sep>/application/helpers/autoload.php
<?php
require 'app.php';
require 'client_info.php';
require 'directory.php';
require 'public.php';
require 'time.php';
?><file_sep>/application/app/Http/Controllers/ResultsController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\Results;
class ResultsController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
public function index()
{
$responseCode = 403;
$responseStatus = '';
$responseMessage = '';
$responseData = [];
$res = new Results;
$responseData = $res->all();
$responseCode = 200;
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
return response()->json($response, $responseCode);
}
}
<file_sep>/application/app/Http/Controllers/WatchController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Models\Users;
use App\Http\Models\Transactions;
use App\Http\Models\Assets;
class WatchController extends Controller
{
public function default($nama, Request $request)
{
$access_token = helpEmpty($request->get("token"), 'null');
$id_file = helpEmpty($request->get("un"), 'null');
$id_parent = helpEmpty($request->get("prt"), 'null');
$category = helpEmpty($request->get("ctg"), 'null');
$source = helpEmpty($request->get("src"), 'null');
$image = ['.jpg', '.jpeg', '.png'];
$file = myBasePath();
$cek_user = Users::getByAccessToken($access_token);
if (!empty($access_token) && !empty($cek_user)) {
$cek_id = '';
if ($category == 'transactions') {
$cek_id = Transactions::find($id_file);
// $id_parent = ($id_parent == md5($cek_id->id_mahasiswa . encText('mahasiswa'))) ? $cek_id->id_mahasiswa : false;
if (!empty($source) && !empty($category) && !empty($cek_id)) {
$file = storage_path('app/public/'.$category . '/' . $id_file . '/' . $source);
}
} else if ($category == 'assets') {
$cek_id = Assets::find($id_file);
// $id_parent = ($id_parent == md5($cek_id->id_mahasiswa . encText('mahasiswa'))) ? $cek_id->id_mahasiswa : false;
if (!empty($source) && !empty($category) && !empty($cek_id)) {
$file = storage_path('app/public/' . $category . '/' . $id_file . '/' . $source);
}
}
$file = protectPath($file);
if (file_exists($file) && !is_dir($file)) {
// $type = 'image';
$ext = pathinfo($file, PATHINFO_EXTENSION);
$ext = strtolower($ext);
if (in_array(strtolower($ext), $image)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
} else {
header('Content-Type:' . finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file));
header('Content-Length: ' . filesize($file));
readfile($file);
}
} else {
$response = helpResponse(404);
return response()->json($response, 404);
}
} else {
$response = helpResponse(401);
return response()->json($response, 401);
}
}
}
<file_sep>/application/app/Http/Models/Users.php
<?php
namespace App\Http\Models;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\SoftDeletes;
class Users extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
use SoftDeletes;
protected $table = 'users';
protected $primaryKey = 'user_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [
'role_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'from_date', 'end_date', 'created_at', 'created_by', 'updated_at', 'updated_by', 'deleted_at', 'deleted_by'
];
protected $dates = ['deleted_at'];
public static function get_auth($username = false)
{
if ($username == false) {
return false;
}
$result = DB::table("user")
->select(DB::raw('usr_id AS id_user, usr_name AS nama, usr_password AS password, usr_username AS username, usr_role AS role, usr_aktif AS aktif, usr_token_permission AS token_permission, usr_token_limits AS token_limits'))
->where('usr_aktif', true)
->whereNull('deleted_at');
$result = $result->where('usr_username', $username)->first();
return $result;
}
public static function get_data($id_user = false, $condition = false)
{
$result = DB::table("user")
->select(DB::raw('user_id AS id_user, username AS nama, usr_username AS username, usr_role AS role, usr_aktif AS aktif, usr_token_permission AS token_permission, usr_token_limits AS token_limits'))
->whereNull('deleted_at');
if ($condition == true) {
$result = $result->where('usr_aktif', '=', $condition);
}
if ($id_user == true) {
$result = $result->where('user_id', $id_user)->first();
} else {
$result = $result->orderBy('username', 'ASC')->get();
}
return $result;
}
public static function getByAccessToken($access_token = false)
{
if ($access_token == false) {
return false;
}
$result = DB::table(DB::raw('"users" usr'))
->select(DB::raw('user_id AS id_user, username AS username, email,role_id AS role, token AS access_token, station_id as id_station'))
->whereNull(DB::raw("usr.deleted_at"));
$result = $result->where('token', $access_token);
$result = $result->first();
return $result;
}
// public function roles()
// {
// return $this->hasOne('App\Http\Models\Roles');
// }
}
<file_sep>/application/database/seeds/ResultsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ResultsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('results')->insert([
'result_name' => 'V',
'result_desc' => 'Valid',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'NR',
'result_desc' => 'Newly Registered',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'NV',
'result_desc' => 'Not Valid',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'R1',
'result_desc' => 'Retest',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'R2',
'result_desc' => 'Repaint',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'R3',
'result_desc' => 'Pasang Balancer & Repaint',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'R4',
'result_desc' => 'Pasang Balancer, Retest, Repaint',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'R5',
'result_desc' => 'Annealing',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'F',
'result_desc' => 'Filled',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'X',
'result_desc' => 'Repaired',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'W',
'result_desc' => 'Waste',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'E',
'result_desc' => 'Empty',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('results')->insert([
'result_name' => 'UR',
'result_desc' => 'Unregistered',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
}
}
<file_sep>/application/helpers/app.php
<?php
function app_info($key=''){
$app_info = [
'title' => 'Energeek Laravel 5.5',
'description' => 'Energeek Laravel 5.5 Template',
'name' => 'Energeek Laravel 5.5',
'shortname' => 'ELA',
'icon' => aset_extends('img/e-logo.png'),
'client' => [
'shortname' => 'Geek',
'fullname' => 'Energeek',
'city' => 'Kota Surabaya',
'category' => 'Private'
],
'copyright' => [
'year' => '2019',
'text' => '© 2019 Energeek The E-Government Solution'
],
'vendor' => [
'company' => 'Energeek The E-Government Solution',
'office' => 'Jl Baratajaya 3/16, Surabaya, Jawa Timur',
'contact' => [
'phone' => '+62 856-3306-260',
'email' => '<EMAIL>',
'instagram' => 'https://www.instagram.com/energeek.co.id/'
],
'site' => 'http://energeek.co.id/'
]
];
$error=0;
if(empty($key)){
$result = $app_info;
}else{
$result = false;
$key = explode('.', $key);
if(is_array($key)){
$temp = $app_info;
for ($i=0; $i < count($key); $i++) {
$error++;
if(is_array($temp) and count($temp) > 0){
if(array_key_exists($key[$i], $temp)){
$error--;
$result = $temp[$key[$i]];
$temp = $temp[$key[$i]];
}
}
}
}
}
if($error > 0){
$result = false;
}
return $result;
}
function encText($value='', $md5=false)
{
$result = $value.'-energeek';
return (($md5 == false)? $result : md5($result));
}
?><file_sep>/application/app/Http/Controllers/SeqSchemeController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\SeqScheme;
class SeqSchemeController extends Controller
{
private $responseCode = 403;
private $responseStatus = '';
private $responseMessage = '';
private $responseData = [];
public function __construct()
{
//
}
public function index()
{
$res = new SeqScheme;
$this->responseData = $res->all();
$this->responseCode = 200;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
public function seeTheFlow()
{
$res = new SeqScheme;
$this->responseData = $res->showFlow();
$this->responseCode = 200;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
<file_sep>/application/database/seeds/AssetTypeTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class AssetTypeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('asset_type')->insert([
'asset_name' => 'Bright Gas 220 Gram',
'asset_desc' => 'Bright Gas 220 Gram',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('asset_type')->insert([
'asset_name' => 'Bright Gas 5,5Kg',
'asset_desc' => 'Bright Gas 5,5Kg',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('asset_type')->insert([
'asset_name' => 'Bright Gas 12Kg',
'asset_desc' => 'Bright Gas 12Kg',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('asset_type')->insert([
'asset_name' => 'Ease Gas 9Kg',
'asset_desc' => 'Ease Gas 9Kg',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('asset_type')->insert([
'asset_name' => 'Ease Gas 14Kg',
'asset_desc' => 'Ease Gas 14Kg',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('asset_type')->insert([
'asset_name' => 'Elpiji Gas 3Kg',
'asset_desc' => 'Elpiji Gas 3Kg',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('asset_type')->insert([
'asset_name' => 'Elpiji Gas 12Kg',
'asset_desc' => 'Elpiji Gas 12Kg',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
}
}
<file_sep>/application/database/seeds/SeqSchemeTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class SeqSchemeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('seq_scheme')->insert([
'station_id' => 2,
'predecessor_station_id' => null,
'result_id' => 13,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Unregistered New Cylinders',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 2,
'predecessor_station_id' => null,
'result_id' => null,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Unregistered New Cylinders',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 3,
'predecessor_station_id' => 2,
'result_id' => 2,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Registered Newly Cylinders',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
//start-----if Cylinders Type NV, R1, R2, R3, R4
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 3,
'result_id' => 3,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders type NV',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 3,
'result_id' => 4,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders type R1',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 3,
'result_id' => 5,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders type R2',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 3,
'result_id' => 6,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders type R3',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 3,
'result_id' => 7,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders type R4',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
//end-----if Cylinders Type NV, R1, R2, R3, R4
//yes
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 4,
'result_id' => 9,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Filled-Cylinders Type F',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
//no
DB::table('seq_scheme')->insert([
'station_id' => 5,
'predecessor_station_id' => 4,
'result_id' => 8,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders R5',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
//start repair order
DB::table('seq_scheme')->insert([
'station_id' => 6,
'predecessor_station_id' => 5,
'result_id' => 8,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repair Order Cylinders R5',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 6,
'predecessor_station_id' => 5,
'result_id' => 4,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repair Order Cylinders R1',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 6,
'predecessor_station_id' => 5,
'result_id' => 5,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repair Order Cylinders R2',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 6,
'predecessor_station_id' => 5,
'result_id' => 6,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repair Order Cylinders R3',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 6,
'predecessor_station_id' => 5,
'result_id' => 7,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repair Order Cylinders R4',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
//end repair order
DB::table('seq_scheme')->insert([
'station_id' => 2,
'predecessor_station_id' => 6,
'result_id' => 11,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repair Order Rejected(Unfixable) Cylinders Type W',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 3,
'predecessor_station_id' => 6,
'result_id' => 10,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Repaired Cylinders (Type X)',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => null,
'predecessor_station_id' => 5,
'result_id' => 3,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders type NV will be inspected and double checked',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 6,
'predecessor_station_id' => 5,
'result_id' => 12,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Empty Cylinders Cylinder Type E',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
DB::table('seq_scheme')->insert([
'station_id' => 4,
'predecessor_station_id' => 3,
'result_id' => 1,
'seq_scheme_group_id' => 1,
'scheme_name' => 'Cylinders Type V',
'created_by' => 1,
'created_at' => date("Y-m-d H:i:s"),
'from_date' => date('Y-m-d H:i:s'),
]);
}
}
<file_sep>/application/helpers/time.php
<?php
/**
* Function helpIndoDay
* Fungsi ini digunakan untuk mencari nama hari dalam bahasa Indonesia
* @access public
* @param (int) $var Nomor urut hari yang dimulai dari angka 0 untuk hari minggu
* @return (string) {'Undefined'}
*/
function helpIndoDay($var)
{
$dayArray = array("Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu");
if(array_key_exists($var, $dayArray )){
return $dayArray[$var];
}else{
return 'Undefined';
}
}
/**
* Function helpIndoMonth
* Fungsi ini digunakan untuk mencari nama bulan dalam bahasa Indonesia
* @access public
* @param (int) $var Nomor urut bulan yang dimulai dari angka 0 untuk bulan januari
* @return (string) {'Undefined'}
*/
function helpIndoMonth($num)
{
$monthArray = array("Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
if(array_key_exists($num, $monthArray)){
return $monthArray[$num];
}else{
return 'Undefined';
}
}
function helpReverseMonth($param, $mode='indo')
{
if($mode == 'indo'){
$monthArray = array("januari" => 1, "februari" => 2, "maret" => 3, "april" => 4, "mei" => 5, "juni" => 6, "juli" => 7, "agustus" => 8, "september" => 9, "oktober" => 10, "november" => 11, "desember" => 12);
}else{
$monthArray = [];
}
if(array_key_exists($param, $monthArray)){
return $monthArray[$param];
}else{
return 'Undefined';
}
}
/**
* Function helpDate
* Fungsi ini digunakan untuk melakukan konversi format tanggal
* @access public
* @param (date) $var Tanggal yang akan dikonversi
* @param (string) $mode Kode untuk model format yang baru
- se (short English) : (Y-m-d) 2015-31-01
- si (short Indonesia) : (d-m-Y) 31-01-2015
- me (medium English) : (F d, Y) January 31, 2015
- mi (medium Indonesia) : (d F Y) 31 Januari 2015
- le (long English) : (l F d, Y) Sunday January 31, 2015
- li (long Indonesia) : (l, d F Y) Senin, 31 Januari 2015
* @return (string) {'Undefined'}
*/
function helpDate($var, $mode = 'se')
{
switch($mode){
case 'se':
return date('Y-m-d', strtotime($var));
break;
case 'si':
return date('d-m-Y', strtotime($var));
break;
case 'me':
return date('F d, Y', strtotime($var));
break;
case 'mi':
$day = date('d', strtotime($var));
$month = date('n', strtotime($var));
$year = date('Y', strtotime($var));
$month = helpIndoMonth($month - 1);
return $day.' '.$month.' '.$year;
break;
case 'le':
return date('l F d, Y', strtotime($var));
break;
case 'li':
$dow = date('w', strtotime($var));
$day = date('d', strtotime($var));
$month = date('n', strtotime($var));
$year = date('Y', strtotime($var));
$hari = helpIndoDay($dow);
$month = helpIndoMonth($month - 1);
return $hari .', '. $day.' '.$month.' '.$year;
break;
case 'bi':
$month = date('n', strtotime($var));
$year = date('Y', strtotime($var));
$month = helpIndoMonth($month - 1);
return $month.' '.$year;
break;
default:
return 'Undefined';
break;
}
}
function helpDateToWeek($date)
{
$minggu = '';
$new_date = date('d', strtotime($date));
if($new_date >= 1 and $new_date <= 7){
$minggu = '1';
}elseif ($new_date <= 14) {
$minggu = '2';
}elseif ($new_date <= 21) {
$minggu = '3';
}else {
$minggu = '4';
}
return $minggu;
}
function helpDateValidation($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function helpTanggalTeks($tgl_mulai='', $tgl_selesai='', $hari=false, $separator=' - ')
{
$hari_mulai = date('w', strtotime($tgl_mulai));
$tanggal_mulai = date('j', strtotime($tgl_mulai));
$bulan_mulai = date('Y-m', strtotime($tgl_mulai));
$tahun_mulai = date('Y', strtotime($tgl_mulai));
$hari_pelatihan = helpIndoDay($hari_mulai);
$tanggal_pelatihan = $tanggal_mulai.' '.helpIndoMonth(date('n', strtotime($tgl_mulai)) - 1).' '.date('Y', strtotime($tgl_mulai));
if($tgl_mulai != $tgl_selesai){
$hari_selesai = date('w', strtotime($tgl_selesai));
$tanggal_selesai = date('j', strtotime($tgl_selesai));
$bulan_selesai = date('Y-m', strtotime($tgl_selesai));
$tahun_selesai = date('Y', strtotime($tgl_selesai));
$hari_pelatihan = helpIndoDay($hari_mulai).$separator.helpIndoDay($hari_selesai);
if($bulan_mulai == $bulan_selesai){
$tanggal_pelatihan = $tanggal_mulai.$separator.$tanggal_selesai.' '.helpIndoMonth(date('n', strtotime($tgl_mulai)) - 1).' '.date('Y', strtotime($tgl_mulai));
}else{
if($tahun_mulai == $tahun_selesai){
$tanggal_pelatihan = $tanggal_mulai.' '.helpIndoMonth(date('n', strtotime($tgl_mulai)) - 1).$separator.$tanggal_selesai.' '.helpIndoMonth(date('n', strtotime($tgl_selesai)) - 1).' '.date('Y', strtotime($tgl_mulai));
}else{
$tanggal_pelatihan = $tanggal_mulai.' '.helpIndoMonth(date('n', strtotime($tgl_mulai)) - 1).' '.date('Y', strtotime($tgl_mulai)).$separator.$tanggal_selesai.' '.helpIndoMonth(date('n', strtotime($tgl_selesai)) - 1).' '.date('Y', strtotime($tgl_selesai));
}
}
}
if($hari == true){
$tanggal_pelatihan = $hari_pelatihan.', '.$tanggal_pelatihan;
}
return $tanggal_pelatihan;
}
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* Function helpDateQuery
* Fungsi ini digunakan untuk melakukan konversi format tanggal
* @access public
* @param (date) $var Tanggal yang akan dikonversi
* @param (string) $mode Kode untuk model format yang baru
- se (short English) : (Y-m-d) 2015-31-01 (x)
- si (short Indonesia) : (d-m-Y) 31-01-2015 (x)
- me (medium English) : (F d, Y) January 31, 2015 (x)
- mi (medium Indonesia) : (d F Y) 31 Januari 2015 (v)
- le (long English) : (l F d, Y) Sunday January 31, 2015 (x)
- li (long Indonesia) : (l, d F Y) Senin, 31 Januari 2015 (x)
* @return (string) {'Undefined'}
*/
function helpDateQuery($column='', $mode='mi', $db='mysql')
{
$result = false;
if($mode == 'mi'){
if($db == 'mysql'){
$temp = 'CASE';
for ($i=0; $i < 12; $i++) {
$temp .= ' WHEN MONTH('.$column.') = '.($i + 1).' THEN CONCAT(DAY('.$column.')," ", "'.helpIndoMonth($i).'", " ", YEAR('.$column.'))';
}
$temp .= 'END';
$result = $temp;
}elseif($db == 'pgsql'){
$temp = 'CASE';
for ($i=0; $i < 12; $i++) {
$temp .= ' WHEN EXTRACT(MONTH FROM '.$column.') = '.($i + 1).' THEN CONCAT(EXTRACT (DAY FROM '.$column.'),\' \', \''.helpIndoMonth($i).'\', \' \', EXTRACT (YEAR FROM '.$column.'))';
}
$temp .= 'END';
$result = $temp;
}
}
return $result;
}<file_sep>/application/app/Http/Controllers/StockMovementController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\StockMovement;
use App\Http\Models\Document;
use App\Http\Models\ReportType;
use App\Http\Models\Assets;
use App\Http\Models\Transactions;
use App\Http\Models\SeqScheme;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class StockMovementController extends Controller
{
private $responseCode = 403;
private $responseStatus = '';
private $responseMessage = '';
private $responseData = [];
private $responseNote = null;
private function processing($res_transaction, $id_result)
{
$res_seq_scheme = new SeqScheme;
$obj = $res_seq_scheme->where('predecessor_station_id', $res_transaction->station_id)->where('result_id', $id_result)->first();
if ($obj !== null) {
return $obj->station_id;
}
}
public function index(Request $req)
{
$rules['start'] = 'required|integer|min:0';
$rules['perpage'] = 'required|integer|min:1';
$validator = Validator::make($req->all(), $rules);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseStatus = 'Missing Param';
$this->responseMessage = 'Silahkan isi form dengan benar terlebih dahulu';
$this->responseData = $validator->errors();
} else {
$res = new StockMovement();
$start = $req->input('start');
$perpage = $req->input('perpage');
$search = $req->input('search');
$order = $req->input('order');
$pattern = '/[^a-zA-Z0-9 !@#$%^&*\/\.\,\(\)-_:;?\+=]/u';
$search = preg_replace($pattern, '', $search);
$sort = $order??'desc';
$field = 'd.created_at';
$total = $res->jsonGrid($start, $perpage, $search, true, $sort, $field);
$resource = $res->jsonGrid($start, $perpage, $search, false, $sort, $field);
$this->responseCode = 200;
$this->responseData = $resource;
// $pagination = ['row' => count($resource), 'rowStart' => ((count($resource) > 0) ? ($start + 1) : 0), 'rowEnd' => ($start + count($resource))];
// $this->responseData['meta'] = ['start' => $start, 'perpage' => $perpage, 'search' => $search, 'total' => $total, 'pagination' => $pagination];
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
public function generateDocumentNumber(Request $req)
{
$user = $req->get('my_auth');
$temp = Document::where('document_status', 1)->where('station_id', $user->id_station)->first();
if (empty($temp)) {
$resource = new StockMovement;
$resource = $resource->getStationRole($user->id_user);
if (!empty($resource)) {
$document = new Document;
$saved = $document->save();
$id_document = $document->document_id;
if (!$saved) {
$this->responseCode = 500;
$this->responseMessage = 'Gagal membuat document number, silahkan ulangi kembali!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$number = $resource->abbreviation;
$angka = 20 - (strlen($number) + strlen($id_document));
for ($i = 0; $i < $angka; $i++) {
$number .= "0";
}
$report_type = ReportType::where('has_designation', 1)->first();
$number .= $id_document;
$document->report_type_id = $report_type->report_type_id;
$document->document_number = $number;
$document->station_id = $user->id_station;
$document->document_status = 1;
$document->created_at = date('Y-m-d H:i:s');
$document->created_by = $user->id_user;
$document->save();
$this->responseCode = 200;
$this->responseData = [
'document_number' => $number,
'document_id' => $document->document_id,
];
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
} else {
$this->responseCode = 500;
$this->responseMessage = 'Users tidak ditemukan! Silahkan login kembali!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
return response()->json($response, $this->responseCode);
} else {
$this->responseCode = 500;
$this->responseMessage = 'Anda tidak diizinkan menambah dokumen selama masih ada draft!';
$this->responseData['document_id'] = $temp->document_id;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
public function getReadyAssets(Request $req)
{
$user = $req->get('my_auth');
$validator = Validator::make($req->all(), [
'qr_code' => 'required',
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$assets = new Assets;
$qr_code = $req->input('qr_code');
$res = $assets->getDetail($qr_code);
echo $res->station_id;
if (empty($res)) {
$this->responseCode = 400;
$this->responseMessage = 'Asset tidak ditemukan';
} else {
if ($res->station_id == $user->id_station && ($res->result_id == 4 || $res->result_id == 5 || $res->result_id == 6 || $res->result_id == 7 || $res->result_id == 8)) {
$this->responseCode = 200;
$this->responseData = $res;
$this->responseNote['pics_url'] = [
'url' => '{base_url}/watch/{pics_url}?token={access_token}&un={asset_id}&ctg=assets&src={pics_url}'
];
} else {
$this->responseCode = 500;
$this->responseMessage = 'Station harus dari shipping plant dan kondisinya R1,R2,R3,R4, atau R5';
}
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus, $this->responseNote);
return response()->json($response, $this->responseCode);
}
}
public function listStockAsset(Request $req)
{
$id_document = $req->input('document_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$detail_asset_stock = new StockMovement();
$res = $detail_asset_stock->assetOfStockMovement($id_document);
$this->responseCode = 200;
$this->responseData = $res;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
public function show(Request $req)
{
$id_document = $req->input('document_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$document = new StockMovement;
$res = $document->getDetail($id_document);
if (empty($res)) {
$this->responseCode = 400;
$this->responseMessage = 'Document tidak ditemukan';
} else {
$this->responseCode = 200;
$this->responseData = $res;
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
public function listScanned(Request $req)
{
$status = $req->input('status');
$id_document = $req->input('document_id');
$validator = Validator::make($req->all(), [
'status' => 'required',
'document_id' => [
'required',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})
]
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
if ($status == 1 or $status == 2) {
$stock_movement = new StockMovement;
$res = $stock_movement->listScan($id_document, $status);
$this->responseCode = 200;
$this->responseData = $res;
} else {
$this->responseCode = 400;
$this->responseMessage = 'Status parameter tidak dikenali!';
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus, $this->responseNote);
return response()->json($response, $this->responseCode);
}
}
public function acceptScan(Request $req)
{
$user = $req->get('my_auth');
$id_document = $req->input('document_id');
$id_asset = $req->input('asset_id');
$validator = Validator::make($req->all(), [
'document_id' => ['required',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})],
'asset_id' => ['required',
Rule::exists('assets')->where(function ($query) use ($id_asset) {
$query->where('asset_id', $id_asset);
})]
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$assets = new Assets;
$rr = $assets->find($id_asset);
$qr_code = $rr->qr_code;
$res = $assets->getDetail($qr_code);
if (empty($res)) {
$this->responseCode = 500;
$this->responseMessage = 'Asset tidak ditemukan';
} else {
if ($res->station_id == 6 && ($res->result_id == 4 || $res->result_id == 5 || $res->result_id == 6 || $res->result_id == 7 || $res->result_id == 8)) {
$jj = StockMovement::where('asset_id', $id_asset)->where('document_id', $id_document)->first();
$jj->stock_move_status = 2;
$jj->updated_at = date('Y-m-d H:i:s');
$jj->updated_by = $user->id_user;
$jj->save();
// $res_doc = Document::find($id_document);
// foreach ($stock_movement as $key) {
// $res_trans = Transactions::where('asset_id', $id_asset)->orderBy('created_at', 'desc')->take(1)->first();
// if (empty($res_trans)) {
// $station = 2;
// } else {
// $station = $this->processing($res_trans, $res_trans->result_id);
// }
// if ($res_doc->destination_station_id == 3) {
// $result_status = 10;
// } else if ($res_doc->destination_station_id == 2) {
// $result_status = 11;
// }
// $arr_store = [
// 'asset_id' => $id_asset,
// 'station_id' => $res_doc->destination_station_id,
// 'result_id' => $result_status,
// 'created_at' => date('Y-m-d H:i:s'),
// 'created_by' => $user->id_user,
// ];
// $saved = Transactions::create($arr_store);
// }
$this->responseCode = 202;
$this->responseData = $jj;
$this->responseMessage = 'Asset Berhasil discan';
} else {
$this->responseCode = 500;
$this->responseMessage = 'Station harus dari shipping plant dan kondisinya R1,R2,R3,R4, atau R5';
}
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus, $this->responseNote);
return response()->json($response, $this->responseCode);
}
}
public function store(Request $req)
{
$id_destination_station = $req->input('station_id');
$id_document = $req->input('document_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})
],
'station_id' => [
'required',
'numeric',
Rule::exists('stations')->where(function ($query) use ($id_destination_station) {
$query->where('station_id', $id_destination_station);
})
],
'start_date' => 'date_format:d-m-Y',
'end_date' => 'date_format:d-m-Y',
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$user = $req->get('my_auth');
$start_date = $req->input('start_date');
$end_date = $req->input('end_date');
$res = Document::find($id_document);
$res->destination_station_id = $id_destination_station;
$res->start_date = date('Y-m-d', strtotime($start_date));
$res->end_date = date('Y-m-d', strtotime($end_date));
$res->updated_at = date('Y-m-d H:i:s');
$res->updated_by = $user->id_user;
$saved = $res->save();
if (!$saved) {
$this->responseCode = 502;
$this->responseMessage = 'Data gagal disimpan!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$this->responseCode = 201;
$this->responseMessage = 'Data berhasil disimpan!';
$this->responseData = $saved;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
public function listDestinationStation(Request $req)
{
// $id_document = $req->input('document_id');
// $validator = Validator::make($req->all(), [
// 'document_id' => [
// 'required',
// 'numeric',
// Rule::exists('document')->where(function ($query) use ($id_document) {
// $query->where('document_id', $id_document);
// })
// ],
// ]);
// if ($validator->fails()) {
// $this->responseCode = 400;
// $this->responseMessage = $validator->errors();
// $response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
// return response()->json($response, $this->responseCode);
// } else {
$stock_movement = new StockMovement;
$res = $stock_movement->listDestination(3);
$this->responseCode = 200;
$this->responseData = $res;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
// }
}
public function accept(Request $req)
{
$id_document = $req->input('document_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
$query->where('document_status', 1);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$user = $req->get('my_auth');
$id_document = $req->input('document_id');
$res = Document::find($id_document);
$res->document_status = 2;
$res->save();
$report_type = ReportType::where('can_be_ref', 1)->first();
$arr = [
'ref_doc_number' => $res->document_number,
'report_type_id' => $report_type->report_type_id,
'station_id' => $res->station_id,
'destination_station_id' => $res->destination_station_id,
'document_status' => 3,
'start_date' => date('Y-m-d', strtotime($res->start_date)),
'end_date' => date('Y-m-d', strtotime($res->end_date)),
'created_at' => date('Y-m-d H:i:s'),
'created_by' => $user->id_user,
];
$saved = Document::create($arr);
$stock_movement = StockMovement::where('document_id', $id_document)->get();
foreach ($stock_movement as $key) {
$gg = [
'document_id' => $saved->document_id,
'asset_id' => $key->asset_id,
'stock_move_status' => 1,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => $user->id_user,
];
StockMovement::create($gg);
}
if (!$saved) {
$this->responseCode = 502;
$this->responseMessage = 'Data gagal disimpan!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
foreach ($stock_movement as $key) {
$res_trans = Transactions::where('asset_id', $key->asset_id)->orderBy('created_at', 'desc')->take(1)->first();
if (empty($res_trans)) {
$station = 2;
} else {
$station = $this->processing($res_trans, $res_trans->result_id);
}
$arr_store = [
'asset_id' => $key->asset_id,
'station_id' => $station,
'result_id' => $res_trans->result_id,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => $user->id_user,
];
$saved = Transactions::create($arr_store);
}
$this->responseCode = 201;
$this->responseMessage = 'Data berhasil disimpan!';
$this->responseData = $saved;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
public function approveGR(Request $req)
{
$id_document = $req->input('document_id');
$user = $req->get('my_auth');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
$query->where('document_status', 3);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$res = Document::find($id_document);
$res->document_status = 4;
$res->updated_at = date('Y-m-d H:i:s');
$res->updated_by = $user->id_user;
$saved = $res->save();
if (!$saved) {
$this->responseCode = 502;
$this->responseMessage = 'Data gagal disimpan!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$this->responseCode = 201;
$this->responseMessage = 'Data berhasil disimpan!';
$this->responseData = $res;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
public function storeAssets(Request $req)
{
$id_document = $req->input('document_id');
$id_asset = $req->input('asset_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})
],
'asset_id' => [
'required',
Rule::exists('assets')->where(function ($query) use ($id_asset) {
$query->where('asset_id', $id_asset);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$stock_movement = StockMovement::where('asset_id', $id_asset)->get();
if ($stock_movement->isEmpty()) {
$user = $req->get('my_auth');
$arr = [
'document_id' => $id_document,
'asset_id' => $id_asset,
'stock_move_status' => 1,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => $user->id_user,
];
StockMovement::create($arr);
$this->responseCode = 201;
$this->responseMessage = 'Data berhasil disimpan!';
$this->responseData = $arr;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$this->responseCode = 400;
$this->responseMessage = 'Asset sudah tidak tersedia! Kemungkinan sudah ditambahkan di stock movement lain';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
}
public function deleteAsset(Request $req)
{
$id_document = $req->input('document_id');
$id_asset = $req->input('asset_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('stock_movement')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})
],
'asset_id' => [
'required',
'numeric',
Rule::exists('stock_movement')->where(function ($query) use ($id_asset) {
$query->where('asset_id', $id_asset);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 500;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$resource = StockMovement::where('document_id', $id_document)->where('asset_id', $id_asset)->first();
$resource->forceDelete();
$this->responseCode = 202;
$this->responseMessage = 'Berhasil dihapus!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
public function delete(Request $req)
{
$id_document = $req->input('document_id');
$validator = Validator::make($req->all(), [
'document_id' => [
'required',
'numeric',
Rule::exists('document')->where(function ($query) use ($id_document) {
$query->where('document_id', $id_document);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 500;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$destroy = Document::destroy($id_document);
if ($destroy) {
$this->responseCode = 202;
$this->responseMessage = 'Document berhasil dihapus!';
$this->responseData = $destroy;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$this->responseCode = 500;
$this->responseMessage = 'Document gagal dihapus! Data mungkin sudah dihapus atau tidak ditemukan';
$this->responseData = $destroy;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
public function deleteAll()
{
$stock_movement = StockMovement::whereNotNull('stock_movement_id');
$destroy2 = $stock_movement->forceDelete();
$document = Document::whereNotNull('document_id');
$destroy = $document->forceDelete();
if ($destroy) {
$this->responseCode = 202;
$this->responseMessage = 'Document berhasil dihapus semua!';
$this->responseData = $destroy;
$this->responseStatus = 'Accepted';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$this->responseCode = 500;
$this->responseMessage = 'Document gagal dihapus! Data kemungkinan sudah dihapus semua!';
$this->responseData = $destroy;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
<file_sep>/application/app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
class UsersController extends Controller
{
private $responseCode = 403;
private $responseStatus = '';
private $responseMessage = '';
private $responseData = [];
public function __construct()
{
//
}
public function index()
{
$responseCode = 403;
$responseStatus = '';
$responseMessage = '';
$responseData = [];
$res = new Users;
$responseData = $res->all();
$responseCode = 200;
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
return response()->json($response, $responseCode);
}
public function changePassword(Request $req)
{
$id_user = $req->input('user_id');
$password = $req->input('password');
$new_password = $req->input('<PASSWORD>');
$retype_password = $req->input('retype_password');
$user = Users::findOrFail($id_user);
$validator = Validator::make($req->all(), [
'user_id' => ['required',
Rule::exists('users')->where(function ($query) use ($id_user) {
$query->where('user_id', $id_user);
})
],
'password' => [
'<PASSWORD>'
],
'new_password' => '<PASSWORD>',
'retype_password' => '<PASSWORD>|same:<PASSWORD>',
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
if (Hash::check($password, $user->password)) {
$user->fill([
'password' => <PASSWORD>($new_<PASSWORD>)
])->save();
$this->responseCode = 200;
$this->responseMessage = 'Password berhasil diubah';
$this->responseData = [];
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$this->responseCode = 500;
$this->responseMessage = 'Password lama tidak cocok!';
$this->responseData = [];
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
}
}
<file_sep>/application/database/migrations/2019_09_09_102748_create_table_station_role.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableStationRole extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('station_role', function (Blueprint $table) {
$table->increments('station_role_id');
$table->integer('role_id')->nullable();
$table->integer('station_id')->nullable();
$table->date('from_date')->nullable();
$table->date('end_date')->nullable();
$table->string('created_by')->nullable();
$table->string('updated_by')->nullable();
$table->string('deleted_by')->nullable();
$table->timestamps();
$table->softDeletes()->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('station_role');
}
}
<file_sep>/application/app/Http/Models/Assets.php
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class Assets extends Model
{
use SoftDeletes;
protected $table = 'assets';
protected $primaryKey = 'asset_id';
protected $guarded = [
'asset_id',
];
protected $hidden = [
'from_date',
'end_date',
'created_at',
'created_by',
'updated_at',
'updated_by',
'deleted_at',
'deleted_by',
];
public $timestamps = false;
public function assetType()
{
return $this->hasMany('App\Http\Models\AssetType', 'asset_type_id', 'asset_type_id');
}
public function getDetail($qr_code, $id_station='')
{
$query = DB::table(DB::raw('assets a'))
->selectRaw('
a.asset_id,
r.result_id,
s.station_id,
asset_name,
at.asset_desc as asset_type_desc,
a.asset_desc as asset_desc,
gross_weight,
net_weight,
pics_url,
qr_code,
serial_number,
TO_CHAR(manufacture_date, \'dd/mm/yyyy\') as manufacture_date,
TO_CHAR(expiry_date, \'dd/mm/yyyy\') as expiry_date,
height,
width,
a.from_date,
a.end_date,
group_name,
group_desc,
COALESCE(s.station_name, \'\')as station_name,
COALESCE(r.result_name, \'\')as result_name,
COALESCE(r.result_desc, \'\')as result_desc,
a.created_at,
a.updated_at')
->leftJoin('transactions as t', 't.asset_id', '=', 'a.asset_id')
->leftJoin('stations as s', 's.station_id', '=', 't.station_id')
->leftJoin('asset_type as at', 'a.asset_type_id', '=', 'at.asset_type_id')
->leftJoin('results as r', 't.result_id', '=', 'r.result_id')
->leftJoin('manufacturer as m', 'm.manufacturer_id', '=', 'a.manufacturer_id')
->leftJoin('seq_scheme_group as ssg', 'a.seq_scheme_group_id', '=', 'ssg.seq_scheme_group_id')
->where('a.qr_code', $qr_code)
->whereNull('a.deleted_at')
->whereNull('t.deleted_at')
->whereNull('s.deleted_at')
->whereNull('at.deleted_at')
->whereNull('r.deleted_at')
->whereNull('m.deleted_at')
->whereNull('ssg.deleted_at')
->orderBy('transaction_id', 'desc')
->take(1);
if ($id_station != '') {
$query->where('s.station_id', '!=', 5);
}
return $query->first();
}
public static function jsonGrid($start, $length, $search = '', $count = false, $sort, $field)
{
$result = DB::table('assets as a')
->selectRaw('
asset_id,
asset_name,
at.asset_desc as asset_type_desc,
a.asset_desc as asset_desc,
gross_weight,
net_weight,
pics_url,
qr_code,
serial_number,
TO_CHAR(manufacture_date, \'dd/mm/yyyy\') as manufacture_date,
TO_CHAR(expiry_date, \'dd/mm/yyyy\') as expiry_date,
height,
width
')
->leftJoin('asset_type as at', 'a.asset_type_id', '=', 'at.asset_type_id')
->whereNull('a.deleted_at');
if (!empty($search)) {
$result = $result->where(function ($where) use ($search) {
$where->where('asset_name', 'ILIKE', '%' . $search . '%')
->orWhere('at.asset_desc', 'ILIKE', '%' . $search . '%')
->orWhere('a.asset_desc', 'ILIKE', '%' . $search . '%')
->orWhere('a.qr_code', 'ILIKE', '%' . $search . '%')
->orWhere('a.serial_number', 'ILIKE', '%' . $search . '%');
});
}
$result = $result->offset($start)->limit($length)->orderBy($field, $sort)->get();
if ($count == false) {
return $result;
} else {
return $result->count();
}
}
public function getAll()
{
$query = DB::table('assets as a')
->selectRaw('
asset_id,
asset_name,
at.asset_desc as asset_type_desc,
a.asset_desc as asset_desc,
gross_weight,
net_weight,
pics_url,
qr_code,
serial_number,
TO_CHAR(manufacture_date, \'dd/mm/yyyy\') as manufacture_date,
TO_CHAR(expiry_date, \'dd/mm/yyyy\') as expiry_date,
height,
width')
->join('asset_type as at', 'a.asset_type_id', '=', 'at.asset_type_id')
->whereNull('a.deleted_at')
->get();
return $query;
}
}
<file_sep>/application/app/Http/Controllers/TransactionsController.php
<?php
namespace App\Http\Controllers;
use App\Http\Models\Assets;
use App\Http\Models\SeqScheme;
use App\Http\Models\Transactions;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
class TransactionsController extends Controller
{
private $responseCode = 403;
private $responseStatus = '';
private $responseMessage = '';
private $responseData = [];
public function __construct()
{
//
}
public function index()
{
$res = new Transactions;
return $res->all();
}
public function reduceSize()
{
$source = storage_path("app/uploads/{$_GET["id"]}/{$_GET["file"]}");
if (!is_dir(storage_path("app/uploads/compress/{$_GET["id"]}/"))) {
mkdir(storage_path("app/uploads/compress/{$_GET["id"]}/"));
}
$destination = storage_path("app/uploads/compress/{$_GET["id"]}/{$_GET["file"]}");
$quality = 90;
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
}
public function store(Request $req)
{
$id_asset = $req->input('asset_id');
$id_result = $req->input('result_id');
$validator = Validator::make($req->all(), [
'asset_id' => [
'required',
Rule::exists('assets')->where(function ($query) use ($id_asset) {
$query->where('asset_id', $id_asset);
})
],
'result_id' => [
'required',
Rule::exists('results')->where(function ($query) use ($id_result) {
$query->where('result_id', $id_result);
})
],
'snapshot_url' => 'required|mimetypes:image/jpeg,image/png,image/bmp,image/gif|max:9000',
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
$res_assets = Assets::find($id_asset);
if ($res_assets !== null) {
$user = $req->get('my_auth');
$res_trans = Transactions::where('asset_id', $id_asset)->orderBy('created_at', 'desc')->take(1)->first();
if (empty($res_trans)) {
$station = 2;
} else {
$station = $this->processing($res_trans, $id_result);
}
$arr_store = [
'asset_id' => $id_asset,
'station_id' => $station,
'result_id' => $id_result,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => $user->id_user,
];
$saved = Transactions::create($arr_store);
if (!$saved) {
$this->responseCode = 502;
$this->responseMessage = 'Data gagal disimpan!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$snapshot = $req->file('snapshot_url')->getClientOriginalName();
if ($req->file('snapshot_url')->isValid()) {
$destinationPath = storage_path('app/public').'/transactions/'.$saved->transaction_id;
$req->file('snapshot_url')->move($destinationPath, $snapshot);
$temp_trans = Transactions::find($saved->transaction_id);
$temp_trans->snapshot_url = $snapshot;
$temp_trans->save();
}
$this->responseCode = 201;
$this->responseMessage = 'Data berhasil disimpan!';
$this->responseData = $temp_trans;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
} else {
$this->responseCode = 500;
$this->responseMessage = 'ID Asset tidak ditemukan!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
public function processing($res_transaction, $id_result)
{
$res_seq_scheme = new SeqScheme;
$obj = $res_seq_scheme->where('predecessor_station_id', $res_transaction->station_id)->where('result_id', $id_result)->first();
if ($obj !== null) {
return $obj->station_id;
}
}
public function generateResult(Request $req)
{
$id_asset = $req->input('asset_id');
$validator = Validator::make($req->all(), [
'asset_id' => ['required',
Rule::exists('assets')->where(function ($query) use ($id_asset) {
$query->where('asset_id', $id_asset);
})],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$id_station = $req->input('station_id');
if ($id_station == null) {
$gathel = Transactions::where('asset_id', $id_asset)->get();
if ($gathel->isEmpty()) {
$seq_scheme = new SeqScheme();
$res = $seq_scheme->getResultByStation(1);
$this->responseCode = 200;
$this->responseData = $res;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
} else {
$this->responseCode = 500;
$this->responseData = '';
$this->responseMessage = 'Asset tidak ditemukan di transaksi dan station harus ada!';
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
} else {
$seq_scheme = new SeqScheme();
$res = $seq_scheme->getResultByStation($id_station);
$this->responseCode = 200;
$this->responseData = $res;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
}
return response()->json($response, $this->responseCode);
}
}
public function currentStatus($id_asset)
{
$res_seq_scheme = new SeqScheme;
$res_trans = $res_seq_scheme->checkPosition($id_asset);
if (empty($res_trans)) {
$this->responseCode = 400;
$this->responseMessage = 'Data tidak ditemukan!';
} else {
$this->responseCode = 200;
$this->responseData = $res_trans;
}
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
public function listTransactionAsset(Request $req)
{
$id_asset = $req->input('asset_id');
$validator = Validator::make($req->all(), [
'asset_id' => [
'required',
Rule::exists('assets')->where(function ($query) use ($id_asset) {
$query->where('asset_id', $id_asset);
})
],
]);
if ($validator->fails()) {
$this->responseCode = 400;
$this->responseMessage = $validator->errors();
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
} else {
$trans = new Transactions;
$res = $trans->listTransaction($id_asset);
$this->responseCode = 200;
$this->responseData = $res;
$response = helpResponse($this->responseCode, $this->responseData, $this->responseMessage, $this->responseStatus);
return response()->json($response, $this->responseCode);
}
}
}
<file_sep>/application/app/Http/Middleware/EnergeekAuthMiddleware.php
<?php
namespace App\Http\Middleware;
use App\Http\Models\Users;
use Closure;
class EnergeekAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $idRole = '')
{
$responseCode = 403;
$responseStatus = '';
$responseMessage = '';
$responseData = [];
$access_token = $request->header('access-token') ? $request->header('access-token') : $request->input('access_token');
if ($access_token) {
$auth = Users::getByAccessToken($access_token);
if ($auth) {
if (!empty($idRole)) {
$roles = (strpos($idRole, '&') !== false) ? explode('&', $idRole) : array($idRole);
if (in_array($auth->role, $roles)) {
$responseCode = 200;
} else {
$responseCode = 403;
$responseMessage = 'Anda tidak dapat mengakses halaman ini, silahkan hubungi Administrator';
}
} else {
$responseCode = 200;
}
} else {
$responseCode = 401;
$responseMessage = 'Token tidak valid';
}
} else {
$responseCode = 403;
$responseMessage = 'Anda tidak dapat mengakses halaman ini, silahkan hubungi Administrator';
}
if ($responseCode == 200) {
$request->attributes->add(['my_auth' => $auth]);
return $next($request);
} else {
$response = helpResponse($responseCode, $responseData, $responseMessage, $responseStatus);
return response()->json($response, $responseCode);
}
}
}
<file_sep>/application/.env.example
APP_ENV=local
APP_DEBUG=true
APP_KEY=<KEY>
APP_TIMEZONE=Asia/Jakarta
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=pertagas_qrtg
DB_USERNAME=postgres
DB_PASSWORD=<PASSWORD>
CACHE_DRIVER=file
QUEUE_DRIVER=sync
<file_sep>/application/database/migrations/2019_09_09_110445_create_table_assets.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableAssets extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('assets', function (Blueprint $table) {
$table->bigIncrements('asset_id');
$table->integer('asset_type_id')->nullable();
$table->integer('manufacturer_id')->nullable();
$table->integer('seq_scheme_group_id')->nullable();
$table->text('asset_desc')->nullable();
$table->float('gross_weight')->nullable();
$table->float('net_weight')->nullable();
$table->string('pics_url')->nullable();
$table->string('serial_number')->nullable();
$table->date('manufacture_date')->nullable();
$table->date('expiry_date')->nullable();
$table->float('height')->nullable();
$table->float('width')->nullable();
$table->date('from_date')->nullable();
$table->date('end_date')->nullable();
$table->string('created_by')->nullable();
$table->string('updated_by')->nullable();
$table->string('deleted_by')->nullable();
$table->timestamps();
$table->softDeletes()->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('assets');
}
}
<file_sep>/application/database/migrations/2019_09_09_111726_create_table_stations.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableStations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stations', function (Blueprint $table) {
$table->increments('station_id');
$table->integer('result_id')->nullable();
$table->string('station_name')->nullable();
$table->string('abbreviation')->nullable();
$table->float('lat')->nullable();
$table->float('long')->nullable();
$table->date('from_date')->nullable();
$table->date('end_date')->nullable();
$table->string('created_by')->nullable();
$table->string('updated_by')->nullable();
$table->string('deleted_by')->nullable();
$table->timestamps();
$table->softDeletes()->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('stations');
}
}
<file_sep>/application/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
use Illuminate\Http\Request;
$router->get('/', function () use ($router) {
return $router->app->version();
});
$router->group(['prefix' => 'auth'], function () use ($router) {
/* Auth */
$router->post('/login', 'AuthController@index');
$router->post('/logout', 'AuthController@logout');
});
$router->group(['prefix' => 'results', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'ResultsController@index');
});
$router->group(['prefix' => 'manufacturer', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'ManufacturerController@index');
});
$router->group(['prefix' => 'asset_type', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'AssetTypeController@index');
});
$router->group(['prefix' => 'report_type', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'ReportTypeController@index');
});
$router->group(['prefix' => 'roles', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'RolesController@index');
$router->get('/get_users[/{user_id}]', 'RolesController@getUsers');
});
$router->group(['prefix' => 'stations', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'StationsController@index');
});
$router->group(['prefix' => 'seqscheme', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'SeqSchemeController@index');
$router->get('/see_the_flow', 'SeqSchemeController@seeTheFlow');
});
$router->group(['prefix' => 'seqschemegroup', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'SeqSchemeGroupController@index');
});
$router->group(['prefix' => 'users', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'UsersController@index');
$router->patch('/change_password', 'UsersController@changePassword');
});
$router->group(['prefix' => 'transactions', 'middleware' => 'eauth'], function () use ($router) {
$router->get('/', 'TransactionsController@index');
$router->put('/create', 'TransactionsController@createTransaction');
$router->post('/save', 'TransactionsController@store');
$router->get('/current_status/{id_asset}', 'TransactionsController@currentStatus');
$router->post('/generate_result', 'TransactionsController@generateResult');
$router->get('/list_transaction', 'TransactionsController@listTransactionAsset');
});
$router->group(['prefix' => 'assets', 'middleware' => 'eauth'], function () use ($router) {
$router->post('/', 'AssetsController@index');
$router->post('/save', 'AssetsController@store');
$router->get('/detail', 'AssetsController@detail');
$router->delete('/delete/{asset_id}', 'AssetsController@delete');
$router->delete('/delete_all', 'AssetsController@deleteAll');
$router->get('/test_detail[/{asset_id}]', 'AssetsController@testDetail');
});
$router->group(['prefix' => 'stock_movement', 'middleware' => 'eauth'], function () use ($router) {
$router->post('/', 'StockMovementController@index');
$router->put('/save', 'StockMovementController@store');
$router->delete('/delete', 'StockMovementController@delete');
$router->delete('/delete_asset', 'StockMovementController@deleteAsset');
$router->put('/save_asset', 'StockMovementController@storeAssets');
$router->delete('/delete_all', 'StockMovementController@deleteAll');
$router->get('/list_stock_asset', 'StockMovementController@listStockAsset');
$router->get('/detail', 'StockMovementController@show');
$router->patch('/accept', 'StockMovementController@accept');
$router->patch('/approve_gr', 'StockMovementController@approveGR');
$router->get('/get_ready_assets', 'StockMovementController@getReadyAssets');
$router->get('/list_destination_station', 'StockMovementController@listDestinationStation');
$router->get('/generate_document_number', 'StockMovementController@generateDocumentNumber');
$router->patch('/accept_scan', 'StockMovementController@acceptScan');
$router->post('/list_scan', 'StockMovementController@listScanned');
});
$router->get('watch/{nama}/', 'WatchController@default');
|
6f74eb12eeaa4593dadaf4732f480aeedf84319a
|
[
"PHP",
"Shell"
] | 34 |
PHP
|
warkop/pertagas-qrtg-api
|
b6e87e9e7e90d1987fe3f92e13ef2d45c1894406
|
1e567e3ccdbf212fac630a633284af63fe766c99
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationAbstractClass
{
public interface IPrint
{
// All methods must be implemented at inherited class
void displayAll();
void displayInt(int i);
void displayString(String s);
void displayObject(Object o);
}
public interface IFax
{
void dial( Int64 number);
}
abstract class Shape
{
// only abstract methods must provide implementation in the inherited class
abstract public void area();
abstract public void display();
public virtual void print() // optional to override
{
Console.WriteLine("Base class Print ");
}
}
class Square : Shape
{
public int Length
{
get;
set;
}
public int Area
{
get;
set;
}
public override void area()
{
Area = Length * Length;
}
public override void display()
{
Console.WriteLine("The area of the sqaure is " + Area);
}
public override void print()
{
Console.WriteLine("Child class print");
}
}
class Rect : Shape
{
public int Length
{
get;
set;
}
public int Area
{
get;
set;
}
public int Breadth
{
get;
set;
}
public override void area()
{
Area = Length * Breadth;
}
public override void display()
{
Console.WriteLine("The area of the Rectangle is " + Area);
}
}
class Document:IPrint,IFax
{
void IPrint.displayAll()
{
}
public void displayInt(int i)
{
Console.WriteLine("Displying Integer :" + i);
// throw new NotImplementedException();
}
public void displayString(string s)
{
Console.WriteLine("Displying string :" + s);
//throw new NotImplementedException();
}
public void displayObject(object o)
{
throw new NotImplementedException();
}
public void dial(long number)
{
Console.WriteLine("Dialing " + number);
// throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
// Shape s = new Shape();//object cannot be instantiate for an abstract class
Square g = new Square();
g.Length = 10;
Rect r = new Rect();
r.Length = 4;
r.Breadth = 5;
Shape s =g;
s.area();
s.display();
s = r;
s.area();
s.display();
Document d = new Document();
d.displayInt(10);
d.displayString("Hello");
d.dial(9980526571)
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationGenrics
{
class Program
{
static void Main(string[] args)
{
Student<int> s1 = new Student<int>(1001);
Student<string> s2 = new Student<string>("RAMU");
Student<bool> s3 = new Student<bool>(true);
Console.ReadLine();
}
}
//Genric datatype to replace with any type during runtime.
class Student<T>
{
public Student(T data)
{
Console.WriteLine(data);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationAnonymousMethods
{
delegate void ArthemeticOperation(int a, int b);
class Program
{
static void Main(string[] args)
{
//Anonymous methods
ArthemeticOperation n1 = delegate (int a, int b)
{
Console.WriteLine(a + b);
};
ArthemeticOperation n2 = delegate (int a, int b)
{
Console.WriteLine(a * b);
};
ArthemeticOperation n = n1 + n2;
n(10, 20);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationExceptionhandling
{
class Example
{
public int ID
{
get;
set;
}
public static int number;
public void display()
{
Console.WriteLine("Display Function and Number = " + number);
}
}
class Program
{
static void Main(string[] args)
{
try
{
var i = 10;
Console.WriteLine("Type of var is casted to " + i.GetType());
// i = "hello"; //cannot cast variable type multiple times
//int k = null; // null values cannot be assigned for primitive/value type datatypes;
int? j=null; // along with integers a null value can be assigned;
Console.WriteLine("Try Block");
Example e = new Example(); //when object is created static members are initialled with 0
e.ID = 10; // normal variables, methods , properties are accesible via objects.
//e.number=20; // cannot use via object. because for all objects static member has only one reference.
e.display(); //number will be 0
Example.number = 20; // have to access using Class Name
e.display();
}
catch
{
//will be execute if try block is not completly executed
Console.WriteLine("Catch Block");
}
finally
{
Console.WriteLine("Finally Block will always get executed");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationAcessSpecifiers
{
class Demo
{
private int a; // accessed by only class members
protected int b; //accessed by only class members and inherited class members
public int c; // accessed by any members using object of the class
}
class Temp:Demo
{
String s;
StringBuilder sb = new StringBuilder("Hello America!!");
public void displayString()
{
sb.Append("Wonderfull"); // to add text to string builder variable
s = s + "Woderfull"; // to add text to string variable
}
public void display()
{
//Console.WriteLine(a);//illegal not allowed as it is private;
Console.WriteLine(b=20); // b can be accessed as it is inherited class
Console.WriteLine(c=100); //c can be accessed as it is public
}
}
class Program
{
static void Main(string[] args)
{
Demo d = new Demo();
// d.a = 10; //illegal not allowed as it is private member
//d.b = 20; //illegal not allowed as it is protected member
d.c = 30; // can be accessd as it is public member;
Temp t = new Temp();
t.display();
t.displayString();
t.displayString();
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationExample1
{
class Player
{
//Data Types
private string name;
private int age;
private char gender;
private string country;
public Player()
{
name = "";
age = 0;
gender = '\0';
country = "";
}
public Player(string name,int age,char gender,string country)
{
this.name = name;
this.age = age;
this.gender = gender;
this.country = country;
}
public void setName(string name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public void setGender(char gender)
{
this.gender = gender;
}
public void setCountry(string country)
{
this.country = country;
}
public string getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public string getCountry()
{
return this.country;
}
public char getGender()
{
return this.gender;
}
}
class CricketPlayer: Player
{
private int runs;
private int wickets;
private int noOfMatches;
public CricketPlayer()
{
runs = 0;
wickets = 0;
noOfMatches = 0;
}
public CricketPlayer(int runs,int wickets,int noOfMatches)
{
this.runs = runs;
this.wickets = wickets;
this.noOfMatches = noOfMatches;
}
public int getRuns()
{
return this.runs;
}
public int getWickets()
{
return this.wickets;
}
public int getMatches()
{
return this.noOfMatches;
}
public void setRuns(int runs)
{
this.runs = runs;
}
public void setWickets(int wickets)
{
this.wickets = wickets;
}
public void setMatches(int matches)
{
this.noOfMatches = matches;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the number of players in a team");
int n = Convert.ToInt16(Console.ReadLine());
CricketPlayer[] sachin = new CricketPlayer[n];// Array of Objects
for (int i = 0; i < n; i++)
sachin[i] = new CricketPlayer();
while (true)
{
Console.WriteLine("Enter the Choice\n 1. Enter the Details of selected Team Players \n 2. Display the Names of selected Team\n 3. Display the Details of a player\n 4.Exit");
int choice = Convert.ToInt16(Console.ReadLine());
switch (choice)
{
case 1:
int k;
for (k = 0; k < n; k++)
{
Console.WriteLine("Enter the name");
sachin[k].setName(Console.ReadLine());
Console.WriteLine("Enter the Age");
sachin[k].setAge(Convert.ToInt16(Console.ReadLine()));
Console.WriteLine("Enter the Gender");
sachin[k].setGender(Convert.ToChar(Console.ReadLine()));
Console.WriteLine("Enter the Runs");
sachin[k].setRuns(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine("Enter the Wickets");
sachin[k].setWickets(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine("Enter the Number of Matches Played");
sachin[k].setMatches(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine("----------------------------------------------------");
}
break;
case 2:
int i;
for (i = 0; i < n; i++)
{
Console.WriteLine("----------------------------------------------------");
Console.WriteLine(i+" Name: " + sachin[i].getName());
Console.WriteLine("----------------------------------------------------");
}
break;
case 3:
Console.WriteLine("----------------------------------------------------");
Console.WriteLine("enter the Id of the Player");
i = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Name: " + sachin[i].getName());
Console.WriteLine("Age: " + sachin[i].getAge());
Console.WriteLine("Gender: " + sachin[i].getGender());
Console.WriteLine("Runs: " + sachin[i].getRuns());
Console.WriteLine("Wickets: " + sachin[i].getWickets());
Console.WriteLine("Matches Played: " + sachin[i].getMatches());
Console.WriteLine("----------------------------------------------------");
break;
case 4: return ;
default:
Console.WriteLine("Wrong Choice.select the right choice");
break;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplicationHashTable
{
class Program
{
static void Main(string[] args)
{
Hashtable h = new Hashtable();
h.Add("PAUL", 1);
h.Add("Ramu", 2);
h.Add("Ramesh", 3);
h.Add("Rahul", 4);
foreach(object i in h.Values)
{
int x=i.GetHashCode();
Console.WriteLine(x);
}
foreach (object i in h.Keys)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
<file_sep># Assignments
examples demonstrating C# & ASP.NET Concepts
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplicationOopsExample
{
class Student
{
private int id;
private string name;
public Student()
{
id = 0;
name = "";
}
public Student(int i,string s)
{
id = i;
name = s;
}
virtual public void display()
{
Console.WriteLine("ID = " + id + "\nName : " + name);
}
}
class GradStudent:Student
{
private string major;
private int gradyear;
public GradStudent(int i, string s, string m, int g):base(i,s)
//passing values to base class constructor
{
major = m;
gradyear = g;
}
public GradStudent()
{
major = "";
gradyear = 0;
}
//override display method
override public void display()
{
base.display();
Console.WriteLine("Major= " + major + "\nGrad Year= " + gradyear);
}
}
class UnderGradStudent : Student
{
private string minor;
private float GPA;
//constructor overloading and passing parameter to base class constructor
public UnderGradStudent(int i,string s,string m,float g):base(i,s)
{
minor = m;
GPA = g;
}
public UnderGradStudent()
{
minor = "";
GPA = 0;
}
//overide function
override public void display()
{
base.display();
Console.WriteLine("Minor= " + minor + "\nGPA= " + GPA);
}
}
class OverloadExample
{
public int add(int a, int b)
{
return a + b;
}
public float add(float a, float b)
{
return a + b;
}
public string add(string a, string b)
{
return a + b;
}
public double add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
//array of student objects
Student[] s = new Student[2];
s[0] = new GradStudent(123,"Sachin","Computer Science",2016);
s[1] = new UnderGradStudent(234, "Rahul", "Information",4);
foreach(Student obj in s)
{
obj.display();
Console.WriteLine("");
}
//////////////////////////////////////////////////////////////////////////////////////////
Console.WriteLine("\nArray List example");
// Array list
ArrayList i = new ArrayList();
//can hold hetrogeneous data(any tyoe of data in an array)
i.Add(10); //integer
i.Add("Ramu");//string
i.Add("IMCS");//string
i.Add('M');//character
i.Add("56.4");//float
for (int j = 0; j<i.Count; j++)
{
Console.WriteLine(i[j]);
}
/////////////////////////////////////////////////////////////////////////////////////////
// Function over loading or static polymorphism
Console.WriteLine("\noverloading example");
OverloadExample obj1=new OverloadExample();
int res=obj1.add(10, 20);
Console.WriteLine(res);
string res1 = obj1.add("Hello"," world ");
Console.WriteLine(res1);
double res2 = obj1.add(10.34, 20.66);
Console.WriteLine(res2);
////////////////////////////////////////////////////////////////////////////////////
Console.WriteLine("\nBoxing and UNboxing example");
int value= 1;
object reference = value; // boxing : Converting value type to reference type(object)
Console.WriteLine(reference);
int value1 = (int)reference; // unboxing : converting reference type to value type
Console.WriteLine(value1);
Console.ReadLine();
}
}
}
|
ef9f4692f3bd45cb4b06d25588e6b8368b7394bc
|
[
"Markdown",
"C#"
] | 9 |
C#
|
theertharaj/Assignments
|
05f0286809333b27619d5d07cbd2dcde42366261
|
ae01f4f48829b6f4ee8c16474c686d1507603819
|
refs/heads/master
|
<file_sep>#git stuff
git init
git add .
#get the comment from the user
echo comment for commit:
read comment
git commit -m $comment
#get projectName and add origin
echo project name:
read projectName
git remote add origin https://www.github.com/farrellfoobar/$projectName
#more git stuff
git remote -v
git push origin master<file_sep>git add .
git commit
git push origin master
|
a7a140f1d48c4a281700e8a2ddef4b9f95bb856d
|
[
"Shell"
] | 2 |
Shell
|
farrellfoobar/basicTemplateWithGit
|
ddb06a6ec14d8c69e31b3cfd525643401c5e314e
|
c9ab389d20c4879daa2be28b290945a914e70e7c
|
refs/heads/master
|
<repo_name>Prajakta15Patil/COVID-analysis<file_sep>/README.md
# COVID-analysis
NLP based text summarization and clustering of COVID-related research.
### Motivation
The world is grappling with one of the deadliest pandemics in history. Each day I receive news about a new COVID-19 research and its findings. I was interested in keeping myself informed with the latest research on coronaviruses and I decided to analyze research papers to understand the different topics being discussed. I was also interested in summarizing these papers to quickly understand the content of the papers without having to read it fully.
### Dataset
[CORD-19: The Covid-19 Open Research Dataset](https://allenai.org/data/cord-19)
CORD-19 is a free resource of tens of thousands of scholarly articles about COVID-19, SARS-CoV-2, and related coronaviruses for use by the global research community.
The data was pulled in August 2020 and has ~19,000 research papers.
### Analysis
#### Clustering and Topic Modeling
Identify the optimal number of clusters for this dataset using k-means clustering. Then perform topic modeling for the number of clusters from clustering analysis.
#### Abstractive summarization
Build abstractive summaries on papers using [BertAbs](https://github.com/nlpyang/PreSumm) and BERT-Base uncased model.
### Code
1. extract_data - Preprocess raw papers and store it in json format for ease of accessibility.
2. covid_analysis - exploratory analysis on extractive summarization and abstracts of papers.
3. covid_clustering - Analyze papers using K-means clustering nd topic modeling.
4. covid_bert - Generate abstractive summarization on papers using BERTAbs and BERT-Base uncased model.
<file_sep>/code/extract_data.py
import json
import glob
def get_paper(paths):
"""
Extract the contents from json files.
Parameters:
paths (list): Paths for all json files
Returns:
data (list): Contents from all json files
"""
data = []
for path in paths:
with open(path) as json_file:
data.append(json.load(json_file))
return data
def merge_abstracts(paper):
"""
Concatenate multiple paragraphs of an abstract into a single text seperated by space.
Parameters:
paper (dictionary): Contents of a json file
Returns:
merge_abstract (string): Single abstract
"""
merge_abstract = ''
if 'abstract' in paper:
for abstract in paper['abstract']:
merge_abstract = ' '.join([merge_abstract, abstract['text']])
return merge_abstract
def merge_sections(paper):
"""
Extract multiple sections within a body text and store it in a dictionary. Merge sections with
multiple paragraphs.
Parameters:
paper (dictionary): Contents of a json file
Returns:
sections (dictionary): Single bodytext
"""
sections = {}
for bodytext in paper['body_text']:
section = bodytext['section']
text = bodytext['text']
if section in sections:
sections[section].append(text)
else:
sections[section] = [text]
for keys, value in sections.items():
sections[keys] = ' '.join(value)
return sections
def merge_bodytexts(paper):
"""
Concatenate multiple paragraphs of body text into a single text seperated by space.
Parameters:
paper (dictionary): Contents of a json file
Returns:
merge_text (string): Single bodytext
"""
merge_text = ''
for text in paper['body_text']:
merge_text = ' '.join([merge_text, text['text']])
return merge_text
def process_paper(paper):
"""
Load contents from a json file into a dictionary
Parameters:
paper (dictionary): Contents of a json file
Returns:
single_paper (dictionary): contents of a paper
"""
single_paper = {}
single_paper['paper_id'] = paper['paper_id']
single_paper['title'] = paper['metadata']['title']
single_paper['abstract'] = merge_abstracts(paper)
single_paper['section_bodytext'] = merge_sections(paper)
single_paper['bodytext'] = merge_bodytexts(paper)
return single_paper
def exportdata(data, path):
"""
Store the pre-processed data as json file
Parameters:
data (list): Contents of json files
path (list): Paths of json files
Returns:
single_paper (dictionary): contents of a paper
"""
with open(path+data['paper_id']+'.json', 'w') as data_file:
json.dump(data, data_file)
if __name__ == '__main__':
directory = "/home/prajakta/Documents/SharpestMinds/COVID-analysis"
data_loc = '/'.join([directory, "papers/*/*.json"])
final_data_loc = '/'.join([directory, "data/"])
files = glob.glob(data_loc)
raw_data = get_paper(files)
for paper in raw_data:
exportdata(process_paper(paper), final_data_loc)
|
990ce4f2a98c4d49b1526d6f0bb06a3d0e6b978b
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
Prajakta15Patil/COVID-analysis
|
f2d869f0934c4a7cc52fc9ded8bee9187ddcdc84
|
0859b7aa107e46788410c78ac72660bbd7f0d688
|
refs/heads/main
|
<file_sep>#!/bin/env python
""" Console to "drive" the turtle
NRC, 12/10/2009
"""
from turtle import *
command = ""
command_hist = []
while command != 'exit':
command = raw_input(">>> ").strip()
try:
eval(command)
command_hist.append(command)
except BaseException, e:
print e
print command_hist
<file_sep>#!/usr/bin/env python
""" Toolbar to "drive" the Python turtle
Copyright 2009, <NAME>, <EMAIL>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from turtle import *
from Tkinter import *
from idlelib.ToolTip import ToolTip
from idlelib.EditorWindow import EditorWindow
import tkColorChooser
import tkMessageBox
import traceback
import sys
import os
from os.path import join, expanduser
import code
# force UTF-8 encoding...
reload(sys) # restore module sys from disk
sys.setdefaultencoding('utf-8') # or whatever codec you need
del sys.setdefaultencoding # ensure against later accidents
command_dict = {'forward':'forward(<distance?>)',
'back': 'back(<distance?>)',
'left': 'left(<degrees?>)',
'right': 'right(<degrees?>)',
'setheading':'setheading(<degrees?>)',
'towards':'towards(<location(x,y)?>)',
'goto': 'goto(<location(x,y)?>)',
'circle':'circle(<radius?>)\n',
'dot':'dot(<radius?>)\n',
'speed':'speed(<"slow"-"normal"-"fast"-"fastest"?>)\n',
'pensize':'pensize(<width?>)\n',
'penup':'penup()\n',
'pendown':'pendown()\n',
'pencolor':'pencolor(<color?>)\n',
'fillcolor':'fillcolor(<color?>)\n',
'begin_fill':'begin_fill()\n',
'end_fill':'end_fill()\n',
'turtlesize':'turtlesize(<how_big?>)\n',
'hideturtle':'hideturtle()\n',
'showturtle':'showturtle()\n',
'if...':'if <what?>:\n# commands go here\n',
'repeat...':'for i in range(<how many times?>):\n# commands go here\n',
'while...':'while <what?>:\n# commands go here\n',
'repeat forever':'while True:\n# commands go here\n',
'Full Screen':'setup(width=1.0, height=1.0)\n',
'exitonclick':'exitonclick()\n',
'':''
}
value_list = ["'white'", "'gray'", "'yellow'", "'orange'", "'red'", "'purple'",
"'blue'", "'green'", "'brown'", "'black'", "random_color()", "HexColorPicker",
'', 'random_location()','random_direction()',
'random_size(<max_size?>)']
move_list = ['forward', 'back', 'left', 'right', '', 'circle', 'dot', '',
'goto', 'setheading', 'towards']
pen_list = ['pencolor', 'pensize', 'penup', 'pendown', '', 'fillcolor',
'begin_fill', 'end_fill', '', 'showturtle', 'hideturtle',
'turtlesize', 'speed']
extra_list = ['if...', 'repeat...', 'repeat forever', 'while...',
'', 'Full Screen', 'exitonclick']
turtle_speed_list = ['slowest','slow','normal','fast','fastest','*instant*']
local_dict = locals()
class newInterp(code.InteractiveInterpreter):
# def __init__(self, locals=None, window=None):
# code.InteractiveInterpreter.__init__(self, locals)
# self.window = window
def showtraceback(self):
"""Ripped out of code.py, and tweaked slightly"""
try:
etype, value, tb = sys.exc_info()
sys.last_type = etype
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
elist = traceback.format_list(tblist)
if elist:
elist.insert(0, "Traceback (most recent call last):\n")
elist[len(elist):] = traceback.format_exception_only(etype, value)
finally:
tblist = tb = None
tkMessageBox.showwarning("Code Error", "".join(elist))
class TurtleConGUI(Frame):
def __init__(self, master=None):
if not master:
master = Tk()
self.master = master
self.master.protocol("WM_DELETE_WINDOW", self.at_exit)
self.indent_level = 0
Frame.__init__(self, master)
self.master.title("TurtleLab")
self.grid()
self.filename = ""
if sys.platform == 'win32':
try:
# Find the "My Documents" folder.
shell_folders_key = '"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"'
shell_folders = os.popen('reg QUERY %s' % shell_folders_key).readlines()
my_docs = [i for i in shell_folders if "Personal" in i][0]
my_docs = my_docs.split("REG_SZ")[1].strip()
self.filename = my_docs
except:
# If any of the above fails, assume "My Documents" is in the default location.
self.filename = join(os.environ.get('HOMEDRIVE', ""),
os.environ.get('HOMEPATH', ""),
"My Documents")
else:
self.filename = os.environ.get('HOME', "")
self.go_filename = join(self.filename, "turtlefile-go.py")
self.filename = join(self.filename, "turtlefile.py")
self.edit_window = EditorWindow(root=master, filename=self.filename)
self.max_width = master.winfo_screenwidth()
self.max_height = master.winfo_screenheight()
# Ubuntu reports these figures in such a way that all the windows'
# area is visible. Windows XP reports them in such a way that the
# Windows are behind the taskbar. Stupid solution:
if sys.platform == 'win32':
self.max_height = self.max_height - 70
self.tools_x = int(self.max_width * .6)+6
self.tools_y = 0
self.create_code_box()
self.code_frame.update()
self.tools_w = self.master.winfo_width()
self.tools_h = self.master.winfo_height()
self.master.geometry("%sx%s+%s+%s" % (self.tools_w, self.tools_h,
self.tools_x, self.tools_y))
self.edit_x = self.tools_x + self.tools_w+ 6
self.edit_y = 0
self.edit_w = self.max_width - (self.tools_x + self.tools_w+16)
self.edit_h = int(self.max_height)
self.edit_window.top.geometry("%sx%s+%s+%s" % (self.edit_w, self.edit_h,
self.edit_x, self.edit_y))
self.edit_window.text_frame.update()
#self.errors_x = self.tools_x + self.tools_w+ 6
#self.errors_y = self.edit_window.top.winfo_height()+80
#self.create_error_box()
#self.error_frame.update()
#self.errors_w = self.edit_window.top.winfo_width()
#self.errors_h = self.toplevel.winfo_height()
#self.toplevel.geometry("%sx%s+%s+%s" % (self.errors_w, self.errors_h,
# self.errors_x, self.errors_y))
#self.error_box.update()
self.interp = newInterp({'status_dict':{'x':self.status_x,
'y':self.status_y,
'heading':self.status_h,
'penrgb':self.status_penrgb,
'fillrgb':self.status_fillrgb}})#,
#window=self.error_box)
self.load_gridline_functs()
self.setup_graphics_window()
self.load_random_functs()
self.edit_window.text.focus_set()
def setup_graphics_window(self):
self.run_code(
"""from turtle import *
from turtle import _CFG
_CFG['using_IDLE'] = True
_CFG['width'] = .6
_CFG['height'] = 1.0
_CFG['topbottom'] = 0
_CFG['leftright'] = True
_CFG['shape'] = 'turtle'
_CFG['pencolor'] = 'red'
_CFG['fillcolor'] = 'red'
_CFG['pensize'] = 5
_CFG['turtlesize'] = 2
_CFG['resizemode'] = 'user'
""")
self.run_code("""
clearscreen()
""")
if not self.hide_grid_check.get():
self.show_grid()
self.run_code("""resizemode('user')
## print _CFG.items()
pensize(_CFG['pensize'])
shape(_CFG['shape'])
color(_CFG['pencolor'])
turtlesize(_CFG['turtlesize'])
""")
self.run_code("speed('%s')\n" % self.turtle_speed.get())
def create_code_box(self):
# MASTER FRAME
self.code_frame = Frame(self.master)
self.code_frame.grid(row=0)
# - COMMANDS FRAME
self.command_v = StringVar()
Label(self.code_frame, text="Insert Code").grid(row=0, sticky=E+W+S,pady=5)
self.tools_frame = Frame(self.code_frame, borderwidth=2, relief='sunken')
self.tools_frame.grid(row=1, sticky=E+W, ipadx=5, ipady=5)
self.tools_frame.columnconfigure(0,minsize=150,weight=1) # <----- This determines the minimum size of the window
Label(self.tools_frame, text="Commands").grid(row=0, sticky=E+W, pady=5)
Label(self.tools_frame, text="Move Control", anchor=W).grid(row=1, sticky=W)
OptionMenu(self.tools_frame, self.command_v, command=self.set_command, *move_list).grid(row=1, sticky=E)
Label(self.tools_frame, text="Pen Control", anchor=W).grid(row=2, sticky=W)
OptionMenu(self.tools_frame, self.command_v, command=self.set_command, *pen_list).grid(row=2, sticky=E)
Label(self.tools_frame, text="Extra", anchor=W).grid(row=3, sticky=W)
OptionMenu(self.tools_frame, self.command_v, command=self.set_command, *extra_list).grid(row=3, sticky=E)
Label(self.tools_frame, text="Values").grid(row=4, sticky=E+W, pady=5)
Label(self.tools_frame, text="Colors, etc.", anchor=W).grid(row=5, sticky=W)
OptionMenu(self.tools_frame, self.command_v, command=self.insert_value, *value_list ).grid(row=5, sticky=E)
#Label(self.tools_frame, text="Commands", anchor=W).grid(row=4, sticky=W)
#OptionMenu(self.tools_frame, self.command_v, command=self.set_command, *command_list).grid(row=4, sticky=E)
# - GRAPHICS WINDOW FRAME
Label(self.code_frame, text="Graphics Window").grid(row=2, sticky=E+W, pady=5)
self.graphics_window_frame = Frame(self.code_frame, borderwidth=2, relief='sunken')
self.graphics_window_frame.grid(row=3,sticky=E+W)
self.graphics_window_frame.columnconfigure(0,weight=1)
# - - BUTTONS IN GRAPHICS WINDOW FRAME
#self.hide_grid_btn = Button(self.graphics_window_frame, text="Hide Grid", command=self.hide_grid)
#self.hide_grid_btn.grid(row=0, sticky=N+S+E+W, pady=5, padx=5)
#Button(self.graphics_window_frame, text="Reset Turtle & Screen", command=self.reset_screen, background="orange3", activebackground="orange").grid(row=1, sticky=N+S+E+W, padx=5)
# - Speed List
self.turtle_speed = StringVar()
Label(self.graphics_window_frame, text="Speed:", anchor=W).grid(row=0, stick=W)
OptionMenu(self.graphics_window_frame, self.turtle_speed, *turtle_speed_list).grid(row=0, sticky=N+S+E)
self.turtle_speed.set("normal")
# - Grid checkbox
self.hide_grid_check = IntVar()
Checkbutton(self.graphics_window_frame, text="Hide Grid", variable=self.hide_grid_check).grid(row=1, sticky=N+S+E+W)
# - Buttons
Button(self.graphics_window_frame, text="Go!", command=self.go, background="green3", activebackground="green").grid(row=2, sticky=N+S+E+W)
Button(self.graphics_window_frame, text="Close Screen", command=self.close_screen, background="orange3", activebackground="orange").grid(row=3, sticky=N+S+E+W)
# - STATUS FRAME
Label(self.code_frame, text="Current Turtle Status").grid(row=4, sticky=E+W+S, pady=5)
self.status_frame = Frame(self.code_frame, borderwidth=2, relief='sunken', background="white")
self.status_frame.grid(row=5, sticky=E+W)
self.status_frame.columnconfigure(0,weight=1)
# - - TEXT IN STATUS FRAME
self.status_x = StringVar(value="0")
self.status_y = StringVar(value="0")
self.status_h = StringVar(value="0")
self.status_penrgb = StringVar(value="0, 0, 0")
self.status_fillrgb = StringVar(value="0, 0, 0")
Label(self.status_frame, text="x:", background="white").grid(row=1, sticky=W)
Label(self.status_frame, textvar=self.status_x, background="white").grid(row=1, sticky=E)
Label(self.status_frame, text="y:", background="white").grid(row=2, sticky=W)
Label(self.status_frame, textvar=self.status_y, background="white").grid(row=2, sticky=E)
Label(self.status_frame, text="heading:", background="white").grid(row=3, sticky=W)
Label(self.status_frame, textvar=self.status_h, background="white").grid(row=3, sticky=E)
Label(self.status_frame, text="pencolor:", background="white").grid(row=4, sticky=W)
Label(self.status_frame, textvar=self.status_penrgb, background="white").grid(row=4, sticky=E)
Label(self.status_frame, text="fillcolor:", background="white").grid(row=5, sticky=W)
Label(self.status_frame, textvar=self.status_fillrgb, background="white").grid(row=5, sticky=E)
# - CODE WINDOW FRAME
#Label(self.code_frame, text="Code Window").grid(row=6, sticky=E+W+S, pady=5)
#self.code_window_frame = Frame(self.code_frame, borderwidth=2, relief='sunken')
#self.code_window_frame.grid(row=7, sticky=N+S+E+W)
#self.code_window_frame.columnconfigure(0,weight=1)
# - - BUTTONS IN CODE WINDOW FRAME
#Button(self.code_window_frame, text="Go!", command=self.go, background="green3", activebackground="green").grid(row=0, sticky=N+S+E+W)
#Button(self.code_window_frame, text="Clear code", command=self.code_clear, background="orange3", activebackground="orange").grid(row=1, sticky=N+S+E+W)
# - BACK IN MASTER FRAME
Button(self.code_frame, text="X - Quit - X", command=self.at_exit, width=10, background="red3",activebackground="red").grid(row=6, sticky=N+S+E+W,padx=5, pady=5)
def create_error_box(self):
self.toplevel = Toplevel()
self.error_frame = Frame(self.toplevel)
self.toplevel.title("Errors")
self.error_frame.grid()
self.error_box = Text(self.error_frame, height=8, width=60)
self.error_box.grid(row=0, column=0, sticky=E+W)
def go(self, event=None):
""" compile code to code object and run """
code_text = self.edit_window.text.get(0.0,END)
#self.error_clear()
open(self.go_filename, "w").write(code_text)
self.setup_graphics_window()
if self.turtle_speed.get() == "*instant*":
self.run_code("tracer(0)\n")
self.run_code(code_text)
if self.turtle_speed.get() == "*instant*":
self.run_code("update()\n")
# need to grab output and display
def run_code(self, code_text):
result = self.interp.runcode(code_text)
if result:
self.interp.showsyntaxerror()
# def reset_screen(self):
# self.run_code("""
#reset()
#hide_grid()
#show_grid()
#resizemode('user')
#pensize(5)
#shape('turtle')
#color('red')
#turtlesize(2)
#tracer(1)
#delay(10)
#""")
def close_screen(self):
self.run_code('bye()')
# def error_clear(self):
# """ clear error box """
# self.error_box.delete(0.0, END)
def code_clear(self):
""" clear code box """
self.edit_window.text.delete(0.0, END)
def insert_value(self, value=None):
self.command_v.set("")
if value == "HexColorPicker":
value = "'" + tkColorChooser.askcolor("black")[1] + "'"
value_str = """%s""" % (value)
self.edit_window.text.insert(INSERT, value_str)
def set_command(self, key=None):
command_strings = command_dict[key].split("\n")
for command_str in command_strings:
startpos = len(command_str) - command_str.rfind("<")
endpos = len(command_str) - (command_str.rfind(">") + 1)
self.edit_window.text.insert(INSERT, command_str)
if startpos <= len(command_str) and endpos < startpos:
self.edit_window.text.tag_add("replace", "%s-%sc" %
(INSERT, startpos),
"%s-%sc" % (INSERT, endpos))
self.edit_window.text.tag_config("replace",foreground="red",
background="lightpink",
underline=1)
if command_str.strip():
self.edit_window.text.event_generate("<<newline-and-indent>>")
self.edit_window.text.focus_set()
self.command_v.set("")
def at_exit(self):
self.run_code("bye()")
try:
self.edit_window.close()
except:
self.edit_window.text_frame.destroy()
self.destroy()
def hide_grid(self):
self.run_code("""hide_grid()""")
#self.hide_grid_btn.config(command=self.show_grid, text="Re-draw Grid")
def show_grid(self):
self.run_code("""show_grid()""")
#self.hide_grid_btn.config(command=self.hide_grid, text="Hide Grid")
def load_gridline_functs(self):
self.run_code("""
grids = []
def show_grid():
global grids
cv = getcanvas()
line = cv.create_line(0, window_height()/2, 0, -window_height()/2, width=2,
tags="gridline", fill="gray75")
grids.append(line)
line = cv.create_line(window_width()/2, 0, -window_width()/2, 0,
width=2, fill="gray75", tags="gridline")
grids.append(line)
for x in range(100, window_width()/2, 100):
line = cv.create_line(x, window_height()/2, x, -window_height()/2,
width=1, fill="gray75",tags="gridline")
grids.append(line)
text = cv.create_text(x+20, 10, fill="gray75", text=str(x),
tags="gridline")
grids.append(text)
for x in range(-100, -window_width()/2, -100):
line = cv.create_line(x, window_height()/2, x, -window_height()/2,
width=1, fill="gray75",tags="gridline")
grids.append(line)
text = cv.create_text(x+20, 10, fill="gray75", text=str(x),
tags="gridline")
grids.append(text)
for y in range(100, window_height()/2, 100):
line = cv.create_line(window_width()/2, y, -window_width()/2, y,
width=1, fill="gray75",tags="gridline")
grids.append(line)
text = cv.create_text(20, y+10, fill="gray75", text=str(-y),
tags="gridline")
grids.append(text)
for y in range(-100, -window_height()/2, -100):
line = cv.create_line(window_width()/2, y, -window_width()/2, y,
width=1, fill="gray75",tags="gridline")
grids.append(line)
text = cv.create_text(20, y+10, fill="gray75", text=str(-y),
tags="gridline")
grids.append(text)
def hide_grid():
cv = getcanvas()
for item in grids:
cv.delete(item)
cv.update()""")
def load_random_functs(self):
self.run_code('''
from random import randint, random
def random_size(max_size=100):
"""returns a random size between 1 and size)"""
return randint(1, max_size)
def random_location():
""" returns a random location on screen"""
return randint(-window_width()/2, window_width()/2), randint(-window_height()/2, window_height()/2)
def random_direction():
return randint(0, 359)
def random_color():
""" returns a random color """
if colormode() == 255:
return randint(0,255), randint(0,255), randint(0,255)
else:
return random(), random(), random()
def status():
t = getturtle()
status_dict['x'].set("%4.0f" % t.position()[0])
status_dict['y'].set("%4.0f" % t.position()[1])
status_dict['heading'].set("%3d" % (t.heading()))
for item in ('pen','fill'):
colorstr = t._colorstr(t.pen()[item+'color'])
if not colorstr.startswith("#"):
try:
rgblist = [c/256 for c in t.screen.cv.winfo_rgb(colorstr)]
except TK.TclError:
raise Exception("bad colorstring: %s" % colorstr)
elif len(colorstr) == 7:
rgblist = [int(colorstr[i:i+2], 16) for i in (1, 3, 5)]
elif len(colorstr) == 4:
rgblist = [16*int(colorstr[h], 16) for h in colorstr[1:]]
else:
raise Exception("bad colorstring: %s" % colorstr)
colorstatus = "%3.0f,%3.0f,%3.0f" % tuple(rgblist)
status_dict[item+'rgb'].set(colorstatus)
def new_update(self):
if Turtle._pen is not None:
status()
self.cv.update()
old_update = TurtleScreen._update
TurtleScreen._update = new_update
maze_data = (( 110.85445804 , 44.9444101085 ),( 14.0362434679 , 37.1079506306 ),
( 316.636577042 , 49.5176736125 ),( 266.268603001 , 46.0977222864 ),
( 197.744671625 , 52.4976189937 ),( 141.666659891 , 54.8178802946 ),
( 90.0 , 31.0 ),( 156.801409486 , 22.8473193176 ),( 270.0 , 43.0 ),
( 305.942111871 , 49.4064773081 ),( 348.340707346 , 64.3272881443 ),
( 278.746162262 , 26.305892876 ),( 168.550662012 , 80.6039701255 ),
( 118.810793743 , 45.6508488421 ),( 104.215853474 , 77.3692445355 ),
( 38.3674853848 , 61.2209114601 ),( 354.289406863 , 60.2992537267 ),
( 328.815025341 , 44.418464629 ),( 289.230672376 , 45.5411901469 ),
( 14.6208739886 , 23.769728648 ),( 109.983106522 , 46.8187996429 ),
( 12.8042660653 , 22.5610283454 ),( 277.431407971 , 69.5844810285 ),
( 241.189206257 , 45.6508488421 ),( 343.300755766 , 31.3209195267 ),
( 73.2442510708 , 97.1236325515 ),( 115.866356794 , 73.3484832836 ),
( 162.570137182 , 90.1387818866 ),( 182.290610043 , 75.0599760192 ),
( 285.945395901 , 21.8403296678 ),( 353.088772881 , 66.4830805544 ),
( 348.503436982 , 60.207972894 ),( 211.607502246 , 30.528675045 ),
( 166.390268104 , 97.7445650663 ),( 208.739795292 , 70.7106781186 ),
( 246.250505507 , 54.626001135 ),( 295.559965172 , 50.9901951359 ),
( 306.15818544 , 64.4049687524 ),( 346.37300514 , 101.867561078 ),
( 12.8750015597 , 35.902646142 ),( 114.943905263 , 47.4236228055 ),
( 154.358994176 , 27.7308492477 ),( 33.690067526 , 57.6888204074 ),
( 252.552811577 , 36.6878726557 ),( 330.945395901 , 51.4781507049 ),
( 22.2490236572 , 47.539457296 ),( 78.9964591483 , 110.022724925 ),
( 128.585398193 , 120.253898066 ),( 173.088772881 , 132.966161109 ),
( 219.255841676 , 120.104121495 ),( 258.190117043 , 112.378823628 ),
( 310.544397167 , 109.224539367 ),( 341.565051177 , 98.0306074652 ))
def maze(username = ''):
username = username.lower()
ascii_total = 0
for c in username:
ascii_total += ord(c)
tr = tracer()
pc = pencolor()
ps = pensize()
tracer(0)
pencolor("black")
pensize(5)
penup()
right(ascii_total)
left(45)
back(45)
left(90)
pendown()
for h,d in maze_data:
setheading(h + ascii_total)
forward(d*2)
penup()
home()
pendown()
tracer(tr)
pencolor(pc)
pensize(ps)
''')
#TODO: make control window stay on top unless minimized
#TODO: make turtle window stay on top unless minimized
if __name__ == '__main__':
app = TurtleConGUI()
app.mainloop()
<file_sep>Turtlelab
=========
Turtlelab is an attempt to make life easier for young and/or very inexperienced Python coders using the turtle library. To do this a tool bar is available which will enter enter common commands into the code window, so that it's possible to code without typing as much.
When the "Go!" button is clicked the code is saved and run in a second interpreter instance. This gives almost the immediacy of a shell window, but with the ability to iteratively build up a program
A grid and coordinate reporting have also been added to help young programmers keep track of where they are.
Screenshots
-----------
The screenshots below should give some idea of what turtlelab does:
1. Below the command menu is showing... clicking on a command will insert that command into the code window:

2. The 'forward' command has just been selected. The highlighted section needs to be replaced with a meaningful value.

3. After putting in 100 for the distance, the student clicks "Go!" and the code is saved and the command is executed:

4. Loops can be added...


5. and more complicated patterns can be created with the supplied random_color(), random_location(), random_size(), etc functions:
<file_sep># TurtleLab example by sruiz
penup()
#This next line makes the program run faster
delay(0)
##############
# First let's create a background for our flower.
###
# A clear blue sky.
pencolor("sky blue")
dot(2000)
###
# A sun way off in space.
goto(-200,300)
pencolor("orange")
for i in range(18):
pensize(10)
pendown()
forward(50)
pensize(6)
forward(30)
pensize(3)
forward(20)
penup()
backward(100)
right(20)
pencolor("yellow")
dot(80)
###
# A mountain in the distance.
pencolor("black")
fillcolor("brown")
goto(-100,-10)
setheading(30)
pendown()
begin_fill()
forward(500)
right(90)
forward(300)
end_fill()
penup()
backward(200)
fillcolor("white")
begin_fill()
backward(100)
left(90)
backward(100)
right(90)
forward(50)
left(120)
forward(30)
right(120)
forward(50)
left(100)
forward(50)
right(100)
forward(30)
end_fill()
###
# Green ground.
pensize(10)
pencolor("green")
fillcolor("light green")
goto(-500,0)
pendown()
begin_fill()
goto(500,0)
goto(500,-400)
goto(-500,-400)
goto(-500,0)
end_fill()
penup()
###
# How about some nice grass?
goto(-400,-20)
setheading(90)
pensize(2)
for i in range(100):
pendown()
forward(75)
penup()
backward(60)
right(90)
forward(5)
left(90)
pendown()
forward(75)
penup()
backward(90)
right(90)
forward(3)
left(90)
######################################
# And now the centerpiece: our flower.
# Set up drawing the stem.
penup()
home()
pensize(5)
setheading(90)
pencolor("dark green")
fillcolor("green")
# Start drawing the main stem.
pendown()
forward(50)
left(36)
forward(20)
# First leaf
pensize(2)
begin_fill()
left(20)
forward(50)
right(40)
forward(50)
right(140)
forward(50)
right(40)
forward(50)
right(160)
end_fill()
forward(30)
backward(30)
pensize(5)
# Back to the stem
backward(20)
right(36)
forward(50)
right(53)
forward(30)
# Another leaf
pensize(2)
begin_fill()
left(20)
forward(50)
right(40)
forward(50)
right(140)
forward(50)
right(40)
forward(50)
right(160)
end_fill()
forward(30)
backward(30)
pensize(5)
# Finish stem
backward(30)
left(53)
forward(100)
# Petals...
pencolor("purple")
fillcolor("violet")
pensize(4)
for i in range(12): # Do this next part 10 times.
left(20)
begin_fill()
forward(50)
right(40)
forward(50)
right(140)
forward(50)
right(40)
forward(50)
end_fill()
right(130)
penup()
# The center of our flower.
color("dark orange")
dot(80)
color("orange")
dot(60)
color("yellow")
dot(40)
<file_sep>"""
Copyright 2009, <NAME>, <EMAIL>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import random
from turtle import *
delay(0)
tracer(False)
h= window_height()
w = window_width()
for x in range (1000):
r = random.randrange(100)
x = random.randrange(-h/2, h/2)
y = random.randrange(-w/2, w/2)-r
c = random.random(), random.random(), random.random()
up()
goto(x,y)
down()
color(c)
fill(1)
circle(r)
fill(0)
<file_sep># Circular String Art
# TurtleLab example by sruiz
import time
from turtle import * # <- so it can be run outside TurtleLab
RADIUS = 300
for NUM_POINTS in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29):
reset()
pensize(3)
hideturtle()
speed("fastest")
tracer(0) # Change this to tracer(0) to turn off animations completely
penup()
# Collect points to use
goto(0,-RADIUS)
pos_list = list()
for i in range(NUM_POINTS):
circle(RADIUS,360.0/NUM_POINTS)
pos_list.append(position())
linecount = 0
# Draw lines between the points
for i in range(1,NUM_POINTS/2+1):
x = (i*2)/float(NUM_POINTS)
color(x,x,x)
for j in range(NUM_POINTS):
goto(pos_list[j])
pendown()
goto(pos_list[(j+i)%NUM_POINTS])
penup()
linecount += 1
goto(0,-7)
color("black")
write("%d vertices\n%d lines drawn"% (NUM_POINTS, linecount), align="center")
time.sleep(2)
exitonclick()
<file_sep># TurtleLab example by sruiz
speed("fastest")
setup(width=1.0, height=1.0)
hideturtle()
delay(0)
penup()
# Define some values
stemthickness = 25
petals = 180
petalringradius = 150
petalseparation = 9.14159
seedrings = 72
seedringradius = 160
# Describe how to draw a single petal
def drawAPetal(degreesout = 10):
circle(-5,90 - degreesout/2)
begin_fill()
circle(-250,degreesout)
circle(-5, (180 - degreesout))
circle(-250,degreesout)
circle(-5, (90 - degreesout/2))
end_fill()
right(90)
forward(75)
back(75)
left(90)
# Draw a sunset-ish sky
goto(200,-200)
color("red")
dot(4000)
for x in range(80):
color((1,x*.01,0))
dot(1800 - x*20)
# Draw the stem
goto(0,0)
pendown()
color("black")
pensize(stemthickness)
right(115)
circle(500,90)
color("green")
pensize(stemthickness-4)
circle(500,-90)
color("black")
pensize(1)
left(115)
penup()
# Draw a circle of petals
goto(0,-petalringradius)
pencolor("black")
fillcolor("yellow")
d = 40.
pendown()
for i in range(petals):
circle(petalringradius,petalseparation)
x = d-(5./petals)*i
drawAPetal(x)
penup()
# Draw the seed ring
goto(0,-seedringradius)
setheading(0)
pendown()
fillcolor("brown")
begin_fill()
circle(seedringradius)
end_fill()
for i in range(seedrings):
circle(seedringradius,360/seedrings)
circle(seedringradius/2)
exitonclick()
<file_sep># TurtleLab example by sruiz
# Set up the screen
setup(1.0,1.0)
update()
width = window_width()
height = window_height()
penup()
delay(0)
tracer(0)
color("black")
dot(3000)
penup()
LARGEST_RADIUS = 200
def rainbow_spike():
radius = LARGEST_RADIUS
while radius > 0:
for c in ('red','orange','yellow','green','blue','purple'):
color(c)
forward(5)
dot(radius)
radius = radius - 1
if radius < 1:
break
x = LARGEST_RADIUS * 5 / 2
setheading(0)
for y in range(height/2,-height/2-LARGEST_RADIUS,-LARGEST_RADIUS):
goto(-x,y)
rainbow_spike()
setheading(180)
for y in range(height/2+LARGEST_RADIUS/2,-height/2-LARGEST_RADIUS/2,-LARGEST_RADIUS):
goto(x,y)
rainbow_spike()
<file_sep>"""
based on logo program - creates "webs"
Copyright 2009, <NAME>, <EMAIL>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# imports turtle library in Tkinter dialogs
from turtle import *
from tkSimpleDialog import askinteger
from tkSimpleDialog import askfloat
from tkSimpleDialog import askstring
# creates turtles for drawing
t1 = Turtle()
t1.tracer(False)
# comment out this line to get main lines
#t1.up()
t2 = Turtle()
t2.tracer(False)
t2.up()
t3 = Turtle()
t3.tracer(False)
t3.delay(0)
t3.up()
# gets values from user
lines = askfloat("","Number of lines: ")
strands = askfloat("","Number of strands: ")
gap = askinteger ("","Number of lines to skip from center :")
size = distance = askinteger("","Diameter :")
color = askstring("", "Color :")
step = size/float(strands)
t1.color(color)
t3.color(color)
# t1 moves to outside of one line
t1.forward(distance)
# draws the figure by connecting different points on two adjacent lines
for x in range(lines):
t2.right(360.0/lines)
t2.forward(step * gap)
for x in range(strands-gap):
t2.forward(step)
t3.goto(t1.position())
t3.down()
t3.goto(t2.position())
t3.up()
t3.goto(t1.position())
t1.backward(step)
t1.backward(step * gap)
t1.right(360.0/lines)
t1.forward(distance)
t2.backward(distance)
t1.backward(distance)
<file_sep>"""
Copyright 2009, <NAME>, <EMAIL>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import random
from turtle import *
delay(0)
tracer(False)
h= window_height()
w = window_width()
x1 = w/4
x2 = -x1
y1 = h/4
y2 = -y1
for x in range(120):
up()
goto(x1,y1)
down()
color(random.random(), random.random(), random.random())
circle(140)
up()
goto(x2,y1)
down()
color(random.random(), random.random(), random.random())
circle(140)
up()
setx(x2)
sety(y2)
down()
color(random.random(), random.random(), random.random())
circle(140)
up()
setx(x1)
sety(y2)
down()
color(random.random(), random.random(), random.random())
circle(140)
right(360/120)
<file_sep>#!/usr/bin/python
# Lotteryball Generator
# TurtleLab example by sruiz
# After running, click on screen to generate lottery numbers.
import random
from turtle import * # <- so it can run outside TurtleLab
delay(0)
hideturtle()
if "hide_grid" in dir(): # <- so it can run outside TurtleLab
hide_grid()
CIRCLERADIUS = 25
FONTSIZE = 12
def lotteryball(x,y):
numbers = []
for i in range(5):
numbers.append(random.randrange(1,60))
numbers.append(random.randrange(1,40))
clear()
pencolor("black")
fillcolor("white")
penup()
goto(-CIRCLERADIUS*5,0)
pendown()
for n in range(len(numbers)):
if n == len(numbers)-1:
fillcolor("red")
begin_fill()
circle(CIRCLERADIUS)
end_fill()
penup()
left(90)
forward(CIRCLERADIUS - FONTSIZE/2)
write(numbers[n],align="center",font=("Arial",FONTSIZE,"bold"))
backward(CIRCLERADIUS - FONTSIZE/2)
right(90)
forward(CIRCLERADIUS * 2)
pendown()
onscreenclick(lotteryball)
mainloop()
|
693e72213f9c211ff08d05bf1b7a7ac1ae934ecb
|
[
"Markdown",
"Python"
] | 11 |
Python
|
nceder/turtlelab
|
c76b36d0513f2a225f768c435828cc4e18a26e8f
|
843d1ead45f99e1a930863411c120aa3d052b5cd
|
refs/heads/master
|
<repo_name>MGA-debug/Compas<file_sep>/src/main/java/ru/appline/controller/Controller.java
package ru.appline.controller;
import org.json.simple.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.appline.logic.Model;
import ru.appline.utils.JsonHelper;
import java.util.Map;
@RestController
public class Controller {
private static Model model = Model.getInstance();
@PostMapping(value = "/setCoordinates", consumes = "application/json", produces = "application/json")
public String setCoordinates(@RequestBody Map<String, String> coordinates) {
String result;
if (model.fillIn(coordinates)) {
result = "All right. You can start searching now";
} else {
result = "Invalid data";
}
return result;
}
@GetMapping(value = "/searchResult", consumes = "application/json", produces = "application/json")
public JSONObject searchResult(@RequestBody Map<String, Integer> coordinates) {
return JsonHelper.getHelper().getSideWorld(Model.searchSide(coordinates.get("Degree")));
}
}
|
805c4cc1a25ff71b131bc7ca2218f86d47d59da3
|
[
"Java"
] | 1 |
Java
|
MGA-debug/Compas
|
af8aa7896b6fde2c56fad97f57c7f0ca44bd6018
|
b0f420ab99aa5c839d9eab2f0dd8354ceefe6fc1
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>nicknelson.io</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Karla%7CSpace+Mono:400,400i" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./css/main.css">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="topnav">
<div class="topnavupper">
<a href="./" data-transition-direction="up">
<span><img src="./images/chevron-top.svg" class="img-glyph" alt="Up arrow"></span><span>Home</span><span><img src="./images/chevron-top.svg" class="img-glyph" alt="Up arrow"></span>
</a>
</div>
<div class="topnavlower">
<a class="leftnav-mobile" data-transition-direction="left" href="./contact.html"><img src="./images/chevron-left.svg" class="img-glyph" alt="Left arrow">Contact</a>
<a class="rightnav-mobile" data-transition-direction="right" href="./education.html">Experience<img src="./images/chevron-right.svg" class="img-glyph" alt="Right arrow"></a>
</div>
</div>
<div class="main">
<div class="leftnav-desktop">
<a href="./contact.html" data-transition-direction="left"><img src="./images/chevron-left.svg" class="img-glyph" alt="Left arrow">Contact</a>
</div>
<div class="showcase">
<h1>Portfolio</h1>
<div class="cardcontainer">
<div class="card">
<div class="cardheading">
<h2>FancyFan</h2>
</div>
<div class="cardcontent">
<p>The FancyFan project is the result of the combination of too many summer days spent sweltering at my computer and an enjoyment of novelty over-engineered solutions.</p>
<p>It incorporates an ESP8266 microprocessor / wifi chip, custom power supply board, motion and temperature sensors, three 120mm PC case fans, four status LEDs, and two very satisfyingly clicky control buttons, all housed in a 330mm hand-crafted brushed aluminium case with a custom wooden control panel.</p>
<p>It's too big to fit nicely on my desk... but that's not really the point.</p>
<ul>
<li><a href="https://github.com/nicholasnelson/FancyFan-CircuitBoard">Circuitboard on Github</a></li>
<li><a href="https://blog.nicknelson.io/categories/electronics/">Photos and design commentary on blog.nicknelson.io</a></li>
</ul>
</div>
</div>
</div>
<div class="cardcontainer">
<div class="card">
<div class="cardheading">
<h2>(HTML)buntu</h2>
</div>
<div class="cardcontent">
<p>I initially started this project as a bit of a toy. From there it became a test of how accurately I could replicate the Ubuntu user interface using only HTML, CSS, and Javascript. There are a few bugs, and a few more features I would still like to implement when I have the time.</p>
<ul>
<li><a href="https://github.com/nicholasnelson/htmlbuntu">(HTML)buntu on Github</a></li>
<li><a href="http://nicknelson.io">Working demo</a></li>
</ul>
</div>
</div>
<div class="card">
<div class="cardheading">
<h2>bf.js</h2>
</div>
<div class="cardcontent">
<p>bf.js is another toy I wrote over a few hours one weekend after reading about esoteric languages on Google. It is an in-browser interpreter for one of the better known esoteric languages.</p>
<p>The language itself uses only 8 commands, represented by 8 different characters: < > + - , , [ ]</p>
<p>The interpreter allows either standard or step-by-step execution, and displays the state of memory cells on either side of the pointer position making it easier to troubleshoot programs.</p>
</div>
<ul>
<li><a href="https://github.com/nicholasnelson/bfjs">bf.js on Github</a></li>
</ul>
</div>
</div>
</div>
<div class="rightnav-desktop">
<a href="./education.html" data-transition-direction="right">Experience<img src="./images/chevron-right.svg" class="img-glyph" alt="Right arrow"></a>
</div>
</div>
</body>
</html>
<file_sep>/**
* @license
* Copyright (c) 2017 <NAME> (S247742)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/*
* A class to dynamically turn a multi page site into a coherent single-page experience
*/
class TransitionManager {
constructor() {
// Default to first screen
this._currentActive = document.querySelector('div.transition-screen');
this._currentActive.setAttribute("data-transition-url", "./");
this.moveTo(this._currentActive, "down");
this._scanLinks(document);
}
_scanLinks(targetDiv) {
// First load any required links into the document
var transitionLinks = targetDiv.querySelectorAll("[data-transition-direction]");
for (var el of transitionLinks) {
var url = el.getAttribute("href");
// Check for existing target div for this url
var transitionScreen = document.querySelector('div.transition-screen[data-transition-url="' + url + '"]');
// If we didn't find a target, create one
if(!transitionScreen) {
var req = new XMLHttpRequest();
var method = "GET";
// Create element for the screen
transitionScreen = document.createElement("div");
transitionScreen.classList.add("transition-screen");
transitionScreen.setAttribute("data-transition-url", url);
document.body.appendChild(transitionScreen);
// Request the page, callback loads the page into the transitionScreen div
req.open(method, url, true);
req.onreadystatechange = function (req, target) {
if(req.readyState === XMLHttpRequest.DONE && req.status === 200) {
var doc = document.implementation.createHTMLDocument(req.responseURL);
doc.documentElement.innerHTML = req.responseText;
target.innerHTML = doc.body.innerHTML;
// Run scanLinks again on new div
this._scanLinks(target);
}
}.bind(this, req, transitionScreen);
req.send();
}
// Setup click handler based on existing / new target div
el.href = "#";
el.onclick = this.moveTo
.bind(this,
transitionScreen,
el.getAttribute('data-transition-direction'));
}
}
// Close the active transition-screen and open a new one
moveTo(newActive, animateDirection) {
var fromSide, toSide;
switch (animateDirection) {
case "down":
fromSide = "bottom";
toSide = "top";
break;
case "up":
fromSide = "top";
toSide = "bottom";
break;
case "left":
fromSide = "left";
toSide = "right";
break;
case "right":
fromSide = "right";
toSide = "left";
break;
default:
throw new Error("Invalid direction: " + animateDirection);
}
// Put newActive in correct position without using transition effects
newActive.classList.add("no-transition");
newActive.setAttribute("data-transition", fromSide);
/* Force reflow before we remove no-transition
* Thanks to <NAME> on Stackoverflow for this answer */
newActive.offsetHeight; // Reflow voodoo here
newActive.classList.remove("no-transition");
// Start closing currentActive
this._currentActive.setAttribute("data-transition", toSide);
// Start opening newActive, with transition effect
newActive.setAttribute("data-transition", "open");
this._currentActive = newActive;
}
}
export { TransitionManager as default };<file_sep>/**
* Scripts for Portfolio
*
* author: <NAME> (S247742)
* website: <EMAIL>
*/
import TransitionManager from "./lib/TransitionManager";
import EmailHide from "./lib/EmailHide";
var transitionManager = new TransitionManager();
var emailHide = new EmailHide();
setInterval(function() {
emailHide.unhide("<EMAIL>", "Hello");
}, 1000);
|
778d1b7da1aa90ebfbf132d18a05cff28f539bcf
|
[
"JavaScript",
"HTML"
] | 3 |
HTML
|
nicholasnelson/HIT226-portfolio
|
032171ab4fea3f663660a4fa259c66db54c7edee
|
299f158f2c11b84a5495c0145b68ca00b7650351
|
refs/heads/master
|
<repo_name>Carrage1121/Barrage<file_sep>/Assets/Scripts/zzy/StopBullet3.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StopBullet3 : IBullet
{
public float time = 2;
public float timer = 0;
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer>= time)
{
transform.Rotate(Vector3.down * 60 * Time.deltaTime);
if (timer > 30)
{
Recycle();
}
}
base.Update();
}
public override void Recycle()
{
base.Recycle();
timer = 0;
}
}
<file_sep>/Assets/Scripts/Weapon/YKWeaponAim.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//自瞄,搭配追踪弹即是导弹
public class YKWeaponAim : IWeapon
{
public override void Fire()
{
if (IEnemy.enemys.Count > 0)
{
target = BarrageUtil.RandomFecthFromList<IEnemy>(IEnemy.enemys).gameObject;
}
base.Fire();
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun9.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//涡轮两条顺向
public class ZZWeaponShotgun9 : IWeapon
{
public override void Init()
{
attackSpeed = 1.0f;
base.Init();
}
//射击方法,需要重写
public override void Fire()
{
Debug.Log("fire");
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
Vector3 vec = new Vector3(0, 0, 1);
Vector3 vec2 = new Vector3(0, 0, -1);
for (int i = -9; i < 36; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(21 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 5;
bulletInfo.delay = 0;
bulletInfo.Fire();
GameObject bullet2 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet2.transform.position = shooter.GetPos();
bullet2.transform.forward = Quaternion.AngleAxis(21 * i, Vector3.up) * vec2;
IBullet bulletInfo2 = bullet2.GetComponent<IBullet>();
bulletInfo2.shooter = shooter;
bulletInfo2.speed = 5;
bulletInfo2.delay = 0;
bulletInfo2.Fire();
yield return new WaitForSeconds(0.5f);
if(shooter==null)
{
yield return null;
}
}
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun10.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//涡轮两条逆向
public class ZZWeaponShotgun10 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
//射击方法,需要重写
public override void Fire()
{
Debug.Log("fire");
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
Vector3 vec = GetVec();
for (int i = -9; i < 36; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(20 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 5;
bulletInfo.delay = 0;
bulletInfo.Fire();
GameObject bullet2 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet2.transform.position = shooter.GetPos();
bullet2.transform.forward = Quaternion.AngleAxis(20 * i, Vector3.down) * vec;
IBullet bulletInfo2 = bullet2.GetComponent<IBullet>();
bulletInfo2.shooter = shooter;
bulletInfo2.speed = 5;
bulletInfo2.delay = 0;
bulletInfo2.Fire();
yield return new WaitForSeconds(0.1f);
}
}
}
<file_sep>/Assets/Resources/HpUI.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HpUI : MonoBehaviour
{
public Image[] hearts;
private void OnEnable()
{
Action<ArrayList> action = new Action<ArrayList>(HpChanged);
EventManager.StartListening("playerBeDamaged", action);
}
void HpChanged(ArrayList param)
{
int hp = (int)param[0];
for(int i = 0; i < hearts.Length; i++)
{
if (i > hp-1)
hearts[i].enabled = false;
else
hearts[i].enabled = true;
}
}
private void OnDestroy()
{
EventManager.StopListening("playerBeDamaged");
}
}
<file_sep>/Assets/Scripts/Movement/LineMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineMove : IMovement
{
}
<file_sep>/Assets/Scripts/Interface/IStatus.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IStatus
{
public int hp=3;
public int MaxHp=3;
public int mp=3;
public int MaxMp=3;
public string master;
bool died;
public IStatus()
{
}
public void GetDamage(int damge)
{
if (hp - damge <= 0)
{
hp = 0;
died = true;
}else
{
hp -= damge;
}
if(master=="player")
EventManager.TriggerEvent("playerBeDamaged", new ArrayList { hp });
}
public void CostMp(int cost)
{
mp -= cost;
}
public bool isDied()
{
return died;
}
public void updateUI()
{
}
}
<file_sep>/Assets/Scripts/SceneState/BattleState12.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
// 战斗状态
public class BattleState12 : ISceneState
{
public BattleState12(SceneStateController Controller):base(Controller)
{
this.StateName = "BattleState12";
}
// 初始化,获取相关信息和物体
public override void StateBegin()
{
BarrageGame.Instance.Init();
}
// 結束
public override void StateEnd()
{
BarrageGame.Instance.Release();
}
// 更新
public override void StateUpdate()
{
// 遊戲邏輯
BarrageGame.Instance.Update();
// Render由Unity負責
// 遊戲是否結束
//if(BarrageGame.Instance.ThisGameIsOver())
// m_Controller.SetState(new MainMenuState(m_Controller), "MainMenuScene" );
if (BarrageGame.Instance.GameIsFinish())
{
m_Controller.SetState(new BattleState12(m_Controller), "Level1-2");
}
}
}
<file_sep>/Assets/Scripts/Interface/IGameSystem.cs
using UnityEngine;
using System.Collections;
// 遊戲子系統共用界面
public abstract class IGameSystem
{
protected BarrageGame barrageGame = null;
public IGameSystem(BarrageGame barrageGame)
{
this.barrageGame = barrageGame;
}
public virtual void Initialize() { }
public virtual void Release() { }
public virtual void Update() { }
}
<file_sep>/Assets/Resources/IAid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IAid : ICharacter,IShootAble
{
GameObject player;
int x;
public override void Init()
{
base.Init();
player = GameObject.FindGameObjectWithTag("Player");
x = Random.Range(-1, 3) >= 1 ? 1 : -1;
}
public override void Fire()
{
weapon.Fire();
}
public override void CharacterUpdate()
{
base.CharacterUpdate();
//transform.position = Vector3.Lerp(transform.position, player.transform.position + new Vector3(x, 0, 0), 0.1f);
if (player)
{
transform.position = Vector3.Lerp(transform.position, player.transform.position, 0.1f);
}
}
}
<file_sep>/Assets/Scripts/Bullet/BallBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBullet : IBullet
{
public void OnEnable()
{
BarrageGame.Instance.getBulletUtil().Recycle(this, 12);
}
// Update is called once per frame
void Update()
{
base.Update();
transform.Rotate(Vector3.up * 90 * Time.deltaTime);
}
}
<file_sep>/Assets/Scripts/Mgr/PartController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PartController : MonoBehaviour
{
public static void MoveToNextPart(string partName)
{
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun5.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//涡轮圆形一波36*12一齐 5
public class ZZWeaponShotgun5 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
private const int V = 3;
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
IBullet[] bullets = new IBullet[20];
Vector3 vec = new Vector3(0, 0, 1);
for (int a = 0; a < 1; a++)
{
for (int i = 0; i < 12; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(30 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.Fire();
bullets[i] = bulletInfo;
bulletInfo.speed = 3.0f;
yield return new WaitForSeconds(0.1f);
}
yield return new WaitForSeconds(1.0f);
for (int i = 0; i < 12; i++)
{
bullets[i].Recycle();
for (int j = -8; j < 29; j++)
{
GameObject bullet2 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet2.transform.position = bullets[i].transform.position;
bullet2.transform.forward = Quaternion.AngleAxis(10 * j, Vector3.up) * vec;
IBullet bulletInfo2 = bullet2.GetComponent<IBullet>();
bulletInfo2.shooter = shooter;
bulletInfo2.Fire();
bulletInfo2.speed = 3.0f;
}
}
}
}
////朝某个方向
//public override void Fire(Vector3 vec)
//{
// //从对象池里取出子弹
// GameObject bullet = BulletUtil.LoadBullet(shooter.bulletName);
// //将取出的子弹的位置设置为射击者的位置
// bullet.transform.position = shooter.GetPos();
// //使子弹的forward向量等于射击者到目标的向量,也就是说让子弹正面朝向目标
// bullet.transform.forward = vec;
// //将子弹的攻击者设置为射击者
// bullet.GetComponent<IBullet>().shooter = shooter;
// //调用子弹的发射函数。可在子弹的发射函数中设置发射延迟或者启动一个新的函数或协程。
// bullet.GetComponent<IBullet>().Fire();
//}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun6.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//涡轮圆形一波36*12
public class ZZWeaponShotgun6 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
private const int V = 3;
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
Vector3[] bulletsPos = new Vector3[20];
float distance = 0;
Vector3 vec = new Vector3(0, 0, 1);
for (int a = 0; a < 1; a++)
{
for (int i = 0; i < 12; i++)
{
bulletsPos[i] = shooter.GetPos()+Quaternion.AngleAxis(28 * i, Vector3.up) * vec*distance;
distance += 4;
}
for (int i = 0; i < 12; i++)
{
for (int j = -8; j < 29; j++)
{
GameObject bullet2 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet2.transform.position = bulletsPos[i];
bullet2.transform.forward = Quaternion.AngleAxis(10 * j, Vector3.up) * vec;
IBullet bulletInfo2 = bullet2.GetComponent<IBullet>();
bulletInfo2.shooter = shooter;
bulletInfo2.Fire();
bulletInfo2.speed = 1.5f;
}
yield return new WaitForSeconds(0.1f);
}
}
}
////朝某个方向
//public override void Fire(Vector3 vec)
//{
// //从对象池里取出子弹
// GameObject bullet = BulletUtil.LoadBullet(shooter.bulletName);
// //将取出的子弹的位置设置为射击者的位置
// bullet.transform.position = shooter.GetPos();
// //使子弹的forward向量等于射击者到目标的向量,也就是说让子弹正面朝向目标
// bullet.transform.forward = vec;
// //将子弹的攻击者设置为射击者
// bullet.GetComponent<IBullet>().shooter = shooter;
// //调用子弹的发射函数。可在子弹的发射函数中设置发射延迟或者启动一个新的函数或协程。
// bullet.GetComponent<IBullet>().Fire();
//}
}
<file_sep>/Assets/Scripts/UI/GameOverUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameOverUI : MonoBehaviour
{
public void Restart()
{
SceneStateController controller = BarrageGame.Instance.sceneStateController;
controller.SetState(new MainMenuState(controller), "MainMenuScene");
}
}
<file_sep>/Assets/Scripts/Tools/BarrageUtil.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BarrageUtil : MonoBehaviour
{
public static T RandomFecthFromList<T>(List<T> list)
{
//bool allNull=true;
//for(int i = 0; i < list.Count; i++)
//{
// if (list[i] != null)
// allNull = false;
//}
//if (allNull)
// return null;
int random = Random.Range(0, list.Count);
return list[random];
}
}
<file_sep>/Assets/Scripts/Weapon/YkWeaponShotgun.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YkWeaponShotgun : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(YkShotgun());
}
IEnumerator YkShotgun()
{
Vector3 vec = GetVec();
for (int i = -72; i < 72; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(10 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 5;
bulletInfo.delay = 0;
bulletInfo.Fire();
yield return new WaitForSeconds(0.05f);
}
}
//按照攻击速度进行攻击
public void Tick()
{
timer.Tick();
if (timer.state == MyTimer.STATE.finished)
{
//核心方法
Fire();
timer.Restart();
}
}
}
<file_sep>/Assets/Scripts/zzy/StopBullet2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StopBullet2 : IBullet
{
public float time = 2;
public float timer = 0;
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (time >= timer)
{
transform.Rotate(Vector3.down * 60 * Time.deltaTime);
}
base.Update();
}
public override void Recycle()
{
base.Recycle();
timer = 0;
}
}
<file_sep>/Assets/Scripts/SceneState/BattleState11.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
// 战斗状态
public class BattleState11 : ISceneState
{
public BattleState11(SceneStateController Controller) : base(Controller)
{
this.StateName = "BattleState11";
BarrageGame.Instance.sceneStateController = m_Controller;
}
//初始化,获取相关信息和物体
public override void StateBegin()
{
BarrageGame.Instance.Init();
}
//結束
public override void StateEnd()
{
BarrageGame.Instance.Release();
BulletPool.bullets.Clear();
IEnemy.enemys.Clear();
}
//更新
public override void StateUpdate()
{
// 遊戲邏輯
BarrageGame.Instance.Update();
// Render由Unity負責
// 遊戲是否結束
if (BarrageGame.Instance.ThisGameIsOver())
{
Debug.Log("游戏结束");
m_Controller.SetState(new MainMenuState(m_Controller), "MainMenuScene");
}
if (BarrageGame.Instance.GameIsFinish())
{
Debug.Log("游戏结束");
m_Controller.SetState(new BattleState12(m_Controller), "Level1-2");
}
}
}
<file_sep>/Assets/Scripts/Weapon/YKWeaponChaos.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//混乱,随机决定子弹方向。
public class YKWeaponChaos : IWeapon
{
public override void Fire()
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
bullet.GetComponent<IBullet>().shooter = shooter;
if (target)
bullet.GetComponent<IBullet>().target = target;
bullet.GetComponent<IBullet>().Fire();
}
}
<file_sep>/Assets/Scripts/Interface/Character/ICharacter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ICharacter : MonoBehaviour,IShootAble
{
public string bulletName;
public string weaponName;
public float attackSpeed=1;
//武器
public IWeapon weapon;
//public float attackSpeed=1;
void Start()
{
Init();
}
//初始化方法
public virtual void Init()
{
weapon = (IWeapon)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(weaponName, false);
weapon.shooter = this;
weapon.SetAttackSpeed(attackSpeed);
}
// Update is called once per frame
public virtual void Update()
{
CharacterUpdate();
}
public virtual void CharacterUpdate()
{
weapon.Tick();
}
public GameObject GetObj()
{
return gameObject;
}
public Vector3 GetPos()
{
return gameObject.transform.position;
}
public virtual void Fire()
{
weapon.Fire();
}
//血量
public IStatus status=new IStatus();
public void GetDamage(int damage)
{
status.GetDamage(damage);
if (status.isDied())
{
Die();
}
}
public void CostMp(int cost)
{
status.CostMp(cost);
}
public string GetBulletName()
{
return bulletName;
}
public void Die()
{
Destroy(this);
}
}
<file_sep>/Assets/Unity-MessageBoxV2-master/README.md
# Unity-MessageBoxV2

导入这个文件夹到unity中,你不需要进行任何的配置
即可通过MessageBoxV2.AddMessage("内容")打印信息
有一个重载可以控制停留时间:MessageBoxV2.AddMessage("内容",停留时间)
在Resources文件中的MessageBox预制体决定了你的打印信息的位置,你可能需要基本的预制体的知识来更改位置
在messageBox上的脚本MessageTextContainer上的space是设置消息之间的垂直间隔
QWQ
<file_sep>/Assets/Scripts/Interface/Character/IPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IPlayer : ICharacter
{
public List<IWeapon> weapons = new List<IWeapon>();
public static StageSystem stageSystem = null;
public int ppt = 0;
int tmpPpt = 0;
public int hpt = 0;
public IAid aid;
public override void Init()
{
base.Init();
//初始武器
weapons.Add(weapon);
aid = GameObject.FindGameObjectWithTag("Aid").GetComponent<IAid>();
status.master = "player";
status.hp = 3;
}
public void OnTriggerEnter(Collider other)
{
if (other.tag == "EnemyBullet")
{
status.GetDamage(1);
if (status.hp <= 0)
Die();
}
if (other.tag == "ppt")
{
ppt += 5;
other.GetComponent<IBullet>().Recycle();
}
if (other.tag == "hpt")
{
hpt += 1;
if (hpt % 3 == 0&&status.hp<3)
{
status.GetDamage(-1);
}
other.GetComponent<IBullet>().Recycle();
}
}
public override void Update()
{
for (int i = 0; i < weapons.Count; i++)
{
weapons[i].Tick();
}
//根据分数切换武器
if (tmpPpt != 15 && ppt == 15)
{
weapons.Clear();
AddWeapon("PlayerWeapon0");
tmpPpt = 15;
aid.attackSpeed += 2;
aid.weapon.timer.Start(1f/aid.attackSpeed);
}
if (tmpPpt != 30 && ppt == 30)
{
weapons.Clear();
AddWeapon("PlayerWeapon1");
tmpPpt = 30;
aid.attackSpeed += 4;
aid.weapon.timer.Start(1f / aid.attackSpeed);
}
if (tmpPpt!=60&&ppt == 60)
{
weapons.Clear();
AddWeapon("PlayerWeapon2");
tmpPpt = 60;
aid.attackSpeed += 6;
aid.weapon.timer.Start(1f / aid.attackSpeed);
}
}
public void Die()
{
EventManager.TriggerEvent("playerDied",null);
GameObject explosion = BulletUtil.LoadBullet("ExplosionParticle");
explosion.transform.position = transform.position;
explosion.GetComponent<IBullet>().Fire();
BarrageGame.Instance.GameOver();
}
public void AddWeapon(string weaponName)
{
weapon = (IWeapon)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(weaponName, false);
weapon.shooter = this;
weapon.SetAttackSpeed(attackSpeed);
weapons.Add(weapon);
}
}
<file_sep>/Assets/Resources/Missle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Missle : IBullet
{
public int r;
public GameObject trail;
public override void Init()
{
base.Init();
r = (Random.Range(-1, 3) >= 1 ? 1 : -1) * Random.Range(10,60);
}
public void OnEnable()
{
GameObject tmpTrail = Instantiate(trail);
UnityTool.Attach(gameObject, tmpTrail, Vector3.zero);
if (IEnemy.enemys.Count > 0)
{
target = BarrageUtil.RandomFecthFromList<IEnemy>(IEnemy.enemys).gameObject;
}
}
// Update is called once per frame
void Update()
{
if (target == null)
{
base.Update();
return;
}
Vector3 a = transform.position;
Vector3 b = target.transform.position;
Vector3 center = (a + b) * 0.5f;
center += new Vector3(r,0,0f);
Vector3 vecA = a - center;
Vector3 vecB = b - center;
Vector3 vec = Vector3.Slerp(vecA, vecB, 0.05f);
vec += center;
transform.forward = vec - transform.position;
transform.position = Vector3.MoveTowards(transform.position, vec, 0.1f);
}
public override void Recycle()
{
if (transform.parent == null)
{
if (recycleAble == true)
{
Transform trail = transform.GetChild(0);
trail.SetParent(null);
Destroy(trail.gameObject, 3);
BulletPool.Put(gameObject);
gameObject.SetActive(false);
}
}
}
}
<file_sep>/Assets/Scripts/Mgr/BarrageGame.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BarrageGame
{
public bool gameOver=false;
public StageSystem stageSystem;
public GameObject playerObj;
private BarrageUtil barrageUtil;
private BulletUtil bulletUtil;
public SceneStateController sceneStateController;
//全局移动速度
public float moveSpeed=2;
public bool gameFinish=false;
//对象池子弹每种子弹的上限数量
public static int BulletPoolCount=64;
//返回BarrageUtil的mono类,当项目中存在时直接调用,不存在则新建空物体并挂载脚本,更新barrageUtil为新的BarrageUtil
public BarrageUtil getBarrageUtil()
{
if (barrageUtil != null)
{
return barrageUtil;
}
BarrageUtil newBarrageUtil = GameObject.FindObjectOfType<BarrageUtil>();
if (newBarrageUtil == null)
{
GameObject empty = new GameObject();
newBarrageUtil=empty.AddComponent<BarrageUtil>();
}
barrageUtil = newBarrageUtil;
return newBarrageUtil;
}
//返回BulletUtil的mono类,当项目中存在时直接调用,不存在则新建空物体并挂载脚本,更新barrageUtil为新的BarrageUtil
public BulletUtil getBulletUtil()
{
if (bulletUtil != null)
{
return bulletUtil;
}
BulletUtil newBulletUtil = GameObject.FindObjectOfType<BulletUtil>();
if (newBulletUtil == null)
{
GameObject empty = new GameObject();
newBulletUtil = empty.AddComponent<BulletUtil>();
}
bulletUtil = newBulletUtil;
return newBulletUtil;
}
public float GetMoveSpeed()
{
return moveSpeed;
}
public bool ThisGameIsOver()
{
return gameOver;
}
public bool GameIsFinish()
{
return gameFinish;
}
//------------------------------------------------------------------------
// Singleton模版
private static BarrageGame _instance;
public static BarrageGame Instance
{
get
{
if (_instance == null)
_instance = new BarrageGame();
return _instance;
}
}
public void Init()
{
//playerObj = GameObject.FindGameObjectWithTag("player");
}
public void Release()
{
}
// Update is called once per frame
public void Update()
{
}
public void GameOver()
{
GUIManager.ShowView("GameOverUI", Vector3.zero);
GameObject Player = GameObject.FindGameObjectWithTag("Player");
GameObject.Destroy(Player);
GameObject Aid = GameObject.FindGameObjectWithTag("Aid");
GameObject.Destroy(Aid);
Time.timeScale = 0.1f;
}
}
<file_sep>/Assets/Scripts/Weapon/GhWeaponShotgun.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GhWeaponShotgun : IWeapon
{
int count = 4;
//射击方法,需要重写
public override void Fire()
{
Vector3 vec = GetVec();
for (int i = -1*count; i < count; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(20*i, Vector3.up)*vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 10;
bulletInfo.delay = 3;
bulletInfo.Fire();
}
}
public void Tick()
{
timer.Tick();
if (timer.state == MyTimer.STATE.finished)
{
if (count > 0)
{
Fire();
count--;
timer.Restart();
}
else
{
attackSpeed = 0.5f;
timer.duration = 1.0f / attackSpeed;
Fire();
timer.Restart();
}
}
}
//朝某个方向
public override void Fire(Vector3 vec)
{
//从对象池里取出子弹
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
//将取出的子弹的位置设置为射击者的位置
bullet.transform.position = shooter.GetPos();
//使子弹的forward向量等于射击者到目标的向量,也就是说让子弹正面朝向目标
bullet.transform.forward = vec;
//将子弹的攻击者设置为射击者
bullet.GetComponent<IBullet>().shooter = shooter;
//调用子弹的发射函数。可在子弹的发射函数中设置发射延迟或者启动一个新的函数或协程。
bullet.GetComponent<IBullet>().Fire();
}
}
<file_sep>/Assets/Scripts/Weapon/YkWeaponBall.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YkWeaponBall : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(YkBall());
}
IEnumerator YkBall()
{
for (int i = 0; i < 3; i++)
{
Vector3 vec = new Vector3(0, 0, 1);
for (int j = -8; j < 10; j++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(20 * j, Vector3.up) * vec;
bullet.GetComponent<IBullet>().shooter = shooter;
bullet.GetComponent<IBullet>().Fire();
}
yield return new WaitForSeconds(0.1f);
}
}
}
<file_sep>/Assets/Scripts/Mgr/BulletUtil.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletUtil : MonoBehaviour
{
public static GameObject LoadBullet(string bulletName)
{
GameObject bullet = null;
//先从对象池中取出
bullet = BulletPool.Get(bulletName);
if (bullet == null)
{
//Debug.Log("强行生成子弹");
Object b = Resources.Load("Bullet/" + bulletName);
bullet = GameObject.Instantiate((GameObject)b);
}
return bullet;
}
public void Recycle(IBullet bullet,float time)
{
StartCoroutine(recycleAfterTime(bullet,time));
}
IEnumerator recycleAfterTime(IBullet bullet,float time)
{
yield return new WaitForSeconds(time);
bullet.Recycle();
}
}
<file_sep>/Assets/Scripts/Interface/IShootAble.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IShootAble
{
GameObject GetObj();
Vector3 GetPos();
string GetBulletName();
void Die();
}
<file_sep>/Assets/Scripts/Interface/Character/Enemy2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy2 : IEnemy
{
int count = 4;
public override void Init()
{
base.Init();
}
public void Update()
{
waitTimer.Tick();
if (waitTimer.state != MyTimer.STATE.finished)
return;
weapon.Tick();
}
}
<file_sep>/Assets/Scripts/Mgr/EventManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventManager : MonoBehaviour
{
private Dictionary<string, Action<ArrayList>> eventDictionary;
private static EventManager eventManager;
//单例
public static EventManager instance
{
get
{
if (!eventManager)
{
//在Unity的Hierarchy中必须有一个名为EventManager的空物体,并挂上EventManager脚本
eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;
if (!eventManager)
{
Debug.Log("项目中没有EventManager,自动创建");
GameObject mangager = new GameObject("EventManager");
eventManager = mangager.AddComponent<EventManager>();
eventManager.Init();
}
else
{
eventManager.Init();
}
}
return eventManager;
}
}
public void Init()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<string, Action<ArrayList>>();
}
}
//在需要监听某个事件的脚本中,调用这个方法来监听这个事件
public static void StartListening(string eventName, Action<ArrayList> action)
{
if (instance.eventDictionary.ContainsKey(eventName))
{
instance.eventDictionary[eventName] = action;
}
else
{
instance.eventDictionary.Add(eventName, action);
}
}
//在不需要监听的时候停止监听
public static void StopListening(string eventName)
{
if (instance.eventDictionary.ContainsKey(eventName))
{
instance.eventDictionary.Remove(eventName);
}
}
//触发某个事件
public static void TriggerEvent(string eventName, ArrayList obj)
{
if (instance.eventDictionary.ContainsKey(eventName))
{
instance.eventDictionary[eventName].Invoke(obj);
}
}
}
<file_sep>/Assets/Scripts/Weapon/GhWeaponRingOnce.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GhWeaponRingOnce : IWeapon
{
Vector3 vec = new Vector3(0, 0, 1);
public override void Fire()
{
GhRing();
}
void GhRing()
{
for (int j = 0; j < 18; j++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(20 * j, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 5;
bulletInfo.Fire();
}
vec = Quaternion.AngleAxis(10 , Vector3.up) * vec;
}
}
<file_sep>/Assets/Scripts/Bullet/IBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Bullet即是子弹类,在里面的update函数里表示移动逻辑,如直线,波形,折现型。
public class IBullet : MonoBehaviour,IShootAble
{
public float speed = 10;
//延迟
public float delay = 0;
public IShootAble shooter;
public GameObject target;
public bool shootAble;
public MyTimer timer=new MyTimer();
string bulletName;
protected Camera camera;
protected float cameraMoveSpeed;
public void Start()
{
Init();
}
public virtual void Init()
{
camera = Camera.main;
cameraMoveSpeed = BarrageGame.Instance.GetMoveSpeed();
}
[Header("回收的开关,如果这颗子弹是手工弹幕中的子弹且弹幕出现了异常,请不要勾选。如无异常,则说明系统自动纠错,请无视此处。")]
//在回收时判断是否有父物体,当有父物体时基本上说明是手工弹幕,则阻止回收
public bool recycleAble=true;
public IWeapon weapon;
public string GetName()
{
return gameObject.name;
}
public void Fire()
{
shootAble = true;
}
// Update is called once per frame
public void Update()
{
if(shootAble)
transform.Translate( Vector3.forward* speed * Time.deltaTime);
transform.Translate(new Vector3(0,0,1) * cameraMoveSpeed * Time.deltaTime, Space.World);
if (OutOfScreen()&&recycleAble)
{
Recycle();
}
}
public virtual void Recycle()
{
if (GetObj().transform.parent==null)
{
if (recycleAble == true)
{
BulletPool.Put(gameObject);
gameObject.SetActive(false);
}
}
}
public bool OutOfScreen()
{
if (Mathf.Abs(transform.position.x) > 25 || Mathf.Abs(transform.position.z - camera.transform.position.z) > 15)
{
return true;
}
return false;
}
public GameObject GetObj()
{
return gameObject;
}
public Vector3 GetPos()
{
return transform.position;
}
public string GetBulletName()
{
return bulletName;
}
public void Die()
{
Recycle();
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun12.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//球形3波36
public class ZZWeaponShotgun12 : IWeapon
{
//射击方法,需要重写
public override void Fire()
{
ZZShotgun();
}
void ZZShotgun()
{
IBullet[] bullets = new IBullet[40];
Vector3 vec = new Vector3(0, 0, 1);
for (int i = 0; i <36; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(10 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.Fire();
bullets[i] = bulletInfo;
bulletInfo.speed = 5.0f;
}
}
}
<file_sep>/Assets/Scripts/Weapon/YkWeaponSingle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YKWeaponSingle : IWeapon
{
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun14.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//圆形三波36
public class ZZWeaponShotgun14 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
private const int V = 3;
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
for (int i = 0; i < 4; i++)
{
Vector3 vec = new Vector3(0,0,1);
Vector3 flowerVec = new Vector3(0, 0, 1);
flowerVec = Quaternion.AngleAxis(Random.Range(0,36)*10, Vector3.up) * vec;
for (int j=0;j< 7; j++)
{
GameObject bullet;
bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(10 * j, Vector3.up) * flowerVec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 1.5f;
bulletInfo.Fire();
}
yield return new WaitForSeconds(2.0f);
}
}
}
<file_sep>/Assets/Resources/Missle1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Missle1 : Missle
{
// Update is called once per frame
void Update()
{
if (target == null)
{
if (IEnemy.enemys.Count > 0)
{
target = BarrageUtil.RandomFecthFromList<IEnemy>(IEnemy.enemys).gameObject;
}
base.Update();
return;
}
transform.forward = Vector3.Slerp(transform.forward, target.transform.position - transform.position, 0.5f / Vector3.Distance(transform.position, target.transform.position));
transform.position += transform.forward * speed * Time.deltaTime;
}
public void OnBecameInvisible()
{
}
}
<file_sep>/Assets/Scripts/SceneState/StageSystem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StageSystem:IGameSystem
{
public string levelName="";
public int level = 1;
public StageSystem(BarrageGame PBDGame) : base(PBDGame)
{
}
}
<file_sep>/Assets/Scripts/Interface/Character/Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : IPlayer
{
public override void Fire()
{
weapon.Fire(transform.forward);
}
}
<file_sep>/Assets/PlayBgm.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayBgm : MonoBehaviour
{
public AudioClip[] clips;
public int index = 0;
bool playCompleted=false;
AudioSource ad;
private void Start()
{
ad = GetComponent<AudioSource>();
ad.clip = clips[index];
ad.Play();
}
// Update is called once per frame
void Update()
{
if (ad.isPlaying)
{
return;
}
else
{
if (index < clips.Length - 1)
{
index++;
ad.clip = clips[index];
ad.Play();
}
else
{
index = 0;
}
}
}
}
<file_sep>/Assets/Scripts/zzy/BallBullet1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBullet1 : IBullet
{
public float time=18;
public float rTimer=0;
// Update is called once per frame
void Update()
{
rTimer += Time.deltaTime;
if (rTimer >= time)
{
rTimer = 0;
recycleAble = true;
Recycle();
}
base.Update();
transform.Rotate(Vector3.up * 20 * Time.deltaTime);
}
public override void Recycle()
{
base.Recycle();
rTimer = 0;
}
}
<file_sep>/Assets/Scripts/Tools/BulletPool.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletPool : MonoBehaviour
{
public static List<GameObject> bullets=new List<GameObject>();
//创建一个字典,维护子弹名和数量,决定子弹可存放对象池数量上限。否则当一次性创建大量子弹会放入大量子弹到对象池中,占用大量内存
public static Dictionary<string, int> bulletsAndCount = new Dictionary<string, int>();
public static GameObject Get(string name)
{
for(int i = 0; i < bullets.Count; i++)
{
if(bullets[i].name==name||bullets[i].name==name + "(Clone)")
{
GameObject obj = bullets[i];
obj.SetActive(true);
bullets.RemoveAt(i);
//Debug.Log("对象池取出:"+obj.name);
bulletsAndCount[obj.name]--;
return obj;
}
}
return null;
}
public static void Put(GameObject obj)
{
if (bulletsAndCount.ContainsKey(obj.name))
{
if( bulletsAndCount[obj.name] < BarrageGame.BulletPoolCount)
{
//如果字典中有这种子弹,且数量低于上限,子弹数加1
bulletsAndCount[obj.name]++;
bullets.Add(obj);
}
else
{
Destroy(obj);
}
}
else
{
bullets.Add(obj);
bulletsAndCount.Add(obj.name, 1);
}
}
}
<file_sep>/Assets/Scripts/Interface/Character/IEnemy.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public abstract class IEnemy : ICharacter
{
public static List<IEnemy> enemys=new List<IEnemy>();
public GameObject player;
public int maxHp = 1;
//不能一出现就攻击,需要等待一会
public float waitTime=3;
[Header("存活期间能攻击的次数,-1为无限次")]
public int count=-1;
[Header("探测玩家的范围。当玩家与这个敌距离小于这个值时敌人开始移动并攻击,只比较z轴方向的距离")]
public float range = 30;
public MyTimer waitTimer = new MyTimer();
IMovement movement;
Camera mainCamera;
bool closeCamera = false;
// Start is called before the first frame update
public override void Init()
{
movement = GetComponent<IMovement>();
base.Init();
status.MaxHp = maxHp;
status.hp = maxHp;
player = GameObject.FindGameObjectWithTag("Player");
weapon.count = count;
weapon.target = player;
mainCamera = Camera.main;
}
private void Update()
{
if (GetDistance() < range&&closeCamera==false)
{
closeCamera = true;
ReadyAttack();
}
if (closeCamera)
{
waitTimer.Tick();
if (waitTimer.state != MyTimer.STATE.finished)
return;
weapon.Tick();
}
}
public void ReadyAttack()
{
movement.CanMove();
waitTimer.Start(waitTime);
enemys.Add(this);
}
public void OnTriggerEnter(Collider other)
{
if (other.tag == "PlayerBullet")
{
status.GetDamage(1);
other.GetComponent<IBullet>().Recycle();
if (status.isDied())
{
Die();
}
}
}
public void Die()
{
GameObject explosion = BulletUtil.LoadBullet("ExplosionParticle");
explosion.transform.position = transform.position;
explosion.GetComponent<IBullet>().Fire();
DropPoint();
weapon = null;
waitTimer = null;
enemys.Remove(this);
if (tag == "Boss")
{
GUIManager.ShowView("GameWinUI", Vector3.zero);
Time.timeScale = 0.1f;
}
Destroy(gameObject);
}
public float GetDistance()
{
return Mathf.Abs(transform.position.z- mainCamera.transform.position.z);
}
public void DropPoint()
{
//随机掉落点数
int count = UnityEngine.Random.Range(-2, 5);
if (count <= 0)
return;
GameObject bullet=BulletUtil.LoadBullet(UnityEngine.Random.Range(0,2)==0?"ppt":"hpt");
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = this;
bullet.transform.position = transform.position;
bulletInfo.Fire();
}
}
<file_sep>/Assets/Scripts/Bullet/ExplosionBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionBullet : IBullet
{
public float explosionTime = 2;
[Header("散弹数量")]
public float count = 3;
public void OnEnable()
{
weapon = WeaponUtil.CreateWeapon("GhWeaponShotgun");
weapon.shooter = this;
weapon.target = GameObject.FindGameObjectWithTag("Player");
timer.Start(explosionTime);
}
// Update is called once per frame
void Update()
{
if (shootAble)
transform.Translate(Vector3.forward * speed * Time.deltaTime);
timer.Tick();
if (timer.state == MyTimer.STATE.finished)
{
weapon.Fire();
timer.Stop();
}
}
public void OnBecameInvisible()
{
Recycle();
}
}
<file_sep>/Assets/Scripts/Mgr/GUIManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public static class GUIManager {
static List<GameObject> DialougueUIs = new List<GameObject>();
/// <summary>
/// 是否直接显示,ui名称,父物体名
/// </summary>
/// <param name="ps,"></param>
/// <returns></returns>
public static GameObject ShowView(bool show,params object[] ps)
{
string path = "UI/Prefab/" + ps[0].ToString();
GameObject tmp = (GameObject)Resources.Load(path, typeof(GameObject));
GameObject parent =( ps.Length>1?GameObject.Find(ps[1].ToString()) :GameObject.Find("Canvas"));
GameObject IGO= GameObject.Instantiate(tmp,new Vector3(-1000,-1000,0),Quaternion.identity);
IGO.transform.SetParent(parent.transform);
//根据是否有第三个参数决定显示位置
if(show)
IGO.transform.localPosition =Vector3.zero;//一开始不显示
IGO.transform.localScale = new Vector3(1, 1, 1);
//Debug.Log("实例化UI-" + ps[0].ToString() + "至" + ps[1].ToString());
return IGO;
}
public static GameObject ShowView(string name,Vector3 position)
{
string path = "UI/" + name;
GameObject tmp = (GameObject)Resources.Load(path, typeof(GameObject));
GameObject parent =GameObject.Find("Canvas");
GameObject IGO = GameObject.Instantiate(tmp,position,parent.transform.rotation,parent.transform);
//IGO.transform.SetParent(parent.transform);
IGO.transform.localScale = new Vector3(1, 1, 1);
return IGO;
}
}
<file_sep>/Assets/Scripts/Bullet/PointBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PointBullet : IBullet
{
public float t = 0;
MyTimer recycleTimer = new MyTimer();
public override void Init()
{
base.Init();
speed = 4;
recycleTimer.Start(10);
}
// Update is called once per frame
void Update()
{
recycleTimer.Tick();
if (shootAble)
{
t += Time.deltaTime;
transform.Translate(new Vector3(0,0,1) * speed * Time.deltaTime);
speed -= 0.0098f * t;
}
transform.Translate(new Vector3(0, 0, 1) * cameraMoveSpeed * Time.deltaTime, Space.World);
if (recycleTimer.state==MyTimer.STATE.finished)
{
Recycle();
}
}
public override void Recycle()
{
base.Recycle();
t = 0;
speed = 4;
recycleTimer.Restart();
}
}
<file_sep>/Assets/Scripts/Weapon/PlayerWeapon/PlayerWeapon2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerWeapon2 : IWeapon
{
//射击方法,需要重写
public override void Fire()
{
Vector3 forward = new Vector3(0, 0, 1);
Vector3 vec = new Vector3(0, 0, 1);
for (int i = -1; i < 2; i++)
{
if (i == 0)
{
continue;
}
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(30 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.delay = 0;
bulletInfo.Fire();
}
for (int i = -1; i < 2; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos() + new Vector3(i * 0.5f, 0, 0);
bullet.transform.forward = new Vector3(0, 0, 1);
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.Fire();
}
}
}
<file_sep>/Assets/Scripts/Weapon/IWeapon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Iweapon理解为武器,也可以理解为弹幕形式。一个weapon类代表一种发射方法,如散弹,圆形弹,旋涡弹。在weapon类实现弹幕。
public abstract class IWeapon
{
public IShootAble shooter;
public GameObject target;
public MyTimer timer = new MyTimer();
public float attackSpeed = 0.5f;
[Header("发射次数")]
public int count=-1;
[Header("特殊值参数")]
public int Integer;
private int curCount;
public GameObject GetObj() {
return shooter.GetObj();
}
public IWeapon()
{
Init();
}
public virtual void Init()
{
curCount = count;
timer.Start(1 / attackSpeed);
}
public void SetAttackSpeed(float attackSpeed)
{
this.attackSpeed = attackSpeed;
timer.Start(1 / attackSpeed);
}
//射击方法,需要重写
public virtual void Fire()
{
Vector3 vec;
if (target == null)
{
vec = shooter.GetObj().transform.forward;
}
else
{
vec = GetVec();
}
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = vec;
bullet.GetComponent<IBullet>().shooter = shooter ;
if(target)
bullet.GetComponent<IBullet>().target = target;
bullet.GetComponent<IBullet>().Fire();
}
public void Tick()
{
if (curCount == count)
{
Fire();
count--;
}
timer.Tick();
if (timer.state == MyTimer.STATE.finished&&count!=0)
{
Fire();
if (count != -1)
{
count--;
}
timer.Restart();
}
}
public virtual void Fire(Vector3 vec)
{
//从对象池里取出子弹
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
//将取出的子弹的位置设置为射击者的位置
bullet.transform.position = shooter.GetPos();
//使子弹的forward向量等于射击者到目标的向量,也就是说让子弹正面朝向目标
bullet.transform.forward = vec;
//将子弹的攻击者设置为射击者
bullet.GetComponent<IBullet>().shooter = shooter;
//调用子弹的发射函数。可在子弹的发射函数中设置发射延迟或者启动一个新的函数或协程。
bullet.GetComponent<IBullet>().Fire();
}
//获取射击者到目标的向量。
public Vector3 GetVec()
{
Vector3 vec;
if (target.tag == "Player")
{
vec= target.transform.position+new Vector3(0,0,1) - shooter.GetPos();
}
vec = target.transform.position - shooter.GetPos();
return vec;
}
}
<file_sep>/Assets/Scripts/Weapon/GhWeaponShotgun1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GhWeaponShotgun1 : GhWeaponShotgun
{
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ShotGun1());
}
IEnumerator ShotGun1()
{
for (int i = 0; i < 3; i++)
{
base.Fire();
yield return new WaitForSeconds(0.3f);
}
}
}
<file_sep>/Assets/Scripts/Movement/IMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IMovement:MonoBehaviour
{
public enum LastStrategy
{
idle,//原地不动
random,//左右随机动
loop
}
[Header("走到最后一个路径点后是否使用策略,如不则直接销毁")]
public bool useStrategy;
[Header("使用的策略,只有开启useStrategy才有效")]
public LastStrategy strategy;
[Header("路径点数组")]
public GameObject[] targets;
public float speed = 2.5f;
float cameraMoveSpeed;
public bool moveAble;
public bool moveToEnd = false;
public int index;//当前接近的路径点的Id
MyTimer randomTimer=new MyTimer();
Vector3 randomPos;
Camera camera;
Vector3 vec;
private void Start()
{
camera = Camera.main;
cameraMoveSpeed = BarrageGame.Instance.GetMoveSpeed();
}
private void Update()
{
if (moveAble)
{
transform.parent.Translate(new Vector3(0, 0, cameraMoveSpeed) * Time.deltaTime, Space.World);
Move();
}
if (moveToEnd)
{
if (strategy == LastStrategy.idle)
{
transform.parent.Translate(new Vector3(0, 0, cameraMoveSpeed) * Time.deltaTime, Space.World);
return;
}
if(strategy == LastStrategy.random)
{
randomTimer.Tick();
if (randomTimer.state == MyTimer.STATE.finished)
{
randomPos = GetRandomPos();
randomTimer.Start(Random.Range(2, 6));
}
transform.Translate((new Vector3(0, 0, cameraMoveSpeed)+(randomPos - transform.position).normalized*speed)*Time.deltaTime, Space.World);
}
}
}
//每帧调用
public void Move()
{
transform.Translate( GetVec() * speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, targets[index].transform.position) < 0.5f)
{
if (index == targets.Length - 1)
{
if (useStrategy==true&& strategy == LastStrategy.loop)
{
index = 0;
return;
}
moveToEnd = true;
moveAble = false;
if (useStrategy == false)
{
Debug.Log("awsl");
Die();
}
else
{
if (strategy == LastStrategy.random)
{
randomTimer.Start(3);
}
}
}
else
{
index++;
}
}
}
public Vector3 GetVec()
{
vec = Vector3.Slerp(vec, (targets[index].transform.position - transform.position).normalized, 0.3f);
return vec.normalized;
}
public Vector3 GetRandomPos()
{
int x = Random.Range(-15, 15);
int z = Random.Range(4, 10);
randomPos = new Vector3(camera.transform.position.x,0,camera.transform.position.z) + new Vector3(x, 0, z);
return randomPos;
}
public void CanMove()
{
moveAble = true;
}
public void Die()
{
Destroy(transform.parent.gameObject);
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//圆形三波36
public class ZZWeaponShotgun1 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
private const int V = 3;
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
for (int i = 0; i>=0; i++)
{
Vector3 vec = new Vector3(0,0,1);
int tj = Random.Range(-8, 20);
for (int j = -8; j < 28; j++)
{
GameObject bullet;
if (i % 2 == 1)
{
bullet = BulletUtil.LoadBullet("红边圆");
}
else
{
bullet = BulletUtil.LoadBullet("蓝边圆");
}
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(10 * j, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 1.0f;
bulletInfo.Fire();
}
Vector3 flowerVec = new Vector3(0, 0, 1);
flowerVec = Quaternion.AngleAxis(Random.Range(0,36)*10, Vector3.up) * vec;
for (int j=0;j< 7; j++)
{
GameObject bullet;
if (i % 2 == 1)
{
bullet = BulletUtil.LoadBullet("红花");
}
else
{
bullet = BulletUtil.LoadBullet("蓝花");
}
bullet.transform.position = shooter.GetPos() + new Vector3(0, 0.3f, 0); ;
bullet.transform.forward = Quaternion.AngleAxis(10 * j, Vector3.up) * flowerVec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 1.0f;
bulletInfo.Fire();
}
yield return new WaitForSeconds(3.5f);
}
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun3.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//散弹三波3
public class ZZWeaponShotgun3 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
private const int V = 3;
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
Vector3 vec = new Vector3(0, 0, -1);
Quaternion leftrota = Quaternion.AngleAxis(-10, Vector3.up);
Quaternion rightrota = Quaternion.AngleAxis(10, Vector3.up);
for (int i = 0; i < 3; i++)
{
for (int j = 9; j < 14; j++)
{
switch(j){
case 9:
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.Fire();
break;
case 10:
GameObject bullet2 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet2.transform.position = shooter.GetPos();
bullet2.transform.forward = leftrota * vec;
IBullet bulletInfo2 = bullet2.GetComponent<IBullet>();
bulletInfo2.shooter = shooter;
bulletInfo2.Fire();
break;
case 11:
GameObject bullet3 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet3.transform.position = shooter.GetPos();
bullet3.transform.forward = rightrota * vec;
IBullet bulletInfo3 = bullet3.GetComponent<IBullet>();
bulletInfo3.shooter = shooter;
bulletInfo3.Fire();
break;
case 12:
GameObject bullet4 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet4.transform.position = shooter.GetPos();
bullet4.transform.forward = rightrota*rightrota * vec;
IBullet bulletInfo4 = bullet4.GetComponent<IBullet>();
bulletInfo4.shooter = shooter;
bulletInfo4.Fire();
break;
case 13:
GameObject bullet5 = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet5.transform.position = shooter.GetPos();
bullet5.transform.forward = leftrota*leftrota * vec;
IBullet bulletInfo5 = bullet5.GetComponent<IBullet>();
bulletInfo5.shooter = shooter;
bulletInfo5.Fire();
break;
}
}
yield return new WaitForSeconds(0.5f);
}
}
////朝某个方向
//public override void Fire(Vector3 vec)
//{
// //从对象池里取出子弹
// GameObject bullet = BulletUtil.LoadBullet(shooter.bulletName);
// //将取出的子弹的位置设置为射击者的位置
// bullet.transform.position = shooter.GetPos();
// //使子弹的forward向量等于射击者到目标的向量,也就是说让子弹正面朝向目标
// bullet.transform.forward = vec;
// //将子弹的攻击者设置为射击者
// bullet.GetComponent<IBullet>().shooter = shooter;
// //调用子弹的发射函数。可在子弹的发射函数中设置发射延迟或者启动一个新的函数或协程。
// bullet.GetComponent<IBullet>().Fire();
//}
}
<file_sep>/Assets/Scripts/Mgr/WeaponUtil.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponUtil
{
public static IWeapon CreateWeapon(string weaponName)
{
IWeapon weapon = (IWeapon)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(weaponName, false);
return weapon;
}
}
<file_sep>/Assets/Scripts/Mgr/ResourceManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 加载资源
/// </summary>
public class ResourceManager
{
#region 单例
private static ResourceManager _Instance = null;
public static ResourceManager Instance
{
get
{
if (_Instance == null)
{
_Instance = new ResourceManager();
}
return _Instance;
}
}
#endregion
private string path = "Prefabs/";
}
<file_sep>/Assets/Scripts/Player/PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public List<GameObject> bullets=new List<GameObject>();
public List<IEnemy> enemys=new List<IEnemy>();
public float speed;
Camera camera;
public float cameraMoveSpeed;
//人妖状态之间切换
public float bMonster;
// Start is called before the first frame update
void Start()
{
camera = Camera.main;
cameraMoveSpeed = BarrageGame.Instance.GetMoveSpeed();
}
// Update is called once per frame
void Update()
{
//debug查看bullet对象池
bullets = BulletPool.bullets;
enemys = IEnemy.enemys;
float h = (Input.GetKey(KeyCode.D) ? 1 : 0) - (Input.GetKey(KeyCode.A) ? 1 : 0);
float v = (Input.GetKey(KeyCode.W) ? 1 : 0) - (Input.GetKey(KeyCode.S) ? 1 : 0);
//边界控制
if (transform.position.x >= 21&&h>0 || transform.position.x <= -21 && h < 0 )
{
h = 0;
}
if( (transform.position.z - camera.transform.position.z) >= 12 && v > 0
|| (transform.position.z - camera.transform.position.z) <= -12 && v < 0)
{
v = 0;
}
transform.Translate(new Vector3(h, 0, v) * speed * Time.deltaTime);
transform.Translate(transform.forward * cameraMoveSpeed * Time.deltaTime, Space.World);
}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun8.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//球形8波36
public class ZZWeaponShotgun8 : IWeapon
{
public override void Init()
{
attackSpeed = 0.1f;
base.Init();
}
private const int V = 3;
//射击方法,需要重写
public override void Fire()
{
BarrageGame.Instance.getBarrageUtil().StartCoroutine(ZZShotgun());
}
IEnumerator ZZShotgun()
{
for (int i = 0; i < 8; i++)
{
Vector3 vec = new Vector3(0, 0, 1);
for (int j = -8; j < 28; j++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(10 * j, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.Fire();
}
yield return new WaitForSeconds(0.5f);
}
}
////朝某个方向
//public override void Fire(Vector3 vec)
//{
// //从对象池里取出子弹
// GameObject bullet = BulletUtil.LoadBullet(shooter.bulletName);
// //将取出的子弹的位置设置为射击者的位置
// bullet.transform.position = shooter.GetPos();
// //使子弹的forward向量等于射击者到目标的向量,也就是说让子弹正面朝向目标
// bullet.transform.forward = vec;
// //将子弹的攻击者设置为射击者
// bullet.GetComponent<IBullet>().shooter = shooter;
// //调用子弹的发射函数。可在子弹的发射函数中设置发射延迟或者启动一个新的函数或协程。
// bullet.GetComponent<IBullet>().Fire();
//}
}
<file_sep>/Assets/Scripts/zzy/ZZWeaponShotgun15.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//缓慢boss收缩圆
public class ZZWeaponShotgun15 : IWeapon
{
int shootCount = 0;
Vector3 vec1 = new Vector3(0, 0, 1);
//射击方法,需要重写
public override void Fire()
{
ZZShotgun();
}
void ZZShotgun()
{
IBullet[] bullets = new IBullet[40];
Vector3 vec = new Vector3(0, 0, 1);
for (int i = 0; i <18; i++)
{
GameObject bullet = BulletUtil.LoadBullet(shooter.GetBulletName());
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(20 * i, Vector3.up) * vec;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.Fire();
bullets[i] = bulletInfo;
bulletInfo.speed = 5.0f;
}
if (count % 2 == 0)
{
for (int j = 0; j < 18; j++)
{
GameObject bullet = BulletUtil.LoadBullet("米粒");
bullet.transform.position = shooter.GetPos();
bullet.transform.forward = Quaternion.AngleAxis(20 * j, Vector3.up) * vec1;
IBullet bulletInfo = bullet.GetComponent<IBullet>();
bulletInfo.shooter = shooter;
bulletInfo.speed = 5;
bulletInfo.Fire();
}
vec1 = Quaternion.AngleAxis(10, Vector3.up) * vec1;
}
}
}
<file_sep>/Assets/Scripts/Bullet/ExplosionParticle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionParticle : IBullet
{
public void Fire()
{
GetComponent<ParticleSystem>().Play();
}
}
<file_sep>/Assets/Scripts/Tools/MyTimer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyTimer
{
public enum STATE
{
idle,
running,
finished
}
public STATE state=STATE.idle;
public float duration = 0.1f;
public float elapsed = 0;
public bool isExtending;
public void Tick()
{
if(state==STATE.running)
{
elapsed += Time.deltaTime;
if (elapsed > duration)
{
state = STATE.finished;
}
}
}
public void Start(float duration)
{
state = STATE.running;
elapsed = 0;
this.duration = duration;
}
public void Restart()
{
Start(duration);
}
public void Stop()
{
state = STATE.idle;
elapsed = 0;
}
}
|
32dfe8fd18e8a89eaf37693a6471708a496efe28
|
[
"Markdown",
"C#"
] | 59 |
C#
|
Carrage1121/Barrage
|
2d7a671b48c18ea8a2d5d6b21e16341ce1a10827
|
fcb3a9b0d7988f2f7c70a006025cb8b40a1fdffb
|
refs/heads/master
|
<repo_name>mliq/Version3.x<file_sep>/RsyncOSXver30/profiles.swift
//
// profiles.swift
// RsyncOSX
//
// Created by <NAME> on 17/10/2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
// Protocol for reporting file errors
protocol FileError: class {
func fileerror(errorstr:String)
}
final class profiles {
// Delegate for reporting file error if any to main view
weak var error_delegate: FileError?
// Set the string to absolute string path
private var filePath:String?
// profiles root - returns the root of profiles
private var profileRoot : String? {
get {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let docuDir = paths.firstObject as! String
let profilePath = docuDir + "/Rsync/" + SharingManagerConfiguration.sharedInstance.getMacSerialNumber()
return profilePath
}
}
// Function for returning directorys in path as array of URLs
private func getDirectorysURLs () -> [URL] {
var array:[URL] = [URL]()
if let filePath = self.profileRoot {
if let fileURLs = self.getfileURLs(path: filePath) {
for i in 0 ..< fileURLs.count {
if fileURLs[i].hasDirectoryPath {
array.append(fileURLs[i])
}
}
return array
}
}
return array
}
// Function for returning profiles as array of Strings
func getDirectorysStrings()-> [String] {
var array:[String] = [String]()
if let filePath = self.profileRoot {
if let fileURLs = self.getfileURLs(path: filePath) {
for i in 0 ..< fileURLs.count {
if fileURLs[i].hasDirectoryPath {
let path = fileURLs[i].pathComponents
let i = path.count
array.append(path[i-1])
}
}
return array
}
}
return array
}
// Function for creating new profile directory
func createProfile(profileName:String) {
let fileManager = FileManager.default
if let path = self.profileRoot {
let profileDirectory = path + "/" + profileName
if (fileManager.fileExists(atPath: profileDirectory) == false) {
do {
try fileManager.createDirectory(atPath: profileDirectory, withIntermediateDirectories: true, attributes: nil)}
catch let e {
let error = e as NSError
self.error(errorstr: error.description)
}
}
}
}
// Function for deleting profile
// if let path = URL.init(string: profileDirectory) {
func deleteProfile(profileName:String) {
let fileManager = FileManager.default
if let path = self.profileRoot {
let profileDirectory = path + "/" + profileName
if (fileManager.fileExists(atPath: profileDirectory) == true) {
let answer = Alerts.dialogOKCancel("Delete profile: " + profileName + "?", text: "Cancel or OK")
if (answer){
do {
try fileManager.removeItem(atPath: profileDirectory)}
catch let e {
let error = e as NSError
self.error(errorstr: error.description)
}
}
}
}
}
// Func that creates directory if not created
func createDirectory() {
let fileManager = FileManager.default
if let path = self.filePath {
if (fileManager.fileExists(atPath: path) == false) {
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
} catch let e {
let error = e as NSError
self.error(errorstr: error.description)
}
}
}
}
// Function for setting fileURLs for a given path
private func getfileURLs (path:String) -> [URL]? {
let fileManager = FileManager.default
if let filepath = URL.init(string: path) {
do {
let files = try fileManager.contentsOfDirectory(at: filepath, includingPropertiesForKeys: nil , options: .skipsHiddenFiles)
return files
} catch let e {
let error = e as NSError
self.error(errorstr: error.description)
return nil
}
}
return nil
}
// Private func for propagating any file error to main view
private func error(errorstr:String) {
if let pvc = SharingManagerConfiguration.sharedInstance.ViewObjectMain {
self.error_delegate = pvc as? ViewControllertabMain
self.error_delegate?.fileerror(errorstr: errorstr)
}
}
init (path:String?) {
self.filePath = path
}
}
<file_sep>/RsyncOSXver30/rsyncProcess.swift
//
// rsyncProcess.swift
//
// Created by <NAME> on 08/02/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
final class rsyncProcess {
// Number of calculated files to be copied
var calculatedNumberOfFiles:Int = 0
// Variable for reference to NSTask
var ProcessReference:Process?
// Message to calling class
weak var process_update:UpdateProgress?
// If process is created in NSOperation
var inOperation:Bool?
// Creating obcect from tabMain
var tabMain:Bool?
// Observer
weak var observationCenter: NSObjectProtocol?
// Command to be executed, normally rsync
var command:String?
func executeProcess (_ arg: [String], output:outputProcess){
// Task
let task = Process()
// Setting the correct path for rsync
// If self.command != nil other command than rsync to be executed
// Other commands are either ssh or scp (from CopyFiles)
if let command = self.command {
task.launchPath = command
} else {
task.launchPath = SharingManagerConfiguration.sharedInstance.setRsyncCommand()
}
task.arguments = arg
// Pipe for reading output from NSTask
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
// Observator for reading data from pipe
// Observer is removed when Process terminates
self.observationCenter = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: nil, queue: nil)
{ notification -> Void in
let data = outHandle.availableData
if data.count > 0 {
if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
// Add files to be copied, the output.addString takes care of
// splitting the output
output.addLine(str as String)
self.calculatedNumberOfFiles = output.getOutputCount()
if (self.inOperation == false) {
// Send message about files
self.process_update?.FileHandler()
}
}
outHandle.waitForDataInBackgroundAndNotify()
}
}
// Observator Process termination
// Observer is removed when Process terminates
self.observationCenter = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification, object: task, queue: nil)
{ notification -> Void in
// Collectiong numbers in output
// Forcing a --stats in dryrun which produces a summarized detail about
// files and bytes. getNumbers collects that info and store the result in the
// object.
output.getNumbers()
if (self.inOperation == false) {
// Send message about process termination
self.process_update?.ProcessTermination()
} else {
// We are in Scheduled operation and must finalize the job
// e.g logging date and stuff like that
SharingManagerConfiguration.sharedInstance.operation?.finalizeScheduledJob(output: output)
// After logging is done set reference to object = nil
SharingManagerConfiguration.sharedInstance.operation = nil
}
NotificationCenter.default.removeObserver(self.observationCenter as Any)
}
self.ProcessReference = task
task.launch()
}
func getProcess() -> Process? {
return self.ProcessReference
}
func abortProcess() {
if self.ProcessReference != nil {
self.ProcessReference!.terminate()
}
}
init (operation: Bool, tabMain:Bool, command : String?) {
self.inOperation = operation
self.tabMain = tabMain
self.command = command
// If process object is created from a scheduled task do not set delegates.
if (self.inOperation == false) {
// Check where to return the delegate call
// Either in ViewControllertabMain or ViewControllerCopyFiles
switch tabMain {
case true:
if let pvc = SharingManagerConfiguration.sharedInstance.ViewObjectMain as? ViewControllertabMain {
self.process_update = pvc
}
case false:
if let pvc = SharingManagerConfiguration.sharedInstance.CopyObjectMain as? ViewControllerCopyFiles {
self.process_update = pvc
}
}
}
}
}
<file_sep>/RsyncOSXver30/configuration.swift
//
// configuration.swift
// Rsync
//
// Created by <NAME> on 08/02/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
struct configuration {
var hiddenID : Int
var task: String
var localCatalog: String
var offsiteCatalog: String
var offsiteUsername: String
var batch: String
var rsync: String
var dryrun: String
var parameter1: String
var parameter2: String
var parameter3: String
var parameter4: String
var parameter5: String
var parameter6: String
var offsiteServer: String
var backupID: String
var dateRun: String?
// parameters choosed by user
var parameter8: String?
var parameter9: String?
var parameter10: String?
var parameter11: String?
var parameter12: String?
var parameter13: String?
var parameter14: String?
var rsyncdaemon: Int?
var sshport: Int?
init(dictionary: NSDictionary) {
self.hiddenID = dictionary.object(forKey: "hiddenID") as! Int
self.task = dictionary.object(forKey: "task") as! String
self.localCatalog = dictionary.object(forKey: "localCatalog") as! String
self.offsiteCatalog = dictionary.object(forKey: "offsiteCatalog") as! String
self.offsiteUsername = dictionary.object(forKey: "offsiteUsername") as! String
self.batch = dictionary.object(forKey: "batch") as! String
self.rsync = dictionary.object(forKey: "rsync") as! String
self.dryrun = dictionary.object(forKey: "dryrun") as! String
self.parameter1 = dictionary.object(forKey: "parameter1") as! String
self.parameter2 = dictionary.object(forKey: "parameter2") as! String
self.parameter3 = dictionary.object(forKey: "parameter3") as! String
self.parameter4 = dictionary.object(forKey: "parameter4") as! String
self.parameter5 = dictionary.object(forKey: "parameter5") as! String
self.parameter6 = dictionary.object(forKey: "parameter6") as! String
self.offsiteServer = dictionary.object(forKey: "offsiteServer") as! String
self.backupID = dictionary.object(forKey: "backupID") as! String
if (dictionary.object(forKey: "dateRun") != nil){
self.dateRun = dictionary.object(forKey: "dateRun") as? String
} else {
self.dateRun = " "
}
if (dictionary.object(forKey: "parameter8") != nil){
self.parameter8 = dictionary.object(forKey: "parameter8") as? String
}
if (dictionary.object(forKey: "parameter9") != nil){
self.parameter9 = dictionary.object(forKey: "parameter9") as? String
}
if (dictionary.object(forKey: "parameter10") != nil){
self.parameter10 = dictionary.object(forKey: "parameter10") as? String
}
if (dictionary.object(forKey: "parameter11") != nil){
self.parameter11 = dictionary.object(forKey: "parameter11") as? String
}
if (dictionary.object(forKey: "parameter12") != nil){
self.parameter12 = dictionary.object(forKey: "parameter12") as? String
}
if (dictionary.object(forKey: "parameter13") != nil){
self.parameter13 = dictionary.object(forKey: "parameter13") as? String
}
if (dictionary.object(forKey: "parameter14") != nil){
self.parameter14 = dictionary.object(forKey: "parameter14") as? String
}
if (dictionary.object(forKey: "rsyncdaemon") != nil){
self.rsyncdaemon = dictionary.object(forKey: "rsyncdaemon") as? Int
}
if (dictionary.object(forKey: "sshport") != nil){
self.sshport = dictionary.object(forKey: "sshport") as? Int
}
}
}
<file_sep>/RsyncOSXver30/scpProcessArguments.swift
//
// scpNSTaskArguments.swift
// RsyncOSX
//
// Created by <NAME> on 27/06/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
enum enumscpTasks {
case create
case scpFind
case copy
}
final class scpProcessArguments {
// File to read
private var file:String?
// Array for storing arguments
private var args = [String]()
// String for display
private var argDisplay:String?
// command string
private var command:String?
// config, is set in init
private var config:configuration?
// Output of NSTask
private var output = [String]()
// Getting arguments
func getArgs() -> [String]? {
return self.args
}
// Getting command
func getCommand() -> String? {
return self.command
}
// Getting the command to displya in view
func getcommandDisplay() -> String? {
return self.argDisplay
}
// Reading content of txt file into an Array of String
func getSearchfile () -> [String]? {
var stringArray:[String]?
if let file = self.file {
let fileContent = try? String(contentsOfFile: file, encoding: String.Encoding.utf8)
if fileContent != nil {
stringArray = fileContent!.components(separatedBy: CharacterSet.newlines)
}
}
return stringArray
}
// Set parameters for SCP for .create og .plist files
private func setSCParguments(_ postfix:String) {
var postfix2:String?
// For SCP copy history.plist from server to local store
if (self.config!.sshport != nil) {
self.args.append("-P")
self.args.append(String(self.config!.sshport!))
}
self.args.append("-B")
self.args.append("-p")
self.args.append("-q")
self.args.append("-o")
self.args.append("ConnectTimeout=5")
if (self.config!.offsiteServer.isEmpty) {
self.args.append(self.config!.offsiteCatalog + "." + postfix)
postfix2 = "localhost" + "_" + postfix
} else {
let offsiteArguments = self.config!.offsiteUsername + "@" + self.config!.offsiteServer + ":" + self.config!.offsiteCatalog + "." + postfix
self.args.append(offsiteArguments)
postfix2 = self.config!.offsiteServer + "_" + postfix
}
self.args.append(self.config!.localCatalog + "." + postfix2!)
self.command = "/usr/bin/scp"
self.file = self.config!.localCatalog + "." + postfix2!
}
init (task : enumscpTasks, config : configuration, remoteFile : String?, localCatalog : String?, drynrun:Bool?) {
// Initialize the argument array
if self.args.count > 0 {
self.args.removeAll()
}
// Set config
self.config = config
switch (task) {
case .create:
// ssh [email protected] "cd offsiteCatalog; find . -print | cat > .files.txt"
if (config.sshport != nil) {
self.args.append("-p")
self.args.append(String(config.sshport!))
}
if (!config.offsiteServer.isEmpty) {
self.args.append(config.offsiteUsername + "@" + config.offsiteServer)
self.command = "/usr/bin/ssh"
} else {
self.args.append("-c")
self.command = "/bin/bash"
}
let str:String = "cd " + config.offsiteCatalog + "; find . -print | cat > .files.txt "
self.args.append(str)
case .scpFind:
// For SCP copy result of find . -name from server to local store
self.setSCParguments("files.txt")
case .copy:
// Drop the two first characeters ("./") as result from the find . -name
let remote_with_whitespace:String = String(remoteFile!.characters.dropFirst(2))
// Replace remote for white spaces
let whitespace:String = "\\ "
let remote = remote_with_whitespace.replacingOccurrences(of: " ", with: whitespace)
let local:String = localCatalog!
if (config.sshport != nil) {
self.args.append("-e")
self.args.append("ssh -p " + String(config.sshport!))
} else {
self.args.append("-e")
self.args.append("ssh")
}
self.args.append("--archive")
self.args.append("--verbose")
// If copy over network compress files
if (!config.offsiteServer.isEmpty) {
self.args.append("--compress")
}
// Set dryrun or not
if (drynrun != nil) {
if (drynrun == true) {
self.args.append("--dry-run")
}
}
if (config.offsiteServer.isEmpty) {
self.args.append(config.offsiteCatalog + remote)
} else {
let offsiteArguments = config.offsiteUsername + "@" + config.offsiteServer + ":" + config.offsiteCatalog + remote
self.args.append(offsiteArguments)
}
self.args.append(local)
// Set command to Process /usr/bin/rysnc or /usr/local/bin/rsync
// or other set by userconfiguration
self.command = SharingManagerConfiguration.sharedInstance.setRsyncCommand()
// Prepare the display version of arguments
self.argDisplay = self.command! + " "
for i in 0 ..< self.args.count {
self.argDisplay = self.argDisplay! + self.args[i] + " "
}
}
}
}
<file_sep>/RsyncOSXver30/RsyncParameters.swift
//
// RsyncParameters.swift
// RsyncOSX
//
// Created by <NAME> on 03/10/2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
final class RsyncParameters {
// Tuple for rsync argument and value
typealias argument = (String , Int)
// Static initial arguments, DO NOT change order
private let rsyncArguments:[argument] = [
("user",1),
("delete",0),
("--stats",0),
("--backup",0),
("--backup-dir",1),
("--exclude-from",1),
("--include-from",1),
("--files-from",1),
("--max-size",1),
("--suffix",1)]
// Preselected parameters for storing a backup of deleted or changed files before
// rsync synchronises the directories
private let backupString = ["--backup","--backup-dir=../backup"]
private let suffixString = ["--suffix=_`date +'%Y-%m-%d.%H.%M'`"]
private let suffixString2 = ["--suffix=_$(date +%Y-%m-%d.%H.%M)"]
/// Function for getting string for backup parameters
/// - parameter none: none
/// - return : array of String
func getBackupString() -> [String] {
return self.backupString
}
/// Function for getting string for suffix parameter
/// - parameter none: none
/// - return : array of String
func getSuffixString() -> [String] {
return self.suffixString
}
/// Function for getting string for alternative suffix parameter
/// - parameter none: none
/// - return : array of String
func getSuffixString2() -> [String] {
return self.suffixString2
}
/// Function for getting for rsync arguments to use in ComboBoxes in ViewControllerRsyncParameters
/// - parameter none: none
/// - return : array of String
func getComboBoxValues() -> [String] {
var values = Array<String>()
for i in 0 ..< self.rsyncArguments.count {
values.append(self.rsyncArguments[i].0)
}
return values
}
// Computes the raw argument for rsync to save in configuration
/// Function for computing the raw argument for rsync to save in configuration
/// - parameter indexComboBox: index of selected ComboBox
/// - parameter value: the value of rsync parameter
/// - return: array of String
func getRsyncParameter (indexComboBox:Int, value:String?) -> String {
guard indexComboBox < self.rsyncArguments.count else {
return ""
}
switch (self.rsyncArguments[indexComboBox].1) {
case 0:
// Predefined rsync argument from combobox
// Must check if DELETE is selected
if self.rsyncArguments[indexComboBox].0 == self.rsyncArguments[1].0 {
return ""
} else {
return self.rsyncArguments[indexComboBox].0
}
case 1:
// If value == nil value is deleted and return empty string
guard value != nil else {
return ""
}
if self.rsyncArguments[indexComboBox].0 != self.rsyncArguments[0].0 {
return self.rsyncArguments[indexComboBox].0 + "=" + value!
} else {
// Userselected argument and value
return value!
}
default:
return ""
}
}
// Returns Int value of argument
private func indexValue (_ argument:String) -> Int {
var index:Int = -1
loop : for i in 0 ..< self.rsyncArguments.count {
if argument == self.rsyncArguments[i].0 {
index = i
break loop
}
}
return index
}
// Split an Rsync argument into argument and value
private func split (_ str:String) -> [String] {
let argument:String?
let value:String?
var split = str.components(separatedBy: "=")
argument = String(split[0])
if split.count > 1 {
value = String(split[1])
} else {
value = argument
}
return [argument!,value!]
}
// Get the rsync parameter to store in the configuration.
// Function computes which parameters are arguments only
// e.g --backup, or --suffix=value.
func getdisplayValue (_ parameter:String) -> String {
let splitstr:[String] = self.split(parameter)
if splitstr.count > 1 {
let argument = splitstr[0]
let value = splitstr[1]
if (argument != value && self.indexValue(argument) >= 0) {
return value
} else {
if self.indexValue(splitstr[0]) >= 0 {
return "\"" + argument + "\" " + "no arguments"
} else {
if (argument != value) {
return argument + "=" + value
} else {
return value
}
}
}
} else {
return ""
}
}
/// Function returns value of rsync argument to set the corrospending
/// value in combobox when rsync parameters are presented
/// - parameter parameter : Stringvalue of parameter
/// - returns : index of parameter
func getvalueCombobox (_ parameter:String) -> Int {
let splitstr:[String] = self.split(parameter)
if splitstr.count > 1 {
let argument = splitstr[0]
let value = splitstr[1]
if (argument != value && self.indexValue(argument) >= 0) {
return self.indexValue(argument)
} else {
if self.indexValue(splitstr[0]) >= 0 {
return self.indexValue(argument)
} else {
return 0
}
}
}
return 0
}
/// Function calculates all userparameters (param8 - param14)
/// - parameter index: index of selected row
/// - returns: array of values with keys "indexComboBox" and "rsyncParameter", array always holding 7 records
func setValuesViewDidLoad(index:Int) -> [NSMutableDictionary] {
var configurations:[configuration] = SharingManagerConfiguration.sharedInstance.getConfigurations()
var values = [NSMutableDictionary]()
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 8))
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 9))
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 10))
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 11))
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 12))
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 13))
values.append(self.getParamAsDictionary(config: configurations[index],parameter: 14))
// Return values
return values
}
// Function for creating NSMutableDictionary of stored rsync parameters
private func getParamAsDictionary(config:configuration, parameter:Int) -> NSMutableDictionary {
let dict = NSMutableDictionary()
var param:String?
switch parameter {
case 8:
param = config.parameter8
case 9:
param = config.parameter9
case 10:
param = config.parameter10
case 11:
param = config.parameter11
case 12:
param = config.parameter12
case 13:
param = config.parameter13
case 14:
param = config.parameter14
default:
param = nil
}
if (param != nil) {
dict.setObject(self.getvalueCombobox(param!), forKey: "indexComboBox" as NSCopying)
dict.setObject(self.getdisplayValue(param!), forKey: "rsyncParameter" as NSCopying)
return dict
} else {
dict.setObject(0, forKey: "indexComboBox" as NSCopying)
dict.setObject("", forKey: "rsyncParameter" as NSCopying)
return dict
}
}
}
|
5c74b0db985964b5f56997cec6967ed94b03648f
|
[
"Swift"
] | 5 |
Swift
|
mliq/Version3.x
|
0630759fb8dd2833d37cd96661df93f7dceb5b4f
|
1b8bf80c53ef5d700a8589c5273aa63812f7deb0
|
refs/heads/main
|
<file_sep><?php
namespace App\Controllers;
class Dashboard extends BaseController
{
public function index()
{
return view('Dashboard/Layout/Header');
return view('Dashboard/Layout/Navbar');
return view('Dashboard/db_main');
return view('Dashboard/Layout/Footer');
}
public function db_main()
{
echo view('Dashboard/Layout/Header');
echo view('Dashboard/Layout/Navbar');
echo view('Dashboard/db_main');
echo view('Dashboard/Layout/Footer');
}
public function db_cif_main()
{
echo view('Dashboard/Layout/Header');
echo view('Dashboard/Layout/Navbar');
echo view('Dashboard/CIF/db_cif_main');
echo view('Dashboard/Layout/Footer');
}
public function db_tabungan_main()
{
echo view('Dashboard/Layout/Header');
echo view('Dashboard/Layout/Navbar');
echo view('Dashboard/Tabungan/db_tabungan_main');
echo view('Dashboard/Layout/Footer');
}
public function db_murabahah_main()
{
echo view('Dashboard/Layout/Header');
echo view('Dashboard/Layout/Navbar');
echo view('Dashboard/Murabahah/db_murabahah_main');
echo view('Dashboard/Layout/Footer');
}
public function db_mudharabah_main()
{
echo view('Dashboard/Layout/Header');
echo view('Dashboard/Layout/Navbar');
echo view('Dashboard/Mudharabah/db_mudharabah_main');
echo view('Dashboard/Layout/Footer');
}
}<file_sep></body>
<!-- Bootstrap core JS-->
<!--<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- Core theme JS-->
<script src="<?php echo base_url('components/dashboard/js/sidebar_wrapper.js'); ?>"></script>
</html><file_sep><div class="container-fluid">
<!-- Content -->
<h1>Customer Identification File</h1>
<div class="cif-btn-ext">
<button class="btn btn-primary" data-toggle="modal" data-target="#cifREG">Buat CIF Baru</button>
</div>
<!-- Untuk data tabel -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="<?= base_url('components/dashboard/js/jquery.dataTables.min.js'); ?>"></script>
<script>
$(document).ready(function() {
$('#tbcif').DataTable();
} );
</script>
<script src="<?= base_url('components/dashboard/js/dataTables.bootstrap4.min.js'); ?>"></script>
<div class="cif-content">
<table class="table table-striped table-bordered" id="tbcif">
<thead class="thead-light">
<tr>
<th scope="col">No CIF</th>
<th scope="col">No Kartu Identitas</th>
<th scope="col">Nama Sesuai Identitas</th>
<th scope="col">Cabang</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kadal</td>
<td>Kadal</td>
<td>Kadal</td>
<td>Kadal</td>
<td>Kadal</td>
</tr>
<tr>
<td>Puma</td>
<td>Puma</td>
<td>Puma</td>
<td>Puma</td>
<td>Puma</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
<tr>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
<td>Tubruk</td>
</tr>
</tbody>
</table>
</div>
<!-- Modal Box for CIF Registration-->
<div class="modal fade" id="cifREG" tabindex="-1" aria-labelledby="kotakRegistrasiCIF" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="kotakRegistrasiCIF">Registrasi CIF</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="cards">Kartu Identitas</label>
<select class="custom-select" id="cards">
<option selected>Pilih salah satu</option>
<option value="1">KTP</option>
<option value="2">Kartu Pelajar</option>
</select>
</div>
<div class="form-group">
<label for="uid">Nomor Identitas</label>
<input type="text" class="form-control" placeholder="Nomor Kartu Identitas" id="uid">
</div>
<div class="form-group">
<label for="name">Nama Lengkap</label>
<input type="text" class="form-control" placeholder="Nama sesuai identitas" id="name">
</div>
<div class="form-group">
<label for="pob">Tempat Lahir</label>
<input type="text" class="form-control" placeholder="Tempat Lahir" id="pob">
</div>
<div class="form-group">
<label for="dob">Tanggal Lahir</label>
<input type="date" class="form-control" placeholder="Tanggal Lahir" placeholder="Tanggal Lahir sesuai identitas" id="dob">
</div>
<div class="form-group">
<label for="gen">Jenis Kelamin</label>
<div class="custom-control custom-radio">
<input type="radio" id="man" name="gender" class="custom-control-input">
<label class="custom-control-label" for="man" >Laki-Laki</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="girl" name="gender" class="custom-control-input">
<label class="custom-control-label" for="girl" >Perempuan</label>
</div>
</div>
<div class="form-group">
<label for="addr">Alamat Lengkap</label>
<input type="text" class="form-control" placeholder="Alamat sesuai identitas" id="addr">
</div>
<div class="form-group">
<label for="statusNikah">Status Pernikahan</label>
<select class="custom-select" id="statusNikah">
<option selected>Pilih salah satu</option>
<option value="1">Menikah</option>
<option value="2">Belum Menikah</option>
<option value="3">Duda</option>
<option value="4">Janda</option>
</select>
</div>
<div class="form-group">
<label for="national">Kewarganegaraan</label>
<input type="text" class="form-control" placeholder="Kewarganegaraan" id="national">
</div>
<div class="form-group">
<div class="custom-control custom-radio">
<input type="radio" id="yes" name="resident" class="custom-control-input">
<label class="custom-control-label" for="yes">Ya</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="no" name="resident" class="custom-control-input">
<label class="custom-control-label" for="no">Tidak</label>
</div>
</div>
<div class="form-group">
<label for="address">Alamat</label>
<input type="text" class="form-control" placeholder="Alamat sesuai identitas">
</div>
<div class="form-group">
<label for="rtrw">RT/RW</label>
<input type="text" id="rtrw" class="form-control" placeholder="Contoh : 01/02">
</div>
<div class="form-group">
<label for="subdistrict">Desa/Kelurahan</label>
<input type="text" class="form-control" id="subdistrict">
</div>
<div class="form-group">
<label for="district">Kecamatan</label>
<input type="text" class="form-control" id="district">
</div>
<div class="form-group">
<label for="province">Provinsi</label>
<input type="text" class="form-control" id="province">
</div>
<div class="form-group">
<label for="city">Kabupaten/Kota</label>
<input type="text" class="form-control" id="city">
</div>
<div class="form-group">
<label for="psscode">Kode pos</label>
<input type="text" class="form-control" id="psscode">
</div>
<div class="form-group">
<label for="phregion">Kode Area Telepon</label>
<input type="text" class="form-control" id="phregion">
</div>
<div class="form-group">
<label for="homeph">No. Telp. Rumah</label>
<input type="text" class="form-control" id="homeph">
</div>
<div class="form-group">
<label for="portph">No. Telp. Selular</label>
<input type="text" class="form-control" id="portph">
</div>
<div class="form-group">
<label for="mail">Email</label>
<input type="email" class="form-control" id="mail">
</div>
<div class="form-group">
<label for="jobtype">Jenis Pekerjaan</label>
<select class="custom-select" id="jobtype">
<option selected>Pilih salah satu</option>
<option value="1">Tidak bekerja</option>
<option value="2">PNS</option>
<option value="3">Swasta</option>
<option value="4">Tentara</option>
</select>
</div>
<div class="form-group">
<label for="scfund">Sumber Dana</label>
<select class="custom-select" id="scfund">
<option selected>Pilih salah satu</option>
<option value="1">Bisnis</option>
<option value="1">Lainnya</option>
</select>
</div>
<div class="form-group">
<label for="fdmonthly">Penghasilan Per bulan</label>
<select class="custom-select" id="fdmonthly">
<option selected>Pilih salah satu</option>
<option value="1">Kurang dari 50 Juta</option>
<option value="2">50 Juta sampai 100 Juta</option>
<option value="3">100 Juta sampai 250 Juta</option>
<option value="4">250 Juta sampai 500 Juta</option>
<option value="5">Lebih dari 500 Juta</option>
</select>
</div>
<div class="form-group">
<label for="frmonthly">Maksimal Frekuensi Transaksi per Hari</label>
<select class="custom-select">
<option selected>Pilih salah satu</option>
<option value="1">Kurang dari 10 kali</option>
<option value="1">10 kali sampai 50 kali</option>
<option value="1">lebih dari 50 kali</option>
</select>
</div>
<div class="form-group">
<label for="accoffice">Account Officer</label>
<input type="text" class="form-control" readonly value="Admin">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
<button type="button" class="btn btn-primary">Simpan</button>
</div>
</div>
</div>
</div>
<!-- END of CIF REG BOX -->
<!-- END Content -->
</div> <!-- For Container Fluid or Content -->
</div> <!-- For Frame -->
</div><!-- For All Body -->
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Syariah Banking System | Welcome </title>
<!-- Favicon-->
<!--<link rel="icon" type="image/x-icon" href="assets/favicon.ico" />-->
<!-- Core theme CSS (includes Bootstrap)-->
<link href="<?php echo base_url('components/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet" />
<link href="<?php echo base_url('components/dashboard/css/style.css'); ?>" rel="stylesheet" />
</head>
<body class="bg-light"><file_sep><!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<link rel="stylesheet" href="<?php echo base_url('components/bootstrap/css/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?php echo base_url('components/login_page/style.css'); ?>">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="card kotak-login">
<div class="card-body">
<h5 class="card-title">Syariah Banking System</h5>
<p>Please login to continue</p>
<form>
<!-- Form Input Username-->
<label for="user" class="form-label">Username</label>
<input type="text" name="username" class="form-control" id="user" placeholder="Username">
<!-- Form Input Password-->
<label for="pass" class="form-label">Password</label>
<input type="<PASSWORD>" name="password" class="form-control" id="pass" placeholder="<PASSWORD>">
<!-- Tombol Login -->
<input type="submit" name="login" class="btn btn-primary btn-login" value="Login">
</form>
</div>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html>
|
8d74dfd8ab594c4bfc625cfafdf5e2892ff56371
|
[
"PHP"
] | 5 |
PHP
|
vernika64/syariahbanking
|
aafca41b5e795b56ba69a601c821107e3819105b
|
f9db3ecaa63ccef230c0b89b6844b3b330879c77
|
refs/heads/master
|
<file_sep>/**
*
* @authors <NAME> (<EMAIL>)
* @date 2016-08-05 15:40:46
* @version $Id$
*/
'use strict'
import React from 'react';
import ReactDOM from 'react-dom';
import Component from './component.jsx';
<file_sep>
import React from 'react';
import './bootstrap.css';
import './basic.css';
export default class Button extends React.Component {
render(){
return (
<div className="container">
<a className="btn btn-default">Button</a>
</div>
);
}
}
|
33cbfd85255ef7b9149577af30c10a152b0f42b9
|
[
"JavaScript"
] | 2 |
JavaScript
|
TP-ISP/templateSet
|
90847eea3acfbed49a585b969d47603ab7486ea4
|
cada5c1ced3482a93b17cda904c05dc7e30ebe3c
|
refs/heads/master
|
<file_sep># WebServiceRHB
RHB Webservice - Spring Boot application for CRUD operation for a person
- Sample springboot app with JPA and mysql
- docker-compose.yml and Dockerfile provided
Docker Command:
- Make changes to application.yml, application.properties and Dockerfile accordingly
- Create network: docker network create springboot-mysql-docker
- Create db container: docker container run --name mysqldb --network springboot-mysql-docker -e MYSQL_ROOT_PASSWORD=<PASSWORD> -e MYSQL_DATABASE=rhb_db -e MYSQL_USER=sa -e MYSQL_PASSWORD=<PASSWORD> -d mysql:8
- Build springboot app image: docker build . -t rhb-service-app-api
- Run as container with network, app and db: docker container run --network springboot-mysql-docker --name rhb-service-app-container -p 8080:8080 --link mysqldb:mysql -d rhb-service-app-api
- list of container: docker container ls
- list of network: docker network ls
- list of images: docker images
- view log: docker logs *container*
- accessing db: docker exec -it mysqldb bash
- start container: docker container start *container*
- stop container: docker container stop *container*
- check docker-compose format: docker-compose config
- run docker-compose: docker-compose up<file_sep>package com.webservice.model;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.Email;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* @author Hafiz
* @version 0.01
*/
@Entity
@Table(name = "t_persons")
public class Persons {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name="uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)", nullable=false)
@JsonIgnore
private UUID id;
@NotNull(message = "Username cannot be null")
@Column(name="username")
private String username;
@NotNull(message = "Firstname cannot be null")
@Column(name="firstname")
private String firstName;
@NotNull(message = "Lastname cannot be null")
@Column(name="lastname")
private String lastName;
@NotNull(message = "Email cannot be null")
@Email(message = "Email should be valid")
@Column(name = "email", unique = true)
private String email;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>FROM openjdk:8
ADD target/rhb-service-app-api.jar rhb-service-app-api.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "rhb-service-app-api.jar"]
|
c2129722ba2a2f0d5864ca0506bac44fbb3055a3
|
[
"Markdown",
"Java",
"Dockerfile"
] | 3 |
Markdown
|
HafizAboy/WebServiceRHB
|
12c8ba0ea0146f78c438df473f42997bc768f6b5
|
633c6554637048ea35d22560c64f684aaff5e482
|
refs/heads/master
|
<repo_name>enriquedcs/PyStructure<file_sep>/Algorithm/Prime_Number.py
# Prime Number
def IsPrime(nums):
if nums <= 0:
return False
if (nums%2) == 0:
print ("Number is not Prime: ")
else:
print("Number is Prime: ")
return nums
nums = 0
print(IsPrime(nums))<file_sep>/Algorithm/fibobacci.py
def fibonacci(num):
sum1 = 0
L = [0, 1]
for i in range(1, num):
L.append(L[-1] + L[-2])
if L[-1] > 4000000:
return False
else:
print(L)
for i in range(1, num):
if L[i] % 2 == 0:
sum1 = L[i] + sum1
return sum1
num = 33
print(fibonacci(num))
<file_sep>/Algorithm/Anagram.py
# Anagram problem
def anagram(str1, str2):
str1 = str1.replace(' ', ' ').lower()
str2 = str2.replace(' ', ' ').lower()
return sorted(str1) == sorted(str2)
str1 = "God"
str2 = "dog"
print(anagram(str1,str2))
<file_sep>/Algorithm/Bubble_sort.py
# Bubble Sort Algorithm
def bubble_sort(arr):
for n in range(len(arr)-1, 0,-1):
for k in range(n):
if arr[k]>arr[k+1]:
temp = arr[k]
arr[k] = arr[k+1]
arr[k+1] = temp
return arr
arr = [1,10,12,48,52,6,3,14]
print(bubble_sort(arr))
arr.sort()
print(arr)
|
22c18ce056d125df8a2d6cf20bd69f90f8f8e93f
|
[
"Python"
] | 4 |
Python
|
enriquedcs/PyStructure
|
20c9c554ffe32fd2097eff7b7df74e56859ec621
|
04be667e50dab2008967673be43fabb61d2d275c
|
refs/heads/master
|
<repo_name>mosuke5/terraform-provider-mosuke5<file_sep>/resource_server.go
package main
import (
"fmt"
"log"
"os"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceServer() *schema.Resource {
return &schema.Resource{
Create: resourceServerCreate,
Read: resourceServerRead,
Update: resourceServerUpdate,
Delete: resourceServerDelete,
Schema: map[string]*schema.Schema{
"file": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"address": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceServerCreate(d *schema.ResourceData, m interface{}) error {
file, err := os.OpenFile(d.Get("file").(string), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatal(err)
return err
}
defer file.Close()
output, err := createServerConfigContents(d)
if err != nil {
return err
}
fmt.Fprintln(file, output)
id := d.Get("file").(string)
d.SetId(id)
return nil
}
func resourceServerRead(d *schema.ResourceData, m interface{}) error {
return nil
}
func resourceServerUpdate(d *schema.ResourceData, m interface{}) error {
file, err := os.OpenFile(d.Get("file").(string), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatal(err)
return err
}
defer file.Close()
output, err := createServerConfigContents(d)
if err != nil {
return err
}
fmt.Fprintln(file, output)
return nil
}
func resourceServerDelete(d *schema.ResourceData, m interface{}) error {
if err := os.Remove(d.Get("file").(string)); err != nil {
fmt.Println(err)
return err
}
return nil
}
func createServerConfigContents(d *schema.ResourceData) (string, error) {
name := d.Get("name").(string)
description := d.Get("description").(string)
address := d.Get("address").(string)
output := "name: \"" + name + "\"\n" +
"description: \"" + description + "\"\n" +
"address: \"" + address + "\""
return output, nil
}
<file_sep>/resource_database.go
package main
import (
"fmt"
"log"
"os"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceDatabase() *schema.Resource {
return &schema.Resource{
Create: resourceDatabaseCreate,
Read: resourceDatabaseRead,
Update: resourceDatabaseUpdate,
Delete: resourceDatabaseDelete,
Schema: map[string]*schema.Schema{
"file": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"address": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceDatabaseCreate(d *schema.ResourceData, m interface{}) error {
file, err := os.OpenFile(d.Get("file").(string), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatal(err)
return err
}
defer file.Close()
output, err := createDatabaseConfigContents(d)
if err != nil {
return err
}
fmt.Fprintln(file, output)
id := d.Get("file").(string)
d.SetId(id)
return nil
}
func resourceDatabaseRead(d *schema.ResourceData, m interface{}) error {
return nil
}
func resourceDatabaseUpdate(d *schema.ResourceData, m interface{}) error {
file, err := os.OpenFile(d.Get("file").(string), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatal(err)
return err
}
defer file.Close()
output, err := createDatabaseConfigContents(d)
if err != nil {
return err
}
fmt.Fprintln(file, output)
return nil
}
func resourceDatabaseDelete(d *schema.ResourceData, m interface{}) error {
if err := os.Remove(d.Get("file").(string)); err != nil {
fmt.Println(err)
return err
}
return nil
}
func createDatabaseConfigContents(d *schema.ResourceData) (string, error) {
name := d.Get("name").(string)
description := d.Get("description").(string)
address := d.Get("address").(string)
output := "name: \"" + name + "\"\n" +
"description: \"" + description + "\"\n" +
"address: \"" + address + "\""
return output, nil
}
<file_sep>/provider.go
package main
import (
"github.com/hashicorp/terraform/helper/schema"
)
// Provider settings
func Provider() *schema.Provider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"config_file": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
ResourcesMap: map[string]*schema.Resource{
"example_server": resourceServer(),
"example_database": resourceDatabase(),
},
}
}
|
a4e399cfec99e50d147f490375862286acd0103b
|
[
"Go"
] | 3 |
Go
|
mosuke5/terraform-provider-mosuke5
|
c99d8a8fca707eabe2baf11fa8db36e1730a046c
|
5ded1c4422abaf12548182816568413ead2a61a8
|
refs/heads/master
|
<file_sep>import { Url, URL } from 'url';
export class Highlight {
filename: string | undefined;
title: string | undefined;
postUrl: Url | undefined;
date: Date | undefined;
permalink: string | undefined;
video: string | undefined;
excerpt: string | undefined;
constructor(initObject: any) {
this.filename = initObject.filename || '';
this.title = initObject.title || '';
this.postUrl = initObject.postUrl || new URL('https://google.com');
this.date = initObject.date || new Date();
this.permalink = initObject.permalink || '';
this.video = initObject.video || '';
this.excerpt = initObject.excerpt || '';
}
}<file_sep>import start from './src/AutoPuller';
import { Logger } from "tslog";
require('dotenv').config();
const log: Logger = new Logger({ name: "Index Logger" });
log.info(`Starting the auto puller`);
start();
<file_sep>import { Highlight } from './highlight';
import { Octokit } from '@octokit/rest';
import _ from 'lodash';
import { Logger } from "tslog";
import { ReposGetContentResponseData, RequestParameters } from '@octokit/types';
const log: Logger = new Logger({ name: "SendFilesToGitHub" });
export async function SendNewFilesToGitHubRepo(
options: any,
highlightsFromWebsite: Highlight[]
) {
const octokit = new Octokit({
auth: `${process.env.GITHUB_ACCESS_TOKEN}`
});
let existingRepoPosts: ReposGetContentResponseData[] = [];
try {
const postsRequest = await octokit.repos.getContent({
owner: options.owner,
repo: options.repo,
path: `_posts/mnufc`,
ref: `heads/master`
});
existingRepoPosts = postsRequest.data as unknown as ReposGetContentResponseData[];
log.info(`The number of posts we already have ${existingRepoPosts}`);
} catch (e) {
log.error(`Error in getting content from mnufc repo`, e);
//error occured because we can't get the old posts
}
//We don't want to recreate old files so we will diff the two arrays
let newPosts = _.differenceWith<Highlight, ReposGetContentResponseData>(
highlightsFromWebsite,
existingRepoPosts,
function checkPreviousPostVsNew(mnufcValue: Highlight, githubObject: ReposGetContentResponseData) {
log.debug(`match the existing files for a diff from the old ${mnufcValue.filename} to the new ${githubObject.name}. Do they match ${mnufcValue.filename === githubObject.name}`);
return mnufcValue.filename === githubObject.name;
}
);
log.info(`New posts length ${newPosts.length}`);
const refParams = {
owner: options.owner,
repo: options.repo,
ref: `heads/master`
};
const masterData = await octokit.git.getRef(refParams);
const masterSha = masterData.data.object.sha;
for (let post of newPosts) {
const postText = `---
title: ${post.title}
date: ${post.date}
permalink: ${post.permalink}
excerpt: ${post.excerpt}
${options.postHeader}
${post.video}`;
const newBranchName = `refs/heads/${_.snakeCase(post.title)}`;
// Send each new file to the github triggering jekyll rebuild/deploy to the site
try {
await octokit.git.createRef({
owner: options.owner,
repo: options.repo,
ref: newBranchName,
sha: masterSha
});
} catch (e) {
log.prettyError(e);
}
const createNewFileContents = await octokit.repos.createOrUpdateFileContents({
owner: options.owner,
repo: options.repo,
path: `_posts/mnufc/${post.filename}`,
message: post.title || 'Default MNUFC hightlight',
content: Buffer.from(postText).toString('base64'),
branch: newBranchName
});
log.info("Creating a new file contents", createNewFileContents.data.commit.sha);
const pullParams = {
owner: options.owner,
repo: options.repo,
title: post.title || `Default MNUFC Highlight`,
base: `master`,
body: `${post.excerpt}`,
head: newBranchName
};
const result = await octokit.pulls.create(pullParams);
log.info("Creating the new PR", result.url);
}
return newPosts;
}<file_sep># auto-pull-req-new-mnufc
## Why
* :heart: - MNUFC
* Automated updates to my blog (in the MNUFC update)
* Scraping content without manual intervention
## How
* Using basic node web scraping techniques to grab the content from the mnufc page
* Get the repo/subfolder for the MNUFC posts from mutmatt.github.io
* Diff what exists with what is new
* Create new html posts using the highlight videos
* Using the github api create new files and create a PR to the mutmatt.github.io repo
## Dev
This is a node/typescript based project.
* `Git Clone`
* `npm install`
* `touch .env`
* `echo "GITHUB_ACCESS_TOKEN=[Your Personal Access Token]" > .env`
* [Can be created/found here](https://github.com/settings/tokens)
* `npm run start`
* That will run `ts-node index` (this could be run manually if you _really_ want to).
This will run the entirety of the #How section and create any PRs to the mutmatt.github.io repo.
## Testing
Ha
## How this functions
This app is run via GitHub Actions.
There are two trigger methods
1) pushing to this repo
1) cron at 03:00 and 15:00 UTC
<file_sep>import rp from 'request-promise-native';
import _ from 'lodash';
import * as cheerio from 'cheerio';
import Promises from 'bluebird';
import { Highlight } from './highlight';
import { SendNewFilesToGitHubRepo } from './SendFilesToGitHub';
import { Logger } from "tslog";
const log: Logger = new Logger({ name: "AutoPuller" });
/**
*
*/
async function start() {
const options = {
highlightHost: 'https://www.mnufc.com',
owner: 'Mutmatt',
repo: 'mutmatt.github.io',
postHeader: `author: <NAME> (ME)
layout: post
tags:
- mnufc
- soccer
- auto-post
hidden: true
---`,
iframeTemplate: `<div class='soccer-video-wrapper'>
<iframe class='soccer-video' width='100%' height='auto' frameborder='0' allowfullscreen src='https://www.mnufc.com/iframe-video?brightcove_id={replaceMe}&brightcove_player_id=default&brightcove_account_id=5534894110001'></iframe>
</div>`
};
let highlightArray: Highlight[] = [];
let videoPromises: any[] = [];
const cheerioHighlightBody = await rp({
uri: `${options.highlightHost}/videos/match-highlights`,
transform: function(body: any) {
return cheerio.load(body);
}
});
log.info(`Loaded the match highlights`);
//crawl the page and get all the nodes for each highlight video
_.map(cheerioHighlightBody('.views-row .node'), function mapTheNodes(
node: any
) {
const highlightHtml = cheerioHighlightBody(node).find('.node-title a');
//Remove unneeded parts of the title that make things look weird
const title = highlightHtml
.text()
.replace('HIGHLIGHTS: ', '')
.replace(/\'/gi, '');
const titleWithoutEndDate = title.replace(/\|.*/gi, '').replace('.', '');
const titleWOEDAndSpaces = titleWithoutEndDate
.replace(/\s/gi, '-')
.replace(/\-$/, '');
const postUrl = highlightHtml.attr('href');
const date = new Date(
cheerioHighlightBody(node)
.find('.timestamp')
.text()
.replace(/\s\(.*\)/gi, '')
);
let filename =
date.getFullYear() +
'-' +
(date.getMonth() + 1) +
'-' +
date.getDate() +
'-' +
titleWOEDAndSpaces +
'.md';
let permalink = _.snakeCase(filename);
let localHighlight = new Highlight({
filename: filename,
title: title,
postUrl: postUrl,
date: date,
permalink: permalink
});
log.debug(`Found total highlight`, localHighlight);
highlightArray.push(localHighlight);
});
log.info(`Loaded all highlights into the array length[${highlightArray.length}]`);
//After we get all the nodes for the videos we need to fetch the post page for the video url itself
_.forEach(highlightArray, function forEachHighlight(highlight) {
const vidProm = rp({
uri: options.highlightHost + highlight.postUrl,
transform: function transformTheBody(body) {
return cheerio.load(body);
}
});
videoPromises.push(vidProm);
});
//after all the videos come back lets add it to the highlight array and then send it to GH
const videos = await Promises.all(videoPromises);
for (var i = 0; i < highlightArray.length; i++) {
let videoHtml = options.iframeTemplate.replace(
'{replaceMe}',
videos[i]('video').attr('data-video-id')
);
let excerptText = videos[i]('.node .field-type-text-long p').text();
highlightArray[i].video = videoHtml;
highlightArray[i].excerpt = excerptText;
log.debug(`Looping the videos and setting the video and excerpt [${excerptText}], video [${videoHtml}]`);
}
const newPosts = await SendNewFilesToGitHubRepo(
options,
highlightArray
);
return newPosts;
}
export default start;
|
93170a418390c2ab72b90e51331d5eb142c9a283
|
[
"Markdown",
"TypeScript"
] | 5 |
TypeScript
|
Mutmatt/auto-pull-req-new-mnufc
|
2074a96e6039d077fe7cca89bfe4a6a933422b14
|
0e26ff4a2aa33e302b942515b449133804d62496
|
refs/heads/master
|
<repo_name>Mpompili/ARKit_Practice<file_sep>/ARGame/ARGame/ViewController.swift
//
// ViewController.swift
// ARGame
//
// Created by <NAME> on 6/24/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import ARKit
import Each
class ViewController: UIViewController {
@IBOutlet weak var timer: UILabel!
var counter = Each(1).seconds
var killCount = 0
@IBOutlet weak var sceneView: ARSCNView!
let config = ARWorldTrackingConfiguration()
override func viewDidLoad() {
super.viewDidLoad()
// self.sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
self.sceneView.session.run(config)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
self.sceneView.addGestureRecognizer(tapGestureRecognizer)
self.sceneView.autoenablesDefaultLighting = true
// 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.
}
func addNode() {
let slenderScene = SCNScene(named: "art.scnassets/SlenderMan_Model.scn")
let slenderNode = slenderScene?.rootNode.childNode(withName: "Slenderman", recursively: false)
slenderNode?.position = SCNVector3(rNums(firstNum: -4, secondNum: 4),0, rNums(firstNum: 4, secondNum: -4))
slenderNode?.pivot = SCNMatrix4Rotate((slenderNode?.pivot)!, Float.pi, 0, 1, 0)
let constraint = SCNLookAtConstraint(target: sceneView.pointOfView)
constraint.isGimbalLockEnabled = true
slenderNode?.constraints = [constraint]
let originPoint = SCNVector3(0,0,0)
let moveToOrigin = SCNAction.move(to: originPoint, duration: Double(rNums(firstNum: 4, secondNum: 6)))
slenderNode?.runAction(moveToOrigin, completionHandler: {
DispatchQueue.main.async {
self.timer.text = "you lose"
self.counter.stop()
}
})
self.sceneView.scene.rootNode.addChildNode(slenderNode!)
}
@objc func handleTap(sender: UITapGestureRecognizer) {
let sceneViewTappedOn = sender.view as! SCNView
let touchCoordinates = sender.location(in: sceneViewTappedOn)
let hitTest = sceneViewTappedOn.hitTest(touchCoordinates)
var gettingHit = false
if hitTest.isEmpty {
print("didn't hit anything")
} else {
if self.timer.text != "you lose" {
let results = hitTest.first!
let node = results.node
if gettingHit == false {
SCNTransaction.begin()
gettingHit = true
self.animateNode(node: node)
SCNTransaction.completionBlock = {
self.killCount += 1
self.timer.text = String(self.killCount)
SCNTransaction.cancelPreviousPerformRequests(withTarget: self)
node.removeFromParentNode()
self.addNode()
}
SCNTransaction.commit()
gettingHit = false
}
}
print("touched obj")
}
}
func animateMovement(node: SCNNode) {
let moving = CABasicAnimation(keyPath: "position")
moving.fromValue = SCNVector3(rNums(firstNum: -6, secondNum: 6),0, rNums(firstNum: 6, secondNum: -6))
moving.toValue = SCNVector3(0, 0, 0)
moving.duration = 6
node.addAnimation(moving, forKey: "position")
}
func animateNode(node: SCNNode) {
let disappear = CABasicAnimation(keyPath: "opacity")
disappear.fromValue = node.presentation.opacity
disappear.toValue = 0
disappear.duration = 0.5
node.addAnimation(disappear, forKey: "opacity")
}
@IBOutlet weak var playBttn: UIButton!
func restoreTimer() {
self.killCount = 0
self.timer.text = String(self.killCount)
}
@IBAction func reset(_ sender: Any) {
self.counter.stop()
self.restoreTimer()
self.playBttn.isEnabled = true
}
@IBAction func play(_ sender: Any) {
sceneView.scene.rootNode.enumerateChildNodes { (node, _) in
node.removeFromParentNode()
}
self.killCount = 0
self.timer.text = String(self.killCount)
self.addNode()
self.playBttn.isEnabled = false
}
}
func rNums(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat {
var result = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
print(result)
if result > 0 && result < 2 {
result += 3
} else if result < 0 && result > -2 {
result -= 3
}
print("after")
print(result)
return result
}
func degToRadians(degrees:Double) -> Double{
return degrees * (.pi / 180);
}
<file_sep>/PlaneDetection/PlaneDetection/ViewController.swift
//
// ViewController.swift
// PlaneDetection
//
// Created by <NAME> on 6/26/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet weak var sceneView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()
override func viewDidLoad() {
super.viewDidLoad()
self.sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
self.configuration.planeDetection = .horizontal
self.sceneView.session.run(configuration)
self.sceneView.delegate = self
// let lava = createLava(planeAnchor: <#T##ARPlaneAnchor#>)
// self.sceneView.scene.rootNode.addChildNode(lava)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createLava(planeAnchor: ARPlaneAnchor) -> SCNNode {
let lavaNode = SCNNode(geometry: SCNPlane(width: CGFloat(planeAnchor.extent.x), height: CGFloat(planeAnchor.extent.z)))
let material = SCNMaterial()
material.diffuse.contents = #imageLiteral(resourceName: "lava")
material.diffuse.contentsTransform = SCNMatrix4MakeScale(6, 6, 0)
lavaNode.geometry?.firstMaterial? = material
lavaNode.geometry?.firstMaterial?.diffuse.wrapS = SCNWrapMode.repeat
lavaNode.geometry?.firstMaterial?.diffuse.wrapT = SCNWrapMode.repeat
// lavaNode.geometry?.firstMaterial?.diffuse.contents = #imageLiteral(resourceName: "lava")
lavaNode.position = SCNVector3(planeAnchor.center.x, planeAnchor.center.y, planeAnchor.center.z)
lavaNode.eulerAngles = SCNVector3(-90.degreesToRadians, 0, 0 )
return lavaNode
}
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else {return}
let lavaNode = createLava(planeAnchor: planeAnchor)
print("new flat surface detected")
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else {return}
print("planeAnchor updated")
node.enumerateChildNodes { (childNode, _) in
childNode.removeFromParentNode()
}
let lavaNode = createLava(planeAnchor: planeAnchor)
node.addChildNode(lavaNode)
}
func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
guard let _ = anchor as? ARPlaneAnchor else {return}
node.enumerateChildNodes { (childNode, _) in
childNode.removeFromParentNode()
}
print("removed planeAnchor")
}
}
extension Int {
var degreesToRadians: Double { return Double(self) * .pi/180 }
}
|
af529f327b9dd008a04f11423fbfd285ca7d6846
|
[
"Swift"
] | 2 |
Swift
|
Mpompili/ARKit_Practice
|
adeb94688f52c91b450c137063ed2eae74b680ac
|
92cf66a179580c3c3ad15d168230bb355e9551c7
|
refs/heads/master
|
<file_sep>var products = [
{
name: 'cooking oil',
price: 10.5,
type: 'grocery'
},
{
name: 'Pasta',
price: 6.25,
type: 'grocery'
},
{
name: 'Instant cupcake mixture',
price: 5,
type: 'grocery'
},
{
name: 'All-in-one',
price: 260,
type: 'beauty'
},
{
name: 'Zero Make-up Kit',
price: 20.5,
type: 'beauty'
},
{
name: 'Lip Tints',
price: 12.75,
type: 'beauty'
},
{
name: 'Lawn Dress',
price: 15,
type: 'clothes'
},
{
name: 'Lawn-Chiffon Combo',
price: 19.99,
type: 'clothes'
},
{
name: '<NAME>',
price: 9.99,
type: 'clothes'
}
]
var cartList = [];
var cart = [];
var subtotal = {
grocery: {
value: 0,
discount: 0
},
beauty: {
value: 0,
discount: 0
},
clothes: {
value: 0,
discount: 0
},
};
var total = 0;
var preuTotal=0;
var tipus;
var subtotalGrocery=0;
var subtotalClothes=0;
var subtotalBeauty=0;
// Exercise 1
// 1. Loop for to the array products to get the item to add to cart
function mostraProductes(products){
for(let i=0; i<products.length; i++) {
products[i].id=1+i;
console.log('Producte número '+(i+1));
console.log(products[i]);
}
}
// 2. Add found product to the cartList array
function addToCartList(id) {
cartList.push(products[id-1]);
}
// Exercise 2 Segons enunciat s'ha de buidar cartList.
function cleanCart1() {
cartList=[];
}
addToCartList(1);
addToCartList(2);
addToCartList(3);
console.log(cartList.length);
console.log(cartList);
cleanCart1();
console.log(cartList.length);
console.log(cartList);
//Però si es vol buidar qualsevol array es passa per paràmetre l'array a buidar
function cleanCart2(cartList){
cartList=[];
}
// Exercise 3
// 1. Create a for loop on the "cartList" array
// 2. Implement inside the loop an if...else or switch...case to add the quantities of each type of product, obtaining the subtotals: subtotalGrocery, subtotalBeauty and subtotalClothes
function calculateSubtotals(cartList) {
for (i=0; i<cartList.length; i++) {
tipus=cartList[i].type;
cartList.map(v => Object.assign(v, {quantity: 1}));//afegim atribut quantity a tots els objectes de cartList amb valor 1
if (tipus=='grocery'){
subtotal.grocery.value+=cartList[i].price;
}else if(tipus=='beauty'){
subtotal.beauty.value+=cartList[i].price;
}else{
subtotal.clothes.value+=cartList[i].price;
}
}
console.log('Subtotals:')
console.log(' Grocery: '+subtotal.grocery.value);
console.log(' Beauty: '+subtotal.beauty.value);
console.log(' Clothes: '+subtotal.clothes.value);
}
// Exercise 4
// Calculate total price of the cart either using the "cartList" array
//versió 1 comptant directe a l'array amb un for
function calculateTotal(cartList) {
for (i=0; i<cartList.length; i++) {
preuTotal+=cartList[i].price;
}
console.log('Total: '+preuTotal);
}
//versió 2 comptant subtotals amb un for...in
function calculateTotal2(cartList) {
calculateSubtotals(cartList);
var preuTotal2=0;
for (var x in subtotal) {
preuTotal2+=subtotal[x].value;
}
console.log('Total: '+preuTotal2);
}
// Exercise 5
// versió 1 descompte per tipus de producte en general(grocery, beauty o clothes)
function applyPromotionsSubtotals(array,kind,discount) {//(array on treballar, tipus de producte, descompte)
var promoSubTotal=0;
for (let i=0; i<array.length; i++) {
var indice= array[i];
tipus=indice.type;
if (tipus==kind){
promoSubTotal+= indice.price;
}
}console.log(promoSubTotal-(promoSubTotal*discount)/100);
}
// Exercise 6
/*function generateCart() {
// Using the "cartlist" array that contains all the items in the shopping cart,
// generate the "cart" array that does not contain repeated items, instead each item of this array "cart" shows the quantity of product.
}*/
function generateCart(cartList){//afegit el paràmetre cartlist a la funció per poder probar-la amb un altre array sense modificar el codi
let set= new Set(cartList.map( JSON.stringify ))//convertits els objectes a cadena de text per comprobar repetits
cart = Array.from( set ).map( JSON.parse );//afegim a cart els resultats únics i convertim els strings d'abans a objectes
for( let i=0; i<cart.length;i++){
cart[i].quantity=0;// reset del camp a 0 per anar sumant els que venen de cartList
for( let j=0; j<cartList.length; j++ ){
if(cart[i].name==cartList[j].name){
cart[i].quantity++;
cart[i].subtotal=(cart[i].quantity*cart[i].price);
}
}
}
for( let i=0; i<cart.length;i++){
if(cart[i].name=='cooking oil'&cart[i].quantity>=3){
cart[i].subtotalWithDiscount=cart[i].quantity*10; //afegim l'atribut subtotalWithDiscount per l'oferta a l'oli
}else if(cart[i].name=='Instant cupcake mixture'&cart[i].quantity>=10){
cart[i].subtotalWithDiscount=(cart[i].subtotal*2)/3; //afegim l'atribut subtotalWithDiscount per l'oferta a la mescla per pastís
}else{cart[i].subtotalWithDiscount='No discount'} //afegim l'atribut subtotalWithDiscount sense discount per a la resta de productes
}
console.log(cart);
}
//Funció per aplicar les promos que diu l'exercici en comptes d'afegir el codi dins la propia funció de generateCart
function promoOilAndCake(cart){
for( let i=0; i<cart.length;i++){
if(cart[i].name=='cooking oil'&cart[i].quantity>=3){
cart[i].subtotalWithDiscount=cart[i].quantity*10;
}else if(cart[i].name=='Instant cupcake mixture'&cart[i].quantity>=10){
cart[i].subtotalWithDiscount=(cart[i].subtotal*2)/3;
}else{cart[i].subtotalWithDiscount='No discount'}
}
}
// Exercise 7
//Segons l'exercici del moddle s'aplicaven despcomptes per categoria però l'única promo que s'ha demanat era sobre producte...
//funció per aplicar descomptes al total de la compra
function fullDiscount(discount, array){
calculateTotal(array);
console.log(preuTotal-(preuTotal*discount)/100);
}
// Apply promotions to each item in the array "cart"
function applyPromotionsCart(productName, discount, num,){
for( let i=0; i<cart.length;i++){
if(cart[i].name==productName&cart[i].quantity>=num){
cart[i].subtotalWithDiscount=cart[i].subtotal-(cart[i].subtotal*discount)/100;
}else{cart[i].subtotalWithDiscount='No discount'}
}
}
// Exercise 8
// 1. Loop for to the array products to get the item to add to cart
// 2. Add found product to the cartList array
//console.log('Quin producte vols afegir?:');
//mostraProductes(products);//retorna l'array products amb un número d'id
function addToCart(id){
var troba=false;
if(cart.length==0){
cart.push(products[id-1]);
cart[0].quantity=1;
}
else if(cart.length>0){
for(var i=0; i<cart.length; i++){
if(products[id-1].name==cart[i].name){
troba=true;}
if(troba){
cart[i].quantity++;}
}
if(troba==false){
cart.push(products[id-1]);
cart[cart.length-1].quantity=1;
}
}
for( let i=0; i<cart.length; i++){
cart[i].subtotal=cart[i].quantity*cart[i].price;
}
}
// Exercise 9
// 1. Loop for to the array products to get the item to add to cart
//console.log('Quin producte vols esborrar?:');
mostraProductes(cart);//retorna l'array products amb un número d'id
function removeFromCart(id) {
// 2. Add found product to the cartList array
cart.splice(id-1,1);
}
// Exercise 10
function printCart() {
// Fill the shopping cart modal manipulating the shopping cart dom
}<file_sep>// Exercise 10
// Move this variable to a json file and load the data in this js
var products = [
{
name: 'cooking oil',
price: 10.5,
type: 'grocery'
},
{
name: 'Pasta',
price: 6.25,
type: 'grocery'
},
{
name: 'Instant cupcake mixture',
price: 5,
type: 'grocery'
},
{
name: 'All-in-one',
price: 260,
type: 'beauty'
},
{
name: 'Zero Make-up Kit',
price: 20.5,
type: 'beauty'
},
{
name: 'Lip Tints',
price: 12.75,
type: 'beauty'
},
{
name: '<NAME>',
price: 15,
type: 'clothes'
},
{
name: 'Lawn-Chiffon Combo',
price: 19.99,
type: 'clothes'
},
{
name: '<NAME>',
price: 9.99,
type: 'clothes'
}
]
var cartList = [];
var cart = [];
var subtotal = {
grocery: {
value: 0,
discount: 0
},
beauty: {
value: 0,
discount: 0
},
clothes: {
value: 0,
discount: 0
},
};
var total = 0;
var preuTotal=0;
var tipus;
var subtotalGrocery=0;
var subtotalClothes=0;
var subtotalBeauty=0;
// Exercise 1
// 1. Loop for to the array products to get the item to add to cart
function mostraProductes(products){
for(let i=0; i<products.length; i++) {
products[i].id=1+i;
console.log('Producte número '+(i+1));
console.log(products[i]);
}
}
mostraProductes(products);
// 2. Add found product to the cartList array
function addToCartList(id) {
cartList.push(products[id-1]);
}
addToCartList(1);
addToCartList(1);
addToCartList(1);
addToCartList(1);
addToCartList(2);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(3);
addToCartList(4);
addToCartList(5);
console.log(cartList)
// Exercise 2
function cleanCart() {
cartList=[];
}
// Exercise 3
// 1. Create a for loop on the "cartList" array
// 2. Implement inside the loop an if...else or switch...case to add the quantities of each type of product, obtaining the subtotals: subtotalGrocery, subtotalBeauty and subtotalClothes
function calculateSubtotals() {
for (i=0; i<cartList.length; i++) {
tipus=cartList[i].type;
cartList.map(v => Object.assign(v, {quantity: 1}));//afegim atribut quantity a tots els objectes de cartList amb valor 1
if (tipus=='grocery'){
subtotal.grocery.value+=cartList[i].price;
}else if(tipus=='beauty'){
subtotal.beauty.value+=cartList[i].price;
}else{
subtotal.clothes.value+=cartList[i].price;
}
}
console.log('Subtotals:')
console.log(' Grocery: '+subtotal.grocery.value);
console.log(' Beauty: '+subtotal.beauty.value);
console.log(' Clothes: '+subtotal.clothes.value);
};
// Exercise 4
// Calculate total price of the cart either using the "cartList" array
function calculateTotal() {
calculateSubtotals();
for (var x in subtotal) {
preuTotal+=subtotal[x].value;
}
console.log('Total: '+preuTotal);
}calculateTotal()
// Exercise 5
// Using the "cartlist" array that contains all the items in the shopping cart,
// generate the "cart" array that does not contain repeated items, instead each item of this array "cart" shows the quantity of product.
function generateCart(){//afegit el paràmetre cartlist a la funció per poder probar-la amb un altre array sense modificar el codi
let set= new Set(cartList.map( JSON.stringify ))//convertits els objectes a cadena de text per comprobar repetits
cart = Array.from( set ).map( JSON.parse );//afegim a cart els resultats únics i convertim els strings d'abans a objectes
for( let i=0; i<cart.length;i++){
cart[i].quantity=0;// reset del camp a 0 per anar sumant els que venen de cartList
for( let j=0; j<cartList.length; j++ ){
if(cart[i].name==cartList[j].name){
cart[i].quantity++;
cart[i].subtotal=(cart[i].quantity*cart[i].price);
}
}
}console.log(cart);
}generateCart()
// Exercise 6
// Apply promotions to each item in the array "cart"
function applyPromotionsCart() {
for( let i=0; i<cart.length;i++){
if(cart[i].name=='cooking oil'&cart[i].quantity>=3){
cart[i].subtotalWithDiscount=cart[i].quantity*10; //afegim l'atribut subtotalWithDiscount per l'oferta a l'oli
}else if(cart[i].name=='Instant cupcake mixture'&cart[i].quantity>=10){
cart[i].subtotalWithDiscount=(cart[i].subtotal*2)/3; //afegim l'atribut subtotalWithDiscount per l'oferta a la mescla per pastís
}else{cart[i].subtotalWithDiscount='No discount'} //afegim l'atribut subtotalWithDiscount sense discount per a la resta de productes
}
console.log(cart);
}applyPromotionsCart()
// Exercise 7
// 1. Loop for to the array products to get the item to add to cart
// 2. Add found product to the cart array
function addToCart(id) {
var troba=false;
if(cart.length==0){
cart.push(products[id-1]);
cart[0].quantity=1;
}
else if(cart.length>0){
for(var i=0; i<cart.length; i++){
if(products[id-1].name==cart[i].name){
troba=true;}
if(troba){
cart[i].quantity++;}
}
if(troba==false){
cart.push(products[id-1]);
cart[cart.length-1].quantity=1;
}
}
for( let i=0; i<cart.length; i++){
cart[i].subtotal=cart[i].quantity*cart[i].price;
}applyPromotionsCart();
}
// Exercise 8
// 1. Loop for to the array products to get the item to add to cart
mostraProductes(cart);
// 2. Remove found product to the cartList array
function removeFromCart(id) {
cart.splice(id-1,1);
console.log(cart);
}
// Exercise 9
function printCart() {
// Fill the shopping cart modal manipulating the shopping cart dom
}
|
2f468fcf9c55a390f5d77949632dee29d506e098
|
[
"JavaScript"
] | 2 |
JavaScript
|
Ma-ti-as/Sprint3
|
1dad97c48c212410aa24a125343e61e120d17599
|
57b9953d2eed9c649db53f96a1dfa99fdd644dd8
|
refs/heads/master
|
<file_sep>from __future__ import unicode_literals
import random
import string
import hashlib
import hmac
import base64
PAGINATION_MODEL = {
"list_user_pools": {
"input_token": "next_<PASSWORD>",
"limit_key": "max_results",
"limit_default": 60,
"page_ending_range_keys": ["arn"],
},
"list_user_pool_clients": {
"input_token": "next_token",
"limit_key": "max_results",
"limit_default": 60,
"page_ending_range_keys": ["id"],
},
"list_identity_providers": {
"input_token": "next_<PASSWORD>",
"limit_key": "max_results",
"limit_default": 60,
"page_ending_range_keys": ["name"],
},
"list_users": {
"input_token": "pagination_token",
"limit_key": "limit",
"limit_default": 60,
"page_ending_range_keys": ["id"],
},
}
def create_id():
size = 26
chars = list(range(10)) + list(string.ascii_lowercase)
return "".join(str(random.choice(chars)) for x in range(size))
def check_secret_hash(app_client_secret, app_client_id, username, secret_hash):
key = bytes(str(app_client_secret).encode("latin-1"))
msg = bytes(str(username + app_client_id).encode("latin-1"))
new_digest = hmac.new(key, msg, hashlib.sha256).digest()
SECRET_HASH = base64.b64encode(new_digest).decode()
return SECRET_HASH == secret_hash
|
60ec247f3f196a7ea190fa661b196d89bfbdf643
|
[
"Python"
] | 1 |
Python
|
shivani-idexcel/moto
|
f50d80ede66af3bdac31758dad8c2e228142a12a
|
e178d9ed76f3616db01e3422ea879041b0bc7eeb
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.DTOs
{
public class Developer : dbEntity
{
public string LastName { get; set; }
public int Age { get; set; }
public string Role { get; set; }
public Skill[] Skills { get; set; }
public Education[] Educations { get; set; }
public Company[] Companies { get; set; }
}
}
<file_sep>using CV.MW.GraphQLService.GraphTypes;
using CV.MW.Repository;
using GraphQL;
using GraphQL.Types;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.Helpers
{
public class DPInjectionMapper
{
private IServiceCollection _srvCollection;
public DPInjectionMapper(IServiceCollection srv)
{
srv.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
//repos
srv.AddSingleton<DeveloperRepo>();
srv.AddSingleton<SkillRepo>();
srv.AddSingleton<EducationRepo>();
srv.AddSingleton<CompanyRepo>();
//graphql stuff
srv.AddSingleton<CodeNinjaQueries>();
srv.AddSingleton<CodeNinjaMutation>();
//grapgql types
srv.AddSingleton<CodeNinjaType>();
srv.AddSingleton<SkillType>();
srv.AddSingleton<EducationType>();
srv.AddSingleton<CompanyType>();
//input type -> for create data
srv.AddSingleton<SkillInputType>();
//more grapql stuff
srv.AddSingleton<GraphEntityInterface>();
srv.AddSingleton<SkillTypeEnum>();
srv.AddSingleton<ISchema, CodeNinjaSchema>();
_srvCollection = srv;
}
public IServiceCollection GetServiceCollection()
{
return _srvCollection;
}
}
}
<file_sep>using CV.MW.DTOs;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class SkillType: ObjectGraphType<Skill>
{
public SkillType()
{
Name = "Skill";
Field(n => n.Id).Description("id");
Field(n => n.Name, nullable: false).Description("name");
Field(n => n.Lvl, nullable: false).Description("lvl");
Field<SkillTypeEnum>("type", "Type");
Interface<GraphEntityInterface>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CV.MW.WebService.helpers
{
public class DataTableRowViewModel
{
public string DataFieldName { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.Repository
{
public interface _IBaseRepo<T>
{
bool Create(T entity);
T GetById(string id);
IEnumerable<T> GetAll();
}
}
<file_sep>using CV.MW.DTOs;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.Repository
{
public class CompanyRepo : _IBaseRepo<Company>
{
private List<Company> _companyTable = new List<Company>()
{
new Company(){Id = "1", Name = "Sport Solution A/S", Description ="As intern"},
new Company(){Id = "2", Name = "eMino Software ApS", Description = "As intern"},
new Company(){Id = "3", Name ="My Own Company", Description ="2-3 months after education as school project"},
new Company(){Id = "4", Name = "FlexPos", Description = "As full-stack software developer"}
};
public bool Create(Company entity)
{
throw new NotImplementedException();
}
public IEnumerable<Company> GetAll()
{
return _companyTable;
}
public Company GetById(string id)
{
throw new NotImplementedException();
}
}
}
<file_sep>using GraphQL;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService
{
public class CodeNinjaSchema : Schema
{
public CodeNinjaSchema(IDependencyResolver resolver)
:base(resolver)
{
Query = resolver.Resolve<CodeNinjaQueries>();
Mutation = resolver.Resolve<CodeNinjaMutation>();
}
}
}
<file_sep>using CV.MW.DTOs;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.Repository
{
class ProjectRepo : _IBaseRepo<Project>
{
public bool Create(Project entity)
{
throw new NotImplementedException();
}
public IEnumerable<Project> GetAll()
{
throw new NotImplementedException();
}
public Project GetById(string id)
{
throw new NotImplementedException();
}
}
}
<file_sep>using CV.MW.DTOs;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class EducationType : ObjectGraphType<Education>
{
public EducationType()
{
Name = "Education";
Field(n => n.Id).Description("id");
Field(n => n.Name, nullable: false).Description("name");
Field(n => n.StartDate, nullable: false).Description("startDate");
Field(n => n.EndDate, nullable: false).Description("endDate");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CV.MW.WebService.helpers
{
public class DataTableViewModel
{
public string Id { get; set; }
public List<DataTableRowViewModel> Rows { get; set; }
public DataTableViewModel(string id, List<string> rows)
{
Id = id;
Rows = new List<DataTableRowViewModel>();
foreach (string row in rows)
{
Rows.Add(new DataTableRowViewModel() {DataFieldName = row });
}
}
}
}
<file_sep>using CV.MW.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CV.MW.Repository
{
public class DeveloperRepo : _IBaseRepo<Developer>
{
private List<Developer> _devTable = new List<Developer>() { new Developer() {
Id = "1",
Name = "Ervin",
LastName = "Færgemand",
Age = 28,
Role = "CodeNinja",
Uid = Guid.NewGuid()
} };
public bool Create(Developer entity)
{
throw new NotImplementedException();
}
public IEnumerable<Developer> GetAll()
{
throw new NotImplementedException();
}
public Developer GetById(string id)
{
return _devTable.FirstOrDefault();
}
}
}
<file_sep>using GraphQL.Server.Transports.AspNetCore.Common;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CV.MW.WebService.Controllers
{
[EnableCors("AllowAllOrigins")]
public class AppController : Controller
{
public ActionResult Index()
{
return View("/Views/app.cshtml");
}
}
}
<file_sep>using CV.MW.Repository;
using GraphQL;
using GraphQL.Types;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService
{
public class GraphQLKicker
{
public GraphQLKicker()
{
}
public void Kick(IServiceCollection srv)
{
srv.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
//srv.AddSingleton<DeveloperRepo>();
//srv.AddSingleton<SkillRepo>();
//srv.AddSingleton<CodeNinjaQueries>();
//srv.AddSingleton<CodeNinjaType>();
//srv.AddSingleton<SkillType>();
//srv.AddSingleton<GraphEntityInterface>();
//srv.AddSingleton<ISchema, CodeNinjaSchema>();
}
}
}
<file_sep>using CV.MW.DTOs;
using CV.MW.Repository;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class CodeNinjaType : ObjectGraphType<Developer>
{
public CodeNinjaType(SkillRepo skillRepo, EducationRepo educationRepo, CompanyRepo companyRepo)
{
Name = "CodeNinja";
Field(n => n.Id).Description("id");
Field(n => n.Name, nullable: false).Description("name");
Field(n => n.LastName, nullable: false).Description("lastname");
Field(n => n.Age, nullable: false).Description("age");
Field(n => n.Role, nullable: false).Description("Role");
Field<ListGraphType<SkillType>>("skills", resolve: context => skillRepo.GetAll());
Field<ListGraphType<EducationType>>("educations", resolve: context => educationRepo.GetAll());
Field<ListGraphType<CompanyType>>("companies", resolve: context => companyRepo.GetAll());
Interface<GraphEntityInterface>();
}
}
}
<file_sep>declare var require: any
var gulp = require('/gulp');
var del = require('del');
var paths = {
scripts: ['Scripts/**/*.js', 'Scripts/**/*.ts', 'Scripts/**/*.map'],
};
gulp.task('clean', function () {
return del(['wwwroot/Scripts/**/*']);
});
gulp.task('default', function () {
gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/Scripts'))
});<file_sep>using CV.MW.DTOs;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class GraphEntityInterface : InterfaceGraphType<dbEntity>
{
public GraphEntityInterface()
{
Name = "GraphEntity";
Field(d => d.Id).Description("Id");
Field(d => d.Name).Description("name");
}
}
}
<file_sep>using CV.MW.DTOs;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class SkillInputType : InputObjectGraphType<Skill>
{
public SkillInputType()
{
Name = "SkillInput";
Field<NonNullGraphType<StringGraphType>>("Name");
Field<StringGraphType>("lvl");
}
}
}
<file_sep>using CV.MW.DTOs;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class CompanyType : ObjectGraphType<Company>
{
public CompanyType()
{
Name = "Company";
Field(n => n.Id).Description("id");
Field(n => n.Name, nullable: false).Description("name");
Field(n => n.Description, nullable: false).Description("description");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.DTOs
{
public class Education : dbEntity
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string City { get; set; }
}
}
<file_sep># Project.CurriculumVitae.Mindworking
# 1. Prerequisites
To run this project you'll need to install .NET Core 2.1 -> https://www.microsoft.com/net/download/thank-you/dotnet-sdk-2.1.401-windows-x64-installer
<file_sep>declare var _app: App;
declare var $: any;
declare var localUrl: string;
function InitApp() {
localUrl = window.location.href;
_app = new App();
}
class App {
constructor() {
var queryManager: QueryManager = new QueryManager();
var devTable = new GraphQLDataTable('#devTable')
devTable.SendQueryWithCallBack(queryManager.GetDeveloperInfo(), devTable_fallBackFunc)
var skillsTable = new GraphQLDataTable('#skillsTable')
skillsTable.SendQueryWithCallBack(queryManager.GetSkillsList(), skillsTable_fallBackFunc)
var singleSkillTable = new GraphQLDataTable('#singleSkillTable')
singleSkillTable.SendQueryWithCallBack(queryManager.GetSingleStringById(), singleSkillTable_fallBackFunc)
var educationTable = new GraphQLDataTable('#educationTable')
educationTable.SendQueryWithCallBack(queryManager.GetListOfEducations(), educationsTable_fallBackFunc)
var educationTable = new GraphQLDataTable('#companyTable')
educationTable.SendQueryWithCallBack(queryManager.GetAllCompanies(), companyTable_fallBackFunc)
}
}
class GraphQLDataTable {
private _grapQLClient: GraphQLApiClient;
private _id: string;
constructor(id: string) {
this._grapQLClient = new GraphQLApiClient(localUrl + 'graphql?');
this._id = id;
}
public SendQueryWithCallBack(query: string, fallBack: any): void {
this._grapQLClient.SendQuery(query, fallBack);
}
}
class GraphQLApiClient {
private _url: string;
constructor(url: string) {
this._url = url;
}
public SendQuery(query: string, callBack: any) {
this.callGraphQL("query=", "POST", query, callBack);
}
private callGraphQL(url: string, httpMode: string, query: any, callBack: any) {
let xhttp = new XMLHttpRequest();
xhttp.open(httpMode, this._url + url + query, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
xhttp.onload = function (response: any) {
let data = response.target.response;
var jsonObj = JSON.parse(data)
jsonObj.query = query;
callBack(jsonObj);
};
}
}
class QueryManager {
public GetDeveloperInfo(): string {
return "{ervin{id name lastName age role}}";
}
public GetSkillsList(): string {
return "{ ervin { skills{ name lvl type } } }";
}
public GetSingleStringById(): string {
return `{skill(id:"1"){name type}}`;
}
public GetListOfEducations(): string {
return "{ ervin { educations { name startDate endDate} } }";
}
public GetAllData(): string {
return "{ ervin { id name educations { id name } skills { id name } } }";
}
public GetAllCompanies(): string {
return "{ ervin { companies{ name description } } }";
}
}
//callback fucntions :D
function devTable_fallBackFunc(obj: any): void {
obj.data.ervin.query = obj.query;
popTable('#devTable', [obj.data.ervin]);
}
function skillsTable_fallBackFunc(obj: any): void {
obj.data.ervin.skills[0].query = obj.query;
popTable('#skillsTable', obj.data.ervin.skills);
}
function singleSkillTable_fallBackFunc(obj: any): void {
obj.data.skill.query = obj.query;
popTable('#singleSkillTable', [obj.data.skill]);
}
function educationsTable_fallBackFunc(obj: any): void {
obj.data.ervin.educations[0].query = obj.query;
popTable('#educationTable', obj.data.ervin.educations);
}
function companyTable_fallBackFunc(obj: any): void {
obj.data.ervin.companies[0].query = obj.query;
popTable('#companyTable', obj.data.ervin.companies);
}
function popTable(tableId: string, data: any) {
$(tableId).bootstrapTable({
data: data
});
}
<file_sep>using CV.MW.DTOs;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.Repository
{
public class EducationRepo : _IBaseRepo<Education>
{
private List<Education> _educationTable = new List<Education>()
{
new Education(){
Id = "1",
Name = "Datamatiker",
StartDate = new DateTime(2012, 01, 01),
EndDate = new DateTime(2015, 01, 01),
City = "Grenaa"
},
new Education(){
Id = "2",
Name = "HTX",
StartDate = new DateTime(2009, 01, 01),
EndDate = new DateTime(2012, 01, 01),
City = "Haderslev"
}
};
public bool Create(Education entity)
{
throw new NotImplementedException();
}
public IEnumerable<Education> GetAll()
{
return _educationTable;
}
public Education GetById(string id)
{
throw new NotImplementedException();
}
}
}
<file_sep>using CV.MW.GraphQLService.GraphTypes;
using CV.MW.Repository;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CV.MW.GraphQLService
{
public class CodeNinjaQueries : ObjectGraphType<object>
{
public CodeNinjaQueries(DeveloperRepo devRepo, SkillRepo skillRepo)
{
Name = "Query";
Field<CodeNinjaType>(
"Ervin",
resolve: context => devRepo.GetById("1"));
Field<SkillType>(
"Skill",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "id", Description = "id" }
),
resolve: context => skillRepo.GetById(context.GetArgument<string>("id"))
);
//Func<ResolveFieldContext, string, object> func = (context, id) => GetErvinCodeNinja();
//FieldDelegate<CodeNinjaType>(
// "codeNinja",
// arguments: new QueryArguments(
// new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "id", Description = "id" }
// ),
// resolve: func
// );
}
}
}
<file_sep>using CV.MW.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CV.MW.Repository
{
public class SkillRepo : _IBaseRepo<Skill>
{
private List<Skill> _skillTable = new List<Skill>()
{
new Skill() { Id = "1", Name = "C#", Lvl = 7, Type = 1 },
new Skill() { Id = "2", Name = "VB", Lvl = 5, Type = 1 },
new Skill() { Id = "3", Name = "C++", Lvl = 4, Type = 1 },
new Skill() { Id = "4", Name = "Java", Lvl = 3, Type = 1 },
new Skill() { Id = "5", Name = ".NET Core", Lvl = 7, Type = 4 },
new Skill() { Id = "6", Name = "SQL", Lvl = 7, Type = 2 },
new Skill() { Id = "7", Name = "Git", Lvl = 7, Type = 5},
new Skill() { Id = "8", Name = "SCRUM", Lvl = 8, Type = 3 },
new Skill() { Id = "9", Name = "Elasticsearch", Lvl = 4, Type = 2 },
new Skill() { Id = "8", Name = "HAproxy", Lvl = 4, Type = 99 }
};
public bool Create(Skill entity)
{
_skillTable.Add(entity);
throw new NotImplementedException();
}
public IEnumerable<Skill> GetAll()
{
return _skillTable;
}
public Skill GetById(string id)
{
return _skillTable.FirstOrDefault(s => s.Id == id);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.DTOs
{
public class Skill : dbEntity
{
public int Lvl { get; set; }
public int Type { get; set; }
}
}
<file_sep>using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService.GraphTypes
{
public class SkillTypeEnum : EnumerationGraphType
{
public SkillTypeEnum()
{
Name = "SkillTypeEnum";
Description = "SkillTypeEnum";
AddValue("Coding", "Coding", 1);
AddValue("Database", "Database", 2);
AddValue("ProjectManagement", ".ProjectManagement", 3);
AddValue("Frameworks", ".Frameworks", 4);
AddValue("VersionControl", ".VersionControl", 5);
AddValue("NotYetDefined", "Unknown", 99);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.DTOs
{
public abstract class dbEntity
{
public Guid Uid { get; set; }
public string Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime DeltedAt { get; set; }
public bool IsDeleted { get; set; }
}
}
<file_sep>using CV.MW.DTOs;
using CV.MW.GraphQLService.GraphTypes;
using CV.MW.Repository;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace CV.MW.GraphQLService
{
public class CodeNinjaMutation : ObjectGraphType
{
public CodeNinjaMutation(SkillRepo skillRepo)
{
Name = "Mutation";
Field<SkillType>(
"createSkill",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<SkillInputType>> { Name = "skill" }
),
resolve: context =>
{
var skill = context.GetArgument<Skill>("skill");
return skillRepo.Create(skill);
});
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using CV.MW.GraphQLService;
using CV.MW.GraphQLService.Helpers;
using GraphQL;
using GraphQL.Server;
using GraphQL.Server.Ui.Playground;
using GraphQL.Types;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
namespace CV.MW.WebService
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IServiceCollection>(new DPInjectionMapper(services).GetServiceCollection());
services.AddGraphQL(_ =>
{
_.EnableMetrics = true;
_.ExposeExceptions = true;
}).AddUserContextBuilder(httpContext => httpContext.User);
//mvc stuff inc
services.AddMvc();
services.AddMvcCore(options =>
{
options.RequireHttpsPermanent = true;
options.RespectBrowserAcceptHeader = true;
})
.AddFormatterMappings()
.AddJsonFormatters();
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseGraphQL<ISchema>("/graphql");
app.UseGraphQLPlayground(new GraphQLPlaygroundOptions
{
Path = "/playground"
});
//mvc configs
app.UseMvc();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=App}/{action=Index}");
});
//file handling hack :P
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Scripts")),
RequestPath = "/Scripts"
}
);
}
}
}
|
e0f5435eb1d2a2ed534d0f6aee73b8200b278322
|
[
"Markdown",
"C#",
"TypeScript"
] | 29 |
C#
|
plumkaballZ/Project.CurriculumVitae.Mindworking
|
ed600511a56b6f7e5d79b419375ed30991c623a5
|
626e0f33a209505292c0bec1233eba5305b70810
|
refs/heads/master
|
<repo_name>monisun/patronus<file_sep>/Patronus/MyReportCell.swift
//
// MyReportCell.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class MyReportCell: UITableViewCell {
var incident: Incident?
var message = String()
var datetimeString = String()
var incidentDescText = String()
var incidentDateTime = String()
@IBOutlet weak var incidentDesc: UILabel!
@IBOutlet weak var datetime: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
if let incident = incident as Incident? {
message = incident.message!
datetimeString = incident.datetime!
incidentDesc.text = incidentDescText
datetime.text = incidentDateTime
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/Patronus/Incident.swift
//
// Incident.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class Incident: NSObject {
var id: Int?
var survivor_id: Int?
var message: String?
var latCoordinate: Double?
var longCoordinate: Double?
var datetime: String?
var location: String?
init(dict: NSDictionary) {
super.init()
self.id = dict["id"] as? Int
self.survivor_id = dict["survivor_id"] as? Int
self.message = dict["text_message_body"] as? String
self.latCoordinate = dict["location_latitude"] as? Double
self.longCoordinate = dict["location_longitude"] as? Double
self.datetime = dict["date_time"] as? String
}
}
<file_sep>/heroku-cloud-service/migrations/20150712175747-insertIncidentLocations.js
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
// ./node_modules/.bin/db-migrate down --env production --count 1
/* populate date time
Update Incidents set date_time =
FROM_UNIXTIME( UNIX_TIMESTAMP('2013-07-01 14:53:27') + FLOOR(0 + (RAND() * 63072000)) )
WHERE date_time is null;
*/
exports.up = function(db, callback) {
async.series(
[
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7833,-122.4167]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7843,-122.4177]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7853,-122.4187]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7832,-122.4197]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7863,-122.4867]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7838,-122.4117]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7833,-122.4362]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7803,-122.4462]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7831,-122.4352]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7832,-122.4556]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.7853,-122.4492]),
db.insert.bind(db, 'Incidents', ['survivor_id', 'text_message_body', 'location_latitude', 'location_longitude'],
[1, 'Test Incident via Node', 37.5833,-122.3362]),
], callback);
};
exports.down = function(db, callback) {
db.runSql(
'DELETE FROM Incidents WHERE text_message_body="Test Incident via Node"', [], callback);
};
<file_sep>/Patronus/CommunityViewController.swift
//
// CommunityViewController.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class CommunityViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var currentlySelectedRow: Int!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.backgroundColor = UIColor.lightGrayColor()
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("infoCell", forIndexPath: indexPath) as! InfoCell
switch (indexPath.row) {
case 0:
cell.textLabel?.text = "What is Domestic Violence?"
case 1:
cell.textLabel?.text = "How to Help Loved Ones in Abusive Relationships"
case 2:
cell.textLabel?.text = "Domestic Violence Safety Tips"
case 3:
cell.textLabel?.text = "Domestic Violence Hotlines"
default:
NSLog("UNEXPECTED: \(indexPath.row)")
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
currentlySelectedRow = indexPath.row
performSegueWithIdentifier("showMoreInfo", sender: tableView)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showMoreInfo" {
let infoVC = segue.destinationViewController as! InfoResourceViewController
switch currentlySelectedRow {
case 0:
infoVC.numRows = 5
infoVC.infoSectionToShow = 1
case 1:
infoVC.numRows = 4
infoVC.infoSectionToShow = 2
case 2:
infoVC.numRows = 5
infoVC.infoSectionToShow = 3
case 3:
infoVC.numRows = 4
infoVC.infoSectionToShow = 4
default:
NSLog("UNEXPECTED")
}
}
}
}
<file_sep>/heroku-cloud-service/migrations/20150711173451-createSurvivor.js
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
/* sample commands
./node_modules/.bin/db-migrate create createSurvivor --env production
./node_modules/.bin/db-migrate up --env production
./node_modules/.bin/db-migrate down --env production
*/
exports.up = function(db, callback) {
async.series(
[
db.createTable.bind(db, 'Survivors', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true },
name: { type: 'string', length: '256', notNull: false, unique: false },
street_address: { type: 'string', length: '512', notNull: false, unique: false },
zip_code: { type: 'string', length: '128', notNull: false, unique: false },
survivor_phone_number: { type: 'string', length: '256', notNull: false, unique: false },
attacker_phone_number: { type: 'string', length: '256', notNull: false, unique: false },
check_in: { type: 'int', notNull: false, defaultValue: 0 }
}),
db.createTable.bind(db, 'Incidents', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true },
survivor_id: { type: 'int', notNull: false,
foreignKey: {name: 'incident_survivor_id_foreign_key', table: 'Survivors', rules: { onDelete: 'SET NULL', onUpdate: 'CASCADE'}, mapping: 'id' }},
text_message_body: { type: 'string', length: '1600', notNull: true, unique: false },
location_latitude: { type: 'float', notNull: false, unique: false},
location_longitude: { type: 'float)', notNull: false, unique: false},
date_time: { type: 'datetime', notNull: true, unique: false }
}),
// actions: call supporters, trigger interruption call (call attacker), multiple_action (e.g. both)
db.createTable.bind(db, 'Actions', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true },
action_name: { type: 'string', length: '128', notNull: true, unique: true }
}),
db.createTable.bind(db, 'Survivor_Actions', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true },
survivor_id: { type: 'int', notNull: true, unique: false },
action_id: { type: 'int', notNull: true, unique: false }
}),
db.createTable.bind(db, 'Supporters', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true },
survivor_id: { type: 'int', notNull: true, unique: false },
name: { type: 'string', length: '256', notNull: false, unique: false },
phone_number: { type: 'string', length: '256', notNull: false, unique: false },
}),
// seed tables w data
// *******************************************
db.insert.bind(db, 'Actions', ['id', 'action_name'],[1, 'CALL_SUPPORTERS']),
db.insert.bind(db, 'Actions', ['id', 'action_name'],[2, 'INTERRUPT_ATTACKER']),
db.insert.bind(db, 'Actions', ['id', 'action_name'],[3, 'CHIME']),
db.insert.bind(db, 'Survivor_Actions', ['survivor_id', 'action_id'], [1, 1]),
db.insert.bind(db, 'Survivor_Actions', ['survivor_id', 'action_id'], [1, 2]),
db.insert.bind(db, 'Survivor_Actions', ['survivor_id', 'action_id'], [1, 3]),
], callback);
};
exports.down = function(db, callback) {
async.series(
[
db.dropTable.bind(db, 'Incidents'),
db.dropTable.bind(db, 'Actions'),
db.dropTable.bind(db, 'Supporters'),
db.dropTable.bind(db, 'Survivors'),
db.dropTable.bind(db, 'Survivor_Actions'),
], callback);
};
<file_sep>/Patronus/DataAPI.swift
//
// DataAPI.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class DataAPI: NSObject {
// all users:
let listAllSurvivorsUrl = "http://patronus-team.herokuapp.com/json?op=listSurvivors"
// user's friends:
let getSupportersBySurvivorIdUrl = "http://patronus-team.herokuapp.com/json?op=listSupporters&survivor_id="
// all incidents
let listAllIncidentsUrl = "http://patronus-team.herokuapp.com/json?op=listIncidents"
// user's incidents
let getIncidentsForSurvivorById = "http://patronus-team.herokuapp.com/json?op=listIncidents&survivor_id="
let apiManager = AFHTTPRequestOperationManager()
func listAllSurvivors(completion: (survivors: [Person], error: NSError?) -> ()) {
var survivors = [Person]()
apiManager.GET(listAllSurvivorsUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
println(response)
if let dict = response as! NSDictionary! {
if let rows = dict["rows"] as! [NSDictionary]? {
for row in rows {
var p = Person(dict: row)
survivors.append(p)
}
completion(survivors: survivors, error: nil)
}
}
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println(error.description)
completion(survivors: [], error: error)
})
}
func getSupportersBySurvivorId(id: Int, completion: (supporters: [Person], error: NSError?) -> ()) {
var supporters = [Person]()
apiManager.GET(getSupportersBySurvivorIdUrl + String(id), parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
println(response)
if let dict = response as! NSDictionary! {
if let rows = dict["rows"] as! [NSDictionary]? {
for row in rows {
var p = Person(dict: row)
supporters.append(p)
}
completion(supporters: supporters, error: nil)
}
}
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println(error.description)
completion(supporters: [], error: error)
})
}
func listAllIncidents(completion: (incidents: [Incident], error: NSError?) -> ()) {
var incidents = [Incident]()
apiManager.GET(listAllIncidentsUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
println(response)
if let dict = response as! NSDictionary! {
if let rows = dict["rows"] as! [NSDictionary]? {
for row in rows {
var i = Incident(dict: row)
if i.message != nil && !i.message!.isEmpty {
incidents.append(i)
}
}
completion(incidents: incidents, error: nil)
}
}
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println(error.description)
completion(incidents: [], error: error)
})
}
}
<file_sep>/Patronus/DetailedInfoCell.swift
//
// DetailedInfoCell.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class DetailedInfoCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/Patronus/MeViewController.swift
//
// MeViewController.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class MeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var meImage: UIImageView!
@IBOutlet weak var meName: UILabel!
@IBOutlet weak var phoneNum: UILabel!
@IBOutlet weak var streetAddr: UILabel!
var numReports: Int!
let dataAPI = DataAPI()
var survivors = [Person]()
var me: Person!
var myId = 1 // TODO: populate w/ user login id
var incidents = [Incident]()
var newIncident: Incident?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.backgroundColor = UIColor.lightGrayColor()
// self.navigationController?.navigationBar.backgroundColor = UIColor(red: (43/255), green: (11/255), blue: (90/255), alpha: 1.0)
meImage.layer.cornerRadius = 5
numReports = 1
tableView.dataSource = self
tableView.delegate = self
if let newIncident = newIncident as Incident? {
incidents.append(newIncident)
}
dataAPI.listAllSurvivors({ (survivors, error) -> () in
if error != nil {
NSLog("ERROR: listAllSurvivors: \(error)")
} else {
self.survivors = survivors
for s in survivors {
if s.id == self.myId {
self.me = s
self.meName.text = s.name
self.phoneNum.text = s.phoneNumber
self.streetAddr.text = s.streetAddr
}
}
}
})
dataAPI.listAllIncidents({ (incidents, error) -> () in
if error != nil {
NSLog("ERROR: listAllIncidents: \(error)")
} else {
self.incidents = incidents
self.tableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return incidents.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myReportCell", forIndexPath: indexPath) as! MyReportCell
if indexPath.row < incidents.count {
let i = incidents[indexPath.row]
cell.incident = i
cell.incidentDesc.text = i.message!
cell.datetime.text = i.datetime!
} else {
NSLog("ERROR: \(indexPath.row) invalid index for incidents.count: \(incidents.count)")
}
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/Podfile
# Uncomment this line to define a global platform for your project
# platform :ios, '6.0'
target 'Patronus' do
pod 'AFNetworking'
pod 'BDBOAuth1Manager'
pod 'APAddressBook/Swift'
end
target 'PatronusTests' do
end
<file_sep>/Patronus/MainTabBarViewController.swift
//
// MainTabBarViewController.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class MainTabBarViewController: UITabBarController {
var lastSelectedTabIndex = Int()
override func viewDidLoad() {
super.viewDidLoad()
lastSelectedTabIndex = 2
if let tabs = self.tabBar.items as! [UITabBarItem]? {
tabs[0].image = UIImage(named: "me")
tabs[0].title = "Me"
tabs[1].image = UIImage(named: "friends")
tabs[1].title = "Friends"
tabs[2].image = UIImage(named: "community")
tabs[2].title = "Community"
} else {
NSLog("ERROR: tabs is nil!")
}
if let vcs = self.viewControllers as! [UIViewController]? {
var navMeVC = vcs[0] as! UINavigationController
let meVC: MeViewController = navMeVC.topViewController as! MeViewController
var navFriendsVC = vcs[1] as! UINavigationController
let friendsVC: FriendsViewController = navFriendsVC.topViewController as! FriendsViewController
let navCommunityVC = vcs[2] as! UINavigationController
let communityVC: CommunityViewController = navCommunityVC.topViewController as! CommunityViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
// switch(tabBarController.selectedIndex) {
// case 0:
//
// case 1:
// //
// default:
// NSLog("Unexpected tabBar selectedIndex: \(tabBarController.selectedIndex)!")
// }
self.presentViewController(viewController, animated: true, completion: nil)
}
func tabBarController(tabBarController: UITabBarController, didSelectItem: UITabBarItem) {
lastSelectedTabIndex = tabBarController.selectedIndex
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/twilio app/index.php
<?php
require('../vendor/autoload.php');
$account_sid = "AC7f200476a71df6c7016f1dd7e37af78e"; // Your Twilio account sid
$auth_token = "<PASSWORD>"; // Your Twilio auth token
$client = new Services_Twilio($account_sid, $auth_token);
$servername = "192.168.127.12";
$username = "nodeapp";
$password = "<PASSWORD>$$$";
$dbname = "patronus";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM Survivors WHERE survivor_phone_number='".$_REQUEST['From']."'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$survivor_id = $row["id"];
$survivor_name = $row["name"];
$distraction_number = $row["attacker_phone_number"];
$timenow = time();
$client->account->calls->create('+18329812272', $distraction_number, 'http://twimlbin.com/939af572', array(
'Method' => 'GET',
'FallbackMethod' => 'GET',
'StatusCallbackMethod' => 'GET',
'Record' => 'false',
));
if ($row == "") {
$sql2 = "INSERT INTO Survivors (survivor_phone_number) VALUES ('".$_REQUEST['From']."')";
$result2 = $conn->query($sql2);
}
$sql3 = "INSERT INTO Incidents (survivor_id, text_message_body, date_time) VALUES ('".$survivor_id."','".$_REQUEST['Body']."',CURTIME())";
$result3 = $conn->query($sql3);
$sql4 = "SELECT * FROM Supporters WHERE survivor_id='".$survivor_id."'";
$result4 = $conn->query($sql4);
// now greet the sender
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
// <Message to="<?php echo $row["attacker_phone_number"]>" >This is a test distraction</Message>
?>
<Response>
<Message>thanks!</Message>
<?php
while($row4 = $result4->fetch_assoc()) {
echo "<Message to=\"".$row4["phone_number"]."\"".">".$survivor_name." is in distress!</Message>";
}
?>
</Response>
<file_sep>/Patronus/ReportIncidentViewController.swift
//
// ReportIncidentViewController.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ReportIncidentViewController: UIViewController {
@IBOutlet weak var reportTitle: UITextField!
@IBOutlet weak var type: UITextField!
@IBOutlet weak var reportDescription: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
}
@IBAction func submitButtonClicked(sender: AnyObject) {
performSegueWithIdentifier("submitIncidentReport", sender: self)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "submitIncidentReport" {
let meVC = segue.destinationViewController as! MeViewController
var dict = Dictionary<String, AnyObject>()
dict["id"] = 1
dict["survivor_id"] = 1
dict["text_message_body"] = reportDescription.text as String!
dict["date_time"] = String("12:30pm July 12, 2015")
var newIncident = Incident(dict: dict)
meVC.newIncident = newIncident
}
}
}
<file_sep>/Patronus/InfoResourceViewController.swift
//
// InfoResourceViewController.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class InfoResourceViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var backButton: UIButton!
var numRows: Int!
var infoSectionToShow: Int!
var rowPosition: Int!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numRows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("detailedInfoCell", forIndexPath: indexPath) as! DetailedInfoCell
// TODO replace these w/ each section's rows
cell.textLabel!.font = UIFont.systemFontOfSize(14);
cell.textLabel!.numberOfLines = 0;
switch (infoSectionToShow) {
case 1:
if (indexPath.row == 1) { cell.textLabel?.text = "What is Domestic Violence?\nFrom National Coalition Against Domestic Violence" }
else if (indexPath.row == 2) { cell.textLabel?.text = "About Domestic Violence\nFrom Violence Against Women" }
else if (indexPath.row == 3) { cell.textLabel?.text = "What Is Abuse?\nFrom The National Domestic Violence Hotline" }
else if (indexPath.row == 4) { cell.textLabel?.text = "What Is Domestic Violence?\nFrom The US Dept of Justice" }
case 2:
if (indexPath.row == 1) { cell.textLabel?.text = "Help a Loved One or Friend\nFrom Domestic Abuse Intervention Services " }
else if (indexPath.row == 2) { cell.textLabel?.text = "How to Help a Friend\nWho Is Being Abused From Violence Against Women" }
else if (indexPath.row == 3) { cell.textLabel?.text = "Get Help for Someone Else?\nFrom Love Is Respect Org" }
case 3:
if (indexPath.row == 1) { cell.textLabel?.text = "Domestic Violence Safety Tips\nFrom National Resource Center on Domestic Violence" }
else if (indexPath.row == 2) { cell.textLabel?.text = "Safety Tips for You and Your Family\nFrom American Bar Association" }
else if (indexPath.row == 3) { cell.textLabel?.text = "What Is Safety Planning?\nFrom The National Domestic Violence Hotline" }
else if (indexPath.row == 4) { cell.textLabel?.text = "Help for Abused and Battered Women\nFrom HelpGuide.org" }
case 4:
if (indexPath.row == 1) { cell.textLabel?.text = "National Domestic Violence Hotline\n1-800-799-7233 or 1-800-787-3224 (TTY)" }
else if (indexPath.row == 2) { cell.textLabel?.text = "National Center for Victims of Crimes, Stalking Resource Center\n1-800-394-2255 or 1-800-211-7996 (TTY)" }
else if (indexPath.row == 3) { cell.textLabel?.text = "National Teen Dating Abuse Helpline\n1-866-331-9474 or 1-866-331-8453 (TTY)" }
default:
NSLog("UNEXPECTED: \(indexPath.row)")
}
return cell
}
@IBAction func backButtonClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/Patronus/InfoCell.swift
//
// InfoCell.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class InfoCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/Patronus/FriendCell.swift
//
// FriendCell.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class FriendCell: UITableViewCell {
@IBOutlet weak var friendImage: UIImageView!
@IBOutlet weak var friendName: UILabel!
@IBOutlet weak var friendStatus: UILabel!
@IBOutlet weak var friendPhoneNumber: UILabel!
var friend: Person!
override func awakeFromNib() {
super.awakeFromNib()
friendImage.layer.cornerRadius = 5
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/Patronus/FriendsViewController.swift
//
// FriendsViewController.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class FriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var numFriends: Int!
var friends = [Person]()
let dataAPI = DataAPI()
let myId = 1 //TODO implement user login
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.backgroundColor = UIColor.lightGrayColor()
tableView.dataSource = self
tableView.delegate = self
dataAPI.getSupportersBySurvivorId(self.myId, completion: { (supporters, error) -> () in
if error != nil {
NSLog("ERROR: getSupportersBySurvivorId: \(error)")
} else {
self.friends = supporters
self.tableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("friendCell", forIndexPath: indexPath) as! FriendCell
if indexPath.row < friends.count {
var friend = friends[indexPath.row]
cell.friend = friend
cell.friendName.text = friend.name!
if let status = friend.checkIn as Int! {
if status == 0 {
cell.friendStatus.text = "Safe" //TODO need status field in Node app!
} else {
cell.friendStatus.text = "In Danger"
}
} else {
cell.friendStatus.text = "In Danger"
}
if let phoneNumber = friend.phoneNumber as String! {
cell.friendPhoneNumber.text = friend.phoneNumber!
} else {
cell.friendPhoneNumber.text = " "
}
} else {
NSLog("ERROR: indexPath.row: \(indexPath.row) invalid for friends.count: \(friends.count)")
}
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/heroku-cloud-service/ops.js
// DB connection
var mysql = require('mysql');
var dbConfig = require('./database.json');
var connection = mysql.createConnection({
host : dbConfig.production.host,
user : dbConfig.production.user,
password : <PASSWORD>,
database : dbConfig.production.database
});
connection.connect();
// Handle someone submitting ?op=METHOD etc
module.exports = exports = Object.create(null);
// Sample URLs:
// patronus-team.herokuapp.com/survivor?op=createNewSurvivor => returns ID
// patronus-team.herokuapp.com/survivor?op=createNewSurvivor&survivor_phone_number=12345 => returns ID
exports['createNewSurvivor'] = function (req, res, next) {
var query_params;
connection.beginTransaction(function(err) {
if (err) { throw err; }
query_params = {survivor_phone_number: req.param('survivor_phone_number')};
connection.query('DELETE FROM Survivors WHERE ?', query_params, function(err, result) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
connection.query('INSERT INTO Survivors SET ?', query_params, function(err, result) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
console.log('Survivor ID ' + result.insertId + ' added!');
connection.commit(function(err) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
console.log('SUCCESS!');
res.render('index', { title: 'createNewSurvivor Done with ID ' + result.insertId });
});
});
});
});
};
// patronus-team.herokuapp.com/survivor?op=addSurvivorName&id=[survivor_id]&name=MY_NAME_IS
exports['addSurvivorName'] = function (req, res, next) {
var id = req.param('id');
query_params = {id: req.param('id'), name: connection.escape(req.param('name'))};
connection.query('UPDATE Survivors SET name="' + query_params.name +'" WHERE id=' + query_params.id, function (err, result) {
if (err) throw err;
console.log('changed ' + result.changedRows + ' rows');
res.render('index', { title: 'addSurvivorName Done for ID '+ id });
});
};
// TODO: Fix authentication
// patronus-team.herokuapp.com/json?op=listSurvivors
exports['listSurvivors'] = function (req, res, next) {
var id = req.param('id');
connection.query('SELECT * FROM Survivors', function (err, rows, fields) {
if (err) throw err;
res.send({length: rows.length, rows: rows});
});
};
// patronus-team.herokuapp.com/json?op=listSupporters&survivor_id=1
exports['listSupporters'] = function (req, res, next) {
query_params = {survivor_id: req.param('survivor_id')};
connection.query('SELECT * FROM Supporters WHERE ?', query_params, function (err, rows, fields) {
if (err) throw err;
res.send({length: rows.length, rows: rows});
});
};
// patronus-team.herokuapp.com/json?op=listIncidents
// patronus-team.herokuapp.com/json?op=listIncidents&survivor_id=1
exports['listIncidents'] = function (req, res, next) {
query_params = {survivor_id: req.param('survivor_id')};
if (query_params.survivor_id) {
connection.query('SELECT * FROM Incidents WHERE ?', query_params, function (err, rows, fields) {
if (err) throw err;
res.send({length: rows.length, rows: rows});
});
} else {
connection.query('SELECT * FROM Incidents', function (err, rows, fields) {
if (err) throw err;
res.send({length: rows.length, rows: rows});
});
}
};
// patronus-team.herokuapp.com/map
exports['map'] = function (req, res, next) {
// all incidents
connection.query('SELECT location_latitude, location_longitude FROM Incidents WHERE location_latitude IS NOT NULL and location_longitude IS NOT NULL', function (err, rows, fields) {
if (err) throw err;
var arr = [];
var util = require('util');
console.log("rows: ", util.inspect(rows));
for(var i = 0; i < rows.length; i++) {
arr.push([rows[i].location_latitude, rows[i].location_longitude]);
}
res.render('map', { addressPointsArray: arr });
});
};
<file_sep>/heroku-cloud-service/routes/index.js
var express = require('express');
var router = express.Router();
// https://codeforgeek.com/2014/09/handle-get-post-request-express-4/
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// Main Operations Router
var ops = require('../ops');
var op_name;
router.get('/survivor', function(req, res, next) {
//var util = require('util');
//console.log("ops: ", util.inspect());
//param: https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters
op_name = req.param('op');
ops[op_name](req, res, next);
});
router.get('/json', function(req, res, next) {
op_name = req.param('op');
ops[op_name](req, res, next);
});
router.get('/map', function(req, res, next) {
ops["map"](req, res, next);
});
module.exports = router;
<file_sep>/Patronus/Person.swift
//
// Person.swift
// Patronus
//
// Created by <NAME> on 7/12/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class Person: NSObject {
// Victim or Supporter
var id: Int?
var name: String?
var streetAddr: String?
var zip: String?
var phoneNumber: String?
var attackerPhoneNumber: String?
var checkIn: Int?
init(dict: NSDictionary) {
super.init()
self.id = dict["id"] as? Int
self.name = dict["name"] as? String
self.streetAddr = dict["street_address"] as? String
self.zip = dict["zip_code"] as? String
self.phoneNumber = dict["survivor_phone_number"] as? String
self.attackerPhoneNumber = dict["attacker_phone_number"] as? String
self.checkIn = dict["check_in"] as? Int
}
// init(id: Int, name: String, streetAddr: String, zip: String, phoneNumber: String, attackerPhoneNumber: String, checkIn: Int) {
// super.init()
//
// self.id = id
// self.name = name
// self.streetAddr = streetAddr
// self.zip = zip
// self.phoneNumber = phoneNumber
// self.attackerPhoneNumber = attackerPhoneNumber
// self.checkIn = checkIn
// }
}
|
a8fe9f133b3ec91c2742e7d23685735de5be1e4b
|
[
"Swift",
"JavaScript",
"Ruby",
"PHP"
] | 19 |
Swift
|
monisun/patronus
|
ad4a965db58f091ef776386a3a4446b62e10a240
|
639be0cb7ebf9cf16877525c82e51dbcd23d02df
|
refs/heads/master
|
<file_sep>Django==1.4.1
Fabric==1.4.3
South==0.7.6
Werkzeug==0.8.3
dj-database-url==0.2.1
django-extensions==0.9
gunicorn==0.14.6
psycopg2==2.4.5
pycrypto==2.6
sendgrid==0.1.3
ssh==1.7.14
wsgiref==0.1.2
<file_sep>from fabric.api import *
# current_git_branch = local('git symbolic-ref HEAD', capture=True).split('/')[-1]
# === Environments ===
def development():
env.env = 'development'
env.settings = 'hangman.settings.development'
def staging():
env.env = 'staging'
env.settings = 'hangman.settings.staging'
env.remote = ''
env.heroku_app = ''
def production():
env.env = 'production'
env.settings = 'hangman.settings.production'
env.remote = ''
env.heroku_app = 'hangman-ota'
# Default Environment
development()
# === Deployment ===
def deploy():
local('git push {remote}'.format(**env))
# === Static assets stuff ===
def collectstatic():
# brunchbuild()
local('python manage.py collectstatic --noinput -i app -i config.coffee \
-i node_modules -i package.json --settings={settings}'.format(**env))
# if env.env != 'development':
# commit_id = local('git rev-parse HEAD', capture=True)
# _config_set(key='HEAD_COMMIT_ID', value=commit_id)
def brunchwatch(app_name='core'):
local('cd hangman/%s/static/ && brunch w' % app_name)
def brunchbuild(app_name='core'):
with settings(warn_only=True):
local('rm -r hangman/%s/static/public/' % app_name)
local('cd hangman/%s/static/ && brunch b -m' % app_name)
# === DB ===
def resetdb():
if env.env == 'development':
with settings(warn_only=True):
local('rm dev.sqlite3')
local('python manage.py syncdb --settings={settings}'.format(**env))
local('python manage.py migrate --settings={settings}'.format(**env))
else:
if raw_input('\nDo you really want to RESET DATABASE of {heroku_app}? YES or [NO]: '.format(**env)) == 'YES':
local('heroku run python manage.py syncdb --noinput --settings={settings} --app {heroku_app}'.format(**env))
local('heroku run python manage.py migrate --settings={settings} --app {heroku_app}'.format(**env))
else:
print '\nRESET DATABASE aborted'
def schemamigration(app_names='core'):
local('python manage.py schemamigration {app_names} --auto --settings={settings}'.format(app_names, **env))
def migrate():
if env.env == 'development':
local('python manage.py migrate --settings={settings}'.format(**env))
else:
if raw_input('\nDo you really want to MIGRATE DATABASE of {heroku_app}? YES or [NO]: '.format(**env)) == 'YES':
local('heroku run python manage.py migrate --settings={settings} --app {heroku_app}'.format(**env))
else:
print '\nMIGRATE DATABASE aborted'
def updatedb():
schemamigration()
migrate()
# === Heroku ===
def ps():
local('heroku ps --app {heroku_app}'.format(**env))
def restart():
if raw_input('\nDo you really want to RESTART (web/worker) {heroku_app}? YES or [NO]: '.format(**env)) == 'YES':
local('heroku ps:restart web --app {heroku_app}'.format(**env))
else:
print '\nRESTART aborted'
def tail():
local('heroku logs --tail --app {heroku_app}'.format(**env))
def shell():
local('heroku run bash --app {heroku_app}'.format(**env))
def config():
local('heroku config --app {heroku_app}'.format(**env))
def _config_set(key=None, value=None):
if key and value:
local('heroku config:set {}={} --app {heroku_app}'.format(key, value, **env))
else:
print '\nErr!'
<file_sep>import re
import json
import sendgrid
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from .utils import Hangman as HangmanGame, generate_ascii
from .models import Hangman
def index(request):
hangman = HangmanGame('hello')
print ' '.join(hangman.keys)
ascii = """
__________
| |
| 0
| /|\\
| / \\
|
|
"""
print ascii
return HttpResponse('Hello World')
@csrf_exempt
def webhook(request):
# make a secure connection to SendGrid
s = sendgrid.Sendgrid(settings.SENDGRID_USERNAME,
settings.SENDGRID_PASSWORD, secure=True)
post_data = request.POST
envelope = json.loads(post_data['envelope'])
subject = post_data['subject'].lower().strip()
body_text = post_data['text']
body_text_list = [line.lower().strip() for line in body_text.splitlines()]
if 'create' in subject:
player = body_text_list[0]
word = body_text_list[1]
Hangman.objects.create(sender=envelope['from'],
player=player, word=word)
elif ('re:' in subject and 'play' in subject) or ('re:' in subject and 'playing' in subject):
email_pattern = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
emails = re.findall(email_pattern, subject)
email = emails[0]
letter = body_text_list[0][0]
h = Hangman.objects.get(sender=email, player=envelope['from'])
used_letters = h.used_letters.split(',')
keys = list(h.keys)
if h.mistakes < 5:
if letter in h.word:
match = True
indexes = [i for i, item in enumerate(h.word) if item == letter]
for index in indexes:
keys[index] = letter
used_letters.append(letter)
else:
# guessed letter didn't match
used_letters.append(letter)
h.mistakes += 1
match = False
_keys = ''
for key in keys:
if key != '':
_keys += key
else:
_keys += '_'
h.keys = _keys
h.used_letters = ','.join(set(used_letters))
h.save()
if match:
if h.word == h.keys:
ascii_message = """
YOU WIN!
.-~~~~~~-.
.' '.
/ O O \\
: :
| |
: ', ,' :
\ '-......-' /
'. .'
'-......-'
The word was %s
""" % h.word
# make a message object
message = sendgrid.Message(
settings.SENDGRID_FROM,
'Playing Hangman game by %s' % h.sender,
ascii_message
)
# add a recipient
message.add_to(h.player)
h.delete()
else:
ascii_message = """
Doing good!
You played the letter: %s
%s
Used Letters: %s
""" % (letter, ' '.join(keys), ', '.join(set(used_letters)))
ascii_message += generate_ascii(h.mistakes)
# make a message object
message = sendgrid.Message(
settings.SENDGRID_FROM,
'Playing Hangman game by %s' % h.sender,
ascii_message
)
# add a recipient
message.add_to(h.player)
# use the Web API to send your message
s.web.send(message)
if not match and (h.mistakes >= 1 and h.mistakes <= 5):
ascii_message = """
Ouch!
You played the letter: %s
%s
Used Letters: %s
""" % (letter, ' '.join(keys), ', '.join(set(used_letters)))
ascii_message += generate_ascii(h.mistakes)
if not match and h.mistakes > 0:
# make a message object
message = sendgrid.Message(
settings.SENDGRID_FROM,
'Playing Hangman game by %s' % h.sender,
ascii_message
)
# add a recipient
message.add_to(h.player)
# use the Web API to send your message
s.web.send(message)
else:
# loss
ascii_message = """
Sorry you lost!
.-~~~~~~-.
.' '.
/ O O \\
: ` :
| |
: .------. :
\ ' ' /
'. .'
'-......-'
The word was: %s
""" % h.word
ascii_message += generate_ascii(6)
# make a message object
message = sendgrid.Message(
settings.SENDGRID_FROM,
'You lost',
ascii_message
)
# add a recipient
message.add_to(h.player)
# use the Web API to send your message
s.web.send(message)
h.delete()
return HttpResponse('Hello Webhook')
<file_sep>import sendgrid
from django.db import models
from django.conf import settings
from .utils import Hangman as HangmanGame, generate_ascii
class Hangman(models.Model):
sender = models.EmailField()
player = models.EmailField()
word = models.CharField(max_length=255)
used_letters = models.TextField(blank=True, null=True)
keys = models.CharField(max_length=255)
mistakes = models.IntegerField(default=0)
def __unicode__(self):
return self.word
def save(self, *args, **kwargs):
if not self.pk:
# make a secure connection to SendGrid
s = sendgrid.Sendgrid(settings.SENDGRID_USERNAME,
settings.SENDGRID_PASSWORD, secure=True)
hangman = HangmanGame(self.word)
self.keys = ''.join(hangman.keys)
used_letters = []
for key in self.keys:
if key != '_':
used_letters.append(key)
self.used_letters = ','.join(set(used_letters))
ascii_message = """
%s
""" % ' '.join(hangman.keys)
ascii_message += generate_ascii(0)
ascii_message += """
How to play:
Reply to this email and guess one letter. You'll get another email
that will tell you if your letter was found or not in the word. If
it doesn't match you'll get another part of the hangman body.
"""
# make a message object
message = sendgrid.Message(
settings.SENDGRID_FROM,
'%s invited you to play Hangman' % self.sender,
ascii_message
)
# add a recipient
message.add_to(self.player)
# use the Web API to send your message
s.web.send(message)
return super(Hangman, self).save(*args, **kwargs)
<file_sep>from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'hangman.core.views.index', name='home'),
url(r'^webhook/$', 'hangman.core.views.webhook', name='webhook'),
# url(r'^hangman/', include('hangman.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
)
<file_sep>from django.contrib import admin
from .models import Hangman
admin.site.register(Hangman)
<file_sep>Hangman via Email
=================
Built this in a Hackathon using SendGrid to send and parse incoming emails.
This won me a very awesome SendGrid limited edition Sphero.
Need to write a decent README though.
<file_sep>import os
from hangman.settings.common import *
#==============================================================================
# Generic Django project settings
#==============================================================================
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dev.sqlite3',
}
}
|
269d706e551f4809adc1784fcb260bdf04e5f5ee
|
[
"Markdown",
"Python",
"Text"
] | 8 |
Text
|
jpadilla/email-hangman
|
928c107362531fefb5105e9f20536f9c3fd61976
|
e8775252bc97a8327edde43c45cd013199ab8b19
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.4.3
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Nov 07, 2015 at 11:31 AM
-- Server version: 5.6.24
-- PHP Version: 5.6.8
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: `aib_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `AIB_data`
--
CREATE TABLE IF NOT EXISTS `AIB_data` (
`id` bigint(20) NOT NULL,
`time` bigint(20) NOT NULL,
`location_bought` varchar(50) NOT NULL,
`currency` varchar(20) NOT NULL,
`item_type` varchar(50) NOT NULL,
`value` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `AIB_data`
--
ALTER TABLE `AIB_data`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `AIB_data`
--
ALTER TABLE `AIB_data`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
/* Author: <NAME> & <NAME> */
class AIB_model extends CI_Model {
function add_item($time, $location, $currency, $item_type, $item_value) {
$sql = "INSERT INTO AIB_data(time, location_bought, currency, item_type, value) VALUES(?, ?, ?, ?, ?)";
$data_to_be_inserted = array(
$time,
$location,
$currency,
$item_type,
$item_value
);
$insert = $this->db->query($sql,$data_to_be_inserted);
return $insert;
}
function get_data() {
$sql = "SELECT * FROM AIB_data";
$data = $this->db->query($sql);
return $data->result_array();
}
}
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* Author: <NAME> & <NAME> */
class Home extends CI_Controller {
public function index()
{
$this->homepage();
}
public function homepage() {
$this->load->model('AIB_model');
$all_data = $this->AIB_model->get_data();
$pie_slices = [];
$location_slices = [];
$data['total'] = 0;
$data_by_month = [];
foreach($all_data as $piece) {
if(isset($pie_slices[$piece['item_type']])) {
$pie_slices[$piece['item_type']]['value'] += $piece['value'];
$data['total'] += $piece['value'];
} else {
$pie_slices[$piece['item_type']]['value'] = $piece['value'];
$pie_slices[$piece['item_type']]['type'] = $piece['item_type'];
$data['total'] += $piece['value'];
}
if(isset($location_slices[$piece['location_bought']])) {
$location_slices[$piece['location_bought']]['value'] += $piece['value'];
} else {
$location_slices[$piece['location_bought']]['value'] = $piece['value'];
$location_slices[$piece['location_bought']]['location_bought'] = $piece['location_bought'];
}
if(isset($data_by_month[date('m/Y', $piece['time'])])) {
$length = count($data_by_month[date('m/Y', $piece['time'])]);
$data_by_month[date('m/Y', $piece['time'])][$length] = $piece;
$data_by_month[date('m/Y', $piece['time'])]['total'] += $piece['value'];
} else {
$data_by_month[date('m/Y', $piece['time'])][0] = $piece;
$data_by_month[date('m/Y', $piece['time'])]['total'] = $piece['value'];
$data_by_month[date('m/Y', $piece['time'])]['month'] = date('m/Y', $piece['time']);
}
}
$largestTypeValue = 0;
$largestType = "";
foreach($pie_slices as $slice) {
if($slice['value'] > $largestTypeValue) {
$largestTypeValue = $slice['value'];
$largestType = $slice['type'];
}
}
$largestLocationValue = 0;
$largestLocation = "";
foreach($location_slices as $slice) {
if($slice['value'] > $largestLocationValue) {
$largestLocationValue = $slice['value'];
$largestLocation = $slice['location_bought'];
}
}
$largestMonthValue = 0;
$largestMonth = "";
foreach($data_by_month as $month) {
if($month['total'] > $largestMonthValue) {
$largestMonthValue = $month['total'];
$largestMonth = $month['month'];
}
}
$data['largestMonth'] = $largestMonth;
$data['largestMonthValue'] = $largestMonthValue;
$data['monthly'] = $data_by_month;
$data['largestLocation'] = $largestLocation;
$data['largestType'] = $largestType;
$data['pie'] = $pie_slices;
$data['transactions'] = $all_data;
$this->load->view('home', $data);
}
public function test() {
$this->load->view('welcome_message');
}
public function update() {
$this->load->model('AIB_model');
$segments = $this->uri->segment_array();
$data['head'] = "Test page for updating";
if(count($segments) > 3) {
$time = explode("=", $segments[3]);
$time = $time[1];
$location = explode("=", $segments[4]);
$location = $location[1];
$currency = explode("=", $segments[5]);
$currency = $currency[1];
$items = array_slice($segments, 5);
$i = 0;
foreach($items as $item) {
$item_data = explode("=", $item);
$item_type = $item_data[0];
$item_value = $item_data[1];
$this->AIB_model->add_item((int) $time, $location, $currency, $item_type, (float) $item_value);
$i++;
}
}
redirect('/home');
}
}
?>
<file_sep># QR Code Receipt Scanner
For the <a href="https://www.aibdatahack.com">AIB 2015 Hackathon</a> we wanted to build a QR Code Receipt Scanner
that would be able to be incorporated with the AIB online budgeting and savings portal. We saw a fundamental flaw with their
online budgeting and savings system since it cannot account for Cash transactions which makes budgeting using their online system very hard to do effectively.
We built an Android app that scans the QR codes and then sends the data through a basic API we created which stores the data
in a database and is also hooked up to a website which compiles all this data and displays it.
We invented a standard for creating these QR codes to comply with our API with the idea that any shop owner could generate them
instead or alongside a receipt for use with our apps.
# Web Portal
The web portal was built using the CodeIgniter framework and is connected to a MySQL database.
<img src="images/webportal.png" />
The pie chart was created using the <a href="http://chartjs.org">Chart.js</a> and <a href="http://github.com/davidmerfield/randomColor">randomColor.js</a> libraries.
All the information on the right is what's compiled and calculated from the database which is supplied by the Android App.
The API that the App calls to compromises of a single function "update". By following our QR code standard and with our current structure we expect requests like:
<ul>
<li>example.com/AIB/home/update/time=1446910715/location=Odeon/currency=euro/Entertainment=30/</li>
<li>example.com/AIB/home/update/time=1446910715/location=Tesco/currency=euro/Food=40/Health=20/</li>
</ul>
Our standard expects something in the form:
<ul>
<li>example.com/AIB/home/update/time=UTCTimestamp/location=String/currency=String/Item=Float/…</li>
</ul>
Where you can specify an as many Items as you like, all seperated by forward slashes with whatever type you would like for the Item category as show in the examples above.
Setting the Web Portal up:
<ol>
<li>Clone the repo</li>
<li>Move the AIB folder into the htdocs of your server setup</li>
<li>Import the AIB_db.sql through phpmyadmin or make it yourself</li>
<li>Set the correct url by changing the base_url in application/config/config.php (at the moment it's set to "localhost/AIB")</li>
</ol>
If you don't have a server setup: XAMPP was used for this project and is easy to get started, ensure you have also have PHP and MySQl installed.
# Android App
<file_sep><html>
<head>
<meta name="author" content="<NAME> & <NAME>">
<link rel="stylesheet" href="<?php echo base_url(); ?>css/style.css" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Raleway:100,200' rel='stylesheet' type='text/css'>
<script src="<?php echo base_url(); ?>/js/Chart.js"></script>
<script src="<?php echo base_url(); ?>/js/randomColor.js"></script>
</head>
<body>
<div class="wrapper">
<h2 class="title">AIB Cash Expenditure</h2>
<div class="charts">
<canvas id="myChart" style="margin-top: 0px; margin-left: 0px;"></canvas>
<script>
var data = [
<?php foreach($pie as $slice): ?>
{
value: <?php echo $slice['value']; ?>,
label: "<?php echo $slice['type']; ?>",
color: randomColor({
hue: "red"
}),
highlight: "#FFFFFF"
},
<?php endforeach; ?>
]
var ctx = document.getElementById("myChart").getContext("2d");
var myPieChart = new Chart(ctx).Pie(data,{
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : false,
//String - The colour of each segment stroke
segmentStrokeColor : "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth : 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout : 0, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps : 50,
//String - Animation easing effect
animationEasing : "linear",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate : true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale : false,
//String - A legend template
legendTemplate : "",
responsive: true
});
</script>
</div>
<div class="data">
<h5 class="transaction-title">TRANSACTIONS</h5>
<div class="transactions" style="margin-top: 10px;">
<div class='legend' style="margin-left: 20px">
<p>TYPE</p>
<p style="margin-left:40px">LOCATION</p>
<p style="margin-left: 10px">DATE</p>
<p style="float:right;">VALUE</p>
</div>
<ul class="transaction-list" style="margin-top: 0px">
<?php foreach($transactions as $transaction): ?>
<li class="transaction-li" style="margin-left: -10px">
<p>
<?php if (strlen($transaction['item_type']) > 6) {
echo substr($transaction['item_type'], 0, 6);
} else {
echo $transaction['item_type'];
}
?>
</p>
<p style="margin-left:40px"><?php echo $transaction['location_bought']; ?></p>
<p style="margin-left: 10px"><?php echo date('d/m/Y', $transaction['time']); ?></p>
<p style="float:right; margin-right: 10px;">€<?php echo $transaction['value']; ?></p>
</li>
<?php endforeach; ?>
</ul>
</div>
<h3 class="total-title">TOTAL EXPENDITURE: €<?php echo $total; ?></h3>
<H3 class="total-title" style="margin-top: 50px;">MOST SPENT BY:</h3>
<h3 class="total-sub-title">MONTH: <?php echo $largestMonth; ?> (€<?php echo $largestMonthValue; ?>)</h3>
<h3 class="total-sub-title">LOCATION: <?php echo strtoupper($largestLocation); ?></h3>
<h3 class="total-sub-title">TYPE: <?php echo strtoupper($largestType); ?></h3>
</div>
</div>
</body>
</html>
|
3ceaa4b957d215e3a2d491bb7596a5f04705d97f
|
[
"Markdown",
"SQL",
"PHP"
] | 5 |
SQL
|
CalvinNolan/QR-Code-Receipt-Scanner
|
10f88fd019eaabe8299db88c7175cb339fd8f2e5
|
a08253be21c207599a9d78c3cfbf8a81fd80419f
|
refs/heads/master
|
<repo_name>VasimHayat/fn-tag<file_sep>/src/app/fn-tag/fn-tags.component.ts
import {
Component,
OnInit,
Input,
ViewEncapsulation,
Output,
EventEmitter,
} from '@angular/core';
export interface FnTagData {
id: number | string;
name: string;
}
@Component({
selector: 'fn-tag',
templateUrl: 'fn-tags.component.html',
styleUrls: ['fn-tags.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class FnTagComponent {
@Input() items: FnTagData[];
@Input() showLabel: boolean;
@Output() addCallback: EventEmitter<any> = new EventEmitter();
selectedTags: Array<FnTagData> = [];
addTagFn(name) {
return { id: name, name };
}
addAction() {
setTimeout(() => {
this.addCallback.emit(this.selectedTags);
});
}
filterTags(fnTagData: FnTagData) {
this.selectedTags = this.selectedTags.filter(el => {
return el.name !== fnTagData.name;
});
this.addCallback.emit(this.selectedTags);
}
}
<file_sep>/src/app/fn-tag/index.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FnTagComponent } from './fn-tags.component';
import { CommonModule } from '@angular/common';
import { NgSelectModule } from '@ng-select/ng-select';
@NgModule({
imports: [CommonModule, FormsModule, NgSelectModule],
declarations: [FnTagComponent],
exports: [FnTagComponent]
})
export class FnTagModule {
}
|
dca2fd16137dc261949063b96f1299ba37eea9b6
|
[
"TypeScript"
] | 2 |
TypeScript
|
VasimHayat/fn-tag
|
4fff13c9a647403c3231d38e397fbe99275eaa3c
|
b174f3353ca44e326ebe24facd6a4a85904c8179
|
refs/heads/master
|
<file_sep>package com.neoway.ssmvc.service;
import com.neoway.ssmvc.domain.Book;
import com.neoway.ssmvc.dto.AppointExecution;
import java.util.List;
/**
* @author 20190712713
* @date 2019/8/26 20:54
*/
public interface BookService {
/**
* 查询一本图书
*
* @param bookId 图书id
* @return 图书对象
*/
Book getById(long bookId);
/**
* 查询所有图书
*
* @return 图书对象列表
*/
List<Book> getList();
/**
* 预约图书
*
* @param bookId 图书ID
* @param studentId 学生学号
* @return 自定义异常
*/
AppointExecution appoint(long bookId, long studentId);
}
<file_sep>package com.neoway.ssmvc.dao;
import com.neoway.ssmvc.domain.Appointment;
import org.apache.ibatis.annotations.Param;
/**
* 预约DAO
* @author 20190712713
* @date 2019/8/26
*/
public interface AppointmentDao {
/**
* 插入预约图书记录
*
* @param bookId 图书ID
* @param studentId 学生学号
* @return 插入的行数
*/
int insertAppointment(@Param("bookId") long bookId, @Param("studentId") long studentId);
/**
* 通过主键查询预约图书记录,并且携带图书实体
*
* @param bookId 图书id
* @param studentId 学生id
* @return 预约实体记录
*/
Appointment queryByKeyWithBook(@Param("bookId") long bookId, @Param("studentId") long studentId);
}
<file_sep>
USE ssmvc;
-- 创建图书表
CREATE TABLE `book`
(
`book_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '图书ID',
`name` varchar(100) NOT NULL COMMENT '图书名称',
`number` int(11) NOT NULL COMMENT '馆藏数量',
PRIMARY KEY (`book_id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1000
DEFAULT CHARSET = utf8 COMMENT ='图书表';
-- 初始化图书数据
INSERT INTO `book` (`book_id`, `name`, `number`)
VALUES (1000, 'Java程序设计', 10),
(1001, '数据结构', 10),
(1002, '设计模式', 10),
(1003, '编译原理', 10);
-- 创建预约图书表
CREATE TABLE `appointment`
(
`book_id` bigint(20) NOT NULL COMMENT '图书ID',
`student_id` bigint(20) NOT NULL COMMENT '学号',
`appoint_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '预约时间',
PRIMARY KEY (`book_id`, `student_id`),
INDEX `idx_appoint_time` (`appoint_time`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='预约图书表';
<file_sep>package com.neoway.ssmvc.exception;
/**
* 重复预约异常
* @author 20190712713
* @date 2019/8/26 20:43
*/
public class RepeatAppointException extends RuntimeException {
public RepeatAppointException(String message) {
super(message);
}
public RepeatAppointException(String message, Throwable cause) {
super(message, cause);
}
}
<file_sep>package com.neoway.ssmvc.service.impl;
import com.neoway.ssmvc.service.AppointmentService;
/**
* @author 20190712713
* @date 2019/8/26 20:55
*/
public class AppointmentServiceImpl implements AppointmentService {
}
<file_sep>package com.neoway.ssmvc.service.impl;
import com.neoway.ssmvc.dao.BaseTest;
import com.neoway.ssmvc.dto.AppointExecution;
import com.neoway.ssmvc.service.BookService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class BookServiceImplTest extends BaseTest {
@Autowired
private BookService bookService;
@Test
public void testAppoint() {
long bookId = 1003;
long studentId = 12345678910L;
AppointExecution execution = bookService.appoint(bookId, studentId);
System.out.println(execution);
}
}
|
f30f8180a970724d8951ca5f8e58265bcee9994e
|
[
"Java",
"SQL"
] | 6 |
Java
|
OYangxt/ssmvc
|
5f79c7f76acbc7f9ecb52ea9b437a6aa87e06226
|
ec9d47c4e36b40f8e4d8dd4669727e0fb1dd34bd
|
refs/heads/master
|
<repo_name>bobsilverberg/pytest-selenium<file_sep>/pytest_selenium/safety.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from functools import partial
import os
import re
import pytest
import requests
def pytest_addoption(parser):
group = parser.getgroup('safety', 'safety')
group._addoption('--sensitiveurl',
dest='sensitive_url',
default=os.environ.get('SELENIUM_SENSITIVE_URL', '.*'),
help='regular expression for identifying sensitive urls.'
' (default: %default)')
group._addoption('--destructive',
action='store_true',
dest='run_destructive',
help='include destructive tests (tests '
'not explicitly marked as \'nondestructive\').'
' (default: %default)')
def pytest_configure(config):
if hasattr(config, 'slaveinput'):
return # xdist slave
config.addinivalue_line(
'markers', 'nondestructive: mark the test as nondestructive. '
'Tests are assumed to be destructive unless this marker is '
'present. This reduces the risk of running destructive tests '
'accidentally.')
if not config.option.run_destructive:
if config.option.markexpr:
# preserve a user configured mark expression
config.option.markexpr = 'nondestructive and (%s)' % \
config.option.markexpr
else:
config.option.markexpr = 'nondestructive'
@pytest.fixture
def _sensitive_skipping(request, base_url):
if request.config.option.skip_url_check:
return
# consider this environment sensitive if the base url or any redirection
# history matches the regular expression
response = requests.get(base_url)
urls = [history.url for history in response.history] + [response.url]
search = partial(re.search, request.config.option.sensitive_url)
matches = map(search, urls)
sensitive = any(matches)
item = request.node
destructive = 'nondestructive' not in item.keywords
if sensitive and destructive:
first_match = next(x for x in matches if x)
pytest.skip(
'This test is destructive and the target URL is '
'considered a sensitive environment. If this test is '
'not destructive, add the \'nondestructive\' marker to '
'it. Sensitive URL: %s' % first_match.string)
<file_sep>/testing/test_firefox.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
pytestmark = pytest.mark.nondestructive
def test_launch(testdir):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_pass(webtext):
assert webtext == u'Success!'
""")
testdir.quick_qa(file_test, passed=1)
def test_profile(testdir):
"""Test that specified profile is used when starting Firefox.
The profile changes the colors in the browser, which are then reflected
when calling value_of_css_property.
"""
profile = testdir.tmpdir.mkdir('profile')
profile.join('prefs.js').write(
'user_pref("browser.anchor_color", "#FF69B4");'
'user_pref("browser.display.foreground_color", "#FF0000");'
'user_pref("browser.display.use_document_colors", false);')
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_profile(base_url, mozwebqa):
mozwebqa.selenium.get(base_url)
header = mozwebqa.selenium.find_element_by_tag_name('h1')
anchor = mozwebqa.selenium.find_element_by_tag_name('a')
header_color = header.value_of_css_property('color')
anchor_color = anchor.value_of_css_property('color')
assert header_color == 'rgba(255, 0, 0, 1)'
assert anchor_color == 'rgba(255, 105, 180, 1)'
""")
testdir.quick_qa('--profilepath=%s' % profile, file_test, passed=1)
def test_profile_with_preferences(testdir):
"""Test that preferences override profile when starting Firefox.
The profile changes the colors in the browser, which are then reflected
when calling value_of_css_property. The test checks that the color of the
h1 tag is overridden by the profile, while the color of the a tag is
overridden by the preference.
"""
profile = testdir.tmpdir.mkdir('profile')
profile.join('prefs.js').write(
'user_pref("browser.anchor_color", "#FF69B4");'
'user_pref("browser.display.foreground_color", "#FF0000");'
'user_pref("browser.display.use_document_colors", false);')
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_preferences(mozwebqa):
mozwebqa.selenium.get(mozwebqa.base_url)
header = mozwebqa.selenium.find_element_by_tag_name('h1')
anchor = mozwebqa.selenium.find_element_by_tag_name('a')
header_color = header.value_of_css_property('color')
anchor_color = anchor.value_of_css_property('color')
assert header_color == 'rgba(255, 0, 0, 1)'
assert anchor_color == 'rgba(255, 0, 0, 1)'
""")
testdir.quick_qa('--firefoxpref=browser.anchor_color:#FF0000',
'--profilepath=%s' % profile, file_test, passed=1)
def test_extension(testdir):
"""Test that a firefox extension can be added when starting Firefox."""
import os
path = os.path.join(os.path.split(os.path.dirname(__file__))[0], 'testing')
extension = os.path.join(path, 'empty.xpi')
file_test = testdir.makepyfile("""
import time
import pytest
@pytest.mark.nondestructive
def test_extension(mozwebqa):
mozwebqa.selenium.get('about:support')
time.sleep(1)
extensions = mozwebqa.selenium.find_element_by_id(
'extensions-tbody').text
assert 'Test Extension (empty)' in extensions
""")
testdir.quick_qa('--extension=%s' % extension, file_test, passed=1)
def test_proxy(testdir, webserver_base_url, webserver):
"""Test that a proxy can be set for Firefox."""
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_proxy(mozwebqa):
mozwebqa.selenium.get('http://example.com')
header = mozwebqa.selenium.find_element_by_tag_name('h1')
assert header.text == 'Success!'
""")
testdir.quick_qa(webserver_base_url, '--proxyhost=localhost',
'--proxyport=%s' % webserver.port, file_test, passed=1)
<file_sep>/testing/test_opera.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
pytestmark = pytest.mark.nondestructive
@pytest.mark.opera
def test_proxy(testdir, webserver_base_url, webserver):
"""Test that a proxy can be set for Opera."""
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_selenium(mozwebqa):
mozwebqa.selenium.get('http://example.com')
header = mozwebqa.selenium.find_element_by_tag_name('h1')
assert header.text == 'Success!'
""")
testdir.quick_qa(webserver_base_url,
'--driver=opera',
'--proxyhost=localhost',
'--proxyport=%s' % webserver.port, file_test, passed=1)
<file_sep>/testing/test_timeout.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
pytestmark = pytest.mark.nondestructive
def test_default_timeout(testdir, webserver):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_timeout(mozwebqa):
assert mozwebqa.timeout == 60
""")
testdir.quick_qa(file_test, passed=1)
def test_custom_timeout(testdir, webserver):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_timeout(mozwebqa):
assert mozwebqa.timeout == 30
""")
testdir.quick_qa('--webqatimeout=30', file_test, passed=1)
<file_sep>/testing/test_webdriver.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from selenium.webdriver.support.abstract_event_listener import \
AbstractEventListener
pytestmark = pytest.mark.nondestructive
def test_event_listening_webdriver(testdir, webserver):
file_test = testdir.makepyfile("""
import pytest
from selenium.webdriver.support.event_firing_webdriver import \
EventFiringWebDriver
@pytest.mark.nondestructive
def test_selenium(base_url, mozwebqa):
assert isinstance(mozwebqa.selenium, EventFiringWebDriver)
with pytest.raises(Exception) as e:
mozwebqa.selenium.get(base_url)
assert 'before_navigate_to' in e.exconly()
""")
testdir.quick_qa('--eventlistener=test_webdriver.ConcreteEventListener',
file_test, passed=1)
class ConcreteEventListener(AbstractEventListener):
def before_navigate_to(self, url, driver):
raise Exception('before_navigate_to')
<file_sep>/pytest_selenium/cloud/browserstack.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from ConfigParser import ConfigParser
import os
import pytest
import requests
from selenium import webdriver
name = 'BrowserStack'
def _get_config(option):
config = ConfigParser()
config.read('setup.cfg')
section = 'browserstack'
if config.has_section(section) and config.has_option(section, option):
return config.get(section, option)
def _credentials():
username = os.getenv('BROWSERSTACK_USERNAME', _get_config('username'))
access_key = os.getenv('BROWSERSTACK_ACCESS_KEY',
_get_config('access-key'))
if not username:
raise pytest.UsageError('BrowserStack username must be set')
if not access_key:
raise pytest.UsageError('BrowserStack access key must be set')
return username, access_key
def _split_class_and_test_names(nodeid):
# TODO remove duplication of shared code
names = nodeid.split("::")
names[0] = names[0].replace("/", '.')
names = [x.replace(".py", "") for x in names if x != "()"]
classnames = names[:-1]
classname = ".".join(classnames)
name = names[-1]
return (classname, name)
def start_driver(item, options, capabilities):
test_id = '.'.join(_split_class_and_test_names(item.nodeid))
capabilities.update({
'name': test_id,
'browserName': options.browser_name})
if options.platform is not None:
capabilities['platform'] = options.platform
if options.browser_version is not None:
capabilities['version'] = options.browser_version
if options.build is not None:
capabilities['build'] = options.build
executor = 'http://%s:%[email protected]:80/wd/hub' % _credentials()
return webdriver.Remote(command_executor=executor,
desired_capabilities=capabilities)
def url(session):
response = requests.get(
'https://www.browserstack.com/automate/sessions/%s.json' % session,
auth=_credentials())
return response.json()['automation_session']['browser_url']
def additional_html(session):
return []
def update_status(session, passed):
status = {'status': 'completed' if passed else 'error'}
requests.put(
'https://www.browserstack.com/automate/sessions/%s.json' % session,
headers={'Content-Type': 'application/json'},
params=status,
auth=_credentials())
<file_sep>/pytest_selenium/driver.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import json
import pytest
from selenium.webdriver.support.event_firing_webdriver import \
EventFiringWebDriver
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium import webdriver
def proxy_from_options(options):
if options.proxy_host and options.proxy_port:
proxy_str = '%(proxy_host)s:%(proxy_port)s' % vars(options)
proxy = Proxy()
proxy.ssl_proxy = proxy.http_proxy = proxy_str
return proxy
def make_driver(item):
options = item.config.option
capabilities = {}
if options.capabilities is not None:
for c in options.capabilities:
name, value = c.split(':')
# handle integer capabilities
if value.isdigit():
value = int(value)
# handle boolean capabilities
elif value.lower() in ['true', 'false']:
value = value.lower() == 'true'
capabilities[name] = value
proxy = proxy_from_options(options)
if proxy is not None:
proxy.add_to_capabilities(capabilities)
return start_driver(item, options, capabilities)
def start_driver(item, options, capabilities):
specific_driver = '%s_driver' % options.driver.lower()
driver_method = globals().get(specific_driver, generic_driver)
driver = driver_method(item, options, capabilities)
if options.event_listener is not None:
mod_name, class_name = options.event_listener.rsplit('.', 1)
mod = __import__(mod_name, fromlist=[class_name])
event_listener = getattr(mod, class_name)
if not isinstance(driver, EventFiringWebDriver):
driver = EventFiringWebDriver(driver, event_listener())
return driver
def generic_driver(item, options, capabilities):
return getattr(webdriver, options.driver)()
def browserstack_driver(item, options, capabilities):
from cloud import browserstack
return browserstack.start_driver(item, options, capabilities)
def chrome_driver(item, options, capabilities):
chrome_options = _create_chrome_options(options)
extra = {}
if options.chrome_path:
extra['executable_path'] = options.chrome_path
return webdriver.Chrome(
chrome_options=chrome_options,
desired_capabilities=capabilities or None,
**extra)
def firefox_driver(item, options, capabilities):
if options.firefox_path:
binary = FirefoxBinary(options.firefox_path)
else:
binary = None
profile = _create_firefox_profile(options)
return webdriver.Firefox(
firefox_binary=binary,
firefox_profile=profile,
capabilities=capabilities or None)
def ie_driver(item, options, capabilities):
return webdriver.Ie()
def opera_driver(item, options, capabilities):
capabilities.update(webdriver.DesiredCapabilities.OPERA)
return webdriver.Opera(
executable_path=options.opera_path,
desired_capabilities=capabilities)
def phantomjs_driver(item, options, capabilities):
return webdriver.PhantomJS()
def remote_driver(item, options, capabilities):
if not options.browser_name:
raise pytest.UsageError(
'--browsername must be specified when using a server.')
if not options.platform:
raise pytest.UsageError(
'--platform must be specified when using a server.')
capabilities.update(getattr(webdriver.DesiredCapabilities,
options.browser_name.upper()))
if json.loads(options.chrome_options) or options.extension_paths:
capabilities = _create_chrome_options(options).to_capabilities()
if options.browser_name.lower() == 'firefox':
profile = _create_firefox_profile(options)
if options.browser_version:
capabilities['version'] = options.browser_version
capabilities['platform'] = options.platform.upper()
executor = 'http://%s:%s/wd/hub' % (options.host, options.port)
try:
return webdriver.Remote(
command_executor=executor,
desired_capabilities=capabilities or None,
browser_profile=profile)
except AttributeError:
valid_browsers = [
attr for attr in dir(webdriver.DesiredCapabilities)
if not attr.startswith('__')
]
raise AttributeError(
"Invalid browser name: '%s'. Valid options are: %s" %
(options.browser_name, ', '.join(valid_browsers)))
def saucelabs_driver(item, options, capabilities):
from cloud import saucelabs
return saucelabs.start_driver(item, options, capabilities)
def _create_chrome_options(options):
chrome_options = webdriver.ChromeOptions()
if options.chrome_options is None:
return chrome_options
options_from_json = json.loads(options.chrome_options)
if 'arguments' in options_from_json:
for args_ in options_from_json['arguments']:
chrome_options.add_argument(args_)
if 'binary_location' in options_from_json:
chrome_options.binary_location = options_from_json['binary_location']
if options.extension_paths is not None:
for extension in options.extension_paths:
chrome_options.add_extension(extension)
return chrome_options
def _create_firefox_profile(options):
profile = webdriver.FirefoxProfile(options.profile_path)
if options.firefox_preferences is not None:
for p in options.firefox_preferences:
name, value = p.split(':')
# handle integer preferences
if value.isdigit():
value = int(value)
# handle boolean preferences
elif value.lower() in ['true', 'false']:
value = value.lower() == 'true'
profile.set_preference(name, value)
profile.assume_untrusted_cert_issuer = options.assume_untrusted
profile.update_preferences()
if options.extension_paths is not None:
for extension in options.extension_paths:
profile.add_extension(extension)
return profile
<file_sep>/README.rst
pytest-selenium
===============
pytest-selenium is a plugin for `py.test <http://pytest.org>`_ that provides
support for running `Selenium <http://seleniumhq.org/>`_ based tests. This
plugin is still in development. Please check back for updates.
.. image:: https://img.shields.io/pypi/l/pytest-selenium.svg
:target: https://github.com/davehunt/pytest-selenium/blob/master/LICENSE
:alt: License
.. image:: https://img.shields.io/pypi/v/pytest-selenium.svg
:target: https://pypi.python.org/pypi/pytest-selenium/
:alt: PyPI
.. image:: https://img.shields.io/travis/davehunt/pytest-selenium.svg
:target: https://travis-ci.org/davehunt/pytest-selenium/
:alt: Travis
.. image:: https://img.shields.io/github/issues-raw/davehunt/pytest-selenium.svg
:target: https://github.com/davehunt/pytest-selenium/issues
:alt: Issues
.. image:: https://img.shields.io/requires/github/davehunt/pytest-selenium.svg
:target: https://requires.io/github/davehunt/pytest-selenium/requirements/?branch=master
:alt: Requirements
<file_sep>/pytest_selenium/cloud/saucelabs.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from ConfigParser import ConfigParser
import os
import json
from py.xml import html
import pytest
import requests
from selenium import webdriver
name = 'Sauce Labs'
def _get_config(option):
config = ConfigParser()
config.read('setup.cfg')
section = 'saucelabs'
if config.has_section(section) and config.has_option(section, option):
return config.get(section, option)
def _credentials():
username = os.getenv('SAUCELABS_USERNAME', _get_config('username'))
api_key = os.getenv('SAUCELABS_API_KEY', _get_config('api-key'))
if not username:
raise pytest.UsageError('Sauce Labs username must be set')
if not api_key:
raise pytest.UsageError('Sauce Labs API key must be set')
return username, api_key
def _tags():
tags = _get_config('tags')
if tags:
return tags.split(',')
return []
def _split_class_and_test_names(nodeid):
# TODO remove duplication of shared code
names = nodeid.split("::")
names[0] = names[0].replace("/", '.')
names = [x.replace(".py", "") for x in names if x != "()"]
classnames = names[:-1]
classname = ".".join(classnames)
name = names[-1]
return (classname, name)
def start_driver(item, options, capabilities):
from _pytest.mark import MarkInfo
tags = _tags() + [m for m in item.keywords.keys() if isinstance(
item.keywords[m], MarkInfo)]
try:
privacy = item.keywords['privacy'].args[0]
except (IndexError, KeyError):
# privacy mark is not present or has no value
privacy = _get_config('privacy')
if options.browser_name is None:
raise pytest.UsageError('Sauce Labs requires a browser name')
test_id = '.'.join(_split_class_and_test_names(item.nodeid))
capabilities.update({
'name': test_id,
'public': privacy,
'browserName': options.browser_name})
if options.build is not None:
capabilities['build'] = options.build
if tags is not None and len(tags) > 0:
capabilities['tags'] = tags
if options.platform is not None:
capabilities['platform'] = options.platform
if options.browser_version is not None:
capabilities['version'] = options.browser_version
executor = 'http://%s:%[email protected]:80/wd/hub' % _credentials()
return webdriver.Remote(command_executor=executor,
desired_capabilities=capabilities)
def url(session):
return 'http://saucelabs.com/jobs/%s' % session
def additional_html(session):
return [_video_html(session)]
def update_status(session, passed):
username, api_key = _credentials()
status = {'passed': passed}
requests.put(
'http://saucelabs.com//rest/v1/%s/jobs/%s' % (username, session),
data=json.dumps(status), auth=(username, api_key))
def _video_html(session):
flash_vars = 'config={\
"clip":{\
"url":"https://assets.saucelabs.com/jobs/%(session)s/video.flv",\
"provider":"streamer",\
"autoPlay":false,\
"autoBuffering":true},\
"play": {\
"opacity":1,\
"label":null,\
"replayLabel":null},\
"plugins":{\
"streamer":{\
"url":"https://cdn1.saucelabs.com/sauce_skin_deprecated/lib/flowplayer/flowplayer.pseudostreaming-3.2.13.swf",\
"queryString":"%%3Fstart%%3D%%24%%7Bstart%%7D"},\
"controls":{\
"mute":false,\
"volume":false,\
"backgroundColor":"rgba(0,0,0,0.7)"}},\
"playerId":"player%(session)s",\
"playlist":[{\
"url":"https://assets.saucelabs.com/jobs/%(session)s/video.flv",\
"provider":"streamer",\
"autoPlay":false,\
"autoBuffering":true}]}' % {'session': session}
return html.div(html.object(
html.param(value='true', name='allowfullscreen'),
html.param(value='always', name='allowscriptaccess'),
html.param(value='high', name='quality'),
html.param(value='#000000', name='bgcolor'),
html.param(
value=flash_vars.replace(' ', ''),
name='flashvars'),
width='100%',
height='100%',
type='application/x-shockwave-flash',
data='https://cdn1.saucelabs.com/sauce_skin_deprecated/lib/flowplayer/'
'flowplayer-3.2.17.swf',
name='player_api',
id='player_api'),
id='player%s' % session,
style='border:1px solid #e6e6e6; float:right; height:240px;'
'margin-left:5px; overflow:hidden; width:320px')
<file_sep>/testing/test_destructive.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
pytestmark = pytest.mark.nondestructive
def test_skip_destructive_by_default(testdir):
file_test = testdir.makepyfile('def test_pass(): pass')
testdir.quick_qa(file_test, passed=0, failed=0, skipped=0)
def test_run_non_destructive_by_default(testdir):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_pass(): pass
""")
testdir.quick_qa(file_test, passed=1)
def test_run_destructive_when_forced(testdir):
file_test = testdir.makepyfile('def test_pass(): pass')
testdir.quick_qa('--destructive', file_test, passed=1)
def test_run_destructive_and_non_destructive_when_forced(testdir):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_pass1(): pass
def test_pass2(): pass
""")
testdir.quick_qa('--destructive', file_test, passed=2)
def test_skip_destructive_when_forced_and_sensitive(testdir):
file_test = testdir.makepyfile('def test_pass(_sensitive_skipping): pass')
testdir.quick_qa('--destructive', file_test, skipped=1)
def test_run_destructive_when_forced_and_not_sensitive(testdir):
file_test = testdir.makepyfile('def test_pass(_sensitive_skipping): pass')
testdir.quick_qa('--destructive', '--sensitiveurl=foo', file_test,
passed=1)
<file_sep>/testing/test_base_url.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
pytestmark = pytest.mark.nondestructive
def failure_with_output(testdir, *args, **kwargs):
reprec = testdir.inline_run(*args, **kwargs)
passed, skipped, failed = reprec.listoutcomes()
assert len(failed) == 1
out = failed[0].longrepr.reprcrash.message
return out
def test_missing_base_url(testdir):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_pass(mozwebqa): pass
""")
out = failure_with_output(testdir, file_test)
assert out == 'UsageError: --baseurl must be specified.'
def test_fixture(testdir):
file_test = testdir.makepyfile("""
import pytest
@pytest.fixture(scope='session')
def base_url():
return 'foo'
@pytest.fixture(scope='session')
def _verify_base_url():
pass
@pytest.mark.nondestructive
def test_fixture(base_url):
assert base_url == 'foo'
""")
testdir.quick_qa(file_test, passed=1)
def test_funcarg(testdir, webserver):
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_funcarg(base_url):
assert base_url == 'http://localhost:%s'
""" % webserver.port)
testdir.quick_qa(file_test, passed=1)
def test_failing_base_url(testdir, webserver):
status_code = 500
base_url = 'http://localhost:%s/%s/' % (webserver.port, status_code)
testdir.makepyfile("""
import pytest
@pytest.fixture(scope='session')
def base_url():
return '%s'
@pytest.mark.nondestructive
def test_pass(_verify_base_url): pass
""" % base_url)
result = testdir.runpytest()
assert result.ret != 0
# tracestyle is native by default for hook failures
result.stdout.fnmatch_lines([
'*UsageError: Base URL did not return status code '
'200 or 401*Response: %s, Headers:*{*}*' % status_code
])
<file_sep>/testing/conftest.py
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from webserver import SimpleWebServer
pytest_plugins = 'pytester'
@pytest.fixture(scope='session')
def base_url(webserver):
return 'http://localhost:%s' % webserver.port
@pytest.fixture
def webserver_base_url(webserver):
return '--baseurl=%s' % base_url(webserver)
@pytest.fixture(autouse=True)
def testdir(request, webserver_base_url):
item = request.node
if 'testdir' not in item.funcargnames:
return
testdir = request.getfuncargvalue('testdir')
testdir.makepyfile(conftest="""
import pytest
@pytest.fixture
def webtext(base_url, mozwebqa):
mozwebqa.selenium.get(base_url)
return mozwebqa.selenium.find_element_by_tag_name('h1').text
""")
def inline_runqa(*args, **kwargs):
return testdir.inline_run(
webserver_base_url,
'--driver=firefox',
*args, **kwargs)
testdir.inline_runqa = inline_runqa
def quick_qa(*args, **kwargs):
reprec = inline_runqa(*args)
outcomes = reprec.listoutcomes()
names = ('passed', 'skipped', 'failed')
for name, val in zip(names, outcomes):
wantlen = kwargs.get(name)
if wantlen is not None:
assert len(val) == wantlen, name
testdir.quick_qa = quick_qa
return testdir
@pytest.fixture(scope='session', autouse=True)
def webserver(request):
webserver = SimpleWebServer()
webserver.start()
request.addfinalizer(webserver.stop)
return webserver
<file_sep>/pytest_selenium/pytest_selenium.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import ConfigParser
import pytest
import requests
import cloud
REQUESTS_TIMEOUT = 10
class DeferPlugin(object):
"""Simple plugin to defer pytest-html hook functions."""
def pytest_html_environment(self, config):
driver = config.option.driver
if hasattr(cloud, driver.lower()):
server = getattr(cloud, driver.lower()).name
else:
server = 'http://%s:%s' % (config.option.host,
config.option.port)
browser = config.option.browser_name and \
config.option.browser_version and \
config.option.platform and \
'%s %s on %s' % (str(config.option.browser_name).title(),
config.option.browser_version,
str(config.option.platform).title())
return {'Base URL': config.option.base_url,
'Build': config.option.build,
'Driver': config.option.driver,
'Firefox Path': config.option.firefox_path,
'Google Chrome Path': config.option.chrome_path,
'Server': server,
'Browser': browser,
'Timeout': config.option.webqatimeout}
@pytest.mark.tryfirst
def pytest_configure(config):
if config.pluginmanager.hasplugin('html'):
config.pluginmanager.register(DeferPlugin())
def pytest_sessionstart(session):
# configure session proxies
option = session.config.option
if hasattr(session.config, 'browsermob_session_proxy'):
option.proxy_host = option.bmp_host
option.proxy_port = session.config.browsermob_session_proxy.port
zap = getattr(session.config, 'zap', None)
if zap is not None:
if option.proxy_host and option.proxy_port:
zap.core.set_option_proxy_chain_name(option.proxy_host)
zap.core.set_option_proxy_chain_port(option.proxy_port)
option.proxy_host = option.zap_host
option.proxy_port = option.zap_port
@pytest.fixture(scope='session')
def base_url(request):
url = request.config.option.base_url
if not url:
raise pytest.UsageError('--baseurl must be specified.')
return url
@pytest.fixture(scope='session', autouse=True)
def _verify_base_url(request, base_url):
option = request.config.option
if base_url and not option.skip_url_check:
response = requests.get(base_url, timeout=REQUESTS_TIMEOUT)
if response.status_code not in (200, 401):
raise pytest.UsageError(
'Base URL did not return status code 200 or 401. '
'(URL: %s, Response: %s, Headers: %s)' % (
base_url, response.status_code, response.headers))
@pytest.fixture
def driver(request):
from .driver import make_driver
driver = make_driver(request.node)
request.node._driver = driver
request.addfinalizer(lambda: driver.quit())
return driver
@pytest.fixture
def mozwebqa(request, _sensitive_skipping, driver, base_url):
return TestSetup(request, driver, base_url)
def pytest_runtest_setup(item):
# configure test proxies
option = item.config.option
if hasattr(item.config, 'browsermob_test_proxy'):
option.proxy_host = item.config.option.bmp_host
option.proxy_port = item.config.browsermob_test_proxy.port
def pytest_runtest_makereport(__multicall__, item, call):
pytest_html = item.config.pluginmanager.getplugin('html')
extra_summary = []
report = __multicall__.execute()
extra = getattr(report, 'extra', [])
try:
report.public = item.keywords['privacy'].args[0] == 'public'
except (IndexError, KeyError):
# privacy mark is not present or has no value
report.public = False
if report.when == 'call':
driver = getattr(item, '_driver', None)
if driver is not None:
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
url = driver.current_url
if url is not None:
extra_summary.append('Failing URL: %s' % url)
if pytest_html is not None:
extra.append(pytest_html.extras.url(url))
screenshot = driver.get_screenshot_as_base64()
if screenshot is not None and pytest_html is not None:
extra.append(pytest_html.extras.image(
screenshot, 'Screenshot'))
html = driver.page_source.encode('utf-8')
if html is not None and pytest_html is not None:
extra.append(pytest_html.extras.text(html, 'HTML'))
driver_name = item.config.option.driver
if hasattr(cloud, driver_name.lower()) and driver.session_id:
provider = getattr(cloud, driver_name.lower())
extra_summary.append('%s Job: %s' % (
provider.name, provider.url(driver.session_id)))
if pytest_html is not None:
extra.append(pytest_html.extras.url(
provider.url(driver.session_id),
'%s Job' % provider.name))
extra.append(pytest_html.extras.html(
provider.additional_html(driver.session_id)))
passed = report.passed or (report.failed and xfail)
provider.update_status(driver.session_id, passed)
report.sections.append(('pytest-selenium', '\n'.join(extra_summary)))
report.extra = extra
return report
def pytest_addoption(parser):
config = ConfigParser.ConfigParser(defaults={'baseurl': ''})
config.read('mozwebqa.cfg')
group = parser.getgroup('selenium', 'selenium')
group._addoption('--baseurl',
action='store',
dest='base_url',
default=config.get('DEFAULT', 'baseurl'),
metavar='url',
help='base url for the application under test.')
group._addoption('--skipurlcheck',
action='store_true',
dest='skip_url_check',
default=False,
help='skip the base url and sensitivity checks. '
'(default: %default)')
group._addoption('--host',
action='store',
default=os.environ.get('SELENIUM_HOST', 'localhost'),
metavar='str',
help='host that selenium server is listening on. '
'(default: %default)')
group._addoption('--port',
action='store',
type='int',
default=os.environ.get('SELENIUM_PORT', 4444),
metavar='num',
help='port that selenium server is listening on. '
'(default: %default)')
group._addoption('--driver',
action='store',
dest='driver',
default=os.environ.get('SELENIUM_DRIVER', 'Remote'),
metavar='str',
help='webdriver implementation. (default: %default)')
group._addoption('--capability',
action='append',
dest='capabilities',
metavar='str',
help='additional capability to set in format '
'"name:value".')
group._addoption('--chromepath',
action='store',
dest='chrome_path',
metavar='path',
help='path to the google chrome driver executable.')
group._addoption('--firefoxpath',
action='store',
dest='firefox_path',
metavar='path',
help='path to the target firefox binary.')
group._addoption('--firefoxpref',
action='append',
dest='firefox_preferences',
metavar='str',
help='firefox preference name and value to set in format '
'"name:value".')
group._addoption('--profilepath',
action='store',
dest='profile_path',
metavar='str',
help='path to the firefox profile to use.')
group._addoption('--extension',
action='append',
dest='extension_paths',
metavar='str',
help='path to browser extension to install.')
group._addoption('--chromeopts',
action='store',
dest='chrome_options',
metavar='str',
help='json string of google chrome options to set.')
group._addoption('--operapath',
action='store',
dest='opera_path',
metavar='path',
help='path to the opera driver.')
group._addoption('--browsername',
action='store',
dest='browser_name',
default=os.environ.get('SELENIUM_BROWSER'),
metavar='str',
help='target browser name (default: %default).')
group._addoption('--browserver',
action='store',
dest='browser_version',
default=os.environ.get('SELENIUM_VERSION'),
metavar='str',
help='target browser version (default: %default).')
group._addoption('--platform',
action='store',
default=os.environ.get('SELENIUM_PLATFORM'),
metavar='str',
help='target platform (default: %default).')
group._addoption('--webqatimeout',
action='store',
type='int',
default=60,
metavar='num',
help='timeout (in seconds) for page loads, etc. '
'(default: %default)')
group._addoption('--build',
action='store',
dest='build',
metavar='str',
help='build identifier (for continuous integration).')
group._addoption('--untrusted',
action='store_true',
dest='assume_untrusted',
default=False,
help='assume that all certificate issuers are untrusted. '
'(default: %default)')
group._addoption('--proxyhost',
action='store',
dest='proxy_host',
metavar='str',
help='use a proxy running on this host.')
group._addoption('--proxyport',
action='store',
dest='proxy_port',
metavar='int',
help='use a proxy running on this port.')
group._addoption('--eventlistener',
action='store',
dest='event_listener',
metavar='str',
help='selenium eventlistener class, e.g. '
'package.module.EventListenerClassName.')
class TestSetup:
default_implicit_wait = 10
def __init__(self, request, driver, base_url):
self.request = request
self.selenium = driver
self.base_url = base_url
self.timeout = request.node.config.option.webqatimeout
self.selenium.implicitly_wait(self.default_implicit_wait)
<file_sep>/testing/test_saucelabs.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from functools import partial
import re
import pytest
pytestmark = pytestmark = [pytest.mark.skip_selenium,
pytest.mark.nondestructive]
@pytest.fixture
def testfile(testdir):
return testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_pass(mozwebqa): pass
""")
def failure_with_output(testdir, *args, **kwargs):
reprec = testdir.inline_run(*args, **kwargs)
passed, skipped, failed = reprec.listoutcomes()
assert len(failed) == 1
out = failed[0].longrepr.reprcrash.message
return out
@pytest.fixture
def failure(testdir, testfile, webserver_base_url):
return partial(failure_with_output, testdir, testfile, webserver_base_url,
'--driver=saucelabs')
def test_missing_browser_name(failure, monkeypatch):
monkeypatch.setenv('SAUCELABS_USERNAME', 'foo')
monkeypatch.setenv('SAUCELABS_API_KEY', 'bar')
out = failure()
assert out == 'UsageError: Sauce Labs requires a browser name'
def test_missing_username(failure):
out = failure('--browsername=firefox')
assert out == 'UsageError: Sauce Labs username must be set'
def test_missing_api_key(failure, monkeypatch):
monkeypatch.setenv('SAUCELABS_USERNAME', 'foo')
out = failure('--browsername=firefox')
assert out == 'UsageError: Sauce Labs API key must be set'
def test_invalid_credentials(failure, monkeypatch):
monkeypatch.setenv('SAUCELABS_USERNAME', 'foo')
monkeypatch.setenv('SAUCELABS_API_KEY', 'bar')
out = failure('--browsername=firefox')
assert re.search('(auth failed)|(Sauce Labs Authentication Error)', out)
<file_sep>/testing/test_chrome.py
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from functools import partial
import pytest
pytestmark = pytest.mark.nondestructive
@pytest.fixture
def testfile(testdir):
return testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_pass(mozwebqa): pass
""")
def failure_with_output(testdir, *args, **kwargs):
reprec = testdir.inline_run(*args, **kwargs)
passed, skipped, failed = reprec.listoutcomes()
assert len(failed) == 1
out = failed[0].longrepr.reprcrash.message
return out
@pytest.fixture
def failure(testdir, testfile, webserver_base_url):
return partial(failure_with_output, testdir, testfile, webserver_base_url)
def test_missing_chrome_binary(failure):
out = failure('--driver=chrome',
'--chromeopts={"binary_location":"foo"}')
if 'ChromeDriver executable needs to be available in the path' in out:
pytest.fail('You must have Chrome Driver installed on your path for '
'this test to run correctly. For further information see '
'pytest-mozwebqa documentation.')
assert 'Could not find Chrome binary at: foo' in out
@pytest.mark.chrome
def test_proxy(testdir, webserver_base_url, webserver):
"""Test that a proxy can be set for Chrome."""
file_test = testdir.makepyfile("""
import pytest
@pytest.mark.nondestructive
def test_selenium(mozwebqa):
mozwebqa.selenium.get('http://example.com')
header = mozwebqa.selenium.find_element_by_tag_name('h1')
assert header.text == 'Success!'
""")
testdir.quick_qa(webserver_base_url,
'--driver=chrome',
'--proxyhost=localhost',
'--proxyport=%s' % webserver.port, file_test, passed=1)
|
b1d085f2e0e87a5dea95c6b38b39febdf2e8d97c
|
[
"Python",
"reStructuredText"
] | 15 |
Python
|
bobsilverberg/pytest-selenium
|
f058203698979bb1c99020b3ebd752987a6d7c2c
|
9530a91fc794146174353eeb4acb732a3cfe701f
|
refs/heads/main
|
<file_sep>import React, { useContext } from 'react';
import Link from 'next/link';
const Sidebar = () => {
return (
<div className='md:w-2/5 xl:w-1/5 bg-blue-600 rounded-xl mt-2'>
<div className='p-6'>
<p className='mt-2 text-white uppercase text-2xl tracking-wide text-center font-bold'>
MENU
</p>
<nav className='mt-10 group'>
<Link href='/reservahora'>
<a className='mt-5 text-xl text-white textColor group-hover:text-gray-600'>
Reserva de Horas
</a>
</Link>
<div className='mt-4'>
<Link href='misreservas'>
<a className='text-xl text-white group-hover:text-gray-600'>
Mis Reservas
</a>
</Link>
</div>
</nav>
</div>
</div>
);
};
export default Sidebar;
<file_sep>import React, { useContext, useEffect } from 'react';
import Link from 'next/link';
import authContext from '../context/auth/authContext';
const Header = () => {
const AuthContext = useContext(authContext);
const { usuario, usuarioAutenticado, cerrarSesion } = AuthContext;
useEffect(() => {
usuarioAutenticado();
}, []);
return (
<header className=' bg-gray-200 py-8 flex flex-col md:flex-row items-center justify-between h-32 rounded-full'>
<Link href='/'>
<a>
<img
className=' object-contain object-left-top w-64'
src='logo.png'
/>
</a>
</Link>
<div>
{usuario ? (
<div className='flex items-center'>
<div class='p-10'>
<div className='dropdown inline-block relative'>
<button
type='button'
className='bg-blue-500 px-5 py-3 rounded-lg text-white uppercase'
>
<span className='mr-1'>Mi Perfil</span>
</button>
<ul className='dropdown-menu absolute hidden bg-blue-200 pt-0'>
<li className=''>
<a
className='rounded-t bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap'
href='#'
>
Editar datos
</a>
</li>
{/* <li className=''>
<a
className='bg-blue-500 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap'
href='#'
>
Two
</a>
</li> */}
</ul>
</div>
</div>
{/* <p className='mr-2 font-bold text-transform: capitalize'>
Hola {usuario.nombre}
</p> */}
<button
type='button'
className='bg-blue-500 px-5 py-3 rounded-lg text-white uppercase mr-3'
onClick={() => cerrarSesion()}
>
Cerrar Sesión
</button>
</div>
) : (
<>
<Link href='/login'>
<a className='bg-blue-500 px-5 py-3 rounded-lg text-white uppercase mr-2'>
Iniciar Sesión
</a>
</Link>
<Link href='/crearcuenta'>
<a className='bg-blue-500 px-5 py-3 rounded-lg text-white uppercase'>
Crear Cuenta
</a>
</Link>
</>
)}
</div>
</header>
);
};
export default Header;
<file_sep>import React, { useState } from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';
const FormDoctor = () => {
const [medicos, guardarMedictos] = useState([
'<NAME>',
'<NAME>',
'<NAME>',
]);
let medicosList =
medicos.length > 0 &&
medicos.map((item, i) => {
return (
<>
<option key={item} value={item}>
{item}
</option>
</>
);
});
const formik = useFormik({
initialValues: {
email: '',
password: '',
},
validationSchema: Yup.object({
email: Yup.string()
.email('El email no es válido')
.required('El email es obligatorio'),
password: Yup.string().required('El password es obligatorio'),
}),
onSubmit: (valores) => {
iniciarSesion(valores);
},
});
return (
<>
<div className='md:w-3/5 xl:w-4/5 mx-auto p-6 '>
<div className='flex'>
<div className='w-full'>
<form
className='bg-white rounded shadown-md px-8 pt-6 pb-8 mb-4 grid grid-cols-2'
onSubmit={formik.handleSubmit}
>
<div className='col-auto mr-4'>
<div className='mb-4'>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='nombre'
>
Nombre
</label>
<input
type='text'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mb-2'
id='nombre'
placeholder='Nombre'
// value={formik.values.password}
// onChange={formik.handleChange}
// onBlur={formik.handleBlur}
/>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='apellido'
>
Apellido
</label>
<input
type='text'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mb-2'
id='apellido'
placeholder='Apellido'
// value={formik.values.password}
// onChange={formik.handleChange}
// onBlur={formik.handleBlur}
/>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='email'
>
Email
</label>
<input
type='email'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
id='email'
placeholder='Correo'
value={formik.values.email}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
{formik.touched.email && formik.errors.email ? (
<div className='my-2 bg-gray-200 border-l-4 border-blue-500 text-red-600 p-4'>
<p className='font-bold'>Error</p>
<p>{formik.errors.email}</p>
</div>
) : null}
</div>
<div className='mb-4'>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='number'
>
Número de contacto
</label>
<input
type='text'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
id='numero'
placeholder='Número telefonico'
// value={formik.values.password}
// onChange={formik.handleChange}
// onBlur={formik.handleBlur}
/>
{formik.touched.password && formik.errors.password ? (
<div className='my-2 bg-gray-200 border-l-4 border-blue-500 text-red-600 p-4'>
<p className='font-bold'>Error</p>
<p>{formik.errors.password}</p>
</div>
) : null}
</div>
</div>
<div className='col-auto'>
<div className='mb-4'>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='fecha'
>
Fecha
</label>
<input
type='date'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mb-2'
id='fecha'
placeholder='Fecha'
// value={formik.values.password}
// onChange={formik.handleChange}
// onBlur={formik.handleBlur}
/>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='medico'
>
Medico
</label>
<select className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mb-2'>
<option>Seleccionar Médico</option>
{medicosList}
</select>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='hora'
>
Hora de atencion
</label>
<select
type='email'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
id='hora'
placeholder='Hora'
// value={formik.values.email}
// onChange={formik.handleChange}
// onBlur={formik.handleBlur}
/>
{formik.touched.email && formik.errors.email ? (
<div className='my-2 bg-gray-200 border-l-4 border-blue-500 text-red-600 p-4'>
<p className='font-bold'>Error</p>
<p>{formik.errors.email}</p>
</div>
) : null}
</div>
<div className='mb-4'>
<label
className='block text-black text-sm font-bold mb-2'
htmlFor='motivo'
>
Motivo Consulta
</label>
<textarea
type='text'
className='shadow appereance-none border rounder w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
id='motivo'
placeholder='Motivo'
// value={formik.values.password}
// onChange={formik.handleChange}
// onBlur={formik.handleBlur}
/>
{formik.touched.password && formik.errors.password ? (
<div className='my-2 bg-gray-200 border-l-4 border-blue-500 text-red-600 p-4'>
<p className='font-bold'>Error</p>
<p>{formik.errors.password}</p>
</div>
) : null}
<input
type='submit'
className='bg-blue-500 hover:bg-gay-900 w-full p-2 mt-5 text-white uppercase font-bold rounded'
value='Confirmar hora'
/>
</div>
</div>
</form>
</div>
</div>
</div>
</>
);
};
export default FormDoctor;
<file_sep>import React, { useState } from 'react';
import clienteAxios from '../../config/axios';
const GestionarDiasTrabajo = () => {
const [diastrabajo, guardarDiasTrabajo] = useState([]);
const [days, setDays] = useState({
Lunes: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
Martes: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
Miercoles: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
Jueves: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
Viernes: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
Sabado: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
Domingo: [
{
activo: false,
manana_comienzo: '',
manana_fin: '',
tarde_comienzo: '',
tarde_fin: '',
},
],
});
const [timemorning, setTimemorning] = useState([
{ Id: '05:00', value: '05:00' },
{ Id: '05:30', value: '05:30' },
{ Id: '06:00', value: '06:00' },
{ Id: '06:30', value: '06:30' },
{ Id: '07:00', value: '07:00' },
{ Id: '07:30', value: '07:30' },
{ Id: '08:00', value: '08:00' },
{ Id: '08:30', value: '08:30' },
{ Id: '09:00', value: '09:00' },
{ Id: '09:30', value: '09:30' },
{ Id: '10:00', value: '10:00' },
{ Id: '10:30', value: '10:30' },
{ Id: '11:00', value: '11:00' },
{ Id: '11:30', value: '11:30' },
{ Id: '12:00', value: '12:00' },
]);
let timeListMorning =
timemorning.length > 0 &&
timemorning.map((item, i) => {
return (
<>
<option key={item.Id} value={item.id}>
{item.value}
</option>
</>
);
});
const [timeafternoon, setTimeafternoon] = useState([
{ Id: '12:30', value: '12:30' },
{ Id: '13:00', value: '13:00' },
{ Id: '13:30', value: '13:30' },
{ Id: '14:00', value: '14:00' },
{ Id: '14:30', value: '14:30' },
{ Id: '15:00', value: '15:00' },
{ Id: '15:30', value: '15:30' },
{ Id: '16:00', value: '16:00' },
{ Id: '16:30', value: '16:30' },
{ Id: '17:00', value: '17:00' },
{ Id: '17:30', value: '17:30' },
{ Id: '18:00', value: '18:00' },
{ Id: '18:30', value: '18:30' },
{ Id: '19:00', value: '19:00' },
{ Id: '19:30', value: '19:30' },
{ Id: '20:00', value: '20:00' },
{ Id: '20:30', value: '20:30' },
{ Id: '21:00', value: '21:00' },
{ Id: '21:30', value: '21:30' },
{ Id: '22:00', value: '22:00' },
{ Id: '22:30', value: '22:30' },
{ Id: '23:00', value: '23:00' },
{ Id: '23:30', value: '23:30' },
{ Id: '24:00', value: '24:00' },
]);
let timeListAfternoon =
timeafternoon.length > 0 &&
timeafternoon.map((item, i) => {
return (
<>
<option key={item.Id} value={item.id}>
{item.value}
</option>
</>
);
});
const handleInputChangeForDay = (e, day, index) => {
const { name, value } = e.target;
const list = [...days[day]];
list[index][name] = value;
setDays((days) => ({
...days,
[day]: list,
}));
};
const handleInputChangeForInput = (e, day, index) => {
const { name, value } = e.target;
let valuec = false;
if (value == 'false') {
valuec = true;
} else {
valuec = false;
}
const list = [...days[day]];
list[index][name] = valuec;
setDays((days) => ({
...days,
[day]: list,
}));
};
const onSubmit = (e) => {
e.preventDefault();
crearHoras({
days,
});
crearAgenda({ days });
};
console.log(days);
const crearHoras = (days) => {
guardarDiasTrabajo([...diastrabajo, days]);
};
const crearAgenda = async (datos) => {
try {
const respuesta = await clienteAxios.post(
'/api/admin/horasmedicas',
datos
);
console.log(respuesta.data);
} catch (error) {
console.log(error);
}
};
return (
<>
<form onSubmit={onSubmit}>
<div className='overflow-x-auto'>
<div className='flex justify-end'>
<input
type='submit'
className='bg-blue-500 hover:bg-gay-900 w-40 p-2 text-white font-bold rounded mt-5'
value='Guardar cambios'
/>
</div>
<div className='min-w-screen min-h-screen bg-gray-100 flex items-center justify-center bg-gray-100 font-sans overflow-hidden'>
<div className='w-full lg:w-5/6'>
<div className='bg-white shadow-md rounded my-6'>
<table className='min-w-max w-full table-auto'>
<thead>
<tr className='bg-gray-200 text-gray-600 uppercase text-sm leading-normal'>
<th className='py-3 px-6 text-left'>Día</th>
<th className='py-3 px-6 text-left'>Activo</th>
<th className='py-3 px-6 text-center'>Turno Mañana</th>
<th className='py-3 px-6 text-center'>Turno Tarde</th>
</tr>
</thead>
{Object.entries(days).map(([dayKey, day]) => {
return day.map((x, i) => {
return (
<>
<tbody className='text-gray-600 text-sm font-light'>
<tr className='border-b border-gray-200 hover:bg-gray-100'>
<td className='py-3 px-6 text-left whitespace-nowrap'>
<div className='flex items-center'>
<span>{dayKey}</span>
</div>
</td>
<td className='py-3 px-6'>
<div className='flex items-center'>
<div className=''>
<div className='toggle colour'>
<input
id={dayKey}
className='toggle-checkbox hidden'
type='checkbox'
name='activo'
value={x.activo}
onChange={(e) =>
handleInputChangeForInput(
e,
dayKey,
i
)
}
/>
<label
htmlFor={dayKey}
className='toggle-label block w-12 h-6 rounded-full transition-color duration-150 ease-out'
></label>
</div>
</div>
</div>
</td>
<td className='py-3 px-6 text-center'>
<div className='flex items-center justify-center row-auto'>
<div className='col-auto mr-3'>
<select
type='time'
className='form-control'
name='manana_comienzo'
value={x.manana_comienzo}
onChange={(e) =>
handleInputChangeForDay(e, dayKey, i)
}
>
{timeListMorning}
</select>
</div>
<div className='col-auto'>
<select
type='time'
className='form-control'
name='manana_fin'
value={x.manana_fin}
onChange={(e) =>
handleInputChangeForDay(e, dayKey, i)
}
>
{timeListMorning}
</select>
</div>
</div>
</td>
<td className='py-3 px-6 text-center'>
<div className='flex items-center justify-center row-auto'>
<div className='col-auto mr-3'>
<select
type='time'
className='form-control'
name='tarde_comienzo'
value={x.tarde_comienzo}
onChange={(e) =>
handleInputChangeForDay(e, dayKey, i)
}
>
{timeListAfternoon}
</select>
</div>
<div className='col-auto'>
<select
type='time'
className='form-control'
name='tarde_fin'
value={x.tarde_fin}
onChange={(e) =>
handleInputChangeForDay(e, dayKey, i)
}
>
{timeListAfternoon}
</select>
</div>
</div>
</td>
</tr>
</tbody>
</>
);
});
})}
;
</table>
</div>
</div>
</div>
</div>
</form>
</>
);
};
export default GestionarDiasTrabajo;
<file_sep>import React, { useContext, useEffect } from 'react';
import Sidebar from '../components/Sidebar';
import GestionarDiasTrabajo from '../components/Admin/GestionarDiasTrabajo';
import Layout from '../components/Layout';
import authContext from '../context/auth/authContext';
const Index = () => {
//extraer usuario autenticado storage
const AuthContext = useContext(authContext);
const { usuario, usuarioAutenticado, rol } = AuthContext;
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
usuarioAutenticado();
}
}, []);
return (
<>
<Layout>
{rol ? <Sidebar /> : null}
{/* // {rol == 'admin' && usuario ? <GestionarDiasTrabajo /> : null} */}
</Layout>
</>
);
};
export default Index;
<file_sep>import React from 'react';
import Head from 'next/head';
import Header from './Header';
const Layout = ({ children }) => {
return (
<>
<Head>
<title>TELEMEDICINA APP</title>
<link
href='https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css'
rel='stylesheet'
integrity='<KEY>'
crossOrigin='anonymous'
></link>
<script
src='https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js'
integrity='<KEY>'
crossOrigin='anonymous'
></script>
</Head>
<div className='bg-gray-100 min-h-screen'>
<div className='container mx-auto'>
<Header />
<main className='md:flex min-h-screen'>{children}</main>
</div>
</div>
</>
);
};
export default Layout;
<file_sep>import React from 'react';
import Layout from '../components/Layout';
import Sidebar from '../components/Sidebar';
import MisReservas from '../components/Paciente/MisReservas';
const miReservas = () => {
return (
<>
<Layout>
<Sidebar />
<MisReservas />
</Layout>
</>
);
};
export default miReservas;
<file_sep>import { FORMULARIO_MEDICO } from "../../types/index";
export default (state, action) => {
switch (action.type) {
case FORMULARIO_MEDICO:
return {
...state,
formulariomedico: true,
};
default:
return state;
}
};
<file_sep>import { Router, useRouter } from "next/router";
import React, { useReducer } from "react";
import doctorContext from "./doctorContext";
import doctorReducer from "./doctorReducer";
import {} from "../../types/index";
import clienteAxios from "../../config/axios";
import tokenAuth from "../../config/tokenAuth";
const DoctorState = ({ children }) => {
const router = useRouter();
//Definiedo state inicial
const initialState = {
doctores: [],
formulariomedico: false,
errorformulariomedico: false,
doctor: null,
mensaje: null,
};
//Definendo F() del reducer
const [state, dispatch] = useReducer(authReducer, initialState);
//Mostrar formulario de crear medico
const mostrarFormulario = () => {
dispatch({
FORMULARIO_MEDICO,
});
};
//Obtener Médicos
const obtenerMedicos = async () => {
try {
//const resultado = await clienteAxios.get("/api/medicos");
} catch (error) {}
};
return (
<doctorContext.Provider
value={{
doctores: state.doctores,
formulariomedico: state.formulariomedico,
errorformulariomedico: state.errorformulariomedico,
doctor: state.doctor,
mensaje: state.mensaje,
mostrarFormulario,
obtenerMedicos,
}}
>
{children}
</doctorContext.Provider>
);
};
export default DoctorState;
<file_sep>import React from 'react';
const misReservas = () => {
return (
<>
<div className='md:w-3/5 xl:w-4/5 mx-auto p-6 flex'>
<div className='w-full'>
<form className='bg-white rounded shadown-md px-8 pt-6 pb-8 mb-4'>
<div className='w-full lg:w-6/6'>
<div className='bg-white shadow-md rounded my-6'>
<table className='min-w-max w-full table-auto'>
<thead>
<tr className='bg-gray-200 text-gray-600 uppercase text-sm leading-normal'>
<th className='py-3 px-6 text-left'>Fecha</th>
<th className='py-3 px-6 text-left'>Hora</th>
<th className='py-3 px-6 text-center'>Doctor</th>
<th className='py-3 px-6 text-center'>Especialidad</th>
<th className='py-3 px-6 text-center'>Estado</th>
</tr>
</thead>
<tbody className='text-gray-600 text-sm font-light'>
<tr className='border-b border-gray-200 hover:bg-gray-100'>
<td className='py-3 px-6 text-left whitespace-nowrap'>
<div className='flex items-center'>
<span>12/2/2021</span>
</div>
</td>
<td className='py-3 px-6'>
<div className='flex items-center'>
<span>12:30</span>
</div>
</td>
<td className='py-3 px-6 text-center'>
<div className='flex items-center justify-center'>
<span><NAME></span>
</div>
</td>
<td className='py-3 px-6 text-center'>
<div className='flex items-center justify-center'>
<span>Neurocirujano</span>
</div>
</td>
<td className='py-3 px-6 text-center'>
<div className='flex items-center justify-center'>
<button
type='button'
className='bg-blue-500 px-5 py-3 rounded-lg text-white'
>
<span className='mr-1'>Pagar</span>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</>
);
};
export default misReservas;
|
96fea435d7cd1baee56b3916f3bed576c24511f5
|
[
"JavaScript"
] | 10 |
JavaScript
|
pbindisramos/Telemedicine
|
86f0241155c75a9f29db833cf8a956c9a0328a0c
|
2e8a77e4fcb3ecf9719d1f7ca6339a955ec21f68
|
refs/heads/master
|
<file_sep>'use strict';
/**
* Priority queue.
*/
module.exports = class PriorityQueue {
/**
* Creates a queue from a list.
* @param {Array} list { priority, anything }
*/
constructor(list) {
this.list = list.sort((a, b) => a.priority - b.priority);
}
/**
* Dequeues an element with min priority and shifts it,
* so next time another element with the same priority is dequeued
* (that allows more even (fair) distribution of the elements).
* @param {Function} skipFunction Is called for a candidate to dequeue.
* Is used for possiblity to be able to skip a candidate and switch to th next one.
*/
dequeue(skipFunction) {
let index = 0;
if (skipFunction) {
while (this.list[index] && skipFunction(this.list[index])) {
index += 1;
}
}
const item = this.list[index];
if (item) {
item.priority = item.priority + 1;
for (let i = index; i < this.list.length - 1; i += 1) {
if (this.list[i + 1].priority > item.priority) {
break;
}
const temp = this.list[i + 1];
this.list[i + 1] = this.list[i];
this.list[i] = temp;
}
}
return item;
};
}
<file_sep>'use strict';
const data = require('./data');
const constraints = require('./constraints');
const EMPLOYEES_PER_SHIFT_RULE_ID = 7;
function feature1(weekStart, weekEnd, employees, shiftRules, timeOffs) {
const result = {};
let currentEmployeeIndex = -1;
let adjustedEmployeePerShift = Math.min(shiftRules.filter(r => r.rule_id === EMPLOYEES_PER_SHIFT_RULE_ID)[0].value, employees.length);
for (let w = weekStart; w <= weekEnd; w += 1) {
const cw = result[w] = [];
const res = constraints.applyConstraints(
cw,
[
() => constraints.assumeAllAreOnShift(cw, employees)
],
[
tryCount => constraints.ensureNumberOfEmployeesPerShift(tryCount, cw, employees, adjustedEmployeePerShift)
]);
if (!res) {
console.log('Unable to process data');
}
}
return result;
}
module.exports = function (weekStart, weekEnd) {
return Promise.all(
[
data.getEmployees(),
data.getShiftRules()
]
)
.then(([employees, shiftRules]) => feature1(weekStart, weekEnd, employees, shiftRules));
}
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class EmployeeList extends Component {
constructor(props) {
super(props);
this.state = {
employees: []
};
}
componentDidMount() {
fetch('/api/employees')
.then(r => r.json())
.then(r => {
this.setState({
employees: r
});
})
.catch(console.error);
}
render() {
return (
<div>
<h3>Employees</h3>
<ul>
{this.state.employees.map(e => (
<li key={e.id}><Link to={`/employee/${e.id}`}>{e.name}</Link></li>
))}
</ul>
</div>
);
}
}
export default EmployeeList;
<file_sep>'use strict';
const axios = require('axios');
module.exports = {
getEmployees: () => axios(`http://interviewtest.replicon.com/employees`).then(r => r.data),
getEmployee: (id) => axios(`http://interviewtest.replicon.com/employees/${id}`).then(r => r.data),
getTimeOffs: () => axios(`http://interviewtest.replicon.com/time-off/requests`).then(r => r.data),
getWeeks: () => axios(`http://interviewtest.replicon.com/weeks`).then(r => r.data),
getWeek: (id) => axios(`http://interviewtest.replicon.com/week/${id}`).then(r => r.data),
getRuleDefinitions: () => axios(`http://interviewtest.replicon.com/rule-definitions`).then(r => r.data),
getShiftRules: () => axios(`http://interviewtest.replicon.com/shift-rules`).then(r => r.data),
};<file_sep>import React, { Component } from 'react';
import logo from './icon.png';
import './App.css';
import EmployeeList from './EmployeeList';
import EmployeeInfo from './EmployeeInfo';
import { BrowserRouter as Router, Route } from 'react-router-dom';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to Shifts</h2>
</div>
<div className="App-content">
<Router>
<div>
<Route exact path="/" component={EmployeeList}/>
<Route path="/employee/:id" component={EmployeeInfo}/>
</div>
</Router>
</div>
</div>
);
}
}
export default App;
<file_sep>To run the app locally:
```bash
git clone https://github.com/mikalai-silivonik/ra.git
cd ra
npm install
npm start
```
I picked greedy approach to implement assignment features. The idea is that all employees are assigned to an each day and then iteration by iteration we adjust that using constraints. The following constraints are implemented for features 1 and 2:
- two employees per shift
- day-offs request consideration
If there is situation when a day cannot be full-filled with required number of employees, whole routines is repeated with some day-off requests canceled. Please see code comments.
I also implemented a priority queue that provides more fair distribution of employees during a week.
To implement features 3-6 I would follow existing approach with some tweaks. Constraints in these cases have to be executed one-by-one for a day, as opposed to one-by-one for a week as in current implementation. MAX_SHIFTS is pretty straight forward: skip function of an employee queue would have one more filter that checks whether given person is assigned more than given number of times.<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import moment from 'moment';
class EmployeeInfo extends Component {
constructor(props) {
super(props);
this.state = {
employee: null
};
}
componentDidMount() {
fetch(`/api/employees/${this.props.match.params.id}`)
.then(r => r.json())
.then(e => {
this.setState({
employee: e
});
})
.catch(console.error);
}
render() {
const empl = this.state.employee;
return (
<div>
<Link to="/"><-- Back to employees</Link>
<br />
<br />
{empl
? (
<div>
{empl.name}
<br />
<br />
{this.renderSchedule(empl.weeks)}
</div>
)
: (
<div>Loading...</div>
)}
</div>
);
}
renderSchedule(weeks) {
return (
<div>
<table className="schedule">
<thead>
<tr>
<th>Week</th>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
</thead>
<tbody>
{weeks.map(w => (
<tr key={w.week}>
<td className="schedule-week">{w.week}</td>
{w.days.map((d, i) => (
<td key={w.week + i} className={'schedule schedule-day ' + (d ? 'day-shift' : 'day-off')}>
<div>{moment(w.startDate, 'YYYY/MM/DD').add(i, 'day').format('MMMM Do')}</div>
<div>{d && 'shift'}</div>
<div className={w.daysOff[i] ? 'requested-day-off' : ''}>{w.daysOff[i] && 'requested day-off'}</div>
</td>
))}
</tr>
))}
</tbody>
</table>
{weeks.days}
</div>
);
}
}
export default EmployeeInfo;
|
9c725698ba4f819034b0441a67d7e5cb58b29a75
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
mikalai-s/ra
|
ffdaa25c72c2215ec4913c7514236424bbba028f
|
670487c17147c093dc47a20ea1e1960c2c83b31f
|
refs/heads/main
|
<repo_name>mithon42/PSD-to-H-C-Bs4<file_sep>/README.md
# PSD-to-H-C-Bs4<file_sep>/js/main.js
// $(function () {
// var mixer = mixitup('.Product-item')
// });
|
79bd582046c1a5a6ba4669439059fb3b37cd8b1b
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
mithon42/PSD-to-H-C-Bs4
|
d194a3ee76dae63120259d17d53849ce53c68369
|
551e556ed96e107fe113a10235b1f7bce3d3d03a
|
refs/heads/master
|
<repo_name>arlesonsilva/iPautas<file_sep>/iPautas/PautaCelula.swift
//
// PautaCelula.swift
// iPautas
//
// Created by <NAME> on 03/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class PautaCelula: UITableViewCell {
@IBOutlet weak var titulo: UILabel!
@IBOutlet weak var breveDescricao: UILabel!
@IBOutlet weak var descricaoCompleta: UITextView!
@IBOutlet weak var autor: UILabel!
@IBOutlet weak var botaoAcao: UIButton!
}
<file_sep>/iPautas/ViewController.swift
//
// ViewController.swift
// iPautas
//
// Created by <NAME> on 30/04/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
var context: NSManagedObjectContext!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var senha: UITextField!
@IBAction func entrar(_ sender: Any) {
if let email = email.text, email.isEmpty {
alerta(mensagem: "Email inválido \(email)")
return
}
if let senha = senha.text, senha.isEmpty {
alerta(mensagem: "Senha inválida \(senha)")
return
}
buscarUsuario()
}
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func buscarUsuario() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
let predicate = NSPredicate (format:"email = %@", email.text!)
requisicao.predicate = predicate
do {
let usuarios = try context.fetch(requisicao)
if usuarios.count > 0 {
for usuario in usuarios as! [NSManagedObject] {
let email: String = usuario.value(forKey: "email") as! String
let senha: String = usuario.value(forKey: "senha") as! String
if email == self.email.text {
if senha == self.senha.text {
atualizarUsuarioLogado(usuario: usuario)
}else {
alerta(mensagem: "Senha inválida")
return
}
}else {
alerta(mensagem: "Email inválido")
return
}
}
}else {
alerta(mensagem: "Email não cadastrado")
return
}
} catch {
alerta(mensagem: "Erro ao buscar usuário")
return
}
}
func atualizarUsuarioLogado(usuario: NSManagedObject) {
usuario.setValue("S", forKey: "login")
do {
try context.save()
print("Usuario logado atualizado")
} catch {
print("Erro ao tentar atualizar usuario")
}
}
func alerta(mensagem: String) {
let alert = UIAlertController(title: "Atenção", message: "\(mensagem)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
<file_sep>/iPautas/EsqueciMinhaSenhaViewController.swift
//
// EsqueciMinhaSenhaViewController.swift
// iPautas
//
// Created by <NAME> on 02/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
import MessageUI
class EsqueciMinhaSenhaViewController: UIViewController, MFMailComposeViewControllerDelegate {
var context: NSManagedObjectContext!
@IBOutlet weak var email: UITextField!
@IBAction func enviarEmail(_ sender: Any) {
if let email = email.text, email.isEmpty {
alerta(mensagem: "Email inválido")
return
}
verificaSeEmailJaCadastrado()
}
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func verificaSeEmailJaCadastrado() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
let predicate = NSPredicate (format:"email = %@" ,email.text!)
requisicao.predicate = predicate
do {
let usuarios = try context.fetch(requisicao)
if usuarios.count > 0 {
for usuario in usuarios as! [NSManagedObject] {
let nome: String = usuario.value(forKey: "nome") as! String
let email: String = usuario.value(forKey: "email") as! String
let senha: String = usuario.value(forKey: "senha") as! String
sendEmail(email: email, nome: nome, senha: senha)
}
}else {
alerta(mensagem: "Não existe cadastrado com este email \(email.text!)")
return
}
} catch {
alerta(mensagem: "Erro ao bus<NAME>")
return
}
}
func sendEmail(email: String, nome: String, senha: String) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self as MFMailComposeViewControllerDelegate
mail.setToRecipients([email])
mail.setSubject("Senha de acesso ")
mail.setMessageBody("<h1>Olá \(nome), Sua senha de acesso ao app iPautas é: \(senha).<h1>", isHTML: true)
present(mail, animated: true)
} else {
alerta(mensagem: "Não foi possivél enviar o email")
}
}
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .cancelled:
print("Mail cancelled")
break
case .saved:
print("Mail saved")
break
case .sent:
print("Mail sent")
break
case .failed:
print("Mail failed")
break
default:
break
}
self.dismiss(animated: true, completion: nil)
//controller.dismiss(animated: true)
}
func alerta(mensagem: String) {
let alert = UIAlertController(title: "Atenção", message: "\(mensagem)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
<file_sep>/iPautas/CadastroUsuarioViewController.swift
//
// CadastroUsuarioViewController.swift
// iPautas
//
// Created by <NAME> on 30/04/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
class CadastroUsuarioViewController: UIViewController {
var context: NSManagedObjectContext!
@IBOutlet weak var nome: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var senha: UITextField!
@IBAction func cadastrar(_ sender: Any) {
if let nome = nome.text, nome.isEmpty {
alerta(mensagem: "Nome nao esta ok \(nome)")
return
}
if let email = email.text, email.isEmpty {
alerta(mensagem: "Email nao esta ok \(email)")
return
}
if let senha = senha.text, senha.isEmpty {
alerta(mensagem: "Senha nao esta ok \(senha)")
return
}
if verificaSeEmailJaCadastrado() {
alerta(mensagem: "Email já existe em nossa base de dados")
return
}
cadastrarUsuario()
}
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func verificaSeEmailJaCadastrado() -> Bool {
let predicate = NSPredicate (format:"email = %@" ,email.text!)
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
requisicao.predicate = predicate
do {
let usuarios = try context.fetch(requisicao)
if usuarios.count > 0 {
return true
}else {
return false
}
} catch {
alerta(mensagem: "Erro ao buscar usuário")
return false
}
}
func cadastrarUsuario() {
let usuario = NSEntityDescription.insertNewObject(forEntityName: "Usuario", into: context)
usuario.setValue(nome.text, forKey: "nome")
usuario.setValue(email.text, forKey: "email")
usuario.setValue(senha.text, forKey: "<PASSWORD>")
usuario.setValue("N", forKey: "login")
do {
try context.save()
alerta(mensagem: "Usuário salvo com sucesso")
} catch let erro as Error {
alerta(mensagem: "Erro ao salvar usuário: \(erro.localizedDescription)")
}
}
func alerta(mensagem: String) {
let alert = UIAlertController(title: "Atenção", message: "\(mensagem)", preferredStyle: .alert)
if mensagem == "Usuário salvo com sucesso" {
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
self.navigationController?.popViewController(animated: true)
}))
}else {
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
}
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
<file_sep>/iPautas/PerfilUsuarioViewController.swift
//
// PerfilUsuarioViewController.swift
// iPautas
//
// Created by <NAME> on 03/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
class PerfilUsuarioViewController: UIViewController {
var context: NSManagedObjectContext!
@IBOutlet weak var nome: UILabel!
@IBOutlet weak var email: UILabel!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueSairApp" {
sairApp()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
buscarInfoUsuarioLogado()
}
func buscarInfoUsuarioLogado() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
let predicate = NSPredicate (format:"login = %@", "S")
requisicao.predicate = predicate
do {
let result = try context.fetch(requisicao)
if result.count > 0 {
for data in result as! [NSManagedObject] {
if data.value(forKey: "login") as! String == "S" {
nome.text = (data.value(forKey: "nome") as! String)
email.text = (data.value(forKey: "email") as! String)
}
}
}else {
alerta(mensagem: "Nenhum usuario logado")
let loginPageView = self.storyboard?.instantiateViewController(withIdentifier: "LoginPageID") as! ViewController
self.present(loginPageView, animated: true, completion: nil)
}
} catch {
alerta(mensagem: "Falha ao tentar buscar informação do usuário")
}
}
func sairApp() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
let predicate = NSPredicate (format:"email = %@", email.text!)
requisicao.predicate = predicate
do {
let result = try context.fetch(requisicao)
for data in result as! [NSManagedObject] {
if data.value(forKey: "login") as! String == "S" {
data.setValue("N", forKey: "login")
do {
try context.save()
print("Usuario deslogado do app")
} catch {
alerta(mensagem: "Erro ao tentar deslogar usuário")
}
}
}
} catch {
alerta(mensagem: "Failha ao tentar deslogar usuário")
}
}
func alerta(mensagem: String) {
let alert = UIAlertController(title: "Atenção", message: "\(mensagem)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
<file_sep>/iPautas/PautasTableViewController.swift
//
// PautasTableViewController.swift
// iPautas
//
// Created by <NAME> on 03/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
class PautasTableViewController: UITableViewController {
var context: NSManagedObjectContext!
var nome: String!
var selectedIndex = -1
var selectedSection = -1
var selectedIndexPath: IndexPath!
var isCollapse = false
var pautasAbertas: [NSManagedObject] = []
var pautasFechadas: [NSManagedObject] = []
@IBOutlet var tableViewPauta: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
verificaSeUsuarioLogado()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
recuperarPautasAberta()
recuperarPautasFechadas()
//tableViewPauta.rowHeight = 243
//tableViewPauta.rowHeight = UITableView.automaticDimension
//tableViewPauta.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Pautas Abertas"
}else {
return "Pautas Fechadas"
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return pautasAbertas.count
}else {
return pautasFechadas.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let pauta: NSManagedObject
if indexPath.section == 0 {
pauta = pautasAbertas[indexPath.row]
}else {
pauta = pautasFechadas[indexPath.row]
}
let cell = tableView.dequeueReusableCell(withIdentifier: "celula", for: indexPath) as! PautaCelula
cell.titulo.text = (pauta.value(forKey: "titulo") as! String)
cell.breveDescricao.text = (pauta.value(forKey: "descricao") as! String)
cell.descricaoCompleta.text = (pauta.value(forKey: "descricao") as! String)
cell.autor.text = nome
if indexPath.section == 0 {
cell.botaoAcao.setTitle("Finalizar", for: .normal)
}else {
cell.botaoAcao.setTitle("Reabrir", for: .normal)
}
cell.botaoAcao.tag = pauta.value(forKey: "codigo") as! Int
cell.botaoAcao.addTarget(self, action: #selector(subscribeTapped(_:)), for: .touchUpInside)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
if selectedIndex == indexPath.row && isCollapse && selectedSection == indexPath.section {
return 250
}else {
return 70
}
}else {
if selectedIndex == indexPath.row && isCollapse && selectedSection == indexPath.section {
return 250
}else {
return 70
}
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.dequeueReusableCell(withIdentifier: "celula", for: indexPath) as! PautaCelula
cell.breveDescricao.isHidden = true
if indexPath.section == 0 {
if selectedIndex == indexPath.row && selectedSection == indexPath.section {
if !isCollapse {
isCollapse = true
cell.breveDescricao.isHidden = true
cell.descricaoCompleta.isHidden = false
}else{
isCollapse = false
cell.breveDescricao.isHidden = false
cell.descricaoCompleta.isHidden = true
}
}else {
isCollapse = true
cell.breveDescricao.isHidden = true
cell.descricaoCompleta.isHidden = false
}
}else {
if selectedIndex == indexPath.row && selectedSection == indexPath.section {
if !isCollapse {
isCollapse = true
cell.breveDescricao.isHidden = true
cell.descricaoCompleta.isHidden = false
}else{
isCollapse = false
cell.breveDescricao.isHidden = false
cell.descricaoCompleta.isHidden = true
}
}else {
isCollapse = true
cell.breveDescricao.isHidden = true
cell.descricaoCompleta.isHidden = false
}
}
selectedIndexPath = indexPath
selectedSection = indexPath.section
selectedIndex = indexPath.row
tableView.reloadRows(at: [indexPath], with: .automatic)
}
@objc func subscribeTapped(_ sender: UIButton){
if !isCollapse {
isCollapse = true
}else{
isCollapse = false
}
tableView.reloadRows(at: [self.selectedIndexPath], with: .automatic)
atualizaPauta(codigo: sender.tag)
}
func atualizaPauta(codigo: Int) {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Pauta")
let predicate = NSPredicate (format:"codigo == %i", codigo)
requisicao.predicate = predicate
do {
let pautas = try context.fetch(requisicao)
if pautas.count > 0 {
for pauta in pautas as! [NSManagedObject] {
let status = (pauta.value(forKey: "status") as! String)
if status == "Aberto" {
pauta.setValue("Fechado", forKey: "status")
}else {
pauta.setValue("Aberto", forKey: "status")
}
do {
try context.save()
alerta(mensagem: "Pauta atualizada com sucesso")
} catch {
alerta(mensagem: "Erro ao tentar atualizar pauta, tente novamente")
}
}
}
}catch let erro as Error? {
alerta(mensagem: "Erro ao recupertar pautas \(erro!.localizedDescription)")
}
}
func recuperarPautasAberta() {
self.pautasAbertas.removeAll()
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Pauta")
let predicate = NSPredicate (format:"status = %@", "Aberto")
requisicao.predicate = predicate
do {
let pautasRecuperadas = try context.fetch(requisicao)
if pautasRecuperadas.count > 0 {
self.pautasAbertas = pautasRecuperadas as! [NSManagedObject]
}
}catch let erro as Error? {
alerta(mensagem: "Erro ao recupertar pautas \(erro!.localizedDescription)")
}
tableViewPauta.reloadData()
}
func recuperarPautasFechadas() {
self.pautasFechadas.removeAll()
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Pauta")
let predicate = NSPredicate (format:"status = %@", "Fechado")
requisicao.predicate = predicate
do {
let pautasRecuperadas = try context.fetch(requisicao)
if pautasRecuperadas.count > 0 {
self.pautasFechadas = pautasRecuperadas as! [NSManagedObject]
}
}catch let erro as Error? {
alerta(mensagem: "Erro ao recupertar pautas \(erro!.localizedDescription)")
}
tableViewPauta.reloadData()
}
func verificaSeUsuarioLogado() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
let predicate = NSPredicate (format:"login = %@", "S")
requisicao.predicate = predicate
do {
let result = try context.fetch(requisicao)
if result.count > 0 {
for data in result as! [NSManagedObject] {
if data.value(forKey: "login") as! String == "S" {
nome = (data.value(forKey: "nome") as! String)
print("Usuario logado: ", data.value(forKey: "email") as! String)
}else {
voltarParaTelaLogin()
print("Nenhum usuario logado")
}
}
}else {
voltarParaTelaLogin()
print("Nenhum usuario logado")
}
} catch {
print("Failed")
}
}
func voltarParaTelaLogin() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginPageID") as UIViewController
navigationController?.pushViewController(vc, animated: true)
}
func alerta(mensagem: String) {
let alert = UIAlertController(title: "Atenção", message: "\(mensagem)", preferredStyle: .alert)
if mensagem == "Pauta atualizada com sucesso" {
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
self.recuperarPautasAberta()
self.recuperarPautasFechadas()
}))
}else {
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
}
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
<file_sep>/iPautas/AdicionarPautaViewController.swift
//
// AdicionarPautaViewController.swift
// iPautas
//
// Created by <NAME> on 03/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
class AdicionarPautaViewController: UIViewController, UITextViewDelegate {
var context: NSManagedObjectContext!
var email: String!
var codigo: Int = 0
var vtitulo: Bool = false
var vdescricao: Bool = false
var vdetalhe: Bool = false
@IBOutlet weak var titulo: UITextField!
@IBOutlet weak var descricao: UITextView!
@IBOutlet weak var detalhe: UITextField!
@IBOutlet weak var autor: UILabel!
@IBOutlet weak var finalizar: UIButton!
@IBAction func salvar(_ sender: Any) {
if let titulo = titulo.text, titulo.isEmpty {
alerta(mensagem: "Título inválido \(titulo)")
return
}
if let descricao = descricao.text, descricao.isEmpty {
alerta(mensagem: "Título inválido \(descricao)")
return
}
if let detalhe = detalhe.text, detalhe.isEmpty {
alerta(mensagem: "Título inválido \(detalhe)")
return
}
cadastrarPauta()
}
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
descricao.delegate = (self as UITextViewDelegate)
titulo.addTarget(self, action: #selector(myTargetFunction), for: .editingChanged)
detalhe.addTarget(self, action: #selector(myTargetFunction), for: .editingChanged)
descricao.text = "Digite aqui uma descrição para a pauta"
descricao.textColor = UIColor.lightGray
//descricao.delegate = self
descricao.text = "Digite a descrição da pauta"
descricao.textColor = UIColor.lightGray
buscarInfoUsuarioLogado()
buscarUltimoCodigoPautaInserido()
verificaSeHabilitaBtnFinalizar()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func textViewDidBeginEditing(_ textView: UITextView) {
if descricao.textColor == UIColor.lightGray {
descricao.text = ""
}
}
func textViewDidChange(_ textView: UITextView) {
if let descricao = descricao.text, descricao.count > 0 {
vdescricao = true
}else {
vdescricao = false
}
verificaSeHabilitaBtnFinalizar()
}
@objc func myTargetFunction(textField: UITextField) {
if let titulo = titulo.text, titulo.count > 0 {
vtitulo = true
}else {
vtitulo = false
}
if let detalhe = detalhe.text, detalhe.count > 0 {
vdetalhe = true
}else {
vdetalhe = false
}
verificaSeHabilitaBtnFinalizar()
}
func verificaSeHabilitaBtnFinalizar() {
if vtitulo && vdescricao && vdetalhe {
finalizar.isEnabled = true
}else {
finalizar.isEnabled = false
}
}
func buscarInfoUsuarioLogado() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Usuario")
let predicate = NSPredicate (format:"login = %@", "S")
requisicao.predicate = predicate
do {
let result = try context.fetch(requisicao)
if result.count > 0 {
for data in result as! [NSManagedObject] {
if data.value(forKey: "login") as! String == "S" {
email = (data.value(forKey: "email") as! String)
autor.text = "Criado por: \(data.value(forKey: "nome") as! String)"
}
}
}
} catch {
alerta(mensagem: "Falha ao tentar buscar informações do usuário logado")
}
}
func buscarUltimoCodigoPautaInserido() {
let requisicao = NSFetchRequest<NSFetchRequestResult>(entityName: "Pauta")
do {
let result = try context.fetch(requisicao)
if result.count > 0 {
codigo = result.count + 1
print(codigo)
}else {
codigo = 1
print(codigo)
}
} catch {
alerta(mensagem: "Falha ao tentar buscar informações do usuário logado")
}
}
func cadastrarPauta() {
let pauta = NSEntityDescription.insertNewObject(forEntityName: "Pauta", into: context)
pauta.setValue(codigo, forKey: "codigo")
pauta.setValue(titulo.text, forKey: "titulo")
pauta.setValue(descricao.text, forKey: "descricao")
pauta.setValue(detalhe.text, forKey: "detalhe")
pauta.setValue(email, forKey: "email_autor")
pauta.setValue("Aberto", forKey: "status") //Aberto //Fechado
do {
try context.save()
alerta(mensagem: "Pauta salvo com sucesso")
} catch let erro as Error? {
alerta(mensagem: "Erro ao salvar pauta: \(erro!.localizedDescription)")
}
}
func alerta(mensagem: String) {
let alert = UIAlertController(title: "Atenção", message: "\(mensagem)", preferredStyle: .alert)
if mensagem == "Pauta salvo com sucesso" {
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
self.navigationController?.popViewController(animated: true)
}))
}else {
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
}
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
|
28b978968721c1141be62679e3594fef41304324
|
[
"Swift"
] | 7 |
Swift
|
arlesonsilva/iPautas
|
15859899e105f4cd2b3496a27013969e0d3264f4
|
cfc583990d0d69cbf03ecc28c6bdfc9028ae6f39
|
refs/heads/master
|
<repo_name>ianleongg/Behavioral-Cloning<file_sep>/model.py
import csv
import cv2
import numpy as np
import sklearn
import random
# read log data
samples = []
with open('./data/driving_log.csv') as csvfile:
reader = csv.reader(csvfile)
next(reader) #skips the first line
for line in reader:
samples.append(line)
from sklearn.model_selection import train_test_split
train_samples, validation_samples = train_test_split(samples, test_size=0.2)
from sklearn.utils import shuffle
print("Number of training samples: ",len(train_samples))
print("Number of validation samples: ",len(validation_samples))
# load image from row/index
def load_image(index, sample):
image = cv2.imread('data/IMG/' + sample[index].split('/')[-1])
#Generate random brightness function, produce darker transformation
##Convert 2 HSV colorspace from BGR colorspace
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
##Generate new random brightness
rand = random.uniform(0.3,1.0)
hsv[:,:,2] = rand*hsv[:,:,2]
##Convert back to RGB colorspace
new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
return new_img
# flip image
def flip_input(image, angle):
processed_image = cv2.flip(image,1)
processed_angle = angle*-1.0
return (processed_image, processed_angle)
# generate images to save memory
def generator(samples, batch_size = 128):
num_samples = len(samples)
while(1):#loop while always true
shuffle(samples)
for offset in range(0, num_samples , batch_size):
batch_samples =samples[offset:offset+batch_size]
images = []
angles = []
correction = 0.25
for batch_sample in batch_samples:
# load center image / angle
center_image = load_image(0, batch_sample)
center_angle = float(batch_sample[3])
# flip center image / angle
center_flipped = flip_input(center_image, center_angle)
images.extend([center_image, center_flipped[0]])
angles.extend([center_angle, center_flipped[1]])
# load left image / angle
left_image = load_image(1, batch_sample)
left_angle = center_angle + correction
# flip left image /angle
left_flipped = flip_input(left_image, left_angle)
images.extend([left_image, left_flipped[0]])
angles.extend([left_angle, left_flipped[1]])
# load right image / angle
right_image = load_image(2, batch_sample)
right_angle = center_angle - correction
# flip right image / angle
right_flipped = flip_input(right_image, right_angle)
images.extend([right_image, right_flipped[0]])
angles.extend([right_angle, right_flipped[1]])
X_train = np.array(images)
y_train = np.array(angles)
yield sklearn.utils.shuffle(X_train , y_train)
# Set our batch size
batch_size=128
# compile and train the model using the generator function
train_generator = generator(train_samples, batch_size=batch_size)
validation_generator = generator(validation_samples, batch_size=batch_size)
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Activation, Dropout
from keras.layers import Conv2D, Cropping2D, SpatialDropout2D
from keras.layers import MaxPooling2D
# Our model is based on NVIDIA's "End to End Learning for Self-Driving Cars" paper
# Source: https://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf
model = Sequential()
# trim image to only see section with road
model.add(Cropping2D(cropping=((52,23), (0,0)), input_shape=(160,320,3)))
# Preprocess incoming data, centered around zero with small standard deviation (Normalize)
model.add(Lambda(lambda x: (x / 255.0) - 0.5))
#five convolutional and maxpooling layers
## three 5x5 convolution
model.add(Conv2D(24, (5, 5), padding="same", strides=(2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))
model.add(Conv2D(36, (5, 5), padding="same", strides=(2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))
model.add(Conv2D(48, (5, 5), padding="same", strides=(2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))
## two 3x3 convolution
model.add(Conv2D(64, (3, 3), padding="same", strides=(1, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))
model.add(Conv2D(64, (3, 3), padding="same", strides=(1, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))
model.add(Flatten())
#five fully connected layers
model.add(Dense(1164))
model.add(Activation('relu'))
model.add(Dense(100))
model.add(Activation('relu'))
model.add(Dense(50))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('relu'))
model.add(Dense(1))
model.summary()
model.compile(loss='mse', optimizer ='adam')
# Fit the model
history_object = model.fit_generator(train_generator, steps_per_epoch=(len(train_samples) / batch_size), validation_data=validation_generator, validation_steps=(len(validation_samples)/batch_size), epochs=20, verbose=1)
# Save model
model.save('model.h5')
print('Model saved successfully')
### print the keys contained in the history object
print ('History Keys')
print(history_object.history.keys())
import matplotlib.pyplot as plt
# Plot the training and validation loss for each epoch
print('Generating loss chart...')
plt.plot(history_object.history['loss'])
plt.plot(history_object.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'], loc='upper right')
plt.savefig('model.png')
# Done
print('Done.')
<file_sep>/README.md
# **Behavioral Cloning**
## Deep neural networks and convolutional neural networks to clone driving behavior
### Train, validate and test a CNN model using Keras
---
**Behavaral Cloning Project**
The goals / steps of this project are the following:
* Use the simulator to collect data of good driving behavior
* Build, a convolution neural network in Keras that predicts steering angles from images
* Train and validate the model with a training and validation set
* Test that the model successfully drives around track one without leaving the road
[//]: # (Image References)
[image1]: ./Images_forReadMe/birds_eye_view.gif "bird eye view"
[image2]: ./Images_forReadMe/center.jpg "center"
[image3]: ./Images_forReadMe/center_flip.jpg "center flip"
[image4]: ./Images_forReadMe/combined.png "combined"
[image5]: ./Images_forReadMe/combined_crop.png "combined crop"
[image6]: ./Images_forReadMe/drivers_view.gif "drivers view"
[image7]: ./Images_forReadMe/model.png "model"
[image8]: ./Images_forReadMe/left_flip.jpg "left flip"
[image9]: ./Images_forReadMe/right.jpg "right"
[image10]: ./Images_forReadMe/right_flip.jpg "right flip"
[image11]: ./Images_forReadMe/sample_csv.png "csv"
[image12]: ./Images_forReadMe/layer.png "layer"
[image13]: ./Images_forReadMe/left.jpg "left"
---
### README
- A neural network model was trained and then used to drive the car autonomously around the track.
- There are 4 important files in this project:
* [model.py](./model.py) (script used to create and train the model)
* [drive.py](./drive.py) (script to drive the car in autonomous mode)
* [model.h5](./model.h5) (a trained Keras CNN model)
* [driving_log.csv](./data/driving_log.csv) (data used to train Keras model)
- Below is the result for the CNN model to output a steering angle to an autonomous vehicle at its max speed setting (~30mph):
| Birds-eye View | Drivers view |
| ------------- | ------------- |
| ![alt text][image1]| ![alt text][image6] |
|Note: The vehicle can be more stable at slower speeds but still maintained its lane keeping at max speed setting.|
### Repo contained
#### 1. Functional code
* [model.py](./model.py) file contains the code for training and saving the convolution neural network [(saved as model.h5)](./model.h5). The file shows the pipeline I used for training and validating the model, and it contains comments to explain how the code works.
* Using the Udacity provided simulator and my [drive.py](./drive.py) file, the car can be driven autonomously around the track by executing
```sh
python drive.py model.h5
```
### Model Architecture
#### 1. Solution Design Approach
* My [model](./model.py) was based off the [NVIDIA's "End to End Learning for Self-Driving Cars" paper](https://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf) and consists of a convolution neural network with three 5x5 convolution layers, two 3x3 convolution layers, and five fully connected layers.
* The model includes RELU layers to introduce nonlinearity, the data is normalized in the model using a Keras lambda layer, and Max Pooling layers to progressively reduce the spatial size of the representation by reducing the amount of parameters and computation in the network.
* The model architecture is seen as the following:
![alt text][image12]
#### 2. Attempts to reduce overfitting in the model
* The model was trained and validated on different data sets to ensure that the model was not overfitting. It was splitted into a 80:20 ratio with the train_test_split function in sklearnn.model_selection. The data sets can be found [here](./data)
- Number of training samples: 6428
- Number of validation samples: 1608
* The ideal number of epochs was 20 as evidenced by a mean squared error loss graph to avoid underfitting/ overfitting.
![alt text][image7]
* The model's batch size was 128 and was tested by running it through the simulator and ensuring that the vehicle could stay on the track.
#### 3. Model parameter tuning
* The model used an adam optimizer, so the learning rate was not tuned manually.
#### 4. Appropriate training data
* Training data was chosen to keep the vehicle driving on the road. I used a combination of center lane driving, recovering from the left and right sides of the road.
* For details about how I created the training data, see the next section.
### Training Data Strategy
#### 1. Creation of the Training Set & Training Process
* All the training set data can be found in the [data file](./data). In this file, contains:
- [images](./data/IMG)
- [csv file for driving log](./data/driving_log.csv)
* The simulator captures images from three cameras mounted on the car: a center, right and left camera with its steering, throttle commands for each frame recorded.
| Left | Center | Right |
| ------------- | ------------- | ------------- |
| ![alt text][image13]| ![alt text][image2] | ![alt text][image9] |
* The first 10 recorded data in the csv file can be seen as the following:
![alt text][image11]
* To augment the data set, I also flipped images and angles thinking that this would increase the training set available. For example, here are images that has then been flipped:
| Left Original | Left Flipped |
| ------------- | ------------- |
| ![alt text][image13]| ![alt text][image8] |
| Center Original | Center Flipped |
| ------------- | ------------- |
| ![alt text][image2]| ![alt text][image3] |
| Right Original | Right Flipped |
| ------------- | ------------- |
| ![alt text][image9]| ![alt text][image10] |
* By using not only the center image but with also both left and right images, the training set data was also increased.
- From the perspective of the left camera, the steering angle would be less than the steering angle from the center camera.
- From the right camera's perspective, the steering angle would be larger than the angle from the center camera
- An arbitrary number of 0.25 was used for the above correction:
- left_angle = center_angle + correction
- right_angle = center_angle - correction
* The data for all 3 camera view images were also cropped by 52px(top) and 23px(bottom) to focus just on the road as seen:
![alt text][image5]
* When loading the data images, a random brightness function was utlized to produce darker transformation by using HSV colorspace.
### Conclusion
* Ultimately, it was a great exposure to use train, test, and validate a CNN model with Keras.
* The data can be pre-processed even further which includes manipulating color spaces, etc.
* The final product can be seen below:
|[Birds-Eye View](./Images_forReadMe/birds_eye_view.mp4) | [Drivers View](./Images_forReadMe/drivers_view.mp4) |
### More resources/ information
* [This article](https://repository.tudelft.nl/islandora/object/uuid%3Af536b829-42ae-41d5-968d-13bbaa4ec736) adds temporal visual cues using LSTM
* Another alternative is [this architecture](https://github.com/commaai/research/blob/master/train_steering_model.py) developed by [comma.ai](https://comma.ai/)
* Another technique commonly used is [L2 regularization](https://keras.io/api/layers/regularizers/).
* Check [this article](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) for an in-depth explanation of Dropout as that's another alternative here.
* Check [this article](https://ruder.io/optimizing-gradient-descent/index.html#adam) for a nice description and comparison of different algorithms.
* Instead of using a fixed number of epochs one alternative is using [Keras' EarlyStopping](https://keras.io/api/callbacks/#earlystopping) callback which stops training the model when it stops improving.
* Another useful callback is [ModelCheckpoint](https://keras.io/api/callbacks/#modelcheckpoint) which can be used to save the best model found during training.
#### Behavioral Cloning
* The below paper shows one of the techniques Waymo has researched using imitation learning (aka behavioral cloning) to drive a car.
- [ChauffeurNet: Learning to Drive by Imitating the Best and Synthesizing the Worst by <NAME>, <NAME> and <NAME>](https://arxiv.org/abs/1812.03079)
#### Object Detection and Tracking
* The below papers include various deep learning-based approaches to 2D and 3D object detection and tracking.
- [SSD: Single Shot MultiBox Detector by <NAME>, et. al.](https://arxiv.org/abs/1512.02325)
- [VoxelNet: End-to-End Learning for Point Cloud Based 3D Object Detection by <NAME> and <NAME>](https://arxiv.org/abs/1711.06396)
- [Fast and Furious: Real Time End-to-End 3D Detection, Tracking and Motion Forecasting with a Single Convolutional Net by <NAME>, et. al.](https://openaccess.thecvf.com/content_cvpr_2018/papers/Luo_Fast_and_Furious_CVPR_2018_paper.pdf)
#### Semantic Segmentation
* The below paper concerns a technique called semantic segmentation, where each pixel of an image gets classified individually
- [SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation by <NAME>, <NAME> and <NAME>](https://arxiv.org/abs/1511.00561)
|
6b068c5b1ad5953da7481105f000b4b412d78a15
|
[
"Markdown",
"Python"
] | 2 |
Python
|
ianleongg/Behavioral-Cloning
|
08789989e1ff932aa500ff1b55a0789553d53faa
|
050041d70106e3f402f8019f7abc02ad23dcb7b6
|
refs/heads/master
|
<repo_name>maet-01/RedisSamples<file_sep>/src/main/springboot-redis-resources/config/application-jedis.properties
jedis.host=127.0.0.1
jedis.port=6379
jedis.max-total=20
jedis.max-idle=5
jedis.max-wait=1000
jedis.max-wait-millis=1000
jedis.test-on-borrow=false<file_sep>/src/test/spring-redis-test/com/vergilyn/demo/redis/spring/SpringRedisTest.java
package com.vergilyn.demo.redis.spring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.concurrent.TimeUnit;
/**
* @author VergiLyn
* @bolg http://www.cnblogs.com/VergiLyn/
* @date 2017/4/2
*/
@ContextConfiguration(locations = {"classpath:spring-redis-application.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringRedisTest extends AbstractJUnit4SpringContextTests {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 测试插入与获取Redis的数据
*/
@Test
public void testPutAndGet() {
redisTemplate.opsForHash().put("user", "name", "vergilyn");
Object object = redisTemplate.opsForHash().get("user", "name");
System.out.println(object);
}
/**
* 测试Redis作为缓存的例子
*/
@Test
public void testCache() throws InterruptedException {
// 插入一条数据
redisTemplate.opsForHash().put("user", "name", "vergilyn");
// 设置失效时间为2秒
redisTemplate.expire("user", 2, TimeUnit.SECONDS);
Thread.sleep(1000);
// 1秒后获取
Object object = redisTemplate.opsForHash().get("user", "name");
System.out.println("1秒后,重新获取:" + object);
redisTemplate.opsForHash().put("user", "name","dante");
System.out.println("2秒前,重新获取:" + redisTemplate.opsForHash().get("user", "name"));
Thread.sleep(1000);
// 2秒后获取
object = redisTemplate.opsForHash().get("user", "name");
System.out.println("2秒后,重新获取:" + object);
}
}
<file_sep>/src/main/java/com/vergilyn/demo/redis/TypeOperate/StringOperate.java
package com.vergilyn.demo.redis.TypeOperate;
/**
* Created by VergiLyn on 2016/8/22.
*/
public class StringOperate extends TypeOperateObject {
public void show() {
//jedis具备的功能shardedJedis中也可直接使用,下面测试一些前面没用过的方法
System.out.println("======================String_2==========================");
// 清空数据
System.out.println("清空库中所有数据:"+jedis.flushDB());
System.out.println("=============新增键值对时防止覆盖原先值=============");
System.out.println("原先key301不存在时,新增key301:"+shardedJedis.setnx("key301", "value301"));
System.out.println("原先key302不存在时,新增key302:"+shardedJedis.setnx("key302", "value302"));
System.out.println("当key302存在时,尝试新增key302:"+shardedJedis.setnx("key302", "value302_new"));
System.out.println("获取key301对应的值:"+shardedJedis.get("key301"));
System.out.println("获取key302对应的值:"+shardedJedis.get("key302"));
System.out.println("=============超过有效期键值对被删除=============");
// 设置key的有效期,并存储数据
System.out.println("新增key303,并指定过期时间为2秒"+shardedJedis.setex("key303", 2, "key303-2second"));
System.out.println("获取key303对应的值:"+shardedJedis.get("key303"));
try{
Thread.sleep(3000);
}
catch (InterruptedException e){
}
System.out.println("3秒之后,获取key303对应的值:"+shardedJedis.get("key303"));
System.out.println("=============获取原值,更新为新值一步完成=============");
System.out.println("key302原值:"+shardedJedis.getSet("key302", "value302-after-getset"));
System.out.println("key302新值:"+shardedJedis.get("key302"));
System.out.println("=============获取子串=============");
System.out.println("获取key302对应值中的子串:"+shardedJedis.getrange("key302", 5, 7));
}
}
<file_sep>/src/main/java/com/vergilyn/demo/redis/listener/jedis/JedisExpiredListener.java
package com.vergilyn.demo.redis.listener.jedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
/**
* key过期事件推送到topic中只有key,无value,因为一旦过期,value就不存在了。
*
* @author VergiLyn
* @blog http://www.cnblogs.com/VergiLyn/
* @date 2017/8/3
*/
@Component
public class JedisExpiredListener extends JedisPubSub {
/** 参考redis目录下redis.conf中的"EVENT NOTIFICATION", redis默认的db{0, 15}一共16个数据库
* K Keyspace events, published with __keyspace@<db>__ prefix.
* E Keyevent events, published with __keyevent@<db>__ prefix.
*
*/
public final static String LISTENER_PATTERN = "__keyevent@*__:expired";
/**
* 虽然能注入,但貌似在listener-class中jedis无法使用(无法建立连接到redis),exception message:
* "only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"
*/
@Autowired
private Jedis jedis;
/**
* 初始化按表达式的方式订阅时候的处理
* @param pattern
* @param subscribedChannels
*/
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.print("onPSubscribe >> ");
System.out.println(String.format("pattern: %s, subscribedChannels: %d", pattern, subscribedChannels));
}
/**
* 取得按表达式的方式订阅的消息后的处理
* @param pattern
* @param channel
* @param message
*/
@Override
public void onPMessage(String pattern, String channel, String message) {
System.out.print("onPMessage >> ");
System.out.println(String.format("key: %s, pattern: %s, channel: %s", message, pattern, channel));
}
/**
* 取得订阅的消息后的处理
* @param channel
* @param message
*/
@Override
public void onMessage(String channel, String message) {
super.onMessage(channel, message);
}
/**
* 初始化订阅时候的处理
* @param channel
* @param subscribedChannels
*/
@Override
public void onSubscribe(String channel, int subscribedChannels) {
super.onSubscribe(channel, subscribedChannels);
}
/**
* 取消订阅时候的处理
* @param channel
* @param subscribedChannels
*/
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
super.onUnsubscribe(channel, subscribedChannels);
}
/**
* 取消按表达式的方式订阅时候的处理
* @param pattern
* @param subscribedChannels
*/
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
super.onPUnsubscribe(pattern, subscribedChannels);
}
}
<file_sep>/src/main/java/com/vergilyn/demo/redis/TypeOperate/SortedSetOperate.java
package com.vergilyn.demo.redis.TypeOperate;
/**
* Created by VergiLyn on 2016/8/22.
*/
public class SortedSetOperate extends TypeOperateObject {
public void show() {
System.out.println("======================zset==========================");
// 清空数据
System.out.println(jedis.flushDB());
System.out.println("=============增=============");
System.out.println("zset中添加元素element001:"+shardedJedis.zadd("zset", 7.0, "element001"));
System.out.println("zset中添加元素element002:"+shardedJedis.zadd("zset", 8.0, "element002"));
System.out.println("zset中添加元素element003:"+shardedJedis.zadd("zset", 2.0, "element003"));
System.out.println("zset中添加元素element004:"+shardedJedis.zadd("zset", 3.0, "element004"));
System.out.println("zset集合中的所有元素:"+shardedJedis.zrange("zset", 0, -1));//按照权重值排序
System.out.println();
System.out.println("=============删=============");
System.out.println("zset中删除元素element002:"+shardedJedis.zrem("zset", "element002"));
System.out.println("zset集合中的所有元素:"+shardedJedis.zrange("zset", 0, -1));
System.out.println();
System.out.println("=============改=============");
System.out.println();
System.out.println("=============查=============");
System.out.println("统计zset集合中的元素中个数:"+shardedJedis.zcard("zset"));
System.out.println("统计zset集合中权重某个范围内(1.0——5.0),元素的个数:"+shardedJedis.zcount("zset", 1.0, 5.0));
System.out.println("查看zset集合中element004的权重:"+shardedJedis.zscore("zset", "element004"));
System.out.println("查看下标1到2范围内的元素值:"+shardedJedis.zrange("zset", 1, 2));
}
}
<file_sep>/README.md
# RedisSamples
个人学习redis的demo,by vergilyn.
主要是通过spring boot配置redis。
其中,也有原始的spring集成redis(jedis)的demo,参考demo中的srping-redis-resources。<file_sep>/src/main/java/com/vergilyn/demo/redis/config/ShardedJedisConfig.java
package com.vergilyn.demo.redis.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import java.util.ArrayList;
import java.util.List;
/**
* @author VergiLyn
* @bolg http://www.cnblogs.com/VergiLyn/
* @date 2017/4/4
*/
@Configuration
@EnableConfigurationProperties({JedisProperties.class})
public class ShardedJedisConfig{
@Autowired
private JedisProperties jedisProperties;
@Bean
public ShardedJedisPool initShardedJedisPool(JedisPoolConfig jedisPoolConfig){
// slave链接
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(jedisProperties.getHost(), jedisProperties.getPort(), "master"));
return new ShardedJedisPool(jedisPoolConfig,shards);
}
@Bean
public ShardedJedis initShardedJedis(ShardedJedisPool shardedJedisPool){
return shardedJedisPool.getResource();
}
}
|
b3355c1a84b74dfc240e53dbfd57ff7dc9cc3c6b
|
[
"Markdown",
"Java",
"INI"
] | 7 |
INI
|
maet-01/RedisSamples
|
40c07590031539117f7d47f06ffa6f259dde49a6
|
d3a8655e37f66da5e1af78cef838bfcb5212f15f
|
refs/heads/main
|
<file_sep># HolaMundo
Hola mundo con MVC
|
42ac09206dfd96d061e97987df7889bcd2b55e5b
|
[
"Markdown"
] | 1 |
Markdown
|
esteban14658/HolaMundo
|
17720e634a1f66f2e80bf78c3479690389a29649
|
0487f0c2a1a1cc819af4730a6c3157c33f00ec6d
|
refs/heads/master
|
<file_sep>import pickle
import matplotlib.pyplot as plt
from operator import add
import numpy
pcfg_dict_fpr = []
pcfg_dict_tpr = []
pcfg_ipv4_fpr = []
pcfg_ipv4_tpr = []
pcfg_dict_num_fpr = []
pcfg_dict_num_tpr = []
pcfg_ipv4_num_fpr = []
pcfg_ipv4_num_tpr = []
pcfg_dict_roc_auc = []
pcfg_ipv4_num_roc_auc = []
pcfg_dict_num_roc_auc = []
pcfg_ipv4_roc_auc = []
def average_list(item_list):
for i in range(0, len(item_list)):
item_list[i] = item_list[i]/count
def pad_zeros(list1, list2):
if len(list1) > len(list2):
list2.extend([0] * (len(list1) - len(list2)))
# list1 = list1[:len(list2)]
else:
list1.extend([0] * (len(list2) - len(list1)))
# list2 = list2[:len(list1)]'''
return list1, list2
with open('/home/ashiq/Pictures/Thesis_data/Thesis_data', 'rb') as f:
count = 0
while True:
try:
print(count)
pcfg_dict_fpr, itemlist = pad_zeros(pcfg_dict_fpr, pickle.load(f).tolist())
pcfg_dict_fpr = list(map(add, pcfg_dict_fpr, itemlist))
pcfg_dict_tpr, itemlist = pad_zeros(pcfg_dict_tpr, pickle.load(f).tolist())
pcfg_dict_tpr = list(map(add, pcfg_dict_tpr, itemlist))
pcfg_dict_roc_auc.append(pickle.load(f).tolist())
pcfg_ipv4_fpr, itemlist = pad_zeros(pcfg_ipv4_fpr, pickle.load(f).tolist())
pcfg_ipv4_fpr = list(map(add, pcfg_ipv4_fpr, itemlist))
pcfg_ipv4_tpr, itemlist = pad_zeros(pcfg_ipv4_tpr, pickle.load(f).tolist())
pcfg_ipv4_tpr = list(map(add, pcfg_ipv4_tpr, itemlist))
pcfg_ipv4_roc_auc.append(pickle.load(f).tolist())
pcfg_ipv4_num_fpr, itemlist = pad_zeros(pcfg_ipv4_num_fpr, pickle.load(f).tolist())
pcfg_ipv4_num_fpr = list(map(add, pcfg_ipv4_num_fpr, itemlist))
pcfg_ipv4_num_tpr, itemlist = pad_zeros(pcfg_ipv4_num_tpr, pickle.load(f).tolist())
pcfg_ipv4_num_tpr = list(map(add, pcfg_ipv4_num_tpr, itemlist))
pcfg_ipv4_num_roc_auc.append(pickle.load(f).tolist())
pcfg_dict_num_fpr, itemlist = pad_zeros(pcfg_dict_num_fpr, pickle.load(f).tolist())
pcfg_dict_num_fpr = list(map(add, pcfg_dict_num_fpr, itemlist))
pcfg_dict_num_tpr, itemlist = pad_zeros(pcfg_dict_num_tpr, pickle.load(f).tolist())
pcfg_dict_num_tpr = list(map(add, pcfg_dict_num_tpr, itemlist))
pcfg_dict_num_roc_auc.append(pickle.load(f).tolist())
count = count + 1
except Exception as e:
print(e)
break
average_list(pcfg_ipv4_fpr)
average_list(pcfg_ipv4_tpr)
average_list(pcfg_dict_num_tpr)
average_list(pcfg_dict_num_fpr)
average_list(pcfg_dict_fpr)
average_list(pcfg_dict_tpr)
average_list(pcfg_ipv4_num_fpr)
average_list(pcfg_ipv4_num_tpr)
pcfg_dict_num_roc_auc = sum(pcfg_dict_num_roc_auc)/len(pcfg_dict_num_roc_auc)
pcfg_dict_roc_auc = sum(pcfg_dict_roc_auc)/len(pcfg_dict_roc_auc)
pcfg_ipv4_num_roc_auc = sum(pcfg_ipv4_num_roc_auc)/len(pcfg_ipv4_num_roc_auc)
pcfg_ipv4_roc_auc = sum(pcfg_ipv4_roc_auc)/len(pcfg_ipv4_roc_auc)
fig, ax = plt.subplots()
plt.title('ROC curve for PCFG BOTNETs, 20 times, 2000 data')
plt.plot(pcfg_dict_fpr, pcfg_dict_tpr, 'b', label='pcfg_dict, AUC = %0.2f' % pcfg_dict_roc_auc)
plt.plot(pcfg_ipv4_fpr, pcfg_ipv4_tpr, 'g', label='pcfg_ipv4, AUC = %0.2f' % pcfg_ipv4_roc_auc)
plt.plot(pcfg_ipv4_num_fpr, pcfg_ipv4_num_tpr, 'r', label='pcfg_ipv4_num, AUC = %0.2f' % pcfg_ipv4_num_roc_auc)
plt.plot(pcfg_dict_num_fpr, pcfg_dict_num_tpr, 'c', label='pcfg_dict_num, AUC = %0.2f' % pcfg_dict_num_roc_auc)
# common part for all files
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
fig.savefig('/home/ashiq/Pictures/Thesis_image/PCFG_US.eps', format='eps')
plt.show()<file_sep>import sklearn
import sklearn as sk
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.metrics import roc_curve
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman"
# constant variables or hyperparamaters
n_class = 2 # change it to 1
n_hidden_1 = 50
n_hidden_2 = 40
n_hidden_3 = 30
n_hidden_4 = 20
learning_rate = 0.05
training_epoch = 150
def thesis(file_path, name, fn):
feature_no = fn
n_dim = feature_no
# data processing
def read_dataset(file_path):
# Reading the dataset using panda's dataframe
df = pd.read_csv(file_path)
X = df[df.columns[0: feature_no]].values
y = df[df.columns[feature_no]]
# Encode the dependent variable
Y = one_hot_encode(y)
return X, Y
# Define the encoder function.
def one_hot_encode(labels):
n_labels = len(labels)
n_unique_labels = len(np.unique(labels))
one_hot_encode = np.zeros((n_labels, n_unique_labels))
one_hot_encode[np.arange(n_labels), labels] = 1
return one_hot_encode
X, Y = read_dataset(file_path)
X, Y = shuffle(X, Y, random_state=20)
final_train_x, final_test_x, final_train_y, final_test_y = train_test_split(X, Y, test_size=0.20, random_state=415)
# model parameters
weights = {
'h1': tf.Variable(tf.truncated_normal([n_dim, n_hidden_1])),
'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2])),
'h3': tf.Variable(tf.truncated_normal([n_hidden_2, n_hidden_3])),
'h4': tf.Variable(tf.truncated_normal([n_hidden_3, n_hidden_4])),
'out': tf.Variable(tf.truncated_normal([n_hidden_4, n_class]))
}
biases = {
'b1': tf.Variable(tf.truncated_normal([n_hidden_1])),
'b2': tf.Variable(tf.truncated_normal([n_hidden_2])),
'b3': tf.Variable(tf.truncated_normal([n_hidden_3])),
'b4': tf.Variable(tf.truncated_normal([n_hidden_4])),
'out': tf.Variable(tf.truncated_normal([n_class]))
}
# inputs and outputs
x = tf.placeholder(tf.float32, [None, n_dim])
y = tf.placeholder(tf.float32, [None, n_class])
# model definition
def multilayer_perceptron(x, weights, biases):
# Hidden layer with leaky relu activation
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.tanh(layer_1)
# Hidden layer with leaky relu activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.tanh(layer_2)
# Hidden layer with leaky relu activation
layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])
layer_3 = tf.nn.tanh(layer_3)
# Hidden layer with leaky relu activation
layer_4 = tf.add(tf.matmul(layer_3, weights['h4']), biases['b4'])
layer_4 = tf.nn.tanh(layer_4)
# Output layer with linear activation
out_layer = tf.add(tf.matmul(layer_4, weights['out']), biases['out'])
out_layer = tf.nn.softmax(out_layer)
return out_layer
model = multilayer_perceptron(x, weights, biases)
# loss function and optimizer
reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
cost_function = tf.losses.mean_squared_error(labels=y, predictions=model)
# cost_function += sum(reg_losses)
# cost_function = cost_function + 0.01*tf.nn.l2_loss(weights['h1']) + 0.01*tf.nn.l2_loss(weights['h2']) +\
# 0.01*tf.nn.l2_loss(weights['h3']) + 0.01*tf.nn.l2_loss(weights['h4'])
training_step = tf.train.AdamOptimizer(learning_rate).minimize(cost_function)
# accuracy measurement
correct_prediction = tf.equal(tf.argmax(model, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# initialize global variables
init = tf.global_variables_initializer()
saver = tf.train.Saver()
sess = tf.Session()
sess.run(init)
# correct weights and biases
cost_history = []
accuracy_history = []
for epoch in range(0, training_epoch):
sess.run(training_step, {x: final_train_x, y: final_train_y})
print(name, "Epoch: ", epoch, end=' ')
accuracy_value = sess.run(accuracy, {x: final_train_x, y: final_train_y})
accuracy_history.append(accuracy_value)
print("Accuracy: ", accuracy_value, end=' ')
cost = sess.run(cost_function, {x: final_train_x, y: final_train_y})
cost_history.append(cost)
print("Cost: ", cost)
'''
# training accuracy and cost graph plot
fig, ax = plt.subplots()
plt.plot(accuracy_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('Training Accuracy')
fig.savefig('/home/ashiq/Pictures/filename1.eps', format='eps')
plt.show()
fig, ax = plt.subplots()
plt.plot(cost_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('Training Error')
fig.savefig('/home/ashiq/Pictures/filename2.eps', format='eps')
plt.show()
'''
# test accuracy & f1-score calculation
print(name)
print("Accuracy: ", sess.run(accuracy, {x: final_test_x, y: final_test_y}))
final_y = sess.run(model, feed_dict={x: final_test_x})
actual_y = np.argmax(final_test_y, 1) # 1 0 -> 0 , 0 1 -> 1
predicted_y = np.argmax(final_y, 1) # max min -> 0 , min max -> 1
f1_score = sk.metrics.f1_score(actual_y, predicted_y)
precision = sk.metrics.precision_score(actual_y, predicted_y)
recall = sk.metrics.recall_score(actual_y, predicted_y)
print("F1 score: ", f1_score)
mse = sess.run(cost_function, {x: final_test_x, y: final_test_y})
print("Mean Squared Error: ", mse)
# print("Recall: ", recall, "Precision: ", precision)
# auc_score calculation
predicted_y = np.array(final_y)[:, 1]
y_true = []
for i in range(0, len(final_test_y)):
if final_test_y[i][0] == 1:
y_true.append(0)
else:
y_true.append(1)
y_true = np.array(y_true)
# print(y_true)
fpr, tpr, thresholds = roc_curve(y_true, predicted_y)
roc_auc = sklearn.metrics.auc(fpr, tpr)
# print(fpr, tpr, thresholds)
print("AUC score: ", roc_auc)
with open('/home/ashiq/Pictures/Thesis_data/hmm_dga.txt', 'a') as f:
f.write(name + '\n')
f.write('Accuracy: ' + str(sess.run(accuracy, {x: final_test_x, y: final_test_y})) + '\n')
f.write('F1_Score: ' + str(f1_score) + '\n')
f.write('Mean Squared Error: ' + str(mse) + '\n')
f.write('AUC Score: ' + str(roc_auc) + '\n')
sess.close()
return fpr, tpr, thresholds, roc_auc, accuracy_history, cost_history
# open file
KL3_fpr, KL3_tpr, KL3_threshholds, KL3_roc_auc, \
KL3_accuracy_graph, KL3_cost_graph = thesis("input_csv_files/hmm_dga/500KL3.csv", '500KL3', 9)
KL2_fpr, KL2_tpr, KL2_threshholds, KL2_roc_auc, \
KL2_accuracy_graph, KL2_cost_graph = thesis("input_csv_files/hmm_dga/500KL2.csv", '500KL2', 9)
DNL3_fpr, DNL3_tpr, DNL3_threshholds, DNL3_roc_auc, \
DNL3_accuracy_graph, DNL3_cost_graph= thesis("input_csv_files/hmm_dga/DNL3.csv", 'DNL3', 9)
DNL2_fpr, DNL2_tpr, DNL2_threshholds, DNL2_roc_auc, \
DNL2_accuracy_graph, DNL2_cost_graph= thesis("input_csv_files/hmm_dga/DNL2.csv", 'DNL2', 9)
ML1_fpr, ML1_tpr, ML1_threshholds, ML1_roc_auc, \
ML1_accuracy_graph, ML1_cost_graph= thesis("input_csv_files/hmm_dga/9ML1.csv", '9ML1', 9)
DNL4_fpr, DNL4_tpr, DNL4_threshholds, DNL4_roc_auc, \
DNL4_accuracy_graph, DNL4_cost_graph= thesis("input_csv_files/hmm_dga/DNL4.csv", 'DNL4', 9)
DNL1_fpr, DNL1_tpr, DNL1_threshholds, DNL1_roc_auc, \
DNL1_accuracy_graph, DNL1_cost_graph= thesis("input_csv_files/hmm_dga/DNL1.csv", 'DNL1', 9)
KL1_fpr, KL1_tpr, KL1_threshholds, KL1_roc_auc, \
KL1_accuracy_graph, KL1_cost_graph = thesis("input_csv_files/hmm_dga/500KL1.csv", '500KL1', 9)
# ROC graph drawing
fig, ax = plt.subplots()
plt.title('ROC curve for HMM BOTNETs, 20 times, 2000 data')
plt.plot(KL3_fpr, KL3_tpr, color='b', label='500KL3, AUC = %0.2f' % KL3_roc_auc)
plt.plot(KL2_fpr, KL2_tpr, color='g', label='500KL2, AUC = %0.2f' % KL2_roc_auc)
plt.plot(DNL3_fpr, DNL3_tpr, color='r', label='DNL3, AUC = %0.2f' % DNL3_roc_auc)
plt.plot(DNL2_fpr, DNL2_tpr, color='c', label='DNL2, AUC = %0.2f' % DNL2_roc_auc)
plt.plot(ML1_fpr, ML1_tpr, color='m', label='9ML1, AUC = %0.2f' % ML1_roc_auc)
plt.plot(DNL4_fpr, DNL4_tpr, color='y', label='DNL4, AUC = %0.2f' % DNL4_roc_auc)
plt.plot(DNL1_fpr, DNL1_tpr, color='k', label='DNL1, AUC = %0.2f' % DNL1_roc_auc)
plt.plot(KL1_fpr, KL1_tpr, color='grey', label='500KL1, AUC = %0.2f' % KL1_roc_auc)
# common part for all files
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
fig.savefig('/home/ashiq/Pictures/Thesis_image/500KL_US.eps', format='eps')
plt.show()
'''
fig, ax = plt.subplots()
plt.plot(KL3_accuracy_graph, 'b', label='%s' % '500KL3')
plt.plot(KL2_accuracy_graph, 'g', label='%s' % '500KL2')
plt.plot(DNL3_accuracy_graph, 'r', label='%s' % 'DNL3')
plt.plot(DNL2_accuracy_graph, 'c', label='%s' % 'DNL2')
plt.plot(ML1_accuracy_graph, 'm', label='%s' % '9ML1')
plt.plot(DNL4_accuracy_graph, 'y', label='%s' % 'DNL4')
plt.plot(DNL1_accuracy_graph, 'k', label='%s' % 'DNL1')
plt.plot(KL1_accuracy_graph, 'grey', label='%s' % '500KL1')
plt.xlabel('Epoch')
plt.ylabel('Training Accuracy')
plt.legend(loc='lower right')
fig.savefig('/home/ashiq/Pictures/Thesis_image/hmm_accuracy.eps', format='eps')
plt.show()
fig, ax = plt.subplots()
plt.plot(KL3_cost_graph, 'b', label='%s' % '500KL3')
plt.plot(KL2_cost_graph, 'g', label='%s' % '500KL2')
plt.plot(DNL3_cost_graph, 'r', label='%s' % 'DNL3')
plt.plot(DNL2_cost_graph, 'c', label='%s' % 'DNL2')
plt.plot(ML1_cost_graph, 'm', label='%s' % '9ML1')
plt.plot(DNL4_cost_graph, 'y', label='%s' % 'DNL4')
plt.plot(DNL1_cost_graph, 'k', label='%s' % 'DNL1')
plt.plot(KL1_cost_graph, 'grey', label='%s' % '500KL1')
plt.xlabel('Epoch')
plt.ylabel('Training Error')
plt.legend(loc='lower right')
fig.savefig('/home/ashiq/Pictures/Thesis_image/hmm_error.eps', format='eps')
plt.show()
'''<file_sep>import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.model_selection import LeaveOneOut, KFold, cross_val_score
def read_dataset():
# Reading the dataset using panda's dataframe
df = pd.read_csv("input.csv")
X = df[df.columns[0:4]].values
y = df[df.columns[4]]
# Encode the dependent variable
Y = one_hot_encode(y)
return X, Y
# Define the encoder function.
def one_hot_encode(labels):
n_labels = len(labels)
n_unique_labels = len(np.unique(labels))
one_hot_encode = np.zeros((n_labels, n_unique_labels))
one_hot_encode[np.arange(n_labels), labels] = 1
return one_hot_encode
# for k-fold cross validation
def make_dataset(X_data, y_data, n_splits):
def gen():
for train_index, test_index in KFold(n_splits=n_splits).split(X_data):
X_train, X_test = X_data[train_index], X_data[test_index]
y_train, y_test = y_data[train_index], y_data[test_index]
print('Train: %s | test: %s' % (train_index, test_index))
yield X_train, y_train, X_test, y_test
return tf.data.Dataset.from_generator(gen, (tf.float64,tf.float64,tf.float64,tf.float64))
# Read the dataset
X, Y = read_dataset()
# print(X, Y)
dataset = make_dataset(X, Y, 3)
#print(dataset)
# sess = tf.Session()
# sess.run(tf.global_variables_initializer())
# print(sess.run(dataset))
<file_sep>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.c_[[0.70, 0.84, 0.86, 0.55, 0.84, 0.83, 0.84, 0.84, 0.88, 0.95, 0.95, 0.94, 0.89, 0.81, 0.80, 0.75, 0.75, 0.58],
[0.61, 0.62, 0.63, 0.55, 0.67, 0.69, 0.66, 0.65, 0.81, 0.88, 0.95, 0.95, 0.73, 0.75, 0.72, 0.68, 0.67, 0.59],
[0.70, 0.90, 0.92, 0.62, 0.91, 0.90, 0.89, 0.87, 0.90, 0.91, 0.99, 1.00, 0.88, 0.89, 0.88, 0.86, 0.88, 0.60],
[0.96, 0.98, 0.98, 0.93, 0.92, 0.89, 0.88, 0.88, 0.99, 0.98, 0.99, 1.00, 0.98, 0.79, 0.77, 0.79, 0.92, 0.94]],
columns=['KL score', 'ED score', 'JI score', 'Our score'])
'''[0.91, 0.613, 0.61, 0.91], [0.684, 0.62, 0.78, 0.95], [0.68, 0.63, 0.783, 0.95],
[0.68, 0.55, 0.803, 0.65], [0.757, 0.655, 0.82, 0.57], [0.78, 0.894, 0.81, 0.58],
[0.78, 0.65, 0.82, 0.61], [0.88, 0.81, 0.93, 0.91], [0.95, 0.88, 0.95, 0.92],
[0.55, 0.70, 0.62, 0.69], [0.94, 0.91, 0.97, 0.98], [0.77, 0.71, 0.84, 0.77],
[0.74, 0.68, 0.79, 0.73], [0.74, 0.67, 0.74, 0.76], [0.58, 0.59, 0.60, 0.77]'''
value = df.mean()
print(value)
std = df.std()
print(std)
fig, ax = plt.subplots()
colors = ["red", "green", "blue", "purple"]
# plt.axhline(y=0.87, zorder=0)
plt.bar(np.arange(len(df.columns)), value, width=0.5, bottom=0,
yerr=std, align='center', alpha=0.5, color=colors)
plt.xticks(range(len(df.columns)), df.columns)
plt.ylabel('AUC score')
plt.title('Confidence Interval Bar Graph')
fig.savefig('/home/ashiq/Pictures/Thesis_image/conf_bar_graph.eps', format='eps')
plt.show()
<file_sep>import matplotlib.pyplot as plt
import sklearn
import sklearn as sk
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.metrics import roc_curve
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.model_selection import LeaveOneOut, KFold
# ongoing:
# metrics:
# 1. accuracy
# 2. f1-score
# 3. false-positive
# 4. false-negative
# 5. roc curve
# with datasets of different source
# change learning rate, epoch, k-fold, hidden_layer and no. of neurons in hidden layer
# parameters for DGA botnet detection
feature_no = 6
'''no_of_hidden_layers = int(input())
hidden_layer_neurons = []
for i in range(0, no_of_hidden_layers):
hidden_layer_neurons.append(int(input()))'''
def Thesis(file_path, name):
def read_dataset():
# Reading the dataset using panda's dataframe
df = pd.read_csv(file_path)
X = df[df.columns[0:feature_no]].values
y = df[df.columns[feature_no]]
# Encode the dependent variable
Y = one_hot_encode(y)
return X, Y
# Define the encoder function.
def one_hot_encode(labels):
n_labels = len(labels)
n_unique_labels = len(np.unique(labels))
one_hot_encode = np.zeros((n_labels, n_unique_labels))
one_hot_encode[np.arange(n_labels), labels] = 1
return one_hot_encode
# Read the dataset
X, Y = read_dataset()
# Shuffle the dataset to mix up the rows.
X, Y = shuffle(X, Y, random_state=20)
# X, Y = X[0:10000], Y[0:10000]
# Convert the dataset into train and test part
final_train_x, final_test_x, final_train_y, final_test_y = train_test_split(X, Y, test_size=0.20, random_state=415)
# train_x, test_x, train_y, test_y = [], [], [], []
# Inspect the shape of the training and testing.
'''print(train_x.shape)
print(train_y.shape)
# print()
print(test_x.shape)
print(test_y.shape)'''
# Define the important parameters and variable to work with the tensors
learning_rate = 0.6
training_epochs = 150
# cost_history = np.empty(shape=[1], dtype=float)
n_dim = X.shape[1]
n_class = 2
model_path = "/home/ashiq/PycharmProjects/TensorFlow_MLP_test/Graphs/graph"
# Define the number of hidden layers and number of neurons for each layer
n_hidden_1 = 50 # hidden_layer_neurons[0]
n_hidden_2 = 40
n_hidden_3 = 30
n_hidden_4 = 20
# x = value of feature vectors, y_ = vector of actual output values
x = tf.placeholder(tf.float32, [None, n_dim])
y_ = tf.placeholder(tf.float32, [None, n_class])
# Define the model
def multilayer_perceptron(x, weights, biases):
# Hidden layer with RELU activation
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.sigmoid(layer_1)
# Hidden layer with sigmoid activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.sigmoid(layer_2)
# Hidden layer with sigmoid activation
layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])
layer_3 = tf.nn.sigmoid(layer_3)
# Hidden layer with RELU activation
layer_4 = tf.add(tf.matmul(layer_3, weights['h4']), biases['b4'])
layer_4 = tf.nn.sigmoid(layer_4)
# Output layer with linear activation
out_layer = tf.add(tf.matmul(layer_4, weights['out']), biases['out'])
out_layer = tf.nn.softmax(out_layer)
return out_layer
# Define the weights and the biases for each layer
weights = {
'h1': tf.Variable(tf.truncated_normal([n_dim, n_hidden_1])),
'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2])),
'h3': tf.Variable(tf.truncated_normal([n_hidden_2, n_hidden_3])),
'h4': tf.Variable(tf.truncated_normal([n_hidden_3, n_hidden_4])),
'out': tf.Variable(tf.truncated_normal([n_hidden_4, n_class]))
}
biases = {
'b1': tf.Variable(tf.truncated_normal([n_hidden_1])),
'b2': tf.Variable(tf.truncated_normal([n_hidden_2])),
'b3': tf.Variable(tf.truncated_normal([n_hidden_3])),
'b4': tf.Variable(tf.truncated_normal([n_hidden_4])),
'out': tf.Variable(tf.truncated_normal([n_class]))
}
# Initialize all the variables
# Call your model defined
y = multilayer_perceptron(x, weights, biases)
# Define the cost function and optimizer
reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
reg_constant = 0 # Choose an appropriate one.
cost_function = tf.losses.mean_squared_error(labels=y_, predictions=y) + reg_constant * sum(reg_losses)
training_step = tf.train.AdamOptimizer(learning_rate).minimize(cost_function)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
def run_train(sess, train_x, train_y, test_x, test_y, flag, i):
sess.run(init)
# Calculate the cost and the accuracy for each epoch
# print(train_x, test_x)
mse_history = []
accuracy_history = []
f1_history = []
# cost_history = []
for epoch in range(training_epochs):
sess.run(training_step, feed_dict={x: train_x, y_: train_y})
cost = sess.run(cost_function, feed_dict={x: train_x, y_: train_y})
# cost_history = np.append(cost_history, cost)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# print("Accuracy: ", (sess.run(accuracy, feed_dict={x: test_x, y_: test_y})))
pred_y = sess.run(y, feed_dict={x: test_x})
mse = tf.reduce_mean(tf.square(pred_y - test_y))
mse_ = sess.run(mse)
mse_history.append(mse_)
accuracy = (sess.run(accuracy, feed_dict={x: train_x, y_: train_y}))
accuracy_history.append(accuracy)
y_true = np.argmax(test_y, 1) # 1 0 -> 0 , 0 1 -> 1
y_pred = np.argmax(pred_y, 1) # max min -> 0 , min max -> 1
f1_score = sk.metrics.f1_score(y_true, y_pred)
print('fold: ', i, "F1-score", f1_score)
f1_history.append(f1_score)
print('fold: ', i, 'epoch : ', epoch, ' - ', 'cost: ', cost, " - MSE: ", mse_, "- Train Accuracy: ", accuracy)
save_path = saver.save(sess, model_path)
print("Model saved in file: %s" % save_path)
# Plot Accuracy Graph
if flag == 1:
plt.plot(accuracy_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('Training Accuracy')
plt.show()
plt.plot(f1_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('F1 Score')
plt.show()
plt.plot(mse_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('Training Error')
plt.show()
def cross_validate(session, split_size=5):
results = []
kf = KFold(n_splits=split_size)
i = 0
for train_index, test_index in kf.split(final_train_x):
train_x1, test_x1 = X[train_index], X[test_index]
train_y1, test_y1 = Y[train_index], Y[test_index]
# print(train_index, test_index)
# print("trx", train_x1)
# print("try", train_y1)
# print("tex", test_x1)
# print("tey", test_y1)
# if i == 0:
# flag = 1
#else:
# flag = 0
flag = 1
run_train(session, train_x1, train_y1, test_x1, test_y1, flag, i)
i += 1
results.append(session.run(accuracy, feed_dict={x: test_x1, y_: test_y1}))
return results
def without_cross_validate(session):
results = []
train_x1, test_x1, train_y1, test_y1 = train_test_split(final_train_x, final_train_y, test_size=0.20, random_state=415)
run_train(session, train_x1, train_y1, test_x1, test_y1, 1, 1)
results.append(session.run(accuracy, feed_dict={x: test_x1, y_: test_y1}))
return results
with tf.Session() as session:
# result = cross_validate(session)
result = without_cross_validate(session)
print("For %s" % name)
print("Without Cross-validation result %s:" % result)
# print("Cross-validation result %s:" % result)
print("Test accuracy: %f" % session.run(accuracy, feed_dict={x: final_test_x, y_: final_test_y}))
pred_y = session.run(y, feed_dict={x: final_test_x})
mse = tf.reduce_mean(tf.square(pred_y - final_test_y))
# print(pred_y)
# print(final_test_y)
actual_y = np.argmax(final_test_y, 1) # 1 0 -> 0 , 0 1 -> 1
predicted_y = np.argmax(pred_y, 1) # max min -> 0 , min max -> 1
f1_score = sk.metrics.f1_score(actual_y, predicted_y)
precision = sk.metrics.precision_score(actual_y, predicted_y)
recall = sk.metrics.recall_score(actual_y, predicted_y)
print(predicted_y[0: 10])
print("F1-Score: %.4f" % f1_score)
print("Precision-Score: %.4f" % precision)
print("Recall-Score: %.4f" % recall)
print("MSE: %.4f" % session.run(mse))
print()
pred_y = np.array(pred_y)[:, 1]
# print(pred_y)
y_true = []
for i in range(0, len(final_test_y)):
if final_test_y[i][0] == 1:
y_true.append(0)
else:
y_true.append(1)
y_true = np.array(y_true)
# print(y_true)
fpr, tpr, thresholds = roc_curve(y_true, pred_y)
roc_auc = sklearn.metrics.auc(fpr, tpr)
# print(fpr, tpr, thresholds)
return fpr, tpr, thresholds, roc_auc
# conflicker_fpr, conflicker_tpr, conflicker_threshholds, conflicker_roc_auc = Thesis("input_csv_files/other/conflicker.csv", 'conflicker')
# kraken_fpr, kraken_tpr, kraken_threshholds, kraken_roc_auc = Thesis("input_csv_files/other/kraken.csv", 'kraken')
# kwyjibo_fpr, kwyjibo_tpr, kwyjibo_threshholds, kwyjibo_roc_auc = Thesis("input_csv_files/other/kwyjibo.csv", 'kwyjibo')
# srizbi_fpr, srizbi_tpr, srizbi_threshholds, srizbi_roc_auc = Thesis("input_csv_files/other/srizbi.csv", 'srizbi')
# torpig_fpr, torpig_tpr, torpig_threshholds, torpig_roc_auc = Thesis("input_csv_files/other/torpig.csv", 'torpig')
# zeus_fpr, zeus_tpr, zeus_threshholds, zeus_roc_auc = Thesis("input_csv_files/other/zeus.csv", 'zeus')
# ML1_9_fpr, ML1_9_tpr, ML1_9_threshholds, ML1_9_roc_auc = Thesis("input_csv_files/hmm_dga/9ML1.csv", '9ML1')
# KL1_500_fpr, KL1_500_tpr, KL1_500_threshholds, KL1_500_roc_auc = Thesis("input_csv_files/hmm_dga/500KL1.csv", '500KL1')
# KL2_500_fpr, KL2_500_tpr, KL2_500_threshholds, KL2_500_roc_auc = Thesis("input_csv_files/hmm_dga/500KL2.csv", '500KL2')
# KL3_500_fpr, KL3_500_tpr, KL3_500_threshholds, KL3_500_roc_auc = Thesis("input_csv_files/hmm_dga/500KL3.csv", '500KL3')
# DNL1_fpr, DNL1_tpr, DNL1_threshholds, DNL1_roc_auc = Thesis("input_csv_files/hmm_dga/DNL1.csv", 'DNL1')
# DNL2_fpr, DNL2_tpr, DNL2_threshholds, DNL2_roc_auc = Thesis("input_csv_files/hmm_dga/DNL2.csv", 'DNL2')
# DNL3_fpr, DNL3_tpr, DNL3_threshholds, DNL3_roc_auc = Thesis("input_csv_files/hmm_dga/DNL3.csv", 'DNL3')
# DNL4_fpr, DNL4_tpr, DNL4_threshholds, DNL4_roc_auc = Thesis("input_csv_files/hmm_dga/DNL4.csv", 'DNL4')
pcfg_dict_fpr, pcfg_dict_tpr, pcfg_dict_threshholds, pcfg_dict_roc_auc = Thesis("input_csv_files/pcfg_dga/pcfg_dict.csv", 'PCFG_DICT')
pcfg_dict_num_fpr, pcfg_dict_num_tpr, pcfg_dict_num_threshholds, pcfg_dict_num_roc_auc = Thesis("input_csv_files/pcfg_dga/pcfg_dict_num.csv", 'PCFG_DICT_NUM')
pcfg_ipv4_fpr, pcfg_ipv4_tpr, pcfg_ipv4_threshholds, pcfg_ipv4_roc_auc = Thesis("input_csv_files/pcfg_dga/pcfg_ipv4.csv", 'PCFG_IPV4')
pcfg_ipv4_num_fpr, pcfg_ipv4_num_tpr, pcfg_ipv4_num_threshholds, pcfg_ipv4_num_roc_auc = Thesis("input_csv_files/pcfg_dga/pcfg_ipv4_num.csv", 'PCFG_IPV4_NUM')
plt.title('Receiver Operating Characteristic for PCFG BOTNETs')
plt.plot(pcfg_dict_fpr, pcfg_dict_tpr, color='darkgrey', label='pcfg_dict, AUC = %0.2f' % pcfg_dict_roc_auc)
plt.plot(pcfg_dict_num_fpr, pcfg_dict_num_tpr, 'g', label='pcfg_dict_num, AUC = %0.2f' % pcfg_dict_num_roc_auc)
plt.plot(pcfg_ipv4_fpr, pcfg_ipv4_tpr, 'b', label='pcfg_ipv4, AUC = %0.2f' % pcfg_ipv4_roc_auc)
plt.plot(pcfg_ipv4_num_fpr, pcfg_ipv4_num_tpr, 'm', label='pcfg_ipv4_num, AUC = %0.2f' % pcfg_ipv4_num_roc_auc)
'''
plt.title('Receiver Operating Characteristic for HMM BOTNETs')
plt.plot(ML1_9_fpr, ML1_9_tpr, color='darkgrey', label='9ML1, AUC = %0.2f' % ML1_9_roc_auc)
plt.plot(KL1_500_fpr, KL1_500_tpr, 'g', label='500KL1, AUC = %0.2f' % KL1_500_roc_auc)
plt.plot(KL2_500_fpr, KL2_500_tpr, 'b', label='500KL2, AUC = %0.2f' % KL2_500_roc_auc)
plt.plot(KL3_500_fpr, KL3_500_tpr, 'm', label='500KL3, AUC = %0.2f' % KL3_500_roc_auc)
plt.plot(DNL1_fpr, DNL1_tpr, 'c', label='DNL1, AUC = %0.2f' % DNL1_roc_auc)
plt.plot(DNL2_fpr, DNL2_tpr, 'k', label='DNL2, AUC = %0.2f' % DNL2_roc_auc)
plt.plot(DNL3_fpr, DNL3_tpr, 'r', label='DNL3, AUC = %0.2f' % DNL3_roc_auc)
plt.plot(DNL4_fpr, DNL4_tpr, 'y', label='DNL4, AUC = %0.2f' % DNL4_roc_auc)
'''
'''
plt.title('Receiver Operating Characteristic for KNOWN BOTNETs')
# plt.plot(conflicker_fpr, conflicker_tpr, color='darkgrey', label='conflicker, AUC = %0.2f' % conflicker_roc_auc)
plt.plot(kraken_fpr, kraken_tpr, 'g', label='kraken, AUC = %0.2f' % kraken_roc_auc)
# plt.plot(kwyjibo_fpr, kwyjibo_tpr, 'b', label='kwyjibo, AUC = %0.2f' % kwyjibo_roc_auc)
plt.plot(srizbi_fpr, srizbi_tpr, 'm', label='srizbi, AUC = %0.2f' % srizbi_roc_auc)
plt.plot(torpig_fpr, torpig_tpr, 'c', label='torpig, AUC = %0.2f' % torpig_roc_auc)
plt.plot(zeus_fpr, zeus_tpr, 'k', label='zeus, AUC = %0.2f' % zeus_roc_auc)
'''
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()<file_sep>import sklearn
import sklearn as sk
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.metrics import roc_curve
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman"
# constant variables or hyperparamaters
feature_no = 9
n_dim = feature_no
n_class = 2 # change it to 1
n_hidden_1 = 50
n_hidden_2 = 40
n_hidden_3 = 30
n_hidden_4 = 20
learning_rate = 0.05
training_epoch = 150
def thesis(file_path, name, layer_no):
# data processing
def read_dataset(file_path):
# Reading the dataset using panda's dataframe
df = pd.read_csv(file_path)
X = df[df.columns[0:9]].values
y = df[df.columns[9]]
# Encode the dependent variable
Y = one_hot_encode(y)
return X, Y
# Define the encoder function.
def one_hot_encode(labels):
n_labels = len(labels)
n_unique_labels = len(np.unique(labels))
one_hot_encode = np.zeros((n_labels, n_unique_labels))
one_hot_encode[np.arange(n_labels), labels] = 1
return one_hot_encode
X, Y = read_dataset(file_path)
X, Y = shuffle(X, Y, random_state=20)
final_train_x, final_test_x, final_train_y, final_test_y = train_test_split(X, Y, test_size=0.20, random_state=415)
# model parameters
if layer_no == 2:
weights = {
'h1': tf.Variable(tf.truncated_normal([n_dim, n_hidden_1])),
'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.truncated_normal([n_hidden_2, n_class]))
}
biases = {
'b1': tf.Variable(tf.truncated_normal([n_hidden_1])),
'b2': tf.Variable(tf.truncated_normal([n_hidden_2])),
'out': tf.Variable(tf.truncated_normal([n_class]))
}
elif layer_no == 3:
weights = {
'h1': tf.Variable(tf.truncated_normal([n_dim, n_hidden_1])),
'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2])),
'h3': tf.Variable(tf.truncated_normal([n_hidden_2, n_hidden_3])),
'out': tf.Variable(tf.truncated_normal([n_hidden_3, n_class]))
}
biases = {
'b1': tf.Variable(tf.truncated_normal([n_hidden_1])),
'b2': tf.Variable(tf.truncated_normal([n_hidden_2])),
'b3': tf.Variable(tf.truncated_normal([n_hidden_3])),
'out': tf.Variable(tf.truncated_normal([n_class]))
}
else:
weights = {
'h1': tf.Variable(tf.truncated_normal([n_dim, n_hidden_1])),
'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2])),
'h3': tf.Variable(tf.truncated_normal([n_hidden_2, n_hidden_3])),
'h4': tf.Variable(tf.truncated_normal([n_hidden_3, n_hidden_4])),
'out': tf.Variable(tf.truncated_normal([n_hidden_4, n_class]))
}
biases = {
'b1': tf.Variable(tf.truncated_normal([n_hidden_1])),
'b2': tf.Variable(tf.truncated_normal([n_hidden_2])),
'b3': tf.Variable(tf.truncated_normal([n_hidden_3])),
'b4': tf.Variable(tf.truncated_normal([n_hidden_4])),
'out': tf.Variable(tf.truncated_normal([n_class]))
}
# inputs and outputs
x = tf.placeholder(tf.float32, [None, n_dim])
y = tf.placeholder(tf.float32, [None, n_class])
# model definition
def multilayer_perceptron(x, weights, biases):
# Hidden layer with tanh activation
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.tanh(layer_1)
# Hidden layer with tanh activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.tanh(layer_2)
# Hidden layer with tanh activation
if layer_no > 2:
layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])
layer_3 = tf.nn.tanh(layer_3)
# Hidden layer with tanh activation
if layer_no > 3:
layer_4 = tf.add(tf.matmul(layer_3, weights['h4']), biases['b4'])
layer_4 = tf.nn.tanh(layer_4)
# Output layer with linear activation
if layer_no == 2:
out_layer = tf.add(tf.matmul(layer_2, weights['out']), biases['out'])
elif layer_no == 3:
out_layer = tf.add(tf.matmul(layer_3, weights['out']), biases['out'])
else:
out_layer = tf.add(tf.matmul(layer_4, weights['out']), biases['out'])
out_layer = tf.nn.softmax(out_layer)
return out_layer
model = multilayer_perceptron(x, weights, biases)
# loss function and optimizer
reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
cost_function = tf.losses.mean_squared_error(labels=y, predictions=model)
# cost_function += sum(reg_losses)
# cost_function = cost_function + 0.01*tf.nn.l2_loss(weights['h1']) + 0.01*tf.nn.l2_loss(weights['h2']) +\
# 0.01*tf.nn.l2_loss(weights['h3']) + 0.01*tf.nn.l2_loss(weights['h4'])
training_step = tf.train.AdamOptimizer(learning_rate).minimize(cost_function)
# accuracy measurement
correct_prediction = tf.equal(tf.argmax(model, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# initialize global variables
init = tf.global_variables_initializer()
saver = tf.train.Saver()
sess = tf.Session()
sess.run(init)
# correct weights and biases
cost_history = []
accuracy_history = []
for epoch in range(0, training_epoch):
sess.run(training_step, {x: final_train_x, y: final_train_y})
print(name, "Epoch: ", epoch, end=' ')
accuracy_value = sess.run(accuracy, {x: final_train_x, y: final_train_y})
accuracy_history.append(accuracy_value)
print("Accuracy: ", accuracy_value, end=' ')
cost = sess.run(cost_function, {x: final_train_x, y: final_train_y})
cost_history.append(cost)
print("Cost: ", cost)
'''
# training accuracy and cost graph plot
fig, ax = plt.subplots()
plt.plot(accuracy_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('Training Accuracy')
fig.savefig('/home/ashiq/Pictures/filename1.eps', format='eps')
plt.show()
fig, ax = plt.subplots()
plt.plot(cost_history, label='%s' % name)
plt.xlabel('Epoch')
plt.ylabel('Training Error')
fig.savefig('/home/ashiq/Pictures/filename2.eps', format='eps')
plt.show()
'''
# test accuracy & f1-score calculation
print(name)
print("Accuracy: ", sess.run(accuracy, {x: final_test_x, y: final_test_y}))
final_y = sess.run(model, feed_dict={x: final_test_x})
actual_y = np.argmax(final_test_y, 1) # 1 0 -> 0 , 0 1 -> 1
predicted_y = np.argmax(final_y, 1) # max min -> 0 , min max -> 1
f1_score = sk.metrics.f1_score(actual_y, predicted_y)
precision = sk.metrics.precision_score(actual_y, predicted_y)
recall = sk.metrics.recall_score(actual_y, predicted_y)
print("F1 score: ", f1_score)
# print("Recall: ", recall, "Precision: ", precision)
# auc_score calculation
predicted_y = np.array(final_y)[:, 1]
y_true = []
for i in range(0, len(final_test_y)):
if final_test_y[i][0] == 1:
y_true.append(0)
else:
y_true.append(1)
y_true = np.array(y_true)
# print(y_true)
fpr, tpr, thresholds = roc_curve(y_true, predicted_y)
roc_auc = sklearn.metrics.auc(fpr, tpr)
# print(fpr, tpr, thresholds)
print("AUC score: ", roc_auc)
sess.close()
return fpr, tpr, thresholds, roc_auc, accuracy_history, cost_history
# open file
fpr_2, tpr_2, threshholds_2, roc_auc_2, \
accuracy_graph_2, cost_graph_2 = thesis("input_csv_files/pcfg_dga/pcfg_dict.csv", '500KL3', 2)
fpr_3, tpr_3, threshholds_3, roc_auc_3, \
accuracy_graph_3, cost_graph_3 = thesis("input_csv_files/pcfg_dga/pcfg_dict.csv", '500KL3', 3)
fpr_4, tpr_4, threshholds_4, roc_auc_4, \
accuracy_graph_4, cost_graph_4 = thesis("input_csv_files/pcfg_dga/pcfg_dict.csv", '500KL3', 4)
# ROC graph drawing
'''
fig, ax = plt.subplots()
plt.title('Receiver Operating Characteristic for PCFG BOTNETs')
plt.plot(pcfg_dict_fpr, pcfg_dict_tpr, color='darkgrey', label='pcfg_dict, AUC = %0.2f' % pcfg_dict_roc_auc)
plt.plot(pcfg_dict_num_fpr, pcfg_dict_num_tpr, 'g', label='pcfg_dict_num, AUC = %0.2f' % pcfg_dict_num_roc_auc)
plt.plot(pcfg_ipv4_fpr, pcfg_ipv4_tpr, 'b', label='pcfg_ipv4, AUC = %0.2f' % pcfg_ipv4_roc_auc)
plt.plot(pcfg_ipv4_num_fpr, pcfg_ipv4_num_tpr, 'm', label='pcfg_ipv4_num, AUC = %0.2f' % pcfg_ipv4_num_roc_auc)
# common part for all files
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
fig.savefig('/home/ashiq/Pictures/filename.eps', format='eps')
plt.show()
'''
fig, ax = plt.subplots()
plt.title('For pcfg_dict DGAs')
plt.plot(accuracy_graph_2, label='%s' % 'number of hidden layers = 2')
plt.plot(accuracy_graph_3, label='%s' % 'number of hidden layers = 3')
plt.plot(accuracy_graph_4, label='%s' % 'number of hidden layers = 4')
plt.xlabel('Epoch')
plt.ylabel('Training Accuracy')
plt.legend(loc='lower right')
fig.savefig('/home/ashiq/Pictures/Thesis_image/hidden_layer_variation.eps', format='eps')
plt.show()
'''
fig, ax = plt.subplots()
plt.plot(pcfg_dict_cost_graph, label='%s' % 'pcfg_dict')
plt.plot(pcfg_dict_num_cost_graph, label='%s' % 'pcfg_dict_num')
plt.plot(pcfg_ipv4_cost_graph, label='%s' % 'pcfg_ipv4')
plt.plot(pcfg_ipv4_num_cost_graph, label='%s' % 'pcfg_ipv4_num')
plt.xlabel('Epoch')
plt.ylabel('Training Error')
fig.savefig('/home/ashiq/Pictures/error.eps', format='eps')
plt.show()
'''
|
982c3c6903a0744866e9e367cef5a262dd1590e0
|
[
"Python"
] | 6 |
Python
|
Ashiq5/Botnet_Detection
|
90ad78b7049f584857f7e9bd345d700d419fef84
|
7634a68dedb6555e3563773a76bfe694156c25c7
|
refs/heads/master
|
<repo_name>RohanGupta24/Hello-World<file_sep>/FacebookRetrieval.R
install.packages("Rfacebook")
//install.packages("contrib.url")
library(devtools)
install_github("Rfacebook", "pablobarbera", subdir = "Rfacebook")
library(Rfacebook)
token <- "<KEY>"
me <- getUsers("pablobarbera", token, private_info = TRUE)
me$name
getPage <- function(page, token, n=25, since=NULL, until=NULL, feed=FALSE, reactions=FALSE) {
url <- paste0('https://graph.facebook.com/', page, 'posts?fields=from,message,created_time,type,link,story,comments.summary(true)','likes.summary(true),shares')
if(feed) {
url <- paste0('https://graph.facebook.com/', page, '/feed?fields=from,message,created_time,type,link,story,comments.summary(true)', 'likes.summary(true),shares')
if(!is.null(until)) {
url <- paste0(url, '&until=', until)
}
if(!is.null(since)) {
url <- paste0(url, '&since=', since)
}
if(n<=25) {
url <- paste0(url, "&limit=", n)
}
content <- callAPI(url=url, token=token)
l <- length(content$data); cat(l, "posts")
error <- 0
while(length(content$error_code)>0) {
cat("Error!\n")
Sys.sleep(0.5)
error <- error + 1
content <- callAPI(url=url, token=token)
if(error==3) {
stop(content$error_msg) }
}
if(length(content$data)==0) {
message("No public posts were found")
return(data.frame())
}
df <- pageDataToDF(content$data)
if(!is.null(since)) {
dates <- formatFbDate(df$created_time, 'date')
mindate <- min(dates)
sincedate <- as.Date(since)
}
if(is.null(since)) {
sincedate <- as.Date('1970/01/01')
mindate <- as.Date(Sys.time())
}
if(n > 25) {
df.list <- list(df)
while(l < n & length(content$data) > 0) & !is.null(content$paging$`next`) & sincedate <= mindate) {
Sys.sleep(0.5)
url <- content$paging$`next`
content <- callAPI(url=url, token=token)
l <- l + length(content$data)
if(length(content$data) > 0) { cat(l, "posts") }
error <- 0
while(length(content$error_code) > 0) {
cat("Error!\n")
Sys.sleep(0.5)
error <- error + 1
content <- callAPI(url=url, token=token)
if(error==3) { stop(content$error_msg) }
}
new.df <- pageDataToDF(content$data)
df.list <- c(df.list, list(new.df))
if(!is.null(since) & nrow(new.df) > 0) {
dates <- formatFbDate(new.df$created_time, 'date')
mindate <- min(dates)
}
df <- do.call(rbind, df.list)
}
if(nrow(df) > n) {
df <- df[1:n,]
}
if(!is.null(since)) {
dates <- formatFbDate(df$created_time, 'date')
df <- df[dates>=sincedate,]
}
if(reactions == TRUE) {
re = getReactions(df$id, token=token, verbose=FALSE)
df <- merge(df, re, all.x=TRUE)
df <- df[order(df$created_time),]
}
return (df)
format.facebook.date <- function(datestring) {
date <- as.POSIXct(datestring, format = "%Y-%m-%dT%H:%M:%S+0000", tz = "GMT")
}
aggregate.metric <- function(metric) {
m <- aggregate(page[[paste0(metric, "_count")]], list(month = page$month), mean)
m$month <- as.Date(paste0(m$month, "-15"))
m$metric <- metric
return(m)
}
page$datetime <- format.facebook.date(page$created_time)
page$month <- format(page$datetime, "%Y-%m")
df.list <- lapply(c("likes", "comments", "shares"), aggregate.metric)
df <- do.call(rbind, df.list)
library(ggplot2)
library(scales)
ggplot(df, aes(x = month, y = x, group = metric)) + geom_line(aes(color = metric)) +
scale_x_date(breaks = "years", labels = date_format("%Y")) + scale_y_log10("Average count per post",
breaks = c(10, 100, 1000, 10000, 50000)) + theme_bw() + theme(axis.title.x = element_blank())
page <- getPage("DonaldTrump", token, n = 5000, since='2015/01/01', until='2015/12/31')
post_id <- head(page$id, n = 1)
post <- getPost(post_id, token, n = 1000, likes = TRUE, comments = FALSE)
}
<file_sep>/Tweet Count.R
library(twiitteR)
library(ROAuth)
library(ggplot2)
ARG.list <- searchTwitter('#BRA #FIFA', n=1000, cainfo="cacert.pem")
BRA.df = twListToDF(BRA.list)
GER.list <- searchTwiiter('#GER #FIFA', n=1000, cainfo="cacert.pem")
GER.df = twListtoDF(GER.list)
NED.list <- searchTwiiter('#NED #FIFA', n=1000, cainfo="cacert.pem")
NED.df = twListToDF(NED.list)
score.sentiment = function(sentences, pos.words, neg.words,.progress='none')
{
require(plyr)
require(stringr)
good.smiley <- c(":)")
bad.smiley <- c(":(", ";)", ":'", ":P")
scores = laply(sentences, function(sentence, pos.words, neg.words) {
sentence = gsub(":)", 'asum', sentence)
sentence = gsub('[[:punct:]]', '', sentence)
sentence = gsub('[[:cntrl;]]', '', sentence)
sentence = gsub('\\d+', '', sentence)
sentence = toLower(sentence)
word.list = str_split(sentence, '\\s+')
words = unlist(word.list)
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
score = sum(pos.matches) - sum(neg.matches)
return(score)
}, pos.words, neg.words, .progress=.progress)
scores.df = data.frame(score=scores, text=sentences)
return(scores.df)
}
hu.liu.pos = scan('C:/temp/positive-words.txt', what='character', comment.char=';')
hu.liu.neg = scan('C:/temp/negative-words.txt', what='character', comment.char=';')
pos.words = c(hu.liu.pos, 'upgrade', 'awsum')
neg.words = c(hu.liu.neg, 'wtf', 'wait', 'waiting', 'epicfail', 'mechanical', "suspension", "no")
team = c("vs.", "vs", "versus")
ARG.df$text<-as.factor(ARG.df$text)
BRA.df$text<-as.factor(BRA.df$text)
NED.df$text<-as.factor(NED.df$text)
GER.df$text<-as.factor(GER.df$text)
ARG.scores = score.sentiment(ARG.df$text,pos.words,neg.words,.progress='text')
BRA.scores = score.sentiment(BRA.df$text, pos.words, neg.words, progress='text')
NED.scores = score.sentiment(NED.df$text,pos.words, neg.words, .progress='text')
GER.scores = score.sentiment(GER.df$text, pos.words, neg.words, .progress='text')
ARG.scores$Team = 'Argentina'
BRA.scores$Team = 'Brazil'
NED.scores$Team = 'Netherland'
GER.scores$Team = 'Germany'
ARG.scores.2 = subset(ARG.scores, ARG.scores$score < 0)
head(ARG.scores.2)
hist(ARG.score$score)
hist(BRA.score$score)
hist(NED.score$sscore)
hist(GER.score$score)
table(ARG.scores$score)
table(BRA.scores$score)
table(NED.scores$score)
table(GER.scores$score)
head(all.scores)
all.scores = rbind(ARG.scores, NED.scores, GER.scores, BRA.scores)
table(all.scores$score, all.scores$Team)
ggplot(data=all.scores) + geom_bar(mapping=aes(x=score, fill=Team), binwidth=1) + facet_grid(Team~.) + theme.bw() + scale_fill_brewer()
<file_sep>/README.md
# Hello-World
The following are some of the projects that I worked on during Hello World, a freshman-only hackathon at Purdue University.
|
6e08f6bb39dc0a897188c36e0bce774df8048808
|
[
"Markdown",
"R"
] | 3 |
R
|
RohanGupta24/Hello-World
|
708f81a613d2267ec2e15a68da9d8f1b124f1ec9
|
acebaea01396d57fdb315de00e0d8984619a15aa
|
refs/heads/master
|
<repo_name>yuyang0/ryu<file_sep>/ryu/lib/process.py
import sys
import os
import logging
import errno
import multiprocessing
LOG = logging.getLogger('ryu.lib.hub')
def setproctitle(x):
try:
from setproctitle import setproctitle as _setproctitle
_setproctitle(x)
except ImportError:
pass
def get_errno(exc):
""" Get the error code out of socket.error objects.
socket.error in <2.5 does not have errno attribute
socket.error in 3.x does not allow indexing access
e.args[0] works for all.
There are cases when args[0] is not errno.
i.e. http://bugs.python.org/issue6471
Maybe there are cases when errno is set, but it is not the first argument?
"""
try:
if exc.errno is not None:
return exc.errno
except AttributeError:
pass
try:
return exc.args[0]
except IndexError:
return None
def cpu_count():
"""Returns the number of processors on this machine."""
if multiprocessing is None:
return 1
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except (AttributeError, ValueError):
pass
LOG.error("Could not detect number of processors; assuming 1")
return 1
_task_id = None
def fork_processes(num_processes, max_restarts=100):
"""Starts multiple worker processes.
If ``num_processes`` is None or <= 0, we detect the number of cores
available on this machine and fork that number of child
processes. If ``num_processes`` is given and > 0, we fork that
specific number of sub-processes.
Since we use processes and not threads, there is no shared memory
between any server code.
Note that multiple processes are not compatible with the autoreload
module (or the ``autoreload=True`` option to `tornado.web.Application`
which defaults to True when ``debug=True``).
When using multiple processes, no IOLoops can be created or
referenced until after the call to ``fork_processes``.
In each child process, ``fork_processes`` returns its *task id*, a
number between 0 and ``num_processes``. Processes that exit
abnormally (due to a signal or non-zero exit status) are restarted
with the same id (up to ``max_restarts`` times). In the parent
process, ``fork_processes`` returns None if all child processes
have exited normally, but will otherwise only exit by throwing an
exception.
"""
global _task_id
assert _task_id is None
if num_processes is None or num_processes <= 0:
num_processes = cpu_count()
LOG.info("Starting %d processes", num_processes)
children = {}
def start_child(i):
pid = os.fork()
if pid == 0:
# child process
setproctitle("ryu worker")
# _reseed_random()
global _task_id
_task_id = i
return i
else:
children[pid] = i
return None
for i in range(num_processes):
id = start_child(i)
if id is not None:
return id
num_restarts = 0
while children:
try:
pid, status = os.wait()
except OSError as e:
if get_errno(e) == errno.EINTR:
continue
raise
if pid not in children:
continue
id = children.pop(pid)
if os.WIFSIGNALED(status):
LOG.warning("child %d (pid %d) killed by signal %d, restarting",
id, pid, os.WTERMSIG(status))
elif os.WEXITSTATUS(status) != 0:
LOG.warning("child %d (pid %d) exited with status %d, restarting",
id, pid, os.WEXITSTATUS(status))
else:
LOG.info("child %d (pid %d) exited normally", id, pid)
continue
num_restarts += 1
if num_restarts > max_restarts:
raise RuntimeError("Too many child restarts, giving up")
new_id = start_child(id)
if new_id is not None:
return new_id
# All child processes exited cleanly, so exit the master process
# instead of just returning to right after the call to
# fork_processes (which will probably just start up another IOLoop
# unless the caller checks the return value).
sys.exit(0)
|
0d53b7d02cdef189415bd9697d604bd413854bee
|
[
"Python"
] | 1 |
Python
|
yuyang0/ryu
|
af2746fa040b0e7ede2713f8e44cb5a5b8de39c2
|
7e6551cc64b8b88f16e30fd79ad162de053407c5
|
refs/heads/master
|
<repo_name>BugfreeGames/Roboticon-Colony<file_sep>/Assets/Code/Classes/Game Manager/RandomEvent.cs
// Game Executable hosted at: http://www-users.york.ac.uk/~jwa509/alpha01BugFree.exe
using UnityEngine;
using System.Collections;
public class RandomEvent
{
private GameObject eventGameObject;
private string eventTitle;
private string eventDescription;
public bool isNullEvent = false;
public RandomEvent(RandomEventStore randomEventStore)
{
eventGameObject = new RandomEventFactory().Create(randomEventStore);
if (eventGameObject != null)
{
EventInfo eventInfo = eventGameObject.GetComponent<EventInfo>();
eventTitle = eventInfo.title;
eventDescription = eventInfo.description;
}
else
{
isNullEvent = true;
}
}
public void Instantiate()
{
if(isNullEvent)
{
return;
}
GameObject.Instantiate(eventGameObject, Vector3.zero, Quaternion.identity);
}
public string getTitle()
{
if (isNullEvent)
{
return "NULL_EVENT";
}
return eventTitle;
}
public string getDescription()
{
if (isNullEvent)
{
return "NULL_EVENT";
}
return eventDescription;
}
}<file_sep>/Assets/Code/Classes/Game Manager/RandomEventEffect.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Represents a non-permanent effect on the resources produced by a tile.
/// </summary>
public class RandomEventEffect
{
private ResourceGroup resourceEffects;
private int turnsRemaining;
private GameObject perpetualVisualEffect; //Optional effect to play while this RandomEventEffect is active.
private GameObject visualEffectInWorld;
public RandomEventEffect(ResourceGroup effect, int turns)
{
resourceEffects = effect;
turnsRemaining = turns;
}
public bool IsFinished()
{
return turnsRemaining == 0;
}
public ResourceGroup GetEffects()
{
return resourceEffects;
}
public void SetVisualEffect(GameObject effect)
{
perpetualVisualEffect = effect;
}
public void InstantiateVisualEffect(Vector3 position)
{
if(perpetualVisualEffect != null)
{
visualEffectInWorld = (GameObject)GameObject.Instantiate(perpetualVisualEffect, position, Quaternion.identity);
visualEffectInWorld.name = Random.Range(1, 1000).ToString();
}
}
public void EndEffect()
{
if(visualEffectInWorld != null)
{
MonoBehaviour.Destroy(visualEffectInWorld);
}
}
public void Tick()
{
turnsRemaining--;
if(IsFinished())
{
EndEffect();
}
}
/// <summary>
/// Returns a copy of this RandomEventEffect
/// </summary>
/// <returns></returns>
public RandomEventEffect Copy()
{
RandomEventEffect copy = new RandomEventEffect(resourceEffects, turnsRemaining);
copy.SetVisualEffect(perpetualVisualEffect);
return copy;
}
}
<file_sep>/Assets/Code/Classes/TagManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TagManager
{
public static string mapTile = "mapTile";
}
<file_sep>/Assets/Resources/Prefabs/Random Events/Meteor/Assets/meteorScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class meteorScript : MonoBehaviour
{
public float detectRadius = 2.4f;
public float blastRadius = 5;
public GameObject explosionGameObject;
public GameObject meteorDestroyedGameObject;
public GameObject meteorModelGameObject;
private ResourceGroup eventEffect = new ResourceGroup(-50,-50,3);
// Use this for initialization
void Start ()
{
GetComponent<Rigidbody>().AddForce(Random.Range(-500, 500), 0, Random.Range(-500, 500));
}
// Update is called once per frame
void Update ()
{
Collider[] detectedColliders = Physics.OverlapSphere(transform.position, detectRadius);
if (detectedColliders.Length > 0) //Detected colliders within detect radius. Meteor explodes.
{
bool onlyHitSelf = true;
foreach(Collider collider in detectedColliders)
{
if(collider.gameObject != gameObject)
{
onlyHitSelf = false;
}
}
if(onlyHitSelf)
{
return;
}
Collider[] damagedTiles = Physics.OverlapSphere(transform.position, blastRadius);
foreach(Collider collider in damagedTiles)
{
if(collider.tag == TagManager.mapTile)
{
Tile hitTile = GameHandler.GetGameManager().GetMap().GetTile(collider.GetComponent<mapTileScript>().GetTileId());
hitTile.ApplyEventEffect(new RandomEventEffect(eventEffect, 0));
}
}
Destroy(meteorModelGameObject);
GameObject.Instantiate(explosionGameObject, transform.position, Quaternion.identity);
GameObject.Instantiate(meteorDestroyedGameObject, transform.position, Quaternion.identity);
Destroy(this.GetComponent<SphereCollider>());
Destroy(this.GetComponent<Rigidbody>());
transform.Translate(0, -2, 0);
Destroy(this);
}
}
}
<file_sep>/Assets/Resources/Prefabs/Random Events/Godzilla/Assets/godzillaScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class godzillaScript : MonoBehaviour
{
public GameObject hitEffect;
public List<BoxCollider> damagePointColliders = new List<BoxCollider>();
public float defaultWalkSpeed = 1;
public float walkStopFalloff = 1;
private float walkSpeed;
private static string TRIGGER_BREAK_THINGS = "breakThings";
private static string TRIGGER_WALK = "startWalking";
private bool breakingThings = false;
// Use this for initialization
void Start ()
{
foreach (BoxCollider collider in damagePointColliders)
{
damagePointScript damagePointScript = collider.gameObject.AddComponent<damagePointScript>();
damagePointScript.SetResourceEffects(new RandomEventEffect(new ResourceGroup(-1, -1, -1), 3));
damagePointScript.SetHitEffect(hitEffect);
}
walkSpeed = defaultWalkSpeed;
StartCoroutine(DelayBreakThings());
}
// Update is called once per frame
void Update ()
{
if (breakingThings)
{
walkSpeed -= Time.deltaTime * walkStopFalloff;
if(walkSpeed < 0)
{
walkSpeed = 0;
breakingThings = false;
}
}
transform.Translate(new Vector3(0, 0, -walkSpeed * Time.deltaTime), Space.Self);
}
private IEnumerator DelayBreakThings()
{
yield return new WaitForSeconds(Random.Range(3, 5) * 3.25f);
breakingThings = true;
GetComponent<Animator>().SetTrigger(TRIGGER_BREAK_THINGS);
GetComponent<AudioSource>().PlayDelayed(3.2f);
StartCoroutine(WalkAway());
}
private IEnumerator WalkAway()
{
yield return new WaitForSeconds(10);
GetComponent<Animator>().SetTrigger(TRIGGER_WALK);
yield return new WaitForSeconds(12.3f);
walkSpeed = defaultWalkSpeed;
yield return new WaitForSeconds(20);
Destroy(transform.parent.gameObject);
}
}
<file_sep>/Assets/Code/Scripts/GUI/mainMenuScript.cs
//Game executable hosted by JBT at: http://robins.tech/jbt/documents/assthree/GameExecutable.zip
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
//Made by JBT
/// <summary>
/// Handles UI interaction for the Main Menu scene
/// </summary>
public class mainMenuScript : MonoBehaviour
{
public Toggle player2aiToggle;
public Toggle player3aiToggle;
public Toggle player4aiToggle;
public InputField player1Name;
public InputField player2Name;
public InputField player3Name;
public InputField player4Name;
private List<setupPlayer> setupPlayers;
public GameObject eventSystem;
public const int GAME_SCENE_INDEX = 1;
public string gameName = "game";
public GameObject addPlayerButton;
public GameObject removePlayerButton;
private int numPlayersShown = 2;
private struct setupPlayer
{
InputField nameField;
Toggle isAi;
int playerNum; //Used to set the default name
public setupPlayer(InputField field, Toggle toggle, int playerNum)
{
nameField = field;
isAi = toggle;
this.playerNum = playerNum;
}
public bool isAI()
{
if(isAi == null)
{
return false;
}
return isAi.isOn;
}
public string getName()
{
return nameField.text;
}
public void setNameToDefaultIfNoNameSet()
{
if(nameField.text == "" || nameField.text == null)
{
nameField.text = "Player" + playerNum.ToString();
}
}
public bool isDisabled()
{
return !nameField.IsActive();
}
public Color getColor()
{
switch(playerNum)
{
case 1:
return new Color(1, 0, 0);
case 2:
return new Color(0, 1, 1);
case 3:
return new Color(0, 0, 1);
case 4:
return new Color(1, 0, 1);
default:
throw new System.ArgumentException("SetupPlayer has no assigned player number. Player number is necessary for generating default name and color.");
}
}
public void Show()
{
nameField.transform.parent.gameObject.SetActive(true);
}
public void Hide()
{
nameField.transform.parent.gameObject.SetActive(false);
}
}
public void Start()
{
//If a player is quitting to the menu from the game itself, or the end of game screen, then remove the GUI canvas that was not destroyed on load
if (GameObject.Find("Player GUI Canvas(Clone)") != null)
{
Destroy(GameObject.Find("Player GUI Canvas(Clone)"));
}
setupPlayers = new List<setupPlayer>();
setupPlayer player1 = new setupPlayer(player1Name, null, 1);
setupPlayer player2 = new setupPlayer(player2Name, player2aiToggle, 2);
setupPlayer player3 = new setupPlayer(player3Name, player3aiToggle, 3);
setupPlayer player4 = new setupPlayer(player4Name, player4aiToggle, 4);
setupPlayers.Add(player1);
setupPlayers.Add(player2);
setupPlayers.Add(player3);
setupPlayers.Add(player4);
}
/// <summary>
/// Starts the game by creating a new gamehandler
/// </summary>
public void StartGame()
{
List<Player> players = new List<Player>();
foreach (setupPlayer player in setupPlayers)
{
//If no player name entered, set default player names
player.setNameToDefaultIfNoNameSet();
//If the current player is disabled, don't add it to the players list and break as all future players must also be disabled.
if(player.isDisabled())
{
break;
}
//If AI Is on, then add an AI player, else add a human player
if (player.isAI())
{
AI ai = new AI(new ResourceGroup(10, 10, 10), player.getName(), 500);
ai.SetTileColor(player.getColor());
players.Add(ai);
}
else
{
Human human = new Human(new ResourceGroup(10, 10, 10), player.getName(), 500);
human.SetTileColor(player.getColor());
players.Add(human);
}
}
Destroy(eventSystem);
GameHandler.CreateNew(gameName, players);
GameHandler.GetGameManager().StartGame();
SceneManager.LoadScene(GAME_SCENE_INDEX); //LoadScene is asynchronous
}
public void AddPlayerClicked()
{
setupPlayers[numPlayersShown].Show();
numPlayersShown++;
addPlayerButton.transform.Translate(0, -30, 0);
removePlayerButton.transform.Translate(0, -30, 0);
removePlayerButton.SetActive(true);
if (numPlayersShown == 4)
{
addPlayerButton.SetActive(false);
}
}
public void RemovePlayerClicked()
{
numPlayersShown--;
setupPlayers[numPlayersShown].Hide();
addPlayerButton.transform.Translate(0, 30, 0);
removePlayerButton.transform.Translate(0, 30, 0);
addPlayerButton.SetActive(true);
if (numPlayersShown == 2)
{
removePlayerButton.SetActive(false);
}
}
/// <summary>
/// Quits the game
/// </summary>
public void QuitGame()
{
Application.Quit();
}
}<file_sep>/Assets/Code/Scripts/damagePointScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class damagePointScript : MonoBehaviour
{
RandomEventEffect tileEffect;
Collider damagePointCollider;
GameObject hitEffect;
float delayBetweenHits = 0.8f;
float hitStartDelay = 0;
bool readyToHit = true;
bool oneShotEffect = false;
bool doActivateRigidbody = false;
float rigidbodyTimeout = 5;
// Use this for initialization
void Start ()
{
damagePointCollider = GetComponent<Collider>();
if(damagePointCollider == null)
{
throw new System.Exception("Damage Point Script attached to GameObject with no collider. This script needs a collider to work properly.");
}
if(hitStartDelay > 0)
{
StartCoroutine(SetColliderActiveAfterDelay());
damagePointCollider.enabled = false;
}
}
// Update is called once per frame
void Update ()
{
}
/// <summary>
/// This is the effect that will be added to each tile within the hit collider at every hit.
/// </summary>
/// <param name="effect"></param>
public void SetResourceEffects(RandomEventEffect effect)
{
tileEffect = effect;
}
/// <summary>
/// This GameObject will be instantiated every time a hit is incurred
/// </summary>
/// <param name="effect"></param>
public void SetHitEffect(GameObject effect)
{
hitEffect = effect;
}
/// <summary>
/// Sets the minimum time delay between two successive hits.
/// </summary>
/// <param name="delay"></param>
public void SetHitDelay(float delay)
{
delayBetweenHits = delay;
}
/// <summary>
/// Sets the time after instantiation to wait before activating the damage point collider.
/// </summary>
/// <param name="delay"></param>
public void SetHitStartDelay(float delay)
{
hitStartDelay = delay;
}
/// <summary>
/// Set to true to have the hitEffect only ever go off one time, although damage may be incurred multiple times.
/// </summary>
public void SetOneShotEffect(bool isOneShot)
{
oneShotEffect = isOneShot;
}
/// <summary>
/// Set to true to enable a rigidbody on the collider object for rigidbodyTimeout seconds.
/// </summary>
/// <param name="doActivateRigidbody"></param>
public void SetDoActivateRigidbody(bool doActivateRigidbody)
{
this.doActivateRigidbody = doActivateRigidbody;
}
/// <summary>
/// Used when DoActivateRigidbody is set to true. Enables a rigidbody for timeout seconds
/// </summary>
/// <param name="timeout"></param>
public void SetRigidbodyTimeout(float timeout)
{
rigidbodyTimeout = timeout;
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == TagManager.mapTile && readyToHit)
{
Tile hitTile = GameHandler.GetGameManager().GetMap().GetTile(other.gameObject.GetComponent<mapTileScript>().GetTileId());
hitTile.ApplyEventEffect(tileEffect.Copy());
if(hitEffect != null)
{
GameObject.Instantiate(hitEffect, transform.position, Quaternion.identity);
}
if (oneShotEffect)
{
hitEffect = null;
}
if (delayBetweenHits > 0)
{
readyToHit = false;
StartCoroutine(DelayNextHit());
}
}
}
private void OnTriggerExit(Collider other)
{
}
private IEnumerator DelayNextHit()
{
yield return new WaitForSeconds(delayBetweenHits);
readyToHit = true;
}
private IEnumerator SetColliderActiveAfterDelay()
{
yield return new WaitForSeconds(hitStartDelay);
damagePointCollider.enabled = true;
if(doActivateRigidbody)
{
damagePointCollider.gameObject.AddComponent<Rigidbody>();
StartCoroutine(RigidbodyTimeout());
}
}
private IEnumerator RigidbodyTimeout()
{
yield return new WaitForSeconds(rigidbodyTimeout);
Destroy(damagePointCollider.gameObject.GetComponent<Rigidbody>());
}
}
<file_sep>/Assets/Code/Classes/Game Manager/EventInfo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Holder for information about the random event, such as title and description. This is needed on
/// the random event GameObject in order for your random event to be included in the game.
/// </summary>
public class EventInfo : MonoBehaviour
{
public string title;
public string description;
}
<file_sep>/README.md
# Bugfree Software - Roboticon Colony
SEPR Assessment 4 <br />
www-users.york.ac.uk/~jwa509/index.html
<file_sep>/Assets/Code/Classes/Game Manager/RandomEventStore.cs
// Game Executable hosted at: http://www-users.york.ac.uk/~jwa509/alpha01BugFree.exe
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomEventStore
{
private static string randomEventGameObjectsPath = "Prefabs/Random Events/Event GameObjects"; //Assumes all assets in this folder are GameObjects.
public List<GameObject> randomEvents = new List<GameObject>();
int numEvents;
public RandomEventStore()
{
System.Object[] loadedObjects = Resources.LoadAll(randomEventGameObjectsPath);
for(int i = 0; i < loadedObjects.Length; i ++)
{
randomEvents.Add((GameObject)loadedObjects[i]);
}
numEvents = randomEvents.Count;
foreach (GameObject randomEvent in randomEvents)
{
if(randomEvent.GetComponent<EventInfo>() == null)
{
throw new System.NullReferenceException("No EventInfo script found on random event GameObject. Add EventInfo to provide an event title and description.");
}
}
}
public GameObject chooseEvent()
{
if (numEvents == 0)
{
Debug.LogWarning("No random events to instantiate.");
return null;
}
return this.randomEvents[UnityEngine.Random.Range(0, numEvents)]; // Choose a random event from the randomEvents list
}
}
<file_sep>/Assets/Resources/Prefabs/Random Events/Godzilla/Assets/spawnGodzillaScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnGodzillaScript : MonoBehaviour
{
public GameObject godzillaGameObject;
public float spawnRadiusFromOrigin;
// Use this for initialization
void Start ()
{
float theta = Random.Range(0, 360.0f);
Vector3 spawnPos = new Vector3(spawnRadiusFromOrigin * Mathf.Cos(theta), 0, spawnRadiusFromOrigin * Mathf.Sin(theta));
GameObject.Instantiate(godzillaGameObject, spawnPos, Quaternion.LookRotation(spawnPos), transform);
}
// Update is called once per frame
void Update ()
{
}
}
<file_sep>/Assets/Code/Scripts/playAudioAfterDelay.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playAudioAfterDelay : MonoBehaviour
{
public float delay = 1;
// Use this for initialization
void Start ()
{
try
{
GetComponent<AudioSource>().PlayDelayed(delay);
}
catch (System.NullReferenceException)
{
throw new System.NullReferenceException("No AudioSource attached to playAudioAfterDelay script.");
}
}
// Update is called once per frame
void Update ()
{
}
}
<file_sep>/Assets/Code/Classes/Game Manager/RandomEventFactory.cs
// Game Executable hosted at: http://www-users.york.ac.uk/~jwa509/alpha01BugFree.exe
using UnityEngine;
using System.Collections;
using System;
public class RandomEventFactory
{
public GameObject Create(RandomEventStore randomEventStore)
{
if (UnityEngine.Random.Range(0, 2) == 0) //TODO correct percentage chance of event occuring - 50% currently
{
return randomEventStore.chooseEvent();
}
else
{
return null; // Return null indicating no event should take place
}
}
}<file_sep>/Assets/Resources/Prefabs/Random Events/Dragon/Assets/dragonScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dragonScript : MonoBehaviour
{
public BoxCollider fireHitRegion;
public BoxCollider landingHitRegion;
public GameObject landingHitEffect;
public GameObject fireAfterGlowEffect;
public float fireStartTime = 11.2f; //Time after animation start when the fire particles begin. Match with delay in particle systems.
// Use this for initialization
void Start()
{
transform.parent.Rotate(0, Random.Range(0, 360), 0);
damagePointScript fireHitDamagePointScript = fireHitRegion.gameObject.AddComponent<damagePointScript>();
RandomEventEffect fireDamageEffect = new RandomEventEffect(new ResourceGroup(-1, -1, -1), 1);
fireDamageEffect.SetVisualEffect(fireAfterGlowEffect);
fireHitDamagePointScript.SetResourceEffects(fireDamageEffect);
fireHitDamagePointScript.SetHitStartDelay(fireStartTime);
fireHitDamagePointScript.SetHitDelay(0);
fireHitDamagePointScript.SetDoActivateRigidbody(true);
damagePointScript landingDamagePointScript = landingHitRegion.gameObject.AddComponent<damagePointScript>();
landingDamagePointScript.SetResourceEffects(new RandomEventEffect(new ResourceGroup(-3, -3, -3), 2));
landingDamagePointScript.SetHitEffect(landingHitEffect);
landingDamagePointScript.SetHitDelay(0);
landingDamagePointScript.SetOneShotEffect(true);
landingDamagePointScript.SetHitStartDelay(Time.deltaTime * 2); //Animation takes 2 frames to start
fireHitRegion.enabled = false;
landingHitRegion.enabled = false;
Destroy(transform.parent.gameObject, 30);
}
}
|
26a53cb86bf2d43774cd5fbbc65a41cab99d7824
|
[
"Markdown",
"C#"
] | 14 |
C#
|
BugfreeGames/Roboticon-Colony
|
8cd16ed2b910585e02e9712e87e3be161162fe06
|
6ada38dcd95c3ac840021de85ecf8bff4dc75fc0
|
refs/heads/master
|
<repo_name>humanaseem/next-express-commerce-app<file_sep>/components/Slider/MySlider.styles.jsx
const MySliderStyles = () => (
<style jsx global>{`
.center {
text-align: center;
margin-top: 100px;
}
.slider {
position: relative;
width: 100%;
height: 90vh;
overflow: hidden;
}
.slider a.previousButton,
.slider a.nextButton {
font-size: 22px;
line-height: 0;
display: block;
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
-webkit-transition: all 0.3s linear;
transition: all 0.3s linear;
z-index: 1;
color: #333;
padding: 10px;
text-decoration: none;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
/* prevent jump effect when scaling */
}
.slider a.previousButton:not(.disabled):hover,
.slider a.nextButton:not(.disabled):hover {
-webkit-transform: translateY(-50%) scale(1.25);
transform: translateY(-50%) scale(1.25);
cursor: pointer;
}
.slider a.previousButton {
left: 20px;
}
.slider a.nextButton {
right: 20px;
}
.slide {
width: 100%;
height: 100%;
position: absolute;
overflow: hidden;
}
.slide.hidden {
visibility: hidden;
}
.slide.previous {
left: -100%;
}
.slide.current {
left: 0;
}
.slide.next {
left: 100%;
}
.slide.animateIn,
.slide.animateOut {
-webkit-transition: all 2s ease;
transition: all 2s ease;
}
.slide.animateIn.previous,
.slide.animateIn.next {
left: 0;
visibility: visible;
}
.slide.animateOut.previous {
left: 100%;
}
.slide.animateOut.next {
left: -100%;
}
.slide h1 {
transition: all 0.3s ease;
-webkit-transform: translateY(-20px);
transform: translateY(-20px);
opacity: 0;
}
.slide button {
transition: all 0.3s ease;
-webkit-transform: translateY(20px);
transform: translateY(20px);
opacity: 0;
}
.slide p {
transition: all 0.3s ease;
-webkit-transform: translateY(20px);
transform: translateY(20px);
opacity: 0;
}
.slide section * {
transition: all 0.3s ease;
}
.slide section img {
-webkit-transform: translateX(-10px);
transform: translateX(-10px);
opacity: 0;
}
.slide section span {
-webkit-transform: translateY(-10px);
transform: translateY(-10px);
opacity: 0;
}
.slide section span strong {
-webkit-transform: translateY(10px);
transform: translateY(10px);
opacity: 0;
}
.slide.animateIn.previous h1,
.slide.current h1,
.slide.animateIn.next h1,
.slide.animateIn.previous button,
.slide.current button,
.slide.animateIn.next button,
.slide.animateIn.previous p,
.slide.current p,
.slide.animateIn.next p,
.slide.animateIn.previous section *,
.slide.current section *,
.slide.animateIn.next section * {
-webkit-transform: translateX(0);
transform: translateX(0);
-webkit-transition-delay: 0.9s;
transition-delay: 0.9s;
opacity: 1;
}
.slide.animateIn.previous p,
.slide.animateIn.next p {
-webkit-transition-delay: 1.1s;
transition-delay: 1.1s;
}
.slide.animateIn.previous button,
.slide.animateIn.next button {
-webkit-transition-delay: 1.3s;
transition-delay: 1.3s;
}
.slide.animateIn.previous section img,
.slide.animateIn.next section img {
-webkit-transition-delay: 1.3s;
transition-delay: 1.3s;
}
.slide.animateIn.previous section span,
.slide.animateIn.next section span {
-webkit-transition-delay: 1.4s;
transition-delay: 1.4s;
}
.slide.animateIn.previous section span strong,
.slide.animateIn.next section span strong {
-webkit-transition-delay: 1.5s;
transition-delay: 1.5s;
}
.slide.animateOut h1 {
-webkit-transition-delay: 0.3s;
transition-delay: 0.3s;
}
.slide.animateOut p {
-webkit-transition-delay: 0.2s;
transition-delay: 0.2s;
}
.slide.animateOut section span {
-webkit-transition-delay: 0.1s;
transition-delay: 0.1s;
}
.slide.animateOut section span strong {
-webkit-transition-delay: 0s;
transition-delay: 0s;
}
`}</style>
);
export default MySliderStyles;
<file_sep>/components/admin/bill/EditBill.js
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import {
Paper,
Table,
TableRow,
TableCell,
TableBody,
Select,
MenuItem,
Button,
CircularProgress
} from '@material-ui/core';
import { editBill, getBillsWithRedux } from '../../../store/action/billAction';
import { connect } from 'react-redux';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
import Link from 'next/link';
import { EditBillStyles } from './bill.styles.jss';
const styles = EditBillStyles;
class EditBill extends Component {
state = {
_id: '',
authId: '',
totalPrice: '',
status: '',
details: '',
onLoading: '',
message: '',
open: false,
bill: {}
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
validated__input = (stateValue, regex, inputName, setError) => {
const value = stateValue;
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input) {
return false;
}
if (!regex.exec(value)) {
input.focus();
input.click();
return false;
}
if (regex.exec(value)[0] !== regex.exec(value).input) {
input.focus();
return false;
}
if (setError) this.setState({ err: { [setError.key]: false } });
return true;
};
valudated__form = () => {
if (!this.validated__input(this.state.bill_name, /[\w\s-]{1,}/, 'status')) {
return false;
}
return true;
};
// submit edit
handleSubmit = async e => {
e.preventDefault();
if (!this.valudated__form()) {
return;
}
this.setState({ onLoading: true });
await this.props.editBill(this.state);
if (!this.props.editError) {
this.setState({
onLoading: false,
open: true,
message: `Edit ${this.state._id} success`
});
} else {
alert('Permission Denied!');
window.location = '/admin';
}
};
async componentDidMount() {
await this.props.getBillsWithRedux();
if (this.props.haveBill) {
const b = this.props.bill;
let details = [];
for (let i = 0; i < b.details.proId.length; i++) {
const obj = {
proId: b.details.proId[i],
proPrice: b.details.proPrice[i],
proQuantity: b.details.proQuantity[i]
};
details.push(obj);
}
this.setState({
_id: b._id,
createAt: b.createAt,
authId: b.authId,
totalPrice: b.totalPrice,
status: b.status,
details: details
});
}
}
render() {
const { classes } = this.props;
if (!this.state.details) {
return (
<div className="admin-content fadeIn">
<div className="loading-text">Loading...</div>
</div>
);
}
const rows = this.state.details;
return (
<div className="admin-content fadeIn">
<h2 className={classes.formTitle}>
Edit Bill
<Link href="/admin/bill">
<a style={{ marginLeft: 200 }}>
<Button variant="contained" color="default">
Back
</Button>
</a>
</Link>
</h2>
{this.props.haveBill ? (
<Paper>
<Table>
<TableBody>
<TableRow>
<TableCell>
<b>Bill Id : </b> {this.state._id}
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<b>Create At : </b> {this.state.createAt}
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<b>User Id : </b> {this.state.authId}
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<b>Total Price : </b> {this.state.totalPrice}
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<b>Status : </b>
<form
onSubmit={this.handleSubmit}
id="formEditBill"
style={{ display: 'inline' }}
>
<Select
value={this.state.status}
onChange={this.handleChange}
name="status"
>
<MenuItem value="paid">Paid</MenuItem>
<MenuItem value="unpaid">Unpaid</MenuItem>
</Select>
{this.state.onLoading ? (
<Button>
<CircularProgress
size={20}
className={classes.bgWhite}
/>
</Button>
) : (
<Button
type="submit"
form="formEditBill"
variant="contained"
color="primary"
size="small"
style={{ marginLeft: '10px' }}
>
Update
</Button>
)}
</form>
{this.props.editError && (
<h4 style={{ color: 'red' }}>{this.props.editError}</h4>
)}
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<h2 style={{ color: 'gray' }}>Details</h2>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Table>
<TableBody>
<TableRow>
<TableCell align="center">Product Id</TableCell>
<TableCell align="center">Quantity</TableCell>
<TableCell align="center">
Product Price ($)
</TableCell>
</TableRow>
{rows.map((item, index) => (
<TableRow key={index}>
<TableCell align="center">{item.proId}</TableCell>
<TableCell align="center">
{item.proQuantity}
</TableCell>
<TableCell align="center">
{item.proPrice}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableCell>
</TableRow>
</TableBody>
</Table>
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</Paper>
) : (
<h1>Not have this bill.</h1>
)}
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
const { id } = ownProps;
const bills = state.bill.bills;
let bill = null;
let haveBill = false;
if (bills) {
if (bills.data) {
bill = bills.data.find(b => b._id === id);
if (bill) {
haveBill = true;
}
}
}
return {
bill: bill,
haveBill,
editError: state.bill.editError
};
};
const mapDispatchToProps = dispatch => {
return {
editBill: bill => dispatch(editBill(bill)),
getBillsWithRedux: () => dispatch(getBillsWithRedux())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(EditBill)
);
<file_sep>/components/Navbar/SearchBar.jsx
import React, { Component } from 'react';
import { InputBase } from '@material-ui/core';
import { Search } from '@material-ui/icons';
import Router from 'next/router';
export class SearchBar extends Component {
state = {
searchValue: ''
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
Router.push(`/search?searchValue=${this.state.searchValue}`);
};
render() {
const { classes } = this.props;
return (
<form onSubmit={this.handleSubmit}>
<div className={classes.search}>
<div className={classes.searchIcon}>
<Search />
</div>
<InputBase
name="searchValue"
type="search"
placeholder="Search…"
onChange={this.handleChange}
classes={{
root: classes.inputRoot,
input: classes.inputInput
}}
/>
</div>
</form>
);
}
}
export default SearchBar;
<file_sep>/store/reducer/productReducer.js
const initialState = {
products: [],
categories: [],
getError: null,
createError: null,
editError: null,
deleteError: null,
numDeleted: null
};
export default (
state = initialState,
{ type, products, err, numDeleted, categories }
) => {
switch (type) {
case 'GET_PRODUCTS_REQUEST':
return { ...state, products: products, getError: null };
case 'GET_PRODUCTS_SUCCESS':
return { ...state, products: products, getError: null };
case 'GET_PRODUCTS_ERROR':
return { ...state, getError: err };
case 'CREATE_PRODUCT_SUCCESS':
return { ...state, createError: null };
case 'CREATE_PRODUCT_ERROR':
return { ...state, createError: err };
case 'DELETE_PRODUCTS_SUCCESS':
return { ...state, deleteError: null, numDeleted: numDeleted };
case 'DELETE_PRODUCTS_ERROR':
return { ...state, deleteError: err, numDeleted: null };
case 'CLOSE_ALERT_DELETED':
return { ...state, numDeleted: null };
case 'EDIT_PRODUCT_SUCCESS':
return { ...state, editError: null };
case 'EDIT_PRODUCT_ERROR':
return { ...state, editError: err };
case 'GET_PRODUCTS_AND_CATEGORIES_SUCCESS':
return {
...state,
getError: null,
products: products,
categories: categories
};
case 'GET_PRODUCTS_AND_CATEGORIES_ERROR':
return {
...state,
getError: err,
products: products,
categories: categories
};
default:
return state;
}
};
<file_sep>/components/Bill/BillItem.jsx
import {
Paper,
Table,
TableHead,
TableRow,
TableCell,
TableBody,
Button
} from '@material-ui/core';
import { Delete } from '@material-ui/icons';
import React, { Component } from 'react';
class BillItem extends Component {
render() {
const { item, onDelete } = this.props;
return (
<>
<h2
style={{
marginTop: 50,
color: 'gray',
padding: 20,
textAlign: 'center'
}}
>
THE BILL
</h2>
<Paper style={{ margin: 'auto', width: '90%' }}>
<Table>
<TableHead>
<TableRow>
<TableCell colSpan={7}>ID : {item.bill._id}</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={7}>
Create At : {item.bill.createAt}
</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={7}>
Total Price : ${item.bill.totalPrice}
</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={7}>Status : {item.bill.status}</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Image</TableCell>
<TableCell>Name</TableCell>
<TableCell>Price ($)</TableCell>
<TableCell>Quatity</TableCell>
<TableCell>Total ($)</TableCell>
</TableRow>
{item.productsOfBill.map(product => (
<TableRow key={product._doc.product_id}>
<TableCell>{product._doc.product_id}</TableCell>
<TableCell>
<img
src={'/static' + product._doc.product_img}
width="80px"
alt="product image"
/>
</TableCell>
<TableCell>{product._doc.product_name}</TableCell>
<TableCell>${product.product_price}</TableCell>
<TableCell>{product.quantity}</TableCell>
<TableCell>
${product.product_price * product.quantity}
</TableCell>
</TableRow>
))}
<TableRow>
<TableCell colSpan={7} align="right">
<Button onClick={onDelete(item.bill._id)}>
<Delete color="error" />{' '}
<span style={{ color: 'red' }}>Cancel</span>
</Button>
</TableCell>
</TableRow>
</TableBody>
</Table>
</Paper>
</>
);
}
}
export default BillItem;
<file_sep>/components/Product/ProductDetails.jsx
import React, { Component } from 'react';
import { Grid, TextField, Button } from '@material-ui/core';
import Axios from 'axios';
import Link from 'next/link';
import { ShoppingCart, AddShoppingCart } from '@material-ui/icons';
class ProductDetails extends Component {
state = {
quantity: 1,
addError: '',
addSuccess: false
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
checkQuantity = e => {
if (e.target.value > 5 || e.target.value < 1) {
alert('1 to 5');
this.setState({ quantity: 1 });
}
};
validated__input = (stateValue, name, regex) => {
const input = window.document.getElementsByName(name)[0];
if (!input) return false;
if (regex.test(stateValue)) return true;
else {
input.value = '';
this.setState({ [name]: '' });
input.placeholder = '1 to 5';
input.focus();
return false;
}
};
componentWillUnmount() {
this.setState({ addSuccess: false });
}
handleSubmit = async e => {
e.preventDefault();
if (!this.validated__input(this.state.quantity, 'quantity', /^[1-5]$/))
return;
const auth = JSON.parse(window.sessionStorage.getItem('auth'));
if (!auth) {
alert('Login First!');
return;
}
try {
const addCart = await Axios.post('/api/carts', {
userId: auth.auth_key,
quantity: this.state.quantity,
proId: this.props.product.product_id,
proPrice: this.props.product.product_price
});
if (addCart.data.err) this.setState({ addError: addCart.data.err });
else {
this.setState({ addSuccess: true });
}
} catch (err) {
this.setState({ addError: err.message });
}
};
render() {
const { product, producer } = this.props;
return (
<div className="product-details">
<div className="product-img">
<img src={'/static' + product.product_img} alt="img" />
</div>
<div className="split" />
<div className="details">
<div className="name">{product.product_name}</div>
<div className="producer">{producer.producer_name}</div>
<div className="price">${product.product_price}</div>
<div className="describe">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos
placeat dolore ipsum, voluptatibus mollitia, ex obcaecati harum quae
qui veritatis quasi pariatur quaerat. Commodi libero vitae sapiente
dolor adipisci nulla!
</div>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
name="quantity"
onBlur={this.checkQuantity}
onChange={this.handleChange}
value={this.state.quantity}
label="Quantity"
type="number"
autoComplete="off"
/>
{this.state.addError && (
<p style={{ color: 'red' }}>{this.state.addError}</p>
)}
<br />
{this.state.addSuccess ? (
<Link href="/cart">
<a>
<Button
style={{ marginTop: 20 }}
variant="contained"
color="secondary"
type="submit"
>
In Your Cart
<ShoppingCart style={{ marginLeft: 5 }} />
</Button>
</a>
</Link>
) : (
<Button
style={{ marginTop: 20 }}
variant="contained"
color="primary"
type="submit"
>
Add To Cart <AddShoppingCart style={{ marginLeft: 5 }} />
</Button>
)}
</form>
</div>
</div>
);
}
}
export default ProductDetails;
<file_sep>/pages/index.jsx
import React, { Component } from 'react';
import Product from '../components/Product/Product';
import MySlider from '../components/Slider/MySlider';
import { Divider } from '@material-ui/core';
import GoToTop from '../components/GoToTop';
import CategoryList from '../components/CategoryList';
import Axios from 'axios';
const isServer = !process.browser;
const isProduction = !process.env.NODE_ENV === 'production';
export class index extends Component {
static async getInitialProps(ctx) {
const url = isServer
? `${isProduction ? 'https' : 'http'}://${
ctx.req.headers.host
}/api/producers`
: '/api/producers';
const categories = await Axios.get(url);
if (!categories.data.err) {
return { categories: categories.data.data };
}
return {};
}
state = {
categories: [],
query: ''
};
static getDerivedStateFromProps(props, state) {
if (!props.categories) {
return null;
} else {
return { categories: props.categories, query: props.query };
}
}
componentDidMount() {
window.onload = () => {
const navbar = document.querySelector('.NavBar');
const slider = document.querySelector('.slider');
navbar.style.display = 'fixed';
if (window.scrollY > slider.clientHeight - navbar.clientHeight) {
navbar.classList.remove('bg-transparent');
} else {
navbar.classList.add('bg-transparent');
}
};
}
render() {
const { categories, query } = this.state;
return (
<>
<style jsx global>{`
* {
scroll-behavior: smooth;
}
`}</style>
<div>
<MySlider />
<div id="content" />
<CategoryList categories={categories} selectedCategory={query} />
<div />
<h1 style={{ color: 'gray', textAlign: 'center', marginTop: 70 }}>
Products
</h1>
<div className="divider" />
<Product category={query && query.category ? query.category : null} />
<GoToTop />
</div>
</>
);
}
}
export default index;
<file_sep>/server/routes/cart.route.js
const express = require('express');
const controller = require('../controllers/cart.controller');
const router = express.Router();
router.get('/:id', controller.index);
router.post('/removeCart', controller.removeCart);
router.post('/addBill', controller.addBill);
module.exports = router;
<file_sep>/store/reducer/rootReducer.js
import productReducer from './productReducer';
import { combineReducers } from 'redux';
import userReducer from './userReducer';
import billReducer from './billReducer';
import categoryReducer from './categoryReducer';
const rootReducer = combineReducers({
product: productReducer,
user: userReducer,
bill: billReducer,
category: categoryReducer
});
export default rootReducer;
<file_sep>/components/admin/user/user.styles.jss.js
export const UserStyles = () => ({
root: {
backgroundColor: 'white',
minHeight: '100vh',
borderRadius: '7px',
padding: 20
},
header: {
fontSize: '1.7em',
color: 'gray',
fontWeight: 'bold',
textAlign: 'center'
},
m_20: {
margin: 20
}
});
export const AddUserStyles = () => ({
textField: {
margin: 10,
width: 400
},
formTitle: {
color: '#4445'
},
bgWhite: {
color: 'white'
},
root: {
backgroundColor: 'white',
borderRadius: '7px',
padding: 20
}
});
<file_sep>/pages/admin/user.jsx
import React, { Component } from 'react';
import User from '../../components/admin/user/User';
import EditUser from '../../components/admin/user/EditUser';
export class user extends Component {
render() {
return (
<>
{this.props.query.id ? <EditUser id={this.props.query.id} /> : <User />}
</>
);
}
}
export default user;
<file_sep>/components/Navbar/UnSigninedNav.jsx
import React, { Component } from 'react';
import { Button, MenuItem } from '@material-ui/core';
import Link from 'next/link';
export class UnSigninedNav extends Component {
render() {
let { btnColor } = this.props;
let Color = btnColor;
if (btnColor === 'inherit') Color = 'white';
return (
<>
{this.props.screen === 'mobile' ? (
<>
<MenuItem onClick={this.props.handleMobileMenuClose}>
<div>
<Link href="/signin">
<a>
<Button
color={btnColor}
variant="outlined"
style={{ marginLeft: 10, color: Color }}
>
Login
</Button>
</a>
</Link>
</div>
</MenuItem>
<MenuItem onClick={this.props.handleMobileMenuClose}>
<div>
<Link href="/signup">
<a>
<Button
style={{ marginLeft: 10, color: Color }}
color={btnColor}
variant="outlined"
>
Sign Up
</Button>
</a>
</Link>
</div>
</MenuItem>
</>
) : (
<>
<Link href="/signin">
<a>
<Button
color={btnColor}
variant="outlined"
style={{ marginLeft: 10, color: Color }}
>
Login
</Button>
</a>
</Link>
<Link href="/signup">
<a>
<Button
style={{ marginLeft: 10, color: Color }}
color={btnColor}
variant="outlined"
>
Sign Up
</Button>
</a>
</Link>
</>
)}
</>
);
}
}
export default UnSigninedNav;
<file_sep>/components/admin/Dashboard/TopUsers.jsx
import React, { Component } from 'react';
import Axios from 'axios';
import {
Table,
TableHead,
TableRow,
TableCell,
TableBody,
Fab,
Paper
} from '@material-ui/core';
export class TopUsers extends Component {
state = {
statistical: ''
};
async componentDidMount() {
const statistical = await Axios.get('/api/dashboard');
this.setState({ statistical: statistical.data });
}
render() {
return (
<>
<h2 style={{ color: 'gray' }}>Top Users</h2>
<Paper>
{this.state.statistical ? (
<Table>
<TableHead>
<TableRow>
<TableCell>Top</TableCell>
<TableCell>ID</TableCell>
<TableCell>Name</TableCell>
<TableCell>Email</TableCell>
<TableCell>Phone NUmber</TableCell>
<TableCell>Total Paid Price</TableCell>
<TableCell>Status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.statistical.topUsers &&
this.state.statistical.topUsers
.slice(0, 10)
.map((item, i) => (
<TableRow key={item.user._id}>
<TableCell>
<Fab
variant="extended"
size="small"
color={i === 0 ? 'secondary' : 'primary'}
style={{ boxShadow: 'none' }}
>
{i + 1}
</Fab>
</TableCell>
<TableCell>{item.user._id}</TableCell>
<TableCell>{item.user.user_name}</TableCell>
<TableCell>{item.user.user_email}</TableCell>
<TableCell>{item.user.user_phone}</TableCell>
<TableCell>
<b style={{ color: 'red' }}>${item.paidMoney}</b>
</TableCell>
<TableCell>
{item.user.user_status.toString()}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="loading-text">Loading...</div>
)}
</Paper>
</>
);
}
}
export default TopUsers;
<file_sep>/components/admin/Dashboard/TopSellerProducts.jsx
import React, { Component } from 'react';
import {
TextField,
Button,
Grid,
Fab,
Paper,
LinearProgress
} from '@material-ui/core';
import Axios from 'axios';
export class TopSellerProducts extends Component {
async componentDidMount() {
const statistical = await Axios.get('/api/dashboard');
this.setState({ statistical: statistical.data });
}
state = {
dateStart: '',
dateEnd: '',
statistical: {}
};
getStatistical = async () => {
const statistical = await Axios.get(
`/api/dashboard?dateStart=${this.state.dateStart}&dateEnd=${
this.state.dateEnd
}`
);
this.setState({ statistical: statistical.data });
};
handleChangeDate = async e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
return (
<div>
<h2 style={{ color: 'gray' }}>Top Seller Products</h2>
{/* filter by date */}
<TextField
onChange={this.handleChangeDate}
value={this.state.dateStart}
type="date"
name="dateStart"
/>
<TextField
onChange={this.handleChangeDate}
value={this.state.dateEnd}
type="date"
name="dateEnd"
/>
<Button
variant="contained"
color="primary"
onClick={this.getStatistical}
size="small"
>
Filter
</Button>
<br />
<br />
{/* map list */}
<Grid container spacing={16} justify="flex-start" alignItems="stretch">
{this.state.statistical.soldProducts &&
this.state.statistical.soldProducts
.sort((x1, x2) => x2.amount - x1.amount)
.slice(0, 10)
.map((item, i) => (
<Grid item xs={6} md={3} key={i} style={{ padding: 10 }}>
<Paper style={{ padding: 10, height: '100%' }}>
{/* Top Number */}
<Fab
variant="round"
size="small"
color={i === 0 ? 'secondary' : 'primary'}
style={{ boxShadow: 'none' }}
>
{i + 1}
</Fab>
{/* Image */}
<img
alt="product_img"
src={`/static${item.details.product_img}`}
width={100}
/>
{/* Info */}
<h3 style={{ color: 'gray' }}>
{item.details.product_name}
</h3>
<p>Type: {item.details.producer}</p>
<p>Total Revenue: ${item.totalPrice}</p>
<p>Total Amout: {item.amount}</p>
{/* Progress bar */}
<LinearProgress
variant="determinate"
style={{ marginTop: 10, padding: 2 }}
value={
(item.amount /
this.state.statistical.totalSoldProducts) *
100
}
color={i === 0 ? 'secondary' : 'primary'}
/>
</Paper>
</Grid>
))}
</Grid>
</div>
);
}
}
export default TopSellerProducts;
<file_sep>/server/server.js
require('dotenv/config');
const express = require('express');
const next = require('next');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const fs = require('fs');
const https = require('https');
const PORT = process.env.PORT || 3002;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const isUseDBLocal = process.env.DB === 'local';
app.prepare().then(() => {
const server = express();
const MONGO_URI = isUseDBLocal
? 'mongodb://127.0.0.1:27017/webbanhangdb'
: process.env.MONGO_URI;
// config middleware
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
// connect to mongodb
mongoose.connect(MONGO_URI, { useNewUrlParser: true }).catch(err => {
if (err) console.log(err);
else console.log('Connected to MongoDB');
});
// API route
const apiProductRoute = require('./api/routes/product.api.route');
const apiUserRoute = require('./api/routes/user.api.route');
const apiBillRoute = require('./api/routes/bill.api.route');
const apiProducerRoute = require('./api/routes/producer.api.route');
const apiCartRoute = require('./api/routes/cart.api.route');
const apiDashboard = require('./api/routes/dashboard.route');
server.use('/api/products', apiProductRoute);
server.use('/api/users', apiUserRoute);
server.use('/api/bills', apiBillRoute);
server.use('/api/producers', apiProducerRoute);
server.use('/api/carts', apiCartRoute);
server.use('/api/dashboard', apiDashboard);
// handle next app
server.get('*', (req, res) => {
return handle(req, res);
});
// const options = {
// key: fs.readFileSync('/home/ninh/ninh.key'),
// cert: fs.readFileSync('/home/ninh/ninh.crt'),
// passphrase: '<PASSWORD>',
// requestCert: false,
// rejectUnauthorized: false
// };
// const localServer = https.createServer(options, server);
// localServer.listen(PORT, function() {
// console.log('Start at https://ninh:' + PORT);
// });
// server listen
server.listen(PORT, () => {
console.log('Ready on http://localhost:' + PORT);
});
});
<file_sep>/components/admin/bill/bill.styles.jss.js
export const EditBillStyles = () => ({
textField: {
margin: 10,
width: 400
},
formTitle: {
color: '#4445'
},
bgWhite: {
color: 'white'
},
root: {
backgroundColor: 'white',
// minHeight: "100%",
borderRadius: '7px',
padding: 20
}
});
<file_sep>/server/api/controllers/dashboard.controller.js
const moment = require('moment');
const Bills = require('../../models/bills.model');
const Producers = require('../../models/producers.model');
const Products = require('../../models/products.model');
const Users = require('../../models/user.model');
module.exports.getDashboard = async (req, res) => {
try {
// get data from DB
const bills = await Bills.find();
const producers = await Producers.find();
const products = await Products.find();
const users = await Users.find();
// define variants
const totalProducts = products.length;
const totalBills = bills.length;
const totalCategories = producers.length;
const totalUsers = users.length;
let totalSoldProducts = 0;
const soldProducts = [];
const statistialOfEachType = [];
let totalRevenue = 0;
const time = {
start: req.query.dateStart,
end: req.query.dateEnd
};
for (let i = 0; i < bills.length; i += 1) {
const bill = bills[i];
const dateStart = time.start
? moment(time.start, 'YYYY-MM-DD')
: undefined;
const dateEnd = time.end ? moment(time.end, 'YYYY-MM-DD') : undefined;
const notGetTime = !time.start && !time.end;
// check request time
if (
moment(bill.createAt, 'MM-DD-YYYY').isBetween(
dateStart,
dateEnd,
null,
'[]'
) ||
notGetTime
) {
// loop all products in this bill
for (let j = 0; j < bill.details.proId.length; j += 1) {
const proId = bill.details.proId[j];
const proQuantity = bill.details.proQuantity[j];
const proPrice = bill.details.proPrice[j];
const currentProduct = products.find(
product => product.product_id === proId
);
const totalPrice = proQuantity * proPrice;
if (!soldProducts[0]) {
// init soldProducts
soldProducts.push({
details: currentProduct,
amount: proQuantity,
totalPrice
});
} else {
// check douplicate
const douplicateInSoldProducts = soldProducts.findIndex(
pro => pro.details.product_id === currentProduct.product_id
);
// push this product to sold products. If douplicate, update it
if (douplicateInSoldProducts !== -1) {
const index = douplicateInSoldProducts;
const newAmount = soldProducts[index].amount + proQuantity;
const newTotalPrice = newAmount * proPrice;
soldProducts[index] = {
details: currentProduct,
amount: newAmount,
totalPrice: newTotalPrice
};
} else {
soldProducts.push({
details: currentProduct,
amount: proQuantity,
totalPrice
});
}
}
}
}
}
producers.forEach(producer => {
const type = producer.producer_name;
// get total price of this type
const totalPrice = soldProducts.reduce((total, curr) => {
if (curr.details.producer === producer.producer_id) {
return total + curr.totalPrice;
}
return total;
}, 0);
// get total amount of this type
const totalAmount = soldProducts.reduce((total, curr) => {
if (curr.details.producer === producer.producer_id) {
return total + curr.amount;
}
return total;
}, 0);
// push these value to statistialOfEachType
statistialOfEachType.push({ type, totalPrice, totalAmount });
});
// get total revenue
totalRevenue = statistialOfEachType.reduce(
(total, curr) => total + curr.totalPrice,
0
);
// get total sold products
totalSoldProducts = soldProducts.reduce(
(total, curr) => total + curr.amount,
0
);
// getTopUser
let topUsers = [];
users.forEach(user => {
const billsOfUser = bills.filter(
bill => bill.authId === user.id && bill.status === 'paid'
);
if (billsOfUser[0]) {
const paidMoney = billsOfUser.reduce(
(total, curr) => total + curr.totalPrice,
0
);
topUsers.push({ user, paidMoney });
}
});
topUsers = topUsers.sort((x1, x2) => x1.paidMoney - x2.paidMoney < 1);
// server response
res.json({
soldProducts,
statistialOfEachType,
totalRevenue,
totalProducts,
totalBills,
totalCategories,
totalUsers,
totalSoldProducts,
topUsers
});
} catch (err) {
res.json(err);
}
};
<file_sep>/server/api/routes/cart.api.route.js
const express = require('express');
const router = express.Router();
const controller = require('../controllers/cart.api.controller');
router.get('/', controller.getCarts);
router.post('/', controller.addCart);
router.delete('/:id', controller.deleteCart);
module.exports = router;
<file_sep>/components/Product/Product.jsx
import React, { Component } from 'react';
import ProductList from './ProductList';
import Axios from 'axios';
export class Product extends Component {
state = {
products: [],
err: null,
isLoading: true
};
getProducts = async category => {
this.setState({ isLoading: true });
try {
const res = category
? await Axios.get(`/api/products?producer_id=${category}`)
: await Axios.get('/api/products');
const products = res.data.data;
this.setState({ ...this.state, products });
} catch (err) {
this.setState({ ...this.state, err: err.message });
}
this.setState({ isLoading: false });
};
componentDidUpdate(prevProps) {
if (this.props.category !== prevProps.category)
this.getProducts(this.props.category);
}
componentDidMount() {
this.getProducts(this.props.category);
}
render() {
const { products, isLoading } = this.state;
return (
<>
{products[0] ? (
<ProductList products={products} />
) : (
<div className="loading-text">Loading...</div>
)}
</>
);
}
}
export default Product;
<file_sep>/components/admin/category/EditCategory.jsx
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { TextField, Button, CircularProgress, Grid } from '@material-ui/core';
import {
editCategory,
getCategoriesWithRedux
} from '../../../store/action/categoryAction';
import { connect } from 'react-redux';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
import Link from 'next/link';
const styles = () => ({
textField: {
margin: 10,
width: 400
},
formTitle: {
color: '#4445'
},
bgWhite: {
color: 'white'
},
root: {
backgroundColor: 'white',
borderRadius: '7px',
padding: 20
}
});
class EditCategory extends Component {
state = {
_id: '',
producer_name: '',
producer_id: '',
onLoading: '',
message: '',
open: false,
category: {},
validateError: false
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
validated__input = (stateValue, regex, inputName, setError) => {
const value = stateValue;
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input) {
return false;
}
if (!regex.test(value)) {
input.focus();
this.setState({ validateError: 'Please complete this field' });
return false;
}
this.setState({ validateError: '' });
return true;
};
valudated__form = () => {
if (
!this.validated__input(
this.state.producer_name,
/[\w\s-]{1,}/,
'producer_name'
) ||
!this.validated__input(
this.state.producer_id,
/^[A-Z]{1,}$/,
'producer_id'
)
) {
return false;
}
return true;
};
// submit edit
handleSubmit = async e => {
e.preventDefault();
if (!this.valudated__form()) {
return;
}
this.setState({ onLoading: true });
await this.props.editCategory(this.state);
if (!this.props.editError) {
this.setState({
onLoading: false,
open: true,
message: `Edit ${this.state.producer_id} success`
});
} else {
alert('Permission Denied!');
window.location = '/admin';
}
};
async componentDidMount() {
await this.props.getCategoriesWithRedux();
if (this.props.haveCategory) {
const u = this.props.category;
this.setState({
producer_name: u.producer_name,
producer_id: u.producer_id,
_id: u._id
});
}
}
render() {
const { classes } = this.props;
return (
<div className="admin-content fadeIn">
<h2 className={classes.formTitle}>
Edit Category
<Link href="/admin/category">
<a style={{ marginLeft: 200 }}>
<Button variant="contained" color="default">
Back
</Button>
</a>
</Link>
</h2>
{this.props.haveCategory ? (
<Grid container>
<Grid item xs={6}>
<form
noValidate
id="editCategory"
autoComplete="off"
onSubmit={this.handleSubmit}
>
{/* ID */}
<TextField
required
name="producer_name"
label="Category Name"
value={this.state.producer_name}
className={classes.textField}
onChange={this.handleChange}
helperText="Uppercase Only"
/>
<br />
{/* Name */}
<TextField
required
name="producer_id"
label="ID"
className={classes.textField}
onChange={this.handleChange}
value={this.state.producer_id}
helperText="Not special character"
/>
<br />
{this.props.editError && (
<p style={{ color: 'red' }}>{this.props.editError}</p>
)}{' '}
<br />
{this.state.validateError && (
<p style={{ color: 'red' }}>{this.state.validateError}</p>
)}
</form>
{this.state.onLoading ? (
<Button variant="contained" color="primary">
<CircularProgress size={24} className={classes.bgWhite} />
</Button>
) : (
<Button
variant="contained"
color="primary"
form="editCategory"
type="submit"
>
Edit
</Button>
)}
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</Grid>
</Grid>
) : (
<h1>Not have this category.</h1>
)}
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
const { id } = ownProps;
const categories = state.category.categories;
let category = null;
let haveCategory = false;
if (categories) {
if (categories.data) {
category = categories.data.find(u => u._id === id);
if (category) {
haveCategory = true;
}
}
}
return {
category: category,
haveCategory,
editError: state.category.editError
};
};
const mapDispatchToProps = dispatch => {
return {
editCategory: category => dispatch(editCategory(category)),
getCategoriesWithRedux: () => dispatch(getCategoriesWithRedux())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(EditCategory)
);
<file_sep>/components/admin/product/Product.jsx
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import Router from 'next/router';
import Axios from 'axios';
import { withStyles } from '@material-ui/core/styles';
import { Divider, Button } from '@material-ui/core';
import AddProduct from './AddProduct';
import ProductList from './ProductList';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
import {
getProductsWithRedux,
closeAlertDeleted
} from '../../../store/action/productAction';
import ProductStyles from './product.styles.jss';
import { KeyboardArrowUp, KeyboardArrowDown } from '@material-ui/icons';
const styles = ProductStyles;
class Product extends PureComponent {
state = {
openSnackNumDeleted: false,
messDeleted: '',
adminAccess: true,
isAddFormOpen: false
};
async componentDidMount() {
const admin_key = JSON.parse(
window.sessionStorage.getItem('adminPageAccess')
).admin_key;
const admin = await Axios.get(`/api/users/${admin_key}/adminPermission`);
if (!admin.data.admin.product) {
this.setState({ ...this.state, adminAccess: false });
return;
} else {
this.setState({ ...this.state, adminAccess: true });
const { dispatch } = this.props;
await dispatch(getProductsWithRedux());
}
}
handleClose = () => {
this.setState({ openSnackNumDeleted: false });
const { dispatch } = this.props;
dispatch(closeAlertDeleted());
};
componentWillReceiveProps(nextProps) {
if (nextProps.numDeleted) {
this.setState({
openSnackNumDeleted: true,
messDeleted: `${nextProps.numDeleted} products has been deleted`
});
}
}
toggleOpenAddForm = () => {
this.setState({ isAddFormOpen: !this.state.isAddFormOpen });
};
render() {
const { classes, numDeleted } = this.props;
const { isAddFormOpen } = this.state;
return (
<>
{this.state.adminAccess ? (
<>
<div className="admin-content fadeIn">
<div className="admin-content-header">Product Manager</div>
<div className="divider" />
{/* Button Add */}
<Button
onClick={this.toggleOpenAddForm}
variant={'contained'}
color={'primary'}
>
Add Product{' '}
{isAddFormOpen ? <KeyboardArrowUp /> : <KeyboardArrowDown />}
</Button>
{/* Form Add*/}
{isAddFormOpen && <AddProduct />}
{/* List Product */}
<div className="divider" />
{this.props.products ? (
<ProductList products={this.props.products.data} />
) : (
<div className="loading-text">Loading...</div>
)}
</div>
{numDeleted && (
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.openSnackNumDeleted}>
{this.state.messDeleted}
</CustomizedSnackbars>
</div>
)}
</>
) : (
<>{Router.push('/admin')}</>
)}
</>
);
}
}
const mapStateToProps = state => {
return {
products: state.product.products,
numDeleted: state.product.numDeleted,
deleteError: state.product.deleteError
};
};
export default withStyles(styles)(connect(mapStateToProps)(Product));
<file_sep>/pages/signup.jsx
import React, { Component } from 'react';
import { TextField, Button, CircularProgress, Paper } from '@material-ui/core';
import Link from 'next/link';
import Axios from 'axios';
import Router from 'next/router';
import ShopContext from '../context/shop-context';
class signup extends Component {
static contextType = ShopContext;
state = {
user_name: {
value: '',
error: false
},
user_password: {
value: '',
error: false
},
user_phone: {
value: '',
error: false
},
user_email: {
value: '',
error: false
},
confirmPassword: {
value: '',
error: false
},
onLoading: false,
isDoublicateEmail: false,
signupError: ''
};
async componentDidMount() {
await this.context.checkLogin();
if (this.context.auth.auth_key) Router.push('/');
}
validated__form = () => {
const { confirmPassword, user_password, isDoublicateEmail } = this.state;
if (isDoublicateEmail) {
document.querySelector(`input[name='user_email']`).focus();
return false;
}
if (
!this.validate__input('user_email') ||
!this.validate__input('user_name') ||
!this.validate__input('user_phone') ||
!this.validate__input('user_password')
)
return false;
if (user_password.value !== confirmPassword.value) {
this.setState({ confirmPassword: { ...confirmPassword, error: true } });
document.querySelector("input[name='confirmPassword']").focus();
return false;
}
return true;
};
validate__input = name => {
const input = document.querySelector(`input[name='${name}']`);
const regex = new RegExp(input.pattern);
if (regex.test(input.value)) return true;
input.focus();
this.setState({ [name]: { error: true } });
return false;
};
handleChange = e => {
const regex = new RegExp(e.target.pattern);
this.setState({
[e.target.name]: {
value: e.target.value,
error: !regex.test(e.target.value)
}
});
};
checkDuplicateEmail = async () => {
const { user_email } = this.state;
try {
const findUser = await Axios.get(
'/api/users/find/?user_email=' + user_email.value
);
this.setState({
...this.state,
isDoublicateEmail: findUser.data.found ? true : false
});
} catch (err) {
console.log(err);
}
};
handleSubmit = async e => {
const { user_email, user_name, user_password, user_phone } = this.state;
this.setState({ onLoading: true });
e.preventDefault();
if (!this.validated__form()) {
this.setState({ onLoading: false });
return;
} else {
try {
const signup = await Axios.post('/api/users', {
user_name: user_name.value,
user_password: <PASSWORD>,
user_phone: user_phone.value,
user_email: user_email.value
});
if (signup.data.err) {
this.setState({ signupError: signup.data.err });
} else {
this.setState({ signupError: '' });
Router.push('/signin');
}
} catch (err) {
console.log(err);
}
}
this.setState({ onLoading: false });
};
render() {
const {
user_email,
user_password,
user_name,
user_phone,
signupError,
onLoading,
confirmPassword,
isDoublicateEmail
} = this.state;
return (
<>
<form className={'form-center'} noValidate onSubmit={this.handleSubmit}>
<div className={'text-center title'}>SIGN UP</div>
{/* Email */}
<TextField
required
error={user_email.error || isDoublicateEmail}
onBlur={this.checkDuplicateEmail}
label="Email"
name="user_email"
defaultValue={user_email.value}
onChange={e => {
this.handleChange(e);
}}
margin="dense"
className="textField"
helperText={
isDoublicateEmail
? 'This email has been used'
: '<EMAIL>'
}
inputProps={{
pattern: '[a-z][a-z0-9_.]{5,32}@[a-z0-9]{2,}(.[a-z0-9]{2,4}){1,2}'
}}
/>
{/* Name */}
<TextField
error={user_name.error}
required
label="Name"
name="user_name"
defaultValue={user_name.value}
onChange={this.handleChange}
margin="dense"
className="textField"
inputProps={{
pattern: '^[ ._A-z0-9]*$'
}}
helperText={'no speacial character [!,@,#,$,%,^,&,*]'}
/>
{/* Phone */}
<TextField
error={user_phone.error}
required
label="Phone"
name="user_phone"
defaultValue={user_phone.value}
onChange={this.handleChange}
margin="dense"
className="textField"
type="number"
helperText="10 number, first number is 0"
inputProps={{ pattern: '0[0-9]{9}' }}
/>
{/* Password */}
<TextField
error={user_password.error}
required
label="Password"
name="user_password"
defaultValue={user_password.value}
onChange={this.handleChange}
margin="dense"
className="textField"
helperText="min 6 charaters"
type="password"
inputProps={{ pattern: '.{6,}' }}
/>
{/* Confirm Password */}
<TextField
error={confirmPassword.error}
required
label="Confirm Password"
name="confirmPassword"
className="textField"
defaultValue={confirmPassword.value}
type="password"
onChange={this.handleChange}
margin="dense"
inputProps={{ pattern: '.{6,}' }}
/>
{signupError && <div style={{ color: 'red' }}>{signupError}</div>}
{onLoading ? (
<Button
className={'submit'}
variant="contained"
color="primary"
type="button"
>
<CircularProgress size={25} color="inherit" />
</Button>
) : (
<Button
className={'submit'}
variant="contained"
color="primary"
type="submit"
>
Sign up
</Button>
)}
<p style={{ color: 'gray', fontSize: '12px' }}>
Have account ?
<Link href="/signin">
<a>
<Button color="primary">sign in</Button>
</a>
</Link>
</p>
</form>
</>
);
}
}
export default signup;
<file_sep>/store/action/billAction.js
import Axios from "axios";
import checkAdmin from "./checkAdmin";
export function getBillsWithRedux() {
return async (dispatch, getState) => {
dispatch({ type: "GET_BILLS_REQUEST" });
const res = await Axios("/api/bills/");
return dispatch({ type: "GET_BILLS_SUCCESS", bills: res.data });
};
}
export const createBill = bill => {
return async (dispatch, getState) => {
const isAdmin = await checkAdmin();
if (!isAdmin) {
return dispatch({ type: "CREATE_BILL_ERROR", err: "Permision Denied" });
}
try {
await Axios.post("/api/bills/", bill);
return dispatch({ type: "CREATE_BILL_SUCCESS" });
} catch (err) {
return dispatch({ type: "CREATE_BILL_ERROR", err: err.message });
}
};
};
export const deleteBills = bills => {
return async (dispatch, getState) => {
const isAdmin = await checkAdmin();
if (!isAdmin) {
return dispatch({ type: "DELETE_BILLS_ERROR", err: "Permision Denied" });
}
try {
let del = [];
bills.forEach(bill => {
del.push(Axios.delete(`/api/bills/${bill}`));
});
await Promise.all(del);
dispatch(getBillsWithRedux());
return dispatch({
type: "DELETE_BILLS_SUCCESS",
numDeleted: bills.length
});
} catch (err) {
return dispatch({ type: "DELETE_BILLS_ERROR", err: err.message });
}
};
};
export const closeAlertDeleted = () => {
return dispatch => {
return dispatch({ type: "CLOSE_ALERT_DELETED" });
};
};
export const editBill = bill => {
return async dispatch => {
const isAdmin = await checkAdmin();
if (!isAdmin) {
return dispatch({ type: "EDIT_BILL_ERROR", err: "Permision Denied" });
}
try {
const promiseData = await Axios.put(`/api/bills/${bill._id}`, bill);
if (promiseData.data.err) {
return dispatch({ type: "EDIT_BILL_ERROR", err: promiseData.data.err });
}
return dispatch({ type: "EDIT_BILL_SUCCESS" });
} catch (err) {
return dispatch({ type: "EDIT_BILL_ERROR", err: err.message });
}
};
};
<file_sep>/components/Slider/MySlider.jsx
import Slider from 'react-animated-slider';
import React, { Component } from 'react';
import { Button } from '@material-ui/core';
const content = [
{
image: '/static/image/banner_iphone_large.jpg',
description:
'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sed cum eum exercitationem, aliquam vero iste? Minus sapiente officia animi amet ex maxime alias tempora est autem quia, illo iure nesciunt?',
title: 'Wellcome To Shopphone',
button: 'Buy now'
},
{
image: '/static/image/banner_iphone_large.jpg',
description:
'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sed cum eum exercitationem, aliquam vero iste? Minus sapiente officia animi amet ex maxime alias tempora est autem quia, illo iure nesciunt?',
title: 'Wellcome To Shopphone',
button: 'Buy now'
},
{
image: '/static/image/banner_iphone_large.jpg',
description:
'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sed cum eum exercitationem, aliquam vero iste? Minus sapiente officia animi amet ex maxime alias tempora est autem quia, illo iure nesciunt?',
title: 'Wellcome To Shopphone',
button: 'Buy now'
}
];
export class MySlider extends Component {
render() {
return (
<>
<Slider autoplay={3000} touchDisabled={true}>
{content.map((item, index) => (
<div
key={index}
style={{
background: `url('${item.image}') no-repeat`,
backgroundSize: 'cover'
}}
>
<div className="center">
<h1 style={{ color: 'white', textShadow: '0 0 5px black' }}>
{item.title}
</h1>
<p
style={{
maxWidth: '600px',
wordWrap: 'break-word',
margin: 'auto',
color: 'white',
textShadow: '0 0 5px black'
}}
>
{item.description}
</p>
<a href="#content">
<Button
style={{
marginTop: 20,
borderRadius: '9999px',
padding: '10px 20px',
boxShadow: '0 0 5px black'
}}
variant="contained"
color="primary"
>
{item.button}
</Button>
</a>
</div>
</div>
))}
</Slider>
</>
);
}
}
export default MySlider;
<file_sep>/components/admin/product/AddProduct.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import {
TextField,
Button,
MenuItem,
FormControl,
InputLabel,
Select,
CircularProgress
} from '@material-ui/core';
import ProductStyles from './product.styles.jss';
import {
createProduct,
getProductsWithRedux
} from '../../../store/action/productAction';
import { getCategoriesWithRedux } from '../../../store/action/categoryAction';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
const styles = ProductStyles;
class AddProduct extends Component {
state = {
product_name: '',
product_price: '',
producer: '',
quantity: '',
product_img: '',
product_img_path: '',
isAdding: false,
message: '',
open: false,
err: {
errSelection: false
},
categories: [],
validateError: false
};
async componentDidMount() {
await this.props.getCategoriesWithRedux();
if (this.props.categories && this.props.categories.data) {
this.setState({ categories: this.props.categories.data });
}
}
handleChangeFile = e => {
this.setState({
product_img: e.target.files[0],
product_img_path: e.target.files[0].name
});
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
validated__input = (stateValue, regex, inputName, setError) => {
const value = stateValue;
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input) {
return false;
}
if (!regex.test(value)) {
input.focus();
this.setState({ validateError: 'Please complete this field' });
return false;
}
if (setError)
this.setState({ err: { [setError.key]: false }, validateError: '' });
return true;
};
validated__input_file = (inputName, setError) => {
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input || !input.value) {
input.click();
return false;
}
if (setError) this.setState({ err: { [setError.key]: false } });
return true;
};
valudated__form = () => {
if (
!this.validated__input(
this.state.product_name,
/[\w\s-]{1,}/,
'product_name'
) ||
!this.validated__input(
this.state.product_price,
/^[1-9][0-9]{0,5}$/,
'product_price'
) ||
!this.validated__input(
this.state.quantity,
/^[1-9][0-9]{0,5}$/,
'quantity'
) ||
!this.validated__input(
this.state.producer,
/^[\w]{1,20}$/,
'producer',
'errSelection'
) ||
!this.validated__input_file('product_img')
) {
return false;
}
return true;
};
handleSubmit = async e => {
const { createProduct, getProductsWithRedux } = this.props;
this.setState({ isAdding: true });
e.preventDefault();
if (!this.valudated__form()) {
this.setState({ isAdding: false });
return;
}
await createProduct(this.state);
if (!this.props.createError) {
getProductsWithRedux();
this.setState({
open: true,
message: `Adding ${this.state.product_name} success`
});
} else if (this.props.createError === 'Permision Denied') {
alert('Permission Denied!');
window.location = '/admin';
}
this.setState({ isAdding: false });
};
render() {
const { classes } = this.props;
return (
<>
<h2 className={classes.formTitle}>Add new Product</h2>
<form
encType="multipart/form-data"
id="addNewProduct"
className={classes.container}
noValidate
autoComplete="off"
onSubmit={this.handleSubmit}
>
{/* Product Name */}
<TextField
required
name="product_name"
label="Product Name"
className={classes.textField}
onChange={this.handleChange}
/>
{/* Product Price */}
<TextField
required
name="product_price"
label="Price ($)"
className={classes.textField}
onChange={this.handleChange}
type="number"
/>
{/* Quantity */}
<TextField
required
value={this.state.quantity}
name="quantity"
label="Quantity"
className={classes.textField}
onChange={this.handleChange}
type="number"
/>
{/* Producer - Catefory */}
<FormControl className={classes.textField}>
<InputLabel htmlFor="select-producer">Catefory</InputLabel>
<Select
error={this.state.err.errSelection}
value={this.state.producer}
onChange={this.handleChange}
inputProps={{
name: 'producer',
id: 'select-producer'
}}
>
{this.state.categories &&
this.state.categories.map((item, index) => (
<MenuItem key={index} value={item.producer_id}>
{item.producer_name}
</MenuItem>
))}
</Select>
</FormControl>
{/* Input img */}
<TextField
required
name="product_img"
label="Choose Image"
className={classes.textField}
onChange={this.handleChangeFile}
type="file"
/>
{this.props.createError && (
<p style={{ color: 'red' }}>{this.props.createError}</p>
)}
{this.state.validateError && (
<p style={{ color: 'red' }}>{this.state.validateError}</p>
)}
</form>
<Button
variant="contained"
color="primary"
form="addNewProduct"
type="submit"
>
{this.state.isAdding ? (
<CircularProgress size={24} className={classes.bgWhite} />
) : (
<span>Add New Product</span>
)}
</Button>
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</>
);
}
}
const mapStateToProps = state => {
return {
createError: state.product.createError,
categories: state.category.categories
};
};
const mapDispatchToProps = dispatch => {
return {
createProduct: product => dispatch(createProduct(product)),
getProductsWithRedux: () => dispatch(getProductsWithRedux()),
getCategoriesWithRedux: () => dispatch(getCategoriesWithRedux())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(AddProduct)
);
<file_sep>/store/reducer/billReducer.js
const initialState = {
bills: [],
getError: null,
createError: null,
deleteError: null
};
export default (
state = initialState,
{ type, payload, bills, err, numDeleted }
) => {
switch (type) {
case 'GET_BILLS_REQUEST':
return { ...state, ...payload, bills: bills, getError: null };
case 'GET_BILLS_SUCCESS':
return { ...state, ...payload, bills: bills, getError: null };
case 'GET_BILLS_ERROR':
return { ...state, ...payload, getError: err };
case 'CREATE_BILL_SUCCESS':
return { ...state, ...payload, createError: null };
case 'CREATE_BILL_ERROR':
return { ...state, ...payload, createError: err };
case 'DELETE_BILLS_SUCCESS':
return {
...state,
...payload,
numDeleted: numDeleted,
deleteError: null
};
case 'DELETE_BILLS_ERROR':
return { ...state, ...payload, deleteError: err };
case 'CLOSE_ALERT_DELETED':
return { ...state, ...payload, numDeleted: null };
case 'EDIT_BILL_SUCCESS':
return { ...state, ...payload, editError: null };
case 'EDIT_BILL_ERROR':
return { ...state, ...payload, editError: err };
default:
return state;
}
};
<file_sep>/components/admin/Dashboard/BusinessSituation.jsx
import React, { Component } from 'react';
import {
TextField,
Button,
Grid,
Paper,
LinearProgress
} from '@material-ui/core';
import Axios from 'axios';
export class BusinessSituation extends Component {
state = {
dateStart: '',
dateEnd: '',
statistical: {}
};
async componentDidMount() {
const statistical = await Axios.get('/api/dashboard');
this.setState({ statistical: statistical.data });
}
getStatistical = async () => {
const statistical = await Axios.get(
`/api/dashboard?dateStart=${this.state.dateStart}&dateEnd=${
this.state.dateEnd
}`
);
this.setState({ statistical: statistical.data });
};
handleChangeDate = async e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
let statistialOfEachType = this.state.statistical.statistialOfEachType
? [...this.state.statistical.statistialOfEachType]
: '';
if (statistialOfEachType[0]) {
statistialOfEachType = statistialOfEachType.sort((x1, x2) => {
return x2.totalAmount - x1.totalAmount;
});
}
return (
<div>
<h2 style={{ color: 'gray' }}>Business Situation</h2>
{/* filter by day */}
<TextField
onChange={this.handleChangeDate}
value={this.state.dateStart}
type="date"
name="dateStart"
/>
<TextField
onChange={this.handleChangeDate}
value={this.state.dateEnd}
type="date"
name="dateEnd"
/>
<Button
variant="contained"
color="primary"
onClick={this.getStatistical}
size="small"
>
Filter
</Button>
<br />
{/* map list */}
<Grid container spacing={16} justify="flex-start">
{statistialOfEachType &&
statistialOfEachType.map((item, i) => (
<Grid item xs={'auto'} md={3} key={i}>
<Paper style={{ padding: 10, marginTop: 20 }}>
<h1 style={{ color: 'gray' }}>{item.type}</h1>
<p style={{ color: 'gray' }}>
Total Revenue:{' '}
<b style={{ color: '#ff835d' }}>${item.totalPrice}</b>
</p>
<p style={{ color: 'gray' }}>
Total Amout:{' '}
<b style={{ color: '#616161' }}>{item.totalAmount}</b>{' '}
Products
</p>
<LinearProgress
variant="determinate"
style={{ marginTop: 10, padding: 2 }}
value={
this.state.statistical.totalSoldProducts
? (item.totalAmount /
this.state.statistical.totalSoldProducts) *
100
: 0
}
color={i === 0 ? 'secondary' : 'primary'}
/>
</Paper>
</Grid>
))}
</Grid>
</div>
);
}
}
export default BusinessSituation;
<file_sep>/server/controllers/search.controller.js
const Producers = require('../models/producers.model');
const Products = require('../models/products.model');
module.exports.index = async (req, res) => {
const querys = req.query;
const producers = await Producers.find();
let products = await Products.find();
if (querys.search) {
products = products.filter(
product => product.product_name
.toLowerCase()
.trim()
.indexOf(querys.search.toLowerCase().trim()) !== -1,
);
}
if (querys.price) {
const minPrice = parseInt(querys.price.split('to')[0], 10);
const maxPrice = parseInt(querys.price.split('to')[1], 10);
products = products.filter((pro) => {
const price = parseInt(pro.product_price, 10);
return price <= maxPrice && price >= minPrice;
});
}
if (querys.producer) {
products = products.filter(pro => pro.producer === querys.producer);
}
if (querys.sortByName) {
if (querys.sortByName === 'AtoZ') {
products.sort((a, b) => {
const nameA = a.product_name.toLowerCase();
const nameB = b.product_name.toLowerCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
} else {
products.sort((a, b) => {
const nameA = a.product_name.toLowerCase();
const nameB = b.product_name.toLowerCase();
if (nameA < nameB) {
return 1;
}
if (nameA > nameB) {
return -1;
}
return 0;
});
}
}
if (querys.sortByPrice) {
products.sort((a, b) => {
const priceA = parseInt(a.product_price, 10);
const priceB = parseInt(b.product_price, 10);
return priceA - priceB;
});
if (querys.sortByPrice !== 'Asc') {
products.reverse();
}
}
res.render('search/index', {
querys,
producers,
products,
});
};
// getSearch
module.exports.getSearch = async (req, res) => {
const querys = req.body;
const producers = await Producers.find();
let products = await Products.find();
if (querys.search) {
products = products.filter(
product => product.product_name
.toLowerCase()
.trim()
.indexOf(querys.search.toLowerCase().trim()) !== -1,
);
}
if (querys.price) {
const minPrice = parseInt(querys.price.split('to')[0], 10);
const maxPrice = parseInt(querys.price.split('to')[1], 10);
products = products.filter((pro) => {
const price = parseInt(pro.product_price, 10);
return price <= maxPrice && price >= minPrice;
});
}
if (querys.producer) {
products = products.filter(pro => pro.producer === querys.producer);
}
if (querys.sortByName) {
if (querys.sortByName === 'AtoZ') {
products.sort((a, b) => {
const nameA = a.product_name.toLowerCase();
const nameB = b.product_name.toLowerCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
} else {
products.sort((a, b) => {
const nameA = a.product_name.toLowerCase();
const nameB = b.product_name.toLowerCase();
if (nameA < nameB) {
return 1;
}
if (nameA > nameB) {
return -1;
}
return 0;
});
}
}
if (querys.sortByPrice) {
products.sort((a, b) => {
const priceA = parseInt(a.product_price, 10);
const priceB = parseInt(b.product_price, 10);
return priceA - priceB;
});
if (querys.sortByPrice !== 'Asc') {
products.reverse();
}
}
res.render('search/get', {
querys,
producers,
products,
});
};
<file_sep>/layouts/Main.jsx
import React, { Component } from 'react';
import Footer from '../components/Footer/Footer';
import Axios from 'axios';
import Router from 'next/router';
import GlobalState from '../context/GlobalState';
import Navbar from '../components/Navbar/Navbar';
import ButtonDarkMode from '../components/ButtonDarkMode';
class Main extends Component {
state = {
auth: {},
isDarkMode: false
};
handleLogout = () => {
window.sessionStorage.removeItem('auth');
Router.push('/signin');
};
checkLogin = async () => {
let newAuth = {};
// get auth from session
const auth = JSON.parse(window.sessionStorage.getItem('auth'));
if (auth) {
// check auth with database
const user = await Axios.get('/api/users/' + auth.auth_key);
if (!user.data.err) {
newAuth = {
auth_name: user.data.user.user_name,
auth_key: user.data.user._id,
auth_group: user.data.user.user_group
};
}
}
// update login status
if (this.state.auth.auth_key !== newAuth.auth_key) {
this.setState({ auth: newAuth });
}
};
componentDidUpdate() {
this.checkLogin();
}
componentDidMount() {
const navbar = document.querySelector('.NavBar');
let slider = null;
this.checkLogin();
const { route } = Router;
if (route === '/') {
slider = document.querySelector('.slider');
navbar.classList.add('bg-transparent');
navbar.style.position = 'fixed';
window.onscroll = () => {
if (window.scrollY > slider.clientHeight - navbar.clientHeight) {
navbar.classList.remove('bg-transparent');
} else {
navbar.classList.add('bg-transparent');
}
};
} else {
navbar.classList.remove('bg-transparent');
navbar.style.position = 'sticky';
}
}
toggleDarkMode = () => {
this.setState({ isDarkMode: !this.state.isDarkMode });
};
render() {
const { isDarkMode, auth } = this.state;
return (
<GlobalState
isDarkMode={isDarkMode}
auth={auth}
checkLogin={this.checkLogin}
toggleDarkMode={this.toggleDarkMode}
>
<style jsx global>{`
body {
background: ${isDarkMode ? '#000' : '#fff'};
}
`}</style>
<div style={{ position: 'relative' }}>
{/* Navigation Bar */}
<Navbar auth={this.state.auth} onLogout={this.handleLogout} />
{/* Content here */}
<div className="full-height">{this.props.children}</div>
{/* Footer */}
<Footer />
{/* Toggle Dark mode */}
<ButtonDarkMode />
</div>
</GlobalState>
);
}
}
export default Main;
<file_sep>/components/Product/ProductCard.jsx
import React, { Component } from 'react';
import { ShoppingCart } from '@material-ui/icons';
import Link from 'next/link';
import ShopContext from '../../context/shop-context';
import Axios from 'axios';
class ProductCard extends Component {
static contextType = ShopContext;
state = {
addError: '',
addSuccess: false,
isLoading: false
};
componentWillMount() {
this.setState({ isLoading: false });
}
componentWillUnmount() {
this.setState({ addSuccess: false });
}
shouldComponentUpdate(nextProps, nextState) {
return this.props.product !== nextProps.product || nextState !== this.state;
}
handleAddToCart = async () => {
const { auth } = this.context;
if (!auth || !auth.auth_key) {
alert('You must to Login First!');
return;
}
this.setState({ isLoading: true });
try {
const addCart = await Axios.post('/api/carts', {
userId: auth.auth_key,
quantity: 1,
proId: this.props.product.product_id,
proPrice: this.props.product.product_price
});
if (addCart.data.err) this.setState({ addError: addCart.data.err });
else {
this.setState({ addSuccess: true });
}
} catch (err) {
this.setState({ addError: err.message });
}
this.setState({ isLoading: false });
};
render() {
const { product } = this.props;
return (
<div className="ProductCard">
<div className="card-image">
<div className="card-image-wrap">
<Link href={`/product?id=${product._id}`}>
<a>
<img src={`/static${product.product_img}`} alt="img" />
</a>
</Link>
{this.state.addError ? (
<div style={{ color: 'red' }}>{this.state.addError}</div>
) : (
<>
{this.state.addSuccess ? (
<Link href={'/cart'}>
<a>
<div className="btn-cart active">
<ShoppingCart />
</div>
</a>
</Link>
) : (
<div className="btn-cart" onClick={this.handleAddToCart}>
{this.state.isLoading ? '...' : <ShoppingCart />}
</div>
)}
</>
)}
</div>
</div>
<Link href={`/product?id=${product._id}`}>
<a>
<div className="card-content">
<div className="card-title">{product.product_name}</div>
<div className="card-title text-gray">{product.producer}</div>
<div className="price">{product.product_price}</div>
</div>{' '}
</a>
</Link>
</div>
);
}
}
export default ProductCard;
<file_sep>/server/api/controllers/cart.api.controller.js
const Carts = require('../../models/cart.model');
const Products = require('../../models/products.model');
module.exports.addCart = async (req, res) => {
const { proId, userId, quantity } = req.body;
try {
const product = await Products.findOne({ product_id: proId });
const cart = await Carts.findOne({
userId: userId,
proId: proId
});
if (cart) {
const newQuantity = cart.quantity + parseInt(quantity, 10);
if (newQuantity > 5)
return res.send({
err: 'Only 5 products of the same type in your cart!!'
});
if (product.quantity - newQuantity < 0)
return res.send({
err: 'This product is out of stock',
product_name: product.product_name
});
await Carts.findByIdAndUpdate(cart.id, { quantity: newQuantity });
return res.send('success');
}
if (product.quantity - parseInt(quantity, 10) < 0)
return res.send({
err: 'This product is out of stock',
product_name: product.product_name
});
await Carts.insertMany(req.body);
return res.send('success');
} catch (err) {
return res.send({ err: err.message });
}
};
module.exports.getCarts = async (req, res) => {
try {
const carts = await Carts.find();
res.json(carts);
} catch (err) {
return res.send({ err: err.message });
}
};
module.exports.deleteCart = async (req, res) => {
try {
await Carts.findByIdAndDelete(req.params.id);
return res.send('success');
} catch (err) {
return res.send({ err: err.message });
}
};
<file_sep>/server/controllers/home.controller.js
const Products = require('../models/products.model');
const Producers = require('../models/producers.model');
module.exports.getCategory = async (req, res) => {
const querys = req.query;
const producers = await Producers.find();
let products = [];
products = await Products.find({ producer: querys.producer });
res.render('home/getCategory', { products, producers, querys });
};
module.exports.getAll = async (req, res) => {
const querys = req.query;
const producers = await Producers.find();
let products = [];
products = await Products.find();
res.render('home/getAll', { products, producers, querys });
};
module.exports.index = async (req, res) => {
const querys = req.query;
const producers = await Producers.find();
let products = [];
if (querys.producer) {
products = await Products.find({ producer: querys.producer });
const producer = await Producers.find({ producer_id: querys.producer });
return res.render('home/category', {
products,
producers,
querys,
producer,
});
}
if (querys.producer === '') {
products = await Products.find();
return res.render('home/allProducts', { products, producers, querys });
}
if (!querys.producer) {
products = await Products.find();
return res.render('home/index', {
products,
producers,
querys,
});
}
};
<file_sep>/pages/search.jsx
import React, { Component } from 'react';
import SearchForm from '../components/Product/SearchForm';
import Axios from 'axios';
import ProductList from '../components/Product/ProductList';
import { Divider } from '@material-ui/core';
export class search extends Component {
state = {
categories: [],
products: [],
searchResult: [],
isLoading: true
};
async componentDidMount() {
const products = await Axios.get('/api/products');
const categories = await Axios.get('/api/producers');
this.setState({
...this.state,
isLoading: false,
categories: categories.data.data,
products: products.data.data
});
this.renderSearchResult({
product_name: this.props.query.searchValue
});
}
renderSearchResult = query => {
let products = [...this.state.products];
// filter by name
if (query.product_name) {
products = products.filter(
item =>
item.product_name
.toLowerCase()
.trim()
.indexOf(query.product_name.toLowerCase().trim()) !== -1
);
}
// filter by category - producer
if (query.producer) {
products = products.filter(item => item.producer === query.producer);
}
// filter by price
if (query.product_price && query.product_price.from) {
products = products.filter(
item =>
item.product_price >= query.product_price.from &&
item.product_price <= query.product_price.to
);
}
// sort by price
if (query.sortByPrice) {
products.sort((a, b) => {
if (query.sortByPrice === 'Asc')
return a.product_price - b.product_price;
else return b.product_price - a.product_price;
});
}
// sort by name
if (query.sortByName) {
products.sort((a, b) => {
const name_a = a.product_name.toLowerCase();
const name_b = b.product_name.toLowerCase();
if (query.sortByName === 'A-Z') return name_a < name_b ? -1 : 1;
else return name_a > name_b ? -1 : 1;
});
}
this.setState({ searchResult: products });
};
render() {
return (
<>
<style jsx global>{`
* {
scroll-behavior: smooth;
}
`}</style>
<h1 style={{ color: 'gray', textAlign: 'center' }}>YOUR SEARCH</h1>
<div className="divider" />
<SearchForm
categories={this.state.categories}
renderSearchResult={this.renderSearchResult}
/>
{this.state.isLoading ? (
<div className="loading-text">Loading...</div>
) : (
<>
{this.state.searchResult[0] ? (
<ProductList products={this.state.searchResult} />
) : (
<h1 style={{ color: 'gray', textAlign: 'center' }}>Empty</h1>
)}
</>
)}
</>
);
}
}
export default search;
<file_sep>/pages/_app.js
import React from 'react';
import App, { Container } from 'next/app';
import Head from 'next/head';
import { MuiThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import JssProvider from 'react-jss/lib/JssProvider';
import getPageContext from '../src/getPageContext';
import AdminMain from '../layouts/AdminMain';
import Main from '../layouts/Main';
import Router from 'next/router';
import Nprogress from 'nprogress';
import '../layouts/styles/profile.scss';
import '../layouts/styles/Navbar.scss';
import '../layouts/styles/MySlider.scss';
import '../layouts/styles/ProductCard.scss';
import '../layouts/styles/CategoryList.scss';
import '../layouts/styles/ResetPassword.scss';
import '../layouts/styles/FormCenter.scss';
import '../layouts/styles/ProductDetails.scss';
import '../layouts/styles/AdminFooter.scss';
Router.events.on('routeChangeComplete', () => {
if (Router.route !== '/') window.scrollTo({ top: '0' });
});
Router.events.on('routeChangeStart', () => {
Nprogress.start();
});
Router.events.on('routeChangeComplete', () => {
Nprogress.done();
});
Router.events.on('routeChangeError', () => {
Nprogress.done();
});
const toggleBgNavBar = (navbar, slider) => {
if (window.scrollY > slider.clientHeight - navbar.clientHeight) {
navbar.classList.remove('bg-transparent');
} else {
navbar.classList.add('bg-transparent');
}
};
Router.events.on('routeChangeComplete', () => {
const navbar = document.querySelector('.NavBar');
const { route } = Router;
if (navbar) {
if (route === '/') {
const slider = document.querySelector('.slider');
if (window.screen.width < 560) {
navbar.style.position = 'sticky';
} else {
navbar.style.position = 'fixed';
}
toggleBgNavBar(navbar, slider);
window.onscroll = () => {
toggleBgNavBar(navbar, slider);
};
} else {
navbar.classList.remove('bg-transparent');
navbar.style.position = 'sticky';
}
}
});
class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps, query: ctx.query };
}
constructor() {
super();
this.pageContext = getPageContext();
}
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles && jssStyles.parentNode) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<Head>
<title>ShopPhone</title>
</Head>
{/* Wrap every page in Jss and Theme providers */}
<JssProvider
registry={this.pageContext.sheetsRegistry}
generateClassName={this.pageContext.generateClassName}
>
{/* MuiThemeProvider makes the theme available down the React
tree thanks to React context. */}
<MuiThemeProvider
theme={this.pageContext.theme}
sheetsManager={this.pageContext.sheetsManager}
>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
{/* Pass pageContext to the _document though the renderPage enhancer
to render collected styles on server-side. */}
<>
{this.props.router.route.indexOf('/admin') !== -1 ? (
<AdminMain>
<Component
query={this.props.query}
pageContext={this.pageContext}
{...pageProps}
/>
</AdminMain>
) : (
<Main>
<Component
query={this.props.query}
pageContext={this.pageContext}
{...pageProps}
/>
</Main>
)}
</>
</MuiThemeProvider>
</JssProvider>
</Container>
);
}
}
export default MyApp;
<file_sep>/pages/admin/index.jsx
import React, { Component } from 'react';
import Dashboard from '../../components/admin/Dashboard/Dashboard';
export class index extends Component {
render() {
return <Dashboard />;
}
}
export default index;
<file_sep>/components/Product/Pagination.jsx
import React, { Component } from 'react';
import { Fab } from '@material-ui/core';
import {
ChevronLeft,
LastPage,
FirstPage,
ChevronRight
} from '@material-ui/icons';
class Pagination extends Component {
shouldComponentUpdate(nextProps, nextState) {
return nextProps !== this.props;
}
render() {
const { currPage, lastPage, handleChangePage } = this.props;
return (
<div>
{currPage > 1 && (
<>
<a href="#content" key="firstPage">
<Fab
onClick={handleChangePage(1)}
size="small"
style={{ margin: 5 }}
>
<FirstPage />
</Fab>
</a>
<a key="prevPage" href="#content">
<Fab
onClick={handleChangePage(currPage - 1)}
size="small"
style={{ margin: 5 }}
color={'default'}
>
<ChevronLeft />
</Fab>
</a>
</>
)}
{currPage > 2 && (
<Fab
key={'hiddenPageLeft'}
size="small"
title={`1 - ${currPage - 2}`}
style={{ margin: 5, boxShadow: 'none' }}
>
{'...'}
</Fab>
)}
{[currPage - 1, currPage, currPage + 1].map(item => {
if (item > 0 && item <= lastPage) {
return (
<a href={'#content'} key={item}>
<Fab
onClick={handleChangePage(item)}
size="small"
style={{ margin: 5, boxShadow: 'none' }}
color={currPage === item ? 'primary' : 'default'}
>
{item}
</Fab>
</a>
);
}
})}
{currPage + 1 < lastPage && (
<Fab
key={'hiddenPageRight'}
title={`${currPage + 2} - ${lastPage}`}
size="small"
style={{ margin: 5, boxShadow: 'none' }}
>
{'...'}
</Fab>
)}
{currPage < lastPage && (
<>
<a href="#content" key="nextPage">
<Fab
onClick={handleChangePage(currPage + 1)}
size="small"
style={{ margin: 5 }}
>
<ChevronRight />
</Fab>
</a>
<a href="#content" key="lastPage">
<Fab
onClick={handleChangePage(lastPage)}
size="small"
style={{ margin: 5 }}
>
<LastPage />
</Fab>
</a>
</>
)}
</div>
);
}
}
export default Pagination;
<file_sep>/components/admin/Dashboard/Overview.jsx
import React, { Component } from 'react';
import Axios from 'axios';
import { Paper, Grid } from '@material-ui/core';
import {
MonetizationOn,
Store,
ListAlt,
FeaturedPlayList,
People,
Inbox
} from '@material-ui/icons';
export class Overview extends Component {
state = {
statistical: ''
};
async componentDidMount() {
const statistical = await Axios.get('/api/dashboard');
this.setState({ statistical: statistical.data });
}
render() {
const cards = [
{
cardColor: '#f86c6b',
cardTitle: 'Total Revenue ($)',
cardDescription: `$${this.state.statistical.totalRevenue}`,
cardIcon: () => (
<MonetizationOn
style={{ fontSize: 70, color: '#ffffff80' }}
color="inherit"
/>
)
},
{
cardColor: 'rgb(79, 141, 255)',
cardTitle: 'Total Products',
cardDescription: this.state.statistical.totalProducts,
cardIcon: () => (
<Store style={{ fontSize: 70, color: '#ffffff80' }} color="inherit" />
)
},
{
cardColor: 'rgb(126, 79, 202)',
cardTitle: 'Total Bills',
cardDescription: this.state.statistical.totalBills,
cardIcon: () => (
<ListAlt
style={{ fontSize: 70, color: '#ffffff80' }}
color="inherit"
/>
)
},
{
cardColor: 'rgb(64, 138, 45)',
cardTitle: 'Total Categories',
cardDescription: this.state.statistical.totalCategories,
cardIcon: () => (
<FeaturedPlayList
style={{ fontSize: 70, color: '#ffffff80' }}
color="inherit"
/>
)
},
{
cardColor: 'rgb(88, 98, 171)',
cardTitle: 'Total Users',
cardDescription: this.state.statistical.totalUsers,
cardIcon: () => (
<People
style={{ fontSize: 70, color: '#ffffff80' }}
color="inherit"
/>
)
},
{
cardColor: 'rgb(39, 39, 39)',
cardTitle: 'Total Sold Products',
cardDescription: this.state.statistical.totalSoldProducts,
cardIcon: () => (
<Inbox style={{ fontSize: 70, color: '#ffffff80' }} color="inherit" />
)
}
];
return (
<div>
{this.state.statistical ? (
<Grid container spacing={16}>
{cards &&
cards.map(card => (
<Grid
key={card.cardTitle}
item
xs={'auto'}
style={{ minWidth: '270px' }}
lg={3}
md={3}
sm={12}
>
<Paper style={{ padding: 10, background: card.cardColor }}>
<Grid container spacing={16}>
<Grid item xs={8}>
<div
style={{
color: 'white',
fontSize: 30,
textShadow: '0 0 5px white'
}}
>
{card.cardDescription}
</div>
</Grid>
<Grid item xs={4}>
{card.cardIcon()}
</Grid>
<Grid item xs={8}>
<b style={{ color: 'white' }}>{card.cardTitle}</b>
</Grid>
</Grid>
</Paper>
</Grid>
))}
</Grid>
) : (
<div className="loading-text">Loading...</div>
)}
</div>
);
}
}
export default Overview;
<file_sep>/server/models/tokenResetPassword.model.js
const mongoose = require('mongoose');
const tokenSchema = new mongoose.Schema({
token: String,
expired: Date,
user: String
});
const TokensResetPassword = mongoose.model(
'TokensResetPassword',
tokenSchema,
'TokensResetPassword'
);
module.exports = TokensResetPassword;
<file_sep>/server/controllers/user.controller.js
/* eslint-disable */
const Users = require('../models/user.model');
const Producers = require('../models/producers.model');
const Products = require('../models/products.model');
module.exports.index = async (req, res) => {
const { id } = req.params;
const user = await Users.findById(id);
const products = await Products.find();
const producers = await Producers.find();
if (user) {
res.render('user/index', {
user,
products,
producers,
});
} else {
res.send(`False to get user ${id}, User are not exist!`);
}
};
module.exports.signup = async (req, res) => {
res.render('user/signup');
};
module.exports.login = (req, res) => {
res.render('user/login');
};
module.exports.postLogin = async (req, res) => {
const { password, email } = req.body;
const producers = await Producers.find();
const user = await Users.findOne({ user_email: email, user_password: <PASSWORD> });
if (user) {
if (!user.user_status) {
const err = 'Account is Blocked';
res.render('user/login', {
err,
password,
email,
});
} else {
res.render('user/index', {
producers,
user,
});
}
} else {
const err = 'Account incorrect';
res.render('user/login', {
err,
password,
email,
});
}
};
function validateEmail(email) {
return email.indexOf('@') !== -1;
}
module.exports.postSignup = async (req, res) => {
const users = await Users.find();
const reqUser = req.body;
const isDuplicatedEmail = false;
let isEmail = false;
let foundUser = users.find(user => user.user_email === reqUser.user_email);
if (foundUser) {
isDuplicatedEmail = true;
}
if (validateEmail(reqUser.user_email)) {
isEmail = true;
}
if (isDuplicatedEmail || !isEmail) {
res.render('user/signup', { error: 'Fail to sign up, please try again' });
} else {
const obj = {
user_name: reqUser.user_name,
user_phone: reqUser.user_phone,
user_email: reqUser.user_email,
user_password: <PASSWORD>,
user_group: 'client',
user_permission: {
product: false,
user: false,
bill: false,
category: false,
},
user_status: true,
};
await Users.insertMany(obj);
res.redirect('/user/login');
}
};
<file_sep>/store/reducer/userReducer.js
const initialState = {
users: [],
getError: null,
createError: null,
deleteError: null,
editError: null,
numDeleted: null
};
export default (state = initialState, { type, users, err, numDeleted }) => {
switch (type) {
case 'GET_USER_REQUEST':
return { ...state, users: users, getError: null };
case 'GET_USER_SUCCESS':
return { ...state, users: users, getError: null };
case 'GET_USER_ERROR':
return { ...state, getError: err };
case 'CREATE_USER_SUCCESS':
return { ...state, createError: null };
case 'CREATE_USER_ERROR':
return { ...state, createError: err };
case 'DELETE_USER_SUCCESS':
return { ...state, numDeleted: numDeleted, deleteError: null };
case 'DELETE_USER_ERROR':
return { ...state, deleteError: err };
case 'CLOSE_ALERT_DELETED':
return { ...state, numDeleted: null };
case 'EDIT_USER_SUCCESS':
return { ...state, editError: null };
case 'EDIT_USER_ERROR':
return { ...state, editError: err };
default:
return state;
}
};
<file_sep>/server/controllers/cart.controller.js
/* eslint-disable */
const Products = require('../models/products.model');
const Producers = require('../models/producers.model');
const Cart = require('../models/cart.model');
const Bills = require('../models/bills.model');
module.exports.index = async (req, res) => {
const { id } = req.params;
const userId = id;
const cart = await Cart.find({ userId: id });
const products = await Products.find();
const producers = await Producers.find();
res.render('cart/index', {
cart,
products,
producers,
userId,
});
};
module.exports.removeCart = async (req, res) => {
const { id, userId } = req.body;
await Cart.findByIdAndDelete(id);
res.redirect(`/cart/${userId}`);
};
module.exports.addBill = async (req, res) => {
const theBill = JSON.parse(req.body.bill);
await Bills.insertMany(theBill);
await Cart.deleteMany({});
let pro = [];
for (let i = 0; i < theBill.details.proId.length; i += 1) {
const proId = theBill.details.proId[i];
const proQua = theBill.details.proQuantity[i];
const obj = { proId, proQua };
pro.push(obj);
}
pro.forEach(async p => {
// find() return an array
const curr = await Products.find({ product_id: p.proId });
const newQua = curr[0].quantity - p.proQua;
await Products.findOneAndUpdate({ product_id: p.proId }, { quantity: newQua });
});
res.redirect(`/bill/${theBill.authId}`);
};
<file_sep>/components/admin/user/EditUser.js
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import {
TextField,
Button,
MenuItem,
FormControl,
InputLabel,
Select,
CircularProgress,
Grid,
Input,
Checkbox
} from '@material-ui/core';
import { editUser, getUsersWithRedux } from '../../../store/action/userAction';
import { connect } from 'react-redux';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
import Link from 'next/link';
const styles = () => ({
textField: {
margin: 10,
width: 400
},
formTitle: {
color: '#4445'
},
bgWhite: {
color: 'white'
},
root: {
backgroundColor: 'white',
// minHeight: "100%",
borderRadius: '7px',
padding: 20
}
});
class EditUser extends Component {
state = {
_id: '',
user_name: '',
user_password: '',
user_group: '',
user_phone: '',
user_email: '',
onLoading: '',
message: '',
user_permission: {
product: false,
user: false,
bill: false,
category: false
},
user_status: true,
open: false,
user: {}
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
checkedCheckBox = () => {
const permiss = window.document.getElementsByName('user_permission');
for (let i = 0; i < permiss.length; i++) {
permiss[i].checked = '';
}
};
validated__input = (stateValue, regex, inputName, setError) => {
const value = stateValue;
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input) {
return false;
}
if (!regex.exec(value)) {
input.focus();
input.click();
return false;
}
if (regex.exec(value)[0] !== regex.exec(value).input) {
input.focus();
return false;
}
if (setError) this.setState({ err: { [setError.key]: false } });
return true;
};
valudated__form = () => {
if (
!this.validated__input(
this.state.user_name,
/[\w\s-]{1,}/,
'user_name'
) ||
!this.validated__input(
this.state.user_phone,
/[0-9]{10,12}/,
'user_phone'
) ||
!this.validated__input(
this.state.user_group,
/[\w]{1,20}/,
'user_group',
'errSelection'
) ||
!this.validated__input(
this.state.user_email,
/^[a-z][a-z0-9_.]{5,32}@[a-z0-9]{2,}(\.[a-z0-9]{2,4}){1,2}$/,
'user_email'
)
) {
return false;
}
return true;
};
// submit edit
handleSubmit = async e => {
this.setState({ onLoading: true });
e.preventDefault();
if (!this.valudated__form()) return;
await this.props.editUser(this.state);
if (!this.props.editError) {
this.setState({
open: true,
message: `Edit ${this.state.user_email} success`
});
} else {
alert('Permission Denied!');
window.location = '/admin';
}
this.setState({ onLoading: false });
};
async componentDidMount() {
await this.props.getUsersWithRedux();
if (this.props.haveUser) {
const u = this.props.user;
this.setState({
user_name: u.user_name,
user_password: <PASSWORD>,
user_group: u.user_group,
user_phone: u.user_phone,
user_email: u.user_email,
_id: u._id,
user_permission: u.user_permission,
user_status: u.user_status
});
}
}
handleSelectPermission = event => {
this.setState({
user_permission: {
...this.state.user_permission,
[event.target.name]: event.target.checked
}
});
};
handleSelectUserStatus = event => {
this.setState({
user_status: event.target.checked
});
};
render() {
const { classes } = this.props;
return (
<div className="admin-content fadeIn">
<h2 className={classes.formTitle}>
Edit User
<Link href="/admin/user">
<a style={{ marginLeft: 200 }}>
<Button variant="contained" color="default">
Back
</Button>
</a>
</Link>
</h2>
{this.props.haveUser ? (
<Grid container>
<Grid item xs={6}>
<form
id="addNewUser"
autoComplete="off"
onSubmit={this.handleSubmit}
>
{/* User Name */}
<TextField
required
name="user_name"
label="User Name"
value={this.state.user_name}
className={classes.textField}
onChange={this.handleChange}
/>
<br />
<Button
variant="contained"
color="primary"
onClick={() => {
this.setState({
...this.state,
user_password: '<PASSWORD>'
});
}}
>
RESET PASSWORD
</Button>
<br />
{/* Phone */}
<TextField
required
value={this.state.user_phone}
name="user_phone"
label="Phone"
className={classes.textField}
onChange={this.handleChange}
type="number"
/>
<br />
{/* Group */}
<FormControl className={classes.textField}>
<InputLabel htmlFor="user_group-select">Group</InputLabel>
<Select
required
value={this.state.user_group}
onChange={this.handleChange}
name="user_group"
renderValue={value => value}
input={<Input id="user_group-select" />}
>
<MenuItem value="admin">Admin</MenuItem>
<MenuItem value="client">Client</MenuItem>
</Select>
</FormControl>
<br />
{/* permission */}
{this.state.user_group === 'admin' ? (
<>
<p style={{ color: 'gray', fontSize: '13px' }}>
Choose permission manager:
</p>
<Checkbox
checked={this.state.user_permission.bill}
onChange={this.handleSelectPermission}
name="bill"
/>
Bill
<Checkbox
checked={this.state.user_permission.user}
onChange={this.handleSelectPermission}
name="user"
/>
User
<Checkbox
checked={this.state.user_permission.product}
onChange={this.handleSelectPermission}
name="product"
/>
Product
<Checkbox
checked={this.state.user_permission.category}
onChange={this.handleSelectPermission}
name="category"
/>
Category
</>
) : null}
{/* Email */}
<TextField
required
value={this.state.user_email}
name="user_email"
label="Email"
className={classes.textField}
onChange={this.handleChange}
type="email"
/>
<br />
{/* user status */}
Status :
<Checkbox
checked={this.state.user_status}
onChange={this.handleSelectUserStatus}
/>
{this.props.editError && (
<h4 style={{ color: 'red' }}>{this.props.editError}</h4>
)}
</form>
{this.state.onLoading ? (
<Button variant="contained" color="primary">
<CircularProgress size={24} className={classes.bgWhite} />
</Button>
) : (
<Button
variant="contained"
color="primary"
form="addNewUser"
type="submit"
>
Edit
</Button>
)}
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</Grid>
</Grid>
) : (
<h1>Not have this user.</h1>
)}
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
const { id } = ownProps;
const users = state.user.users;
let user = null;
let haveUser = false;
if (users) {
if (users.data) {
user = users.data.find(u => u._id === id);
if (user) {
haveUser = true;
}
}
}
return {
user: user,
haveUser,
editError: state.user.editError
};
};
const mapDispatchToProps = dispatch => {
return {
editUser: user => dispatch(editUser(user)),
getUsersWithRedux: () => dispatch(getUsersWithRedux())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(EditUser)
);
<file_sep>/store/action/userAction.js
import Axios from 'axios';
import checkAdmin from './checkAdmin';
export function getUsersWithRedux() {
return async dispatch => {
dispatch({ type: 'GET_USER_REQUEST' });
const res = await Axios('/api/users/');
return dispatch({ type: 'GET_USER_SUCCESS', users: res.data });
};
}
export const createUser = user => {
return async (dispatch, getState) => {
const isAdmin = await checkAdmin();
if (!isAdmin) {
return dispatch({ type: 'CREATE_USER_ERROR', err: 'Permision Denied' });
}
try {
// adding user
const res = await Axios.post('/api/users/', user);
if (res.data.err)
return dispatch({ type: 'CREATE_USER_ERROR', err: res.data.err });
return dispatch({ type: 'CREATE_USER_SUCCESS' });
} catch (err) {
return dispatch({ type: 'CREATE_USER_ERROR', err: err.message });
}
};
};
export const deleteUsers = users => {
return async (dispatch, getState) => {
const isAdmin = await checkAdmin();
if (!isAdmin) {
return dispatch({ type: 'DELETE_USER_ERROR', err: 'Permision Denied' });
}
try {
let del = [];
let err = [];
users.forEach(user => {
del.push(Axios.delete(`/api/users/${user}`));
});
del = await Promise.all(del);
del.forEach(item => {
if (item.data.err) {
err.push(item.data.err);
}
});
if (err[0]) {
return dispatch({ type: 'DELETE_USER_ERROR', err: err });
}
return dispatch({
type: 'DELETE_USER_SUCCESS',
numDeleted: users.length
});
} catch (err) {
return dispatch({ type: 'DELETE_USER_ERROR', err: err.message });
}
};
};
export const closeAlertDeleted = () => {
return dispatch => {
return dispatch({ type: 'CLOSE_ALERT_DELETED' });
};
};
export const editUser = user => {
return async dispatch => {
const isAdmin = await checkAdmin();
if (!isAdmin) {
return dispatch({ type: 'EDIT_USER_ERROR', err: 'Permision Denied' });
}
try {
const promiseData = await Axios.put(`/api/users/${user._id}`, user);
if (promiseData.data.err) {
return dispatch({ type: 'EDIT_USER_ERROR', err: promiseData.data.err });
}
return dispatch({ type: 'EDIT_USER_SUCCESS' });
} catch (err) {
return dispatch({ type: 'EDIT_USER_ERROR', err: err.message });
}
};
};
<file_sep>/components/admin/category/AddCategory.jsx
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { TextField, Button, CircularProgress } from '@material-ui/core';
import {
createCategory,
getCategoriesWithRedux
} from '../../../store/action/categoryAction';
import { connect } from 'react-redux';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
const styles = () => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
textField: {
margin: 10,
width: 200
},
dense: {
marginTop: 19
},
menu: {
width: 200
},
formTitle: {
color: '#4445'
},
bgWhite: {
color: 'white'
}
});
class AddCategory extends Component {
state = {
producer_name: '',
producer_id: '',
isAdding: false,
message: '',
open: false,
validateError: false
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
validated__input = (stateValue, regex, inputName, setError) => {
const value = stateValue;
const input = document.getElementsByName(inputName)[0];
if (!input) {
return false;
}
if (!regex.test(value)) {
input.focus();
this.setState({ validateError: 'Please complete this field' });
return false;
}
this.setState({ validateError: '' });
return true;
};
valudated__form = () => {
if (
!this.validated__input(
this.state.producer_name,
/[\w\s-]{1,}/,
'producer_name'
) ||
!this.validated__input(
this.state.producer_id,
/^[A-Z]{1,}$/,
'producer_id'
)
) {
return false;
}
return true;
};
handleSubmit = async e => {
this.setState({ isAdding: true });
e.preventDefault();
if (!this.valudated__form()) {
this.setState({ isAdding: false });
return;
}
await this.props.createCategory(this.state);
if (!this.props.createError) {
this.props.getCategoriesWithRedux();
this.setState({
open: true,
message: `Adding ${this.state.producer_id} success`
});
} else if (this.props.createError === 'Permision Denied') {
alert('Permission Denied!');
window.location = '/admin';
}
this.setState({ isAdding: false });
};
render() {
const { classes } = this.props;
return (
<>
<h2 className={classes.formTitle}>Add new Category</h2>
<form
encType="multipart/form-data"
id="addNewCategory"
className={classes.container}
noValidate
autoComplete="off"
onSubmit={this.handleSubmit}
>
{/* Category Name */}
<TextField
required
name="producer_name"
label="Category Name"
className={classes.textField}
onChange={this.handleChange}
helperText="Not special character"
/>
{/* ID */}
<TextField
required
name="producer_id"
label="ID"
className={classes.textField}
onChange={this.handleChange}
helperText="Uppercase Only"
/>
</form>
{this.props.createError && (
<p style={{ color: 'red' }}>{this.props.createError}</p>
)}
{this.state.validateError && (
<p style={{ color: 'red' }}>{this.state.validateError}</p>
)}
<Button
variant="contained"
color="primary"
form="addNewCategory"
type="submit"
>
{this.state.isAdding ? (
<CircularProgress size={24} className={classes.bgWhite} />
) : (
<span>Add New Category</span>
)}
</Button>
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</>
);
}
}
const mapStateToProps = state => {
return {
createError: state.category.createError
};
};
const mapDispatchToProps = dispatch => {
return {
createCategory: category => dispatch(createCategory(category)),
getCategoriesWithRedux: () => dispatch(getCategoriesWithRedux())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(AddCategory)
);
<file_sep>/server/controllers/product.controller.js
const Products = require('../models/products.model');
const Producers = require('../models/producers.model');
const Cart = require('../models/cart.model');
module.exports.index = async (req, res) => {
const proId = req.params.id;
const product = await Products.findById(proId);
const producers = await Producers.find();
res.render('product/index', {
product,
producers,
});
};
module.exports.postAddToCart = async (req, res) => {
const reqBody = await req.body;
const cart = await Cart.find({ proId: reqBody.proId, userId: reqBody.userId });
if (cart[0]) {
const newQua = parseInt(reqBody.quantity, 10) + cart[0].quantity;
await Cart.findOneAndUpdate({ proId: reqBody.proId }, { quantity: newQua });
} else {
await Cart.insertMany(reqBody);
}
res.redirect(`/cart/${reqBody.userId}`);
};
<file_sep>/components/CategoryList.jsx
import React from 'react';
import Link from 'next/link';
import { Divider } from '@material-ui/core';
class CategoryList extends React.Component {
state = {
anchorEl: null,
categories: []
};
render() {
const { category } = this.props.selectedCategory;
return (
<div>
<h1 className="header">Categories</h1>
<div className="divider" />
<div className="CategoryList">
{this.props.categories && (
<>
{this.props.categories.map(item => (
<Link
key={item._id}
href={`/?category=${item.producer_id}#content`}
>
<a>
<div
data-aos="fade-up"
className={
category === item.producer_id ? 'item active' : 'item'
}
>
{item.producer_name}
</div>
</a>
</Link>
))}
</>
)}
</div>
</div>
);
}
}
export default CategoryList;
<file_sep>/pages/bill.jsx
import React, { Component } from 'react';
import Bill from '../components/Bill/Bill';
export class bill extends Component {
render() {
return <Bill/>;
}
}
export default bill;
<file_sep>/components/Auth/SignIn.jsx
import React from 'react';
import PropTypes from 'prop-types';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import FormControl from '@material-ui/core/FormControl';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import withStyles from '@material-ui/core/styles/withStyles';
import Axios from 'axios';
import Router from 'next/router';
import ShopContext from '../../context/shop-context';
import SignInStyle from './SignIn.styles';
import {
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
DialogActions,
TextField,
InputAdornment,
IconButton
} from '@material-ui/core';
import { Visibility, VisibilityOff } from '@material-ui/icons';
const styles = SignInStyle;
class SignIn extends React.Component {
static contextType = ShopContext;
state = {
user_email: '',
user_password: '',
signInError: '',
isOpenForgotPassword: false,
isSendingMail: false,
emailForgotPassword: '',
sendMailMess: '',
showPassword: false
};
async componentDidMount() {
await this.context.checkLogin();
if (this.context.auth.auth_key) Router.push('/');
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClickForgotPassword = () => {
this.setState({ isOpenForgotPassword: true });
};
handleCloseForgotPassword = () => {
this.setState({ isOpenForgotPassword: false, sendMailMess: '' });
};
handleSubmitForgotPassword = async e => {
e.preventDefault();
this.setState({ isSendingMail: true });
const sendMail = await Axios.post('/api/users/forgotPassword', {
user_email: this.state.emailForgotPassword
});
if (sendMail.data.err) {
this.setState({ sendMailMess: sendMail.data.err });
} else {
this.setState({ sendMailMess: 'Success! Let check your mail!' });
}
this.setState({ isSendingMail: false });
};
handleClickShowPassword = () => {
this.setState({ showPassword: !this.state.showPassword });
};
handleSubmit = async e => {
this.setState({ onLoading: true });
e.preventDefault();
const signin = await Axios.post('/api/users/signinClient', {
user_email: this.state.user_email,
user_password: <PASSWORD>
});
if (signin.data.err) {
this.setState({ signInError: signin.data.err });
} else {
this.setState({ signInError: '' });
const obj = {
auth_name: signin.data.user.user_name,
auth_key: signin.data.user._id
};
window.sessionStorage.setItem('auth', JSON.stringify(obj));
Router.push('/');
}
this.setState({ onLoading: false });
};
render() {
const { classes } = this.props;
return (
<main className={classes.main}>
<CssBaseline />
<Paper className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form
className={classes.form}
onSubmit={this.handleSubmit}
id="signIn"
>
<FormControl margin="normal" required fullWidth>
<InputLabel htmlFor="user_email">Email Address</InputLabel>
<Input
type="email"
id="user_email"
name="user_email"
value={this.state.user_email}
onChange={this.handleChange}
/>
</FormControl>
<FormControl margin="normal" required fullWidth>
<InputLabel htmlFor="user_password">Password</InputLabel>
<Input
type={!this.state.showPassword ? 'password' : 'text'}
id="user_password"
name="user_password"
value={this.state.user_password}
onChange={this.handleChange}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="Toggle password visibility"
onClick={this.handleClickShowPassword}
>
{this.state.showPassword ? (
<Visibility />
) : (
<VisibilityOff />
)}
</IconButton>
</InputAdornment>
}
/>
</FormControl>
<p
onClick={this.handleClickForgotPassword}
style={{ textAlign: 'center', cursor: 'pointer' }}
>
<a>Forgot password?</a>
</p>
<b style={{ color: 'red' }}>{this.state.signInError}</b>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
form="signIn"
>
Sign in
</Button>
</form>
{/* dialog for forgot password */}
<Dialog
open={this.state.isOpenForgotPassword}
onClose={this.handleCloseForgotPassword}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
{
<>
{this.state.sendMailMess ? (
<h3 style={{ color: 'gray', padding: '0 20px' }}>
{this.state.sendMailMess}
</h3>
) : (
<>
{this.state.isSendingMail ? (
<h3 style={{ color: 'gray', padding: '0 20px' }}>
Sending...
</h3>
) : (
<form
onSubmit={this.handleSubmitForgotPassword}
id="formForgotPassword"
>
<DialogTitle id="alert-dialog-title">
Forgot Password
</DialogTitle>
<DialogContent>
<TextField
label="Your email"
required
type="email"
onChange={this.handleChange}
style={{ width: '100%' }}
name="emailForgotPassword"
/>
<DialogContentText id="alert-dialog-description">
We will send the link for reset password to your
email
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
onClick={this.handleCloseForgotPassword}
color="primary"
>
Disagree
</Button>
<Button
color="primary"
type="submit"
form="formForgotPassword"
>
Agree
</Button>
</DialogActions>
</form>
)}
</>
)}
</>
}
</Dialog>
</Paper>
</main>
);
}
}
SignIn.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(SignIn);
<file_sep>/components/Product/SearchForm.jsx
import React, { Component } from 'react';
import { TextField, MenuItem, Select, Button } from '@material-ui/core';
export class SearchForm extends Component {
state = {
searchByPriceTo: '',
searchByPriceFrom: '',
searchByName: '',
searchByCategory: '',
sortByName: '',
sortByPrice: ''
};
handleReset = () => {
this.setState({
searchByPriceTo: '',
searchByPriceFrom: '',
searchByName: '',
searchByCategory: '',
sortByName: '',
sortByPrice: ''
});
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmitSearch = e => {
e.preventDefault();
const query = {
product_price: {
from: parseInt(this.state.searchByPriceFrom, 10),
to: parseInt(this.state.searchByPriceTo, 10)
},
product_name: this.state.searchByName,
producer: this.state.searchByCategory,
sortByPrice: this.state.sortByPrice,
sortByName: this.state.sortByName
};
this.props.renderSearchResult(query);
};
render() {
return (
<>
<style jsx>{`
.search-form {
background: #fff;
display: flex;
flex-wrap: wrap;
align-items: flex-end;
justify-content: center;
}
.search-form * {
margin: 3px;
}
`}</style>
<form onSubmit={this.handleSubmitSearch} className="search-form">
{/* Search by name */}
<div>
<div>Search by Name</div>
<TextField
onChange={this.handleChange}
label="Search by name"
name="searchByName"
/>
</div>
{/* Search by price */}
<div>
<div>Search by Price</div>
<TextField
label="From"
name="searchByPriceFrom"
onChange={this.handleChange}
style={{ width: 100 }}
/>
<TextField
label="To"
name="searchByPriceTo"
onChange={this.handleChange}
style={{ width: 100 }}
/>
</div>
<br />
{/* Select Category */}
<div>
<div>Category</div>
<br />
<Select
style={{ width: 150 }}
value={this.state.searchByCategory}
onChange={this.handleChange}
inputProps={{
name: 'searchByCategory'
}}
>
<MenuItem value="">All</MenuItem>
{this.props.categories &&
this.props.categories.map((item, index) => (
<MenuItem key={index} value={item.producer_name}>
{item.producer_name}
</MenuItem>
))}
</Select>
</div>
{/* Sort by Price */}
<div>
<div>Sort by Price</div>
<br />
<Select
style={{ width: 150 }}
value={this.state.sortByPrice}
onChange={this.handleChange}
inputProps={{
name: 'sortByPrice'
}}
>
<MenuItem value="">All</MenuItem>
<MenuItem value="Asc">Asc</MenuItem>
<MenuItem value="Desc">Desc</MenuItem>
</Select>
</div>
{/* Sort by Name */}
<div>
<div>Sort by Name</div>
<br />
<Select
style={{ width: 150 }}
value={this.state.sortByName}
onChange={this.handleChange}
inputProps={{
name: 'sortByName'
}}
>
<MenuItem value="">All</MenuItem>
<MenuItem value="A-Z">A-Z</MenuItem>
<MenuItem value="Z-A">Z-A</MenuItem>
</Select>
</div>
{/* reset */}
<Button onClick={this.handleReset} type="reset">
reset
</Button>
{/* Filter */}
<Button type="submit" variant="contained" color="primary">
Filter
</Button>
</form>
</>
);
}
}
export default SearchForm;
<file_sep>/components/admin/product/EditProduct.jsx
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import {
TextField,
Button,
MenuItem,
FormControl,
InputLabel,
Select,
CircularProgress,
Grid,
Input
} from '@material-ui/core';
import {
editProduct,
getProductsAndCategories
} from '../../../store/action/productAction';
import { connect } from 'react-redux';
import Link from 'next/link';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
const styles = () => ({
textField: {
margin: 10,
width: 400
},
formTitle: {
color: '#4445'
},
bgWhite: {
color: 'white'
},
root: {
backgroundColor: 'white',
borderRadius: '7px',
padding: 20
}
});
class EditProduct extends Component {
state = {
_id: '',
product_name: '',
product_price: 1,
producer: '',
quantity: 1,
product_img: null,
product_img_path: '',
onLoading: false,
message: '',
open: false,
product: {},
stateImgPath: '',
validateError: false
};
handleChangeFile = e => {
this.setState({
product_img: e.target.files[0],
product_img_path: e.target.files[0] ? e.target.files[0].name : null
});
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
validated__input = (stateValue, regex, inputName, setError) => {
const value = stateValue;
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input) {
return false;
}
if (!regex.test(value)) {
input.focus();
this.setState({
err: { [setError]: true },
validateError: 'Please complete this field'
});
return false;
}
if (setError)
this.setState({ err: { [setError.key]: false }, validateError: '' });
return true;
};
validated__input_file = (inputName, setError) => {
const input = document.getElementsByName(inputName)[0];
if (setError) this.setState({ err: { [setError]: true } });
if (!input || !input.value) {
input.click();
return false;
}
if (setError) this.setState({ err: { [setError.key]: false } });
return true;
};
valudated__form = () => {
if (
!this.validated__input(
this.state.product_name,
/[\w\s-]{1,}/,
'product_name'
) ||
!this.validated__input(
this.state.product_price,
/^[0-9]{1,5}$/,
'product_price'
) ||
!this.validated__input(this.state.quantity, /^[0-9]{1,5}$/, 'quantity') ||
!this.validated__input(
this.state.producer,
/[\w]{1,20}/,
'producer',
'errSelection'
)
) {
return false;
}
return true;
};
// submit edit
handleSubmit = async e => {
const { editProduct } = this.props;
e.preventDefault();
if (!this.valudated__form()) {
return;
}
this.setState({ onLoading: true });
await editProduct(this.state);
if (!this.props.editError) {
this.setState({
...this.state,
onLoading: false,
open: true,
message: `Edit ${this.state.product_name} success`,
stateImgPath: this.state.product_img_path
? `/static/uploads/${this.state.product_img_path.trim()}`
: `${this.state.stateImgPath}`
});
} else {
alert('Permission Denied!');
window.location = '/admin';
this.setState({
...this.state,
onLoading: false,
message: this.props.editError
});
}
};
async componentDidMount() {
await this.props.getProductsAndCategories();
if (this.props.haveProduct) {
const pro = this.props.product;
const producer = this.props.categories.find(
item => item.producer_name === pro.producer
);
this.setState({
product_name: pro.product_name,
product_price: pro.product_price,
producer: producer.producer_id,
quantity: pro.quantity,
_id: pro._id,
stateImgPath: `/static${pro.product_img}`
});
}
}
render() {
const { classes } = this.props;
return (
<div className="admin-content fadeIn">
<h2 className={classes.formTitle}>
Edit Product
<Link href="/admin/product">
<a style={{ marginLeft: 200 }}>
<Button variant="contained" color="default">
Back
</Button>
</a>
</Link>
</h2>
{this.props.haveProduct ? (
<Grid container>
<Grid item xs={6}>
<form
noValidate
id="addNewProduct"
autoComplete="off"
onSubmit={this.handleSubmit}
>
{/* Product Name */}
<TextField
required
name="product_name"
label="Product Name"
value={this.state.product_name}
className={classes.textField}
onChange={this.handleChange}
/>
<br />
{/* Product Price */}
<TextField
required
name="product_price"
label="Price ($)"
className={classes.textField}
onChange={this.handleChange}
value={this.state.product_price}
type="number"
min={1}
/>
<br />
{/* Quantity */}
<TextField
required
value={this.state.quantity}
name="quantity"
label="Quantity"
className={classes.textField}
onChange={this.handleChange}
type="number"
/>
<br />
{/* Producer - Catefory */}
<FormControl className={classes.textField}>
<InputLabel htmlFor="producer-select">Category</InputLabel>
<Select
required
value={this.state.producer}
onChange={this.handleChange}
name="producer"
renderValue={value => value}
input={<Input id="producer-select" />}
>
{this.props.categories &&
this.props.categories.map((item, index) => (
<MenuItem key={index} value={item.producer_id}>
{item.producer_name}
</MenuItem>
))}
</Select>
</FormControl>
<br />
{/* Input img */}
<TextField
accept="image/*"
name="product_img"
className="hidden"
onChange={this.handleChangeFile}
type="file"
id="contained-button-file"
/>
<label htmlFor="contained-button-file">
<Button variant="contained" component="span">
Upload Image
</Button>
</label>
<br />
<br />
{this.props.createError && (
<p style={{ color: 'red' }}>{this.props.createError}</p>
)}
{this.state.validateError && (
<p style={{ color: 'red' }}>{this.state.validateError}</p>
)}
</form>
{this.state.onLoading ? (
<Button variant="contained" color="primary">
<CircularProgress size={24} className={classes.bgWhite} />
</Button>
) : (
<Button
variant="contained"
color="primary"
form="addNewProduct"
type="submit"
>
Edit
</Button>
)}
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</Grid>
<Grid item xs={6}>
<img
alt="product image"
src={this.state.stateImgPath}
width="310"
/>
</Grid>
</Grid>
) : (
<h1>Not have this product.</h1>
)}
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
const { id } = ownProps;
const { products } = state.product;
let product = null;
let haveProduct = false;
if (products) {
if (products.data) {
product = products.data.find(pro => pro._id === id);
if (product) {
haveProduct = true;
}
}
}
return {
product: product,
haveProduct,
editError: state.product.editError,
categories: state.product.categories.data
};
};
const mapDispatchToProps = dispatch => {
return {
editProduct: product => dispatch(editProduct(product)),
getProductsAndCategories: () => dispatch(getProductsAndCategories())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(EditProduct)
);
<file_sep>/components/Cart/Cart.jsx
import React, { Component } from 'react';
import Link from 'next/link';
import Axios from 'axios';
import {
Paper,
Table,
TableHead,
TableRow,
TableCell,
TableBody,
Button,
Divider,
withStyles
} from '@material-ui/core';
import ShopContext from '../../context/shop-context';
import CartItem from './CartItem';
import CartStyles from './Cart.styles.jss';
import Payment from '../Payment/Payment';
import moment from 'moment';
const styles = CartStyles;
class Cart extends Component {
static contextType = ShopContext;
state = {
getError: '',
carts: '',
renderPayment: false,
loading: true
};
getCarts = async userID => {
try {
const getCarts = await Axios.get(`/api/users/${userID}/carts`);
if (getCarts.data.err) this.setState({ getError: getCarts.data.err });
else {
this.setState({
carts: getCarts.data.makeupCarts
});
}
} catch (err) {
this.setState({ getError: err.message });
}
};
async componentDidMount() {
await this.context.checkLogin();
if (this.context.auth.auth_key) {
await this.getCarts(this.context.auth.auth_key);
this.setState({ loading: false });
} else {
this.setState({ getError: 'You must to Login first!' });
}
}
handleClickCheckout = async () => {
try {
let products = await Axios.get('/api/products');
products = products.data.data;
for (let i = 0; i < this.state.carts.length; i++) {
const proId = this.state.carts[i].cartItem.proId;
const proQuantity = this.state.carts[i].cartItem.quantity;
const product = products.find(p => p.product_id === proId);
if (product.quantity < proQuantity) {
alert(`Product ${product.product_name} is out of stock!`);
} else {
this.setState({ renderPayment: true });
}
}
} catch (err) {
console.log(err);
}
};
handleDelete = id => async () => {
try {
const deleteCart = await Axios.delete('/api/carts/' + id);
if (deleteCart.data.err) alert(deleteCart.data.err);
else {
this.getCarts(this.context.auth.auth_key);
}
} catch (err) {
alert(err.message);
}
};
handleChange = e => {
const { id, value } = e.target;
const { carts } = this.state;
if (value < 1 || value > 5) {
alert('You must to buy 1 - 5 item for this product');
return;
}
carts[id].cartItem.quantity = value;
this.setState({ carts });
};
getTotalPrice = () => {
let total = 0;
this.state.carts.forEach(item => {
total += item.cartItem.quantity * item.cartItem.proPrice;
});
return total;
};
handleCheckout = async () => {
try {
let proId = [];
let proPrice = [];
let proQuantity = [];
for (let i = 0; i < this.state.carts.length; i++) {
proId.push(this.state.carts[i].cartItem.proId);
proPrice.push(this.state.carts[i].cartItem.proPrice);
proQuantity.push(this.state.carts[i].cartItem.quantity);
}
const obj = {
authId: this.context.auth.auth_key,
createAt: moment().format('MM/DD/YYYY'),
totalPrice: this.getTotalPrice(),
status: 'unpaid',
details: {
proId,
proPrice,
proQuantity
}
};
const checkout = await Axios.post('/api/bills', obj);
if (checkout.data.err) alert(checkout.data.err);
else {
alert('Check Out Success ');
this.getCarts(this.context.auth.auth_key);
this.setState({ renderPayment: false });
}
} catch (err) {
alert(err.message);
}
};
plusQuantity = id => {
console.log(id);
const { carts } = this.state;
const value = carts[id].cartItem.quantity + 1;
if (value < 1 || value > 5) {
alert('You must to buy 1 - 5 item for this product');
return;
}
carts[id].cartItem.quantity = value;
this.setState({ carts });
};
minusQuantity = id => {
const { carts } = this.state;
const value = carts[id].cartItem.quantity - 1;
if (value < 1 || value > 5) {
alert('You must to buy 1 - 5 item for this product');
return;
}
carts[id].cartItem.quantity = value;
this.setState({ carts });
};
render() {
const { classes } = this.props;
return (
<>
<style jsx global>{`
* {
scroll-behavior: smooth;
}
`}</style>
<h1 className={classes.header}>YOUR CART</h1>
<div className="divider" />
<Paper className={classes.paper + ' ' + classes.root}>
{this.state.loading ? (
<div className="loading-text">Loading...</div>
) : (
<>
{this.state.renderPayment ? (
<Payment onCheckOut={this.handleCheckout} />
) : (
<>
{this.state.carts[0] ? (
<Table>
<TableHead>
<TableRow>
<TableCell>Id</TableCell>
<TableCell>Image</TableCell>
<TableCell>Name</TableCell>
<TableCell>Quantity</TableCell>
<TableCell>Price($)</TableCell>
<TableCell>Total($)</TableCell>
<TableCell>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.carts.map((item, index) => (
<CartItem
key={index}
item={item}
onDelete={this.handleDelete}
id={index.toString()}
handleChange={this.handleChange}
plusQuantity={this.plusQuantity}
minusQuantity={this.minusQuantity}
/>
))}
<TableRow>
<TableCell colSpan={6} align="right">
<h4>SUMMARY</h4>
</TableCell>
<TableCell />
</TableRow>
<TableRow>
<TableCell colSpan={6} align="right">
Total Price :
</TableCell>
<TableCell colSpan={6}>
{this.getTotalPrice()}
</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={6} align="right">
Shipping :
</TableCell>
<TableCell colSpan={6}>$0</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={6} align="right">
Result :
</TableCell>
<TableCell colSpan={6}>
<b style={{ color: 'red' }}>
${this.getTotalPrice()}
</b>
</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={3}>
<Link href="/">
<a>
<Button
color="secondary"
style={{ display: 'block', width: '100%' }}
variant="contained"
>
Back To Shopping
</Button>
</a>
</Link>
</TableCell>
<TableCell />
<TableCell colSpan={3}>
<a href="#">
<Button
style={{ display: 'block', width: '100%' }}
variant="contained"
color="primary"
onClick={this.handleClickCheckout}
>
Check Out
</Button>
</a>
</TableCell>
</TableRow>
</TableBody>
</Table>
) : (
<>
<h3 className={classes.textGrayCenter}>
{this.state.getError ? (
<p className={classes.textError}>
{this.state.getError}
</p>
) : (
'Your cart is Empty'
)}
<Link href="/">
<a>
<Button
style={{ marginLeft: 20 }}
variant="contained"
color="primary"
>
Go To Shopping
</Button>
</a>
</Link>
</h3>
</>
)}
</>
)}
</>
)}
</Paper>
</>
);
}
}
export default withStyles(styles)(Cart);
<file_sep>/components/admin/sidebar/Sidebar.jsx
import React, { Component } from 'react';
import { List, ListItem, ListItemText } from '@material-ui/core';
import {
Store,
People,
ListAlt,
FeaturedPlayList,
Dashboard
} from '@material-ui/icons';
import Link from 'next/link';
import Router from 'next/router';
export class Sidebar extends Component {
shouldComponentUpdate(nextProps, nextState) {
return nextProps !== this.props;
}
handleSidebarClick = () => {
if (window.screen.width <= '538') {
window.document.getElementsByClassName('sidebar')[0].style.display =
'none';
window.document.getElementsByClassName('App')[0].style.marginLeft = '0';
}
};
render() {
const NavLinks = [
{
href: '/admin',
icon: <Dashboard />,
text: 'Dashboard',
hidden: false
},
{
href: '/admin/product',
icon: <Store />,
text: 'Product',
hidden: !this.props.adminPermission.product
},
{
href: '/admin/user',
icon: <People />,
text: 'User',
hidden: !this.props.adminPermission.user
},
{
href: '/admin/bill',
icon: <ListAlt />,
text: 'Bill',
hidden: !this.props.adminPermission.bill
},
{
href: '/admin/category',
icon: <FeaturedPlayList />,
text: 'Category',
hidden: !this.props.adminPermission.category
}
];
const { route } = Router;
console.log(route);
return (
<div>
<List className="sidebar">
{/* Product */}
{NavLinks[0] &&
NavLinks.map((item, i) => {
return item.hidden ? null : (
<Link href={item.href} key={i}>
<a
className={item.href === route ? 'active' : ''}
onClick={this.handleSidebarClick}
>
<ListItem button>
{item.icon}
<ListItemText
disableTypography
className="text-white"
primary={item.text}
/>
</ListItem>
</a>
</Link>
);
})}
</List>
</div>
);
}
}
export default Sidebar;
<file_sep>/components/admin/SignInAdmin.jsx
import React, { Component } from 'react';
import { Paper, TextField, Button } from '@material-ui/core';
import Axios from 'axios';
import Link from 'next/link';
class SignInAdmin extends Component {
state = {
user_email: '',
user_password: '',
loginError: ''
};
validated__input = (inputId, stateValue, regex) => {
const input = document.getElementById(inputId);
const value = stateValue;
if (regex.test(value)) {
return true;
} else {
input.focus();
input.placeholder = 'Input this Field';
this.setState({ loginError: 'This Field is Require' });
return false;
}
};
validated__form = () => {
if (
!this.validated__input(
'user_email',
this.state.user_email,
/^[a-z][a-z0-9_.]{5,32}@[a-z0-9]{2,}(\.[a-z0-9]{2,4}){1,2}$/
) ||
!this.validated__input(
'user_password',
this.state.user_password,
/^.{6,}$/
)
) {
return false;
}
return true;
};
handleChange = name => e => {
this.setState({ [name]: e.target.value });
};
handleSubmit = async e => {
e.preventDefault();
if (!this.validated__form()) {
return;
}
try {
const admin = await Axios.post('/api/users/signin', this.state);
if (admin.data.err) {
this.setState({ loginError: admin.data.err });
} else if (admin.data.adminDetails) {
const objAdmin = {
admin_name: admin.data.adminDetails.user_name,
admin_key: admin.data.adminDetails._id
};
window.sessionStorage.setItem(
'adminPageAccess',
JSON.stringify(objAdmin)
);
window.location = '/admin';
} else {
this.setState({ loginError: 'Can not handle this error' });
}
} catch (err) {
this.setState({ loginError: err.message });
}
};
render() {
return (
<div>
<Paper
elevation={1}
style={{
position: 'fixed',
transform: 'translate(-50%, -50%)',
top: '40%',
left: '50%',
padding: '20px 50px',
minHeight: '50%'
}}
>
<h2 style={{ color: 'gray' }}>
Sign In Admin
<Link href="/">
<a>
<Button
variant="contained"
color="default"
style={{ float: 'right' }}
>
Back
</Button>
</a>
</Link>
</h2>
<form
onSubmit={this.handleSubmit}
noValidate
style={{ margin: 'auto' }}
>
<TextField
style={{ width: '300px' }}
id="user_email"
margin="normal"
label="Email"
onChange={this.handleChange('user_email')}
/>
<br />
<TextField
style={{ width: '300px' }}
id="user_password"
margin="normal"
label="Password"
onChange={this.handleChange('user_password')}
type="<PASSWORD>"
/>
{/* inner error */}
<p style={{ color: 'red' }}>{this.state.loginError}</p>
<Button
color="primary"
style={{ marginTop: 10 }}
type="submit"
variant="contained"
>
Login
</Button>
</form>
</Paper>
</div>
);
}
}
export default SignInAdmin;
<file_sep>/server/models/products.model.js
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
product_img: String,
product_name: String,
product_id: Number,
product_price: Number,
producer: String,
quantity: Number,
});
const Products = mongoose.model('Products', productSchema, 'Products');
module.exports = Products;
<file_sep>/components/Product/ProductList.jsx
import React, { Component } from 'react';
import { Grid } from '@material-ui/core';
import ProductCard from './ProductCard';
import PropTypes from 'prop-types';
import Pagination from './Pagination';
export class ProductList extends Component {
state = {
productsOnPage: null,
pages: 1,
currentPage: 1
};
renderPage = products => {
this.setState({
productsOnPage: products.slice(0, 8),
pages: Math.ceil(products.length / 8),
currentPage: 1
});
};
componentDidMount() {
this.renderPage(this.props.products);
}
componentWillReceiveProps(nextProps) {
if (this.props.products !== nextProps.products)
this.renderPage(nextProps.products);
}
handleChangePage = page => () => {
if (!page) return;
const start = (page - 1) * 8;
const end = page * 8;
this.setState({
...this.state,
productsOnPage: this.props.products.slice(start, end),
currentPage: page
});
};
handleClickPrevPage = () => {
this.handleChangePage(this.state.currentPage - 1);
};
handleClickNextPage = () => {
this.handleChangePage(this.state.currentPage + 1);
};
render() {
return (
<>
<div className={'product-list__container'}>
{this.state.productsOnPage &&
this.state.productsOnPage.map(product => (
<ProductCard product={product} key={product._id} />
))}
</div>
{/* Page Buttons */}
{this.state.pages !== 1 && (
<Grid
container
justify="center"
style={{
marginTop: 30
}}
>
<Pagination
currPage={this.state.currentPage}
lastPage={this.state.pages}
handleChangePage={this.handleChangePage}
/>
</Grid>
)}
</>
);
}
}
ProductList.propTypes = {
products: PropTypes.array.isRequired
};
export default ProductList;
<file_sep>/server/controllers/admin.controller.js
const Products = require('../models/products.model');
const Producers = require('../models/producers.model');
const Users = require('../models/user.model');
const Bills = require('../models/bills.model');
module.exports.index = async (req, res) => {
const products = await Products.find();
const producers = await Producers.find();
const users = await Users.find();
const bills = await Bills.find();
res.render('admin/index', {
producers,
products,
users,
bills,
});
};
// -----------------------------> Bill
// index
module.exports.bill = async (req, res) => {
const bills = await Bills.find();
const users = await Users.find();
const products = await Products.find();
const {
page, idIsDeleted, idIsEdited, added, error,
} = req.query;
res.render('admin/bill', {
bills,
products,
users,
page,
idIsDeleted,
idIsEdited,
added,
error,
});
};
// delete
module.exports.deleteBill = async (req, res) => {
const idToDelete = req.body.id;
const billIsDeleted = await Bills.findById(idToDelete);
if (!billIsDeleted) {
res.redirect('/admin/bill?page=1');
} else {
const idIsDeleted = billIsDeleted.id;
await Bills.findByIdAndDelete(idToDelete);
res.redirect(`/admin/bill?page=1&idIsDeleted=${idIsDeleted}`);
}
};
// delete many
module.exports.deleteManyBill = async (req, res) => {
const { idToDeletes } = req.body;
const ids = idToDeletes.split(',');
const lenghtIds = ids.length;
// ids.forEach(async (id) => {
// await Bills.findByIdAndDelete(id);
// });
res.redirect(
`/admin/bill?page=1&error=There+Are+${lenghtIds}+Bills+Have+Been+Deleted!
Delete Many - Tạm thời chặn . Sợ mất hết dữ liệu thôi :))`,
);
};
// edit
module.exports.editBill = async (req, res) => {
const idToEdit = req.body.id;
const editData = req.body;
const billIsEdited = await Bills.findById(idToEdit);
const idIsEdited = billIsEdited.id;
await Bills.findByIdAndUpdate(idToEdit, {
status: editData.status,
});
res.redirect(`/admin/bill?page=1&idIsEdited=${idIsEdited}`);
};
// add
module.exports.addBill = async (req, res) => {
// check doublicate
const producer = await Producers.find({ producer_id: req.body.producer_id });
if (producer[0]) {
res.redirect(`/admin/category?page=1&error=id-${req.body.producer_id}-Has-Been-Used!`);
} else {
await Producers.insertMany(req.body);
res.redirect('/admin/category?page=1&added=1');
}
};
// -----------------------------> Category
// index
module.exports.category = async (req, res) => {
const producers = await Producers.find();
const {
page, idIsDeleted, idIsEdited, added, error,
} = req.query;
res.render('admin/category', {
producers,
page,
idIsDeleted,
idIsEdited,
added,
error,
});
};
// delete
module.exports.deleteProducer = async (req, res) => {
const idToDelete = req.body.id;
const producerIsDeleted = await Producers.findById(idToDelete);
if (!producerIsDeleted) {
res.redirect('/admin/category?page=1');
} else {
const idIsDeleted = producerIsDeleted.id;
await Producers.findByIdAndDelete(idToDelete);
res.redirect(`/admin/category?page=1&idIsDeleted=${idIsDeleted}`);
}
};
// delete many
module.exports.deleteManyCategory = async (req, res) => {
const { idToDeletes } = req.body;
const ids = idToDeletes.split(',');
const lenghtIds = ids.length;
// ids.forEach(async (id) => {
// await Producers.findByIdAndDelete(id);
// });
res.redirect(`/admin/category?page=1&error=There+Are+${lenghtIds}+Category+Have+Been+Deleted!
Delete Many - Tạm thời chặn . Sợ mất hết dữ liệu thôi :))`);
};
// edit
module.exports.editProducer = async (req, res) => {
const idToEdit = req.body.id;
const editData = req.body;
const producerIsEdited = await Producers.findById(idToEdit);
const idIsEdited = producerIsEdited.id;
await Producers.findByIdAndUpdate(idToEdit, {
producer_name: editData.producer_name,
});
res.redirect(`/admin/category?page=1&idIsEdited=${idIsEdited}`);
};
// add
module.exports.addProducer = async (req, res) => {
// check doublicate
const producer = await Producers.find({ producer_id: req.body.producer_id });
if (producer[0]) {
res.redirect(`/admin/category?page=1&error=id-${req.body.producer_id}-Has-Been-Used!`);
} else {
await Producers.insertMany(req.body);
res.redirect('/admin/category?page=1&added=1');
}
};
// ------------------------> Product
// index
module.exports.product = async (req, res) => {
const products = await Products.find().sort({ product_id: 1 });
const producers = await Producers.find();
const {
page, idIsDeleted, idIsEdited, added, error, note,
} = req.query;
res.render('admin/product', {
products,
producers,
page,
idIsDeleted,
idIsEdited,
added,
error,
note,
});
};
// delete
module.exports.deleteProduct = async (req, res) => {
const idToDelete = req.body.id;
const productIsDeleted = await Products.findById(idToDelete);
if (!productIsDeleted) {
res.redirect('/admin/product?page=1');
} else {
const idIsDeleted = productIsDeleted.product_id;
await Products.findByIdAndDelete(idToDelete);
res.redirect(`/admin/product?page=1&idIsDeleted=${idIsDeleted}`);
}
};
// delete many
module.exports.deleteManyProduct = async (req, res) => {
const { idToDeletes } = req.body;
const ids = idToDeletes.split(',');
const lenghtIds = ids.length;
// ids.forEach(async (id) => {
// await Products.findByIdAndDelete(id);
// });
res.redirect(`/admin/product?page=1&error=There+Are+${lenghtIds}+Products+Have+Been+Deleted!
Delete Many - Tạm thời chặn . Sợ mất hết dữ liệu thôi :))`);
};
// edit
module.exports.editProduct = async (req, res) => {
const idToEdit = req.body.id;
const editData = req.body;
const productIsEdited = await Products.findById(idToEdit);
const idIsEdited = productIsEdited.id;
if (req.file) {
const imgPath = req.file.path;
await Products.findByIdAndUpdate(idToEdit, {
product_img: `/${imgPath}`,
product_name: editData.product_name,
producer: editData.producer,
product_price: editData.product_price,
quantity: editData.quantity,
});
} else {
await Products.findByIdAndUpdate(idToEdit, {
product_name: editData.product_name,
producer: editData.producer,
product_price: editData.product_price,
quantity: editData.quantity,
});
}
res.redirect(`/admin/product?page=1&idIsEdited=${idIsEdited}`);
};
// add
module.exports.addProduct = async (req, res) => {
await Products.insertMany({
product_img: `/${req.file.path}`,
product_id: req.body.product_id,
product_name: req.body.product_name,
producer: req.body.producer,
product_price: req.body.product_price,
quantity: req.body.quantity,
});
res.redirect(`/admin/product?page=1&added=1¬e=${req.body.product_name}`);
};
// ------------------------------> User
// index
module.exports.user = async (req, res) => {
const users = await Users.find();
const {
page, idIsDeleted, idIsEdited, added, error,
} = req.query;
res.render('admin/user', {
users,
page,
idIsDeleted,
idIsEdited,
added,
error,
});
};
// delete
module.exports.deleteUser = async (req, res) => {
const idToDelete = req.body.id;
const userIsDeleted = await Users.findById(idToDelete);
if (!userIsDeleted) {
res.redirect('/admin/user?page=1');
} else {
const idIsDeleted = userIsDeleted.id;
await Users.findByIdAndDelete(idToDelete);
res.redirect(`/admin/user?page=1&idIsDeleted=${idIsDeleted}`);
}
};
// delete many
module.exports.deleteManyUser = async (req, res) => {
const { idToDeletes } = req.body;
const ids = idToDeletes.split(',');
const lenghtIds = ids.length;
// ids.forEach(async (id) => {
// await Users.findByIdAndDelete(id);
// });
res.redirect(`/admin/user?page=1&error=There+Are+${lenghtIds}+Users+Have+Been+Deleted!
Delete Many - Tạm thời chặn . Sợ mất hết dữ liệu thôi :))`);
};
// edit
module.exports.editUser = async (req, res) => {
const idToEdit = req.body.id;
const editData = req.body;
const idIsEdited = idToEdit;
if (editData.admin_password) {
const admin = await Users.findById(idToEdit);
if (admin.user_password === editData.admin_password) {
await Users.findByIdAndUpdate(idToEdit, {
user_name: editData.user_name,
user_email: editData.user_email,
user_phone: editData.user_phone,
user_permission: editData.user_permission,
});
res.redirect(`/admin/user?page=1&idIsEdited=${idIsEdited}`);
} else {
res.redirect('/admin/user?page=1&error=WrongAdminPassword');
}
} else {
await Users.findByIdAndUpdate(idToEdit, {
user_name: editData.user_name,
user_email: editData.user_email,
user_phone: editData.user_phone,
user_permission: editData.user_permission,
user_password: <PASSWORD>,
});
res.redirect(`/admin/user?page=1&idIsEdited=${idIsEdited}`);
}
};
// add
module.exports.addUser = async (req, res) => {
await Users.insertMany(req.body);
res.redirect('/admin/user?page=1&added=1');
};
<file_sep>/store/action/checkAdmin.js
import Axios from 'axios';
const checkAdmin = async () => {
const admin = JSON.parse(window.sessionStorage.getItem('adminPageAccess'));
if (!admin || !admin.admin_key || !admin.admin_name) {
return false;
}
const res = await Axios.get(`/api/users/${admin.admin_key}/adminPermission`);
if (res.data.err) {
return false;
}
return true;
};
export default checkAdmin;
<file_sep>/README.md
## An e-commerce project using NextJS, ReactJS, NodeJS, MongoDB
**What is** [NextJS](https://github.com/zeit/next.js), [ReactJS](https://reactjs.org/), [NodeJS](https://nodejs.org/), [MongoDB](https://www.mongodb.com/)
**Demo**
[Hosting on Heroku](https://nextjs-first-app.herokuapp.com) -
You may have to wait for the Heroku to start
**Setup**
1. Download or clone this project.
2. Rename the file `.env-example` to `.env`
3. Go into this folder and type on your terminal:
```
npm install
```
**Start this project :**
1. Dev (required nodemon and mongodb in your host) :
```
npm run dev
```
2. Run as production (just type and run) :
```
npm start
```
## Authors
- <NAME> ([Facebook](https://www.facebook.com/ninhnguyen375)) - [Email](<EMAIL>)
<file_sep>/components/admin/user/AddUser.js
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import {
TextField,
Button,
MenuItem,
FormControl,
InputLabel,
Select,
CircularProgress,
Grid,
Input,
Checkbox
} from '@material-ui/core';
import {
getUsersWithRedux,
createUser
} from '../../../store/action/userAction';
import { connect } from 'react-redux';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
import { AddUserStyles } from './user.styles.jss';
import Axios from 'axios';
const styles = AddUserStyles;
class EditUser extends Component {
state = {
isAdding: '',
message: '',
user_permission: {
product: false,
user: false,
bill: false,
category: false
},
user_status: true,
open: false,
user_group: {
value: '',
error: true
},
user_name: {
value: '',
error: true
},
user_password: {
value: '',
error: true
},
user_phone: {
value: '',
error: true
},
user_email: {
value: '',
error: true
},
confirmPassword: {
value: '',
error: true
},
isDoublicateEmail: false
};
validated__form = () => {
const {
confirmPassword,
user_email,
user_name,
user_phone,
user_password,
user_group,
isDoublicateEmail
} = this.state;
if (user_email.error || isDoublicateEmail) {
document.querySelector("input[name='user_email']").focus();
return false;
}
if (user_name.error) {
document.querySelector("input[name='user_name']").focus();
return false;
}
if (user_phone.error) {
document.querySelector("input[name='user_phone']").focus();
return false;
}
if (user_password.error) {
document.querySelector("input[name='user_password']").focus();
return false;
}
if (user_group.error) {
document.querySelector("input[name='user_password']").focus();
return false;
}
if (user_password.value !== confirmPassword.value) {
this.setState({ confirmPassword: { ...confirmPassword, error: true } });
document.querySelector("input[name='confirmPassword']").focus();
return false;
}
return true;
};
handleChange = e => {
const regex = new RegExp(e.target.pattern);
if (!regex.test(e.target.value)) {
this.setState({
[e.target.name]: { value: e.target.value, error: true }
});
} else {
this.setState({
[e.target.name]: { value: e.target.value, error: false }
});
}
};
checkDuplicateEmail = async () => {
const { user_email } = this.state;
try {
const findUser = await Axios.get(
'/api/users/find/?user_email=' + user_email.value
);
if (findUser.data.found)
this.setState({ ...this.state, isDoublicateEmail: true });
else {
this.setState({ ...this.state, isDoublicateEmail: false });
}
} catch (err) {
console.log(err);
}
};
handleClose = () => {
this.setState({ open: false });
};
checkedCheckBox = () => {
const permiss = window.document.getElementsByName('user_permission');
for (let i = 0; i < permiss.length; i++) {
permiss[i].checked = '';
}
};
// submit
handleSubmit = async e => {
this.setState({ isAdding: true });
e.preventDefault();
if (!this.validated__form()) {
this.setState({ isAdding: false });
return;
}
const {
user_email,
user_name,
user_password,
user_group,
user_permission,
user_phone,
user_status
} = this.state;
const user = {
user_name: user_name.value,
user_password: <PASSWORD>,
user_phone: user_phone.value,
user_permission: user_permission,
user_group: user_group.value,
user_email: user_email.value,
user_status: user_status
};
await this.props.createUser(user);
if (!this.props.createError) {
this.setState({
open: true,
message: `Create ${this.state.user_email.value} success`
});
this.props.getUsersWithRedux();
} else if (this.props.createError === 'Permision Denied') {
alert('Permission Denied!');
window.location = '/admin';
}
this.setState({ isAdding: false });
};
handleSelectPermission = event => {
this.setState({
user_permission: {
...this.state.user_permission,
[event.target.name]: event.target.checked
}
});
};
handleOptionChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSelectUserStatus = event => {
this.setState({
user_status: event.target.checked
});
};
render() {
const { classes } = this.props;
const {
user_email,
user_password,
user_name,
user_phone,
confirmPassword,
user_group,
isDoublicateEmail
} = this.state;
return (
<div className="admin-content fadeIn">
<h2 className={classes.formTitle}>Create New User</h2>
<Grid container>
<Grid item xs={6}>
<form noValidate id="addNewUser" onSubmit={this.handleSubmit}>
{/* Email */}
<TextField
required
error={user_email.error || isDoublicateEmail}
onBlur={this.checkDuplicateEmail}
label="Email"
name="user_email"
defaultValue={user_email.value}
onChange={this.handleChange}
className={classes.textField}
helperText={
isDoublicateEmail
? 'This email has been used'
: '<EMAIL>'
}
inputProps={{
pattern:
'[a-z][a-z0-9_.]{5,32}@[a-z0-9]{2,}(.[a-z0-9]{2,4}){1,2}'
}}
/>
{/* Name */}
<TextField
autocomplete="false"
error={user_name.error}
required
label="Name"
name="user_name"
defaultValue={user_name.value}
onChange={this.handleChange}
className={classes.textField}
inputProps={{
pattern: '^[ ._A-z0-9]*$'
}}
helperText={'no speacial character [!,@,#,$,%,^,&,*]'}
/>
{/* Phone */}
<TextField
error={user_phone.error}
required
label="Phone"
name="user_phone"
defaultValue={user_phone.value}
onChange={this.handleChange}
className={classes.textField}
type="number"
helperText="10 number, first number is 0"
inputProps={{ pattern: '0[0-9]{9}' }}
/>
{/* Password */}
<TextField
error={user_password.error}
required
label="Password"
name="user_password"
defaultValue={user_password.value}
onChange={this.handleChange}
className={classes.textField}
helperText="min 6 charaters"
type="password"
inputProps={{ pattern: '.{6,}' }}
/>
{/* Confirm Password */}
<TextField
error={confirmPassword.error}
required
label="Confirm Password"
name="confirmPassword"
className={classes.textField}
defaultValue={confirmPassword.value}
type="password"
onChange={this.handleChange}
inputProps={{ pattern: '.{6,}' }}
/>
<br />
{/* Group */}
<FormControl className={classes.textField}>
<InputLabel htmlFor="user_group-select">Group</InputLabel>
<Select
required
value={this.state.user_group.value}
onChange={this.handleChange}
name="user_group"
renderValue={value => value}
input={<Input id="user_group-select" />}
error={user_group.error}
>
<MenuItem value="admin">Admin</MenuItem>
<MenuItem value="client">Client</MenuItem>
</Select>
</FormControl>
<br />
{/* permission */}
{this.state.user_group.value === 'admin' ? (
<>
<p style={{ color: 'gray', fontSize: '13px' }}>
Choose permission manager:
</p>
<Checkbox
checked={this.state.user_permission.bill}
onChange={this.handleSelectPermission}
name="bill"
/>
Bill
<Checkbox
checked={this.state.user_permission.user}
onChange={this.handleSelectPermission}
name="user"
/>
User
<Checkbox
checked={this.state.user_permission.product}
onChange={this.handleSelectPermission}
name="product"
/>
Product
<Checkbox
checked={this.state.user_permission.category}
onChange={this.handleSelectPermission}
name="category"
/>
Category
</>
) : null}
<br />
{/* user status */}
Status :
<Checkbox
checked={this.state.user_status}
onChange={this.handleSelectUserStatus}
/>
{this.props.createError && (
<h4 style={{ color: 'red' }}>{this.props.createError}</h4>
)}
</form>
{this.state.isAdding ? (
<Button variant="contained" color="primary">
<CircularProgress size={24} className={classes.bgWhite} />
</Button>
) : (
<Button
variant="contained"
color="primary"
form="addNewUser"
type="submit"
>
Create
</Button>
)}
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.open}>
{this.state.message}
</CustomizedSnackbars>
</div>
</Grid>
</Grid>
</div>
);
}
}
const mapStateToProps = state => {
return {
createError: state.user.createError
};
};
const mapDispatchToProps = dispatch => {
return {
createUser: user => dispatch(createUser(user)),
getUsersWithRedux: () => dispatch(getUsersWithRedux())
};
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(EditUser)
);
<file_sep>/server/api/controllers/producer.api.controller.js
const Producers = require('../../models/producers.model');
const Products = require('../../models/products.model');
module.exports.index = async (req, res) => {
const producers = await Producers.find();
const data = {
data: producers
};
res.json(data);
};
module.exports.deleteProducer = async (req, res) => {
const { id } = req.params;
if (id) {
try {
const producer = await Producers.findById(id);
const product = await Products.findOne({
producer: producer.producer_id
});
if (product) {
return res.send({
err: `Can't delete ${
producer.producer_name
}, this has a lot of products`
});
} else {
await Producers.findByIdAndDelete(id);
return res.send('success');
}
} catch (err) {
return res.send({ err });
}
} else {
return res.send({
err: 'invalid id'
});
}
};
module.exports.addProducer = async (req, res) => {
const { body } = req;
const producers = await Producers.find();
if (!body) {
res.send({ err: 'Not have any form' });
} else {
const isDuplicate = producers.find(
item => item.producer_id === body.producer_id
);
if (isDuplicate) res.send({ err: 'Duplicate ID' });
else {
try {
await Producers.insertMany(body);
res.send('Success');
} catch (err) {
res.send({ err: err.message });
}
}
}
};
module.exports.editProducer = async (req, res) => {
const { id } = req.params;
let producers = await Producers.find();
if (!req.body.producer_name) {
res.send({ err: 'Not have any form' });
} else if (id) {
const producer = await Producers.findById(id);
if (!producer) {
res.send({ err: 'Not have this producer' });
} else {
const u = req.body;
producers = producers.filter(
item => item.producer_id !== producer.producer_id
);
const validId = producers.find(
item => item.producer_id === u.producer_id
);
if (validId) res.send({ err: 'Duplicate ID' });
else {
await Producers.findByIdAndUpdate(id, {
producer_name: u.producer_name,
producer_id: u.producer_id
});
res.send('Success');
}
}
} else {
res.send({ err: 'Invalid id' });
}
};
<file_sep>/components/Cart/CartItem.jsx
import React, { Component } from 'react';
import {
TableRow,
TableCell,
Button,
TextField,
withStyles
} from '@material-ui/core';
import { Delete, Remove, Add } from '@material-ui/icons';
import CartStyles from './Cart.styles.jss';
const styles = CartStyles;
class CartItem extends Component {
render() {
const { item, id, onDelete, classes } = this.props;
return (
<TableRow>
<TableCell>{item.cartItem.proId}</TableCell>
<TableCell>
<img
alt={'product img'}
src={`/static${item.currPro.product_img}`}
className={classes.image}
/>
</TableCell>
<TableCell>{item.currPro.product_name}</TableCell>
<TableCell>
<div className="group-btn-plus-and-minus">
<button
variant={'raised'}
onClick={() => this.props.minusQuantity(id)}
className="btn-minus"
>
<Remove color={'secondary'} fontSize={'small'} />
</button>
<input
readOnly={true}
type="text"
value={item.cartItem.quantity}
name="quantity"
id={id}
className="input-number"
/>
<button
variant={'raised'}
onClick={() => this.props.plusQuantity(id)}
className="btn-plus"
>
<Add fontSize={'small'} color={'primary'} />
</button>
</div>
</TableCell>
<TableCell>{item.cartItem.proPrice}</TableCell>
<TableCell>{item.cartItem.proPrice * item.cartItem.quantity}</TableCell>
<TableCell>
<Button onClick={onDelete(item.cartItem._id)}>
<Delete color="error" />
</Button>
</TableCell>
</TableRow>
);
}
}
export default withStyles(styles)(CartItem);
<file_sep>/components/admin/Dashboard/Dashboard.jsx
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { Divider } from '@material-ui/core';
import BusinessSituation from './BusinessSituation';
import TopSellerProducts from './TopSellerProducts';
import Overview from './Overview';
import TopUsers from './TopUsers';
export class Dashboard extends Component {
render() {
return (
<div className="admin-content fadeIn">
<div className="admin-content-header">Dash Board</div>
<div className="divider" />
<Overview />
<div className="divider" />
<BusinessSituation />
<div className="divider" />
<TopSellerProducts />
<div className="divider" />
<TopUsers />
</div>
);
}
}
export default Dashboard;
<file_sep>/components/Payment/Payment.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { TextField, Select, MenuItem } from '@material-ui/core';
const styles = theme => ({
root: {
width: '90%'
},
backButton: {
marginRight: theme.spacing.unit
},
instructions: {
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit,
textAlign: 'center'
}
});
export class StepOne extends React.Component {
handleSubmit = e => {
e.preventDefault();
this.props.onNext();
};
render() {
return (
<form
style={{
width: '80%',
margin: 'auto'
}}
onSubmit={this.handleSubmit}
>
<TextField required style={{ width: '100%' }} label="Your Address" />
<br />
<br />
<TextField
required
inputProps={{ pattern: '0[0-9]{9}' }}
style={{ width: '100%' }}
label="Your Phone number"
/>
<div style={{ textAlign: 'right', padding: '20px 0' }}>
<Button
disabled={this.props.activeStep === 0}
onClick={this.props.onBack}
>
Back
</Button>
<Button variant="contained" color="primary" type="submit">
{this.props.activeStep === getSteps().length - 1
? 'Finish'
: 'Next'}
</Button>
</div>
</form>
);
}
}
export class StepTwo extends React.Component {
state = {
paymentMethod: ''
};
handleChange = e => {
this.setState({ paymentMethod: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
if (this.state.paymentMethod) this.props.onNext();
};
render() {
return (
<form
style={{
width: '50%',
margin: 'auto'
}}
onSubmit={this.handleSubmit}
>
Select payment method
<Select
required
style={{ marginLeft: 10 }}
onChange={this.handleChange}
value={this.state.paymentMethod}
>
<MenuItem value="Pay on Delivery">Pay on Delivery</MenuItem>
<MenuItem value="Credit Card">Credit Card</MenuItem>
</Select>
{this.state.paymentMethod === 'Credit Card' && (
<>
<TextField required style={{ width: '100%' }} label="Full name" />
<br />
<br />
<TextField
required
value="4539745478038591"
inputProps={{
pattern:
'^(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12})$'
}}
style={{ width: '100%' }}
label="Card number"
/>
<br />
<br />
Expiration
<br />
<TextField
required
inputProps={{ type: 'number', min: 1, max: 12 }}
style={{ width: '30%' }}
label="MM"
/>
<TextField
inputProps={{ type: 'number' }}
required
style={{ width: '30%' }}
label="YY"
/>
<TextField
required
inputProps={{ type: 'number' }}
style={{ width: '30%', float: 'right' }}
label="CVV"
/>
</>
)}
<div style={{ textAlign: 'right', padding: '20px 0' }}>
<Button
disabled={this.props.activeStep === 0}
onClick={this.props.onBack}
>
Back
</Button>
<Button variant="contained" color="primary" type="submit">
{this.props.activeStep === getSteps().length - 1
? 'Finish'
: 'Next'}
</Button>
</div>
</form>
);
}
}
function getSteps() {
return ['Comfirm address and phone number', 'Choose payment method'];
}
class Payment extends React.Component {
state = {
activeStep: 0,
paymentMethod: ''
};
getStepContent = stepIndex => {
switch (stepIndex) {
case 0:
return (
<StepOne
activeStep={this.state.activeStep}
onBack={this.handleBack}
onNext={this.handleNext}
/>
);
case 1:
return (
<StepTwo
activeStep={this.state.activeStep}
onBack={this.handleBack}
onNext={this.handleNext}
/>
);
default:
return 'Unknown stepIndex';
}
};
handleNext = () => {
this.setState(state => ({
activeStep: state.activeStep + 1
}));
};
handleBack = () => {
this.setState(state => ({
activeStep: state.activeStep - 1
}));
};
handleReset = () => {
this.setState({
activeStep: 0
});
};
render() {
const { classes } = this.props;
const steps = getSteps();
const { activeStep } = this.state;
return (
<div className={classes.root} style={{ margin: 'auto' }}>
<Stepper activeStep={activeStep} alternativeLabel>
{steps.map(label => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
</Step>
))}
</Stepper>
<div>
{this.state.activeStep === steps.length ? (
<div style={{ textAlign: 'center' }}>
<Typography className={classes.instructions}>
All steps completed
</Typography>
<Button style={{ margin: 30 }} onClick={this.handleReset}>
Reset
</Button>
<Button
style={{ margin: 30 }}
variant="contained"
color="primary"
onClick={this.props.onCheckOut}
>
Let Go
</Button>
</div>
) : (
<div>{this.getStepContent(activeStep)}</div>
)}
</div>
</div>
);
}
}
Payment.propTypes = {
classes: PropTypes.object
};
export default withStyles(styles)(Payment);
<file_sep>/pages/profile.jsx
import React, { Component } from 'react';
import ShopContext from '../context/shop-context';
import Axios from 'axios';
import Link from 'next/link';
import { Divider, Button, TextField } from '@material-ui/core';
class profile extends Component {
static contextType = ShopContext;
state = {
user: null,
getError: null,
currPassword: '',
newPassword: '',
editPassword: false,
editMess: ''
};
async componentDidMount() {
await this.context.checkLogin();
if (this.context.auth.auth_key) {
try {
const user = await Axios.get(
'/api/users/' + this.context.auth.auth_key
);
if (user.data.err) this.setState({ getError: user.data.err });
else {
this.setState({ user: user.data.user });
}
} catch (err) {
this.setState({ getError: err.message });
}
} else {
console.log('none auth');
}
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
toggleEditPassword = () => {
this.setState({ editPassword: !this.state.editPassword });
};
handleEditPassword = async e => {
e.preventDefault();
try {
const res = await Axios.put(
`/api/users/${this.state.user._id}/editPassword`,
this.state
);
if (res.data.err) this.setState({ editMess: res.data.err });
else this.setState({ editMess: 'Success' });
} catch (err) {}
};
render() {
const { user, getError, editPassword } = this.state;
const userDetails = user
? [
{
id: 1,
label: 'Name',
content: user.user_name
},
{
id: 2,
label: 'Phone',
content: user.user_phone
},
{
id: 3,
label: 'Email',
content: user.user_email
},
{
id: 4,
label: 'Password',
content: <Button onClick={this.toggleEditPassword}>Edit</Button>
}
]
: null;
const renderDetails = () => (
<>
{userDetails &&
userDetails.map(item => (
<div className="row" key={item.id}>
<div className="col label">{item.label} :</div>
<div className="col">{item.content}</div>
</div>
))}
</>
);
const renderEditPassword = () => (
<form onSubmit={this.handleEditPassword}>
<div className="row">
<div className="col">
<TextField
required
value={this.state.currPassword}
type="password"
inputProps={{ pattern: '.{6,}' }}
name="currPassword"
label="Current password"
onChange={this.handleChange}
/>
</div>
<div className="col">
<TextField
required
value={this.state.newPassword}
type="password"
inputProps={{ pattern: '.{6,}' }}
name="newPassword"
label="New password"
onChange={this.handleChange}
/>
</div>
</div>
<div className="row">{this.state.editMess}</div>
<div className="row">
<Button type="submit" color="primary" variant="contained">
Edit
</Button>
</div>
</form>
);
return (
<div>
{
<>
{user ? (
<div className="profile">
<h1>Your Profile</h1>
<div className="divider" />
<div className="profile-content">
{renderDetails()}
{editPassword && renderEditPassword()}
{/* action */}
<div className="row" style={{ justifyContent: 'center' }}>
<div
className="col"
style={{ width: '100%', textAlign: 'center' }}
>
<Link href="/">
<a>
<Button
style={{ width: '100%' }}
variant="contained"
color="primary"
>
GO TO SHOPPING
</Button>
</a>
</Link>
</div>
</div>
</div>
</div>
) : (
<div className="loading-text">Loading...</div>
)}
{getError && <h1>{getError}</h1>}
</>
}
</div>
);
}
}
export default profile;
<file_sep>/components/admin/user/User.js
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { Divider, Button } from '@material-ui/core';
import UserList from './UserList';
import { connect } from 'react-redux';
import Router from 'next/router';
import {
getUsersWithRedux,
closeAlertDeleted
} from '../../../store/action/userAction';
import CustomizedSnackbars from '../snackbar/CustomizedSnackbars';
import Axios from 'axios';
import AddUser from './AddUser';
import { UserStyles } from './user.styles.jss';
import { KeyboardArrowDown, KeyboardArrowUp } from '@material-ui/icons';
const styles = UserStyles;
class User extends Component {
state = {
openSnackNumDeleted: false,
messDeleted: '',
adminAccess: true,
isAddFormOpen: false
};
componentWillReceiveProps(nextProps) {
if (nextProps.numDeleted) {
this.setState({
openSnackNumDeleted: true,
messDeleted: `${nextProps.numDeleted} users has been deleted`
});
}
}
async componentDidMount() {
this.getUsers();
}
getUsers = async () => {
const admin_key = JSON.parse(
window.sessionStorage.getItem('adminPageAccess')
).admin_key;
const admin = await Axios.get(`/api/users/${admin_key}/adminPermission`);
// check access to "User permission"
if (!admin.data.admin.user) {
this.setState({ ...this.state, adminAccess: false });
return;
} else {
this.setState({ ...this.state, adminAccess: true });
const { dispatch } = this.props;
await dispatch(getUsersWithRedux());
}
};
handleClose = () => {
this.setState({ openSnackNumDeleted: false });
const { dispatch } = this.props;
dispatch(closeAlertDeleted());
};
toggleOpenAddForm = () => {
this.setState({ isAddFormOpen: !this.state.isAddFormOpen });
};
render() {
const { classes, numDeleted } = this.props;
const { isAddFormOpen } = this.state;
return (
<>
{this.state.adminAccess ? (
<>
<div className="admin-content fadeIn">
<div className="admin-content-header">User Manager</div>
<div className="divider" />
{/* Button Add */}
<Button
onClick={this.toggleOpenAddForm}
variant={'contained'}
color={'primary'}
>
Add User{' '}
{isAddFormOpen ? <KeyboardArrowUp /> : <KeyboardArrowDown />}
</Button>
{/* Form Add*/}
{isAddFormOpen && <AddUser />}
<div className="divider" />
{/* List User */}
{this.props.users ? (
<UserList users={this.props.users.data} />
) : (
<div className="loading-text">Loading...</div>
)}
</div>
{numDeleted && (
<div onClick={this.handleClose}>
<CustomizedSnackbars open={this.state.openSnackNumDeleted}>
{this.state.messDeleted}
</CustomizedSnackbars>
</div>
)}
</>
) : (
<>{Router.push('/admin')}</>
)}
</>
);
}
}
const mapStateToProps = state => {
return {
users: state.user.users,
numDeleted: state.user.numDeleted
};
};
export default withStyles(styles)(connect(mapStateToProps)(User));
<file_sep>/server/api/routes/product.api.route.js
const express = require('express');
const multer = require('multer');
const controller = require('../controllers/product.api.controller');
const router = express.Router();
// config upload file
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'static/uploads/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage });
router.get('/', controller.index);
router.post('/search', controller.search);
router.get('/:id', controller.getProduct);
router.delete('/:product_id', controller.deleteProduct);
router.post('/', upload.single('product_img'), controller.addProduct);
router.put('/:id', controller.editProduct);
module.exports = router;
|
a8842dbf01849e875b8fd7f190cf12055958db8c
|
[
"JavaScript",
"Markdown"
] | 66 |
JavaScript
|
humanaseem/next-express-commerce-app
|
94419f9e0726c16fc411f151acebf387f891a014
|
e384bf0cb60d5574f244bd3dba44744e01faf7d0
|
refs/heads/master
|
<file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## API Info
- Powered by PHP 7.2.4
- Rate limited
---
## API Endpoints
<details>
<summary>
### Signup
*Used to create a new user on the system, immediately after receiving, sends 200 and does an automatic login*
https://staging.api.teams.wethos.co/api/v1/auth/signup
</summary>
**POST**
- `` object
- `checkbox` boolean
- `email` string
- `first_name` string
- `last_name` string
- `password` string
- `user_type` string
Afterwards, does:
https://staging.api.teams.wethos.co/oauth/token
**POST**
- `` object
- `client_id` number, hardcoded
- `client_secret` string, hardcoded
- `grant_type` string, hardcoded
- `password` string
- `scope` string, hardcoded
- `username` string
Which in turn returns:
- `` object
- `access_token` JWT
- `expires_in` number
- `refresh_token` string
- `token_type` string
</details>
<details>
<summary>
### Login
*Used to get the Bearer Token*
https://staging.api.teams.wethos.co/oauth/token
</summary>
**POST**
- `` object
- `client_id` number, hardcoded
- `client_secret` string, hardcoded
- `grant_type` string, hardcoded
- `password` string
- `scope` string, hardcoded
- `username` string
returns:
- `` object
- `access_token` JWT
- `expires_in` number
- `refresh_token` string
- `token_type` string
</details>
<details>
<summary>
### Signout
*Used to signout, sends nothing, receives nothing, probably blacklists the token in the API?*
https://staging.api.teams.wethos.co/api/v1/auth/signout
</summary>
**POST**
### Forgotpassword
*Used to send a recovery link to the email, returns 200 if the email exists, 404 if the email doesn't*
https://staging.api.teams.wethos.co/api/v1/auth/resetpassword/
**POST**
- `` object
- `email` string
</details>
<details>
<summary>
### Password
*Used to change the password*
https://staging.api.teams.wethos.co/api/v1/auth/password/
</summary>
**PATCH**
- `` object
- `confirmpassword` string
- `oldpassword` string
- `password` string
</details>
<details>
<summary>
### User
*Used to get the user's data*
https://staging.api.teams.wethos.co/api/v1/user
</summary>
**GET**
returns:
- `` object
- `active` boolean (number)
- `checkpoints` ???
- `created_at` date
- `email` string
- `first_name` string
- `id` number
- `last_login` ???
- `last_name` string
- `permissions` array (empty?)
- `phone_number` string
- `roles` array
- `` object
- `id` number
- `name` string
- `permissions` array
- `slug` string
- `updated_at` date
**PATCH**
- `` object
- `first_name` string
- `last_name` string
- `phone_number` string
</details>
<details>
<summary>
### Network
*Not sure what this is used for*
https://staging.api.teams.wethos.co/api/v1/network
</summary>
**GET**
returns:
- ???
</details>
<details>
<summary>
### CurrentEspecialist
*Used to bring all the user's profile data*
https://staging.api.teams.wethos.co/api/v1/currentspecialist
</summary>
**GET**
returns:
- `capabilities` array
- `` object
- `brief` string
- `description` string
- `id` number
- `name` string
- `causes` array
- `` object
- `description` string
- `id` number
- `name` string
- `reason` string
- `checkpoints` array
- `` object
- `created_at` date
- `slug` string
- `city` object
- `id` number
- `latitude` number
- `longitude` number
- `name` string
- `region` object
- `country` object
- `id` number
- `name` string
- `slug` string
- `id` number
- `name` string
- `slug` string
- `slug` string
- `description` string
- `experience` array
- `` object
- `company` string
- `description` string
- `title` string
- `id` number
- `languages` array
- `` object
- `code` string
- `level` number
- `links` array
- `` object
- `title` string
- `url` string
- `profile_image` string
- `projects` array
- `` object
- `id` number
- `name` string
- `raw` string
- `roles` array
- `` object
- `description` string
- `id` number
- `name` string
- `tasks` array
- `` *out of scope for this test, must be similar to projects*
- `title` string
- `user` object
- `created_at` date
- `email` string
- `first_name` string
- `id` number
- `last_name` string
- `phone_number` number ???
**PUT** for Specialist Details
- `` object
- `city_id` number
- `description` string, empty
- `profile_image` string, (URL, careful with XSS)
- `title` string
returns:
- whole data as in GET
**PUT** for Social Links
- `links` array
- `` object
- `title` string
- `url` string
returns:
- whole data as in GET
**PUT** for Capabilities
- `capabilities` array
- `` number (id of the capability)
returns:
- whole data as in GET
**PUT** for Languages
- `languages` array
- `` object
- `code` string
- `level` number
returns:
- whole data as in GET
**PUT** for Causes
- `causes` array
- `` object
- `id` number
- `reasons` string
returns:
- whole data as in GET
**PUT** for Experience
- `experience` array
- `` object
- `company` string
- `description` string (HTML with inline styles, careful with XSS)
- `title`
returns:
- whole data as in GET
</details>
<details>
<summary>
### Causes
*Used to fill the dropdown for the individual `Causes` the user may have*
*Supports pagination*
https://staging.api.teams.wethos.co/api/v1/specialists/causes
</summary>
**GET**
returns:
- `data` array
- `` object
- `description` null
- `id` number
- `name` string
- `reason` null
- `links` for pagination
- `meta` for pagination
</details>
<details>
<summary>
### Capabilities
*Used to fill the selector for the individual `Capabilities` the user may have*
*Supports pagination, however on the current page, 99,999 items are requested*
https://staging.api.teams.wethos.co/api/v1/work/capabilities
</summary>
**GET**
returns:
- `data` array
- `` object
- `brief` string
- `description` string
- `id` number
- `name` string
- `links` for pagination
- `meta` for pagination
</details>
<details>
<summary>
### Projects
*Used to receive data about an specific project ID, using that ID instead of XXX in the URL*
https://staging.api.teams.wethos.co/api/v1/projects/XXX
</summary>
**GET**
returns:
- `data` array
- `` object
- `assets` array
- `checkpoints` array
- `currentscope` array
- `description` string (HTML)
- `id` number
- `name` string
- `summary` object
- `` *many things that are out of scope for the test, mostly for assesing cost and value and payments (?)*
- `description` string
- `events` array
- `id` number
- `name` string
- `organization` object
- `about` string (HTML)
- `assets` array
- `contacts` array
- `description` string
- `id` number
- `link` array
- `name` string
- `website_url` string (URL)
- `slack_channel` null
- `specialists` array
- `` object
- `description` string
- `id` number
- `profile_image` string (URL)
- `projectrole` string
- `title` string
- `user` object
- `email` string (email)
- `first_name` string
- `last_name` string
- `statement_of_purpose` string (HTML)
- `timeline` array
</details>
<details>
<summary>
### Specialists
*Used to receive data about all the specialists in the network, it appears to support regular url params*
https://staging.api.teams.wethos.co/api/v1/specialists
</summary>
**GET**
returns:
- `data` array
- `` *out of scope for test*
- `pagination` object
- `` *out of scope for test*
</details><file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## Performance
There are areas of opportunity in performance with the dashboard, because even with no throttling on, the site takes more than expected to load.
One could argue that being a work application there's no need to focus so much on performance, but I believe with a few tweaks we can improve performance without much time investment.

The main take aways from this report are:
- Preload key requests
- Eg. Main CSS
- Defer other requests
- Eg. The whole list of capabilities can be run only if the user will modify them, no need to download them all from the beggining<file_sep>// Middleware to confirm the user is authenticated
// auth ? set Bearer token : go back to login
export default function ({ app, redirect }) {
// Confirm we're in the browser
if (!process.server) {
// No Wethos local storage, go to login
if (window.localStorage.wethos == undefined) {
return redirect('/login')
} else {
let wethosLS = JSON.parse(window.localStorage.wethos)
// No Wethos authToken, go to login
if (!wethosLS.user.authToken) {
return redirect('/login')
}
// Wethos authToken found, set it globally
if (wethosLS.user.authToken) {
app.$axios.setToken(wethosLS.user.authToken, 'Bearer')
app.$axios.setHeader('Content-Type', 'application/json')
app.$axios.setHeader('X-Requested-With', 'XMLHttpRequest')
}
}
}
}<file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## Relevant information to show in app
Currently, there are several sets of information that are relevant to be shown:
- Specialist details
- Image.
- Name.
- City, Country.
- Title.
- Description
- Here since
- Social links
- Can be anything, from personal blogs to social media
- Languages
- With skill level (1-5)
- Capabilities
- Title
- Subtitle *this is common in my case, for all capabilities, as I'm only selecting Development ones. For mobile this could be an anchor where we could expand from there to see the details of all the titles in that 'category'*
- Causes
- Title
- Text
- Experience
- Title
- Company
- Text
Finally:
- Projects *which the customer required be a link of some sort, possibly to separate that from the main info*
---
## Main Features
- CTA @ top will be ignored for this test
- Links will be evaluated to see if they're a social network specifically, to show the proper svg
- Ideally we can show a little map? Or maybe current time (could help for general availability between teams)
- Sections should be easy to skim
- Clear clean look
- Rounded boxes with light shadow
---
<details>
<summary>
## Inspiration from Dribbble for main app
</summary>





</details>
---
<details>
<summary>
## Wireframes
</summary>
Round 1

Round 2, mobile menu


</details><file_sep>[build]
publish = "dist/"
command = "npm run generate"
[context.production]
[context.production.environment]
OAUTH_URL="https://staging.api.teams.wethos.co/oauth/token"
API_URL_BASE="https://staging.api.teams.wethos.co/api/v1/"
GRANT_TYPE="password"
CLIENT_SECRET="<KEY>"
SCOPE="*"
CLIENT_ID="2"<file_sep>// URLS
OAUTH_URL="https://staging.api.teams.wethos.co/oauth/token"
API_URL_BASE="https://staging.api.teams.wethos.co/api/v1/"
// OAUTH DATA
GRANT_TYPE="password"
CLIENT_SECRET=""
SCOPE="*"
CLIENT_ID=9999999999<file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## Explicit Requirements
The requirements were very clear:
`1) Please write a little application that authenticates against the staging API server with your personal account, and then display a page with a summary of your user profile.`
We want a read-only app to login and present the user's profile in a summary.
`2) Somewhere in the app provide a link to the projects you have been added to; when you click the link, show a brief summary of the project however you like.`
Include the projects that are not shown in the current version of the app, through a link.
---
## Deadline
The project is to be delivered on Monday July 29th.
---
## Main focus
My main focus for this test, considering the time frame and requirements, is to cover:
- Mobile first design
- Performant
- Accessibility compliant
<file_sep>import Vue from 'vue'
import VTooltip from 'v-tooltip'
VTooltip.enabled = window.innerWidth > 768
Vue.use(VTooltip)<file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## Accessibility
Accessibility has been included in the current app, with proper outlines on the selected items, and an easy to use keyboard navigation.
There are, however, a couple things from the report

The main take aways from this report are:
- Contrasts
- Eg. The call to action boxes at the top, and the `Remove` from the `Capabilities` divs colors can be modified to improve contrast for people who have a situation with their eyesight.
- `[alt]` attributes
- Some images are missing this attribute, which is essential for screen readers.<file_sep>
// Plugin to logout user if 401 or 403 is returned by the API
export default function ({ $axios, store, router }) {
$axios.onError(err => {
let code = parseInt(err.response && err.response.status) // TC39 moved Optional Chaining to Stage 3 today 🥳
if ([401, 403].includes(code)) {
// Most surely the token has been blacklisted
store.dispatch('logout').then(() => {
router.push('/login')
})
}
return Promise.reject(err)
})
}<file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## Competitors
In this case, there are no 'competitors' per se, as it is an internal tool, but we can analyze competitors to get a better understanding of the possibilities in a profile page.
I won't go into detail with this review, it will be mostly visual, to gather information to do wireframes.
### Linkedin
<details>
<summary>
**Mobile Screens**
</summary>



</details>
<details>
<summary>
**Desktop Screens**
</summary>



</details>
**Key Points**
Linkedin chose to go with a single column implementation, that is centered on desktop, and goes full width on mobile.
This solution is easier to implement, as basically elements are just scaled down.
They also make use of collapsible blocks, that show only a part of the information, to allow for an easier scrolling experience, since blocks by default, are small.
### Vettery
<details>
<summary>
**Mobile Screens**
</summary>



</details>
<details>
<summary>
**Desktop Screens**
</summary>


</details>
**Key Points**
Just as Linkedin, Vettery chose to go with a single column implementation, that is centered on desktop, and goes full width on mobile.
One aspect.
There are however, no collapsible blocks, as all information is presented in such a way that scrolling feels easy and natural.
It is important to note that they, contrary to Linkedin, show less details in general.<file_sep># Wethos Test
A hiring test from Wethos: Nuxt app to show a summary of the user's profile and projects
---
## Performance Analysis
Click [here](./docs/performance/PERFORMANCE.md) for more info
---
## Accessibility Analysis
Click [here](./docs/a11y/A11Y.md) for more info
---
## SEO Analysis
Not done, as this is an internal dashboard
---
## Requirements
Click [here](./docs/reqs/REQUIREMENTS.md) for more info
---
## Competitors Analysis
Click [here](./docs/competitors/COMPANALYSIS.md) for more info
---
## API Info
Click [here](./docs/api/API.md) for more info
---
## Tech stack
[Nuxt.js](https://nuxtjs.org/) will be used due to the development speed, as it being opinionated, it helps us avoid Vue's boilerplate code and easily output a static site to host on [Netlify](https://netlify.com)
---
## Build Setup
``` bash
# install dependencies
$ npm run install
# serve with hot reload at localhost:3000
$ npm run dev
# build for production and launch server
$ npm run build
$ npm run start
# generate static project
$ npm run generate
# upload to GitHub & Netlify (CI Pipeline)
$ git push
```
---
## WebPage
https://israelmuca-wethos.netlify.com/
---
## Notes
- There's a secret hardcoded, correct?
- `currentspecialist` is receiving PUT with incomplete data, should be PATCH to adhere to REST
- When updating `currentspecialist` with PUT, the API sends back the whole object again, and then something GETs the whole object again...
- No validation of `remove`; easy to make mistakes and erase something valuable
- `Password` and `User` handle PATCH correctly
- Link in header sends to /admin/dashboard but there's a mixin there to redirect if regular user to /home
- No mobile menu, impossible to access projects on the phone
- icons licence: https://iconmonstr.com/license/
## TODOs
- 'login': Improve the login screen, too basic
- 'SignIn': Add better comments to the component
- '/': Try the bottom navbar with individual items, not hamburguer menu
- Move 'SignIn' loading indicator to the store, same for 'BasicInfo'
- Set Skeleton screens for the image and text loading
- Verify which domains are used the most for the links, get the appropiate svg's and map them so we add the proper icon depending on the domain (eg. Twitter, Linkedin, etc...)
- Language function should ideally be in the backend, as to make the front faster; Or maybe I could add it to the prototype, but it would be clearer if it lived in the backend.
- No error handling for when API returns no data or just fails
- Had to hard code some percentage % instead of relying on flexbox for the columns in the index; Go back to that
- Implement native-like animations to move the picture from the main description, to the top-right corner when we change to the other pages
https://css-tricks.com/native-like-animations-for-page-transitions-on-the-web/
- Remove the data processing from the Capabilities component, send that function to a utils/mapCapabilities function and use that in the store before saving the data
- Implement a function in the backend that gives a hash or sets a _lastUpdatedDate_. Query the API for this data, if it's the same, avoid making another call.
- Move the Store Dispatches from the Login page into the store (after login)
- Add more data to the individual project box
- FIX! on 1023+ px the X in the ind project goes out of the screen<file_sep>import Vuex from 'vuex'
const createStore = () => {
return new Vuex.Store({
state: {
loadingCurEsp: null,
user: {
authToken: null,
id: null,
createdAt: null,
email: null,
firstName: null,
lastName: null,
},
curEsp: {
capabilities: [],
causes: [],
city: {},
description: null,
experience: [],
id: null,
languages: [],
links: [],
profileImage: null,
projects: [],
title: null
},
projects: []
},
mutations: {
setAuthToken(state, authToken) {
state.user.authToken = authToken
},
setUser(state, user) {
state.user.id = user.id
state.user.createdAt = user.created_at
state.user.email = user.email
state.user.firstName = user.first_name
state.user.lastName = user.last_name
},
setLoadingCurEsp(state, loadStatus) {
state.loadingCurEsp = loadStatus
},
setCurEsp(state, curEsp) {
state.curEsp.capabilities = curEsp.capabilities
state.curEsp.causes = curEsp.causes
state.curEsp.city = curEsp.city
state.curEsp.description = curEsp.description
state.curEsp.experience = curEsp.experience
state.curEsp.id = curEsp.id
state.curEsp.languages = curEsp.languages
state.curEsp.links = curEsp.links
state.curEsp.profileImage = curEsp.profile_image
state.curEsp.projects = curEsp.projects
state.curEsp.title = curEsp.title
},
pushProject(state, project) {
// Get the ids from the state
let ids = state.projects.map(p => p.id)
// Compare the project id with the ones from state
if (!ids.includes(project.id)) {
// New project, push!
state.projects.push(project)
}
}
},
actions: {
login({ commit }, user) {
return new Promise(async (resolve, reject) => {
try {
// Try to login
let login = await this.$axios.post(process.env.OAUTH_URL, {
username: user.email,
password: <PASSWORD>,
grant_type: process.env.GRANT_TYPE,
client_secret: process.env.CLIENT_SECRET,
scope: process.env.SCOPE,
client_id: process.env.CLIENT_ID
})
// Save token for future use
commit('setAuthToken', login.data.access_token)
// Resolve and send the login data
resolve(login.data)
// TODO: When time permits, work the refresh token function (it is ignored here)
// Could be through middleware in layout or nuxt.config
// Or also through an axios interceptor!
} catch (error) {
// Reject and send the error
reject(error)
}
})
},
getUser({ commit }) {
return new Promise(async (resolve, reject) => {
try {
// Get the User's info
let user = await this.$axios.$get(`${process.env.API_URL_BASE}user`)
// Save the info to the store
commit('setUser', user.data)
// Resolve and send the login data
resolve(user.data)
} catch (error) {
// Reject and send the error
reject(error)
}
})
},
getCurrentSpecialist({ commit, dispatch }) {
// Start loading
commit('setLoadingCurEsp', true)
return new Promise(async (resolve, reject) => {
try {
// Get the Current Specialist info
let curEsp = await this.$axios.$get(`${process.env.API_URL_BASE}currentspecialist`)
// Save the info to the store
commit('setCurEsp', curEsp.data)
// Done loading
commit('setLoadingCurEsp', false)
// Now that we know which projects the user has, get them all
dispatch('getProjects').then(res => {
console.info("Projects loaded successfully")
})
// Resolve and send the current especialist data
resolve(curEsp.data)
} catch (error) {
// Done loading
commit('setLoadingCurEsp', false)
// Reject and send the error
reject(error)
}
})
},
getProjects({ commit, state }) {
// Start loading
return new Promise(async (resolve, reject) => {
try {
// From the currentSpecialist's projects, get all of their data
state.curEsp.projects.forEach(async p => {
// Get one new full project
let project = await this.$axios.$get(`${process.env.API_URL_BASE}projects/${p.id}`)
// Add the new full project to the state
commit('pushProject', project.data)
})
// Resolve and send the whole array of full projects
resolve(state.projects)
} catch (error) {
// Reject and send the error
reject(error)
}
})
},
logout({ commit }) {
return new Promise((resolve, reject) => {
commit('setAuthToken', null)
commit('setUser', null)
resolve()
})
}
}
})
}
export default createStore<file_sep>// Middleware to confirm the user is NOT authenticated
// auth ? redirect(/) : do nothing
export default function ({ redirect }) {
// Confirm we're in the browser
if (!process.server) {
// Wethos local storage found
if (window.localStorage.wethos != undefined) {
let wethosLS = JSON.parse(window.localStorage.wethos)
// authToken found, go home!
if (wethosLS.user.authToken) {
return redirect('/')
}
}
}
}
|
4b612b31b060a20e6b2d9a757ae4054691e771e1
|
[
"Markdown",
"TOML",
"JavaScript",
"Shell"
] | 14 |
Markdown
|
israelmuca/wethos-test
|
635057f4a2ed01ef23d5e7e2e451f4871369b444
|
f52ee7d633a6a92b501c8567f4f2777c86f2333d
|
refs/heads/main
|
<repo_name>Caphace-Ethan/Breast-Cancer-Diagnosis<file_sep>/scripts/data_processor.py
import pandas as pd
import numpy as np
from log import logger
import logging
import logging.handlers
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from project_config import Config
class data_processor():
def __init__(self) -> None:
self._logger = logger
# Percentage % of total missing values in the dataset
def total_percent_missing_data(self, df):
# Calculate total number of cells in dataframe
totalCells = np.product(df.shape)
# Count number of missing values per column
missingCount = df.isnull().sum()
# Calculate total number of missing values
totalMissing = missingCount.sum()
# Calculate percentage of missing values
return round(((totalMissing/totalCells) * 100), 2)
def missing_data_per_column(self, df):
item_list = []
row_list = []
new_columns=['Column', 'No. of Missing Values', '% Missing Values per column']
total_no_data_per_column = df.shape[0]-1
i=0
for item in df.columns:
no_missing_values = df[item].isna().sum()
percentage = str(round(((no_missing_values/total_no_data_per_column) * 100), 2))+" %"
row_list.append(item)
row_list.append(no_missing_values)
row_list.append(percentage)
item_list.append(row_list)
row_list = []
df_data = pd.DataFrame(item_list, columns = new_columns)
return df_data
def drop_columns(self, df, column_list):
df_new = df.drop(column_list, axis=1)
return df_new
def fix_outlier(self, data, column_list):
for column in column_list:
data[column] = np.where(data[column] > data[column].quantile(0.95), data[column].median(),data[column])
return data
def data_scaler(self, df):
scaler = MinMaxScaler()
df = pd.DataFrame(scaler.fit_transform(df))
return df<file_sep>/scripts/project_config.py
from pathlib import Path
class Config:
Root_Path = Path("../")
Repository = "https://github.com/Caphace-Ethan/Breast-Cancer-Diagnosis"
Data_path = Root_Path / "data/"
Image_path = Data_path / "img"
scripts_path = Root_Path / "scripts"
csv_data_path = Path("../data/data.csv")
<file_sep>/scripts/FileHandler.py
import pandas as pd
from log import logger
import logging
import logging.handlers
from project_config import Config
class FileHandler():
def __init__(self):
self._logger = logging
def csv_file_save(self, df, name, index=False):
try:
path = Config.Data_path / str(name + '.csv')
df.to_csv(path, index=index)
self._logger.info(f"{name} file saved successfully in csv format")
except Exception:
self._logger.exception(f"{name} save failed")
def csv_file_read(self, name, missing_values=[]):
try:
path = Config.Data_path / str(name + '.csv')
df = pd.read_csv(path, na_values=missing_values)
self._logger.info(f"{name} file read successfully")
return df
except FileNotFoundError:
self._logger.exception(f"{name} not found")
<file_sep>/README.md
# Breast-Cancer-Diagnosis
Breast-Cancer-Diagnosis
**Table of content**
- [Project Overview](#overview)
- [Requirements](#requirements)
- [Installation](#installation)
- [Data](#data)
- [Scripts](#pacakage_scripts)
## Overview
## Requirements
The project requires Python 3.6+, and python packages listed in `requirements.txt` file
## Installation
1. Creating conda virtual environment [in Linux]
```
conda create -n env
conda activate env
conda config --env --add channels conda-forge
conda config --env --set channel_priority strict
```
2. Cloning the repo and install the dependency packages using `requirements.txt`
```
git clone https://github.com/Caphace-Ethan/Breast-Cancer-Diagnosis
cd Breast-Cancer-Diagnosis
conda install -r requirements.txt or try using pip instead of conda
sudo apt-get install graphviz or conda install python-graphviz
```
## Data
### The Dataset Contains the following Attributes
* radius (mean of distances from center to points on the perimeter)
* texture (standard deviation of gray-scale values)
* perimeter
* area
* smoothness (local variation in radius lengths)
* compactness (perimeter^2 / area - 1.0)
* concavity (severity of concave portions of the contour)
* concave points (number of concave portions of the contour)
* symmetry
* fractal dimension ("coastline approximation" - 1)
The mean, standard error (SE) and "worst" or largest (mean of the three largest values) of these features were computed for each image
## Package_Scripts
Package Scripts are found in ```scripts``` directory, its content is explained below.
- ```FileHandler:``` Helper class for reading and writing different file formats.
- ```package_config: ```Script for handling package configurations such as location of files and url(s), etc.
- ```data_processor: ```Script for performing data processing for example computing missing values, fixing outliers, etc.
- ```plot: ```Script for ploting different figures including box-plot, scatter-plot, histogram, bar-plot, etc.
- ```log: ```script for logging package logs
<file_sep>/scripts/plot.py
# Graph and Diagram Ploting script.
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from log import logger
import logging
import logging.handlers
from project_config import Config
class Plot():
def __init__(self):
self._logger = logger
################### PLOTTING FUNCTIONS #####################
def plot_box(self, df:pd.DataFrame, x_col:str, title:str) -> None:
plt.figure(figsize=(6, 3))
sns.boxplot(data = df, x=x_col)
plt.title(title, size=12)
plt.xticks(rotation=15, fontsize=12)
plt.show()
def plot_hist(self, df:pd.DataFrame, column:str, color:str)->None:
sns.displot(data=df, x=column, color=color, kde=True, height=4, aspect=2)
plt.title(f'Distribution of {column}', size=20, fontweight='bold')
plt.show()
def plot_count(self, df:pd.DataFrame, column:str) -> None:
plt.figure(figsize=(12, 7))
sns.countplot(data=df, x=column)
plt.title(f'Distribution of {column}', size=20, fontweight='bold')
plt.show()
def plot_bar(self, df:pd.DataFrame, x_col:str, y_col:str, title:str, xlabel:str, ylabel:str)->None:
plt.figure(figsize=(6, 4))
sns.barplot(data = df, x=x_col, y=y_col)
plt.title(title, size=20)
plt.xticks(rotation=45, fontsize=12)
plt.yticks( fontsize=14)
plt.xlabel(xlabel, fontsize=13)
plt.ylabel(ylabel, fontsize=13)
plt.show()
def plot_heatmap(self, df:pd.DataFrame, title:str, cbar=False)->None:
plt.figure(figsize=(12, 7))
sns.heatmap(df, annot=True, cmap='viridis', vmin=0, vmax=1, fmt='.2f', linewidths=.7, cbar=cbar )
plt.title(title, size=18, fontweight='bold')
plt.show()
def plot_box(self, df:pd.DataFrame, x_col:str, title:str) -> None:
plt.figure(figsize=(12, 7))
sns.boxplot(data = df, x=x_col)
plt.title(title, size=20)
plt.xticks(rotation=75, fontsize=14)
plt.show()
def plot_box_multi(self, df:pd.DataFrame, x_col:str, y_col:str, title:str) -> None:
plt.figure(figsize=(12, 7))
sns.boxplot(data = df, x=x_col, y=y_col)
plt.title(title, size=20)
plt.xticks(rotation=75, fontsize=14)
plt.yticks( fontsize=14)
plt.show()
def plot_scatter(self, df: pd.DataFrame, x_col: str, y_col: str, title: str, hue: str, style: str) -> None:
plt.figure(figsize=(8, 5))
sns.scatterplot(data = df, x=x_col, y=y_col, hue=hue, style=style)
plt.title(title, size=20)
plt.xticks(fontsize=14)
plt.yticks( fontsize=14)
plt.show()
def heat(self, df, color, size):
corr = df.corr()
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(corr)] = True
plt.figure(figsize=size)
sns.heatmap(corr, mask=mask, annot=True, cmap=color)
plt.show()
def scatter_feature_plot(self, df, feature1, feature2, title, fields):
fig = go.Figure()
fig.update_layout(
title=title,
width=600,
height=400,
margin=dict(
l=20,
r=20,
t=40,
b=20,
)
)
fig.add_trace(go.Scatter(x=df[feature1+"_"+fields[0]],
y=df[feature2+"_"+fields[0]],
mode="markers",
name="mean",
))
fig.add_trace(go.Scatter(x=df[feature1+"_"+fields[1]],
y=df[feature2+"_"+fields[1]],
mode="markers",
name="se",
))
fig.add_trace(go.Scatter(x=df[feature1+"_"+fields[2]],
y=df[feature2+"_"+fields[2]],
mode="markers",
name="worst",
))
fig.show()<file_sep>/scripts/log.py
# Import packages for logging
import logging
import logging.handlers
import os
def logger(filename):
handler = logging.handlers.WatchedFileHandler(
os.environ.get("LOGFILE", f"../logs/{filename}.log"))
formatter = logging.Formatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
root = logging.getLogger()
root.setLevel(os.environ.get("LOGLEVEL", "INFO"))
root.addHandler(handler)
# logging.info("Testing Loggings")
|
68c19592216657c33ecef9ab879fab14f2955bb1
|
[
"Markdown",
"Python"
] | 6 |
Python
|
Caphace-Ethan/Breast-Cancer-Diagnosis
|
a835eab25b4f2bacd09bc23e99fb49a7a7b45cde
|
c47b7b6a07b8720092980f04c7f22adff4c2fc65
|
refs/heads/main
|
<repo_name>EffenrilAgung/tugas_10_react_js<file_sep>/src/App.js
import { Component } from "react";
import 'semantic-ui-css/semantic.min.css'
import { Container, Flag, Grid, Icon, Input, Image, Header, Divider, Label, Button } from 'semantic-ui-react'
class App extends Component {
render() {
return (
<div>
<Container>
<Grid columns='equal' padded devided>
<Grid.Row>
<Grid.Column width={1}>
<Flag name='id' />
</Grid.Column>
<Grid.Column width={2}>
<Icon name='chevron left' />
<Icon name='chevron right' style={{ marginLeft: '50px' }} />
</Grid.Column>
<Grid.Column width={10}>
<Input icon='star' fluid placeholder='Search' />
</Grid.Column>
<Grid.Column width={3}>
<Header as="h3">
<Image src='https://react.semantic-ui.com/images/avatar/large/patrick.png' avatar />
Patrick
</Header>
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
<Divider horizontal>SELAMAT DATANG !!!!</Divider>
<Container>
<Grid columns={2}>
<Grid.Column width={15}>
</Grid.Column>
<Grid.Column width={1}>
<Label as='a' color='teal' tag>
SPORTS
</Label>
</Grid.Column>
</Grid>
</Container>
<Container textAlign='center' style={{ margin: '30px 0' }}>
<p>
Ducati tengah menunggu sidang Pengadilan Banding FIM tentang komponen aerodinamis. Andai gugatan para rivalnya diterima, akankah Ducati akan melanjutkan ke cas(Pengadilan Arbitrase Olahraga)?
Suzuki, Honda, KTM, dan Aprilia memprotes penggunaan komponen aero di motor Desmosedici Andrea Dovizioso dan Danilo Petrucci dalam balapan pertama MotoGP 2019 di Qatar karena dianggap ilegal. Pada prosesnya, Dovizioso tampil sebagai pemenang usai mengalahkan <NAME>.
Keempat tim meyakini, komponen itu memiliki fungsi aerodinamis, dan menghasilkan downforce, yang membantu motor melesat di trek. Sementara Ducati bersikukuh komponen itu cuma untuk mendinginkan ban dan sudah disetujui Technical Director sebelum balapan.Pada awalnya, protes keempat tim itu ditolak oleh steward MotoGP sehingga dibawa ke Pengadilan Banding FIM. Sidang itu sendiri akan dilakukan sebelum seri kedua di Argentina digelar pada 29-31 Maret mendatang.Manajer umum Ducati Gigi Dall'Igna berkukuh tidak ada yang ilegal dengan komponen itu. Namun, seandainya pengadilan mengabulkan gugatan tersebut Ducati akan mempertimbangkan melanjutkan kasus ini ke CAS.
"Di dalam federasi, derajatnya berakhir di Pengadilan Banding FIM. Anda harus pergi ke CAS, yang adalah pengadilan olahraga tapi di dalam kasus ini Anda keluar dari perimeter FIM," Dall'Igna mengungkapkan kepada MotoGP.com.
"Saya bahkan tidak ingin memikirkan sampai titik ini. Kami sangat yakin bahwa kami tidak melanggar regulasi kok, dan yakin kami tidak melihat adanya alasan mengapa pengadilan banding bisa memutuskan secara berbeda."
</p>
<Button icon color='teal' labelPosition='center'>
<Icon name='plus' />
Tambah Tautan Ke List
</Button>
</Container>
</div >
)
}
}
export default App
|
05bdb1be64503deded4b841c266b0c6cf1cf1039
|
[
"JavaScript"
] | 1 |
JavaScript
|
EffenrilAgung/tugas_10_react_js
|
27e6901836181b5fced5d28ca402062eafa2d148
|
f9ae905fdb2464277e8d0f318b0233ebb6065eb8
|
refs/heads/master
|
<repo_name>dengbuqi/melanoma-detection<file_sep>/melanoma/feature_extraction/color_variation.py
import numpy as np
def get_RGB(img):
r_lesion = []
g_lesion = []
b_lesion = []
r_skin = []
g_skin = []
b_skin = []
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if np.array_equal(img[i][j], np.asarray([255,255,255])):
r_lesion.append(img[i][j][0])
g_lesion.append(img[i][j][1])
b_lesion.append(img[i][j][2])
else:
r_skin.append(img[i][j][0])
g_skin.append(img[i][j][1])
b_skin.append(img[i][j][2])
return r_lesion, g_lesion, b_lesion, r_skin, g_skin, b_skin
<file_sep>/melanoma/feature_extraction/binarize.py
import scipy
from scipy import ndimage
def binarize(img, show = False):
#Binarize the image
for idx1 in range(img.shape[0]):
for idx2 in range(img.shape[1]):
if img[idx1][idx2] > 0.9:
img[idx1][idx2] = False
else:
img[idx1][idx2] = True
img = ndimage.binary_fill_holes(img)
return img
<file_sep>/melanoma/feature_extraction/color_homogeneity.py
import skimage
from skimage import color, filter
from skimage.filter import threshold_adaptive, threshold_otsu
from skimage.measure import perimeter, label, regionprops
from binarize import *
from color_variation import *
def get_color_homogeneity(color_img, show = False):
all_var_r = []
all_var_g = []
all_var_b = []
bw_img = skimage.color.rgb2gray(color_img)
binarized_img = binarize(bw_img)
#Find area and perimeter
label_img = label(binarized_img)
region = regionprops(label_img)
area = max([props.area for props in region]) #Want the max because they could be many spaces
#Call function to compute rgb values
r_lesion, g_lesion, b_lesion, r_skin, g_skin, b_skin = get_RGB(color_img)
mean_r_skin = np.mean(r_skin)
mean_g_skin = np.mean(g_skin)
mean_b_skin = np.mean(b_skin)
var_r = 0.
var_g = 0.
var_b = 0.
for i in range(len(r_lesion)):
var_r += (r_lesion[i] - mean_r_skin)**2
var_g += (g_lesion[i] - mean_g_skin)**2
var_b += (b_lesion[i] - mean_b_skin)**2
var_r /= area
var_g /= area
var_b /= area
all_var_r.append(var_r)
all_var_g.append(var_g)
all_var_b.append(var_b)
if(show):
ppl.imshow(color_img)
ppl.show()
return all_var_r, all_var_g, all_var_b
<file_sep>/melanoma/feature_extraction/relative_chromaticity.py
from color_variation import *
def get_relative_chromaticity(img):
r_lesion, g_lesion, b_lesion, r_skin, g_skin, b_skin = get_RGB(img)
rel_r = ((np.mean(r_lesion)) / (np.mean(r_lesion) + np.mean(g_lesion) + np.mean(b_lesion))) \
- (np.mean(r_skin) / (np.mean(r_skin) + np.mean(g_skin) + np.mean(b_skin)))
rel_g = ((np.mean(g_lesion)) / (np.mean(r_lesion) + np.mean(g_lesion) + np.mean(b_lesion))) \
- (np.mean(g_skin) / (np.mean(r_skin) + np.mean(g_skin) + np.mean(b_skin)))
rel_b = ((np.mean(b_lesion)) / (np.mean(r_lesion) + np.mean(g_lesion) + np.mean(b_lesion))) \
- (np.mean(b_skin) / (np.mean(r_skin) + np.mean(g_skin) + np.mean(b_skin)))
return rel_r, rel_g, rel_b
<file_sep>/melanoma/preprocessing/preprocess.py
import scipy
from scipy import ndimage
from scipy.misc import imread, imsave
import skimage
from skimage import color, filter
class Preprocessing():
def preprocess_img(self, img_color):
#Store for later usage
start = img_color
#Convert to black & white
img = skimage.color.rgb2gray(img_color)
print "[PRE-PROCESSING] bw img done"
#Change shape to fixed width of 340
basewidth = img.shape[1] / 340.
img = scipy.misc.imresize(arr = img, size = (int(img.shape[0]/basewidth), int(img.shape[1]/basewidth)))
start = scipy.misc.imresize(arr = start, size = (int(start.shape[0]/basewidth), int(start.shape[1]/basewidth)))
print "[PRE-PROCESSING] size normaliztion done"
#Median filtering
img = ndimage.median_filter(img, 7)
print "[PRE-PROCESSING] median filtering done"
#Sharpening
filter_blurred_l = ndimage.gaussian_filter(img, 1)
alpha = 3
img = img + alpha * (img - filter_blurred_l)
print "[PRE-PROCESSING] sharpening done"
return img, start
<file_sep>/melanoma/preprocessing/macwe.py
import numpy as np
from scipy import ndimage
from itertools import cycle
from scipy.ndimage import binary_dilation, binary_erosion, \
gaussian_filter, gaussian_gradient_magnitude
class fcycle(object):
def __init__(self, iterable):
"""Call functions from the iterable each time it is called."""
self.funcs = cycle(iterable)
def __call__(self, *args, **kwargs):
f = self.funcs.next()
return f(*args, **kwargs)
# SI and IS operators for 2D and 3D.
_P2 = [np.eye(3), np.array([[0,1,0]]*3), np.flipud(np.eye(3)), np.rot90([[0,1,0]]*3)]
_P3 = [np.zeros((3,3,3)) for i in xrange(9)]
_P3[0][:,:,1] = 1
_P3[1][:,1,:] = 1
_P3[2][1,:,:] = 1
_P3[3][:,[0,1,2],[0,1,2]] = 1
_P3[4][:,[0,1,2],[2,1,0]] = 1
_P3[5][[0,1,2],:,[0,1,2]] = 1
_P3[6][[0,1,2],:,[2,1,0]] = 1
_P3[7][[0,1,2],[0,1,2],:] = 1
_P3[8][[0,1,2],[2,1,0],:] = 1
_aux = np.zeros((0))
def SI(u):
"""SI operator."""
global _aux
if np.ndim(u) == 2:
P = _P2
elif np.ndim(u) == 3:
P = _P3
else:
raise ValueError, "u has an invalid number of dimensions (should be 2 or 3)"
if u.shape != _aux.shape[1:]:
_aux = np.zeros((len(P),) + u.shape)
for i in xrange(len(P)):
_aux[i] = binary_erosion(u, P[i])
return _aux.max(0)
def IS(u):
"""IS operator."""
global _aux
if np.ndim(u) == 2:
P = _P2
elif np.ndim(u) == 3:
P = _P3
else:
raise ValueError, "u has an invalid number of dimensions (should be 2 or 3)"
if u.shape != _aux.shape[1:]:
_aux = np.zeros((len(P),) + u.shape)
for i in xrange(len(P)):
_aux[i] = binary_dilation(u, P[i])
return _aux.min(0)
# # SIoIS operator.
SIoIS = lambda u: SI(IS(u))
ISoSI = lambda u: IS(SI(u))
curvop = fcycle([SIoIS, ISoSI])
# Stopping factors (function g(I) in the paper).
def gborders(img, alpha=1.0, sigma=1.0):
"""Stopping criterion for image borders."""
# The norm of the gradient.
gradnorm = gaussian_gradient_magnitude(img, sigma, mode='constant')
return 1.0/np.sqrt(1.0 + alpha*gradnorm)
def glines(img, sigma=1.0):
"""Stopping criterion for image black lines."""
return gaussian_filter(img, sigma)
class MorphGAC(object):
"""Morphological GAC based on the Geodesic Active Contours."""
def __init__(self, data, smoothing=1, threshold=0, balloon=0):
self._u = None
self._v = balloon
self._theta = threshold
self.smoothing = smoothing
self.set_data(data)
def set_levelset(self, u):
self._u = np.double(u)
self._u[u>0] = 1
self._u[u<=0] = 0
def set_balloon(self, v):
self._v = v
self._update_mask()
def set_threshold(self, theta):
self._theta = theta
self._update_mask()
def set_data(self, data):
self._data = data
self._ddata = np.gradient(data)
self._update_mask()
# The structure element for binary dilation and erosion.
self.structure = np.ones((3,)*np.ndim(data))
def _update_mask(self):
"""Pre-compute masks for speed."""
self._threshold_mask = self._data > self._theta
self._threshold_mask_v = self._data > self._theta/np.abs(self._v)
levelset = property(lambda self: self._u,
set_levelset,
doc="The level set embedding function (u).")
data = property(lambda self: self._data,
set_data,
doc="The data that controls the snake evolution (the image or g(I)).")
balloon = property(lambda self: self._v,
set_balloon)
threshold = property(lambda self: self._theta,
set_threshold,
doc="The threshold value (0).")
def step(self):
"""Perform a single step of the morphological snake evolution."""
# Assign attributes to local variables for convenience.
u = self._u
gI = self._data
dgI = self._ddata
theta = self._theta
v = self._v
if u is None:
raise ValueError, "the levelset is not set (use set_levelset)"
res = np.copy(u)
# Balloon.
if v > 0:
aux = binary_dilation(u, self.structure)
elif v < 0:
aux = binary_erosion(u, self.structure)
if v!= 0:
res[self._threshold_mask_v] = aux[self._threshold_mask_v]
# Image attachment.
aux = np.zeros_like(res)
dres = np.gradient(res)
for el1, el2 in zip(dgI, dres):
aux += el1*el2
res[aux > 0] = 1
res[aux < 0] = 0
# Smoothing.
for i in xrange(self.smoothing):
res = curvop(res)
self._u = res
def run(self, iterations):
"""Run several iterations of the morphological snakes method."""
for i in xrange(iterations):
self.step()
class MorphACWE(object):
"""Morphological ACWE based on the Chan-Vese energy functional."""
c01 = []
def __init__(self, data, smoothing=1, lambda1=1, lambda2=1):
"""Create a Morphological ACWE solver.
Parameters
----------
data : ndarray
The image data.
smoothing : scalar
The number of repetitions of the smoothing step (the
curv operator) in each iteration. In other terms,
this is the strength of the smoothing. This is the
parameter u.
lambda1, lambda2 : scalars
Relative importance of the inside pixels (lambda1)
against the outside pixels (lambda2).
"""
self._u = None
self.smoothing = smoothing
self.lambda1 = lambda1
self.lambda2 = lambda2
self.data = data
def set_levelset(self, u):
self._u = np.double(u)
self._u[u>0] = 1
self._u[u<=0] = 0
levelset = property(lambda self: self._u,
set_levelset,
doc="The level set embedding function (u).")
def step(self):
"""Perform a single step of the morphological Chan-Vese evolution."""
# Assign attributes to local variables for convenience.
u = self._u
if u is None:
raise ValueError, "the levelset function is not set (use set_levelset)"
data = self.data
# Determine c0 and c1.
inside = u>0
outside = u<=0
c0 = data[outside].sum() / float(outside.sum())
c1 = data[inside].sum() / float(inside.sum())
# Image attachment.
dres = np.array(np.gradient(u))
abs_dres = np.abs(dres).sum(0)
aux = abs_dres * (c0 - c1) * (c0 + c1 - 2*data)
aux = abs_dres * (self.lambda1*np.square(data - c1) - self.lambda2*np.square(data - c0))
res = np.copy(u)
res[aux < 0] = 1
res[aux > 0] = 0
# Smoothing.
for i in xrange(self.smoothing):
res = curvop(res)
self._u = res
def run(self, iterations):
"""Run several iterations of the morphological Chan-Vese method."""
for i in xrange(iterations):
self.step()
def evolve(msnake, levelset=None, num_iters=20, background=None):
from matplotlib import pyplot as ppl
if levelset is not None:
msnake.levelset = levelset
for i in xrange(num_iters):
msnake.step()
return msnake.levelset
def circle_levelset(shape, center, sqradius,scalerow=1.0):
"""Build a binary function with a circle as the 0.5-levelset."""
grid = np.mgrid[map(slice, shape)].T - center
phi = sqradius - np.sqrt(np.sum((grid.T)**2, 0))
u = np.float_(phi > 0)
return u
def extract_lesion(img, start):
macwe = MorphACWE(img, smoothing=4, lambda1=1, lambda2=1)
macwe.levelset = circle_levelset(img.shape, (100, 170), 50)
end_snake = evolve(macwe, num_iters=150, background=img)
bool_end = end_snake.astype(bool)
curr_bool = np.invert(bool_end)
start[curr_bool] = 255
print "[PRE-PROCESSING] Separated lesion from image"
return start
<file_sep>/melanoma/feature_extraction/feature_extractor.py
from centroid import *
from color_variation import *
from color_homogeneity import *
from relative_chromaticity import *
from asymmetry_index import *
from border_irregularity import *
import skimage
from skimage import color, filter
import numpy as np
class FeatureExtractor():
def normalize_feature(self, feature):
feature_mean = np.mean(feature)
feature_stddev = np.std(feature)
return (feature - feature_mean) / feature_stddev
def get_features(self, color_img):
#Convert to black and white
bw_img = skimage.color.rgb2gray(color_img)
#Get centroid for later usage
max_rad_point, max_rad, outline_img, centroid_to_edges, centroid = get_centroid(bw_img)
print "[FEATURE] Centroid retrieved"
#Getting the ratio of the radius of the image
ratio = max_rad
print "[FEATURE] Radius retrieved"
#Color Variation
r_lesion, g_lesion, b_lesion, r_skin, g_skin, b_skin = get_RGB(color_img)
print "[FEATURE] Color Variation retrieved"
#Color Homogeneity Varianceo
all_var_r, all_var_g, all_var_b = get_color_homogeneity(color_img)
normalized_var_r = all_var_r
normalized_var_g = all_var_g
normalized_var_b = all_var_b
print "[FEATURE] Color Homogeneity retrieved"
#Relative Chromaticity of RGB
rel_r, rel_g, rel_b = get_relative_chromaticity(color_img)
normalized_rel_r = rel_r
normalized_rel_g = rel_g
normalized_rel_b = rel_b
print "[FEATURE] Relative Chromaticity of RGB retrieved"
#Finding Asymmetry of Image
asymmetry_index = get_asymmetry_index(color_img)
print "[FEATURE] Asymmetry Index retrieved"
#Border Irregularity Compactness Index
border_irregularity_compactness_index = get_border_irregularity_ci(color_img)
print "[FEATURE] Border Irregularity Compactness Index"
#Border Irregularity - Edge Abruptness
border_irregularity_edge_abruptness = get_border_edge_abruptness(color_img)
print "[FEATURE] Border Irregularity Edge Abruptness"
return np.asarray([
normalized_var_r[0], #ColorHomogeneityVariance (R)
normalized_var_g[0], #ColorHomogeneityVariance (G)
normalized_var_b[0], #ColorHomogeneityVariance (B)
normalized_rel_r, #ColorRelativeChromaticity (R)
normalized_rel_g, #ColorRelativeChromaticity (G)
normalized_rel_b, #ColorRelativeChromaticity (B)
asymmetry_index, #TODO Getting none
border_irregularity_compactness_index,
border_irregularity_edge_abruptness
])
<file_sep>/melanoma/feature_extraction/centroid.py
import scipy
from scipy import ndimage
import numpy as np
from binarize import *
def get_centroid(curr_img):
curr_img = binarize(curr_img, show = True)
outline_img = np.zeros((curr_img.shape[0], curr_img.shape[1]), dtype=bool)
for i in range(1, curr_img.shape[0] - 1):
for j in range(1, curr_img.shape[1] - 1):
if (curr_img[i][j] == True): #if black...
if((curr_img[i-1][j-1] == False) or
(curr_img[i-1][j] == False) or
(curr_img[i+1][j+1] == False) or
(curr_img[i][j+1] == False) or
(curr_img[i+1][j] == False) or
(curr_img[i][j-1] == False) or
(curr_img[i-1][j+1] == False) or
(curr_img[i+1][j-1] == False)):
outline_img[i][j] = True
else:
outline_img[i][j] = False
#Find centroid
centroid = scipy.ndimage.measurements.center_of_mass(outline_img)
#Use euclidean to find distances
centroid_to_edges = []
max_rad = -1
max_x = -1
max_y = -1
for i in range(outline_img.shape[0]):
for j in range(outline_img.shape[1]):
if outline_img[i][j] == True:
curr_diam = (np.abs(i - centroid[0])**2) + (np.abs(j - centroid[1])**2)
curr_diam = np.sqrt(curr_diam)
if(curr_diam > max_rad):
max_rad = curr_diam
max_x = i
max_y = j
centroid_to_edges.append(curr_diam)
return (max_y, max_x), max_rad, outline_img, centroid_to_edges, centroid[::-1]
<file_sep>/melanoma/__init__.py
from flask import Flask, request
import scipy
from scipy import ndimage
from scipy.misc import imread, imsave
import skimage
from skimage import color, filter
from preprocessing.preprocess import *
from preprocessing.macwe import *
from feature_extraction.feature_extractor import *
from ml.prediction_model import *
from flask import json
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/predict', methods=['POST'])
def predict():
#Retrieve image
img_url = request.data
img = imread(app.root_path + "/img/" + img_url)/255.
#Preprocess
p = Preprocessing()
preprocessed_img, start = p.preprocess_img(img)
#Extract lesion from image
img_lesion = extract_lesion(preprocessed_img, start)
imsave(app.root_path + "/img/processed/" + img_url, img_lesion)
#Feature Extraction
f = FeatureExtractor()
features = f.get_features(img_lesion)
#Call trained model
prediction_prob = predict_input(features)
#Send back response in JSON
json_str = {}
json_str['probability_false'] = prediction_prob[0][0]
json_str['probability_true'] = prediction_prob[0][1]
response = app.response_class(
response = json.dumps(json_str),
status = 200,
mimetype='application/json'
)
return response
<file_sep>/melanoma/feature_extraction/asymmetry_index.py
import numpy as np
import skimage
from skimage import color, filter
def checkOverlap(shape1, shape2):
#Find the accuracy of symmetry
all_pixels = 0.
correct = 0.
wrong = 0.
for i in range(shape1.shape[0]):
for j in range(shape1.shape[1]):
curr_pixel1 = (shape1[i][j])
curr_pixel2 = (shape2[i][j])
if(curr_pixel1 or curr_pixel2):
all_pixels += 1
if(curr_pixel1 and curr_pixel2):
correct += 1
else:
wrong += 1
return correct, wrong, all_pixels
def get_asymmetry_index(img):
imgcolor = img
img = skimage.color.rgb2gray(img)
x = []
y = []
#DOING FOR THE FIRST TIME TO GET LEFT AND TOP
top = np.zeros((img.shape[0], img.shape[1]), dtype=bool)
left = np.zeros((img.shape[0], img.shape[1]), dtype=bool)
#Don't want to take the white parts
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if img[i][j] != 1:
x.append(j)
y.append(i)
# Trying to find center, x-intercept and y-intercept
centroid = (sum(x) / len(x), sum(y) / len(y))
y_axis = centroid[1]
x_axis = centroid[0]
#Performing splitting for top/down images
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if(img[i][j] < 0.95):
if(i < y_axis):
top[i][j] = True
#Performing splitting for left/right images
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if (img[i][j] < 0.95):
if (j < x_axis):
left[i][j] = True
#DOING FOR FLIP UP/DOWN TO GET THE DOWN PART
flipped_ud = np.flipud(img)
bottom = np.zeros((flipped_ud.shape[0], flipped_ud.shape[1]), dtype=bool)
#Performing splitting for top/down images
for i in range(flipped_ud.shape[0]):
for j in range(flipped_ud.shape[1]):
if(flipped_ud[i][j] < 0.95):
if(i < y_axis):
bottom[i][j] = True
#DOING FOR FLIP UP/DOWN TO GET THE DOWN PART
flipped_lr = np.fliplr(img)
right = np.zeros((flipped_lr.shape[0], flipped_lr.shape[1]), dtype=bool)
#Performing splitting for top/down images
for i in range(flipped_lr.shape[0]):
for j in range(flipped_lr.shape[1]):
if(flipped_lr[i][j] < 0.95):
if(j < x_axis):
right[i][j] = True
correct_TB, wrong_TB, all_TB = checkOverlap(top, bottom)
correct_LR, wrong_LR, all_LR = checkOverlap(left, right)
return 1 - sum([correct_TB / all_TB, correct_TB / all_LR])/2.
<file_sep>/melanoma/feature_extraction/border_irregularity.py
from binarize import *
import skimage
from skimage.measure import perimeter, label, regionprops
from skimage import color, filter
import math
from centroid import *
def get_border_irregularity_ci(img, show = False):
img = skimage.color.rgb2gray(img)
img = binarize(img)
#Find area and perimeter
label_img = label(img)
region = regionprops(label_img)
img_area = max([props.area for props in region]) #Want the max because they could be many spaces
img_perimeter = max([props.perimeter for props in region])
#Calculate CI's formula
return (img_perimeter**2) / (4.*math.pi*img_area)
def get_border_edge_abruptness(img, show = False):
#Import lesion and convert it to black/white
img = skimage.color.rgb2gray(img)
#Get the centroid and distances to edgesx
_max_rad_pt, _max_rad, outline_img, centroid_to_edges, centroid = get_centroid(img)
#Get the average distance
mean_dist = np.mean(centroid_to_edges)
binarized_img = img.astype(bool)
binarized_img = ndimage.binary_fill_holes(binarized_img)
#Get the perimeter of image
label_img = label(binarized_img)
region = regionprops(label_img)
img_perimeter = max([props.perimeter for props in region])
edge_score = 0.
for d in centroid_to_edges:
edge_score += (d - mean_dist)**2
edge_score /= (img_perimeter * (mean_dist**2))
return edge_score
<file_sep>/melanoma/ml/prediction_model.py
from sklearn.externals import joblib
from flask import Flask, request
app = Flask(__name__)
def predict_input(feature_list):
clf = retrieve_classifier()
#prediction_class = clf.predict(feature_list)
prediction_prob = clf.predict_proba(feature_list)
#print "[Prediction] Prediction class" + str(prediction_class)
print "[Prediction] Prediction probability" + str(prediction_prob)
return prediction_prob
def retrieve_classifier():
clf = joblib.load(app.root_path + "/linear_model.pkl")
return clf
|
127f5b112fa5f72afb93fc94a70287b3bce2c6db
|
[
"Python"
] | 12 |
Python
|
dengbuqi/melanoma-detection
|
e9f392919f4e364f9effc8139ca5df9cd2d2109d
|
b73241b4c3a9342c252fc1ac5dcacd346f51c02a
|
refs/heads/master
|
<repo_name>akrylysov/lambda-phantom-scraper<file_sep>/scraper/index.js
var path = require('path');
var childProcess = require('child_process');
var phantomJsPath = require('phantomjs-prebuilt').path;
exports.scrape = function(url, callback) {
var childArgs = [path.join(__dirname, 'phantomjs-script.js')];
var phantom = childProcess.execFile(phantomJsPath, childArgs, {
env: {
URL: url
},
maxBuffer: 2048*1024
});
var stdout = '';
var stderr = '';
phantom.stdout.on('data', function(data) {
stdout += data;
});
phantom.stderr.on('data', function(data) {
stderr += data;
});
phantom.on('uncaughtException', function(err) {
console.log('uncaught exception: ' + err);
});
phantom.on('exit', function(exitCode) {
if (exitCode !== 0) {
return callback(true, stderr);
}
callback(null, stdout);
});
};
<file_sep>/deploy.sh
#!/usr/bin/env bash
PACKAGE=lambda-phantom-scraper.zip
OUTPUT=dist
aws lambda update-function-code \
--region us-east-1 \
--function-name lambda-phantom-scraper \
--zip-file fileb://$PWD/$OUTPUT/$PACKAGE
<file_sep>/devserver.js
var express = require('express');
var bodyParser = require('body-parser');
var lambda = require('./lambda');
var app = express();
app.use(bodyParser.json());
app.post('/', function(req, res) {
lambda.handler(req.body, {}, function(err, result) {
if (err) {
return res.send(err);
}
res.send(result);
});
});
app.listen(3000);
<file_sep>/README.md
Lambda Phantom Scraper
======================
An example of PhantomJS/Node.js web scraper for AWS Lambda.
This repository contains the source code for "Scraping the Web with AWS Lambda and PhantomJS" [talk](https://speakerdeck.com/akrylysov/scraping-the-web-with-aws-lambda-and-phantomjs) given at Greater Philadelphia AWS User Group meetup on May 25, 2016.
<file_sep>/lambda.js
var scrapper = require('./scraper');
exports.handler = function(event, context, callback) {
if (event.url) {
scrapper.scrape(event.url, function(err, result) {
if (err) {
return callback(null, {error: result});
}
callback(null, {result: result});
})
}
else {
callback(null, {error: 'bad query'});
}
};
<file_sep>/build.sh
#!/usr/bin/env bash
PACKAGE=lambda-phantom-scraper.zip
OUTPUT=dist
TMP=.tmp
mkdir $TMP
mkdir $OUTPUT
rm $OUTPUT/$PACKAGE
rsync -rv --exclude=node_modules --exclude=dist --exclude=.tmp . $TMP
pushd $TMP
PHANTOMJS_PLATFORM=linux PHANTOMJS_ARCH=x64 npm install phantomjs-prebuilt --phantomjs_cdnurl=http://cnpmjs.org/downloads --save
zip -r ../$OUTPUT/$PACKAGE ./*
popd
|
5ae3db62e058065bbb4697dc9914bbda1818af99
|
[
"JavaScript",
"Markdown",
"Shell"
] | 6 |
JavaScript
|
akrylysov/lambda-phantom-scraper
|
8d42b3a9f4197fcbb5eb7e3957366da9ee26f3e4
|
b2ffd0ea728b674c09b1b2e199f906b56680937a
|
refs/heads/master
|
<repo_name>Adriansip/sistema3rios<file_sep>/database/migrations/2018_12_12_175331_create_estatus.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEstatus extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('estatus', function (Blueprint $table) {
$table->increments('idEstatus');
$table->Integer('idBitacora');
$table->Integer('idCapturador');
$table->string('lugar');
$table->Integer('noTransito');
$table->date('fecha');
$table->time('hora');
$table->Integer('idObservacion');
$table->text('otro')->nullable();
$table->boolean('entregado')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('estatus');
}
}
<file_sep>/app/Capturistas.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Capturistas extends Model
{
protected $table="capturadores";
protected $fillable=[
'idCapturador','nombre','correo','telefono','idCiudad','direccion',
];
}
<file_sep>/app/Http/Requests/ClientesUpdateRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ClientesUpdateRequest 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 [
'nombre' => 'required',
'correo' => ['required', Rule::unique('clientes')->ignore($this->idCliente,'idCliente'),], //No olvidar importar la clase
//'correo' => 'required|email|unique:clientes,'.'idCliente',
'telefono' => 'required|min:8',
'direccion' => 'required',
'distancia' => 'required'
];
}
}
<file_sep>/app/Exports/EstatusExport.php
<?php
namespace App\Exports;
use App\Estados;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class EstatusExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return Estados::all();
}
public function headings(): array
{
return [
'# Transito',
'Lugar',
];
}
}
<file_sep>/app/Http/Controllers/EstatusController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\EstatusExport;
use App\Http\Requests\EstatusUpdateRequest;
use App\Http\Requests\EstatusStoreRequest;
use App\Estatus;
use App\Observaciones;
use App\Bitacora;
use App\Estados;
use App\Ciudades;
use App\Clientes;
use Session;
use Redirect;
class EstatusController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$clientes=Clientes::all();
$estados=Estados::all();
if(count($clientes)>0 && count($estados)>0){
return view('estatus.index',compact('clientes','estados'));
}else{
Session::flash('message','No hay registros en la BD');
Session::flash('class','danger');
return Redirect::to('/');
}
}
public function getEstatus($idEstatus){
$estatus=Estatus::find($idEstatus);
$ciudad=explode(",",$estatus->lugar);
$ciudad=Ciudades::where('ciudad',$ciudad[0])->first();
$data=array(
"estatus" => $estatus,
"idCiudad" => $ciudad->idCiudad,
"idEstado" => $ciudad->estado->idEstado
);
return $data;
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(EstatusStoreRequest $request,$idBitacora)
{
$estatus=new Estatus;
$estatus->idBitacora=$idBitacora;
$estatus->idCapturador=1; //PEndiente
$noEmbarque=$estatus->bitacora->noEmbarque;
//Armar lugar Edo, ciudad
$idCiudad=$request->input('idCiudad');
$ciudad=Ciudades::where('idCiudad',$idCiudad)->first();
$estado=$ciudad->estado->estado;
//Guardar lugar
$estatus->lugar=$ciudad->ciudad.", ".$estado;
$estatus->noTransito=$request->input('noTransito');
$estatus->fecha=$request->input('fecha');
$estatus->hora=$request->input('hora');
$estatus->idObservacion=$request->input('idObservacion');
$estatus->otro=$request->input('otro');
//Convertir a true
$entregado=$request->input('entregado');
if($entregado){
$estatus->entregado=true;
}
if($estatus->save()){
Session::flash('message','Estatus guardado correctamente');
Session::flash('class','success');
}else{
Session::flash('message','Ha ocurrido un error');
Session::flash('class','danger');
}
return back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
//Buscar por cliente
$dato=$request->input('cliente');
if($dato==null){ //Si cliente esta vacio
$dato=$request->input('noEmbarque'); //Buscar por numero de embarque
if($dato!=null){
$bitacoras=Bitacora::where('noEmbarque',$dato)->get();
}else{ //Si ambos datos vienen vacio
Session::flash('message','Por favor ingrese un dato');
Session::flash('class','danger');
return Redirect::to('/Estatus');
}
}else{
//Si consulta por cliente debemos mostrar todos los estatus de cada bitacora
$bitacoras=Bitacora::where('idCliente',$dato)->get();
}
if(count($bitacoras)==0){
Session::flash('message','El cliente u orden de embarque no tienen registros');
Session::flash('class','warning');
return Redirect::to('/Estatus');
}
return view('estatus.ver',compact('bitacoras'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($noEmbarque)
{
$bitacora=Bitacora::where('noEmbarque',$noEmbarque)->first();
if($bitacora!=null){
$transito=$bitacora->estatus->last();
if($transito==null){
$transito=1;
}else{
$transito=($transito->noTransito)+1;
}
$estados=Estados::all();
$observaciones=Observaciones::all();
return view('estatus.agregar',compact('bitacora','estados','observaciones','transito'));
}else{
//PEndiente retornar mensage de session y checar ruta
return 'No hay registros';
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(EstatusUpdateRequest $request,$idEstatus)
{
$estatus=Estatus::find($idEstatus);
$estatus->fill($request->all());
//Convertir a true
$entregado=$request->input('entregado');
if($entregado){
$estatus->entregado=true;
}else{
$estatus->entregado=null;
}
if($estatus->save()){
Session::flash('message','Estatus actualizado correctamente');
Session::flash('class','success');
}else{
Session::flash('message','Ha ocurrido un error');
Session::flash('class','danger');
}
return back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$id=$request->input('eliminar');
Estatus::destroy($id);
Session::flash('message','Estatus eliminado correctamente');
Session::flash('class','success');
return back();
}
public function excel($idBitacora)
{
return Excel::download(new EstatusExport,'Estados.xlsx');
}
}
<file_sep>/app/Ciudades.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Estados;
class Ciudades extends Model
{
protected $table="ciudades";
protected $fillable=[
'idEstado','ciudad',
];
protected $primaryKey='idCiudad';
public function estado(){
return $this->belongsTo('App\Estados','idEstado');
}
}
<file_sep>/app/Http/Controllers/ClientesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ClientesStoreRequest;
use App\Http\Requests\ClientesUpdateRequest;
use Illuminate\Support\Facades\Input;
use App\Estados;
use App\Clientes;
use App\Ciudades;
use Session;
use Redirect;
class ClientesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$clientes=Clientes::all();
$estados=Estados::all();
return view('cliente.index',compact('clientes','estados'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$estados=Estados::all();
return view('cliente.insertar',compact('estados'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(ClientesStoreRequest $request)
{
$cliente=new Clientes;
$cliente->nombre=$request->input('nombre');
$cliente->correo=$request->input('correo');
$cliente->telefono=$request->input('telefono');
$cliente->idCiudad=$request->input('idCiudad');
$cliente->direccion=$request->input('direccion');
$cliente->distancia=$request->input('distancia');
if($cliente->save()){
Session::flash('message','Cliente guardado correctamente');
Session::flash('class','success');
}else{
Session::flash('message','Ha ocurrido un error');
Session::flash('class','danger');
}
return back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($idCliente)
{
return Clientes::find($idCliente);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(ClientesUpdateRequest $request, $id)
{
$cliente=Clientes::find($id);
$cliente->fill($request->all());
if($cliente->save()){
Session::flash('message','Cliente actualizado correctamente');
Session::flash('class','success');
}else{
Session::flash('message','Ha ocurrido un error');
Session::flash('class','danger');
}
return back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Clientes::destroy($id);
Session::flash('message','Cliente eliminado correctamente');
Session::flash('class','success');
return back();
}
}
<file_sep>/app/Estatus.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Observaciones;
use App\Bitacora;
class Estatus extends Model
{
protected $table="estatus";
protected $fillable=[
'idEstatus','idBitacora','idCapturador','lugar','noTransito','fecha','hora','idObservacion','otro',
];
protected $primaryKey='idEstatus';
public function observacion(){
return $this->belongsTo(Observaciones::class,'idObservacion');
}
public function bitacora(){
return $this->belongsTo(Bitacora::class,'idBitacora');
}
}
<file_sep>/app/Estados.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Ciudades;
class Estados extends Model
{
protected $table="estados";
protected $fillable=[
'estado',
];
protected $primaryKey='idEstado';
public function ciudades(){
return $this->hasMany('App\Ciudades','idEstado');
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/Estatus','EstatusController@index');
Route::post('/Estatus/mostrar','EstatusController@show');
Route::get('/Estatus/{idBitacora}/excel','EstatusController@excel');
Auth::routes();
Route::group(['middleware'=> ['admin']],function(){
Route::get('/Clientes','ClientesController@index');
Route::get('/Cliente/nuevo','ClientesController@create');
Route::get('/Cliente/{idCliente}','ClientesController@show');
Route::post('/Cliente/nuevo/add','ClientesController@store');
Route::post('/Cliente/actualizar/{idCliente}','ClientesController@update');
Route::get('/Cliente/eliminar/{idCliente}','ClientesController@destroy');
Route::get('/Bitacora','BitacoraController@index');
Route::get('/Bitacora/listar/{idBitacora}','BitacoraController@show');
Route::get('/Bitacora/crear','BitacoraController@create');
Route::post('/Bitacora/add','BitacoraController@store');
Route::post('/Bitacora/actualizar/{idBitacora}','BitacoraController@update');
Route::get('/Bitacora/editar/{idBitacora}','BitacoraController@edit');
Route::get('/Bitacora/eliminar/{idBitacora}','BitacoraController@destroy');
Route::post('/Estatus/create/{idBitacora}','EstatusController@store');
Route::get('/Estatus/agregar/{noEmbarque}','EstatusController@edit');
Route::post('/Estatus/eliminar','EstatusController@destroy');
Route::post('/Estatus/actualizar/{idEstatus}','EstatusController@update');
Route::get('/Estatus/listar/{idEstatus}','EstatusController@getEstatus');
Route::get('/Ciudades/{idCiudad}','CiudadesController@show');
});
Route::get('/home', 'HomeController@index')->name('home');
<file_sep>/database/migrations/2018_12_12_183053_create_clientes.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClientes extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('clientes', function (Blueprint $table) {
$table->increments('idCliente');
$table->string('nombre');
$table->string('correo')->unique();
$table->string('telefono',15);
$table->Integer('idCiudad');
$table->text('direccion');
$table->float('distancia',8,2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('clientes');
}
}
<file_sep>/database/seeds/RolTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Roles;
class RolTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$rol=new Roles();
$rol->rol='admin';
$rol->descripcion='Administrador';
$rol->save();
$rol=new Roles();
$rol->rol='invitado';
$rol->descripcion='Invitado';
$rol->save();
}
}
<file_sep>/app/Bitacora.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bitacora extends Model
{
protected $table="bitacora";
protected $fillable=[
'idBitacora','idCliente','noEmbarque','kilosBrutos','kilosNetos','numeroTarimas',
];
protected $primaryKey='idBitacora';
public function estatus()
{
//Campo que comparten ambos
return $this->hasMany(Estatus::class,'idBitacora');
}
public function cliente()
{
return $this->belongsTo(Clientes::class,'idCliente');
}
}
<file_sep>/database/migrations/2018_12_12_183402_create_capturadores.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCapturadores extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('capturadores', function (Blueprint $table) {
$table->increments('idCapturador');
$table->string('nombre');
$table->string('correo')->unique();
$table->string('contrasenia');
$table->string('telefono',15);
$table->Integer('idCiudad');
$table->text('direccion');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('capturadores');
}
}
<file_sep>/database/seeds/UserTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\User;
use App\Roles;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$rol_usuario=Roles::where('rol','invitado')->first();
$rol_admin=Roles::where('rol','admin')->first();
$usuario=new User();
$usuario->name="Invitado";
$usuario->email='<EMAIL>';
$usuario->password=bcrypt('<PASSWORD>');
$usuario->save();
$usuario->roles()->attach($rol_usuario);
$usuario=new User();
$usuario->name="Adrian";
$usuario->email='<EMAIL>';
$usuario->password=bcrypt('<PASSWORD>%()');
$usuario->save();
$usuario->roles()->attach($rol_admin);
}
}
<file_sep>/app/Observaciones.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Observaciones;
class Observaciones extends Model
{
protected $table="observaciones";
protected $fillable=[
'observacion',
];
protected $primaryKey='idObservacion';
public function estatus(){
return $this->belongsTo(Estatus::class);
}
}
<file_sep>/public/js/estatus/estatus.js
$('#estados').on('change',function(){
getCiudades($(this).val());
});
$('.editar').on('click',function(){
getEstatus($(this).val());
$(".modal-title").text("Editar Estatus");
});
$("#btnAgregar").on("click",function(){
//Obtener idBitacora
var idBitacora=$("#bitacora").attr("data-id");
//Proteger noTransito
$('input[name=noTransito]').attr("readonly",true);
//Resetear combobox
$("#estados").find(":selected").attr("selected",false);
$("#estados option[value='1']").attr("selected",true);
getCiudades(1);
//Limpiar inputs si se presiono editar
$("#frmAgregar")[0].reset();
$('textarea[name=otro]').text("");
$("#observaciones").find(":selected").attr("selected",false);
$(".modal-title").text("Nuevo Estatus");
$("#frmAgregar").attr("action","/Estatus/create/"+idBitacora);
$("#btnRegistrar").val("Agregar");
$("#btnRegistrar").addClass("btn-success");
$("#btnRegistrar").removeClass("btn-info");
});
function getEstatus(idEstatus, ciudad) {
$('input[name=noTransito]').removeAttr("readonly");
//AJAX (Checar version de jQuery)
$.get("/Estatus/listar/"+idEstatus,function(data){
//console.log(data);
$('input[name=noTransito]').val(data.estatus.noTransito);
$('input[name=fecha]').val(data.estatus.fecha);
$('input[name=hora]').val(data.estatus.hora);
$("#estados").find(":selected").attr("selected",false);
$("#estados option[value='"+data.idEstado+"']").attr("selected",true);
getCiudades(data.idEstado,data.idCiudad);
$("#observaciones").find(":selected").attr("selected",false);
$("#observaciones option[value='"+data.estatus.idObservacion+"']").attr("selected",true);
//Llenar otro
if(data.estatus.otro!=null){
$('textarea[name=otro]').html(data.estatus.otro);
}else{
$('textarea[name=otro]').html(null);
}
if(data.estatus.entregado!=null){
$('input[name=entregado]').attr("checked","true");
}else{
$('input[name=entregado]').removeAttr("checked");
}
});
$('#frmAgregar').attr('action','/Estatus/actualizar/'+idEstatus);
$("#btnRegistrar").val("Actualizar");
$("#btnRegistrar").removeClass("btn-success");
$("#btnRegistrar").addClass("btn-info");
}<file_sep>/app/Http/Controllers/BitacoraController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\BitacoraStoreRequest;
use App\Http\Requests\BitacoraUpdateRequest;
use Session;
use Redirect;
use App\Clientes;
use App\Bitacora;
use App\Estados;
class BitacoraController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$bitacoras=Bitacora::all();
return view('bitacora.index',compact('bitacoras'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$clientes=Clientes::all();
$estados=Estados::all();
return view('bitacora.crear',compact('clientes','estados'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(BitacoraStoreRequest $request)
{
$bitacora=new Bitacora;
$bitacora->fill($request->all());
if($bitacora->save()){
Session::flash('message','Bitacora creada correctamente');
Session::flash('class','success');
}else{
Session::flash('message','Ha ocurrido un error');
Session::flash('class','danger');
}
return redirect('/Bitacora');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
return Bitacora::find($id);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$clientes=Clientes::all();
$estados=Estados::all();
return view('bitacora.crear',compact('id','clientes','estados'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(BitacoraUpdateRequest $request, $id)
{
$bitacora=Bitacora::find($id);
$bitacora->fill($request->all());
if($bitacora->save()){
Session::flash("message","Bitacora Actualizada");
Session::flash("class","success");
}else {
Session::flash("message","Ha ocurrido un error");
Session::flash("class","danger");
}
return back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Bitacora::destroy($id);
Session::flash('message','Bitacora eliminada correctamente');
Session::flash('class','success');
return back();
}
}
<file_sep>/app/Clientes.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clientes extends Model
{
protected $table="clientes";
protected $fillable=[
'idCliente','nombre','correo','telefono','idCiudad','direccion','distancia',
];
protected $primaryKey='idCliente';
public function bitacoras()
{
return $this->hasMany(Bitacoras::class,'idCliente');
}
public function ciudad()
{
return $this->belongsTo(Ciudades::class,'idCiudad');
}
}
<file_sep>/public/js/bitacora/editar.js
//Obtener el id de la URL
var idBitacora=window.location.pathname.split("/")[3];
$("#titulo").text("Editar Bitacora");
$("#frmAgregar").attr("action","/Bitacora/actualizar/"+idBitacora);
$("#btnAgregar").removeClass("btn-success");
$("#btnAgregar").addClass("btn-info");
$("#btnAgregar").val("Actualizar");
$.get("/Bitacora/listar/"+idBitacora,function (data) {
console.log(data);
$("#cliente option[value='"+data.idCliente+"']").attr("selected",true);
$("input[name=noEmbarque]").val(data.noEmbarque);
$("input[name=numeroTarimas]").val(data.numeroTarimas);
$("input[name=kilosBrutos]").val(data.kilosBrutos);
$("input[name=kilosNetos").val(data.kilosNetos);
});<file_sep>/public/js/estados-ciudades.js
$(document).ready(function(){
getCiudades(1);
});
$('#estados').on('change',function(){
getCiudades($(this).val());
});
function getCiudades($id_estado,idCiudadSelected) {
//AJAX (Checar version de jQuery)
$.get("/Ciudades/"+$id_estado,function(data){
$('#ciudades').empty();
$('#ciudades').append('<option value="">Seleccione un municipio</option>');
var texto="";
for (var i = 0; i < data.length; i++) {
if(data[i].idCiudad==idCiudadSelected){
texto='<option selected value="'+data[i].idCiudad+'">'+data[i].ciudad+'</option>'
}else{
texto='<option value="'+data[i].idCiudad+'">'+data[i].ciudad+'</option>'
}
$('#ciudades').append(texto);
}
});
}
|
5249e1d1ff79ae7be3248bd6fdfc874d4fe1c631
|
[
"JavaScript",
"PHP"
] | 21 |
PHP
|
Adriansip/sistema3rios
|
3be9790dd7efe7b450b0c373036b0685f7f34303
|
7797f0f4b5e0a05762a3a02b392a10297465cc21
|
refs/heads/main
|
<file_sep><?php
error_reporting(0);
function cek($keyword){
// Github : https://github.com/tinwaninja/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://expo.expeditors.com/expo/SQGuest?SearchType=pagedShipmentSearch&TrackingNumber='.strtoupper(trim($keyword)).'&offset=0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt( $ch, CURLOPT_COOKIEFILE, 'cookie.txt' );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Connection: keep-alive';
$headers[] = 'Dnt: 1';
$headers[] = 'Upgrade-Insecure-Requests: 1';
$headers[] = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36';
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9';
$headers[] = 'Accept-Language: id,en-US;q=0.9,en;q=0.8';
$headers[] = 'Referer: http://expo.expeditors.com/expo/css/header.css';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = explode("<tbody>",$result);
$data = explode("</tbody>",$data[1]);
$datanya = explode("<tr>",$data[0]);
$keluaran = array();
foreach($datanya as $value){
$keluar = explode("<td>",$value);
if(array_key_exists(6,$keluar)){
$tanggal = trim(strip_tags($keluar[6]));
}else{
$tanggal = null;
}
if(array_key_exists(3,$keluar)){
$val = trim(strip_tags($keluar[3]));
}else{
$val = null;
}
$keluaran[$tanggal] = $val;
}
print_r($keluaran);
}
function cmp($a, $b){
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
if(isset($argv[1])){
$keyword = $argv[1];
}else{
$keyword = null;
}
if(isset($keyword)){
cek(trim($keyword));
}else{
echo "Penggunaan: php cek.php john".PHP_EOL;
}
?><file_sep><?php
error_reporting(0);
function cek($keyword){
// Github : https://github.com/tinwaninja/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.tnt.com/api/v3/shipment?ref='.strtoupper(trim($keyword)).'&locale=in_ID&searchType=REF&channel=OPENTRACK');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt( $ch, CURLOPT_COOKIEFILE, 'cookie.txt' );
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Authority: t.svtrd.com';
$headers[] = 'Sec-Ch-Ua: \"Google Chrome\";v=\"89\", \"Chromium\";v=\"89\", \";Not A Brand\";v=\"99\"';
$headers[] = 'Sec-Ch-Ua-Mobile: ?0';
$headers[] = 'Upgrade-Insecure-Requests: 1';
$headers[] = 'Dnt: 1';
$headers[] = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36';
$headers[] = 'Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8';
$headers[] = 'Sec-Fetch-Site: cross-site';
$headers[] = 'Sec-Fetch-Mode: no-cors';
$headers[] = 'Sec-Fetch-User: ?1';
$headers[] = 'Sec-Fetch-Dest: image';
$headers[] = 'Referer: ';
$headers[] = 'Accept-Language: id,en-US;q=0.9,en;q=0.8';
$headers[] = 'Origin: https://www.tnt.com';
$headers[] = 'X-Requested-With: XMLHttpRequest';
$headers[] = 'Connection: keep-alive';
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Client-Data: CIe2yQEIorbJAQipncoBCPjHygEI+M/KAQixmssBCOOcywEIqJ3LAQ==';
$headers[] = 'Access-Control-Request-Method: POST';
$headers[] = 'Access-Control-Request-Headers: content-type';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode($result,true);
$keluaran = array();
foreach($data["tracker.output"]["consignment"] as $value){
if(array_key_exists("analytics",$value)){
$status = $value["analytics"]["destinationDateSources"]["usedDate"];
if($status == "delivered"){
$keluaran[$value["analytics"]["destinationDateSources"]["delivered"]] = $value["consignmentNumber"];
}
}
}
print_r($keluaran);
}
function cmp($a, $b){
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
if(isset($argv[1])){
$keyword = $argv[1];
}else{
$keyword = null;
}
if(isset($keyword)){
cek(trim($keyword));
}else{
echo "Penggunaan: php cek.php 123".PHP_EOL;
}
?><file_sep><?php
error_reporting(0);
function cek($keyword){
// Github : https://github.com/tinwaninja/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://eschenker.dbschenker.com/nges-portal/public/en-US_US/resources/tracking/search/customer?customerReferenceTypeId=1f9d8dea-3885-9cab-e053-1062e00af271&searchText='.trim($keyword));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt( $ch, CURLOPT_COOKIEFILE, 'cookie.txt' );
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Authority: eschenker.dbschenker.com';
$headers[] = 'Cache-Control: max-age=0';
$headers[] = 'Sec-Ch-Ua: \"Google Chrome\";v=\"89\", \"Chromium\";v=\"89\", \";Not A Brand\";v=\"99\"';
$headers[] = 'Sec-Ch-Ua-Mobile: ?0';
$headers[] = 'Dnt: 1';
$headers[] = 'Upgrade-Insecure-Requests: 1';
$headers[] = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36';
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9';
$headers[] = 'Sec-Fetch-Site: none';
$headers[] = 'Sec-Fetch-Mode: navigate';
$headers[] = 'Sec-Fetch-User: ?1';
$headers[] = 'Sec-Fetch-Dest: document';
$headers[] = 'Accept-Language: id';
$headers[] = 'Cookie: SESSION=ODIzZWFkMzEtZTA3NC00YTgwLTliYWQtY2Q2Y2Q5MWFmODk3; INGRESSCOOKIE=1617808099.7.897.269863; trackingId=37b0f5cc-57f4-4814-8163-4ebe6ff7cf47; _pk_ses.2.9400=1; _ga=GA1.2.2112552575.1617808411; _gid=GA1.2.1989344153.1617808411; language_region=en-US_ID; XSRF-TOKEN=<KEY>; _pk_id.2.9400=59cc103b82495b30.1617808105.1.1617808863.1617808105.';
$headers[] = 'Referer: ';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode(json_encode(simplexml_load_string($result)),true);
if(array_key_exists("foundShipmentOverviewItems",$data)){
if(array_key_exists("foundShipmentOverviewItems",$data['foundShipmentOverviewItems'])){
$datanya = $data['foundShipmentOverviewItems']['foundShipmentOverviewItems'];
$simpan = array();
foreach($datanya as $value){
if(array_key_exists("estimatedTimeOfDelivery",$value)){
if(array_key_exists("timestamp",$value["estimatedTimeOfDelivery"])){
$simpan[$value["estimatedTimeOfDelivery"]["timestamp"]] = $value["sttNumber"] ."(https://eschenker.dbschenker.com/app/tracking-public/?refNumber=".$value["sttNumber"].")";
}else{
$simpan[$value["lastEventDate"]["timestamp"]] = $value["sttNumber"] ."(https://eschenker.dbschenker.com/app/tracking-public/?refNumber=".$value["sttNumber"].")";
}
}
}
rsort($simpan,"cmp");
$keluaran = array();
foreach($simpan as $key => $value){
$tanggal = date('l, j F Y H:i:s', $key/1000);
$keluaran[$tanggal] = $value;
}
print_r($keluaran);
}else{
echo "Kosong";exit();
}
}
}
function cmp($a, $b){
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
if(isset($argv[1])){
$keyword = $argv[1];
}else{
$keyword = null;
}
if(isset($keyword)){
cek(trim($keyword));
}else{
echo "Penggunaan: php cek.php john".PHP_EOL;
}
?><file_sep># Tracking Number Generator
To get and monitor the Echo, Eschenker, Expo, Startrack, and TNT tracking number
## Installation
1. Install Git
2. Install PHP
## How to use
```sh
git clone https://github.com/tinwaninja/Tracking-Number-Generator.git
cd Tracking-Number-Generator/Echo Tracking Number Generator
php cek.php name
```
## Information
Call "php cek.php" for information on how to use it<file_sep><?php
error_reporting(0);
function cek($keyword){
// Github : https://github.com/tinwaninja/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://digitalapi.auspost.com.au/consignmentapi/v1/consignments?q='.strtoupper(trim($keyword)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt( $ch, CURLOPT_COOKIEFILE, 'cookie.txt' );
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Authority: ssl.o.auspost.com.au';
$headers[] = 'Sec-Ch-Ua: \"Google Chrome\";v=\"89\", \"Chromium\";v=\"89\", \";Not A Brand\";v=\"99\"';
$headers[] = 'Dnt: 1';
$headers[] = 'Sec-Ch-Ua-Mobile: ?0';
$headers[] = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36';
$headers[] = 'Accept: */*';
$headers[] = 'Sec-Fetch-Site: cross-site';
$headers[] = 'Sec-Fetch-Mode: no-cors';
$headers[] = 'Sec-Fetch-Dest: empty';
$headers[] = 'Referer: https://startrack.com.au/';
$headers[] = 'Accept-Language: id,en-US;q=0.9,en;q=0.8';
$headers[] = 'Connection: keep-alive';
$headers[] = 'X-Datadome-Clientid: .keep';
$headers[] = 'Api-Key: nzsET4kyTEOBfkEZZ2ew2OGOby8GwNPa';
$headers[] = 'Origin: https://startrack.com.au';
$headers[] = 'Content-Length: 0';
$headers[] = 'Content-Type: text/plain;charset=UTF-8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode($result,true);
$keluaran = array();
foreach($data['consignments'] as $value){
$keluaran[$value["estimatedDeliveryOn"]] = $value["code"];
}
print_r($keluaran);
}
function cmp($a, $b){
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
if(isset($argv[1])){
$keyword = $argv[1];
}else{
$keyword = null;
}
if(isset($keyword)){
cek(trim($keyword));
}else{
echo "Penggunaan: php cek.php john".PHP_EOL;
}
?><file_sep><?php
error_reporting(0);
function cek($keyword){
// Github : https://github.com/tinwaninja/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://echo.com/ShipmentTracking/Services/TrackShipment.asmx/Track');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"referenceNumber":"'.trim($keyword).'"}');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt( $ch, CURLOPT_COOKIEFILE, 'cookie.txt' );
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Connection: keep-alive';
$headers[] = 'Sec-Ch-Ua: \"Google Chrome\";v=\"89\", \"Chromium\";v=\"89\", \";Not A Brand\";v=\"99\"';
$headers[] = 'Accept: application/json, text/javascript, */*; q=0.01';
$headers[] = 'Dnt: 1';
$headers[] = 'X-Requested-With: XMLHttpRequest';
$headers[] = 'Sec-Ch-Ua-Mobile: ?0';
$headers[] = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36';
$headers[] = 'Content-Type: application/json; charset=UTF-8';
$headers[] = 'Origin: https://echo.com';
$headers[] = 'Sec-Fetch-Site: same-origin';
$headers[] = 'Sec-Fetch-Mode: cors';
$headers[] = 'Sec-Fetch-Dest: empty';
$headers[] = 'Referer: https://echo.com/ShipmentTracking/Scripts/font-awesome.min.css';
$headers[] = 'Accept-Language: id,en-US;q=0.9,en;q=0.8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode($result,true);
$datanya = json_decode($data["d"]["Data"],true);
$keluaran = array();
foreach($datanya as $value){
$tanggal = explode("/",$value["DelOpenDateDTO"]);
if(array_key_exists(2,$tanggal)){
$tanggalnya = $tanggal[1]."-".$tanggal[0]."-".$tanggal[2];
}else{
$tanggalnya = null;
}
$keluaran[$tanggalnya] = $value["LoadId"];
}
print_r($keluaran);
}
function cmp($a, $b){
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
if(isset($argv[1])){
$keyword = $argv[1];
}else{
$keyword = null;
}
if(isset($keyword)){
cek(trim($keyword));
}else{
echo "Penggunaan: php cek.php john".PHP_EOL;
}
?>
|
a7a11121555a0b0244f022d71bc5435c436f01df
|
[
"Markdown",
"PHP"
] | 6 |
PHP
|
tinwaninja/Tracking-Number-Generator
|
233f4feb83ead8365f681f7398f8186dd2e7eeed
|
a765f9fb1174f0e9685516505be6ed93d82d613a
|
refs/heads/master
|
<repo_name>Jaeguins/DotBoom<file_sep>/Assets/Scripts/Terrains/ChunkDataManager.cs
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ChunkDataManager {
private static ChunkDataManager Instance;
//public Dictionary<Vector2, ChunkData> Data;
public TerrainSavor savor = new TerrainSavor();
float load, unload;
World world;
public void SetWorld() {
world = World.GetInstance();
load = world.load;
unload = world.unload;
savor.Load();
}
public static ChunkDataManager GetInstance() {
if (Instance == null) Instance=new ChunkDataManager();
return Instance;
}
}
<file_sep>/Assets/Scripts/Terrains/Chunk/Chunk.cs
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class Chunk : MonoBehaviour {
public GameObject WaterPrefeb;
int renderHeight;
//public ChunkData data;
private List<Vector3> newVertices = new List<Vector3>();
private List<int> newTriangles = new List<int>();
private List<Vector2> newUV = new List<Vector2>();
private Queue<Vector3> trees = new Queue<Vector3>();
private float tUnitX = 0.125f;
private float tUnitY = 0.03125f;
private static Vector2 tStone = new Vector2(0, 0);//former is horizontal
private static Vector2 tSnowSide = new Vector2(1, 1);
private static Vector2 tSnowTop = new Vector2(0, 1);
private static Vector2 tGrassTop = new Vector2(0, 2);
private static Vector2 tGrassSide = new Vector2(1, 2);
private static Vector2 tDirt = new Vector2(1, 0);
private static Vector2 tWater = new Vector2(2, 0);
private static Vector2 tDebug = new Vector3(3, 0);
private WaterChunk WaterChunk;
private Mesh mesh;
private MeshCollider col;
private World world;
private int faceCount;
public int chunkX;
public int chunkZ;
public bool update = false;
public override string ToString() {
return chunkX + " " + chunkZ;
}
void Start() {
mesh = GetComponent<MeshFilter>().mesh;
col = GetComponent<MeshCollider>();
world = World.GetInstance();
WaterChunk = Instantiate(WaterPrefeb, gameObject.transform, false).GetComponent<WaterChunk>();
WaterChunk.SetChunk(this);
}
private void LateUpdate() {
if (update && World.FrameCount > 0) {
World.FrameCount -= 1;
GenerateMesh();
WaterChunk.update = true;
update = false;
}
}
public static bool IsTransparent(byte blockValue) {
if ((blockValue & (byte)BLOCK.TRANSPARENT_CHECK) == blockValue)
return true;
else return false;
}
public static bool IsStepable(Vector3 location) {
World world = World.GetInstance();
if (!IsTransparent(world.Block(location)) &&
world.Block(location + new Vector3(0, 1, 0))==(byte)BLOCK.AIR &&
world.Block(location + new Vector3(0, 2, 0))==(byte)BLOCK.AIR)
return true;
else return false;
}
public byte Block(int x, int y, int z) {
if (y < 0 || y >= World.IchunkHeight) return 1;
return world.Block(x + chunkX, y, z + chunkZ);
}
public void UnloadTrees() {
while (trees.Count > 0) {
world.UnloadTree(trees.Dequeue());
}
}
public void GenerateMesh() {
//UnloadTreeAll();
name = "Chunk " + chunkX + " : " + chunkZ;
for (int x = 0; x < World.chunkSize; x++) {
for (int z = 0; z < World.chunkSize; z++) {
for (int y = 0; y < World.chunkHeight; y++) {
//This code will run for every block in the chunk
byte tBlock = Block(x, y, z);
Vector3 tVect = new Vector3(x + chunkX, y + 3.5f, z + chunkZ);
World Inst = World.GetInstance();
switch (tBlock) {//cases of block is object
case (byte)BLOCK.TREE://tree
Inst.LoadTree(tVect);
trees.Enqueue(tVect);
break;
default:
Inst.UnloadTree(tVect);
break;
}
if (!IsTransparent(tBlock) || (tBlock == (byte)BLOCK.TPBLOCK && world.Debuging)) {
//If the block is solid
if (IsTransparent(Block(x, y + 1, z))) {
//Block above is air
CubeTop(x, y, z, tBlock);
}
if (IsTransparent(Block(x, y - 1, z))) {
//Block below is air
CubeBot(x, y, z, tBlock);
}
if (IsTransparent(Block(x + 1, y, z))) {
//Block east is air
CubeEast(x, y, z, tBlock);
}
if (IsTransparent(Block(x - 1, y, z))) {
//Block west is air
CubeWest(x, y, z, tBlock);
}
if (IsTransparent(Block(x, y, z + 1))) {
//Block north is air
CubeNorth(x, y, z, tBlock);
}
if (IsTransparent(Block(x, y, z - 1))) {
//Block south is air
CubeSouth(x, y, z, tBlock);
}
}
}
}
}
UpdateMesh();
}
void UpdateMesh() {
mesh.Clear();
//mesh
mesh.vertices = newVertices.ToArray();
mesh.uv = newUV.ToArray();
mesh.triangles = newTriangles.ToArray();
//mesh.Optimize();
mesh.RecalculateNormals();
col.sharedMesh = null;
col.sharedMesh = mesh;
newVertices.Clear();
newUV.Clear();
newTriangles.Clear();
faceCount = 0; //Fixed: Added this thanks to a bug pointed out by ratnushock!
}
void Cube(Vector2 texturePos) {
newTriangles.Add(faceCount * 4); //1
newTriangles.Add(faceCount * 4 + 1); //2
newTriangles.Add(faceCount * 4 + 2); //3
newTriangles.Add(faceCount * 4); //1
newTriangles.Add(faceCount * 4 + 2); //3
newTriangles.Add(faceCount * 4 + 3); //4
newUV.Add(new Vector2(tUnitX * texturePos.x + tUnitX, tUnitY * texturePos.y));
newUV.Add(new Vector2(tUnitX * texturePos.x + tUnitX, tUnitY * texturePos.y + tUnitY));
newUV.Add(new Vector2(tUnitX * texturePos.x, tUnitY * texturePos.y + tUnitY));
newUV.Add(new Vector2(tUnitX * texturePos.x, tUnitY * texturePos.y));
faceCount++; // Add this line
}
void CubeTop(int x, int y, int z, byte block) {
newVertices.Add(new Vector3(x, y, z + 1));
newVertices.Add(new Vector3(x + 1, y, z + 1));
newVertices.Add(new Vector3(x + 1, y, z));
newVertices.Add(new Vector3(x, y, z));
Vector2 texturePos = new Vector2(0, 3);
if (block == (byte)BLOCK.TPBLOCK && world.Debuging) {
texturePos = tDebug;
}
else if (block == (byte)BLOCK.STONE) {
texturePos = tStone;
}
else if (block == (byte)BLOCK.DIRT) {
if (y > world.SnowHeight) texturePos = tSnowTop;
else if (y < world.WaterHeight - 1) texturePos = tDirt;
else texturePos = tGrassTop;
//if (b == Biome.PLAIN)
}
Cube(texturePos);
}
void CubeNorth(int x, int y, int z, byte block) {
//CubeNorth
newVertices.Add(new Vector3(x + 1, y - 1, z + 1));
newVertices.Add(new Vector3(x + 1, y, z + 1));
newVertices.Add(new Vector3(x, y, z + 1));
newVertices.Add(new Vector3(x, y - 1, z + 1));
Vector2 texturePos = new Vector2(0, 3);
if (block == (byte)BLOCK.TPBLOCK && world.Debuging) {
texturePos = tDebug;
}
else if (block == (byte)BLOCK.STONE) {
texturePos = tStone;
}
else if (block == (byte)BLOCK.DIRT) {
if (y > world.SnowHeight) texturePos = tSnowSide;
else if (y < world.WaterHeight - 1) texturePos = tDirt;
else texturePos = tGrassSide;
}
Cube(texturePos);
}
void CubeEast(int x, int y, int z, byte block) {
//CubeEast
newVertices.Add(new Vector3(x + 1, y - 1, z));
newVertices.Add(new Vector3(x + 1, y, z));
newVertices.Add(new Vector3(x + 1, y, z + 1));
newVertices.Add(new Vector3(x + 1, y - 1, z + 1));
Vector2 texturePos = new Vector2(0, 3);
if (block == (byte)BLOCK.TPBLOCK && world.Debuging) {
texturePos = tDebug;
}
else if (block == (byte)BLOCK.STONE) {
texturePos = tStone;
}
else if (block == (byte)BLOCK.DIRT) {
if (y > world.SnowHeight) texturePos = tSnowSide;
else if (y < world.WaterHeight - 1) texturePos = tDirt;
else texturePos = tGrassSide;
}
Cube(texturePos);
}
void CubeSouth(int x, int y, int z, byte block) {
//CubeSouth
newVertices.Add(new Vector3(x, y - 1, z));
newVertices.Add(new Vector3(x, y, z));
newVertices.Add(new Vector3(x + 1, y, z));
newVertices.Add(new Vector3(x + 1, y - 1, z));
Vector2 texturePos = new Vector2(0, 3);
if (block == (byte)BLOCK.TPBLOCK && world.Debuging) {
texturePos = tDebug;
}
else if (block == (byte)BLOCK.STONE) {
texturePos = tStone;
}
else if (block == (byte)BLOCK.DIRT) {
if (y > world.SnowHeight) texturePos = tSnowSide;
else if (y < world.WaterHeight - 1) texturePos = tDirt;
else texturePos = tGrassSide;
}
Cube(texturePos);
}
void CubeWest(int x, int y, int z, byte block) {
//CubeWest
newVertices.Add(new Vector3(x, y - 1, z + 1));
newVertices.Add(new Vector3(x, y, z + 1));
newVertices.Add(new Vector3(x, y, z));
newVertices.Add(new Vector3(x, y - 1, z));
Vector2 texturePos = new Vector2(0, 3);
if (block == (byte)BLOCK.TPBLOCK && world.Debuging) {
texturePos = tDebug;
}
else if (block == (byte)BLOCK.STONE) {
texturePos = tStone;
}
else if (block == (byte)BLOCK.DIRT) {
if (y > world.SnowHeight) texturePos = tSnowSide;
else if (y < world.WaterHeight - 1) texturePos = tDirt;
else texturePos = tGrassSide;
}
Cube(texturePos);
}
void CubeBot(int x, int y, int z, byte block) {
//CubeBot
newVertices.Add(new Vector3(x, y - 1, z));
newVertices.Add(new Vector3(x + 1, y - 1, z));
newVertices.Add(new Vector3(x + 1, y - 1, z + 1));
newVertices.Add(new Vector3(x, y - 1, z + 1));
Vector2 texturePos = new Vector2(0, 3);
if (block == (byte)BLOCK.TPBLOCK && world.Debuging) {
texturePos = tDebug;
}
else if (block == (byte)BLOCK.STONE) {
texturePos = tStone;
}
else if (block == (byte)BLOCK.DIRT) {
texturePos = tDirt;
}
Cube(texturePos);
}
public void Disable() {
gameObject.SetActive(false);
}
}
<file_sep>/Assets/Scripts/Terrains/TerrainSavor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class TerrainSavor {
public Dictionary<Vector2, Dictionary<Vector3, byte>> commands;
public void AddCommand(Vector2 chunk, Vector3 localBlock,byte content) {
if (!commands.ContainsKey(chunk)) commands.Add(chunk,new Dictionary<Vector3,byte>());
if (!commands[chunk].ContainsKey(localBlock)) commands[chunk].Add(localBlock, content);
else commands[chunk][localBlock] = content;
}
public TerrainSavor() {
}
public void Save() {
IOManager.Save(commands, "Terrain/Terrain");
}
public void Load() {
commands=IOManager.Load<Dictionary<Vector2, Dictionary<Vector3, byte>>>("Terrain/Terrain");
if (commands == null) {
commands = new Dictionary<Vector2, Dictionary<Vector3, byte>>();
InitialChunk();
}
}
public KeyValuePair<Vector3,byte>[] GetCommand(Vector2 chunk) {
if (commands.ContainsKey(chunk))
return commands[chunk].ToArray<KeyValuePair<Vector3,byte>>();
else return new KeyValuePair<Vector3, byte>[0];
}
public void InitialChunk() {
Vector2 initier = new Vector2(0, 0);
commands.Add(initier, new Dictionary<Vector3, byte>());
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
AddCommand(initier, new Vector3(i, 25, j), (byte)BLOCK.STONE);
for (int k = 26; k < World.IchunkHeight; k++) {
AddCommand(initier, new Vector3(i, k, j), (byte)BLOCK.AIR);
}
}
}
}
}<file_sep>/Assets/Scripts/World/World.cs
using UnityEngine;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class World : MonoBehaviour {
public static int FrameCount = 3;
public int WaterHeight = 19;
public int SnowHeight = 35;
public int searchRange = 5;
public GameObject ChunkPrefab;
public GameObject TreePrefab;
public CityManager citymanager;
static World Instance;
public ChunkDataManager Data;
public static int IchunkSize = 8;
public static int IchunkHeight = 48;
public static float chunkSize, chunkHeight;
public GameObject CamTarget;
public int show, hide, load, unload;
public int worldSeed = 10;
public GameObject TreePoolObject;
public GameObject ChunkPoolObject;
public bool Debuging = false;
//testing live act
public bool TP = false;
bool TPinner = false;
ChunkPool ChunkPool;
TreePool TreePool;
int stone = 0, dirt = 0, preX = 0, preZ = 0;
void Start() {
IOManager.Initiate();
Instance = this;
chunkHeight = IchunkHeight;
chunkSize = IchunkSize;
Instance = this;
TreePool = TreePoolObject.GetComponent<TreePool>();
ChunkPool = ChunkPoolObject.GetComponent<ChunkPool>();
Data = ChunkDataManager.GetInstance();
Data.SetWorld();
//block generation initiate
stone = Noise.Noise.PerlinNoise(preX, 0, preZ, 50, 3, 3f) + Noise.Noise.PerlinNoise(preX, 300, preZ, 50, 4, 0) + 16;
dirt = Noise.Noise.PerlinNoise(preX, 100, preZ, 50, 2, 0) + 1;
}
public byte Block(int x, int y, int z) {
byte t = GenerateBlock(x, y, z);
byte k = GenerateObjectBlock(x, y, z);
if (k != (byte)BLOCK.TRANSPARENT_CHECK) t = k;
byte f = GenerateByCommand(x, y, z);
if (f != (byte)BLOCK.TRANSPARENT_CHECK) t = f;
return t;
}
public byte Block(Vector3 loc) {
return Block((int)loc.x, (int)loc.y, (int)loc.z);
}
public byte GenerateBlock(int x, int y, int z) {
if (x != preX || z != preZ) {
UnityEngine.Profiling.Profiler.BeginSample("PerlinNoise");
stone = Noise.Noise.PerlinNoise(x, 0, z, 50, 3, 3f) + Noise.Noise.PerlinNoise(x, 300, z, 50, 4, 0) + 16;
dirt = Noise.Noise.PerlinNoise(x, 100, z, 50, 2, 0) + 1;
UnityEngine.Profiling.Profiler.EndSample();
preX = x;
preZ = z;
}
byte k = (byte)BLOCK.AIR;
if (y <= stone)
k = (byte)BLOCK.STONE;
else if (y <= dirt + stone)
k = (byte)BLOCK.DIRT;
else if (y < WaterHeight)
k = (byte)BLOCK.WATER;
return k;
}
public byte GenerateObjectBlock(int x, int y, int z) {
Vector2 chunk = GetChunkAddress(new Vector2(x, z));
if ((y > 0 && GenerateBlock(x, y - 1, z) == (byte)BLOCK.DIRT) && Noise.Noise.PerlinNoise(x,y,z,3.5f,10,5) < 1f) {//Tree
bool isTree = false;
for (int i = 0; i < 4; i++) {
if (y + i < World.IchunkHeight && GenerateBlock(x - 1, y + i, z) == (byte)BLOCK.AIR && GenerateBlock(x, y + i, z - 1) == (byte)BLOCK.AIR) {
if (i == 3) {
isTree = true;
}
}
else {
break;
}
}
if (isTree) {
return (byte)BLOCK.TREE;
}
}
return (byte)BLOCK.TRANSPARENT_CHECK;
}
public byte GenerateByCommand(int x, int y, int z) {
Vector2 ChunkAddr = GetChunkAddress(new Vector2(x, z));
if (Data.savor.commands.ContainsKey(ChunkAddr) && Data.savor.commands[ChunkAddr].ContainsKey(new Vector3(x, y, z))) {
return Data.savor.commands[ChunkAddr][new Vector3(x, y, z)];
}
return (byte)BLOCK.TRANSPARENT_CHECK;
}
public static Vector3 GetIntegerObjectAddress(Vector3 objectLoc) {
return new Vector3(Mathf.FloorToInt(objectLoc.x), Mathf.FloorToInt(objectLoc.y), Mathf.FloorToInt(objectLoc.z));
}
public static Vector2 GetChunkAddress(Vector3 objectLoc) {
return new Vector2(Mathf.FloorToInt(objectLoc.x / IchunkSize) * IchunkSize, Mathf.FloorToInt(objectLoc.z / IchunkSize) * IchunkSize);
}
public static Vector2 GetChunkAddress(Vector2 objectLoc) {
return new Vector2(Mathf.FloorToInt(objectLoc.x / IchunkSize) * IchunkSize, Mathf.FloorToInt(objectLoc.y / IchunkSize) * IchunkSize);
}
public static Vector3 GetLocalObjectAddress(Vector3 globalLoc) {
Vector2 chunkAddr = GetChunkAddress(globalLoc);
return new Vector3(globalLoc.x - chunkAddr.x, globalLoc.y, globalLoc.z - chunkAddr.y);
}
public void SetBlock(Vector3 loc, byte content) {
Vector3 localAddr = GetLocalObjectAddress(loc);
}
public void AddCommand(Vector3 chunk, Vector3 loc, byte content) {
Data.savor.AddCommand(chunk, loc, content);
}
private void Update() {
//live testing
if (TP) {
if (TPinner) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 26; k < World.IchunkHeight; k++) {
AddCommand(Vector2.zero, new Vector3(i, k, j), (byte)BLOCK.AIR);
}
}
}
TPinner = false;
}
else {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 26; k < World.IchunkHeight; k++) {
AddCommand(Vector2.zero, new Vector3(i, k, j), (byte)BLOCK.TPBLOCK);
}
}
}
TPinner = true;
}
UpdateChunk(Vector2.zero);
TP = false;
}
//end live testing
FrameCount = 3;
}
public void UpdateChunk(Vector2 chunk) {
/*if (Data.Data.ContainsKey(chunk)) {
Data.Data[chunk].Update();
}*/
if (ChunkPool.Chunks.ContainsKey(chunk)) {
ChunkPool.Chunks[chunk].update = true;
}
}
// Update is called once per frame
void LateUpdate() {
//Data.UpdateData(CamTarget.transform.position);
ChunkPool.UpdateChunks(CamTarget.transform.position);
}
public static World GetInstance() {
return Instance;
}
public void LoadChunk(int x, int z) {
ChunkPool.LoadChunk(x, z);
}
public void UnloadChunk(int x, int z) {
ChunkPool.UnloadChunk(x, z);
}
public Tree LoadTree(Vector3 loc) {
return TreePool.LoadTree(loc);
}
public void UnloadTree(Vector3 loc) {
TreePool.UnloadTree(loc);
}
}
<file_sep>/Assets/Scripts/City/Objects/Building/CityHallObject.cs
using UnityEngine;
using System.Collections;
public class CityHallObject : Building {
public new static int sizeX = 3, sizeY = 4, sizeZ = 3;
// Use this for initialization
public new void Start(){
base.Start();
}
// Update is called once per frame
void Update() {
}
public void SetData(CityHallData data) {
base.SetData(data);
}
}
<file_sep>/Assets/Scripts/City/Objects/CityObject.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class CityObject : MonoBehaviour {
CityManager manager;
public GameObject CityHallPrefab;
public GameObject CitizenPrefab;
public string CityName;
CityData data;
public CityHallObject hallObj;
public Dictionary<int, Citizen> citizens;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
}
public void SetData(CityData reference,CityManager manager) {
data = reference;
this.manager = manager;
CityName = data.name;
name = data.name;
citizens = new Dictionary<int, Citizen>();
}
public void AddBuilding(int buildingType, Vector3 loc, int dir) {//add building in this city with data and broadcast
GameObject tObj = new GameObject();
System.Type type=typeof(Building);
switch (buildingType) {
case CityEnums.CITYHALL:
tObj = Instantiate(CityHallPrefab, gameObject.transform);
type = typeof(CityHallObject);
break;
}
if (tObj == null) print("error");
tObj.transform.position = loc;
switch (dir) {
case CityEnums.E:
tObj.transform.rotation = Quaternion.Euler(Vector3.right);
break;
case CityEnums.W:
tObj.transform.rotation = Quaternion.Euler(Vector3.left);
break;
case CityEnums.S:
tObj.transform.rotation = Quaternion.Euler(Vector3.back);
break;
case CityEnums.N:
tObj.transform.rotation = Quaternion.Euler(Vector3.forward);
break;
}
manager.AddBuilding(CityName,buildingType, loc, dir, tObj.GetComponent(type));
}
public void LoadBuilding(int buildingType,Vector3 loc,int dir,BuildingData dataRef) {
GameObject tObj = new GameObject();
System.Type type = typeof(Building);
switch (buildingType) {
case CityEnums.CITYHALL:
tObj = Instantiate(CityHallPrefab, gameObject.transform);
type = typeof(CityHallObject);
hallObj = (CityHallObject)tObj.GetComponent(type);
hallObj.SetData((CityHallData)dataRef);
break;
}
if (tObj == null) print("error");
}
public void SummonCitizen(int name,CitizenData dataref) {
GameObject tObj = Instantiate(CitizenPrefab,gameObject.transform);
citizens.Add(name, tObj.GetComponent<Citizen>());
citizens[name].SetData(dataref);
citizens[name].data.SetObj(this);
}
}
<file_sep>/Assets/Scripts/City/CityEnum.cs
using System;
using UnityEngine;
public class CityEnums {
/*??UD ESWN
* 0000 0000
*/
public const int
UP = 0x20, //0010 0000
DOWN = 0x10, //0001 0000
E = 0x08, //0000 1000
S = 0x04, //0000 0100
W = 0x02, //0000 0010
N = 0x01; //0000 0001
public const int
CITYHALL = 0x00;
public static int[] ALLDIR = new int[] {
E,S,W,N,UP,DOWN,//basic 6way
E|S,E|N,W|S,W|N,//more 4way
UP|E,UP|S,UP|W,UP|N,UP|E|S,UP|E|N,UP|W|S,UP|W|N,//upper 8way
DOWN|E,DOWN|S,DOWN|W,DOWN|N,DOWN|E|S,DOWN|E|N,DOWN|W|S,DOWN|W|N//belower 8way
};
public static int CountBits(int dir) {
int val = dir;
int ret = 0;
while (val != 0) {
ret++;
val &= (val - 1);
}
return ret;
}
public static int Invert(int dir) {
return ~dir;
}
public static Vector3 DirToVect(int dir) {
Vector3 move = Vector3.zero;
if ((dir & E) == E) {
move += Vector3.right;
}
if ((dir & W) == W) {
move += Vector3.left;
}
if ((dir & S) == S) {
move += Vector3.back;
}
if ((dir & N) == N) {
move += Vector3.forward;
}
if ((dir & UP) == UP) {
move += Vector3.up;
}
if ((dir & DOWN) == DOWN) {
move += Vector3.down;
}
return move;
}
public static float DirToRot(int dir) {
float rot = -1;
int normal = dir & 0x0f;
switch (normal) {
case E:
rot = 180;
break;
case N|E:
rot = 135;
break;
case N:
rot = 90;
break;
case N|W:
rot = 45;
break;
case W:
rot = 0;
break;
case S|W:
rot = 315;
break;
case S:
rot = 270;
break;
case S|E:
rot = 225;
break;
}
return rot;
}
}<file_sep>/Assets/Scripts/City/Objects/CityManager.cs
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class CityManager : MonoBehaviour {
public GameObject CityPrefab;
CityDataManager data;
public Dictionary<string, CityObject> objectDict;
// Use this for initialization
void Start() {
objectDict = new Dictionary<string, CityObject>();
data = CityDataManager.GetInstance();
data.SetObj(this);
data.Load();
}
// Update is called once per frame
void Update() {
}
public void AddCity(string cityName) {//TODO add city in cityManager with data
GameObject tObj = new GameObject();
tObj = Instantiate(CityPrefab, gameObject.transform);
if (tObj == null) print("error");
data.AddCity(name, tObj.GetComponent(typeof(CityObject)));
}
public void AddBuilding(string name, int buildingType, Vector3 loc, int dir, Component contentRef) {//deliever building add order in cityManager with data
data.AddBuilding(name, buildingType, loc, dir, contentRef);
}
public void LoadCity(string name) {
CityObject tCity = Instantiate(CityPrefab, gameObject.transform).GetComponent<CityObject>();
tCity.SetData(data.cities[name], this);
objectDict.Add(name, tCity);
}
public void LoadBuilding(string name,int buildingType,Vector3 loc,int dir,BuildingData dataRef) {
objectDict[name].LoadBuilding(buildingType,loc,dir,dataRef);
}
public void SummonCitizen(int name,string cityName,CitizenData dataref) {
objectDict[cityName].SummonCitizen(name, dataref);
}
}
<file_sep>/Assets/Scripts/City/Data/Building/CityHallData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
[Serializable]
public class CityHallData : BuildingData {
public CityHallData(Vector3 position, int direction) : base(position, direction) {
type = CityEnums.CITYHALL;
}
}
<file_sep>/Assets/Scripts/System/PathFinder.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public static class PathFinder {
public static byte way8checker = 0x0f;
public static Queue<int> FindPath(Vector3 startVect, Vector3 targetVect) {
Dictionary<Vector3, PathNode> nodes = new Dictionary<Vector3, PathNode>();
nodes.Add(startVect, new PathNode(startVect, 0,10*(int)(targetVect.x+targetVect.y+targetVect.z-startVect.x-startVect.y-startVect.z)));
int count = 0;
while (true) {
if (count++ > 100000) {
return new Queue<int>();
}
PathNode tNode = GetLowestF(nodes);
if (tNode.location == targetVect) break;
tNode.isClosed = true;
foreach (int dir in CityEnums.ALLDIR) {
Vector3 offset = CityEnums.DirToVect(dir);
if (!possibilityCheck(tNode.location, dir)) continue;
byte dirValue = (byte)dir;
int accG = 0;
if (CityEnums.CountBits(dir) == 1)
accG = 10;
else
accG = 14;
accG += tNode.g;
Vector3 tLoc = tNode.location + offset;
if (nodes.ContainsKey(tLoc)) {
if (nodes[tLoc].g > accG) {
nodes[tLoc].parent = CityEnums.Invert(dir);
nodes[tLoc].g = accG;
}
}
else {
nodes.Add(tLoc, new PathNode(tLoc, accG, 10*(int)(targetVect.x + targetVect.y + targetVect.z - tLoc.x - tLoc.y - tLoc.z)));
nodes[tLoc].parent = CityEnums.Invert(dir);
}
}
}
Stack<int> stack = new Stack<int>();
PathNode pointer = nodes[targetVect];
while (pointer.location != startVect) {
stack.Push(CityEnums.Invert(pointer.parent));
pointer = nodes[pointer.location + CityEnums.DirToVect(pointer.parent)];
}
Queue<int> ret = new Queue<int>();
while (stack.Count > 0) {
int tDir = stack.Pop();
if ((tDir & CityEnums.UP) == CityEnums.UP) {
ret.Enqueue(CityEnums.UP);
ret.Enqueue(tDir & ~CityEnums.UP);
}
else if ((tDir & CityEnums.DOWN) == CityEnums.DOWN) {
ret.Enqueue(tDir & ~CityEnums.DOWN);
ret.Enqueue(CityEnums.DOWN);
}
else ret.Enqueue(tDir);
}
return ret;
}
public static bool possibilityCheck(Vector3 parent, int dir) {
Vector3 afterParent = parent + CityEnums.DirToVect(dir);
if (CityEnums.CountBits(dir) > 2) {
if ((dir & CityEnums.E) == CityEnums.E && !possibilityCheck(parent, CityEnums.E)) return false;
if ((dir & CityEnums.W) == CityEnums.W && !possibilityCheck(parent, CityEnums.W)) return false;
if ((dir & CityEnums.S) == CityEnums.S && !possibilityCheck(parent, CityEnums.S)) return false;
if ((dir & CityEnums.N) == CityEnums.N && !possibilityCheck(parent, CityEnums.N)) return false;
if ((dir & CityEnums.UP) == CityEnums.UP && !possibilityCheck(parent, CityEnums.UP)) return false;
if ((dir & CityEnums.DOWN) == CityEnums.DOWN && !possibilityCheck(parent, CityEnums.DOWN)) return false;
}
if (Chunk.IsStepable(afterParent)) return true;
else return false;
}
static PathNode GetLowestF(Dictionary<Vector3, PathNode> map) {
KeyValuePair<Vector3, PathNode>[] arrField = map.ToArray<KeyValuePair<Vector3, PathNode>>();
PathNode ret = arrField[0].Value;
int minimumF = int.MaxValue;
for (int i = 0; i < map.Count; i++) {
if (!arrField[i].Value.isClosed && arrField[i].Value.getF() < minimumF) {
ret = arrField[i].Value;
minimumF = arrField[i].Value.getF();
}
}
return ret;
}
}
class PathNode {
public int g, h;
public Vector3 location;
public bool isClosed = false;
public int parent;
public PathNode(Vector3 loc, int g, int h) {
this.g = g;
this.h = h;
location = loc;
}
public int getF() {
return g + h;
}
}<file_sep>/README.md
# DotBoom
unity game
making terrain algorithm got in
https://forum.unity.com/threads/tutorial-procedural-meshes-and-voxel-terrain-c.198651/<file_sep>/Assets/Scripts/Terrains/Objects/WorldObject.cs
using UnityEngine;
using System.Collections;
public abstract class WorldObject : MonoBehaviour {
public int locX, locZ;
public static void SetBlockData(Vector3 loc,byte[][][] field) {}
public abstract void PutCommand(Vector3 loc);
public abstract void PopCommand(Vector3 loc);
}
<file_sep>/Assets/Scripts/UI/ShowFPS.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ShowFPS : MonoBehaviour {
public Text fpsText;
public float deltaTime;
// Use this for initialization
void Start() {
//fpsText=gameObject.GetComponent<Text>();
}
// Update is called once per frame
void Update() {
deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
float fps = 1.0f / deltaTime;
fpsText.text = Mathf.Ceil(fps).ToString();
}
}<file_sep>/Assets/Scripts/City/Data/Citizen/CitizenData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
[Serializable]
public class CitizenData {
public Vector3 position;
public float rotation;
Component obj;
public Queue<int> moveQueue;
public int id;
public CitizenData(Vector3 position, float rotation) {
this.position = position;
this.rotation= rotation;
moveQueue = new Queue<int>();
}
public void SetObj(Component obj) {
this.obj = obj;
}
}
<file_sep>/Assets/Scripts/City/Data/Building/BuildingData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
[Serializable]
public class BuildingData{
public int type;
public Vector3 position;
public int direction;
Component obj;
public BuildingData(Vector3 position,int direction) {
this.position = position;
this.direction = direction;
}
public void SetObj(Component obj) {
this.obj = obj;
}
}<file_sep>/Assets/Scripts/UI/CameraMover.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMover : MonoBehaviour {
public int offsetX = 0, offsetY = 0, offsetZ = 0;
public float moveSpeed = 10f;
public float rotateSpeed = 3f;
World world;
public Vector3 lastClick;
public bool isTransparent;
public byte resultBlock;
// Use this for initialization
void Start() {
world = World.GetInstance();
}
// Update is called once per frame
void Update() {
/*if (Input.GetAxis("ScrollWheel") > 0f) {
}
if (Input.GetAxis("ScrollWheel") < 0f) {
}*/
if (Input.GetKey(KeyCode.A)) {
transform.Translate((Vector3.left) * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D)) {
transform.Translate((Vector3.right) * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.W)) {
transform.Translate((Vector3.forward) * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S)) {
transform.Translate((Vector3.back) * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.E)) {
transform.Rotate(new Vector3(0, rotateSpeed, 0));
}
if (Input.GetKey(KeyCode.Q)) {
transform.Rotate(new Vector3(0, -rotateSpeed, 0));
}
if (Input.GetKey(KeyCode.Space)) {
if (transform.position.y < 40) transform.Translate((Vector3.up) * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftControl)) {
if (transform.position.y > 0) transform.Translate((Vector3.down) * moveSpeed * Time.deltaTime);
}
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100) == true) {
Transform hitTransform = hit.transform;
Vector3 target = hit.point;
target = World.GetIntegerObjectAddress(target);
if (Chunk.IsStepable(target))
lastClick = target;
isTransparent=Chunk.IsTransparent(world.Block(target + new Vector3(0, 1, 0)));
resultBlock=world.Block(target + new Vector3(0, 1, 0));
if (Input.GetMouseButtonDown(0)) {
world.citymanager.objectDict["Eden"].citizens[0].MoveTo(lastClick);
}
}
offsetX = (int)transform.position.x;
offsetY = (int)transform.position.y;
offsetZ = (int)transform.position.z;
}
}
<file_sep>/Assets/Scripts/Terrains/Objects/Tree.cs
using UnityEngine;
using System.Collections;
public class Tree : WorldObject {
// Use this for initialization
void Start() {
gameObject.transform.rotation = Quaternion.Euler(270, 90 * (int)(UnityEngine.Random.value * 4), 0);
}
public static new void SetBlockData(Vector3 loc,byte[][][] field) {
Vector3 tLoc = World.GetLocalObjectAddress(loc);
field[(int)tLoc.x][(int)tLoc.y][(int)tLoc.z] = (byte)BLOCK.TREE;
tLoc.y += 1;
field[(int)tLoc.x][(int)tLoc.y][(int)tLoc.z] = (byte)BLOCK.TPBLOCK;
tLoc.y += 1;
field[(int)tLoc.x][(int)tLoc.y][(int)tLoc.z] = (byte)BLOCK.TPBLOCK;
}
public override void PutCommand(Vector3 loc) {
Vector3 tLoc = loc;
World.GetInstance().AddCommand(World.GetChunkAddress(tLoc),World.GetLocalObjectAddress(tLoc), (byte)BLOCK.TREE);
tLoc.y += 1;
World.GetInstance().AddCommand(World.GetChunkAddress(tLoc), World.GetLocalObjectAddress(tLoc), (byte)BLOCK.TPBLOCK);
tLoc.y += 1;
World.GetInstance().AddCommand(World.GetChunkAddress(tLoc), World.GetLocalObjectAddress(tLoc), (byte)BLOCK.TPBLOCK);
}
public override void PopCommand(Vector3 loc) {
Vector3 tLoc = loc;
World.GetInstance().AddCommand(World.GetChunkAddress(tLoc), World.GetLocalObjectAddress(tLoc), (byte)BLOCK.AIR);
tLoc.y += 1;
World.GetInstance().AddCommand(World.GetChunkAddress(tLoc), World.GetLocalObjectAddress(tLoc), (byte)BLOCK.AIR);
tLoc.y += 1;
World.GetInstance().AddCommand(World.GetChunkAddress(tLoc), World.GetLocalObjectAddress(tLoc), (byte)BLOCK.AIR);
}
}
<file_sep>/Assets/Scripts/City/Objects/Citizen/Citizen.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
public class Citizen : MonoBehaviour {
World world;
public CitizenData data;
static float moveSpeed = 5f;
public Vector3 nowTarget;
public GameObject armature;
Animator animator;
Queue<int> moveQueue;
// Use this for initialization
void Start() {
animator = gameObject.GetComponent<Animator>();
world = World.GetInstance();
}
// Update is called once per frame
void Update() {
if (Vector3.Distance(nowTarget, gameObject.transform.position) > 0.1f) {
gameObject.transform.Translate(Vector3.Normalize(nowTarget - gameObject.transform.position) * moveSpeed * Time.deltaTime);
}
else if (moveQueue.Count != 0) {
gameObject.transform.position.Set((int)gameObject.transform.position.x, (int)gameObject.transform.position.y, (int)gameObject.transform.position.z);
data.position = gameObject.transform.position;
int dir = moveQueue.Dequeue();
Vector3 move = new Vector3();
float rot = 0;
move = CityEnums.DirToVect(dir);
rot = CityEnums.DirToRot(dir);
if (rot != -1) armature.transform.rotation = Quaternion.Euler(new Vector3(-90, rot, 0));
nowTarget = nowTarget+ move;
}
animator.SetFloat(Animator.StringToHash("speed"), Vector3.Distance(nowTarget, gameObject.transform.position));
}
public void SetData(CitizenData dataref) {
data = dataref;
gameObject.transform.position = dataref.position;
gameObject.transform.rotation = Quaternion.Euler(Vector3.up * data.rotation);
moveQueue = data.moveQueue;
nowTarget = dataref.position;
}
public void moveOne(int dir) {
moveQueue.Enqueue(dir);
}
public void MoveTo(Vector3 target) {
moveQueue.Clear();
moveQueue= PathFinder.FindPath(nowTarget, target);
}
}
<file_sep>/Assets/Scripts/System/Cursor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cursor : MonoBehaviour {
CameraMover cam;
// Use this for initialization
void Start () {
cam = GameObject.FindGameObjectWithTag("Player").GetComponent<CameraMover>();
}
// Update is called once per frame
void Update () {
gameObject.transform.position = cam.lastClick+new Vector3(0,0,0);
}
}
<file_sep>/Assets/Scripts/Terrains/Objects/ObjectEnum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//from 0xC0 is not Transparent
public enum BLOCK {
AIR=0x00, //0000 0000
TPBLOCK=0x01, //0000 0001
STONE=0xC0, //1100 0000
DIRT=0xC1, //1100 0001
WATER=0x02, //0000 0010
TREE=0x03, //0000 0011
TRANSPARENT_CHECK =0x3F //0011 1111
}
<file_sep>/Assets/Scripts/Terrains/Objects/TreePool.cs
using System.Collections.Generic;
using UnityEngine;
public class TreePool : MonoBehaviour {
public GameObject TreePrefab;
public Dictionary<Vector3, Tree> Trees;
Queue<Tree> Pool;
World world;
// Use this for initialization
void Start() {
Trees = new Dictionary<Vector3, Tree>();
Pool = new Queue<Tree>();
world = World.GetInstance();
}
// Update is called once per frame
void Update() {
}
public Tree LoadTree(Vector3 loc) {
Tree newTree;
if (Trees.ContainsKey(loc)) {
newTree = Trees[loc];
}
else if (Pool.Count == 0) {
newTree = Instantiate(TreePrefab, gameObject.transform, false).GetComponent<Tree>();
newTree.gameObject.transform.position = loc;
Trees.Add(loc, newTree);
}else {
newTree = Pool.Dequeue();
newTree.gameObject.transform.position = loc;
Trees.Add(loc, newTree);
newTree.gameObject.SetActive(true);
}
return newTree;
}
public void UnloadTree(Vector3 loc) {
if (!Trees.ContainsKey(loc)) return;
Tree tmp = Trees[loc];
tmp.gameObject.SetActive(false);
Pool.Enqueue(tmp);
Trees.Remove(loc);
}
}
<file_sep>/Assets/Scripts/System/IOManager.cs
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class IOManager {
static BinaryFormatter bf = new BinaryFormatter();
static FileStream file;
public static string WorldName = "DebugWorld";
public static T Load<T>(string name) {
T ret = default(T);
file = File.Open(Application.persistentDataPath + "/" + WorldName+"/" + name, FileMode.OpenOrCreate);
if (file.Length > 0 && file != null) {
ret = (T)bf.Deserialize(file);
}
file.Close();
return ret;
}
public static void Initiate() {
string path = Application.persistentDataPath + "/" + WorldName;
System.IO.Directory.CreateDirectory(path);
System.IO.Directory.CreateDirectory(path + "/Terrain");
System.IO.Directory.CreateDirectory(path + "/Cities");
}
public static void Save<T>(T data, string name) {
file = File.Create(Application.persistentDataPath + "/" + WorldName + "/" + name);
bf.Serialize(file, data);
file.Close();
}
}<file_sep>/Assets/Scripts/City/Data/CityData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
[Serializable]
public class CityData {
CityDataManager manager;
public string name;
CityObject obj;
public CityHallData hall;
Dictionary<int, CitizenData> citizens;
int popularity;
//building structure will be add here
public CityData(string name) {
this.name = name;
manager = CityDataManager.GetInstance();
citizens = new Dictionary<int, CitizenData>();
popularity = 0;
}
public void LoadBuilding(int type, Vector3 loc, int dir, BuildingData data) {//TODO add building in this city with object and broadcast
switch (type) {
case CityEnums.CITYHALL:
manager.LoadBuilding(name, CityEnums.CITYHALL, hall.position, hall.direction, data);
break;
}
}
public void AddBuilding(int buildingType, Vector3 loc, int dir, Component contentRef) {//add building data
switch (buildingType) {
case CityEnums.CITYHALL:
hall = new CityHallData(loc, dir);
hall.SetObj(contentRef);
break;
}
}
public void SetObj(CityObject reference) {
obj = reference;
}
public void SummonCitizen(int name) {
manager.SummonCitizen(name, this.name, citizens[name]);
}
public int NewCitizen(Vector3 loc, float rot) {
CitizenData tData = new CitizenData(loc, rot);
citizens.Add(popularity, tData);
return popularity;
}
}
<file_sep>/Assets/Scripts/Terrains/ChunkPool.cs
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ChunkPool : MonoBehaviour {
public GameObject ChunkPrefab;
World world;
public Dictionary<Vector2, Chunk> Chunks;
Queue<Chunk> Pool;
// Use this for initialization
void Start() {
Chunks = new Dictionary<Vector2, Chunk>();
Pool = new Queue<Chunk>();
}
// Update is called once per frame
void Update() {
}
public void LoadChunk(int x, int z) {
Chunk newChunk;
if (Pool.Count == 0) {
newChunk = Instantiate(ChunkPrefab, gameObject.transform, false).GetComponent<Chunk>();
newChunk.gameObject.transform.position = new Vector3(x - 0.5f, 0, z - 0.5f);
newChunk.chunkX = x;
newChunk.chunkZ = z;
Chunks.Add(new Vector2(x, z), newChunk);
}
else {
newChunk = Pool.Dequeue();
newChunk.gameObject.transform.position = new Vector3(x - 0.5f, 0, z - 0.5f);
newChunk.chunkX = x;
newChunk.chunkZ = z;
Chunks.Add(new Vector2(x, z), newChunk);
newChunk.gameObject.SetActive(true);
}
//newChunk.data = world.Data.GetData(x, z);
newChunk.update = true;
}
public void UnloadChunk(int x, int z) {
Vector2 coord = new Vector2(x, z);
if (!Chunks.ContainsKey(coord)) return;
Chunk tmp = Chunks[coord];
tmp.gameObject.SetActive(false);
tmp.UnloadTrees();
Pool.Enqueue(tmp);
Chunks.Remove(coord);
}
public void UpdateChunks(Vector3 position) {
world = World.GetInstance();
Vector2 floor = World.GetChunkAddress(position);
for (int i = (int)floor.x - World.IchunkSize * world.searchRange; i < (int)floor.x + World.IchunkSize * world.searchRange; i += World.IchunkSize) {
for (int j = (int)floor.y - World.IchunkSize * world.searchRange; j < (int)floor.y + World.IchunkSize * world.searchRange; j += World.IchunkSize) {
Vector2 offset = new Vector2(i, j);
float dist = Vector2.Distance(new Vector2(position.x, position.z), offset);
if (dist < world.show+1* position.y&& !Chunks.ContainsKey(offset)) {
LoadChunk(i, j);
}
}
}
for (int i = 0; i < Chunks.Count; i++) {
Vector2 offset = Chunks.ToArray()[i].Key;
float dist = Vector2.Distance(new Vector2(position.x, position.z), offset);
if (dist > world.hide+ 1*position.y) {
UnloadChunk((int)offset.x, (int)offset.y);
}
}
}
}
<file_sep>/Assets/Scripts/City/Objects/Building/Building.cs
using UnityEngine;
using System.Collections;
public class Building : MonoBehaviour {
BuildingData data;
public static int sizeX = -1, sizeY = -1, sizeZ = -1;
// Use this for initialization
public void Start() {
}
// Update is called once per frame
void Update() {
}
public void SetData(BuildingData data) {
int tSizeX = sizeX, tSizeY = sizeY, tSizeZ = sizeZ;
switch (data.type) {
case CityEnums.CITYHALL:
tSizeX = CityHallObject.sizeX;
tSizeY = CityHallObject.sizeY;
tSizeZ = CityHallObject.sizeZ;
break;
}
this.data = data;
bool rotateCol = false;
int rot =0;
switch (data.direction) {
case CityEnums.E:
rot = -90;
rotateCol = true;
break;
case CityEnums.W:
rot = 90;
rotateCol = true;
break;
case CityEnums.S:
rot = 0;
break;
case CityEnums.N:
rot = 180;
break;
}
gameObject.transform.rotation = Quaternion.Euler(new Vector3(0,rot,0));
if(rotateCol)
gameObject.transform.position = data.position + new Vector3(tSizeX / 2 + 0.5f, 0, tSizeZ / 2 + 0.5f);
else
gameObject.transform.position = data.position + new Vector3(tSizeZ / 2 + 0.5f, 0, tSizeX / 2 + 0.5f);
}
}
<file_sep>/Assets/Scripts/City/Data/CityDataManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class CityDataManager {
CityManager obj;
public static CityDataManager Instance;
public Dictionary<string, CityData> cities;
public static CityDataManager GetInstance() {
if (Instance == null) Instance = new CityDataManager();
return Instance;
}
public void SetObject(CityManager obj) {
this.obj = obj;
}
public void Save() {
IOManager.Save(cities, "/Cities/Cities");
}
public void Load() {
cities = IOManager.Load<Dictionary<string, CityData>>("/Cities/Cities");
if (cities == null) {
cities = new Dictionary<string, CityData>();
InitialSet();
}
}
public void InitialSet() {
Vector3 tLoc = new Vector3(0, 25, 0);
int tDir=CityEnums.E;
LoadCity("Eden");
cities["Eden"].hall= new CityHallData(tLoc, tDir);
cities["Eden"].LoadBuilding(CityEnums.CITYHALL,tLoc,tDir,cities["Eden"].hall);
int tIndex=cities["Eden"].NewCitizen(new Vector3(0, 25, 4), 0f);
cities["Eden"].SummonCitizen(tIndex);
}
public void SetObj(CityManager obj) {
this.obj = obj;
}
public void LoadCity(string cityName) {//TODO add city in CityDataManager with object
cities.Add(cityName,new CityData(cityName));
obj.LoadCity(cityName);
}
public void LoadBuilding(string name,int buildingType,Vector3 loc,int dir,BuildingData dataRef) {//TODO deliever building load order in CityDataManager with object
obj.LoadBuilding(name,buildingType, loc, dir, dataRef);
}
public void AddBuilding(string name,int buildingType,Vector3 loc,int dir,Component contentRef) {//cast proper city that add command
cities[name].AddBuilding(buildingType, loc, dir, contentRef);
}
public void AddCity(string name,Component contentRef) {//Add city in data
cities.Add(name, new CityData(name));
cities[name].SetObj((CityObject)contentRef);
}
public void SummonCitizen(int name, string cityName, CitizenData dataref) {
obj.SummonCitizen(name, cityName, dataref);
}
}
<file_sep>/Assets/Scripts/Terrains/Chunk/WaterChunk.cs
using System.Collections.Generic;
using UnityEngine;
public class WaterChunk : MonoBehaviour {
private List<Vector3> newVertices = new List<Vector3>();
private List<int> newTriangles = new List<int>();
private List<Vector2> newUV = new List<Vector2>();
private float tUnitX = 0.125f;
private float tUnitY = 0.03125f;
private Vector2 tWater = new Vector2(2, 0);
private Mesh mesh;
private MeshCollider col;
public Chunk chunk;
private World world;
private int faceCount;
public bool update = false;
// Use this for initialization
void Start() {
mesh = GetComponent<MeshFilter>().mesh;
col = GetComponent<MeshCollider>();
gameObject.transform.localPosition=Vector3.zero;
world = World.GetInstance();
}
public void SetChunk(Chunk c) {
this.chunk = c;
}
public void GenerateMesh() {
for (int x = 0; x < World.chunkSize; x++) {
for (int z = 0; z < World.chunkSize; z++) {
//This code will run for every block in the chunk
byte tBlock = chunk.Block(x,world.WaterHeight-1,z);
//Vector3 tVect = new Vector3(x + chunkX, 20 + 3.5f, z + chunkZ);
if (tBlock == (byte)BLOCK.WATER) {
if (Chunk.IsTransparent(chunk.Block(x, world.WaterHeight, z))) {
//Block above is air
CubeTop(x, world.WaterHeight-1, z, tBlock);
}
}
}
}
UpdateMesh();
}
public void LateUpdate() {
if (update) {
GenerateMesh();
update = false;
}
}
void UpdateMesh() {
mesh.Clear();
mesh.vertices = newVertices.ToArray();
mesh.uv = newUV.ToArray();
mesh.triangles = newTriangles.ToArray();
mesh.RecalculateNormals();
col.sharedMesh = null;
col.sharedMesh = mesh;
newVertices.Clear();
newUV.Clear();
newTriangles.Clear();
faceCount = 0; //Fixed: Added this thanks to a bug pointed out by ratnushock!
}
void Cube(Vector2 texturePos) {
newTriangles.Add(faceCount * 4); //1
newTriangles.Add(faceCount * 4 + 1); //2
newTriangles.Add(faceCount * 4 + 2); //3
newTriangles.Add(faceCount * 4); //1
newTriangles.Add(faceCount * 4 + 2); //3
newTriangles.Add(faceCount * 4 + 3); //4
newUV.Add(new Vector2(tUnitX * texturePos.x + tUnitX, tUnitY * texturePos.y));
newUV.Add(new Vector2(tUnitX * texturePos.x + tUnitX, tUnitY * texturePos.y + tUnitY));
newUV.Add(new Vector2(tUnitX * texturePos.x, tUnitY * texturePos.y + tUnitY));
newUV.Add(new Vector2(tUnitX * texturePos.x, tUnitY * texturePos.y));
faceCount++; // Add this line
}
void CubeTop(int x, int y, int z, byte block) {
float sub = 0.2f;
newVertices.Add(new Vector3(x, y - sub, z + 1));
newVertices.Add(new Vector3(x + 1, y - sub, z + 1));
newVertices.Add(new Vector3(x + 1, y - sub, z));
newVertices.Add(new Vector3(x, y - sub, z));
Vector2 texturePos = new Vector2(0, 3);
texturePos = tWater;
Cube(texturePos);
}
}
|
6c77c250ae0d67bab8cb1bb0b21341c71817d03c
|
[
"Markdown",
"C#"
] | 27 |
C#
|
Jaeguins/DotBoom
|
0c422f45a07f4e10717f8b57bd97e962814c15f4
|
d3213d6956fa5af037726a3fa1f177a2afae6c83
|
refs/heads/master
|
<file_sep>'use strict';
const GLOBAL_TIMEOUT = 40e3;
const os = require('os');
const path = require('path');
const requireIt = require('require-it');
exports.config = {
specs: 'features/**/*.feature',
capabilities: {
browserName: 'chrome'
},
directConnect: true,
cucumberOpts: {
require: ['step_definitions/**/*.js'],
tags: ['~@wip','@current'],
format: ['pretty','json:cucumber.json']
},
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
chromeDriver: path.join(requireIt.directory('protractor'), 'node_modules', 'webdriver-manager', 'selenium', 'chromedriver_77.0.3865.40' + (os.platform() === 'win32' ? '.exe' : '')),
onPrepare: function () {
global.GLOBAL_TIMEOUT = GLOBAL_TIMEOUT;
global.extraWait = 3000;
global.ec = protractor.ExpectedConditions;
const chai = require('chai');
chai.use(require('chai-as-promised'));
global.expect = chai.expect;
global.convertDataTable = table => {
let array = [];
table.raw().forEach(element => {
array.push(element[0]);
});
return array;
};
protractor.ElementFinder.prototype.isVisible = function () {
return this.isPresent().then(present => {
if (present) {
return this.isDisplayed();
}
return false;
})
};
browser.waitForAngularEnabled(false);
return browser.manage().window().maximize().catch(() => {
return browser.manage().window().setSize(1800, 1012);
});
}
};<file_sep>'use strict';
class DashboardPage {
constructor() {
this.dashInner = element(by.css('.dash-inner'));
}
/**
* Returns if the Dashboard page is visible.
*
* @returns {Promise.<boolean>}
*/
isVisible() {
return this.dashInner.isVisible();
}
}
module.exports = new DashboardPage();<file_sep>'use strict';
class WelcomePage {
constructor() {
this.logo = element(by.css('img[src*="logo"]'));
this.button = text => element(by.cssContainingText('.btn', text));
}
/**
* Opens the MyStudyLife Welcome page.
*
* @returns {WebElementPromise}
*/
load() {
browser.get('https://app.mystudylife.com');
return this.waitForLogo();
}
/**
* Returns if the logo is visible.
*
* @returns {Promise.<boolean>}
*/
isLogoVisible() {
return this.logo.isVisible();
}
/**
* Waits until the logo is visible.
*
* @returns {Promise}
*/
waitForLogo() {
return browser.wait(() => {
return this.isLogoVisible();
});
}
/**
* Returns if the given button is visible.
*
* @param {string} text Text of the given button.
* @returns {Promise.<boolean>}
*/
isButtonVisible(text) {
return this.button(text).isVisible();
}
/**
* Returns if the given buttons are visible.
*
* @param {array} buttons The given buttons.
*/
areButtonsVisible(buttons) {
return buttons.every(button => {
return this.isButtonVisible(button);
});
}
/**
* Clicks on the given button.
*
* @param {string} text Text of the given button.
* @returns {Promise}
*/
clickOnButton(text) {
return this.button(text).click().then(() => browser.sleep(extraWait));
}
}
module.exports = new WelcomePage();<file_sep># mystudylife-test
E2E automated test on the MyStudyLife page.
<file_sep>'use strict';
class SignUpPage {
constructor() {
this.logo = element(by.css('img[src*="logo"]'));
this.form = element(by.css('.sign-up form'));
this.footer = element(by.css('footer'));
this.title = text => element(by.cssContainingText('.title', text));
}
/**
* Returns if the logo is visible.
*
* @returns {Promise.<boolean>}
*/
isLogoVisible() {
return this.logo.isVisible();
}
/**
* Returns if the given title is visible.
*
* @param {string} text The given text.
* @returns {Promise.<boolean>}
*/
isTitleVisible(text) {
return this.title(text).isVisible();
}
/**
* Returns if the sign up form is visible.
*
* @returns {Promise.<boolean>}
*/
isFormVisible() {
return this.form.isVisible();
}
/**
* Returns if the footer is visible.
*
* @returns {Promise.<boolean>}
*/
isFooterVisible() {
return this.footer.isVisible();
}
/**
* Waits until the logo is visible.
*
* @returns {Promise.<boolean>}
*/
waitForLoading() {
return browser.wait(() => {
return this.isLogoVisible();
});
}
}
module.exports = new SignUpPage();
|
af4504cacebf51f3942c8fab74e34adf03ac1534
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
horvathmilan/mystudylife-test
|
ae73656215079b6434e2458061b66a7d83e3dd84
|
fda3c6debd4aef10fbe1a78b02dfb6c9464f04c3
|
refs/heads/master
|
<repo_name>ecliptik/MobyTest<file_sep>/entrypoint.sh
#!/bin/bash
#Wouldn't be a demo without a bash script
# moby tool needs docker running to pull in images
exec dockerd &
# You will see some errors in the output. This can be ignored. Just complaining about the image not existing before it is pulled.
# ERRO[0522] Handler for POST /v1.23/containers/create returned error: No such image: linuxkit/mkimage-iso-bios:6ebdce90f63991eb1d5a578e6570dc1e5781e9fe@sha256:0c6116d4c069d17ebdaa86737841b3be6ae84f6c69a5e79fe59cd8310156aa96
#start the image build
moby build JenkinsOS.yml
#At this point you will have a bunch of images created based on the "format" specified in JenkinsOS.yml
# Copy them out to the host
# I didn't test this. Laptop almost dead and starbucks wifi is terrible.
mv * /images
<file_sep>/Dockerfile
FROM golang:1.7.5-alpine3.5
#Update to latest packages and install bash
RUN apk update && apk add bash git qemu-system-x86_64 gcc docker openrc --no-cache
#Install linuxKit 'moby' tool
RUN CGO_ENABLED=0 go get -u github.com/linuxkit/linuxkit/src/cmd/moby
#Add customised JenkinsOS.yml
ADD JenkinsOS.yml /tmp
ADD entrypoint.sh /tmp
WORKDIR /tmp
ENTRYPOINT ./entrypoint.sh
|
4d04637df90c82084861420a8bdea9f2444abd7e
|
[
"Dockerfile",
"Shell"
] | 2 |
Shell
|
ecliptik/MobyTest
|
80914f5cf7fe0026d359a55793e463cd06dfd4cb
|
ce47c6ef783ddd21cecc125bcdf5c496ba5d9fd9
|
refs/heads/master
|
<file_sep>// Note: $(() => {}); is equivalent to $(document).ready(function(){})
class KeyboardController {
constructor(key) {
this.key = key;
this.value = key.text();
}
print_value() {
if (this.key.hasClass("key-space")) {
var oldText = $(".text-output").text();
$(".text-output").text(oldText + " ");
} else if (this.key.hasClass("key-special") || this.key.hasClass("key-wide")) {
if (this.value.includes("Bksp")){
oldText = $(".text-output").text();
var newText = oldText.substr(0, (oldText.length)-1);
$(".text-output").text(newText);
}
if (this.value.includes("Enter")) {
oldText = $(".text-output").text();
var newText = oldText.substr(0, (oldText.length)-1);
}
} else {
var oldText = $(".text-output").text();
$(".text-output").text(oldText + this.value.trim())
}
}
}
$(document).ready(function() {
console.log('Document ready! [app/assets/javascripts/keyboard.js]');
$('.key').click(function(){
var key = new KeyboardController($(this));
key.print_value();
});
$("#keyboard-show").click(function(){
$("#kcontainer").toggle("slide");
});
});
|
ecfe795e1e54f6805ea8e10d5ec172b15a852087
|
[
"JavaScript"
] | 1 |
JavaScript
|
UANDES-4103-201910/lab-assignment-8-MEspinosaGH
|
cfc88753437fdfdc55a1df6a80ec3a015c4396e8
|
85a513789db13c2bfce051a32f7ba7fc18e566e7
|
refs/heads/main
|
<file_sep># serverless-rust
Examples to run Rust based workloads on
- Azure Functions
- AWS Lambda
<file_sep>[package]
name = "lamda-deno"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
lambda_runtime = "0.3.0"
tokio = "1.9.0"
serde_json = "1.0.64"
itertools = "0.10.1"
num = "0.4.0"
[[bin]]
name = "bootstrap"
path = "src/main.rs"
[profile.release]
opt-level = 3
lto = true
<file_sep>use std::{collections::{HashMap, HashSet}};
use std::env;
use std::net::Ipv4Addr;
use warp::{http::Response, Filter};
use itertools::Itertools;
use num::{FromPrimitive, Integer};
#[derive(Debug, PartialEq, Eq)]
pub struct Palindrome {
factors: HashSet<(u64, u64)>,
value: u64,
}
impl Palindrome {
pub fn new(a: u64, b: u64) -> Palindrome {
let mut set: HashSet<(u64, u64)> = HashSet::new();
set.insert((a, b));
Self {
value: a * b,
factors: set,
}
}
pub fn value(&self) -> u64 {
self.value
}
pub fn insert(&mut self, a: u64, b: u64) {
self.factors.insert((a, b));
}
}
fn is_palindrome(a: u64, b: u64) -> bool {
let prod = a * b;
prod == reverse(prod)
}
/// Reverses an unsigned integer number (e.g. 123 -> 321)
fn reverse<T: Copy + FromPrimitive + Integer>(a: T) -> T {
let radix = FromPrimitive::from_usize(10).unwrap();
let mut n = a;
let mut reversed = FromPrimitive::from_usize(0).unwrap();
while !n.is_zero() {
reversed = reversed * radix + n % radix;
n = n / radix;
}
reversed
}
fn check_palindrom(map: &mut HashMap<u64, Palindrome>, a: u64, b: u64) {
if is_palindrome(a, b) {
let prod = a * b;
map.entry(prod)
.or_insert_with(|| Palindrome::new(a, b))
.insert(a, b);
}
}
pub fn palindrome_products(min: u64, max: u64) -> Option<(Palindrome, Palindrome)> {
let mut map: HashMap<u64, Palindrome> = HashMap::new();
for (a, b) in (min..=max).tuple_combinations() {
check_palindrom(&mut map, a, b);
}
for c in min..=max {
check_palindrom(&mut map, c, c);
}
let prod_min_max = map.keys().minmax().into_option();
if let Some((i, j)) = prod_min_max {
let (i, j) = (i.to_owned(), j.to_owned());
Some((map.remove(&i).unwrap(), map.remove(&j).unwrap()))
} else {
None
}
}
#[tokio::main]
async fn main() {
let example1 = warp::get()
.and(warp::path("api"))
.and(warp::path("httpexample"))
.and(warp::query::<HashMap<String, String>>())
.map(|p: HashMap<String, String>| match (p.get("min"), p.get("max")) {
(Some(min), Some(max)) => {
let min: u64 = min.parse().unwrap();
let max: u64 = max.parse().unwrap();
let val = match palindrome_products(min, max) {
Some((pal_one, pal_two)) =>
format!("min {} max {}", pal_one.value, pal_two.value),
None => String::from("Error")
};
Response::builder().body(val)
},
_ => Response::builder().body(String::from("Error"))
});
let port_key = "FUNCTIONS_CUSTOMHANDLER_PORT";
let port: u16 = match env::var(port_key) {
Ok(val) => val.parse().expect("Custom Handler port is not a number"),
Err(_) => 3000,
};
println!("Starting at {}", port);
warp::serve(example1)
.run((Ipv4Addr::UNSPECIFIED, port))
.await
}
<file_sep>[package]
name = "handler"
version = "0.1.0"
authors = ["stefan.baumgartner <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
warp = "0.3"
tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] }
itertools = "0.10.1"
num = "0.4.0"
[[bin]]
name = "handler"
path = "src/main.rs"
[profile.release]
opt-level = 3
lto = true
<file_sep>use lambda_runtime::{Context, handler_fn};
use serde_json::{Value, json};
use itertools::Itertools;
use num::{FromPrimitive, Integer};
use std::{collections::{HashMap, HashSet}};
#[derive(Debug, PartialEq, Eq)]
pub struct Palindrome {
factors: HashSet<(u64, u64)>,
value: u64,
}
impl Palindrome {
pub fn new(a: u64, b: u64) -> Palindrome {
let mut set: HashSet<(u64, u64)> = HashSet::new();
set.insert((a, b));
Self {
value: a * b,
factors: set,
}
}
pub fn value(&self) -> u64 {
self.value
}
pub fn insert(&mut self, a: u64, b: u64) {
self.factors.insert((a, b));
}
}
fn is_palindrome(a: u64, b: u64) -> bool {
let prod = a * b;
prod == reverse(prod)
}
/// Reverses an unsigned integer number (e.g. 123 -> 321)
fn reverse<T: Copy + FromPrimitive + Integer>(a: T) -> T {
let radix = FromPrimitive::from_usize(10).unwrap();
let mut n = a;
let mut reversed = FromPrimitive::from_usize(0).unwrap();
while !n.is_zero() {
reversed = reversed * radix + n % radix;
n = n / radix;
}
reversed
}
fn check_palindrom(map: &mut HashMap<u64, Palindrome>, a: u64, b: u64) {
if is_palindrome(a, b) {
let prod = a * b;
map.entry(prod)
.or_insert_with(|| Palindrome::new(a, b))
.insert(a, b);
}
}
pub fn palindrome_products(min: u64, max: u64) -> Option<(Palindrome, Palindrome)> {
let mut map: HashMap<u64, Palindrome> = HashMap::new();
for (a, b) in (min..=max).tuple_combinations() {
check_palindrom(&mut map, a, b);
}
for c in min..=max {
check_palindrom(&mut map, c, c);
}
let prod_min_max = map.keys().minmax().into_option();
if let Some((i, j)) = prod_min_max {
let (i, j) = (i.to_owned(), j.to_owned());
Some((map.remove(&i).unwrap(), map.remove(&j).unwrap()))
} else {
None
}
}
#[tokio::main]
async fn main() -> Result<(), lambda_runtime::Error>{
let func = handler_fn(handler);
lambda_runtime::run(func).await?;
Ok(())
}
async fn handler(event: Value, _: Context) -> Result<Value, lambda_runtime::Error> {
let (min, max) = match (event["min"].as_u64(), event["max"].as_u64()) {
(Some(min), Some(max)) => (min, max),
_ => (0, 0)
};
match palindrome_products(min, max) {
Some((pal_1, pal_2)) => Ok(json!({ "palindromes": { "one": pal_1.value, "two": pal_2.value } })),
None => Ok(json!({ "message": "none found" }))
}
}
|
7cd667decf21f1b7169747f8cd6d74f9eb71d057
|
[
"Markdown",
"TOML",
"Rust"
] | 5 |
Markdown
|
ddprrt/serverless-rust
|
78ad06d6d21fdedfb53a56660391788082da7a44
|
9a57b7d9971a315f465893c6b1802d8143dc0fcc
|
refs/heads/master
|
<repo_name>sander76/telegram_async_poll<file_sep>/telegram_async_poll.py
import asyncio
import logging
from homeassistant.const import EVENT_HOMEASSISTANT_START, \
EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback
# from telegram.bot import Bot
import aiohttp
_LOGGER = logging.getLogger(__name__)
EVENT_TELEGRAM_COMMAND = 'telegram.command'
ATTR_COMMAND = 'command'
ATTR_USER_ID = 'user_id'
ATTR_ARGS = 'args'
ATTR_FROM_FIRST = 'from_first'
ATTR_FROM_LAST = 'from_last'
# The domain of your component. Should be equal to the name of your component.
DOMAIN = 'telegram_async_poll'
BOT_TOKEN = '<PASSWORD>'
ALLOWED_CHAT_IDS = 'allowed_chat_ids'
REQUIREMENTS = ['python-telegram-bot==5.3.0']
@asyncio.coroutine
def async_setup(hass, config):
"""Setup is called when Home Assistant is loading our component."""
import telegram
class AsyncBot(telegram.Bot):
def __init__(self, loop, token, base_url=None, base_file_url=None,
request=None):
telegram.Bot.__init__(self, token, base_url, base_file_url, request)
self.loop = loop
self.session = aiohttp.ClientSession(loop=self.loop)
self.update_url = '{0}/getUpdates'.format(self.base_url)
@asyncio.coroutine
def getUpdates(self, offset=None, limit=100, timeout=60,
network_delay=5.,
**kwargs):
data = {'timeout': timeout}
if offset:
data['offset'] = offset
if limit:
data['limit'] = limit
resp = yield from self.session.post(self.update_url,data=data,
headers={
'connection': 'keep-alive'}
)
try:
_json = yield from resp.json()
yield from resp.release()
return _json
except Exception as ex:
logging.exception(ex)
resp.close()
raise
bot_token = config[DOMAIN].get(BOT_TOKEN)
# instance the Telegram bot
bot = AsyncBot(hass.loop,bot_token)
val = yield from _setup(hass, config, bot, telegram)
return val
@asyncio.coroutine
def _setup(hass, config, bot, telegram):
logger = logging.getLogger(__name__)
allowed_chat_ids = config[DOMAIN].get(ALLOWED_CHAT_IDS)
@callback
def _start_bot(_event):
hass.loop.create_task(check_incoming())
@callback
def _stop_bot(_event):
"""Stops the bot. Unfortunately no clean stopping of
the telepot instance available yet (?)"""
pass
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START,
_start_bot
)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
_stop_bot
)
@asyncio.coroutine
def check_incoming():
while 1:
try:
update = yield from bot.getUpdates()
except asyncio.TimeoutError as ex:
# timeout is no problem as we are long polling
pass
else:
yield from handle(incoming)
@asyncio.coroutine
def handle(msg):
"""Callback function which handles incoming telegram messages."""
content_type = 'text'
chat_id = 'abc'
# glance to get some meta on the message
# content_type, chat_type, chat_id = telepot.glance(msg)
# chat_id = str(chat_id)
# we only want to process text messages from our specified chat
if (content_type == 'text') and (chat_id in allowed_chat_ids):
command = msg['text'].split(' ')
hass.bus.async_fire(EVENT_TELEGRAM_COMMAND, {
ATTR_COMMAND: command[0],
ATTR_ARGS: ' '.join(command[1:]),
ATTR_FROM_FIRST: msg['from']['first_name'],
ATTR_FROM_LAST: msg['from']['last_name'],
ATTR_USER_ID: chat_id
})
else:
pass
# Return boolean to indicate that initialization was successfully.
return True
|
774b22802cc16639ca343e4ca0cd38740bc10b80
|
[
"Python"
] | 1 |
Python
|
sander76/telegram_async_poll
|
13611af707993e86180de02e0696589f232880fa
|
8b0d225fd82fe18e98a499c08224c6d90a201fc6
|
refs/heads/master
|
<file_sep>#assignment commands
# {}
x=5
# { (x, f)}
y=6
# {(x, 5) , (y, 6)}
#conditions
if(True):
x=0
z= 10
else:
x=1
z=11
# {(x, 0) , (y, 6), (z, 10)}
#procedures and procedure call
def fun(a, b, c, x):
result = a * (x*x) +b*x + c
return result
if (x>0 or y==6):
x=0
z= 10
else:
x=1
z=11
#iteration
times = 10
while (times > 0):
print ("Hello")
times = (times -1)
<file_sep>#{} intialize state
x=5 #assignment statement
#{(x, 5)}
print (x)
#state is the same
x = 6 # x gets 6
# {(x, 6)}
print (x)
#same
y = 7
# {(x,6) (y, 7)}
print (y)
print (x)
<file_sep>print "Hello, World!"
print "Hellow, CS1113!"
<file_sep>'''def update (n):
if (n % 2== 0):
n = n//2
return (n)
print(n)
else:
n= 3*n +1
return (n)
print (n)
def baz (n):
x= 1
while (n != 1):
n = update(n)
return (n)
x= x +1
def hs (n):
if (n != 1):
print (n)
n = baz(n)
else:
print ("x")
return (None) '''
#new version
def hs (n):
print (n)
# n = baz(n)
x= 1
while (n != 1):
if (n % 2== 0):
n = n//2
x= x+1
print(n)
else:
n= 3*n +1
print (n)
x= x +1
print (x)
<file_sep> <NAME>: cse4qf
|
e9011b2b59a542fd49105136aac3819a962c9905
|
[
"Python"
] | 5 |
Python
|
cse4qf/cs1113
|
c92485f03f277cd6e3096d44921cda3008c2b248
|
d9762e20f1256f3c92b820159186023d5116b605
|
refs/heads/master
|
<repo_name>vbragin/docs.qameta.io<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'jekyll-redirect-from'
gem 'jekyll-asciidoc'
gem 'coderay'<file_sep>/allure/1.4/reporting/bamboo.adoc
= Bamboo
:icons: font
:imagesdir: /allure/1.4/img/
:page-layout: docs
:page-version: 1.4
:page-product: allure
:source-highlighter: coderay
== Allure Bamboo Plugin
This repository contains source code of Allure plugin for
https://www.atlassian.com/software/bamboo[Atlassian Bamboo CI].
It allows you to generate Allure report from
https://github.com/allure-framework/allure-core/wiki#gathering-information-about-tests[existing Allure XML files].
== Building and Installing
=== Short way
Download precompiled JAR from https://github.com/allure-framework/allure-bamboo-plugin/releases[releases page]
and install it manually as described
https://confluence.atlassian.com/display/UPM/Installing+add-ons#Installingadd-ons-Installingbyfileupload[here]. We use JDK 1.7+ to compile the plugin so be sure to use Java 1.7+
for running Bamboo.
=== Long way
. Set up Atlassian plugin SDK as described
https://developer.atlassian.com/display/DOCS/Set+up+the+Atlassian+Plugin+SDK+and+Build+a+Project[here].
. Clone this repository
. Run `$ atlas-run`
. Access http://localhost:6990/bamboo/ to view development instance of Bamboo
. Verify that plugin is working as expected
. Install *target/allure-bamboo-plugin-VERSION.jar* manually as described
https://confluence.atlassian.com/display/UPM/Installing+add-ons#Installingadd-ons-Installingbyfileupload[here].
== Configuration and Usage
When installed this plugin provides a new task called *Allure*. To use it configure your build as follows:
. Add Allure task to your job:
+
image::bamboo_add_task.png[Add Task in Bamboo]
. Configure task - specify glob pattern to the folder where Allure should search for XML files and desired
report version to be used:
+
image::bamboo_task_fields.png[Task configuration]
. Run the build as usually and click on Allure report artifact on the *Artifacts* tab:
+
image::bamboo_view_artifact.png[Allure artifact]
|
725a011402ac22e26d1032544c38bcdd1a60cfe7
|
[
"Ruby",
"AsciiDoc"
] | 2 |
Ruby
|
vbragin/docs.qameta.io
|
b429a9d9289aa7e38fae037bb6339419190757aa
|
7ac70332d2d599bace42681211a17ee9322a8b78
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.