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>Jackie1995/junjia_model<file_sep>/622685code.R
data0_avg = read.csv('622685.csv')
getwd()
summary(data0_avg$geography_dim)
str(data0_avg_res)
#发现有很多数值型的变量都被数据框给识别成了 factor类型的变量。
names(data0_avg)
#希望在 data0_avg 数据框中把变量名称以‘price’和‘amount’结尾的变量找出来?
pricenames = grep('price',names(data0_avg))
amountnames = grep('amount',names(data0_avg))
convert_names = c(pricenames,amountnames)
#一行代码改变几列的数据类型:
data0_avg[,convert_names] = apply(data0_avg[,convert_names],2,as.numeric)
#到这一步:data0_avg 中的价格与数量变量都已经转化为数值型了。
##下面都是错误的探索
#***************************************************
#convert_names2 = names(data0_avg)[convert_names]
data0_avg[convert_names] = as.numeric(as.character(data0_avg[convert_names]))
#这样做不行。全都是NA
data0_avg$convert_names2 = as.numeric(as.character(data0_avg$convert_names2))
#这样不行
#colname = 'median_deal_price'
for (colname in convert_names2){
data0_avg$colname = as.numeric(data0_avg$colname)
}
as.numeric(data0_avg["median_deal_price"])
for (colindex in convert_names){
data0_avg[colindex] = as.numeric(as.character(data0_avg[colindex]))
}
data0_avg$max_deal_price = as.numeric(as.character(data0_avg$max_deal_price))
data0_avg[15] = as.numeric(as.character(data0_avg[15]))
class(data0_avg['max_deal_price'])
data0_avg[convert_names] = as.numeric((data0_avg[convert_names]))
#Error: (list) object cannot be coerced to type 'double'
str(data0_avg)
summary(data0_avg)
#***************************************************
a <- ls()
rm(list=a[which(a!='data0_avg' & a !='colname')])
#删除当前环境中不需要的变量。
data0_avg_res = data0_avg[data0_avg$geography_dim=='resblock',]
dim(data0_avg_res) #29513 22
summary(data0_avg_res$trans_amount)
index1 = which(is.na(data0_avg_res$trans_amount) & is.na(data0_avg_res$listing_amount))
index1 #integer(0)
#意思就是说。所有的小区在过去的一个月里都有挂牌记录或者交易记录。
#这个结论在excel表中通过对两列同时也得到了验证。
table(data0_avg_res$type)
#apartment simple_rent
#5003 24510
#在数据框中新添一个字段:mean_price_two
which(names(data0_avg_res)=='mean_deal_price') #13
which(names(data0_avg_res)=='mean_listing_price') #18
data0_avg$mean_price_two = rowMeans(data0_avg[,c(13,18)],na.rm = T)
data0_avg_res$mean_price_two = rowMeans(data0_avg_res[,c(13,18)],na.rm = T)
hist(data0_avg_res$mean_price_two)
summary(data0_avg_res$mean_price_two)
#
sort(data0_avg_res$mean_price_two)[1:100]
sort(data0_avg_res$mean_deal_price) [1:100]
sort(data0_avg_res$mean_listing_price)[1:100]
sum(is.na(data0_avg_res$mean_deal_price)) #最近一个月小区地理维度层面:有17276个交易缺失记录
#所以考虑:缩减分组条件。
sum(is.na(data0_avg_res$mean_listing_price)) #3231个缺失
quantile(data0_avg_res$mean_price_two,probs = c(0.8,0.9,0.95,0.99) )
boxplot(data0_avg_res$mean_price_two)
summary(data0_avg_res$hdic_district_id)
boxplot(mean_price_two~hdic_district_id,data = data0_avg_res)
#这个画的有点丑
library(ggplot2)
ggplot(data = data0_avg_res,mapping = aes(x=hdic_district_id,y = mean_price_two) )+
geom_boxplot(mapping = aes(fill = hdic_district_id))
#发现有异常值
<file_sep>/625703code.R
ziru0 = read.csv('625703.csv')
setwd("C:/Users/lianjia/Desktop/junjia_model_lianjia")
getwd()
str(ziru0)
dim(ziru0)# 17202 16
library(dplyr)
#第一步修改数据类型
numeric_names = names(ziru0)[grep('per_area',names(ziru0))]
#numeric_names :是需要把数据类型变成数值型的变量名字符向量。
attach(ziru0)
ziru0[,numeric_names] = apply(ziru0[,numeric_names],2,as.numeric)
ziru0$decoration = as.factor(ziru0$decoration)
ziru0$rent_type = as.factor(ziru0$rent_type)
summary(ziru0$decoration)#自如房源的装修情况:
summary(ziru0$rent_type)#自如房源的租赁类型情况:
sum(price_trans_per_area!=price_listing_per_area,na.rm = T)
#17202
sum(is.na(price_trans_per_area)) #1
sum(is.na(price_listing_per_area)) #1
ziru0[which(is.na(price_trans_per_area)),]
ziru0=ziru0[-15030,]
#在原数据框中删除价格为空的值。
#看一下挂牌价格和成交价格差多少呢
hist(abs(price_trans_per_area-price_listing_per_area)/price_listing_per_area)
ziru1 = group_by(ziru0, hdic_resblock_id,rent_type)
n_groups(ziru1)#3932
table(group_size(ziru1))
ziru2 = ziru0 %>%
group_by(hdic_resblock_id,rent_type) %>%
summarise(n = n(),mean_price = mean(price_trans_per_area))
#将ziru2写出
write.table(ziru2,'ziru2.csv',sep = ",",row.names=F)
#########################################################
zirulian0 = read.csv('628756.csv')
#删掉数据集zirulian0中rent_type或者decoration取0的样本:
zirulian0 = zirulian0[!(zirulian0$decoration==0|zirulian0$rent_type==0),]
str(zirulian0)
#第一步修改数据类型
numeric_names2 = names(zirulian0)[grep('per_area',names(zirulian0))]
#numeric_names :是需要把数据类型变成数值型的变量名字符向量。
zirulian0[,numeric_names] = apply(zirulian0[,numeric_names],2,as.numeric)
#正确设置因子型的变量:decoration,rent_type
zirulian0$decoration = as.factor(zirulian0$decoration)
zirulian0$rent_type = as.factor(zirulian0$rent_type)
summary(zirulian0[zirulian0$appid ==104,'decoration'])#链家房源的装修情况
summary(zirulian0[zirulian0$appid ==104,'rent_type'])#链家房源的租赁情况
complete_logical = complete.cases(zirulian0$price_trans_per_area,zirulian0$price_listing_per_area)
sum(complete_logical)
zirulian0 = zirulian0[complete_logical,]
zirulian1 = group_by(zirulian0, hdic_bizcircle_id,hdic_resblock_id,rent_type)
n_groups(zirulian1)#6307
table(group_size(zirulian1))
#按小区来分类:
zirulian2 = zirulian0 %>%
group_by(hdic_bizcircle_id,hdic_resblock_id,rent_type,decoration) %>%
summarise(n_2 = n(),mean_price_2 = mean(price_trans_per_area))
write.table(zirulian2,'zirulian2.csv',sep = ",",row.names=F)
##按商圈来分类:
zirulian3 = zirulian0 %>%
group_by(hdic_bizcircle_id,rent_type,decoration) %>%
summarise(n_3 = n(),mean_price_3 = mean(price_trans_per_area))
sum(table(zirulian3$n_3))
distinct(zirulian0,hdic_bizcircle_id)#224个不同商圈。
join_data = right_join(ziru2, zirulian2)
join_data2 = inner_join(ziru2, zirulian2)
join_data2 = mutate(join_data2,diff_rate = abs(mean_price_2-mean_price)/mean_price)
summary(join_data2$diff_rate)
sort(join_data2$diff_rate,decreasing = T)
#在链家18000的房源中,装修或者租赁方式不详的样本数目是:
sum(zirulian0$decoration=='0'|zirulian0$rent_type=='0')
#看一下单位面积租赁价的极值:
summary(zirulian0$price_trans_per_area)
#用cast将长表转化为宽表:ziru2_rent_type_junjia:
ziru2_rent_type_junjia = dcast(data = ziru2,formula = hdic_resblock_id~rent_type) #长表变宽表。
names(ziru2_rent_type_junjia)[2:3]=c('zheng_mean','he_mean')
#建立回归模型:谁做因变量?对于自如的房源:合租的居多,所以将整租作为因变量来预测。
lm_2 = lm(formula = sqrt(he_mean)~zheng_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
lm_3 = lm(formula = sqrt(zheng_mean)~he_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
#lm_3的R2是0.51.
#找到缺失值的位置:
indexNA = which(is.na(ziru2_rent_type_junjia$zheng_mean))
indexNA2 = which(is.na(ziru2_rent_type_junjia$he_mean))
#对zheng_mean进行补缺
predict_lm3 = predict(object = lm_3,newdata = ziru2_rent_type_junjia[indexNA,c(2,3)])**2
ziru2_rent_type_junjia[indexNA,'zheng_mean']=predict_lm3
#对he_mean进行补缺
lm_1 = lm(formula = he_mean~zheng_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
predict_lm1 = predict(object = lm_1,newdata = ziru2_rent_type_junjia[indexNA2,c(2,3)])
hist(predict_lm1)
ziru2_rent_type_junjia[indexNA2,'he_mean']=predict_lm1
dim(ziru2_rent_type_junjia)
#ggplot画图
library(ggplot2)
names(data3)
data3$rent_type = as.factor(data3$rent_type)
ggplot(data = data3,aes(x = rent_type,y=price_trans))+
geom_boxplot()
<file_sep>/avg-price/src/main/java/com/lianjia/rent/data/avgprice/avg.sql
select
'resblock' as geography_dim,
appid as type,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
frame_bedroom_num,
rent_type,
decoration,
date_sub (from_unixtime(unix_timestamp(substr(pt,0,8),'yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp(substr(pt,0,8),'yyyymmdd'),'yyyy-mm-dd') as end_date,
pt,
count(if(sign_time is not null, true, null)) as trans_amount,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_trans) as min_trans_price,
max(price_trans) as max_trans_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'0'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'0'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'0'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when from_unixtime(unix_timestamp(sign_time,'yyyy-mm-dd ss:ss:ss'),'yyyymmddssssss')> '201801020000000' and from_unixtime(unix_timestamp(sign_time,'yyyy-mm-dd ss:ss:ss'),'yyyymmddssssss')<='201801160000000' THEN sign_time ELSE NULL END as sign_time,
CASE WHEN from_unixtime(unix_timestamp(app_ctime,'yyyy-mm-dd ss:ss:ss'),'yyyymmddssssss')> '201801020000000' and from_unixtime(unix_timestamp(app_ctime,'yyyy-mm-dd ss:ss:ss'),'yyyymmddssssss')<='201801160000000' THEN app_ctime ELSE NULL ENd as app_ctime,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt>='201801120000000' and pt<'20180117000000'and app_ctime like '2018%' and sign_time like '2018%'
limit 100
) a
where price_trans>0 and price_listing>0
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,hdic_resblock_id,frame_bedroom_num,rent_type,decoration,pt;
<file_sep>/avg-price/src/main/java/com/lianjia/rent/data/avgprice/avg_price_table.sql
create table if not exists rentplat.rentplat_dw_avg_price_di
(
geography_dim string comment '地理粒度',
hdic_city_id int comment '城市ID',
hdic_district_id int comment '市区ID',
hdic_bizcircle_id bigint comment '商圈ID',
hdic_resblock_id bigint comment '小区ID',
start_date string comment '统计起始日期',
end_date string comment '统计截止日期',
frame_bedroom_num int comment '居室数量',
rent_type bigint comment '出租类型',
decoration bigint comment '装修情况',
trans_amount bigint comment '成交数',
median_deal_price decimal comment '成交中位价格',
mean_deal_price decimal comment '成交平均价格',
min_deal_price decimal comment '最小成交价格',
max_deal_price decimal comment '最大成交价格',
listing_amount bigint comment '挂牌数',
median_listing_price decimal comment '挂牌中位价格',
mean_listing_price decimal comment '挂牌平均价格',
min_listing_price decimal comment '最小挂牌价格',
max_listing_price decimal comment '最大挂牌价格',
type string comment '房源来源',
)
comment '不同地理粒度均价表'
ROW FORMAT DELIMITED
PARTITION BY pt
FIELDS TERMINATED BY '\u0001'
COLLECTION ITEMS TERMINATED BY '\u0002'
MAP KEYS TERMINATED BY '\u0003'
STORED AS ORCFILE
location 'hdfs://jx-bd-hadoop00.lianjia.com:9000/user/bigdata/rentplat/dw_log_all_info_di';<file_sep>/avg-price/src/main/java/com/lianjia/rent/data/avgprice/avg_pri.sh
#! /bin/bash
ptt='20170719000000'
end='20180128000000'
while [ "$ptt" != "$end" ]
do
##################################################################
dat=${ptt:0:8}
echo $dat
hive -e"insert into table rentplat.rentplat_dw_avg_price_di
PARTITION (pt = '$ptt')
select
'resblock' as geography_dim,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type
from(
select
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type,
pt
from(
select
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,hdic_resblock_id,frame_bedroom_num,rent_type,decoration,pt
) a
left join (
select
hdic_city_id as city,
hdic_district_id as dis,
hdic_bizcircle_id as biz,
hdic_resblock_id as res,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,hdic_resblock_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.hdic_district_id=b.dis and a.hdic_bizcircle_id=b.biz and a.hdic_resblock_id=b.res and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
union
select
city as hdic_city_id,
dis as hdic_district_id,
biz as hdic_bizcircle_id,
res as hdic_resblock_id,
sta as start_date,
end_ as end_date,
bed as frame_bedroom_num,
ren as rent_type,
dec as decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
typ,
pt1
from(
select
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,hdic_resblock_id,frame_bedroom_num,rent_type,decoration,pt
) a
right join (
select
hdic_city_id as city,
hdic_district_id as dis,
hdic_bizcircle_id as biz,
hdic_resblock_id as res,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,hdic_resblock_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.hdic_district_id=b.dis and a.hdic_bizcircle_id=b.biz and a.hdic_resblock_id=b.res and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
) p;
"
#####################################################################################################################################
dat=${ptt:0:8}
echo $dat
hive -e"insert into table rentplat.rentplat_dw_avg_price_di
PARTITION (pt = '$ptt')
select
'bizcircle' as geography_dim,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
'' as hdic_resblock_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type
from(
select
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type,
pt
from(
select
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,frame_bedroom_num,rent_type,decoration,pt
) a
left join (
select
hdic_city_id as city,
hdic_district_id as dis,
hdic_bizcircle_id as biz,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.hdic_district_id=b.dis and a.hdic_bizcircle_id=b.biz and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
union
select
city as hdic_city_id,
dis as hdic_district_id,
biz as hdic_bizcircle_id,
sta as start_date,
end_ as end_date,
bed as frame_bedroom_num,
ren as rent_type,
dec as decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
typ,
pt1
from(
select
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,frame_bedroom_num,rent_type,decoration,pt
) a
right join (
select
hdic_city_id as city,
hdic_district_id as dis,
hdic_bizcircle_id as biz,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,hdic_district_id,hdic_bizcircle_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.hdic_district_id=b.dis and a.hdic_bizcircle_id=b.biz and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
) p;
"
#####################################################################################################################################
dat=${ptt:0:8}
echo $dat
hive -e"insert into table rentplat.rentplat_dw_avg_price_di
PARTITION (pt = '$ptt')
select
'district' as geography_dim,
hdic_city_id,
hdic_district_id,
'' as hdic_bizcircle_id,
'' as hdic_resblock_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type
from(
select
hdic_city_id,
hdic_district_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type,
pt
from(
select
hdic_city_id,
hdic_district_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
hdic_district_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,hdic_district_id,frame_bedroom_num,rent_type,decoration,pt
) a
left join (
select
hdic_city_id as city,
hdic_district_id as dis,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
hdic_district_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,hdic_district_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.hdic_district_id=b.dis and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
union
select
city as hdic_city_id,
dis as hdic_district_id,
sta as start_date,
end_ as end_date,
bed as frame_bedroom_num,
ren as rent_type,
dec as decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
typ,
pt1
from(
select
hdic_city_id,
hdic_district_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
hdic_district_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,hdic_district_id,frame_bedroom_num,rent_type,decoration,pt
) a
right join (
select
hdic_city_id as city,
hdic_district_id as dis,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
hdic_district_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,hdic_district_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.hdic_district_id=b.dis and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
) p;
"
#####################################################################################################################################
dat=${ptt:0:8}
echo $dat
hive -e"insert into table rentplat.rentplat_dw_avg_price_di
PARTITION (pt = '$ptt')
select
'city' as geography_dim,
hdic_city_id,
'' as hdic_district_id,
'' as hdic_bizcircle_id,
'' as hdic_resblock_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type
from(
select
hdic_city_id,
start_date,
end_date,
frame_bedroom_num,
rent_type,
decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
type,
pt
from(
select
hdic_city_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,frame_bedroom_num,rent_type,decoration,pt
) a
left join (
select
hdic_city_id as city,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
union
select
city as hdic_city_id,
sta as start_date,
end_ as end_date,
bed as frame_bedroom_num,
ren as rent_type,
dec as decoration,
trans_amount,
median_deal_price,
mean_deal_price,
min_deal_price,
max_deal_price,
listing_amount,
median_listing_price,
mean_listing_price,
min_listing_price,
max_listing_price,
typ,
pt1
from(
select
hdic_city_id,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as start_date,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_date,
frame_bedroom_num,
rent_type,
decoration,
count(if(sign_time is not null, true, null)) as trans_amount,
percentile(cast(price_trans as bigint),0.5) as median_deal_price,
avg(price_trans) as mean_deal_price,
min(price_trans) as min_deal_price,
max(price_trans) as max_deal_price,
appid as type,
pt as pt
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_trans is not null,price_trans,0) as price_trans,
CASE when substr(sign_time,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(sign_time,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN sign_time ELSE NULL END as sign_time,
hdic_city_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_trans>0 and sign_time is not null
group by appid, hdic_city_id,frame_bedroom_num,rent_type,decoration,pt
) a
right join (
select
hdic_city_id as city,
date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) as sta,
from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') as end_,
frame_bedroom_num as bed,
rent_type as ren,
decoration as dec,
count(if(app_ctime is not null, true, null)) as listing_amount,
percentile(cast(price_listing as bigint),0.5) as median_listing_price,
avg(price_listing) as mean_listing_price,
min(price_listing) as min_listing_price,
max(price_listing) as max_listing_price,
appid as typ,
pt as pt1
from (
SELECT
case frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as frame_bedroom_num ,
case rent_type
when '1' then '1'
when '2' then '2'
else
'3'
end as rent_type,
case decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else
'4'
end as decoration,
case appid
when '104' then 'simple_rent'
else
'apartment'
end as appid,
if(price_listing is not null,price_listing,0) as price_listing,
CASE when substr(app_ctime,0,10)>date_sub(from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd'),30) and substr(app_ctime,0,10)<=from_unixtime(unix_timestamp('${dat}','yyyymmdd'),'yyyy-mm-dd') THEN app_ctime ELSE NULL END as app_ctime,
hdic_city_id,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id in ('110000', '510100') and appid in ('500', '104') and pt='$ptt'
) w
where price_listing>0 and app_ctime is not null
group by appid, hdic_city_id,frame_bedroom_num,rent_type,decoration,pt
) b
on a.hdic_city_id=b.city and a.start_date=b.sta and a.end_date=b.end_ and a.frame_bedroom_num=b.bed and a.rent_type=b.ren and a.decoration=b.dec and a.type=b.typ and a.pt=b.pt1
) p;
"
echo '4'
dat=${ptt:0:8}
dat=`date -d "-1 days ago $dat" +%Y%m%d`
echo $dat
echo $dat"000000"
let ptt=`echo $dat"000000"`
done <file_sep>/README.md
# junjia_model
doc , code & data
<file_sep>/sql_jk.sql
-- 下面这个sql是:自如 北京 2018年之后签约 2017年之后创建记录 的数据。
-- 查询标号:625703
SELECT
hdic_city_id,
hdic_district_id,
hdic_bizcircle_id,
hdic_resblock_id,
case
frame_bedroom_num
when '1' then '1'
when '2' then '2'
when '3' then '3'
else '0'
end as frame_bedroom_num ,
case
rent_type
when '1' then '1'
when '2' then '2'
else '0'
end as rent_type,
case
decoration
when '1' then '1'
when '2' then '2'
when '3' then '3'
else'0'
end as decoration,
appid,
price_trans,
price_listing,
price_trans/rent_area as price_trans_per_area,
price_listing/rent_area as price_listing_per_area,
to_date(sign_time) as sign_date,
to_date(app_ctime) as appc_date,
datediff(to_date(sign_time),to_date(app_ctime)) as diff_days,
pt
FROM
ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id = 110000 and appid = 500 and pt='20180315000000' and sign_time like '2018%' and from_unixtime(unix_timestamp(app_ctime,'yyyy-mm-dd ss:ss:ss'),'yyyymmddssssss')> '201701010000000'
<file_sep>/avg-price/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>strategy</artifactId>
<groupId>com.lianjia.rent.data</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>avg-price</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<version>2.14.1</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<scalaVersion>2.11.8</scalaVersion>
<sourceDir>src/main/scala</sourceDir>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>${project.artifactId}</finalName>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>conf/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/conf/${profiles.active}</directory>
</resource>
</resources>
</build>
</project><file_sep>/avg-price/src/main/java/com/lianjia/rent/data/valueprice/preprocess_test_bj.py
import pandas as pd
import numpy as np
import re
from sklearn.ensemble import GradientBoostingClassifier
from sklearn import cross_validation, metrics
from sklearn.ensemble import RandomForestClassifier
def preprocess():
#df=pd.read_csv("cd_test.csv",sep="\t")
df=pd.read_csv("bj_test.csv",sep="\t")
df=df[['frame_orientation','hdic_resblock_id','decoration','heating_type','rent_type','sign_time','floor_level','building_finish_year','house_area','frame_hall_num','frame_bedroom_num','frame_kitchen_num','frame_bathroom_num','price_listing','price_trans','rent_area']]
df=df[df['frame_orientation'].notnull()]
df=df[(df['building_finish_year']<2018) & (df['building_finish_year']>1970)]
df=df[(df['house_area']>=8) & (df['rent_area']<=2000)]
df=df[(df['rent_area']>=8) & (df['rent_area']<=2000)]
df=df[df['price_listing']>=500]
df=df[df['price_trans']>=500]
a = df['frame_orientation'].as_matrix()
ori = []
# print df['frame_orientation'].value_counts()
for i in range(len(a)):
n = re.split(r";|,|\?", a[i])
ori.append([x for x in n if x])
df.insert(1,"orientation_E", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_N", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_W", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_S", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_ES", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_EN", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_WS", np.zeros(len(df['frame_orientation'])))
df.insert(1,"orientation_WN", np.zeros(len(df['frame_orientation'])))
for i in range(len(ori)):
for j in range(len(ori[i])):
if(ori[i][j]=='100500000001'):
df.iloc[i,8]=1
elif(ori[i][j]=='100500000002'):
df.iloc[i,4]=1
elif(ori[i][j]=='100500000003'):
df.iloc[i,5]=1
elif(ori[i][j]=='100500000004'):
df.iloc[i,2]=1
elif(ori[i][j]=='100500000005'):
df.iloc[i,6]=1
elif(ori[i][j]=='100500000006'):
df.iloc[i,1]=1
elif(ori[i][j]=='100500000007'):
df.iloc[i,7]=1
elif(ori[i][j]=='100500000008'):
df.iloc[i,3]=1
df.drop(['frame_orientation'], axis=1, inplace=True)
df['sign_time'] = pd.to_datetime(df['sign_time'],format='%Y-%m-%d %H:%M:%S')
month=[i.month for i in df["sign_time"]]
df['month']=month
df.drop(['sign_time'], axis=1, inplace=True)
bt_df1=df[['heating_type','hdic_resblock_id','decoration']]
dummies_hdic_resblock_id = pd.get_dummies(bt_df1['hdic_resblock_id'], prefix= 'hdic_resblock_id')
dummies_decoration = pd.get_dummies(bt_df1['decoration'], prefix= 'decoration')
bt_df1 = pd.concat([bt_df1,dummies_decoration,dummies_hdic_resblock_id], axis=1)
bt_df1.drop(['decoration','hdic_resblock_id'], axis=1, inplace=True)
ye_1=bt_df1[bt_df1['heating_type']==0]
no_1=bt_df1[bt_df1['heating_type']!=0]
ye_ma1=ye_1.as_matrix()
no_ma1=no_1.as_matrix()
y1=no_ma1[:,0]
X1=no_ma1[:,1:]
non1=ye_ma1[:,1:]
clf1=RandomForestClassifier(oob_score=True, random_state=10)
clf1.fit(X1,y1)
pred1=clf1.predict(non1)
df.loc[ (bt_df1['heating_type']==0), 'heating_type' ] = pred1
#print df['heating_type'].value_counts()
#print df['building_type'].value_counts()
#print df.head()
#dummies_hdic_resblock_id = pd.get_dummies(df['hdic_resblock_id'], prefix= 'hdic_resblock_id')
#dummies_hdic_building_id = pd.get_dummies(df['hdic_building_id'], prefix= 'hdic_building_id')
dummies_decoration = pd.get_dummies(df['decoration'], prefix= 'decoration')
dummies_heating_type = pd.get_dummies(df['heating_type'], prefix= 'heating_type')
dummies_rent_type = pd.get_dummies(df['rent_type'], prefix= 'rent_type')
dummies_month = pd.get_dummies(df['month'], prefix= 'month')
dummies_floor_level = pd.get_dummies(df['floor_level'], prefix= 'floor_level')
df= pd.concat([df,dummies_decoration,dummies_heating_type,dummies_rent_type,dummies_month,dummies_floor_level], axis=1)
df.drop(['hdic_resblock_id','decoration','heating_type','rent_type','month','floor_level'], axis=1, inplace=True)
df[['building_year']]=2017-df[['building_finish_year']]
df.drop(['building_finish_year'],axis=1,inplace=True)
df.insert(26,"month_2", np.zeros(len(df['month_1'])))
df.insert(27,"month_3", np.zeros(len(df['month_1'])))
df.insert(28,"month_4", np.zeros(len(df['month_1'])))
df.insert(29,"month_5", np.zeros(len(df['month_1'])))
df.insert(30,"month_6", np.zeros(len(df['month_1'])))
df.insert(31,"month_7", np.zeros(len(df['month_1'])))
df.insert(32,"month_8", np.zeros(len(df['month_1'])))
df.insert(33,"month_9", np.zeros(len(df['month_1'])))
df.insert(34,"month_10", np.zeros(len(df['month_1'])))
df.insert(35,"month_11", np.zeros(len(df['month_1'])))
#df.to_csv("after_pre.csv",index=False)
return df
print(df.info())
<file_sep>/avg-price/src/main/java/com/lianjia/rent/data/valueprice/train.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.externals import joblib
import preprocess_train
from math import sqrt
from sklearn import ensemble
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import KFold
# #############################################################################
# Load data
df=preprocess_train.preprocess()
print(df.head())
#df=pd.read_csv("after_pre.csv")
y=df[['price_trans']]
df.drop(['price_trans'],axis=1,inplace=True)
print df.info()
print(y.info())
y=y.as_matrix()
X=df.as_matrix()
kf=KFold(n_splits=10)
params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2,
'learning_rate': 0.020, 'loss': 'ls'}
clf = ensemble.GradientBoostingRegressor(**params)
sum1=0
sum2=0
df.insert(0,"error", np.zeros(len(df[['house_area']])))
df.insert(1,"predict", np.zeros(len(df[['house_area']])))
for train_index,val_index in kf.split(X):
X_train,X_val=X[train_index],X[val_index]
y_train,y_val=y[train_index],y[val_index]
clf.fit(X_train, y_train)
pre=clf.predict(X_val)
m=[]
for i in range(len(pre)):
m.append([pre[i]])
error=abs(m-y_val)/y_val
#print error
df.loc[val_index,['error']]=error
df.loc[val_index,['predict']]=pre
rmse=sqrt(mean_squared_error(y_val, pre))
mae=mean_absolute_error(y_val, pre)
sum1+=rmse
sum2+=mae
print("once")
avg_error=np.mean(df['error'].as_matrix())
print("avg_error=",avg_error)
print("in_1.0%_true_rate=",float(len(df[df['error']<=0.010]['error']))/len(df['error']))
print("in_2.0%_true_rate=",float(len(df[df['error']<=0.020]['error']))/len(df['error']))
print("in_3.0%_true_rate=",float(len(df[df['error']<=0.030]['error']))/len(df['error']))
print("in_4.0%_true_rate=",float(len(df[df['error']<=0.040]['error']))/len(df['error']))
print("in_5.0%_true_rate=",float(len(df[df['error']<=0.050]['error']))/len(df['error']))
print("in_6.0%_true_rate=",float(len(df[df['error']<=0.060]['error']))/len(df['error']))
print("in_7.0%_true_rate=",float(len(df[df['error']<=0.070]['error']))/len(df['error']))
print("in_8.0%_true_rate=",float(len(df[df['error']<=0.080]['error']))/len(df['error']))
print("in_9.0%_true_rate=",float(len(df[df['error']<=0.090]['error']))/len(df['error']))
print("in_10.0%_true_rate=",float(len(df[df['error']<=0.100]['error']))/len(df['error']))
print ("avg_rmse=" ,sum1/10)
print ("avg_mae=",sum2/10)
df.insert(1,"price_trans",y)
#df.to_csv("predict.csv")
df[['error']].plot(kind='kde')
plt.xlim((0,0.2))
plt.xlabel('error_rate')
plt.ylabel('Desinty')
my_x_ticks = np.arange(0, 0.2, 0.02)
plt.xticks(my_x_ticks)
plt.show()
<file_sep>/zirucode.R
data0 = read.csv('C:\\Users\\lianjia\\Downloads\\616858.csv')
#data0:基准数据集,不要再动它。
#重新添加一行
#关于行政区
summary(data0$hdic_district_id)
data0$hdic_district_id = as.factor(data0$hdic_district_id) #将它转化为因子型的变量
#关于住宅的规划类型
data0$house_type = as.factor(data0$house_type)#转化为因子型的变量
table(data0$house_type)#查看因子型变量的频数分布表
data1 = data0[data0$house_type==107500000003,]
dim(data1) #只保存了商业住宅的数据
library(ggplot2)
ggplot(data = data1,mapping = aes(y = price_trans,x=hdic_district_id))+
geom_boxplot()
ggplot(data = data0,mapping = aes(y = price_trans,x=house_type))+
geom_boxplot()
summary(data1$house_area)
boxplot(data1$house_area)
data2 = data1[data1$house_area<250,]
dim(data2) # 198089 35
boxplot(data2$house_area)
hist(data2$house_area)
#装修情况
summary(data2$decoration) #自如的数据去都是3,所以将这个变量删掉。
#所以要删掉的字段:decoration
#租赁类型
data2$rent_type = factor(data2$rent_type)
summary(data2$rent_type) #整租是1;合租是2
#初步的思路是根据租赁类型的不同,对不同租赁类型的房源分别建模。
# 我们应该根据不同的租赁类型来进行均价的估计
#出租区域面积
summary(data2$rent_area)
data2 = data2[data2$rent_area<250,]
summary(data2[data2$rent_type==1,]$house_area-data2[data2$rent_type==1,]$rent_area)
data2 = data2[data2$house_area>=data2$rent_area,] #数据清洗:房源面积一定要大于等于出租面积
hist(data2$house_area-data2$rent_area)
#合租的话:租赁面积占房源面积的比例。
hist((data2[data2$rent_type==2,]$house_area-data2[data2$rent_type==2,]$rent_area)/data2[data2$rent_type==2,]$house_area)
#商圈编号 hdic_bizcircle_id
data2$hdic_bizcircle_id= factor(data2$hdic_bizcircle_id)
table(data2$hdic_bizcircle_id)
order1_bizcircle = order(table(data2$hdic_bizcircle_id),decreasing = T)
table(data2$hdic_bizcircle_id)[order1_bizcircle]
barplot(table(data2$hdic_bizcircle_id)[order1_bizcircle])
length(table(data2$hdic_bizcircle_id)) #223个商圈
ggplot(data = data2,aes(x = hdic_bizcircle_id))+
geom_bar()
library(dplyr)
data_new1 <- data2%>%
group_by(hdic_bizcircle_id,rent_type)%>%
summarise(n=n(),mean_price = mean(price_trans),cv_price = sd(price_trans)/mean_price,std_price = sd(price_trans))
data_new1
#小区编号 hdic_resblock_id
<file_sep>/avg-price/src/main/java/com/lianjia/rent/data/valueprice/test.py
import numpy as np
import pandas as pd
import preprocess_train
import preprocess_test_cd
#import matplotlib.pyplot as plt
from sklearn.externals import joblib
from math import sqrt
from sklearn import ensemble
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import KFold
train=preprocess_train.preprocess()
train_y=train[['price_trans']].as_matrix()
train.drop(['price_trans'],axis=1,inplace=True)
train_X=train.as_matrix()
test=preprocess_test_cd.preprocess()
test_y=test[['price_trans']].as_matrix()
test.drop(['price_trans'],axis=1,inplace=True)
test_X=test.as_matrix()
params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2,
'learning_rate': 0.020, 'loss': 'ls'}
clf = ensemble.GradientBoostingRegressor(**params)
clf.fit(train_X,train_y)
pre=clf.predict(test_X)
rmse=sqrt(mean_squared_error(test_y,pre))
print("avg_rmse=",rmse)
m=[]
for i in range(len(pre)):
m.append([pre[i]])
error=abs(m-test_y)/test_y
print(type(error))
test.insert(1,"predict", pre)
test.insert(1,"error", error)
avg_error=np.mean(test['error'].as_matrix())
print("avg_error=",avg_error)
print("in_1.0%_true_rate=",float(len(test[test['error']<=0.010]['error']))/len(test['error']))
print("in_2.0%_true_rate=",float(len(test[test['error']<=0.020]['error']))/len(test['error']))
print("in_3.0%_true_rate=",float(len(test[test['error']<=0.030]['error']))/len(test['error']))
print("in_4.0%_true_rate=",float(len(test[test['error']<=0.040]['error']))/len(test['error']))
print("in_5.0%_true_rate=",float(len(test[test['error']<=0.050]['error']))/len(test['error']))
print("in_6.0%_true_rate=",float(len(test[test['error']<=0.060]['error']))/len(test['error']))
print("in_7.0%_true_rate=",float(len(test[test['error']<=0.070]['error']))/len(test['error']))
print("in_8.0%_true_rate=",float(len(test[test['error']<=0.080]['error']))/len(test['error']))
print("in_9.0%_true_rate=",float(len(test[test['error']<=0.090]['error']))/len(test['error']))
print("in_10.0%_true_rate=",float(len(test[test['error']<=0.100]['error']))/len(test['error']))
test.insert(1,"price_trans",test_y)
test.to_csv("predict_test.csv")
#test[['error']].plot(kind='kde')
#plt.xlim((0,0.2))
#plt.xlabel('error_rate')
#plt.ylabel('Desinty')
#my_x_ticks = np.arange(0, 0.2, 0.02)
#plt.xticks(my_x_ticks)
#plt.show()
<file_sep>/ziru0323.Rmd
---
title: "北京自如[2018.1.1-2018.3.15]签约房源的均价分析"
author: "季康"
date: "2018年3月23日"
output:
html_document:
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = TRUE,
warning = FALSE
)
```
## 背景介绍:
数据来源:商家=自如;城市=北京;时间范围:sign_time:2018年;pt=20180315</br>
模型目标:对原始数据集中出现的所有小区,求整租均值和合租均值两个均值。</br>
遇到的主要难题:我们的来源数据,可能不会覆盖所有的小区的整租与合租类型。会造成均值统计数据的缺失。</br>
解决方法就是:在北京市范围内,以小区为统计单元,建立整租均价和合租均价的回归关系。实现二者的相互预测和插补。</br>
本案例对均价模型的助益:在某小区的整租与合租数据历史数据<知一缺一>的情况下,可以通过回归关系补全缺失数据。</br>
不足:如果历史数据对某小区的数据完全缺失,本例这种基于租赁类型维度的插补策略失效。</br>
## step 1:在adhoc中提取数据:
在adhoc中的使用的sql查询语句如下:导出数据存为:625703.csv
```{sql eval=FALSE}
SELECT hdic_city_id, hdic_district_id, hdic_bizcircle_id, hdic_resblock_id,
case frame_bedroom_num when '1' then '1' when '2' then '2' when '3' then '3' else '0' end as frame_bedroom_num ,
case rent_type when '1' then '1' when '2' then '2' else '0' end as rent_type, case decoration when '1' then '1' when '2' then '2' when '3' then '3' else'0' end as decoration,
appid,
price_trans,
price_listing,
price_trans/rent_area as price_trans_per_area,
price_listing/rent_area as price_listing_per_area,
to_date(sign_time) as sign_date,
to_date(app_ctime) as appc_date,
datediff(to_date(sign_time),to_date(app_ctime)) as diff_days,
pt
FROM ods.ods_lianjia_house_rent_new_da
WHERE hdic_city_id = 110000 and appid = 500 and pt='20180315000000'
and sign_time like '2018%' and from_unixtime(unix_timestamp(app_ctime,'yyyy-mm-dd ss:ss:ss'),'yyyymmddssssss')> '201701010000000'
```
##step 2:读入数据。
读入在adhoc中导出的数据:625703.csv
数据的维数是:17202行 16列</br>
数据框ziru0的部分数据如下:</br>
```{r warning=FALSE}
setwd("C:/Users/lianjia/Desktop/junjia_model_lianjia")
ziru0 = read.csv('625703.csv')
dim(ziru0)# 17202 16
head(ziru0)
```
##step 3:数据类型转换:
将价格转换成数值型变量。</br>
将装修情况和租赁类型转换成因子型变量。</br>
添加出租面积area这个字段。</br>
在数据框ziru0中删除价格price_listing_per_area缺失或者price_trans_per_area缺失的观测。</br>
以保证我们的源数据的单位价格变量没有缺失。</br>
```{r }
##要变成数值型的变量:numeric_names
numeric_names = names(ziru0)[grep('per_area',names(ziru0))]
ziru0[,numeric_names] = apply(ziru0[,numeric_names],2,as.numeric)
##要变成因子型的变量:factor_names
ziru0$decoration = as.factor(ziru0$decoration)
ziru0$rent_type = as.factor(ziru0$rent_type)
##增加新的一列:area(因为在sql中提数的时候忘记提这个字段了)
ziru0$area = ziru0$price_listing/ziru0$price_listing_per_area
#在数据框ziru0中删除价格price_listing_per_area缺失或者price_trans_per_area缺失的观测。
complete_row = complete.cases(ziru0$price_trans_per_area,ziru0$price_listing_per_area)
ziru0 = ziru0[complete_row,]
```
## 对商圈这个地理维度进行数据挖掘
### 构建新的数据框:shangquan
```{r}
a = sort(table(ziru0$hdic_bizcircle_id))
#共216个商圈 length(a)=216
#新建一个数据框:shangquan
shangquan = data.frame(number = a)
#依照商圈的租房热门程度,编码离散化变量:商圈热度:
#变量离散化过程中阈值的选择依据:(1-33:冷清)包含25%的商圈,(34-100:一般)包含50%的商圈,(101及以上:热门)包含25%的商圈。
#商圈过去3个月成交量的分位数如下:
summary(shangquan$number.Freq)
#在数据框shangquan中新增加一列:shangquan_degree
library(dplyr)
shangquan <- shangquan %>%
mutate(
shangquan_degree = case_when(
number.Freq <=33 ~ '冷清商圈',
number.Freq>34 & number.Freq<100 ~ '一般商圈',
number.Freq>=100 ~ '热门商圈'
)
)
#重命名数据框各列。
shangquan$shangquan_degree=as.factor(shangquan$shangquan_degree)
names(shangquan) = c('hdic_bizcircle_id','shangquan_pinshu','shangquan_degree')
#将北京自如的商圈的热门情况导出:
write.csv(shangquan,file = 'C:/Users/lianjia/Desktop/junjia_model_lianjia/ziru_hot_shangquan',sep = ',')
```
###画图:北京自如的热门商圈展示
```{r}
windowsFonts(myFont=windowsFont("楷体"))
library(ggplot2)
ggplot(shangquan[shangquan$shangquan_degree=='热门商圈',],aes(x = hdic_bizcircle_id,y = shangquan_pinshu))+
geom_bar(stat = 'identity',fill='#FFD700',color = '#8B6508')+
theme_bw()+
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=1))+
labs(x= 'top25%热门商圈ID',y='商圈近3个月的成交量',title = '北京自如热门商圈展示',subtitle = '热门商圈定义:过去3个月成交量>100笔')+
theme(plot.title = element_text(hjust = 0.5),plot.subtitle = element_text(family = 'myFont',size = 8 ,colour = 'red'))
```
##step :对出租面积area进行描述性的统计分析,来挖掘出租面积对签约价格的影响。
### 1) 出租面积箱线图(整租合租对比):
结论:75%的自如整租房源出租面积在50平米到100平米之间</br>
50%的自如合租房源出租面积在10平米到15平米之间</br>
```{r}
library(ggplot2)
ggplot(data = ziru0,aes(x = rent_type,y=area))+
geom_boxplot(aes(colour = rent_type),alpha=0.4)+
labs(x='房源租赁类型',y='房源出租面积',color = '租赁类型',title='房源出租面积——箱线图')+
scale_x_discrete(labels = c('整租','合租'))+
scale_y_continuous(limits = c(0,200))+
scale_color_discrete(labels = c('整租','合租'))+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5))
```
###2)房源签约价格与出租面积散点图(整租合租对比):
结论:从图中可以看出签约价格(price_listing)与出租面积(area)的线性关系明显。</br>
整租与合租的房源在这面积和价格维度上有明显的聚类分离现象。</br>
#### 1.用北京所有商圈的房源数据来做图(17000条)
```{r}
ggplot(data = ziru0,aes(x = area,y=price_trans))+
geom_point(aes(color = rent_type),alpha=0.4)+
labs(x='房源租赁面积',y='房源签约价格',color = '租赁类型',title='房源签约价格与租赁面积——散点图')+
scale_x_continuous(limits = c(0,175))+
scale_y_continuous(limits = c(0,15000))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))+
scale_color_discrete(labels = c('整租','合租'))
ggplot(data = ziru0[ziru0$rent_type==2,],aes(x = area,y=price_trans))+
geom_point(color='DeepSkyBlue',alpha=0.4)+
labs(x='合租房源租赁面积',y='房源签约价格',color = '租赁类型',title='<合租房源>签约价格与租赁面积——散点图')+
scale_x_continuous(limits = c(0,50))+
scale_y_continuous(limits = c(0,7000))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5),)
#合租房源的成交价格和出租面积的相关系数:0.1 #所以合租房源的成交价格不能用单位价格来衡量。
cor(x = ziru0[ziru0$rent_type==2,'price_trans'],y = ziru0[ziru0$rent_type==2,'area'],method = 'pearson')
#整租房源的成交价格和出租面积的相关系数:0.44
cor(x = ziru0[ziru0$rent_type==1,'price_trans'],y = ziru0[ziru0$rent_type==1,'area'],method = 'pearson')
```
</br>
#### 2.用北京某个商圈内的房源数据来做图(614条)
```{r}
ggplot(data = ziru0[ziru0$hdic_bizcircle_id==18335745,],aes(x = area,y=price_trans))+
geom_point(aes(color = rent_type),alpha=0.8)+
labs(x='房源租赁面积',y='房源签约价格',color = '租赁类型',title='<回龙观>房源签约价格与租赁面积——散点图')+
#scale_x_continuous(limits = c(0,175))+
#scale_y_continuous(limits = c(0,15000))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))+
scale_color_discrete(labels = c('整租','合租'))
ggplot(data = ziru0[ziru0$rent_type==2&ziru0$hdic_bizcircle_id==18335745,],aes(x = area,y=price_trans,color = as.factor(frame_bedroom_num)))+
geom_point(alpha = 0.5)+
labs(x='合租房源租赁面积',y='房源签约价格',title='<回龙观><合租房源>签约价格与租赁面积——散点图',color='卧室数量',subtitle = '不同颜色的点代表不同的卧室数量')+
#scale_x_continuous(limits = c(0,40))+
#scale_y_continuous(limits = c(1500,4000))+
scale_color_manual(values = c('red','blue'))+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5),plot.subtitle = element_text(family = 'myFont',size = 8 ,colour = 'blue'))
ggplot(data = ziru0[ziru0$rent_type==2&ziru0$hdic_bizcircle_id==18335745,],aes(x = area,y=price_trans,color = as.factor(hdic_resblock_id)))+
geom_point(alpha = 0.8,size =1.3)+
labs(x='合租房源租赁面积',y='房源签约价格',title='<回龙观><合租房源>签约价格与租赁面积——散点图',color='小区编号',subtitle = '不同颜色的点代表不同的小区')+
scale_x_continuous(limits = c(6,35))+
scale_y_continuous(limits = c(1600,3700))+
scale_color_manual(values = rainbow(6))+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5),plot.subtitle = element_text(family = 'myFont',size = 8 ,colour = 'blue'))
#同一商圈内:合租房源的成交价格和出租面积的相关系数:0.09
cor(x = ziru0[ziru0$rent_type==2&ziru0$hdic_bizcircle_id==18335745,'price_trans'],y = ziru0[ziru0$rent_type==2&ziru0$hdic_bizcircle_id==18335745,'area'],method = 'pearson')
#同一商圈内:整租房源的成交价格和出租面积的相关系数:0.81
cor(x = ziru0[ziru0$rent_type==1&ziru0$hdic_bizcircle_id==18335745,'price_trans'],y = ziru0[ziru0$rent_type==1&ziru0$hdic_bizcircle_id==18335745,'area'],method = 'pearson')
```
#### 回龙观:小区是不是影响合租价格的显著因素?
```{r}
#
library(dplyr)
hlg_xiaoqu = ziru0 %>%
filter(hdic_bizcircle_id==18335745,rent_type==2) %>%
group_by(hdic_resblock_id) %>%
summarise(n = n(),mean_price = mean(price_trans),std_price = sd(price_trans))
names(hlg_xiaoqu) = c('回龙观小区编号','成交的合租房源数量','成交均价','成交价格的标准差')
ggplot(data =hlg_xiaoqu,aes(x= as.factor(hdic_resblock_id),y=mean_price,fill= as.factor(hdic_resblock_id)) ) +
geom_bar(stat = 'identity')+
labs(x='回龙观小区编号',y='合租成交均价',title='<回龙观><合租房源>按小区合租均价柱状图',
fill = '小区编号',subtitle = '柱子顶部的数字为该小区成交的合租房源数量')+
geom_text(aes(label = n))+
#scale_x_continuous(limits = c(6,35))+
#scale_y_continuous(limits = c(1600,3700))+
#scale_color_manual(values = rainbow(6))+
theme_bw()+
theme(axis.text.x = element_text(angle = 270),plot.title = element_text(hjust = 0.5),plot.subtitle = element_text(family = 'myFont',size = 8 ,colour = 'blue'))
aov2 = aov(formula = price_trans~as.factor(hdic_resblock_id),data =ziru0[ziru0$rent_type==2&ziru0$hdic_bizcircle_id==18335745,])
summary(aov2)
aov2$coefficients
```
#### 回龙观:小区是不是影响合租价格的显著因素?
```{r}
library(dplyr)
hlg_bedroom = ziru0 %>%
filter(hdic_bizcircle_id==18335745,rent_type==2) %>%
group_by(frame_bedroom_num) %>%
summarise(n = n(),mean_price = mean(price_trans),std_price = sd(price_trans))
ggplot(data =hlg_bedroom,aes(x= as.factor(frame_bedroom_num),y=mean_price,fill= as.factor(frame_bedroom_num)) ) +
geom_bar(stat = 'identity',size = 0.5)+
labs(x='不同卧室数量',y='合租成交均价',title='<回龙观><合租房源>按卧室数量均价柱状图',
fill = '卧室数量',subtitle = '柱子顶部的数字为该类型房源成交的合租房源数量')+
geom_text(aes(label = n))+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5),plot.subtitle = element_text(family = 'myFont',size = 8 ,colour = 'blue'))
names(hlg_bedroom) = c('卧室数量','成交的合租房源数量','成交均价','成交价格的标准差')
aov3 = aov(formula = price_trans~as.factor(frame_bedroom_num),data =ziru0[ziru0$rent_type==2&ziru0$hdic_bizcircle_id==18335745,])
summary(aov3)
aov2$coefficients
```
###3)房源签约单价与出租面积散点图(整租合租对比):
结论:1. 自如房源中:合租方式的签约单价是明显高于整租方式的签约单价的。</br>
2. 对于整租房源而言,在同一商圈内,可以认为满足 price_listing =
#### 1.用北京所有商圈的房源数据来做图(17000条)
```{r}
ggplot(data = ziru0,aes(x = area,y=price_trans_per_area))+
geom_point(aes(color = rent_type),alpha=0.4)+
labs(x='房源租赁面积',y='房源签约单价',color = '租赁类型',title='房源签约单价与租赁面积——散点图')+
scale_x_continuous(limits = c(0,175))+
scale_y_continuous(limits = c(0,600))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))+
scale_color_discrete(labels = c('整租','合租'))
```
#### 2.用北京某个商圈内的房源数据来做图(614条)
```{r}
ggplot(data = ziru0[ziru0$hdic_bizcircle_id==18335745,],aes(x = area,y=price_trans_per_area))+
geom_point(aes(color = rent_type),alpha=0.4)+
labs(x='房源租赁面积',y='房源签约单价',color = '租赁类型',title='房源签约单价与租赁面积——散点图')+
scale_x_continuous(limits = c(0,175))+
scale_y_continuous(limits = c(0,600))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))+
scale_color_discrete(labels = c('整租','合租'))
```
##step 4:对数据框ziru0分组
按(商圈,小区,租赁方式)对数据框ziru0分组:得到ziru1_group</br>
按这种方式可以分为:3937组。</br>
查看各个组包含样本数的table表。</br>
```{r}
##查看自如房源的装修情况和租赁情况:
str(ziru0$decoration)
summary(ziru0$decoration)#自如房源的装修情况:
summary(ziru0$rent_type)#自如房源的租赁类型情况:
library(dplyr)
#按(商圈,小区,租赁方式)对数据框ziru0分组:得到ziru1_group
ziru1_group = group_by(ziru0, hdic_bizcircle_id,hdic_resblock_id,rent_type)
#依这样的分组方式可以分成3937组。
n_groups(ziru1_group)
#查看各个组包含样本数的统计表:
table(group_size(ziru1_group))
```
##step 5:对分组数据求聚合:
应用dplyr包中对ziru0这个数据框分组(分组依据:小区,租赁类型)</br>
并对每组求聚合值(组内样本数n,组内平均单价mean_price)</br>
得到新的数据框:ziru2(宽表)。</br>
ziru2(宽表)维度:3932行 4列</br>
ziru2 的head如下:</br>
```{r}
ziru2 = ziru0 %>%
group_by(hdic_district_id,hdic_resblock_id,rent_type) %>%
summarise(n = n(),mean_price = mean(price_trans_per_area))
dim(ziru2)
head(ziru2)
```
##step 6:聚合长表变宽表
将长表ziru2转换为宽表 ziru2_rent_type_junjia</br>
新宽表的3列:小区ID,整租的平均单价,合租的平均单价。</br>
宽表的维度是: 2745 行 3列</br>
统计下宽表中的缺失值数目:1558个。</br>
其中808个小区的整租均值缺失;750个小区的合租均值缺失。</br>
ziru2_rent_type_junjia(宽表)的head如下:</br>
```{r}
library(reshape2)
ziru2_rent_type_junjia = dcast(data = ziru2,formula =hdic_district_id+hdic_resblock_id~rent_type) #长表变宽表。
#改变宽表ziru2_rent_type_junjia中的数据类型:
ziru2_rent_type_junjia$hdic_district_id = as.factor(ziru2_rent_type_junjia$hdic_district_id)
ziru2_rent_type_junjia$hdic_resblock_id =
as.factor(ziru2_rent_type_junjia$hdic_resblock_id)
#修改一下的宽表的列名称,新数据框的3列:小区ID,整租的平均单价,合租的平均单价。
names(ziru2_rent_type_junjia)[3:4]=c('zheng_mean','he_mean')
dim(ziru2_rent_type_junjia)
sum(is.na(ziru2_rent_type_junjia))
#统计整租与合租的缺失值数目。
sum(is.na(ziru2_rent_type_junjia$zheng_mean))#808个整租均值缺失
sum(is.na(ziru2_rent_type_junjia$he_mean))#750个合租均值缺失
head(ziru2_rent_type_junjia)
#绘制箱线图与散点图来挖掘整租均值和合租均值这两个变量的关系;
#绘制箱线图如下:
library(ggplot2)
ggplot(data = ziru2,aes(x = rent_type,y =mean_price))+
geom_boxplot(aes(fill =rent_type ),outlier.colour = '#FF0000')+
labs(x = "租赁类型",y= '单位面积租赁价格(元)',fill='租赁类型',title='单位面积租赁价格——箱线图')+
scale_x_discrete(labels = c('整租','合租'))+
scale_fill_discrete(labels = c('整租','合租'))+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5))
#绘制散点图如下:
ggplot(data = ziru2_rent_type_junjia,aes(x = zheng_mean,y=he_mean))+
geom_point(aes(color = hdic_district_id))+
labs(x='整租单位面积价格',y='合租单位面积价格',color = '所在行政区',title='整租与合租价格——散点图(插补前)')+
scale_x_continuous(limits = c(50,180))+
#scale_y_continuous(limits = c(50,400))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))
#绘制缺失数据所在的行政区:
indexNA_zheng = which(is.na(ziru2_rent_type_junjia$zheng_mean))
indexNA_he = which(is.na(ziru2_rent_type_junjia$he_mean))
ggplot(data = ziru2_rent_type_junjia[c(indexNA_he,indexNA_zheng),],aes(x=reorder(hdic_district_id,rep(1,length(hdic_district_id)),sum)))+
geom_bar(fill = '#FF6347',color = '#8B1A1A')+theme_bw()+
theme(axis.text.x = element_text(angle=30, hjust=1, vjust=1))+
labs(x='行政区编号',y='信息不完整的小区数目',title = '各行政区信息缺失情况对比图')+
theme(plot.title = element_text(hjust = 0.5))
#geom_text(aes(label = count))
```
</br>从箱线图可以看出:这两个均价均呈右偏分布。</br>
从散点图可以看出,整租均价与合租均价呈现明显的线性相关性。</br>
##step 7:建立整租均价和合租均价间的回归模型
首要问题:这两个变量谁做因变量?可参考:统计整租与合租的缺失值数目.</br>
808个整租均值缺失; 750个合租均值缺失.</br>
合租的缺失值少,所以将合租作为自变量,整租作为因变量来预测。</br>
首次回归使用的的样本量:1558个。</br>
回归模型的选择:选择R2最大的lm_1模型(sqrt(zheng_mean)~he_mean)来预测整租均值。</br>
```{r}
#首要问题:谁做因变量?
#首次回归的样本量:1558个观测值。
dim(ziru2_rent_type_junjia)[1]-sum(complete.cases(ziru2_rent_type_junjia))
#结论:合租的缺失值少,所以将合租作为自变量,整租作为因变量来预测。
#回归建模:
#回归模型1 lm_1:Multiple R-squared: 0.624
lm_1 = lm(formula = sqrt(zheng_mean)~he_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
summary(lm_1)
#回归模型2 lm_2:Multiple R-squared: 0.4939
lm_2 = lm(formula = zheng_mean~he_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
summary(lm_2)$r.squared
#回归模型3 lm_3:Multiple R-squared: 0.5115
lm_3 = lm(formula = zheng_mean~sqrt(he_mean),data =ziru2_rent_type_junjia,na.action = na.omit )
summary(lm_3)$r.squared
#模型选择结论:选择R2最大的lm_1模型来预测整租均值。
```
##step 8:对小区均值表中的<整租均价>缺失值进行插补。
先找到两列变量缺失值的位置索引indexNA_zheng和indexNA_he。</br>
对缺失的zheng_mean进行回归预测,对缺失的zheng_mean进行补缺。</br>
```{r}
#找到缺失值的位置:
indexNA_zheng = which(is.na(ziru2_rent_type_junjia$zheng_mean))
indexNA_he = which(is.na(ziru2_rent_type_junjia$he_mean))
#对缺失的zheng_mean进行回归预测
predict_lm1 = predict(object = lm_1,newdata= ziru2_rent_type_junjia[indexNA_zheng,])
#对缺失的zheng_mean进行补缺。
ziru2_rent_type_junjia[indexNA_zheng,'zheng_mean']=predict_lm1**2
```
##step 9:再对小区均值表中的<合租均价>缺失值进行插补。
zheng_mean完整之后,再he_mean进行第二次回归补缺:由lm_1可知,两变量间是是两次函数关系.</br>
第二次回归使用的的样本量:2330个。第二次回归的R2:0.5041</br>
补缺后查看均值表ziru2_rent_type_junjia:现在均值表中已经没有缺失的均价数据</br>
```{r}
#zheng_mean完整之后,再he_mean进行补缺:由lm_1可知,两变量间是是两次函数关系
lm_4 = lm(formula = he_mean~sqrt(zheng_mean),data =ziru2_rent_type_junjia,na.action = na.omit )
summary(lm_4)$r.squared #Multiple R-squared: 0.5041
#选用lm_4模型来对he_mean补缺。
predict_lm4 = predict(object = lm_4,newdata = ziru2_rent_type_junjia[indexNA_he,])
ziru2_rent_type_junjia[indexNA_he,'he_mean']=predict_lm4
head(ziru2_rent_type_junjia)
#现在均值表中已经没有缺失的均价数据。
sum(is.na(ziru2_rent_type_junjia))
```
##step 10:将插补后效果可视化:
回归插补之后的散点图如下:
```{r}
ggplot(data = ziru2_rent_type_junjia,aes(x = zheng_mean,y=he_mean))+
geom_point(aes(color = hdic_district_id))+
labs(x='整租单位面积价格',y='合租单位面积价格',color = '所在行政区',title='整租与合租价格——散点图(插补后)')+
scale_x_continuous(limits = c(50,180))+
#scale_y_continuous(limits = c(50,400))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))
```
<file_sep>/ziru_resblock_renttype_meanprice_per_aera.R
setwd("C:/Users/lianjia/Desktop/junjia_model_lianjia")
#第一步:读入数据。
ziru0 = read.csv('625703.csv')
##数据介绍:adhoc查询条件:自如+北京地区+创建记录在2017.01.01之后+并且在【2018.01.01-2018.03.15】之间成交的房源数据。
dim(ziru0)# 17202 16
#第二步:数据类型转换:
##要变成数值型的变量:numeric_names
numeric_names = names(ziru0)[grep('per_area',names(ziru0))]
attach(ziru0)
ziru0[,numeric_names] = apply(ziru0[,numeric_names],2,as.numeric)
##要变成因子型的变量:factor_names
factor_names = c('decoration','rent_type')
ziru0[,factor_names] = apply(ziru0[,factor_names],2,as.factor)
##查看自如房源的装修情况和租赁情况:
summary(ziru0$decoration)#自如房源的装修情况:
summary(ziru0$rent_type)#自如房源的租赁类型情况:
#在数据框ziru0中删除价格price_listing_per_area缺失或者price_trans_per_area缺失的观测。
complete_row = complete.cases(ziru0$price_trans_per_area,ziru0$price_listing_per_area)
ziru0 = ziru0[complete_logical,]
#按(商圈,小区,租赁方式)对数据框ziru0分组:得到ziru1_group
ziru1_group = group_by(ziru0, hdic_bizcircle_id,hdic_resblock_id,rent_type)
#依这样的分组方式可以分成多少组?
n_groups(ziru1_group)
#查看各个组包含样本数的统计表:
table(group_size(ziru1))
#应用dplyr包对ziru0这个数据框分组(分组依据:小区,租赁类型)求聚合值(组内样本数,组内平均单价)
#得到新的数据框:ziru2。
ziru2 = ziru0 %>%
group_by(hdic_resblock_id,rent_type) %>%
summarise(n = n(),mean_price = mean(price_trans_per_area))
#ziru2现在是一个长表,需要用cast函数将其变成一个宽表ziru2_rent_type_junjia
library(reshape2)
ziru2_rent_type_junjia = dcast(data = ziru2,formula = hdic_resblock_id~rent_type) #长表变宽表。
#修改一下新数据框的列名称,新数据框的3列:小区ID,整租的平均单价,合租的平均单价。
names(ziru2_rent_type_junjia)[2:3]=c('zheng_mean','he_mean')
#建立整租均价和合租均价的回归模型
#首要问题:谁做因变量?
#统计整租与合租的缺失值数目。
#对于自如的房源:合租的居多,所以将整租作为因变量来预测。
lm_2 = lm(formula = sqrt(he_mean)~zheng_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
lm_3 = lm(formula = sqrt(zheng_mean)~he_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
#lm_3的R2是0.51.
#找到缺失值的位置:
indexNA = which(is.na(ziru2_rent_type_junjia$zheng_mean))
indexNA2 = which(is.na(ziru2_rent_type_junjia$he_mean))
#对zheng_mean进行补缺
predict_lm3 = predict(object = lm_3,newdata = ziru2_rent_type_junjia[indexNA,c(2,3)])**2
ziru2_rent_type_junjia[indexNA,'zheng_mean']=predict_lm3
#对he_mean进行补缺
lm_1 = lm(formula = he_mean~zheng_mean,data =ziru2_rent_type_junjia,na.action = na.omit )
predict_lm1 = predict(object = lm_1,newdata = ziru2_rent_type_junjia[indexNA2,c(2,3)])
hist(predict_lm1)
ziru2_rent_type_junjia[indexNA2,'he_mean']=predict_lm1
dim(ziru2_rent_type_junjia)
#房源的租赁面积---箱线图
ziru0$area = ziru0$price_listing/ziru0$price_listing_per_area
ziru0 = ziru0[ziru0$area<200,]
ggplot(data = ziru0,aes(x = rent_type,y=area))+
geom_boxplot(aes(colour = rent_type),alpha=0.4)+
labs(x='房源租赁类型',y='房源出租面积',color = '租赁类型',title='房源出租面积——箱线图')+
scale_x_discrete(labels = c('整租','合租'))+
scale_y_continuous(limits = c(0,200))+
scale_color_discrete(labels = c('整租','合租'))+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5))
#结论:整租的出租面积(75%在50m2-100m2之间)明显高于合租的出租面积(50%在10m2-15m2之间)
summary(ziru0[ziru0$rent_type==1,'area'])
summary(ziru0[ziru0$rent_type==2,'area'])
#房源签约价格与租赁面积---散点图:
names(ziru0)
str(ziru0)
library(ggplot2)
ggplot(data = ziru0,aes(x = area,y=price_listing))+
geom_point(aes(color = rent_type),alpha=0.4)+
labs(x='房源租赁面积',y='房源签约价格',color = '租赁类型',title='房源签约价格与租赁面积——散点图')+
scale_x_continuous(limits = c(0,175))+
scale_y_continuous(limits = c(0,15000))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))+
scale_color_discrete(labels = c('整租','合租'))
#房屋签约单价与租赁面积---散点图:
ggplot(data = ziru0,aes(x = area,y=price_listing_per_area))+
geom_point(aes(color = rent_type),alpha=0.4)+
labs(x='房源租赁面积',y='房源签约单价',color = '租赁类型',title='房源签约单价与租赁面积——散点图')+
scale_x_continuous(limits = c(0,175))+
scale_y_continuous(limits = c(0,600))+
theme_bw()+
scale_color_discrete()+
theme(plot.title = element_text(hjust = 0.5))+
scale_color_discrete(labels = c('整租','合租'))
a = sort(table(ziru0$hdic_bizcircle_id))
length(a)#共216个商圈
class(a)#table
summary(a)
barplot(a)
shangquan = data.frame(number = a)
#依照商圈的租房热门程度,编码离散化变量:商圈热度:
#变量离散化过程中阈值的选择依据:(1-33:冷清)包含25%的商圈,(34-100:一般)包含50%的商圈,(101及以上:热门)包含25%的商圈。
summary(shangquan$number.Freq)
#重编码
library(dplyr)
shangquan <- shangquan %>%
mutate(
shangquan_degree = case_when(
number.Freq <=33 ~ '冷清商圈',
number.Freq>34 & number.Freq<100 ~ '一般商圈',
number.Freq>=100 ~ '热门商圈'
)
)
shangquan$shangquan_degree=as.factor(shangquan$shangquan_degree)
names(shangquan) = c('hdic_bizcircle_id','shangquan_pinshu','shangquan_degree')
#画图:北京自如的热门商圈展示
windowsFonts(myFont=windowsFont("楷体"))
ggplot(shangquan[shangquan$shangquan_degree=='热门商圈',],aes(x = hdic_bizcircle_id,y = shangquan_pinshu))+
geom_bar(stat = 'identity',fill='#FFD700',color = '#8B6508')+
theme_bw()+
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=1))+
labs(x= 'top25%热门商圈ID',y='商圈近3个月的成交量',title = '北京自如热门商圈展示',subtitle = '热门商圈定义:过去3个月成交量>100笔')+
theme(plot.title = element_text(hjust = 0.5),plot.subtitle = element_text(family = 'myFont',size = 8 ,colour = 'red'))
| f29a307344ce42271eb45d765d08fa18be5b7060 | [
"SQL",
"Markdown",
"Maven POM",
"Python",
"R",
"RMarkdown",
"Shell"
] | 14 | R | Jackie1995/junjia_model | 2df32bfc416d6df19e0f5fb324cf044091f463b4 | 2928d4cdc42d3e9fbd21a2bb4aec328af208945a |
refs/heads/master | <file_sep>-- In this file, write insert queries to populate the burgers table with at least three entries.
<file_sep>CREATE DATABASE burgers_db;
USE burgers_db;
CREATE TABLE burgers (
id INT NOT NULL AUTO_INCREMENT,
burger_name VARCHAR(255) NOT NULL,
devoured BOOL DEFAULT false,
PRIMARY KEY (id)
);
INSERT INTO burgers (burger_name, devoured) VALUES ('Mother Blues Burger', FALSE);
INSERT INTO burgers (burger_name, devoured) VALUES ('Royale Buerger', FALSE);
INSERT INTO burgers (burger_name, devoured) VALUES ('Chupacabra Burger', FALSE);
INSERT INTO burgers (burger_name, devoured) VALUES ('Terlingua Burger', FALSE); | 4f57dcced9e1ee7ae78f970d56cabac236d03b99 | [
"SQL"
] | 2 | SQL | mikegarcia7/burger | aa2739ff8704f8f9866b5013492405d7017a1527 | 15e4779345d8c23717e1abf56402c4dfcb139cd4 |
refs/heads/master | <file_sep># Generated by Django 2.2.14 on 2020-08-09 06:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0003_remove_article_content'),
]
operations = [
migrations.AddField(
model_name='article',
name='content',
field=models.TextField(default='default text'),
),
]
<file_sep>import io
from django.http import HttpResponse
from wsgiref.util import FileWrapper
from django.shortcuts import render, get_object_or_404
from django.core.files import File
from django.template import loader
from .models import Article
# Create your views here.
def home(request):
articles = Article.objects.order_by('-publish_date')[:5]
context = {'articles': articles}
return render(request, 'app/ArticleList.html', context)
def content_view(request, id):
article = get_object_or_404(Article, pk=id)
return render(request, 'app/ArticleView.html', {'article': article})<file_sep>from django.db import models
from tinymce.models import HTMLField
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
content = HTMLField()
publish_date = models.DateTimeField('date published')
#TO-DO: Add tags<file_sep>"""
Package for BioWebsite.
"""
<file_sep># Generated by Django 2.2.14 on 2020-08-09 22:09
from django.db import migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('app', '0005_auto_20200809_0136'),
]
operations = [
migrations.AlterField(
model_name='article',
name='content',
field=tinymce.models.HTMLField(),
),
]
<file_sep># Generated by Django 2.2.14 on 2020-08-09 06:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20200809_0045'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='content',
),
]
| 97f04c2909328116cf1225743f5b53a638aca6a5 | [
"Python"
] | 6 | Python | danielandrejczyk/BioWebsite | 047239ee18aab104307fabeb97d192b2386e44dc | f0b69d6f4014464fbbb07ccf0afc78da1a864257 |
refs/heads/master | <repo_name>LittleSpades/CPD<file_sep>/Serial/matFact.c
/**************************Declarations**************************/
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#define RAND01 ((double)random() / (double)RAND_MAX)
typedef struct entry {
int user;
int item;
double rate;
double recom;
struct entry *nextItem;
struct entry *nextUser;
} entry;
void alloc_A(int nU, int nI, entry ***_A_user, entry ***_A_item,
entry ***_A_user_aux, entry ***_A_item_aux);
entry *createNode();
void alloc_LRB(int nU, int nI, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B);
void random_fill_LR(int nU, int nI, int nF, double ***L, double ***R,
double ***newL, double ***newR);
void update_recom(int nU, int nF, double ***L, double ***R,
entry ***A_user);
void update_LR(double ***L, double ***R, double ***newL, double ***newR);
void free_LR(int nU, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B);
/****************************************************************/
int main(int argc, char *argv[]) {
FILE *fp;
int nIter, nFeat, nUser, nItem, nEntry;
int *solution;
double deriv = 0;
double alpha, sol_aux;
double **L, **R, **B, **newL, **newR;
char *outputFile;
entry **A_user, **A_user_aux, **A_item, **A_item_aux;
entry *A_aux1, *A_aux2;
if (argc != 2) {
printf("error: command of type ./matFact <filename.in>\n");
exit(1);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("error: cannot open file\n");
exit(1);
}
/******************************Setup******************************/
// read of first parameters of file
fscanf(fp, "%d", &nIter);
fscanf(fp, "%lf", &alpha);
fscanf(fp, "%d", &nFeat);
fscanf(fp, "%d %d %d", &nUser, &nItem, &nEntry);
// alloc struct that holds A and it's approximation, B
alloc_A(nUser, nItem, &A_user, &A_item, &A_user_aux, &A_item_aux);
// alloc vector that holds highest recom. per user
solution = (int *)malloc(sizeof(int) * nUser);
// construct of a list of lists
for (int i = 0; i < nEntry; i++) {
A_aux1 = createNode();
// load of entry of matrix A
fscanf(fp, "%d %d %lf", &(A_aux1->user), &(A_aux1->item), &(A_aux1->rate));
if (A_user[A_aux1->user] == NULL) {
A_user[A_aux1->user] = A_aux1;
A_user_aux[A_aux1->user] = A_aux1;
} else {
A_user_aux[A_aux1->user]->nextItem = A_aux1;
A_user_aux[A_aux1->user] = A_aux1;
}
if (A_item[A_aux1->item] == NULL) {
A_item[A_aux1->item] = A_aux1;
A_item_aux[A_aux1->item] = A_aux1;
} else {
A_item_aux[A_aux1->item]->nextUser = A_aux1;
A_item_aux[A_aux1->item] = A_aux1;
}
}
fclose(fp);
free(A_item_aux);
free(A_user_aux);
// alloc L, R and B where B is only used for the final calculation
alloc_LRB(nUser, nItem, nFeat, &L, &R, &newL, &newR, &B);
// init L and R with random values
random_fill_LR(nUser, nItem, nFeat, &L, &R, &newL, &newR);
// init of values of B that are to be approximated to the rate of
// items per user
update_recom(nUser, nFeat, &L, &R, &A_user);
/****************************End Setup****************************/
/***********************Matrix Factorization**********************/
// main loop with stopping criterium
for (int n = 0; n < nIter; n++) {
// calculation of the t+1 iteration of L
for (int i = 0; i < nUser; i++) {
for (int k = 0; k < nFeat; k++) {
A_aux1 = A_user[i];
// sum of derivatives per item
while (A_aux1 != NULL) {
deriv +=
2 * (A_aux1->rate - A_aux1->recom) * (-R[k][A_aux1->item]);
A_aux1 = A_aux1->nextItem;
}
// final calculation of t+1
newL[i][k] = L[i][k] - alpha * deriv;
deriv = 0;
}
}
// calculation of the t+1 iteration of R
for (int j = 0; j < nItem; j++) {
for (int k = 0; k < nFeat; k++) {
A_aux1 = A_item[j];
// sum of derivatives per user
while (A_aux1 != NULL) {
deriv +=
2 * (A_aux1->rate - A_aux1->recom) * (-L[A_aux1->user][k]);
A_aux1 = A_aux1->nextUser;
}
// final calculation of t+1
newR[k][j] = R[k][j] - alpha * deriv;
deriv = 0;
}
}
// update of L and R with the t+1 values
update_LR(&L, &R, &newL, &newR);
// update of B for each non-zero element of A
update_recom(nUser, nFeat, &L, &R, &A_user);
}
/*********************End Matrix Factorization********************/
// calculation of the entire B matrix meaning the
// internal product between L and R
for (int i = 0; i < nUser; i++)
for (int j = 0; j < nItem; j++) {
B[i][j] = 0;
for (int k = 0; k < nFeat; k++)
B[i][j] += L[i][k] * R[k][j];
}
// update of solution with highest calculated recomendation
// rate per user
for (int k = 0; k < nUser; k++) {
sol_aux = 0;
A_aux1 = A_user[k];
// update entry of B to 0 if item already rated
while (A_aux1 != NULL) {
B[k][A_aux1->item] = 0;
A_aux1 = A_aux1->nextItem;
}
// save item with highest rate
for(int j = 0; j < nItem; j++){
if (B[k][j] > sol_aux) {
solution[k] = j;
sol_aux = B[k][j];
}
}
}
/****************************Write File***************************/
// create .out file for writing
outputFile = strtok(argv[1], ".");
strcat(outputFile, ".out\0");
fp = fopen(outputFile, "w");
if (fp == NULL) {
printf("error: cannot open file\n");
exit(1);
}
// write recomendation on file per user
for (int i = 0; i < nUser; i++) {
fprintf(fp, "%d\n", solution[i]);
}
fclose(fp);
/*****************************************************************/
/******************************Free A*****************************/
for (int i = 0; i < nUser; i++) {
A_aux1 = A_user[i];
while (A_aux1 != NULL) {
A_aux2 = A_aux1->nextItem;
free(A_aux1);
A_aux1 = A_aux2;
}
}
free(A_user);
free(A_item);
/*****************************************************************/
free(solution);
free_LR(nUser, nFeat, &L, &R, &newL, &newR, &B);
return 0;
}
void alloc_A(int nU, int nI, entry ***_A_user, entry ***_A_item,
entry ***_A_user_aux, entry ***_A_item_aux) {
*_A_user = (entry **)calloc(sizeof(entry *), nU);
*_A_item = (entry **)calloc(sizeof(entry *), nI);
*_A_user_aux = (entry **)calloc(sizeof(entry *), nU);
*_A_item_aux = (entry **)calloc(sizeof(entry *), nI);
}
entry *createNode() {
entry *A;
A = (entry *)malloc(sizeof(entry));
A->nextItem = NULL;
A->nextUser = NULL;
return A;
}
void alloc_LRB(int nU, int nI, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B) {
*B = (double **)malloc(sizeof(double *) * nU);
*L = (double **)malloc(sizeof(double *) * nU);
*newL = (double **)malloc(sizeof(double *) * nU);
*R = (double **)malloc(sizeof(double *) * nF);
*newR = (double **)malloc(sizeof(double *) * nF);
for (int i = 0; i < nU; i++) {
(*B)[i] = (double *)malloc(sizeof(double) * nI);
(*L)[i] = (double *)malloc(sizeof(double) * nF);
(*newL)[i] = (double *)malloc(sizeof(double) * nF);
}
for (int i = 0; i < nF; i++) {
(*R)[i] = (double *)malloc(sizeof(double) * nI);
(*newR)[i] = (double *)malloc(sizeof(double) * nI);
}
}
void random_fill_LR(int nU, int nI, int nF, double ***L, double ***R,
double ***newL, double ***newR) {
srandom(0);
// init of L, stable version, and newL for t+1
for (int i = 0; i < nU; i++)
for (int j = 0; j < nF; j++) {
(*L)[i][j] = RAND01 / (double)nF;
(*newL)[i][j] = (*L)[i][j];
}
// init of R, stable version, and newR for t+1
for (int i = 0; i < nF; i++)
for (int j = 0; j < nI; j++) {
(*R)[i][j] = RAND01 / (double)nF;
(*newR)[i][j] = (*R)[i][j];
}
}
void update_LR(double ***L, double ***R, double ***newL, double ***newR) {
double **aux;
// update stable version of L with L(t+1) by switching
// the pointers
aux = *L;
*L = *newL;
*newL = aux;
// update stable version of R with R(t+1) by switching
// the pointers
aux = *R;
*R = *newR;
*newR = aux;
}
void update_recom(int nU, int nF, double ***L, double ***R,
entry ***A_user) {
entry *A_aux1;
// update recomendation for all non-zero entries meaning
// the approximation of B to A
for (int i = 0; i < nU; i++) {
A_aux1 = (*A_user)[i];
while (A_aux1 != NULL) {
A_aux1->recom = 0;
for (int k = 0; k < nF; k++)
A_aux1->recom += (*L)[i][k] * (*R)[k][A_aux1->item];
A_aux1 = A_aux1->nextItem;
}
}
}
void free_LR(int nU, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B) {
for (int i = 0; i < nU; i++) {
free((*B)[i]);
free((*L)[i]);
free((*newL)[i]);
}
free(*B);
free(*L);
free(*newL);
for (int i = 0; i < nF; i++) {
free((*R)[i]);
free((*newR)[i]);
}
free(*newR);
free(*R);
}
<file_sep>/OpenMP/makefile
OpenMP: matFact-omp.c
gcc -fopenmp matFact-omp.c -o matFact-omp
<file_sep>/Serial/makefile
Serial: matFact.c
gcc matFact.c -o matFact
<file_sep>/OpenMP/matFact-omp.c
/**************************Declarations**************************/
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#define RAND01 ((double)random() / (double)RAND_MAX)
typedef struct entryA {
int user;
int item;
double rate;
double recom;
struct entryA *nextItem;
struct entryA *nextUser;
} entryA;
void alloc_A(int nU, int nI, entryA ***_A_user, entryA ***_A_item,
entryA ***_A_user_aux, entryA ***_A_item_aux);
entryA *createNode();
void random_fill_LR(int nU, int nI, int nF, double ***L, double ***R,
double ***newL, double ***newR);
void alloc_LRB(int nU, int nI, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B);
void update_recom(int nU, int nF, double ***L, double ***R, entryA ***A_user);
void update_LR(double ***L, double ***R, double ***newL, double ***newR);
void free_LR(int nU, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B);
/****************************************************************/
int main(int argc, char *argv[]) {
FILE *fp;
int nIter, nFeat, nUser, nItem, nEntry;
int *solution;
double deriv = 0;
double alpha, sol_aux;
double **L, **R, **B, **newL, **newR;
char *outputFile;
entryA **A_user, **A_user_aux, **A_item, **A_item_aux;
entryA *A_aux1, *A_aux2;
if (argc != 2) {
printf("error: command of type ./matFact <filename.in>\n");
exit(1);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("error: cannot open file\n");
exit(1);
}
/******************************Setup******************************/
// read of first parameters of file
fscanf(fp, "%d", &nIter);
fscanf(fp, "%lf", &alpha);
fscanf(fp, "%d", &nFeat);
fscanf(fp, "%d %d %d", &nUser, &nItem, &nEntry);
// alloc struct that holds A and it's approximation, B
alloc_A(nUser, nItem, &A_user, &A_item, &A_user_aux, &A_item_aux);
// alloc vector that holds highest recom. per user
solution = (int *)malloc(sizeof(int) * nUser);
// construct of a list of lists
for (int i = 0; i < nEntry; i++) {
A_aux1 = createNode();
// load of entry of matrix A
fscanf(fp, "%d %d %lf", &(A_aux1->user), &(A_aux1->item), &(A_aux1->rate));
if (A_user[A_aux1->user] == NULL) {
A_user[A_aux1->user] = A_aux1;
A_user_aux[A_aux1->user] = A_aux1;
} else {
A_user_aux[A_aux1->user]->nextItem = A_aux1;
A_user_aux[A_aux1->user] = A_aux1;
}
if (A_item[A_aux1->item] == NULL) {
A_item[A_aux1->item] = A_aux1;
A_item_aux[A_aux1->item] = A_aux1;
} else {
A_item_aux[A_aux1->item]->nextUser = A_aux1;
A_item_aux[A_aux1->item] = A_aux1;
}
}
fclose(fp);
free(A_item_aux);
free(A_user_aux);
// alloc L, R and B where B is only used for the final calculation
alloc_LRB(nUser, nItem, nFeat, &L, &R, &newL, &newR, &B);
// init L and R with random values
random_fill_LR(nUser, nItem, nFeat, &L, &R, &newL, &newR);
// init of values of B that are to be approximated to the rate of
// items per user, meaning the values present on A
update_recom(nUser, nFeat, &L, &R, &A_user);
/****************************End Setup****************************/
/***********************Matrix Factorization**********************/
// main main loop with stopping criterium
for (int n = 0; n < nIter; n++) {
// parallelized section
#pragma omp parallel default(none) shared(nUser, nItem, nFeat, A_user, A_item, R, L,newR, newL, alpha, deriv, A_aux1)
{
// parallelized t+1 calculation of L with nowait and dynamic due to
// unbalanced data and no dependencies in the next loop
#pragma omp for firstprivate(A_aux1, deriv) nowait schedule(dynamic)
for (int i = 0; i < nUser; i++) {
for (int k = 0; k < nFeat; k++) {
A_aux1 = A_user[i];
while (A_aux1 != NULL) {
deriv +=
2 * (A_aux1->rate - A_aux1->recom) * (-R[k][A_aux1->item]);
A_aux1 = A_aux1->nextItem;
}
newL[i][k] = L[i][k] - alpha * deriv;
deriv = 0;
}
}
// parallelized t+1 calculation of R with dynamic due to
// unbalanced data
#pragma omp for firstprivate(A_aux1, deriv) schedule(dynamic)
for (int j = 0; j < nItem; j++) {
for (int k = 0; k < nFeat; k++) {
A_aux1 = A_item[j];
while (A_aux1 != NULL) {
deriv +=
2 * (A_aux1->rate - A_aux1->recom) * (-L[A_aux1->user][k]);
A_aux1 = A_aux1->nextUser;
}
newR[k][j] = R[k][j] - alpha * deriv;
deriv = 0;
}
}
}
// update of L and R with the t+1 values
update_LR(&L, &R, &newL, &newR);
// update of B for each non-zero element of A
update_recom(nUser, nFeat, &L, &R, &A_user);
}
/*********************End Matrix Factorization********************/
// parallelized calculation of B
#pragma omp parallel for //default(none) shared(nUser, B, L, R, nFeat, nItem)
for (int i = 0; i < nUser; i++){
for (int j = 0; j < nItem; j++){
B[i][j] = 0;
for (int k = 0; k < nFeat; k++)
B[i][j] += L[i][k] * R[k][j];
}
}
// parallelized section
#pragma omp parallel default(none) private(sol_aux, A_aux1) shared(B, solution, nUser, A_user, nItem)
{
// parallelized calculation of highest recomendation rate
#pragma omp for schedule(dynamic)
for (int k = 0; k < nUser; k++) {
sol_aux = 0;
A_aux1 = A_user[k];
while (A_aux1 != NULL) {
B[k][A_aux1->item] = 0;
A_aux1 = A_aux1->nextItem;
}
for(int j = 0; j < nItem; j++){
if (B[k][j] > sol_aux) {
solution[k] = j;
sol_aux = B[k][j];
}
}
}
}
/****************************Write File***************************/
// create .out file for writing
outputFile = strtok(argv[1], ".");
strcat(outputFile, ".out\0");
fp = fopen(outputFile, "w");
if (fp == NULL) {
printf("error: cannot open file\n");
exit(1);
}
// write recomendation on file per user
for (int i = 0; i < nUser; i++) {
fprintf(fp, "%d\n", solution[i]);
}
fclose(fp);
/*****************************************************************/
/******************************Free A*****************************/
for (int i = 0; i < nUser; i++) {
A_aux1 = A_user[i];
while (A_aux1 != NULL) {
A_aux2 = A_aux1->nextItem;
free(A_aux1);
A_aux1 = A_aux2;
}
}
free(A_user);
free(A_item);
/*****************************************************************/
free(solution);
free_LR(nUser, nFeat, &L, &R, &newL, &newR, &B);
return 0;
}
void alloc_A(int nU, int nI, entryA ***_A_user, entryA ***_A_item,
entryA ***_A_user_aux, entryA ***_A_item_aux) {
*_A_user = (entryA **)calloc(sizeof(entryA *), nU);
*_A_item = (entryA **)calloc(sizeof(entryA *), nI);
*_A_user_aux = (entryA **)calloc(sizeof(entryA *), nU);
*_A_item_aux = (entryA **)calloc(sizeof(entryA *), nI);
}
entryA *createNode() {
entryA *A;
A = (entryA *)malloc(sizeof(entryA));
A->nextItem = NULL;
A->nextUser = NULL;
return A;
}
void alloc_LRB(int nU, int nI, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B) {
*B = (double **)malloc(sizeof(double *) * nU);
*L = (double **)malloc(sizeof(double *) * nU);
*newL = (double **)malloc(sizeof(double *) * nU);
*R = (double **)malloc(sizeof(double *) * nF);
*newR = (double **)malloc(sizeof(double *) * nF);
// parallelized section
#pragma omp parallel default(none) shared(B, L, newL, R, newR, nU, nF, nI)
{
// parallelized allocation with nowait because there
// are no dependencies in the next loop
#pragma omp for nowait
for (int i = 0; i < nU; i++) {
(*B)[i] = (double *)malloc(sizeof(double) * nI);
(*L)[i] = (double *)malloc(sizeof(double) * nF);
(*newL)[i] = (double *)malloc(sizeof(double) * nF);
}
// parallelized allocation without nowait due to
// synchronization in the end of the section
#pragma omp for
for (int i = 0; i < nF; i++) {
(*R)[i] = (double *)malloc(sizeof(double) * nI);
(*newR)[i] = (double *)malloc(sizeof(double) * nI);
}
}
}
void random_fill_LR(int nU, int nI, int nF, double ***L, double ***R,
double ***newL, double ***newR) {
srandom(0);
// init of L, stable version, and newL for t+1
for (int i = 0; i < nU; i++)
for (int j = 0; j < nF; j++) {
(*L)[i][j] = RAND01 / (double)nF;
(*newL)[i][j] = (*L)[i][j];
}
// init of R, stable version, and newR for t+1
for (int i = 0; i < nF; i++)
for (int j = 0; j < nI; j++) {
(*R)[i][j] = RAND01 / (double)nF;
(*newR)[i][j] = (*R)[i][j];
}
}
void update_LR(double ***L, double ***R, double ***newL, double ***newR) {
double **aux;
// update stable version of L with L(t+1) by switching
// the pointers
aux = *L;
*L = *newL;
*newL = aux;
// update stable version of R with R(t+1) by switching
// the pointers
aux = *R;
*R = *newR;
*newR = aux;
}
void update_recom(int nU, int nF, double ***L, double ***R, entryA ***A_user) {
entryA *A_aux1;
// parallelized section
#pragma omp parallel default(none) private(A_aux1) shared(nU, nF, L, R, A_user)
{
// parallelized update of recomendation with dynamic
// due to unbalanced data
#pragma omp for schedule(dynamic)
for (int i = 0; i < nU; i++) {
A_aux1 = (*A_user)[i];
while (A_aux1 != NULL) {
A_aux1->recom = 0;
for (int k = 0; k < nF; k++)
A_aux1->recom += (*L)[i][k] * (*R)[k][A_aux1->item];
A_aux1 = A_aux1->nextItem;
}
}
}
}
void free_LR(int nU, int nF, double ***L, double ***R, double ***newL,
double ***newR, double ***B) {
for (int i = 0; i < nU; i++) {
free((*B)[i]);
free((*L)[i]);
free((*newL)[i]);
}
free(*B);
free(*L);
free(*newL);
for (int i = 0; i < nF; i++) {
free((*R)[i]);
free((*newR)[i]);
}
free(*newR);
free(*R);
}
| 1cc82c9b76856eb91355ed852e9c758e0073bb83 | [
"C",
"Makefile"
] | 4 | C | LittleSpades/CPD | 7571c5eae7269ec64b7d436f6a8c4f5673f55d88 | 575d5ef2cf538ec05e38edbaadc8e1410670dc34 |
refs/heads/master | <file_sep>first-firefox-os-app
====================
"<NAME>" - Search for everything using Google on douban.com, one of my favourite sites which I think has poor search function.
<file_sep>$( document ).ready(function() {
$('#search_form').submit(function() {
var keywords = $('#search_text').val();
var query = keywords + ' site:douban.com';
$('#search_value').val(query);
return true;
});
});
| 01f3f5049d2f7cd7e627525c59f3afa411132ab2 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | zenja/first-firefox-os-app | 9891d7d12eb1fd31d3c283915769c37982b6fa1a | c891489e2d29c8f910b30f87e736345339f53462 |
refs/heads/master | <repo_name>thebigdeal916/Burger<file_sep>/README.md
# Burger App
This is the Burger homework, the goal of this app is to demonstrate
what I have learned in the past couple of weeks about various technologies,
those technoligies are as foillows:
* handlebars
* config files
* controllers
* database useage(MySQL)
* model usage
* css
* javascript
* servers
This project is my first deep dive into full stack programming, my main troubles
came from the routing and ORM , i'm still having problems with the concepts of ORM, it
will come together I feel more time working on it will benifit me greatly.<file_sep>/config/orm.js
const connection = require("./connection.js")
const orm = {
selectAll: function(tableInput, colToSearch, valOfCol) {
let queryString = "SELECT * FROM ?? WHERE?? = ?";
connection.query(queryString, [tableInput, colToSearch, valOfCol], function(err, result){
if (err) throw err;
cb(result)
})
},
insertOne: function(whatToSelect, table, orderCol) {
var queryString = "SELECT ?? FROM ?? ORDER BY ?? DESC";
console.log(queryString);
connection.query(queryString [whatToSelect, table, orderCol], function(err, result){
if (err) throw err;
cb(result)
})
},
updateOne: function(){
}
}
module.exports = orm;<file_sep>/db/seeds.sql
INSERT INTO burgers(id, burger_name, devoured)
VALUES (1, "baco blaster", true);
INSERT INTO burgers (id, burger_name, devoured)
VALUES (2, "still mooing", false);
INSERT INTO burgers (id, burger_name, devoured)
VALUES (3, "ham heart attack", true);
SELECT * FROM burgers
| 37736d578c63bb0838c2e2bc8d5153e7cb948c39 | [
"Markdown",
"SQL",
"JavaScript"
] | 3 | Markdown | thebigdeal916/Burger | c9b6aae7ae2792b8fa35ba268e64f5b103c26616 | cdc10d6f552c79fa7ea373a8ce8c9df7300716b5 |
refs/heads/master | <file_sep>package betterArchitecture.GUI;
//import DAO.UserDao;
import betterArchitecture.GUI.HelloWindow;
import betterArchitecture.implementation.MySQLDaoFactory;
import betterArchitecture.implementation.UserDaoImpl;
import betterArchitecture.valueObjects.User;
import com.mysql.jdbc.exceptions.MySQLDataException;
import java.sql.*;
import javax.swing.*;
import java.awt.Checkbox;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.ArrayList;
import java.util.List;
/**
* Created by <NAME> on 09.03.2016.
*/
public class Registration {
private JPanel panel1;
private JLabel registrationForm;
private JLabel firstName;
private JLabel lastName;
private JLabel nickName;
private JButton registerButton;
private JTextField firstNameField;
private JTextField lastNameField;
private JTextField nickNameField;
private JCheckBox manCheckBox;
private JCheckBox womanCheckBox;
private JPasswordField confPasswordField;
private JPasswordField passwordField;
private JFrame frame;
private MySQLDaoFactory factory = new MySQLDaoFactory();
private UserDaoImpl userDa0 = new UserDaoImpl(factory.getConnection());
public Registration () throws SQLException{
frame = new JFrame("Registration");
frame.setContentPane(panel1);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setLocation(600, 300);
frame.setVisible(true);
passwordField.setEchoChar('*');
confPasswordField.setEchoChar('*');
registerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
registrarion();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
}
public void registrarion () throws SQLException{
if (isUserDataCorrect() && isPasswordsEquals() && isSex() && isTheSameUser()){
User newUser = new User();
newUser.setFirstName(firstNameField.getText());
newUser.setLastName(lastNameField.getText());
newUser.setNickName(nickNameField.getText());
newUser.setSex(getSex());
newUser.setPassword(passwordField.getText());
DateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
newUser.setRegistrationDate(dateFormat.format(cal.getTime()));
userDa0.create(newUser);
JOptionPane.showMessageDialog(null, "User \""+newUser.getNickName()+"\" was registered ", "Registration message", JOptionPane.PLAIN_MESSAGE);
frame.dispose();
}
}
public boolean isTheSameUser () throws SQLException{
ArrayList<User> list = new ArrayList<User>();
boolean result = true;
list = (ArrayList<User>)userDa0.getAll();
for (User user: list){
if (user.getNickName().equals(nickNameField.getText())){
JOptionPane.showMessageDialog(null, "Nickname is already exist", "Registration message", JOptionPane.PLAIN_MESSAGE);
result = false;
}
}
return result;
}
public boolean isUserDataCorrect (){
if (lastNameField.getText().equals("") ||
firstNameField.getText().equals("") ||
nickNameField.getText().equals("") ||
passwordField.getText().equals("") ||
confPasswordField.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Please fill all fields", "Registration message", JOptionPane.PLAIN_MESSAGE);
return false;
}
else return true;
}
public String getSex (){
boolean man = manCheckBox.isSelected();
boolean woman = womanCheckBox.isSelected();
String sex = "";
if (man) sex= "man";
if (woman) sex= "woman";
return sex;
}
public boolean isSex (){
boolean man = manCheckBox.isSelected();
boolean woman = womanCheckBox.isSelected();
boolean result = true;
if (man && woman) {
JOptionPane.showMessageDialog(null, "Please choose you sex", "Registration message", JOptionPane.PLAIN_MESSAGE);
result = false;
}
if (!man && !woman) {
JOptionPane.showMessageDialog(null, "Please choose you sex", "Registration message", JOptionPane.PLAIN_MESSAGE);
result=false;
}
return result;
}
public boolean isPasswordsEquals (){
if (passwordField.getText().equals(confPasswordField.getText()) && passwordField.getText().length()>4) return true;
else {
passwordField.setText("");
confPasswordField.setText("");
JOptionPane.showMessageDialog(null,"Passwords are not equal or too short","Registration message",JOptionPane.PLAIN_MESSAGE);
return false;
}
}
}
<file_sep>package betterArchitecture.implementation;
import betterArchitecture.interfaces.MySqlDao;
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import betterArchitecture.valueObjects.Theme;
import betterArchitecture.valueObjects.User;
/**
* Created by <NAME> on 08.03.2016.
*/
public class UserDaoImpl extends MySqlDao<User>{
public UserDaoImpl(Connection connection){
super(connection);
}
@Override
protected String getSelectQuery() {
return "SELECT * FROM users";
}
@Override
protected String getInsertQuery() {
return "INSERT INTO users (first_name, last_name, nickname, password, sex, registration_date) VALUES (?,?,?,?,?,?)";
}
@Override
protected String getUpdateQuery() {
return "UPDATE users SET first_name=?, last_name=?,nickname=?,password=?,sex=?,registration_date=? WHERE id=?";
}
@Override
protected String getDeleteQuery() {
return "DELETE FROM users WHERE id=?";
}
public ArrayList<Theme> getAllThemes (User user) throws SQLException{
String sql = "SELECT * FROM themes WHERE user_id=?";
PreparedStatement stm = getConnection().prepareStatement(sql);
stm.setInt(1, user.getId());
ResultSet rs = stm.executeQuery();
ArrayList<Theme> result = new ArrayList<Theme>();
while (rs.next()){
result.add(new Theme(rs.getString("theme_name"),rs.getString("create_date"),rs.getInt("user_id")));
}
return result;
}
public User getByNickName(String name) throws SQLException{
String sql = "SELECT * FROM users WHERE nickname=?";
PreparedStatement stm = getConnection().prepareStatement(sql);
stm.setString(1, name);
ResultSet rs = stm.executeQuery();
List<User> answ = parseResultSet(rs);
if(answ.isEmpty()) {
System.out.println("user with this name does not exist");
return null;
}
else
return answ.get(0);
}
@Override
protected List<User> parseResultSet(ResultSet rs) throws SQLException {
List<User> list = new ArrayList<User>();
while(rs.next()){
User p = new User();
p.setId(rs.getInt("id"));
p.setFirstName(rs.getString("first_name"));
p.setLastName(rs.getString("last_name"));
p.setNickName(rs.getString("nickname"));
p.setPassword(rs.getString("<PASSWORD>"));
p.setSex(rs.getString("sex"));
p.setRegistrationDate(rs.getString("registration_date"));
list.add(p);
}
return list;
}
@Override
protected void prepareInsertStatement(PreparedStatement stm, User object) throws SQLException {
stm.setString(1, object.getFirstName());
stm.setString(2, object.getLastName());
stm.setString(3, object.getNickName());
stm.setString(4, object.getPassword());
stm.setString(5, object.getSex());
stm.setString(6, object.getRegistrationDate());
}
@Override
protected void prepareUpdateStatement(PreparedStatement stm, User object) throws SQLException {
prepareInsertStatement(stm, object);
stm.setInt(7, object.getId());
}
@Override
protected void prepareDeleteStatement(PreparedStatement stm, User object) throws SQLException {
stm.setInt(1, object.getId());
}
}
<file_sep>package betterArchitecture.test;
import betterArchitecture.implementation.MySQLDaoFactory;
import betterArchitecture.implementation.NoteDaoImpl;
import betterArchitecture.implementation.ThemeDaoImpl;
import betterArchitecture.implementation.UserDaoImpl;
import betterArchitecture.interfaces.MySqlDao;
import betterArchitecture.valueObjects.Note;
import betterArchitecture.valueObjects.Theme;
import betterArchitecture.valueObjects.User;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created by <NAME> on 08.03.2016.
*/
public class TestMethods{
public static void main(String[] args) throws SQLException{
// MySQLDaoFactory testFactory = new MySQLDaoFactory();
//
// NoteDaoImpl test = new NoteDaoImpl(testFactory.getConnection());
//
// Note testNote = new Note("here must be some text", "31/1/2013", 4);
// testNote.setId(3);
// test.delete(testNote);
}
}
<file_sep>package betterArchitecture.implementation;
import betterArchitecture.interfaces.MySqlDao;
import betterArchitecture.valueObjects.Note;
import betterArchitecture.valueObjects.Theme;
import betterArchitecture.valueObjects.User;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by <NAME> on 08.03.2016.
*/
public class ThemeDaoImpl extends MySqlDao<Theme> {
public ThemeDaoImpl (Connection connection){
super(connection);
}
@Override
protected String getSelectQuery() {
return "SELECT * FROM themes";
}
@Override
protected String getInsertQuery() {
return "INSERT INTO themes (theme_name, create_date, user_id) VALUES (?,?,?)";
}
@Override
protected String getUpdateQuery() {
return "UPDATE themes SET theme_name=?,create_date=?,user_id=? WHERE id=?";
}
@Override
protected String getDeleteQuery() {
return "DELETE FROM themes WHERE id=?";
}
public ArrayList<Note> getAllNotes (Theme theme) throws SQLException{
String sql = "SELECT * FROM notes WHERE theme_id=?";
PreparedStatement stm = getConnection().prepareStatement(sql);
stm.setInt(1, theme.getId());
ResultSet rs = stm.executeQuery();
ArrayList<Note> result = new ArrayList<Note>();
while (rs.next()){
Note note = new Note();
note.setId(rs.getInt("id"));
note.setText(rs.getString("text"));
note.setCreateDate(rs.getString("create_date"));
note.setThemeId(rs.getInt("theme_id"));
result.add( note );
}
return result;
}
public Theme getByNickName(String name) throws SQLException{
String sql = "SELECT * FROM themes WHERE theme_name=?";
PreparedStatement stm = getConnection().prepareStatement(sql);
stm.setString(1, name);
ResultSet rs = stm.executeQuery();
List<Theme> answ = parseResultSet(rs);
if(answ.isEmpty()) {
System.out.println("theme with this name does not exist");
return null;
}
else
return answ.get(0);
}
@Override
protected List<Theme> parseResultSet(ResultSet rs) throws SQLException {
List<Theme> list = new ArrayList<Theme>();
while(rs.next()){
Theme p = new Theme();
p.setId(rs.getInt("id"));
p.setThemeName(rs.getString("theme_name"));
p.setCreateDate(rs.getString("create_date"));
p.setUserId(rs.getInt("user_id"));
list.add(p);
}
return list;
}
@Override
protected void prepareInsertStatement(PreparedStatement stm, Theme object) throws SQLException {
stm.setString(1, object.getThemeName());
stm.setString(2, object.getCreateDate());
stm.setInt(3, object.getUserId());
}
@Override
protected void prepareUpdateStatement(PreparedStatement stm, Theme object) throws SQLException {
prepareInsertStatement(stm, object);
stm.setInt(4, object.getId());
}
@Override
protected void prepareDeleteStatement(PreparedStatement stm, Theme object) throws SQLException {
stm.setInt(1, object.getId());
}
}
<file_sep>package betterArchitecture.interfaces;
import betterArchitecture.valueObjects.Item;
import betterArchitecture.valueObjects.User;
import java.sql.SQLException;
import java.util.List;
/**
* Created by <NAME> on 08.03.2016.
*/
public interface GenericDAO <T extends Item> {
public T create (T object) throws SQLException;
public T read (int key) throws SQLException;
public void update(T object) throws SQLException;
public void delete(T object) throws SQLException;
public List<T> getAll() throws SQLException;
//public <E extends Item> List<T> relation(E object) throws SQLException, UnsupportedOperationException;
}
<file_sep>package betterArchitecture.GUI;
import betterArchitecture.implementation.MySQLDaoFactory;
import betterArchitecture.implementation.NoteDaoImpl;
import betterArchitecture.implementation.ThemeDaoImpl;
import betterArchitecture.implementation.UserDaoImpl;
import betterArchitecture.valueObjects.Note;
import betterArchitecture.valueObjects.Theme;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created by <NAME> on 13.03.2016.
*/
public class Notes {
private JPanel panel1;
private JButton addNoteButton;
private JList notesList;
private JLabel yourNotes;
private JButton deleteNoteButton;
private JButton editNoteButton;
private DefaultListModel listModel;
private JFrame frame;
protected Theme currentTheme;
private MySQLDaoFactory factory = new MySQLDaoFactory();
// private UserDaoImpl userDa0 = new UserDaoImpl(factory.getConnection());
private ThemeDaoImpl themeDao= new ThemeDaoImpl(factory.getConnection());
private NoteDaoImpl noteDao= new NoteDaoImpl(factory.getConnection());
public Notes(final Theme currentTheme, String userNickname) throws SQLException{
this.currentTheme = currentTheme;
String title = "User ["+userNickname+"] theme ["+currentTheme.getThemeName() +"]";
frame = new JFrame(title);
frame.setContentPane(panel1);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(500,400);
frame.setLocation(500,200);
frame.setVisible(true);
//notesList.setw
notesList.setCellRenderer(new MyCellRenderer(300));
listModel = new DefaultListModel();
notesList.setModel(listModel);
fillNotesList();
editNoteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (notesList.getSelectedValue() != null){
try {
NoteEdit ne = new NoteEdit( (Note) notesList.getSelectedValue(), listModel,currentTheme);
updateList();
} catch (SQLException e1) {
e1.printStackTrace();
}
}else JOptionPane.showMessageDialog(frame,"At first choose note which you want to edit");
}
});
addNoteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
NewNote nn = new NewNote(currentTheme,listModel);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
deleteNoteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (notesList.getSelectedValue() != null){
try {
Note note = (Note) notesList.getSelectedValue();
noteDao.delete(note);
String s = note.toString();
if (s.length() > 25) {
String message = s.substring(0, 20);
JOptionPane.showMessageDialog(null, "Note " + message + "... has been deleted", "Message", JOptionPane.PLAIN_MESSAGE);
} else
JOptionPane.showMessageDialog(null, "Note has been deleted", "Message", JOptionPane.PLAIN_MESSAGE);
updateList();
} catch (SQLException e1) {
e1.printStackTrace();
}
}else JOptionPane.showMessageDialog(frame, "Choose note that you want to delete");
}
});
}
public void updateList () throws SQLException{
ArrayList<Note> list = new ArrayList<Note>();
list = themeDao.getAllNotes(currentTheme);
listModel.removeAllElements();
for (Note note : list) {
listModel.addElement(note);
}
}
public void fillNotesList() throws SQLException {
ArrayList<Note> list = new ArrayList<Note>();
list = themeDao.getAllNotes(currentTheme);
for (Note note: list){
if ( ! list.isEmpty()){
listModel.addElement(note);
}
}
// if (list.isEmpty()) listModel.addElement("empty");
}
}
class MyCellRenderer extends DefaultListCellRenderer {
public static final String HTML_1 = "<html><body style='width: ";
public static final String HTML_2 = "px'>";
public static final String HTML_3 = "</html>";
private int width;
TitledBorder border;
public MyCellRenderer(int width) {
this.width = width;
this.border = new TitledBorder(LineBorder.createGrayLineBorder(),"Note");
}
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
String text = HTML_1 + String.valueOf(width) + HTML_2 + value.toString()
+ HTML_3;
Component component = super.getListCellRendererComponent(list, text, index, isSelected,
cellHasFocus);
((JComponent)component).setBorder(border);
return component;
}
}
<file_sep>package betterArchitecture.GUI;
import java.sql.SQLException;
/**
* Created by <NAME> on 09.03.2016.
*/
public class GuiTest {
public static void main(String[] args)throws SQLException{
HelloWindow test = new HelloWindow();
//String [] list = {"pika","chika","gueue","yamal","zud0","abruzzi"};
}
}
<file_sep>package betterArchitecture.GUI;
import betterArchitecture.implementation.*;
import betterArchitecture.valueObjects.Note;
import betterArchitecture.valueObjects.Theme;
import betterArchitecture.valueObjects.User;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
/**
* Created by <NAME> on 10.03.2016.
*/
public class UserWindow {
private JPanel panel1;
private JTextArea lastNote;
private JButton createThemeButton;
private JButton deleteThemeButton;
private JButton renameThemeButton;
private JButton readNotesButton;
private JPanel panel2;
private JPanel listPanel;
private JFrame frame;
private User currentUser;
private JList themesList;
private JLabel yourThemes;
private JPanel buttonsPanel;
private DefaultListModel listModel;
//private NewTheme newTheme;
private MySQLDaoFactory factory = new MySQLDaoFactory();
private UserDaoImpl userDa0 = new UserDaoImpl(factory.getConnection());
private ThemeDaoImpl themeDao = new ThemeDaoImpl(factory.getConnection());
private NoteDaoImpl noteDao = new NoteDaoImpl(factory.getConnection());
public static void main(String[] args) throws SQLException {
UserWindow userWindow = new UserWindow(new User("Olena", "Kirba", "yamik", "jhgfds", "woman", "5/6/2000"));
}
public UserWindow(final User currentUser) throws SQLException {
this.currentUser = currentUser;
//currentUser.setId(4);
frame = new JFrame("Memento [user: " + currentUser.getNickName() + "]");
frame.setContentPane(panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(645, 325);
frame.setVisible(true);
//lastNote.setWrapStyleWord(true);
listModel = new DefaultListModel();
themesList.setModel(listModel);
fillThemesList();
createThemeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String newThemeName = JOptionPane.showInputDialog(frame,"Enter name of new theme");
try {
if ( !newThemeName.equals("")){
if ( ! isThemeExist(newThemeName) && !newThemeName.equals("")){
DateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
Theme newTheme = new Theme(newThemeName,dateFormat.format(cal.getTime()),currentUser.getId());
themeDao.create(newTheme);
listModel.addElement(newTheme.getThemeName());
JOptionPane.showMessageDialog(null, "Theme " + newThemeName + " has been created", "Message", JOptionPane.PLAIN_MESSAGE);
updateList();
}
}else JOptionPane.showMessageDialog(frame,"New name is empty");
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
readNotesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (themesList.getSelectedValue() != null){
Notes nn = new Notes(themeDao.getByNickName((String) themesList.getSelectedValue()), currentUser.getNickName());
updateList();
}else JOptionPane.showMessageDialog(frame, "At first choose theme");
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
deleteThemeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selected = (String) themesList.getSelectedValue();
try {
if (selected != null) {
ArrayList<Note> noteToDelete= themeDao.getAllNotes(themeDao.getByNickName(selected));
themeDao.delete(themeDao.getByNickName(selected));
{
for (Note note : noteToDelete) {
noteDao.delete(note);
}
}
updateList();
} else JOptionPane.showMessageDialog(frame, "Choose theme which will be deleted");
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
renameThemeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String newName = JOptionPane.showInputDialog("Enter new name:",themesList.getSelectedValue());
String name = (String) themesList.getSelectedValue();
if (name != null) {
if (!newName.equals("")) {
try {
Theme themeToUpdate = new Theme();
themeToUpdate.setId(themeDao.getByNickName(name).getId());
themeToUpdate.setThemeName(newName);
themeToUpdate.setCreateDate(themeDao.getByNickName(name).getCreateDate());
themeToUpdate.setUserId(themeDao.getByNickName(name).getUserId());
themeDao.update(themeToUpdate);
updateList();
} catch (SQLException e1) {
e1.printStackTrace();
}
} else
JOptionPane.showMessageDialog(null, "New name is empty", "Warning", JOptionPane.PLAIN_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "At first choose theme", "Warning", JOptionPane.PLAIN_MESSAGE);
}
}
});
}
public void updateList() throws SQLException {
ArrayList<Theme> list = new ArrayList<Theme>();
list = userDa0.getAllThemes(currentUser);
listModel.removeAllElements();
for (Theme theme : list) {
listModel.addElement(theme.getThemeName());
}
}
public void fillThemesList() throws SQLException {
ArrayList<Theme> list = new ArrayList<Theme>();
list = userDa0.getAllThemes(currentUser);
for (Theme theme : list) {
if (!list.isEmpty()) {
listModel.addElement(theme.getThemeName());
//System.out.println(theme.getThemeName());
}
}
// if (list.isEmpty()) listModel.addElement("empty");
}
public boolean isThemeExist (String name) throws SQLException{
ArrayList<Theme>list = userDa0.getAllThemes(currentUser);
boolean result = false;
for (Theme theme: list){
if (name.equals(theme.getThemeName())){
result = true;
JOptionPane.showMessageDialog(null, "Theme " +name+" is already exist", "Warning", JOptionPane.PLAIN_MESSAGE);
}
}
return result;
}
}
| 221a1ae0ac40f53268dd5a0ce831e1fa413185f7 | [
"Java"
] | 8 | Java | RomanBortnyk/Memento | 05a7cec548b424173899d89edb6a42f1c251c14b | b95efd29e0a8ffd0aa6cf676e9490818332d5284 |
refs/heads/master | <file_sep>function staircase(N,jumps){
var root= BuildNode({},0)
var uniques = []
var stack = [];
stack.push(root); // stack is now [2]
while(stack.length>0){
var cnode = stack.pop();
for (var j= 0; j<jumps.length;j++){
var node = BuildNode(cnode,jumps[j])
if (node.sum == N){
uniques.push(node);
//console.log('found unique, curently: ' +uniques.length);
} else if (node.sum < N){
stack.push(node);
} else if(node.sum >N){
//invalid do nothing
}
}
}
console.log(uniques.length);
if (uniques.length<=500){
for(var i=0; i<uniques.length;i++){
//console.log(uniques[i].jumps.toString())
}
}
return uniques.length;
}
function BuildNode(parent, mod){
//f parent = null
node = {sum:parent.sum+mod||0,jumps:[]};
if (typeof parent.sum !== 'undefined'){
node.jumps = parent.jumps.slice(0)
node.jumps.push(mod)
}
return node
}
function num_ways(n){
if (n==0 || n==1){
return 1;
}
else {
return num_ways(n-1)+ num_ways(n-2)
}
}
function num_ways_bottom_up(n){
if(n==0||n==1){
return 1;
}
var nums =[]
nums[0] ==1;
nums[1] ==1;
for(var i=2;i<=n;i++){
nums[i] = nums[i-1] + nums[i-2]
}
return nums[n]
}
function num_ways_x(n,s){
if (n==0){
return 1;
}
var total = 0;
for(var i=0;i<s.length;i++){
var el = s[i];
if(n-el >=0){
total+= num_ways_x(n-el,s)
}
}
return total;
}
function num_ways_bottom_up_x(n,s){
if (n==0){
return 1;
}
debugger
var nums =[]
nums[0] ==1;
for(var i=1;i<=n;i++){
var total = 0;
for(var j=0;j<s.length;j++){
var el = s[j];
if (i-el >=0){
total += nums[i-el]
}
}
nums[i]=total;
}
return nums[n]
}
function testing(min,max,steps){
for (var t=min;t<=max;t++){
console.log('t value is ' + t + ', steps value is: ' + JSON.stringify(steps));
console.log(staircase(t,steps));
console.log(num_ways_bottom_up_x(t,steps));
if(num_ways_bottom_up_x(t,steps)==staircase(t,steps)){
console.log('true');
}
}
}
<file_sep># DailyCodingProblem
A repo to collect and work on problems from DailyCodingProblem.com and other sources
| d81f769b300b3b51e72fcfd4fed29965ec90073a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Darrick255/DailyCodingProblem | 5408a83288589bd7135175e2123d087f4beed102 | 2a009ac83fd25242824002b714fb0202a4e90401 |
refs/heads/master | <repo_name>ivarvong/newsassign<file_sep>/newsassign/admin.py
from django.contrib import admin
from newsassign.models import Story
from newsassign.models import Assignment
class AssignmentInline(admin.StackedInline):
model = Assignment
extra = 1
class StoryAdmin(admin.ModelAdmin):
fields = ['slug', 'description', 'created_date']
inlines = [AssignmentInline]
list_display = ['slug', 'description', 'created_date', 'was_created_recently']
#list_filter = ['created_date']
search_fields = ['slug', 'description']
#date_hierarchy = 'created_date'
admin.site.register(Story, StoryAdmin)
class AssignmentAdmin(admin.ModelAdmin):
list_display = ['story', 'slug', 'description', 'was_created_recently']
admin.site.register(Assignment, AssignmentAdmin)
<file_sep>/README.md
newsassign
==========<file_sep>/newsassign/models.py
from django.db import models
from django.contrib.auth.models import User
class Story(models.Model):
slug = models.CharField(max_length=200)
description = models.CharField(max_length=200)
created_date = models.DateTimeField('date created')
def __unicode__(self):
return self.slug
def was_created_recently(self):
return self.created_date >= timezone.now() - datetime.timedelta(days=1)
class Assignment(models.Model):
story = models.ForeignKey(Story)
slug = models.CharField(max_length=200)
description = models.TextField()
desk = models.CharField(max_length=20)
destination = models.CharField(max_length=20)
who_cares = models.CharField(max_length=200)
editor = models.ForeignKey(User, related_name="%(class)s_editor_ownership")
reporter = models.ForeignKey(User, related_name="%(class)s_reporter_ownership")
created_date = models.DateTimeField('date created')
deadline_date = models.DateTimeField('deadline')
publish_date = models.DateTimeField('date published')
def __unicode__(self):
return self.slug
def was_created_recently(self):
return self.created_date >= timezone.now() - datetime.timedelta(days=1)
| 6a84a53cf3004401e6944858ef9e9659188a6b41 | [
"Markdown",
"Python"
] | 3 | Python | ivarvong/newsassign | 73ed3826a8f6a0ce7b3f71d386c7e18d9e2faf38 | 4da09bb28801d78f0fe12e3dda4a265c3fda4002 |
refs/heads/main | <file_sep>import sqlite3
import argparse
import sys
# Проверка для выхода из программы
def check():
print("Еще хотите что-то сделать?\n1.Да\n2.Нет")
if (input("--> ") == "1"):
print("Перечень комманд:\n1.Добавить\n2.Изменить существующий контакт\n3.Удалить\n4.Что-то найти\n5.Увидеть полную базу\n000. Выйти из программы")
return False
else:
return True
# Вывод всей базы
def fullBase(c):
for row in c.execute('SELECT * FROM book '):
print(row)
def advancedFullBase(c):
inputValue = input(
"По какому виду сортировки вам надо показать базу?\n1.По ID(стандартная)\n2.По Имени\n3.По адресу\n4.По номеру\n5.По электронной почте\n--> ")
if int(inputValue) == 1:
for row in c.execute('SELECT * FROM book '):
print(row)
elif int(inputValue) == 2:
for row in c.execute('SELECT * FROM book ORDER BY name'):
print(row)
elif int(inputValue) == 3:
for row in c.execute('SELECT * FROM book ORDER BY adress'):
print(row)
elif int(inputValue) == 4:
for row in c.execute('SELECT * FROM book ORDER BY number'):
print(row)
elif int(inputValue) == 5:
for row in c.execute('SELECT * FROM book ORDER BY email'):
print(row)
else:
print("Вы ввели неправльную цифру, из за этого вы ничего не увидели")
# Парсер
parser = argparse.ArgumentParser()
parser.add_argument('-log', '--logs', action="store_true",
help="Вывод данных для разработчика")
parser.add_argument('-add', '--adds', action="store_true",
help="Сразу проведение функции добавления")
parser.add_argument('-delete', '--deletes', action="store_true",
help="Сразу проведение функции удаления")
parser.add_argument('-change', '--changes', action="store_true",
help="Сразу проведение функции изменения")
parser.add_argument('-find', '--finds', action="store_true",
help="Сразу проведение функции нахождения")
parser.add_argument('-watch', '--watchs', action="store_true",
help="Сразу проведение функции просмотра всей базы")
parser.add_argument('-clear', '--clears', action="store_true",
help="Очистка всей базы")
args = parser.parse_args()
# Подключение базы
conn = sqlite3.connect('book.sqlite')
c = conn.cursor()
# Попытка создания таблицы
try:
c.execute('''CREATE TABLE book(
id INTEGER PRIMARY KEY,
name text,
adress text,
number text,
email text)''')
if args.logs:
print("#Автоматическое создание таблицы призошло успешно")
except(sqlite3.OperationalError):
if args.logs:
print("#Автоматическое создание таблицы призошло безуспешно(файл уже создан)")
# Переменная помогающая для выхода из программы
exitFromProgramm = False
# Подсчет последнего id в таблице
kolvoID = 0
for i in c.execute('SELECT * FROM book '):
kolvoID += 1
if args.logs:
print("# {} найденное количество id".format(kolvoID))
# Очистка всей базы
if args.clears:
c.execute("DELETE FROM book ")
print("Были удалены все данные с таблицы")
sys.exit()
# Проверка был ли парсинг и надо ли исчезать строке команд
if args.adds or args.changes or args.deletes or args.finds or args.watchs:
pass
else:
print("Здравствуйте,что вы хотите сделать с базой данных?\n1.Добавить\n2.Изменить существующий контакт\n3.Удалить\n4.Что-то найти\n5.Увидеть полную базу\n000. Выйти из программы")
# Сам процесс программы
while exitFromProgramm == False:
if args.adds:
vibor = "1"
elif args.changes:
vibor = "2"
elif args.deletes:
vibor = "3"
elif args.finds:
vibor = "4"
elif args.watchs:
vibor = "5"
else:
vibor = input("--> ")
# Добавление
if(vibor == "1"):
kolvoID += 1
name = input("Введите имя: ")
adress = input("Введите адрес: ")
number = input("Введите номер телефона: ")
email = input("Введите адрес электронной почты: ")
table = [(kolvoID, name, adress, number, email)]
if name == "" or adress == "" or number == "" or email == "":
pass
else:
c.executemany(
''' INSERT OR REPLACE INTO book VALUES (?,?,?,?,?)''', table)
if args.logs:
for i in c.execute('SELECT * FROM book WHERE id = ? ', (kolvoID,)):
print("#Была введена строка данных:", i)
conn.commit()
if args.adds:
sys.exit()
exitFromProgramm = check()
# обновления контактной информации
elif(vibor == "2"):
if(input("Нужно ли вам посмотреть полную Базу? \n 1. Да \n 0. Нет\n-->") == "1"):
fullBase(c)
print("Выберете id контакта, которого вы хотите изменить")
idChoose = input("--> ")
name = input("Введите имя(нажимайте Enter если не хотите менять): ")
adress = input(
"Введите адрес(нажимайте Enter если не хотите менять): ")
number = input(
"Введите номер телефона(нажимайте Enter если не хотите менять): ")
email = input(
"Введите адрес электронной почты(нажимайте Enter если не хотите менять): ")
c.execute('SELECT * FROM book WHERE id = ? ', (idChoose))
bufferbase = c.fetchone()
bufferbase = list(bufferbase)
print(bufferbase)
if name != "":
bufferbase[1] = name
if adress != "":
bufferbase[2] = adress
if number != "":
bufferbase[3] = number
if email != "":
bufferbase[4] = email
if args.logs:
for i in c.execute('SELECT * FROM book WHERE id = ? ', (idChoose)):
print("#Была изменена эта строка: ", i)
print(bufferbase)
bufferbase = [tuple(bufferbase)]
c.executemany(
'''INSERT OR REPLACE INTO book VALUES (?,?,?,?,?)''', bufferbase)
conn.commit()
if args.changes:
sys.exit()
exitFromProgramm = check()
# Удаление
elif (vibor == "3"):
if(input("Нужно ли вам посмотреть полную Базу? \n 1. Да \n 0. Нет\n-->") == "1"):
fullBase(c)
print("Выберете id контакта, которого вы хотите удалить")
idChoose = input("-->")
if args.logs:
for i in c.execute('SELECT * FROM book WHERE id = ? ', (idChoose)):
print("#Была удалена эта строка: ", i)
c.execute('DELETE FROM book WHERE id = ? ', (idChoose))
c.execute('UPDATE book SET id = (id-1) WHERE id > ? ', (idChoose))
conn.commit()
kolvoID -= 1
if args.deletes:
sys.exit()
exitFromProgramm = check()
# Нахождение
elif (vibor == "4"):
print("Какую информацию вы можете дать? Если вы не знаете что написать в одном из пунктов, то просто жмите ENTER")
name = input("Введите имя: ")
adress = input("Введите адрес: ")
number = input("Введите номер телефона: ")
email = input("Введите адрес электронной почты: ")
findBase = []
for row in c.execute('SELECT * FROM book'):
findBase.append(list(row))
index = 0
if name != "":
for i in range(len(findBase)):
try:
bufferBase = findBase[index]
if bufferBase[1] != name:
findBase.pop(index)
index -= 1
index += 1
except IndexError:
break
index = 0
if adress != "":
for i in range(len(findBase)):
try:
bufferBase = findBase[index]
if bufferBase[2] != adress:
findBase.pop(index)
index -= 1
index += 1
except IndexError:
break
index = 0
if number != "":
for i in range(len(findBase)):
try:
bufferBase = findBase[index]
if bufferBase[3] != number:
findBase.pop(index)
index -= 1
index += 1
except IndexError:
break
index = 0
if email != "":
for i in range(len(findBase)):
try:
bufferBase = findBase[index]
if bufferBase[4] != email:
findBase.pop(index)
index -= 1
index += 1
except IndexError:
break
index = 0
print("Вот варианты:")
for x in findBase:
print(x)
if args.finds:
sys.exit()
exitFromProgramm = check()
# Полная база
elif (vibor == "5"):
advancedFullBase(c)
if args.watchs:
sys.exit()
exitFromProgramm = check()
# Выход + неправильный ввод
elif (vibor == "000"):
print("Завершение программы. Удачи!")
exitFromProgramm = True
else:
print("Вы ввели неправильную команду")
conn.close()
<file_sep>import time
#Первое задание
print("Первое задание:")
print("Silence is golden")
time.sleep(1)
#Второе задание
print("Второе задание:")
print("Введите два числа:")
a= int(input())
b=int(input())
print(a, "+", b, "=", a+b)
print(a, "*", b, "=", a*b)
time.sleep(1)
#Третее задание
print("Третее задание:")
print("Введите три числа:")
c= int(input())
d=int(input())
f=int(input())
c*=2
d-=3
f*=f
print(c, "+", d, "+", f, "=", c+d+f)
time.sleep(1)
#Четвертое задание
print("Четвертое задание:")
print('''
AAAAAAAA
AAAAAAAA
AAAAAAAA
AAAAAAAA
AAAAAAAA
''')
time.sleep(5)
<file_sep>str=input("Введите строку: ")
a=0
for i in str:
a+=1
print("Длина строки: ",a)<file_sep>#а условие
a =10.0
for i in range(10):
print(i+1,"день ",round(a,2),"км")
a=a+a/10
print("-------------")
#б условие
a=10.0
b=0.0
for i in range(7):
b+=a
a+=a/10
print("Суммарный путь за первые 7 дней тренировок: ",b)
print("-------------")
#в условие
a=10.0
b=0.0
n=int(input("Введите за какое кол-во дней вы хотите узнать суммарный путь - "))
for i in range(n):
b+=a
a+=a/10
print("Суммарный путь за n дней тренировок: ",round(b,2))
print("-------------")
#г условие
a=10.0
n=0
while a<=80:
n+=1
a+=a/10
print("На",n,"день он должен прекратить увеличивать пробег ")
<file_sep>import random
class massive:
firstmassive=[]
secondmassive=[]
thirdmassive=[]
def __init__(self,a,b):
self.firstmassive.extend(a)
self.secondmassive.extend(b)
for i in range(len(self.firstmassive)):
self.thirdmassive.append(self.secondmassive[i]/sum(self.secondmassive))
def returning(self):
return self.firstmassive,self.secondmassive,self.thirdmassive
def generate(self):
randomvalue=random.uniform(0,1)
count=0.0
a=0
for i in range(len(self.firstmassive)):
if self.thirdmassive[i]+count>=randomvalue and randomvalue>=count:
a=self.firstmassive[i]
break
else:
count+=self.thirdmassive[i]
return a
firstmassive=[1,2,3]
print(firstmassive)
ves=[1,2,10]
print(ves)
generatormassive=massive(firstmassive,ves)
print(generatormassive.returning())
print(generatormassive.generate())
<file_sep>a=int(input("Ввеите число: "))
b=0
for i in range(1,a+1):
if a%i==0:
b+=1
if b==2:
print("Число простое")
else:
print("Число непростое")<file_sep>a=25
for i in range(11):
print(a, a+0.5, a-0.2)
a+=1
<file_sep>class MyQueue:
stack1=[]
stack2=[]
def __init__(self):
self.MyQueue=[self.stack1,self.stack2]
def pushInStackOne(self,x):
self.stack1.append(x)
return self.stack1[-1]
def pushInStackTwo(self,x):
self.stack2.append(x)
return self.stack2[-1]
def popInStackOne(self):
try:
return self.stack1.pop()
except IndexError:
return "Stack One is empty."
def popInStackTwo(self):
try:
return self.stack2.pop()
except IndexError:
return "Stack Two is empty."
def popQueue(self):
try:
return self.stack1.pop(0)
except IndexError:
try:
return self.stack2.pop(0)
except IndexError:
return "Queue is empty."
def count(self):
return len(self.MyQueue)
someQueue=MyQueue()
for i in range(20):
if (i<10):
print(someQueue.pushInStackOne(i),end=",")
else:
print(someQueue.pushInStackTwo(i),end=";")
print()
for i in range(20):
print(someQueue.popQueue(),end=".")
<file_sep>#первое задание
print("Первое задание: ")
print("Введите число: ")
a=float(input())
if a < 10 and a > -10 :
a+=5;
else:
a-=10;
print("Ваше изменённое число: ", a)
#Второе задание
print("Второе задание: ")
print("Введите номер месяца: ")
b=int(input())
if b==1:
print("Январь")
elif b==2:
print("Февраль")
elif b==3:
print("Март")
elif b==4:
print("Апрель")
elif b==5:
print("Май")
elif b==6:
print("Июнь")
elif b==7:
print("Июль")
elif b==8:
print("Август")
elif b==9:
print("Сентябрь")
elif b==10:
print("Октябрь")
elif b==11:
print("Ноябрь")
elif b==12:
print("Декабрь")
elif b<1:
print("В прошлое хочешь вернуться?")
else:
print("Мы не на марсе чел,у нас таких месяцев нет")
#ТРЕТЬЕ ЗАДАНИЕ
print("Третье задание")
print("Введите изначальное направление робота: '11'- север, '12' - запад, '13' - юг,'14' - восток ")
c=int(input())
print("Теперь введите одну из цифровых комманд: '0' - продолжить движение , '1' - поворот налево, '-1' - поворот направо ")
d=int(input())
if d == 0:
if c == 11:
print("Робот продолжает идти на север")
elif c == 12:
print("Робот продолжает идти на запад")
elif c == 13:
print("Робот продолжает идти на юг")
elif c == 14:
print("Робот продолжает идти на восток")
else:
print("Не знает куда идти")
elif d == 1:
if c == 11:
c+=1
print("Робот повернул на запад")
elif c == 12:
c+=1
print("Робот повернул на юг")
elif c == 13:
c+=1
print("Робот повернул на восток")
elif c == 14:
c=11
print("Робот повернул на север")
else:
print("Не знает куда идти")
elif d == -1:
if c == 11:
c=14
print("Робот повернул на восток")
elif c == 14:
c-=1
print("Робот повернул на юг")
elif c == 13:
c-=1
print("Робот повернул на запад")
elif c == 12:
c-=1
print("Робот повернул на север")
else:
print("Не знает куда идти")
<file_sep>import random
#---------------------------------------------------------------------------
someList = [random.randint(0, 10) for i in range(random.randint(7, 15))]
max = 0
print(someList)
for elem in range(len(someList) - 2):
if(someList[elem]+someList[elem+1]+someList[elem+2] > max):
max = someList[elem]+someList[elem+1]+someList[elem+2]
for elem in range(len(someList) - 2):
if(someList[elem]+someList[elem+1]+someList[elem+2] == max):
print("Три последовательных элемента в массиве, сумма которых максимальна: ", someList[elem],
someList[elem+1], someList[elem+2])
break
#---------------------------------------------------------------------------
countMax=0
for elem in someList:
if someList.count(elem) > countMax:
countMax=someList.count(elem)
for elem in someList:
if someList.count(elem)==countMax:
print("Самое часто встречающийся элемент: ", elem)
break
#---------------------------------------------------------------------------
triMax=0
for elem in range(len(someList)):
if (elem+1)%2!=0:
if someList[elem]%3==0 and someList[elem]>triMax:
triMax=someList[elem]
print("Среди элементов с нечетными номерами,наибольший элемент массива, который делится на 3:", triMax)
<file_sep>a = int(input())
for i in range(a):
print('0' * 5)
<file_sep>from statistics import mean
import random
from time import sleep
class Imitation:
Path = 0
mass = 0
ownBase = " "
customerBase = " "
# переменная показывающая хорошая погода ли в городах
weather = True
# доход компании,измеряется в усл.ед.
doxodOnAirplane=0.0
doxodOnTrain=0.0
doxodOnCar=0.0
# среднее время(все время суётся в список,потом арифметическое среднее)
averageTime = []
averageTimeonAirplane = []
averageTimeonTrain = []
averageTimeonCar = []
# потери вследствии аварии
lossAvaria = 0
lossAvariaonAirplane = 0
lossAvariaonTrain = 0
lossAvariaonCar = 0
#поездки
poezdokOnTrain=0
poezdokOnAvto=0
poezdokOnAirplane=0
def _init_(self, path, mass):
self.Path = path
self.mass = mass
# случаная генерация нашей базы,т.е. в каком она городе
randomINT = random.randint(1,3)
if(randomINT == 1):
ownBase = "Big"
elif(randomINT == 2):
ownBase = "Medium"
elif(randomINT == 3):
ownBase = "Small"
# генерация базы заказчика,т.е. в каком она городе
randomINT = random.randint(1,3)
if(randomINT == 1):
customerBase = "Big"
elif(randomINT == 2):
customerBase = "Medium"
elif(randomINT == 3):
customerBase = "Small"
# шанс на плохую погоду
randomWeather = random.randint(0, 100)
if randomWeather < 6:
self.weather = False
else:
self.weather = True
# выбор транспорта
if (self.weather == True and ownBase == "Big" and customerBase == "Big"):
print("Самым оптимальным решением стал самолет.")
self.airplane()
elif((ownBase == "Big" or ownBase == "Medium") and (customerBase == "Big" or customerBase =="Medium")):
print("Самым оптимальным решением стал поезд.")
self.train()
else:
print("Самым оптимальным решением стал автомобиль.")
self.car()
def airplane(self):
airplaneSpeed = 500
path = self.Path
# реализация пути
while path > 0:
# шанс на поломку,снижение дохода,резкий выход из функции,увеличивается потеря из-за аварий
polomka = random.randint(0, 1000)
if polomka == 55:
print("Самолет пал во время полета,деньги идут в минус")
self.doxodOnAirplane -= 3*self.mass
self.lossAvaria += 1
self.lossAvariaonAirplane += 1
return
path -= airplaneSpeed
# если все закончилось успешно
print("Ваш самолет долетел до конца и отдал груз. ")
# доход на этом транспорте
self.doxodOnAirplane+=3*self.mass
# кол-во поездок успешных
self.poezdokOnAirplane+=1
# в список добавляется время пути
self.averageTime.append(self.Path/airplaneSpeed)
self.averageTimeonAirplane.append(self.Path/airplaneSpeed)
print("Самолет долетел за ", self.Path/(airplaneSpeed), " часов")
def train(self):
path = self.Path
# кол-во магистралей было пройдено
count_magistral = 0
# реализация пути поезда
while path > 0:
trainspeed = 100
# шанс на поломку и снижение дохода в этом случаи,резкий выход из функции,увеличивается потеря из-за аварий
polomka = random.randint(0, 500)
if polomka == 1:
print("Поезд пал во время езды,деньги идут в минус")
self.doxodOnTrain -= 1.5*self.mass
self.lossAvaria += 1
self.lossAvariaonTrain += 1
return
# шанс на выход на магистраль + увеличение скорости
magistral = random.randint(0, 100)
if magistral < 10:
trainspeed += 50
count_magistral += 1
# снижается путь,якобы прошел час езды
path -= trainspeed
# если все закончилось успешно
print("Ваш Поезд доехал до конца и отдал груз. ")
# доход на этом транспорте
self.doxodOnTrain += 1.5*self.mass
self.poezdokOnTrain+=1
self.averageTime.append(self.Path/(trainspeed+count_magistral*50))
self.averageTimeonTrain.append(self.Path/(trainspeed+count_magistral*50))
print("Поезд доехал за ", self.Path /
(trainspeed+count_magistral*50), " часов")
def car(self):
path = self.Path
# кол-во магистралей было пройдено
count_magistral = 0
#время из-за поломки
timePolomka=0
# реализация пути
while path > 0:
avtospeed = 70
#шанс на поломку
polomka = random.randint(0, 500)
if polomka < 5:
print("Автомобиль поломался во время езды,для восстановления нужно время")
timePolomka+=random.randint(1,3)
# шанс на поломку или аварию,снижение дохода в этом случаи,резкий выход из функции,увеличивается потеря из-за аварий
Avaria = random.randint(0, 1000)
if Avaria < 5:
print("Автомобиль пал во время езды,деньги идут в минус")
self.doxodOnCar -= 0.5*self.mass
self.lossAvaria += 1
self.lossAvariaonCar += 1
return
# шанс на выход в магистраль
magistral = random.randint(0, 100)
if magistral < 10:
avtospeed += 30
count_magistral += 1
# снижается путь,якобы прошел час езды
path -= avtospeed
# если все закончилось успешно
print("Ваш Автомобиль доехал до конца и отдал груз. ")
# доход на этом транспорте
self.doxodOnCar += 0.5*self.mass
self.poezdokOnAvto+=1
self.averageTime.append(self.Path/(avtospeed+count_magistral*30)+timePolomka)
self.averageTimeonCar.append(self.Path/(avtospeed+count_magistral*30)+timePolomka)
print("Автомобиль доехал за ", self.Path /
(avtospeed+count_magistral*30)+timePolomka, " часов")
def printAll(self):
print("Среднее время поездок: ", mean(self.averageTime), " часов")
print("Среднее время поездок на самолёте: ", mean(self.averageTimeonAirplane), " часов")
print("Среднее время поездок на поезде: ", mean(self.averageTimeonTrain), " часов")
print("Среднее время поездок на автомобиле: ", mean(self.averageTimeonCar), " часов\n")
print("Доход на самолете(в усл.ед.):",self.doxodOnAirplane)
print("Доход на поезде(в усл.ед.):",self.doxodOnTrain)
print("Доход на автомобиле(в усл.ед.):",self.doxodOnCar)
print("Итоговый доход(в усл.ед.):", self.doxodOnAirplane + self.doxodOnTrain + self.doxodOnCar,"\n")
print("Количество аварий:", self.lossAvaria)
print("Количество аварий на самолете:", self.lossAvariaonAirplane)
print("Количество аварий на поезде:", self.lossAvariaonTrain)
print("Количество аварий на автомобиле:", self.lossAvariaonCar,"\n")
print("Поездок на самолете:",self.poezdokOnAirplane)
print("Поездок на поезде:",self.poezdokOnTrain)
print("Поездок на автомобиле:",self.poezdokOnAvto)
print("Итоговое количество удачных поездок:",self.poezdokOnAirplane+self.poezdokOnTrain+self.poezdokOnAvto,"\n")
someImitation = Imitation()
a=input("Сколько тестов провести ?\n")
for i in range(int(a)):
path = random.randint(300, 2000)
mass = random.randint(1, 10)
print("Был получен заказ: {} км, {} тонн".format(path, mass))
someImitation._init_(path, mass)
#sleep(3)
print("-"*30)
if i == int(a)-1:
someImitation.printAll()
<file_sep>a=int(input())
for i in range (1,101):
print(i,'$ -',a*i,'Руб. -',a*i/20,'Кг.')<file_sep>import random
class FIFO:
def __init__(self):
self.FIFO = []
def push(self, x):
self.FIFO.append(x)
try:
return self.FIFO[-1]
except IndexError:
return self.FIFO[0]
def delete(self):
try:
return self.FIFO.pop(0)
except IndexError:
return "Очередь пуста"
def watch(self, x):
try:
return self.FIFO[x]
except IndexError:
return "Такого элемента в очереди нет"
def count(self):
return len(self.FIFO)
someFIFO = FIFO()
for i in range(random.randint(5, 50)):
print(someFIFO.push(random.randint(0, 100)),end=" ")
print("")
for i in range(someFIFO.count()):
print(someFIFO.delete(), end=" ")
print("")
print(someFIFO.delete())
<file_sep>s = input("Введите строку в которой надо удалить группу символов: ")
while s.find("/*") != -1:
firstPlace = s.find("/*")
lastPlace = s.find("*/")
i=firstPlace
while i < lastPlace+2:
s = s[:firstPlace] + s[firstPlace+1:]
i+=1
print("Вот готовый вариант: ",s)
<file_sep>import random
def computerChoose(choose):
d = {1: "Ножницы", 2: "Бумагу", 3: "Камень"}
print("Компьютер выбрал", d[choose])
#def whoWin(man,computer):
def statistic(ManWins,ComputerWins,ManCutChoose,ManPaperChoose,ManStoneChoose):
print("Количество побед у человека:", ManWins)
print("Количество побед у компьютера:", ComputerWins)
print("Вы выбрали Ножницы ", ManCutChoose, "раза")
print("Вы выбрали Бумагу ", ManPaperChoose, "раза")
print("Вы выбрали Камень ", ManStoneChoose, "раза")
pass
kol_vo = int(input("Введите кол-во игр: "))
i = 0
ManWins = 0
ComputerWins = 0
ManCutChoose = 0
ManPaperChoose = 0
ManStoneChoose = 0
while i < kol_vo:
print("\nВведите что вы хотите поставить: \n 1.Ножницы \n 2.Бумага \n 3.Камень")
ManChoose = int(input("Ваш выбор: "))
ComputerChoose = random.randint(1, 3)
computerChoose(ComputerChoose)
if ManChoose == 1:
ManCutChoose += 1
elif ManChoose == 2:
ManPaperChoose += 1
elif ManChoose == 3:
ManStoneChoose += 1
if (ManChoose == 1 and ComputerChoose == 2)\
or (ManChoose == 2 and ComputerChoose == 3)\
or (ManChoose == 3 and ComputerChoose == 1):
print("Вы выйграли!", "\n"*2)
i += 1
ManWins+=1
elif ManChoose == ComputerChoose:
print("Ничья!", "\n"*2)
elif ManChoose > 3 or ManChoose < 1:
print("Вы что-то неправильно ввели,попробуйте еще раз")
else:
print("Увы, но вы проиграли.", "\n"*2)
ComputerWins+=1
i += 1
statistic(ManWins,ComputerWins,ManCutChoose,ManPaperChoose,ManStoneChoose)
<file_sep>s=input("input string: ")
if(len(s)%2!=0):
s=s+" "
s1=s[:int(len(s)/2)]
print("first half: ",s1)
s2=s[int(len(s)/2):]
print("second half: ",s2)
j=0
i=0
while i<int(len(s)/2):
if(i==len(s2)-1):
s1=s1+s2[int(len(s2)-1)]
break
s1=s1.replace(s1[j]+s1[j+1],s1[j]+s2[i]+s1[j+1])
j+=2
i+=1
print("shivrovka: ",s1)
#-------------------------------------------------
s3=""
s4=""
i=0
while i < len(s1):
if i%2==0:
s3=s3+s1[i]
else:
s4=s4+s1[i]
i+=1
deshifr=s3+s4
print("deshifrovka: ", deshifr)
<file_sep>import random
seriya = 1
summa_v_seriyi = 0
kolvo_1 = 0
kolvo_2 = 0
dlina = 0
all_2 = 0
all_dlina = 0
not_zero = 0
max_not_zero = 0
while seriya != 21:
print("Пошла", seriya, "серия:")
while summa_v_seriyi != 12:
random_cishlo = random.randint(0, 2)
if(summa_v_seriyi + random_cishlo <= 12):
print(random_cishlo, end="")
summa_v_seriyi += random_cishlo
dlina += 1
all_dlina += 1
if(random_cishlo == 1):
kolvo_1 += 1
elif(random_cishlo == 2):
all_2 += 1
kolvo_2 += 1
if(random_cishlo != 0):
not_zero += 1
print(" ")
print("Количество двоек в серии:", kolvo_2)
print("Количество единиц в серии:", kolvo_1)
print("Длина серии:", dlina)
print("\n", "-"*10, "\n")
if(not_zero > max_not_zero):
max_not_zero = not_zero
not_zero = 0
kolvo_2 = 0
kolvo_1 = 0
dlina = 0
summa_v_seriyi = 0
seriya += 1
print("Среднее количество двоек:", all_2/20)
print("Средная длина:", all_dlina/20)
print("Максиальное количетсво НЕ нулей в одной серии:", max_not_zero)
<file_sep>import random
kol_vo = int(input("Введите кол-во игр: "))
i = 0
ManWins = 0
ComputerWins = 0
ManCutChoose = 0
ManPaperChoose = 0
ManStoneChoose = 0
while i < kol_vo:
print("\nВведите что вы хотите поставить: \n 1.Ножницы \n 2.Бумага \n 3.Камень")
ManChoose = int(input("Ваш выбор: "))
ComputerChoose = random.randint(1, 3)
if ComputerChoose == 1:
print("Компьютер выбрал Ножницы")
elif ComputerChoose == 2:
print("Компьютер выбрал Бумагу")
elif ComputerChoose == 3:
print("Компьютер выбрал Камень")
if ManChoose == 1:
ManCutChoose += 1
elif ManChoose == 2:
ManPaperChoose += 1
elif ManChoose == 3:
ManStoneChoose += 1
if (ManChoose == 1 and ComputerChoose == 2)\
or (ManChoose == 2 and ComputerChoose == 3)\
or (ManChoose == 3 and ComputerChoose == 1):
print("Вы выйграли!", "\n"*2)
i += 1
ManWins += 1
elif ManChoose == ComputerChoose:
print("Ничья!", "\n"*2)
elif ManChoose > 3 or ManChoose < 1:
print("Вы что-то неправильно ввели,попробуйте еще раз")
else:
print("Увы, но вы проиграли.", "\n"*2)
i += 1
ComputerWins += 1
print("Количество побед у человека:", ManWins)
print("Количество побед у компьютера:", ComputerWins)
print("Вы выбрали Ножницы ", ManCutChoose, "раза")
print("Вы выбрали Бумагу ", ManPaperChoose, "раза")
print("Вы выбрали Камень ", ManStoneChoose, "раза")
<file_sep># Дано
# 1.Есть два числа и знак,которые вводятся пользователем
# 2.Программа зациклена
# 3.Завершение программы на знак '0'
# 4.Введение неверного знака приводит к ошибке и повторному запросу
# 5.Сообщение о невозможности деления на 0(нуль)
# Задачи
# 1. правильный input
# 2. программу зациклить под while
# 3. Обработка запросов
# 4. перехват ошибок
def inputNum():
num = 0
while True:
try:
num = int(input("Введите число: "))
break
except ValueError:
print("Вы ввели НЕ число,попробуйте ещё раз.")
return num
def input_checkChar():
check = False
char = ''
while check == False:
char = input('''
1.Cложение - '+' ;
2.Вычитание - '-' ;
3.Умножение - '*' ;
4.Деление - '/' ;
5.Выход из программы - '0' .
Введите знак :''')
if char != '+' and char != '-' and char != '*' and char != '/' and char != '0':
print("Вы ввели направильный знак,попробуйте еще раз.")
else:
check = True
return char
exit = False
while exit == False:
num1 = inputNum()
num2 = inputNum()
char = input_checkChar()
if char == '+':
print("Сумма чисел: ", num1+num2)
if char == '-':
print("Разница чисел: ", num1-num2)
if char == '*':
print("Умножение чисел: ", num1*num2)
if char == '/':
if num1 * num2 == 0:
print("Деление на нуль невозможно.")
else:
print("Деление чисел: ", num1/num2)
if char=='0':
print("Выход из программы.")
exit=True
<file_sep>import math
import random
class Vector:
x1 = 0
y1 = 0
z1 = 0
def __init__(self, x, y, z):
self.x1 = x
self.y1 = y
self.z1 = z
def vectorLength(self, x2=float('nan'), y2=float('nan'), z2=float('nan')):
if(math.isnan(x2) and math.isnan(y2) and math.isnan(z2)):
return math.sqrt(math.pow(self.x1, 2) + math.pow(self.y1, 2) + math.pow(self.z1, 2))
else:
return math.sqrt(math.pow(x2, 2) + math.pow(y2, 2) + math.pow(z2, 2))
def scalarMultiplication(self, x2, y2, z2):
return self.x1*x2+self.y1*y2+self.z1*z2
def vectorData(self):
return self.x1, self.y1, self.z1
def multiplicationOf_a_VectorWithAnotherVector(self, x2, y2, z2):
return self.y1*z2-self.z1*y2, self.z1*x2-self.x1*z2, self.x1*y2-self.y1*x2
def angle(self, x, y, z):
return math.degrees(math.acos((self.scalarMultiplication(x, y, z))/(math.fabs(self.vectorLength())*math.fabs(self.vectorLength(x2=x, y2=y, z2=z)))))
def sumVector(self, x2, y2, z2):
return self.x1+x2, self.y1+y2, self.z1+z2
def differenceVector(self, x2, y2, z2):
return self.x1-x2, self.y1-y2, self.z1-z2
def vectorGenerate(count):
massive=[]
for i in range(count):
x=random.uniform(-100,100)
y=random.uniform(-100,100)
z=random.uniform(-100,100)
massive.append([x,y,z])
return massive
print(vectorGenerate(5))<file_sep>import random
n=int(input())
a = [0 for i in range(n)]
print(a)
m=int(input())
for i in range(m):
a[i]+=1
for i in range(m,n):
a[i]+=2
print(a)
for i in range(n):
if(len(a)==1):
break
try:
a[m]+=a[m-1]
a.pop(m-1)
except IndexError:
a[-1] += a[0]
a.pop(0)
print ("Номер последнего человека:", m-1)
print ("Всего собрано монет:", a[0]) | 06b7458aca6e4f179a1d3ffbc5865f0bdfe6bdb6 | [
"Python"
] | 22 | Python | DanikKaragodin/python | aaec648fd122233d234c8f060932a08f3f1f0242 | 1134c73a1a42163bf9bf65090c92ae9ce57c44f3 |
refs/heads/master | <file_sep>/********* Copyright (c) 2018-2020, a5021 ************************************/
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
#endif
#include "nrf.h"
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#ifdef USE_UART
#include <stdio.h>
#define UART_TX_PIN 6
#endif
#define NRF_FREQ_CHANNEL 99
#define TX_PERIOD 60
#define SDA_PIN 26
#define SCL_PIN 27
#define NRF_TWIMx NRF_TWIM1
#define NRF_TWIx NRF_TWI1
#define NRF_TIMERy NRF_TIMER2
#define WAIT_FOR_EVENT(EVT) while((EVT) == 0); EVT = 0
#define TWI_ERROR 0
#define TWI_OK !TWI_ERROR
#define CRCINIT0 0x0UL
#define CRCPOLY0 0x0UL
#define CRCINIT8 0xFFUL
#define CRCPOLY8 0x107UL
#define CRCINIT16 0xFFFFUL
#define CRCPOLY16 0x11021UL
/* width=24 poly=0x00065b init=0x555555 refin=true refout=true xorout=0x000000 check=0xc25a56 residue=0x000000 name="CRC-24/BLE" */
#define CRCINIT24 0x555555UL
#define CRCPOLY24 0x00065bUL
/*** allowed value for `BITS' is: 0, 8, 16, 24 */
#define NRF_RADIO_SET_CRC(BITS) NRF_RADIO->CRCCNF = BITS / 8; \
NRF_RADIO->CRCINIT = CRCINIT ## BITS; \
NRF_RADIO->CRCPOLY = CRCPOLY ## BITS
#define BME280_I2C_ADDR_PRIM 0x76
#define BME280_CHIP_ID 0x60
#define BME280_RESET_CMD 0xB6
#define BME280_FORCED_MODE 0x01
#define BME280_FILTER_POS 0x02
#define BME280_SENSOR_MODE_POS 0x00
#define BME280_CTRL_HUM_POS 0x00
#define BME280_CTRL_PRESS_POS 0x02
#define BME280_CTRL_TEMP_POS 0x05
#define BME280_NO_OVERSAMPLING 0x00
#define BME280_OVERSAMPLING_1X 0x01
#define BME280_OVERSAMPLING_2X 0x02
#define BME280_OVERSAMPLING_4X 0x03
#define BME280_OVERSAMPLING_8X 0x04
#define BME280_OVERSAMPLING_16X 0x05
#define BME280_FILTER_COEFF_OFF 0x00
#define BME280_FILTER_COEFF_2 0x01
#define BME280_FILTER_COEFF_4 0x02
#define BME280_FILTER_COEFF_8 0x03
#define BME280_FILTER_COEFF_16 0x04
typedef enum {
CHIP_ID_REG = 0xD0,
RESET_REG = 0xE0,
TEMP_PRESS_CALIB_DATA_REG = 0x88,
HUMIDITY_CALIB_DATA_REG = 0xE1,
CONFIG_REG = 0xF5,
CTRL_HUM_REG = 0xF2,
CTRL_MEAS_REG = 0xF4,
DATA_REG = 0xF7
} bme280_reg_addr_t;
typedef enum {
ID_LEN = 1,
TEMP_PRESS_CALIB_DATA_LEN = 26,
HUMIDITY_CALIB_DATA_LEN = 7,
P_T_H_DATA_LEN = 8
} bme280_len_t;
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
typedef struct {
uint16_t T1;
int16_t T2;
int16_t T3;
uint16_t P1;
int16_t P2;
int16_t P3;
int16_t P4;
int16_t P5;
int16_t P6;
int16_t P7;
int16_t P8;
int16_t P9;
uint8_t H1;
int16_t H2;
uint8_t H3;
int16_t H4;
int16_t H5;
int8_t H6;
int32_t t_fine;
} bme280_calib_data_t ;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#define PRESS_EXP(D) ((uint32_t)D[0] << 12) | ((uint32_t)D[1] << 4) | (D[2] >> 4)
#define TEMP_EXP(D) ((uint32_t)D[3] << 12) | ((uint32_t)D[4] << 4) | (D[5] >> 4)
#define HUM_EXP(D) ((uint32_t)D[6] << 8) | D[7]
static unsigned char i2c_status;
__STATIC_INLINE void init_radio(uint8_t freq, uint8_t *payload) {
NRF_RADIO->FREQUENCY = freq; /* Set RF channel */
NRF_RADIO->MODE = RADIO_MODE_MODE_Nrf_2Mbit; /* Set data rate and modulation */
NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos4dBm; /* Set TX power */
NRF_RADIO->PCNF0 = ( /* Packet configuration register 0 */
(6 << RADIO_PCNF0_LFLEN_Pos) | /* 6 bits for LENGTH field */
(3 << RADIO_PCNF0_S1LEN_Pos) /* 3 bits for PKT ID & NO_ACK field */
);
NRF_RADIO->PCNF1 = ( /* Packet configuration register 1 */
(RADIO_PCNF1_ENDIAN_Msk) | /* Most significant bit on air first */
(2 << RADIO_PCNF1_BALEN_Pos) | /* Base address length in number of bytes */
(32 << RADIO_PCNF1_MAXLEN_Pos) /* Max payload size in bytes */
);
/*** Address consists of one byte PREFIX0 + n bytes BASE0 ***/
/*** where n is a value of BALEN field in PCNF1 register ***/
NRF_RADIO->BASE0 = 0xE7E7E7E7; /* Base address 0 */
NRF_RADIO->PREFIX0 = 0xE7; /* Prefixes bytes for logical addresses */
NRF_RADIO->RXADDRESSES = 0x01; /* Receive address select */
NRF_RADIO_SET_CRC(16); /* Set 16 bit CRC mode */
NRF_RADIO->PACKETPTR = (uint32_t) payload; /* Set TX buffer pointer */
NRF_RADIO->TASKS_TXEN = 1; /* Enable RADIO in TX mode */
}
__STATIC_INLINE void init_twi(uint8_t twi_addr) {
NRF_TWIx->ENABLE = TWI_ENABLE_ENABLE_Enabled << TWI_ENABLE_ENABLE_Pos; /* Enable I2C */
NRF_TWIx->ADDRESS = twi_addr; /* Set I2C slave device (sensor) address */
NRF_TWIx->FREQUENCY = TWI_FREQUENCY_FREQUENCY_K400; /* Set 400kHz I2C mode */
NRF_TWIx->PSELSDA = SDA_PIN; /* Define SDA pin */
NRF_TWIx->PSELSCL = SCL_PIN; /* Define SCL pin */
}
__STATIC_INLINE void init_rtc(void) {
NRF_RTC2->PRESCALER = 1; /* freq = 32768 / 2 */
NRF_RTC2->CC[0] = 16384 * TX_PERIOD; /* sleep period between data sendings */
NRF_RTC2->CC[1] = 135; /* short sleep while data converting */
NRF_RTC2->INTENSET = RTC_INTENSET_COMPARE0_Msk | RTC_INTENSET_COMPARE1_Msk;
NRF_RTC2->EVENTS_COMPARE[1] = /* reset compare 1 event flag */
NRF_RTC2->EVENTS_COMPARE[0] = 0; /* reset compare 0 event flag */
NVIC_ClearPendingIRQ(RTC2_IRQn);
// do not use NVIC_EnableIRQ(RTC2_IRQn); !!!
}
#ifdef USE_UART
void __STATIC_INLINE init_uart(void) {
NRF_UART0->PSELTXD = UART_TX_PIN;
NRF_UART0->BAUDRATE = UART_BAUDRATE_BAUDRATE_Baud9600;
NRF_UART0->ENABLE = UART_ENABLE_ENABLE_Enabled;
NRF_UART0->EVENTS_TXDRDY = 0x0UL;
NRF_UART0->TASKS_STARTTX = 0x1UL;
}
#define UART_PUTC(C) \
NRF_UART0->TXD = C; \
WAIT_FOR_EVENT(NRF_UART0->EVENTS_TXDRDY)
uint8_t __STATIC_INLINE uart_puts(char *s) {
while (*s != 0) {
UART_PUTC(*s++);
}
return 1;
}
#define PRINTF(...) for(char _[100]; snprintf(_, sizeof(_), __VA_ARGS__), uart_puts(_), 0;)
#endif
#define TWI_CHECK_ERR() if (NRF_TWIx->EVENTS_ERROR) { \
NRF_TWIx->TASKS_STOP = 1; \
WAIT_FOR_EVENT(NRF_TWIx->EVENTS_STOPPED); \
i2c_status |= NRF_TWIx->ERRORSRC; \
return TWI_ERROR; \
}
#define TWI_WAIT(FLAG) do {while(!FLAG) TWI_CHECK_ERR();} while(0)
#define TWI_XFER(T, E) \
NRF_TWIx->TASKS_##T = 1; \
TWI_WAIT(NRF_TWIx->EVENTS_##E)
__STATIC_INLINE uint8_t twi_read(uint8_t r, uint8_t *d, uint8_t len) {
NRF_TWIx->EVENTS_TXDSENT =
NRF_TWIx->EVENTS_RXDREADY = 0;
NRF_TWIx->TXD = r;
TWI_XFER(STARTTX, TXDSENT);
if (len == 1) {
NRF_TWIx->SHORTS = TWI_SHORTS_BB_STOP_Enabled << TWI_SHORTS_BB_STOP_Pos;
TWI_XFER(STARTRX, RXDREADY);
*d = (uint8_t)NRF_TWIx->RXD;
} else {
NRF_TWIx->SHORTS = TWI_SHORTS_BB_SUSPEND_Enabled << TWI_SHORTS_BB_SUSPEND_Pos;
NRF_TWIx->TASKS_STARTRX = 1;
do {
if (--len == 0) {
NRF_TWIx->SHORTS = TWI_SHORTS_BB_STOP_Enabled << TWI_SHORTS_BB_STOP_Pos;
}
NRF_TWIx->EVENTS_RXDREADY = 0;
TWI_XFER(RESUME, RXDREADY);
*d++ = (uint8_t)NRF_TWIx->RXD;
} while (len);
}
WAIT_FOR_EVENT(NRF_TWIx->EVENTS_STOPPED);
NRF_TWIx->SHORTS = 0;
return TWI_OK;
}
__STATIC_INLINE uint8_t twi_write(uint8_t r, uint8_t d) {
NRF_TWIx->TXD = r;
NRF_TWIx->EVENTS_TXDSENT = 0;
TWI_XFER(STARTTX, TXDSENT);
NRF_TWIx->EVENTS_TXDSENT = 0;
NRF_TWIx->TXD = d;
TWI_WAIT(NRF_TWIx->EVENTS_TXDSENT);
NRF_TWIx->TASKS_STOP = 1;
WAIT_FOR_EVENT(NRF_TWIx->EVENTS_STOPPED);
return TWI_OK;
}
__STATIC_INLINE uint8_t bme280_read(const bme280_reg_addr_t r, uint8_t* d, bme280_len_t len) {
return twi_read((uint8_t)r, d, (uint8_t)len);
}
__STATIC_INLINE uint8_t bme280_write(const bme280_reg_addr_t r, uint8_t d) {
return twi_write((uint8_t)r, d);
}
__STATIC_INLINE int32_t compensate_temperature(uint32_t u_temp, bme280_calib_data_t *c) {
int32_t var1, var2, temperature;
int32_t temperature_min = -4000;
int32_t temperature_max = 8500;
var1 = (int32_t)(u_temp / 8) - (int32_t)c->T1 * 2;
var1 = (var1 * ((int32_t)c->T2)) / 2048;
var2 = (int32_t)(u_temp / 16) - ((int32_t)c->T1);
var2 = (((var2 * var2) / 4096) * ((int32_t)c->T3)) / 16384;
c->t_fine = var1 + var2;
temperature = (c->t_fine * 5 + 128) / 256;
if (temperature < temperature_min)
temperature = temperature_min;
else if (temperature > temperature_max)
temperature = temperature_max;
return temperature;
}
__STATIC_INLINE uint32_t compensate_pressure(uint32_t u_press, bme280_calib_data_t *c) {
#define pressure_min 3000000UL
#define pressure_max 11000000UL
int64_t var1, var2, var3;
uint32_t pressure;
var1 = ((int64_t)c->t_fine) - 128000;
var2 = var1 * var1 * (int64_t)c->P6;
var2 = var2 + ((var1 * (int64_t)c->P5) * 131072);
var2 = var2 + (((int64_t)c->P4) * 34359738368);
var1 = ((var1 * var1 * (int64_t)c->P3) / 256) + ((var1 * ((int64_t)c->P2) * 4096));
var3 = ((int64_t)1) * 140737488355328;
var1 = (var3 + var1) * ((int64_t)c->P1) / 8589934592;
/* To avoid divide by zero exception */
if (var1 != 0) {
int64_t var4 = 1048576 - u_press;
var4 = (((var4 * 2147483648) - var2) * 3125) / var1;
var1 = (((int64_t)c->P9) * (var4 / 8192) * (var4 / 8192)) / 33554432;
var2 = (((int64_t)c->P8) * var4) / 524288;
var4 = ((var4 + var1 + var2) / 256) + (((int64_t)c->P7) * 16);
pressure = (uint32_t)(((var4 / 2) * 100) / 128);
if (pressure < pressure_min)
pressure = pressure_min;
else if (pressure > pressure_max)
pressure = pressure_max;
} else {
pressure = pressure_min;
}
return pressure;
}
__STATIC_INLINE uint32_t compensate_humidity(uint32_t u_hum, bme280_calib_data_t *c) {
int32_t var1, var2, var3, var4, var5;
var1 = c->t_fine - ((int32_t)76800);
var2 = (int32_t)(u_hum * 16384);
var3 = (int32_t)(((int32_t)c->H4) * 1048576);
var4 = ((int32_t)c->H5) * var1;
var5 = (((var2 - var3) - var4) + (int32_t)16384) / 32768;
var2 = (var1 * ((int32_t)c->H6)) / 1024;
var3 = (var1 * ((int32_t)c->H3)) / 2048;
var4 = ((var2 * (var3 + (int32_t)32768)) / 1024) + (int32_t)2097152;
var2 = ((var4 * ((int32_t)c->H2)) + 8192) / 16384;
var3 = var5 * var2;
var4 = ((var3 / 32768) * (var3 / 32768)) / 128;
var5 = var3 - ((var4 * ((int32_t)c->H1)) / 16);
var5 = (var5 < 0 ? 0 : var5);
var5 = (var5 > 419430400 ? 419430400 : var5);
uint32_t humidity = (uint32_t)(var5 / 4096);
if (humidity > 102400)
humidity = 102400;
return humidity;
}
__STATIC_INLINE void sleep(void) {
NVIC_ClearPendingIRQ(RTC2_IRQn);
NRF_POWER->TASKS_LOWPWR = 1;
__WFE();
}
__STATIC_INLINE void init_clock(void) {
/* Start 32 MHz crystal oscillator */
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
/* Wait for the external oscillator to start up */
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);
/* Start low frequency crystal oscillator */
NRF_CLOCK->LFCLKSRC = (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos);
NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
NRF_CLOCK->TASKS_LFCLKSTART = 1;
/* Wait for the external oscillator to start up */
while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0);
}
__STATIC_INLINE void init_adc(void) {
NRF_SAADC->RESOLUTION = SAADC_RESOLUTION_VAL_12bit;
NRF_SAADC->CH[0].PSELP = SAADC_CH_PSELP_PSELP_VDD;
NRF_SAADC->CH[0].CONFIG = (
SAADC_CH_CONFIG_TACQ_15us << SAADC_CH_CONFIG_TACQ_Pos |
SAADC_CH_CONFIG_BURST_Enabled << SAADC_CH_CONFIG_BURST_Pos
);
NRF_SAADC->OVERSAMPLE = SAADC_OVERSAMPLE_OVERSAMPLE_Over64x;
NRF_SAADC->RESULT.MAXCNT = 1;
NRF_SAADC->SAMPLERATE = SAADC_SAMPLERATE_MODE_Task << SAADC_SAMPLERATE_MODE_Pos;
NRF_SAADC->ENABLE = SAADC_ENABLE_ENABLE_Enabled << SAADC_ENABLE_ENABLE_Pos;
NRF_SAADC->TASKS_CALIBRATEOFFSET = 1; /* Start calibration */
while (NRF_SAADC->EVENTS_CALIBRATEDONE == 0);
NRF_SAADC->EVENTS_CALIBRATEDONE = 0;
while (NRF_SAADC->STATUS == (SAADC_STATUS_STATUS_Busy <<SAADC_STATUS_STATUS_Pos));
}
__STATIC_INLINE uint32_t measure_vdd(void) {
volatile uint16_t res;
NRF_SAADC->RESULT.PTR = (uint32_t) &res;
NRF_SAADC->EVENTS_DONE = 0;
NRF_SAADC->ENABLE = SAADC_ENABLE_ENABLE_Enabled << SAADC_ENABLE_ENABLE_Pos;
NRF_SAADC->TASKS_START = 1; // Start the SAADC
while (NRF_SAADC->EVENTS_STARTED == 0); // Wait for STARTED event
NRF_SAADC->EVENTS_STARTED = 0; // Reset event flag
NRF_SAADC->TASKS_SAMPLE = 1;
while (NRF_SAADC->EVENTS_END == 0);
NRF_SAADC->EVENTS_END = 0;
// Disable SAADC
NRF_SAADC->ENABLE = SAADC_ENABLE_ENABLE_Disabled << SAADC_ENABLE_ENABLE_Pos;
return res * 3600 / 4095;
}
#define MASK_SIGN (0x00000200UL)
#define MASK_SIGN_EXTENSION (0xFFFFFC00UL)
#define READ_TEMP() (((unsigned)NRF_TEMP->TEMP & MASK_SIGN) != 0) ? (signed)((unsigned)NRF_TEMP->TEMP | MASK_SIGN_EXTENSION) : (NRF_TEMP->TEMP)
int main(void) {
struct {
uint8_t l;
uint8_t i;
uint32_t p : 24;
int8_t t0: 8;
int32_t t : 16;
uint32_t h : 16;
uint16_t v : 16;
} __attribute__((packed)) payload_buf = {.l = 10, .i = 6};
init_clock();
init_adc();
init_twi(BME280_I2C_ADDR_PRIM);
init_rtc();
#ifdef USE_UART
init_uart();
#endif
SCB->SCR |= SCB_SCR_SEVONPEND_Msk;
__SEV();
__WFE();
bme280_calib_data_t c_data;
uint8_t buf[TEMP_PRESS_CALIB_DATA_LEN];
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcomma"
#endif
while(
! bme280_read(CHIP_ID_REG, buf, ID_LEN) ||
! (buf[0] == BME280_CHIP_ID) ||
! bme280_write(RESET_REG, BME280_RESET_CMD) ||
(
NRF_TWIx->ENABLE = TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos ,
NRF_RTC2->TASKS_START = 1 ,
sleep() ,
NRF_RTC2->EVENTS_COMPARE[1] = 0 ,
NRF_RTC2->TASKS_STOP = 1 ,
NRF_RTC2->TASKS_CLEAR = 1 ,
NRF_TWIx->ENABLE = TWI_ENABLE_ENABLE_Enabled << TWI_ENABLE_ENABLE_Pos ,
0
) ||
! bme280_read(TEMP_PRESS_CALIB_DATA_REG, (uint8_t*)&c_data, TEMP_PRESS_CALIB_DATA_LEN) ||
! bme280_read(HUMIDITY_CALIB_DATA_REG, buf, HUMIDITY_CALIB_DATA_LEN) ||
(
c_data.H2 = (int16_t)((int16_t)buf[1] << 8) | buf[0] ,
c_data.H3 = buf[2] ,
c_data.H4 = ((int16_t)buf[3] * 16) | (buf[4] & 0x0F) ,
c_data.H5 = ((int16_t)buf[5] * 16) | (buf[4] >> 4) ,
c_data.H6 = (int8_t)buf[6] ,
0
) ||
! bme280_write(CONFIG_REG, BME280_FILTER_COEFF_OFF << BME280_FILTER_POS) ||
! bme280_write(CTRL_HUM_REG, BME280_OVERSAMPLING_1X << BME280_CTRL_HUM_POS)
);
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
init_radio(NRF_FREQ_CHANNEL, (uint8_t*)&payload_buf);
NRF_RTC2->TASKS_START = 1;
/* Workaround for PAN_028 rev2.0A anomaly 31 - TEMP: Temperature offset value has to be manually loaded to the TEMP module */
*(uint32_t *) 0x4000C504 = 0;
while (1) {
bme280_write(CTRL_MEAS_REG, (BME280_OVERSAMPLING_1X << BME280_CTRL_TEMP_POS) | (BME280_OVERSAMPLING_1X << BME280_CTRL_PRESS_POS) | BME280_FORCED_MODE);
sleep();
NRF_RTC2->EVENTS_COMPARE[1] = 0;
bme280_read(DATA_REG, buf, P_T_H_DATA_LEN);
NRF_TWIx->ENABLE = TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos;
NRF_TEMP->TASKS_START = 1; /** Start the temperature measurement. */
/* Busy wait while temperature measurement is not finished */
while (NRF_TEMP->EVENTS_DATARDY == 0);
NRF_TEMP->EVENTS_DATARDY = 0;
/* Workaround for PAN_028 rev2.0A anomaly 29 - TEMP: Stop task clears the TEMP register. */
payload_buf.t0 = (int8_t)(READ_TEMP() / 4);
/* Workaround for PAN_028 rev2.0A anomaly 30 - TEMP: Temp module analog front end does not power down when DATARDY event occurs. */
NRF_TEMP->TASKS_STOP = 1; /* Stop the temperature measurement. */
payload_buf.t = compensate_temperature(TEMP_EXP(buf), &c_data);
payload_buf.p = compensate_pressure(PRESS_EXP(buf), &c_data);
payload_buf.h = compensate_humidity(HUM_EXP(buf), &c_data) / 10;
payload_buf.i = ((((payload_buf.i >> 1) + 1) << 1) & 0x06) | 1;
payload_buf.v = (uint16_t) measure_vdd();
#ifdef USE_UART
NRF_UART0->ENABLE = UART_ENABLE_ENABLE_Enabled;
NRF_UART0->TASKS_STARTTX = 1;
PRINTF("%d.%02uC,\t\t %u.%02u Pa / %u.%02u mmHg,\t %u.%02u%%\t%u\t0x%02X\r\n", payload_buf.t / 100, (unsigned) payload_buf.t % 100, payload_buf.p / 100, payload_buf.p % 100, payload_buf.p / 13332, payload_buf.p % 13332 * 100 / 13332, payload_buf.h / 1000, payload_buf.h % 1000, payload_buf.i, NRF_CLOCK->HFCLKSTAT);
#endif
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->TASKS_START = 1;
WAIT_FOR_EVENT(NRF_RADIO->EVENTS_END);
#ifdef USE_UART
static unsigned a_cnt;
PRINTF("TX Loop count = %u \n", ++a_cnt);
NRF_UART0->TASKS_STOPTX = 1;
NRF_UART0->ENABLE = UART_ENABLE_ENABLE_Disabled;
#endif
NRF_RADIO->TASKS_DISABLE = 1;
WAIT_FOR_EVENT(NRF_RADIO->EVENTS_DISABLED);
NRF_CLOCK->TASKS_HFCLKSTOP = 1;
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
sleep();
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->TASKS_TXEN = 1;
while (NRF_RADIO->EVENTS_READY == 0);
NRF_TWIx->ENABLE = TWI_ENABLE_ENABLE_Enabled << TWI_ENABLE_ENABLE_Pos;
NRF_RTC2->EVENTS_COMPARE[0] = 0;
NRF_RTC2->TASKS_CLEAR = 1;
}
}
<file_sep># NRF52832-BME280-RADIO
Wireless sensor firmware.
[](https://travis-ci.org/a5021/NRF52832-BME280-RADIO) [](https://www.codacy.com/app/a5021/NRF52832-BME280-RADIO?utm_source=github.com&utm_medium=referral&utm_content=a5021/NRF52832-BME280-RADIO&utm_campaign=Badge_Grade)
<file_sep>PROJECT_NAME := NRF52832-BME280-RADIO
TARGETS := NRF52832-BME280-RADIO
OUTPUT_DIRECTORY := _build
PROJ_DIR := .
$(OUTPUT_DIRECTORY)/NRF52832-BME280-RADIO.out: \
LINKER_SCRIPT := $(PROJ_DIR)/IDE/GCC/ld/gcc_nrf52.ld
# Source files common to all targets
SRC_FILES += \
$(PROJ_DIR)/drv/src/gcc_startup_nrf52.S \
$(PROJ_DIR)/drv/src/system_nrf52.c \
$(PROJ_DIR)/main.c
# Include folders common to all targets
INC_FOLDERS += \
$(PROJ_DIR)/drv/inc/CMSIS \
$(PROJ_DIR)/drv/inc \
# Libraries common to all targets
LIB_FILES += \
# Optimization flags
OPT = -Ofast -g0
# Uncomment the line below to enable link time optimization
OPT += -flto
# C flags common to all targets
CFLAGS += $(OPT) -fverbose-asm
CFLAGS += -DNRF52832_XXAA
CFLAGS += -DCONFIG_GPIO_AS_PINRESET
CFLAGS += -mcpu=cortex-m4
CFLAGS += -mthumb -mabi=aapcs
CFLAGS += -Wall -Wextra -Werror -Wpedantic -std=gnu11
CFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
# keep every function in a separate section, this allows linker to discard unused ones
#CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
CFLAGS += -ffunction-sections -fdata-sections -fstrict-aliasing
CFLAGS += -fno-builtin -fshort-enums
# C++ flags common to all targets
CXXFLAGS += $(OPT)
# Assembler flags common to all targets
ASMFLAGS += -g0 -fverbose-asm
ASMFLAGS += -mcpu=cortex-m4
ASMFLAGS += -mthumb -mabi=aapcs
ASMFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
# Linker flags
LDFLAGS += $(OPT) -fverbose-asm
LDFLAGS += -mthumb -mabi=aapcs -L$(PROJ_DIR)/IDE/GCC/ld -T$(LINKER_SCRIPT)
LDFLAGS += -mcpu=cortex-m4
LDFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
# let linker dump unused sections
LDFLAGS += -Wl,--gc-sections
# use newlib in nano version
LDFLAGS += --specs=nano.specs
NRF52832-BME280-RADIO: CFLAGS += -D__HEAP_SIZE=2048
NRF52832-BME280-RADIO: CFLAGS += -D__STACK_SIZE=2048
NRF52832-BME280-RADIO: ASMFLAGS += -D__HEAP_SIZE=2048
NRF52832-BME280-RADIO: ASMFLAGS += -D__STACK_SIZE=2048
# Add standard libraries at the very end of the linker input, after all objects
# that may need symbols provided by these libraries.
LIB_FILES += -lc -lnosys -lm
STLINK = ST-LINK_CLI.exe
#STLINK_FLAGS = -c UR -V -P $< -Hardrst -Run
STLINK_FLAGS = -c SWD -V -ME -P $< -Hardrst -Run
.PHONY: default help
# Default target - first one defined
default: NRF52832-BME280-RADIO
TEMPLATE_PATH := $(PROJ_DIR)/IDE/GCC/mk
include $(TEMPLATE_PATH)/Makefile.common
$(foreach target, $(TARGETS), $(call define_target, $(target)))
.PHONY: flash erase
# Flash the program
jflash: $(OUTPUT_DIRECTORY)/NRF52832-BME280-RADIO.hex
@echo Flashing: $<
nrfjprog -f nrf52 --program $< --sectorerase --verify --log
nrfjprog -f nrf52 --reset
stflash: $(OUTPUT_DIRECTORY)/NRF52832-BME280-RADIO.hex
@echo Flashing: $<
$(STLINK) $(STLINK_FLAGS)
erase:
nrfjprog -f nrf52 --eraseall
| 781bf95599f7bd80f00e4255917afc0751f527bc | [
"Markdown",
"C",
"Makefile"
] | 3 | C | a5021/NRF52832-BME280-RADIO | ddd3b11df1c23a8d4069aec80f770d5ed411086b | 9e9641f200bc5122f8de6714a4904f5d961aa740 |
refs/heads/main | <repo_name>pymanopt/pymanopt.github.io<file_sep>/docs/stable/_static/katex_autorenderer.js
katex_options = {
macros: {"\\manM": "\\mathcal{M}",
"\\R": "\\mathbb{R}",
"\\C": "\\mathbb{C}",
"\\O": "\\mathrm{O}",
"\\SO": "\\mathrm{SO}",
"\\U": "\\mathrm{U}",
"\\E": "\\mathcal{E}",
"\\Skew": "\\mathrm{Skew}",
"\\St": "\\mathrm{St}",
"\\Id": "\\mathrm{Id}",
"\\set": "\\{#1\\}",
"\\inner": "\\langle #1, #2 \\rangle",
"\\opt": "#1^\\star",
"\\sphere": "\\mathcal{S}",
"\\transp": "#1^\\top",
"\\conj": "#1^*",
"\\norm": "\\|#1\\|",
"\\abs": "|#1|",
"\\parens": "\\left(#1\\right)",
"\\tangent":"\\mathrm{T}_{#1}",
"\\vma":"\\mathbf{a}",
"\\vmb":"\\mathbf{b}",
"\\vmc":"\\mathbf{c}",
"\\vmd":"\\mathbf{d}",
"\\vme":"\\mathbf{e}",
"\\vmf":"\\mathbf{f}",
"\\vmg":"\\mathbf{g}",
"\\vmh":"\\mathbf{h}",
"\\vmi":"\\mathbf{i}",
"\\vmj":"\\mathbf{j}",
"\\vmk":"\\mathbf{k}",
"\\vml":"\\mathbf{l}",
"\\vmm":"\\mathbf{m}",
"\\vmn":"\\mathbf{n}",
"\\vmo":"\\mathbf{o}",
"\\vmp":"\\mathbf{p}",
"\\vmq":"\\mathbf{q}",
"\\vmr":"\\mathbf{r}",
"\\vms":"\\mathbf{s}",
"\\vmt":"\\mathbf{t}",
"\\vmu":"\\mathbf{u}",
"\\vmv":"\\mathbf{v}",
"\\vmw":"\\mathbf{w}",
"\\vmx":"\\mathbf{x}",
"\\vmy":"\\mathbf{y}",
"\\vmz":"\\mathbf{z}",
"\\vmA":"\\mathbf{A}",
"\\vmB":"\\mathbf{B}",
"\\vmC":"\\mathbf{C}",
"\\vmD":"\\mathbf{D}",
"\\vmE":"\\mathbf{E}",
"\\vmF":"\\mathbf{F}",
"\\vmG":"\\mathbf{G}",
"\\vmH":"\\mathbf{H}",
"\\vmI":"\\mathbf{I}",
"\\vmJ":"\\mathbf{J}",
"\\vmK":"\\mathbf{K}",
"\\vmL":"\\mathbf{L}",
"\\vmM":"\\mathbf{M}",
"\\vmN":"\\mathbf{N}",
"\\vmO":"\\mathbf{O}",
"\\vmP":"\\mathbf{P}",
"\\vmQ":"\\mathbf{Q}",
"\\vmR":"\\mathbf{R}",
"\\vmS":"\\mathbf{S}",
"\\vmT":"\\mathbf{T}",
"\\vmU":"\\mathbf{U}",
"\\vmV":"\\mathbf{V}",
"\\vmW":"\\mathbf{W}",
"\\vmX":"\\mathbf{X}",
"\\vmY":"\\mathbf{Y}",
"\\vmZ":"\\mathbf{Z}",
"\\vmOmega":"\\mathbf{\\Omega}",
"\\argmin":"\\mathop{\\operatorname{argmin}}\\limits",
"\\arccosh":"\\operatorname{arccosh}",
"\\dist":"\\operatorname{dist}"},
delimiters: [
{ left: "\\(", right: "\\)", display: false },
{ left: "\\[", right: "\\]", display: true }
]
}
document.addEventListener("DOMContentLoaded", function() {
renderMathInElement(document.body, katex_options);
});
<file_sep>/docs/stable/_modules/pymanopt/tools/diagnostics.html
<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>pymanopt.tools.diagnostics — Pymanopt stable (2.1.1) documentation</title>
<link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/css/style.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.1/dist/katex.min.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/katex-math.css" type="text/css" />
<link rel="canonical" href="pymanopt.org/_modules/pymanopt/tools/diagnostics.html" />
<!--[if lt IE 9]>
<script src="../../../_static/js/html5shiv.min.js"></script>
<![endif]-->
<script data-url_root="../../../" id="documentation_options" src="../../../_static/documentation_options.js"></script>
<script src="../../../_static/jquery.js"></script>
<script src="../../../_static/underscore.js"></script>
<script src="../../../_static/doctools.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.15.1/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.15.1/dist/contrib/auto-render.min.js"></script>
<script src="../../../_static/katex_autorenderer.js"></script>
<script crossorigin="anonymous" integrity="<KEY> src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script src="../../../_static/js/theme.js"></script>
<link rel="index" title="Index" href="../../../genindex.html" />
<link rel="search" title="Search" href="../../../search.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" >
<a href="../../../index.html" class="icon icon-home"> Pymanopt
<img src="../../../_static/logo.png" class="logo" alt="Logo"/>
</a>
<div class="version">
stable (2.1.1)
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<p class="caption" role="heading"><span class="caption-text">Getting Started</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../quickstart.html">Quickstart</a></li>
<li class="toctree-l1"><a class="reference external" href="https://github.com/pymanopt/pymanopt/tree/master/examples">Examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../api-reference.html">API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../CONTRIBUTING.html">Contributing</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">Notebooks</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../examples/notebooks/mixture_of_gaussians.html">Riemannian Optimization for Inference in MoG models</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../../index.html">Pymanopt</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../../index.html" class="icon icon-home"></a> »</li>
<li><a href="../../index.html">Module code</a> »</li>
<li>pymanopt.tools.diagnostics</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<h1>Source code for pymanopt.tools.diagnostics</h1><div class="highlight"><pre>
<span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="k">try</span><span class="p">:</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
<span class="n">plt</span> <span class="o">=</span> <span class="kc">None</span>
<div class="viewcode-block" id="identify_linear_piece"><a class="viewcode-back" href="../../../tools.html#pymanopt.tools.diagnostics.identify_linear_piece">[docs]</a><span class="k">def</span> <span class="nf">identify_linear_piece</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">window_length</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""Identify a segment of the curve (x, y) that appears to be linear.</span>
<span class="sd"> This function attempts to identify a contiguous segment of the curve</span>
<span class="sd"> defined by the vectors x and y that appears to be linear. A line is fit</span>
<span class="sd"> through the data over all windows of length window_length and the best</span>
<span class="sd"> fit is retained. The output specifies the range of indices such that</span>
<span class="sd"> x(segment) is the portion over which (x, y) is the most linear and the</span>
<span class="sd"> output poly specifies a first order polynomial that best fits (x, y) over</span>
<span class="sd"> that segment (highest degree coefficients first).</span>
<span class="sd"> """</span>
<span class="n">residues</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">-</span> <span class="n">window_length</span><span class="p">)</span>
<span class="n">polys</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">residues</span><span class="p">)))</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">residues</span><span class="p">)):</span>
<span class="n">segment</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">k</span> <span class="o">+</span> <span class="n">window_length</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">poly</span><span class="p">,</span> <span class="n">residuals</span><span class="p">,</span> <span class="o">*</span><span class="n">_</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">polyfit</span><span class="p">(</span>
<span class="n">x</span><span class="p">[</span><span class="n">segment</span><span class="p">],</span> <span class="n">y</span><span class="p">[</span><span class="n">segment</span><span class="p">],</span> <span class="n">deg</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">full</span><span class="o">=</span><span class="kc">True</span>
<span class="p">)</span>
<span class="n">residues</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">residuals</span><span class="p">)</span>
<span class="n">polys</span><span class="p">[:,</span> <span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">poly</span>
<span class="n">best</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">argmin</span><span class="p">(</span><span class="n">residues</span><span class="p">)</span>
<span class="n">segment</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">best</span><span class="p">,</span> <span class="n">best</span> <span class="o">+</span> <span class="n">window_length</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">poly</span> <span class="o">=</span> <span class="n">polys</span><span class="p">[:,</span> <span class="n">best</span><span class="p">]</span>
<span class="k">return</span> <span class="n">segment</span><span class="p">,</span> <span class="n">poly</span></div>
<div class="viewcode-block" id="check_directional_derivative"><a class="viewcode-back" href="../../../tools.html#pymanopt.tools.diagnostics.check_directional_derivative">[docs]</a><span class="k">def</span> <span class="nf">check_directional_derivative</span><span class="p">(</span>
<span class="n">problem</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">*</span><span class="p">,</span> <span class="n">use_quadratic_model</span><span class="o">=</span><span class="kc">False</span>
<span class="p">):</span>
<span class="w"> </span><span class="sd">"""Checks the consistency of the cost function and directional derivatives.</span>
<span class="sd"> check_directional_derivative performs a numerical test to check that the</span>
<span class="sd"> directional derivatives defined in the problem agree up to first or second</span>
<span class="sd"> order with the cost function at some point x, along some direction d. The</span>
<span class="sd"> test is based on a truncated Taylor series.</span>
<span class="sd"> Both x and d are optional and will be sampled at random if omitted.</span>
<span class="sd"> """</span>
<span class="c1"># If x and / or d are not specified, pick them at random.</span>
<span class="k">if</span> <span class="n">d</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">x</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
<span class="s2">"If d is provided, x must be too, "</span> <span class="s2">"since d is tangent at x."</span>
<span class="p">)</span>
<span class="k">if</span> <span class="n">x</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">random_point</span><span class="p">()</span>
<span class="k">if</span> <span class="n">d</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">d</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">random_tangent_vector</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="c1"># Compute the value of f at points on the geodesic (or approximation</span>
<span class="c1"># of it) originating from x, along direction d, for step_sizes in a</span>
<span class="c1"># large range given by h.</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logspace</span><span class="p">(</span><span class="o">-</span><span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">51</span><span class="p">)</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros_like</span><span class="p">(</span><span class="n">h</span><span class="p">)</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">h_k</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">h</span><span class="p">):</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">h_k</span> <span class="o">*</span> <span class="n">d</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">NotImplementedError</span><span class="p">:</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">retraction</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">h_k</span> <span class="o">*</span> <span class="n">d</span><span class="p">)</span>
<span class="n">value</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">cost</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="c1"># Compute the value f0 of f at x and directional derivative at x along d.</span>
<span class="n">f0</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">cost</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">grad</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">riemannian_gradient</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">df0</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">grad</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
<span class="k">if</span> <span class="n">use_quadratic_model</span><span class="p">:</span>
<span class="n">hessd</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">riemannian_hessian</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
<span class="n">d2f0</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">hessd</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">polyval</span><span class="p">([</span><span class="mf">0.5</span> <span class="o">*</span> <span class="n">d2f0</span><span class="p">,</span> <span class="n">df0</span><span class="p">,</span> <span class="n">f0</span><span class="p">],</span> <span class="n">h</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">polyval</span><span class="p">([</span><span class="n">df0</span><span class="p">,</span> <span class="n">f0</span><span class="p">],</span> <span class="n">h</span><span class="p">)</span>
<span class="c1"># Compute the approximation error</span>
<span class="n">error</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">model</span> <span class="o">-</span> <span class="n">value</span><span class="p">)</span>
<span class="n">model_is_exact</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">all</span><span class="p">(</span><span class="n">error</span> <span class="o"><</span> <span class="mf">1e-12</span><span class="p">)</span>
<span class="k">if</span> <span class="n">model_is_exact</span><span class="p">:</span>
<span class="k">if</span> <span class="n">use_quadratic_model</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"Hessian check. "</span>
<span class="s2">"It seems the quadratic model is exact: "</span>
<span class="s2">"model error is numerically zero for all h."</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"Directional derivative check. "</span>
<span class="s2">"It seems the linear model is exact: "</span>
<span class="s2">"model error is numerically zero for all h."</span>
<span class="p">)</span>
<span class="c1"># The model is exact: all errors are (numerically) zero.</span>
<span class="c1"># Fit line from all points, use log scale only in h.</span>
<span class="n">segment</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">h</span><span class="p">))</span>
<span class="n">poly</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">polyfit</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">h</span><span class="p">),</span> <span class="n">error</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="c1"># Set mean error in log scale for plot.</span>
<span class="n">poly</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">poly</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">if</span> <span class="n">use_quadratic_model</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"Hessian check. The slope of the "</span>
<span class="s2">"continuous line should match that of the dashed "</span>
<span class="s2">"(reference) line over at least a few orders of "</span>
<span class="s2">"magnitude for h."</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"Directional derivative check. The slope of the "</span>
<span class="s2">"continuous line should match that of the dashed "</span>
<span class="s2">"(reference) line over at least a few orders of "</span>
<span class="s2">"magnitude for h."</span>
<span class="p">)</span>
<span class="n">window_len</span> <span class="o">=</span> <span class="mi">10</span>
<span class="c1"># Despite not all coordinates of the model being close to the true</span>
<span class="c1"># value, some entries of 'error' can be zero. To avoid numerical issues</span>
<span class="c1"># we add an epsilon here.</span>
<span class="n">eps</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">finfo</span><span class="p">(</span><span class="n">error</span><span class="o">.</span><span class="n">dtype</span><span class="p">)</span><span class="o">.</span><span class="n">eps</span>
<span class="n">segment</span><span class="p">,</span> <span class="n">poly</span> <span class="o">=</span> <span class="n">identify_linear_piece</span><span class="p">(</span>
<span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">h</span><span class="p">),</span> <span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">error</span> <span class="o">+</span> <span class="n">eps</span><span class="p">),</span> <span class="n">window_len</span>
<span class="p">)</span>
<span class="k">return</span> <span class="n">h</span><span class="p">,</span> <span class="n">error</span><span class="p">,</span> <span class="n">segment</span><span class="p">,</span> <span class="n">poly</span></div>
<div class="viewcode-block" id="check_gradient"><a class="viewcode-back" href="../../../tools.html#pymanopt.tools.diagnostics.check_gradient">[docs]</a><span class="k">def</span> <span class="nf">check_gradient</span><span class="p">(</span><span class="n">problem</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""Checks the consistency of the cost function and the gradient.</span>
<span class="sd"> check_gradient performs a numerical test to check that the gradient</span>
<span class="sd"> defined in the problem agrees up to first order with the cost function at</span>
<span class="sd"> some point x, along some direction d. The test is based on a truncated</span>
<span class="sd"> Taylor series.</span>
<span class="sd"> It is also tested that the gradient is indeed a tangent vector.</span>
<span class="sd"> Both x and d are optional and will be sampled at random if omitted.</span>
<span class="sd"> """</span>
<span class="c1"># If x and / or d are not specified, pick them at random.</span>
<span class="k">if</span> <span class="n">plt</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">"The 'check_gradient' function requires matplotlib"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">d</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">x</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
<span class="s2">"If d is provided, x must be too, since d is tangent at x."</span>
<span class="p">)</span>
<span class="k">if</span> <span class="n">x</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">random_point</span><span class="p">()</span>
<span class="k">if</span> <span class="n">d</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">d</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">random_tangent_vector</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">h</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">segment</span><span class="p">,</span> <span class="n">poly</span> <span class="o">=</span> <span class="n">check_directional_derivative</span><span class="p">(</span><span class="n">problem</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">plt</span><span class="o">.</span><span class="n">loglog</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s2">"h"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s2">"Approximation error"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">loglog</span><span class="p">(</span>
<span class="n">h</span><span class="p">[</span><span class="n">segment</span><span class="p">],</span> <span class="mi">10</span> <span class="o">**</span> <span class="n">np</span><span class="o">.</span><span class="n">polyval</span><span class="p">(</span><span class="n">poly</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">h</span><span class="p">[</span><span class="n">segment</span><span class="p">])),</span> <span class="n">linewidth</span><span class="o">=</span><span class="mi">3</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">([</span><span class="mf">1e-8</span><span class="p">,</span> <span class="mf">1e0</span><span class="p">],</span> <span class="p">[</span><span class="mf">1e-8</span><span class="p">,</span> <span class="mf">1e8</span><span class="p">],</span> <span class="n">linestyle</span><span class="o">=</span><span class="s2">"--"</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s2">"k"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span>
<span class="s2">"Gradient check</span><span class="se">\n</span><span class="s2">The slope of the continuous line "</span>
<span class="s2">"should match that of the dashed</span><span class="se">\n</span><span class="s2">(reference) line "</span>
<span class="s2">"over at least a few orders of magnitude for h."</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="n">grad</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">riemannian_gradient</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">projected_grad</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">to_tangent_space</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">grad</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">NotImplementedError</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"Pymanopt was unable to verify that the gradient is indeed a "</span>
<span class="sa">f</span><span class="s2">"tangent vector since </span><span class="si">{</span><span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="s2"> does "</span>
<span class="s2">"not provide a 'to_tangent_space' implementation."</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">residual</span> <span class="o">=</span> <span class="n">grad</span> <span class="o">-</span> <span class="n">projected_grad</span>
<span class="n">err</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span><span class="o">.</span><span class="n">norm</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">residual</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"The residual should be 0, or very close. Residual: </span><span class="si">{</span><span class="n">err</span><span class="si">:</span><span class="s2">g</span><span class="si">}</span><span class="s2">."</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"If it is far from 0, then the gradient "</span>
<span class="s2">"is not in the tangent space."</span>
<span class="p">)</span></div>
<div class="viewcode-block" id="check_retraction"><a class="viewcode-back" href="../../../tools.html#pymanopt.tools.diagnostics.check_retraction">[docs]</a><span class="k">def</span> <span class="nf">check_retraction</span><span class="p">(</span><span class="n">manifold</span><span class="p">,</span> <span class="n">point</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">tangent_vector</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""Check order of agreement between a retraction and the exponential."""</span>
<span class="k">if</span> <span class="n">point</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">point</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">random_point</span><span class="p">()</span>
<span class="n">tangent_vector</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">random_tangent_vector</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">tangent_vector</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">tangent_vector</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">random_tangent_vector</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="n">manifold_class</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">manifold</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">point</span><span class="p">,</span> <span class="n">tangent_vector</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">NotImplementedError</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"The manifold '</span><span class="si">{</span><span class="n">manifold_class</span><span class="si">}</span><span class="s2">' provides no exponential map as "</span>
<span class="s2">"reference to compare the retraction."</span>
<span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">manifold</span><span class="o">.</span><span class="n">retraction</span><span class="p">(</span><span class="n">point</span><span class="p">,</span> <span class="n">tangent_vector</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">NotImplementedError</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"The manifold '</span><span class="si">{</span><span class="n">manifold_class</span><span class="si">}</span><span class="s2">' provides no retraction."</span>
<span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">manifold</span><span class="o">.</span><span class="n">retraction</span><span class="p">(</span><span class="n">point</span><span class="p">,</span> <span class="n">tangent_vector</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">NotImplementedError</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"This manifold '</span><span class="si">{</span><span class="n">manifold_class</span><span class="si">}</span><span class="s2">'provides no distance map which "</span>
<span class="s2">"is required to run this check."</span>
<span class="p">)</span>
<span class="c1"># Compare the retraction and the exponential over steps of varying</span>
<span class="c1"># length, on a wide log-scale.</span>
<span class="n">step_sizes</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logspace</span><span class="p">(</span><span class="o">-</span><span class="mi">12</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">251</span><span class="p">)</span>
<span class="n">errors</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">step_sizes</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">step_size</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">step_sizes</span><span class="p">):</span>
<span class="n">errors</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">dist</span><span class="p">(</span>
<span class="n">manifold</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">point</span><span class="p">,</span> <span class="n">step_size</span> <span class="o">*</span> <span class="n">tangent_vector</span><span class="p">),</span>
<span class="n">manifold</span><span class="o">.</span><span class="n">retraction</span><span class="p">(</span><span class="n">point</span><span class="p">,</span> <span class="n">step_size</span> <span class="o">*</span> <span class="n">tangent_vector</span><span class="p">),</span>
<span class="p">)</span>
<span class="c1"># Figure out the slope of the error in log-log, by identifying a piece of</span>
<span class="c1"># the error curve which is mostly linear.</span>
<span class="n">window_length</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">segment</span><span class="p">,</span> <span class="n">poly</span> <span class="o">=</span> <span class="n">identify_linear_piece</span><span class="p">(</span>
<span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">step_sizes</span><span class="p">),</span> <span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">errors</span><span class="p">),</span> <span class="n">window_length</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"The slope must be at least 2 to have a proper retraction.</span><span class="se">\n</span><span class="s2">"</span>
<span class="s2">"For the retraction to be second order, the slope should be 3.</span><span class="se">\n</span><span class="s2">"</span>
<span class="sa">f</span><span class="s2">"It appears the slope is: </span><span class="si">{</span><span class="n">poly</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="si">}</span><span class="s2">.</span><span class="se">\n</span><span class="s2">"</span>
<span class="s2">"Note: if the implementation of the exponential map and the</span><span class="se">\n</span><span class="s2">"</span>
<span class="s2">"retraction are identical, this should be zero: "</span>
<span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">norm</span><span class="p">(</span><span class="n">errors</span><span class="p">)</span><span class="si">}</span><span class="s2">.</span><span class="se">\n</span><span class="s2">"</span>
<span class="s2">"In that case, the slope test is irrelevant."</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="c1"># Plot the difference between the exponential and the retraction over that</span>
<span class="c1"># span of steps on a doubly-logarithmic scale.</span>
<span class="n">plt</span><span class="o">.</span><span class="n">loglog</span><span class="p">(</span><span class="n">step_sizes</span><span class="p">,</span> <span class="n">errors</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span>
<span class="p">[</span><span class="mf">1e-12</span><span class="p">,</span> <span class="mf">1e0</span><span class="p">],</span> <span class="p">[</span><span class="mf">1e-30</span><span class="p">,</span> <span class="mf">1e6</span><span class="p">],</span> <span class="n">linestyle</span><span class="o">=</span><span class="s2">"--"</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s2">"k"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"Slope 3"</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span>
<span class="p">[</span><span class="mf">1e-14</span><span class="p">,</span> <span class="mf">1e0</span><span class="p">],</span> <span class="p">[</span><span class="mf">1e-20</span><span class="p">,</span> <span class="mf">1e8</span><span class="p">],</span> <span class="n">linestyle</span><span class="o">=</span><span class="s2">":"</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s2">"k"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"Slope 2"</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="o">.</span><span class="n">loglog</span><span class="p">(</span>
<span class="n">step_sizes</span><span class="p">[</span><span class="n">segment</span><span class="p">],</span>
<span class="mi">10</span> <span class="o">**</span> <span class="n">np</span><span class="o">.</span><span class="n">polyval</span><span class="p">(</span><span class="n">poly</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">step_sizes</span><span class="p">[</span><span class="n">segment</span><span class="p">])),</span>
<span class="n">linewidth</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s2">"Step size multiplier t"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s2">"Distance between exp(x, v, t) and retraction(x, v, t)"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span>
<span class="s2">"Retraction check.</span><span class="se">\n</span><span class="s2">A slope of 2 is required for a valid retraction, "</span>
<span class="s2">"3 is desired."</span>
<span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span></div>
</pre></div>
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>© Copyright 2016-2023, <NAME>, <NAME>, <NAME>.
<span class="lastupdated">Last updated on Apr 04, 2023.
</span></p>
</div>
</footer>
</div>
</div>
</section>
</div>
<div class="rst-versions" data-toggle="rst-versions" role="note" aria-label="versions">
<span class="rst-current-version" data-toggle="rst-current-version">
<span class="fa fa-book"> Other Versions</span>
v: stable
<span class="fa fa-caret-down"></span>
</span>
<div class="rst-other-versions">
<dl>
<dt>Versions</dt>
<dd><a href="/docs/stable">stable</a></dd>
<dd><a href="/docs/latest">latest</a></dd>
</dl>
</div>
</div><script>
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html><file_sep>/docs/latest/_modules/pymanopt/optimizers/trust_regions.html
<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>pymanopt.optimizers.trust_regions — Pymanopt latest (2.1.2.dev93+gacb52b2) documentation</title>
<link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/css/style.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.1/dist/katex.min.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/katex-math.css" type="text/css" />
<link rel="canonical" href="pymanopt.org/_modules/pymanopt/optimizers/trust_regions.html" />
<!--[if lt IE 9]>
<script src="../../../_static/js/html5shiv.min.js"></script>
<![endif]-->
<script data-url_root="../../../" id="documentation_options" src="../../../_static/documentation_options.js"></script>
<script src="../../../_static/jquery.js"></script>
<script src="../../../_static/underscore.js"></script>
<script src="../../../_static/doctools.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.15.1/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.15.1/dist/contrib/auto-render.min.js"></script>
<script src="../../../_static/katex_autorenderer.js"></script>
<script crossorigin="anonymous" integrity="<KEY> src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script src="../../../_static/js/theme.js"></script>
<link rel="index" title="Index" href="../../../genindex.html" />
<link rel="search" title="Search" href="../../../search.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" >
<a href="../../../index.html" class="icon icon-home"> Pymanopt
<img src="../../../_static/logo.png" class="logo" alt="Logo"/>
</a>
<div class="version">
latest (2.1.2.dev93+gacb52b2)
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<p class="caption" role="heading"><span class="caption-text">Getting Started</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../quickstart.html">Quickstart</a></li>
<li class="toctree-l1"><a class="reference external" href="https://github.com/pymanopt/pymanopt/tree/master/examples">Examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../api-reference.html">API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../CONTRIBUTING.html">Contributing</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">Notebooks</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../examples/notebooks/mixture_of_gaussians.html">Riemannian Optimization for Inference in MoG models</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../../index.html">Pymanopt</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../../index.html" class="icon icon-home"></a> »</li>
<li><a href="../../index.html">Module code</a> »</li>
<li>pymanopt.optimizers.trust_regions</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<h1>Source code for pymanopt.optimizers.trust_regions</h1><div class="highlight"><pre>
<span></span><span class="c1"># References, taken from trustregions.m in manopt:</span>
<span class="c1"># Please cite the Manopt paper as well as the research paper:</span>
<span class="c1"># @Article{genrtr,</span>
<span class="c1"># Title = {Trust-region methods on {Riemannian} manifolds},</span>
<span class="c1"># Author = {<NAME>. and <NAME>. and <NAME>.},</span>
<span class="c1"># Journal = {Foundations of Computational Mathematics},</span>
<span class="c1"># Year = {2007},</span>
<span class="c1"># Number = {3},</span>
<span class="c1"># Pages = {303--330},</span>
<span class="c1"># Volume = {7},</span>
<span class="c1"># Doi = {10.1007/s10208-005-0179-9}</span>
<span class="c1"># }</span>
<span class="c1">#</span>
<span class="c1"># See also: steepestdescent conjugategradient manopt/examples</span>
<span class="c1"># An explicit, general listing of this algorithm, with preconditioning,</span>
<span class="c1"># can be found in the following paper:</span>
<span class="c1"># @Article{boumal2015lowrank,</span>
<span class="c1"># Title = {Low-rank matrix completion via preconditioned optimization</span>
<span class="c1"># on the {G}rassmann manifold},</span>
<span class="c1"># Author = {<NAME>. and <NAME>.},</span>
<span class="c1"># Journal = {Linear Algebra and its Applications},</span>
<span class="c1"># Year = {2015},</span>
<span class="c1"># Pages = {200--239},</span>
<span class="c1"># Volume = {475},</span>
<span class="c1"># Doi = {10.1016/j.laa.2015.02.027},</span>
<span class="c1"># }</span>
<span class="c1"># When the Hessian is not specified, it is approximated with</span>
<span class="c1"># finite-differences of the gradient. The resulting method is called</span>
<span class="c1"># RTR-FD. Some convergence theory for it is available in this paper:</span>
<span class="c1"># @incollection{boumal2015rtrfd</span>
<span class="c1"># author={<NAME>.},</span>
<span class="c1"># title={Riemannian trust regions with finite-difference Hessian</span>
<span class="c1"># approximations are globally convergent},</span>
<span class="c1"># year={2015},</span>
<span class="c1"># booktitle={Geometric Science of Information}</span>
<span class="c1"># }</span>
<span class="c1"># This file is part of Manopt: www.manopt.org.</span>
<span class="c1"># This code is an adaptation to Manopt of the original GenRTR code:</span>
<span class="c1"># RTR - Riemannian Trust-Region</span>
<span class="c1"># (c) 2004-2007, <NAME>, <NAME>, <NAME></span>
<span class="c1"># Florida State University</span>
<span class="c1"># School of Computational Science</span>
<span class="c1"># (http://www.math.fsu.edu/~cbaker/GenRTR/?page=download)</span>
<span class="c1"># See accompanying license file.</span>
<span class="c1"># The adaptation was executed by <NAME>.</span>
<span class="c1"># Ported to pymanopt by <NAME>. January 2016.</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">pymanopt.optimizers.optimizer</span> <span class="kn">import</span> <span class="n">Optimizer</span><span class="p">,</span> <span class="n">OptimizerResult</span>
<div class="viewcode-block" id="TrustRegions"><a class="viewcode-back" href="../../../optimizers.html#pymanopt.optimizers.trust_regions.TrustRegions">[docs]</a><span class="k">class</span> <span class="nc">TrustRegions</span><span class="p">(</span><span class="n">Optimizer</span><span class="p">):</span>
<span class="p">(</span>
<span class="n">NEGATIVE_CURVATURE</span><span class="p">,</span>
<span class="n">EXCEEDED_TR</span><span class="p">,</span>
<span class="n">REACHED_TARGET_LINEAR</span><span class="p">,</span>
<span class="n">REACHED_TARGET_SUPERLINEAR</span><span class="p">,</span>
<span class="n">MAX_INNER_ITER</span><span class="p">,</span>
<span class="n">MODEL_INCREASED</span><span class="p">,</span>
<span class="p">)</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="n">TCG_STOP_REASONS</span> <span class="o">=</span> <span class="p">{</span>
<span class="n">NEGATIVE_CURVATURE</span><span class="p">:</span> <span class="s2">"negative curvature"</span><span class="p">,</span>
<span class="n">EXCEEDED_TR</span><span class="p">:</span> <span class="s2">"exceeded trust region"</span><span class="p">,</span>
<span class="n">REACHED_TARGET_LINEAR</span><span class="p">:</span> <span class="s2">"reached target residual-kappa (linear)"</span><span class="p">,</span>
<span class="n">REACHED_TARGET_SUPERLINEAR</span><span class="p">:</span> <span class="s2">"reached target residual-theta "</span>
<span class="s2">"(superlinear)"</span><span class="p">,</span>
<span class="n">MAX_INNER_ITER</span><span class="p">:</span> <span class="s2">"maximum inner iterations"</span><span class="p">,</span>
<span class="n">MODEL_INCREASED</span><span class="p">:</span> <span class="s2">"model increased"</span><span class="p">,</span>
<span class="p">}</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">miniter</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span>
<span class="n">kappa</span><span class="o">=</span><span class="mf">0.1</span><span class="p">,</span>
<span class="n">theta</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span>
<span class="n">rho_prime</span><span class="o">=</span><span class="mf">0.1</span><span class="p">,</span>
<span class="n">use_rand</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
<span class="n">rho_regularization</span><span class="o">=</span><span class="mf">1e3</span><span class="p">,</span>
<span class="o">*</span><span class="n">args</span><span class="p">,</span>
<span class="o">**</span><span class="n">kwargs</span><span class="p">,</span>
<span class="p">):</span>
<span class="w"> </span><span class="sd">"""Riemannian Trust-Regions algorithm.</span>
<span class="sd"> Second-order method that approximates the objective function by a</span>
<span class="sd"> quadratic surface and then updates the current estimate based on that.</span>
<span class="sd"> Also included is the truncated (Steihaug-Toint) conjugate gradient</span>
<span class="sd"> algorithm.</span>
<span class="sd"> """</span>
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">miniter</span> <span class="o">=</span> <span class="n">miniter</span>
<span class="bp">self</span><span class="o">.</span><span class="n">kappa</span> <span class="o">=</span> <span class="n">kappa</span>
<span class="bp">self</span><span class="o">.</span><span class="n">theta</span> <span class="o">=</span> <span class="n">theta</span>
<span class="bp">self</span><span class="o">.</span><span class="n">rho_prime</span> <span class="o">=</span> <span class="n">rho_prime</span>
<span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span> <span class="o">=</span> <span class="n">use_rand</span>
<span class="bp">self</span><span class="o">.</span><span class="n">rho_regularization</span> <span class="o">=</span> <span class="n">rho_regularization</span>
<div class="viewcode-block" id="TrustRegions.run"><a class="viewcode-back" href="../../../optimizers.html#pymanopt.optimizers.trust_regions.TrustRegions.run">[docs]</a> <span class="k">def</span> <span class="nf">run</span><span class="p">(</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">problem</span><span class="p">,</span>
<span class="o">*</span><span class="p">,</span>
<span class="n">initial_point</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">mininner</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
<span class="n">maxinner</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">Delta_bar</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">Delta0</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="p">)</span> <span class="o">-></span> <span class="n">OptimizerResult</span><span class="p">:</span>
<span class="n">manifold</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span>
<span class="k">if</span> <span class="n">maxinner</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">maxinner</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">dim</span>
<span class="c1"># Set default Delta_bar and Delta0 separately to deal with additional</span>
<span class="c1"># logic: if Delta_bar is provided but not Delta0, let Delta0</span>
<span class="c1"># automatically be some fraction of the provided Delta_bar.</span>
<span class="k">if</span> <span class="n">Delta_bar</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">Delta_bar</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">typical_dist</span>
<span class="k">except</span> <span class="ne">NotImplementedError</span><span class="p">:</span>
<span class="n">Delta_bar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">manifold</span><span class="o">.</span><span class="n">dim</span><span class="p">)</span>
<span class="k">if</span> <span class="n">Delta0</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">Delta0</span> <span class="o">=</span> <span class="n">Delta_bar</span> <span class="o">/</span> <span class="mi">8</span>
<span class="n">cost</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">cost</span>
<span class="n">gradient</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">riemannian_gradient</span>
<span class="n">hess</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">riemannian_hessian</span>
<span class="c1"># If no starting point is specified, generate one at random.</span>
<span class="k">if</span> <span class="n">initial_point</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">random_point</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">initial_point</span>
<span class="c1"># Initializations</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="c1"># Number of outer (TR) iterations. The semantic is that `iteration`</span>
<span class="c1"># counts the number of iterations fully executed so far.</span>
<span class="n">iteration</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># Initialize solution and companion measures: f(x), fgrad(x)</span>
<span class="n">fx</span> <span class="o">=</span> <span class="n">cost</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">fgradx</span> <span class="o">=</span> <span class="n">gradient</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">norm_grad</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">norm</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">)</span>
<span class="c1"># Initialize the trust region radius</span>
<span class="n">Delta</span> <span class="o">=</span> <span class="n">Delta0</span>
<span class="c1"># To keep track of consecutive radius changes, so that we can warn the</span>
<span class="c1"># user if it appears necessary.</span>
<span class="n">consecutive_TRplus</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">consecutive_TRminus</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># ** Display:</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">>=</span> <span class="mi">1</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Optimizing..."</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">>=</span> <span class="mi">2</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="s1">' '</span><span class="si">:</span><span class="s2">44s</span><span class="si">}</span><span class="s2">f: </span><span class="si">{</span><span class="n">fx</span><span class="si">:</span><span class="s2">+.6e</span><span class="si">}</span><span class="s2"> |grad|: </span><span class="si">{</span><span class="n">norm_grad</span><span class="si">:</span><span class="s2">.6e</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_initialize_log</span><span class="p">()</span>
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="n">iteration</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="c1"># *************************</span>
<span class="c1"># ** Begin TR Subproblem **</span>
<span class="c1"># *************************</span>
<span class="c1"># Determine eta0</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span>
<span class="c1"># Pick the zero vector</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">zero_vector</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># Random vector in T_x M (this has to be very small)</span>
<span class="n">eta</span> <span class="o">=</span> <span class="mf">1e-6</span> <span class="o">*</span> <span class="n">manifold</span><span class="o">.</span><span class="n">random_tangent_vector</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="c1"># Must be inside trust region</span>
<span class="k">while</span> <span class="n">manifold</span><span class="o">.</span><span class="n">norm</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">)</span> <span class="o">></span> <span class="n">Delta</span><span class="p">:</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">spacing</span><span class="p">(</span><span class="mi">1</span><span class="p">)))</span> <span class="o">*</span> <span class="n">eta</span>
<span class="c1"># Solve TR subproblem approximately</span>
<span class="n">eta</span><span class="p">,</span> <span class="n">Heta</span><span class="p">,</span> <span class="n">numit</span><span class="p">,</span> <span class="n">stop_inner</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_truncated_conjugate_gradient</span><span class="p">(</span>
<span class="n">problem</span><span class="p">,</span>
<span class="n">x</span><span class="p">,</span>
<span class="n">fgradx</span><span class="p">,</span>
<span class="n">eta</span><span class="p">,</span>
<span class="n">Delta</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">theta</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">kappa</span><span class="p">,</span>
<span class="n">mininner</span><span class="p">,</span>
<span class="n">maxinner</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">srstr</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">TCG_STOP_REASONS</span><span class="p">[</span><span class="n">stop_inner</span><span class="p">]</span>
<span class="c1"># If using randomized approach, compare result with the Cauchy</span>
<span class="c1"># point. Convergence proofs assume that we achieve at least (a</span>
<span class="c1"># fraction of) the reduction of the Cauchy point. After this</span>
<span class="c1"># if-block, either all eta-related quantities have been changed</span>
<span class="c1"># consistently, or none of them have.</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span>
<span class="n">used_cauchy</span> <span class="o">=</span> <span class="kc">False</span>
<span class="c1"># Check the curvature</span>
<span class="n">Hg</span> <span class="o">=</span> <span class="n">hess</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">)</span>
<span class="n">g_Hg</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">,</span> <span class="n">Hg</span><span class="p">)</span>
<span class="k">if</span> <span class="n">g_Hg</span> <span class="o"><=</span> <span class="mi">0</span><span class="p">:</span>
<span class="n">tau_c</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">tau_c</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">norm_grad</span><span class="o">**</span><span class="mi">3</span> <span class="o">/</span> <span class="p">(</span><span class="n">Delta</span> <span class="o">*</span> <span class="n">g_Hg</span><span class="p">),</span> <span class="mi">1</span><span class="p">)</span>
<span class="c1"># and generate the Cauchy point.</span>
<span class="n">eta_c</span> <span class="o">=</span> <span class="o">-</span><span class="n">tau_c</span> <span class="o">*</span> <span class="n">Delta</span> <span class="o">/</span> <span class="n">norm_grad</span> <span class="o">*</span> <span class="n">fgradx</span>
<span class="n">Heta_c</span> <span class="o">=</span> <span class="o">-</span><span class="n">tau_c</span> <span class="o">*</span> <span class="n">Delta</span> <span class="o">/</span> <span class="n">norm_grad</span> <span class="o">*</span> <span class="n">Hg</span>
<span class="c1"># Now that we have computed the Cauchy point in addition to the</span>
<span class="c1"># returned eta, we might as well keep the best of them.</span>
<span class="n">mdle</span> <span class="o">=</span> <span class="p">(</span>
<span class="n">fx</span>
<span class="o">+</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">,</span> <span class="n">eta</span><span class="p">)</span>
<span class="o">+</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">Heta</span><span class="p">,</span> <span class="n">eta</span><span class="p">)</span>
<span class="p">)</span>
<span class="n">mdlec</span> <span class="o">=</span> <span class="p">(</span>
<span class="n">fx</span>
<span class="o">+</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">,</span> <span class="n">eta_c</span><span class="p">)</span>
<span class="o">+</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">Heta_c</span><span class="p">,</span> <span class="n">eta_c</span><span class="p">)</span>
<span class="p">)</span>
<span class="k">if</span> <span class="n">mdlec</span> <span class="o"><</span> <span class="n">mdle</span><span class="p">:</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">eta_c</span>
<span class="n">Heta</span> <span class="o">=</span> <span class="n">Heta_c</span>
<span class="n">used_cauchy</span> <span class="o">=</span> <span class="kc">True</span>
<span class="c1"># This is only computed for logging purposes, because it may be</span>
<span class="c1"># useful for some user-defined stopping criteria. If this is not</span>
<span class="c1"># cheap for specific applications (compared to evaluating the</span>
<span class="c1"># cost), we should reconsider this.</span>
<span class="c1"># norm_eta = manifold.norm(x, eta)</span>
<span class="c1"># Compute the tentative next iterate (the proposal)</span>
<span class="n">x_prop</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">retraction</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">)</span>
<span class="c1"># Compute the function value of the proposal</span>
<span class="n">fx_prop</span> <span class="o">=</span> <span class="n">cost</span><span class="p">(</span><span class="n">x_prop</span><span class="p">)</span>
<span class="c1"># Will we accept the proposal or not? Check the performance of the</span>
<span class="c1"># quadratic model against the actual cost.</span>
<span class="n">rhonum</span> <span class="o">=</span> <span class="n">fx</span> <span class="o">-</span> <span class="n">fx_prop</span>
<span class="n">rhoden</span> <span class="o">=</span> <span class="o">-</span><span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span>
<span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">,</span> <span class="n">eta</span>
<span class="p">)</span> <span class="o">-</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">,</span> <span class="n">Heta</span><span class="p">)</span>
<span class="c1"># rhonum could be anything.</span>
<span class="c1"># rhoden should be nonnegative, as guaranteed by tCG, baring</span>
<span class="c1"># numerical errors.</span>
<span class="c1"># Heuristic -- added Dec. 2, 2013 (NB) to replace the former</span>
<span class="c1"># heuristic. This heuristic is documented in the book by <NAME></span>
<span class="c1"># and Toint on trust-region methods, section 17.4.2. rhonum</span>
<span class="c1"># measures the difference between two numbers. Close to</span>
<span class="c1"># convergence, these two numbers are very close to each other, so</span>
<span class="c1"># that computing their difference is numerically challenging: there</span>
<span class="c1"># may be a significant loss in accuracy. Since the acceptance or</span>
<span class="c1"># rejection of the step is conditioned on the ratio between rhonum</span>
<span class="c1"># and rhoden, large errors in rhonum result in a very large error</span>
<span class="c1"># in rho, hence in erratic acceptance / rejection. Meanwhile, close</span>
<span class="c1"># to convergence, steps are usually trustworthy and we should</span>
<span class="c1"># transition to a Newton- like method, with rho=1 consistently. The</span>
<span class="c1"># heuristic thus shifts both rhonum and rhoden by a small amount</span>
<span class="c1"># such that far from convergence, the shift is irrelevant and close</span>
<span class="c1"># to convergence, the ratio rho goes to 1, effectively promoting</span>
<span class="c1"># acceptance of the step. The rationale is that close to</span>
<span class="c1"># convergence, both rhonum and rhoden are quadratic in the distance</span>
<span class="c1"># between x and x_prop. Thus, when this distance is on the order of</span>
<span class="c1"># sqrt(eps), the value of rhonum and rhoden is on the order of eps,</span>
<span class="c1"># which is indistinguishable from the numerical error, resulting in</span>
<span class="c1"># badly estimated rho's.</span>
<span class="c1"># For abs(fx) < 1, this heuristic is invariant under offsets of f</span>
<span class="c1"># but not under scaling of f. For abs(fx) > 1, the opposite holds.</span>
<span class="c1"># This should not alarm us, as this heuristic only triggers at the</span>
<span class="c1"># very last iterations if very fine convergence is demanded.</span>
<span class="n">rho_reg</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">abs</span><span class="p">(</span><span class="n">fx</span><span class="p">))</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">spacing</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">rho_regularization</span>
<span class="n">rhonum</span> <span class="o">=</span> <span class="n">rhonum</span> <span class="o">+</span> <span class="n">rho_reg</span>
<span class="n">rhoden</span> <span class="o">=</span> <span class="n">rhoden</span> <span class="o">+</span> <span class="n">rho_reg</span>
<span class="c1"># This is always true if a linear, symmetric operator is used for</span>
<span class="c1"># the Hessian (approximation) and if we had infinite numerical</span>
<span class="c1"># precision. In practice, nonlinear approximations of the Hessian</span>
<span class="c1"># such as the built-in finite difference approximation and finite</span>
<span class="c1"># numerical accuracy can cause the model to increase. In such</span>
<span class="c1"># scenarios, we decide to force a rejection of the step and a</span>
<span class="c1"># reduction of the trust-region radius. We test the sign of the</span>
<span class="c1"># regularized rhoden since the regularization is supposed to</span>
<span class="c1"># capture the accuracy to which rhoden is computed: if rhoden were</span>
<span class="c1"># negative before regularization but not after, that should not be</span>
<span class="c1"># (and is not) detected as a failure.</span>
<span class="c1">#</span>
<span class="c1"># Note (Feb. 17, 2015, NB): the most recent version of tCG already</span>
<span class="c1"># includes a mechanism to ensure model decrease if the Cauchy step</span>
<span class="c1"># attained a decrease (which is theoretically the case under very</span>
<span class="c1"># lax assumptions). This being said, it is always possible that</span>
<span class="c1"># numerical errors will prevent this, so that it is good to keep a</span>
<span class="c1"># safeguard.</span>
<span class="c1">#</span>
<span class="c1"># The current strategy is that, if this should happen, then we</span>
<span class="c1"># reject the step and reduce the trust region radius. This also</span>
<span class="c1"># ensures that the actual cost values are monotonically decreasing.</span>
<span class="n">model_decreased</span> <span class="o">=</span> <span class="n">rhoden</span> <span class="o">>=</span> <span class="mi">0</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">model_decreased</span><span class="p">:</span>
<span class="n">srstr</span> <span class="o">=</span> <span class="n">srstr</span> <span class="o">+</span> <span class="s2">", model did not decrease"</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">rho</span> <span class="o">=</span> <span class="n">rhonum</span> <span class="o">/</span> <span class="n">rhoden</span>
<span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
<span class="c1"># Added June 30, 2015 following observation by BM. With this</span>
<span class="c1"># modification, it is guaranteed that a step rejection is</span>
<span class="c1"># always accompanied by a TR reduction. This prevents</span>
<span class="c1"># stagnation in this "corner case" (NaN's really aren't</span>
<span class="c1"># supposed to occur, but it's nice if we can handle them</span>
<span class="c1"># nonetheless).</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">"rho is NaN! Forcing a radius decrease. This should "</span>
<span class="s2">"not happen."</span>
<span class="p">)</span>
<span class="n">rho</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">nan</span>
<span class="c1"># Choose the new TR radius based on the model performance</span>
<span class="n">trstr</span> <span class="o">=</span> <span class="s2">" "</span>
<span class="c1"># If the actual decrease is smaller than 1/4 of the predicted</span>
<span class="c1"># decrease, then reduce the TR radius.</span>
<span class="k">if</span> <span class="n">rho</span> <span class="o"><</span> <span class="mf">1.0</span> <span class="o">/</span> <span class="mi">4</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">model_decreased</span> <span class="ow">or</span> <span class="n">np</span><span class="o">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">rho</span><span class="p">):</span>
<span class="n">trstr</span> <span class="o">=</span> <span class="s2">"TR-"</span>
<span class="n">Delta</span> <span class="o">=</span> <span class="n">Delta</span> <span class="o">/</span> <span class="mi">4</span>
<span class="n">consecutive_TRplus</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">consecutive_TRminus</span> <span class="o">=</span> <span class="n">consecutive_TRminus</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">if</span> <span class="n">consecutive_TRminus</span> <span class="o">>=</span> <span class="mi">5</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">>=</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">consecutive_TRminus</span> <span class="o">=</span> <span class="o">-</span><span class="n">np</span><span class="o">.</span><span class="n">inf</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">" +++ Detected many consecutive TR- (radius "</span>
<span class="s2">"decreases)."</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">" +++ Consider decreasing options.Delta_bar "</span>
<span class="s2">"by an order of magnitude."</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">" +++ Current values: Delta_bar = </span><span class="si">{</span><span class="n">Delta_bar</span><span class="si">:</span><span class="s2">g</span><span class="si">}</span><span class="s2"> "</span>
<span class="sa">f</span><span class="s2">"and Delta0 = </span><span class="si">{</span><span class="n">Delta0</span><span class="si">:</span><span class="s2">g</span><span class="si">}</span><span class="s2">"</span>
<span class="p">)</span>
<span class="c1"># If the actual decrease is at least 3/4 of the precicted decrease</span>
<span class="c1"># and the tCG (inner solve) hit the TR boundary, increase the TR</span>
<span class="c1"># radius. We also keep track of the number of consecutive</span>
<span class="c1"># trust-region radius increases. If there are many, this may</span>
<span class="c1"># indicate the need to adapt the initial and maximum radii.</span>
<span class="k">elif</span> <span class="n">rho</span> <span class="o">></span> <span class="mf">3.0</span> <span class="o">/</span> <span class="mi">4</span> <span class="ow">and</span> <span class="p">(</span>
<span class="n">stop_inner</span> <span class="ow">in</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">NEGATIVE_CURVATURE</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">EXCEEDED_TR</span><span class="p">)</span>
<span class="p">):</span>
<span class="n">trstr</span> <span class="o">=</span> <span class="s2">"TR+"</span>
<span class="n">Delta</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="mi">2</span> <span class="o">*</span> <span class="n">Delta</span><span class="p">,</span> <span class="n">Delta_bar</span><span class="p">)</span>
<span class="n">consecutive_TRminus</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">consecutive_TRplus</span> <span class="o">=</span> <span class="n">consecutive_TRplus</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">if</span> <span class="n">consecutive_TRplus</span> <span class="o">>=</span> <span class="mi">5</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">>=</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">consecutive_TRplus</span> <span class="o">=</span> <span class="o">-</span><span class="n">np</span><span class="o">.</span><span class="n">inf</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">" +++ Detected many consecutive TR+ (radius "</span>
<span class="s2">"increases)."</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="s2">" +++ Consider increasing options.Delta_bar "</span>
<span class="s2">"by an order of magnitude."</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">" +++ Current values: Delta_bar = </span><span class="si">{</span><span class="n">Delta_bar</span><span class="si">:</span><span class="s2">g</span><span class="si">}</span><span class="s2"> "</span>
<span class="sa">f</span><span class="s2">"and Delta0 = </span><span class="si">{</span><span class="n">Delta0</span><span class="si">:</span><span class="s2">g</span><span class="si">}</span><span class="s2">."</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># Otherwise, keep the TR radius constant.</span>
<span class="n">consecutive_TRplus</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">consecutive_TRminus</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># Choose to accept or reject the proposed step based on the model</span>
<span class="c1"># performance. Note the strict inequality.</span>
<span class="k">if</span> <span class="n">model_decreased</span> <span class="ow">and</span> <span class="n">rho</span> <span class="o">></span> <span class="bp">self</span><span class="o">.</span><span class="n">rho_prime</span><span class="p">:</span>
<span class="c1"># accept = True</span>
<span class="n">accstr</span> <span class="o">=</span> <span class="s2">"acc"</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">x_prop</span>
<span class="n">fx</span> <span class="o">=</span> <span class="n">fx_prop</span>
<span class="n">fgradx</span> <span class="o">=</span> <span class="n">gradient</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">norm_grad</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">norm</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># accept = False</span>
<span class="n">accstr</span> <span class="o">=</span> <span class="s2">"REJ"</span>
<span class="c1"># ** Display:</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">accstr</span><span class="si">:</span><span class="s2">.3s</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">trstr</span><span class="si">:</span><span class="s2">.3s</span><span class="si">}</span><span class="s2"> k: </span><span class="si">{</span><span class="n">iteration</span><span class="si">:</span><span class="s2">5d</span><span class="si">}</span><span class="s2"> "</span>
<span class="sa">f</span><span class="s2">"num_inner: </span><span class="si">{</span><span class="n">numit</span><span class="si">:</span><span class="s2">5d</span><span class="si">}</span><span class="s2"> f: </span><span class="si">{</span><span class="n">fx</span><span class="si">:</span><span class="s2">+e</span><span class="si">}</span><span class="s2"> |grad|: "</span>
<span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">norm_grad</span><span class="si">:</span><span class="s2">e</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">srstr</span><span class="si">:</span><span class="s2">s</span><span class="si">}</span><span class="s2">"</span>
<span class="p">)</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">></span> <span class="mi">2</span><span class="p">:</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span> <span class="ow">and</span> <span class="n">used_cauchy</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"USED CAUCHY POINT"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">accstr</span><span class="si">:</span><span class="s2">.3s</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">trstr</span><span class="si">:</span><span class="s2">.3s</span><span class="si">}</span><span class="s2"> k: </span><span class="si">{</span><span class="n">iteration</span><span class="si">:</span><span class="s2">5d</span><span class="si">}</span><span class="s2"> "</span>
<span class="sa">f</span><span class="s2">"num_inner: </span><span class="si">{</span><span class="n">numit</span><span class="si">:</span><span class="s2">5d</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">srstr</span><span class="si">:</span><span class="s2">s</span><span class="si">}</span><span class="s2">"</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">" f(x) : </span><span class="si">{</span><span class="n">fx</span><span class="si">:</span><span class="s2">+e</span><span class="si">}</span><span class="s2"> |grad| : </span><span class="si">{</span><span class="n">norm_grad</span><span class="si">:</span><span class="s2">e</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">" rho : </span><span class="si">{</span><span class="n">rho</span><span class="si">:</span><span class="s2">e</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="c1"># ** CHECK STOPPING criteria</span>
<span class="n">stopping_criterion</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_check_stopping_criterion</span><span class="p">(</span>
<span class="n">start_time</span><span class="o">=</span><span class="n">start_time</span><span class="p">,</span>
<span class="n">gradient_norm</span><span class="o">=</span><span class="n">norm_grad</span><span class="p">,</span>
<span class="n">iteration</span><span class="o">=</span><span class="n">iteration</span><span class="p">,</span>
<span class="p">)</span>
<span class="k">if</span> <span class="n">stopping_criterion</span><span class="p">:</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_verbosity</span> <span class="o">>=</span> <span class="mi">1</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">stopping_criterion</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">""</span><span class="p">)</span>
<span class="k">break</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_return_result</span><span class="p">(</span>
<span class="n">start_time</span><span class="o">=</span><span class="n">start_time</span><span class="p">,</span>
<span class="n">point</span><span class="o">=</span><span class="n">x</span><span class="p">,</span>
<span class="n">cost</span><span class="o">=</span><span class="n">fx</span><span class="p">,</span>
<span class="n">iterations</span><span class="o">=</span><span class="n">iteration</span><span class="p">,</span>
<span class="n">stopping_criterion</span><span class="o">=</span><span class="n">stopping_criterion</span><span class="p">,</span>
<span class="n">gradient_norm</span><span class="o">=</span><span class="n">norm_grad</span><span class="p">,</span>
<span class="p">)</span></div>
<span class="k">def</span> <span class="nf">_truncated_conjugate_gradient</span><span class="p">(</span>
<span class="bp">self</span><span class="p">,</span> <span class="n">problem</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">,</span> <span class="n">eta</span><span class="p">,</span> <span class="n">Delta</span><span class="p">,</span> <span class="n">theta</span><span class="p">,</span> <span class="n">kappa</span><span class="p">,</span> <span class="n">mininner</span><span class="p">,</span> <span class="n">maxinner</span>
<span class="p">):</span>
<span class="n">manifold</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">manifold</span>
<span class="n">inner</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">inner_product</span>
<span class="n">hess</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">riemannian_hessian</span>
<span class="n">preconditioner</span> <span class="o">=</span> <span class="n">problem</span><span class="o">.</span><span class="n">preconditioner</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span> <span class="c1"># and therefore, eta == 0</span>
<span class="n">Heta</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">zero_vector</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">fgradx</span>
<span class="n">e_Pe</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">else</span><span class="p">:</span> <span class="c1"># and therefore, no preconditioner</span>
<span class="c1"># eta (presumably) ~= 0 was provided by the caller.</span>
<span class="n">Heta</span> <span class="o">=</span> <span class="n">hess</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">fgradx</span> <span class="o">+</span> <span class="n">Heta</span>
<span class="n">e_Pe</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">,</span> <span class="n">eta</span><span class="p">)</span>
<span class="n">r_r</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">r</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span>
<span class="n">norm_r</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">r_r</span><span class="p">)</span>
<span class="n">norm_r0</span> <span class="o">=</span> <span class="n">norm_r</span>
<span class="c1"># Precondition the residual</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">preconditioner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">r</span>
<span class="c1"># Compute z'*r</span>
<span class="n">z_r</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">z</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span>
<span class="n">d_Pd</span> <span class="o">=</span> <span class="n">z_r</span>
<span class="c1"># Initial search direction</span>
<span class="n">delta</span> <span class="o">=</span> <span class="o">-</span><span class="n">z</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span>
<span class="n">e_Pd</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">e_Pd</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">,</span> <span class="n">delta</span><span class="p">)</span>
<span class="c1"># If the Hessian or a linear Hessian approximation is in use, it is</span>
<span class="c1"># theoretically guaranteed that the model value decreases strictly with</span>
<span class="c1"># each iteration of tCG. Hence, there is no need to monitor the model</span>
<span class="c1"># value. But, when a nonlinear Hessian approximation is used (such as</span>
<span class="c1"># the built-in finite-difference approximation for example), the model</span>
<span class="c1"># may increase. It is then important to terminate the tCG iterations</span>
<span class="c1"># and return the previous (the best-so-far) iterate. The variable below</span>
<span class="c1"># will hold the model value.</span>
<span class="k">def</span> <span class="nf">model_fun</span><span class="p">(</span><span class="n">eta</span><span class="p">,</span> <span class="n">Heta</span><span class="p">):</span>
<span class="k">return</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">,</span> <span class="n">fgradx</span><span class="p">)</span> <span class="o">+</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">eta</span><span class="p">,</span> <span class="n">Heta</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span>
<span class="n">model_value</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">model_value</span> <span class="o">=</span> <span class="n">model_fun</span><span class="p">(</span><span class="n">eta</span><span class="p">,</span> <span class="n">Heta</span><span class="p">)</span>
<span class="c1"># Pre-assume termination because j == end.</span>
<span class="n">stop_tCG</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">MAX_INNER_ITER</span>
<span class="c1"># Begin inner/tCG loop.</span>
<span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">maxinner</span><span class="p">)):</span>
<span class="c1"># This call is the computationally intensive step</span>
<span class="n">Hdelta</span> <span class="o">=</span> <span class="n">hess</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">delta</span><span class="p">)</span>
<span class="c1"># Compute curvature (often called kappa)</span>
<span class="n">d_Hd</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">delta</span><span class="p">,</span> <span class="n">Hdelta</span><span class="p">)</span>
<span class="c1"># Note that if d_Hd == 0, we will exit at the next "if" anyway.</span>
<span class="k">if</span> <span class="n">d_Hd</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
<span class="n">alpha</span> <span class="o">=</span> <span class="n">z_r</span> <span class="o">/</span> <span class="n">d_Hd</span>
<span class="c1"># <neweta,neweta>_P =</span>
<span class="c1"># <eta,eta>_P</span>
<span class="c1"># + 2*alpha*<eta,delta>_P</span>
<span class="c1"># + alpha*alpha*<delta,delta>_P</span>
<span class="n">e_Pe_new</span> <span class="o">=</span> <span class="n">e_Pe</span> <span class="o">+</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">alpha</span> <span class="o">*</span> <span class="n">e_Pd</span> <span class="o">+</span> <span class="n">alpha</span><span class="o">**</span><span class="mi">2</span> <span class="o">*</span> <span class="n">d_Pd</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">e_Pe_new</span> <span class="o">=</span> <span class="n">e_Pe</span>
<span class="c1"># Check against negative curvature and trust-region radius</span>
<span class="c1"># violation. If either condition triggers, we bail out.</span>
<span class="k">if</span> <span class="n">d_Hd</span> <span class="o"><=</span> <span class="mi">0</span> <span class="ow">or</span> <span class="n">e_Pe_new</span> <span class="o">>=</span> <span class="n">Delta</span><span class="o">**</span><span class="mi">2</span><span class="p">:</span>
<span class="c1"># want</span>
<span class="c1"># ee = <eta,eta>_prec,x</span>
<span class="c1"># ed = <eta,delta>_prec,x</span>
<span class="c1"># dd = <delta,delta>_prec,x</span>
<span class="n">tau</span> <span class="o">=</span> <span class="p">(</span>
<span class="o">-</span><span class="n">e_Pd</span> <span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">e_Pd</span> <span class="o">*</span> <span class="n">e_Pd</span> <span class="o">+</span> <span class="n">d_Pd</span> <span class="o">*</span> <span class="p">(</span><span class="n">Delta</span><span class="o">**</span><span class="mi">2</span> <span class="o">-</span> <span class="n">e_Pe</span><span class="p">))</span>
<span class="p">)</span> <span class="o">/</span> <span class="n">d_Pd</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">eta</span> <span class="o">+</span> <span class="n">tau</span> <span class="o">*</span> <span class="n">delta</span>
<span class="c1"># If only a nonlinear Hessian approximation is available, this</span>
<span class="c1"># is only approximately correct, but saves an additional</span>
<span class="c1"># Hessian call.</span>
<span class="n">Heta</span> <span class="o">=</span> <span class="n">Heta</span> <span class="o">+</span> <span class="n">tau</span> <span class="o">*</span> <span class="n">Hdelta</span>
<span class="c1"># Technically, we may want to verify that this new eta is</span>
<span class="c1"># indeed better than the previous eta before returning it (this</span>
<span class="c1"># is always the case if the Hessian approximation is linear,</span>
<span class="c1"># but I am unsure whether it is the case or not for nonlinear</span>
<span class="c1"># approximations.) At any rate, the impact should be limited,</span>
<span class="c1"># so in the interest of code conciseness (if we can still hope</span>
<span class="c1"># for that), we omit this.</span>
<span class="k">if</span> <span class="n">d_Hd</span> <span class="o"><=</span> <span class="mi">0</span><span class="p">:</span>
<span class="n">stop_tCG</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">NEGATIVE_CURVATURE</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">stop_tCG</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">EXCEEDED_TR</span>
<span class="k">break</span>
<span class="c1"># No negative curvature and eta_prop inside TR: accept it.</span>
<span class="n">e_Pe</span> <span class="o">=</span> <span class="n">e_Pe_new</span>
<span class="n">new_eta</span> <span class="o">=</span> <span class="n">eta</span> <span class="o">+</span> <span class="n">alpha</span> <span class="o">*</span> <span class="n">delta</span>
<span class="c1"># If only a nonlinear Hessian approximation is available, this is</span>
<span class="c1"># only approximately correct, but saves an additional Hessian call.</span>
<span class="n">new_Heta</span> <span class="o">=</span> <span class="n">Heta</span> <span class="o">+</span> <span class="n">alpha</span> <span class="o">*</span> <span class="n">Hdelta</span>
<span class="c1"># Verify that the model cost decreased in going from eta to</span>
<span class="c1"># new_eta. If it did not (which can only occur if the Hessian</span>
<span class="c1"># approximation is nonlinear or because of numerical errors), then</span>
<span class="c1"># we return the previous eta (which necessarily is the best reached</span>
<span class="c1"># so far, according to the model cost). Otherwise, we accept the</span>
<span class="c1"># new eta and go on.</span>
<span class="n">new_model_value</span> <span class="o">=</span> <span class="n">model_fun</span><span class="p">(</span><span class="n">new_eta</span><span class="p">,</span> <span class="n">new_Heta</span><span class="p">)</span>
<span class="k">if</span> <span class="n">new_model_value</span> <span class="o">>=</span> <span class="n">model_value</span><span class="p">:</span>
<span class="n">stop_tCG</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">MODEL_INCREASED</span>
<span class="k">break</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">new_eta</span>
<span class="n">Heta</span> <span class="o">=</span> <span class="n">new_Heta</span>
<span class="n">model_value</span> <span class="o">=</span> <span class="n">new_model_value</span>
<span class="c1"># Update the residual.</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">r</span> <span class="o">+</span> <span class="n">alpha</span> <span class="o">*</span> <span class="n">Hdelta</span>
<span class="c1"># Compute new norm of r.</span>
<span class="n">r_r</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">r</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span>
<span class="n">norm_r</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">r_r</span><span class="p">)</span>
<span class="c1"># Check kappa/theta stopping criterion.</span>
<span class="c1"># Note that it is somewhat arbitrary whether to check this stopping</span>
<span class="c1"># criterion on the r's (the gradients) or on the z's (the</span>
<span class="c1"># preconditioned gradients). [CGT2000], page 206, mentions both as</span>
<span class="c1"># acceptable criteria.</span>
<span class="k">if</span> <span class="n">j</span> <span class="o">>=</span> <span class="n">mininner</span> <span class="ow">and</span> <span class="n">norm_r</span> <span class="o"><=</span> <span class="n">norm_r0</span> <span class="o">*</span> <span class="nb">min</span><span class="p">(</span>
<span class="n">norm_r0</span><span class="o">**</span><span class="n">theta</span><span class="p">,</span> <span class="n">kappa</span>
<span class="p">):</span>
<span class="c1"># Residual is small enough to quit</span>
<span class="k">if</span> <span class="n">kappa</span> <span class="o"><</span> <span class="n">norm_r0</span><span class="o">**</span><span class="n">theta</span><span class="p">:</span>
<span class="n">stop_tCG</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">REACHED_TARGET_LINEAR</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">stop_tCG</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">REACHED_TARGET_SUPERLINEAR</span>
<span class="k">break</span>
<span class="c1"># Precondition the residual.</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_rand</span><span class="p">:</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">preconditioner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">r</span>
<span class="c1"># Save the old z'*r.</span>
<span class="n">zold_rold</span> <span class="o">=</span> <span class="n">z_r</span>
<span class="c1"># Compute new z'*r.</span>
<span class="n">z_r</span> <span class="o">=</span> <span class="n">inner</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">z</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span>
<span class="c1"># Compute new search direction</span>
<span class="n">beta</span> <span class="o">=</span> <span class="n">z_r</span> <span class="o">/</span> <span class="n">zold_rold</span>
<span class="n">delta</span> <span class="o">=</span> <span class="o">-</span><span class="n">z</span> <span class="o">+</span> <span class="n">beta</span> <span class="o">*</span> <span class="n">delta</span>
<span class="c1"># Re-tangentialize delta to make sure it remains within the tangent</span>
<span class="c1"># space.</span>
<span class="n">delta</span> <span class="o">=</span> <span class="n">manifold</span><span class="o">.</span><span class="n">to_tangent_space</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">delta</span><span class="p">)</span>
<span class="c1"># Update new P-norms and P-dots [CGT2000, eq. 7.5.6 & 7.5.7].</span>
<span class="n">e_Pd</span> <span class="o">=</span> <span class="n">beta</span> <span class="o">*</span> <span class="p">(</span><span class="n">e_Pd</span> <span class="o">+</span> <span class="n">alpha</span> <span class="o">*</span> <span class="n">d_Pd</span><span class="p">)</span>
<span class="n">d_Pd</span> <span class="o">=</span> <span class="n">z_r</span> <span class="o">+</span> <span class="n">beta</span> <span class="o">*</span> <span class="n">beta</span> <span class="o">*</span> <span class="n">d_Pd</span>
<span class="k">return</span> <span class="n">eta</span><span class="p">,</span> <span class="n">Heta</span><span class="p">,</span> <span class="n">j</span><span class="p">,</span> <span class="n">stop_tCG</span></div>
</pre></div>
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>© Copyright 2016-2023, <NAME>, <NAME>, <NAME>.
<span class="lastupdated">Last updated on Apr 04, 2023.
</span></p>
</div>
</footer>
</div>
</div>
</section>
</div>
<div class="rst-versions" data-toggle="rst-versions" role="note" aria-label="versions">
<span class="rst-current-version" data-toggle="rst-current-version">
<span class="fa fa-book"> Other Versions</span>
v: latest
<span class="fa fa-caret-down"></span>
</span>
<div class="rst-other-versions">
<dl>
<dt>Versions</dt>
<dd><a href="/docs/stable">stable</a></dd>
<dd><a href="/docs/latest">latest</a></dd>
</dl>
</div>
</div><script>
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html> | f95e803c5554371dc256f06b901d610c12f78089 | [
"JavaScript",
"HTML"
] | 3 | JavaScript | pymanopt/pymanopt.github.io | 2223ad44915376abbee214e666eb18853a5eae82 | d619bd3c8f4b4248cd9c81337d72306146f6011c |
refs/heads/master | <repo_name>trinityrnaseq/bamsifter<file_sep>/sift_bam_max_cov.cpp
#include <stdio.h>
// #include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <getopt.h>
#include <stdint.h>
#include <limits.h>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include "htslib/sam.h"
#include "htslib/bgzf.h"
enum test_op {
READ_COMPRESSED = 1,
WRITE_COMPRESSED = 2,
READ_CRAM = 4,
WRITE_CRAM = 8,
WRITE_UNCOMPRESSED = 16,
};
void insert_or_increment(std::map<int32_t, int32_t> & pos_map, int32_t rpos) {
auto it = pos_map.find(rpos);
if (it != pos_map.end()) {
++(it->second);
}
else {
pos_map.insert({rpos, 1});
}
}
void help() {
fprintf(stderr, "Usage: bamsifter [-c max_coverage] [-i max_identical_cigar_pos] [-o out.bam] [--FLAGS] <in.bam>\n");
fprintf(stderr, "\n");
fprintf(stderr, "-c: Max coverage value.\n");
fprintf(stderr, "-o: Output file name. Default is to stdout.\n");
fprintf(stderr, "-i: Max number of reads with an identical cigar starting at the some position to keep.\n");
fprintf(stderr, "--keep_unmapped: keep unmapped reads (0x4 flag). \n");
fprintf(stderr, "--keep_secondary: keep alignments flagged as secondary (0x100 flag).\n");
fprintf(stderr, "--keep_supplementary: keep alignments flagged as supplementary (0x800 flag).\n");
fprintf(stderr, "--keep_chimeric: keep chimeric alignments (SA: tag).\n");
fprintf(stderr, "File to process.\n");
fprintf(stderr, "\n");
}
int main(int argc, char *argv[])
{
samFile *in; // open input alignment file
int flag = 0;
int clevel = -1; // compression level
bam_hdr_t *input_header; // alignment header
htsFile *out;
char modew[800];
int exit_code = 0;
int coverage_limit = 100;
int similar_cigar_limit = INT_MAX;
int keep_unmapped = 0;
int keep_supplementary = 0;
int keep_secondary = 0;
int keep_chimeric = 0;
const char *out_name = "-";
int c; // for parsing input arguments
// add option to keep only "proper pairs" (both reads mapped)
// add option to run strand specificlly
// add option for BAM index loading (+ generation if needed) to be able to run each chromosome on a seperate thread
// while ((c = getopt(argc, argv, "DSIt:i:bCul:o:N:BZ:@:M")) >= 0) {
while (1) {
static struct option long_options[] = {
/* These options set a flag. */
{"keep_unmapped", no_argument, &keep_unmapped, 1},
{"keep_supplementary", no_argument, &keep_supplementary, 1},
{"keep_secondary", no_argument, &keep_secondary, 1},
{"keep_chimeric", no_argument, &keep_chimeric, 1},
/* No flags set. */
{"coverage_limit", required_argument, 0, 'c'},
{"out_name", required_argument, 0, 'o'},
{"similar_cigar_limit", required_argument, 0, 'i'},
{NULL, 0, NULL, 0}
};
int option_index = 0;
c = getopt_long(argc, argv, "c:o:i:", long_options, &option_index);
if (c == -1) {
break;
}
switch (c)
{
case 0:
if (long_options[option_index].flag != 0)
break;
printf("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'c': coverage_limit = atoi(optarg); break;
case 'o': out_name = optarg; break;
case 'i': similar_cigar_limit = atoi(optarg); break;
default:
help();
exit(2);
}
}
if (argc == optind) { // missing input file, print help
help();
return (1);
}
in = sam_open(argv[optind], "r");
const htsFormat *in_format = hts_get_format(in);
// Enable multi-threading (only effective when the library was compiled with -DBGZF_MT)
// bgzf_mt(in, n_threads, 0);
if (in == NULL) {
fprintf(stderr, "Error opening \"%s\"\n", argv[optind]);
return EXIT_FAILURE;
}
input_header = sam_hdr_read(in);
if (input_header == NULL) {
fprintf(stderr, "Couldn't read header for \"%s\"\n", argv[optind]);
return EXIT_FAILURE;
}
// check that sort order (SO) flag is set
std::string tmp_text(input_header->text, input_header->l_text);
size_t start_pos = tmp_text.find("@HD");
if (start_pos == std::string::npos) {
fprintf(stderr, "Error, missing @HD field in header.\n");
return EXIT_FAILURE;
}
size_t end_pos = tmp_text.find("\n", start_pos);
if (end_pos == std::string::npos) {
end_pos = tmp_text.length();
}
tmp_text = tmp_text.substr(start_pos, end_pos - start_pos);
start_pos = tmp_text.find("SO:");
if (start_pos == std::string::npos) {
fprintf(stderr, "Error, missing SO field in @HD header line.\n");
return EXIT_FAILURE;
}
tmp_text.find("coordinate", start_pos);
if (start_pos == std::string::npos) {
fprintf(stderr, "Error, file is not coordinate sorted.\n");
return EXIT_FAILURE;
}
strcpy(modew, "w");
if (clevel >= 0 && clevel <= 9) sprintf(modew + 1, "%d", clevel);
if (flag & WRITE_CRAM) strcat(modew, "c");
else if (flag & WRITE_COMPRESSED) strcat(modew, "b");
else if (flag & WRITE_UNCOMPRESSED) strcat(modew, "bu");
// out = hts_open(out_name, modew);
out = hts_open_format(out_name, modew, in_format);
if (out == NULL) {
fprintf(stderr, "Error opening standard output\n");
return EXIT_FAILURE;
}
if (sam_hdr_write(out, input_header) < 0) { // write header from input to output
fprintf(stderr, "Error writing output header.\n");
exit_code = 1;
}
// map for start/end positions of alignments that are already selected
std::map<int32_t, int32_t> starts;
std::map<int32_t, int32_t> ends;
// keep a set of mate reads we decided to keep when encountering the first read
std::set<std::string> mates_to_keep;
std::map<std::vector<uint32_t>, int> current_cigar_counts;
bam1_t *aln = bam_init1(); //initialize an alignment
int32_t current_rname_index = 0; // index compared to header: input_header->target_name[current_rname_index]
int32_t current_coverage = 0;
bool chimeric_to_keep;
int32_t current_pos = 0;
while(sam_read1(in, input_header, aln) > 0) {
if (current_rname_index != aln->core.tid) {
// should have finished writing reads from current_rname_index contig, so can just reset vars
current_coverage = 0;
starts.clear();
ends.clear();
fprintf(stdout, "Done with chr %s.\n", input_header->target_name[current_rname_index]);
current_rname_index = aln->core.tid;
}
// make sure the read is mapped
if (!keep_unmapped && ((aln->core.flag & BAM_FUNMAP) != 0))
continue;
// check if the read has a chimeric alignement and only keep if asked to
// then check if the alignment is a secondary alignment or a supplementary alignment, and keep only if asked to
chimeric_to_keep = false;
if (keep_chimeric && (bam_aux_get(aln, "SA") != NULL)) {
chimeric_to_keep = true;
}
else if ((!keep_secondary && (aln->core.flag & BAM_FSECONDARY) != 0) || (!keep_supplementary && (aln->core.flag & BAM_FSUPPLEMENTARY) != 0)) // suppl: and not chimeric tag
continue;
if (current_pos != aln->core.pos) { // left most position, does NOT need adjustment for reverse strand if summing their coverage
// add the range we want and then erase all the matching entries at once rather than 1 by 1
auto it = starts.begin();
if (it->first <= aln->core.pos) {
for (; it != starts.end(); ++it) {
if (it->first <= aln->core.pos) { // or equal because already selected reads take priority in coverage
current_coverage += it->second;
}
else break;
}
starts.erase(starts.begin(), it);
}
it = ends.begin();
if (it->first <= aln->core.pos) {
for (; it != ends.end(); ++it) {
if (it->first <= aln->core.pos) { // or equal because already selected reads take priority in coverage
current_coverage -= it->second;
}
else break;
}
ends.erase(ends.begin(), it);
}
current_cigar_counts.clear();
current_pos = aln->core.pos;
}
// if we are below the max coverage or the read has already been selected to keep through its pair or because it is chimeric
if ((current_coverage < coverage_limit) ||
(mates_to_keep.find(bam_get_qname(aln)) != mates_to_keep.end()) ||
chimeric_to_keep) {
// get cigar
uint32_t *cigar = bam_get_cigar(aln);
// check that the cigar
if ((similar_cigar_limit < coverage_limit) && !chimeric_to_keep) {
std::vector<uint32_t> tmp_cigar(aln->core.n_cigar);
std::copy(cigar, cigar + aln->core.n_cigar, tmp_cigar.begin());
auto it = current_cigar_counts.find(tmp_cigar);
if (it != current_cigar_counts.end()) { // found
if (it->second < similar_cigar_limit) {
it->second++;
}
else {
continue;
}
}
else {
current_cigar_counts.emplace(std::move(tmp_cigar), 1);
}
}
int32_t rpos = aln->core.pos; // update position on the ref with cigar
for (uint32_t k = 0; k < aln->core.n_cigar; ++k) {
if ((bam_cigar_type(bam_cigar_op(cigar[k]))&2)) { // consumes reference
if (bam_cigar_op(cigar[k]) == BAM_CREF_SKIP) {
insert_or_increment(ends, rpos);
rpos += bam_cigar_oplen(cigar[k]);
insert_or_increment(starts, rpos);
}
else {
rpos += bam_cigar_oplen(cigar[k]);
}
}
}
insert_or_increment(ends, rpos);
++current_coverage;
// save pair mate
mates_to_keep.insert(bam_get_qname(aln));
}
}
int ret;
// close and reopen input file to seek to start regardless of compression
ret = hts_close(in);
if (ret < 0) {
fprintf(stderr, "Error closing input.\n");
exit_code = EXIT_FAILURE;
}
in = sam_open(argv[optind], "r");
input_header = sam_hdr_read(in);
if (input_header == NULL) {
fprintf(stderr, "Couldn't read header for \"%s\"\n", argv[optind]);
return EXIT_FAILURE;
}
while (sam_read1(in, input_header, aln) > 0) {
// output the alignment
if (mates_to_keep.find(bam_get_qname(aln)) != mates_to_keep.end()) {
if (sam_write1(out, input_header, aln) == -1) {
fprintf(stderr, "Could not write selected record \"%s\"\n", bam_get_qname(aln));
return EXIT_FAILURE;
}
}
}
ret = hts_close(in);
if (ret < 0) {
fprintf(stderr, "Error closing input.\n");
exit_code = EXIT_FAILURE;
}
ret = hts_close(out);
if (ret < 0) {
fprintf(stderr, "Error closing output.\n");
exit_code = EXIT_FAILURE;
}
return exit_code;
}
<file_sep>/build_htslib.sh
#!/usr/bin/env bash
set -e -v
cd htslib
git submodule init && git submodule update
mkdir -p build
autoheader
autoconf
./configure --prefix=`pwd`/build/
make
make install
<file_sep>/README.md
# bamsifter
Normalizes coverage depth by position-specific read sampling in a bam file to give a target max depth
### Usage:
bamsifter [-c max_coverage] [-i max_identical_cigar_pos] [-o out.bam] [--FLAGS] <in.bam>
#### Options:
-c Max coverage value
-o Output file name. Default is stdout
-i Max number of reads with an identical cigar starting at the some position to keep
--keep_unmapped Keep unmapped reads (0x4 flag)
--keep_secondary Keep alignments flagged as secondary (0x100 flag)
--keep_supplementary Keep alignments flagged as supplementary (0x800 flag)
--keep_chimeric Keep chimeric alignments (SA: tag)
***
engineered by <NAME> @ BroadInst
| f021d8b1593b6d89b743aa0d1095b6dd81f264c7 | [
"Markdown",
"C++",
"Shell"
] | 3 | C++ | trinityrnaseq/bamsifter | 348150fa5627ca20928ef3958ae43750c0d58cfa | 2ecfeef62e651a1e5ee6d43695a0af7e9f9bd2ca |
refs/heads/master | <repo_name>argyricon/sandbox-pug-maps<file_sep>/start.js
const app = require('./app')
// Set port to environment variable of available, otherwise default to 3000
const port = process.env.PORT || 3000
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`)
})
<file_sep>/public/javascripts/map.js
console.log('You dude - now I am here.')<file_sep>/routes/index.js
const express = require('express')
const router = express.Router()
const lat1 = 47.367479;
const lng1 = 8.629040;
router.get('/', (req, res) => {
console.log('GET request')
res.render('main',
{prop1: 'Brandschenkestrasse 64',
prop2: 'Seestrasse 12',
lat1: lat1,
lng1: lng1})
})
module.exports = router | 1039260e2a2feea0919d70667a9fd2f8ae05afca | [
"JavaScript"
] | 3 | JavaScript | argyricon/sandbox-pug-maps | 2d2d8a629ee8d547a5d7e5720d74924a43d0aafb | 3d273dddf8d19921e6fbba1a13da336568383feb |
refs/heads/master | <repo_name>iddaramola/TypeScript<file_sep>/tests/baselines/reference/mappedTypeErrors.js
//// [mappedTypeErrors.ts]
interface Shape {
name: string;
width: number;
height: number;
visible: boolean;
}
interface Named {
name: string;
}
interface Point {
x: number;
y: number;
}
// Constraint checking
type T00 = { [P in P]: string }; // Error
type T01 = { [P in number]: string }; // Error
type T02 = { [P in Date]: number }; // Error
type T03 = Record<Date, number>; // Error
type T10 = Pick<Shape, "name">;
type T11 = Pick<Shape, "foo">; // Error
type T12 = Pick<Shape, "name" | "foo">; // Error
type T13 = Pick<Shape, keyof Named>;
type T14 = Pick<Shape, keyof Point>; // Error
type T15 = Pick<Shape, never>;
type T16 = Pick<Shape, undefined>; // Error
function f1<T>(x: T) {
let y: Pick<Shape, T>; // Error
}
function f2<T extends string | number>(x: T) {
let y: Pick<Shape, T>; // Error
}
function f3<T extends keyof Shape>(x: T) {
let y: Pick<Shape, T>;
}
function f4<T extends keyof Named>(x: T) {
let y: Pick<Shape, T>;
}
// Type identity checking
function f10<T>() {
type K = keyof T;
var x: { [P in keyof T]: T[P] };
var x: { [Q in keyof T]: T[Q] };
var x: { [R in K]: T[R] };
}
function f11<T>() {
var x: { [P in keyof T]: T[P] };
var x: { [P in keyof T]?: T[P] }; // Error
var x: { readonly [P in keyof T]: T[P] }; // Error
var x: { readonly [P in keyof T]?: T[P] }; // Error
}
function f12<T>() {
var x: { [P in keyof T]: T[P] };
var x: { [P in keyof T]: T[P][] }; // Error
}
//// [mappedTypeErrors.js]
function f1(x) {
var y; // Error
}
function f2(x) {
var y; // Error
}
function f3(x) {
var y;
}
function f4(x) {
var y;
}
// Type identity checking
function f10() {
var x;
var x;
var x;
}
function f11() {
var x;
var x; // Error
var x; // Error
var x; // Error
}
function f12() {
var x;
var x; // Error
}
//// [mappedTypeErrors.d.ts]
interface Shape {
name: string;
width: number;
height: number;
visible: boolean;
}
interface Named {
name: string;
}
interface Point {
x: number;
y: number;
}
declare type T00 = {
[P in P]: string;
};
declare type T01 = {
[P in number]: string;
};
declare type T02 = {
[P in Date]: number;
};
declare type T03 = Record<Date, number>;
declare type T10 = Pick<Shape, "name">;
declare type T11 = Pick<Shape, "foo">;
declare type T12 = Pick<Shape, "name" | "foo">;
declare type T13 = Pick<Shape, keyof Named>;
declare type T14 = Pick<Shape, keyof Point>;
declare type T15 = Pick<Shape, never>;
declare type T16 = Pick<Shape, undefined>;
declare function f1<T>(x: T): void;
declare function f2<T extends string | number>(x: T): void;
declare function f3<T extends keyof Shape>(x: T): void;
declare function f4<T extends keyof Named>(x: T): void;
declare function f10<T>(): void;
declare function f11<T>(): void;
declare function f12<T>(): void;
<file_sep>/tests/baselines/reference/isomorphicMappedTypeInference.js
//// [isomorphicMappedTypeInference.ts]
type Box<T> = {
value: T;
}
type Boxified<T> = {
[P in keyof T]: Box<T[P]>;
}
function box<T>(x: T): Box<T> {
return { value: x };
}
function unbox<T>(x: Box<T>): T {
return x.value;
}
function boxify<T>(obj: T): Boxified<T> {
let result = {} as Boxified<T>;
for (let k in obj) {
result[k] = box(obj[k]);
}
return result;
}
function unboxify<T>(obj: Boxified<T>): T {
let result = {} as T;
for (let k in obj) {
result[k] = unbox(obj[k]);
}
return result;
}
function assignBoxified<T>(obj: Boxified<T>, values: T) {
for (let k in values) {
obj[k].value = values[k];
}
}
function f1() {
let v = {
a: 42,
b: "hello",
c: true
};
let b = boxify(v);
let x: number = b.a.value;
}
function f2() {
let b = {
a: box(42),
b: box("hello"),
c: box(true)
};
let v = unboxify(b);
let x: number = v.a;
}
function f3() {
let b = {
a: box(42),
b: box("hello"),
c: box(true)
};
assignBoxified(b, { c: false });
}
function f4() {
let b = {
a: box(42),
b: box("hello"),
c: box(true)
};
b = boxify(unboxify(b));
b = unboxify(boxify(b));
}
function makeRecord<T, K extends string>(obj: { [P in K]: T }) {
return obj;
}
function f5(s: string) {
let b = makeRecord({
a: box(42),
b: box("hello"),
c: box(true)
});
let v = unboxify(b);
let x: string | number | boolean = v.a;
}
function makeDictionary<T>(obj: { [x: string]: T }) {
return obj;
}
function f6(s: string) {
let b = makeDictionary({
a: box(42),
b: box("hello"),
c: box(true)
});
let v = unboxify(b);
let x: string | number | boolean = v[s];
}
//// [isomorphicMappedTypeInference.js]
function box(x) {
return { value: x };
}
function unbox(x) {
return x.value;
}
function boxify(obj) {
var result = {};
for (var k in obj) {
result[k] = box(obj[k]);
}
return result;
}
function unboxify(obj) {
var result = {};
for (var k in obj) {
result[k] = unbox(obj[k]);
}
return result;
}
function assignBoxified(obj, values) {
for (var k in values) {
obj[k].value = values[k];
}
}
function f1() {
var v = {
a: 42,
b: "hello",
c: true
};
var b = boxify(v);
var x = b.a.value;
}
function f2() {
var b = {
a: box(42),
b: box("hello"),
c: box(true)
};
var v = unboxify(b);
var x = v.a;
}
function f3() {
var b = {
a: box(42),
b: box("hello"),
c: box(true)
};
assignBoxified(b, { c: false });
}
function f4() {
var b = {
a: box(42),
b: box("hello"),
c: box(true)
};
b = boxify(unboxify(b));
b = unboxify(boxify(b));
}
function makeRecord(obj) {
return obj;
}
function f5(s) {
var b = makeRecord({
a: box(42),
b: box("hello"),
c: box(true)
});
var v = unboxify(b);
var x = v.a;
}
function makeDictionary(obj) {
return obj;
}
function f6(s) {
var b = makeDictionary({
a: box(42),
b: box("hello"),
c: box(true)
});
var v = unboxify(b);
var x = v[s];
}
//// [isomorphicMappedTypeInference.d.ts]
declare type Box<T> = {
value: T;
};
declare type Boxified<T> = {
[P in keyof T]: Box<T[P]>;
};
declare function box<T>(x: T): Box<T>;
declare function unbox<T>(x: Box<T>): T;
declare function boxify<T>(obj: T): Boxified<T>;
declare function unboxify<T>(obj: Boxified<T>): T;
declare function assignBoxified<T>(obj: Boxified<T>, values: T): void;
declare function f1(): void;
declare function f2(): void;
declare function f3(): void;
declare function f4(): void;
declare function makeRecord<T, K extends string>(obj: {
[P in K]: T;
}): {
[P in K]: T;
};
declare function f5(s: string): void;
declare function makeDictionary<T>(obj: {
[x: string]: T;
}): {
[x: string]: T;
};
declare function f6(s: string): void;
| 783c3620d352f0f1d0aec5cc635b0f112d84e3d3 | [
"JavaScript"
] | 2 | JavaScript | iddaramola/TypeScript | 5dd4c9ef542ae2f8086a71fc513c202aab6ac63c | 714d874d2a92d73b5b31378f6988577f64063e7a |
refs/heads/master | <file_sep>sass src/milligram.sass:dist/milligram.css
sass src/milligram.sass:dist/milligram.min.css --style compressed
| 8e0c93e77669995247946ac677e06bd6170133ff | [
"Shell"
] | 1 | Shell | corejan/milligram | c6d6941b088fb44ee0e73af09444c3582c449ebb | 7364378794fcbeaf39968e257afbe29c71e9b302 |
refs/heads/master | <repo_name>7e2f/stali.stali-iso<file_sep>/buildiso
#!/bin/sh
PWD=`pwd`
export ROOT_FS=$PWD/../rootfs-x86_64/
export ISO_FS=$PWD/iso9660/
export ISO_IMAGE=$PWD/stali.iso
cp $ROOT_FS/boot/vmlinuz $ISO_FS/isolinux/vmlinuz
(cd $ROOT_FS && find . -type l -printf '%p %Y\n' | sed -n 's/ [LN]$//p' | xargs -rL1 rm -f)
(cd $ROOT_FS && find . | grep -v \.\/\.git | cpio --owner root:root --quiet -o -H newc | gzip -9 >${ISO_FS}/isolinux/initrd.img)
rm -f $ISO_IMAGE
genisoimage -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -l -input-charset default -V stali -A "stali" -o $ISO_IMAGE $ISO_FS
| 247ee342da75abf17b4836572316528b45107e07 | [
"Shell"
] | 1 | Shell | 7e2f/stali.stali-iso | 9525ef72bd5bb0a1b49683cdd05e99908940a58f | 540c707cc278b4ea5ae1b3ad413bdc5da0e30ef3 |
refs/heads/master | <file_sep># nodejsapi
how to build RESTful API in node
<file_sep>var express=require("express");
var app=express();
var path=require('path');
const nunjucks=require("nunjucks");
const db=require('./dao');
const Pin=require('./models/pin');
app.use(express.static('src/public'));
nunjucks.configure(path.resolve(__dirname,'public/views'),{
express:app,
autoscape:true,
noCache:false,
watch:true
});
var data=["sun","mon","tues","wed","thurs","fri","sat"];
app.get('/',(req,res)=>{
res.render('index.html')
});
app.get('/api',(req,res)=>{
res.header('Access-Control-Allow-Origin',"*");
return res.send(data);
});
app.get('/pincode',(req,res)=>{
var pin=req.query.pincode;
Pin.find({pincode:pin}, (err, data) => {
if (err) {
res.render('error.html', { errorMessage: err.message });
}
else {
res.render('pincode.html', { data: data });
}
});
});
app.listen(3000,()=>{
console.log(`server running at http://127.0.0.1:3000`)
}) | d41687ad4803db3822484b2bcb01ce3dc13038cb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | avimalhotra/nodejsapi | 7f1517d692f181c26690c9f4ccb949b03c627f7c | ddb1dd6b93d5d09749892e31848c608125ae56bd |
refs/heads/master | <file_sep>const arrRotate = (input: Array<any>, n: number) => {
const x = input.slice();
const num = typeof n === 'number' ? n : 0;
return x.splice(-num % x.length).concat(x);
}
export {arrRotate} | e2e72e39b0b98d5ea685a789a0b6442255be8169 | [
"TypeScript"
] | 1 | TypeScript | Eastonboy99/ink-select-input | a1a2ff3469b729f27627eca4623ed950d15547da | 145e5be6a712b86793882576b5962895cba96a9a |
refs/heads/master | <repo_name>AddMoreBoosters/GameJam150520<file_sep>/Assets/Scripts/KillZone.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillZone : MonoBehaviour
{
[SerializeField]
private bool _isThisAFall = false;
private void OnTriggerEnter(Collider other)
{
if (!other.transform.CompareTag("Player"))
{
// Not the player, don't care
return;
}
// Player entered a killzone, game over
GameController.Instance.GameOver(_isThisAFall);
}
}
<file_sep>/Assets/Scripts/FinishFlag.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FinishFlag : MonoBehaviour
{
[SerializeField]
private MeshRenderer _flag;
[SerializeField]
private Material _startMaterial, _finishMaterial;
// Start is called before the first frame update
void Start()
{
_flag.material = _startMaterial;
}
private void OnTriggerEnter(Collider other)
{
if (other.transform.CompareTag("Player"))
{
_flag.material = _finishMaterial;
}
}
}
<file_sep>/Assets/Scripts/CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
[SerializeField]
private Transform _playerTransform;
private Vector3 _offset;
public bool followPlayer = true;
// Start is called before the first frame update
void Start()
{
_offset = transform.position - _playerTransform.position;
}
private void LateUpdate()
{
if (followPlayer == true)
{
transform.position = _playerTransform.position + _offset;
}
}
}
<file_sep>/Assets/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody _playerRB;
private CapsuleCollider _playerCollider;
private bool _controlsEnabled = true;
public bool _canJump = false;
[SerializeField]
private float _moveSpeed = 3.0f;
//[SerializeField]
//private float _rotationSpeed = 2.0f;
private float _elapsedJumpTime = 0f;
[SerializeField]
private float _coyoteTime = 0.2f;
[SerializeField]
private float _jumpSpeed = 5f;
private float _horizontalInput;
//private float _verticalInput;
//private float _rotationHorizontalInput;
// Start is called before the first frame update
void Start()
{
_playerRB = gameObject.GetComponent<Rigidbody>();
_playerCollider = gameObject.GetComponent<CapsuleCollider>();
}
// Update is called once per frame
void Update()
{
if (_controlsEnabled == false)
{
return;
}
GetInput();
CheckAbleToJump();
//transform.Translate(new Vector3(_horizontalInput, 0f, 0f) * Time.deltaTime * _moveSpeed);
if (Input.GetKeyDown(KeyCode.Space) && _canJump == true)
{
Jump();
}
}
private void FixedUpdate()
{
if (_controlsEnabled == false)
{
return;
}
transform.Translate(new Vector3(_horizontalInput, 0f, 0f) * Time.fixedDeltaTime * _moveSpeed);
}
private void GetInput ()
{
_horizontalInput = Input.GetAxis("Horizontal");
}
private void CheckAbleToJump ()
{
Vector3 bottom = new Vector3(_playerCollider.bounds.center.x, _playerCollider.bounds.min.y + _playerCollider.radius - 0.1f, _playerCollider.bounds.center.z);
LayerMask mask = LayerMask.GetMask("Default");
// Check if the bottom of the collider is touching something in the default layer
if (Physics.CheckCapsule(_playerCollider.bounds.center, bottom, _playerCollider.radius * 0.9f, mask) == true)
{
_canJump = true;
_elapsedJumpTime = 0f;
return;
}
// If we are not touching something, but we were before, activate coyote time
if (_canJump == true)
{
if (_elapsedJumpTime > _coyoteTime)
{
_canJump = false;
return;
}
_elapsedJumpTime += Time.deltaTime;
}
}
public void Jump ()
{
_playerRB.velocity = new Vector3(_playerRB.velocity.x, _jumpSpeed, _playerRB.velocity.z);
}
public void SetControlsEnabled (bool enabled)
{
_controlsEnabled = enabled;
}
/// <summary>
/// Disables controls and collider, cancels velocity, and optionally
/// jumps as a stand-in for a proper death animation.
///
/// Note that the camera's followPlayer must be disabled separately if
/// that is desired.
/// </summary>
/// <param name="shouldJump"></param>
public void Die (bool shouldJump = false)
{
_playerCollider.enabled = false;
SetControlsEnabled(false);
_playerRB.velocity = Vector3.zero;
if (shouldJump == true)
{
Jump();
}
}
}
<file_sep>/Assets/Scripts/MovingPlatform.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
[SerializeField]
private Transform _transform1, _transform2;
private Vector3 _position1, _position2;
[SerializeField]
private float _speed = 1f;
private bool _reverse = false;
[SerializeField]
private float _position = 0f;
private void Start()
{
_position1 = _transform1.position;
_position2 = _transform2.position;
}
// Update is called once per frame
void Update()
{
if (_reverse == true)
{
_position -= Time.deltaTime * _speed;
}
else
{
_position += Time.deltaTime * _speed;
}
if (_position <= 0f)
{
_reverse = false;
}
else if (_position >= 1f)
{
_reverse = true;
}
}
private void FixedUpdate()
{
transform.position = Vector3.Lerp(_position1, _position2, _position);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.CompareTag("Player"))
{
collision.transform.SetParent(transform);
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.transform.CompareTag("Player"))
{
collision.transform.SetParent(null);
}
}
}
<file_sep>/Assets/Scripts/GameController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
private static GameController instance = null;
public static GameController Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<GameController>();
if (instance == null)
{
GameObject backup = new GameObject();
backup.name = "Game Controller";
instance = backup.AddComponent<GameController>();
DontDestroyOnLoad(backup);
}
}
return instance;
}
}
[SerializeField]
private CameraController _camera;
[SerializeField]
private PlayerController _player;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
if (_camera == null)
{
_camera = FindObjectOfType<CameraController>();
if (_camera == null)
{
Debug.LogError("Game Controller could not find a Camera Controller!");
}
}
if (_player == null)
{
_player = FindObjectOfType<PlayerController>();
if (_player == null)
{
Debug.LogError("Game Controller could not find a Player Controller!");
}
}
}
public void GameOver (bool fellOffTheLevel = false)
{
_camera.followPlayer = false;
_player.Die(!fellOffTheLevel);
}
}
<file_sep>/Assets/Scripts/Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField]
private float _moveSpeed = 1f;
private float _direction = 1f;
private void FixedUpdate()
{
transform.Translate(transform.right * Time.fixedDeltaTime * _moveSpeed * _direction);
}
private void OnCollisionEnter(Collision collision)
{
if (!collision.transform.CompareTag("Player"))
{
// Not the player, just turn around
_direction *= -1f;
return;
}
// Hit the player, it's game over
GameController.Instance.GameOver();
}
private void OnTriggerEnter(Collider other)
{
if (!other.transform.CompareTag("Player"))
{
// Not the player, don't care
return;
}
PlayerController playerController = other.gameObject.GetComponent<PlayerController>();
if (playerController == null)
{
Debug.LogError("Something with Player tag hit an Enemy trigger collider, but no PlayerController component was found");
return;
}
playerController.Jump();
// Enemy was jumped on, player bounces, now enemy needs to despawn and score needs to be increased
}
}
| aea573b0ea10179144f4a316c775e34414f0e54a | [
"C#"
] | 7 | C# | AddMoreBoosters/GameJam150520 | 93ee2b95e12396492fd77d2f4a9f8d8fdfdd14a0 | 8f1798afacc2377fdc2679227db6c75a5a3455a3 |
refs/heads/main | <repo_name>tanzeelgcuf/knnclassicationbustabit<file_sep>/live_limit.py
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from shutil import which
import time
import pandas as pd
import numpy as np
import joblib
from numpy import savetxt
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
chrome_path = 'chromedriver.exe'
Players = []
Bets = []
Cashs_Out =[]
Profits = []
game_ids =[]
Busted_At = []
driver = webdriver.Chrome(executable_path=chrome_path)
# driver.get('https://www.bustabit.com/game/2000')
# time.sleep(5)
i=3973010 #starting id
idd=[]
pred=[]
m=1
while (m<21):
j=i+1
m=m+1
for id in range(i,j):
Players = []
Bets = []
Cashs_Out = []
Profits = []
game_ids = []
Busted_At = []
#i=i+1
url = f'https://www.bustabit.com/game/{id}'
driver.get(url)
time.sleep(8)
for a in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[1]/a'):
Players.append(a.text)
#print(Players)
for b in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[2]'):
Bets.append(b.text)
for c in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[3]'):
Cashs_Out.append(c.text)
for d in driver.find_elements_by_xpath('//div[@class="<KEY>IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[4]'):
Profits.append(d.text)
game_1 = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//h3')))
ab = (game_1.text)
Busted = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//p[@class="_2IumaQfnOQsiJTuwTJZlvp"]/span[2]')))
bc = (Busted.text)
for game in range(len(Players)):
game_ids.append(ab)
Busted_At.append(bc)
df = pd.DataFrame(game_ids, columns = ['Game_ID'])
df["Players"] = Players
df["Bets"] = Bets
df["Cashout"] = Cashs_Out
df["Profits"] = Profits
df["Busted_At"] = Busted_At
df.drop(["Players"], axis=1, inplace=True)
df['Cashout'] = df['Cashout'].str.replace('-','0')
df['Cashout'] = df['Cashout'].str.replace('x','0')
df['Cashout'] = df['Cashout'].str.replace('Cashout','0')
df['Busted_At'] = df['Busted_At'].str.replace('z','0')
df['Busted_At'] = df['Busted_At'].str.replace('x','')
df['Game_ID'] = df['Game_ID'].str.replace('Game #','')
df['Bets'] = df['Bets'].str.replace(',','')
df['Profits'] = df['Profits'].str.replace(',','')
df['Cashout'] = df['Cashout'].str.replace(',','')
x = df.iloc[:,[1,2,3]].values
print(x)
id1=[]
id1=df['Game_ID']
model = joblib.load('train_LR')
res= model.predict(x)
#pred.append(list(model.predict(x)))
show=[id1,res]
show=np.transpose(show)
print(show)
i=i+1
for k in range(len(id1)):
idd.append(id1[k])
for l in range(len(res)):
pred.append(res[l])
#savetxt('predicted_data.csv', data,'%s',delimiter=',')
# # Set Path for where you want to save file
#df.to_csv ('test.csv', index = False, header=True)
data=[idd,pred]
data=np.transpose(data)
#df=pd.DataFrame(data,columns=['Game_id','Price'])
savetxt('predicted_data.csv', data, '%s', delimiter=',')
#print(data)
#print(data)
#savetxt("nxx", data.reshape((3,-1)), fmt="%s", header=str(data.shape))
driver.close()<file_sep>/new (1).py
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from shutil import which
import time
import pandas as pd
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from fake_useragent import UserAgent
options_1 = Options()
ua = UserAgent()
userAgent = ua.random
options_1.add_argument(f'user-agent={userAgent}')
chrome_path = which('chromedriver')
Players = []
Bets = []
Cashs_Out =[]
Profits = []
game_ids =[]
Busted_At = []
driver = webdriver.Chrome(executable_path=chrome_path, options= options_1)
def get():
for a in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[1]/a'):
Players.append(a.text)
for b in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[2]'):
Bets.append(b.text)
for c in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[3]'):
Cashs_Out.append(c.text)
for d in driver.find_elements_by_xpath('//div[@class="oMRXjPQYe_IJLADVIUrdO modal-body"]/div/div[2]/table/tbody/tr/td[4]'):
Profits.append(d.text)
# driver.get('https://www.bustabit.com/game/2000')
# time.sleep(5)
for id in range(3984300, 3984450):
url = f'https://www.bustabit.com/game/{id}'
driver.get(url)
time.sleep(10)
get()
game_1 = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//h3')))
ab = (game_1.text)
Busted = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//p[@class="_2IumaQfnOQsiJTuwTJZlvp"]/span[2]')))
bc = (Busted.text)
for game in range(len(Players)):
game_ids.append(ab)
Busted_At.append(bc)
df = pd.DataFrame(Players, columns = ['Players'])
df["Game_ID"] = game_ids
df["Bets"] = Bets
df["Cashout"] = Cashs_Out
df["Profits"] = Profits
df["Busted_At"] = Busted_At
# # Set Path for where you want to save file
df.to_csv (r'C:\Users\Amaar\Desktop\demo2.csv', index = False, header=True)
print(df)
driver.close() | 034effe51d2900614fdbde4b41ad98e599cd68c9 | [
"Python"
] | 2 | Python | tanzeelgcuf/knnclassicationbustabit | dab3ad343feeada90da876d5ca6a75d70e6bb365 | f0a49b8568e8936c75e86badefbdb580aad396cd |
refs/heads/master | <repo_name>KaushalyaSandamali/Emotion-Recognition<file_sep>/README.md
# Emotion-Recognition
Emotion recognition Test
this is for emotioni recognition from images
<file_sep>/test.py
from __future__ import print_function
import numpy as np
# get the data
filname = 'F:\\copy.csv'
label_map = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
| 36914e6c9e892cc74212957e859881564acf25a2 | [
"Markdown",
"Python"
] | 2 | Markdown | KaushalyaSandamali/Emotion-Recognition | 65fea05c394bc23700b21028e900c4db95240582 | 84bcf7edde75a30b5c145489065fe9c551a476b5 |
refs/heads/main | <file_sep>from math import e
from os import fpathconf
from typing import Callable, Dict, List, Optional, Tuple, Type, Union
import gym
import torch as th
from torch import nn
from stable_baselines3.common.policies import ActorCriticPolicy
from GA import GA
class CustomNetwork(nn.Module):
"""
Custom network for policy and value function.
It receives as input the features extracted by the feature extractor.
:param feature_dim: dimension of the features extracted with the features_extractor (e.g. features from a CNN)
:param last_layer_dim_pi: (int) number of units for the last layer of the policy network
:param last_layer_dim_vf: (int) number of units for the last layer of the value network
"""
def __init__(
self,
feature_dim: int,
last_layer_dim_pi: int = 64,
last_layer_dim_vf: int = 64,
):
super(CustomNetwork, self).__init__()
# IMPORTANT:
# Save output dimensions, used to create the distributions
self.latent_dim_pi = last_layer_dim_pi
self.latent_dim_vf = last_layer_dim_vf
# Env module
self.image_embedder = nn.Sequential(
nn.Conv2d(3, 16, 3),
nn.ReLU(),
nn.Conv2d(16, 32, 3),
nn.ReLU(),
nn.Conv2d(32, 32, 2),
nn.ReLU(),
nn.Flatten()
)
# LTL module
# TODO: parameterize
# self.ltl_embedder = nn.Embedding(11, 8, padding_idx=0)
self.ltl_embedder = nn.Embedding(11, 16, padding_idx=0)
self.ga = GA(seq_len=10, num_rel=8, num_heads=32, num_layers=3, device="cuda")
# Policy network
self.policy_net = nn.Sequential(
nn.Linear(288, 64), # 208
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, last_layer_dim_pi),
# nn.ReLU()
)
# Value network
self.value_net = nn.Sequential(
nn.Linear(288, 64), # 208
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, last_layer_dim_vf),
# nn.ReLU()
)
def forward(self, features: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
"""
:return: (th.Tensor, th.Tensor) latent_policy, latent_value of the specified network.
If all layers are shared, then ``latent_policy == latent_value``
"""
batch_size = features.shape[0]
# TODO: parameterize
img = features[:, :147].reshape(batch_size,7,7,3).permute(0, 3, 1, 2)
direction = features[:, 147]
formula = features[:, 148:158].to(th.long)
rels = features[:, 158:]
rels = rels.reshape(batch_size, 10, 10).to(th.long)
# Env module
embedded_image = self.image_embedder(img) #128
# LTL module
embedded_formula = self.ltl_embedder(formula)
embedded_formula = self.ga(embedded_formula, rels) # [B,10,8], [B,10,16]
embedded_formula = embedded_formula.reshape(batch_size, -1) # [B,80], [B,160]
# RL module
composed_state = th.cat([embedded_image, embedded_formula], dim=1) # [B,208], [B,288]
return self.policy_net(composed_state), self.value_net(composed_state)
class CustomActorCriticPolicy(ActorCriticPolicy):
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Callable[[float], float],
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None,
activation_fn: Type[nn.Module] = nn.Tanh,
*args,
**kwargs,
):
super(CustomActorCriticPolicy, self).__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
activation_fn,
# Pass remaining arguments to base class
*args,
**kwargs,
)
# Disable orthogonal initialization
self.ortho_init = False
def _build_mlp_extractor(self) -> None:
self.mlp_extractor = CustomNetwork(self.features_dim)
<file_sep>from hashlib import new
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
# rough hack
import sys
sys.path.insert(0, './envs')
from minigrid_extensions import *
# sys.path.insert(0, '../')
from resolver import progress
from random import randint
class AdversarialMyopicEnv(MiniGridEnv):
"""
An environment where a myopic agent will fail. The two possible goals are "Reach blue then green" or "Reach blue then red".
"""
def __init__(
self,
size=8, # size of the grid world
agent_start_pos=(1,1), # starting agent position
agent_start_dir=0, # starting agent orientation
timeout=100 # max steps that the agent can do
):
self.agent_start_pos = agent_start_pos
self.agent_start_dir = agent_start_dir
self.event_objs = []
self.timeout = timeout
self.time = 0
self.complete_task = None
self.super_init(
grid_size=size,
max_steps=4*size*size,
see_through_walls=True # set this to True for maximum speed
)
def super_init(
self,
grid_size=None,
width=None,
height=None,
max_steps=100,
see_through_walls=False,
seed=1337,
agent_view_size=7
):
# Can't set both grid_size and width/height
if grid_size:
assert width == None and height == None
width = grid_size
height = grid_size
# Action enumeration for this environment
self.actions = MiniGridEnv.Actions
# Actions are discrete integer values
self.action_space = spaces.Discrete(len(self.actions))
# Number of cells (width and height) in the agent view
assert agent_view_size % 2 == 1
assert agent_view_size >= 3
self.agent_view_size = agent_view_size
# Observations are dictionaries containing an
# encoding of the grid and a textual 'mission' string
self.observation_space = spaces.Box(
low=0,
high=255,
shape=(180,), # Mission needs to be padded
dtype='uint8'
)
# self.observation_space = spaces.Dict({
# 'image': self.observation_space
# })
# Range of possible rewards
self.reward_range = (-1, 1)
# Window to use for human rendering mode
self.window = None
# Environment configuration
self.width = width
self.height = height
self.max_steps = max_steps
self.see_through_walls = see_through_walls
# Current position and direction of the agent
self.agent_pos = None
self.agent_dir = None
# Initialize the RNG
self.seed(seed=seed)
# Initialize the state
self.reset()
def reset(self):
obs = super().reset()
self.time = 0
return obs
def draw_task(self):
''' Helper function to randomly draw a new LTL task from the task distribution. '''
tasks = [
[['E', 'b'], ['E', 'r']], # blue first, then red
[['E', 'b'], ['E', 'g']] # blue first, then green
]
return tasks[randint(0, len(tasks) - 1)]
def _gen_grid(self, width, height):
''' Helper function to generate a new random world. Called at every env reset. '''
# Create an empty grid
self.grid = Grid(width, height)
# Generate the surrounding walls
self.grid.wall_rect(0, 0, width, height)
# Generate inner walls
self.grid.vert_wall(4, 0)
self.grid.horz_wall(4, 4)
self.door_1 = Door(COLOR_NAMES[0], is_open=True)
self.door_2 = Door(COLOR_NAMES[0], is_open=True)
self.door_1_loc = (4,2)
self.door_2_loc = (4,6)
self.grid.set(*self.door_1_loc, self.door_1)
self.grid.set(*self.door_2_loc, self.door_2)
# Place a goal square in the bottom-right corner
self.blue_goal_1_pos = (5, 7)
self.blue_goal_2_pos = (5, 1)
self.blue_goal_1 = CGoal('blue')
self.blue_goal_2 = CGoal('blue')
self.green_goal_pos = (7, 7)
self.red_goal_pos = (7, 1)
self.green_goal = CGoal('green')
self.red_goal = CGoal('red')
# Randomize which room contains the green and red goals
if randint(0,1) == 0:
self.green_goal_pos, self.red_goal_pos = self.red_goal_pos, self.green_goal_pos
self.put_obj(self.green_goal, *self.green_goal_pos)
self.put_obj(self.red_goal, *self.red_goal_pos)
self.put_obj(self.blue_goal_1, *self.blue_goal_1_pos)
self.put_obj(self.blue_goal_2, *self.blue_goal_2_pos)
self.event_objs = []
self.event_objs.append((self.blue_goal_1_pos, 'b'))
self.event_objs.append((self.blue_goal_2_pos, 'b'))
self.event_objs.append((self.green_goal_pos, 'g'))
self.event_objs.append((self.red_goal_pos, 'r'))
# Place the agent
if self.agent_start_pos is not None:
self.agent_pos = self.agent_start_pos
self.agent_dir = self.agent_start_dir
else:
self.place_agent(top=(1,1), size=(3,7))
# Task
self.complete_task = self.draw_task()
self.mission = str(self.complete_task[0])
def reward(self):
'''
Helper function to establish the reward and the done signals.
Returns the (reward, done) tuple.
'''
if self.mission == "True": return (1, True)
elif self.mission == "False": return (-1, True)
else: return (0, False)
def encode_mission(self, mission):
syms = "AONGUXE[]rgb"
V = {k: v+1 for v, k in enumerate(syms)}
return [V[e] for e in mission if e not in ["\'", ",", " "]]
def gen_obs(self):
"""
Generate the agent's view (partially observable, low-resolution encoding)
"""
obs = super().gen_obs()
# obs = {
# 'image': image, (7,7,3)
# 'direction': self.agent_dir,
# 'mission': self.mission
# }
img = np.array(obs["image"]).reshape(-1) #147
direction = np.array([obs["direction"]]) # 1
mission = np.array(self.encode_mission(obs["mission"]))
new_obs = np.concatenate((img, direction, mission))
obs = np.zeros(180)
obs[:new_obs.shape[0]] = new_obs
return obs
def step(self, action):
# Lock the door automatically behind you
if action == self.actions.forward and self.agent_dir == 0:
if tuple(self.agent_pos) == self.door_1_loc:
self.door_1.is_open = False
self.door_1.is_locked = True
elif tuple(self.agent_pos) == self.door_2_loc:
self.door_2.is_open = False
self.door_2.is_locked = True
obs, _, _, _ = super().step(action)
# prog function call
if progress(self.complete_task[0], self.get_events()) == "True":
self.complete_task.pop(0)
self.mission = str(self.complete_task[0]) if self.complete_task else "True"
reward, done = self.reward()
# max steps elapsed
self.time += 1
if self.time >= self.timeout:
reward, done = -1, True
return obs, reward, done, {}
def get_events(self):
''' Event detector. '''
events = []
for obj in self.event_objs:
if tuple(self.agent_pos) == obj[0]:
events.append(obj[1])
return events
class AdversarialMyopicEnv9x9(AdversarialMyopicEnv):
def __init__(self, agent_start_pos=None):
super().__init__(size=9, agent_start_pos=agent_start_pos)
<file_sep>
import torch
from envs.adversarial import AdversarialEnv9x9
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.evaluation import evaluate_policy
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
env = AdversarialEnv9x9()
model = PPO.load("./logs/generalization_gru", device=DEVICE)
# evaluate generalization
mean_rew, std_rew = evaluate_policy(model.policy, Monitor(env),
n_eval_episodes=100,
render=False,
deterministic=False)
print(f"Mean reward: {mean_rew:.2f} +/- {std_rew:.2f}")
<file_sep>from math import e
from os import fpathconf
from typing import Callable, Dict, List, Optional, Tuple, Type, Union
import gym
import torch as th
from torch import nn
from stable_baselines3.common.policies import ActorCriticPolicy
class CustomNetwork(nn.Module):
"""
Custom network for policy and value function.
It receives as input the features extracted by the feature extractor.
:param feature_dim: dimension of the features extracted with the features_extractor (e.g. features from a CNN)
:param last_layer_dim_pi: (int) number of units for the last layer of the policy network
:param last_layer_dim_vf: (int) number of units for the last layer of the value network
"""
def __init__(
self,
feature_dim: int,
last_layer_dim_pi: int = 64,
last_layer_dim_vf: int = 64,
):
super(CustomNetwork, self).__init__()
# IMPORTANT:
# Save output dimensions, used to create the distributions
self.latent_dim_pi = last_layer_dim_pi
self.latent_dim_vf = last_layer_dim_vf
# Env module
self.image_embedder = nn.Sequential(
nn.Conv2d(3, 16, 3),
nn.ReLU(),
nn.Conv2d(16, 32, 3),
nn.ReLU(),
nn.Conv2d(32, 32, 2),
nn.ReLU(),
nn.Flatten()
)
# # direction embedding
# self.dir_embedding = nn.Embedding(4, 16)
# LTL module
self.ltl_embedder = nn.Embedding(13, 8, padding_idx=0)
self.rnn = nn.GRU(8, 32, num_layers=2, bidirectional=True, batch_first=True)
# Policy network
self.policy_net = nn.Sequential(
nn.Linear(192, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, last_layer_dim_pi),
# nn.ReLU()
)
# Value network
self.value_net = nn.Sequential(
nn.Linear(192, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, last_layer_dim_vf),
# nn.ReLU()
)
def forward(self, features: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
"""
:return: (th.Tensor, th.Tensor) latent_policy, latent_value of the specified network.
If all layers are shared, then ``latent_policy == latent_value``
"""
batch_size = features.shape[0]
img = features[:, :147].reshape(batch_size,7,7,3).permute(0, 3, 1, 2)
direction = features[:, 147]
formula = features[:, 148:]
# Env module
embedded_image = self.image_embedder(img) #128
# embedded_dir = self.dir_embedding(direction.to(th.long)) # [B,16]
# LTL module
embedded_formula = self.ltl_embedder(formula.to(th.long))
_, h = self.rnn(embedded_formula)
embedded_formula = h[:-2,:,:].transpose(0,1).reshape(batch_size, -1) # [B,64]
# RL module
composed_state = th.cat([embedded_image, embedded_formula], dim=1) # [B,192]
# composed_state = th.cat([embedded_image, embedded_dir, embedded_formula], dim=1) # [B,192]
return self.policy_net(composed_state), self.value_net(composed_state)
class CustomActorCriticPolicy(ActorCriticPolicy):
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Callable[[float], float],
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None,
activation_fn: Type[nn.Module] = nn.Tanh,
*args,
**kwargs,
):
super(CustomActorCriticPolicy, self).__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
activation_fn,
# Pass remaining arguments to base class
*args,
**kwargs,
)
# Disable orthogonal initialization
self.ortho_init = False
def _build_mlp_extractor(self) -> None:
self.mlp_extractor = CustomNetwork(self.features_dim)
<file_sep>
import random, math, os
import numpy as np
import gym
from gym import spaces
from gym_minigrid.register import register
# rough hack
import sys
# sys.path.insert(0, '../')
from resolver import progress, is_accomplished
from GA import build_relations
from random import randint
class LTLBootcamp(gym.Env):
"""
An environment to pre-train the LTL module for the adversarial env.
"""
def __init__(
self,
fixed_task=None, # set an LTL instruction to be kept at every env reset
timeout=25, # max steps that the agent can do
):
self.timeout = timeout
self.time = 0
self.fixed_task = fixed_task
self.task = None
# Actions are discrete integer values
self.action_space = spaces.Discrete(len(' rgb'))
self.observation_space = spaces.Box(
low=0,
high=255,
shape=(110,), # Mission needs to be padded
dtype='uint8'
)
# Initialize the state
self.reset()
def draw_task(self):
''' Helper function to randomly draw a new LTL task from the task distribution. '''
if self.fixed_task is not None:
return self.fixed_task
tasks = [
['A', ['G', ['N', 'b']], ['E', 'r']],
['A', ['G', ['N', 'b']], ['E', 'g']],
['A', ['G', ['N', 'r']], ['E', 'b']],
['A', ['G', ['N', 'g']], ['E', 'b']],
['A', ['E', 'b'], ['E', 'g']],
['O', ['E', 'b'], ['E', 'g']],
['A', ['E', 'b'], ['E', 'r']],
['O', ['E', 'b'], ['E', 'r']],
['E', ['A', 'r', ['E', 'b']]],
['E', ['A', 'b', ['E', 'r']]],
['E', ['A', 'g', ['E', 'b']]],
['E', ['A', 'b', ['E', 'g']]],
['E', ['A', 'r', ['E', ['A', 'b', ['E', 'r']]]]],
['E', ['A', 'g', ['E', ['A', 'b', ['E', 'g']]]]],
['E', ['A', 'b', ['E', ['A', 'r', ['E', 'b']]]]],
['E', ['A', 'b', ['E', ['A', 'g', ['E', 'b']]]]],
['E', 'r'],
['E', 'b'],
['E', 'g'],
]
return tasks[randint(0, len(tasks) - 1)]
def reset(self):
''' Env reset, must be called every time 'done' becomes True. '''
self.task = self.draw_task()
self.mission = str(self.task)
return self.gen_obs()
def reward(self):
'''
Helper function to establish the reward and the done signals.
Returns the (reward, done) tuple.
'''
if self.task == "True" or is_accomplished(self.task): return (1, True)
elif self.task == "False": return (-1, True)
return (0, False)
def gen_obs(self):
def encode_mission(mission):
assert mission == str(self.task), "Task and mission are not equivalent!"
syms = "AONGUXErgb"
V = {k: v+1 for v, k in enumerate(syms)}
enc = np.array([V[e] for e in mission if e not in "\', []"])
# TODO: parameterize
rels = build_relations(self.task, 10)
return np.concatenate([enc, np.zeros(10 - len(enc))]), np.array(rels)
obs = np.zeros(110) # max mission length
if self.mission == 'True' or self.mission == 'False':
return obs
mission, rels = encode_mission(self.mission)
return np.concatenate((mission, rels.reshape(-1))) # 10 + 10x10 = 110
def step(self, action):
# event detector
if action == 0:
event_objs = []
elif action == 1:
event_objs = ['r']
elif action == 2:
event_objs = ['g']
elif action == 3:
event_objs = ['b']
# prog function call
self.task = progress(self.task, event_objs)
self.mission = str(self.task)
reward, done = self.reward()
# max steps elapsed
self.time += 1
if self.time > self.timeout:
reward, done = -1, True
self.time = 0
return self.gen_obs(), reward, done, {}
<file_sep># LTL2Action: Multi-task Reinforcement Learning using LTL
The repository implements a reinforcement learning algorithm to address the problem of instruct RL agents to learn temporally extended goals in multi-task environments. The project is based on the idea introduced in [LTL2Action: LTL Instruction for multi-task RL](https://arxiv.org/pdf/2102.06858.pdf) (Vaezipoor et al. 2021).
More details can be found in the **[Report](https://github.com/bebbo203/LTL2Action/blob/main/report.pdf)**.
## Environment
The environment is implemented with [gym-minigrid](https://github.com/maximecb/gym-minigrid): an agent (red triangle) must navigate in a 7x7 map. There are walls (grey squares), goals (colored squares) that are shuffled at each episode and doors (blue rectangles). The actions are _go straight_, _turn left_, _turn right_ and the observations returned are the 7x7 colored grid and the orientation of the agent codified by an integer.
<div style="text-align:center"><img src=imgs/env.png width="300" height="300"></div>
## Framework
We implemented a RL framework with LTL instructions which learn to solve complex tasks (formalized in LTL language) in challenging environments. At every iteration the RL agent can partially observe the environment sorrounding it and through an event detector a set of truth assignments which are going to progressed (through a progression function) the LTL instruction, identifying the remaining aspect of the tasks to be accomplished.
Therefore, the overall method relies on two modules which serve as feature extractors: one for the observation of the environment and one for the LTL instruction, which are later combined together to forms the input of a standard RL algorithm (PPO).
<div style="text-align:center"><img src=imgs/modules.png width="550" height="350"></div>
## Results
The method is able to solve multi-task environments with an high success rate.
To make the agent generalize over the task formulas, every episode is descripted with a different LTL task sampled from a finite set.
In the following plot, a normal PPO agent and the novel agent are trained on the same environment.
The two task taken in consideration are:
* go to *blue* THEN go to *red*
* go to *blue* THEN go to *green*
A Myopic agent reach a success rate of 50%, meaning that it cannot "see" what is the successive goal after the blue one.
<div style="text-align:center"><img src=imgs/ep_rew_mean.png width="450" height="350"></div>
## Experiments
The agent is trained over a variety of LTL tasks, like partially ordered tasks and avoidance tasks.
In the gif below the task *"eventually go to blue square and then go to green square"* is performed.
<div style="text-align:center"><img src=imgs/openaigym.video.0.gif width="402" height="402"></div>
In the second example video the agent execute a sequence of partially ordered task that appear in the image bottom part, showing also the progression mechanism. When the task is accomplished the LTL formula progresses to *true*. Note that LTL formulae are represented in *prefix notation* by using tokens for operators and prepositions and brackets for relations.
<div style="text-align:center"><img src=imgs/video.gif width="402" height="450"></div>
## Installation
### Requirements
* [Stable-Baselines3](https://stable-baselines3.readthedocs.io/en/master/)
* [gym-minigrid](https://github.com/maximecb/gym-minigrid)
or, for better compatibility, the following command can be used:
### Set up the conda environment
```
conda env create -f environment.yml
```
## How to Use
### Training RL agent
```
python train.py
```
### Test
```
python test.py
```
## References
- Vaezipoor, Pashootan, Li, Andrew, Icarte, <NAME>, and <NAME> (2021). “LTL2Action:Generalizing LTL Instructions for Multi-Task RL”. In:International Conference on MachineLearning (ICML)
- Icarte, <NAME>, Klassen, <NAME>., Valenzano, <NAME>, and McIlraith, <NAME>.(2018). “Teaching Multiple Tasks to an RL Agent using LTL.” In:International Conferenceon Autonomous Agents and Multiagent. Systems (AAMAS), (pp. 452–461)
<file_sep>if __name__ == '__main__':
# This is a terrible hack just to be able to execute this file directly
import sys
sys.path.insert(0, '../../')
import random, math, os
import numpy as np
import gym
from gym import spaces
from adversarial import *
class MinigridEnv(gym.Env):
"""
A simple wrapper for a gym-minigrid environment. This implements propositions on top of the minigrid.
"""
def __init__(self, env, letters="abc", timeout=100):
"""
## env is the wrapped MiniGrid environment
"""
self.env = env
self.letters = letters
self.letter_types = list(set(letters))
self.letter_types.sort()
self.action_space = env.action_space
self.observation_space = env.observation_space['image']
self.num_episodes = 0
self.time = 0
self.timeout = timeout
def step(self, action):
obs, reward, done, _ = self.env.step(action)
self.time += 1
if self.time >= self.timeout:
done = True
return obs['image'], 0, done, _
def seed(self, seed=None):
random.seed(seed)
self.env.seed(seed)
def reset(self):
"""
This function resets the world and collects the first observation.
"""
self.num_episodes += 1
self.time = 0
return self.env.reset()['image']
def get_events(self):
return self.env.get_events()
def get_propositions(self):
return self.letter_types
class AdversarialMinigridEnv(MinigridEnv):
def __init__(self):
super().__init__(AdversarialEnv9x9(), 'abc', 1000)
if __name__ == '__main__':
AdversarialMinigridEnv()
<file_sep>
import os
import time
import torch
from envs.adversarial import AdversarialEnv9x9
from envs.myopic import AdversarialMyopicEnv9x9
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.evaluation import evaluate_policy
MANUAL_CONTROL = False
MYOPIC = False
MODEL = "best_model" # {'main' | 'toy_grid' | 'myopic'} #
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
def control(letter):
''' Helper function to manually control the agent. '''
if letter == 'a': return 0 # sx
elif letter == 'd': return 1 # dx
elif letter == 'w': return 2 # forward
else: return 3 # no move
env = AdversarialEnv9x9() if not MYOPIC else AdversarialMyopicEnv9x9()
model = PPO.load(os.path.join("logs", MODEL), device=DEVICE) if not MANUAL_CONTROL else None
# Evaluation #
mean_rew, std_rew = evaluate_policy(model.policy, Monitor(env),
n_eval_episodes=100,
render=False,
deterministic=False)
print(f"Mean reward: {mean_rew:.2f} +/- {std_rew:.2f}")
exit()
obs = env.reset()
for i in range(10000):
action = control(input()) if MANUAL_CONTROL else model.predict(obs)[0]
obs, rew, done, _ = env.step(action)
env.render()
time.sleep(.25)
if done:
env.reset()
<file_sep>
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class GA(nn.Module):
def __init__(self,
seq_len, # sequence length
num_rel, # number of possible relations
num_heads, # number of attention heads
num_layers, # deep of the module
device='cpu', # {'cuda' | 'cpu'}
):
super().__init__()
self.num_heads = num_heads
# relation embedding layer
self.rel_embs = nn.Embedding(num_rel,
num_heads,
padding_idx=0)
self.num_layers = num_layers
for i in range(num_layers):
setattr(self, "lin" + str(i), nn.Parameter(torch.randn((seq_len, num_heads, 1))))
setattr(self, "bias" + str(i), nn.Parameter(torch.randn((seq_len, 1))))
self.to(device)
self.device = device
def forward(self, x, relations):
'''
params:
x: torch.FloatTensor [B,S,D]
relations: torch.LongTensor [B,S,S]
returns:
res: torch.FloatTensor [B,S,D]
'''
# Relation-based multi head self-attention
A = self.rel_embs(relations) # [B,S,S,H]
A = A.transpose(3,2).transpose(2,1) # [B,H,S,S]
A = F.softmax(A, dim=-1) # row-softmaxed relation matrix
for i in range(self.num_layers):
x = self.forward_(x, A, i)
return x
def forward_(self, x, A, idx_layer):
'''
x: [B,S,D]
A: [B,H,S,S]
idx_layer: number of current layer
'''
lin = getattr(self, "lin" + str(idx_layer))
bias = getattr(self, "bias" + str(idx_layer))
x = x.unsqueeze(dim=1).repeat(1, self.num_heads, 1, 1) # [B,H,S,D]
Ax = torch.matmul(A, x) # [B,H,S,D]
# put all the heads together through a linear transformation
Ax = Ax.transpose(1,2).transpose(2,3) # [B,S,D,H]
r = torch.matmul(Ax, lin).squeeze(-1) + bias # [B,S,D]
return torch.tanh(r) # non-linear activation function
def build_relations(formula, max_len=10):
''' Function to construct the skew-symmetric relation matrix. '''
def length(formula):
''' Aux method to recursively determine the length of formula. '''
if type(formula) == str:
return 1
if len(formula) == 2:
return length(formula[1]) + 1
if len(formula) == 3:
return length(formula[1]) + length(formula[2]) + 1
# define a max_len x max_len matrix with as many 1s on the diagonal as the length of formula
rel_len = length(formula) # length of formula
pad_len = max_len - rel_len # length of padding
mat = np.diag(np.concatenate([np.ones(rel_len), np.zeros(pad_len)]))
# define a proper relation vocabulary
V = {k: v for v, k in enumerate([" ", "s", "p", "l", "r", "p_", "l_", "r_"])}
def tagger(formula, mat, prev_idx=-1, idx=0, rel=None):
''' Aux method to recursively fill the relation matrix based on formula. '''
def aux(mat, i, j, rel):
if prev_idx != -1 and rel is not None:
mat[prev_idx, idx] = V[rel]
mat[idx, prev_idx] = V[rel + '_']
if type(formula) == str:
aux(mat, prev_idx, idx, rel)
return idx
if len(formula) == 2:
aux(mat, prev_idx, idx, rel)
return tagger(formula[1], mat, idx, idx+1, 'p')
if len(formula) == 3:
aux(mat, prev_idx, idx, rel)
offset = tagger(formula[1], mat, idx, idx+1, 'l')
return tagger(formula[2], mat, idx, offset+1, 'r')
tagger(formula, mat)
# return the properly filled relation matrix of formula
return mat
<file_sep>#True = true
#False = false
#N = Not
#A = And
#O = Or
#G = Always
#E = Eventually
#X = Next
#U = Until
def progress(formula, assignment):
'''
Progression function to update the LTL instructions left to accomplish.
formula: List[List[...]] | List[...] | str
assignment: List[predicates]
'''
# no operator case
if type(formula) == str:
if len(formula) == 1:
return "True" if formula in assignment else "False"
# already a bool str: { "True" | "False" }
return formula
assert len(formula) > 0, "Empty LTL formula."
op = formula[0]
# AND operator
if(op == "A"):
res1 = progress(formula[1], assignment)
res2 = progress(formula[2], assignment)
if res1 == "True" and res2 == "True": return "True"
if res1 == "False" or res2 == "False": return "False"
if res1 == "True": return res2
if res2 == "True": return res1
if res1 == res2: return res1
return ["A", res1, res2]
# OR operator
elif(op == "O"):
res1 = progress(formula[1], assignment)
res2 = progress(formula[2], assignment)
if res1 == "True" or res2 == "True": return "True"
if res1 == "False" and res2 == "False": return "False"
if res1 == "False": return res2
if res2 == "False": return res1
if res1 == res2: return res1
return ["O", res1, res2]
# NOT operator
elif(op == "N"):
res = progress(formula[1], assignment)
if res == "True": return "False"
if res == "False": return "True"
return ["N", res]
# ALWAYS operator
elif(op == "G"):
res = progress(formula[1], assignment)
if res == "False": return "False"
if res == "True": return formula
return ["G", res]
# EVENTUALLY operator
elif(op == "E"):
res = progress(formula[1], assignment)
if res == "True": return "True"
if res == "False": return formula
return ["E", res]
# NEXT operator
elif(op == "X"):
res = progress(formula[1], assignment)
return res
# UNTIL operator
elif(op == "U"):
res1 = progress(formula[1], assignment)
res2 = progress(formula[2], assignment)
if res2 == "True": return "True"
if res1 == "False": return res2
if res2 == "False":
if res1 == "True": return formula
return ["A", res1, formula]
if res1 == "True":
if res2 == "False": return formula
return ["O", res2, formula]
return ["O", res2, ["A", res1, formula]]
else:
# unknown operator found
raise NotImplementedError
def is_accomplished(formula):
'''
Helper function to check for goal satisfying.
Return True in case of only safety constraints left, False otherwise.
'''
# base cases
if type(formula) == str: return False
elif formula[0] == 'G': return True
# recursive calls
return all([is_accomplished(formula[i]) for i in range(1, len(formula))])
if __name__ == "__main__":
assignment = ['r']
# formula = ["E", ["A", "b", ["E", "r"]]]
formula = ['A', ['G', ['N', 'b']], ['E', 'r']]
print(formula)
print(is_accomplished(formula))
result = progress(formula, assignment)
print(result)
print(is_accomplished(result))
<file_sep>import os
import warnings
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Union
import gym
import numpy as np
from stable_baselines3.common import base_class, logger
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.vec_env import DummyVecEnv, VecEnv, sync_envs_normalization
from stable_baselines3.common.callbacks import BaseCallback, EvalCallback
from stable_baselines3.common.utils import safe_mean
class CustomCallback(EvalCallback):
def __init__(
self,
eval_env: Union[gym.Env, VecEnv],
min_ep_rew_mean: float, # new param
callback_on_new_best: Optional[BaseCallback] = None,
n_eval_episodes: int = 5,
eval_freq: int = 10000,
log_path: str = None,
best_model_save_path: str = None,
deterministic: bool = True,
render: bool = False,
verbose: int = 0,
warn: bool = True,
):
super().__init__(eval_env, callback_on_new_best, n_eval_episodes,
eval_freq, log_path, best_model_save_path,
deterministic, render, verbose, warn)
# minimum mean_reward to trigger evaluation callback
self.min_ep_rew_mean = min_ep_rew_mean
def _on_step(self) -> bool:
if(
self.eval_freq > 0 and
self.n_calls % self.eval_freq == 0 and
safe_mean([ep_info['r'] for ep_info in self.model.ep_info_buffer]) >= self.min_ep_rew_mean
):
# Sync training and eval env if there is VecNormalize
sync_envs_normalization(self.training_env, self.eval_env)
# Reset success rate buffer
self._is_success_buffer = []
episode_rewards, episode_lengths = evaluate_policy(
self.model,
self.eval_env,
n_eval_episodes=self.n_eval_episodes,
render=self.render,
deterministic=self.deterministic,
return_episode_rewards=True,
warn=self.warn,
callback=self._log_success_callback,
)
if self.log_path is not None:
self.evaluations_timesteps.append(self.num_timesteps)
self.evaluations_results.append(episode_rewards)
self.evaluations_length.append(episode_lengths)
kwargs = {}
# # Save success log if present
# if len(self._is_success_buffer) > 0:
# self.evaluations_successes.append(self._is_success_buffer)
# kwargs = dict(successes=self.evaluations_successes)
np.savez(
self.log_path,
timesteps=self.evaluations_timesteps,
results=self.evaluations_results,
ep_lengths=self.evaluations_length,
**kwargs,
)
mean_reward, std_reward = np.mean(episode_rewards), np.std(episode_rewards)
mean_ep_length, std_ep_length = np.mean(episode_lengths), np.std(episode_lengths)
self.last_mean_reward = mean_reward
if self.verbose > 0:
print(f"Eval num_timesteps={self.num_timesteps}, " f"episode_reward={mean_reward:.2f} +/- {std_reward:.2f}")
print(f"Episode length: {mean_ep_length:.2f} +/- {std_ep_length:.2f}")
# Add to current Logger
self.logger.record("eval/mean_reward", float(mean_reward))
self.logger.record("eval/mean_ep_length", mean_ep_length)
# success_rate = len(self._is_success_buffer) / float(self.n_eval_episodes)
# if self.verbose > 0:
# print(f"Success rate: {100 * success_rate:.2f}%")
# self.logger.record("eval/success_rate", success_rate)
if mean_reward > self.best_mean_reward:
if self.verbose > 0:
print("New best mean reward!")
if self.best_model_save_path is not None:
self.model.save(os.path.join(self.best_model_save_path, "best_model"))
self.best_mean_reward = mean_reward
# Trigger callback if needed
if self.callback is not None:
return self._on_event()
return True
<file_sep>from gym_minigrid.minigrid import *
from gym_minigrid.register import register
## Colored Goals
class CGoal(WorldObj):
def __init__(self, color):
super().__init__('goal', color)
def can_overlap(self):
return True
def render(self, img):
fill_coords(img, point_in_rect(0, 1, 0, 1), COLORS[self.color])<file_sep>
from math import e
from os import fpathconf
from typing import Callable, Dict, List, Optional, Tuple, Type, Union
import gym
import torch as th
from torch import nn
from envs.ltl_bootcamp import LTLBootcamp
from customcallback import CustomCallback
from stable_baselines3 import PPO
from stable_baselines3.common.policies import ActorCriticPolicy
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.evaluation import evaluate_policy
DEVICE = "cuda" if th.cuda.is_available() else "cpu"
class CustomNetwork(nn.Module):
"""
Custom network for policy and value function.
It receives as input the features extracted by the feature extractor.
:param feature_dim: dimension of the features extracted with the features_extractor (e.g. features from a CNN)
:param last_layer_dim_pi: (int) number of units for the last layer of the policy network
:param last_layer_dim_vf: (int) number of units for the last layer of the value network
"""
def __init__(
self,
feature_dim: int,
last_layer_dim_pi: int = 64,
last_layer_dim_vf: int = 64,
):
super(CustomNetwork, self).__init__()
# IMPORTANT:
# Save output dimensions, used to create the distributions
self.latent_dim_pi = last_layer_dim_pi
self.latent_dim_vf = last_layer_dim_vf
# LTL module
self.ltl_embedder = nn.Embedding(13, 8, padding_idx=0)
self.rnn = nn.GRU(8, 32, num_layers=2, bidirectional=True, batch_first=True)
# Policy network
self.policy_net = nn.Linear(64, last_layer_dim_pi)
# Value network
self.value_net = nn.Linear(64, last_layer_dim_vf)
def forward(self, features: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
"""
:return: (th.Tensor, th.Tensor) latent_policy, latent_value of the specified network.
If all layers are shared, then ``latent_policy == latent_value``
"""
batch_size = features.shape[0]
# LTL module
embedded_formula = self.ltl_embedder(features.to(th.long))
_, h = self.rnn(embedded_formula)
embedded_formula = h[:-2,:,:].transpose(0,1).reshape(batch_size, -1) # [B,64]
# RL module
return self.policy_net(embedded_formula), self.value_net(embedded_formula)
class CustomActorCriticPolicy(ActorCriticPolicy):
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Callable[[float], float],
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None,
activation_fn: Type[nn.Module] = nn.Tanh,
*args,
**kwargs,
):
super(CustomActorCriticPolicy, self).__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
activation_fn,
# Pass remaining arguments to base class
*args,
**kwargs,
)
# Disable orthogonal initialization
self.ortho_init = False
def _build_mlp_extractor(self) -> None:
self.mlp_extractor = CustomNetwork(self.features_dim)
env = LTLBootcamp()
model = PPO(CustomActorCriticPolicy, env, verbose=1, device=DEVICE)
# Training
model.learn(int(1e6))
# Evaluation
mean_rew, std_rew = evaluate_policy(model.policy, Monitor(env),
n_eval_episodes=25,
render=False,
deterministic=False)
print(f"Mean reward: {mean_rew:.2f} +/- {std_rew:.2f}")
# Save LTL module pre-trained weights
th.save(model.policy.mlp_extractor.ltl_embedder.state_dict(), "./pre_logs/weights_ltl.pt")
th.save(model.policy.mlp_extractor.rnn.state_dict(), "./pre_logs/weights_rnn.pt")
<file_sep>
import gym
import torch as th
from custom_policy import CustomActorCriticPolicy
from envs.adversarial import AdversarialEnv9x9
from envs.myopic import AdversarialMyopicEnv9x9
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.evaluation import evaluate_policy
from customcallback import CustomCallback
MYOPIC = False
DEVICE = "cuda" if th.cuda.is_available() else "cpu"
env = AdversarialEnv9x9() if not MYOPIC else AdversarialMyopicEnv9x9()
model = PPO(CustomActorCriticPolicy, env, verbose=1, tensorboard_log="./tensorboard", device=DEVICE)
# Load pre-trained weights for the LTL module
model.policy.mlp_extractor.ltl_embedder.load_state_dict(th.load("./pre_logs/weights_ltl.pt"))
model.policy.mlp_extractor.ga.load_state_dict(th.load("./pre_logs/weights_ga.pt"))
# Callback function to save the best model
eval_callback = CustomCallback(Monitor(env), min_ep_rew_mean=.9, n_eval_episodes=20,
best_model_save_path='./logs/', log_path='./logs/',
eval_freq=int(1e4), verbose=1, render=False)
# Training
model.learn(int(4e6), callback=eval_callback)
# Evaluation
mean_rew, std_rew = evaluate_policy(model.policy, Monitor(env),
n_eval_episodes=25,
render=False,
deterministic=False)
print(f"Mean reward: {mean_rew:.2f} +/- {std_rew:.2f}")
| 620fb01577861d38bccb3bc76b9f455c9a852ad5 | [
"Markdown",
"Python"
] | 14 | Python | bebbo203/LTL2Action | 9aa95881dc2c8c510ea9b452b166b51c9354d7bc | c46ea54722ea930d7f0ca4d7f1dce7cf5a2fa601 |
refs/heads/master | <repo_name>SpotIM/postcss-increase-specificity<file_sep>/README.md
# PostCSS Increase Specificity
[PostCSS](https://github.com/postcss/postcss) plugin to increase the specificity of our selectors.
# Usage
## Basic Example
```
const increaseCssSpecificity = require('@spotim/postcss-increase-specificity');
Webpack usage:
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [
increaseCssSpecificity({id: "#conversation" }),
];
},
},
},
## Results
Input:
```css
body {
background: #485674;
height: 100%;
}
.blocks {
background: #34405B;
}
#main-nav {
color: #ffffff;
}
.foo,
.bar {
display: inline-block;
width: 50%;
}
```
Output (result):
```css
body {
background: #485674;
height: 100%;
}
#conversation#conversation .blocks {
background: #34405B;
}
#conversation#conversation #main-nav {
color: #ffffff;
}
#conversation#conversation .foo,
#conversation#conversation .bar {
display: inline-block;
width: 50%;
}
```
# Why?
After leaving iframe, we're trying to avoid css conflicts between our apps and the publiser css rules.
# What it does? *(by default)*
- repeats every class *repeat* times (default is 2)
# Options
- `repeat`: number - The number of times id is being added before each rule / classes being repeated.
- Default: `2`
- `id`: string - if id is provided, the id is being added to each rule to increase specificity
- `withoutCssLoaderPrefix`: boolean - add your css-loader prefix to your id.
- Default: false
<file_sep>/index.js
var postcss = require("postcss");
var objectAssign = require("object-assign");
var classRepeat = require("class-repeat");
var isPresent = require("is-present");
var hasClass = require("has-class-selector");
require("string.prototype.repeat");
let opts;
function specifyByClassRepeat(root) {
root.walkRules(function (node) {
if (isPresent(node.selectors)) {
node.selectors = node.selectors.map(function (selector) {
return hasClass(selector) ? classRepeat(selector, opts) : selector;
});
}
return node;
});
}
function specifyById(css) {
css.walkRules(function (rule) {
var isInsideKeyframes =
rule.parent.type === "atrule" &&
(rule.parent.name === "keyframes" ||
rule.parent.name === "-webkit-keyframes" ||
rule.parent.name === "webkit-keyframes" ||
rule.parent.name === "-moz-keyframes" ||
rule.parent.name === "-o-keyframes");
if (!isInsideKeyframes) {
increaseSpecifityOfRule(rule, opts);
}
});
}
function increaseSpecifityOfRule(rule, opts) {
rule.selectors = rule.selectors.map(function (selector) {
if (
selector.includes(":root") ||
selector === "html" ||
selector === "body"
) {
return selector;
}
if (opts.withoutCssLoaderPrefix) {
return `:global(${opts.id.repeat(opts.repeat)})` + " " + selector;
}
return opts.id.repeat(opts.repeat) + " " + selector;
});
}
module.exports = postcss.plugin(
"postcss-increase-specificity",
function (options) {
const defaults = {
repeat: 2,
};
opts = objectAssign({}, defaults, options);
let specifyBy = opts.id ? specifyById : specifyByClassRepeat;
return specifyBy;
}
);
| cae6473bc3f5b0b0ae07b4bb3cd421c864842262 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | SpotIM/postcss-increase-specificity | 5fdbdbb18bd8e5b5612dc9f5d4c3127384bfec7e | 48cbe5ca4a62d1989bdea77ad05247f94043fadf |
refs/heads/master | <repo_name>sauloweikert/fincole<file_sep>/crowdfunding/core/admin.py
from django.contrib import admin
from .models import Pesquisador, Instituicao, Projeto
class PesquisadorAdmin(admin.ModelAdmin):
list_display = ('nome','instituicao_origem')
list_filter = ('instituicao_origem',)
admin.site.register(Pesquisador, PesquisadorAdmin)
admin.site.register(Instituicao)
admin.site.register(Projeto)<file_sep>/README.md
# fincole
Sistema web para crowdfunding
pipenv shell
pipenv install django
django-admin startproject crowdfundingd
creates superuser
.<file_sep>/crowdfunding/core/migrations/0003_remove_projeto_foto.py
# Generated by Django 2.2.5 on 2019-09-17 18:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_remove_pesquisador_foto'),
]
operations = [
migrations.RemoveField(
model_name='projeto',
name='foto',
),
]
<file_sep>/crowdfunding/core/migrations/0001_initial.py
# Generated by Django 2.2.5 on 2019-09-08 23:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Instituicao',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Pesquisador',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=70)),
('email', models.EmailField(max_length=254)),
('rg', models.CharField(max_length=12)),
('cpf', models.CharField(max_length=15)),
('foto', models.ImageField(upload_to='pesquisador_fotos')),
('instituicao_origem', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='core.Instituicao')),
],
),
migrations.CreateModel(
name='Projeto',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('titulo', models.CharField(max_length=120)),
('descricao', models.TextField(max_length=500)),
('objetivo', models.IntegerField()),
('arrecadado', models.IntegerField()),
('data_criacao', models.DateTimeField(auto_now_add=True)),
('foto', models.ImageField(upload_to='projeto_fotos')),
('autor', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='core.Pesquisador')),
],
),
]
<file_sep>/crowdfunding/core/views.py
from django.shortcuts import render, redirect
from .models import (
Pesquisador,
Projeto,
Instituicao
)
from .forms import PesquisadorForm, ProjetoForm
def home(request):
return render(request, 'core/index.html')
def lista_pesquisadores(request):
pesquisadores = Pesquisador.objects.all()
form = PesquisadorForm()
data = {'pesquisadores':pesquisadores, 'form': form}
return render(request, 'core/lista_pesquisadores.html', data)
def pesquisador_novo(request):
form = PesquisadorForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('core_lista_pesquisadores')
def pesquisador_update(request, id):
data = {}
pesquisador = Pesquisador.objects.get(id=id)
form = PesquisadorForm(request.POST or None, instance=pesquisador)
data['pesquisador'] = pesquisador
data['form'] = form
if request.method =='POST':
if form.is_valid():
form.save()
return redirect('core_lista_pesquisadores')
else:
return render(request, 'core/update_pesquisador.html',data)
def pesquisador_delete(request, id):
data = {}
pesquisador = Pesquisador.objects.get(id=id)
if request.method == 'POST':
pesquisador.delete()
return redirect('core_lista_pesquisadores')
else:
return render(request, 'core/delete_confirm.html',{'obj':pesquisador})
def lista_projetos(request):
projetos = Projeto.objects.all()
form = ProjetoForm()
data = {'projetos':projetos, 'form': form}
return render(request, 'core/lista_projetos.html',data)
def projeto_novo(request):
form = ProjetoForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('core_lista_projetos')
def projeto_update(request, id):
data = {}
projeto = Projeto.objects.get(id=id)
form = ProjetoForm(request.POST or None, instance=projeto)
data['projeto'] = projeto
data['form'] = form
if request.method =='POST':
if form.is_valid():
form.save()
return redirect('core_lista_projetos')
else:
return render(request, 'core/update_projeto.html',data)
def projeto_delete(request, id):
data = {}
projeto = Projeto.objects.get(id=id)
if request.method == 'POST':
projeto.delete()
return redirect('core_lista_projetos')
else:
return render(request, 'core/delete_confirm.html',{'obj':projeto})
def lista_instituicoes(request):
instituicoes = Instituicao.objects.all()
return render(request, 'core/lista_instituicoes.html',{'instituicoes':instituicoes})<file_sep>/crowdfunding/core/models.py
from django.db import models
class Instituicao(models.Model):
nome = models.CharField(max_length=100)
def __str__(self):
return self.nome
class Pesquisador(models.Model):
nome = models.CharField(max_length=70, null=False)
email = models.EmailField()
rg = models.CharField(max_length=12, null=False)
cpf = models.CharField(max_length=15, null=False)
instituicao_origem = models.ForeignKey(Instituicao, on_delete=models.PROTECT)
#foto = models.ImageField(upload_to='pesquisador_fotos')
def __str__(self):
return self.nome
class Projeto(models.Model):
titulo = models.CharField(max_length=120, null=False)
descricao = models.TextField(max_length=500)
autor = models.ForeignKey(Pesquisador, on_delete=models.PROTECT)
objetivo = models.IntegerField(null=False)
arrecadado = models.IntegerField()
data_criacao = models.DateTimeField(auto_now_add=True)
#foto = models.ImageField(upload_to='projeto_fotos')
def __str__(self):
return self.titulo
<file_sep>/crowdfunding/core/urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from .views import (
home,
lista_pesquisadores,
pesquisador_novo,
pesquisador_update,
pesquisador_delete,
lista_projetos,
projeto_novo,
projeto_update,
projeto_delete,
lista_instituicoes,
)
urlpatterns = [
path('',home, name='core_home'),
path('pesquisadores',lista_pesquisadores, name='core_lista_pesquisadores'),
path('pesquisador-novo',pesquisador_novo, name='core_pesquisador_novo'),
url('pesquisador-update/(?P<id>\d+)/$', pesquisador_update, name='core_pesquisador_update'),
url('pesquisador-delete/(?P<id>\d+)/$', pesquisador_delete, name='core_pesquisador_delete'),
path('projeto-novo',projeto_novo, name='core_projeto_novo'),
path('projetos', lista_projetos, name='core_lista_projetos'),
url('projeto-update/(?P<id>\d+)/$', projeto_update, name='core_projeto_update'),
url('projeto-delete/(?P<id>\d+)/$', projeto_delete, name='core_projeto_delete'),
path('instituicoes', lista_instituicoes, name='core_lista_instituicoes'),
]
<file_sep>/crowdfunding/core/forms.py
from django.forms import ModelForm
from .models import Pesquisador, Projeto
class PesquisadorForm(ModelForm):
class Meta:
model = Pesquisador
fields = '__all__'
class ProjetoForm(ModelForm):
class Meta:
model = Projeto
fields = '__all__' | 84b45e1d19d443a71cf07f4123a22e19e320a1c5 | [
"Markdown",
"Python"
] | 8 | Python | sauloweikert/fincole | b4cb08dd977a3956b54d3b82c687f831aa51046d | 6dfeae285b7225d5e60ffae3d0c719dea6bd35ad |
refs/heads/master | <repo_name>fei6409/IR<file_sep>/main.py
import math
import os.path
import pickle
import subprocess
import sys
import time
import random
import xml.etree.ElementTree as etree
import numpy as np
delim = '\r\n '
def printTime():
print('clock =', time.clock(), file=sys.stderr)
def printAnswer(score, queryID, fp):
for i in range(min(len(score), 200)):
print(score[i], file=sys.stderr)
tree = etree.parse(fileList[score[i][0]])
root = tree.getroot()
name = root.find('doc').find('id').text
print(queryID, name, file=fp)
def grade(queryVec, docsVec):
score = {}
queryWeight = float(np.dot(queryVec, queryVec))
for i in docsVec:
score[i] = float(np.dot(queryVec, docsVec[i])) / math.sqrt( docWeight[i] * queryWeight )
sortedScore = sorted(score.items(), key=lambda x:x[1], reverse=True)
return sortedScore
def RocchioFeedback(queryDic, score):
random.seed()
scoreLen = len(score)
for r in range(10):
r = random.randrange(0, 1000)
rID = score[r][0]
for key in index[rID]:
if key not in queryDic:
queryDic[key] = 0
queryDic[key] += TFIDF[key][rID] * 0.01
printTime()
return queryDic
def genVector(queryDic):
wordID = [c for c in queryDic.keys()]
L = len(wordID)
queryVec = np.zeros(L)
docsVec = {}
for key in queryDic: # may have unigram and bigram
ind = wordID.index(key)
queryVec[ind] = queryDic[key]
for docID in TFIDF[key]:
if docID not in docsVec:
docsVec[docID] = np.zeros(L)
docsVec[docID][ind] = TFIDF[key][docID]
return (queryVec, docsVec)
def addWeight(string, vector, w):
strLen = len(string)
symbol = ',。?!、:;'
i = 0
while i < strLen:
#unigram
id1 = vocab.index(string[i])
if i+1 < strLen:
id2 = vocab.index(string[i+1])
else:
id2 = -1
tup = (id1, id2)
if tup in invIndexBigram:
if tup not in vector:
vector[tup] = 0
vector[tup] += w
if id1 in invIndexUnigram:
if id1 not in vector:
vector[id1] = 0
vector[id1] += w
i += 1
def isChar(char):
return ('a' <= char and char <= 'z') or ('A' <= char and char <= 'Z')
def parseString(string):
ans = []
i = 0
strLen = len(string)
while i < strLen:
if string[i] == ' ': # use delim?
continue
elif isChar(string[i]):
j = i+1
while isChar(string[j]):
j += 1
ans.append(string[i:j])
i = j
if string[j] != ' ':
i -= 1
else:
ans.append(string[i])
i += 1
return ans
def stopWordRemoval(string):
for i in range(len(stopWords)):
while True:
try:
string.remove(stopWords[i])
except:
break
return string
def queryProcess():
print('In query process', file=sys.stderr)
tree = etree.parse(inputFileName)
root = tree.getroot()
nodes = ['title', 'question', 'narrative', 'concepts']
w = [30,4,1,30] #tuning
strings = [ [] for i in range(len(nodes)) ]
fp = open(outputFileName, 'w')
for topic in root:
queryDic = {}
queryID = topic.find('number').text
queryID = queryID[len(queryID)-3:len(queryID)]
print('Query ID =', queryID, file=sys.stderr)
for i in range(len(nodes)):
strings[i] = topic.find(nodes[i]).text.lstrip(delim).rstrip(delim)
strings[i] = stopWordRemoval(strings[i])
strings[i] = parseString(strings[i])
addWeight(strings[i], queryDic, w[i])
print('Query len =', len(queryDic), file=sys.stderr)
(queryVec, docsVec) = genVector(queryDic)
print('#doc =', len(docsVec), file=sys.stderr)
score = grade(queryVec, docsVec)
if releFeedback == True:
print('Doing RocchioFeedback', file=sys.stderr)
queryDic = RocchioFeedback(queryDic, score)
print('Query len =', len(queryDic), file=sys.stderr)
(queryVec, docsVec) = genVector(queryDic)
print('#doc =', len(docsVec), file=sys.stderr)
score = grade(queryVec, docsVec)
printAnswer(score, queryID, fp)
fp.close()
printTime()
def TF_IDF():
print('Doing TF_IDF', file=sys.stderr)
global TFIDF, docWeight, index
if os.path.isfile('TFIDF.dat') and os.path.isfile('docWeight.dat') and os.path.isfile('index.dat'):
f = open('TFIDF.dat', 'rb')
TFIDF = pickle.load(f)
f.close()
f = open('docWeight.dat', 'rb')
docWeight = pickle.load(f)
f.close()
f = open('index.dat', 'rb')
index = pickle.load(f)
f.close()
else:
print('.dat not exist, generating', file=sys.stderr)
TFIDF = {}
docCnt = len(docSize)
avgSize = 0
index = [[] for i in range(docCnt)]
for i in range(docCnt):
avgSize += docSize[i]
avgSize /= docCnt
docWeight = [0 for i in range(docCnt)]
para_b = 0.7 # tuning
d = [(1 - para_b + para_b*docSize[i]/avgSize) for i in range(docCnt)]
for i in invIndexUnigram: # word id
IDF = math.log( docCnt / len(invIndexUnigram[i]) )
TFIDF[i] = {}
for j in invIndexUnigram[i]: # doc id
v = (invIndexUnigram[i][j] / d[j]) * IDF
TFIDF[i][j] = v
docWeight[j] += v * v
index[j].append(i)
for i in invIndexBigram: # word id
IDF = math.log( docCnt / len(invIndexBigram[i]) )
TFIDF[i] = {}
for j in invIndexBigram[i]: # doc id
v = (invIndexBigram[i][j] / d[j]) * IDF
TFIDF[i][j] = v
docWeight[j] += v * v
index[j].append(i)
f = open('TFIDF.dat', 'wb')
pickle.dump(TFIDF, f)
f.close()
f = open('docWeight.dat', 'wb')
pickle.dump(docWeight, f)
f.close()
f = open('index.dat', 'wb')
pickle.dump(index, f)
f.close()
printTime()
def getDocSize():
global docSize
path = 'docSize.dat'
print('Getting doc size', file=sys.stderr)
if os.path.isfile(path) == True:
f = open(path, 'rb')
docSize = pickle.load(f)
f.close()
else:
print('.dat not exist, generating', file=sys.stderr)
docSize = [0 for i in range(len(fileList))]
for i in invIndexUnigram:
for j in invIndexUnigram[i]:
docSize[j] += invIndexUnigram[i][j]
f = open(path, 'wb')
pickle.dump(docSize, f)
f.close()
printTime()
def readFile():
global vocab, fileList, invIndexUnigram, invIndexBigram, stopWords
print('Reading stopword.txt', file=sys.stderr)
f = open('stopword.txt', 'r')
stopWords = [line.rstrip(delim) for line in f.readlines()]
f.close()
print(stopWords, file=sys.stderr)
print('Reading vocab.all', file=sys.stderr)
vocab = []
f = open(os.path.join(modelDir, 'vocab.all'), 'r')
for line in f.readlines():
vocab.append(line.rstrip(delim))
f.close()
print('Reading file-list', file=sys.stderr)
fileList = []
f = open(os.path.join(modelDir, 'file-list'), 'r')
for line in f.readlines():
fileList.append(line.rstrip(delim))
f.close()
print('Reading inverted-index', file=sys.stderr)
invIndexUnigram = {}
invIndexBigram = {}
if os.path.isfile('invIndexUnigram.dat') and os.path.isfile('invIndexUnigram.dat'):
f = open('invIndexUnigram.dat', 'rb')
invIndexUnigram = pickle.load(f)
f.close()
f = open('invIndexBigram.dat', 'rb')
invIndexBigram = pickle.load(f)
f.close()
else:
print('.dat not exist, generating', file=sys.stderr)
f = open(os.path.join(modelDir, 'inverted-index'), 'r')
fileLen = len(fileList)
while True:
line = f.readline()
if(line == ''):
break
(id1, id2, n) = list( map( int, line.split(' ') ) )
if n == 0:
continue
dic = {}
for i in range(n):
subline = f.readline()
(file_id, cnt) = list( map( int, subline.split(' ') ) )
dic[file_id] = cnt
if n > fileLen*0.5:
continue
if id2 == -1:
invIndexUnigram[id1] = dic
else:
invIndexBigram[(id1, id2)] = dic
f = open('invIndexUnigram.dat', 'wb')
pickle.dump(invIndexUnigram, f)
f.close()
f = open('invIndexBigram.dat', 'wb')
pickle.dump(invIndexBigram, f)
f.close()
printTime()
def argvProcess():
global releFeedback, inputFileName, outputFileName, modelDir, ntcirDir
releFeedback = False
for i in range(0, len(sys.argv)):
if sys.argv[i] == '-r':
releFeedback = True
elif sys.argv[i] == '-i':
inputFileName = sys.argv[i+1]
elif sys.argv[i] == '-o':
outputFileName = sys.argv[i+1]
elif sys.argv[i] == '-m':
modelDir = sys.argv[i+1]
elif sys.argv[i] == '-d':
ntcirDir = sys.argv[i+1]
print('relevance feedback: ' + str(releFeedback), file=sys.stderr)
print('query file: ' + inputFileName, file=sys.stderr)
print('ranked list: ' + outputFileName, file=sys.stderr)
print('input model dictionary: ' + modelDir, file=sys.stderr)
print('NTCIR dictionary: ' + ntcirDir, file=sys.stderr)
def main():
argvProcess()
readFile()
getDocSize()
TF_IDF()
queryProcess()
return
if __name__ == '__main__':
main()
| 6f58cb0cdc5c6496077490b3e4d6a9c14b57feae | [
"Python"
] | 1 | Python | fei6409/IR | 69dcde815f33fad5a92b14c03521092addf9d23b | d096eccdd33f50fa256150c1de5ba1304008aaf3 |
refs/heads/master | <repo_name>v-a-l-i-k-o/CryptoS<file_sep>/src/main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';
import Index from './Index.vue';
import router from './router';
Vue.use(VueRouter);
Vue.use(VueResource);
new Vue({
el: '#app',
router,
render: h => h(Index)
});
| e680427ce68a4677cef9e7b5570d9091b7c41b45 | [
"JavaScript"
] | 1 | JavaScript | v-a-l-i-k-o/CryptoS | ca74d77562d1e8f2d48264d32594b9a97100ce63 | 1c3bd0c19b4b70d8375dc5884ce52f756c0a6884 |
refs/heads/master | <repo_name>chrisworld/nn_ku<file_sep>/task4/ModelTester.py
from ErrorCollector import ErrorCollector
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from Model import Model
from ResNetModel import ResNetModel
import logging
import os
# Model Tester class
class ModelTester():
def __init__(self, epochs, learning_rates, n_hidden, n_layer, n_in=300, n_out=26, activation='relu', is_res_net = False):
self.epochs = epochs
self.learning_rates = learning_rates
self.n_hidden = n_hidden
self.n_layer = n_layer
self.models = []
self.n_in = n_in
self.n_out = n_out
self.best_test_acc = 0
self.best_model_param = "None"
self.activation = activation
self.is_res_net = is_res_net
def run(self, train_batches, test_batches):
# training and validation error collector
ec = ErrorCollector()
print("-----ModelTester-----")
logging.info("-----ModelTester-----")
for n_hidden in self.n_hidden:
for n_layer in self.n_layer:
if self.is_res_net:
self.models.append(ResNetModel(n_in=self.n_in, n_hidden=n_hidden, n_out=self.n_out, n_layer=n_layer, activation='relu'))
else:
for activation in self.activation:
# create models
self.models.append(Model(n_in=self.n_in, n_hidden=n_hidden, n_out=self.n_out, n_layer=n_layer, activation=activation))
for model in self.models:
trainer = Trainer(model, train_batches, ec)
for learning_rate in self.learning_rates:
trainer.train(learning_rate, self.epochs, early_stop_lim=25)
# print error plots
ec.plotTrainTestError(model, train_batches.batch_size, learning_rate, self.epochs, model.activation)
ec.plotTrainTestAcc(model, train_batches.batch_size, learning_rate, self.epochs, model.activation)
ec.resetErrors()
evaluator = Evaluator(model, test_batches, trainer.getSaveFilePath())
test_loss, test_acc = evaluator.eval()
trainer.resetBestScore()
if self.best_test_acc == 0 or test_acc > self.best_test_acc:
self.best_test_acc = test_acc
self.best_model_param = 'Param_' + model.name + '_ep-' + str(self.epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate)
print("-----ModelTester finished, best test acc: [%.6f] with model: %s " % (self.best_test_acc, self.best_model_param))
logging.info("-----ModelTester finished, best test acc: [%.6f] with model: %s " % (self.best_test_acc, self.best_model_param))
<file_sep>/task4/ResNetModel.py
import tensorflow as tf
import numpy as np
import numpy.random as rd
# ResNetModel
class ResNetModel():
def __init__(self, n_in, n_hidden, n_out, n_layer=1, activation='relu'):
self.name = 'ResNet_Model'
self.n_in = n_in
self.n_hidden = n_hidden
self.n_out = n_out
self.n_layer = n_layer
self.n_resnet_blocks = int(n_layer/2)
self.activation = activation
# Weights, biases and activations
self.W = []
self.b = []
self.h = []
print('---Create ResNet Model--- ')
# create list of weights and biases upon each layers
# input layer
print('Input W/b')
self.W.append(tf.Variable(rd.randn(self.n_in, self.n_hidden) / np.sqrt(self.n_in), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
if self.n_resnet_blocks != 0:
# create resnet blocks
for block in range(self.n_resnet_blocks):
print('ResNet W/b at Block: ', block)
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_hidden) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_hidden) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
print('Output W/b')
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_out) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_out), trainable=True))
# Define the neuron operations
# input layer
layer = 0
self.x = tf.placeholder(shape=(None, self.n_in),dtype=tf.float64)
self.h.append(tf.nn.relu(tf.matmul(self.x, self.W[layer]) + self.b[layer]))
layer += 1
# create resnet blocks
if self.n_resnet_blocks != 0:
for block in range(self.n_resnet_blocks):
print('Activations of block: ', block)
print('--activation at layer: ', layer)
self.h.append(tf.nn.relu(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer]))
layer += 1
print('--activation at layer: ', layer)
self.h.append(tf.nn.relu(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer] + self.h[layer-2]))
layer += 1
# output activation
#if n_layer == 0:
# self.z = tf.nn.softmax(tf.matmul(self.x, self.W[n_layer]) + self.b[n_layer])
#else:
self.z = tf.nn.softmax(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer])
# labels
self.z_ = tf.placeholder(shape=(None, self.n_out),dtype=tf.float64)
#loss
self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.z_ * tf.log(self.z), reduction_indices=[1]))
#self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = self.z, labels = self.z_))
<file_sep>/task5/debug_aa.py
from ErrorCollector import ErrorCollector
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from ReberBatches import ReberBatches
from RnnModel import RnnModel
from RnnModelTester import RnnModelTester
import numpy as np
import logging
import os
# Main function
if __name__ == '__main__':
# setup logging
log_file_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'logs' + os.sep
log_file_name = "Model.log"
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
logging.basicConfig(filename=log_file_path + log_file_name, level=logging.INFO)
# Parameters and model
epochs = 50
#learning_rates = [1e-2,1e-2,1e-2,1e-2,1e-2,1e-2,1e-2,1e-2,1e-2,1e-2]
learning_rates = [1e-1 ,1e-2, 1e-3, 1e-4, 1e-5]
n_hidden = [14] # number of hidden units within layer
n_layer = [1] # number of hidden layers
activation = ['relu', 'tanh']
batch_size = 40
n_train_samples, n_val_samples, n_test_samples = 5000, 500, 500
reber_batches = ReberBatches(n_train_samples, n_val_samples, n_test_samples, batch_size)
max_sequence_length = reber_batches.train_max_seq_len
#model_tester = RnnModelTester(epochs, learning_rates, max_sequence_length, n_layer, n_hidden, n_symbols=7,
# n_out=7, rnn_unit='lstm')
model_tester = RnnModelTester(epochs, learning_rates, n_layer, n_hidden,adam_optimizer=False)
model_tester.run(reber_batches)
<file_sep>/task2/main.py
from nn18_ex2_load import load_isolet
from BatchNormalizer import BatchNormalizer
from ClassifiedBatches import ClassifiedBatches
import numpy as np
def main():
X, C, X_tst, C_tst = load_isolet()
#print(X)
Y=np.array([[1,2,3,4]])
#print(X.shape)
#print(C)
#print(C.shape)
b1 = BatchNormalizer(X,C,batch_size=40,shuffle=True)
train = b1.getBatches(X,C)
test = b1.getBatches(X_tst,C_tst,test=True)
#print(b1.cbatches.batch_num)
print(X.shape)
print(X_tst.shape)
#b1.normalize()
if __name__ == '__main__':
main()
<file_sep>/task2/Trainer.py
# Trainer class for training Neural Networks
import tensorflow as tf
import logging
import os
from Evaluator import Evaluator
class Trainer():
def __init__(self, model, batches, error_collector):
self.model = model
self.batches = batches
self.error_collector = error_collector
self.best_validation_loss = 0
self.best_validation_acc = 0
self.best_epoch = 0
#self.save_path = os.path.realpath(__file__)
self.save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'tmp' + os.sep
self.file_name = ""
#self.save_path = os.path.normpath(join(os.getcwd(), path)) + '/tmp'
def train(self, learning_rate, epochs, early_stop_lim=1000):
# save parameter file name
self.file_name = 'Param_ep-' + str(epochs) + '_hidu-' + str(self.model.n_hidden) + '_hidl-' + str(self.model.n_layer) + '_lr-' + str(learning_rate) + '.ckpt'
# setup training
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(self.model.cross_entropy)
correct_prediction = tf.equal(tf.argmax(self.model.z,1), tf.argmax(self.model.z_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
# init variables
init = tf.global_variables_initializer()
# save variables
saver = tf.train.Saver()
# logging infos
print("-----Training-----")
print('Epochs: ' + str(epochs) + ', Hidden Units: ' + str(self.model.n_hidden) + ', HiddenLayer: ' + str(self.model.n_layer) + ', LearningRate: ' + str(learning_rate))
logging.info("-----Training-----")
logging.info('Epochs: ' + str(epochs) + ', Hidden Units: ' + str(self.model.n_hidden) + ', HiddenLayer: ' + str(self.model.n_layer) + ', LearningRate: ' + str(learning_rate))
early_stop_counter = 0
with tf.Session() as sess:
sess.run(init)
# run epochs
for k in range(epochs):
# gradient over each batch
for batch_example, batch_class in zip(self.batches.batch_examples_train, self.batches.batch_classes_train):
# training step
sess.run(train_step, feed_dict={self.model.x: batch_example, self.model.z_: batch_class})
# Compute the errors and acc over the training dataset
train_loss = sess.run(self.model.cross_entropy, feed_dict={self.model.x: self.batches.examples_train, self.model.z_: self.batches.classes_train})
train_acc = sess.run(accuracy, feed_dict={self.model.x: self.batches.examples_train, self.model.z_: self.batches.classes_train})
self.error_collector.addTrainError(train_loss)
self.error_collector.addTrainAcc(train_acc)
# Compute the errors and acc of the validation set
test_loss = sess.run(self.model.cross_entropy, feed_dict={self.model.x: self.batches.examples_validation, self.model.z_: self.batches.classes_validation})
test_acc = sess.run(accuracy, feed_dict={self.model.x: self.batches.examples_validation, self.model.z_: self.batches.classes_validation})
self.error_collector.addTestError(test_loss)
self.error_collector.addTestAcc(test_acc)
# Early stopping, save best parameters
if self.batches.is_validation == True:
if self.best_validation_loss == 0 or test_loss < self.best_validation_loss:
#print("---Model saved: %s" % self.save_path + self.file_name)
saver.save(sess, self.save_path + self.file_name)
self.best_validation_loss = test_loss
self.best_validation_acc = test_acc
self.best_epoch = k
early_stop_counter = 0
else:
early_stop_counter += 1
# stop the training if no improvement
if early_stop_counter > early_stop_lim:
print("---end due to early stopping limit")
logging.info("---end due to early stopping limit")
break
# logging iterations
print("Iteration: ",k, " train loss: [%.4f]" % train_loss, " train acc: [%.4f]" % train_acc, " valid loss: [%.4f]" % test_loss, " valid acc: [%.4f]" % test_acc)
logging.info("Iteration: %i" % k + " train loss: [%.4f]" % train_loss + " train acc: [%.4f]" % train_acc + " valid loss: [%.4f]" % test_loss + " valid acc: [%.4f]" % test_acc)
if self.batches.is_validation == False:
saver.save(sess, self.save_path + self.file_name)
# finish log
print("-----Training finished with best validation loss: [%.4f] validation acc: [%.4f] at epoch:[%i]" %(self.best_validation_loss, self.best_validation_acc, self.best_epoch) )
logging.info("-----Training finished with best validation loss: [%.4f] validation acc: [%.4f] at epoch:[%i]" %(self.best_validation_loss, self.best_validation_acc, self.best_epoch ) )
# returns the path of saved model
def getSaveFilePath(self):
return self.save_path + self.file_name
def resetBestScore(self):
self.best_validation_loss = 0
self.best_validation_acc = 0
self.best_epoch = 0
<file_sep>/task4/Model.py
import tensorflow as tf
import numpy as np
import numpy.random as rd
# Feedforward Model
class Model():
def __init__(self, n_in, n_hidden, n_out, n_layer=1, activation='relu'):
self.name = 'FeedForward_Model'
self.n_in = n_in
self.n_hidden = n_hidden
self.n_out = n_out
self.n_layer = n_layer
self.activation = activation
# Weights, biases and activations
self.W = []
self.b = []
self.h = []
print('---Create Model--- ')
# create list of weights and biases upon each layers
for layer in range(n_layer + 1):
# set connections upon layer
if layer == 0:
print('Input W/b in layer: ', layer)
if n_layer == 0:
self.W.append(tf.Variable(rd.randn(self.n_in, self.n_out) / np.sqrt(self.n_in), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_out), trainable=True))
else:
self.W.append(tf.Variable(rd.randn(self.n_in, self.n_hidden) / np.sqrt(self.n_in), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
elif layer == n_layer:
print('Output W/b in layer: ', layer)
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_out) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_out), trainable=True))
else:
print('Hidden W/b in layer: ', layer)
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_hidden) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
# Define the neuron operations
# input layer
self.x = tf.placeholder(shape=(None, self.n_in),dtype=tf.float64)
# connections and activation of hidden layer
for layer in range(n_layer):
if self.activation == 'tanh':
if layer == 0:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.tanh(tf.matmul(self.x, self.W[0]) + self.b[0]))
else:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.tanh(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer]))
elif self.activation == 'relu':
if layer == 0:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.relu(tf.matmul(self.x, self.W[0]) + self.b[0]))
else:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.relu(tf.matmul(self.h[layer - 1], self.W[layer]) + self.b[layer]))
# output activation
if n_layer == 0:
self.z = tf.nn.softmax(tf.matmul(self.x, self.W[n_layer]) + self.b[n_layer])
else:
self.z = tf.nn.softmax(tf.matmul(self.h[n_layer-1], self.W[n_layer]) + self.b[n_layer])
# labels
self.z_ = tf.placeholder(shape=(None, self.n_out),dtype=tf.float64)
#loss
self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.z_ * tf.log(self.z), reduction_indices=[1]))
#self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = self.z, labels = self.z_))
<file_sep>/task4/main.py
from nn18_ex2_load import load_isolet
from BatchNormalizer import BatchNormalizer
import numpy as np
def main():
X, C, X_tst, C_tst = load_isolet()
#print(X)
Y=np.array([[1,2,3,4]])
print(X.shape)
#print(C)
#print(C.shape)
b1 = BatchNormalizer(X)
b1.getMean()
b1.getStd()
b1.getNormalized()
b1.getBatches()
#b1.normalize()
if __name__ == '__main__':
main()
<file_sep>/task4/debug_cw.py
from ErrorCollector import ErrorCollector
from BatchNormalizer import BatchNormalizer
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from Model import Model
from ResNetModel import ResNetModel
from ModelTester import ModelTester
from nn18_ex2_load import load_isolet
import numpy as np
import logging
import os
# Main function
if __name__ == '__main__':
X, C, X_tst, C_tst = load_isolet()
# setup logging
log_file_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'logs' + os.sep
log_file_name = "Model.log"
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
logging.basicConfig(filename=log_file_path + log_file_name, level=logging.INFO)
# Parameters and model
epochs = 200
learning_rate = [3e-5]
n_hidden = [40] # number of hidden units within layer
n_layer = [49] # number of hidden layers
#activation = ['relu', 'tanh']
activation = ['relu']
batch_size = 20
# Batch Normalizer
bn = BatchNormalizer(X, C, batch_size=batch_size, shuffle=True)
train_batches = bn.getBatches(X, C)
test_batches = bn.getBatches(X_tst, C_tst, test=True)
# use Test set as Validation
train_batches.examples_validation = test_batches.examples_validation
train_batches.classes_validation = test_batches.classes_validation
# Testing Models
model_tester = ModelTester(epochs, learning_rate, n_hidden, n_layer, activation=activation, is_res_net = False)
model_tester.run(train_batches, test_batches)
resnet_tester = ModelTester(epochs, learning_rate, n_hidden, n_layer, activation=activation, is_res_net = True)
# get the best from the other model tester
resnet_tester.best_test_acc = model_tester.best_test_acc
resnet_tester.best_model_param = model_tester.best_model_param
# run test
resnet_tester.run(train_batches, test_batches)
<file_sep>/task2/debug_cw_model.py
from ErrorCollector import ErrorCollector
from BatchNormalizer import BatchNormalizer
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from Model import Model
from ModelTester import ModelTester
from nn18_ex2_load import load_isolet
import numpy as np
import logging
import os
# Main function
if __name__ == '__main__':
X, C, X_tst, C_tst = load_isolet()
# Parameters and model
epochs = 100
#learning_rates = [0.01]
learning_rates = [0.01]
#n_hidden = [150, 300, 600]
n_hidden = [150]
#n_layer = [0, 1, 2]
n_layer = [0, 1]
batch_size = 40
# Batch Normalizer
bn = BatchNormalizer(X, C, batch_size=batch_size, shuffle=True)
train_batches = bn.getBatches(X, C)
test_batches = bn.getBatches(X_tst, C_tst, test=True)
model_tester = ModelTester(epochs, learning_rates, n_hidden, n_layer)
model_tester.run(train_batches, test_batches)
# run best model at best epoch with whole training set and use test set as validation
epochs = 123
learning_rates = [0.01]
n_hidden = [150]
n_layer = [1]
train_batches = bn.getBatches(X, C, is_validation=False)
# use Test set as Validation
train_batches.examples_validation = test_batches.examples_validation
train_batches.classes_validation = test_batches.classes_validation
model_tester = ModelTester(epochs, learning_rates, n_hidden, n_layer)
model_tester.run(train_batches, test_batches)
<file_sep>/task2/debug_cw.py
from ErrorCollector import ErrorCollector
from BatchNormalizer import BatchNormalizer
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from Model import Model
from nn18_ex2_load import load_isolet
import numpy as np
import logging
import os
if __name__ == '__main__':
# training and validation error collector
ec = ErrorCollector()
X, C, X_tst, C_tst = load_isolet()
#print("X shape: ", X.shape[0])
#print("X shape: ", X.shape[1])
# Parameters and model
epochs = 5
#learning_rate = 0.001
learning_rate = 0.01
model = Model(n_in=X.shape[1], n_hidden=300, n_out=26, n_layer=1)
batch_size = 40
# setup logging
log_file_name = 'logs' + os.sep + 'Log' + '_ep' + str(epochs) + '_hidu' + str(model.n_hidden) + '_hidl' + str(model.n_layer) + '_lr' + str(learning_rate) + '.log'
logging.basicConfig(filename=log_file_name, level=logging.INFO)
# Batch Normalize
bn = BatchNormalizer(X, C, batch_size=batch_size, shuffle=True)
train_batches = bn.getBatches(X, C, is_validation=False)
test_batches = bn.getBatches(X_tst, C_tst, test=True)
print('examples to train: ', train_batches.examples_train.shape)
# Training
trainer = Trainer(model, train_batches, ec)
trainer.train(learning_rate, epochs, early_stop_lim=25)
# print error plots
ec.plotTrainTestError(model, batch_size, learning_rate, epochs)
ec.plotTrainTestAcc(model, batch_size, learning_rate, epochs)
# Testing
evaluator = Evaluator(model, test_batches, trainer.getSaveFilePath())
evaluator.eval()
<file_sep>/task5/ErrorCollector.py
import matplotlib.pyplot as plt
import os
import numpy as np
import logging
class ErrorCollector():
def __init__(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
self.convergence_time_list = []
def resetErrors(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def addConvergenceTime(self, epoch):
#test_error_array = np.array(self.test_error_list)
#epoch_of_convergence = np.nonzero(test_error_array<1e-7)[0][0] + 1
#self.convergence_time_list.append(epoch_of_convergence)
self.convergence_time_list.append(epoch)
def convergenceTimeMeanAndStd(self):
convergence_time_mean = np.mean(self.convergence_time_list)
convergence_time_std = np.std(self.convergence_time_list)
print("-----ModelTester Convergence Time of Models-----")
print("convergence time in epochs\nmean: [%.2f]\n standard deviation: [%.2f]" %(convergence_time_mean,convergence_time_std))
logging.info("convergence time in epochs\nmean: [%.2f]\n standard deviation: [%.2f]" %(convergence_time_mean,convergence_time_std))
return convergence_time_mean, convergence_time_std
def addTrainError(self, train_error):
self.train_error_list.append(train_error)
def addTestError(self, test_error):
self.test_error_list.append(test_error)
def addTrainAcc(self, train_acc):
self.train_acc_list.append(1-train_acc) # actually it's misclassification
def addTestAcc(self, test_acc):
self.test_acc_list.append(1-test_acc)
def plotTrainTestError(self, model, batch_size, learning_rate, epochs, plot_id):
print("Plot Errors")
fig, ax = plt.subplots(1)
ax.plot(self.train_error_list, color='blue', label='training', lw=2)
ax.plot(self.test_error_list, color='red', label='test/validation', lw=1.7, linestyle= '--',alpha=0.9)
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Cross-entropy loss')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Loss_' + model.name + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_opt-'+ str(model.optimizer_name) + '_lr-' + str(learning_rate) + '_id-' + str(plot_id) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
def plotTrainTestAcc(self, model, batch_size, learning_rate, epochs):
print("Plot Misclassification")
fig, ax = plt.subplots(1)
ax.plot(self.train_acc_list, color='blue', label='training', lw=2)
ax.plot(self.test_acc_list, color='green', label='test', lw=2)
ax.set_autoscaley_on(False)
ax.set_ylim([0, 1])
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Misclassification')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Misclass_'+ model.name + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
<file_sep>/task5/debug_cw.py
from ErrorCollector import ErrorCollector
from ReberBatches import ReberBatches
from Trainer import Trainer
from Evaluator import Evaluator
from RnnModelTester import RnnModelTester
from grammar import *
import numpy as np
import logging
import os
# Main function
if __name__ == '__main__':
# setup logging
log_file_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'logs' + os.sep
log_file_name = "Model.log"
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
logging.basicConfig(filename=log_file_path + log_file_name, level=logging.INFO)
# Parameters and model
epochs = 100
learning_rates = [1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2]
n_hidden = [14] # number of hidden units within layer
n_layer = [1] # number of hidden layers
rnn_unit = ['lstm']
adam_optimizer = True
# Get Grammar data
batch_size = 40
n_train_samples = 5000
n_val_samples = 500
n_test_samples = 500
# Create Reber Batches
reber_batches = ReberBatches(n_train_samples, n_val_samples, n_test_samples, batch_size)
# Model Testing
model_tester = RnnModelTester(epochs, learning_rates, n_layer, n_hidden, rnn_unit=rnn_unit, adam_optimizer=adam_optimizer)
model_tester.run(reber_batches)
<file_sep>/task5/ReberBatches.py
import numpy as np
from grammar import *
class ReberBatches():
def __init__(self, n_train_samples, n_val_samples, n_test_samples, batch_size, sym_size=7):
self.n_train_samples = n_train_samples
self.n_val_samples = n_val_samples
self.n_test_samples = n_test_samples
self.batch_size = batch_size
self.sym_size = sym_size
self.max_seq_len = 0
# always has validation set
self.is_validation = True
# lists
examples_train_list = []
seq_len_train_list = []
targets_train_list = []
examples_val_list = []
targets_val_list = []
examples_test_list = []
targets_test_list = []
# max length of sequence
self.train_max_seq_len = 0
self.val_max_seq_len = 0
self.test_max_seq_len = 0
# create list of training examples
for n in range(n_train_samples):
example = make_embedded_reber()
label = str_to_vec(example)
target = str_to_next_embed(example)
example_len = len(example)
seq_len_train_list.append(example_len)
if self.train_max_seq_len < example_len:
self.train_max_seq_len = example_len
examples_train_list.append(label)
targets_train_list.append(target)
# create list of validation examples
for n in range(n_val_samples):
example = make_embedded_reber()
label = str_to_vec(example)
target = str_to_next_embed(example)
example_len = len(example)
if self.val_max_seq_len < example_len:
self.val_max_seq_len = example_len
examples_val_list.append(label)
targets_val_list.append(target)
# create list of test examples
for n in range(n_test_samples):
example = make_embedded_reber()
label = str_to_vec(example)
target = str_to_next_embed(example)
example_len = len(example)
if self.test_max_seq_len < example_len:
self.test_max_seq_len = example_len
examples_test_list.append(label)
targets_test_list.append(target)
# max seq length of all reber strings
self.max_seq_len = max(self.train_max_seq_len, self.val_max_seq_len, self.test_max_seq_len)
# create 0-padded numpy matrix for train
self.examples_train = np.zeros((n_train_samples, self.max_seq_len, sym_size))
self.seq_len_train = np.zeros(n_train_samples)
self.targets_train = np.zeros((n_train_samples, self.max_seq_len, sym_size))
for sample_idx in range(n_train_samples):
self.seq_len_train[sample_idx] = self.max_seq_len
for str_idx in range(examples_train_list[sample_idx].shape[0]):
self.examples_train[sample_idx][str_idx] = examples_train_list[sample_idx][str_idx]
self.targets_train[sample_idx][str_idx] = targets_train_list[sample_idx][str_idx]
# create 0-padded numpy matrix for validation
self.examples_val = np.zeros((n_val_samples, self.max_seq_len, sym_size))
self.seq_len_val = np.zeros(n_val_samples)
self.targets_val = np.zeros((n_val_samples, self.max_seq_len, sym_size))
for sample_idx in range(n_val_samples):
self.seq_len_val[sample_idx] = self.max_seq_len
for str_idx in range(examples_val_list[sample_idx].shape[0]):
self.examples_val[sample_idx][str_idx] = examples_val_list[sample_idx][str_idx]
self.targets_val[sample_idx][str_idx] = targets_val_list[sample_idx][str_idx]
# create 0-padded numpy matrix for test
self.examples_test = np.zeros((n_test_samples, self.max_seq_len, sym_size))
self.seq_len_test = np.zeros(n_test_samples)
self.targets_test = np.zeros((n_test_samples, self.max_seq_len, sym_size))
for sample_idx in range(n_test_samples):
self.seq_len_test[sample_idx] = self.max_seq_len
for str_idx in range(examples_test_list[sample_idx].shape[0]):
self.examples_test[sample_idx][str_idx] = examples_test_list[sample_idx][str_idx]
self.targets_test[sample_idx][str_idx] = targets_test_list[sample_idx][str_idx]
# create training batches
# number of batches corresponding to batch_size
self.batch_num = np.ceil(self.examples_train.shape[0] / batch_size)
self.batch_num_val = np.ceil(self.examples_val.shape[0] / batch_size)
self.batch_num_test = np.ceil(self.examples_test.shape[0] / batch_size)
# split all examples and classes
self.batch_examples_train = np.array_split(self.examples_train, self.batch_num)
self.batch_target_train = np.array_split(self.targets_train, self.batch_num)
self.batch_seq_len_train = np.array_split(self.seq_len_train, self.batch_num)
self.batch_seq_len_val = np.array_split(self.seq_len_val, self.batch_num_val)
self.batch_seq_len_test = np.array_split(self.seq_len_test, self.batch_num_test)
<file_sep>/task2/ModelTester.py
from ErrorCollector import ErrorCollector
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from Model import Model
import logging
import os
class ModelTester():
def __init__(self, epochs, learning_rates, n_hidden, n_layer, n_in=300, n_out=26):
self.epochs = epochs
self.learning_rates = learning_rates
self.n_hidden = n_hidden
self.n_layer = n_layer
self.models = []
self.n_in = n_in
self.n_out = n_out
self.best_test_acc = 0
self.best_model_param = "None"
def run(self, train_batches, test_batches):
# training and validation error collector
ec = ErrorCollector()
# setup logging
log_file_name = 'logs' + os.sep + 'Model_Trainer.log'
logging.basicConfig(filename=log_file_name, level=logging.INFO)
print("-----ModelTester-----")
logging.info("-----ModelTester-----")
for n_hidden in self.n_hidden:
for n_layer in self.n_layer:
# create models
self.models.append(Model(n_in=self.n_in, n_hidden=n_hidden, n_out=self.n_out, n_layer=n_layer))
for model in self.models:
trainer = Trainer(model, train_batches, ec)
for learning_rate in self.learning_rates:
trainer.train(learning_rate, self.epochs, early_stop_lim=25)
# print error plots
ec.plotTrainTestError(model, train_batches.batch_size, learning_rate, self.epochs)
ec.plotTrainTestAcc(model, train_batches.batch_size, learning_rate, self.epochs)
ec.resetErrors()
evaluator = Evaluator(model, test_batches, trainer.getSaveFilePath())
test_loss, test_acc = evaluator.eval()
trainer.resetBestScore()
if self.best_test_acc == 0 or test_acc > self.best_test_acc:
self.best_test_acc = test_acc
self.best_model_param = 'Param_ep-' + str(self.epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate)
print("-----ModelTester finished, best test acc: [%.6f] with model: %s " % (self.best_test_acc, self.best_model_param))
logging.info("-----ModelTester finished, best test acc: [%.6f] with model: %s " % (self.best_test_acc, self.best_model_param))
<file_sep>/task4/Evaluator.py
import tensorflow as tf
import logging
# Evaluator class
class Evaluator():
def __init__(self, model, batches, save_path):
self.model = model
self.batches = batches
self.save_path = save_path
def eval(self):
# evaluation
correct_prediction = tf.equal(tf.argmax(self.model.z,1), tf.argmax(self.model.z_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
# restore parameters
saver = tf.train.Saver()
print("-----Evaluation of Test set-----")
logging.info("-----Evaluation of Test set-----")
# evaluate tf graph
with tf.Session() as sess:
saver.restore(sess, self.save_path)
test_loss = sess.run(self.model.cross_entropy, feed_dict={self.model.x: self.batches.examples, self.model.z_: self.batches.classes})
test_acc = sess.run(accuracy, feed_dict={self.model.x: self.batches.examples, self.model.z_: self.batches.classes})
print("test loss: [%.6f]" % test_loss, " test acc: [%.6f]" % test_acc)
logging.info("test loss: [%.6f]" % test_loss + " test acc: [%.6f]" % test_acc)
return test_loss, test_acc
<file_sep>/task5/RnnModel.py
import tensorflow as tf
import numpy as np
import numpy.random as rd
# ResNetModel
class RnnModel():
def __init__(self, n_symbols, n_hidden, n_out, rnn_unit, max_sequence_length, n_layer, adam_optimizer):
self.name = 'RNN_Model_' + rnn_unit
self.n_symbols = n_symbols
self.n_hidden = n_hidden
self.n_out = n_out
self.n_layer = n_layer
self.cell_type = rnn_unit
self.max_sequence_length = max_sequence_length
self.adam_optimizer = adam_optimizer
# Set optimizer
if adam_optimizer == True:
self.optimizer_name = 'Adam'
else:
self.optimizer_name = 'GD'
print('---Create ' + self.name + '---')
self.seq_length = tf.placeholder(tf.int32, [None])
self.X = tf.placeholder(tf.float32, [None, self.max_sequence_length, self.n_symbols])
#labels
self.z_ = tf.placeholder(tf.float32, [None, self.max_sequence_length, self.n_symbols])
# define recurrent layer
if self.cell_type == 'simple':
cell = tf.nn.rnn_cell.BasicRNNCell(n_hidden)
# cell = tf.keras.layers.SimpleRNNCell(num_hidden) #alternative
elif self.cell_type == 'lstm':
cell = tf.nn.rnn_cell.LSTMCell(n_hidden)
elif self.cell_type == 'gru':
cell = tf.nn.rnn_cell.GRUCell(n_hidden)
else:
raise ValueError('bad cell type.')
cell = tf.contrib.rnn.OutputProjectionWrapper(cell, self.n_out, reuse=tf.AUTO_REUSE)
outputs, states = tf.nn.dynamic_rnn(cell, self.X, dtype=tf.float32, sequence_length=self.seq_length)
self.last_outputs = outputs[:,-1,:]
# define loss, minimizer and error
self.cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=outputs, labels=self.z_)
self.mistakes = tf.not_equal(self.z_, tf.maximum(tf.sign(outputs), 0))
self.error = tf.reduce_mean(tf.cast(self.mistakes, tf.float32))
# This is incorporated in the Trainer
#correct_prediction = tf.equal(y, tf.maximum(tf.sign(y_pred), 0))
#accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
<file_sep>/README.md
# nn_ku
Neural Network Konstruction Exercise
<file_sep>/task5/Evaluator.py
import tensorflow as tf
import logging
# Evaluator class
class Evaluator():
def __init__(self, model, batches, save_path):
self.model = model
self.batches = batches
self.save_path = save_path
def eval(self):
# evaluation
correct_prediction = tf.equal(self.model.z_, tf.maximum(tf.sign(self.model.last_outputs), 0))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# restore parameters
saver = tf.train.Saver()
print("-----Evaluation of Test set-----")
logging.info("-----Evaluation of Test set-----")
# evaluate tf graph
with tf.Session() as sess:
saver.restore(sess, self.save_path)
#test_loss = sess.run(self.model.error, feed_dict={self.model.X: self.batches.examples_test, self.model.z_: self.batches.targets_test})
test_loss = sess.run(self.model.error, feed_dict={self.model.X: self.batches.examples_test,
self.model.z_: self.batches.targets_test,
self.model.seq_length: self.batches.seq_len_test})
#test_acc = sess.run(accuracy, feed_dict={self.model.X: self.batches.examples_test, self.model.z_: self.batches.targets_test})
print("test loss: [%.6f]" % test_loss)#, " test acc: [%.6f]" % test_acc)
logging.info("test loss: [%.6f]" % test_loss)# + " test acc: [%.6f]" % test_acc)
return test_loss#, test_acc
<file_sep>/task2/ErrorCollector.py
import matplotlib.pyplot as plt
class ErrorCollector():
def __init__(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def resetErrors(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def addTrainError(self, train_error):
self.train_error_list.append(train_error)
def addTestError(self, test_error):
self.test_error_list.append(test_error)
def addTrainAcc(self, train_acc):
self.train_acc_list.append(train_acc)
def addTestAcc(self, test_acc):
self.test_acc_list.append(test_acc)
def plotTrainTestError(self, model, batch_size, learning_rate, epochs):
print("Plot Errors")
fig, ax = plt.subplots(1)
ax.plot(self.train_error_list, color='blue', label='training', lw=2)
ax.plot(self.test_error_list, color='green', label='validation', lw=2)
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Cross-entropy loss')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_name = 'plots/' + 'Loss' + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
plt.savefig(save_name, dpi=150, bbox_inches='tight')
#plt.show()
def plotTrainTestAcc(self, model, batch_size, learning_rate, epochs):
print("Plot Accuracy")
fig, ax = plt.subplots(1)
ax.plot(self.train_acc_list, color='blue', label='training', lw=2)
ax.plot(self.test_acc_list, color='green', label='validation', lw=2)
ax.set_autoscaley_on(False)
ax.set_ylim([0, 1])
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Accuracy')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_name = 'plots/' + 'Accuracy' + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
plt.savefig(save_name, dpi=150, bbox_inches='tight')
#plt.show()
<file_sep>/task5/RnnModelTester.py
from ErrorCollector import ErrorCollector
from ClassifiedBatches import ClassifiedBatches
from Trainer import Trainer
from Evaluator import Evaluator
from RnnModel import RnnModel
import logging
import os
# Model Tester class
class RnnModelTester():
def __init__(self, epochs, learning_rates, n_layer, n_hidden, n_symbols=7,
n_out=7, rnn_unit='lstm', adam_optimizer=True):
self.epochs = epochs
self.learning_rates = learning_rates
self.n_hidden = n_hidden
self.n_layer = n_layer
self.models = []
self.n_out = n_out
self.best_test_loss = 0
self.best_conv_time = 100000
self.best_model_param = "None"
self.n_symbols = n_symbols
self.rnn_unit = rnn_unit
self.adam_optimizer = adam_optimizer
def run(self, batches):
# training and validation error collector
ec = ErrorCollector()
print("-----ModelTester-----")
logging.info("-----ModelTester-----")
# create models
for n_hidden in self.n_hidden:
for n_layer in self.n_layer:
for rnn_unit in self.rnn_unit:
print("RNN with max seq len: ", batches.max_seq_len)
self.models.append(RnnModel(self.n_symbols, n_hidden, self.n_out,
rnn_unit, batches.max_seq_len, n_layer, self.adam_optimizer))
# training and evaluation
plot_id = 0
for model in self.models:
trainer = Trainer(model, batches, ec)
for learning_rate in self.learning_rates:
plot_id += 1
trainer.train(learning_rate, self.epochs, adam_optimizer=self.adam_optimizer, early_stopping=True, early_stop_lim=10)
# print error plots
ec.plotTrainTestError(model, batches.batch_size, learning_rate, self.epochs, plot_id)
ec.resetErrors()
evaluator = Evaluator(model, batches, trainer.getSaveFilePath())
test_loss = evaluator.eval()
# get best conversion time
if trainer.best_epoch < self.best_conv_time:
self.best_conv_time = trainer.best_epoch
self.best_model_param = 'Param_' + model.name + '_ep-' + str(self.epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '_id-' + str(plot_id)
# reset scores
trainer.resetBestScore()
# print convergence times
ec.convergenceTimeMeanAndStd()
print("-----ModelTester finished, best test error: [%.6f] and conv time (epochs): [%i] with model: %s " % (self.best_test_loss, self.best_conv_time, self.best_model_param))
logging.info("-----ModelTester finished, best test error: [%.6f] and conv time (epochs): [%i] with model: %s " % (self.best_test_loss, self.best_conv_time, self.best_model_param))
<file_sep>/task5/nn_ku_t5_main.py
import matplotlib.pyplot as plt
import logging
import os
import numpy as np
import numpy.random as rd
import logging
import random
import tensorflow as tf
# State transition table
TRANSITIONS = [
[('T', 1), ('P', 2)], # 0=B
[('X', 3), ('S', 1)], # 1=BT
[('V', 4), ('T', 2)], # 2=BP
[('X', 2), ('S', 5)], # 3=BTX
[('P', 3), ('V', 5)], # 4=BPV
[('E', -1)], # 5=BTXS
]
TRANSITIONS_EMB = [
[('T', 1), ('P', 11)],
[('B', 1), ('P', 11)],
[('X', 3), ('S', 1)],
[('V', 4), ('T', 2)],
[('X', 2), ('S', 5)],
[('P', 3), ('V', 5)],
[('E', -1)],
]
# Symbol encoding
SYMS = {'T': 0, 'P': 1, 'X': 2, 'S': 3, 'V': 4, 'B': 5, 'E': 6}
def make_reber():
"""Generate one string from the Reber grammar."""
idx = 0
out = 'B'
while idx != -1:
ts = TRANSITIONS[idx]
symbol, idx = random.choice(ts)
out += symbol
return out
def make_embedded_reber():
"""Generate one string from the embedded Reber grammar."""
c = random.choice(['T', 'P'])
return 'B%s%s%sE' % (c, make_reber(), c)
def str_to_vec(s):
"""Convert a (embedded) Reber string to a sequence of unit vectors."""
a = np.zeros((len(s), len(SYMS)))
for i, c in enumerate(s):
a[i][SYMS[c]] = 1
return a
def str_to_next(s):
"""Given a Reber string, return a vectorized sequence of next chars.
This is the target output of the Neural Net."""
out = np.zeros((len(s), len(SYMS)))
idx = 0
for i, c in enumerate(s[1:]):
ts = TRANSITIONS[idx]
for next_c, _ in ts:
out[i, SYMS[next_c]] = 1
next_idx = [j for next_c, j in ts if next_c == c]
assert len(next_idx) == 1
idx = next_idx[0]
return out
def str_to_next_embed(s):
"""Given an embedded Reber string, return a vectorized sequence of next chars.
This is the target output of the Neural Net for embedded Reber."""
out_reb = str_to_next(s[2:-2])
ns = out_reb.shape[1]
out = np.zeros((out_reb.shape[0]+4,ns))
out[0,SYMS['T']]=1
out[0,SYMS['P']]=1
out[1,SYMS['E']]=1
for i, st in enumerate(out_reb):
out[i+2,:] = st
idx = i+2
out[idx,SYMS[s[1]]]=1
out[idx+1,SYMS['E']]=1
return out
def vec_to_str(xs):
"""Given a matrix, return a Reber string (with choices)."""
idx_to_sym = dict((v,k) for k,v in SYMS.iteritems())
out = ''
for i in range(0, xs.shape[0]):
vs = np.nonzero(xs[i,:])[0]
chars = [idx_to_sym[v] for v in vs]
if len(chars) == 1:
out += chars[0]
else:
out += '{%s}' % ','.join(chars)
return out
# Reber Batches class
class ReberBatches():
def __init__(self, n_train_samples, n_val_samples, n_test_samples, batch_size, sym_size=7):
self.n_train_samples = n_train_samples
self.n_val_samples = n_val_samples
self.n_test_samples = n_test_samples
self.batch_size = batch_size
self.sym_size = sym_size
self.max_seq_len = 0
# always has validation set
self.is_validation = True
# lists
examples_train_list = []
seq_len_train_list = []
targets_train_list = []
examples_val_list = []
targets_val_list = []
examples_test_list = []
targets_test_list = []
# max length of sequence
self.train_max_seq_len = 0
self.val_max_seq_len = 0
self.test_max_seq_len = 0
# create list of training examples
for n in range(n_train_samples):
example = make_embedded_reber()
label = str_to_vec(example)
target = str_to_next_embed(example)
example_len = len(example)
seq_len_train_list.append(example_len)
if self.train_max_seq_len < example_len:
self.train_max_seq_len = example_len
examples_train_list.append(label)
targets_train_list.append(target)
# create list of validation examples
for n in range(n_val_samples):
example = make_embedded_reber()
label = str_to_vec(example)
target = str_to_next_embed(example)
example_len = len(example)
if self.val_max_seq_len < example_len:
self.val_max_seq_len = example_len
examples_val_list.append(label)
targets_val_list.append(target)
# create list of test examples
for n in range(n_test_samples):
example = make_embedded_reber()
label = str_to_vec(example)
target = str_to_next_embed(example)
example_len = len(example)
if self.test_max_seq_len < example_len:
self.test_max_seq_len = example_len
examples_test_list.append(label)
targets_test_list.append(target)
# max seq length of all reber strings
self.max_seq_len = max(self.train_max_seq_len, self.val_max_seq_len, self.test_max_seq_len)
# create 0-padded numpy matrix for train
self.examples_train = np.zeros((n_train_samples, self.max_seq_len, sym_size))
self.seq_len_train = np.zeros(n_train_samples)
self.targets_train = np.zeros((n_train_samples, self.max_seq_len, sym_size))
for sample_idx in range(n_train_samples):
self.seq_len_train[sample_idx] = self.max_seq_len
for str_idx in range(examples_train_list[sample_idx].shape[0]):
self.examples_train[sample_idx][str_idx] = examples_train_list[sample_idx][str_idx]
self.targets_train[sample_idx][str_idx] = targets_train_list[sample_idx][str_idx]
# create 0-padded numpy matrix for validation
self.examples_val = np.zeros((n_val_samples, self.max_seq_len, sym_size))
self.seq_len_val = np.zeros(n_val_samples)
self.targets_val = np.zeros((n_val_samples, self.max_seq_len, sym_size))
for sample_idx in range(n_val_samples):
self.seq_len_val[sample_idx] = self.max_seq_len
for str_idx in range(examples_val_list[sample_idx].shape[0]):
self.examples_val[sample_idx][str_idx] = examples_val_list[sample_idx][str_idx]
self.targets_val[sample_idx][str_idx] = targets_val_list[sample_idx][str_idx]
# create 0-padded numpy matrix for test
self.examples_test = np.zeros((n_test_samples, self.max_seq_len, sym_size))
self.seq_len_test = np.zeros(n_test_samples)
self.targets_test = np.zeros((n_test_samples, self.max_seq_len, sym_size))
for sample_idx in range(n_test_samples):
self.seq_len_test[sample_idx] = self.max_seq_len
for str_idx in range(examples_test_list[sample_idx].shape[0]):
self.examples_test[sample_idx][str_idx] = examples_test_list[sample_idx][str_idx]
self.targets_test[sample_idx][str_idx] = targets_test_list[sample_idx][str_idx]
# create training batches
# number of batches corresponding to batch_size
self.batch_num = np.ceil(self.examples_train.shape[0] / batch_size)
self.batch_num_val = np.ceil(self.examples_val.shape[0] / batch_size)
self.batch_num_test = np.ceil(self.examples_test.shape[0] / batch_size)
# split all examples and classes
self.batch_examples_train = np.array_split(self.examples_train, self.batch_num)
self.batch_target_train = np.array_split(self.targets_train, self.batch_num)
self.batch_seq_len_train = np.array_split(self.seq_len_train, self.batch_num)
self.batch_seq_len_val = np.array_split(self.seq_len_val, self.batch_num_val)
self.batch_seq_len_test = np.array_split(self.seq_len_test, self.batch_num_test)
# Error Collector Class
class ErrorCollector():
def __init__(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
self.convergence_time_list = []
def resetErrors(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def addConvergenceTime(self, epoch):
#test_error_array = np.array(self.test_error_list)
#epoch_of_convergence = np.nonzero(test_error_array<1e-7)[0][0] + 1
#self.convergence_time_list.append(epoch_of_convergence)
self.convergence_time_list.append(epoch)
def convergenceTimeMeanAndStd(self):
convergence_time_mean = np.mean(self.convergence_time_list)
convergence_time_std = np.std(self.convergence_time_list)
print("-----ModelTester Convergence Time of Models-----")
print("convergence time in epochs\nmean: [%.2f]\n standard deviation: [%.2f]" %(convergence_time_mean,convergence_time_std))
logging.info("convergence time in epochs\nmean: [%.2f]\n standard deviation: [%.2f]" %(convergence_time_mean,convergence_time_std))
return convergence_time_mean, convergence_time_std
def addTrainError(self, train_error):
self.train_error_list.append(train_error)
def addTestError(self, test_error):
self.test_error_list.append(test_error)
def addTrainAcc(self, train_acc):
self.train_acc_list.append(1-train_acc) # actually it's misclassification
def addTestAcc(self, test_acc):
self.test_acc_list.append(1-test_acc)
def plotTrainTestError(self, model, batch_size, learning_rate, epochs, plot_id):
print("Plot Errors")
fig, ax = plt.subplots(1)
ax.plot(self.train_error_list, color='blue', label='training', lw=2)
ax.plot(self.test_error_list, color='red', label='test/validation', lw=1.7, linestyle= '--',alpha=0.9)
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Cross-entropy loss')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Loss_' + model.name + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_opt-'+ str(model.optimizer_name) + '_lr-' + str(learning_rate) + '_id-' + str(plot_id) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
def plotTrainTestAcc(self, model, batch_size, learning_rate, epochs):
print("Plot Misclassification")
fig, ax = plt.subplots(1)
ax.plot(self.train_acc_list, color='blue', label='training', lw=2)
ax.plot(self.test_acc_list, color='green', label='test', lw=2)
ax.set_autoscaley_on(False)
ax.set_ylim([0, 1])
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Misclassification')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Misclass_'+ model.name + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
# ResNetModel
class RnnModel():
def __init__(self, n_symbols, n_hidden, n_out, rnn_unit, max_sequence_length, n_layer, adam_optimizer):
self.name = 'RNN_Model_' + rnn_unit
self.n_symbols = n_symbols
self.n_hidden = n_hidden
self.n_out = n_out
self.n_layer = n_layer
self.cell_type = rnn_unit
self.max_sequence_length = max_sequence_length
self.adam_optimizer = adam_optimizer
# Set optimizer
if adam_optimizer == True:
self.optimizer_name = 'Adam'
else:
self.optimizer_name = 'GD'
print('---Create ' + self.name + '---')
self.seq_length = tf.placeholder(tf.int32, [None])
self.X = tf.placeholder(tf.float32, [None, self.max_sequence_length, self.n_symbols])
#labels
self.z_ = tf.placeholder(tf.float32, [None, self.max_sequence_length, self.n_symbols])
# define recurrent layer
if self.cell_type == 'simple':
cell = tf.nn.rnn_cell.BasicRNNCell(n_hidden)
# cell = tf.keras.layers.SimpleRNNCell(num_hidden) #alternative
elif self.cell_type == 'lstm':
cell = tf.nn.rnn_cell.LSTMCell(n_hidden)
elif self.cell_type == 'gru':
cell = tf.nn.rnn_cell.GRUCell(n_hidden)
else:
raise ValueError('bad cell type.')
cell = tf.contrib.rnn.OutputProjectionWrapper(cell, self.n_out, reuse=tf.AUTO_REUSE)
outputs, states = tf.nn.dynamic_rnn(cell, self.X, dtype=tf.float32, sequence_length=self.seq_length)
self.last_outputs = outputs[:,-1,:]
# define loss, minimizer and error
self.cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=outputs, labels=self.z_)
self.mistakes = tf.not_equal(self.z_, tf.maximum(tf.sign(outputs), 0))
self.error = tf.reduce_mean(tf.cast(self.mistakes, tf.float32))
# This is incorporated in the Trainer
#correct_prediction = tf.equal(y, tf.maximum(tf.sign(y_pred), 0))
#accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Trainer class
class Trainer():
def __init__(self, model, batches, error_collector):
self.model = model
self.batches = batches
self.error_collector = error_collector
self.best_validation_loss = 1000
self.best_validation_acc = 100
self.best_epoch = 0
self.save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'tmp' + os.sep
self.file_name = ""
def train(self, learning_rate, epochs, adam_optimizer=True, early_stopping=False, early_stop_lim=1000):
# save parameter file name
self.file_name = 'Param_' + self.model.name + '_ep-' + str(epochs) + '_hidu-' + str(self.model.n_hidden) + '_hidl-' + str(self.model.n_layer) + '_lr-' + str(learning_rate) + '.ckpt'
# setup training
if adam_optimizer == True:
train_step = tf.train.AdamOptimizer(learning_rate).minimize(self.model.cross_entropy)
self.optimizer_name = 'Adam'
else:
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(self.model.cross_entropy)
self.optimizer_name = 'Gradient_Descent'
# init variables
init = tf.global_variables_initializer()
# save variables
saver = tf.train.Saver()
# logging infos
print("-----Training-----")
print('Model: ' + self.model.name + ', Optimizer: ' + self.optimizer_name + ', Epochs: ' + str(epochs) + ', Hidden Units: ' + str(self.model.n_hidden) + ', HiddenLayer: ' + str(self.model.n_layer) + ', LearningRate: ' + str(learning_rate))
logging.info("-----Training-----")
logging.info('Model: ' + self.model.name + ', Optimizer: ' + self.optimizer_name + ', Epochs: ' + str(epochs) + ', Hidden Units: ' + str(self.model.n_hidden) + ', HiddenLayer: ' + str(self.model.n_layer) + ', LearningRate: ' + str(learning_rate))
early_stop_counter = 0
with tf.Session() as sess:
sess.run(init)
# run epochs
for k in range(epochs):
# gradient over each batch
for batch_example, batch_class, batch_seq_len in zip(self.batches.batch_examples_train, self.batches.batch_target_train, self.batches.batch_seq_len_train):
# training step
sess.run(train_step, feed_dict={self.model.X: batch_example, self.model.z_: batch_class, self.model.seq_length: batch_seq_len})
# Compute the errors and acc over the training dataset
train_err = sess.run(self.model.error, feed_dict={self.model.X: self.batches.examples_train, self.model.z_: self.batches.targets_train, self.model.seq_length: self.batches.seq_len_train})
test_loss = sess.run(self.model.error, feed_dict={self.model.X: self.batches.examples_val,
self.model.z_: self.batches.targets_val,
self.model.seq_length: self.batches.seq_len_val})
# add errors to error collector
self.error_collector.addTrainError(train_err)
self.error_collector.addTestError(test_loss)
# Early stopping, save best parameters
if self.batches.is_validation == True and early_stopping == True:
if test_loss < self.best_validation_loss:
#if self.best_validation_acc == 100 or test_acc > self.best_validation_acc:
#print("---Model saved: %s" % self.save_path + self.file_name)
saver.save(sess, self.save_path + self.file_name)
self.best_validation_loss = test_loss
#self.best_validation_acc = test_acc
self.best_epoch = k
early_stop_counter = 0
else:
early_stop_counter += 1
# stop the training if no improvement
if early_stop_counter > early_stop_lim:
print("---end due to early stopping limit")
logging.info("---end due to early stopping limit")
break
# logging iterations
print("Iteration: ",k, " train loss: [%.4f]" % train_err, " valid loss: [%.4f]" % test_loss)
logging.info("Iteration: %i" % k + " train loss: [%.4f]" % train_err + " valid loss: [%.4f]" % test_loss)
if self.batches.is_validation == False or early_stopping == False:
saver.save(sess, self.save_path + self.file_name)
#self.error_collector.addConvergenceTime()
self.error_collector.addConvergenceTime(self.best_epoch)
# finish log
print("-----Training finished with best validation loss: [%.4f] at epoch:[%i]" %(self.best_validation_loss, self.best_epoch) )
logging.info("-----Training finished with best validation loss: [%.4f] at epoch:[%i]" %(self.best_validation_loss, self.best_epoch ) )
# returns the path of saved model
def getSaveFilePath(self):
return self.save_path + self.file_name
def resetBestScore(self):
self.best_validation_loss = 1000
self.best_validation_acc = 0
self.best_epoch = 0
# Evaluator class
class Evaluator():
def __init__(self, model, batches, save_path):
self.model = model
self.batches = batches
self.save_path = save_path
def eval(self):
# evaluation
correct_prediction = tf.equal(self.model.z_, tf.maximum(tf.sign(self.model.last_outputs), 0))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# restore parameters
saver = tf.train.Saver()
print("-----Evaluation of Test set-----")
logging.info("-----Evaluation of Test set-----")
# evaluate tf graph
with tf.Session() as sess:
saver.restore(sess, self.save_path)
#test_loss = sess.run(self.model.error, feed_dict={self.model.X: self.batches.examples_test, self.model.z_: self.batches.targets_test})
test_loss = sess.run(self.model.error, feed_dict={self.model.X: self.batches.examples_test,
self.model.z_: self.batches.targets_test,
self.model.seq_length: self.batches.seq_len_test})
#test_acc = sess.run(accuracy, feed_dict={self.model.X: self.batches.examples_test, self.model.z_: self.batches.targets_test})
print("test loss: [%.6f]" % test_loss)#, " test acc: [%.6f]" % test_acc)
logging.info("test loss: [%.6f]" % test_loss)# + " test acc: [%.6f]" % test_acc)
return test_loss#, test_acc
# Model Tester class
class RnnModelTester():
def __init__(self, epochs, learning_rates, n_layer, n_hidden, n_symbols=7,
n_out=7, rnn_unit='lstm', adam_optimizer=True):
self.epochs = epochs
self.learning_rates = learning_rates
self.n_hidden = n_hidden
self.n_layer = n_layer
self.models = []
self.n_out = n_out
self.best_test_loss = 0
self.best_conv_time = 100000
self.best_model_param = "None"
self.n_symbols = n_symbols
self.rnn_unit = rnn_unit
self.adam_optimizer = adam_optimizer
def run(self, batches):
# training and validation error collector
ec = ErrorCollector()
print("-----ModelTester-----")
logging.info("-----ModelTester-----")
# create models
for n_hidden in self.n_hidden:
for n_layer in self.n_layer:
for rnn_unit in self.rnn_unit:
print("RNN with max seq len: ", batches.max_seq_len)
self.models.append(RnnModel(self.n_symbols, n_hidden, self.n_out,
rnn_unit, batches.max_seq_len, n_layer, self.adam_optimizer))
# training and evaluation
plot_id = 0
for model in self.models:
trainer = Trainer(model, batches, ec)
for learning_rate in self.learning_rates:
plot_id += 1
trainer.train(learning_rate, self.epochs, adam_optimizer=self.adam_optimizer, early_stopping=True, early_stop_lim=10)
# print error plots
ec.plotTrainTestError(model, batches.batch_size, learning_rate, self.epochs, plot_id)
ec.resetErrors()
evaluator = Evaluator(model, batches, trainer.getSaveFilePath())
test_loss = evaluator.eval()
# get best conversion time
if trainer.best_epoch < self.best_conv_time:
self.best_conv_time = trainer.best_epoch
self.best_model_param = 'Param_' + model.name + '_ep-' + str(self.epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '_id-' + str(plot_id)
# reset scores
trainer.resetBestScore()
# print convergence times
ec.convergenceTimeMeanAndStd()
print("-----ModelTester finished, best test error: [%.6f] and conv time (epochs): [%i] with model: %s " % (self.best_test_loss, self.best_conv_time, self.best_model_param))
logging.info("-----ModelTester finished, best test error: [%.6f] and conv time (epochs): [%i] with model: %s " % (self.best_test_loss, self.best_conv_time, self.best_model_param))
# Main function
if __name__ == '__main__':
# setup logging
log_file_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'logs' + os.sep
log_file_name = "Model.log"
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
logging.basicConfig(filename=log_file_path + log_file_name, level=logging.INFO)
# Parameters and model
epochs = 100
learning_rates = [1e-2]
n_hidden = [14] # number of hidden units within layer
n_layer = [1] # number of hidden layers
rnn_unit = ['lstm', 'simple']
adam_optimizer = True
# Get Grammar data
batch_size = 40
n_train_samples = 5000
n_val_samples = 500
n_test_samples = 500
# Create Reber Batches
reber_batches = ReberBatches(n_train_samples, n_val_samples, n_test_samples, batch_size)
# Model Testing
model_tester = RnnModelTester(epochs, learning_rates, n_layer, n_hidden, rnn_unit=rnn_unit, adam_optimizer=adam_optimizer)
model_tester.run(reber_batches)
<file_sep>/task4/nn_ku_t4_main.py
import numpy as np
import numpy.random as rd
import tensorflow as tf
import matplotlib.pyplot as plt
import logging
import os
# load data function
def load_isolet():
# Loads the isolet dataset
# Returns:
# X....feature vectors (training set), X[i,:] is the i-th example
# C....target classes
# X_tst...feature vectors (test set)
# C_tst...classes (test set)
import pickle as pckl # to load dataset
import pylab as pl # for graphics
#from numpy import *
pl.close('all') # closes all previous figures
# Load dataset
file_in = open('isolet_crop_train.pkl','rb')
isolet_data = pckl.load(file_in) # Python 3
#isolet_data = pckl.load(file_in, encoding='bytes') # Python 3
file_in.close()
X = isolet_data[0] # input vectors X[i,:] is i-th example
C = isolet_data[1] # classes C[i] is class of i-th example
file_in = open('isolet_crop_test.pkl','rb')
isolet_test = pckl.load(file_in) # Python 3
file_in.close()
X_tst = isolet_test[0] # input vectors X[i,:] is i-th example
C_tst = isolet_test[1] # classes C[i] is class of i-th example
return (X, C, X_tst, C_tst)
# Error Collector class
class ErrorCollector():
def __init__(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def resetErrors(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def addTrainError(self, train_error):
self.train_error_list.append(train_error)
def addTestError(self, test_error):
self.test_error_list.append(test_error)
def addTrainAcc(self, train_acc):
self.train_acc_list.append(1-train_acc) # actually it's misclassification
def addTestAcc(self, test_acc):
self.test_acc_list.append(1-test_acc)
def plotTrainTestError(self, model, batch_size, learning_rate, epochs, activation='relu'):
print("Plot Errors")
fig, ax = plt.subplots(1)
ax.plot(self.train_error_list, color='blue', label='training', lw=2)
ax.plot(self.test_error_list, color='green', label='test', lw=2)
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Cross-entropy loss')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Loss_' + model.name + '_act-'+ activation + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
def plotTrainTestAcc(self, model, batch_size, learning_rate, epochs,activation='relu'):
print("Plot Misclassification")
fig, ax = plt.subplots(1)
ax.plot(self.train_acc_list, color='blue', label='training', lw=2)
ax.plot(self.test_acc_list, color='green', label='test', lw=2)
ax.set_autoscaley_on(False)
ax.set_ylim([0, 1])
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Misclassification')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Misclass_'+ model.name + '_act-'+ activation + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
# ClassifiedBatch class
class ClassifiedBatches():
def __init__(self, examples, classes, batch_size, is_test_set=False, is_validation=True):
self.examples = examples
self.classes = classes
self.batch_size = batch_size
self.is_test_set = is_test_set
self.is_validation = is_validation
self.examples_train = examples
self.examples_validation = examples
self.classes_train = classes
self.classes_validation = classes
if self.is_test_set == True:
return
# return if no validation set is needed
if self.is_validation == False:
train_set_percent = 1.0
else:
train_set_percent = 0.7
# init Arrays if test set
train_num = int(round(train_set_percent*examples.shape[0]))
print(train_num)
#split into validation and training set
self.examples_train = self.examples[0:(train_num)]
self.examples_validation = self.examples[(train_num):]
self.classes_train = self.classes[0:(train_num)]
self.classes_validation = self.classes[(train_num):]
# Batch List
# number of batches corresponding to batch_size
self.batch_num = np.ceil(self.examples_train.shape[0] / batch_size)
# split all examples and classes
self.batch_examples_train = np.array_split(self.examples_train, self.batch_num)
self.batch_classes_train = np.array_split(self.classes_train, self.batch_num)
# Batch Normalizer class
class BatchNormalizer():
def __init__(self, examples, classes=None, batch_size=40, shuffle=False, num_classes=26):
self.examples = examples
self.classes = classes
self.batch_size = batch_size
#self.batch_num = np.round(self.examples.shape[0]/batch_size) #number of batches corresponding to batch_size
self.shuffle = shuffle
self.num_classes = num_classes
self.mean_features = np.mean(self.examples, axis=0)
self.std_features = np.std(self.examples, axis=0)
def shuffle_in_unison(self,examples,classes):
assert len(examples) == len(classes)
shuffled_a = np.empty(examples.shape, dtype=examples.dtype)
shuffled_b = np.empty(classes.shape, dtype=classes.dtype)
permutation = np.random.permutation(len(examples))
for old_index, new_index in enumerate(permutation):
shuffled_a[new_index] = examples[old_index]
shuffled_b[new_index] = classes[old_index]
return shuffled_a, shuffled_b
def getMean(self):
return self.mean_features
def getStd(self):
return self.std_features
def getNormalized(self,examples, classes):
if (self.shuffle==True):
examples, classes = self.shuffle_in_unison(examples,classes)
norm=(examples-(self.mean_features))/(self.std_features)
return norm,classes
def getBatches(self,examples,classes, test=False, is_validation=True):
norm,norm_classes = self.getNormalized(examples,classes)
c_oh = tf.one_hot(norm_classes-1, self.num_classes)
with tf.Session() as sess:
self.classes_one_hot = sess.run(c_oh)
cbatches = ClassifiedBatches(norm, self.classes_one_hot, self.batch_size, test, is_validation)
return cbatches
# Feedforward Model
class Model():
def __init__(self, n_in, n_hidden, n_out, n_layer=1, activation='relu'):
self.name = 'FeedForward_Model'
self.n_in = n_in
self.n_hidden = n_hidden
self.n_out = n_out
self.n_layer = n_layer
self.activation = activation
# Weights, biases and activations
self.W = []
self.b = []
self.h = []
print('---Create Model--- ')
# create list of weights and biases upon each layers
for layer in range(n_layer + 1):
# set connections upon layer
if layer == 0:
print('Input W/b in layer: ', layer)
if n_layer == 0:
self.W.append(tf.Variable(rd.randn(self.n_in, self.n_out) / np.sqrt(self.n_in), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_out), trainable=True))
else:
self.W.append(tf.Variable(rd.randn(self.n_in, self.n_hidden) / np.sqrt(self.n_in), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
elif layer == n_layer:
print('Output W/b in layer: ', layer)
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_out) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_out), trainable=True))
else:
print('Hidden W/b in layer: ', layer)
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_hidden) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
# Define the neuron operations
# input layer
self.x = tf.placeholder(shape=(None, self.n_in),dtype=tf.float64)
# connections and activation of hidden layer
for layer in range(n_layer):
if self.activation == 'tanh':
if layer == 0:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.tanh(tf.matmul(self.x, self.W[0]) + self.b[0]))
else:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.tanh(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer]))
elif self.activation == 'relu':
if layer == 0:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.relu(tf.matmul(self.x, self.W[0]) + self.b[0]))
else:
print('Activation function of layer: ', layer, 'is', self.activation)
self.h.append(tf.nn.relu(tf.matmul(self.h[layer - 1], self.W[layer]) + self.b[layer]))
# output activation
if n_layer == 0:
self.z = tf.nn.softmax(tf.matmul(self.x, self.W[n_layer]) + self.b[n_layer])
else:
self.z = tf.nn.softmax(tf.matmul(self.h[n_layer-1], self.W[n_layer]) + self.b[n_layer])
# labels
self.z_ = tf.placeholder(shape=(None, self.n_out),dtype=tf.float64)
#loss
self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.z_ * tf.log(self.z), reduction_indices=[1]))
#self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = self.z, labels = self.z_))
# ResNetModel
class ResNetModel():
def __init__(self, n_in, n_hidden, n_out, n_layer=1, activation='relu'):
self.name = 'ResNet_Model'
self.n_in = n_in
self.n_hidden = n_hidden
self.n_out = n_out
self.n_layer = n_layer
self.n_resnet_blocks = int(n_layer/2)
self.activation = activation
# Weights, biases and activations
self.W = []
self.b = []
self.h = []
print('---Create ResNet Model--- ')
# create list of weights and biases upon each layers
# input layer
print('Input W/b')
self.W.append(tf.Variable(rd.randn(self.n_in, self.n_hidden) / np.sqrt(self.n_in), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
if self.n_resnet_blocks != 0:
# create resnet blocks
for block in range(self.n_resnet_blocks):
print('ResNet W/b at Block: ', block)
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_hidden) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_hidden) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_hidden), trainable=True))
print('Output W/b')
self.W.append(tf.Variable(rd.randn(self.n_hidden, self.n_out) / np.sqrt(self.n_hidden), trainable=True))
self.b.append(tf.Variable(np.zeros(self.n_out), trainable=True))
# Define the neuron operations
# input layer
layer = 0
self.x = tf.placeholder(shape=(None, self.n_in),dtype=tf.float64)
self.h.append(tf.nn.relu(tf.matmul(self.x, self.W[layer]) + self.b[layer]))
layer += 1
# create resnet blocks
if self.n_resnet_blocks != 0:
for block in range(self.n_resnet_blocks):
print('Activations of block: ', block)
print('--activation at layer: ', layer)
self.h.append(tf.nn.relu(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer]))
layer += 1
print('--activation at layer: ', layer)
self.h.append(tf.nn.relu(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer] + self.h[layer-2]))
layer += 1
# output activation
#if n_layer == 0:
# self.z = tf.nn.softmax(tf.matmul(self.x, self.W[n_layer]) + self.b[n_layer])
#else:
self.z = tf.nn.softmax(tf.matmul(self.h[layer-1], self.W[layer]) + self.b[layer])
# labels
self.z_ = tf.placeholder(shape=(None, self.n_out),dtype=tf.float64)
#loss
self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.z_ * tf.log(self.z), reduction_indices=[1]))
#self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = self.z, labels = self.z_))
# Evaluator class
class Evaluator():
def __init__(self, model, batches, save_path):
self.model = model
self.batches = batches
self.save_path = save_path
def eval(self):
# evaluation
correct_prediction = tf.equal(tf.argmax(self.model.z,1), tf.argmax(self.model.z_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
# restore parameters
saver = tf.train.Saver()
print("-----Evaluation of Test set-----")
logging.info("-----Evaluation of Test set-----")
# evaluate tf graph
with tf.Session() as sess:
saver.restore(sess, self.save_path)
test_loss = sess.run(self.model.cross_entropy, feed_dict={self.model.x: self.batches.examples, self.model.z_: self.batches.classes})
test_acc = sess.run(accuracy, feed_dict={self.model.x: self.batches.examples, self.model.z_: self.batches.classes})
print("test loss: [%.6f]" % test_loss, " test acc: [%.6f]" % test_acc)
logging.info("test loss: [%.6f]" % test_loss + " test acc: [%.6f]" % test_acc)
return test_loss, test_acc
# Trainer class
class Trainer():
def __init__(self, model, batches, error_collector):
self.model = model
self.batches = batches
self.error_collector = error_collector
self.best_validation_loss = 0
self.best_validation_acc = 100
self.best_epoch = 0
self.save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'tmp' + os.sep
self.file_name = ""
def train(self, learning_rate, epochs, adam_optimizer=True, early_stopping=False, early_stop_lim=1000):
# save parameter file name
self.file_name = 'Param_' + self.model.name + '_ep-' + str(epochs) + '_hidu-' + str(self.model.n_hidden) + '_hidl-' + str(self.model.n_layer) + '_lr-' + str(learning_rate) + '.ckpt'
# setup training
if adam_optimizer == True:
train_step = tf.train.AdamOptimizer(learning_rate).minimize(self.model.cross_entropy)
optimizer_name = 'Adam'
else:
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(self.model.cross_entropy)
optimizer_name = 'Gradient Descent'
correct_prediction = tf.equal(tf.argmax(self.model.z,1), tf.argmax(self.model.z_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
# init variables
init = tf.global_variables_initializer()
# save variables
saver = tf.train.Saver()
# logging infos
print("-----Training-----")
print('Model: ' + self.model.name + ', Optimizer: ' + optimizer_name + ', Activation: ' + self.model.activation + ', Epochs: ' + str(epochs) + ', Hidden Units: ' + str(self.model.n_hidden) + ', HiddenLayer: ' + str(self.model.n_layer) + ', LearningRate: ' + str(learning_rate))
logging.info("-----Training-----")
logging.info('Model: ' + self.model.name + ', Optimizer: ' + optimizer_name + ', Activation: ' + self.model.activation + ', Epochs: ' + str(epochs) + ', Hidden Units: ' + str(self.model.n_hidden) + ', HiddenLayer: ' + str(self.model.n_layer) + ', LearningRate: ' + str(learning_rate))
early_stop_counter = 0
with tf.Session() as sess:
sess.run(init)
# run epochs
for k in range(epochs):
# gradient over each batch
for batch_example, batch_class in zip(self.batches.batch_examples_train, self.batches.batch_classes_train):
# training step
sess.run(train_step, feed_dict={self.model.x: batch_example, self.model.z_: batch_class})
# Compute the errors and acc over the training dataset
train_loss = sess.run(self.model.cross_entropy, feed_dict={self.model.x: self.batches.examples_train, self.model.z_: self.batches.classes_train})
train_acc = sess.run(accuracy, feed_dict={self.model.x: self.batches.examples_train, self.model.z_: self.batches.classes_train})
self.error_collector.addTrainError(train_loss)
self.error_collector.addTrainAcc(train_acc)
# Compute the errors and acc of the validation set
test_loss = sess.run(self.model.cross_entropy, feed_dict={self.model.x: self.batches.examples_validation, self.model.z_: self.batches.classes_validation})
test_acc = sess.run(accuracy, feed_dict={self.model.x: self.batches.examples_validation, self.model.z_: self.batches.classes_validation})
self.error_collector.addTestError(test_loss)
self.error_collector.addTestAcc(test_acc)
# Early stopping, save best parameters
if self.batches.is_validation == True and early_stopping == True:
#if self.best_validation_loss == 0 or test_loss < self.best_validation_loss:
if self.best_validation_acc == 100 or test_acc > self.best_validation_acc:
#print("---Model saved: %s" % self.save_path + self.file_name)
saver.save(sess, self.save_path + self.file_name)
self.best_validation_loss = test_loss
self.best_validation_acc = test_acc
self.best_epoch = k
early_stop_counter = 0
else:
early_stop_counter += 1
# stop the training if no improvement
if early_stop_counter > early_stop_lim:
print("---end due to early stopping limit")
logging.info("---end due to early stopping limit")
break
# logging iterations
print("Iteration: ",k, " train loss: [%.4f]" % train_loss, " train acc: [%.4f]" % train_acc, " valid loss: [%.4f]" % test_loss, " valid acc: [%.4f]" % test_acc)
logging.info("Iteration: %i" % k + " train loss: [%.4f]" % train_loss + " train acc: [%.4f]" % train_acc + " valid loss: [%.4f]" % test_loss + " valid acc: [%.4f]" % test_acc)
if self.batches.is_validation == False or early_stopping == False:
saver.save(sess, self.save_path + self.file_name)
# finish log
print("-----Training finished with best validation loss: [%.4f] validation acc: [%.4f] at epoch:[%i]" %(self.best_validation_loss, self.best_validation_acc, self.best_epoch) )
logging.info("-----Training finished with best validation loss: [%.4f] validation acc: [%.4f] at epoch:[%i]" %(self.best_validation_loss, self.best_validation_acc, self.best_epoch ) )
# returns the path of saved model
def getSaveFilePath(self):
return self.save_path + self.file_name
def resetBestScore(self):
self.best_validation_loss = 0
self.best_validation_acc = 0
self.best_epoch = 0
# Model Tester class
class ModelTester():
def __init__(self, epochs, learning_rates, n_hidden, n_layer, n_in=300, n_out=26, activation='relu', is_res_net = False):
self.epochs = epochs
self.learning_rates = learning_rates
self.n_hidden = n_hidden
self.n_layer = n_layer
self.models = []
self.n_in = n_in
self.n_out = n_out
self.best_test_acc = 0
self.best_model_param = "None"
self.activation = activation
self.is_res_net = is_res_net
def run(self, train_batches, test_batches):
# training and validation error collector
ec = ErrorCollector()
print("-----ModelTester-----")
logging.info("-----ModelTester-----")
for n_hidden in self.n_hidden:
for n_layer in self.n_layer:
if self.is_res_net:
self.models.append(ResNetModel(n_in=self.n_in, n_hidden=n_hidden, n_out=self.n_out, n_layer=n_layer, activation='relu'))
else:
for activation in self.activation:
# create models
self.models.append(Model(n_in=self.n_in, n_hidden=n_hidden, n_out=self.n_out, n_layer=n_layer, activation=activation))
for model in self.models:
trainer = Trainer(model, train_batches, ec)
for learning_rate in self.learning_rates:
trainer.train(learning_rate, self.epochs, early_stop_lim=25)
# print error plots
ec.plotTrainTestError(model, train_batches.batch_size, learning_rate, self.epochs, model.activation)
ec.plotTrainTestAcc(model, train_batches.batch_size, learning_rate, self.epochs, model.activation)
ec.resetErrors()
evaluator = Evaluator(model, test_batches, trainer.getSaveFilePath())
test_loss, test_acc = evaluator.eval()
trainer.resetBestScore()
if self.best_test_acc == 0 or test_acc > self.best_test_acc:
self.best_test_acc = test_acc
self.best_model_param = 'Param_' + model.name + '_ep-' + str(self.epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate)
print("-----ModelTester finished, best test acc: [%.6f] with model: %s " % (self.best_test_acc, self.best_model_param))
logging.info("-----ModelTester finished, best test acc: [%.6f] with model: %s " % (self.best_test_acc, self.best_model_param))
# Main function
if __name__ == '__main__':
X, C, X_tst, C_tst = load_isolet()
# setup logging
log_file_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'logs' + os.sep
log_file_name = "Model.log"
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
logging.basicConfig(filename=log_file_path + log_file_name, level=logging.INFO)
# Parameters and model
epochs = 100
learning_rate = [3e-5]
n_hidden = [40] # number of hidden units within layer
n_layer = [9] # number of hidden layers
activation = ['relu', 'tanh']
batch_size = 20
# Batch Normalizer
bn = BatchNormalizer(X, C, batch_size=batch_size, shuffle=True)
train_batches = bn.getBatches(X, C)
test_batches = bn.getBatches(X_tst, C_tst, test=True)
# use Test set as Validation
train_batches.examples_validation = test_batches.examples_validation
train_batches.classes_validation = test_batches.classes_validation
model_tester = ModelTester(epochs, learning_rate, n_hidden, n_layer, activation=activation, is_res_net = False)
model_tester.run(train_batches, test_batches)
resnet_tester = ModelTester(epochs, learning_rate, n_hidden, n_layer, activation=activation, is_res_net = True)
# get the best from the other model tester
resnet_tester.best_test_acc = model_tester.best_test_acc
resnet_tester.best_model_param = model_tester.best_model_param
resnet_tester.run(train_batches, test_batches)
<file_sep>/task4/ErrorCollector.py
import matplotlib.pyplot as plt
import os
class ErrorCollector():
def __init__(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def resetErrors(self):
self.train_error_list = []
self.test_error_list = []
self.train_acc_list = []
self.test_acc_list = []
def addTrainError(self, train_error):
self.train_error_list.append(train_error)
def addTestError(self, test_error):
self.test_error_list.append(test_error)
def addTrainAcc(self, train_acc):
self.train_acc_list.append(1-train_acc) # actually it's misclassification
def addTestAcc(self, test_acc):
self.test_acc_list.append(1-test_acc)
def plotTrainTestError(self, model, batch_size, learning_rate, epochs, activation='relu'):
print("Plot Errors")
fig, ax = plt.subplots(1)
ax.plot(self.train_error_list, color='blue', label='training', lw=2)
ax.plot(self.test_error_list, color='green', label='test', lw=2)
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Cross-entropy loss')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Loss_' + model.name + '_act-'+ activation + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
def plotTrainTestAcc(self, model, batch_size, learning_rate, epochs,activation='relu'):
print("Plot Misclassification")
fig, ax = plt.subplots(1)
ax.plot(self.train_acc_list, color='blue', label='training', lw=2)
ax.plot(self.test_acc_list, color='green', label='test', lw=2)
ax.set_autoscaley_on(False)
ax.set_ylim([0, 1])
#ax.set_title('Bla')
ax.set_xlabel('Training epoch')
ax.set_ylabel('Misclassification')
plt.rc('grid', linestyle="--")
plt.grid()
plt.legend()
# save
save_path = os.path.dirname(os.path.abspath( __file__ )) + os.sep + 'plots' + os.sep
save_name = 'Misclass_'+ model.name + '_act-'+ activation + '_ep-' + str(epochs) + '_hidu-' + str(model.n_hidden) + '_hidl-' + str(model.n_layer) + '_lr-' + str(learning_rate) + '.png'
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + save_name, dpi=150, bbox_inches='tight')
#plt.show()
<file_sep>/task2/ClassifiedBatches.py
#import tensorflow as tf
import numpy as np
class ClassifiedBatches():
def __init__(self, examples, classes, batch_size, is_test_set=False, is_validation=True):
self.examples = examples
self.classes = classes
self.batch_size = batch_size
self.is_test_set = is_test_set
self.is_validation = is_validation
self.examples_train = examples
self.examples_validation = examples
self.classes_train = classes
self.classes_validation = classes
if self.is_test_set == True:
return
# return if no validation set is needed
if self.is_validation == False:
train_set_percent = 1.0
else:
train_set_percent = 0.7
# init Arrays if test set
train_num = int(round(train_set_percent*examples.shape[0]))
print(train_num)
#split into validation and training set
self.examples_train = self.examples[0:(train_num)]
self.examples_validation = self.examples[(train_num):]
self.classes_train = self.classes[0:(train_num)]
self.classes_validation = self.classes[(train_num):]
# Batch List
# number of batches corresponding to batch_size
self.batch_num = np.ceil(self.examples_train.shape[0] / batch_size)
# split all examples and classes
self.batch_examples_train = np.array_split(self.examples_train, self.batch_num)
self.batch_classes_train = np.array_split(self.classes_train, self.batch_num)
<file_sep>/task4/BatchNormalizer.py
import numpy as np
import tensorflow as tf
from ClassifiedBatches import ClassifiedBatches
class BatchNormalizer():
def __init__(self, examples, classes=None, batch_size=40, shuffle=False, num_classes=26):
self.examples = examples
self.classes = classes
self.batch_size = batch_size
#self.batch_num = np.round(self.examples.shape[0]/batch_size) #number of batches corresponding to batch_size
self.shuffle = shuffle
self.num_classes = num_classes
self.mean_features = np.mean(self.examples, axis=0)
self.std_features = np.std(self.examples, axis=0)
def shuffle_in_unison(self,examples,classes):
assert len(examples) == len(classes)
shuffled_a = np.empty(examples.shape, dtype=examples.dtype)
shuffled_b = np.empty(classes.shape, dtype=classes.dtype)
permutation = np.random.permutation(len(examples))
for old_index, new_index in enumerate(permutation):
shuffled_a[new_index] = examples[old_index]
shuffled_b[new_index] = classes[old_index]
return shuffled_a, shuffled_b
def getMean(self):
return self.mean_features
def getStd(self):
return self.std_features
def getNormalized(self,examples, classes):
if (self.shuffle==True):
examples, classes = self.shuffle_in_unison(examples,classes)
norm=(examples-(self.mean_features))/(self.std_features)
#print("normalized_data shape: ", norm.shape)
#print("normalized_data mean: ", norm.mean(axis=0)[0])
#print("normalized_data std: ", norm.std(axis=0)[0])
return norm,classes
def getBatches(self,examples,classes, test=False, is_validation=True):
norm,norm_classes = self.getNormalized(examples,classes)
c_oh = tf.one_hot(norm_classes-1, self.num_classes)
with tf.Session() as sess:
self.classes_one_hot = sess.run(c_oh)
cbatches = ClassifiedBatches(norm, self.classes_one_hot, self.batch_size, test, is_validation)
return cbatches
#print("feature_score shape: ", feature_score.shape)
#norm_examples =
#batch = ClassifiedBatches()
return | eeb3d4124d7b2046dfdc7ff247557e0660484e92 | [
"Markdown",
"Python"
] | 25 | Python | chrisworld/nn_ku | 301a36441db2c42a64ab1ccdca66a464043510c3 | f283753c1b339535d472a903740ecbc31e368042 |
refs/heads/master | <file_sep>import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import 'firebase/storage';
export const fbConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID,
};
firebase.initializeApp(fbConfig);
export const storage = firebase.storage().ref();
export default firebase;
<file_sep>import App from './App';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as HashRouter } from 'react-router-dom';
import * as serviceWorker from './serviceWorker';
import { createStore, applyMiddleware } from 'redux';
import { Provider, useSelector } from 'react-redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { getFirestore, reduxFirestore, createFirestoreInstance } from 'redux-firestore';
import { getFirebase, ReactReduxFirebaseProvider, isLoaded } from 'react-redux-firebase';
import firebase from './config/fbConfig';
import { ToastContainer } from 'react-toastify';
import reducer from './Reducers/index';
import './index.css';
const middleware = [thunk.withExtraArgument({ getFirebase, getFirestore })];
let store = createStore(reducer, composeWithDevTools(applyMiddleware(...middleware), reduxFirestore(firebase)));
const rrfConfig = {
userProfile: 'users',
useFirestoreForProfile: true,
};
const rrfProps = {
firebase,
config: rrfConfig,
dispatch: store.dispatch,
createFirestoreInstance,
};
function AuthIsLoaded({ children }) {
const auth = useSelector((state) => state.firebase.auth);
if (!isLoaded(auth)) return null;
return children;
}
ReactDOM.render(
<Provider store={store}>
<ReactReduxFirebaseProvider {...rrfProps}>
<AuthIsLoaded>
<HashRouter basename='/equipment-rent/'>
<ToastContainer />
<App></App>
</HashRouter>
</AuthIsLoaded>
</ReactReduxFirebaseProvider>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
<file_sep>export const removeItemAction = (item) => {
return (dispath, getState, { getFirebase, getFirestore }) => {
const firestore = getFirestore();
firestore
.collection(`categories/${item.category.id}/items`)
.doc(`${item.id}`)
.delete()
.then(() => {})
.catch((err) => {});
};
};
<file_sep>const initialState = { err: '', loading: false, items: [] };
export default function saveProductReducer(state = initialState, action) {
switch (action.type) {
case 'FETCH_SAVED_ITEMS_REQUEST':
return { ...state, loading: true };
case 'FETCH_SAVED_ITEMS_SUCCESS':
return { ...state, loading: false, items: action.payload };
case 'FETCH_SAVED_ITEMS_FAILURE':
return {
...state,
loading: false,
err: action.payload,
};
default:
return state;
}
}
<file_sep>const fetchProfileInfoRequest = () => {
return { type: 'FETCH_PROFILE_INFO_REQUEST' };
};
const fetchProfileInfoSuccess = (data) => {
return { type: 'FETCH_PROFILE_INFO_SUCCESS', payload: data };
};
// const fetchProfileInfoFailure = err => {
// return { type: "FETCH_PROFILE_INFO_FAILURE", payload: err };
// };
export const fetchProfileInfo = () => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
dispatch(fetchProfileInfoRequest());
const firestore = getFirestore();
const userId = getState().firebase.auth.uid;
firestore
.collectionGroup('items')
.where('ownerId', '==', userId)
.onSnapshot((response) => {
const items = response.docs.map((doc) => {
const data = doc.data();
data.id = doc.id;
return data;
});
dispatch(fetchProfileInfoSuccess(items));
});
// .catch(err => {
// dispatch(fetchProfileInfoFailure(err));
// });
};
};
<file_sep>import { fetchSavedItems } from './usersSavedProductsAction';
export const fetchSaveItemRequest = (item) => {
return { type: 'FETCH_SAVE_ITEM_REQUEST', payload: item };
};
export const fetchSaveItemSuccess = () => {
return { type: 'FETCH_SAVE_ITEM_SUCCESS' };
};
export const fetchSaveItemFailure = (err) => {
return { type: 'FETCH_SAVE_ITEM_FAILURE', payload: err };
};
export const fetchSaveItem = (productId) => {
//not just id atm
return (dispatch, getState, { getFirebase, getFirestore }) => {
dispatch(fetchSaveItemRequest());
const firestore = getFirestore();
const userId = getState().firebase.auth.uid;
firestore
.collection(`users/${userId}/savedProducts`)
.doc(productId.id)
.set({
...productId,
createdAt: new Date(),
})
.then(() => {
dispatch(fetchSaveItemSuccess());
})
.catch((err) => dispatch(fetchSaveItemFailure(err)));
};
};
//delete reducer is in usersSavedProductsReducer.js
export const fetchDeleteItemRequest = (item) => {
return { type: 'FETCH_DELETE_ITEM_REQUEST', payload: item };
};
export const fetchDeleteItemSuccess = () => {
return { type: 'FETCH_DELETE_ITEM_SUCCESS' };
};
export const fetchDeleteItemFailure = (err) => {
return { type: 'FETCH_DELETE_ITEM_FAILURE', payload: err };
};
export const fetchDeleteItem = (productId) => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
dispatch(fetchDeleteItemRequest());
const firestore = getFirestore();
const userId = getState().firebase.auth.uid;
firestore
.collection(`users/${userId}/savedProducts`)
.doc(productId)
.delete()
.then(() => {
dispatch(fetchDeleteItemSuccess());
dispatch(fetchSavedItems());
})
.catch((err) => {
dispatch(fetchDeleteItemFailure(err));
});
};
};
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class cardGenerator extends Component {
renderCard = (product, categoryId, categoryName, withImage = false, className) => {
return (
<Link to={`/${categoryId}/${categoryName}/${product.id}`} className={`${className}`}>
{withImage ? <img src={product.displayImageUrl} alt='Something cool'></img> : null}
<div>
<h3>{product.name}</h3>
<p>{product.description}</p>
</div>
</Link>
);
};
}
export default cardGenerator;
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { firestoreConnect } from 'react-redux-firebase';
import { fetchSaveItem } from '../../Actions/saveDeleteProductAction';
import { removeItemAction } from '../../Actions/removeItemAction';
import defaultImage from '../../assets/images/default-image.jpg';
import './ProductPage.scss';
class ProductPage extends Component {
render() {
document.title = 'Product page';
const { product, handleSave, uid, handleRemoveItem } = this.props;
return (
<section className={`product-page`}>
{product && product.length > 0 ? (
<>
<div className={`product-page__background-image ${product[0].category.categoryName}`} />
<div className='product-page__wrapper'>
<div className='product-page__image-wrapper'>
{product[0].displayImageUrl ? (
<img className='product-page__image' alt='Product' src={`${product[0].displayImageUrl}`} />
) : (
<img className='product-page__image' alt='Product' src={`${defaultImage}`} />
)}
</div>
<div className='product-page__info'>
<h1 className='product-page__info-name'>{product[0].name}</h1>
{uid === product[0].ownerId ? (
<div className='product-page__owner-options'>
<Link className='product-page__link' to={`/item-configuration`}>
<button className='product-page__button' disabled>
Edit
</button>
</Link>
<Link className='product-page__link' to='/'>
<button
className='product-page__button'
onClick={() => {
handleRemoveItem(product[0]);
}}
>
Remove this product
</button>
</Link>
</div>
) : null}
<h3 className='product-page__info-price'>Price (for a one day): {product[0].price}$</h3>
<p className='product-page__info-description'>{product[0].description}</p>
<div className='product-page__owner'>
<h3 className='product-page__owner-name'>
Owner: {product[0].ownerFirstName} {product[0].ownerLastName}
</h3>
<h3 className='product-page__owner-email'>Email: {product[0].ownerEmailAddress}</h3>
<h3 className='product-page__owner-number'>Phone Number: {product[0].ownerPhoneNumber}</h3>
</div>
{product[0].youtubeLink && (
<iframe
title='youtubeVideo'
width='560'
height='315'
src={`//www.youtube.com/embed/${product[0].youtubeLink}`}
frameBorder='0'
allowFullScreen
></iframe>
)}
<button onClick={() => handleSave(product[0])} className='product-page__button'>
Bookmark this product
</button>
</div>
</div>
</>
) : (
<div className='product-page__background-image home-page-background'>
<h1 className='product-page__wrapper-error'>This product is not available anymore</h1>
</div>
)}
</section>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
product: state.firestore.ordered[`categories/${ownProps.match.params.categoryId}/items`],
uid: state.firebase.auth.uid,
};
};
const mapDispatchToProps = (dispatch) => {
return {
handleSave: (item) => {
dispatch(fetchSaveItem(item));
},
handleRemoveItem: (item) => dispatch(removeItemAction(item)),
};
};
export default compose(
firestoreConnect((props) => [
{
collection: `categories/${props.match.params.categoryId}/items`,
doc: `${props.match.params.productId}`,
},
]),
connect(mapStateToProps, mapDispatchToProps)
)(ProductPage);
<file_sep>import { storage } from '../config/fbConfig';
export const addItemAction = (newItem) => {
return (dispath, getState, { getFirebase, getFirestore }) => {
const firestore = getFirestore();
const profile = getState().firebase.profile;
const ownerId = getState().firebase.auth.uid;
newItem.youtubeLink = getId(newItem.youtubeLink);
console.log(newItem.image);
newItem.image.name
? storage
.child(`images/${ownerId}_${new Date().getTime()}`)
.put(newItem.image)
.then(async (snapshot) => {
const downloadUrl = await snapshot.ref.getDownloadURL();
newItem.image = snapshot.metadata.fullPath;
newItem.displayImageUrl = downloadUrl;
firestore
.collection(`categories/${newItem.category.id}/items`)
.add({
...newItem,
ownerFirstName: profile.firstName,
ownerLastName: profile.lastName,
ownerId,
createdAt: new Date(),
})
.then(() => {
dispatchEvent({ type: 'ADD_NEW_PRODUCT', payload: newItem });
})
.catch((err) => {
dispath({ type: 'ADD_NEW_PRODUCT_ERROR', payload: err });
});
})
: firestore
.collection(`categories/${newItem.category.id}/items`)
.add({
...newItem,
ownerFirstName: profile.firstName,
ownerLastName: profile.lastName,
ownerId,
createdAt: new Date(),
})
.then(() => {
dispatchEvent({ type: 'ADD_NEW_PRODUCT', payload: newItem });
})
.catch((err) => {
dispath({ type: 'ADD_NEW_PRODUCT_ERROR', payload: err });
});
};
};
function getId(url) {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
const match = url.match(regExp);
return match && match[2].length === 11 ? match[2] : null;
}
<file_sep>import React, { Component } from 'react';
import { signUp } from '../../../Actions/authActions';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import './RegisterPage.scss';
class RegisterPage extends Component {
state = {
email: '',
password: '',
firstName: '',
lastName: '',
};
handleChange = (e) => {
this.setState({
[e.target.id]: e.target.value,
});
};
handleSubmit = (e) => {
e.preventDefault();
this.props.signUp(this.state);
};
render() {
document.title = 'Register';
const { uid, authError } = this.props;
if (uid) return <Redirect to='/' />;
return (
<section className='register-page'>
<div className='register-page__form-wrapper'>
<form className='register-page__form-wrapper-form' onSubmit={this.handleSubmit}>
<h2>Register</h2>
<div>
<label htmlFor='email'>Email</label>
<input onChange={this.handleChange} type='email' id='email' />
</div>
<div>
<label htmlFor='firstName'>First Name</label>
<input onChange={this.handleChange} type='firstName' id='firstName' />
</div>
<div>
<label htmlFor='lastName'>Last Name</label>
<input onChange={this.handleChange} type='lastName' id='lastName' />
</div>
<div>
<label htmlFor='password'>Password</label>
<input onChange={this.handleChange} type='password' id='password' />
</div>
<button>Register</button>
{authError && <p className='alert'>{authError.message}</p>}
</form>
</div>
<div className='register-page__image home-page-background'></div>
</section>
);
}
}
const mapStateToProps = (state) => {
return {
authError: state.auth.authError,
auth: state.firebase.auth,
uid: state.firebase.auth.uid,
};
};
const mapDispatchToProps = (dispatch) => {
return {
signUp: (newUser) => dispatch(signUp(newUser)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(RegisterPage);
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import productsList from '../productsList.json';
import cardGenerator from '../Common/cardGenerator';
import './SearchPage.scss';
class SearchPage extends cardGenerator {
componentDidMount() {
this.prevSearch = this.props.submittedSearchString;
let results = productsList.filter(
(item) =>
item.name.toUpperCase().indexOf(
(this.props.submittedSearchString || this.props.location.pathname.split('/').pop()) //Что-бы после перезагрузки страницы не показывало все товары
.toUpperCase()
) > -1
);
this.props.getSearchedProducts(results);
}
componentDidUpdate() {
if (this.prevSearch !== this.props.submittedSearchString) {
this.componentDidMount(); //Делать новый поиск без потребности перезагружать страницу
}
}
render() {
return (
<div className='search-page'>
{this.props.items.length === 0 ? (
<h1 className='search-page__no-items-error'>
'{this.props.submittedSearchString}' doesn't exist here. I'm sorry...
</h1>
) : (
this.props.items.map((product) => (
<div key={product.key} className='item-card'>
{this.renderCard(product, true, true, 'search-page__element')}
</div>
))
)}
</div>
);
}
}
export default connect(
(state) => state.search,
(dispatch) => ({
getSearchedProducts: (products) => {
dispatch({ type: 'ON_LOAD_SEARCHED_ITEMS', payload: products });
},
})
)(SearchPage);
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { useFirestoreConnect } from 'react-redux-firebase';
import Loader from '../Common/loader/loader';
import './Catalogue.scss';
const Catalogue = () => {
useFirestoreConnect('categories');
const categories = useSelector((state) => state.firestore);
return (
<section className='catalogue-wrapper'>
{categories.status.requesting.categories ? (
<Loader />
) : categories.errors.byQuery.length > 0 ? (
<h2 className='error'>{categories.error}</h2>
) : (
<div className='catalogue'>
<ol className='catalogue__elements'>
{categories.ordered.categories &&
categories.ordered.categories.map((category) => (
<li className='catalogue__elements-element' key={category.id}>
<span></span>
<span></span>
<span></span>
<span></span>
<Link to={`/${category.categoryName.toLowerCase()}/${category.id}`}>
<div className={`catalogue__elements-element-image ${category.categoryName}`}>
<h1 className={'catalogue__elements-element-text'}>{category.categoryName.toUpperCase()}</h1>
</div>
</Link>
</li>
))}
</ol>
</div>
)}
</section>
);
};
export default Catalogue;
<file_sep>import { Component } from 'react';
import { connect } from 'react-redux';
import { signOut } from '../../../Actions/authActions';
class LogoutPage extends Component {
componentDidMount() {
this.props.onLogout();
window.location = '/';
}
render() {
return null;
}
}
const mapDispathToprops = (dispatch) => {
return {
onLogout: () => {
dispatch(signOut());
},
};
};
export default connect(null, mapDispathToprops)(LogoutPage);
<file_sep>import React, { Component } from 'react';
import Catalogue from '../Catalogue/Catalogue';
import './HomePage.scss';
class HomePage extends Component {
render() {
document.title = 'Home';
return (
<div className='home-page home-page-background'>
<Catalogue></Catalogue>
</div>
);
}
}
export default HomePage;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import cardGenerator from '../Common/cardGenerator';
import { fetchSavedItems } from '../../Actions/usersSavedProductsAction';
import { fetchDeleteItem } from '../../Actions/saveDeleteProductAction';
import './UsersSavedProductPage.scss';
class ShoppingCart extends cardGenerator {
componentDidMount() {
document.title = 'Bookmarked items';
this.props.onLoadSavedItems();
}
render() {
const { savedItems } = this.props;
return (
<section className='shopping-cart home-page-background'>
<ul className='shopping-cart__items'>
{savedItems.items.length > 0 &&
savedItems.items.map((product) => (
<li key={product.id} className='shopping-cart__items-item'>
<button
className='shopping-cart__items-item-delete-button'
onClick={() => this.props.onDeleteItem(product.id)}
></button>
{this.renderCard(product, product.category.categoryName, product.category.id, true, 'product-card')}
</li>
))}
</ul>
</section>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
savedItems: state.savedItems,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onLoadSavedItems: () => dispatch(fetchSavedItems()),
onDeleteItem: (id) => dispatch(fetchDeleteItem(id)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ShoppingCart);
<file_sep>import React from 'react';
import Joi from 'joi-browser';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { firestoreConnect } from 'react-redux-firebase';
import { addItemAction } from '../../Actions/addItemAction';
import Form from '../Common/form';
import Loader from '../Common/loader/loader';
import './ItemConfigPage.scss';
class ItemConfigPage extends Form {
state = {
data: {
name: '',
category: {},
price: '',
ownerPhoneNumber: '',
ownerEmailAddress: '',
description: '',
youtubeLink: '',
image: {},
},
errors: {},
};
schema = {
name: Joi.string().required().label('Name'),
category: Joi.string()
.required()
.label('Category')
.error(() => {
return { message: 'Please choose a cetegory' };
}),
price: Joi.number().required().label('Price'),
description: Joi.label('Description'),
id: Joi.label('Id'),
youtubeLink: Joi.string()
.required(false)
.regex(/^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+/)
.label('Youtube Link')
.error(() => {
return { message: 'Please use vaild Youtube link' };
}),
ownerPhoneNumber: Joi.number().required().label('Phone number'),
ownerEmailAddress: Joi.string().email().required().label('Email address'),
image: Joi.any(),
};
onSubmit = () => {
const data = { ...this.state.data };
const categoryId = this.state.data.category;
const category = this.props.categories.find((category) => categoryId === category.id);
data.category = category;
this.setState({ data }, () => {
this.props.handleAddNewItem(this.state.data);
this.props.history.push('/');
});
};
render() {
document.title = 'Item configuration';
const { categories } = this.props;
return (
<section className='item-config-page home-page-background'>
{!categories ? (
<Loader />
) : (
<div className='item-config-page__form-wrapper'>
<form className='item-config-page__form' onSubmit={this.handleSubmit}>
{this.renderInput('name', 'Name')}
{this.renderInput('price', 'Price')}
{this.renderSelect('category', 'Category', categories)}
{this.renderInput('ownerPhoneNumber', 'Phone number')}
{this.renderInput('ownerEmailAddress', 'Email address')}
{this.renderInput('youtubeLink', 'Youtube Link')}
{this.renderTextarea('description', 'Description')}
{this.renderFileField('image', 'Image')}
{this.renderButton('Save', 'item-config-page__form-button')}
</form>
</div>
)}
</section>
);
}
}
const mapStateToProps = (state) => {
return {
categories: state.firestore.ordered.categories,
};
};
const mapDispatchToProps = (dispatch) => {
return {
handleAddNewItem: (newItem) => dispatch(addItemAction(newItem)),
};
};
export default compose(
connect(mapStateToProps, mapDispatchToProps),
firestoreConnect(() => [{ collection: `categories` }])
)(ItemConfigPage);
<file_sep>import React from 'react';
import { fetchProfileInfo } from '../../Actions/userProfileAction';
import { connect } from 'react-redux';
import { removeItemAction } from '../../Actions/removeItemAction';
import './UserProfilePage.scss';
import cardGenerator from '../Common/cardGenerator';
class UserProfilePage extends cardGenerator {
componentDidMount() {
document.title = 'Your account';
this.props.getUserItems();
}
render() {
const { userItems, handleRemoveItem } = this.props;
return (
<section className='user-profile home-page-background'>
<ul className='user-profile__items'>
{userItems.items &&
userItems.items.map((item) => (
<li className='user-profile__items-item' key={item.id}>
{this.renderCard(item, item.category.categoryName, item.category.id, true, 'product-card')}
<button
className='user-profile__items-item-button'
onClick={() => {
handleRemoveItem(item);
}}
>
Remove
</button>
</li>
))}
</ul>
</section>
);
}
}
const mapStateToProps = (state) => {
return {
userItems: state.userInfo,
};
};
const mapDispatchToProps = (dispatch) => {
return {
getUserItems: () => dispatch(fetchProfileInfo()),
handleRemoveItem: (item) => dispatch(removeItemAction(item)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserProfilePage);
<file_sep>import React, { useState } from 'react';
import { NavLink } from 'react-router-dom';
// import Search from "../SearchBar/SearchBar";
import { useSelector } from 'react-redux';
import './Navbar.scss';
const Navbar = (props) => {
const [burgerState, setBurgerState] = useState(false);
const signedIn = useSelector((state) => state.firebase.auth.uid);
const userInfo = useSelector((state) => state.firebase.profile);
const updateBurgerState = () => {
const state = !burgerState;
setBurgerState(state);
};
const getClass = (initialClass) => {
return burgerState ? `${initialClass} open` : `${initialClass}`;
};
return (
<React.Fragment>
<div onClick={updateBurgerState} className='navbar-btn'>
<span className={getClass('navbar-btn__burger')}></span>
</div>
<nav className={getClass('navbar')}>
{/* <Search history={props.history}></Search> */}
<ul onClick={updateBurgerState} className={getClass('navbar__links')}>
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' exact to='/'>
Home
</NavLink>
</li>
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' to='/saved-products'>
Bookmarked items
</NavLink>
</li>
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' to='/item-configuration'>
Add new item
</NavLink>
</li>
{!signedIn ? (
<React.Fragment>
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' to='/login'>
Login
</NavLink>
</li>
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' to='/register'>
Register
</NavLink>
</li>
</React.Fragment>
) : (
<React.Fragment>
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' to='/logout'>
Logout
</NavLink>
</li>
{userInfo.initials ? (
<li className={getClass('navbar__links-link')}>
<NavLink activeClassName='activeNavLink' to='/profile'>
{userInfo.initials}
</NavLink>
</li>
) : null}
</React.Fragment>
)}
</ul>
</nav>
</React.Fragment>
);
};
export default Navbar;
<file_sep>const initialState = { err: '', loading: false, items: [] };
export default function userInfo(state = initialState, action) {
switch (action.type) {
case 'FETCH_PROFILE_INFO_REQUEST':
return { ...state, loading: true };
case 'FETCH_PROFILE_INFO_SUCCESS':
return { ...state, loading: false, items: action.payload };
case 'FETCH_PROFILE_INFO_FAILURE':
return {
...state,
loading: false,
err: action.payload,
};
default:
return state;
}
}
| 58662b8c925dbc51f7115a54082ebfc9437044ca | [
"JavaScript"
] | 19 | JavaScript | havit1/equipment-rent | 4b50328981c6e524cec0608fb836ec441329c34c | b789fb60c2a4aa2329bdd6304a93806a7f5dcb02 |
refs/heads/main | <file_sep>module.exports = {
jwtSecret: process.env.JWT_SECRET || '91224ea0-47bb-46e1-b0e9-a681a9153f38'
}; | d59c4b2324909ce8d974299be78cd63a44a9152c | [
"JavaScript"
] | 1 | JavaScript | rafaelsouz/react-avancado-api | 93ac9e41b97cbe883072f1570930660785d268b3 | 15a7b0de334a77b09bf1d04ee3261624fb0e9245 |
refs/heads/master | <file_sep># koa-301
Simple KoaJS application that preforms HTTP 301 redirects based on hosts configuration file.
## Hosts configuration file
This file contains an array of objects that contain:
- host - where should I redirect to
- domains - a list of domains that I need to issue a redirect for
```javascript
[
{
host: 'localhost',
domains: [
'example.com',
'www.example.com',
],
},
]
```
<file_sep>module.exports = [
{
host: 'localhost',
domains: [
'example.com',
'www.example.com'
]
},
]
| 6024bb427feffae77068a07c1bda2a7b5a1df4c2 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | bmcorum/koa-301 | c397e504cb98e69de3ae4803cacc5e258613a96d | 2670051fa8da05c9a53472a5c2211324529019dc |
refs/heads/main | <file_sep># Date-Hour-Javascript
Widget que informa data e hora atual
<file_sep>function mostrar() {
var mensagem = document.getElementById('mensagem')
var imagem = document.getElementById('imagem')
var data = new Date();
var hora = data.getHours();
var minutos = data.getMinutes();
if (hora >= 0 && hora < 12) {
mensagem.innerHTML = `Bom dia! Agora são ${hora}:${minutos} horas`
imagem.src = "./image/dia.jpg"
document.body.style.background = "#e2cd9f"
}else if(hora >= 12 && hora < 18){
mensagem.innerHTML = `Boa tarde! Agora são ${hora}:${minutos} horas`
imagem.src = "./image/tarde.jpg"
document.body.style.background = "#b98496f"
}else{
mensagem.innerHTML = `Boa noite! Agora são ${hora}:${minutos} horas`
imagem.src = "./image/noite.jpg"
document.body.style.background = "#515154"
}
}
| 68a6f34a9242a3c2bd5c8b2ee634ed317da92514 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ViniciusSararoli/Date-Hour-Javascript | d86d571b39ebbab289f3dda800251c36841dde60 | b1143c0af69aa4b9732d4926282f1b9a7e9b041f |
refs/heads/master | <repo_name>Amberlamps/gntm-dgmp-v2<file_sep>/gulpfile.js
'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var less = require('gulp-less');
var path = require('path');
var util = require('gulp-util');
var rename = require("gulp-rename");
var LessPluginCleanCSS = require("less-plugin-clean-css");
var cleancss = new LessPluginCleanCSS({advanced: true});
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var getBundleName = function () {
var version = require('./package.json').version;
var name = require('./package.json').name;
return name + '.' + version + '.' + 'min';
};
gulp.task('js', function() {
var bundler = browserify({
entries: ['./assets/js/main.js'],
debug: true
});
var bundle = function() {
return bundler
.bundle()
.pipe(source(getBundleName() + '.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/dist/js/'));
};
return bundle();
});
gulp.task('styles', function () {
gulp.src('./assets/styles/main.less')
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(less({
plugins: [cleancss]
}).on('error', util.log))
.pipe(rename(getBundleName() + '.css'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/dist/css/'));
});
gulp.task('watch', function() {
gulp.watch('./assets/styles/**/*.less', ['styles']);
gulp.watch('./assets/js/**/*.js', ['js']);
});
gulp.task('serve', function() {
browserSync.init(null, {
proxy: "http://localhost:3000",
files: ["public/dist/**/*.*", "views/**/*.jade"],
browser: "google chrome",
port: 7000
});
});
gulp.task('default', ['js', 'styles', 'watch']);<file_sep>/assets/js/pages/rulebooksPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function RulebooksPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
RulebooksPage.prototype = Object.create(Page.prototype);
RulebooksPage.prototype.constructor = RulebooksPage;
RulebooksPage.prototype.render = function render(html, response, callback) {
callback(null, this.container);
}
/**
* EXPORTS.
*/
module.exports = RulebooksPage;<file_sep>/routes/index.js
(function() {
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var apis = require('routes/apis.js');
var pages = require('routes/pages.js');
/**
* ROUTES.
*/
router.use('/api', apis)
router.use('/', pages);
module.exports = router;
}) ();<file_sep>/routes/apis/rulebooksApi.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Rulebook = require('schemes').Rulebook;
var authentication = require('middleware').authentication;
var validation = require('middleware').validation;
var patchRulebooksValidation = require('validations').patchRulebooksValidation;
var postRulebooksValidation = require('validations').postRulebooksValidation;
var putRulebooksValidation = require('validations').putRulebooksValidation;
/**
* VARIABLES.
*/
/**
* ROUTES.
*/
// GET
router.get('/:rulebookId',
authentication(),
getRulebook);
// GET
router.get('/',
authentication(),
getRulebooks);
// POST
router.post('/',
authentication(),
validation(postRulebooksValidation),
postRulebooks);
// PUT
router.put('/:rulebookId',
authentication(),
validation(putRulebooksValidation),
putRulebooks);
// PATCH
router.patch('/:rulebookId',
authentication(),
validation(patchRulebooksValidation),
patchRulebooks)
// DELETE
router.delete('/:rulebookId',
authentication(),
deleteRulebooks);
/**
* FUNCTIONS.
*/
function getRulebook(req, res, next) {
var leagueId = req.query.leagueId;
var selector = {
league: leagueId
};
Rulebook.findOne(selector, gotRulebook);
function gotRulebook(err, rulebook) {
if (err) {
return next(err);
}
res.json({
rulebook: rulebook
});
}
}
function getRulebooks(req, res, next) {
Rulebook.find({}).exec(gotRulebooks);
function gotRulebooks(err, rulebooks) {
if (err) {
return next(err);
}
res.json({
rulebooks: rulebooks
});
}
}
function postRulebooks(req, res, next) {
var params = req.body;
var rulebook = new Rulebook(params);
rulebook.save(savedRulebook);
function savedRulebook(err, rulebook) {
if (err) {
return next(err);
}
res.status(201).json({
rulebook: rulebook
});
}
}
function putRulebooks(req, res, next) {
res.json(1);
}
function patchRulebooks(req, res, next) {
var rulebookId = req.params.rulebookId;
var updates = req.body;
var selector = {
_id: rulebookId
};
var data = {
$set: updates,
$inc: {
__v: 1
}
};
Rulebook.update(selector, data, updatedRulebook);
function updatedRulebook(err, updated) {
if (err) {
return next(err);
}
res.json({
updated: updated
});
}
}
function deleteRulebooks(req, res, next) {
var rulebookId = req.params.rulebookId;
var selector = {
_id: rulebookId
};
Rulebook.remove(selector, removedRulebook);
function removedRulebook(err, deleted) {
if (err) {
return next(err);
}
res.json({
deleted: deleted
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/schemes/Rulebook.js
/**
* Schema for rulebook.
*
* User: <NAME> <<EMAIL>>
*/
'use strict';
/**
* MODULES.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/**
* VARIABLES.
*/
var schema = new Schema({
_createdOn: {
type: Date,
default: Date.now
},
_modifiedOn: {
type: Date,
default: Date.now
},
active: {
type: Boolean,
required: true,
default: false
},
league: {
type: Schema.ObjectId,
ref: 'League',
required: true
},
name: {
type: String,
required: true,
default: 'Rulebook Draft 1.0'
},
jobRules: {
type: Array,
required: true,
default: [{
name: 'Mädchen hat einen Job bekommen',
description: 'Getrunken wird, wenn das Mädchen einen Job bekommen hat.',
jobs: 1
}]
},
drinkingRules: {
type: Array,
required: true,
default: [{
name: 'Name gesagt',
description: 'Getrunken wird, wenn der Name eines Models genannt wird.',
target: 'manager',
gulps: 1
}, {
name: 'Name geschrieben',
description: 'Getrunken wird, wenn der Name eines Models irgendwo geschrieben steht.',
target: 'manager',
gulps: 2
}, {
name: 'Model weint',
description: 'Getrunken wird, wenn ein Model weint.',
target: 'manager',
gulps: 5
}, {
name: 'Mädchen/Chicas gesagt',
description: 'Getrunken wird, wenn "Mädchen" in irgendeiner Sprache genannt wird.',
target: 'alle',
gulps: 1
}]
},
drinkingDistribution: {
type: Array,
required: true,
default: [5, 4, 3, 2, 1]
}
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
/**
* EXPORTS.
*/
mongoose.model('Rulebook', schema);
module.exports = mongoose.model('Rulebook');<file_sep>/schemes/Model.js
/**
* Schema for model.
*
* User: <NAME> <<EMAIL>>
*/
'use strict';
/**
* MODULES.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/**
* VARIABLES.
*/
var schema = new Schema({
_createdOn: {
type: Date,
default: Date.now
},
displayname: {
type: String,
required: true
},
firstname: {
type: String
},
lastname: {
type: String
},
pictureFull: {
type: String
},
pictureFace: {
type: String
},
age: {
type: Number
},
height: {
type: Number
},
eliminated: {
type: Date
}
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
/**
* EXPORTS.
*/
mongoose.model('Model', schema);
module.exports = mongoose.model('Model');<file_sep>/assets/js/pages/leaguesAddPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function LeaguesAddPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
LeaguesAddPage.prototype = Object.create(Page.prototype);
LeaguesAddPage.prototype.constructor = LeaguesAddPage;
LeaguesAddPage.prototype.render = function render(html, response, callback) {
callback(null, this.container);
};
LeaguesAddPage.prototype._formCallback = function _formCallback(err, data, status, response, form) {
if (err) {
return swal({
title: 'Error!',
text: err.error,
type: 'error'
});
}
require('../router').getPage('/leagues/' + data.league._id + '/', true);
}
/**
* EXPORTS.
*/
module.exports = LeaguesAddPage;<file_sep>/schemes/Post.js
/**
* Schema for post.
*
* User: <NAME> <<EMAIL>>
*/
'use strict';
/**
* MODULES.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/**
* VARIABLES.
*/
var schema = new Schema({
_createdOn: {
type: Date,
default: Date.now
},
_modifiedOn: {
type: Date
},
member: {
type: Schema.ObjectId,
ref: 'User',
required: true
},
league: {
type: Schema.ObjectId,
ref: 'League',
required: true
},
comments: {
type: Number,
required: true,
default: 0
},
title: {
type: String,
required: true
},
post: {
type: String,
required: true
},
icon: {
type: String,
required: true
}
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
/**
* EXPORTS.
*/
mongoose.model('Post', schema);
module.exports = mongoose.model('Post');<file_sep>/assets/js/components/lists.js
'use strict';
/**
* FUNCTIONS.
*/
function enable(container) {
$.each(container.find('.list'), function checkList(index, list) {
list = $(list);
if (list.attr('data-enable') !== 'false') {
enableList(list);
}
});
}
function enableList(list) {
list.find('.list-handle').click(handleClick.bind(null, list));
}
function handleClick(list, e) {
var handle = $(e.currentTarget);
var sortName = handle.attr('data-sortname');
var sortOrder = handle.attr('data-sortorder');
var sortValue = (sortOrder === 'asc') ? 1 : -1;
var dataType = handle.attr('data-type') || 'string';
var listItems = list.find('.list-item');
listItems.sort(function sortList(a, b) {
var aValue = $(a).attr('data-' + sortName);
var bValue = $(b).attr('data-' + sortName);
if (dataType === 'number') {
aValue = +aValue;
bValue = +bValue;
} else if (dataType === 'date') {
if (!aValue) {
aValue = new Date(2016, 0, 1);
} else {
aValue = new Date(aValue);
}
if (!bValue) {
bValue = new Date(2016, 0, 1);
} else {
bValue = new Date(bValue);
}
} else if (dataType === 'string') {
aValue = aValue.toLowerCase();
bValue = bValue.toLowerCase();
}
if (aValue > bValue) {
return sortValue * 1;
} else if (aValue < bValue) {
return sortValue * -1;
} else {
return 0;
}
});
handle.attr('data-sortorder', (sortValue === 1) ? 'desc': 'asc');
$.each(listItems, function rearrangeList(index, item) {
list.append(item);
});
}
/**
* EXPORTS.
*/
module.exports = {
enable: enable
};<file_sep>/assets/js/router.js
'use strict';
/**
* MODULES.
*/
var config = require('./config.js');
/**
* PAGES.
*/
var IndexPage = require('./pages').IndexPage;
var LeaguesPage = require('./pages').LeaguesPage;
var LeaguePage = require('./pages').LeaguePage;
var LeaguesAddPage = require('./pages').LeaguesAddPage;
var LivePage = require('./pages').LivePage;
var LoginPage = require('./pages').LoginPage;
var LogoutPage = require('./pages').LogoutPage;
var ModelsPage = require('./pages').ModelsPage;
var Page = require('./pages').Page;
var RulebooksPage = require('./pages').RulebooksPage;
/**
* VARIABLES.
*/
var routes = [];
var pushPage;
var loadPage;
var pages = {
'/': IndexPage,
'/leagues/add/': LeaguesAddPage,
'/leagues/': LeaguesPage,
'/leagues/:leagueId/:page?': LeaguePage,
'/live/': LivePage,
'/login/': LoginPage,
'/logout/': LogoutPage,
'/models/:modelId?': ModelsPage,
'/rulebooks/:rulebookId?': RulebooksPage
};
var currentPath = location.pathname;
var initialLoad = true;
/**
* INIT.
*/
// Initialize routes.
for (var key in pages) {
var page = pages[key];
var matching = preparePath(key);
routes.push({
route: new RegExp(matching.path),
lookup: matching.lookup,
page: page
});
}
// Checking for push strategy.
if (history.pushState) {
pushPage = function pushPushState(path) {
history.pushState(null, null, path);
};
loadPage = function loadPushState(e) {
getPage(location.pathname);
};
// setTimeout hack because popstate also fires on page load.
window.setTimeout(function() {
$(window).on('popstate', loadPage);
}, 1000);
} else {
pushPage = function pushHashtag(page) {
location.hash = '!' + page;
};
loadPage = function loadHashtag(e) {
getPage(location.hash.substr(2));
};
if (location.hash) {
loadPage();
}
$(window).on('hashchange', loadPage);
}
// Enabling DOM elements.
enablePage($('body'));
// Activate Page
if (currentPath.charAt(currentPath.length-1) !== '/') {
currentPath += '/';
}
getPage(currentPath);
/**
* FUNCTIONS.
*/
function preparePath(path) {
var paramsLookup = [];
path = '^' + path + '$';
path = path.replace(/(:.*?)(\?|\$|\/)/g, function(match, parameter, delimiter) {
paramsLookup.push(parameter.substr(1));
return '(.*?)' + delimiter;
});
return {
path: path,
lookup: paramsLookup
};
}
function getPage(path, updatePath) {
if (path === currentPath && !initialLoad) {
return;
}
console.log(path);
for (var i = 0, _len = routes.length; i < _len; i++) {
var route = routes[i];
var matches = path.match(route.route);
if (matches) {
var params = {};
route.lookup.forEach(function(param, index) {
var value = matches[index+1];
if (value) {
if (value.charAt(value.length-1) === '/') {
value = value.substr(0, value.length-1);
}
params[param] = value;
}
});
NProgress.start();
var page = new route.page(path, params);
if (initialLoad) {
page.activatePage();
NProgress.done();
initialLoad = false;
} else {
page.init(function(err, container) {
NProgress.done();
if (err) {
return false;
}
currentPath = path;
if (updatePath) {
pushPage(path);
}
enablePage(container);
});
}
break;
}
}
}
function enablePage(container) {
container.find('a').click(linkClick);
}
function linkClick(e) {
if (!this.href.match(/\.pdf$/)) {
e.preventDefault();
}
var path = this.pathname;
if (path.charAt(path.length-1) !== '/') {
path += '/';
}
getPage(path, true);
}
/**
* EXPORTS.
*/
module.exports = {
getPage: getPage
};<file_sep>/assets/js/pages/logoutPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function LogoutPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
LogoutPage.prototype = Object.create(Page.prototype);
LogoutPage.prototype.constructor = LogoutPage;
LogoutPage.prototype.render = function render(html, response, callback) {
location.href = '/';
};
/**
* EXPORTS.
*/
module.exports = LogoutPage;<file_sep>/schemes/index.js
module.exports.Comment = require('./Comment.js');
module.exports.Event = require('./Event.js');
module.exports.League = require('./League.js');
module.exports.Membership = require('./Membership.js');
module.exports.Model = require('./Model.js');
module.exports.Playday = require('./Playday.js');
module.exports.Post = require('./Post.js');
module.exports.Rulebook = require('./Rulebook.js');
module.exports.User = require('./User.js');<file_sep>/assets/js/pages/page.js
'use strict';
/**
* MODULES.
*/
var forms = require('../components').forms;
var lists = require('../components').lists;
/**
* FUNCTIONS.
*/
function Page(path, params) {
this.path = path;
this.params = params;
this.container = $('.mainpage');
}
Page.prototype.init = function init(callback) {
var self = this;
$.ajax({
type: 'get',
url: this.path,
success: onSuccess,
error: onError
});
function onSuccess(html, success, response) {
self.container.html(html);
self.activatePage();
self.render(html, response, callback);
}
function onError(err, error, message) {
swal({
title: 'Oops...',
text: message,
type: 'error'
});
if (Object.prototype.toString.call(self.error) === '[object Function]') {
self.error(err, error, message);
} else {
callback(err);
}
}
};
Page.prototype.render = function render(html, response, callback) {
callback(null, this.container);
};
Page.prototype._formCallback = function _formCallback() {
console.log(arguments);
};
Page.prototype.activatePage = function activatePage() {
forms.enable(this.container, this._formCallback.bind(this));
lists.enable(this.container);
if (this.activated && Object.prototype.toString.call(this.activated) === '[object Function]') {
this.activated();
}
};
/**
* EXPORTS.
*/
module.exports = Page;<file_sep>/schemes/League.js
/**
* Schema for league.
*
* User: <NAME> <<EMAIL>>
*/
'use strict';
/**
* MODULES.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/**
* VARIABLES.
*/
var schema = new Schema({
_createdOn: {
type: Date,
default: Date.now
},
founder: {
type: Schema.ObjectId,
ref: 'User',
required: true
},
name: {
type: String,
required: true
},
sortname: {
type: String,
required: true
},
playdays: {
type: Number,
required: true,
default: 0
},
members: {
type: Number,
required: true,
default: 1
},
motto: {
type: String
}
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
/**
* EXPORTS.
*/
mongoose.model('League', schema);
module.exports = mongoose.model('League');<file_sep>/middleware/errorHandler.js
'use strict';
/**
* VARIABLES.
*/
var pageNotFound = errorHandler.bind(null, {
message: 'Page not found',
status: 404
});
/**
* FUNCTIONS.
*/
function errorHandler(err, req, res, next) {
var status = err.status || 500;
console.log(err);
var errorObject = {
message: err.message,
error: {
status: status,
stack: err.stack
}
};
res.status(status);
if (req.xhr) {
res.json(errorObject)
} else {
res.render('pages/error', errorObject);
}
}
/**
* EXPORTS.
*/
module.exports.development = errorHandler;
module.exports.production = errorHandler;
module.exports.pageNotFound = pageNotFound;<file_sep>/validations/index.js
module.exports.patchLeaguesValidation = require('./patchLeaguesValidation.js');
module.exports.postLeaguesValidation = require('./postLeaguesValidation.js');
module.exports.putLeaguesValidation = require('./putLeaguesValidation.js');
module.exports.patchMembershipsValidation = require('./patchMembershipsValidation.js');
module.exports.postMembershipsValidation = require('./postMembershipsValidation.js');
module.exports.putMembershipsValidation = require('./putMembershipsValidation.js');
module.exports.patchModelsValidation = require('./patchModelsValidation.js');
module.exports.postModelsValidation = require('./postModelsValidation.js');
module.exports.putModelsValidation = require('./putModelsValidation.js');
module.exports.patchPlaydaysValidation = require('./patchPlaydaysValidation.js');
module.exports.postPlaydaysValidation = require('./postPlaydaysValidation.js');
module.exports.putPlaydaysValidation = require('./putPlaydaysValidation.js');
module.exports.patchRulebooksValidation = require('./patchRulebooksValidation.js');
module.exports.postRulebooksValidation = require('./postRulebooksValidation.js');
module.exports.putRulebooksValidation = require('./putRulebooksValidation.js');
module.exports.patchUsersValidation = require('./patchUsersValidation.js');
module.exports.postUsersValidation = require('./postUsersValidation.js');
module.exports.putUsersValidation = require('./putUsersValidation.js');<file_sep>/routes/pages/livePage.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Membership = require('schemes').Membership;
var Model = require('schemes').Model;
var Playday = require('schemes').Playday;
var Rulebook = require('schemes').Rulebook;
var authentication = require('middleware').authentication;
/**
* VARIABLES.
*/
/**
* ROUTES.
*/
router.route('/')
.all(authentication())
.get(getLivePage);
/**
* FUNCTIONS.
*/
function getLivePage(req, res, next) {
var selector = {
member: req.session.user.id,
role: 'admin'
};
Membership.findOne(selector, getMembership);
function getMembership(err, membership) {
if (err) {
return next(err);
}
if (!membership) {
var error = new Error('You are not admin of a league.');
error.status = 400;
return next(error);
}
getPlayday(membership.league);
}
function getPlayday(league) {
var selector = {
league: league,
startDate: {
$exists: true
},
endDate: {
$exists: false
}
};
req.league = league;
Playday.findOne(selector).populate('models.model rulebook').exec(checkPlayday);
}
function checkPlayday(err, playday) {
if (err) {
return next(err);
}
if (!playday) {
return createPlayday();
}
renderPlayday(playday);
}
function createPlayday() {
var playday = {
league: req.league
};
var selector = {
eliminated: {
$exists: false
}
};
Model.find(selector, getModels);
function getModels(err, models) {
if (err) {
return next(err);
}
playday.models = models.map(function getModelIds(model) {
return {
model: model.id
};
});
var selector = {
league: req.league,
active: true
};
Rulebook.findOne(selector, getRulebook);
}
function getRulebook(err, rulebook) {
if (err) {
return next(err);
}
playday.rulebook = rulebook.id;
playday = new Playday(playday);
playday.save(savedPlayday);
}
function savedPlayday(err, playday) {
if (err) {
return next(err);
}
getPlayday(playday.league);
}
}
function renderPlayday(playday) {
playday.models.sort(function sortModels(a, b) {
a = a.model.displayname;
b = b.model.displayname;
if (a > b) {
return 1;
} else if (a < b) {
return -1;
} else {
return 0;
}
});
console.log(playday);
res.render('pages/live/live', {
playday: playday
});
}
var selector = {
eliminated: {
$exists: false
}
};
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/assets/js/components/index.js
module.exports.forms = require('./forms.js');
module.exports.lists = require('./lists.js');
module.exports.Login = require('./login.js');
module.exports.template = require('./template.js');<file_sep>/assets/js/pages/indexPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function IndexPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
IndexPage.prototype = Object.create(Page.prototype);
IndexPage.prototype.constructor = IndexPage;
IndexPage.prototype.render = function render(html, response, callback) {
callback(null, this.container);
}
IndexPage.prototype._formCallback = function _formCallback(err, data, status, response) {
if (err) {
return swal({
title: 'Error!',
text: err.response.responseJSON.message,
type: 'error'
});
}
swal({
title: 'Juchu!',
text: data.message,
type: 'success'
});
window.setTimeout(function() {
location.href = '/';
}, 1000);
}
/**
* EXPORTS.
*/
module.exports = IndexPage;<file_sep>/schemes/Event.js
/**
* Schema for event.
*
* User: <NAME> <<EMAIL>>
*/
'use strict';
/**
* MODULES.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/**
* VARIABLES.
*/
var schema = new Schema({
_createdOn: {
type: Date,
default: Date.now
},
key: {
type: String,
required: true,
enum: ['post.new', 'comment.new', 'member.new', 'member.delete', 'playday.new', 'league.new', 'user.new']
},
scope: {
type: Array,
required: true
},
variables: {
type: Object,
required: true
}
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
/**
* EXPORTS.
*/
mongoose.model('Event', schema);
module.exports = mongoose.model('Event');<file_sep>/routes/pages/logoutPage.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
/**
* ROUTES.
*/
router.route('/')
.get(getLogoutPage);
/**
* FUNCTIONS.
*/
function getLogoutPage(req, res, next) {
req.session.destroy();
if (req.xhr) {
res.json({ message: 'Logout successful' });
} else {
res.redirect('/');
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/middleware/authentication.js
'use strict';
/**
* FUNCTIONS.
*/
function authenticate(roles) {
roles = roles || [];
if (Object.prototype.toString.call(roles) !== '[object Array]') {
roles = [roles];
}
return authenticateMiddleware.bind(null, roles);
}
function authenticateMiddleware(roles, req, res, next) {
var user = req.session.user;
if (!user) {
var error = new Error('You need to be logged in.');
error.status = 403;
return next(error);
}
if (roles.length === 0) {
return next();
}
var userRoles = user.roles || [];
userRoles.forEach(function(role) {
if (roles.indexOf(role) !== -1) {
return next();
}
});
var error = new Error('You are not authorized.');
error.status = 401;
return next(error);
}
/**
* EXPORTS.
*/
module.exports = authenticate;<file_sep>/assets/js/resources/index.js
module.exports.eventKeys = require('./eventKeys.js');<file_sep>/middleware/sessionHandler.js
/**
* Middleware to manage and handle sessions.
*
* @author Amberlamps <<EMAIL>>
*/
/**
* MODULES.
*/
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require('redis');
var url = require('url');
/**
* MAIN.
*/
var connection = url.parse(process.env.REDISCLOUD_URL);
connection.username = connection.auth.split(":")[0];
connection.password = connection.auth.split(":")[1];
var redisClient = redis.createClient(connection.port, connection.hostname, {
no_ready_check: true
});
redisClient.auth(connection.password);
var sessionHandler = session({
store: new RedisStore({
client: redisClient
}),
resave: false,
saveUninitialized: true,
secret: 'gntm-dgmp ftw',
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 5184000000
}
});
/**
* EXPORTS.
*/
module.exports = sessionHandler;<file_sep>/routes/modules/index.js
module.exports.events = require('./events.js');<file_sep>/routes/apis.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var commentsApi = require('routes/apis/').commentsApi;
var eventsApi = require('routes/apis/').eventsApi;
var leaguesApi = require('routes/apis/').leaguesApi;
var membershipsApi = require('routes/apis/').membershipsApi;
var modelsApi = require('routes/apis/').modelsApi;
var playdaysApi = require('routes/apis/').playdaysApi;
var postsApi = require('routes/apis/').postsApi;
var roastersApi = require('routes/apis/').roastersApi;
var rulebooksApi = require('routes/apis/').rulebooksApi;
var usersApi = require('routes/apis/').usersApi;
/**
* MIDDLEWARE.
*/
router.use('/:version', function validateVersionNumber(req, res, next) {
next();
});
/**
* ROUTES.
*/
router.use('/:version/comments', commentsApi);
router.use('/:version/events', eventsApi);
router.use('/:version/leagues', leaguesApi);
router.use('/:version/memberships', membershipsApi);
router.use('/:version/models', modelsApi);
router.use('/:version/playdays', playdaysApi);
router.use('/:version/posts', postsApi);
router.use('/:version/roasters', roastersApi);
router.use('/:version/rulebooks', rulebooksApi);
router.use('/:version/users', usersApi);
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/app.js
/**
* Germany's Next Topmodel - Drinking Game Manager Professional.
*
* @author: Amberlamps <<EMAIL>>
*/
/**
* MODULES.
*/
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var routes = require('routes/index.js');
var errorHandler = require('middleware').errorHandler;
var sessionHandler = require('middleware').sessionHandler;
var exposeLocals = require('middleware').exposeLocals;
/**
* VARIABLES.
*/
var app = express();
/**
* SETTINGS.
*/
app.use(sessionHandler);
mongoose.connect(process.env.MONGOLAB_URI);
process.on('exit', function(err) {
mongoose.connection.close();
});
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(exposeLocals(app));
app.use('/', routes);
app.use(errorHandler.pageNotFound);
if (app.get('env') === 'development') {
app.use(errorHandler.development);
} else {
app.use(errorHandler.production);
}
/**
* EXPORTS.
*/
module.exports = app;<file_sep>/assets/js/pages/leaguesPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function LeaguesPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
LeaguesPage.prototype = Object.create(Page.prototype);
LeaguesPage.prototype.constructor = LeaguesPage;
LeaguesPage.prototype.render = function render(html, response, callback) {
callback(null, this.container);
}
/**
* EXPORTS.
*/
module.exports = LeaguesPage;<file_sep>/routes/pages/indexPage.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Event = require('schemes').Event;
/**
* ROUTES.
*/
router.route('/')
.get(getIndexPage);
/**
* FUNCTIONS.
*/
function getIndexPage(req, res, next) {
// Zwischen Wertung und Spieltag unterscheiden.
// Wertungen können kopiert werden und automatisch Spieltage erzeugt werden.
// "Spieltag erstellen" erscheint als Modal, damit man es sowohl über der Spielanimation als auch beim Kopieren der Wertung anzeigen kann.
// Spielanimation nimmt komplette Fläche des Bildschirms ein.
// Jedes Mädel hat eine Kachel.
// Eine zusätzliche Kachel für Aktionen, wo jeder trinken muss.
// Links fügt sie eine Übersicht mit Statistiken an. Aktuell die meisten Trinkschlücke, Jobs, Sonstige Schlücke.
// Linke Navigation durch Mausführung oder anklicken eines "Vergrößern" Pfeils möglich.
//res.send('GNTM DGMP wird rechtzeitig zum Start der neuen Saison zurück sein!');
// Wenn neue Artikel geschrieben wurden, in den Neuigkeiten direkt auf den Artikel linken und nicht auf die Front-Page der Liga.
// Kommentar-Funktion zum Ein- und Ausklappen.
// Unter Hauptpunkt "Regelwerk" erscheint Auflistung aller aktiven Regelwerke der jeweiligen Ligen.
// Im Liga-Menüpunkt "Regelwerk" erscheint das aktuell aktive Regelwerk der Liga. Das ist der gleiche Link, wie wenn man im Hauptmenüpunkt "Regelwerk" auf die entsprechende Liga klickt.
// Ist der User allerdings Admin der Liga, erscheint eine Übersicht mit drafts mit CRUD möglichkeiten.
// Man kann ein Regelwerk nur dann löschen, wenn es noch in keinem Spieltag verwendet wurde oder es nicht aktiv ist.
Event.find({ scope: 'all' }).sort({ _id: -1 }).limit(20).exec(renderEvents);
function renderEvents(err, events) {
if (err) {
return next(err);
}
res.render('pages/index', {
events: events
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/assets/js/pages/loginPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function LoginPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
LoginPage.prototype = Object.create(Page.prototype);
LoginPage.prototype.constructor = LoginPage;
LoginPage.prototype.render = function render(html, response, callback) {
if (response.status === 204) {
return location.href = '/';
}
callback(null, this.container);
};
LoginPage.prototype._formCallback = function _formCallback(err, data, status, response) {
if (err) {
return swal({
title: 'Error!',
text: err.message,
type: 'error'
});
}
swal({
title: 'Juchu!',
text: data.message,
type: 'success'
});
window.setTimeout(function() {
location.href = '/';
}, 1000);
}
/**
* EXPORTS.
*/
module.exports = LoginPage;<file_sep>/routes/modules/events.js
'use strict';
/**
* MODULES.
*/
var Comment = require('schemes').Comment;
var Event = require('schemes').Event;
var League = require('schemes').League;
var Membership = require('schemes').Membership;
var Post = require('schemes').Post;
var Playday = require('schemes').Playday;
var User = require('schemes').User;
/**
* VARIABLES.
*/
var handlerLookup = {
'league.new': leagueData,
'member.new': membershipData,
'member.delete': membershipData,
'post.new': postData,
'playday.new': playdayData,
'comment.new': commentData,
'user.new': userData
};
/**
* FUNCTIONS.
*/
function membershipData(key, data, callback) {
var selector = {
_id: data.membershipId
};
Membership.findOne(selector).populate('league member').exec(prepareEvent);
function prepareEvent(err, membership) {
if (err) {
return callback(err);
}
var variables = {
leagueId: membership.league.id,
leagueName: membership.league.name,
memberName: membership.member.name
};
var eventData = {
key: key,
scope: ['all', membership.league.id],
variables: variables
};
saveEvent(eventData, callback);
}
}
function postData(key, data, callback) {
var selector = {
_id: data.postId
};
Post.findOne(selector).populate('league member').exec(prepareEvent);
function prepareEvent(err, post) {
if (err) {
return callback(err);
}
var variables = {
postId: post.id,
leagueId: post.league.id,
leagueName: post.league.name,
memberName: post.member.name
};
var eventData = {
key: key,
scope: ['all', post.league.id],
variables: variables
};
saveEvent(eventData, callback);
}
}
function playdayData(key, data, callback) {
var selector = {
_id: data.playdaysId
};
Playday.findOne(selector).populate('league member').exec(prepareEvent);
function prepareEvent(err, playday) {
if (err) {
return callback(err);
}
var variables = {
playdaysId: playday.id,
leagueId: playday.league.id,
leagueName: playday.league.name,
memberName: playday.member.name
};
var eventData = {
key: key,
scope: ['all', playday.league.id],
variables: variables
};
saveEvent(eventData, callback);
}
}
function commentData(key, data, callback) {
var selector = {
_id: data.commentId
};
Comment.findOne(selector).populate('league member post').exec(prepareEvent);
function prepareEvent(err, comment) {
if (err) {
return callback(err);
}
var variables = {
postId: comment.post.id,
postTitle: comment.post.title,
leagueId: comment.league.id,
memberName: comment.member.name
};
var eventData = {
key: key,
scope: ['all', comment.league.id],
variables: variables
};
saveEvent(eventData, callback);
}
}
function userData(key, data, callback) {
var selector = {
_id: data.userId
};
User.findOne(selector).exec(prepareEvent);
function prepareEvent(err, user) {
if (err) {
return callback(err);
}
var variables = {
userName: user.name
};
var eventData = {
key: key,
scope: ['all'],
variables: variables
};
saveEvent(eventData, callback);
}
}
function leagueData(key, data, callback) {
var selector = {
_id: data.leagueId
};
League.findOne(selector).populate('founder').exec(prepareEvent);
function prepareEvent(err, league) {
if (err) {
return callback(err);
}
var variables = {
leagueId: league.id,
leagueName: league.name,
memberName: league.founder.name
};
var eventData = {
key: key,
scope: ['all', league.id],
variables: variables
};
saveEvent(eventData, callback);
}
}
function saveEvent(eventData, callback) {
var eventDoc = new Event(eventData);
eventDoc.save(callback);
}
function create(key, data, callback) {
if (!handlerLookup.hasOwnProperty(key)) {
throw new Error('No handler for key: ' + key);
}
handlerLookup[key](key, data, callback);
}
/**
* EXPORTS.
*/
module.exports = {
create: create
};<file_sep>/routes/apis/usersApi.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var User = require('schemes').User;
var authentication = require('middleware').authentication;
var validation = require('middleware').validation;
var patchUsersValidation = require('validations').patchUsersValidation;
var postUsersValidation = require('validations').postUsersValidation;
var putUsersValidation = require('validations').putUsersValidation;
var events = require('routes/modules').events;
/**
* ROUTES.
*/
// GET
router.get('/:userId',
authentication(),
getUser);
// GET
router.get('/',
authentication(),
getUsers);
// POST
router.post('/',
validation(postUsersValidation),
postUsers);
// PUT
router.put('/:userId',
authentication(),
validation(putUsersValidation),
putUsers);
// PATCH
router.patch('/:userId',
authentication(),
validation(patchUsersValidation),
patchUsers);
// DELETE
router.delete('/:userId',
authentication('admin'),
validation(),
deleteUsers)
/**
* FUNCTIONS.
*/
function getUser(req, res, next) {
var userId = req.params.userId;
var selector = {
_id: userId
};
User.findOne(selector, gotUser);
function gotUser(err, user) {
if (err) {
return next(err);
}
res.json({
user: user
});
}
}
function getUsers(req, res, next) {
User.find({}).exec(gotUsers);
function gotUsers(err, user) {
if (err) {
return next(err);
}
res.json({
users: users
});
}
}
function postUsers(req, res, next) {
var params = req.body;
if (params.password !== params.passwordwdh) {
var err = new Error('Die Passwortwiederholung stimmt nicht überein');
err.status = 400;
return next(err);
}
var user = new User(params);
user.setPassword(params.password);
user.save(savedUser);
function savedUser(err, user) {
if (err) {
return next(err);
}
req.session.user = user;
events.create('user.new', {
userId: user.id
}, writeResponse);
function writeResponse(err) {
if (err) {
return next(err);
}
res.status(201).json({
user: user
});
}
}
}
function putUsers(req, res, next) {
res.json(1);
}
function patchUsers(req, res, next) {
var userId = req.params.userId;
var updates = req.body;
var selector = {
_id: userId
};
var data = {
$set: updates,
$inc: {
__v: 1
}
};
User.update(selector, data, updatedUser);
function updatedUser(err, updated) {
if (err) {
return next(err);
}
res.json({
updated: updated
});
}
}
function deleteUsers(req, res, next) {
var userId = req.params.userId;
var selector = {
_id: userId
};
User.remove(selector, removedUser);
function removedUser(err, deleted) {
if (err) {
return next(err);
}
res.json({
deleted: deleted
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/assets/js/components/template.js
'use strict';
/**
* FUNCTIONS.
*/
function template(html, variables) {
return html.replace(/#{(.*?)}/gi, function(match, key) {
return (typeof variables[key] === 'undefined') ? '' : variables[key];
});
};
/**
* EXPORTS.
*/
module.exports = template;<file_sep>/routes/apis/commentsApi.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Membership = require('schemes').Membership;
var Comment = require('schemes').Comment;
var Post = require('schemes').Post;
var authentication = require('middleware').authentication;
var validation = require('middleware').validation;
var events = require('routes/modules').events;
/**
* ROUTES.
*/
router.post('/',
authentication(),
postComments);
router.patch('/:commentId',
authentication(),
patchComments);
router.delete('/:commentId',
authentication(),
deleteComments);
/**
* FUNCTIONS.
*/
function patchComments(req, res, next) {
var commentId = req.params.commentId;
var data = req.body;
var selector = {
_id: commentId
};
Comment.findOne(selector, processComment);
function processComment(err, comment) {
if (err) {
return next(err);
}
if (!comment) {
var error = new Error('Cannot find comment with given id.');
error.status = 400;
return next(error);
}
if (comment.member !== req.session.user.id) {
var error = new Error('You are not allowed to delete this comment.');
error.status = 403;
return next(error);
}
data._modifiedOn = new Date();
Comment.update(selector, { $set: data }, writeResponse);
}
function writeResponse(err, updated) {
if (err) {
return next(err);
}
res.json({
updated: updated
});
}
}
function postComments(req, res, next) {
var data = req.body;
var response = {};
data.member = req.session.user.id;
var comment = new Comment(data);
comment.save(savedComment);
function savedComment(err, comment) {
if (err) {
return next(err);
}
response.comment = comment;
Post.update({ _id: data.post }, { $inc: { comments: 1 } }, updatedPost);
}
function updatedPost(err, updated) {
if (err) {
return next(err);
}
events.create('comment.new', {
commentId: comment.id
}, writeResponse);
}
function writeResponse(err) {
if (err) {
return next(err);
}
res.json(response);
}
}
function deleteComments(req, res, next) {
var commentId = req.params.commentId;
var selector = {
_id: commentId,
member: req.session.user.id
};
Comment.findOneAndRemove(selector, removedComment);
function removedComment(err, comment) {
if (err) {
return next(err);
}
if (!comment) {
var error = new Error("Cannot find comment with given id.");
error.status = 400;
return next(error);
}
Post.update({ _id: comment.post }, { $inc: { comments: -1 } }, writeResponse);
}
function writeResponse(err, updated) {
if (err) {
return next(err);
}
res.json({
updated: updated
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/assets/js/pages/modelsPage.js
'use strict';
/**
* MODULES.
*/
var Page = require('./page.js');
/**
* FUNCTIONS.
*/
function ModelsPage(path, params) {
Page.call(this, path, params);
this.path = path;
this.params = params;
}
ModelsPage.prototype = Object.create(Page.prototype);
ModelsPage.prototype.constructor = ModelsPage;
ModelsPage.prototype.render = function render(html, response, callback) {
this._activated();
callback(null, this.container);
};
ModelsPage.prototype._activated = function _activated() {
};
ModelsPage.prototype.activated = function activated() {
this._activated();
};
/**
* EXPORTS.
*/
module.exports = ModelsPage;<file_sep>/schemes/User.js
/**
* Schema for user.
*
* User: <NAME> <<EMAIL>>
*/
'use strict';
/**
* MODULES.
*/
var mongoose = require('mongoose');
var crypto = require('crypto');
var uuid = require('node-uuid');
var Schema = mongoose.Schema;
/**
* VARIABLES.
*/
var schema = new Schema({
_createdOn: {
type: Date,
default: Date.now
},
email: {
type: String,
required: true,
index: {
unique: true
}
},
name: {
type: String,
required: true
},
roaster: {
type: Array,
default: []
},
roles: {
type: Array,
default: ['user']
},
salt: {
type: String,
required: true,
default: uuid.v1
},
passwdHash: {
type: String
}
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
/**
* FUNCTIONS.
*/
var hash = function(password, salt) {
return crypto.createHmac('sha256', salt).update(password).digest('hex')
};
schema.methods.setPassword = function(password) {
this.passwdHash = hash(password, this.salt);
};
schema.methods.isValidPassword = function(password) {
return this.passwdHash === hash(password, this.salt);
};
/**
* EXPORTS.
*/
mongoose.model('User', schema);
module.exports = mongoose.model('User');<file_sep>/routes/apis/postsApi.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Membership = require('schemes').Membership;
var Post = require('schemes').Post;
var Comment = require('schemes').Comment;
var authentication = require('middleware').authentication;
var validation = require('middleware').validation;
var events = require('routes/modules').events;
/**
* ROUTES.
*/
// POST
router.post('/',
authentication(),
postPosts);
router.patch('/:postId',
authentication(),
patchPosts);
router.delete('/:postId',
authentication(),
deletePosts);
/**
* FUNCTIONS.
*/
function patchPosts(req, res, next) {
var postId = req.params.postId;
var data = req.body;
var response = {};
var selector = {
_id: postId
};
Post.findOne(selector, processPost);
function processPost(err, post) {
if (err) {
return next(err);
}
if (!post) {
var error = new Error('Cannot find post with given id.');
error.status = 400;
return next(error);
}
response.post = post;
data._modifiedOn = new Date();
Post.update(selector, { $set: data }, writeResponse);
}
function writeResponse(err, updated) {
if (err) {
return next(err);
}
response.updated = updated;
res.json(response);
}
}
function postPosts(req, res, next) {
var data = req.body;
var selector = {
member: req.session.user.id,
league: data.league
};
Membership.findOne(selector, checkPermission);
function checkPermission(err, membership) {
if (err) {
return next(err);
}
if (!membership) {
var error = new Error('Not member of league');
error.status = 400;
return next(error);
}
if (membership.role !== 'admin') {
var error = new Error('You have no permission to create post');
error.status = 400;
return next(error);
}
data.member = req.session.user.id;
var post = new Post(data);
post.save(savedPost);
}
function savedPost(err, post) {
if (err) {
return next(err);
}
events.create('post.new', {
postId: post.id
}, writeResponse);
function writeResponse(err) {
if (err) {
return next(err);
}
res.json({
post: post
});
}
}
}
function deletePosts(req, res, next) {
var postId = req.params.postId;
var selector = {
_id: postId,
member: req.session.user.id
};
Post.remove(selector, removedPost);
function removedPost(err, removed) {
if (err) {
return next(err);
}
if (!removed) {
var error = new Error("Cannot find post with given id.");
error.status = 400;
return next(error);
}
var selector = {
post: postId
};
Comment.remove(selector, writeResponse);
}
function writeResponse(err, removed) {
if (err) {
return next(err);
}
res.json({
removed: 1
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/routes/apis/playdaysApi.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Playday = require('schemes').Playday;
var Membership = require('schemes').Membership;
var League = require('schemes').League;
var authentication = require('middleware').authentication;
var validation = require('middleware').validation;
var patchPlaydaysValidation = require('validations').patchPlaydaysValidation;
var postPlaydaysValidation = require('validations').postPlaydaysValidation;
var putPlaydaysValidation = require('validations').putPlaydaysValidation;
var moment = require("moment");
var events = require('routes/modules').events;
/**
* VARIABLES.
*/
/**
* ROUTES.
*/
// GET
router.get('/:playdaysId',
authentication(),
getPlayday);
// GET
router.get('/',
authentication(),
getPlaydays);
// POST
router.post('/',
authentication(),
validation(postPlaydaysValidation),
postPlaydays);
// PUT
router.put('/:playdaysId',
authentication(),
validation(putPlaydaysValidation),
putPlaydays);
// PATCH
router.patch('/:playdaysId',
authentication(),
validation(patchPlaydaysValidation),
patchPlaydays)
// DELETE
router.delete('/:playdaysId',
authentication(),
deletePlaydays);
/**
* FUNCTIONS.
*/
function getPlayday(req, res, next) {
}
function getPlaydays(req, res, next) {
}
function postPlaydays(req, res, next) {
var data = req.body;
var selector = {
member: req.session.user.id,
league: data.league
};
Membership.findOne(selector, checkPermission);
function checkPermission(err, membership) {
if (err) {
return next(err);
}
if (!membership) {
var error = new Error('Not member of league');
error.status = 400;
return next(error);
}
if (membership.role !== 'admin') {
var error = new Error('You have no permission to create post');
error.status = 400;
return next(error);
}
data.member = req.session.user.id;
var datum = data.startDate.split(".");
if (datum.length !== 3) {
var error = new Error("Invalid date.");
error.status = 400;
return next(error);
}
data.startDate = moment(datum[1] + '.' + datum[0] + '.' + datum[2])._d;
var playday = new Playday(data);
playday.save(savedPlayday);
}
function savedPlayday(err, playday) {
if (err) {
return next(err);
}
events.create('playday.new', {
playdaysId: playday.id
}, updateLeague);
function updateLeague(err) {
if (err) {
return next(err);
}
League.update({ _id: data.league }, { $inc: { playdays: 1 } }, writeResponse);
}
function writeResponse(err) {
if (err) {
return next(err);
}
res.json({
playday: playday
});
}
}
}
function putPlaydays(req, res, next) {
res.json(1);
}
function patchPlaydays(req, res, next) {
var playdaysId = req.params.playdaysId;
var data = req.body;
var response = {};
var datum = data.startDate.split(".");
if (datum.length !== 3) {
var error = new Error("Invalid date.");
error.status = 400;
return next(error);
}
data.startDate = moment(datum[1] + '.' + datum[0] + '.' + datum[2])._d;
var selector = {
_id: playdaysId
};
Playday.findOne(selector, processPlayday);
function processPlayday(err, playday) {
if (err) {
return next(err);
}
if (!playday) {
var error = new Error('Cannot find playday with given id.');
error.status = 400;
return next(error);
}
response.playday = playday;
data._modifiedOn = new Date();
Playday.update(selector, { $set: data }, writeResponse);
}
function writeResponse(err, updated) {
if (err) {
return next(err);
}
response.updated = updated;
res.json(response);
}
}
function deletePlaydays(req, res, next) {
var playdaysId = req.params.playdaysId;
var selector = {
_id: playdaysId
};
Playday.findOneAndRemove(selector, removedPlayday);
function removedPlayday(err, playday) {
if (err) {
return next(err);
}
if (!playday) {
var error = new Error("Cannot find playday with given id.");
error.status = 400;
return next(error);
}
var selector = {
_id: playday.league
};
League.update(selector, { $inc: { playdays: -1 } }, writeResponse);
}
function writeResponse(err, updated) {
if (err) {
return next(err);
}
res.json({
removed: 1
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/assets/js/components/forms.js
'use strict';
/**
* MODULES.
*/
var config = require('../config.js');
/**
* VARIABLES.
*/
var apiUrl = ['', config.client.api.path, config.client.api.version].join('/');
/**
* FUNCTIONS.
*/
function enable(container, callback) {
var options = {
callback: callback || function() {}
};
container.find('form').on('submit', _onFormSubmit.bind(null, options));
container.find('form .submit-substitute').click(_submitSubstituteForm);
}
function _submitSubstituteForm(e) {
var target = e.currentTarget;
var formName = target.getAttribute('data-form');
var formular = null;
if (!formName) {
while (target.nodeName !== 'FORM' && target.nodeName !== 'BODY') {
target = target.parentNode;
}
if (target.nodeName === 'FORM') {
formular = target;
}
} else {
formular = document.forms[formName];
}
if (formular) {
if (!formular.submitButton) {
var submit = document.createElement('input');
submit.type = 'submit';
submit.setAttribute('style', 'display:none');
formular.appendChild(submit);
formular.submitButton = submit;
}
formular.submitButton.click();
}
}
function _onFormSubmit(options, e) {
e.preventDefault();
var form = e.currentTarget;
options.url = form.getAttribute('data-action');
options.type = form.getAttribute('data-method');
options.form = form;
var requestType = form.getAttribute('data-html');
if (!requestType || requestType === 'false') {
options.url = apiUrl + options.url;
}
_request(_buildData(form), options);
return false;
}
function _buildData(form) {
var data = {};
for (var i = 0; i < form.length; i++) {
var element = form[i];
if (element.type === 'text' || element.type === 'password' || element.type === 'hidden' || (element.type === 'radio' && element.checked) || element.nodeName === 'TEXTAREA') {
var parts = element.name.match(/^(\w+)\[(\d+)\]\[(\w+)\]/);
if (parts) {
var name = parts[1];
var index = parts[2];
var param = parts[3];
if (!data.hasOwnProperty(name)) {
data[name] = [];
}
if (!data[name].hasOwnProperty(index)) {
data[name][index] = {};
}
data[name][index][param] = element.value;
} else {
data[element.name] = element.value;
}
}
}
return data;
}
function _request(data, options) {
options = options || {};
options.method = options.type || 'get';
options.url = options.url || '';
options.contentType = options.contentType || 'application/json';
options.dataType = options.dataType || 'json';
var request = {
url: options.url,
type: options.method,
contentType: options.contentType + '; charset=UTF-8',
dataType: options.dataType,
success: onSuccess,
error: onError
};
request.data = JSON.stringify(data);
$.ajax(request);
function onSuccess(data, status, response) {
options.callback(null, data, status, response, options.form);
}
function onError(response, status, error) {
var err = {
response: response,
status: status,
error: error,
message: response.responseJSON.message,
form: options.form
};
options.callback(err);
}
}
/**
* EXPORTS.
*/
module.exports = {
enable: enable
};<file_sep>/assets/js/components/login.js
function onSuccess(message) {
location.href = '/login';
}
function onError(err) {
swal({
title: 'Oops...',
text: err.responseJSON.message,
type: 'error'
});
}
module.exports = {
path: '/login',
onSuccess: onSuccess,
onError: onError
};<file_sep>/routes/apis/modelsApi.js
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var Model = require('schemes').Model;
var authentication = require('middleware').authentication;
var validation = require('middleware').validation;
var patchModelsValidation = require('validations').patchModelsValidation;
var postModelsValidation = require('validations').postModelsValidation;
var putModelsValidation = require('validations').putModelsValidation;
/**
* ROUTES.
*/
// GET
router.get('/:modelId',
authentication(),
getModel);
// GET
router.get('/',
//authentication(),
getModels);
// POST
router.post('/',
//authentication('admin'),
validation(postModelsValidation),
postModels);
// PUT
router.put('/:modelId',
//authentication('admin'),
validation(putModelsValidation),
putModels);
// PATCH
router.patch('/:modelId',
//authentication('admin'),
validation(patchModelsValidation),
patchModels)
// DELETE
router.delete('/:modelId',
//authentication('admin'),
deleteModels);
/**
* FUNCTIONS.
*/
function getModel(req, res, next) {
var modelId = req.params.modelId;
var selector = {
_id: modelId
};
Model.findOne(selector, gotModels);
function gotModel(err, model) {
if (err) {
return next(err);
}
res.json({
model: model
});
}
}
function getModels(req, res, next) {
Model.find({}, gotModels);
function gotModels(err, models) {
if (err) {
return next(err);
}
res.json({
models: models
});
}
}
function postModels(req, res, next) {
var params = req.body;
var model = new Model(params);
model.save(savedModel);
function savedModel(err, model) {
if (err) {
return next(err);
}
res.status(201).json({
model: model
});
}
}
function putModels(req, res, next) {
res.json(1);
}
function patchModels(req, res, next) {
var modelId = req.params.modelId;
var updates = req.body;
var selector = {
_id: modelId
};
var data = {
$set: updates,
$inc: {
__v: 1
}
};
Model.update(selector, data, updatedModel);
function updatedModel(err, updated) {
if (err) {
return next(err);
}
res.json({
updated: updated
});
}
}
function deleteModels(req, res, next) {
var modelId = req.params.modelId;
var selector = {
_id: modelId
};
Model.remove(selector, removedModel);
function removedModel(err, deleted) {
if (err) {
return next(err);
}
res.json({
deleted: deleted
});
}
}
/**
* EXPORTS.
*/
module.exports = router;<file_sep>/routes/pages/loginPage.js
(function () {
'use strict';
/**
* MODULES.
*/
var express = require('express');
var router = express.Router();
var User = require('schemes').User;
/**
* ROUTES.
*/
router.route('/')
.get(getLoginPage)
.post(postLoginPage);
/**
* FUNCTIONS.
*/
function getLoginPage(req, res, next) {
if (req.session.user) {
if (req.xhr) {
res.status(204).send();
} else {
res.redirect('/');
}
} else {
res.render('pages/login');
}
}
function postLoginPage(req, res, next) {
var email = req.body.email;
var password = <PASSWORD>;
var selector = {
email: email
};
User.findOne(selector, foundUser);
function foundUser(err, user) {
if (err) {
return next(err);
}
if (!user) {
var err = new Error('Email wurde nicht gefunden!');
err.status = 400;
return next(err);
}
if (!user.isValidPassword(password)) {
var err = new Error('Falsches Passwort!');
err.status = 401;
return next(err);
}
req.session.user = user;
if (req.xhr) {
res.json({ message: 'Erfolgreich eingeloggt' });
} else {
res.redirect('/');
}
}
}
/**
* EXPORTS.
*/
module.exports = router;
}) (); | d51ed3065abbca2a5328f7fff573c348bb320788 | [
"JavaScript"
] | 42 | JavaScript | Amberlamps/gntm-dgmp-v2 | f3963baae8f674ff155ab3353422d94c758438b1 | 9a1011124c6813f9c17ae4f2c39c8cf7664970e6 |
refs/heads/master | <repo_name>bobbystrange/convkit-cs<file_sep>/pptconv/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConvKit
{
class Program
{
static void Main(string[] args)
{
string fileType = null;
string inputPath = null;
string outputPath = null;
if (args.Length == 3)
{
fileType = args[0];
inputPath = args[1];
outputPath = args[2];
}
else if (args.Length == 2)
{
inputPath = args[0];
outputPath = args[1];
int dotIndex = outputPath.LastIndexOf(".");
if (dotIndex > 0 && dotIndex < inputPath.Length - 1)
{
fileType = "-" + outputPath.Substring(dotIndex + 1);
outputPath = outputPath.Substring(0, dotIndex);
}
}
else
{
help();
return;
}
Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType type;
switch (fileType)
{
case "-pdf":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
break;
case "-xps":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsXPS;
break;
case "-xml":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsXMLPresentation;
break;
case "-jpg":
case "-jpeg":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsJPG;
break;
case "-png":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG;
break;
case "-tif":
case "-tiff":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsTIF;
break;
case "-bmp":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsBMP;
break;
case "-gif":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsGIF;
break;
case "-mp4":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsMP4;
break;
case "-wmv":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsWMV;
break;
case "-ppt":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation;
break;
case "-pptx":
type = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsStrictOpenXMLPresentation;
break;
default:
help();
return;
}
saveAs(inputPath, outputPath, type);
}
static void help()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error, invalid usage!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Usage: pptconv.exe -jpeg|-png|-tiff|-bmp|-gif|-mp4|-wmv|-pdf|-xps|-ppt|-pptx inputPath outputPath");
Console.ResetColor();
Environment.Exit(1);
}
static void saveAs(string inputPath, string outputPath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType type)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
app.Presentations.Open(
inputPath,
Microsoft.Office.Core.MsoTriState.msoTrue, // ReadOnly
Microsoft.Office.Core.MsoTriState.msoFalse, // Untitled
Microsoft.Office.Core.MsoTriState.msoFalse) // WithWindow
.SaveAs(outputPath, type);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
}
}
<file_sep>/wordconv/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConvKit
{
class Program
{
static void Main(string[] args)
{
string fileType = null;
string inputPath = null;
string outputPath = null;
if (args.Length == 3)
{
fileType = args[0];
inputPath = args[1];
outputPath = args[2];
}
else if (args.Length == 2)
{
inputPath = args[0];
outputPath = args[1];
int dotIndex = outputPath.LastIndexOf(".");
if (dotIndex > 0 && dotIndex < inputPath.Length - 1)
{
fileType = "-" + outputPath.Substring(dotIndex + 1);
outputPath = outputPath.Substring(0, dotIndex);
}
}
else
{
help();
return;
}
Microsoft.Office.Interop.Word.WdSaveFormat type;
switch (fileType)
{
case "-pdf":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
break;
case "-xps":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXPS;
break;
case "-xml":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;
break;
case "-xml-flat":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFlatXML;
break;
case "-xml-document":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;
break;
case "-html":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
break;
case "-doc":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatOpenDocumentText;
break;
case "-docx":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatStrictOpenXMLDocument;
break;
case "-txt":
case "-text":
type = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatUnicodeText;
break;
default:
help();
return;
}
saveAs(inputPath, outputPath, type);
}
static void help()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error, invalid usage!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Usage: wordconv.exe -pdf|-xps|-xml|-xml-flat|-xml-document|-html|-text|-doc|-docs inputPath outputPath");
Console.ResetColor();
Environment.Exit(1);
}
static void saveAs(string inputPath, string outputPath, Microsoft.Office.Interop.Word.WdSaveFormat type)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
var app = new Microsoft.Office.Interop.Word.Application();
app.Documents.Open(
inputPath,
Microsoft.Office.Core.MsoTriState.msoFalse, // Confirm Conversion
Microsoft.Office.Core.MsoTriState.msoTrue) // Read Only
.SaveAs(outputPath, type);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
}
}
<file_sep>/office2pdf/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConvKit
{
class Program
{
static void Main(string[] args)
{
string fileType = null;
string inputPath = null;
string outputPath = null;
if (args.Length == 2)
{
inputPath = args[0];
outputPath = args[1];
int dotIndex = inputPath.LastIndexOf(".");
if (dotIndex > 0 && dotIndex < inputPath.Length - 1)
{
fileType = "-" + inputPath.Substring(dotIndex + 1);
}
}
else if (args.Length == 3)
{
fileType = args[0];
inputPath = args[1];
outputPath = args[2];
}
else
{
help();
}
switch (fileType)
{
case "-ppt":
case "-pptx":
ppt2pdf(inputPath, outputPath);
break;
case "-word":
case "-doc":
case "-docx":
word2pdf(inputPath, outputPath);
break;
case "-excel":
case "-xls":
case "-xlsx":
excel2pdf(inputPath, outputPath);
break;
default:
help();
return;
}
}
static void help()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error, invalid usage!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Usage: office2pdf.exe [-ppt|-word|-excel] inputPath outputPath");
Console.ResetColor();
Environment.Exit(1);
}
static void ppt2pdf(string inputPath, string outputPath)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
app.Presentations.Open(
inputPath,
Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoFalse)
.SaveAs(
outputPath,
Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
static void word2pdf(string inputPath, string outputPath)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
app.Documents.Open(
inputPath,
// Confirm Conversion
Microsoft.Office.Core.MsoTriState.msoFalse,
// Read Only
Microsoft.Office.Core.MsoTriState.msoTrue)
.SaveAs(
outputPath,
Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
static void excel2pdf(string inputPath, string outputPath)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Workbooks.Open(
inputPath,
Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoTrue)
.ExportAsFixedFormat(
Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF,
outputPath
);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
static void ppt2jpg(string inputPath, string outputPath)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
app.Presentations.Open(
inputPath,
Microsoft.Office.Core.MsoTriState.msoTrue, // ReadOnly
Microsoft.Office.Core.MsoTriState.msoFalse, // Untitled
Microsoft.Office.Core.MsoTriState.msoFalse) // WithWindow
.SaveAs(
outputPath,
Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsJPG);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
}
}
<file_sep>/excelconv/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConvKit
{
class Program
{
static void Main(string[] args)
{
string fileType = null;
string inputPath = null;
string outputPath = null;
if (args.Length == 3)
{
fileType = args[0];
inputPath = args[1];
outputPath = args[2];
}
else if (args.Length == 2)
{
inputPath = args[0];
outputPath = args[1];
int dotIndex = outputPath.LastIndexOf(".");
if (dotIndex > 0 && dotIndex < inputPath.Length - 1)
{
fileType = "-" + outputPath.Substring(dotIndex + 1);
outputPath = outputPath.Substring(0, dotIndex);
}
}
else
{
help();
return;
}
Microsoft.Office.Interop.Excel.XlFixedFormatType? type = null;
Microsoft.Office.Interop.Excel.XlFileFormat? format = null;
switch (fileType)
{
case "-pdf":
type = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
break;
case "-xps":
type = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypeXPS;
break;
case "-csv":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV;
break;
case "-csv-mac":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVMac;
break;
case "-csv-dos":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVMSDOS;
break;
case "-csv-windows":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows;
break;
case "-xml":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet;
break;
case "-xls":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook;
break;
case "-xlsx":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLStrictWorkbook;
break;
case "-html":
format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
break;
default:
help();
return;
}
if (type != null)
exportAsFixedFormat(inputPath, outputPath, (Microsoft.Office.Interop.Excel.XlFixedFormatType)type);
else
saveAs(inputPath, outputPath, (Microsoft.Office.Interop.Excel.XlFileFormat)format);
}
static void help()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error, invalid usage!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Usage: excelconv.exe -pdf|-xps|-csv|-xml|-html|-xls|-xlsx inputPath outputPath");
Console.ResetColor();
Environment.Exit(1);
}
static void exportAsFixedFormat(string inputPath, string outputPath, Microsoft.Office.Interop.Excel.XlFixedFormatType type)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Workbooks.Open(inputPath)
.ExportAsFixedFormat(type, outputPath);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
static void saveAs(string inputPath, string outputPath, Microsoft.Office.Interop.Excel.XlFileFormat format)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
}
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Workbooks.Open(inputPath)
.SaveAs(outputPath, format);
app.Quit();
}
catch (Exception e)
{
throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
}
}
}
}
| 7ccf3f92523a4e29666a28143e29ba9b22796413 | [
"C#"
] | 4 | C# | bobbystrange/convkit-cs | 11a4341f241b0a27d1971baf5b83b2fdf337f09e | 204718276a030c844a01d56b35b1cb63dc2e32c1 |
refs/heads/master | <repo_name>10110111/asterixInspector<file_sep>/asterix.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2014 <NAME> (<EMAIL>)
*/
#ifndef ASTERIX_H
#define ASTERIX_H
#include <QtCore>
class AsterixRecord;
class AsterixDataItem;
#include "uap.h"
#include "bit.h"
class AsterixBlock
{
public:
AsterixBlock(const uchar* data, const Uap& uap);
const uchar* data() const { return m_data; }
quint8 category() const { return *(quint8*)(m_data + 0); }
quint16 length() const { return qFromBigEndian<quint16>(m_data + 1); }
int numRecords() const { return m_records.count(); }
const AsterixRecord& record(int index) const { return m_records[index]; }
static int countExtends(const uchar* p);
static QList<int> decodeFspecSection(const uchar* p, int size);
protected:
const uchar* m_data;
QList<AsterixRecord> m_records;
};
class AsterixRecord
{
public:
AsterixRecord(const uchar* data, int blockIndex, const UapCategory* uapCat);
const uchar* data() const { return m_data; }
int length() const { return m_length; }
int numFields() const { return m_fields.count(); }
const AsterixDataItem& field(int index) const { return m_fields[index]; }
QTime timeOfDay() const { return m_timeOfDay; }
QList<int> decodeFspecSection() const;
protected:
const uchar* m_data;
int m_index; // record-index in block
int m_length;
QTime m_timeOfDay;
QList<AsterixDataItem> m_fields;
};
class AsterixDataItem
{
public:
AsterixDataItem(const uchar* data, const UapDataItem* uapDataItem);
const UapDataItem* uapDataItem() const { return m_uapDataItem; }
const uchar* data() const { return m_data; }
int length() const { return m_length; }
int numSubfields() const { return m_subfields.count(); }
const AsterixDataItem& subField(int index) const { return m_subfields[index]; }
QByteArray bitfield(int o, int l, int msb, int lsb) const;
static QChar decodeIcaoSixBitChar(int c);
static QString decodeIcaoStr(const uchar* p);
protected:
int numExtends() const { return AsterixBlock::countExtends(m_data); }
const uchar* m_data;
int m_length;
const UapDataItem* m_uapDataItem;
QList<AsterixDataItem> m_subfields; // if this is a compound item, otherwise empty
};
#endif // ASTERIX_H
<file_sep>/uap.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "uap.h"
#include <QtXml>
#include "asterix.h"
#include "scaleExpressionParser.h"
#include "global.h"
const QStringList UapDataItem::m_formatStrs = QStringList() << "fixed" << "variable" << "explicit" << "repetive" << "compound"; // must match enum UapDataItem::Format
const QStringList UapField::m_formatStrs = QStringList() << "int" << "uint" << "hex" << "octal" << "icao6str" << "ascii"; // must match enum UapField::Format
// must match enum UapField::Unit
const QStringList UapField::m_unitStrs =
QStringList() << "UNDEFINED" << "deg" << "celsius" << "deg/s" << "ft" << "ft/min" << "FL" << "kn" << "ma" <<
"m" << "m/s" << "m/s^2" << "mb" << "nmi" << "nmi/s" << "s" << "m^2" << "MHz" << "dBm";
UapField::UapField(QDomElement fieldElm) :
m_octed( Uap::parseNumber(Uap::mandAtt(fieldElm, "octed")) ),
m_msb( Uap::parseNumber(fieldElm.attribute("msb")) ),
m_lsb( Uap::parseNumber(fieldElm.attribute("lsb")) ),
m_format(HEX),
m_unit(UNDEFINED),
m_scale(1.0)
{
m_name = fieldElm.firstChildElement("name").text();
m_desc = fieldElm.firstChildElement("desc").text();
m_format = formatFromStr(fieldElm.firstChildElement("format").text());
if (not fieldElm.firstChildElement("unit").text().isEmpty())
{
m_unit = unitFromStr(fieldElm.firstChildElement("unit").text());
}
if (not fieldElm.firstChildElement("scale").text().isEmpty())
{
bool error;
m_scale = ScaleExpressionParser::parse(fieldElm.firstChildElement("scale").text(), error);
if (error)
{
logError(ScaleExpressionParser::lastError + " in <scale> expression '" + fieldElm.firstChildElement("scale").text() + "'");
m_scale = 1.0;
}
}
if (m_msb < m_lsb)
{
logWarn("Invalid msb/lsb on field '" + m_name + "'");
m_msb = m_lsb;
}
QDomNodeList enums = fieldElm.elementsByTagName("enum");
for (int i = 0; i < enums.count(); i++)
{
QDomElement enumElm = enums.at(i).toElement();
UapEnum uapEnum( Uap::parseNumber(enumElm.attribute("value")), enumElm.text() );
m_enums.insert(uapEnum.m_value, uapEnum);
}
}
const QString& UapField::formatStr(Format format)
{
return m_formatStrs[format];
}
UapField::Format UapField::formatFromStr(const QString &str)
{
int i = m_formatStrs.indexOf(str.toLower());
if (i < 0)
return HEX; // Format description unknown or empty. Default to HEX.
else
return (Format)(i);
}
const QString& UapField::unitStr(Unit unit)
{
return m_unitStrs[unit];
}
UapField::Unit UapField::unitFromStr(const QString &str)
{
int i = (Unit)m_unitStrs.indexOf(str);
if (i < 0)
{
logWarn("Unknown <unit> " + str);
return UNDEFINED; // Unit description unknown or empty.
}
else
{
return (Unit)(i);
}
}
const QString& UapDataItem::formatStr(Format format)
{
return m_formatStrs[format];
}
UapDataItem::Format UapDataItem::formatFromStr(const QString &str)
{
return (Format)m_formatStrs.indexOf(str.toLower());
}
UapDataItem::UapDataItem(QDomElement itemElm) :
m_frn( Uap::mandAtt(itemElm, "frn").toInt() ),
m_id( itemElm.attribute("id") ),
m_format( UapDataItem::formatFromStr(Uap::mandAtt(itemElm, "format")) ),
m_length( Uap::parseNumber( itemElm.attribute("length") ) )
{
m_name = itemElm.firstChildElement("name").text();
m_definition = itemElm.firstChildElement("definition").text();
m_description = extractContents(itemElm.firstChildElement("desc"));
if (m_format != COMPOUND)
{
// iterate over child elements <field>
QDomNode node = itemElm.firstChild();
while (not node.isNull())
{
if (node.toElement().tagName() == "field")
{
UapField uapField( node.toElement() );
m_fields.append(uapField);
}
node = node.nextSiblingElement();
}
}
else
{
// iterate over child elements <subfield>
QDomNode node = itemElm.firstChild();
while (not node.isNull())
{
if (node.toElement().tagName() == "subfield")
{
UapDataItem* uapItem = new UapDataItem( node.toElement() );
uapItem->m_id = m_id + "#" + QString::number(uapItem->frn());
m_subFields.insert( uapItem->frn(), uapItem);
}
node = node.nextSiblingElement();
}
}
}
QString UapDataItem::extractContents(QDomElement el)
{
QString ret;
QTextStream s(&ret);
el.save(s, 0);
return ret;
}
int UapDataItem::calcLength(const uchar *p) const
{
switch (m_format) {
case FIXED:
return m_length;
break;
case VARIABLE:
return m_length + AsterixBlock::countExtends(p+m_length-1);
break;
case EXPLICIT:
return *(const quint8*)p;
break;
case REPETIVE:
return 1 + (*(const quint8*)p * m_length);
break;
case COMPOUND:
logError("Error in specification: Compound length cannot be computed.");
break;
}
return 0;
}
bool UapDataItem::fieldPresent(const uchar *p, const UapField &uapField) const
{
switch (m_format) {
case FIXED:
return true;
break;
case VARIABLE:
return uapField.octed() <= calcLength(p);
break;
case EXPLICIT:
return true;
break;
case REPETIVE:
return true;
break;
case COMPOUND:
logError("Error in specification: Field defintion not allowed below compound.");
return false;
break;
}
return false;
}
UapCategory::UapCategory(QDomElement catEl)
{
m_category = Uap::mandAtt(catEl, "cat").toInt();
m_version = catEl.attribute("version");
QDomNode node = catEl.firstChild();
while (not node.isNull())
{
if (node.toElement().tagName() == "dataitem")
{
UapDataItem* uapItem = new UapDataItem( node.toElement() );
m_dataItems.insert( uapItem->frn(), uapItem);
}
node = node.nextSiblingElement();
}
}
/** Return FRN of Time-Of-Day/Time-Of-Track field.
** or -1 if unknown or not present.
**/
int UapCategory::timeOfDayFrn() const
{
switch (m_category)
{
case 1: return 9;
case 2: return 4;
case 4: return 4;
case 7: return 4;
case 8: return 8;
case 10: return 4;
case 11: return 4;
case 19: return 3;
case 20: return 3;
case 21: return 5;
case 23: return 4;
case 25: return 6;
case 34: return 3;
case 48: return 2;
case 62: return 4;
case 63: return 3;
case 65: return 4;
}
return -1;
}
void Uap::readXml(QFile* input)
{
QDomDocument doc;
doc.setContent(input);
QDomNodeList catElms = doc.elementsByTagName("category");
for (int i = 0; i < catElms.count(); i++)
{
UapCategory* uapCategory = new UapCategory(catElms.at(i).toElement());
uapCategory->m_sourceFile = input->fileName();
m_categories.insert(uapCategory->category(), uapCategory);
logInfo("Read cat " + QString::number(uapCategory->m_category) + " version " + uapCategory->m_version + " from file '" + uapCategory->m_sourceFile + "'");
}
}
void Uap::readXml(QString dirpath)
{
QDir dir(dirpath);
logInfo("Reading *.xml files from directory " + dir.absolutePath());
QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.xml", QDir::Files | QDir::Readable);
if (fileInfos.isEmpty())
{
logWarn("No *.xml files found in " + dir.absolutePath());
}
foreach (QFileInfo fileInfo, fileInfos)
{
QFile file(fileInfo.filePath());
if (not file.open(QIODevice::ReadOnly))
{
logWarn("Unable to open file " + fileInfo.filePath());
continue;
}
readXml(&file);
}
}
const UapCategory *Uap::selectedUapCategory(int cat) const
{
if (m_selectedCategory.contains(cat))
{
return m_selectedCategory.value(cat);
}
else if (m_categories.contains(cat))
{
return m_categories.value(cat); // return first found
}
else
{
return nullptr;
}
}
/** Select UapCategory to be used for certain Asterix category.
** Asterix category number is extracted from uapCategory.
**/
void Uap::selectUapCategory(const UapCategory *uapCategory)
{
Q_ASSERT(uapCategory);
m_selectedCategory.insert(uapCategory->category(), uapCategory);
}
int Uap::parseNumber(const QString &number)
{
if (number.left(2) == "0x")
return number.mid( 1 ).toInt(0, 16);
else if (number.right(1) == "b")
return number.left( number.size()-1 ).toInt( 0, 2 );
else
return number.toInt();
}
QString Uap::mandAtt(QDomElement elm, const QString &att)
{
if (elm.attribute(att).isEmpty())
qFatal(qPrintable("Mandadory attribute '" + att + "'' is missing or empty on '" + elm.tagName() + "'."));
return elm.attribute(att);
}
<file_sep>/recordWidget.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "recordWidget.h"
RecordWidget::RecordWidget(QWidget *parent) :
QWidget(parent)
{
QVBoxLayout* vbox = new QVBoxLayout;
setLayout(vbox);
m_textEdit = new QTextEdit(this);
m_textEdit->setReadOnly(true);
layout()->addWidget(m_textEdit);
}
void RecordWidget::setRecord(const AsterixRecord *record)
{
m_textEdit->clear();
if (record == 0)
return;
const uchar* const p = record->data(); // points to fspec bytes
int numFspec = 1 + AsterixBlock::countExtends(p); // get number of fspec bytes
QList<int> frns = AsterixBlock::decodeFspecSection(p, numFspec);
QString html;
html += "<h3>Record field specification</h3>";
html += "<p><table cellspacing=\"0\" border=\"0\" style=\"\">";
html += "<tr style=\"font-family:monospace; font-size:large;\">";
html += "<td> </td>"; // row header
for (int f = 0; f < numFspec; f++)
{
QString byteHex = QString("%1").arg((uint)p[f], 2, 16, QChar('0')).toUpper();
html += "<td colspan=\"4\" align=\"center\" style=\"background-color:#e1ebfa; padding-top:2px; padding-bottom:2px;\">" + byteHex[0] + "</td>"
"<td colspan=\"4\" align=\"center\" style=\"background-color:#e1ebfa; padding-top:2px; padding-bottom:2px;\">" + byteHex[1] + "</td>";
html += "<td> </td>";
}
html += "</tr>";
html += "<tr style=\"font-family:monospace;\">";
html += "<td> </td>"; // row header
for (int f = 0; f < numFspec; f++)
{
QString byteBin = QString("%1").arg((uint)p[f], 8, 2, QChar('0'));
for (int b = 0; b < 8; b++)
{
html += "<td align=\"center\">" + byteBin[b] + "</td>";
}
html += "<td> </td>";
}
html += "</tr>";
html += "<tr>";
html += "<td align=\"right\" style=\"white-space:pre; padding-top:5px; padding-right:2px;\">FRNs</td>"; // row header
for (int f = 0; f < numFspec; f++)
{
for (int frn = f * 7 + 1; frn < f * 7 + 1 + 7; frn++)
{
html += "<td align=\"center\" style=\"white-space:pre; padding-top:5px; padding-left:2px; padding-right:2px;\"><nobr>";
if (frn < 10)
html += " ";
if (frns.contains(frn))
html += "<u>";
html += QString::number(frn);
if (frns.contains(frn))
html += "</u>";
if (frn < 10)
html += " ";
html += "</nobr></td>";
}
if (f < numFspec - 1)
html += "<td style=\"white-space:pre; padding-top:5px; padding-left:2px; padding-right:2px;\"><u>fx</u></td>";
else
html += "<td style=\"white-space:pre; padding-top:5px; padding-left:2px; padding-right:2px;\">fx</td>";
html += "<td> </td>";
}
html += "</tr>";
html += "</tr>";
html += "</table></p>";
m_textEdit->setHtml(html);
}
<file_sep>/asterixModel.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef ASTERIXMODEL_H
#define ASTERIXMODEL_H
#include <QtGui>
#include "asterixFileMapper.h"
#include "asterix.h"
class AsterixModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit AsterixModel(QObject *parent = 0);
int columnCount(const QModelIndex&) const { return 3; }
QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;
QModelIndex index( int row, int column = 0, const QModelIndex& parent = QModelIndex() ) const;
int rowCount(const QModelIndex& parent) const;
QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
QModelIndex parent( const QModelIndex&) const { return QModelIndex(); }
// bool canFetchMore(const QModelIndex &parent) const;
// void fetchMore(const QModelIndex &parent);
const AsterixBlockInfo& blockInfo(const QModelIndex& index) const;
int numBlocks() const { return m_numBlocks; }
const QVector<AsterixBlockInfo> getBlockInfos() const { return m_blocks; }
signals:
public slots:
void reserve(qint64 blocks) { m_blocks.resize(blocks); }
void squeeze() { m_blocks.resize(m_numBlocks); m_blocks.squeeze(); }
void asterixBlock(const QList<AsterixBlockInfo> block);
void blocksScanned(qint64 blockNum);
protected:
QVector<AsterixBlockInfo> m_blocks;
int m_numBlocks;
int m_blockInsertPos;
int m_blocksExposed;
QFile m_file;
};
class AsterixBlockModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit AsterixBlockModel(const uchar* base, const AsterixBlock& block, QObject *parent = 0);
int columnCount(const QModelIndex&) const { return 4; }
QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;
QModelIndex index( int row, int column = 0, const QModelIndex& parent = QModelIndex() ) const;
int rowCount(const QModelIndex& parent) const;
QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
QModelIndex parent( const QModelIndex&) const { return QModelIndex(); }
protected:
const uchar* m_base;
const AsterixBlock& m_asterixBlock;
};
class AsterixRecordModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit AsterixRecordModel(const uchar* base, const AsterixRecord& record, QObject *parent = 0);
int columnCount(const QModelIndex&) const { return 5; }
QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;
QModelIndex index( int row, int column = 0, const QModelIndex& parent = QModelIndex() ) const;
int rowCount(const QModelIndex& parent) const;
QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
QModelIndex parent( const QModelIndex&) const { return QModelIndex(); }
const AsterixDataItem& dataItemAtRow( int r ) const;
protected:
void buildRowHeaders();
const uchar* m_base;
const AsterixRecord& m_asterixRecord;
QStringList m_rowHeaders;
};
#endif // ASTERIXMODEL_H
<file_sep>/uap.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef UAP_H
#define UAP_H
#include <QtCore>
#include <QtXml>
class UapEnum
{
public:
UapEnum(int value, const QString& desc) : m_value(value), m_desc(desc) { }
int m_value;
QString m_desc;
};
class UapField
{
public:
enum Format {
INTEGER,
UINTEGER,
HEX,
OCTAL,
ICAO6STR, // str of 8 6-bit characters
ASCII,
};
enum Unit {
UNDEFINED,
DEGREE_CELSIUS,
DEGREE,
DEGREE_PER_SECOND,
FOOT,
FOOT_PER_MINUTE,
FLIGHTLEVEL,
KNOT,
MACH,
METER,
METER_PER_SECOND,
METER_PER_SQSECOND,
MILLIBAR,
NAUTICALMILE,
NAUTICALMILE_PER_SECOND,
SECOND,
SQMETER,
MEGAHERTZ,
DECIBELMILLIWATT,
};
UapField(QDomElement fieldElm);
QString name() const { return m_name; }
int octed() const { return m_octed; }
int msb() const { return m_msb; }
int lsb() const { return m_lsb; }
QString desc() const { return m_desc; }
Format format() const { return m_format; }
Unit unit() const { return m_unit; }
double scale() const { return m_scale; }
const QMap<int, UapEnum>& enums() const { return m_enums; }
static const QString& formatStr(Format format);
static Format formatFromStr(const QString& str);
static const QString& unitStr(Unit format);
static Unit unitFromStr(const QString& str);
protected:
void initStaticHashes();
QString m_name;
QString m_desc;
int m_octed;
int m_msb;
int m_lsb;
Format m_format;
Unit m_unit;
double m_scale;
QMap<int, UapEnum> m_enums;
static const QStringList m_formatStrs;
static const QStringList m_unitStrs;
};
class UapDataItem
{
public:
UapDataItem() { }
UapDataItem(QDomElement dataItemElm);
enum Format {
FIXED,
VARIABLE,
EXPLICIT,
REPETIVE,
COMPOUND
};
int frn() const { return m_frn; }
const QString id() const { return m_id; }
const QString name() const { return m_name; }
Format format() const { return m_format; }
int length() const { return m_length; }
const QString& definition() const { return m_definition; }
const QString& description() const { return m_description; }
int calcLength(const uchar* p) const;
bool fieldPresent(const uchar* p, const UapField& uapField) const;
static const QString& formatStr(Format format);
static Format formatFromStr(const QString& str);
static QString extractContents(QDomElement el);
QList<UapField> m_fields;
QMap<int, const UapDataItem*> m_subFields; // maps from sub-FRN to DataItem, if m_format==COMPOUND
protected:
int m_frn;
QString m_id;
QString m_name;
Format m_format;
int m_length;
QString m_definition;
QString m_description;
static const QStringList m_formatStrs;
};
class UapCategory
{
public:
UapCategory() : m_category(-1) { }
~UapCategory() { qDeleteAll(m_dataItems); }
UapCategory(QDomElement catEl);
int category() const { return m_category; }
const UapDataItem* dataItem(int frn) const;
int timeOfDayFrn() const;
int m_category;
QString m_version;
QString m_sourceFile;
QMap<int, const UapDataItem*> m_dataItems; // maps from FRN to DataItem
};
class Uap
{
public:
~Uap() { qDeleteAll(m_categories); }
void readXml(QFile *input);
void readXml(QString dirpath);
const UapCategory* selectedUapCategory(int cat) const;
void selectUapCategory(const UapCategory* uapCategory);
static int parseNumber(const QString& number);
static QString mandAtt(QDomElement elm, const QString& att);
QMultiMap<int, const UapCategory*> m_categories;
QMap<int, const UapCategory*> m_selectedCategory; // selected UAP for category
};
#endif // UAP_H
<file_sep>/asterixFileMapper.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "asterixFileMapper.h"
AsterixFileMapper::AsterixFileMapper(QIODevice* file, QObject *parent) :
QThread(parent),
m_file(file),
m_offset(0)
{
m_reachedEnd = false;
qRegisterMetaType<QList<AsterixBlockInfo> >();
}
void AsterixFileMapper::run()
{
qint64 blockCount = 0;
m_stopRequested = false;
m_file->seek(m_offset);
while (m_reachedEnd == false && m_stopRequested == false)
{
QList<AsterixBlockInfo> ret;
QTime time;
time.start();
do {
if (m_file->atEnd())
{
m_reachedEnd = true;
break;
}
m_file->seek(m_offset);
qint64 offset = m_file->pos();
quint8 category;
if (not m_file->read((char*)&category, 1))
break;
char sbuffer[2];
if (not m_file->read(sbuffer, 2))
break;
quint16 blockSize = qFromBigEndian<quint16>((uchar*)sbuffer);
if (blockSize >= 3 // valid blocksize
&& // and
offset + blockSize <= m_file->size() ) // block not truncated?
{
// yes
AsterixBlockInfo block = { offset, category, blockSize };
ret << block;
}
else
{
m_reachedEnd = true;
break;
}
m_offset += blockSize;
blockCount++;
} while (time.elapsed() < 100);
emit asterixBlock(ret);
emit bytesScanned(m_offset);
emit blocksScanned(blockCount);
msleep(50);
}
}
<file_sep>/bit.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2014 <NAME> (<EMAIL>)
*/
#ifndef BIT_H
#define BIT_H
// generate mask for lowest/lsb 'n' bits. E.g. BITMASK(6) => 0x3f
#ifndef BITMASK
#define BITMASK(n) ((1<<(n))-1)
#endif
// test if the 'n'th lowest/lsb is set
#ifndef BITTEST
#define BITTEST(v,n) ((bool)((v) & (1 << (n))))
#endif
// set the 'n'th lowest/lsb bit
#ifndef BITSET
#define BITSET(v,n) (v |= (1 << (n)))
#endif
// get u8/u16/u32 at octed offset 'ofs' without alignment&endian constraints
inline quint8 getU8(const uchar* p, int ofs) { return *reinterpret_cast<const quint8*>(p + ofs); }
inline quint16 getU16(const uchar* p, int ofs) { return qFromBigEndian<quint16>(p + ofs); }
inline quint32 getU32(const uchar* p, int ofs) { return qFromBigEndian<quint32>(p + ofs); }
/** Right shift QByteArray by 0..7 bits.
**/
inline
void shiftRight(QByteArray& a, int n)
{
Q_ASSERT(n < 8);
if (a.isEmpty())
return;
for (int i = a.length()-1; i > 0; i--)
{
a[i] = (a[i-1] << (8-n)) | ((uchar)a[i] >> n);
}
a[0] = (uchar)a[0] >> n;
}
/** Extract arbitrary bitfield (i.e. memory section on bit precision).
** Extract from memory at p with size n with inclusive bit indexes msb and lsb counting from 0 from end of memory.
** Resulting Bytearray is right-justified and 0-padded on left side.
**/
inline
QByteArray bitfield(const uchar* p, int n, int msb, int lsb)
{
Q_ASSERT(p);
Q_ASSERT(n > 0);
Q_ASSERT((msb >= lsb));
int lByte = n-1 - lsb/8; // offset of least sig byte
int mByte = n-1 - msb/8; // offset of most sig byte
QByteArray ret((const char*)(p + mByte), lByte-mByte+1); // copy memory to buffer
ret[0] = ret[0] & BITMASK(msb%8+1); // mask out left side
shiftRight(ret, lsb%8); // shift right
ret = ret.right((msb-lsb)/8+1); // drop leftover bytes
return ret;
}
/** Converts arbitrary data/bitfield to quint64.
**/
inline
quint64 bitfieldToUInt(QByteArray bitfield)
{
bitfield.prepend( QByteArray(8 - bitfield.size(), 0 )); // extend 'bitfield' to 64bit with prepended zeros
return qFromBigEndian<quint64>((const uchar*)bitfield.constData());
}
/** Converts arbitrary data/bitfield to qint64, cares for sign.
**/
inline
qint64 bitfieldToInt(QByteArray bitfield, int msb)
{
if (BITTEST(bitfield[bitfield.size()-1-msb/8], msb%8))
{
// msb is 1: sign extension
bitfield.prepend( QByteArray(8 - bitfield.size(), 0xff)); // extend 'bitfield' to 64bit with prepended 0xff
bitfield[7 - (msb/8)] = (0xff & ~BITMASK(msb % 8)) | bitfield[7 - (msb/8)];
return qFromBigEndian<qint64>((const uchar*)bitfield.constData());
}
else
{
return bitfieldToUInt(bitfield);
}
}
#endif // BIT_H
<file_sep>/mainWindow.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui>
#include "asterixModel.h"
#include "hexedit.h"
#include "dataItemWidget.h"
#include "recordWidget.h"
#include "TextHexDumpEdit.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected Q_SLOTS:
void openFile();
void showSpecificationSelectionDialog();
void readFile( const QString& filename );
void mapFile(qint64 ofs);
void blockClicked(const QModelIndex& index);
void recordClicked(const QModelIndex& index);
void fieldClicked(const QModelIndex& index);
void hexCursorPosChanged(qint64 pos);
void generateXmlReport();
void showAboutDialog();
protected:
Ui::MainWindow *ui;
void createDockWidgets();
QFile m_file;
AsterixFileMapper* m_mapper;
AsterixBlockModel* m_blockModel;
AsterixRecordModel* m_recordModel;
AsterixBlock* m_currentBlock;
int m_currentBlockIndex;
const AsterixRecord* m_currentRecord;
const AsterixDataItem* m_currentDataItem;
QLabel* m_blockCountLabel;
QLabel* m_cursorPosLabel;
HexEdit* m_hexEdit;
TextHexDumpEdit* m_hexDumpLoadEdit;
QDockWidget* m_detailDock;
DataItemWidget* m_dataItemWidget;
RecordWidget* m_recordWidget;
};
#endif // MAINWINDOW_H
<file_sep>/logger.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2013 <NAME> (<EMAIL>)
*/
#ifndef LOGGER_H
#define LOGGER_H
#include <QtWidgets>
#ifdef __MINGW32__
#ifdef ERROR
#undef ERROR
#endif
#endif
class Logger : public QObject
{
Q_OBJECT
public:
explicit Logger(QObject *parent = 0);
QTextEdit* textWidget() const { return m_textEdit; }
enum class Type {
INFO,
WARN,
ERROR
};
signals:
public slots:
void log(Type type, const QString& msg);
private:
QTextEdit* m_textEdit;
};
#endif // LOGGER_H
<file_sep>/specificationSelectDialog.cpp
#include "specificationSelectDialog.h"
#include "ui_specificationSelectDialog.h"
#include <map>
#include "global.h"
#include "uap.h"
struct HeaderEntry
{
QString title;
QString url;
};
std::map<int, HeaderEntry> categoryHeader
{
{ 1, {"Monoradar Target Reports (Part 2a)", ""} },
{ 2, {"Monoradar Service Messages (Part2b)", ""} },
{ 3, {"Distribution of Synthetic Air Traffic Data", ""} },
{ 4, {"Safety Net Messages (Part 17)", ""} },
{ 7, {"Directed Interrogation Messages", ""} },
{ 8, {"Monoradar Derived Weather Information", ""} },
{ 9, {"Multisensor Derived Weather Information", ""} },
{ 10, {"Monosensor Surface Movement Data", ""} },
{ 11, {"Advanced-SMGCS Data", ""} },
{ 12, {"Monoradar Target Reports", ""} },
{ 13, {"Monoradar Service Messages", ""} },
{ 14, {"Monoradar Weather Reports", ""} },
{ 17, {"Mode S Surveillance Co-ordination Function messages", ""} },
{ 18, {"Mode S Data-Link Function messages", ""} },
{ 19, {"MLT System Status Messages", ""} },
{ 20, {"MLT Messages", ""} },
{ 21, {"ADS-B Messages", ""} },
{ 22, {"TIS-B Management Messages", ""} },
{ 23, {"CNS/ATM Ground Station Service Messages", ""} },
{ 24, {"ADS-C Messages", ""} },
{ 25, {"CNS/ATM Ground System Status Reports", ""} },
{ 30, {"Exchange of Air Situation Pictures", ""} },
{ 31, {"Sensors Information messages (transmission of surveillance biases to users)", ""} },
{ 32, {"Information provided by users to ARTAS", ""} },
{ 33, {"ADS-B Messages (Assigned for use by FAA)", ""} },
{ 34, {"Monoradar Service Messages (Part 2b - next version of Cat 002)", ""} },
{ 48, {"Monoradar Target Reports (Part 4 - next version of Cat 001)", ""} },
{ 61, {"SDPS Session and Service Control Messages", ""} },
{ 62, {"System Track Data (Part 9)", ""} },
{ 63, {"Sensor Status Messages", ""} },
{ 65, {"SDPS Service Status Messages", ""} },
{128, {"Exchange of C3I messages", ""} },
{150, {"Flight Data Messages", ""} },
{151, {"Association Messages", ""} },
{152, {"Time Stamp Messages", ""} },
{153, {"Special Purpose Messages", ""} },
{204, {"Recognised Air Picture", ""} },
{221, {"Replaced by CAT024", ""} },
{239, {"Foreign Object Debris (FOD)", ""} },
{240, {"Radar Video Transmission", ""} },
{247, {"Version Number Exchange", ""} },
};
SpecificationSelectDialog::SpecificationSelectDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SpecificationSelectDialog)
{
m_scrollWidget = 0;
ui->setupUi(this);
populateTable();
}
SpecificationSelectDialog::~SpecificationSelectDialog()
{
delete ui;
}
void SpecificationSelectDialog::populateTable()
{
if (!g_uap)
return;
ui->scrollArea->takeWidget();
delete m_scrollWidget;
m_radioButtonGroups.clear();
m_radioButtonCategories.clear();
m_scrollWidget = new QWidget;
ui->scrollArea->setWidget(m_scrollWidget);
m_scrollWidget->setLayout(new QVBoxLayout);
foreach (int cat, g_uap->m_categories.uniqueKeys())
{
QFrame* frame = new QFrame;
m_scrollWidget->layout()->addWidget(frame);
frame->setFrameStyle(QFrame::Box | QFrame::Plain);
QVBoxLayout* vbox1 = new QVBoxLayout;
frame->setLayout(vbox1);
QLabel* label = new QLabel(QString::number(cat));
vbox1->addWidget(label);
QFont font(label->font());
font.setBold(true);
label->setFont(font);
if (categoryHeader.count(cat))
{
label->setText(QString("Cat %1: ").arg(cat) + categoryHeader[cat].title);
}
QVBoxLayout* vbox2 = new QVBoxLayout;
vbox1->addLayout(vbox2);
vbox2->setContentsMargins(8, 4, 0, 4);
vbox2->setSpacing(8);
m_radioButtonGroups.insert(cat, new QButtonGroup(m_scrollWidget));
// iterate over defined UapCategory for current cat
foreach (const UapCategory* uapCat, g_uap->m_categories.values(cat))
{
QRadioButton* button = new QRadioButton(uapCat->m_version + "\n" + uapCat->m_sourceFile);
vbox2->addWidget(button);
m_radioButtonCategories.insert(button, uapCat);
m_radioButtonGroups[cat]->addButton(button);
// if current UapCategory is selected for usage check button
if (uapCat == g_uap->selectedUapCategory(cat))
{
button->setChecked(true);
}
}
if (m_radioButtonGroups[cat]->checkedButton() == nullptr)
{
m_radioButtonGroups[cat]->buttons().first()->setChecked(true);
}
}
m_scrollWidget->setStyleSheet("* {background:" + palette().color(QPalette::Base).name() + "}"); // set base color (usualy white) as background color
}
void SpecificationSelectDialog::accept()
{
foreach (const QButtonGroup* group, m_radioButtonGroups)
{
Q_ASSERT(group->checkedButton());
g_uap->selectUapCategory(m_radioButtonCategories[group->checkedButton()]);
}
QDialog::accept();
}
<file_sep>/specificationSelectDialog.h
#ifndef SPECIFICATIONSELECTDIALOG_H
#define SPECIFICATIONSELECTDIALOG_H
#include <QtWidgets>
namespace Ui {
class SpecificationSelectDialog;
}
class UapCategory;
class SpecificationSelectDialog : public QDialog
{
Q_OBJECT
public:
explicit SpecificationSelectDialog(QWidget *parent = 0);
~SpecificationSelectDialog();
void populateTable();
public slots:
virtual void accept() override;
private:
Ui::SpecificationSelectDialog *ui;
QWidget *m_scrollWidget;
QMap<int, QButtonGroup*> m_radioButtonGroups;
QMap<QAbstractButton*, const UapCategory*> m_radioButtonCategories;
};
#endif // SPECIFICATIONSELECTDIALOG_H
<file_sep>/asterixFileMapper.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef ASTERIXFILEMAPPER_H
#define ASTERIXFILEMAPPER_H
#include <QtCore>
class AsterixBlockInfo
{
public:
qint64 offset;
qint16 category;
quint16 size;
};
Q_DECLARE_METATYPE(AsterixBlockInfo);
Q_DECLARE_METATYPE(QList<AsterixBlockInfo>);
class AsterixFileMapper : public QThread
{
Q_OBJECT
public:
explicit AsterixFileMapper(QIODevice* file, QObject *parent = 0);
bool reachedEnd() const { return m_reachedEnd; }
signals:
void asterixBlock(const QList<AsterixBlockInfo> block);
void bytesScanned(qint64 pos);
void blocksScanned(qint64 pos);
public slots:
void stop() { m_stopRequested = true; }
void setOffset(qint64 ofs) { m_offset = ofs; }
protected:
virtual void run();
QIODevice* m_file;
quint64 m_offset;
bool m_reachedEnd;
bool m_stopRequested;
};
#endif // ASTERIXFILEMAPPER_H
<file_sep>/scaleExpressionParser.h
#ifndef SCALEEXPRESSIONPARSER_H
#define SCALEEXPRESSIONPARSER_H
#include <QtCore>
class ScaleExpressionParser
{
public:
ScaleExpressionParser();
static double parse(const QString& expression, bool& error);
static QString lastError;
};
#endif // SCALEEXPRESSIONPARSER_H
<file_sep>/TextHexDumpEdit.h
#ifndef TEXTEDIT_H
#define TEXTEDIT_H
#include <QWidget>
namespace Ui
{
class TextHexDumpEdit;
}
class TextHexDumpEdit : public QWidget
{
Q_OBJECT
public:
explicit TextHexDumpEdit(QWidget *parent = nullptr);
~TextHexDumpEdit();
signals:
void hexDumpLoaded(const QString &filename);
private slots:
void on_pushButton_clicked();
private:
Ui::TextHexDumpEdit *ui;
};
#endif // TEXTEDIT_H
<file_sep>/recordWidget.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef RECORDWIDGET_H
#define RECORDWIDGET_H
#include <QtWidgets>
#include "asterix.h"
class RecordWidget : public QWidget
{
Q_OBJECT
public:
explicit RecordWidget(QWidget *parent = 0);
void setRecord(const AsterixRecord* rec);
signals:
public slots:
protected:
QTextEdit* m_textEdit;
};
#endif // RECORDWIDGET_H
<file_sep>/unittests/asterix/asterix_unittest.cpp
#include "asterix_unittest.h"
Asterix_UnitTest::Asterix_UnitTest(QObject *parent) :
QObject(parent)
{
}
void Asterix_UnitTest::correctnessBitmask()
{
QVERIFY( BITMASK(0) == 0x00 );
QVERIFY( BITMASK(1) == 0x01 );
QVERIFY( BITMASK(2) == 0x03 );
QVERIFY( BITMASK(3) == 0x07 );
QVERIFY( BITMASK(6) == 0x3f );
QVERIFY( BITMASK(8) == 0xff );
QVERIFY( BITMASK(9) == 0x01ff );
QVERIFY( BITMASK(16) == 0xffff );
}
void Asterix_UnitTest::correctnessBittest()
{
for (int i = 0; i < 15; i++)
{
QVERIFY( BITTEST(0, i) == false );
}
for (int i = 0; i < 15; i++)
{
QVERIFY( BITTEST(0xffff, i) == true );
}
QVERIFY( BITTEST(0xcaffee, 4) == false );
QVERIFY( BITTEST(0xcaffee, 5) == true );
}
void Asterix_UnitTest::correctnessBitfield()
{
const uchar data[] = { 0x12, 0x34, 0x57, 0x79, 0xf2 };
Bitfield bf(data, sizeof(data));
for (int msb = sizeof(data)*8-1; msb >= 0; msb--)
{
for (int lsb = msb; lsb >= 0; lsb--)
{
QByteArray actual = bitfield(data, sizeof(data), msb, lsb);
QByteArray expected = bf.bitfield(msb, lsb).byteData();
QVERIFY2(actual == expected, qPrintable(QString("msb: %1 lsb:%2").arg(msb).arg(lsb)));
}
}
QByteArray data2;
for (int i = 0; i < 256; i++)
data2.append((uchar)i);
for (int i = 255; i >= 0; i--)
data2.append((uchar)i);
Bitfield bf2((uchar*)data2.data(), data2.length());
for (int msb = data2.length()*8-1; msb >= 0; msb--)
{
for (int lsb = msb; lsb >= 0; lsb--)
{
QByteArray actual = bitfield((uchar*)data2.data(), data2.length(), msb, lsb);
QByteArray expected = bf2.bitfield(msb, lsb).byteData();
QVERIFY2(actual == expected, qPrintable(QString("msb: %1 lsb:%2").arg(msb).arg(lsb)));
}
}
}
QTEST_MAIN(Asterix_UnitTest)
<file_sep>/hexedit.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef HEXEDIT_H
#define HEXEDIT_H
#include <QtWidgets>
class HexEdit : public QAbstractScrollArea
{
Q_OBJECT
public:
HexEdit(QWidget *parent = 0);
~HexEdit();
enum OffsetColumn { NONE, SIZE32, SIZE64 };
void setData( const uchar* data, quint64 size );
qint64 cursorPosition() const { return m_cursorPosition; }
int visibleLines() const;
virtual QSize sizeHint () const;
public Q_SLOTS:
void setHighlight( const uchar* start, qint64 size, bool ensureVisible = false );
void ensureHighlightVisible();
void setCursorPosition( const uchar* pos );
Q_SIGNALS:
void cursorPosition(qint64 pos);
void rescanRequested(qint64 ofs);
protected:
virtual void paintEvent( QPaintEvent * event );
virtual void resizeEvent( QResizeEvent * event );
virtual void scrollContentsBy ( int dx, int dy );
virtual void keyPressEvent( QKeyEvent* event );
virtual void mousePressEvent( QMouseEvent* event );
virtual void contextMenuEvent(QContextMenuEvent *);
void updateScrollbar();
void ensureCursorVisible();
QPair<int,int> calculateHexTextArea(const QString& hexStr, int start, int end) const;
QPair<int,int> calculateAsciiTextArea(const QString& asciiStr, int start, int end) const;
qint64 mousePosToOffset( const QPoint& pos ) const;
const uchar* m_data;
qint64 m_dataSize;
qint64 m_cursorPosition;
const uchar* m_highlightStartAdr; // byte offset
qint64 m_highlightSize; // bytes
int m_lineCount;
OffsetColumn m_offsetColumnMode;
QSize m_sizeHint;
};
#endif
<file_sep>/scaleExpressionParser.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "scaleExpressionParser.h"
extern double parseScaleExpression(const QString& expression, bool& error);
QString ScaleExpressionParser::lastError;
ScaleExpressionParser::ScaleExpressionParser()
{
}
double ScaleExpressionParser::parse(const QString &expression, bool& error)
{
return ::parseScaleExpression(expression, error);
}
<file_sep>/unittests/asterix/asterix_unittest.h
#ifndef ASTERIX_UNITTEST_H
#define ASTERIX_UNITTEST_H
#include <QtCore>
#include <QtTest/QtTest>
#include "asterix.h"
#include "bit.h"
class Bitfield : public QByteArray
{
public:
Bitfield(const uchar* data, int len) {
for (int i = 0; i < len; i++)
{
for (int j = 7; j >= 0; j--)
{
append(BITTEST(data[i], j) ? 1 : 0);
}
}
Q_ASSERT(length()/8 == len);
}
int numBytes() const { return length()/8; }
QByteArray byteData() const {
QByteArray ret;
for (int i = 0; i < numBytes(); i++)
{
uchar b = 0;
for (int j = 0; j < 8; j++)
{
if (at(i*8+j) > 0)
BITSET(b, 7-j);
}
ret.append(b);
}
return ret;
}
Bitfield bitfield(int msb, int lsb) const {
QByteArray a(mid(length()-msb-1, msb-lsb+1));
return Bitfield(a);
}
private:
Bitfield(const QByteArray& bitfield) : QByteArray(bitfield) {
if (bitfield.length() == 0 || bitfield.length()%8 > 0)
prepend(QByteArray(8-(bitfield.length()%8), 0));
}
};
class Asterix_UnitTest : public QObject
{
Q_OBJECT
public:
Asterix_UnitTest(QObject* parent = 0);
private slots:
void correctnessBitmask();
void correctnessBittest();
void correctnessBitfield();
};
#endif
<file_sep>/asterixReportGenerator.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2016 <NAME> (<EMAIL>)
*/
#ifndef ASTERIXREPORTGENERATOR_H
#define ASTERIXREPORTGENERATOR_H
#include <QtCore>
#include <QTextStream>
#include "asterix.h"
class AbstractGenerator;
class AsterixReportGenerator : public QObject
{
Q_OBJECT
public:
explicit AsterixReportGenerator( QObject *parent = 0 );
enum Type {
XML,
};
void createReport(QTextStream& output, Type type);
void handleBlock(AbstractGenerator* gen, const AsterixBlock& block);
protected:
void createBlockReport( const AsterixBlock& block, QTextStream& out );
void createRecordReport( const AsterixRecord& record, QTextStream& out );
void createDataItemReport(const AsterixDataItem &dataItem, QTextStream &out);
void applyUnitAndScale(const UapField &uapField, int value, QTextStream &out);
};
class AbstractGenerator
{
public:
struct Field {
QString value;
QString unit;
qint64 rawval;
bool hasraw;
};
AbstractGenerator(QTextStream& out) : m_stream(out), m_indention(4) {}
virtual ~AbstractGenerator() {}
virtual void startBlock(const AsterixBlock& block) = 0;
virtual void finishBlock(const AsterixBlock& block) = 0;
virtual void startRecordsSection(const AsterixBlock& /*block*/) {}
virtual void finishRecordsSection(const AsterixBlock& /*block*/) {}
virtual void startRecord(const AsterixRecord& record) = 0;
virtual void finishRecord(const AsterixRecord& record) = 0;
virtual void startDataItemsSection(const AsterixRecord& /*record*/, int /*indent*/ = 0) {}
virtual void startDataItem(const AsterixDataItem& dataItem, const UapDataItem& uap, int indent = 0) = 0;
virtual void finishDataItem(const AsterixDataItem& dataItem, const UapDataItem& uap, int indent = 0) = 0;
virtual void finishDataItemsSection(const AsterixRecord& /*record*/, int /*indent*/ = 0) {}
virtual void startFinishField(const AsterixDataItem& dataItem, const UapField& uap, int indent = 0) = 0;
static Field decodeField(const AsterixDataItem& dataItem, const UapField& uapField);
static Field unitAndScale(const UapField &uapField, qint64 rawvalue);
protected:
QTextStream& ind(int level) const { m_stream << QString(level * m_indention, ' '); return m_stream; } // indent line
QTextStream& m_stream;
int m_indention;
};
class XmlGenerator : public AbstractGenerator
{
public:
XmlGenerator(QTextStream& out) : AbstractGenerator(out) { m_stream << "<report>" << endl; }
~XmlGenerator() { m_stream << "</report>" << endl; }
void startBlock(const AsterixBlock& block) override;
void finishBlock(const AsterixBlock& block) override;
void startRecord(const AsterixRecord& record) override;
void finishRecord(const AsterixRecord& record) override;
void startDataItem(const AsterixDataItem& dataItem, const UapDataItem& uap, int indent = 0) override;
void finishDataItem(const AsterixDataItem& dataItem, const UapDataItem& uap, int indent = 0) override;
void startFinishField(const AsterixDataItem& dataItem, const UapField& uap, int indent = 0) override;
static QString wrapInCData(const QString& s);
};
#endif // ASTERIXREPORTGENERATOR_H
<file_sep>/main.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include <QtWidgets>
#include <iostream>
#include <getopt.h>
#include <locale.h>
#include "global.h"
#include "mainWindow.h"
#include <map>
void printUsage( const QString& appname )
{
std::cout << "Usage: " << appname.toStdString() << " [OPTIONS] [ASTERIXFILE]" << std::endl;
std::cout << "OPTIONS:" << std::endl;
std::cout << " -h Print this text" << std::endl;
std::cout << " --specs DIRECTORY Add specifications from DIRECTORY" << std::endl;
// std::cout << " -V Print version and exit" << std::endl;
std::cout << std::endl;
}
void processCommandLine( int argc, char** argv )
{
const char* optstring = "h?";
int option_index;
int c;
// extern char* optarg;
extern int optind;
static struct option long_options[] = {
{"specs", required_argument, 0, 0},
{0, 0, 0, 0}
};
while(1) {
if ((c = getopt_long( argc, argv, optstring, long_options, &option_index )) == -1)
break; // no more recognized options
switch (c) {
case 0: // longoption
{
if (option_index == 0)
{
g_specsDirectory = QString::fromUtf8(optarg);
}
}
break;
case 'h':
case '?':
printUsage( argv[0] );
exit( 0 );
break;
case 'V':
exit( 0 );
break;
default:
break;
}
}
// options left over?
if (optind < argc) {
g_openFileName = argv[optind++];
if (optind < argc) {
printUsage( argv[0] );
exit( 1 );
}
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QApplication::setApplicationName("asterixInspector");
processCommandLine(argc, argv);
// UAP parser uses sscanf() to parse floats. Force sane locale.
setlocale(LC_NUMERIC, "C");
MainWindow w;
w.show();
return app.exec();
}
<file_sep>/dataItemWidget.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef DATAITEMWIDGET_H
#define DATAITEMWIDGET_H
#include <QtGui>
#include <QtWebEngineWidgets>
#include "asterix.h"
class DataItemWidget : public QWidget
{
Q_OBJECT
public:
explicit DataItemWidget(QWidget *parent = 0);
void setDataItem(const AsterixBlock* block, const AsterixRecord* record, const AsterixDataItem* dataItem);
signals:
public slots:
void clear() { m_webView->setContent(QByteArray()); }
static QString printEnumeration(const UapField& uapField, int value);
static QString applyUnitAndScale(const UapField& uapField, int value);
protected:
QString renderBitTable(const AsterixDataItem& dataItem, const UapField& uapField) const;
QSize sizeHint() const { return QSize(100, 300); }
QString m_css;
QWebEngineView* m_webView;
};
#endif // DATAITEMWIDGET_H
<file_sep>/dataItemWidget.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "dataItemWidget.h"
#include "uap.h"
#include "global.h"
extern Uap* g_uap;
DataItemWidget::DataItemWidget(QWidget *parent) :
QWidget(parent)
{
QVBoxLayout* vbox = new QVBoxLayout;
setLayout(vbox);
QFile cssFile(":/dataItem.css");
if (not cssFile.open(QIODevice::ReadOnly))
qFatal("CSS not found.");
m_css = cssFile.readAll();
m_webView = new QWebEngineView(0);
m_webView->settings()->setFontFamily(QWebEngineSettings::StandardFont, QFont().family());
m_webView->settings()->setFontSize(QWebEngineSettings::DefaultFontSize, QFont().pointSize() * 1.4);
m_webView->setMinimumSize(100, 88);
m_webView->resize(100, 88);
layout()->addWidget(m_webView);
}
void DataItemWidget::setDataItem(const AsterixBlock* block, const AsterixRecord* record, const AsterixDataItem *dataItem)
{
if (block == 0)
return;
if (g_uap->selectedUapCategory(block->category()))
{
const UapDataItem& uapDataItem = *dataItem->uapDataItem();
const int ofs = uapDataItem.format() == UapDataItem::REPETIVE ? 1 : 0;
QString html;
html += "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en_US\" lang=\"en_US\">";
html += "<head>";
html += "<style type=\"text/css\"><!--";
html += m_css;
html += "--></style></head>";
html += "<body>";
html += "<h3>" + uapDataItem.id() + " " + uapDataItem.name() + "</h3>";
if (not uapDataItem.definition().isEmpty())
html += "<p>Definition: " + uapDataItem.definition() + "</p>";
html += "<p><table border=\"0\" style=\"margin-left:26px\">";
foreach (const UapField& uapField, uapDataItem.m_fields)
{
if (not uapDataItem.fieldPresent(dataItem->data(), uapField))
continue;
html += "<tr><td style=\"border-top:10px solid transparent;\" colspan=\"3\">" + renderBitTable(*dataItem, uapField) + "</td></tr>";
html += "<tr>";
html += "<td style=\"vertical-align:top;\">" + (uapField.name().isEmpty() ? "<i>nn</i>" : uapField.name()) + "</td>";
html += "<td style=\"vertical-align:top; padding-left:6px; padding-right:6px\"><u>";
const int correctedLength = uapDataItem.format() == UapDataItem::VARIABLE ? 1 : uapDataItem.length();
QByteArray field = dataItem->bitfield(uapField.octed() + ofs, correctedLength, uapField.msb()-1, uapField.lsb()-1);
int value = 0;
switch (uapField.format())
{
case UapField::ICAO6STR:
{
QString s = AsterixDataItem::decodeIcaoStr((const uchar*)field.constData());
html += "\"" + s.replace(' ', " ") + "\"";
}
break;
case UapField::UINTEGER:
{
value = bitfieldToUInt(field);
html += QString("%1").arg(value) + "</u>";
html += " (<u>" + applyUnitAndScale(uapField, value) + "</u>)<u>";
}
break;
case UapField::INTEGER:
{
value = bitfieldToInt(field, uapField.msb()-1 - (((uapField.lsb()-1)/8)*8) );
html += QString("%1").arg(value) + "</u>";
html += " (<u>" + applyUnitAndScale(uapField, value) + "</u>)<u>";
}
break;
case UapField::OCTAL:
{
value = bitfieldToUInt(field);
html += QString("0%1").arg(value, 0, 8);
}
break;
case UapField::ASCII:
{
QString s = QString::fromLatin1(field);
s.replace(" ", " ");
html += "\"" + s + "\"";
}
break;
case UapField::HEX:
default:
{
value = bitfieldToUInt(field);
html += "0x";
for (int i=0; i < field.size(); i++)
html += QString("%1").arg((uint)((uchar)field[i]), 2, 16, QChar('0'));
}
break;
}
// line += dataItem->decode(uapField.m_octed, uapField.msb(), uapField.lsb());
html += "</u></td>";
html += "<td style=\"vertical-align:top; padding:0;\">";
if (not uapField.desc().isEmpty())
html += uapField.desc();
html += printEnumeration(uapField, value);
html += "</td></tr>";
}
html += "</table></p>";
if (not uapDataItem.description().isEmpty())
html += "<p>" + uapDataItem.description() + "</p>";
html += "</body></html>";
m_webView->setHtml(html);
}
}
QString DataItemWidget::printEnumeration(const UapField& uapField, int value)
{
QString html = "<table border=\"0\">";
for (QMap<int, UapEnum>::const_iterator it = uapField.enums().begin(); it != uapField.enums().end(); ++it)
{
html += "<tr><td>= " + QString::number(it.key()) + "</td><td>";
if (it.key() == value)
html+= "<u>";
html += it.value().m_desc;
if (it.key() == value)
html+= "</u>";
html += "</td></tr>";
}
html += "</table>";
return html;
}
QString DataItemWidget::applyUnitAndScale(const UapField& uapField, int value)
{
QString html;
if (uapField.unit() != UapField::UNDEFINED)
{
html += QString::number((double)value * uapField.scale()) + " " + uapField.unitStr(uapField.unit());
}
return html;
}
QString DataItemWidget::renderBitTable(const AsterixDataItem &dataItem, const UapField& uapField) const
{
const UapDataItem uapDataItem = *dataItem.uapDataItem();
const int correctedLength = uapDataItem.format() == UapDataItem::VARIABLE ? 1 : uapDataItem.length();
const int ofs = uapDataItem.format() == UapDataItem::REPETIVE ? 1 : 0;
const int lsb = uapField.lsb()-1;
const int msb = uapField.msb()-1;
const int lByte = uapField.octed()-1 + ofs + correctedLength-1 - lsb/8; // offset of least sig byte
const int mByte = uapField.octed()-1 + ofs + correctedLength-1 - msb/8; // offset of most sig byte
const QString title = QString("Bits-%1/%2").arg(msb+1).arg(lsb+1);
QString s = "<table border=\"0\" cellspacing=\"0\" class=\"bittable\" title=\"" + title + "\">";
s += "<tr>";
for (int byte = mByte; byte <= lByte; byte++)
{
QString byteHex = QString("%1").arg((uint)dataItem.data()[byte], 2, 16, QChar('0')).toUpper();
s += "<td colspan=\"4\" align=\"center\" bgcolor=\"" + g_highlightColor.name() + "\">" + byteHex[0] + "</td>";
s += "<td colspan=\"4\" align=\"center\" bgcolor=\"" + g_highlightColor.name() + "\">" + byteHex[1] + "</td>";
if (byte != lByte)
{
s += "<td style=\"padding-left:4px;\"></td>";
}
}
s += "</tr>";
s += "<tr>";
for (int byte = mByte; byte <= lByte; byte++)
{
QString byteBin = QString("%1").arg((uint)dataItem.data()[byte], 8, 2, QChar('0'));
bool inside = true;
for (int b = 0; b < 8; b++)
{
const int bitpos = (correctedLength-byte+ofs+(uapField.octed()-1))*8-b-1;
if (bitpos == msb && bitpos == lsb)
s += "<td class=\"both\">" + byteBin[b] + "</td>";
else if (bitpos == msb && bitpos > lsb)
s += "<td class=\"left\">" + byteBin[b] + "</td>";
else if (bitpos < msb && bitpos > lsb)
s += "<td class=\"mid\">" + byteBin[b] + "</td>";
else if (bitpos < msb && bitpos == lsb)
{
s += "<td class=\"right\">" + byteBin[b] + "</td>";
inside = false;
}
else
s += "<td class=\"node\">" + byteBin[b] + "</td>";
}
if (byte != lByte)
{
if (inside)
s += "<td class=\"mid\"></td>";
else
s += "<td style=\"padding-bottom:0;\" ></td>";
}
}
s += "</tr>";
s += "</table>";
return s;
}
<file_sep>/asterix.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2014 <NAME> (<EMAIL>)
*/
#include "asterix.h"
#include "global.h"
AsterixBlock::AsterixBlock(const uchar* data, const Uap& uap) :
m_data(data)
{
if (not uap.m_categories.contains( category() ))
{
logError("Cat " + QString::number(category()) + " is undefined");
return; // undefined cat
}
const UapCategory* uapCat = uap.selectedUapCategory(category());
const uchar* p = m_data + 3;
int recordIndex = 0;
while (p < m_data + length())
{
AsterixRecord record(p, recordIndex++, uapCat);
if (record.length() < 1)
{
logError("invalid record");
return;
}
m_records.append(record);
p += record.length();
}
}
/** count number of extended octeds at p
**/
int AsterixBlock::countExtends(const uchar *p)
{
const uchar* ep = p;
while (*ep & 0x1)
ep++;
return ep - p;
}
// extracts field-reference-numbers (FRNs) from FSPEC (multi)byte section
QList<int> AsterixBlock::decodeFspecSection(const uchar *p, int size)
{
QList<int> ret;
for (int fspecIdx = 0; fspecIdx < size; fspecIdx++) // iterate over fspec bytes
{
for (int b = 7; b > 0; b--) // iterate over bits from left/msb to right/lsb of fspec byte
{
if (BITTEST(p[fspecIdx], b))
{
// bit at position b is set. this yields a FRN
int frn = (fspecIdx * 7) + (8-b);
ret.append(frn);
}
}
}
return ret;
}
AsterixRecord::AsterixRecord(const uchar *data, int blockIndex, const UapCategory* uapCat) :
m_data(data),
m_index(blockIndex)
{
int numFspec = 1 + AsterixBlock::countExtends(m_data); // get number of fspec bytes
QList<int> frns = AsterixBlock::decodeFspecSection(m_data, numFspec);
const uchar* dataItemPtr = data + numFspec;
foreach (int frn, frns)
{
if (not uapCat->m_dataItems.contains(frn))
{
logError("FRN " + QString::number(frn) + " is undefined");
m_length = -1; // mark this record as invalid
return; // undefined frn
}
const UapDataItem* uapItem = uapCat->m_dataItems[frn];
AsterixDataItem dataItem(dataItemPtr, uapItem);
m_fields.append(dataItem);
if (frn == uapCat->timeOfDayFrn() && !uapItem->m_fields.empty()) // Time-of-Day field is comming along
{
const UapField& uapField = uapItem->m_fields.first();
// some checks if it actualy contains a time entry
if (dataItem.length() >= 2 && uapField.format() == UapField::UINTEGER)
{
const int value = bitfieldToUInt(dataItem.bitfield(uapField.octed(), dataItem.length(), uapField.msb()-1, uapField.lsb()-1));
m_timeOfDay = QTime::fromMSecsSinceStartOfDay((1000.0*value)/128.0);
}
}
dataItemPtr += dataItem.length(); // advance to start of next dataitem
}
m_length = dataItemPtr - m_data;
}
AsterixDataItem::AsterixDataItem(const uchar *data, const UapDataItem *uapDataItem) :
m_data(data),
m_uapDataItem(uapDataItem)
{
if (m_uapDataItem->format() == UapDataItem::COMPOUND)
{
int numFspec = 1 + AsterixBlock::countExtends(m_data); // get number of fspec bytes
QList<int> frns = AsterixBlock::decodeFspecSection(m_data, numFspec);
const uchar* dataItemPtr = m_data + numFspec;
foreach (int frn, frns)
{
if (not uapDataItem->m_subFields.contains(frn))
{
logError("Subfield FRN " + QString::number(frn) + " is undefined");
m_length = -1; // mark this record as invalid
return; // undefined frn
}
const UapDataItem* uapItem = uapDataItem->m_subFields[frn];
AsterixDataItem dataItem(dataItemPtr, uapItem);
m_subfields.append(dataItem);
dataItemPtr += dataItem.length(); // advance to start of next dataitem
}
m_length = dataItemPtr - m_data;
}
else
{
m_length = uapDataItem->calcLength(m_data);
}
}
/** decode a character from ICAO 6bit presentation to ascii/QChar
**/
QChar AsterixDataItem::decodeIcaoSixBitChar(int c)
{
c &= BITMASK(6);
if (c >= 1 && c <= 26) // 1..26 => 'A'..'Z'
{
return 'A' + c-1;
}
else if (c == 32) // 32 => space
{
return ' ';
}
else if (c >= 48 && c <= 57) // 48..57 => '0'..'9'
{
return '0' + c-48;
}
else
{
return QChar::ReplacementCharacter;
}
}
/** decode ICAO 6bit 8 character string located in 6 bytes at 'p'
**/
QString AsterixDataItem::decodeIcaoStr(const uchar* p)
{
QByteArray buffer(8, 0); // a buffer of 8 bytes, set to 0
buffer.replace(2, 6, (const char*)p); // align *p to end of buffer
quint64 s = qFromBigEndian<quint64>((const uchar*)buffer.constData()); // and convert buffer into 64bit machine word
QString ret;
for (int b = 42; b >= 0; b -= 6) // first char at bit pos 42, second at 36 ... last at 0
{
ret += decodeIcaoSixBitChar(s >> b);
}
return ret;
}
/** Extract arbitrary bitfield (i.e. memory section on bit precision).
** Extract from multiple octeds starting at 'o' (counting from 1) and length l
** with bit index 0 at o+l.
** Resulting Bytearray is right-justified and 0-padded on left side.
**/
QByteArray AsterixDataItem::bitfield(int o, int l, int msb, int lsb) const
{
return ::bitfield(this->m_data + o - 1, l, msb, lsb);
}
<file_sep>/global.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "global.h"
#include <QColor>
QMainWindow* g_mainWindow = 0;
QString g_specsDirectory;
QString g_openFileName;
const uchar* g_file = 0;
qint64 g_fileSize = 0;
QLabel* g_blockCountLabel = 0;
AsterixModel* g_asterixModel = 0;
Uap* g_uap = 0;
QColor g_highlightColor = QColor( 225, 235, 250 );
Logger* g_logger;
void logInfo(const QString &msg)
{
g_logger->log(Logger::Type::INFO, msg);
qDebug() << msg;
}
void logWarn(const QString &msg)
{
g_logger->log(Logger::Type::WARN, msg);
qWarning(qPrintable(msg));
}
void logError(const QString &msg)
{
g_logger->log(Logger::Type::ERROR, msg);
qWarning(qPrintable(msg));
}
<file_sep>/mainWindow.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "mainWindow.h"
#include "ui_mainWindow.h"
#include "global.h"
#include "uap.h"
#include "asterixReportGenerator.h"
#include "specificationSelectDialog.h"
#include "scaleExpressionParser.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
m_mapper = 0;
m_currentBlock = 0;
m_blockModel = 0;
m_recordModel = 0;
m_currentBlockIndex = -1;
g_mainWindow = this;
g_logger = new Logger(this);
ui->setupUi(this);
connect(ui->actionOpenFile, SIGNAL(triggered()), this, SLOT(openFile()));
connect(ui->actionGenerateXmlReport, &QAction::triggered, this, &MainWindow::generateXmlReport);
connect(ui->actionSpecificationSelection, SIGNAL(triggered()), this, SLOT(showSpecificationSelectionDialog()));
connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAboutDialog()));
connect(ui->actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
m_blockCountLabel = new QLabel;
g_blockCountLabel = m_blockCountLabel;
m_blockCountLabel->setText( "Blocks: " );
statusBar()->addPermanentWidget( m_blockCountLabel );
m_cursorPosLabel = new QLabel;
m_cursorPosLabel->setText( "Cursor Pos: " );
statusBar()->addPermanentWidget( m_cursorPosLabel );
createDockWidgets();
g_uap = new Uap;
// collect directories to scan for specification files
QStringList specDirectories;
if (QFileInfo("asterixSpecification").isDir())
{
specDirectories << "asterixSpecification";
}
#ifdef __linux__
if (QFileInfo("/usr/share/asterixInspector/asterixSpecification").isDir())
{
specDirectories << "/usr/share/asterixInspector/asterixSpecification";
}
if (QFileInfo(QDir::homePath()+"/opt/asterixInspector/share/asterixSpecification").isDir())
{
specDirectories << QDir::homePath()+"/opt/asterixInspector/share/asterixSpecification";
}
#endif
if (not g_specsDirectory.isEmpty())
{
specDirectories << g_specsDirectory;
}
for (const QString& dir : specDirectories)
{
g_uap->readXml(dir);
}
if (g_uap->m_categories.isEmpty())
{
logWarn("No specification xml files found. Check directory 'asterixSpecification/'.");
}
if (not g_openFileName.isEmpty())
{
readFile(g_openFileName);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::createDockWidgets()
{
QDockWidget* hexDock = new QDockWidget("Hex");
m_hexEdit = new HexEdit(this);
connect(m_hexEdit, SIGNAL(rescanRequested(qint64)), this, SLOT(mapFile(qint64)));
connect(m_hexEdit, SIGNAL(cursorPosition(qint64)), this, SLOT(hexCursorPosChanged(qint64)));
hexDock->setWidget(m_hexEdit);
addDockWidget(Qt::RightDockWidgetArea, hexDock);
QDockWidget* hexDumpLoadDock = new QDockWidget("Hex dump to load data from");
m_hexDumpLoadEdit = new TextHexDumpEdit(this);
hexDumpLoadDock->setWidget(m_hexDumpLoadEdit);
addDockWidget(Qt::RightDockWidgetArea, hexDumpLoadDock);
connect(m_hexDumpLoadEdit, &TextHexDumpEdit::hexDumpLoaded, this, &MainWindow::readFile);
m_detailDock = new QDockWidget("Data Item");
m_dataItemWidget = new DataItemWidget(this);
m_detailDock->setWidget(m_dataItemWidget);
addDockWidget(Qt::RightDockWidgetArea, m_detailDock);
m_recordWidget = new RecordWidget(0);
QDockWidget* logDock = new QDockWidget("Log");
logDock->setWidget(g_logger->textWidget());
addDockWidget(Qt::BottomDockWidgetArea, logDock);
}
void MainWindow::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this, "Choose Asterix File");
if (not fileName.isEmpty())
{
readFile(fileName);
}
}
void MainWindow::showSpecificationSelectionDialog()
{
SpecificationSelectDialog* dialog = new SpecificationSelectDialog(this);
dialog->exec();
}
void MainWindow::readFile(const QString &filename)
{
m_file.close();
m_file.setFileName(filename);
if (not m_file.open(QIODevice::ReadOnly))
return;
setWindowTitle(filename + " - AsterixInspector");
g_file = m_file.map(0, m_file.size());
g_fileSize = m_file.size();
ui->m_fieldTable->setModel(0);
ui->m_recordTable->setModel(0);
m_dataItemWidget->setDataItem(0, 0, 0);
m_recordWidget->setRecord(0);
m_hexEdit->setData(g_file, g_fileSize);
m_hexEdit->setCursorPosition(g_file);
m_dataItemWidget->clear();
mapFile(0);
}
void MainWindow::mapFile(qint64 ofs)
{
ui->m_blockTable->setModel(0);
delete g_asterixModel;
delete m_blockModel;
m_blockModel = 0;
delete m_recordModel;
m_recordModel = 0;
m_currentBlockIndex = -1;
m_hexEdit->setHighlight( 0, 0 );
g_asterixModel = new AsterixModel;
ui->m_blockTable->setModel(g_asterixModel);
connect(ui->m_blockTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(blockClicked(QModelIndex)));
if (m_mapper)
{
m_mapper->stop();
m_mapper->wait();
}
delete m_mapper;
m_mapper = new AsterixFileMapper(&m_file);
m_mapper->setOffset(ofs);
g_asterixModel->reserve(qMax(100LL, (g_fileSize - ofs)/250));
connect(m_mapper, SIGNAL(asterixBlock(QList<AsterixBlockInfo>)), g_asterixModel, SLOT(asterixBlock(QList<AsterixBlockInfo>)));
connect(m_mapper, SIGNAL(blocksScanned(qint64)), g_asterixModel, SLOT(blocksScanned(qint64)));
connect(m_mapper, SIGNAL(finished()), g_asterixModel, SLOT(squeeze()));
m_mapper->start();
}
/** a asterix block has been selected in block-table
**/
void MainWindow::blockClicked(const QModelIndex &index)
{
if (index.row() != m_currentBlockIndex)
{
const AsterixBlockInfo blockInfo = g_asterixModel->blockInfo(index);
m_currentBlockIndex = index.row();
delete m_currentBlock;
m_currentBlock = new AsterixBlock(g_file + blockInfo.offset, *g_uap);
AsterixBlockModel* model = new AsterixBlockModel(g_file, *m_currentBlock, this);
ui->m_recordTable->setModel(model);
ui->m_fieldTable->setModel(0);
m_dataItemWidget->setDataItem(0, 0, 0);
m_recordWidget->setRecord(0);
connect(ui->m_recordTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(recordClicked(QModelIndex)));
delete m_blockModel;
m_blockModel = model;
}
m_hexEdit->setHighlight(m_currentBlock->data(), m_currentBlock->length(), true);
m_hexEdit->setCursorPosition(m_currentBlock->data());
}
/** a block record has been selected in record-table
**/
void MainWindow::recordClicked(const QModelIndex &index)
{
m_currentRecord = &m_currentBlock->record(index.row());
AsterixRecordModel* model = new AsterixRecordModel(g_file, *m_currentRecord, this);
ui->m_fieldTable->setModel(model);
m_dataItemWidget->setDataItem(0, 0, 0);
connect(ui->m_fieldTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(fieldClicked(QModelIndex)));
delete m_recordModel;
m_recordModel = model;
m_hexEdit->setHighlight(m_currentRecord->data(), m_currentRecord->length(), true);
m_hexEdit->setCursorPosition(m_currentRecord->data());
m_detailDock->setWidget(m_recordWidget);
m_detailDock->setWindowTitle("Record");
m_recordWidget->setRecord(m_currentRecord);
}
void MainWindow::fieldClicked(const QModelIndex &index)
{
m_currentDataItem = &m_recordModel->dataItemAtRow(index.row());
m_hexEdit->setHighlight(m_currentDataItem->data(), m_currentDataItem->length(), true);
m_hexEdit->setCursorPosition(m_currentDataItem->data());
m_detailDock->setWidget(m_dataItemWidget);
m_detailDock->setWindowTitle("Data Item");
m_dataItemWidget->setDataItem(m_currentBlock, m_currentRecord, m_currentDataItem);
}
void MainWindow::hexCursorPosChanged(qint64 pos)
{
m_cursorPosLabel->setText( QString("Cursor Pos: 0x%1").arg(pos, 0, 16) );
}
void MainWindow::generateXmlReport()
{
QString fileName = QFileDialog::getSaveFileName(this, "Specify output file");
if (fileName.isEmpty())
return;
QFile file(fileName);
if (not file.open( QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this, "Error", "Unable to open '" + fileName + "' for writing.");
return;
}
QTextStream out(&file);
AsterixReportGenerator reportGenerator;
reportGenerator.createReport(out, AsterixReportGenerator::XML);
}
void MainWindow::showAboutDialog()
{
const QString text = "<h3>AsterixInspector 0.12.3</h3>"
"displays contents of files in <a href=\"http://www.eurocontrol.int/asterix/\">Eurocontrol Asterix</a> format."
"<p>Written by <NAME> and licensed under BSD license (see below)</p>"
"<p>Report bugs and suggestions to <EMAIL>.</p>"
"<p><pre>Copyright (c) 2018, <NAME>. All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are met:\n"
" * Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
" * Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
" * Neither the name of the copyright holder nor the\n"
" names of its contributors may be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n"
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n"
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n"
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY\n"
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n"
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n"
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n"
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"</pre></p>";
QMessageBox::about(this, "About AsterixInspector", text);
}
<file_sep>/hexedit.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "hexedit.h"
#include "global.h"
const int H_MARGIN = 4;
template <typename T>
constexpr inline bool within(const T& value, const T& left, const T& right) { return left <= value && value < right; }
HexEdit::HexEdit(QWidget *parent)
: QAbstractScrollArea(parent),
m_data(0),
m_offsetColumnMode( SIZE32 )
{
setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
setFocusPolicy(Qt::StrongFocus); // accept mouse and tab focus
QFont myfont = QFontDatabase::systemFont(QFontDatabase::FixedFont); // ( "monospace" )
myfont.setStyleHint(QFont::TypeWriter);
myfont.setKerning(false);
myfont.setFixedPitch(true);
setFont( myfont );
setMouseTracking(true);
switch (m_offsetColumnMode)
{
case SIZE32:
m_sizeHint = fontMetrics().boundingRect( " 01234567: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0123456789abcdef " ).size();
break;
case SIZE64:
m_sizeHint = fontMetrics().boundingRect( " 0123456789abcdef: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0123456789abcdef " ).size();
break;
default:
m_sizeHint = fontMetrics().boundingRect( " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0123456789abcdef " ).size();
break;
}
m_sizeHint.rwidth() += (2 * H_MARGIN) + (2*frameWidth()) + verticalScrollBar()->sizeHint().width();
m_sizeHint.rheight() = (fontMetrics().lineSpacing() * 16) + (2*frameWidth()); // extend to 16 lines
setMinimumHeight( fontMetrics().lineSpacing() * 4 + (2*frameWidth()) );
setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Expanding );
m_cursorPosition = 0;
}
HexEdit::~HexEdit()
{
}
void HexEdit::setData(const uchar * data, quint64 size)
{
m_data = data;
m_dataSize = size;
m_lineCount = m_dataSize / 16;
if (m_dataSize % 16 != 0)
m_lineCount++;
verticalScrollBar()->setValue( 0 );
updateScrollbar();
setHighlight( 0, 0 );
m_cursorPosition = 0;
emit cursorPosition( m_cursorPosition );
}
void HexEdit::paintEvent(QPaintEvent * event)
{
if (m_data == 0)
{
return;
}
QPainter painter( viewport() );
const int cw = fontMetrics().width( '0' );
const int ch = fontMetrics().height() - fontMetrics().descent() + 1;
int hexX = H_MARGIN;
if (m_offsetColumnMode == SIZE32)
hexX = H_MARGIN + (8 + 2) * cw;
else if (m_offsetColumnMode == SIZE64)
hexX = H_MARGIN + (16 + 2) * cw;
int asciiX = hexX + H_MARGIN + 16*3*cw + 5*cw;
/*
* draw fileoffset background rect
*/
painter.save();
painter.setBrush( QBrush( QColor( 230, 230, 230 ) ) );
painter.setPen( Qt::NoPen );
painter.drawRect( 0, event->rect().top(), hexX-cw, event->rect().bottom() );
painter.restore();
const int linesVisible = viewport()->height() / fontMetrics().lineSpacing();
int firstToBeUpdatedLine = qMax(event->rect().top() / fontMetrics().lineSpacing() - 1, 0);
int lastToBeUpdatedLine = qMax(event->rect().bottom() / fontMetrics().lineSpacing() + 1, linesVisible);
const uchar* firstLineAddress = m_data + (verticalScrollBar()->value() * 16); // address of first visible line
// handle line by line
for ( int i = firstToBeUpdatedLine; i < lastToBeUpdatedLine; i++ )
{
const uchar* lineAddress = firstLineAddress + i*16; // address of first byte in line
int bytesInLine = 16; // a complete line has 16 bytes, the very last line has [1..16]
if (verticalScrollBar()->value() + i + 1 == m_lineCount)
{
// this is the last line
bytesInLine = m_dataSize % 16;
if (bytesInLine == 0)
bytesInLine = 16;
}
else if (verticalScrollBar()->value() + i + 1 > m_lineCount)
{
bytesInLine = 0;
}
/*
* build hex and ascii columns
*/
QString hexColumn;
QString asciiColumn;
for ( int o = 0; o < 16; o++ )
{
if (o < bytesInLine)
{
quint8 b = *(lineAddress + o);
QString bs = QString("%1").arg((b), 2, 16, QChar('0'));
hexColumn += bs;
if(o != bytesInLine-1)
hexColumn += ' ';
QChar c( b );
if (c.isPrint())
asciiColumn += b;
else
asciiColumn += QChar(0x00b7); // QChar(QChar::ReplacementCharacter);
}
else
{
hexColumn += " ";
asciiColumn += " ";
}
if (o % 4 == 3)
hexColumn += " ";
}
int textBaseLineY = ((i+1) * fontMetrics().lineSpacing()) - fontMetrics().leading() - 3;
/*
* if this is a highlighted line, draw background
*/
QRect highlightHex(-1, textBaseLineY+2, 0, -ch);
QRect highlightAscii(-1, textBaseLineY+2, 0, -ch);
// check for overlap with highlight region
if (within(m_highlightStartAdr, lineAddress, lineAddress + 16) ||
within(m_highlightStartAdr + m_highlightSize, lineAddress, lineAddress + 16) ||
(m_highlightStartAdr <= lineAddress && m_highlightStartAdr + m_highlightSize >= lineAddress + 16))
{
const QPair<int,int> hexpx = calculateHexTextArea(hexColumn, m_highlightStartAdr - lineAddress, m_highlightStartAdr + m_highlightSize - lineAddress);
highlightHex.setLeft(hexX + hexpx.first);
highlightHex.setRight(hexX + hexpx.second);
const QPair<int,int> asciipx = calculateAsciiTextArea(asciiColumn, m_highlightStartAdr - lineAddress, m_highlightStartAdr + m_highlightSize - lineAddress);
highlightAscii.setLeft(asciiX + asciipx.first);
highlightAscii.setRight(asciiX + asciipx.second);
painter.save();
painter.setPen( Qt::NoPen );
painter.setBrush( g_highlightColor );
painter.drawRect( highlightHex );
painter.drawRect( highlightAscii );
painter.restore();
}
/*
* if the cursor positioned in this line, draw it
*/
if (m_cursorPosition / 16 == verticalScrollBar()->value() + i)
{
const int cursorLineOffset = m_cursorPosition % 16;
QPair<int,int> hex_px = calculateHexTextArea(hexColumn, cursorLineOffset, cursorLineOffset+1);
QPair<int,int> ascii_px = calculateAsciiTextArea(asciiColumn, cursorLineOffset, cursorLineOffset+1);
painter.save();
painter.setPen(Qt::darkGray);
painter.drawRect(hexX + hex_px.first - 1, textBaseLineY - ch + 1, hex_px.second - hex_px.first + 1, ch); // hex cursor
painter.drawRect(asciiX + ascii_px.first - 1, textBaseLineY - ch + 1, ascii_px.second - ascii_px.first + 1, ch); // ascii cursor
painter.restore();
}
/*
* build position column
*/
QString posColumn = QString("%1").arg(quint64(verticalScrollBar()->value() * 16 + i*16), 16, 16, QChar('0'));
if (m_offsetColumnMode == SIZE32)
{
posColumn = posColumn.right(8);
posColumn += ": ";
} else if (m_offsetColumnMode == SIZE64)
{
posColumn += ": ";
} else if (m_offsetColumnMode == NONE)
{
posColumn = "";
}
painter.drawText(H_MARGIN, textBaseLineY, posColumn);
painter.drawText(hexX, textBaseLineY, hexColumn.toUpper() ); // draw line address column + hex column
painter.drawText(asciiX, textBaseLineY, asciiColumn );
}
}
QSize HexEdit::sizeHint() const
{
return m_sizeHint;
}
void HexEdit::resizeEvent(QResizeEvent* event)
{
QAbstractScrollArea::resizeEvent(event);
updateScrollbar();
}
/* configures vscrollbar so that its value reflects the
* first to be displayed line
*
*/
void HexEdit::updateScrollbar()
{
verticalScrollBar()->setRange(0, m_lineCount - visibleLines());
viewport()->update();
}
void HexEdit::scrollContentsBy(int dx, int dy)
{
int pixeldy = dy * fontMetrics().lineSpacing();;
if (qAbs(pixeldy) < viewport()->height())
{
viewport()->scroll( 0, pixeldy );
}
else
{
viewport()->update();
}
}
void HexEdit::keyPressEvent(QKeyEvent * event)
{
switch (event->key())
{
case Qt::Key_Left:
if (m_cursorPosition > 0)
{
m_cursorPosition--;
ensureCursorVisible();
emit cursorPosition( m_cursorPosition );
viewport()->update();
}
break;
case Qt::Key_Right:
if (m_cursorPosition < m_dataSize-1)
{
m_cursorPosition++;
ensureCursorVisible();
emit cursorPosition( m_cursorPosition );
viewport()->update();
}
break;
case Qt::Key_Down:
if (m_cursorPosition < m_dataSize - 16)
{
m_cursorPosition += 16;
ensureCursorVisible();
emit cursorPosition( m_cursorPosition );
viewport()->update();
}
break;
case Qt::Key_Up:
if (m_cursorPosition >= 16)
{
m_cursorPosition -= 16;
ensureCursorVisible();
emit cursorPosition( m_cursorPosition );
viewport()->update();
}
break;
case Qt::Key_PageDown:
if (m_cursorPosition / 16 + visibleLines() < m_dataSize / 16)
{
m_cursorPosition += visibleLines() * 16;
verticalScrollBar()->setValue(m_cursorPosition / 16);
emit cursorPosition( m_cursorPosition );
}
break;
case Qt::Key_PageUp:
if (m_cursorPosition / 16 - visibleLines() >= 0)
{
m_cursorPosition -= visibleLines() * 16;
ensureCursorVisible();
emit cursorPosition( m_cursorPosition );
viewport()->update();
}
break;
default:
QAbstractScrollArea::keyPressEvent( event );
break;
}
}
void HexEdit::ensureCursorVisible()
{
if (m_cursorPosition / 16 < verticalScrollBar()->value())
{
// cursor above viewport
verticalScrollBar()->setValue( m_cursorPosition / 16 );
}
else if ((m_cursorPosition / 16) + 1 >= verticalScrollBar()->value() + visibleLines())
{
// cursor below viewport
verticalScrollBar()->setValue( m_cursorPosition / 16 - visibleLines() + 1);
}
}
/**
* @brief HexEdit::calculateHexTextArea
* Calculate start and end pos in pixels in hex string
* @param hexStr
* @param start start chr index
* @param end end chr index (exclusive)
* @return
*/
QPair<int,int> HexEdit::calculateHexTextArea(const QString &hexStr, int start, int end) const
{
start = qBound(0, start, 16);
end = qMin(end, 16);
int start_char_ofs = (start/4) * (8+3+2) + (start%4) * 3;
int end_char_ofs = (end/4) * (8+3+2) + (end%4) * 3 - 1;
if (end % 4 == 0 && end > 0) // end falls on last byte of 4byte column
{
end_char_ofs -= 1; // remove trailing space
}
int startlen = fontMetrics().width(hexStr.left(start_char_ofs));
int endlen = fontMetrics().width(hexStr.left(end_char_ofs));
return {startlen, endlen};
}
QPair<int, int> HexEdit::calculateAsciiTextArea(const QString &asciiStr, int start, int end) const
{
int startlen = fontMetrics().width(asciiStr.left(qBound(0, start, 16)));
int endlen = fontMetrics().width(asciiStr.left(qMin(end, 16)));
return {startlen, endlen};
}
/* number of lines visible
* based on widget height and data size
*/
int HexEdit::visibleLines() const
{
return viewport()->height() / fontMetrics().lineSpacing();
}
void HexEdit::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton)
setCursorPosition(m_data + mousePosToOffset(event->pos()));
}
void HexEdit::contextMenuEvent(QContextMenuEvent *e)
{
QMenu menu;
QAction* a = menu.addAction("Rescan from offset 0x" + QString::number(m_cursorPosition, 16));
if (menu.exec(e->globalPos()) == a)
{
emit rescanRequested(m_cursorPosition);
}
}
void HexEdit::setHighlight(const uchar * start, qint64 size, bool ensureVisible)
{
m_highlightStartAdr = start;
m_highlightSize = size;
if (ensureVisible)
ensureHighlightVisible();
viewport()->update();
}
void HexEdit::setCursorPosition(const uchar *pos)
{
if (m_cursorPosition != pos - m_data)
{
m_cursorPosition = pos - m_data;
viewport()->update();
emit cursorPosition( m_cursorPosition );
}
}
void HexEdit::ensureHighlightVisible()
{
if (m_highlightStartAdr == 0)
return;
int highlightStartLine = (m_highlightStartAdr - m_data) / 16;
if (highlightStartLine < verticalScrollBar()->value()
||
highlightStartLine >= (verticalScrollBar()->value() + visibleLines()))
{
verticalScrollBar()->setValue( (m_highlightStartAdr - m_data) / 16 );
}
}
qint64 HexEdit::mousePosToOffset(const QPoint &pos) const
{
qint64 firstLineOfs = (verticalScrollBar()->value() * 16); // offset of first visible line
int cw = fontMetrics().width( '0' );
int yofs = 16 * ((pos.y()-1) / fontMetrics().lineSpacing());
int posMargin; // size of posStr column in px
if (m_offsetColumnMode == SIZE32)
{
posMargin = H_MARGIN + cw * 10;
} else if (m_offsetColumnMode == SIZE64)
{
posMargin = H_MARGIN + cw * 18;
} else if (m_offsetColumnMode == NONE)
{
posMargin = H_MARGIN;
}
int asciiX = posMargin - H_MARGIN + (4*(8+3) + 3*2 + 4)*cw;
int xofs;
if (pos.x() < asciiX)
{
const int x = pos.x() - posMargin + cw;
const int blockWidth = (8+3+2)*cw;
const int byteWidth = 3*cw;
const int blockNumber = x / blockWidth;
const int byteInBlock = qBound(0, (x % blockWidth - cw/2) / byteWidth, 3);
xofs = blockNumber * 4 + byteInBlock;
}
else
xofs = (pos.x() - asciiX) / cw;
return qBound((qint64)0, firstLineOfs + yofs + qBound(0, xofs, 15), m_dataSize);
}
<file_sep>/asterixReportGenerator.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2016 <NAME> (<EMAIL>)
*/
#include "asterixReportGenerator.h"
#include <QProgressDialog>
#include "global.h"
#include "asterixModel.h"
#include "uap.h"
AsterixReportGenerator::AsterixReportGenerator( QObject *parent) :
QObject(parent)
{
}
void AsterixReportGenerator::createReport(QTextStream& out, Type type)
{
if (g_asterixModel == 0)
return;
QScopedPointer<AbstractGenerator> generator;
switch (type)
{
case XML:
generator.reset(new XmlGenerator(out));
break;
}
QProgressDialog progressDialog("Generating Report...", "Abort", 0, g_asterixModel->numBlocks(), g_mainWindow);
progressDialog.setWindowModality(Qt::WindowModal);
for (int i = 0; i < g_asterixModel->numBlocks(); ++i)
{
progressDialog.setValue(i);
if (progressDialog.wasCanceled())
{
break;
}
const AsterixBlockInfo& blockInfo = g_asterixModel->getBlockInfos()[i];
const AsterixBlock block(g_file + blockInfo.offset, *g_uap);
handleBlock(generator.data(), block);
}
progressDialog.setValue(g_asterixModel->numBlocks()); // this will close the dialog
}
void AsterixReportGenerator::handleBlock(AbstractGenerator* gen, const AsterixBlock& block)
{
gen->startBlock(block);
for (int j = 0; j < block.numRecords(); ++j)
{
const AsterixRecord& record = block.record(j);
gen->startRecord(record);
gen->startDataItemsSection(record);
for (int k = 0; k < record.numFields(); ++k)
{
const AsterixDataItem &dataItem = record.field(k);
const UapDataItem &uap = *dataItem.uapDataItem();
gen->startDataItem(dataItem, uap);
if (dataItem.numSubfields() == 0)
{
foreach (const UapField& uapField, uap.m_fields)
{
if (not uap.fieldPresent(dataItem.data(), uapField))
continue;
// suppress output of spare fields
if (uapField.name() == "Spare")
continue;
gen->startFinishField(dataItem, uapField);
}
}
else
{
for (int si = 0; si < dataItem.numSubfields(); si++)
{
const AsterixDataItem& subField = dataItem.subField(si);
const UapDataItem& subUap = *subField.uapDataItem();
gen->startDataItem(subField, subUap, 1);
foreach (const UapField& uapField, subUap.m_fields)
{
if (not subUap.fieldPresent(subField.data(), uapField))
continue;
// suppress output of spare fields
if (uapField.name() == "Spare")
continue;
gen->startFinishField(subField, uapField, 1);
}
gen->finishDataItem(subField, *subField.uapDataItem(), 1);
}
}
gen->finishDataItem(dataItem, uap);
}
gen->finishDataItemsSection(record);
gen->finishRecord(record);
}
gen->finishBlock(block);
}
AbstractGenerator::Field AbstractGenerator::decodeField(const AsterixDataItem& dataItem, const UapField& uapField)
{
const int itemLength = (dataItem.uapDataItem()->format() == UapDataItem::VARIABLE) ? 1 : dataItem.length();
const QByteArray field = dataItem.bitfield(uapField.octed(), itemLength, uapField.msb()-1, uapField.lsb()-1);
int value = 0;
Field ret;
ret.hasraw = false;
switch (uapField.format())
{
case UapField::ICAO6STR:
ret.value = AsterixDataItem::decodeIcaoStr((const uchar*)field.constData());
break;
case UapField::UINTEGER:
ret = unitAndScale(uapField, bitfieldToUInt(field));
break;
case UapField::INTEGER:
ret = unitAndScale(uapField, bitfieldToInt(field, uapField.msb()-1 - (((uapField.lsb()-1)/8)*8)));
break;
case UapField::OCTAL:
ret.rawval = bitfieldToUInt(field);
ret.hasraw = true;
ret.value = QString("0%1").arg(ret.rawval, 0, 8);
ret.unit = uapField.unitStr(uapField.unit());
break;
case UapField::ASCII:
ret.value = QString::fromLatin1(field);
break;
case UapField::HEX:
default:
ret.value = "0x";
for (int i=0; i < field.size(); i++)
{
ret.value += QString("%1").arg((uint)((uchar)field[i]), 2, 16, QChar('0')).toUpper();
}
break;
}
// place enum description (if ex.) in 'unit' field
QMap<int, UapEnum>::const_iterator iterator = uapField.enums().constFind(value);
if (iterator != uapField.enums().end())
{
ret.unit = iterator.value().m_desc;
}
return ret;
}
AbstractGenerator::Field AbstractGenerator::unitAndScale(const UapField& uapField, qint64 rawvalue)
{
Field f;
f.rawval = rawvalue;
f.hasraw = true;
if (uapField.unit() != UapField::UNDEFINED)
{
f.value = QString::number((double)rawvalue * uapField.scale());
f.unit = uapField.unitStr(uapField.unit());
}
else
{
f.value = QString::number(rawvalue);
}
return f;
}
void XmlGenerator::startBlock(const AsterixBlock& block)
{
ind(0) << R"(<block cat=")" << block.category() << R"(" len=")" << block.length() << R"(">)" << endl;
}
void XmlGenerator::finishBlock(const AsterixBlock&)
{
ind(0) << R"(</block>)" << endl;
}
void XmlGenerator::startRecord(const AsterixRecord& record)
{
ind(1) << R"(<record len=")" << record.length() << R"(">)" << endl;
}
void XmlGenerator::finishRecord(const AsterixRecord&)
{
ind(1) << R"(</record>)" << endl;
}
void XmlGenerator::startDataItem(const AsterixDataItem& dataItem, const UapDataItem& uap, int i)
{
ind(2+i) << R"(<dataitem type=")" << uap.id() << R"(" frn=")" << uap.frn() << R"(" len=")" << dataItem.length() << R"(">)" << endl;
}
void XmlGenerator::finishDataItem(const AsterixDataItem&, const UapDataItem&, int i)
{
ind(2+i) << R"(</dataitem>)" << endl;
}
void XmlGenerator::startFinishField(const AsterixDataItem& dataItem, const UapField& uap, int i)
{
ind(3+i) << R"(<field name=")" << uap.name() << R"(">)" << endl;
ind(4+i) << R"(<desc>)" << wrapInCData(uap.desc()) << R"(</desc>)" << endl; // desc might contain non xml characters
Field f = decodeField(dataItem, uap);
ind(4+i) << R"(<value)";
if (f.hasraw)
{
ind(0) << R"( raw=")" << f.rawval << R"(")";
}
if (not f.unit.isEmpty())
{
ind(0) << R"( unit=")" << f.unit << R"(")";
}
ind(0) << R"(>)" << f.value << R"(</value>)" << endl;
ind(3+i) << R"(</field>)" << endl;
}
QString XmlGenerator::wrapInCData(const QString& s)
{
if (s.isEmpty())
{
return QString();
}
else
{
return "<![CDATA[" + s + "]]>";
}
}
<file_sep>/asterixModel.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#include "asterixModel.h"
#include "global.h"
#include "asterixFileMapper.h"
AsterixModel::AsterixModel(QObject *parent) :
QAbstractItemModel(parent)
{
m_blocksExposed = 0;
m_blockInsertPos = 0;
}
void AsterixModel::asterixBlock(const QList<AsterixBlockInfo> blocks)
{
if (blocks.isEmpty())
return;
beginInsertRows( QModelIndex(), m_blockInsertPos, m_blockInsertPos + blocks.count() - 1);
foreach (const AsterixBlockInfo& block, blocks)
{
if (m_blockInsertPos >= m_blocks.size())
{
m_blocks.resize(m_blocks.size() + m_blocks.size()/2);
}
m_blocks[m_blockInsertPos++] = block;
}
endInsertRows();
}
//bool AsterixModel::canFetchMore(const QModelIndex &parent) const
//{
// if (parent.isValid())
// {
// return false;
// }
// else
// {
// return m_blocksExposed < m_blocks.size();
// }
//}
//void AsterixModel::fetchMore(const QModelIndex &parent)
//{
// if (not parent.isValid())
// {
// int numFetch = qMin(m_blocks.count() - m_blocksExposed, fetchIncrement);
// if (numFetch > 0)
// {
// beginInsertRows( QModelIndex(), m_blocksExposed, m_blocksExposed + numFetch - 1);
// m_blocksExposed += numFetch;
// endInsertRows();
// }
// }
//}
void AsterixModel::blocksScanned(qint64 blockNum)
{
m_numBlocks = blockNum;
g_blockCountLabel->setText( QString("Blocks: %1").arg(blockNum) );
}
QVariant AsterixModel::headerData(int section, Qt::Orientation orientation, int role) const
{
static QString headers[] = { "Block Offset", "Length", "Category" };
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return headers[section];
else if (orientation == Qt::Horizontal && role == Qt::ToolTipRole)
{
switch (section)
{
case 0: return "Position in file";
case 1: return "Stated length";
case 2: return "Asterix Category";
}
return QVariant();
}
else
return QAbstractItemModel::headerData(section, orientation, role);
}
QModelIndex AsterixModel::index(int row, int column, const QModelIndex &parent) const
{
return createIndex(row, column, row);
}
QVariant AsterixModel::data(const QModelIndex &index, int role) const
{
switch (role)
{
case Qt::DisplayRole:
{
switch (index.column())
{
case 0:
return QString("0x%1").arg(m_blocks[index.row()].offset, 0, 16);
break;
case 1:
return m_blocks[index.row()].size;
break;
case 2:
return m_blocks[index.row()].category;
break;
}
}
default:
return QVariant();
}
}
int AsterixModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
{
return 0;
}
else
{
return m_blockInsertPos;
}
}
const AsterixBlockInfo& AsterixModel::blockInfo(const QModelIndex &index) const
{
Q_ASSERT(index.isValid());
Q_ASSERT(index.row() < m_blocks.count());
return m_blocks[index.row()];
}
AsterixBlockModel::AsterixBlockModel(const uchar* base, const AsterixBlock& block, QObject *parent) :
QAbstractItemModel(parent),
m_base(base),
m_asterixBlock(block)
{
}
QVariant AsterixBlockModel::headerData(int section, Qt::Orientation orientation, int role) const
{
static QString headers[] = { "Record Offset", "Time", "Length", "#Items" };
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return headers[section];
else if (orientation == Qt::Horizontal && role == Qt::ToolTipRole)
{
switch (section)
{
case 0: return "Position in file";
case 1: return "Value of Time-Of-Day item (if applicable)";
case 2: return "Calculated length";
case 3: return "Number of data items";
}
return QVariant();
}
else
return QAbstractItemModel::headerData(section, orientation, role);
}
QModelIndex AsterixBlockModel::index(int row, int column, const QModelIndex &parent) const
{
return createIndex(row, column, row);
}
int AsterixBlockModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
{
return 0;
}
else
{
return m_asterixBlock.numRecords();
}
}
QVariant AsterixBlockModel::data(const QModelIndex &index, int role) const
{
if (not index.isValid() || index.row() >= m_asterixBlock.numRecords())
return QVariant();
switch (role)
{
case Qt::DisplayRole:
{
switch (index.column())
{
case 0:
return QString("0x%1").arg(m_asterixBlock.record(index.row()).data() - m_base, 0, 16);
break;
case 1:
return m_asterixBlock.record(index.row()).timeOfDay().toString("HH:mm:ss.zzz");
break;
case 2:
return m_asterixBlock.record(index.row()).length();
break;
case 3:
return m_asterixBlock.record(index.row()).numFields();
break;
}
}
default:
return QVariant();
}
}
AsterixRecordModel::AsterixRecordModel(const uchar* base, const AsterixRecord& record, QObject *parent) :
QAbstractItemModel(parent),
m_base(base),
m_asterixRecord(record)
{
buildRowHeaders();
}
QVariant AsterixRecordModel::headerData(int section, Qt::Orientation orientation, int role) const
{
static const QString headers[] = { "Item Offset", "Length", "FRN", "Field Type", "Description" };
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return headers[section];
else if (orientation == Qt::Vertical && role == Qt::DisplayRole)
return m_rowHeaders[section];
else if (orientation == Qt::Horizontal && role == Qt::ToolTipRole)
{
switch (section)
{
case 0: return "Position in file";
case 1: return "Specified length";
case 2: return "Specified Field-Reference-Number";
case 3: return "Specified field type";
}
return QVariant();
}
else
return QAbstractItemModel::headerData(section, orientation, role);
}
QModelIndex AsterixRecordModel::index(int row, int column, const QModelIndex &parent) const
{
return createIndex(row, column, row);
}
int AsterixRecordModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
{
return 0;
}
else
{
return m_rowHeaders.count();
}
}
const AsterixDataItem& AsterixRecordModel::dataItemAtRow( int r ) const
{
const int dataItemI = m_rowHeaders[r].left( m_rowHeaders[r].indexOf('#') ).toInt() - 1;
if (m_rowHeaders[r].contains('#'))
{
int subfieldIndex = m_rowHeaders[r].mid( m_rowHeaders[r].indexOf('#') + 1 ).toInt() - 1;
return m_asterixRecord.field(dataItemI).subField(subfieldIndex);
}
else
{
return m_asterixRecord.field(dataItemI);
}
}
QVariant AsterixRecordModel::data(const QModelIndex &index, int role) const
{
if (not index.isValid() || index.row() >= m_rowHeaders.count())
return QVariant();
const int r = m_rowHeaders[index.row()].left( m_rowHeaders[index.row()].indexOf('#') ).toInt() - 1;
switch (role)
{
case Qt::DisplayRole:
{
switch (index.column())
{
case 0:
{
const AsterixDataItem& dataItem = dataItemAtRow( index.row() );
return QString("0x%1").arg(dataItem.data() - m_base, 0, 16);
break;
}
case 1:
{
const AsterixDataItem& dataItem = dataItemAtRow( index.row() );
return dataItem.length();
break;
}
case 2:
{
const AsterixDataItem& dataItem = dataItemAtRow( index.row() );
const UapDataItem& uapItem = *dataItem.uapDataItem();
return uapItem.frn();
}
break;
case 3:
{
const AsterixDataItem& dataItem = dataItemAtRow( index.row() );
const UapDataItem& uapItem = *dataItem.uapDataItem();
return uapItem.id();
}
break;
case 4:
{
const AsterixDataItem& dataItem = dataItemAtRow( index.row() );
const UapDataItem& uapItem = *dataItem.uapDataItem();
return uapItem.name();
break;
}
}
}
default:
return QVariant();
}
}
void AsterixRecordModel::buildRowHeaders()
{
for (int i = 0; i < m_asterixRecord.numFields(); i++)
{
m_rowHeaders << QString::number(i+1);
for (int si = 0; si < m_asterixRecord.field(i).numSubfields(); si++)
{
m_rowHeaders << QString::number(i+1) + "#" + QString::number(si+1);
}
}
}
<file_sep>/global.h
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2010 <NAME> (<EMAIL>)
*/
#ifndef GLOBAL_H
#define GLOBAL_H
#include <QtCore>
#include "logger.h"
class QMainWindow;
class QLabel;
class QColor;
class AsterixModel;
class Uap;
extern QMainWindow* g_mainWindow;
extern QString g_specsDirectory;
extern QString g_openFileName;
extern const uchar* g_file;
extern qint64 g_fileSize;
extern QLabel* g_blockCountLabel;
extern AsterixModel* g_asterixModel;
extern Uap* g_uap;
extern QColor g_highlightColor;
extern Logger* g_logger;
void logInfo(const QString& msg);
void logWarn(const QString& msg);
void logError(const QString& msg);
#endif // GLOBAL_H
<file_sep>/logger.cpp
/*
* This application is free software and is released under the terms of
* the BSD license. See LICENSE file for details.
*
* Copyright (c) 2013 <NAME> (<EMAIL>)
*/
#include "logger.h"
const QString typeStrs[]{"INFO", "WARN", "ERROR"};
class MyTextEdit : public QTextEdit
{
protected:
virtual void contextMenuEvent(QContextMenuEvent *e) override
{
QMenu *menu = createStandardContextMenu();
menu->addAction("Clear", this, SLOT(clear()));
menu->exec(e->globalPos());
delete menu;
}
};
Logger::Logger(QObject *parent) :
QObject(parent)
{
m_textEdit = new MyTextEdit;
m_textEdit->setReadOnly(true);
// m_textEdit->setFontFamily("monospace");
}
void Logger::log(Logger::Type type, const QString& msg)
{
m_textEdit->append(typeStrs[(int)type] + ": " + msg);
}
| 9ea0fd18db6f1af6f649826ab06127cd778e8409 | [
"C",
"C++"
] | 31 | C++ | 10110111/asterixInspector | 0451a49f0e9c4324052e4270461df5c2012a733e | 92a536b52b88968385a433cb19e133d0fe512c76 |
refs/heads/main | <repo_name>shubhiagarwal18/pythonpractice<file_sep>/hzzzzzz.py
import numpy as np
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
data = np.random.rand(4,6)
heat_map=sb.heatmap(data)
plt.show()<file_sep>/sentiment.py
import tweepy
from textblob import TextBlob
import matplotlib.pyplot as plt
def percentage(part, whole):
return 100 * float(part) / float(whole)
consumerKey = "TPQS2mfRtv392pctndfEoThn7"
consumerSecret = "<KEY>"
accessToken = "<KEY>"
accessTokenSecret = "<KEY>"
auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)
searchTerm = input("Enter Keyword/Tag to search about: ")
NoOfTerms = int(input("Enter how many tweets to search: "))
tweets = tweepy.Cursor(api.search, q=searchTerm).items(NoOfTerms)
positive = 0
negative = 0
neutral = 0
polarity = 0
for tweet in tweets:
#print(tweet.text)
analysis = TextBlob(tweet.text)
polarity += analysis.sentiment.polarity
if (analysis.sentiment.polarity == 0):
neutral += 1
elif (analysis.sentiment.polarity > 0.00):
positive += 1
elif (analysis.sentiment.polarity < 0.00):
negative += 1
positive = percentage(positive, NoOfTerms)
negative = percentage(negative, NoOfTerms)
neutral = percentage(neutral, NoOfTerms)
polarity = percentage(polarity, NoOfTerms)
positive = format(positive, '.2f')
negative = format(negative, '.2f')
neutral = format(neutral, '.2f')
print("How people are reacting on " + searchTerm + " by analyzing " + str(NoOfTerms) + " tweets.")
print()
print("General Report: ")
if (polarity == 0):
print("Neutral")
elif (polarity > 0):
print("Positive")
elif (polarity < 0):
print("Negative")
labels = ['positive['+ str(positive) + '%]', 'Neutral [' + str(neutral) + '%]', 'Negative [' + str(negative) + '%]' ]
sizes = [positive,neutral, negative]
colors = ['yellow','green', 'red']
patches,texts = plt.pie(sizes,colors=colors, startangle=90)
plt.legend(patches, labels, loc ="best")
plt.title("How people are reacting on " + searchTerm + " by analyzing " + str(NoOfTerms) + " tweets.")
plt.axis('equal')
plt.tight_layout()
plt.show()<file_sep>/logistic.py
import pandas as pd
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt
plt.rc("font", size=14)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import seaborn as sns
sns.set(style="white")
sns.set(style="whitegrid", color_codes=True)
data = pd.read_csv('banking.csv.txt', header = 0)
data = data.dropna()
print(data.shape)
print(list(data.columns))
print(data.head())
print(data['education'].unique())
data['education']=np.where(data['education'] =='basic.9y', 'Basic', data['education'])
data['education']=np.where(data['education'] =='basic.6y', 'Basic', data['education'])
data['education']=np.where(data['education'] =='basic.4y', 'Basic', data['education'])
print(data['education'].unique())
print(data['y'].value_counts())
sns.countplot(x='y' , data=data,palette='hls')
plt.show()
plt.savefig('count_plot')
count_no_sub = len(data[data['y']==0])
count_sub = len(data[data['y']==1])
pct_of_no_sub = count_no_sub/(count_no_sub+count_sub)
print("percentage of no subscription is", pct_of_no_sub*100)
pct_of_sub = count_sub/(count_no_sub+count_sub)
print("percentage of subscription", pct_of_sub*100)
print(data.groupby('y').mean())<file_sep>/mongodatabase.py
import pymongo
connection= pymongo.MongoClient('localhost',27017)
database = connection['mydb_01']
collection = database['mycol_01']
data = {"Name": "shubhi"}
collection.insert_one(data)
<file_sep>/extractTweets.py
import pymongo
from pymongo import MongoClient
import json
import twitter
from pprint import pprint
CONSUMER_KEY = "TPQS2mfRtv392pctndfEoThn7"
CONSUMER_SECRET = "<KEY>"
OAUTH_TOKEN = "<KEY>"
OAUTH_TOKEN_SECRET = "<KEY>"
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
client = MongoClient()
db = client.tweet_db
tweet_collection = db.tweet_collection
tweet_collection.create_index([("id", pymongo.ASCENDING)], unique=True)
count = 100
q = "Bitcoin"
search_results = twitter_api.search.tweets(count=count, q=q)
# pprint(search_results['search_metadata'])
statuses = search_results["statuses"]
since_id_new = statuses[-1]['id']
for statues in statuses:
try:
tweet_collection.insert(statues)
except:
pass
tweet_cursor = tweet_collection.find()
print(tweet_cursor.count())
user_cursor = tweet_collection.distinct("user.id")
print(len(user_cursor))
for document in tweet_cursor:
try:
print('-----')
print('name:-', document["user"]["name"])
print('text:-', document["text"])
print('Created Date:-', document["created_at"])
except:
print("Error in Encoding")
pass
<file_sep>/MongoSenti.py
import pymongo
from pymongo import MongoClient
import twitter
from pprint import pprint
import tweepy
from textblob import TextBlob
import matplotlib.pyplot as plt
CONSUMER_KEY = "TPQS2mfRtv392pctndfEoThn7"
CONSUMER_SECRET = "<KEY>"
OAUTH_TOKEN = "<KEY>"
OAUTH_TOKEN_SECRET = "<KEY>"
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
client = MongoClient()
db = client.tweet_db
tweet_collection = db.tweet_collection
tweet_collection.create_index([("id", pymongo.ASCENDING)], unique=True)
#count = 100
#q = "Bitcoin"
q = input("Enter Keyword/Tag to search about: ")
count = int(input("Enter how many tweets to search: "))
search_results = twitter_api.search.tweets(count=count, q=q)
# pprint(search_results['search_metadata'])
statuses = search_results["statuses"]
since_id_new = statuses[-1]['id']
for statues in statuses:
try:
tweet_collection.insert(statues)
except:
pass
tweet_cursor = tweet_collection.find()
print(tweet_cursor.count())
user_cursor = tweet_collection.distinct("user.id")
print(len(user_cursor))
'''for document in tweet_cursor:
try:
print('-----')
print('name:-', document["user"]["name"])
print('text:-', document["text"])
print('Created Date:-', document["created_at"])
except:
print("Error in Encoding")
pass'''
def percentage(part, whole):
return 100 * float(part) / float(whole)
positive = 0
negative = 0
neutral = 0
polarity = 0
tweet_cursor = tweet_collection.find()
for tweet in tweet_cursor:
try:
#print(tweet["text"])
analysis = TextBlob(tweet["text"])
polarity += analysis.sentiment.polarity
if (analysis.sentiment.polarity == 0):
neutral += 1
elif (analysis.sentiment.polarity > 0.00):
positive += 1
elif (analysis.sentiment.polarity < 0.00):
negative += 1
except:
print("Error in Encoding")
pass
positive = percentage(positive, count)
negative = percentage(negative, count)
neutral = percentage(neutral, count)
polarity = percentage(polarity, count)
print("shubhi111",positive)
positive = format(positive, '.2f')
negative = format(negative, '.2f')
neutral = format(neutral, '.2f')
print("How people are reacting on " + q + " by analyzing " + str(count) + " tweets.")
print()
print("General Report: ")
if (polarity == 0):
print("Neutral")
elif (polarity > 0):
print("Positive")
elif (polarity < 0):
print("Negative")
labels = ['positive[' + str(positive) + '%]', 'Neutral [' + str(neutral) + '%]', 'Negative [' + str(negative) + '%]']
sizes = [positive, neutral, negative]
colors = ['yellow', 'green', 'red']
patches, texts = plt.pie(sizes, colors=colors, startangle=90)
plt.legend(patches, labels, loc="best")
plt.title("How people are reacting on " + q + " by analyzing " + str(count) + " tweets.")
plt.axis('equal')
plt.tight_layout()
plt.show()<file_sep>/test.py
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
import matplotlib.pyplot as plt
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
plt.show()
bx = sns.heatmap(uniform_data, vmin=0, vmax=1)
plt.show()
normal_data = np.random.randn(10, 12)
cx = sns.heatmap(normal_data, center=0)
plt.show()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
dx = sns.heatmap(flights)
plt.show()
ex = sns.heatmap(flights, annot=True, fmt="d")
plt.show()
fx = sns.heatmap(flights, linewidths=.5)
plt.show()
gx = sns.heatmap(flights, cmap="YlGnBu")
plt.show()
hx = sns.heatmap(flights, center=flights.loc["Jan", 1955])
plt.show()
data = np.random.randn(50, 20)
ix = sns.heatmap(data, xticklabels=2, yticklabels=False)
plt.show()
jx = sns.heatmap(flights, cbar=False)
plt.show()
grid_kws = {"height_ratios": (.9, .05), "hspace": .3}
f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
kx = sns.heatmap(flights, ax=ax,
cbar_ax=cbar_ax,
cbar_kws={"orientation": "horizontal"})
plt.show()
corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
f, ax = plt.subplots(figsize=(7, 5))
lx = sns.heatmap(corr, mask=mask, vmax=.3, square=True)
plt.show()<file_sep>/dataset.py
import pymongo
from pymongo import MongoClient
import twitter
import pandas as pd
from pprint import pprint
import tweepy
from textblob import TextBlob
import matplotlib.pyplot as plt
CONSUMER_KEY = "TPQS2mfRtv392pctndfEoThn7"
CONSUMER_SECRET = "<KEY>"
OAUTH_TOKEN = "<KEY>"
OAUTH_TOKEN_SECRET = "<KEY>"
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
client = MongoClient()
db = client.tweet_db
tweet_collection = db.tweet_collection
tweet_collection.create_index([("id", pymongo.ASCENDING)], unique=True)
#count = 100
#q = "Bitcoin"
q = input("Enter Keyword/Tag to search about: ")
count = int(input("Enter how many tweets to search: "))
search_results = twitter_api.search.tweets(count=count, q=q)
# pprint(search_results['search_metadata'])
statuses = search_results["statuses"]
since_id_new = statuses[-1]['id']
for statues in statuses:
try:
tweet_collection.insert(statues)
except:
pass
tweet_cursor = tweet_collection.find()
print(tweet_cursor.count())
user_cursor = tweet_collection.distinct("user.id")
print(len(user_cursor))
'''for document in tweet_cursor:
try:
print('-----')
print('name:-', document["user"]["name"])
print('text:-', document["text"])
print('Created Date:-', document["created_at"])
except:
print("Error in Encoding")
pass'''
#df = pd.DataFrame(list(tweet_collection.find({},{ "_id": 1, "text": 1 })))
df = pd.DataFrame(list(tweet_collection.find({},{ "_id": 0, "text": 1 })))
#print(df)
#print(df.head())
<file_sep>/clustering_heatmap.py
import seaborn as sns; sns.set_theme(color_codes=True)
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
species = iris.pop("species")
g = sns.clustermap(iris)
#plt.show()
g = sns.clustermap(iris,
figsize=(7, 5),
row_cluster=False,
dendrogram_ratio=(.1, .2),
cbar_pos=(0, .2, .03, .4))
#plt.show()
lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris, row_colors=row_colors)
g = sns.clustermap(iris, cmap="mako", vmin=0, vmax=10)
g = sns.clustermap(iris, metric="correlation")
g = sns.clustermap(iris, method="single")
g = sns.clustermap(iris, standard_scale=1)
g = sns.clustermap(iris, z_score=0, cmap="vlag")
plt.show() | f79711ead349e97086e516810b0f4e0c5acb6abd | [
"Python"
] | 9 | Python | shubhiagarwal18/pythonpractice | 131943934f17e21473c3aec9b4c47fd0cb5e9456 | 454e00ffd40c9e4a75eb350989c4be2a19f054ec |
refs/heads/main | <repo_name>Doskious/TaleSpire-GrabDropPlugin<file_sep>/TaleSpireGrabDropPlugin/GrabDropPlugin.cs
using UnityEngine;
using BepInEx;
using Bounce.Unmanaged;
using System.Collections.Generic;
using System;
using BepInEx.Configuration;
namespace LordAshes
{
[BepInPlugin(Guid, "Grab Drop Plug-In", Version)]
[BepInDependency(RadialUI.RadialUIPlugin.Guid)]
[BepInDependency(StatMessaging.Guid)]
[BepInDependency(FileAccessPlugin.Guid)]
public class GrabDropPlugin : BaseUnityPlugin
{
// Plugin info
public const string Guid = "org.lordashes.plugins.grabdrop";
public const string Version = "1.4.0.0";
public const string StatesPluginGuid = "org.lordashes.plugins.states";
// Content directory
private string dir = UnityEngine.Application.dataPath.Substring(0, UnityEngine.Application.dataPath.LastIndexOf("/")) + "/TaleSpire_CustomData/";
// Track radial asset
private CreatureGuid radialCreature = CreatureGuid.Empty;
private ConfigEntry<bool> actOnMini;
/// <summary>
/// Function for initializing plugin
/// This function is called once by TaleSpire
/// </summary>
void Awake()
{
UnityEngine.Debug.Log("Lord Ashes Grab Drop Plugin Active.");
// Post plugin on TS main page
StateDetection.Initialize(this.GetType());
// Get operation order
actOnMini = Config.Bind("Settings", "Select prop, action on mini", true);
// Create grab menu entry
RadialUI.RadialUIPlugin.AddOnCharacter(Guid + ".grab", new MapMenu.ItemArgs
{
Action = (mmi, obj) =>
{
if (actOnMini.Value)
{
StatMessaging.SetInfo(radialCreature, GrabDropPlugin.Guid + ".grab", LocalClient.SelectedCreatureId.ToString());
}
else
{
StatMessaging.SetInfo(LocalClient.SelectedCreatureId, GrabDropPlugin.Guid + ".grab", radialCreature.ToString());
}
},
Icon = FileAccessPlugin.Image.LoadSprite("Grab.png"),
Title = "Grab",
CloseMenuOnActivate = true
}, Reporter);
// Create drop menu entry
RadialUI.RadialUIPlugin.AddOnCharacter(Guid + ".drop", new MapMenu.ItemArgs
{
Action = (mmi, obj) =>
{
if (actOnMini.Value)
{
StatMessaging.SetInfo(radialCreature, GrabDropPlugin.Guid + ".drop", LocalClient.SelectedCreatureId.ToString());
}
else
{
StatMessaging.SetInfo(LocalClient.SelectedCreatureId, GrabDropPlugin.Guid + ".drop", radialCreature.ToString());
}
},
Icon = FileAccessPlugin.Image.LoadSprite("Drop.png"),
Title = "Drop",
CloseMenuOnActivate = true
}, Reporter);
// Create safe Kill menu entry
RadialUI.RadialUIPlugin.AddOnRemoveSubmenuKill(Guid + ".removeKill", "Kill Creature"); //Remove vanilla TS Kill Menu
RadialUI.RadialUIPlugin.AddOnSubmenuKill(Guid + ".safeKill", new MapMenu.ItemArgs //Replace with GrabDrop safe alternative
{
Action = (mmi, obj) =>
{
CreatureBoardAsset asset;
CreaturePresenter.TryGetAsset(radialCreature, out asset);
if (asset != null)
{
try
{
Debug.Log("Beginning GrabDrop Safe Kill");
List<Transform> tempTransformList = new List<Transform>();
//Find certain transforms to preserve
foreach (Transform child in asset.gameObject.transform.Children())
{
//Debug.Log("Transform Name: " + child.name + " , Game Object Name: " + child.gameObject.name);
if (child.name == "MoveableOffset" || child.name.StartsWith("Effect"))
{
//Debug.Log("Preserving '" + child.name + "' transform for safe delete");
tempTransformList.Add(child);
}
}
//It's imperative we remove the parent child relationship with any dragged creatures before deleting the parent
asset.gameObject.transform.DetachChildren();
//Certain transforms must be preserved to be gracefully disposed of by the engine when the parent object is deleted
if (tempTransformList.Count > 0)
{
foreach (Transform tempTransform in tempTransformList)
{
tempTransform.SetParent(asset.gameObject.transform);
}
}
asset.Creature.BoardAsset.RequestDelete(); //Perform the actual deletion
Debug.Log("GrabDrop Safe Kill Complete");
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
},
Icon = Icons.GetIconSprite("remove"),
Title = "Kill Creature",
CloseMenuOnActivate = true
}, Reporter);
// Subscribe to grab requests
StatMessaging.Subscribe(GrabDropPlugin.Guid + ".grab", (changes) =>
{
foreach (StatMessaging.Change change in changes)
{
if (change.action == StatMessaging.ChangeType.removed)
{
//Change skipped in Grab Callback due to it being a remove which we do not currently care about
continue;
}
try
{
// Grab
CreatureBoardAsset asset;
CreaturePresenter.TryGetAsset(change.cid, out asset);
if (asset != null)
{
CreatureBoardAsset child;
CreaturePresenter.TryGetAsset(new CreatureGuid(change.value), out child);
if (child != null)
{
string grabberStatesString = "";
grabberStatesString = StatMessaging.ReadInfo(asset.Creature.CreatureId, StatesPluginGuid);
if (!grabberStatesString.Contains("Leading"))
{
if (grabberStatesString == "")
grabberStatesString = "Leading";
else
grabberStatesString = "Leading," + grabberStatesString;
StatMessaging.SetInfo(asset.Creature.CreatureId, StatesPluginGuid, grabberStatesString);
}
Debug.Log(StatMessaging.GetCreatureName(asset.Creature) + " grabs '" + child.Creature.Name + "'");
child.transform.SetParent(asset.transform);
StatMessaging.ClearInfo(change.cid, GrabDropPlugin.Guid + ".drop");
string grabbeeStatesString = "";
grabbeeStatesString = StatMessaging.ReadInfo(child.Creature.CreatureId, StatesPluginGuid);
if (!grabbeeStatesString.Contains("Following: " + StatMessaging.GetCreatureName(asset.Creature)))
{
if (grabbeeStatesString == "")
grabbeeStatesString = "Following: " + StatMessaging.GetCreatureName(asset.Creature);
else
grabbeeStatesString = "Following: " + StatMessaging.GetCreatureName(asset.Creature) + "," + grabbeeStatesString;
StatMessaging.SetInfo(child.Creature.CreatureId, StatesPluginGuid, grabbeeStatesString);
}
}
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
});
// Subscribe to drop requests
StatMessaging.Subscribe(GrabDropPlugin.Guid + ".drop", (changes) =>
{
foreach (StatMessaging.Change change in changes)
{
if (change.action == StatMessaging.ChangeType.removed)
{
//Change skipped in Drop Callback due to it being a remove which we do not currently care about
continue;
}
try
{
// Drop
CreatureBoardAsset asset;
CreaturePresenter.TryGetAsset(change.cid, out asset);
if (asset != null)
{
CreatureBoardAsset droppedChild;
CreaturePresenter.TryGetAsset(new CreatureGuid(change.value), out droppedChild);
foreach (Transform child in asset.transform.Children())
{
if (child.gameObject == droppedChild.gameObject) //The child being dropped is one of our children
{
if (asset.transform.childCount == 2) //We only have 2 children left, our baseline moveableoffset, and the child we are about to drop
{
string grabberStatesString = "";
grabberStatesString = StatMessaging.ReadInfo(asset.Creature.CreatureId, StatesPluginGuid);
if (grabberStatesString.Contains("Leading,"))
{
grabberStatesString = grabberStatesString.Replace("Leading,", "");
}
else if (grabberStatesString.Contains("Leading"))
{
grabberStatesString = "";
}
StatMessaging.SetInfo(asset.Creature.CreatureId, StatesPluginGuid, grabberStatesString);
}
Debug.Log(StatMessaging.GetCreatureName(asset.Creature) + " drops '" + StatMessaging.GetCreatureName(droppedChild.Creature) + "'");
child.transform.SetParent(null); //Here we actually drop the child
StatMessaging.ClearInfo(change.cid, GrabDropPlugin.Guid + ".grab");
string grabbeeStatesString = "";
grabbeeStatesString = StatMessaging.ReadInfo(droppedChild.Creature.CreatureId, StatesPluginGuid);
if (grabbeeStatesString.Contains("Following: " + StatMessaging.GetCreatureName(asset.Creature)))
{
if (grabbeeStatesString.Contains("Following: " + StatMessaging.GetCreatureName(asset.Creature) + ","))
{
grabbeeStatesString = grabbeeStatesString.Replace("Following: " + StatMessaging.GetCreatureName(asset.Creature) + ",", "");
}
else if (grabbeeStatesString.Contains("Following: " + StatMessaging.GetCreatureName(asset.Creature)))
{
grabbeeStatesString = grabbeeStatesString.Replace("Following: " + StatMessaging.GetCreatureName(asset.Creature), "");
}
StatMessaging.SetInfo(droppedChild.Creature.CreatureId, StatesPluginGuid, grabbeeStatesString);
}
break;
}
}
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
});
}
/// <summary>
/// Method to track which asset has the radial menu open
/// </summary>
/// <param name="selected"></param>
/// <param name="radialMenu"></param>
/// <returns></returns>
private bool Reporter(NGuid selected, NGuid radialMenu)
{
radialCreature = new CreatureGuid(radialMenu);
return true;
}
/// <summary>
/// Function for determining if view mode has been toggled and, if so, activating or deactivating Character View mode.
/// This function is called periodically by TaleSpire.
/// </summary>
void Update()
{
}
}
}
| 1514d253b674309e171b533bf5e079e8cac44675 | [
"C#"
] | 1 | C# | Doskious/TaleSpire-GrabDropPlugin | f76b6798b67ec419d2e2d77a6f39dd9a7a598052 | a86fc59b2ff5fce33ce86343b095f90cc9de97f5 |
refs/heads/main | <repo_name>FranLion/DSP2020<file_sep>/Scripts DSP 2020/Scripts TP2/unuevohc.py
from Funcionestp2 import *
fs=44100
C1=0.9
C2=0.9
p=100
n_samples=fs*2
def delay1(senal,a1,a2):
zpad=np.zeros(1)
delay=np.append(zpad,senal)
x=np.append(senal,zpad)
y=a1*x+a2*delay
return y
cuerda=karplus_strong(n_samples,1,p,fs)
# x1,z1,dly1=delays(cuerda,1,C1,1,1)
#
# x2,z2,dly2=delays(cuerda,1,C2,1,1)
z1=delay1(cuerda,C1,1)
z2=delay1(cuerda,C1,1)
k1,y1,delayline1=IIR_delay(z1,-C1,1)
k2,y2,delayline2=IIR_delay(z2,-C2,1)
sf.write('HaHbHc.wav',cuerda,fs)
sf.write('HaHbHc1.wav',y1,fs)
sf.write('HaHbHc2.wav',y2,fs)
fftz1=np.fft.fft(z1)
fdB=20*np.log10(abs(fftz1))
fase=np.angle(fftz1)
plt.plot(fdB[0:2500])
# plt.subplot(2,1,1)
# plt.plot(y1,'#738EB6')
# plt.title('Señal generada por la cuerda')
# plt.grid('both')
# plt.ylabel('Amplitud relativa [n]')
# plt.xlabel('Número de muestra [n]')
# plt.subplot(2,1,2)
# plt.plot(y2,'#BF76D2')
# plt.title('Señal generada por la cuerda 2')
# plt.grid('both')
# plt.ylabel('Amplitud relativa [n]')
# plt.xlabel('Número de muestra [n]')
# plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/TP1-LIONTI-VILLATARCO/Python/Items/Item2.py
from FuncionesTP import *
'''
En este ejercicio se generan 6 señales de ruido con distribución Gaussiana y con los largos pedidos
en la consigna. Cada ruido se genera con una media nula y una desviación estandar igual a 1.
'''
# Se generan los ruidos
Señalrandom1 = np.random.normal(0, 1, 5) #ruido de largo 5
Señalrandom2 = np.random.normal(0, 1, 10) #ruido de largo 10
Señalrandom3 = np.random.normal(0, 1, 100) #ruido de largo 100
Señalrandom4 = np.random.normal(0, 1, 1000) #ruido de largo 1000
Señalrandom5 = np.random.normal(0, 1, 10000) #ruido de largo 10000
Señalrandom6 = np.random.normal(0, 1, 100000)#ruido de largo 100000
#A continuación se calculan la media y la desviación estándar de cada ruido generado utilizando las funciones pedidas en el Item 1 y que se encuentran definidas en el módulo "FuncionesTP"(FuncionesTP.py). Se redondea a dos decimales para fines prácticos.
lamedia1=lamedia(Señalrandom1)
desvioestandar1=round(desvioestandar(Señalrandom1,lamedia1),2)
lamedia2=lamedia(Señalrandom2)
desvioestandar2=round(desvioestandar(Señalrandom2,lamedia2),2)
lamedia3=lamedia(Señalrandom3)
desvioestandar3=round(desvioestandar(Señalrandom3,lamedia3),2)
lamedia4=lamedia(Señalrandom4)
desvioestandar4=round(desvioestandar(Señalrandom4,lamedia4),2)
lamedia5=lamedia(Señalrandom5)
desvioestandar5=round(desvioestandar(Señalrandom5,lamedia5),2)
lamedia6=lamedia(Señalrandom6)
desvioestandar6=round(desvioestandar(Señalrandom6,lamedia6),2)
# Se calculan las diferencias porcentuales con un redondeo a 0 decimales.
dif1=int(round(abs((desvioestandar1-1))*100))
dif2=int(round(abs((desvioestandar2-1))*100))
dif3=int(round(abs((desvioestandar3-1))*100))
dif4=int(round(abs((desvioestandar4-1))*100))
dif5=int(round(abs((desvioestandar5-1))*100))
dif6=int(round(abs((desvioestandar6-1))*100))
# Se presentan los resultados obtenidos en una tabla.
datos=[[5,desvioestandar1,dif1], [10,desvioestandar2,dif2], [100,desvioestandar3,dif3], [1000,desvioestandar4,dif4], [10000,desvioestandar5,dif5],[100000,desvioestandar6,dif6]]
Tabla = """\
+------------------------------+
| N | σ | % |
|------------------------------|
{}
+------------------------------+\
"""
Tabla = (Tabla.format('\n \t'.join("| {:>8d} | {:>8} | {:>6d} |".format(*fila)
for fila in datos)))
print ("\n")
print("\t \tResultados Item 2 ")
print (Tabla)
<file_sep>/Scripts DSP 2020/TP2 Lionti Villatarco/Funcionestp2.py
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
import soundfile as sf
def delays(senal,t,fs,a,N):
d=int(round((t/1000)*fs))
delay=np.zeros((N,len(senal)+(N*d)))
x=np.append(senal,np.zeros(N*d))
y=np.zeros_like(x)
dly=np.zeros_like(x)
for i in range(0,N):
D=(i+1)*d
zpad=np.zeros(D)
aux=np.append(zpad,senal)
delay[i]=np.append(aux,np.zeros(len(x)-len(aux)))
dly=(a**(i+1))*delay[i]+dly #x[n-D]
y=x+dly
return y
def IIR_delay(senal,a,t,fs):
D=int(round((t/100)*fs))
delayline=np.zeros(D)
x=np.append(senal,delayline)
y=np.zeros_like(x)
for i in range(len(x)):
y[i]=x[i]+a*delayline[D-1]
delayline=np.append(y[i],delayline[0:D-1])
return y
#Ha y Hb:
def karplus_strong(n_samples, prob , wavetable_size):
"Desde la tabla de onda anterior usando una distribucion binomial se genera un nuevo promedio."
samples = []
current_sample = 0
previous_value = 0
# wavetable_size = fs // p
# conseguir la aleatoriedad de nivel dos
wavetable = (2 * np.random.randint(0, 2, wavetable_size) - 1).astype(np.float)
if prob ==1:
while len(samples) < n_samples:
#aca hago el karplus strong y los guardo en wavetable
wavetable[current_sample] = 0.5 * (wavetable[current_sample] + previous_value)
#aca le agrego a samples lo muestra i que estoy bucleando
samples.append(wavetable[current_sample])
#aca le digo al bucle que lea siempre la ultima muestra del vector que me importa
previous_value = samples[-1]
#acumulador
current_sample += 1
#Resto de la division entre el vector wavetable y el sample que estoy bucleando
current_sample = current_sample % wavetable.size
else:
while len(samples) < n_samples:
#Utilizo binomial
r = np.random.binomial(1, prob)
sign = float(r == 1) * 2 - 1
wavetable[current_sample] = sign * 0.5 * (wavetable[current_sample] + previous_value)
samples.append(wavetable[current_sample])
previous_value = samples[-1]
current_sample += 1
current_sample = current_sample % wavetable.size
return np.array(samples)
def Ha(senal,D,S) :
#D=fs/f1
rho = 0.996
g0 = (1-S)*rho
g1 = S*rho
b = np.array([1.0]) # Zeros numerator coefficients
a = np.array([1.0] + ([0]*(D-3)) + [-g0, -g1]) # Poles denominator coefficients
y = signal.lfilter(b,a,senal)
return y
# def Hc(senal,C):
# b=np.array([C,1])
# a=np.array([1,-C])
# y=signal.lfilter(b, a, senal)
# return y
def Hd(senal,L,fs):
T=1/fs
RL=np.exp(-np.pi*L*T)
b=np.array([1-RL])
a=np.array([1,-RL])
y=signal.lfilter(b,a,senal)
return y
def He(senal,mu,N):
D=int(mu*N)
b=np.zeros(D)
b[0]=1
b[D-1]=-1
a=np.array([1])
y=signal.lfilter(b, a, senal)
return y
<file_sep>/Scripts DSP 2020/Scripts TP2/Ha.py
from Funcionestp2 import *
eps=0.001
fs=44100
T=1/fs
n_samples=fs*2
pa=1/2
f1=220
p1=fs/f1
N= int(np.floor(fs/f1 -pa-eps))
pc=p1-N-pa
c=(1-pc)/(1+pc)
Q=0.1
def IIRdelbueno(senal,a,N):
delayline=np.zeros(N)
x=np.append(senal,delayline)
y=np.zeros_like(x)
for i in range(len(x)):
y[i]=(1-a)*x[i]+a*delayline[N-1]
delayline=np.append(y[i],delayline[0:N-1])
return y
Karpluscuerda = karplus_strong(n_samples,1,N)
K
Karesult = Karpluscuerda -Q*Karpluscuerda
# y0=IIRdelbueno(Karpluscuerda,RL0,1)
# y1=IIRdelbueno(Karpluscuerda,RL1,1)
# y2=IIRdelbueno(Karpluscuerda,RL2,1)
# y3=IIRdelbueno(Karpluscuerda,RL3,1)
# y4=IIRdelbueno(Karpluscuerda,RL4,1)
# y5=IIRdelbueno(Karpluscuerda,RL5,1)
# y6=IIRdelbueno(Karpluscuerda,RL6,1)
sf.write('RL0.wav',y0,fs)
sf.write('RL1.wav',y1,fs)
sf.write('RL2.wav',y2,fs)
sf.write('RL3.wav',y3,fs)
sf.write('RL4.wav',y4,fs)
sf.write('RL5.wav',y5,fs)
sf.write('RL6.wav',y6,fs)
# ffty=np.fft.fft(y0)
# fdB=20*np.log10(abs(ffty))
# fase1=np.angle(ffty)
# fase2=np.angle(fftz2)
# plt.plot(fdB[0:2500])
# plt.plot(fdB)
# plt.plot(fdB[0:int(fs/2)])
# plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1final/TP1/Items/Item3.py
from FuncionesTP import *
'''En este ejercicio se generan 3 señales, cada una compuesta por la señal del Item 1 "data" más un ruido añadido(con sigma 0.1, 1 y 3 respectivamente). Finalmente se grafican las señales y se imprimen los resultado del SNR calculado para cada señal. '''
# Se generan los 3 ruidos y se añaden a la señal original.
ruido01 = np.random.normal(0, 0.1,len(data))
ruido1 = np.random.normal(0, 1, len(data))
ruido3 = np.random.normal(0, 3, len(data))
x01 = data + ruido01
x1 = data + ruido1
x3 = data + ruido3
# Se normalizan las señales generadas utilizando la función "normalizar" definida en FuncionesTP.py
x01=normalizar(x01)
x1=normalizar(x1)
x3=normalizar(x3)
# Se calculan los valores de SNR para cada señales a través de funciones de nuestro módulo de funciones.
SNR1=np.max(x01)/desvioestandar(ruido01,lamedia(ruido01))
SNR2=np.max(x1)/desvioestandar(ruido1,lamedia(ruido1))
SNR3=np.max(x3)/desvioestandar(ruido3,lamedia(ruido3))
# Se presentan los resultados.
datos=[["x01", round(SNR1,2)],["x1",round(SNR2,2)],["x3",round(SNR3,2)]]
Tabla = """\
+---------------------+
| Señal | SNR |
|---------------------|
{}
+---------------------+\
"""
Tabla = (Tabla.format('\n'.join("| {:>8s} | {:>7} |".format(*fila)
for fila in datos)))
print ("\n")
print(" Resultados Item 3 ")
print (Tabla)
#Gráficos
plt.figure('Item 3')
plt.subplot(3,1,1)
plt.plot(x01,'#e52121')
plt.grid('both')
plt.title('Señal x01')
plt.xlabel('Muestras [n]')
plt.ylabel('Amplitud')
plt.subplot(3,1,2)
plt.plot(x1,'#604444')
plt.grid('both')
plt.title('Señal x1')
plt.xlabel('Muestras [n]')
plt.ylabel('Amplitud')
plt.subplot(3,1,3)
plt.plot(x3,'#e35d6a')
plt.title('Señal x3')
plt.xlabel('Muestras [n]')
plt.ylabel('Amplitud')
plt.grid('both')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/GUI.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 18:03:51 2020
@author: santi
"""
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialog,
QGridLayout, QGroupBox, QHBoxLayout, QLabel,
QPushButton, QRadioButton, QVBoxLayout,
QColorDialog)
from io import StringIO
import pandas as pd
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import urllib.request
import sys
class Covid(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.originalPalette = QApplication.palette()
QLabel("&Pais:")
self.dataBase()
self.createTop()
self.createBottomRight()
self.createCenterLeft()
self.createCenterRight()
self.createBottomLeft()
self.createBottomCenter()
mainLayout = QGridLayout()
mainLayout.addWidget(self.top, 0, 0, 1, 3)
mainLayout.addWidget(self.centerLeft, 1, 0)
mainLayout.addWidget(self.centerRight, 1, 1, 1,2)
mainLayout.addWidget(self.bottomLeft, 2, 0)
mainLayout.addWidget(self.bottomCenter, 2, 1)
mainLayout.addWidget(self.bottomRight, 2, 2)
self.setLayout(mainLayout)
self.setWindowTitle("Covid-19 Estadisticas")
self.bottomRight.setEnabled(False)
def closeEvent(self,event):
QApplication.quit()
def dataBase(self):
"""Carga la base de datos de casos confirmados, muertos y recuperados"""
url = """https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"""
confirmed = "time_series_covid19_confirmed_global.csv"
deaths = "time_series_covid19_deaths_global.csv"
recovered = "time_series_covid19_recovered_global.csv"
with urllib.request.urlopen(url+confirmed) as f:
data = f.read().decode('utf-8')
data = StringIO(data)
df = pd.read_csv(data)
df = df.drop(columns=['Province/State','Lat', 'Long'])
self.covid_data_confirmed = df.groupby('Country/Region').agg('sum')
with urllib.request.urlopen(url+deaths) as f:
data = f.read().decode('utf-8')
data = StringIO(data)
df = pd.read_csv(data)
df = df.drop(columns=['Province/State','Lat', 'Long'])
self.covid_data_deaths = df.groupby('Country/Region').agg('sum')
with urllib.request.urlopen(url+recovered) as f:
data = f.read().decode('utf-8')
data = StringIO(data)
df = pd.read_csv(data)
df = df.drop(columns = ['Province/State','Lat', 'Long'])
self.covid_data_recovered = df.groupby('Country/Region').agg('sum')
def createTop(self):
"""Crea el layout de arriba de todo"""
self.top = QGroupBox()
layout = QHBoxLayout()
self.total = QRadioButton("Totales")
self.daily = QRadioButton("Diarios")
self.total.setChecked(True)
self.country = QComboBox()
self.total.toggled.connect(self.graph)
self.country.addItem("Seleccione un país")
self.country.addItems(self.covid_data_confirmed.index.values)
self.country.currentTextChanged.connect(self.graph)
layout.addWidget(self.country, alignment = Qt.AlignLeft)
layout.addWidget(self.total, alignment = Qt.AlignCenter)
layout.addWidget(self.daily, alignment = Qt.AlignRight)
self.top.setLayout(layout)
def createCenterLeft(self):
self.centerLeft = QGroupBox("Opciones temporales")
layout = QVBoxLayout()
self.t_comienzo = QRadioButton("Desde el comienzo")
self.t_month = QRadioButton("Último mes")
self.t_week = QRadioButton("Última semana")
self.t_comienzo.setChecked(True)
self.avg = QCheckBox("Media movil 7 dias")
self.t_comienzo.toggled.connect(self.turnOn)
self.t_month.toggled.connect(self.turnOn)
self.t_week.toggled.connect(self.turnOn)
self.t_comienzo.toggled.connect(self.turnOff)
self.t_month.toggled.connect(self.turnOff)
self.t_week.toggled.connect(self.turnOff)
self.t_comienzo.toggled.connect(self.graph)
self.avg.toggled.connect(self.graph)
self.t_month.toggled.connect(self.graph)
self.t_week.toggled.connect(self.graph)
layout.addWidget(self.t_comienzo)
layout.addWidget(self.t_month)
layout.addWidget(self.t_week)
layout.addWidget(self.avg)
#layout.addStretch(1)
self.centerLeft.setLayout(layout)
def turnOff(self):
if self.t_comienzo.isChecked():
self.interpol.setChecked(True)
self.bottomRight.setEnabled(False)
if self.t_week.isChecked():
self.avg.setEnabled(False)
self.avg.setChecked(False)
def turnOn(self):
if self.t_comienzo.isChecked()==False:
self.bottomRight.setEnabled(True)
if self.t_week.isChecked()==False:
self.avg.setEnabled(True)
def createCenterRight(self):
self.centerRight = QGroupBox()
layout = QVBoxLayout()
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.sub = self.figure.add_subplot(111)
self.sub.plot()
self.sub.clear()
layout.addWidget(self.canvas)
self.centerRight.setLayout(layout)
def createBottomLeft(self):
self.bottomLeft = QGroupBox("Opciones de datos")
layout = QGridLayout()
self.cases = QCheckBox("Contagios")
self.deaths = QCheckBox("Muertos")
self.recovered = QCheckBox("Recuperados")
self.c_cases = QPushButton("")
self.c_cases.setStyleSheet("background-color: blue")
self.c_deaths = QPushButton("")
self.c_deaths.setStyleSheet("background-color: green")
self.c_recovered = QPushButton("")
self.c_recovered.setStyleSheet("background-color: violet")
self.c_cases.clicked.connect(self.color_confirmed)
self.c_deaths.clicked.connect(self.color_deaths)
self.c_recovered.clicked.connect(self.color_recovered)
self.cases.stateChanged.connect(self.graph)
self.deaths.stateChanged.connect(self.graph)
self.recovered.stateChanged.connect(self.graph)
self.all = QPushButton("Todos")
self.all.clicked.connect(self.todos)
self.cases.setChecked(True)
self.deaths.setChecked(False)
self.recovered.setChecked(False)
layout.addWidget(self.cases, 0, 0)
layout.addWidget(self.deaths, 1, 0)
layout.addWidget(self.recovered, 2, 0)
layout.addWidget(self.c_cases, 0, 1)
layout.addWidget(self.c_deaths, 1, 1)
layout.addWidget(self.c_recovered, 2, 1)
layout.addWidget(self.all)
self.bottomLeft.setLayout(layout)
def color_confirmed(self):
self.color_confirmed = QColorDialog.getColor()
self.c_cases.setStyleSheet("background-color:" + self.color_confirmed.name())
self.graph()
def color_deaths(self):
self.color_deaths = QColorDialog.getColor()
self.c_deaths.setStyleSheet("background-color:" + self.color_deaths.name())
self.graph()
def color_recovered(self):
self.color_recovered = QColorDialog.getColor()
self.c_recovered.setStyleSheet("background-color:" + self.color_recovered.name())
self.graph()
def createBottomCenter(self):
self.bottomCenter = QGroupBox("Group 3")
layout = QGridLayout()
self.lin = QRadioButton("Lineal")
self.log = QRadioButton("Logarítmico")
self.lin.setChecked(True)
self.lin.toggled.connect(self.graph)
layout.addWidget(self.lin)
layout.addWidget(self.log)
self.bottomCenter.setLayout(layout)
def createBottomRight(self):
self.bottomRight = QGroupBox("Group 4")
layout = QVBoxLayout()
self.interpol = QRadioButton("Interpolación")
self.bar = QRadioButton("Barra")
self.interpol.setChecked(True)
self.interpol.toggled.connect(self.graph)
layout.addWidget(self.interpol)
layout.addWidget(self.bar)
self.bottomRight.setLayout(layout)
def graph(self):
"""La funcion que se encarga del grafico"""
self.max = 0 #Para que se resetee el maximo, ya que habia un problema
#si pasabas de un pais con muchas muertes a uno con pocas
labeled = []
self.sub.clear()
if self.country.currentIndex()>0:
country = self.covid_data_confirmed.index.values[self.country.currentIndex()-1]
#El -1 esta para no contar el "seleccionar pais"
else:
#No hace nada
return
checked = [self.cases, self.recovered, self.deaths ]
label = ["Casos confirmados", "Recuperados", "Muertos"]
data = [self.covid_data_confirmed, self.covid_data_recovered, self.covid_data_deaths]
color = []
for colores, default in (
(self.color_confirmed, "b"), (self.color_recovered, "violet"), (self.color_deaths, 'g')):
try:
color.append(colores.name())
except:
color.append(default)
#Las siguientes lineas son los cambios si es lineal o log
if self.avg.isChecked():
avg = 7
else:
avg = 1
if self.lin.isChecked():
logY = False
mini = 0
else:
logY = True
mini = 1
#Las siguientes lineas cambian si es grafico de linea o de barra
if self.interpol.isChecked():
kind="line"
else:
kind="bar"
#Las siguientes lineas cambian segun el tiempo de inicio que está seleccionado
if self.t_comienzo.isChecked():
start = -len(self.covid_data_confirmed.columns)
elif self.t_month.isChecked():
start = -30
elif self.t_week.isChecked():
start = -8
for checked_i, data_i, color_i, label_i in zip(checked, data, color, label):
if checked_i.isChecked():
country_data = data_i[data_i.index.values == country]
if self.total.isChecked():
by_date = country_data.filter(like='/20').T
by_date = by_date.rolling(window=avg).mean()
by_date[start:-1].plot(ax=self.sub, color=color_i, logy=logY, label=label_i,
title="Covid 19 acumulativo en " + country, kind=kind, linewidth=2)
else:
by_date = country_data.filter(like='/20').T
#by_date.append(pd.Series(np.zeros(avg)),ignore_index=True)
by_date = by_date.rolling(window=avg).mean()
by_date = by_date.diff(axis=0)
by_date[start:-1].plot(ax=self.sub, color=color_i, logy=logY, label=label_i,
title="Covid 19 diario en " + country, kind=kind, linewidth=2)
if by_date[country].max() >= self.max:
self.max = by_date[country].max()
self.sub.set_ylim(mini, self.max)
labeled.append(label_i)
self.sub.legend(labeled)
#self.sub.grid()
self.canvas.draw()
def todos(self):
#El boton que acciona las 3 opciones
self.cases.setChecked(True)
self.deaths.setChecked(True)
self.recovered.setChecked(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
gallery = Covid()
gallery.show()
app.exec_()
<file_sep>/Scripts DSP 2020/FIR/MenuFIR.py
import os
import MenuWind as mw
'''
Función que limpia la pantalla y muestra nuevamente el menú
'''
def menu():
os.system('cls') # NOTA: para otro sistema operativo, cambiar 'cls' por 'clear'.
print("\t \tPROCESAMIENTO DIGITAL DE SEÑALES")
print ("\n")
print ("\t \t Seleccione una opción: ")
print ("\t \t \t 1 - Low Pass")
print ("\t \t \t 2 - High Pass")
print ("\t \t \t 3 - Band Pass")
print ("\t \t \t 4 - Band Stop")
print ("\t \t \t Q - Salir")
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 4) o Q para salir y presione ENTER >> ")
if opcionMenu=="1":
print ("")
mw.mw(1)
input("\n\t Item 1 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
mw.mw(2)
input("\n\t Item 2 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
mw.mw(3)
input("\n\t Item 3 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
mw.mw(4)
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu =="Q" or opcionMenu =="q":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item1.py
from FuncionesTP import *
señal,n,fs=senalTP() #defino funcion sen(2pi*f*n)
data = np.ones(1000)
lamedia1=lamedia(data)
desviomedio1=desviomedio(data,lamedia1)
desvioestandar1=desvioestandar(data,lamedia1)
rms1=rms(data)
#Reporte de resultados
print("El valor medio es: ",lamedia1)
print("El desvio medio es: ",desviomedio1)
print("El desvio estandar es: ",desvioestandar1)
print("El valor rms es: ", rms1)
print ("\n")
print("Resultados para la señal sinusoidal: ")
print ("\n")
lamediasin=lamedia(señal)
desviomediosin=desviomedio(señal,lamediasin)
desvioestandarsin=desvioestandar(señal,lamediasin)
rmssin=rms(señal)
print("El valor medio es: ",lamediasin)
print("El desvio medio es: ",desviomediosin)
print("El desvio estandar es: ",desvioestandarsin)
print("El valor rms es: ",rmssin)
<file_sep>/Scripts DSP 2020/paralastacuen.py
import scipy.signal as sp
b=[1,0.5]
a=[-0.5,]
coefs, polos, lineal = sp.residuez(b, a, 0.001)
print('Las fracciones simples son: ',coefs,polos,lineal)
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item5.py
from FuncionesTP import *
s1,n,fs=senalTP()
N = len(n)
M=1 # el valor de M es igual a el ingresado + 1
# Comparación de tiempos de ejecución de ambas funciones.
t = time.time() # Iniciar tiempo.
xfd=mediamovild(s1,M) # Ejecutar función.
tiempo_d = time.time()-t # Calcular tiempo de ejecucion total.
t = time.time() # Iniciar tiempo.
xfr= mediamovildr(s1,M) # Ejecutar función.
tiempo_r = time.time()-t # Calcular tiempo de ejecucion total.
#Reporte de resultados temporales
print("Resultados para la comparación de tiempos de ejecución: ")
print ("\n")
print(f"Directo: {round(tiempo_d,3)}, Recursiva: {round(tiempo_r,3)}")
#FFT's
FFTd=abs(np.fft.fft(xfd)) #Calcular la FFt para la señal filtrada con media movil directa
FFTr=abs(np.fft.fft(xfr)) #Idem recursiva
Maxlabel1=heapq.nlargest(2, FFTd) #Crear un vector de valores máximos de la señal FFTd
Maxlabel1=int(Maxlabel1[1]) #Almacenar el valor maximo en una variable
Maxlabel2=heapq.nlargest(2, FFTr) #Idem recursiva
Maxlabel2=int(Maxlabel2[1])
#Gráficos
f = np.arange(0,fs/2,(fs/2)/int(N/2)) #Crear un vector de muestras para graficar con relacion a la Frecuencia de sampleo
t = np.arange(0,N)
sp1=plt.figure('Item 5 comparación de filtrados')
plt.subplot(3,1,1)
plt.plot(t[0:round(N/64)],s1[0:round(N/64)],'#738EB6') #Gráfico de la señal del punto uno
plt.title('Señal antes de filtrar')
plt.grid('both')
plt.ylabel('Señal x[n]')
plt.xlabel('Número de muestra [n]')
sp1=plt.subplot(3,1,2)
plt.plot(t[0:round(N/64)],xfd[0:round(N/64)],'#BF76D2') #Grafico de la señal filtrada con la media movil directa
plt.title('Filtrado de media movil directa')
plt.grid('both')
plt.ylabel('Señal x[n]')
plt.xlabel('Número de muestra [n]')
sp1=plt.subplot(3,1,3)
plt.plot(t[0:round(N/64)],xfr[0:round(N/64)],'#e0503f') #Grafico de la señal filtrada con la media movil recursiva
plt.title('Filtrado de media movil recursiva')
plt.grid('both')
plt.ylabel('Señal x[n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1)
sp2=plt.figure('Item 5 comparación de filtrados con FFT')
plt.subplot(2,1,1)
plt.plot(f,FFTd[0:int(N/2)],'#FF4646') #Grafico en frecuencia de la señal filtrada con la media movil directa
plt.title('Filtro de media movil directa')
plt.grid('both')
plt.ylabel('Señal X[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp1, f"{round(Maxlabel1)}",xy=(10100,Maxlabel1-1100))
sp2=plt.subplot(2,1,2)
plt.plot(f,FFTr[0:int(N/2)],'#327345') #Grafico en frecuencia de la señal filtrada con la media movil recursiva
plt.grid('both')
plt.ylabel('Señal X[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel2)}",xy=(10100,Maxlabel2-1100))
plt.title('Filtro de media movil recursiva')
plt.subplots_adjust(hspace = 0.6)
plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1/FuncionesTP.py
import matplotlib.pyplot as plt
import numpy as np
import math
import heapq
import time
import soundfile as sf
from scipy import signal
'''
En el presente módulo se importan las librerías y se definen las variales globales y las funciones que se necesiten en distintos items.
'''
'''Definición de Variables Globales'''
#Definición de señal de entrada x[n]=data de longitud N=1000.
data=np.ones(1000)
#Definición de la señal senoidal x(t)= 2 + sen(2πft). (Varios Items)
frec=10000
fs = 44100
duración = 0.5
t=np.arange(0,duración,1/fs) #vector de muestras
señal=2 + np.sin(2*np.pi*frec*t) #defino funcion sen(2pi*f*t)
#Importación de Archivos .wav (Item 8 y 11).
[RIR,Fs] = sf.read("RIR.wav")
[Midi69,Fs1] = sf.read("Midi69.wav")
nMidi=np.arange(0,len(Midi69))
nRIR=np.arange(0,len(RIR))
''' Definimos las funciones que se utilizan. '''
def senalTP():
f=10000
fs = 44100
t = 0.5
n=np.arange(0,t,1/fs) #vector de muestras
señal=2 + np.sin(2*np.pi*f*n) #defino funcion sen(2pi*f*t)
return señal,n,fs
def lamedia(input):
mu=np.sum(input)/(len(input)) #Defino la función del calculo de media
return mu
def desviomedio(input,media):
d=np.sum(abs(input-media))/(len(input)) #Defino la función del cálculo del desvío medio
return d
def desvioestandar(input,media):
sigma=((np.sum(abs(input-media)**2))/(len(input)))**(1/2) #Defino la función del cálculo del desvío estándar
return sigma
def rms(input):
rms=((np.sum(abs(input**2)))/(len(input)))**(1/2) #Defino la función del cálculo de RMS
return rms
#Generar ruido
def normalizar(input):
media=lamedia(input)
desviacion=desvioestandar(input,media)
for i in range(len(input)):
input[i]=(input[i]-media)/desviacion
return input
#Relación señal ruido
def SNR(señal,ruido):
media=lamedia(señal)
sigmanoise=desvioestandar(ruido,lamedia(ruido))
SNR=np.max(señal)/sigmanoise
return SNR , sigmanoise
def senales_con_ruido(senal,mu,sigma,N):
# Genera señales con ruido, hace el promedio en ensamble y devuelve el SNR de la señal promediada y el sigma de los ruidos promedios.
ruidos=np.zeros(len(senal))
senales_ruido=np.zeros(len(senal))
for i in range(0,N):
ruido=np.random.normal(mu, sigma, len(senal))
senales_ruido=senal+ruido+senales_ruido
ruidos=ruidos+ruido
promsenal=senales_ruido*(1/N)
promruido=ruidos*(1/N)
sigma=desvioestandar(promruido,lamedia(promruido))
SNR=np.max(promsenal)/sigma
# SNR,sigmanoise = SNR(promsenal,promruido)
return SNR, sigma
def mediamovild(x,M):
#Asiganciones de espacios en memoria
y=np.zeros(len(x))
aux=np.append(x,np.zeros(M))
#Media movil directa
for i in range(len(x)):
for j in range(0,M+1):
y[i]=y[i]+aux[i+j]
y[i]=y[i]*(1/(M+1))
return y
def mediamovildr(x,M):
#Asiganciones de espacios en memoria
y=np.zeros(len(x))
y[0]=(1/(M+1))*np.sum(x[:M+1])
aux=np.append(x,np.zeros(M))
#Media movil recursiva
for i in range(1,len(x)):
y[i]=y[i-1]+(1/(M+1))*aux[i+M]-(1/(M+1))*aux[i-1]
return y
#Ventana Blackman
def wBlackman(M):
a0=(7935/18608)
a1=(9240/18608)
a2=(1430/18608)
m=np.linspace(0,M-1,M)
blackman=a0 - ((a1)*np.cos((2*np.pi*m)/(M))) + ((a2)*np.cos((4*np.pi*m)/(M)))
return blackman
def Importar_Audio(file,señal):
[señal,Fs] = sf.read(file)
n=np.arange(0,len(señal))
return señal,Fs,n
def convCircular(x1,nx1,x2,nx2):
nny = np.arange(0,len(nx1)+len(nx2)-1)
ny = np.arange(0,len(x1)+len(x2)-1) + nx1[0] + nx2[0]
y = np.convolve(x1, x2)
return y[nny], ny
def cConv(x1,nx1,x2,nx2,l):
if l==1:
nny = np.arange(0,len(x1))
ny = np.arange(0,len(x1)) + nx1[0] + nx2[0]
elif l==2:
nny = np.arange(0,len(x2))
ny = np.arange(0,len(x2)) + nx1[0] + nx2[0]
y = np.convolve(x1, x2)
return y[nny], ny
def RF_boxcar(M,f):
RF_rectang=(np.exp(-1j*((M-1)*f)/2))*(np.sin(f*M/2)/np.sin(f/2))
return RF_rectang
def RF_Blackman(T,f):
a0=(7935/18608)
a1=(9240/18608)
a2=(1430/18608)
H0=(np.sin(f*T/2)/np.sin(f/2))
H1=(np.exp(-1j*(np.pi)/T)*(np.sin((T*f/2)-np.pi)/np.sin((f-(2*np.pi/T))/2)))+((np.exp(1j*(np.pi)/T))*(np.sin((f+(2*np.pi/T))*T/2)/np.sin((f+(2*np.pi/T))/2)))
H2=(np.exp(1j*(2*np.pi)/T)*(np.sin((f-(4*np.pi/T))*T/2)/np.sin((f-(4*np.pi/T))/2)))+(np.exp(1j*(2*np.pi)/T)*(np.sin((f+(4*np.pi/T))*T/2)/np.sin((f+(4*np.pi/T))/2)))
RF_blackman=(np.exp(-1j*((T-1)*f)/2))*((a0*H0)-((a1/2)*H1)+((a2/2)*H2))
return RF_blackman
def RFdB_ventanas(RF,T):
resp =RF/(T/2.0)
respN = np.abs(resp/abs(resp).max())
RFdB = 20 * np.log10(np.maximum(respN, 1e-10))
return RFdB
def FFT_convLineal(x1,x2):
y=signal.signaltools.fftconvolve(x1,x2)
return y
def FFT_convCircular(x1,nx1,x2,nx2):
nny = np.arange(0,len(nx1)+len(nx2)-1)
ny = np.arange(0,len(x1)+len(x2)-1) + nx1[0] + nx2[0]
y = signal.signaltools.fftconvolve(x1, x2)
return y[nny], ny
def FFT_cConv(x1,nx1,x2,nx2,l):
if l==1:
nny = np.arange(0,len(x1))
ny = np.arange(0,len(x1)) + nx1[0] + nx2[0]
elif l==2:
nny = np.arange(0,len(x2))
ny = np.arange(0,len(x2)) + nx1[0] + nx2[0]
y = signal.signaltools.fftconvolve(x1, x2)
return y[nny], ny
<file_sep>/Scripts DSP 2020/scripts varios/quelopario.py
import matplotlib.pyplot as plt
import numpy as np
import math
import heapq
import time
import soundfile as sf
from convolucion import *
from scipy import signal
'''Ejercicio 8 '''
'''
revisar aca la convolucion
'''
[RIR,Fs] = sf.read("RIR.wav")
[Midi69,Fs1] = sf.read("Midi69.wav")
L=len(Midi69)
K=len(RIR)
cLineal=np.convolve(Midi69,RIR)
cCirc=np.convolve(Midi69[:K],RIR)
cCircular=convCirc(Midi69,RIR)
cLineal=np.real(cLineal)
cCirc=np.real(cCirc)
cCircular=np.real(cCircular)
sf.write('cLinealout.wav', cLineal, Fs)
sf.write('cCircout.wav', cCirc, Fs)
sf.write('cCircularout.wav', cCircular, Fs)
figure,axis = plt.subplots(3)
axis[0].plot(cLineal)
axis[1].plot(cCircular)
axis[2].plot(cCirc)
plt.show()
<file_sep>/Scripts DSP 2020/TP1-LIONTI-VILLATARCO/Exe/dist/Items/Item4.py
from FuncionesTP import *
'''En este inciso se generan señales a partir de ir añadiendo distintos ruidos a la señal original del Item 1 x[n]=data y realizar un promedio en ensamble de las mismas. Las señales se calculan a partir del promediado de 10, 100 y 1000 señalesde ruido diferentes.
'''
# Se generan las 10 señales de ruido aleatorio con media 0 y sigma 3
z31 = np.random.normal(0, 3, len(data))
z32 = np.random.normal(0, 3, len(data))
z33 = np.random.normal(0, 3, len(data))
z34 = np.random.normal(0, 3, len(data))
z35 = np.random.normal(0, 3, len(data))
z36 = np.random.normal(0, 3, len(data))
z37 = np.random.normal(0, 3, len(data))
z38 = np.random.normal(0, 3, len(data))
z39 = np.random.normal(0, 3, len(data))
z310 = np.random.normal(0, 3, len(data))
# Genero cada señal sumando la señal de entrada y un ruido
x31 = data + z31
x32 = data + z32
x33 = data + z33
x34 = data + z34
x35 = data + z35
x36 = data + z36
x37 = data + z37
x38 = data + z38
x39 = data + z39
x310 = data + z310
# Saco una señal de ruido promedio de las 10 señales de ruido generadas (solo ruido)
ruidoProm=(1/10)*(z31+z32+z33+z34+z35+z36+z37+z38+z39+z310)
#Promedio de las señales con ruido agregado
Señalprom=(1/10)*(x31+x32+x33+x34+x35+x36+x37+x38+x39+x310)
SNRprom , sigmanoise=calc_SNR(Señalprom,ruidoProm) #Calculo el SNR de la señal promedio con los valores obtenidos y saco el sigma de la señal de ruido promedio.
#Calculamos los SNR y los sigmas para las señales con promedio en ensamble para 1, 10, 100 y 1000 señales de ruido. La función senales_con_ruido automatiza el calculo y está definida en FuncionesTP, esta se usará para presentar los resultados.
SNR1,sigmaruido1=senales_con_ruido(data,0,3,1)
SNR10,sigmaruido10=senales_con_ruido(data,0,3,10)
SNR100,sigmaruido100=senales_con_ruido(data,0,3,100)
SNR1000,sigmaruido1000=senales_con_ruido(data,0,3,1000)
# Se prensentan los resultados
datos=[[1,round(SNR1,2),round(sigmaruido1,2)],[10,round(SNR10,2),round(sigmaruido10,2)], [100,round(SNR100,2),round(sigmaruido100,2)], [1000,round(SNR1000,2),round(sigmaruido1000,2)]]
Tabla = """\
+--------------------------------------------+
|N° Señales promediadas | SNR | σ |
|--------------------------------------------|
{}
+--------------------------------------------+\
"""
Tabla = (Tabla.format('\n \t'.join("| {:>21d} | {:>8} | {:>7} |".format(*fila)
for fila in datos)))
print(" \t \t Resultados obtenidos Item 4 ")
print (Tabla)
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item9.py
from FuncionesTP import *
''' En este inciso se grafica la respuesta en frecuencia del filtro media móvil con una resolución de 44100 Hz. Cabe señalar que el largo de la ventana obtenido en el Item 5 corresponde a M+1=2.
'''
M=1 #El largo de la ventana es L=M+1.
w=np.arange(-1*np.pi,np.pi,2*np.pi/44100) #Se genera un vector de muestras con frecuencia de sampleo de 44100 Hz.
H=abs((1/(M+1))*((np.sin(w*(M+1)/2))/(np.sin(w/2)))) #Respuesta en frecuencia del filtro media móvil.
# Se Grafican los resultados.
plt.figure('Item 9 Grafico de magnitud para respuesta del filtro')
plt.plot(w,H)
# Gráfico de magnitud de respuesta en frecuencia del filtro media móvil.
plt.title('Respuesta en frecuencia')
plt.xlabel('Frecuencia angular ω [rad/s]')
plt.ylabel('Respuesta H[ω]')
plt.show()
<file_sep>/Scripts DSP 2020/scripts varios/FuncionesTP.py
import matplotlib.pyplot as plt
import numpy as np
import math
import heapq
import time
import soundfile as sf
from scipy import signal
''' Definimos las funciones que se utilizan en el programa. '''
def senalTP():
f=10000
fs = 44100
t = 0.5
n=np.arange(0,t,1/fs) #vector de muestras
señal=2 + np.sin(2*np.pi*f*n) #defino funcion sen(2pi*f*t)
return señal,n,fs
def lamedia(input):
mu=np.sum(input)/(len(input))
return mu
def desviomedio(input,media):
d=np.sum(abs(input-media))/(len(input))
return d
def desvioestandar(input,media):
sigma=((np.sum(abs(input-media)**2))/(len(input)))**(1/2)
return sigma
def rms(input):
rms=((np.sum(abs(input**2)))/(len(input)))**(1/2)
return rms
#Generar ruido
def normalizar(input):
media=lamedia(input)
desviacion=desvioestandar(input,media)
for i in range(len(input)):
input[i]=(input[i]-media)/desviacion
return input
def SNR(señal,ruido):
media=lamedia(señal)
sigmanoise=desvioestandar(ruido,lamedia(ruido))
SNR=media/sigmanoise
return SNR
''' Genera señales con ruido, hace el promedio en ensamble y devuelve el SNR de la señal promediada y el sigma de los ruidos promedios. '''
def senales_con_ruido(senal,mu,sigma,N):
ruidos=np.zeros(len(senal))
senales_ruido=np.zeros(len(senal))
for i in range(0,N):
ruido=np.random.normal(mu, sigma, len(senal))
senales_ruido=senal+ruido+senales_ruido
ruidos=ruidos+ruido
promsenal=senales_ruido*(1/N)
promruido=ruidos*(1/N)
media=lamedia(promsenal)
sigma=desvioestandar(promruido,lamedia(promruido))
SNR=media/sigma
return SNR, sigma
def mediamovild(x,M):
y=np.zeros(len(x))
aux=np.append(x,np.zeros(M))
for i in range(len(x)):
for j in range(0,M+1):
y[i]=y[i]+aux[i+j]
y[i]=y[i]*(1/(M+1))
return y
def mediamovildr(x,M):
y=np.zeros(len(x))
y[0]=(1/(M+1))*np.sum(x[:M+1])
aux=np.append(x,np.zeros(M))
for i in range(1,len(x)):
y[i]=y[i-1]+(1/(M+1))*aux[i+M]-(1/(M+1))*aux[i-1]
return y
# def plotear(**kwargs):
# figure,axis = plt.subplots(3)
# axis[0].plot(cLineal)
# axis[1].plot(cCircular)
# axis[2].plot(cCirc)
# plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/insertadordesceroschoto.py
import numpy as np
a=[1,2,3,5,6,7,4,2]
def intercaladordeceros(a,c):
k=len(a)
for i in range(0,k-1):
d=np.insert(0,a,i)
return d
d=intercaladordeceros(a,3)
print("d",d)
<file_sep>/Scripts DSP 2020/Scripts TP2/elhcqueando.py
from Funcionestp2 import *
eps=0.001
fs=44100
T=1/fs
n_samples=fs*2
pa=1/2
f1=10
f2=250
f3=500
f4=1000
f5=5000
p1=fs/f1
N= int(np.floor(p1 -pa-eps))
a1=2*(abs(np.cos(2*np.pi*f1)+1))**-1
# a2=2*(abs(np.cos(2*np.pi*f2)+1))**-1
# a3=2*(abs(np.cos(2*np.pi*f3)+1))**-1
# a4=2*(abs(np.cos(2*np.pi*f4)+1))**-1
# a5=2*(abs(np.cos(2*np.pi*f5)+1))**-1
def delayhc(senal,d,a,N):
# d=int(round(t*fs))
delay=np.zeros((N,len(senal)+(N*d)))
x=np.append(senal,np.zeros(N*d))
y=np.zeros_like(x)
dly=np.zeros_like(x)
for i in range(0,N):
D=(i+1)*d
zpad=np.zeros(D)
aux=np.append(zpad,senal)
delay[i]=np.append(aux,np.zeros(len(x)-len(aux)))
dly=delay[i]+dly #x[n-D]
y=a*(x+dly)
return y
cuerda=karplus_strong(n_samples,1,N)
z1=delayhc(cuerda,2,a1,N)
# z2=delayhc(cuerda,2,a2,N)
# z3=delayhc(cuerda,2,a3,N)
# z4=delayhc(cuerda,2,a4,N)
# z5=delayhc(cuerda,2,a5,N)
sf.write('cuerdac.wav',cuerda,fs)
sf.write('Hc1.wav',z1,fs)
# sf.write('Hc2.wav',z2,fs)
# sf.write('Hc3.wav',z3,fs)
# sf.write('Hc4.wav',z4,fs)
# sf.write('Hc5.wav',z5,fs)
fftz1=np.fft.fft(z1)
# fftz2=np.fft.fft(z2)
fdB=20*np.log10(abs(z1))
fase1=np.angle(fftz1)
# fase2=np.angle(fftz2)
# plt.plot(fdB[0:2500])
plt.subplot(2,1,1)
plt.plot(cuerda,'#738EB6')
plt.title('Señal generada por la cuerda')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(2,1,2)
plt.plot(fdB,'#BF76D2')
plt.title('El deca papa')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/FIR/LowPass.py
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from Func import *
''' Diseña un filtro pasa bajos FIR de fase lineal generalizada para distintas tipos de ventanas'''
def LP_fir(Ap,As,wp,ws,FS,id_window):
''' Datos'''
Gp=20*np.log10(Ap)
Gs=20*np.log10(As)
wc=(wp+ws)/2
deltaw=round(ws-wp,3)
hfir=[]
n=[]
M=0
tipo="Ventana"
if id_window==1:#Rectangular
M=int(4/deltaw)-1
h,n=iLP(M,wc)
wind=signal.windows.boxcar(M+1)
hfir=h*wind
tipo="Rectangular"
elif id_window==2:#Barlett
M=int(8/deltaw)
h,n=iLP(M,wc)
wind=signal.windows.bartlett(M+1)
hfir=h*wind
tipo="Barlett"
elif id_window==3:#Hanning
M=int(8/deltaw)
h,n=iLP(M,wc)
wind=signal.windows.hann(M+1)
hfir=h*wind
tipo="Hanning"
elif id_window==4:#Hamming
M=int(8/deltaw)
h,n=iLP(M,wc)
wind=signal.windows.hamming(M+1)
hfir=h*wind
tipo="Hamming"
elif id_window==5:#Blackman
M=int(12/deltaw)
h,n=iLP(M,wc)
wind=signal.windows.blackman(M+1)
hfir=h*wind
tipo="Blackman"
elif id_window==6:#Kaiser
A=-Gs
M=Kaiser_M(A,deltaw)
beta=beta_K(A)
h,n=iLP(M,wc)
wind=signal.windows.kaiser(M+1,beta)
hfir=h*wind
tipo=f"Kaiser(beta={round(beta,5)})"
else: print("Opción incorrecta, ingresa entre 1 y 6.")
'''Resultados'''
HFIL=np.fft.fft(hfir,FS)
faseFIL=np.angle(HFIL)
HFIR=20*np.log10(abs(HFIL))
freq=np.arange(0,1,1/int(FS/2))
iwp=np.where(np.float64(freq)==wp)
iws=np.where(np.float64(freq)==ws)
print(f"Ventana: {tipo}, M={M}, wc={wc}, deltaw={deltaw}")
print(f"Gp={HFIR[iwp]}")
print(f"Gs={HFIR[iws]}")
'''Graficos'''
plt.figure()
plt.subplot(311)
plt.plot(freq,HFIR[0:int(FS/2)],'b')
plt.xlabel('w')
plt.ylabel('|H(jw)|')
plt.subplot(312)
plt.plot(freq,faseFIL[0:int(FS/2)],'r')
plt.xlabel('w')
plt.ylabel('<H(jw')
plt.subplot(313)
plt.plot(freq,(M/2)*np.ones(len(freq)),'g')
plt.xlabel('w')
plt.ylabel('RG(H(jw))')
plt.axis([0,1,(M/2)-0.5,(M/2)+0.5])
plt.subplots_adjust(hspace = 0.9)
plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1final/TP1/Items/Item1.py
from FuncionesTP import *
''' Las funciones para calcular el valor medio, el desvío medio, desvío estandar y el valor rms, pedidos en la consigna, se encuentran definidas en el módulo FuncionesTP. En este script se implementan dichas funciones para calcular los parámetros pedidos para la señal finita x[n]=data de largo N=1000 y la señal senoidal x(t)= 2 + sen(2πft), ambas definidas en el mismo módulo.
'''
#Se calculan los parámetros de la señal data, pedidos en la consigna.
lamedia1=lamedia(data)
desviomedio1=desviomedio(data,lamedia1)
desvioestandar1=desvioestandar(data,lamedia1)
rms1=rms(data)
# Se presentan los resultados.
print ("\n")
print("Resultados Item 1: ")
print ("\n")
print("Resultados para la señal x[n]=u[n] de largo N=1000: ")
print("El valor medio es: ",lamedia1)
print("El desvio medio es: ",desviomedio1)
print("El desvio estandar es: ",desvioestandar1)
print("El valor rms es: ", rms1)
# Se calculan los parámetros de la señal senoidal x(t)= 2 + sen(2πft).
lamediasin=lamedia(señal)
desviomediosin=desviomedio(señal,lamediasin)
desvioestandarsin=desvioestandar(señal,lamediasin)
rmssin=rms(señal)
#Se presentan los resultados.
print ("\n")
print("Resultados para la señal sinusoidal x(t)= 2 + sen(2πft): ")
print("El valor medio es: ",round(lamediasin,3))
print("El desvio medio es: ",round(desviomediosin,3))
print("El desvio estandar es: ",round(desvioestandarsin,3))
print("El valor rms es: ",round(rmssin,3))
<file_sep>/Scripts DSP 2020/scripts varios/conv_circular.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 20:13:56 2020
@author: guillem
"""
import numpy as np
def circular_convolve(in1, in2, period):
"""
Circular convolution of two 1-dimensional arrays.
Circular convolve `in1` and `in2` with given `period`.
Parameters
----------
in1 : array_like, 1-D
First input.
in2 : array_like, 1-D
Second input. Should have the same number of dimensions as `in1`.
period : int
Period of the circular convolution.
Returns
-------
result : array, 1-D
A 1-dimensional array containing the result of the circular
convolution of `in1` with `in2`.
See Also
--------
convolve
Notes
-----
The (modulo-M) circular/cyclic/periodic convolution of period :math:`M`
of the two signals :math:`x[k]` and :math:`h[k]` is defined as
.. math::
y[k] = \sum_{\kappa=0}^{M-1} \tilde{x}[k - \kappa] \; \tilde{h}[\kappa]
where the periodic summations :math:`\tilde{x}[k]` and `\tilde{h}[\kappa]`
of :math:`x[k]` and :math:`x[k]` are defined as
.. math::
\tilde{x}[k] &= \sum_{m = -\infty}^{\infty} x[m \cdot M + k] \\
\tilde{h}[k] &= \sum_{m = -\infty}^{\infty} h[m \cdot M + k]
Examples
--------
Equivalence of circular and linear convolution:
>>> from scipy import signal
>>> a = np.ones(5)
>>> b = np.ones(5)
>>> circular_convolve(a, b, 5)
array([ 5., 5., 5., 5., 5.])
>>> np.convolve(a, b, mode='full')
array([ 1., 2., 3., 4., 5., 4., 3., 2., 1.])
>>> circular_convolve(a, b, 9)
array([ 1., 2., 3., 4., 5., 4., 3., 2., 1.])
"""
in1 = _periodic_summation(in1, period)
in2 = _periodic_summation(in2, period)
return np.fromiter([np.dot(np.roll(in1[::-1], k+1), in2)
for k in np.arange(period)], float)
def _periodic_summation(x, period):
"""
Periodic summation of 1-dimensional array or zero-padding.
If the length of the array is longer or equal to the given `period`
a periodic summation of `x` is perfomed, otherwise zero-padding to length
`period`.
"""
len_x = len(x)
rows = int(np.ceil(len_x/period))
if (len_x < int(period*rows)):
x = np.pad(x, (0, int(period*rows-len_x)), 'constant')
x = np.reshape(x, (rows, period))
return np.sum(x, axis=0)
<file_sep>/Scripts DSP 2020/scripts varios/testies2.py
import matplotlib.pyplot as plt
import numpy as np
import math
import heapq
import time
import pandas as pd
import soundfile as sf
from convolucion import *
from scipy import signal
# mu = 3
# variance = 2
# sigma = math.sqrt(variance)
# x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
# plt.plot(x, stats.norm.pdf(x, mu, sigma))
# plt.show()
# def mediamovild(x,M,defas):
# # for i in range(len(x)):
# cumsum = np.cumsum(np.insert(x,M,defas))
# salida = (cumsum[M:]- cumsum[:-M])/float(M)
# # salida[i]=np.cumsum(M)
# return salida
# # return cumsum / float(M)
# mmd=mediamovild(data,3,3)
def mediamovild(x,M):
# y=np.zeros(len(x))
# aux=np.append(x,np.zeros(M))
df=pd.DataFrame(x)
y = df.rolling(M,min_periods=1,center=False,win_type='boxcar').mean()
# for i in range(len(x)):
# for j in range(0,M+1):
# y[i]=y[i]+aux[i+j]
# y[i]=y[i]*(1/(M+1))
return y
# xfd=mediamovild(data,50)
# print("La media movil es: ",xfd)
def mediamovildr(x,M):
y=np.zeros(len(x))
y[0]=(1/(M+1))*np.sum(x[:M+1])
aux=np.append(x,np.zeros(M))
for i in range(1,len(x)):
y[i]=y[i-1]+(1/(M+1))*aux[i+M]-(1/(M+1))*aux[i-1]
return y
#xfr=mediamovildr(data,50)
#
# print("mmd recursiva: ", xfr)
# F = 10000
#
# T = 1/F
#
# Fs = 44100
#
# Ts = 1/Fs
#
# t = np.arange(0,0.5*T,Ts)
#
# señal = 2 + np.sin(2*np.pi*F*t)
#
# señalfft = np.fft.fft(señal)
#
# print("fft: ",señalfft)
#
# plt.plot(t,señalfft)
#
# plt.show()
fs = 44100
t = 0.5
n=np.arange(0,t,1/fs) #vector de muestras
N = len(n)
x=2 + np.sin(2*np.pi*10000*n) #defino funcion sen(2pi*f*t)
X=np.fft.fft(x) #calculo de la dft
Xr=np.fft.rfft(x)
Xmax=max(X)
# cont=0
# while X>=10000:
# cont=cont+1
# maximos[cont]=X[cont]
X1=abs(X) #tomo el modulo
w0=10000*np.pi/22050
M=2
w=np.arange(-1*np.pi,np.pi,2*np.pi/22050)
H=abs((1/(M+1))*((np.sin(w*(M+1)/2))/(np.sin(w/2))))
# Comparación de tiempos de ejecución de ambas funciones.
t = time.time() # Iniciar tiempo.
xfd=mediamovild(x,M) # Ejecutar función.
xfd = np.reshape(xfd,len(xfd))
# for i in range(0, len(xfd)):
#
# xfd[i] = int(xfd[i])
tiempo_d = time.time()-t # Calcular tiempo de ejecucion total.
print(xfd)
#
# t = time.time() # Iniciar tiempo.
# xfr= mediamovildr(x,M) # Ejecutar función.
# tiempo_r = time.time()-t # Calcular tiempo de ejecucion total.
#
# print(f"Directo: {round(tiempo_d,3)}, Recursiva: {round(tiempo_r,3)}")
# tucardo=heapq.nlargest(5,X1)
# FFTd=abs(np.fft.fft(xfd))
# tuco=heapq.nlargest(5,FFTd)
# FFTr=abs(np.fft.fft(xfr))
# ventanilla=signal.windows.boxcar(M+1)/(M+1)
# xfc=np.convolve(x,ventanilla)
# FFTc=abs(np.fft.fft(xfc))
# print("maximos de conv",heapq.nlargest(5,FFTc) )
# print("largo", len(xfc))
# tuco1=heapq.nlargest(5,FFTr)
# print(tuco)
# print(tuco1)
# print(tucardo)
# f = np.arange(0,fs/2,(fs/2)/int(N/2))
# plt.figure(1)
# plt.plot(f,X1[0:int(N/2)])
# plt.show()
#
# # '''Ejercicio 6'''
# # M=int(0.01*len(x))
# # ri_MM=np.ones(M+1)/(M+1)
# # xMM=np.convolve(x,ri_MM)
# # FFT_MM=abs(np.fft.fft(xMM))
# # tuco2=heapq.nlargest(5,FFT_MM)
# # print(tuco2)
# # f = np.arange(0,fs/2,(fs/2)/int(N/2))
# # ''' Aca viene todo el mambo de la normalización que nose como hacer '''
# # xfd_norm=xfd/np.linalg.linalg.norm(xfd)
# # xfr_norm=xfr/np.linalg.linalg.norm(xfr)
# # xMM_norm=xMM/np.linalg.linalg.norm(xMM)
# # print(np.linalg.linalg.norm(xfd))
# # # figure,axis = plt.subplots(3)
# # # axis[0].plot(xfd_norm[0:M])
# # # axis[1].plot(xfr_norm[0:M])
# # # axis[2].plot(xMM_norm[200:M])
# # # plt.show()
# #
# # '''Ejercicio 7'''
# # m=np.arange(M-1)
# # blackman=0.42 - ((0.5)*np.cos((2*np.pi*m)/(M-1))) + ((0.08)*np.cos((4*np.pi*m)/(M-1)))
# #
# # xBlack=np.convolve(x,blackman)
# # print(len(xBlack))
# # # figure,axis = plt.subplots(3)
# # # axis[0].plot(xfd_norm[0:M])
# # # axis[1].plot(xfr_norm[0:M])
# # # axis[2].plot(xBlack[0:M])
# # # plt.show()
# #
# # '''Ejercicio 8 '''
# #
# # [RIR,Fs] = sf.read("RIR.wav")
# # [Midi69,Fs1] = sf.read("Midi69.wav")
# # L=len(Midi69)
# # K=len(RIR)
# # cLineal=np.convolve(Midi69,RIR)
# # cCirc=np.convolve(Midi69[:K],RIR)
# # cCircular=convCirc(Midi69,RIR)
# #
# # figure,axis = plt.subplots(3)
# # axis[0].plot(cLineal)
# # axis[1].plot(cCircular)
# # axis[2].plot(cCirc)
# # plt.show()
# #
# # '''Ejercicio 9 '''
# # plt.figure(1)
# # plt.plot(w,H)
# # plt.show()
# #
# # '''Ejercicio 10'''
# # T=1000
# # f= np.linspace(-1*np.pi,np.pi,T)
# # rect=signal.windows.boxcar(T)
# # black2=np.blackman(T)
# # # RF_rectang=abs(np.sin(f*T/2)/np.sin(f/2))
# # RF_rectang=abs(np.fft.fft(rect))/(len(rect)/2)
# # RF_blackman=abs(np.fft.fft(black2))/(len(rect)/2)
# # RFdB_r=np.clip(20*np.log10(np.fft.fftshift(RF_rectang)),-100,100)
# # RFdB_B=np.clip(20*np.log10(np.fft.fftshift(RF_blackman)),-100,100)
# # plt.figure(1)
# # # plt.plot(f,RFdB_B)
# # # plt.plot(f,RFdB_r)
# # plt.grid()
# # plt.plot(f,RFdB_B,'g')
# # plt.plot(f,RFdB_r,'b')
# # plt.show()
# #
# # '''Ejercicio 11'''
# # cLineal_fft=convLin(Midi69,RIR)
# # cCirc=convLin(Midi69[:K],RIR)
# # cCircular=convCirc(Midi69,RIR)
# # figure,axis = plt.subplots(3)
# # axis[0].plot(cLineal)
# # axis[1].plot(cCircular)
# # axis[2].plot(cCirc)
# # plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1/Menu.py
import os
print("PROCESAMIENTO DE SEÑALES DIGITALES")
print ("\n")
print("TRABAJO PRÁCTICO 1: PROGRAMACIÓN BÁSICA")
print ("\n")
def menu():
"""
Función que limpia la pantalla y muestra nuevamente el menu
"""
os.system('cls') # NOTA para windows tienes que cambiar clear por cls
print ("Seleccioná un item para ejecutar")
print ("\t1 - Item 1")
print ("\t2 - Item 2")
print ("\t3 - Item 3")
print ("\t4 - Item 4")
print ("\t5 - Item 5")
print ("\t6 - Item 6")
print ("\t7 - Item 7")
print ("\t8 - Item 8")
print ("\t9 - Item 9")
print ("\t10 - Item 10")
print ("\t11 - Item 11")
print ("\t12 - Salir")
while True:
# Mostramos el menu
menu()
# solicituamos una opción al usuario
opcionMenu = input("inserta un numero valor >> ")
if opcionMenu=="1":
print ("")
os.system("Item1.py")
input("Item 1 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="2":
print ("")
os.system("Item2.py")
input("Item 2 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="3":
print ("")
os.system("Item3.py")
input("Item 3 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="4":
print ("")
os.system("Item4.py")
input("Item 4 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="5":
print ("")
os.system("Item5.py")
input("Item 5 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="6":
print ("")
os.system("Item6.py")
input("Item 6 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="7":
print ("")
os.system("Item7.py")
input("Item 7 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="8":
print ("")
os.system("Item8.py")
input("Item 8 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="9":
print ("")
os.system("Item9.py")
input("Item 9 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="10":
print ("")
os.system("Item10.py")
input("Item 10 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="11":
print ("")
os.system("Item11.py")
input("Item 11 ejecutado...\npulsa una tecla para continuar")
elif opcionMenu=="12":
break
else:
print ("")
input("No has pulsado ninguna opción correcta...\npulsa una tecla para continuar")
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item3.py
from FuncionesTP import *
'''En este ejercicio se generan 3 señales, cada una compuesta por la señal del Item 1 "data" más un ruido añadido(con sigma 0.1, 1 y 3 respectivamente). Finalmente se imprimen los resultado del SNR calculado para cada señal. '''
# Se generan los 3 ruidos y se añaden a la señal original.
ruido01 = np.random.normal(0, 0.1,len(data))
ruido1 = np.random.normal(0, 1, len(data))
ruido3 = np.random.normal(0, 3, len(data))
x01 = data + ruido01
x1 = data + ruido1
x3 = data + ruido3
# Se normalizan las señales generadas utilizando la función "normalizar" definida en FuncionesTP.py
x01=normalizar(x01)
x1=normalizar(x1)
x3=normalizar(x3)
# Se calculan los valores de SNR para cada señales a través de funciones de nuestro módulo de funciones.
SNR1=np.max(x01)/desvioestandar(ruido01,lamedia(ruido01))
SNR2=np.max(x1)/desvioestandar(ruido1,lamedia(ruido1))
SNR3=np.max(x3)/desvioestandar(ruido3,lamedia(ruido3))
# Se presentan los resultados.
print("SNR de la señal x01: ",SNR1)
print("SNR de la señal x1: ",SNR2)
print("SNR de la señal x3: ",SNR3)
#Gráficos
plt.figure('Item 3')
plt.subplot(3,1,1)
plt.plot(x01,'#e52121')
plt.grid('both')
plt.title('Señal x01')
plt.xlabel('Muestras [n]')
plt.ylabel('Amplitud')
plt.subplot(3,1,2)
plt.plot(x1,'#604444')
plt.grid('both')
plt.title('Señal x1')
plt.xlabel('Muestras [n]')
plt.ylabel('Amplitud')
plt.subplot(3,1,3)
plt.plot(x3,'#e35d6a')
plt.title('Señal x3')
plt.xlabel('Muestras [n]')
plt.ylabel('Amplitud')
plt.grid('both')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/nidea.py
from Funcionestp2 import *
# Ha base y Hb:
# def karplus_strongestirado(n_samples,f1, wavetable_size,fs):
#
# samples = []
# current_sample = 0
# previous_value = 0
#
# # conseguir la aleatoriedad de nivel dos
# wavetable = (2 * np.random.randint(0, 2, int(wavetable_size)) - 1).astype(np.float)
#
# while len(samples) < n_samples:
#
# if wavetable_size >= fs/4:
# ro=0.45
# S=0
# #aca hago el karplus strong y los guardo en wavetable
# wavetable[current_sample] = (0.5)*(wavetable[current_sample] + previous_value)
# #aca le agrego a samples lo muestra i que estoy bucleando
# samples.append(wavetable[current_sample])
# #aca le digo al bucle que lea siempre la ultima muestra del vector que me importa
# previous_value = samples[-1]
# #acumulador
# current_sample += 1
# #Resto de la division entre el vector wavetable y el sample que estoy bucleando
# current_sample = (ro)*current_sample % wavetable.size
# else:
# S=0.9
# ro=0
# #aca hago el karplus strong y los guardo en wavetable
# wavetable[current_sample] = ((1-S)*(wavetable[current_sample]) + S*(previous_value))
# #aca le agrego a samples lo muestra i que estoy bucleando
# samples.append(wavetable[current_sample])
# #aca le digo al bucle que lea siempre la ultima muestra del vector que me importa
# previous_value = samples[-1]
# #acumulador
# current_sample += 1
# #Resto de la division entre el vector wavetable y el sample que estoy bucleando
# current_sample = current_sample % wavetable.size
#
# return np.array(samples),S,ro
<file_sep>/Scripts DSP 2020/TP1old/TP1/pruebita.py
from FuncionesTP import *
# blackman=np.blackman(1000)
# RF_blackman=(np.fft.fft(blackman))
# RFdB_B=np.clip(20*np.log10(RF_blackman/max(RF_blackman)),-100,50)
T=1000
#f= np.linspace(-1*np.pi,np.pi,T)
f=np.arange(-1*np.pi,np.pi,2*np.pi/(192000-1))
print(len(f))
a0=0.42
a1=0.5
a2=0.08
H1=(np.sin(f*T/2)/np.sin(f/2))
H2=(np.exp(-1j*(np.pi)/T)*(np.sin((T*f/2)-np.pi)/np.sin((f-(2*np.pi/T))/2)))+((np.exp(1j*(np.pi)/T))*(np.sin((f+(2*np.pi/T))*T/2)/np.sin((f+(2*np.pi/T))/2)))
H3=(np.exp(1j*(2*np.pi)/T)*(np.sin((f-(4*np.pi/T))*T/2)/np.sin((f-(4*np.pi/T))/2)))+(np.exp(1j*(2*np.pi)/T)*(np.sin((f+(4*np.pi/T))*T/2)/np.sin((f+(4*np.pi/T))/2)))
RF_blackman=abs(np.exp(-1j*((T-1)*f)/2)*(a0*H1)-(a1*H2)+(a2*H3))
RFdB_B=np.clip(20*np.log10(RF_blackman/max(RF_blackman)),-100,50)
plt.figure(1)
plt.plot(RFdB_B)
# plt.plot(np.fft.fftshift(RF_blackman),'g')
plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item6.py
from FuncionesTP import *
señal,n,fs=senalTP() #Importo la señal sinusoidal definida en el Item 1.
L=int(0.01*len(señal)) #Asignacion de largo de 1% para la ventana
Largo=len(señal)
ri_MM=np.ones(L)/(L) #Respuesta al impulso del FMM de largo igual al 1% del largo de la señal.
sFMM=np.convolve(señal,ri_MM) #FMM a través de convolución lineal.
sfd=mediamovild(señal,L-1) #Aplicar la función de media movil directa
sfr=mediamovildr(señal,L-1) #Aplicar la función de media movil recursiva
#Normalización
sfd_norm=sfd/max(sfd) #Directa
sfr_norm=sfr/max(sfr) #Recursiva
sFMM_norm=sFMM/max(sFMM) #Convolución lineal
#Gráficos
t=np.arange(0,Largo) #Vector de muestras
sp1=plt.figure('Item 6')
plt.subplot(3,1,1)
plt.plot(t[int(Largo/64):int(Largo/48)],sfd_norm[int(Largo/64):int(Largo/48)],'#738EB6')
#Grafico normalizado de la señal filtrada con la media movil directa
plt.title('Señal filtrada con media movil directa')
plt.grid('both')
plt.ylabel('Señal x[n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(3,1,2)
plt.plot(t[int(Largo/64):int(Largo/48)],sfr_norm[int(Largo/64):int(Largo/48)],'#BF76D2')
#Grafico normalizado para la señal filtrada con la media movil recursiva
plt.title('Señal filtrada con media movil recursiva')
plt.grid('both')
plt.ylabel('Señal x[n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(3,1,3)
plt.plot(t[int(Largo/64):int(Largo/48)],sFMM_norm[int(Largo/64):int(Largo/48)],'#e0503f')
#Grafico normalizado para la señal filtrada con la convolución lineal
plt.title('Señal filtrada a traves de convolución')
plt.grid('both')
plt.ylabel('Señal x[n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/tp2.py
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import soundfile as sf
[m69,Fs] = sf.read("Cosas/Midi69.wav")
d=0.5 #segundos
D=int(round(d*Fs))
zpad=np.zeros(D)
delay=np.append(zpad,m69)
a=(2**(1/2))/2
x=np.append(m69,zpad)
n=np.arange(0,len(x))
y=x+a*delay
y-a*delay=x
ny=np.arange(0,len(y))
# print(f"D={D}, señal= {len(m69)}, delay={len(delay)}, x={len(x)}, y={len(y)}")
# sf.write('Midi69+delay.wav', y, Fs)
plt.figure()
plt.plot(n,x,'b',ny,a*delay,'r')
plt.show()
plt.figure()
plt.plot(ny,y)
plt.show()
sf.write('mecho.wav', y, Fs)
<file_sep>/Scripts DSP 2020/Scripts TP2/Hb.py
from Funcionestp2 import *
fs=44100
p1 = 55
p2 = 20
n_samples=3*fs
Karpluscuerda = karplus_strong(n_samples, 1 ,p1 ,fs)
Karpluspercusivo = karplus_strong(n_samples, 0.707 ,p2 ,fs)
sf.write('karpluscuerda.wav', sample1, fs)
sf.write('karpluspercusivo.wav', sample2, fs)
#Plots
sp1=plt.figure('Punto 3')
plt.subplot(2,1,1)
plt.plot(sample1,'#738EB6')
plt.title('Señal generada por la cuerda')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(2,1,2)
plt.plot(sample2,'#BF76D2')
plt.title('Señal generada por la percusión')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/wavetable.py
import matplotlib.pyplot as plt
import numpy as np
import soundfile as sf
import matplotlib.pyplot as plt
fs=44100
p1 = 55
p2 = 20
def make_sine_wavetable(n_samples, amps, phases, freqs):
"""Genero una tabla de ondas a traves de sumas senoidales."""
t = np.linspace(0, 1, num=n_samples)
wavetable = np.zeros_like(t)
for amp, phase, freq in zip(amps,phases,freqs):
wavetable += amp * np.sin(np.sin(2 * np.pi * freq * t + phase)) + \
amp / 2 * np.sin(np.sin(2 * np.pi * 2 * freq * t + phase))
return wavetable
def karplus_strong(wavetable, n_samples):
"Synthesizes a new waveform from an existing wavetable, modifies last sample by averaging."
samples = []
current_sample = 0
previous_value = 0
while len(samples) < n_samples:
#aca hago el karplus strong y los guardo en wavetable
wavetable[current_sample] = 0.5 * (wavetable[current_sample] + previous_value)
#aca le agrego a samples lo muestra i que estoy bucleando
samples.append(wavetable[current_sample])
#aca le digo al bucle que lea siempre la ultima muestra del vector que me importa
previous_value = samples[-1]
#acumulador
current_sample += 1
#Resto de la division entre el vector wavetable y el sample que estoy bucleando
current_sample = current_sample % wavetable.size
return np.array(samples)
def karplus_strong_perc(wavetable, n_samples, prob):
"Desde la tabla de onda anterior usando una distribucion binomial se genera un nuevo promedio."
samples = []
current_sample = 0
previous_value = 0
while len(samples) < n_samples:
r = np.random.binomial(1, prob)
sign = float(r == 1) * 2 - 1
wavetable[current_sample] = sign * 0.5 * (wavetable[current_sample] + previous_value)
samples.append(wavetable[current_sample])
previous_value = samples[-1]
current_sample += 1
current_sample = current_sample % wavetable.size
return np.array(samples)
wavetable_size1 = fs // p1
wavetable_size2 = fs // p2
# conseguir la aleatoriedad de nivel dos
wavetable1 = (2 * np.random.randint(0, 2, wavetable_size1) - 1).astype(np.float)
wavetable2 = (2 * np.random.randint(0, 2, wavetable_size2) - 1).astype(np.float)
sample1 = karplus_strong(wavetable1, 2 * fs)
sample2 = karplus_strong_perc(wavetable2, fs, 0.2)
sf.write('karputo.wav', sample1, fs)
sf.write('karputodrum.wav', sample2, fs)
#Plots
sp1=plt.figure('Karputo')
plt.subplot(2,1,1)
plt.plot(sample1,'#738EB6')
plt.title('Señal generada por la cuerda')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(2,1,2)
plt.plot(sample2,'#BF76D2')
plt.title('Señal generada por la percusión')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/TP1/Items/Item5.py
from FuncionesTP import *
import time
import heapq
'''En este script se implementan las funciones mediamovild y mediamovildr (FuncionesTP) para aplicar el filtro de media movil a la señal senoidal del Item 1 (x(t)=sen(2pi*f*t)) de manera directa y recursiva, respectivamente. Se comparan los tiempos de ejecución de cada una. Finalmente, se aplica el filtro de modo tal que se deja pasar la componente de 10 kHz de dicha señal, atenuendo la energía en la frecuencia indicada alrededor de 3 dB por debajo de la señal original.
'''
s1=señal # Función x(t)=sen(2pi*f*t) definida en módulo FuncionesTP.
n=t
N = len(n)
'''------------------------------------------------Primera parte--------------------------------------------------------------'''
#A continución se procede a conseguir un largo de ventana M tal que el filtro deje pasar la componente de 10kHz con una atenuación de 3dB (30%) aproximadamente.
#Para ello se utiliza la expresión de la respuesta en frecuencia del filtro y se busca calcular los largos L de ventana para los que la magnitud sea nula en la
#frecuencia angular que corresponde a 10 kHz (w0). Estos largos L_k estarán dados por L_k=(2*π/w0)*k, expresión encontrada de manera analítica.
#Como se busca el L_1 para el primer cero, se impone k=1.
w=np.arange(-np.pi,np.pi,2*np.pi/fs) # Vector de frecuencias angulares [-π; π].
w0=np.float32(frec*2*np.pi/fs) # Frecuencia angular correspondiente a 10 kHz (positiva)
k=1 # k correspondiente para el primer cero de la magnitud.
L=int((2*np.pi*k)/w0) # Largo de la ventana del filtro, cuya frecuencia de corte es w0
#Finalmente, a partir de este largo obtenido, se busca encontrar el largo M que permita que la respuesta en frecuencia tenga un valor 3dB menor al de la señal original en w0.
RF_FMM=aux_calcM(L,fs) #Calculo las RF de las ventana de largo L, L-1, L-2 y L-3 (en ese órden). Esto sabiendo que probalemente entre estas opciones estará la buscada.
i_w0=np.array(np.where(np.float32(w[int(len(w)/2):])==w0)) #Posición que ocupa w0 en el vector de frecuencias anguares w.
u=np.ones(L)
dif=np.zeros(L)
aux1=np.zeros(L,np.int32)
#Busco la RF de aquella ventana en la que w0 tiene una amplitud aproximadamente 3 dB menor al maximo(1). El largo de la misma será el M buscado.
for i in range(0,L):
aux=L-i
dif[i]=u[i]-RF_FMM[i][i_w0]
aux1[i]=int(aux)
if RF_FMM[i][i_w0]>=0.707 and RF_FMM[i][i_w0]<0.8:
M=aux
# Se presentan los resultados en una tabla para poder observar el porcentaje de atenuación de cada ventana en 10 kHz.
#El que cumple la condición de atenuar alrededor de un 30% (en realidad un 24%) es la ventana de largo M=2, por lo que se utiliza este valor para la segunda parte del ejercicio.
datos1=[[aux1[0],int(round(dif[0]*100,0))],[aux1[1],int(round(dif[1]*100,0))], [aux1[2],int(round(dif[2]*100,0))], [aux1[3],int(round(dif[3],0))]]
Tabla1 = """\
+----------------------------------------------+
| Largo de Ventana | Atenuación en 10 kHz[%] |
|----------------------------------------------|
{}
+----------------------------------------------+\
"""
Tabla1 = (Tabla1.format('\n \t'.join("| {:>15d} | {:>24} | ".format(*fila)
for fila in datos1)))
print ("\n")
print("\t \t Resultados Item 5 (Parte 1) ")
print ("\n")
print(" Para este Item se calcula un largo de ventana (M) tal que el \n filtro deje pasar la componente de 10 kHz. A continuación se \n muestran los posibles M y su respectiva atenuación:")
print ("\n")
print (Tabla1)
input("\t \t El largo de ventana elegido es M=2.\n \t \t Pulse una ENTER para continuar")
'''------------------------------------------------Segunda parte--------------------------------------------------------------'''
# Comparación de tiempos de ejecución de ambas funciones.
time1 = time.time() # Iniciar tiempo.
xfd=mediamovild(s1,M) # Ejecutar función.
tiempo_d = time.time()-time1 # Calcular tiempo de ejecucion total.
time2 = time.time() # Iniciar tiempo.
xfr= mediamovildr(s1,M) # Ejecutar función.
tiempo_r = time.time()-time2 # Calcular tiempo de ejecucion total.
#Reporte de resultados temporales
datos=[["Directa", round(tiempo_d*1000,2)],["Recursiva",round(tiempo_r*1000,2)]]
Tabla = """\
+----------------------------------------------------+
| Implementación del FMM | Tiempo de ejecución [ms] |
|----------------------------------------------------|
{}
+----------------------------------------------------+\
"""
Tabla = (Tabla.format('\n \t'.join("| {:<21s} | {:>25} |".format(*fila)
for fila in datos)))
print ("\n")
print("\t \t Resultados Item 5 (Parte 2) ")
print (Tabla)
#FFT's
FFT=abs(np.fft.fft(s1)) #FFT de la señal original
FFTd=abs(np.fft.fft(xfd)) #Calcular la FFt para la señal filtrada con media movil directa
FFTr=abs(np.fft.fft(xfr)) #Idem recursiva
Maxlabel1=heapq.nlargest(2, FFTd) #Crear un vector de máximos de la señal FFTd (Corresponderán a los magnitudes en 0 Hz y 10 kHz)
Maxlabel1=int(round(Maxlabel1[1])) #Almacenar el valor maximo en una variable (Es decir la amplitud en 10 kHz)
Maxlabel2=heapq.nlargest(2, FFTr) #Idem recursiva
Maxlabel2=int(round(Maxlabel2[1]))
Maxlabel=heapq.nlargest(2, FFT)
Maxlabel=int(round(Maxlabel[1]))
#Gráficos
f = np.arange(0,fs/2,(fs/2)/int(N/2)) #Crear un vector de muestras para graficar con relacion a la Frecuencia de sampleo
t = np.arange(0,N)
#Gráficos en muestras
sp1=plt.figure('Item 5: Comparación en muestras')
plt.subplot(3,1,1)
plt.plot(t[0:round(N/64)],s1[0:round(N/64)],'#738EB6') #Gráfico de la señal original del punto uno
plt.title('Señal original')
plt.grid('both')
plt.ylabel('x [n]')
plt.xlabel('Número de muestra [n]')
sp1=plt.subplot(3,1,2)
plt.plot(t[0:round(N/64)],xfd[0:round(N/64)],'#BF76D2') #Grafico de la señal filtrada con la media movil directa
plt.title('Señal filtrada por media movil directa')
plt.grid('both')
plt.ylabel('xfd [n]')
plt.xlabel('Número de muestra [n]')
sp1=plt.subplot(3,1,3)
plt.plot(t[0:round(N/64)],xfr[0:round(N/64)],'#e0503f') #Grafico de la señal filtrada con la media movil recursiva
plt.title('Señal filtrada por media movil recursiva')
plt.grid('both')
plt.ylabel('xfr [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
#Gráficos en frecuencias.
plt.figure('Item 5: Comparación en frecuencias')
sp2=plt.subplot(3,1,1)
plt.plot(f,FFT[0:int(N/2)],'#738EB6') #Grafico en frecuencia de la señal filtrada con la media movil directa
plt.title('Señal original')
plt.grid('both')
plt.ylabel('X[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel)}",xy=(10100,Maxlabel-1100))
sp2=plt.subplot(3,1,2)
plt.plot(f,FFTd[0:int(N/2)],'#BF76D2') #Grafico en frecuencia de la señal filtrada con la media movil directa
plt.title('Señal filtrada por media movil directa')
plt.grid('both')
plt.ylabel('XFD[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel1)}",xy=(10100,Maxlabel1-1100))
sp2=plt.subplot(3,1,3)
plt.plot(f,FFTr[0:int(N/2)],'#e0503f') #Grafico en frecuencia de la señal filtrada con la media movil recursiva
plt.grid('both')
plt.ylabel('XFR[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel2)}",xy=(10100,Maxlabel2-1100))
plt.title('Señal filtrada por media movil recursiva')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item8.py
from FuncionesTP import *
'''En este Script se busca estudiar la convolución de las señales de audio importadas 'Midi69.wav' y 'RIR.wav'.
Para ello se comparan los resultados de la convolución lineal, la convolución circular tomando el largo de la señal RIR y
la convolución circular equivalente a la lineal. Finalmente se exportan los resultados en archivos .wav. '''
#En esta sección se calculan las convoluciones pedidas en la consigna.
cLineal=np.convolve(Midi69,RIR) #Convolución lineal
cCirc,nc=cConv(Midi69,nMidi,RIR,nRIR,2) #Convolución circular tomando el largo de la señal RIR(señal N°2)
cCircular,nconv=convCircular(Midi69,nMidi,RIR,nRIR) #Convolución circular equivalente a convolución lineal.
#Se escriben los archivos .wav para cada señal obtenida.
# sf.write('cLinealout.wav', cLineal, Fs)
# sf.write('cCircout.wav', cCirc, Fs)
# sf.write('cCircularout.wav', cCircular, Fs)
#Se grafican los resultados.
sp1=plt.figure('Item 8: Comparación de convoluciones')
plt.subplot(3,1,1)
plt.plot(cLineal,'#738EB6')
# Gráfico de la convolución lineal y[n]= Midi69*RIR.
plt.title('Convolución lineal')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
sp1=plt.subplot(3,1,2)
plt.plot(nconv,cCircular,'#BF76D2')
# Grafico de la convolución circular y[n]= Midi69*RIR equivalente a la lineal.
plt.title('Convolución circular equivalente a lineal')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
sp1=plt.subplot(3,1,3)
plt.plot(nc,cCirc,'#e0503f')
# Gráfico de la convolución circular y[n]= Midi69*RIR de largo igual a la señal RIR.
plt.title('Convolución circular con largo RIR')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/RealHe.py
from Funcionestp2 import *
eps=0.001
fs=44100
T=1/fs
n_samples=fs*2
pa=1/2
f1=220
p1=fs/f1
N= int(np.floor(p1 -pa-eps))
pc=p1-N-pa
C=(1-pc)/(1+pc)
# p=100
# def delay1(senal,a1,a2):
# zpad=np.zeros(1)
# delay=np.append(zpad,senal)
# x=np.append(senal,zpad)
# y=a1*x+a2*delay
# return y
#
cuerda=karplus_strong(n_samples,1,N)
#
# # x1,z1,dly1=delays(cuerda,1,C1,1,1)
# #
# # x2,z2,dly2=delays(cuerda,1,C2,1,1)
#
# z1=delay1(cuerda,C,1)
# z2=delay1(cuerda,C,1)
#
# k1,y1,delayline1=IIR_delay(z1,-C,1)
#
# # k2,y2,delayline2=IIR_delay(z2,-C2,1)
#
# sf.write('HaHbHc.wav',cuerda,fs)
# sf.write('HaHbHc1.wav',y1,fs)
#
# # sf.write('HaHbHc2.wav',y2,fs)
#
# fftz1=np.fft.fft(z1)
# fftz2=np.fft.fft(z2)
# # fdB=20*np.log10(abs(fftz1))
# fase1=np.angle(fftz1)
# fase2=np.angle(fftz2)
# plt.plot(fdB[0:2500])
mu1=1/100
mu2=0.3
mu3=0.5
mu4=0.707
mu5=1/N
y1=He(cuerda,mu1,N,fs)
y2=He(cuerda,mu2,N,fs)
y3=He(cuerda,mu3,N,fs)
y4=He(cuerda,mu4,N,fs)
y5=He(cuerda,mu5,N,fs)
sf.write('mu1.wav',y1,fs)
sf.write('mu2.wav',y2,fs)
sf.write('mu3.wav',y3,fs)
sf.write('mu4.wav',y4,fs)
sf.write('mu5.wav',y5,fs)
# plt.subplot(2,1,1)
# plt.plot(cuerda,'#738EB6')
# plt.title('Señal generada por la cuerda')
# plt.grid('both')
# plt.ylabel('Amplitud relativa [n]')
# plt.xlabel('Número de muestra [n]')
# plt.subplot(2,1,2)
# plt.plot(y1,'#BF76D2')
# plt.title('Señal generada por la cuerda 2')
# plt.grid('both')
# plt.ylabel('Amplitud relativa [n]')
# plt.xlabel('Número de muestra [n]')
# plt.subplots_adjust(hspace = 1.2)
#
# plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/He.py
from Funcionestp2 import *
fs=44100
p1=55
p2=20
sample1 = karplus_strong(1*fs, 1 ,p1 ,fs)
sample2 = karplus_strong(3*fs, 0.707 ,p2 ,fs)
he_s1,n=He(sample1,21,fs)
# sf.write('karputo.wav', sample1, fs)
sf.write('karputoHe.wav', he_s1, fs)
sp1=plt.figure('Karputo')
plt.subplot(2,1,1)
plt.plot(sample1,'#738EB6')
plt.title('Señal generada por la cuerda')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(2,1,2)
plt.plot(he_s1,'#BF76D2')
plt.title('Señal generada por la percusión')
plt.grid('both')
plt.ylabel('Amplitud relativa [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/scripts varios/convolucion.py
import numpy as np
import math
def convLin(x,h):
X=np.fft.fft(x)
H=np.fft.fft(h)
Y=X*H
y=np.fft.ifft(Y)
return y
def convCirc(x,h):
L=len(x)
M=len(h)
xc=np.append(x,np.zeros(M-1))
hc=np.append(h,np.zeros(L-1))
X=np.fft.fft(xc)
H=np.fft.fft(hc)
Y=X*H
y=np.fft.ifft(Y)
return y
def conv_sum(x1,nx1,x2,nx2):
# nnx1 = np.arange(0,len(nx1))
# nnx2 = np.arange(0,len(nx2))
# n1 = nnx1[0]
# n2 = nnx1[-1]
# n3 = nnx2[0]
# n4 = nnx2[-1]
nny = np.arange(0,len(nx1)+len(nx2)-1)
ny = np.arange(0,len(x1)+len(x2)-1) + nx1[0]+nx2[0]
y = np.convolve(x1, x2)
return y[nny], ny
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item10.py
from FuncionesTP import *
''' Este Script compara gráficamente las respuetas en frecuencia en dB de las ventanas rectangular y blackman, ambas de largo T=1000. En suma, realizamos la misma comparación usando las respuestas en frencuencia calculadas analíticamente(Ver FuncionesTP/RF_boxcar y FuncionesTP/RF_blackman).
'''
T=1000 #Largo de las ventanas.
#Se calculan las Respuestas en frecuencias de las ventanas con las definiciones de Scipy y usando FFT.
wRect=signal.windows.boxcar(T)
wBlackman = signal.blackman(T)
RFdB_R=RFdB_ventanas(np.fft.fft(wRect,fs),T) # Respuesta en Frecuencia de la ventana rectangular en dB.
RFdB_B=RFdB_ventanas(np.fft.fft(wBlackman,fs),T) # Respuesta en Frecuencia de la ventana blackman en dB.
# Se obtienen las Respuestas en frecuencia de las ventanas a partir de las Repuestas en frecuncia calculadas analíticamente.
f=np.arange(-1*np.pi,np.pi,2*np.pi/fs)
RF_rect=RF_boxcar(T,f)
RF_blackman=RF_Blackman(T,f)
RFdB_Rect=RFdB_ventanas(RF_rect,T) # Respuesta en Frecuencia analítica de la ventana rectangular en dB.
RFdB_Black=RFdB_ventanas(RF_blackman,T) # Respuesta en Frecuencia analítica de la ventana blackman en dB.
#Gráficos
#El siguiente gráfico es el utilizado para reportar los resultados del punto 10 debido a que presenta mayor precisión
plt.figure('Item 10 metodo 1')
plt.plot(f,np.fft.fftshift(RFdB_B),'#065535', label='Blackman')
#Gráfico de la respuesta en frecuencia de la ventana Blackman
plt.plot(f,np.fft.fftshift(RFdB_R),'#f24738', label='Rectangular')
#Gráfico de la respuesta en frecuencia de la ventana rectangular
plt.legend()
plt.axis([-np.pi/32, np.pi/32, -80, 0])
plt.title("Respuesta en frecuencia de la ventana")
plt.ylabel("Amplitud [dB]")
plt.xlabel("Frecuencia angular [Rad/s]")
plt.grid('both')
#El siguiente Gráfico muestra la respuesta en frecuencia en dB de las ventanas calculadas analíticamente a modo de comparación
#con las respuestas en frecuencia caluladas con funciones nativas del lenguaje.
plt.figure('Item 10 metodo 2')
plt.plot(f,RFdB_Black,'#5e508e',label='Blackman')
#Gráfico de la respuesta en frecuencia de la ventana Blackman
plt.plot(f,RFdB_Rect, '#fbbc5a',label='Rectangular')
#Gráfico de la respuesta en frecuencia de la ventana rectangular
plt.legend()
plt.axis([-np.pi/32, np.pi/32, -80, 0])
plt.title("Respuesta en frecuencia de la ventana")
plt.ylabel("Amplitud [dB]")
plt.xlabel("Frecuencia angular [Rad/s]")
plt.grid('both')
plt.show()
<file_sep>/Scripts DSP 2020/TP2 Lionti Villatarco/Menu.py
import os
from Funcionestp2 import *
'''
Función que limpia la pantalla y muestra nuevamente el menú
'''
def menu():
os.system('cls') # NOTA: para otro sistema operativo, cambiar 'cls' por 'clear'.
print("\t \tPROCESAMIENTO DIGITAL DE SEÑALES")
print("\t TRABAJO PRÁCTICO N° 1: ESTUDIO DE EFECTOS\n\t \tDE AUDIO BASADO EN RETARDOS")
print("\t\t LIONTI-VILLATARCO")
print ("\n")
print ("\t \t Seleccione una opción: ")
print ("\t \t \t 1 - ECOS FINITOS")
print ("\t \t \t 2 - ECOS INFINITOS")
print ("\t \t \t 3 - ALGORITMO DE KARPLUS-STRONG")
print ("\t \t \t 4 - ALGORITMO DE KARPLUS-STRONG MODIFICADO")
print ("\t \t \t 5 - Salir")
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 5) y presione ENTER >> ")
if opcionMenu=="1":
print ("")
''' Ecos Finitos'''
m69,fs=sf.read('Midi69.wav')# Se importa una señal de audio
t=[100,800] #Duración del retardo en ms
a=[-0.5,0.707] #Valores de atenuación alfa
y1=delays(m69,t[0],fs,a[1],4)#Se aplican 4 ecos por cada tiempo de retardo
y2=delays(m69,t[1],fs,a[0],4)
sf.write('EcosFinitos(800 ms).wav',y2,fs)
sp1=plt.figure('Ecos Finitos')
plt.subplot(3,1,1)
plt.plot(np.append(m69,np.zeros(len(y2)-len(m69))),'#0392cf')
plt.title('Señal de entrada')
plt.grid('both')
plt.ylabel('x [n]')
plt.xlabel('Número de muestra [n]')
plt.axis([0,len(y2),-0.3,0.3])
plt.subplot(3,1,2)
plt.plot(np.append(y1,np.zeros(len(y2)-len(y1))),'#7bc043')
plt.title('Señal con 4 ecos(100 ms)')
plt.grid('both')
plt.ylabel('y [n]')
plt.xlabel('Número de muestra [n]')
plt.axis([0,len(y2),-0.3,0.3])
plt.subplot(3,1,3)
plt.plot(y2,'#f37736')
plt.title('Señal con 4 ecos(800 ms)')
plt.grid('both')
plt.ylabel('y [n]')
plt.xlabel('Número de muestra [n]')
plt.axis([0,len(y2),-0.3,0.3])
plt.subplots_adjust(hspace = 1.4)
plt.show()
input("\n\t ECOS FINITOS ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
'''Ecos Infinitos'''
m69,fs=sf.read('Midi69.wav')# Se importa una señal de audio
t=[100,800] #Duración del retardo en ms
a=[-0.5,0.707] #Valores de atenuación alfa
y1=delays(m69,t[0],fs,a[1],4)#Se aplican 4 ecos por cada tiempo de retardo
y2=delays(m69,t[1],fs,a[0],4)
yinf1=IIR_delay(m69,a[1],15,fs)
yinf2=IIR_delay(m69,0.5,t[0],fs)
sf.write('EcosInfinitos(15 ms).wav',yinf1,fs)
sp1=plt.figure('Ecos Infinitos')
plt.subplot(3,1,1)
plt.plot(np.append(m69,np.zeros(len(yinf2)-len(m69))),'#c51f5d')
plt.title('Señal de entrada')
plt.grid('both')
plt.ylabel('x [n]')
plt.xlabel('Número de muestra [n]')
plt.axis([0,len(yinf2),-0.3,0.3])
plt.subplot(3,1,2)
plt.plot(np.append(yinf1,np.zeros(len(yinf2)-len(yinf1))),'#ee4035')
plt.title('Señal con infinitos ecos (15 ms)')
plt.grid('both')
plt.ylabel('y [n]')
plt.xlabel('Número de muestra [n]')
plt.axis([0,len(yinf2),-0.3,0.3])
plt.subplot(3,1,3)
plt.plot(yinf2,'#9400d3')
plt.title('Señal con infinitos ecos (100 ms)')
plt.grid('both')
plt.ylabel('y [n]')
plt.xlabel('Número de muestra [n]')
plt.axis([0,len(yinf2),-0.3,0.3])
plt.subplots_adjust(hspace = 1.4)
plt.show()
input("\n\t ECOS INFINITOS ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
'''Implementación del algoritmo original de Karplus-Strong'''
fs=44100
T=1/fs
f1=220 #Frecuencia fundamental
Pa=1/2 #Pa(f1)
eps=0.001 #epsilon
P1=fs/f1
N= int(np.floor(P1-Pa-eps)) #N
n_samples=fs*2
cuerda=karplus_strong(n_samples, 1 , N)# Cuerda sintetizada
drum=karplus_strong(n_samples, 0.707 , N)# Drum sintetizado
Hcuerda=np.fft.fft(cuerda)
Hdrum=np.fft.fft(drum)
freq = np.arange(0,fs/2,(fs/2)/int(len(cuerda)/2))
sf.write('Cuerda.wav',cuerda,fs)
sf.write('Drum.wav',drum,fs)
sp1=plt.figure(figsize=(10,10))
plt.subplot(2,2,1)
plt.plot(freq,20*np.log10(abs(Hcuerda[:int(len(cuerda)/2)])),'#7bb8b4')
plt.title('Cuerda Sintetizada')
plt.grid('both')
plt.ylabel('|H(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(2,2,2)
plt.plot(freq,20*np.log10(abs(Hdrum[:int(len(drum)/2)])),'#314d5e')
plt.title('Drum Sintetizado')
plt.grid('both')
plt.ylabel('|H(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(2,2,3)
plt.plot(cuerda[:1000],'#94384d')
plt.title('Cuerda Sintetizada')
plt.grid('both')
plt.ylabel('|H(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(2,2,4)
plt.plot(drum[:1000],'#dc7582')
plt.title('Drum Sintetizado')
plt.grid('both')
plt.ylabel('|H(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplots_adjust(hspace = 1)
plt.subplots_adjust(wspace = 0.4)
plt.show()
input("\n\t ALGORITMO KS ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
'''Implementación del algoritmo de Karplus-Strong Modificado (MKS)'''
'''Se Implementan 3 características del MKS, denominadas Ha(z), HL(z) y He(z),respectivamente.'''
fs=44100
T=1/fs
f1=220 #Frecuencia fundamental
Pa=1/2 #Pa(f1)
eps=0.001 #epsilon
P1=fs/f1
N= int(np.floor(P1-Pa-eps)) #N
n_samples=fs*2
cuerda=karplus_strong(n_samples, 1 , N)# Cuerda sintetizada
drum=karplus_strong(n_samples, 0.707 , N)# Drum sintetizado
'''Ha(z): Alteración del tiempo de decaimiento'''
S1=0.51
S2=0.707
S3=0.999999
ya1=Ha(cuerda,int(P1),S1)
ya2=Ha(cuerda,int(P1),S2)
ya3=Ha(cuerda,int(P1),S3)
Ha1=20*np.log10(abs(np.fft.fft(ya1)))
Ha2=20*np.log10(abs(np.fft.fft(ya2)))
Ha3=20*np.log10(abs(np.fft.fft(ya3)))
sf.write('Ha1.wav',ya1,fs)
sf.write('Ha2.wav',ya2,fs)
sf.write('Ha3.wav',ya3,fs)
sp1=plt.figure('Ha(jw): Alteración del tiempo de decaimiento')
plt.subplot(3,1,1)
plt.plot(Ha1[:int(len(Ha1)/8)],'#ee4035')
plt.title('Ha(jw) con S=0.51')
plt.grid('both')
plt.ylabel('|Ha1(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(3,1,2)
plt.plot(Ha2[:int(len(Ha2)/8)],'#42bdcb')
plt.title('Ha(jw) con S=0.707')
plt.grid('both')
plt.ylabel('|Ha2(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(3,1,3)
plt.plot(Ha3[:int(len(Ha3)/8)],'#72697d')
plt.title('Ha(jw) con S=0.999')
plt.grid('both')
plt.ylabel('|Ha3(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplots_adjust(hspace = 1.4)
plt.show()
'''HL(z): Simulación de dinámica'''
L1=100
L2=1000
L3=20000
yL1=Hd(cuerda,L1,fs)
yL2=Hd(cuerda,L2,fs)
yL3=Hd(cuerda,L3,fs)
HL1=20*np.log10(abs(np.fft.fft(yL1)))
HL2=20*np.log10(abs(np.fft.fft(yL2)))
HL3=20*np.log10(abs(np.fft.fft(yL3)))
sf.write('HL1.wav',yL1,fs)
sf.write('HL2.wav',yL2,fs)
sf.write('HL3.wav',yL3,fs)
sp1=plt.figure('HL(jw): Simulación de dinámica')
plt.subplot(3,1,1)
plt.plot(HL1[:int(len(HL1)/8)],'#2d0f59')
plt.title('HL(jw) con L=100 Hz')
plt.grid('both')
plt.ylabel('|HL1(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(3,1,2)
plt.plot(HL2[:int(len(HL2)/8)],'#b04e5d')
plt.title('HL(jw) con L=1000 Hz')
plt.grid('both')
plt.ylabel('|HL2(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(3,1,3)
plt.plot(HL3[:int(len(HL3)/8)],'#2c504a')
plt.title('HL(jw) con L=20000 Hz')
plt.grid('both')
plt.ylabel('|HL3(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplots_adjust(hspace = 1.4)
plt.show()
'''He(z): Simulación de posición de púa'''
mu1=1/100
mu2=0.5
mu3=0.707
mu4=1/N
ye1=He(cuerda,mu1,N)
ye2=He(cuerda,mu2,N)
ye3=He(cuerda,mu3,N)
ye4=He(cuerda,mu4,N)
He1=20*np.log10(abs(np.fft.fft(ye1)))
He2=20*np.log10(abs(np.fft.fft(ye2)))
He3=20*np.log10(abs(np.fft.fft(ye3)))
sf.write('He1.wav',ye1,fs)
sf.write('He2.wav',ye2,fs)
sf.write('He3.wav',ye4,fs)
sp1=plt.figure('He(jw): Posición relativa de la púa')
plt.subplot(3,1,1)
plt.plot(He1[:int(len(He1)/8)],'#8c4a3e')
plt.title('He(jw) con mu=0.001')
plt.grid('both')
plt.ylabel('|He1(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(3,1,2)
plt.plot(He2[:int(len(He2)/8)],'#263e06')
plt.title('He(jw) con mu=0.5')
plt.grid('both')
plt.ylabel('|He2(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplot(3,1,3)
plt.plot(He3[:int(len(He3)/8)],'#012a5e')
plt.title('He(jw) con mu=1/N')
plt.grid('both')
plt.ylabel('|He3(jw)| [dB]')
plt.xlabel('w [rad/muestra]')
plt.subplots_adjust(hspace = 1.4)
plt.show()
input("\n\t ALGORITMO MKS ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="5":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
<file_sep>/Scripts DSP 2020/TP1-LIONTI-VILLATARCO/Python/Menu.py
import os
'''
Función que limpia la pantalla y muestra nuevamente el menú
'''
def menu():
os.system('cls') # NOTA: para otro sistema operativo, cambiar 'cls' por 'clear'.
print("\t \tPROCESAMIENTO DIGITAL DE SEÑALES")
print("\t TRABAJO PRÁCTICO N° 1: PROGRAMACIÓN BÁSICA")
print("\t\t LIONTI-VILLATARCO")
print ("\n")
print ("\t \t Seleccione una opción: ")
print ("\t \t \t 1 - Item 1")
print ("\t \t \t 2 - Item 2")
print ("\t \t \t 3 - Item 3")
print ("\t \t \t 4 - Item 4")
print ("\t \t \t 5 - Item 5")
print ("\t \t \t 6 - Item 6")
print ("\t \t \t 7 - Item 7")
print ("\t \t \t 8 - Item 8")
print ("\t \t \t 9 - Item 9")
print ("\t \t \t 10 - Item 10")
print ("\t \t \t 11 - Item 11")
print ("\t \t \t 12 - Salir")
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 12) y presione ENTER >> ")
if opcionMenu=="1":
print ("")
os.system("Items\Item1.py")
input("\n\t Item 1 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
os.system("Items\Item2.py")
input("\n\t Item 2 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
os.system("Items\Item3.py")
input("\n\t Item 3 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
os.system("Items\Item4.py")
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="5":
print ("")
os.system("Items\Item5.py")
input("\n\t Item 5 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="6":
print ("")
os.system("Items\Item6.py")
input("\n\t Item 6 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="7":
print ("")
os.system("Items\Item7.py")
input("\n\t Item 7 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="8":
print ("")
os.system("Items\Item8.py")
input("\n\t Item 8 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="9":
print ("")
os.system("Items\Item9.py")
input("\n\t Item 9 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="10":
print ("")
os.system("Items\Item10.py")
input("\n\t Item 10 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="11":
print ("")
os.system("Items\Item11.py")
input("\n\t Item 11 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="12":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
<file_sep>/Scripts DSP 2020/Scripts TP2/esperanzaha.py
from Funcionestp2 import *
#Ha base y Hb:
# def karplus_strongestirado(n_samples,f1, wavetable_size,fs):
#
# samples = []
# current_sample = 0
# previous_value = 0
#
# # conseguir la aleatoriedad de nivel dos
# wavetable = (2 * np.random.randint(0, 2, int(wavetable_size)) - 1).astype(np.float)
#
# while len(samples) < n_samples:
#
# if wavetable_size >= fs/4:
# ro=0.45
# S=0
# #aca hago el karplus strong y los guardo en wavetable
# wavetable[current_sample] = (0.5)*(wavetable[current_sample] + previous_value)
# #aca le agrego a samples lo muestra i que estoy bucleando
# samples.append(wavetable[current_sample])
# #aca le digo al bucle que lea siempre la ultima muestra del vector que me importa
# previous_value = samples[-1]
# #acumulador
# current_sample += 1
# #Resto de la division entre el vector wavetable y el sample que estoy bucleando
# current_sample = (ro)*current_sample % wavetable.size
# else:
# S=0.9
# ro=0
# #aca hago el karplus strong y los guardo en wavetable
# wavetable[current_sample] = ((1-S)*(wavetable[current_sample]) + S*(previous_value))
# #aca le agrego a samples lo muestra i que estoy bucleando
# samples.append(wavetable[current_sample])
# #aca le digo al bucle que lea siempre la ultima muestra del vector que me importa
# previous_value = samples[-1]
# #acumulador
# current_sample += 1
# #Resto de la division entre el vector wavetable y el sample que estoy bucleando
# current_sample = current_sample % wavetable.size
#
# return np.array(samples),S,ro
def el_estirador(senal,D,S) :
rho = 0.996
g0 = (1-S)*rho
g1 = S*rho
b = np.array([1.0]) # Zeros numerator coefficients
a = np.array([1.0] + ([0]*(D-3)) + [-g0, -g1]) # Poles denominator coefficients
samples = sp.lfilter(b,a,senal)
return samples
fs=48000
n_samples=2*fs
#f1 va desde 2 hasta 44100 cuanto mas chico el f1 mas alta es la frecuencia
f=20
D=int(fs/f)
#wavetable size es el periodo relativo a la frecuencia que quiero probar
wavetable_size = fs // f
estirar=karplus_strong(n_samples, 1, wavetable_size)
estira3=el_estirador(estirar,D,0.5)
sf.write('estira3.wav',estira3,fs)
plt.plot(estira3)
plt.show()
<file_sep>/Scripts DSP 2020/FIR/MenuWind.py
import os
import numpy as np
import LowPass as LP
import HighPass as hp
import BandPass as bp
import BandStop as bs
'''
Función que limpia la pantalla y muestra nuevamente el menú
'''
def menu():
os.system('cls') # NOTA: para otro sistema operativo, cambiar 'cls' por 'clear'.
print("\t \tPROCESAMIENTO DIGITAL DE SEÑALES")
print ("\n")
print ("\t \t Seleccione una opción: ")
print ("\t \t \t 1 - Rectangular")
print ("\t \t \t 2 - Barlett")
print ("\t \t \t 3 - Hanning")
print ("\t \t \t 4 - Hamming")
print ("\t \t \t 5 - Blackman")
print ("\t \t \t 6 - Kaiser")
print ("\t \t \t Q - Salir")
def mw(id_filter):
if id_filter == 1:
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 6) o Q para salir y presione ENTER >> ")
if opcionMenu=="1":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
LP.LP_fir(data[0],data[1],data[2],data[3],int(data[4]),1)
input("\n\t Item 1 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
LP.LP_fir(data[0],data[1],data[2],data[3],int(data[4]),2)
input("\n\t Item 2 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
LP.LP_fir(data[0],data[1],data[2],data[3],int(data[4]),3)
input("\n\t Item 3 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
LP.LP_fir(data[0],data[1],data[2],data[3],int(data[4]),4)
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="5":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
LP.LP_fir(data[0],data[1],data[2],data[3],int(data[4]),5)
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="6":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
LP.LP_fir(data[0],data[1],data[2],data[3],int(data[4]),6)
input("\n\t Item 6 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu =="Q" or opcionMenu =="q":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
elif id_filter == 2:
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 4) o Q para salir y presione ENTER >> ")
if opcionMenu=="1":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
hp.HP_fir(data[0],data[1],data[2],data[3],int(data[4]),1)
input("\n\t Item 1 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
hp.HP_fir(data[0],data[1],data[2],data[3],int(data[4]),2)
input("\n\t Item 2 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
hp.HP_fir(data[0],data[1],data[2],data[3],int(data[4]),3)
input("\n\t Item 3 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
hp.HP_fir(data[0],data[1],data[2],data[3],int(data[4]),4)
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="5":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
hp.HP_fir(data[0],data[1],data[2],data[3],int(data[4]),5)
input("\n\t Item 5 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="6":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
hp.HP_fir(data[0],data[1],data[2],data[3],int(data[4]),6)
input("\n\t Item 6 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu =="Q" or opcionMenu =="q":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
elif id_filter == 3:
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 4) o Q para salir y presione ENTER >> ")
if opcionMenu=="1":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bp.BP_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),1)
input("\n\t Item 1 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bp.BP_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),2)
input("\n\t Item 2 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bp.BP_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),3)
input("\n\t Item 3 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bp.BP_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),4)
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="5":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bp.BP_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),5)
input("\n\t Item 5 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="6":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bp.BP_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),6)
input("\n\t Item 6 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu =="Q" or opcionMenu =="q":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
elif id_filter ==4:
while True:
# Mostramos el menú
menu()
# solicituamos una opción al usuario
opcionMenu = input(" Inserte un valor entero (entre 1 y 4) o Q para salir y presione ENTER >> ")
if opcionMenu=="1":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bs.BS_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),1)
input("\n\t Item 1 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="2":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bs.BS_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),2)
input("\n\t Item 2 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="3":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bs.BS_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),3)
input("\n\t Item 3 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="4":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bs.BS_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),4)
input("\n\t Item 4 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="5":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bs.BS_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),5)
input("\n\t Item 5 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu=="6":
print ("")
data=np.float64(input("Ingrese valores separados por espacios: ").split(' '))
bs.BS_fir(data[0],data[1],data[2],data[3],data[4],data[5],int(data[6]),6)
input("\n\t Item 6 ejecutado...\n\t pulse una ENTER para continuar")
elif opcionMenu =="Q" or opcionMenu =="q":
print ("\n")
print ("\t \t \t¡MUCHAS GRACIAS!")
break
else:
print ("")
input("\t \tNo has pulsado ninguna opción correcta...\n\t \tpulse ENTER para continuar")
else: print("Opcion incorrecta.")
<file_sep>/Scripts DSP 2020/Scripts TP2/infinitoctm.py
# import soundfile as sf
# import matplotlib.pyplot as plt
# import numpy as np
# import wave
# import time
# [m69,Fs] = sf.read("Midi69.wav")
#
# d=0.5 #segundos
# D=int(round(d*Fs))
# zpad=np.zeros(D)
# delay=np.append(zpad,m69)
# a=(2**(1/2))/2
#
# x=np.append(m69,zpad)
# n=np.arange(0,len(x))
# y=0
# a=0
#
# try:
# while True:
# a=a+1
# b=1/a
# zpad=np.zeros(a)
# x=np.append(m69,zpad)
# delay=np.append(zpad,m69)#x[n-D]
# delay2=y+delay
# y=x+b*delay#y[n]=x[n]+b*y[n-D]
# print("Retardo agregado")
# time.sleep(1)
# result = np.where(y != 0)
# print('a:',a)
# print("Largo total: ",len(y))
# print("Ultima posición distinta de cero: ", result[0][-1])
# except KeyboardInterrupt:
# print("Hard Exit Initiated. Goodbye!")
#
#
# # for tu hermana i:
# y[0]=(1/(M+1))*np.sum(x[:M+1])
# # D=int(round(d*Fs))
# A=1
# zpad=np.zeros(A)
# x=np.append(m69,zpad)
# n=np.arange(0,len(x))
#
#
# aux=np.append(x,np.zeros(M))
# #Media movil recursiva
# for i in range(1,len(x)):
#
#
# y[i]=y[i-D] #Se divide por M+1 ya que este es el largo de ventana
# return y
#
# y=y+x
#
#
#
#
#
#
#
# def mediamovildr(x,L):
# #Implementación recursiva del filtro media móvil de largo L a una señal x.
# M=L-1 #Según la definición utilizada para implementar el FMM el largo de la ventana es M+1
# y=np.zeros(len(x))#Asiganciones de espacios en memoria
# y[0]=(1/(M+1))*np.sum(x[:M+1])
# aux=np.append(x,np.zeros(M))
# #Media movil recursiva
# for i in range(1,len(x)):
# y[i]=y[i-D]+(1/(M+1))*aux[i+M]-(1/(M+1))*aux[i-1] #Se divide por M+1 ya que este es el largo de ventana
# return y
#
# # try:
# # while True:
# # print("Olis")
# # time.sleep(1)
# # except KeyboardInterrupt:
# # print("Hard Exit Initiated. Goodbye!")
a=3%10
print(a)
<file_sep>/Scripts DSP 2020/TP1-LIONTI-VILLATARCO/Python/Items/Item9.py
from FuncionesTP import *
''' En este inciso se grafica la respuesta en frecuencia del filtro media móvil con una resolución de 44100 Hz. Cabe señalar que el largo de la ventana obtenido en el Item 5 corresponde a M=2.
'''
M=2 #El largo de la ventana es L=M+1.
w=np.arange(-1*np.pi,np.pi,2*np.pi/44100) #Se genera un vector de muestras con frecuencia de sampleo de 44100 Hz.
H=abs((1/(M))*((np.sin(w*(M)/2))/(np.sin(w/2)))) #Respuesta en frecuencia del filtro media móvil.
# Se Grafican los resultados.
plt.figure('Item 9 Grafico de magnitud para respuesta del filtro')
plt.plot(w,H,'#83b735')
# Gráfico de magnitud de respuesta en frecuencia del filtro media móvil.
plt.title('Respuesta en frecuencia FMM')
plt.xlabel('ω [rad/s]')
plt.ylabel('|H[ω]|')
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['-π', '-π/2', '0', 'π/2', 'π'])
plt.show()
<file_sep>/Scripts DSP 2020/TP1/Items/Item7.py
from FuncionesTP import *
#Generar señales
L=int(0.01*len(señal)) #Tomar el largo de 1% de la señal
Largo=len(señal)
blackman=wBlackman(L)
sBlack=np.convolve(señal,blackman) #Aplicar la convolución lineal entre la señal y la ventana Blackman
sfd=mediamovild(señal,L) #Aplicar media movil directa
sfr=mediamovildr(señal,L) #Idem recursiva
#Normalizaciones
sfd_norm=sfd/max(sfd)
sfr_norm=sfr/max(sfr)
sBlack_norm=sBlack/max(sBlack)
FFT_Black=abs(np.fft.fft(sBlack))
f = np.arange(0,fs/2,(fs/2)/int(len(t)/2))
#Gráficos
figure=plt.figure('Item 7')
plt.subplot(3,1,1)
plt.plot(sBlack_norm[8000:8150],color='#1c8b82')
# Gráfico del filtrado provocado por la convolución entre la señal y la ventana de largo L
plt.yticks([0.9998,0.9999,1])
plt.title('Ventana Blackman normalizada')
plt.xlabel('Muestras [n]')
plt.ylabel('xfb [n]')
plt.grid('both')
plt.subplot(3,1,2)
plt.plot(sfd_norm[8000:8150],color='#553E4E')
# Gráfico del filtrado generado por la media movil directa
plt.title('Media movil directa')
plt.xlabel('Muestras [n]')
plt.ylabel('xfd [n]')
plt.grid('both')
plt.subplot(3,1,3)
plt.plot(sfr_norm[8000:8150],color='#7e093e')
# Gráfico del filtrado generado por la media movil recursiva
plt.title('Media movil recursiva')
plt.ylabel('xfr [n]')
plt.xlabel('Muestras [n]')
plt.subplots_adjust(hspace = 1.2)
plt.grid('both')
plt.show()
<file_sep>/Scripts DSP 2020/scripts varios/quelopario2.py
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
'''Ejercicio 10'''
T=1000
f= np.linspace(-1,1,T)
rect=signal.windows.boxcar(T)
black2=np.blackman(T)
# RF_rectang=abs(np.sin(f*T/2)/np.sin(f/2))
RF_rectang=abs(np.fft.fft(rect))
RF_blackman=abs(np.fft.fft(black2))
with np.errstate(divide='ignore', invalid='ignore'):
RFdB_r=np.clip(20*np.log10(abs(np.fft.fftshift(RF_rectang))),-200,100)
RFdB_B=np.clip(20*np.log10(abs(np.fft.fftshift(RF_blackman))),-200,100)
max_RFdB_r=max(RFdB_r)
max_RFdB_B=max(RFdB_B)
RFdB_rn=RFdB_r/max_RFdB_r
RFdB_Bn=RFdB_B/max_RFdB_r
'''Arreglar grafico'''
plt.figure(1)
plt.grid()
plt.plot(f,RFdB_Bn,'g')
plt.plot(f,RFdB_rn,'b')
plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1/Item2.py
from FuncionesTP import *
'''
En este ejercicio se generan 6 señales de ruido con distribución Gaussiana y con los largos pedidos
en la consigna. Cada ruido se genera con una media nula y una desviación estandar igual a 1.
'''
Señalrandom1 = np.random.normal(0, 1, 5)
Señalrandom2 = np.random.normal(0, 1, 10)
Señalrandom3 = np.random.normal(0, 1, 100)
Señalrandom4 = np.random.normal(0, 1, 1000)
Señalrandom5 = np.random.normal(0, 1, 10000)
Señalrandom6 = np.random.normal(0, 1, 100000)
#A continuación se calculan la media y la desviación estándar de cada ruido generado utilizando las funciones
#pedidas en el Item 1 y que se encuentran definidas en el módulo "Funciones"(Funciones.py).
#Se redondea a dos decimales para fines prácticos.
lamedia1=lamedia(Señalrandom1)
desvioestandar1=round(desvioestandar(Señalrandom1,lamedia1),2)
lamedia2=lamedia(Señalrandom2)
desvioestandar2=round(desvioestandar(Señalrandom2,lamedia2),2)
lamedia3=lamedia(Señalrandom3)
desvioestandar3=round(desvioestandar(Señalrandom3,lamedia3),2)
lamedia4=lamedia(Señalrandom4)
desvioestandar4=round(desvioestandar(Señalrandom4,lamedia4),2)
lamedia5=lamedia(Señalrandom5)
desvioestandar5=round(desvioestandar(Señalrandom5,lamedia5),2)
lamedia6=lamedia(Señalrandom6)
desvioestandar6=round(desvioestandar(Señalrandom6,lamedia6),2)
# Se calculan las diferencias porcentuales con un redondeo a 0 decimales.
dif1=round((desvioestandar1-1)*100,0)
dif2=round((desvioestandar2-1)*100,0)
dif3=round((desvioestandar3-1)*100,0)
dif4=round((desvioestandar4-1)*100,0)
dif5=round((desvioestandar5-1)*100,0)
dif6=round((desvioestandar6-1)*100,0)
# Se presentan los resultados obtenidos.
print(f" N σ %")
print(f" 5 {desvioestandar1} {int(dif1)}")
print(f" 10 {desvioestandar2} {int(dif2)}")
print(f" 100 {desvioestandar3} {int(dif3)}")
print(f" 1000 {desvioestandar4} {int(dif4)}")
print(f" 10000 {desvioestandar5} {int(dif5)}")
print(f"100000 {desvioestandar6} {int(dif6)}")
<file_sep>/Scripts DSP 2020/TP1old/TP1final/TP1/Items/Item5.py
from FuncionesTP import *
import time
import heapq
'''En este script se implementan las funciones mediamovild y mediamovildr (FuncionesTP) para aplicar el filtro de media movil a la señal senoidal del Item 1 (x(t)=sen(2pi*f*t)) de manera directa y recursiva, respectivamente. Se comparan los tiempos de ejecución de cada una. Finalmente, se aplica el filtro de modo tal que se deja pasar la componente de 10 kHz de dicha señal, atenuendo la energía en la frecuencia indicada alrededor de 3 dB por debajo de la señal original.
'''
s1=señal # Función x(t)=sen(2pi*f*t) definida en módulo FuncionesTP.
n=t
N = len(n)
M=2 # Largo de la ventana del filtro de media movil calculado para conseguir el objetivo solicitado en la consigna.
# Comparación de tiempos de ejecución de ambas funciones.
time1 = time.time() # Iniciar tiempo.
xfd=mediamovild(s1,M) # Ejecutar función.
tiempo_d = time.time()-time1 # Calcular tiempo de ejecucion total.
time2 = time.time() # Iniciar tiempo.
xfr= mediamovildr(s1,M) # Ejecutar función.
tiempo_r = time.time()-time2 # Calcular tiempo de ejecucion total.
#Reporte de resultados temporales
datos=[["Directa", round(tiempo_d*1000,2)],["Recursiva",round(tiempo_r*1000,2)]]
Tabla = """\
+----------------------------------------------------+
| Implementación del FMM | Tiempo de ejecución [ms] |
|----------------------------------------------------|
{}
+----------------------------------------------------+\
"""
Tabla = (Tabla.format('\n'.join("| {:<21s} | {:>25} |".format(*fila)
for fila in datos)))
print ("\n")
print(" Resultados Item 5 ")
print (Tabla)
#FFT's
FFT=abs(np.fft.fft(s1)) #FFT de la señal original
FFTd=abs(np.fft.fft(xfd)) #Calcular la FFt para la señal filtrada con media movil directa
FFTr=abs(np.fft.fft(xfr)) #Idem recursiva
Maxlabel1=heapq.nlargest(2, FFTd) #Crear un vector de máximos de la señal FFTd (Corresponderán a los magnitudes en 0 Hz y 10 kHz)
Maxlabel1=int(round(Maxlabel1[1])) #Almacenar el valor maximo en una variable (Es decir la amplitud en 10 kHz)
Maxlabel2=heapq.nlargest(2, FFTr) #Idem recursiva
Maxlabel2=int(round(Maxlabel2[1]))
Maxlabel=heapq.nlargest(2, FFT)
Maxlabel=int(round(Maxlabel[1]))
#Gráficos
f = np.arange(0,fs/2,(fs/2)/int(N/2)) #Crear un vector de muestras para graficar con relacion a la Frecuencia de sampleo
t = np.arange(0,N)
#Gráficos en muestras
sp1=plt.figure('Item 5: Comparación en muestras')
plt.subplot(3,1,1)
plt.plot(t[0:round(N/64)],s1[0:round(N/64)],'#738EB6') #Gráfico de la señal original del punto uno
plt.title('Señal original')
plt.grid('both')
plt.ylabel('x [n]')
plt.xlabel('Número de muestra [n]')
sp1=plt.subplot(3,1,2)
plt.plot(t[0:round(N/64)],xfd[0:round(N/64)],'#BF76D2') #Grafico de la señal filtrada con la media movil directa
plt.title('Señal filtrada por media movil directa')
plt.grid('both')
plt.ylabel('xfd [n]')
plt.xlabel('Número de muestra [n]')
sp1=plt.subplot(3,1,3)
plt.plot(t[0:round(N/64)],xfr[0:round(N/64)],'#e0503f') #Grafico de la señal filtrada con la media movil recursiva
plt.title('Señal filtrada por media movil recursiva')
plt.grid('both')
plt.ylabel('xfr [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
#Gráficos en frecuencias.
plt.figure('Item 5: Comparación en frecuencias')
sp2=plt.subplot(3,1,1)
plt.plot(f,FFT[0:int(N/2)],'#738EB6') #Grafico en frecuencia de la señal filtrada con la media movil directa
plt.title('Señal original')
plt.grid('both')
plt.ylabel('X[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel)}",xy=(10100,Maxlabel-1100))
sp2=plt.subplot(3,1,2)
plt.plot(f,FFTd[0:int(N/2)],'#BF76D2') #Grafico en frecuencia de la señal filtrada con la media movil directa
plt.title('Señal filtrada por media movil directa')
plt.grid('both')
plt.ylabel('XFD[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel1)}",xy=(10100,Maxlabel1-1100))
sp2=plt.subplot(3,1,3)
plt.plot(f,FFTr[0:int(N/2)],'#e0503f') #Grafico en frecuencia de la señal filtrada con la media movil recursiva
plt.grid('both')
plt.ylabel('XFR[k]')
plt.xlabel('Frecuencia [Hz]')
plt.Axes.annotate(sp2, f"{round(Maxlabel2)}",xy=(10100,Maxlabel2-1100))
plt.title('Señal filtrada por media movil recursiva')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/scripts varios/testies.py
import matplotlib.pyplot as plt
import numpy as np
import math
import heapq
import time
import soundfile as sf
from convolucion import *
from scipy import signal
# mu = 3
# variance = 2
# sigma = math.sqrt(variance)
# x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
# plt.plot(x, stats.norm.pdf(x, mu, sigma))
# plt.show()
# def mediamovild(x,M,defas):
# # for i in range(len(x)):
# cumsum = np.cumsum(np.insert(x,M,defas))
# salida = (cumsum[M:]- cumsum[:-M])/float(M)
# # salida[i]=np.cumsum(M)
# return salida
# # return cumsum / float(M)
# mmd=mediamovild(data,3,3)
'''
Cosas para el punto 1
for i in range(0, len(data)):
data[i] = int(data[i])
print ("\n")
print("La lista ingresada es: ",data)
print ("\n")
rmsdata = data
for i in range(0, len(rmsdata)):
rmsdata[i] = abs(rmsdata[i])**2
## definicion de funciones:
def lamedia(input):
# return np.sum(input)/(len(input))
return st.mean(input)
def desviomedio(input,media):
# return np.sum(abs(input-media))/(len(input))
return st.median(input)
def desvioestandar(input,media):
# return (np.sum(abs(input-media)**2)/len(input))**1/2
return st.stdev(input)
def rms(input):
# return (np.sum(input)/len(input))**1/2
return (st.mean(input))**1/2
'''
def mediamovild(x,M):
y=np.zeros(len(x))
aux=np.append(x,np.zeros(M))
for i in range(len(x)):
for j in range(0,M+1):
y[i]=y[i]+aux[i+j]
y[i]=y[i]*(1/(M+1))
return y
# xfd=mediamovild(data,50)
# print("La media movil es: ",xfd)
def mediamovildr(x,M):
y=np.zeros(len(x))
y[0]=(1/(M+1))*np.sum(x[:M+1])
aux=np.append(x,np.zeros(M))
for i in range(1,len(x)):
y[i]=y[i-1]+(1/(M+1))*aux[i+M]-(1/(M+1))*aux[i-1]
return y
#xfr=mediamovildr(data,50)
#
# print("mmd recursiva: ", xfr)
# F = 10000
#
# T = 1/F
#
# Fs = 44100
#
# Ts = 1/Fs
#
# t = np.arange(0,0.5*T,Ts)
#
# señal = 2 + np.sin(2*np.pi*F*t)
#
# señalfft = np.fft.fft(señal)
#
# print("fft: ",señalfft)
#
# plt.plot(t,señalfft)
#
# plt.show()
fs = 44100
t = 0.5
n=np.arange(0,t,1/fs) #vector de muestras
N = len(n)
x=2 + np.sin(2*np.pi*10000*n) #defino funcion sen(2pi*f*t)
X=np.fft.fft(x) #calculo de la dft
Xr=np.fft.rfft(x)
Xmax=max(X)
# cont=0
# while X>=10000:
# cont=cont+1
# maximos[cont]=X[cont]
X1=abs(X) #tomo el modulo
w0=10000*np.pi/22050
M=16
w=np.arange(-1*np.pi,np.pi,2*np.pi/22050)
print('tuco: ',len(w))
H=abs((1/(M+1))*((np.sin(w*(M+1)/2))/(np.sin(w/2))))
M=int(0.01*len(x))
# Comparación de tiempos de ejecución de ambas funciones.
t = time.time() # Iniciar tiempo.
xfd=mediamovild(x,M) # Ejecutar función.
tiempo_d = time.time()-t # Calcular tiempo de ejecucion total.
t = time.time() # Iniciar tiempo.
xfr= mediamovildr(x,M) # Ejecutar función.
tiempo_r = time.time()-t # Calcular tiempo de ejecucion total.
print(f"Directo: {round(tiempo_d,3)}, Recursiva: {round(tiempo_r,3)}")
tucardo=heapq.nlargest(5,X1)
FFTd=abs(np.fft.fft(xfd))
tuco=heapq.nlargest(5,FFTd)
FFTr=abs(np.fft.fft(xfr))
ventanilla=signal.windows.boxcar(M+1)/(M+1)
xfc=np.convolve(x,ventanilla)
FFTc=abs(np.fft.fft(xfc))
print("maximos de conv",heapq.nlargest(5,FFTc) )
print("largo", len(xfc))
tuco1=heapq.nlargest(5,FFTr)
print(tuco)
print(tuco1)
print(tucardo)
f = np.arange(0,fs/2,(fs/2)/int(N/2))
plt.figure(1)
plt.plot(f,X1[0:int(N/2)])
plt.show()
'''Ejercicio 6'''
M=int(0.01*len(x))
ri_MM=np.ones(M+1)/(M+1)
xMM=np.convolve(x,ri_MM)
FFT_MM=abs(np.fft.fft(xMM))
tuco2=heapq.nlargest(5,FFT_MM)
print(tuco2)
f = np.arange(0,fs/2,(fs/2)/int(N/2))
''' Aca viene todo el mambo de la normalización que nose como hacer '''
# xfd_norm=xfd/np.linalg.linalg.norm(xfd)
# xfr_norm=xfr/np.linalg.linalg.norm(xfr)
# xMM_norm=xMM/np.linalg.linalg.norm(xMM)
# print(np.linalg.linalg.norm(xfd))
xfd_norm=xfd/max(xfd)
xfr_norm=xfr/max(xfr)
xMM_norm=xMM/max(xMM)
print(np.linalg.linalg.norm(xfd))
figure,axis = plt.subplots(3)
axis[0].plot(xfd_norm[0:M])
axis[1].plot(xfr_norm[0:M])
axis[2].plot(xMM_norm[0:M])
plt.show()
#
# '''Ejercicio 7'''
# m=np.arange(M-1)
# blackman=0.42 - ((0.5)*np.cos((2*np.pi*m)/(M-1))) + ((0.08)*np.cos((4*np.pi*m)/(M-1)))
# xBlack=np.convolve(x,blackman)
# print(len(xBlack))
# # figure,axis = plt.subplots(3)
# # axis[0].plot(xfd_norm[0:M])
# # axis[1].plot(xfr_norm[0:M])
# # axis[2].plot(xBlack[0:M])
# # plt.show()
#
# '''Ejercicio 8 '''
# '''
# revisar aca la convolucion
# '''
# [RIR,Fs] = sf.read("RIR.wav")
# [Midi69,Fs1] = sf.read("Midi69.wav")
# L=len(Midi69)
# K=len(RIR)
# cLineal=np.convolve(Midi69,RIR)
# cCirc=np.convolve(Midi69[:K],RIR)
# cCircular=convCirc(Midi69,RIR)
# sf.write('RIR.wav', RIR, Fs)
# sf.write('Midi69.wav', RIR, Fs1)
# figure,axis = plt.subplots(3)
# axis[0].plot(cLineal)
# axis[1].plot(cCircular)
# axis[2].plot(cCirc)
# plt.show()
#
# """
# escribir los archivos wav
#
# """
#
# '''Ejercicio 9 '''
# plt.figure(1)
# plt.plot(w,H)
# plt.show()
#
# '''Ejercicio 10'''
# T=1000
# f= np.linspace(-1*np.pi,np.pi,T)
# rect=signal.windows.boxcar(T)
# black2=np.blackman(T)
# # RF_rectang=abs(np.sin(f*T/2)/np.sin(f/2))
# RF_rectang=abs(np.fft.fft(rect))
# RF_blackman=abs(np.fft.fft(black2))
# RFdB_r=np.clip(20*np.log10(np.fft.fftshift(RF_rectang)),-100,100)
# RFdB_B=np.clip(20*np.log10(np.fft.fftshift(RF_blackman)),-100,100)
# '''Arreglar grafico'''
# plt.figure(1)
# # plt.plot(f,RFdB_B)
# # plt.plot(f,RFdB_r)
# plt.grid()
# plt.plot(f,RFdB_B,'g')
# plt.plot(f,RFdB_r,'b')
# plt.show()
#
# '''Ejercicio 11'''
# cLineal_fft=convLin(Midi69,RIR)
# cCirc=convLin(Midi69[:K],RIR)
# cCircular=convCirc(Midi69,RIR)
# figure,axis = plt.subplots(3)
# axis[0].plot(cLineal)
# axis[1].plot(cCircular)
# axis[2].plot(cCirc)
# plt.show()
<file_sep>/Scripts DSP 2020/FIR/Func.py
import numpy as np
from scipy import signal
def beta_K(A):
A=abs(A)
beta=0
if A>=21 and A<=50:
beta=0.5842*((A-21)**(0.4)) + 0.07886*(A-21)
elif A > 50:
beta=0.1102*(A-8.7)
return beta
def Kaiser_M(A,deltaw):
M=int((A-8)/(2.285*deltaw*np.pi))+1
return M
def iLP(M,wc):
n=np.linspace(0,M,M+1)
n0=M/2
h=np.sinc(wc*(n-n0))*wc
return h,n
def iHP(M,wc):
n=np.linspace(0,M,M+1)
n0=(M/2)
PT=np.sinc(1*(n-n0))*1
LP=np.sinc(wc*(n-n0))*wc
h=PT-LP
return h,n
def iBP(M,wc1,wc2):
n=np.linspace(0,M,M+1)
n0=(M/2)
LP1=np.sinc(wc1*(n-n0))*wc1
LP2=np.sinc(wc2*(n-n0))*wc2
h=LP2-LP1
return h,n
def iBS(M,wc1,wc2):
n=np.linspace(0,M,M+1)
n0=(M/2)
LP=np.sinc(wc1*(n-n0))*wc1
LP1=np.sinc(1*(n-n0))*1
LP2=np.sinc(wc2*(n-n0))*wc2
BP=LP1-LP2
h=LP+BP
return h,n
<file_sep>/Scripts DSP 2020/TP1old/TP1final/TP1/Items/Item6.py
from FuncionesTP import *
L=int(0.01*len(señal))
Largo=len(señal)
ri_MM=np.ones(L)/(L) #Respuesta al impulso del FMM de largo igual al 1% del largo de la señal.
sFMM=np.convolve(señal,ri_MM) #FMM a través de convolución lineal.
sfd=mediamovild(señal,L)
sfr=mediamovildr(señal,L)
sfd_norm=sfd/max(sfd)
sfr_norm=sfr/max(sfr)
sFMM_norm=sFMM/max(sFMM)
#Se comparan los resultados en un gráfico
t=np.arange(0,Largo)
sp1=plt.figure('Item 6')
plt.subplot(3,1,1)
plt.plot(t[int(Largo/64):int(Largo/48)],sfd_norm[int(Largo/64):int(Largo/48)],'#738EB6')
plt.title('Señal filtrada con media movil directa')
plt.grid('both')
plt.ylabel('xfd [n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(3,1,2)
plt.plot(t[int(Largo/64):int(Largo/48)],sfr_norm[int(Largo/64):int(Largo/48)],'#BF76D2')
plt.title('Señal filtrada con media movil recursiva')
plt.grid('both')
plt.ylabel('xfr [n]')
plt.xlabel('Número de muestra [n]')
plt.subplot(3,1,3)
plt.plot(t[int(Largo/64):int(Largo/48)],sFMM_norm[int(Largo/64):int(Largo/48)],'#e0503f')
plt.title('Señal filtrada a traves de convolución')
plt.grid('both')
plt.ylabel('y [n]')
plt.xlabel('Número de muestra [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/ks.py
"""
Created on 07/08/2014
@author: <NAME>
"""
from random import random
from scipy.io.wavfile import write
from pylab import *
from operator import add
from scipy.signal import lfilter, freqz
import math
import numpy as np
import sys
import matplotlib.pyplot as plt
import time
VERBOSE = True
def lagrange(N, delay):
h = [1 for i in range(N+1)]
for n in range(N+1):
for k in range(N+1):
if k != n:
h[n] = h[n] * (delay-k)/(n-k)
return h
"""
# This is the core of the algorithm
# The delay line is updated averaging the current sample and the previous one
# 0.996 is the damping factor
"""
def karplus_strong_diff_eq(f0,Fs,duration):
period = int(round(Fs/f0))
period_frac = Fs/f0
N = Fs*duration
# original karplus-strong with S = 0.5 , weighted ks with others values
rho = 0.996
#rho = 1.0
S = 0.5
b0 = 1-S
b1 = S
t_60 = 4
rho = 0.001**(1.0/(f0*t_60))
B = 0 # brightness factor
# one-zero damping filter
#b1 = 0.5*B # S = B/2
#b0 = 1-b1 # 1-S
# two-zero damping filter
#b0 = (1.0 + B)/2
#b1 = (1.0 - B)/4
g0 = rho*b0
g1 = rho*b1
# pluck (excitation) is made by filling the delay line with random values
t0 = time.clock()
delayline = [random() - 0.5 for i in range(period)]
samples = []
N_lagrange = 4
delay = 0#Fs/f0 - int(Fs/f0) + N_lagrange/2 - 0.5
print("delay",delay)
h_lagrange = lagrange(N_lagrange, delay )
coeff = np.convolve([g0,g1], h_lagrange)
print(coeff)
print([g0,g1])
for n in range(N) :
samples.append(delayline[0])
# one-zero damping filter and original KS (INTERPOLATED)
j=0
interpolated = 0
for c in coeff:
interpolated += c*delayline[j]
j+=1
delayline.append(interpolated)
# one-zero damping filter and original KS (NOT INTERPOLATED)
#delayline.append( g0 * delayline[0] + g1 * delayline[1])
# two-zero damping filter
#delayline.append( g1 * delayline[0] + g0 * delayline[1] + g1 * delayline[2])
delayline.pop(0)
print ("Elapsed time: ", time.clock() - t0, "s")
return samples,delayline
"""
Initialization of the delay line with samples of white noise
random samples have the physical meaning of string displacement
"""
def excitation(period) :
delayline = np.array([random() - 0.5 for _ in range(period)])
return delayline
"""
Definition of the low pass filter, unity-dc-gain one pole : up-pick , down-pick
:p takes two different values 0 or 0.9 depending on the pick direction
"""
def pick_direction(delayline,p=0.9) :
if VERBOSE:
print("pick_direction : "," angle = ",p)
b_pickdir = [1-p]
a_pickdir = [1,-p]
return lfilter(b_pickdir,a_pickdir,delayline)
"""
Definition of the comb filter for the position of the pick
beta is the position of the pick: 0 is the "bridge", 1 is the "nut"
"""
def pick_position(delayline,D,beta=0.5) :
if VERBOSE:
print("pick_position : "," pickpos = ",beta)
P = D
pickpos = int(math.floor(P*beta)) # Pick position
b_pickpos = np.array([1.0] + ([0]*(pickpos-1)) + [-1]) # Numerator zeros coefficients
a_pickpos = np.array([1.0]) # denominator poles coefficients
return lfilter(b_pickpos,a_pickpos,delayline)
"""
Dynamic level low pass filter discretized with the bilinear transform
The spectral centroid tipically rises as plucking/striking becomes more energetic
"""
def dynamic_level_lpfilter(f0,Fs,samples,L) :
if VERBOSE:
print("dynamic_level_lpfilter : "," L = ",L)
# w1 = 2*pi*f0 # fundamental frequency in radians per second
# w1_tilde = w1/(Fs*2)
# Contracted formula
w1_tilde = math.pi*f0/Fs
b_dyn = np.array([w1_tilde, w1_tilde])
a_dyn = np.array([(1+w1_tilde),w1_tilde-1])
y = lfilter(b_dyn,a_dyn,samples)
# Panning among original signal and the low pass
L0 = L**(1/3)
samples = np.array(samples)
samples = (L*L0*samples) + (1.0-L)*y
return samples
"""
Original digitar KS damping filter, two-point avarage
The filter goes in the string feedback loop
"""
def original_KS_digitar_damping_filter(Fs,f0,D) :
if VERBOSE:
print("original_KS_digitar_damping_filter")
rho = 1 #0.996
g0 = 0.5*rho
g1 = 0.5*rho
N_lagrange = 4
OldMax = 1
OldMin = 0
NewMin = N_lagrange-0.5
NewMax = N_lagrange+0.5
delta = Fs/f0 - int(Fs/f0)
NewDelta = (((delta - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
print(delta)
print(NewDelta)
h_lagrange = lagrange(N_lagrange, NewDelta)
coeff = (-1*np.convolve([g0,g1],h_lagrange)).tolist()
coeff = [-g0,-g1]
print(coeff)
b = np.array([1.0]) # Zeros numerator coefficients
#b = np.array(([0]*D) + h_lagrange)
a = np.array([1.0] + ([0]*(D-1)) +(coeff)) # Poles denominator coefficients
return b,a
"""
Original EKS damping filter, weighted two-point avarage
The filter goes in the string feedback loop
Hd(z) = (1-S) + S*z^(-1)
S is stretching factor, it adjusts the relative decay-rate for high versus low frequencies in the string
S = 0 or S = 1 the decay time is stretched infinitely (no decay)
S = 0.5 fastest decay, the filter reduce to the KS digitar damping filter (avaraging the last two samples of the delay line)
The decay rate is always infinity for DC, and higher frequencies decay faster than lower frequencies when S is in (0,1)
"""
def original_EKS_damping_filter(D,S) :
if VERBOSE:
print("original_EKS_damping_filter : "," S = ",S)
rho = 0.996
g0 = (1-S)*rho
g1 = S*rho
b = np.array([1.0]) # Zeros numerator coefficients
a = np.array([1.0] + ([0]*(D-3)) + [-g0, -g1]) # Poles denominator coefficients
return b,a
"""
ONE-ZERO STRING damping FILTER
To control the overall decay rate, another (frequency independent) gain multiplier rho in (0,1) was introduced
to give the loop filter Hd(z) = rho[(1-S) + S*z^(-1)]
Since this filter is applied once per period P = (self.D) at the fundamental frequency, an attenuation of |Hd(e^(j*2*pi/P)| = rho
occours once each P samples. Setting rho to achieve a decay of -60 dB in t_60 seconds is obatained solving:
rho^(t_60/(P*T)) = 0.001 => rho = (0.001)^((P*T)/t_60)
note that P * T = f0*T = f0/f0 = 1
t_60 is the decay time of the string
B is a brightess parameter between 0 and 1
"""
def one_zero_damping_filter(f0,D,t_60=4,B=0.9) :
if VERBOSE:
print("one_zero_damping_filter : "," t_60 = ",t_60," B = ",B)
rho = 0.001**(1.0/(f0*t_60))
h0 = 0.5*B # S = B/2
h1 = 1-h0 # 1-S
g0 = rho*h0
g1 = rho*h1
b = np.array([1.0]) # Zeros numerator coefficients
a = np.array([1.0] + ([0]*(D-3)) + [-g0 , -g1]) # Poles denominator coefficients
return b,a
"""
TWO-ZERO STRING damping FILTER
A disadvantage of the decay-stretching parameter is that it affects tuning, except when S = 0.
This can be alleviated by going to a second-order, symmetric, linear-phase FIR filter having a
transfer function of the form Hd(z) = g1 + g0*z^(-1) + g1*z^(-2) = z^(-1)*[g0 + g1*(z+z^(-1))]
Due to the symmetry of the impulse response hd = [g1,g0,g1,0,0,...] about time n=1, only two
multiplies and two additions are needed per sample. The previous one-zero loop-filter required
one multiply and two additions per sample. Since the delay is equal to one sample at all the
frequencies (in the needed conefficien range) we obatin tuning invariance for the price of one
additional multiply per sample. We also obatain a bit more lowpass filtering.
The one-zero loop filter has a "lighter-sweeter", tone than the two-zero case. In general,
the tone is quite sensitive to the details of all filtering in the feedback path.
t_60 is the decay time of the string
B is a brightess parameter between 0 and 1
"""
def two_zero_damping_filter(f0,D,t_60=4,B=0.9) :
if VERBOSE:
print("two_zero_damping_filter : "," t_60 = ",t_60," B = ",B)
rho = 0.001**(1.0/(f0*t_60))
h0 = (1.0 + B)/2
h1 = (1.0 - B)/4
g0 = rho*h0
g1 = rho*h1
b = np.array([1.0]) # Zeros numerator coefficients
a = np.array([1.0] + ([0]*(D-3)) + [-g1 , -g0, -g1]) # Poles denominator coefficients
return b,a
def pick_string(f0, Fs, duration, **kwargs) :
damping_filter_types = ["KS", "EKS", "one_zero", "two_zero"]
D = int(Fs/f0)
#D_frac = Fs/f0
N = Fs*duration
x = np.array([0]*N)
"""
if kwargs is not None:
for key, value in kwargs.items():
print (key,value)
"""
name = kwargs.get('name')
if not name:
name = "note"
damping_filter = kwargs.get("damping_filter")
if not damping_filter:
damping_filter = "EKS"
else :
if not damping_filter in damping_filter_types :
damping_filter = "EKS"
if damping_filter == "KS":
b,a = original_KS_digitar_damping_filter(Fs,f0,D) # Determine the coefficents of the damping filter
elif damping_filter == "EKS":
S = kwargs.get("S")
if not S:
S = 0.8 # S is stretching factor, it adjusts the relative decay-rate for high versus low frequencies in the string
#S = 0.5 -> Original digitar KS damping filter, two-point avarage
b,a = original_EKS_damping_filter(D,S) # Determine the coefficents of the damping filter
else :
t_60 = kwargs.get("t_60")
if not t_60:
t_60 = 4.0 # in seconds
#t_60 = 0
#t_60 = 10
#t_60 = 0.01
B = kwargs.get("B")
if not B:
B = 0 # B is a brightess parameter between 0 and 1
if damping_filter == "one_zero":
b,a = one_zero_damping_filter(f0,D,t_60,B) # Determine the coefficents of the damping filter
elif damping_filter == "two_zero":
b,a = two_zero_damping_filter(f0,D,t_60,B) # Determine the coefficents of the damping filter
# Plot the frequency response of the damping filter
"""nfft = 4096
F = linspace(0, 1000*2*math.pi/Fs, 4096);
w,h = freqz(b,a,F)
h_dB = 20 * log10(abs(h))
plot(w/max(w),h_dB)
ylabel('Magnitude (db)')
xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
title(r'Frequency response')
show()"""
###
""" FILTER THE EXCITATION, BEFORE LOOP STRING """
# Initial state with random excitation
delayline = excitation(max([len(a),len(b)]) - 1)
pick_dir = kwargs.get("pick_direction")
if pick_dir is None:
pick_dir = True
pick_pos = kwargs.get("pick_position")
if pick_pos is None:
pick_pos = True
if pick_dir:
angle = kwargs.get("angle")
if not angle:
# Choice of pick direction (angle)
angle = 0.9 # values between 0 and 1
delayline = pick_direction(delayline,angle)
if pick_pos:
position = kwargs.get("position")
if not position:
# choice of pick position (bridge,nut)
position = 0.0 # values between 0 and 1
delayline = pick_position(delayline,D,position)
""" FILTER IN THE LOOP STRING """
# Loop-String applying the damping filter
samples, delayline = lfilter(b,a,x,-1,delayline)
#samples, delayline = karplus_strong_diff_eq(f0,Fs,duration)
""" FILTER AFTER THE LOOP STRING """
# Dynamic Level Low Pass Filter
dynamic_level = kwargs.get("dynamic_level")
if dynamic_level is None:
dynamic_level = True
if dynamic_level:
L = kwargs.get("L")
if not L:
#L = 0
#L = 0.001
#L = 0.01
L = 0.1
#L = 0.2
#L = 0.32 # max is 1/3
samples = dynamic_level_lpfilter(f0,Fs,samples,L)
return samples
def wave(Fs,samples,name="note") :
scaled = np.int16(samples/np.max(np.abs(samples)) * 32767)
write(name+'.wav', Fs, scaled)
def play_chord(Fs,chord_frets,duration,offset_strum = 500):
A = 110; # The A string of a guitar is normally tuned to 110 Hz
offset_strings = [-5, 0, 5, 10, 14, 19] # offset of frets for each string E A D G B e
name_strings = ["E","A","D","G","B","E2"]
nsamples = Fs*duration
#frequencies = []
#delays = []
# 50 ms delay btw the strings
delay_strum = round(offset_strum*Fs/1000)
nsamples_strum = nsamples + 6*delay_strum
chord = np.zeros(nsamples)
chord_strum = np.zeros(nsamples_strum)
i = 0
for fret, offset, name_string in zip(chord_frets, offset_strings, name_strings):
# Each fret along a guitar's neck is a half tone
f = (A*2**((fret+offset)/12.0))
#frequencies.append(f)
#delays.append(round(Fs/f))
#samples = pick_string(f, Fs, duration, name = name_string, damping_filter = "one_zero",t_60=4)
samples = pick_string(f, Fs, duration, name = name_string, damping_filter = "two_zero",t_60=4,B=0.5,angle=0.9,position=0.5,L=0.1)
#samples = pick_string(f, Fs, duration, name = name_string, damping_filter = "KS", dynamic_level=False, pick_direction=False, pick_position=False)
if VERBOSE:
print("")
chord = chord + samples
chord_strum[i*delay_strum:(i*delay_strum)+nsamples] = chord_strum[i*delay_strum:(i*delay_strum)+nsamples] + samples
i+=1
return chord_strum
def main():
Fs = 16000
duration = 4
#name_string = "A"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS",dynamic_level=False, pick_direction=False, pick_position=False)
#name_string = "A_pickdirection_angle05"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS", angle = 0.5, dynamic_level=False, pick_position=False)
#name_string = "A_pickdirection_angle01"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS", angle = 0.1, dynamic_level=False, pick_position=False)
#name_string = "A_pickdirection_angle09_position0"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS", angle = 0.9, position = 0, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position1"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS", angle = 0.9, position = 1.0, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position05"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS", angle = 0.9, position = 0.5, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position06"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "KS", angle = 0.9, position = 0.6, )
#name_string = "A_pickdirection_angle09_position05_one_zero_t60_4_B1"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "one_zero", t_60 = 4, B=1, angle = 0.9, position = 0.5, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position05_one_zero_t60_10_B05"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "one_zero", t_60 = 10, B=0.5, angle = 0.9, position = 0.5, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position05_two_zero_t60_4_B05"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "two_zero", t_60 = 4, B=0.5, angle = 0.9, position = 0.5, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position05_two_zero_t60_10_B05"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "two_zero", t_60 = 10, B=0.5, angle = 0.9, position = 0.5, dynamic_level=False)
#name_string = "A_pickdirection_angle09_position05_one_zero_t60_4_B05_L02"
#name_string = "A_NOT_interpolated"
#A = pick_string(110, Fs = 16000, duration = 4, name = name_string, damping_filter = "one_zero", t_60 = 4, B=0.5, angle = 0.9, position = 0.5, L = 0.2)
#print(A)
#name_string = "A_pickdirection_angle09_position05_one_zero_t60_4_B1"
#A = pick_string(110, Fs = 44100, duration = 4, name = name_string, damping_filter = "one_zero", t_60 = 4, B=1, angle = 0.9, position = 0.5, L = 0.1)
name_string = "A_digitar_not_interpolated"
A = pick_string(110, Fs, duration = 4, name = name_string, damping_filter = "KS",dynamic_level=False, pick_direction=False, pick_position=False)
wave(Fs,A,name_string)
exit()
if len(sys.argv) != 7 :
print("You have to type the tab for the chord that you want to play. Ex: Karplus-Strong.py 3 3 2 0 1 3")
exit()
chord_frets = []
for i in range(len(sys.argv)) :
if i > 0 :
chord_frets.append(int(sys.argv[i]))
chord_strum = play_chord(Fs, chord_frets, duration,offset_strum = 500)
wave(Fs,chord_strum,'chord_strum.wav')
if __name__ == '__main__':
main()<file_sep>/Scripts DSP 2020/TP1old/TP1/Item4.py
from FuncionesTP import *
# Se generan las 10 señales de ruido aleatorio con media 0 y sigma 3
z31 = np.random.normal(0, 3, len(data))
z32 = np.random.normal(0, 3, len(data))
z33 = np.random.normal(0, 3, len(data))
z34 = np.random.normal(0, 3, len(data))
z35 = np.random.normal(0, 3, len(data))
z36 = np.random.normal(0, 3, len(data))
z37 = np.random.normal(0, 3, len(data))
z38 = np.random.normal(0, 3, len(data))
z39 = np.random.normal(0, 3, len(data))
z310 = np.random.normal(0, 3, len(data))
# Genero cada señal sumando la señal de entrada y un ruido
x31 = data + z31
x32 = data + z32
x33 = data + z33
x34 = data + z34
x35 = data + z35
x36 = data + z36
x37 = data + z37
x38 = data + z38
x39 = data + z39
x310 = data + z310
# Saco una señal de ruido promedio de las 10 señales de ruido generadas (solo ruido)
ruidoProm1=(1/10)*(z31+z32+z33+z34+z35+z36+z37+z38+z39+z310)
#Promedio de las señales con ruido agregado
prom2=(1/10)*(x31+x32+x33+x34+x35+x36+x37+x38+x39+x310)
sigmanoise=desvioestandar(ruidoProm1,lamedia(ruidoProm1))#Saco el sigma de la señal de ruido promedio
SNRprom=lamedia(prom2)/sigmanoise #Calculo el SNR de esa señal promedio con los valores obtenidos
print(f"sigma ruido promediado: {sigmanoise}")#Muestro los resultados para compararlos
print(f"SNR promedio: {SNRprom}")
#Calcula los SNR y los sigmas para las señales con promedio en ensamble.
SNR10,sigmaruido10=senales_con_ruido(data,0,3,10)
SNR100,sigmaruido100=senales_con_ruido(data,0,3,100)
SNR1000,sigmaruido1000=senales_con_ruido(data,0,3,1000)
#Tener cuidado con usar la media aa tambien.
<file_sep>/Scripts DSP 2020/TP1-LIONTI-VILLATARCO/Python/Items/Item8.py
from FuncionesTP import *
'''En este Script se busca estudiar la convolución de las señales de audio importadas 'Midi69.wav' y 'RIR.wav'.
Para ello se comparan los resultados de la convolución lineal, la convolución circular tomando el largo de la señal RIR y
la convolución circular equivalente a la lineal. Finalmente se exportan los resultados en archivos .wav. '''
#En esta sección se calculan las convoluciones pedidas en la consigna.
cLineal=np.convolve(Midi69,RIR) #Convolución lineal
cCirc,nc=cConv(Midi69,nMidi,RIR,nRIR,2) #Convolución circular tomando el largo de la señal RIR(señal N°2)
cCircular,nconv=convCircular(Midi69,nMidi,RIR,nRIR) #Convolución circular equivalente a convolución lineal.
#Se escriben los archivos .wav para cada señal obtenida.
sf.write('Audio\ConvolucionLineal.wav', cLineal, Fs)
sf.write('Audio\ConvolucionCircular.wav', cCirc, Fs)
sf.write('Audio\ConvolucionCircular-Lineal.wav', cCircular, Fs)
datos=[["Lineal",'ConvolucionLineal.wav', Fs],["Circular",'ConvolucionCircular.wav', Fs], ["Circular/Lineal",'ConvolucionCircular-Lineal.wav', Fs]]
Tabla = """\
+------------------------------------------------------------------+
| Convolución | Nombre de archivo | Fs |
|------------------------------------------------------------------|
{}
+------------------------------------------------------------------+\
"""
Tabla = (Tabla.format('\n'.join("\t| {:^15s} |\t {:^30} | {:^7} |".format(*fila)
for fila in datos)))
print ("\n")
print(" Los archivos .wav generados se guardan en la carpeta TP1\Audio de la siguiente manera: ")
print (Tabla)
#Se grafican los resultados.
sp1=plt.figure('Item 8: Comparación de convoluciones')
plt.subplot(3,1,1)
plt.plot(cLineal,'#738EB6')
# Gráfico de la convolución lineal y[n]= Midi69*RIR.
plt.title('Convolución lineal')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
sp1=plt.subplot(3,1,2)
plt.plot(nconv,cCircular,'#BF76D2')
# Grafico de la convolución circular y[n]= Midi69*RIR equivalente a la lineal.
plt.title('Convolución circular equivalente a lineal')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
sp1=plt.subplot(3,1,3)
plt.plot(nc,cCirc,'#e0503f')
# Gráfico de la convolución circular y[n]= Midi69*RIR de largo igual a la señal RIR.
plt.title('Convolución circular con largo RIR.wav')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/TP1-LIONTI-VILLATARCO/Python/Items/Item11.py
from FuncionesTP import *
'''En este Script se busca estudiar la convolución de las señales de audio importadas 'Midi69.wav' y 'RIR.wav' mediante el algoritmo de la DFT. Para ello se comparan los resultados de la convolución lineal, la convolución circular tomando el largo de la señal RIR y la convolución circular equivalente a la lineal. '''
cLineal=FFT_convLineal(Midi69,RIR) #Convolución lineal mediante FFT.
cCirc,nc=FFT_cConv(Midi69,nMidi,RIR,nRIR,2) #Convolución circular tomando el largo de la señal RIR(señal N°2) mediante FFT.
cCircular,nconv=FFT_convCircular(Midi69,nMidi,RIR,nRIR) #Convolución circular equivalente a convolución lineal mediante FFT.
#Gráficos
sp1=plt.figure('Item 11: Comparación de convoluciones con DFT')
plt.subplot(3,1,1)
plt.plot(cLineal,'#738EB6')
# Gráfico de la convolución lineal y[n]= Midi69*RIR.
plt.title('Convolución lineal')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
sp1=plt.subplot(3,1,2)
plt.plot(nconv,cCircular,'#BF76D2')
#Gráfico de la convolución circular y[n]= Midi69*RIR equivalente a la lineal.
plt.title('Convolución circular equivalente a lineal')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
sp1=plt.subplot(3,1,3)
plt.plot(nc,cCirc,'#e0503f')
#Gráfico de la convolución circular y[n]= Midi69*RIR de largo igual a la señal RIR.
plt.title('Convolución circular con largo RIR')
plt.grid('both')
plt.ylabel('y[n]')
plt.xlabel('Número de muestras [n]')
plt.subplots_adjust(hspace = 1.2)
plt.show()
<file_sep>/Scripts DSP 2020/TP1old/TP1final/TP1/Items/Item10.py
from FuncionesTP import *
''' Este Script compara gráficamente las respuetas en frecuencia en dB de las ventanas rectangular y blackman, ambas de largo T=1000 y con resolución dada por una Fs=44100 Hz.
'''
T=1000 #Largo de las ventanas.
#Se calculan las Respuestas en frecuencias de las ventanas con las definiciones de Scipy y usando FFT.
wRect=signal.windows.boxcar(T)
wBlackman = signal.blackman(T)
RFdB_R=RFdB_ventanas(np.fft.fft(wRect,fs),T) # Respuesta en Frecuencia de la ventana rectangular en dB.
RFdB_B=RFdB_ventanas(np.fft.fft(wBlackman,fs),T) # Respuesta en Frecuencia de la ventana blackman en dB.
f=np.arange(-1*np.pi,np.pi,2*np.pi/fs)
#Gráficos
#El siguiente gráfico es el utilizado para reportar los resultados del punto 10 debido a que presenta mayor precisión
plt.figure('Item 10')
plt.plot(f,np.fft.fftshift(RFdB_B),'#065535', label=' Ventana Blackman')
#Gráfico de la respuesta en frecuencia de la ventana Blackman
plt.plot(f,np.fft.fftshift(RFdB_R),'#f24738', label='Ventana Rectangular')
#Gráfico de la respuesta en frecuencia de la ventana rectangular
plt.legend()
plt.axis([-np.pi/32, np.pi/32, -80, 0])
plt.title("Respuesta en frecuencia ")
plt.ylabel("Amplitud [dB]")
plt.xlabel("Frecuencia angular ω [Rad/s]")
plt.xticks([-np.pi/32, 0, np.pi/32], ['-π/32','0', 'π/32'])
plt.grid('both')
plt.show()
<file_sep>/Scripts DSP 2020/Scripts TP2/Hd.py
from Funcionestp2 import *
eps=0.001
fs=44100
T=1/fs
n_samples=fs*2
pa=1/2
f1=220
p1=fs/f1
N= int(np.floor(fs/f1 -pa-eps))
pc=p1-N-pa
c=(1-pc)/(1+pc)
L0=5
L1=100
L2=500
L3=1000
L4=5000
L5=10000
L6=20000
RL0=np.exp(-np.pi*L0*T)
RL1=np.exp(-np.pi*L1*T)
RL2=np.exp(-np.pi*L2*T)
RL3=np.exp(-np.pi*L3*T)
RL4=np.exp(-np.pi*L4*T)
RL5=np.exp(-np.pi*L5*T)
RL6=np.exp(-np.pi*L6*T)
def IIRdelbueno(senal,a,N):
delayline=np.zeros(N)
x=np.append(senal,delayline)
y=np.zeros_like(x)
for i in range(len(x)):
y[i]=(1-a)*x[i]+a*delayline[N-1]
delayline=np.append(y[i],delayline[0:N-1])
return y
Karpluscuerda = karplus_strong(n_samples,1,N)
y0=IIRdelbueno(Karpluscuerda,RL0,1)
y1=IIRdelbueno(Karpluscuerda,RL1,1)
y2=IIRdelbueno(Karpluscuerda,RL2,1)
y3=IIRdelbueno(Karpluscuerda,RL3,1)
y4=IIRdelbueno(Karpluscuerda,RL4,1)
y5=IIRdelbueno(Karpluscuerda,RL5,1)
y6=IIRdelbueno(Karpluscuerda,RL6,1)
sf.write('RL0.wav',y0,fs)
sf.write('RL1.wav',y1,fs)
sf.write('RL2.wav',y2,fs)
sf.write('RL3.wav',y3,fs)
sf.write('RL4.wav',y4,fs)
sf.write('RL5.wav',y5,fs)
sf.write('RL6.wav',y6,fs)
# ffty=np.fft.fft(y0)
# fdB=20*np.log10(abs(ffty))
# fase1=np.angle(ffty)
# fase2=np.angle(fftz2)
# plt.plot(fdB[0:2500])
# plt.plot(fdB)
# plt.plot(fdB[0:int(fs/2)])
# plt.show()
| 7e508ed80912d1d2ef968de1d9f2165e14678faf | [
"Python"
] | 54 | Python | FranLion/DSP2020 | 929b2098743df0b883ad5ef1ddda0244535a25b0 | 5c2eae9b61270f9dd7fafb5d508199df84a6814e |
refs/heads/master | <file_sep>import time
class user:
def __init__(self,driver):
self.driver = driver
self.click_user="//*[@class='content users']"
self.click_on_user="(//*[@class='userNameContainer'])[2]"
self.close_user="//*[@id='closeUserDataLightBoxBtn']"
def clk_user(self):
self.driver.find_element_by_xpath(self.click_user).click()
time.sleep(8)
self.driver.find_element_by_xpath(self.click_on_user).click()
time.sleep(8)
self.driver.find_element_by_xpath(self.close_user).click()
time.sleep(8)<file_sep>from constants import constants as cs
from selenium.webdriver.support.select import Select
class view:
def __init__(self,driver):
self.driver = driver
self.click_view_xpath="//*[text()='View Time-Track']"
def click_view(self):
self.driver.find_element_by_xpath(self.click_view_xpath).click()
# def select_date(self):
#
# day=Select(self.driver.find_element_by_xpath(self.click_date))
# day.select_by_visible_text("Previous quarter")
<file_sep>import time
from constants import constants as cs
from selenium.webdriver.support.select import Select
import moment
from selenium import webdriver
class task:
def __init__(self,driver):
self.driver=driver
self.click_view_xpath="//*[@class='content tasks']"
self.click_add_new="(//*[@class='title ellipsis'])[2]"
self.click_new_project="//*[@class='item createNewProject ellipsis']"
self.enter_project_name="//*[@id='projectPopup_projectNameField']"
self.enter_custmr_name="(//*[@class='x-btn-center'])[1]"
self.click_cu_name="(//*[@class='x-menu-item-icon '])[5]"
self.click_create_btn="//*[@id='projectPopup_commitBtn']"
def click_on_task(self):
self.driver.find_element_by_xpath(self.click_view_xpath).click()
def clk_add_new(self):
self.driver.find_element_by_xpath(self.click_add_new).click()
def click_on_new_project(self):
self.driver.find_element_by_xpath(self.click_new_project).click()
def enter_a_project_name(self):
self.driver.find_element_by_xpath(self.enter_project_name).send_keys(cs.cur_time)
def click_enter_cutmr(self):
self.driver.find_element_by_xpath(self.enter_custmr_name).click()
self.driver.find_element_by_xpath(self.click_cu_name).click()
time.sleep(10)
self.driver.find_element_by_xpath(self.click_create_btn).click()
<file_sep>import moment
URL="http://localhost:8095/login.do"
UN="admin"
PWD="<PASSWORD>"
cur_time = moment.now().strftime("%d-%m-%Y_%H-%M-%S")
<file_sep>import time
from constants import constants as cs
class report:
def __init__(self,driver):
self.driver=driver
self.click_report="//*[@class='content reports']"
self.click_create_chart="(//*[@class='i'])[1]"
self.click_add_dash="(//*[@class='addToDashboard'])[1]"
self.add_name_to_dash="(//*[@class='reportNameEdit inputFieldWithPlaceholder'])[1]"
self.click_save="(//*[@class='buttonIcon'])[1]"
self.click_close="//*[@id='closeCreateChartLightboxButton']"
self.click_on_new_report="(//*[@class='i'])[2]"
self.click_on_staff_perf="//*[@id='reportName_1']"
self.click_close_report="//*[@id='createReportLightBox_closeLightbox']"
self.click_config_rpt="//*[@id='configureReportParametersButton']"
self.export_rpt="//*[@id='csvPreviewTab']"
self.click_export_csv_rpt="//*[@id='genCSVReportConfiguration']"
self.close_the_csv_rpt="//*[@id='cancelReportConfiguration']"
def click_on_rept(self):
self.driver.find_element_by_xpath(self.click_report).click()
def click_on_create_chart(self):
self.driver.find_element_by_xpath(self.click_create_chart).click()
time.sleep(8)
def add_usr(self):
self.driver.find_element_by_xpath(self.click_add_dash).click()
def add_dash_name(self):
self.driver.find_element_by_xpath(self.add_name_to_dash).send_keys(cs.cur_time)
self.driver.find_element_by_xpath(self.click_save).click()
self.driver.find_element_by_xpath(self.click_close).click()
def new_report(self):
self.driver.find_element_by_xpath(self.click_on_new_report).click()
self.driver.find_element_by_xpath(self.click_on_staff_perf).click()
def click_config_report(self):
self.driver.find_element_by_xpath(self.click_config_rpt).click()
time.sleep(8)
self.driver.find_element_by_xpath(self.export_rpt).click()
time.sleep(10)
self.driver.find_element_by_xpath(self.click_export_csv_rpt).click()
time.sleep(10)
self.driver.find_element_by_xpath(self.close_the_csv_rpt).click()<file_sep>from constants import constants as cs
class Logout:
def __init__(self,driver):
self.driver=driver
self.logout_lnk_id="logoutLink"
def click_on_logout_link(self):
self.driver.find_element_by_id(self.logout_lnk_id).click()<file_sep>from selenium import webdriver
import pytest
import allure
import time
import moment
from selenium.webdriver.common.keys import Keys
from pages.view_page import view
from pages.login_page import LoginPage
from pages.landing_page import Logout
from constants import constants as cs
from pages.task_page import task
from pages.report_page import report
from pages.user_page import user
from pages.setting_page import setting
class TestLogin:
@pytest.fixture(scope="session")
def test_setup(self):
global driver
driver=webdriver.Chrome(executable_path="C:/Users/chethan.R/PycharmProjects/auto_acti/drivers/chromedriver.exe")
time.sleep(5)
driver.get(cs.URL)
driver.maximize_window()
login = LoginPage(driver)
login.enter_un(cs.UN)
login.enter_pwd(<PASSWORD>)
login.click_on_login_btn()
time.sleep(5)
# yield
#
# home = Logout(driver)
# home.click_on_logout_link()
# time.sleep(5)
# driver.quit()
def test_click_view(self,test_setup):
view_time=view(driver)
time.sleep(15)
view_time.click_view()
time.sleep(8)
def test_click_task(self,test_setup):
ts=task(driver)
ts.click_on_task()
time.sleep(5)
ts.clk_add_new()
def test_create_project(self,test_setup):
ts=task(driver)
ts.click_on_new_project()
time.sleep(10)
ts.enter_a_project_name()
time.sleep(10)
ts.click_enter_cutmr()
time.sleep(10)
def test_clik_rpt(self,test_setup):
rpt=report(driver)
rpt.click_on_rept()
time.sleep(10)
rpt.click_on_create_chart()
rpt.add_usr()
rpt.add_dash_name()
def test_click_new_report(self,test_setup):
nw_rpt = report(driver)
nw_rpt.new_report()
time.sleep(10)
def test_congig_rpt_gen(self,test_setup):
rpt_gen=report(driver)
rpt_gen.click_config_report()
def test_usr(self,test_setup):
usr=user(driver)
usr.clk_user()
def test_setting(self,test_setup):
acti_setting=setting(driver)
acti_setting.click_on_stg()
def test_type_work(self,test_setup):
type_work=setting(driver)
type_work.click_type_of_work()
def test_logout(self,test_setup):
home = Logout(driver)
home.click_on_logout_link()
time.sleep(5)
driver.quit()
<file_sep>from constants import constants as cs
class LoginPage:
def __init__(self,driver):
self.driver=driver
self.un_txt_fld_id="username"
self.pwd_txt_fld_name="pwd"
self.login_btn_id="loginButton"
def enter_un(self,un):
self.driver.find_element_by_id(self.un_txt_fld_id).send_keys(cs.UN)
def enter_pwd(self,pwd):
self.driver.find_element_by_name(self.pwd_txt_fld_name).send_keys(cs.PWD)
def click_on_login_btn(self):
self.driver.find_element_by_id(self.login_btn_id).click()
<file_sep>import time
from constants import constants as cs
from selenium.webdriver.support.select import Select
class setting:
def __init__(self,driver):
self.driver=driver
self.click_on_setting="(//*[@class='popup_menu_label'])[1]"
self.click_on_work_schedule="//*[text()='Types of Work']"
self.click_on_type_wrk="//*[text()='Create Type of Work']"
self.click_name="//*[@id='name']"
self.create_type_work="//*[@type='submit']"
def click_on_stg(self):
self.driver.find_element_by_xpath(self.click_on_setting).click()
time.sleep(8)
self.driver.find_element_by_xpath(self.click_on_work_schedule).click()
time.sleep(8)
def click_type_of_work(self):
self.driver.find_element_by_xpath(self.click_on_type_wrk).click()
time.sleep(8)
self.driver.find_element_by_xpath(self.click_name).send_keys(cs.cur_time)
time.sleep(5)
self.driver.find_element_by_xpath(self.create_type_work).click()
| eabda08d22612b34faff8e3f528d5dcd5ea06796 | [
"Python"
] | 9 | Python | vinayaksm01/auto_acti | ca5a116a0a5a004fbe4967a74d983113c3ebec08 | 03f6e3c2ac99f27f0810d71f866692c651efd98d |
refs/heads/main | <file_sep>package com.codingwithmitch.espressouitestexamples.ui.movie
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import com.codingwithmitch.espressouitestexamples.R
import com.codingwithmitch.espressouitestexamples.data.FakeMovieData
import com.codingwithmitch.espressouitestexamples.util.EspressoIdlingResource
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4ClassRunner::class)
class MyMovieListFragmentTest{
@get: Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)
@Before
fun registerIdlingResource(){
IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource)
}
@After
fun unregisterIdlingResource(){
IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource)
}
val listItemInTest = 4
val movieInTest = FakeMovieData.movies[listItemInTest]
val directors = movieInTest.directors
val verifyDirectorsValue = DirectorsFragment.stringBuilderForDirectors(directors!!)
val actors = movieInTest.star_actors
val verifyActorsValue = StarActorsFragment.stringBuilderForStarActors(actors!!)
// recyclerView comes into View
@Test
fun test_isFragmentVisible_onAppLaunch() {
onView(withId(R.id.recycler_view)).check(matches(isDisplayed()))
}
// Is correct movie in view?
@Test
fun test_SelectListItem_isDetailFragmentVisible() {
onView(withId(R.id.recycler_view))
.perform(actionOnItemAtPosition<MoviesListAdapter.MovieViewHolder>(listItemInTest, click()))
onView(withId(R.id.movie_title)).check(matches(withText(movieInTest.title)))
}
//select list item -> nav to DetailFragment -> press back
@Test
fun test_backNavigation_toMovieListFragment() {
onView(withId(R.id.recycler_view))
.perform(
actionOnItemAtPosition<MoviesListAdapter.MovieViewHolder>(
listItemInTest,
click()))
onView(withId(R.id.movie_title)).check(matches(withText(movieInTest.title)))
pressBack()
onView(withId(R.id.recycler_view)).check(matches(isDisplayed()))
}
//nav to DirectorsFragment
@Test
fun test_navDirectorsFragment_validateDirectorsList() {
onView(withId(R.id.recycler_view))
.perform(
actionOnItemAtPosition<MoviesListAdapter.MovieViewHolder>(
listItemInTest,
click()))
onView(withId(R.id.movie_title)).check(matches(withText(movieInTest.title)))
onView(withId(R.id.movie_directiors)).perform(click())
onView(withId(R.id.directors_text))
.check(matches(withText(verifyDirectorsValue)))
}
@Test
fun test_navStarActorsFragment_validateActorsList() {
onView(withId(R.id.recycler_view))
.perform(
actionOnItemAtPosition<MoviesListAdapter.MovieViewHolder>(
listItemInTest,
click()))
onView(withId(R.id.movie_title)).check(matches(withText(movieInTest.title)))
onView(withId(R.id.movie_star_actors)).perform(click())
onView(withId(R.id.star_actors_text))
.check(matches(withText(verifyActorsValue)))
}
}
| aa0ae97b7f31e6da2e1dd72d57a601825b3ad822 | [
"Kotlin"
] | 1 | Kotlin | EgorUdev/recycler_view_test | 48497da2c0a2142714e98c3217e0bffe1c7fff29 | 5732a2bea72d4c1d021840565c4c270281d606d3 |
refs/heads/main | <file_sep># AngularJS Material Starter (Typescript)
[](https://gitter.im/angular/material?utm_source=badge&utm_medium=badge)
This branch contains the final/complete version (i.e. `step-10-finished`) of the
[Material Start ES6 Tutorial](https://github.com/angular/material-start/tree/es6-tutorial) branch
but written in Typescript instead of ES6.
You can see the [Live Demo here](https://angularjs-material-start.web.app).
This project uses the latest master branch of AngularJS Material to build the application outlined
below.

Above is a screenshot of the Starter-App with a **Master-Detail** layout: showing a list of users
(left) and a user detail view (right).
Also shown is the user experience that will be displayed for smaller device sizes. The responsive
layout reveals the **menu** button that can be used to hide the user list. And the **share** button
can be used to show the Share bottom sheet view.
This Starter app demonstrates how:
* AngularJS Material `layout` and `flex` options can easily configure HTML containers
* AngularJS Material components `<md-toolbar>`, `<md-sidenav>`, and `<md-icon>` can quickly provide
a base application structure
* Custom components can be used and show `<md-bottomsheet>` and a `<md-dialog>` with HTML templates
* Custom component can easily, and programmatically open/close the SideNav component
* Responsive breakpoints and `$mdMedia` are used
* Theming can be altered/configured using `$mdThemingProvider`
This sample application is purposed as both a learning tool and a skeleton application for a typical
[AngularJS Material](https://material.angularjs.org) web app, comprised of a side navigation area and a
content area. You can use it to quickly bootstrap your AngularJS webapp projects and dev environment
for these projects.
- - -
#### "How to build an App"
Here are some generalized steps that may be used to conceptualize the application implementation
process:
1. Plan your layout and the components you want to use
2. Use hard-coded HTML and mock content to make sure the components appear as desired
3. Wire components to your application logic
> Use the seamless integration possible with AngularJS directives and controllers.<br/>
> This integration assumes that you have unit tested your application logic.
4. Add Responsive breakpoints
5. Add Theming support
6. Confirm ARIA compliance
7. Write End-to-end (e2e) Tests
> It is important to validate your application logic with AngularJS Material UI components.
###### Wireframe
The illustration below shows how we planned the layout and identified the primary components that
will be used in the Starter app:

> **Note:** The container #2 (above) is a simple `<div>` container and not an AngularJS Material
component.
- - -
###### Prerequisites
This project assumes that you have NodeJS and any relevant development tools (like XCode) already
installed.
We use NPM for dependency management, and SystemJS (built on top of the dynamic ES6 module loader)
to dynamically load our modules. This allows developers to load any module format (ES6, CommonJS,
AMD, and globals).
SystemJS is also used to transpile the Typescript into plain Javascript in the browser rather than
having to download and configure a separate compiler.
###### Getting Started
Clone this repository and execute the following commands in a terminal:
* `git checkout typescript`
* `npm install`
* `npm start`
> **Note:** Open the dev console to see any warnings and browse the elements.
###### Layout
You will notice a few files/directories within this project:
1. `app/src` - This is where all of your application files are stored.
2. `app/assets` - This folder contains some tutorial-provided images and icons which are used by
the application.
3. `index.html` - The entry point to your application. This uses System.js to load the
`app/src/boot/boot.ts` bootstrap file which imports all of your dependencies and declares them
as AngularJS modules. It also configures the icons and theming for the application.
#### Notes
Below are a few important notes about this project.
* Unlike the ES6 version, we have merged the `boot.ts` and `app.ts` files into the `boot.ts` to
simplify the usage a bit and have only one module.
* Additionally, this version of the project shows how to use the Dialog component to show an alert
once a sharing icon is clicked. The ES6 version simply logs a message to the console.
* The UsersList component inlines the HTML template to show an alternative to the `templateUrl` for
simple components.
* The types provided by @types packages are outdated and use
references to interfaces beginning with 'I' which is not in-line with Angular standards. These
typings are provided by the community and not AngularJS Material.
#### Troubleshooting
If you have issues getting the application to run or work as expected:
1. Make sure you have installed NPM and run the `npm install` command (and there were no errors).
2. Reach out on our [Forum](https://groups.google.com/forum/#!forum/ngmaterial) to see if any other
developers have had the same issue.
3. This project is based against the `master` branch of AngularJS Material, so there may be a newer
version available which fixes the issue you are seeing.
4. Search for the issue here on [GitHub](https://github.com/angular/material-start/issues?q=is%3Aissue+is%3Aopen).
5. If you don't see an existing issue, please open a new one with the relevant information and the
details of the problem you are facing.
Note that the `npm run build` command is expected to fail. The project is configured to use
SystemJS to build the TypeScript in the browser. The format required for supporting this in SystemJS
is not compatible with the normal TypeScript compiler (`tsc`).
<file_sep>System.config({
transpiler: 'typescript',
typescriptOptions: {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
},
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// Set the Base URL that files will be loaded from to /dist (instead of /app)
baseURL: '/app/src',
// Tell it how to find our Angular dependencies
map: {
'angular': '../node_modules/angular/angular.js',
'angular-animate': '../node_modules/angular-animate/angular-animate.js',
'angular-aria': '../node_modules/angular-aria/angular-aria.js',
'angular-material': '../node_modules/angular-material/angular-material.js',
'angular-messages': '../node_modules/angular-messages/angular-messages.js',
'angular-sanitize': '../node_modules/angular-sanitize/angular-sanitize.js'
},
meta: {
'angular': { format: 'global' },
'angular-animate': { format: 'global' },
'angular-aria': { format: 'global' },
'angular-material': { format: 'global' },
'angular-messages': { format: 'global' },
'angular-sanitize': { format: 'global' }
}
});
<file_sep>// Import our Angular dependencies
import * as angular from 'angular';
import 'angular-animate';
import 'angular-aria';
import 'angular-material';
import 'angular-messages';
import 'angular-sanitize';
import {AppComponent} from "../components/start-app/start-app.component.ts";
"use strict";
let app = angular.module('netaffinityApp', ['ngMaterial', 'ngSanitize', 'ngAnimate']);
// theme disabling
// app.config(function($mdThemingProvider) {$mdThemingProvider.disableTheming();})
app.controller("menuCtrl", function ($scope) {
$scope.menuitems = [
{
icon: 'mdi-view-dashboard',
content: 'Dashboard'
},
{
icon: 'mdi-bed',
content: 'Rooms'
},
{
icon: 'mdi-star',
content: 'Package'
},
{
icon: 'mdi-palette',
content: 'Design'
}
{
icon: 'mdi-credit-card-outline',
content: 'Billing'
},
{
icon: 'mdi-cog',
content: 'Settings'
}
];
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
})
app.controller("dialogCtrl", function($scope, $mdDialog) {
$scope.status = ' ';
$scope.customFullscreen = false;
$scope.showAdvanced = function (ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'src/components/dialogs/dialog.html',
// Appending dialog to document.body to cover sidenav in docs app
// Modal dialogs should fully cover application to prevent interaction outside of dialog
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
})
};
function DialogController($scope, $mdDialog) {
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
}
})
app.controller("recentTableCtrl", function ($scope) {
$scope.rows = [
{
date: '30/01/2021',
name: '<NAME>',
amount: '€118',
status: 'Active',
},
{
date: '20/12/2020',
name: '<NAME> PhD',
amount: '€132',
status: 'Inative',
},
{
date: '30/01/2021',
name: 'Mr. <NAME>',
amount: '€91',
status: 'Active',
},
{
date: '30/01/2021',
name: '<NAME>',
amount: '€113',
status: 'Inative',
},
{
date: '06/06/2017',
name: '<NAME>',
amount: '€314',
status: 'Active',
},
{
date: '20/04/2017',
name: '<NAME>',
amount: '€284',
status: 'Inative',
},
{
date: '30/01/2021',
name: '<NAME>',
amount: '€113',
status: 'Active',
},
{
date: '30/01/2021',
name: '<NAME> PhD',
amount: '€113',
status: 'Active',
},
];
})
.component(AppComponent.componentName, AppComponent.componentConfig)
<file_sep>import * as angular from 'angular';
import ApexCharts from "../../../../node_modules/apexcharts/dist/apexcharts.min.js"
/**
* @ngInject
*/
export class AppComponent {
static componentName:string = "msApp";
static componentConfig:ng.IComponentOptions = {
bindings: {},
controller: AppComponent,
templateUrl: 'src/components/start-app/start-app.component.html'
};
private $mdSidenav:angular.material.ISidenavService;
constructor($mdSidenav:angular.material.ISidenavService) {
this.$mdSidenav = $mdSidenav;
var options = {
series: [{
name: '2020',
data: [30,35,32,25,50,100]
},
{
name: '2021',
data: [15,30,32,33,45,31]
}],
chart: {
type: 'area',
height: 285,
stacked: true,
animations: {
enabled: true,
easing: 'easeinout',
speed: 800,
animateGradually: {
enabled: true,
delay: 150
},
dynamicAnimation: {
enabled: true,
speed: 350
}
},
events: {
selection: function (chart, e) {
console.log(new Date(e.xaxis.min))
}
},
},
colors: ['#008ffb', '#00E396', '#00e396'],
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
fill: {
type: 'gradient',
gradient: {
opacityFrom: 0.7,
opacityTo: 0.5,
type: "vertical",
stops: [50, 100]
}
},
legend: {
position: 'bottom',
horizontalAlign: 'center',
fontSize: '10px',
offsetY: -5,
markers: {
height: '9px',
width: '9px',
}
},
xaxis: {
categories: [`00:00`,`01:00`,`02:00`,`03:00`,`04:00`,`05:00`,`06:00`]
},
};
let options2 = {
chart: {
type: 'donut',
height: 242,
},
legend:{
fontSize: '11px',
offsetX: 0,
itemMargin: {
vertical: 0
},
},
series: [25.6, 32, 23.8, 9.9, 8.7],
labels: ['Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5']
}
let chartLine = new ApexCharts(document.querySelector("#line-chart"), options);
let chartDonut = new ApexCharts(document.querySelector("#donut-chart"), options2);
chartLine.render();
chartDonut.render();
}
}
| 741487379b6313e21c38d25bdc61413ae50a7d9d | [
"Markdown",
"TypeScript",
"JavaScript"
] | 4 | Markdown | izaplavskiy/NetAffility_AngularJs | a179eea7c14caaf31f915083155589384f6a1fb9 | fdebe09c8157ca94f3849976301a3614bd525740 |
refs/heads/master | <file_sep>import {Application} from "express";
import {FactSummaryS} from "../services/FactSummary.service";
export class FactSummary{
Fact_Summary: FactSummaryS;
constructor(private app: Application){
this.Fact_Summary = new FactSummaryS();
this.routes();
}
private routes(){
this.app.route("/FactSummary").get(this.Fact_Summary.getAll);
this.app.route("/FactSummary/Customer/:id").get(this.Fact_Summary.getOneCustomer);
}
}<file_sep>import express,{Application} from "express";
import bodyParser from "body-parser";
import cors from "cors";
import {config} from "dotenv";
import {resolve} from "path";
config({"path": resolve(__dirname,"../.env")});
import {createConnection} from "typeorm";
import {FactSummary} from "./controller/fact_summary.controller";
class App{
public app: Application;
public Fact_Summary : FactSummary;
constructor(){
this.app = express();
this.setConfig();
this.setBDConnection();
this.Fact_Summary = new FactSummary(this.app);
}
private setConfig(){
this.app.use(bodyParser.json({limit:"50mb"}));
this.app.use(bodyParser.urlencoded({limit:"150mb"}));
this.app.use(cors());
}
private setBDConnection(){
createConnection().then(connection=>{
console.log("DB connected");
})
}
}
export default new App().app;<file_sep>WITH Ctea as
(
SELECT
Supp.SupplierID,
MONTH(Ord.OrderDate) as Mes,
AVG(OrdD.QUantity*Pro.Price ) as Promedio,
SUM(OrdD.QUantity*Pro.Price) as ventas
FROM example.Orders as Ord
INNER JOIN example.OrderDetails as OrdD
on Ord.OrderID = OrdD.OrderID
INNER JOIN example.Products as Pro
on OrdD.ProductID = Pro.ProductID
INNER JOIN example.Suppliers as Supp
on Pro.SupplierID = Supp.SupplierID
GROUP BY MONTH(Ord.OrderDate),Supp.SupplierID
), VentasMensual AS(
SELECT
SUM(Ords.QUantity*Pro.Price) as Ventas
FROM example.Orders as Ord
INNER JOIN example.OrderDetails as Ords
ON Ord.OrderID = Ords.OrderID
INNER JOIN example.Products as Pro
on Ords.ProductID = Pro.ProductID
INNER JOIN example.Suppliers as Supp
on Pro.SupplierID = Supp.SupplierID
)
SELECT
Cus.CustomerID,
Cus.CustomerName,
Supp.SupplierID,
Supp.SupplierName,
MONTH(Ord.OrderDate) as Mes,
YEAR(Ord.OrderDate) as Year,
SUM(Ords.QUantity*Pro.Price) as Total,
CASE
WHEN C.Promedio >= SUM(Ords.QUantity*Pro.Price) THEN 0
WHEN C.Promedio < SUM(Ords.QUantity*Pro.Price) THEN 1
END as SuperoPromedio,
SUM((Ords.QUantity*Pro.Price)/C.ventas) as PorcentajeVentasMensuales
FROM example.Customers as Cus
INNER JOIN example.Orders as Ord
on Cus.CustomerID = Ord.CustomerID
INNER JOIN example.OrderDetails as Ords
on Ord.OrderID = Ords.OrderID
INNER JOIN example.Products as Pro
on Ords.ProductID = Pro.ProductID
INNER JOIN example.Suppliers as Supp
on Pro.SupplierID = Supp.SupplierID
INNER JOIN Ctea as C
on Supp.SupplierID = C.SupplierID and MONTH(Ord.OrderDate) = C.Mes
GROUP BY Cus.CustomerID,Cus.CustomerName,Supp.SupplierID,Supp.SupplierName,MONTH(Ord.OrderDate),YEAR(Ord.OrderDate),C.Promedio<file_sep>ALTER PROCEDURE example.SP_factummaryS
AS
BEGIN
WITH Ctea as
(
SELECT
Supp.SupplierID,
MONTH(Ord.OrderDate) as Mes,
AVG(OrdD.QUantity*Pro.Price ) as Promedio,
SUM(OrdD.QUantity*Pro.Price) as ventas
FROM example.Orders as Ord
INNER JOIN example.OrderDetails as OrdD
on Ord.OrderID = OrdD.OrderID
INNER JOIN example.Products as Pro
on OrdD.ProductID = Pro.ProductID
INNER JOIN example.Suppliers as Supp
on Pro.SupplierID = Supp.SupplierID
GROUP BY MONTH(Ord.OrderDate),Supp.SupplierID
), VentasMensual AS(
SELECT
SUM(Ords.QUantity*Pro.Price) as Ventas
FROM example.Orders as Ord
INNER JOIN example.OrderDetails as Ords
ON Ord.OrderID = Ords.OrderID
INNER JOIN example.Products as Pro
on Ords.ProductID = Pro.ProductID
INNER JOIN example.Suppliers as Supp
on Pro.SupplierID = Supp.SupplierID
)
SELECT
Cus.CustomerID,
Cus.CustomerName,
Supp.SupplierID,
Supp.SupplierName,
MONTH(Ord.OrderDate) as Mes,
YEAR(Ord.OrderDate) as Year,
SUM(Ords.QUantity*Pro.Price) as Total,
CASE
WHEN C.Promedio > SUM(Ords.QUantity*Pro.Price) THEN 0
WHEN C.Promedio <= SUM(Ords.QUantity*Pro.Price) THEN 1
END as SuperoPromedio,
SUM((Ords.QUantity*Pro.Price)/C.ventas) as PorcentajeVentasMensuales
FROM example.Customers as Cus
INNER JOIN example.Orders as Ord
on Cus.CustomerID = Ord.CustomerID
INNER JOIN example.OrderDetails as Ords
on Ord.OrderID = Ords.OrderID
INNER JOIN example.Products as Pro
on Ords.ProductID = Pro.ProductID
INNER JOIN example.Suppliers as Supp
on Pro.SupplierID = Supp.SupplierID
INNER JOIN Ctea as C
on Supp.SupplierID = C.SupplierID and MONTH(Ord.OrderDate) = C.Mes
GROUP BY Cus.CustomerID,Cus.CustomerName,Supp.SupplierID,Supp.SupplierName,MONTH(Ord.OrderDate),YEAR(Ord.OrderDate),C.Promedio
END
DELETE example.fact_summary
INSERT Into example.fact_summary EXEC example.SP_factummaryS
/*
EXEC example.SP_factummaryS
Drop PROCEDURE example.SP_factummaryS
select * FROM example.fact_summary
DELETE example.fact_summary
Drop Table example.fact_summary
INSERT Into example.fact_summary EXEC example.SP_factummaryS
*/<file_sep>SELECT * FROM example.settings
INSERT INTO example.settings(Anio,[Value])VALUES(1997,1998)
INSERT INTO example.settings(Anio,[Value])VALUES(1997,2000) <file_sep>import {Entity, Column, PrimaryColumn} from "typeorm";
@Entity({schema:"example", database:"ingreso_vehiculos", name:"fact_summary"})
export class Factsummary{
@PrimaryColumn() CustomerID: number;
@Column() CustomerName: string;
@Column() SupplierID: number;
@Column() SupplierName: string;
@Column() Mes: number;
@Column() year: number;
@Column() Total: number;
@Column() SuperoPromedio: number;
@Column() PorcentajeVentaMensual: number;
}
export interface Ifactsummary{
CustomerID: number;
CustomerName: string;
SupplierID: number;
SupplierName: string;
Mes: number;
year: number;
Total: number;
SuperoPromedio: number;
PorcentajeVentaMensual: number;
}
export interface IResult{
Successed: boolean;
MSG:string;
}<file_sep>CREATE table example.fact_summary(
CustomerID int,
CustomerName NVARCHAR(50),
SupplierID int,
SupplierName NVARCHAR(100),
Mes int,
[year] int,
Total int,
SuperoPromedio int,
PorcentajeVentaMensual float
)
CREATE table example.settings(
Anio int,
[Value] Int
)
/*
drop table example.fact_summary
drop table example.settings
*/
<file_sep>import {Request,Response} from "express";
import {getConnection} from "typeorm";
import {Factsummary,Ifactsummary,IResult} from "../entity/Factsummary.entity";
export class FactSummaryS{
public async getAll(req: Request, res:Response){
const factummaryS: IResult[] = await getConnection().query(`
EXEC example.SP_factummaryS
`)
res.status(201).json(factummaryS);
}
public async getOneCustomer(req:Request,res:Response){
const factummaryS: IResult[] = await getConnection().query(`
EXEC example.SP_factummarySListar
@CustomerID = ${req.params.id}`);
res.status(200).json(factummaryS);
}
}<file_sep>select * FROM example.fact_summary
/*INSERT Into example.fact_summary EXEC example.SP_factummaryS*/
| cb64fc3f00f5699adaae887ced9ba14657bffde1 | [
"SQL",
"TypeScript"
] | 9 | TypeScript | EdwinQuintero01246/examenDeBases | 2a7e9f34e5988a9f02d7e4a77d783b462de3bdef | 6f41922cc7483f5096fe1348ad8bdfdfc2ca75c3 |
refs/heads/master | <file_sep>bin
===
random scripts to make the world a better place
<file_sep>#!/bin/bash -eux
L_PORT=8080
R_PORT=443
JUJU_UNIT=juju-gui
SSH_HOST=YOUR_HOST
SSH_PORT=22
SSH_USER=ubuntu
SSH_CONTROL=`basename $0`-control
PROTO=http
case $R_PORT in
443)
PROTO=https
;;
esac
echo "Finding the IP address for ${JUJU_UNIT}"
UNIT_IP=`ssh -l ${SSH_USER} -p ${SSH_PORT} ${SSH_HOST} juju status ${JUJU_UNIT} | grep public-address | head -1 | awk '{print $2}'`
if [[ -z ${UNIT_IP} ]]; then
echo "No IP address found for ${JUJU_UNIT}"
exit 1
fi
echo "Creating tunnel localhost:${L_PORT}->${UNIT_IP}:${R_PORT}"
ssh -M -S ${SSH_CONTROL} -fnNT -L ${L_PORT}:${UNIT_IP}:${R_PORT} -l ${SSH_USER} -p ${SSH_PORT} ${SSH_HOST}
echo "Opening browser to local tunnel"
open "${PROTO}://localhost:${L_PORT}"
echo "Close tunnel?"
select i in "yes" "no"; do
case $i in
yes)
echo "Closing tunnel"
ssh -S ${SSH_CONTROL} -O exit -l ${SSH_USER} -p ${SSH_PORT} ${SSH_HOST}
break
;;
no)
echo "Tunnel Status:"
ssh -S ${SSH_CONTROL} -O check -l ${SSH_USER} -p ${SSH_PORT} ${SSH_HOST}
echo "Close tunnel?"
;;
*)
echo "Pick 1..2"
echo "Close tunnel?"
;;
esac
done
| ebe48dd5cdcc03d16c18df0c36479481d5ea4e55 | [
"Markdown",
"Shell"
] | 2 | Markdown | kwmonroe/bin | 7b10dd2375c2893fd5bf040e5af34a4368bb2e14 | 58caec5d828ab3966b802890d11520a883244ce6 |
refs/heads/master | <file_sep>var person = function(){
var fullName = "<NAME>";
var reg= new RegExp(/\d+/);
return{
setFullName :function(newValue){
if(reg.test(newValue)){
console.log("invalid name");
}
else{
fullName = newValue;
}
if(reg.test(newValue)){
console.log("Invalid Name");
}
else{
fullName = newValue;
}
},
getFullName :function(){
return fullName;
}
};
}();
console.log(person.getFullName());
person.setFullName("<NAME>");
console.log(person.getFullName());
person.setFullName(42);
person.fullName=42;
console.log(person.getFullName()); //...42 is printed.
| a2a06278e9651352b1eebc94111ed4b2092a849c | [
"JavaScript"
] | 1 | JavaScript | jcyang36/components | b0700cb0e1ecb1340b773ce3b254b96a7b253961 | e142484d6ef1fe662e39709290827a2fe735252a |
refs/heads/master | <repo_name>gc-lodgment/nurisoop-v2<file_sep>/nurisoop/src/assets/js/review/init.js
$(function () {
//함수실행
//일반 리뷰 자세히보기
$('.normal-list-box .review-list .view-mid .view-tit, .normal-list-box .review-list .view-bot .desc').on('click', function(){
$('.review-list').find('li .list-box').removeClass('on');
$(this).parents('.list-box').addClass('on');
var ht = $('header').height();
var offsetTop = $(this).parents('li').offset().top;
$('html, body').stop().animate({
scrollTop : (offsetTop-(ht+20))
}, 500);
});
});
<file_sep>/nurisoop/src/assets/js/m/script.js
$(function () {
dropselectFn()
fileformFn();
imgformFn();
allChk();
});
function dropselectFn() {
// 드롭메뉴(셀렉트 연결)
$('.dropbtn[data-toggle=dropmenu]').on('click', function () {
$(this)
.closest('.dropselect')
.find('.dropmenu')
.toggleClass('active');
});
$('.dropselect .dropmenu li').on('click', function () {
var idx = $(this).index();
var txt = $(this).text();
$(this)
.closest('.dropselect')
.find('select option')
.eq(idx)
.prop('selected', true)
.siblings()
.prop('selected', false);
$(this)
.closest('.dropselect')
.find('.drop-toggle .in')
.text(txt);
$(this)
.addClass('active')
.siblings()
.removeClass('active');
$(this)
.closest('.dropmenu')
.removeClass('active');
if ($(this).closest('form')) {
$(this).closest('form').submit();
}
});
}
function fileformFn() {
var $filename = $('.fileform-wrapper .filename');
var $deleteBtn = $('.fileform-wrapper .delete-btn');
$('.fileform').on('change', function () {
var files = this.files;
// var limitSize = 5 * 1024 * 1024; // 파일 크기 제한
if (files[0] == undefined) {
$filename.text('선택된 파일없음');
return;
}
// for (var n in files) {
// console.log(files[n].size);
// if (files[n].size > limitSize) return alert('파일크기가 10MB 보다 작아야합니다.')
// }
for (var i = 0; i < files.length; i++) {
// console.log(files[i].size);
// if (files[i].size > limitSize) return alert('파일크기가 5MB 보다 작아야합니다.');
}
if (files.length > 1 && files.length < 6) {
$filename.html('<img src="../../img/m/common/save.png" alt="저장"/ class="save"> ' + files.length + '개 파일');
return;
} else if (files.length >= 6) {
alert('최대 5개까지 가능합니다.');
return;
}
$filename.html('<img src="../../img/m/common/save.png" alt="저장"/ class="save"> ' + files[0].name);
});
$deleteBtn.on('click', function () {
// console.log($('.fileform')[0].files);
if ($('.fileform')[0].files.length) {
$('.fileform').val('');
// console.log($('.fileform')[0].files);
$filename.html('선택된 파일 없음');
}
});
}
function imgformFn() {
var $imgForm = $('#imgForm');
var $imgList = $('#imgList');
var selectFiles = [];
$imgForm.on('change', function (e) {
// console.log($(this)[0].files);
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
console.log(filesArr);
filesArr.forEach(function (item) {
// if (!item.type.match('image.*')) {
// alert('이미지 파일을 업로드해주세요.')
// return;
// }
$imgList.empty();
var reader = new FileReader();
reader.onload = function (e) {
var $html = '\
<a href="javascript:;" class="item">' +
'<img src="' + e.target.result + '" alt="상품">' +
'<span class="x">×</span>' +
'</a>';
$imgList.append($html);
}
reader.readAsDataURL(item);
});
});
$('body').on('click', '#imgList .item', function () {
// console.log($imgForm);
// var idx = $(this).index();
// console.log($imgForm[0].files);
$imgForm.val("");
$imgList.empty();
// console.log($imgForm[0].files);
});
}
// 모두 동의
function allChk() {
$('.check-all').click(function () {
var checkName = $(this).attr('data-check-name');
$('.check-item[data-check-name="' + checkName + '"]').prop('checked', this.checked);
});
}
// 달력 ui
function datePick() {
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd',
prevText: '이전 달',
nextText: '다음 달',
monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
dayNames: ['일', '월', '화', '수', '목', '금', '토'],
dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
showMonthAfterYear: true,
yearSuffix: '년'
});
$("input.date-ui").datepicker({
// minDate: 0,
dateFormat: 'yy-mm-dd'
});
}<file_sep>/nurisoop/config.js
module.exports = function () {
var source = 'src',
development = 'dist',
test = 'test',
remove = ['.sass-cache', 'dist'],
// 템플릿 경로
template = {
src: source + '/template/**/!(_)*.html',
parts: source + '/template/**/_*.html',
dest: development + '/www',
src_m: source + '/template_m/**/!(_)*.html',
parts_m: source + '/template_m/**/_*.html',
dest_m: development + '/m',
},
// Sass 경로
sass = {
src: source + '/assets/sass/**/!(_)*.{scss,sass}',
parts: source + '/assets/sass/**/_*.{scss,sass}',
dest: development + '/static/css'
},
// Css 경로
css = {
src: source + '/assets/css/**/*.css',
dest: development + '/static/css'
},
// JS 경로
js = {
src: source + '/assets/js/**/*.js',
dest: development + '/static/js'
},
// Img 경로
img = {
// src : source + '/assets/assets/img/**/*.{gif,jpg,png,ico}',
src: source + '/assets/img/**/!(sprite)*/*',
src_sprite: source + '/assets/img/**/sprite*/*',
dest: development + '/img',
},
// Img 경로
img_m = {
// src : source + '/assets/assets/img/**/*.{gif,jpg,png,ico}',
src: source + '/assets/img/m/**/!(sprite)*/*',
src_sprite: source + '/assets/img/m/**/sprite*/*',
dest: development + '/img/m',
},
// etc 경로
etc = {
src: source + '/assets/!(css|sass|js|img)/**',
dest: development + '/static',
},
// HTML 옵션
htmlbeautify = {
"indentSize": 4
};
return {
del: remove,
src: source,
test: test,
dev: development,
template: template,
css: css,
sass: sass,
js: js,
img: img,
img_m: img_m,
etc: etc,
htmlbeautify: htmlbeautify
};
};<file_sep>/nurisoop/README.md
# nurisoop
nurisoop
<file_sep>/nurisoop/src/assets/js/order/init.js
$(function () {
//함수 실행
payTabFn();
});
/* (oder)결제수단 탭 */
function payTabFn(){
$('.pay-area ul[class*="-tab"] li').on('click', function(){
var tabCls = $(this).parent('ul[class*="-tab"]').attr('class');
var tab = tabCls.split('-');
var ths = $(this).attr('class');
//console.log(tabCls, tab[0], ths);
if( tab[0] == 'pay' ) {
$(this).parents('.pay-tab').siblings('.pay-cont').find('.pay-row').hide();
$(this).parents('.pay-tab').siblings('.pay-cont').find('.pay-row.'+ths).show();
}else if( tab[0] == 'type' ) {
$(this).parents('.type-tab').parents('tr').siblings('.type-row').hide();
$(this).parents('.type-tab').parents('tr').siblings('.type-row.'+ths).show();
}else {
$(this).parents('.'+tab[0]+'-tab').siblings('.'+tab[0]+'-row').hide();
$(this).parents('.'+tab[0]+'-tab').siblings('.'+tab[0]+'-row.'+ths).show();
}
});
}<file_sep>/nurisoop/src/assets/js/include/pop.js
var num;
$(function () {
$('ul[class*="pop-dt-rv-"] a').on('click', function(){
num = $(this).attr('data-slide-index');
//console.log(num);
return num;
})
});
function rvSdPopOpen(id){
//dtPopSlide(id);
$(id).stop().fadeIn(function(){
//console.log('열림');
dtPopSlide(id, num);
//slider.reloadSlider();
});
popOpen();
}
/* detail pop slide */
function dtPopSlide(id, num){
//console.log(pager)
var slider, pager;
pager = String('.')+(id.substr(1, (id.length)))+String('-pager');
if( $(id).find('ul[id*="pop-dt-slide-"] li').length == 1 ){
//이미지가 1개일 경우
}else {
//console.log('add');
slider = $(id).find('ul[id*="pop-dt-slide-"]').bxSlider({
auto: false,
autoHover: true,
autoControls: false,
controls: true,
//pager: false,
pager: true,
pagerCustom: pager,
speed: 1000,
duration: 6000,
prevText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_left_04.png" alt="이전">',
nextText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_right_04.png" alt="다음">'
});
slider.goToSlide(num);
//slider.reloadSlider();
}
}
<file_sep>/nurisoop/src/assets/js/policy/init.js
$(function () {
//함수 실행
});
<file_sep>/nurisoop/src/assets/js/main/init.js
var hotSlider;
$(function () {
//함수실행
$(window).load(function(){
mainSlideFn();
midSlideFn();
hotSlideFn();
});
//main pop
var mainPop = $('.main-pop-wrap');
if( mainPop.css('display') == 'block' ) {
mainPopFn();
}
});
/* main slider */
function mainSlideFn(){
$('#mainVisual').bxSlider({
mode: 'fade',
auto: true,
autoHover: true,
autoControls: false,
controls: true,
pager: true,
pagerCustom: '#viualPager',
speed: 1000,
duration: 6000,
prevText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_left_01.png" alt="이전">',
nextText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_right_01.png" alt="다음">'
});
}
/* main slider */
function mainPopFn(){
$('#mainSlidePop').bxSlider({
auto: true,
autoHover: true,
autoControls: false,
controls: false,
pager: true,
pagerCustom: '#mainSlidePopPager',
speed: 1000,
duration: 6000
});
}
/* mid slider */
function midSlideFn(){
$('#midSilde').bxSlider({
mode: 'fade',
auto: true,
autoHover: true,
autoControls: false,
controls: true,
pager: false,
speed: 1000,
duration: 6000,
prevText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_left_02.png" alt="이전">',
nextText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_right_02.png" alt="다음">'
});
}
/* hotdeal slider */
function hotSlideFn(){
var current = 0;
hotSlider = $('#hotSlide').bxSlider({
auto: false,
autoHover: true,
autoControls: false,
controls: true,
pager: false,
slideWidth: 620,
minSlides: 2,
maxnSlides: 2,
moveSlides: 1,
slideMargin: 20,
infiniteLoop: false,
speed: 1000,
duration: 6000,
prevText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_left_04.png" alt="이전">',
nextText: '<img src="http://static.nurisoop.co.kr/img/renew/common/btn_arw_right_04.png" alt="다음">',
onSliderLoad: function(currentIndex){
if( currentIndex == 0 ){
//console.log('fir');
$('.hotdeal-area').find('.bx-controls .bx-prev').css({cursor: 'auto'}).addClass('on');
}
},
onSlideAfter: function($slideElement, oldIndex, newIndex){
//console.log(newIndex, current);
var num = Number(current)/2;
if( newIndex == num ){
//console.log('lst');
$('.hotdeal-area').find('.bx-controls .bx-next').addClass('on').end().find('.lst-box').addClass('on')
}else if( newIndex == 0 ) {
//console.log('fir');
$('.hotdeal-area').find('.bx-controls .bx-prev').css({cursor: 'auto'}).addClass('on');
}else {
$('.hotdeal-area').find('.bx-controls .bx-prev').css({cursor: 'pointer'}).removeClass('on');
$('.hotdeal-area').find('.bx-controls .bx-next').removeClass('on').end().find('.lst-box').removeClass('on');
}
}
});
current = hotSlider.getSlideCount();
}
<file_sep>/nurisoop/src/assets/js/board/init_20190531.js
$(function () {
//함수실행
/* 자주 묻는 질문 */
$('.faq-area a').on('click', function(){
$(this).parents('.q-box').toggleClass('on');
$(this).parents('.q-box').next('.a-box').stop().fadeToggle();
});
/* 비밀번호 창 나타남 */
$('.popPw').on('click', function(){
//console.log('password');
$(this).parents('.contact-area').fadeOut();
$(this).parents('.contact-area').siblings('.pw-area').fadeIn();
});
/* 비밀번호 창 숨김 */
$('.btnPwList').on('click', function(){
$(this).parents('.pw-area').fadeOut();
$(this).parents('.pw-area').siblings('.contact-area').fadeIn();
});
});
/*var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
fileTxt = $(this)[0].files[0].name;
//$(this).siblings('.ip-file').val(fileTxt);
filesArr.forEach(function(f){
if(!f.type.match('image.*')){
alert('이미지만 올릴 수 있습니다.');
return;
}
selFile = f;
var reader = new FileReader();
reader.onload = function(e){
$('#txtFile').append('<p class="row-file"><span class="num-txt ico-file-02"><span></span><em>'+fileTxt+'</em></span><a href="javascript:;" class="btn-file-del ico-file-cls fileTxtDel"><span></span>삭제</a></p>');
//e.target.result
}
reader.readAsDataURL(f);
});*/<file_sep>/nurisoop/src/assets/js/samplekit/init.js
$(function () {
$(document).ready(function(){
var noWriteEmail = $("#email_3").val();
if (noWriteEmail != "etc") {
$("input[name='email_2']").attr('readonly', true);
}
$("#email_3").change(function(){
var email_3 = $(this).val();
if(email_3 == "etc") {
$("input[name='email_2']").val('');
$("input[name='email_2']").attr('readonly', false);
}
else {
$("input[name='email_2']").val(email_3);
$("input[name='email_2']").attr('readonly', true);
}
});
});
});
<file_sep>/nurisoop/gulpfile.js
const {
src,
dest,
watch,
parallel,
series,
lastRun
} = require('gulp');
const config = require('./config')();
const imagemin = require('gulp-imagemin');
const fileinclude = require('gulp-file-include');
const htmlbeautify = require('gulp-html-beautify');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
sass.compiler = require('node-sass');
const sourcemaps = require("gulp-sourcemaps");
const csso = require('gulp-csso');
const autoprefixer = require('gulp-autoprefixer');
const del = require('del');
const spritesmith = require('gulp.spritesmith');
const replace = require('gulp-replace');
const copy = require('gulp-copy');
// const rename = require('gulp-rename');
function bSync() {
browserSync.init({
// watch: true,
notify: false,
port: 3030,
startPath: './www/main',
server: {
baseDir: './dist'
}
});
};
function bSyncTest() {
browserSync.init({
notify: false,
port: 3050,
// watch: true,
server: {
baseDir: './dist'
}
});
};
function template() {
return src(config.template.src, {
since: lastRun(template)
})
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
// basepath: '@root'
}))
.pipe(htmlbeautify(config.htmlbeautify))
.pipe(dest(config.template.dest))
.pipe(browserSync.stream({
match: '**/*.html'
}));
};
function templateAll() {
return src([config.template.src])
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
// basepath: '@root'
}))
.pipe(htmlbeautify(config.htmlbeautify))
.pipe(dest(config.template.dest))
.pipe(browserSync.stream({
match: '**/*.html'
}));
};
function templateM() {
return src(config.template.src_m, {
since: lastRun(template)
})
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
// basepath: '@root'
}))
.pipe(htmlbeautify(config.htmlbeautify))
.pipe(dest(config.template.dest_m))
.pipe(browserSync.stream({
match: '**/*.html'
}));
};
function templateMAll() {
return src(config.template.src_m)
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
// basepath: '@root'
}))
.pipe(htmlbeautify(config.htmlbeautify))
.pipe(dest(config.template.dest_m))
.pipe(browserSync.stream({
match: '**/*.html'
}));
};
// {outputStyle: nested} expanded, compact, compressed
function sassDev() {
return src(config.sass.src)
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(
sourcemaps.write(".", {
includeContent: false,
sourceRoot: __dirname
})
)
.pipe(dest(config.sass.dest))
.pipe(browserSync.stream({
match: '**/*.css'
}));
};
function sassDevAll() {
return src([config.sass.src, config.sass.parts])
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(
sourcemaps.write(".", {
includeContent: false,
sourceRoot: __dirname
})
)
.pipe(dest(config.sass.dest))
.pipe(browserSync.stream({
match: '**/*.css'
}));
};
function sassPrd() {
return src(config.sass.src, {
since: lastRun(sass)
})
.pipe(sass({
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(csso())
.pipe(dest(config.sass.dest))
.pipe(browserSync.stream({
match: '**/*.css'
}));
};
function css() {
return src(config.css.src, {
since: lastRun(css)
})
// .pipe(autoprefixer())
// .pipe(csso())
// .pipe(rename({suffix: '.min'}))
.pipe(dest(config.css.dest))
.pipe(browserSync.stream({
match: '**/*.css'
}));
};
function js() {
return src(config.js.src, {
since: lastRun(js)
})
.pipe(dest(config.js.dest))
.pipe(browserSync.stream({
match: '**/*.js'
}));
};
function img() {
return src(config.img.src, {
since: lastRun(img)
})
.pipe(imagemin())
.pipe(dest(config.img.dest));
}
function imgM() {
return src(config.img_m.src, {
since: lastRun(img)
})
.pipe(imagemin())
.pipe(dest(config.img_m.dest));
}
function sprite(cb) {
// var spriteData = src('src/img/sprite/login/*') // custom grouping
var spriteData = src(config.img.src_sprite)
.pipe(spritesmith({
imgName: 'sprite.png',
padding: 6,
cssName: 'sprite.css'
}));
spriteData.img.pipe(dest(config.img.dest + '/sprite'));
// spriteData.css.pipe(dest(config.sass.dest + '/sprite'));
spriteData.css.pipe(dest(config.sass.src_sprite)); // 생성 후 scss로 변경
cb();
};
function etc() {
return src(config.etc.src, {
since: lastRun(etc)
})
.pipe(dest(config.etc.dest));
}
function watching(cb) {
watch([config.template.src], template);
watch([config.template.parts], templateAll);
watch([config.template.src_m], templateM);
watch([config.template.parts_m], templateMAll);
watch(config.sass.src, sassDev)
watch(config.sass.parts, sassDevAll)
watch(config.css.src, css)
watch(config.js.src, js)
watch(config.img.src, img);
watch(config.etc.src, etc);
cb();
};
// util
function cleanDist(cb) {
del(config.dev);
cb();
};
function cleanTest(cb) {
del(config.test);
cb();
};
function cleanTemplate(cb) {
// del([config.template.dest, config.template.dest_m]);
del([config.template.dest]);
cb();
};
function cleanParts(cb) {
// del([config.template.dest_parts, config.template.dest_m_parts]);
del([config.template.dest_parts]);
cb();
};
function cleanSass(cb) {
del(config.sass.dest);
cb();
};
function cleanCss(cb) {
del(config.css.dest);
cb();
};
function cleanJs(cb) {
del(config.js.dest);
cb();
};
function cleanImg(cb) {
del(config.img.dest);
cb();
};
function cleanImgM(cb) {
del(config.img_m.dest);
cb();
};
const assets_local = '/assets';
const assets_server = 'http://toxnsldxn.cafe24.com/template/assets';
const views_local = '/views';
const views_server = 'http://toxnsldxn.cafe24.com/template/views';
function copyTest() {
return src(config.dev + '/**/*')
.pipe(dest(config.test));
};
function testPathServer() {
return src(config.test + '/**/*')
.pipe(replace(assets_local, assets_server))
.pipe(replace(views_local, views_server))
.pipe(dest(config.test));
};
function testPathLocal() {
return src(config.test + '/**/*')
.pipe(replace(assets_server, assets_local))
.pipe(replace(views_server, views_local))
.pipe(dest(config.test));
};
exports.cleanTemplate = cleanTemplate;
exports.cleanDist = cleanDist;
exports.cleanTest = cleanTest;
exports.cleanParts = cleanParts;
exports.cleanImg = cleanImg;
exports.cleanImgM = cleanImgM;
exports.img = img;
exports.imgM = imgM;
exports.sprite = sprite;
exports.etc = etc;
exports.testPathServer = testPathServer;
exports.testPathLocal = testPathLocal;
exports.default = parallel(bSync, watching);
exports.serve = parallel(series(parallel(template, templateM), sassDev, css, js, etc, bSync), watching);
exports.build = parallel(series(parallel(template, templateM), sassDev, css, js, etc, bSync), watching);
exports.buildPC = parallel(series(parallel(template), sassDev, css, js, img, etc, bSync), watching);
exports.buildM = parallel(series(parallel(templateM), sassDev, css, js, img, etc, bSync), watching);
exports.default = parallel(bSync, watching);
exports.test = series(parallel(template, templateM), sassPrd, css, js, img, etc, copyTest, testPathServer, bSyncTest); | bbd84c9a4491f5e4aa3872e1673102d1b3cdfa3a | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | gc-lodgment/nurisoop-v2 | 47f1783d4833e5d1776655dc04f82815b2c249c5 | 395a82001dcedd5c4a3e05f14cc8dae4a323773b |
refs/heads/master | <repo_name>cultuurnet/puppet-borgbackup<file_sep>/spec/spec_helper.rb
require 'puppetlabs_spec_helper/module_spec_helper'
require 'rspec-puppet-facts'
include RspecPuppetFacts
RSpec.configure do |c|
c.after(:suite) do
RSpec::Puppet::Coverage.report!
end
end
<file_sep>/spec/defines/configuration_spec.rb
require 'spec_helper'
describe 'borgbackup::configuration' do
let(:title) { 'filesystem' }
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
context "with ensure => absent" do
let(:params) { { :ensure => 'absent' } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_borgbackup__configuration('filesystem').with(
:ensure => 'absent',
:encryption => 'none',
:type => 'borg',
:timeout => '5',
:excludes => [],
:job_schedule => {},
:job_verbosity => '1',
:borg_rsh => 'ssh'
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with(
:ensure => 'absent'
) }
it { is_expected.to contain_file('/etc/borgmatic/excludes.filesystem').with(
:ensure => 'absent'
) }
it { is_expected.to contain_cron('borgbackup::configuration::filesystem').with(
:ensure => 'absent'
) }
it { is_expected.to_not contain_exec('borg init filesystem') }
context "with type => attic" do
let(:params) { { :ensure => 'absent', :type => 'attic' } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_borgbackup__configuration('filesystem').with(
:ensure => 'absent',
:encryption => 'none',
:type => 'attic',
:timeout => '5',
:excludes => [],
:job_schedule => {},
:job_verbosity => '1',
:borg_rsh => 'ssh'
) }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with(
:ensure => 'absent'
) }
it { is_expected.to contain_file('/etc/atticmatic/excludes.filesystem').with(
:ensure => 'absent'
) }
it { is_expected.to contain_cron('borgbackup::configuration::filesystem').with(
:ensure => 'absent'
) }
it { is_expected.to_not contain_exec('borg init filesystem') }
end
end
context "without any parameters" do
let(:params) { { } }
it { expect { catalogue }.to raise_error(Puppet::PreformattedError, /expects a value for parameter 'source_directories'/) }
end
context "with source_directories => '/home'" do
let(:params) { { :source_directories => '/home' } }
it { expect { catalogue }.to raise_error(Puppet::PreformattedError, /expects a value for parameter 'repository'/) }
end
context "with the required parameters" do
let(:default_params) { { :source_directories => '/home', :repository => '/mnt/backup' } }
let(:params) { default_params }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_borgbackup__configuration('filesystem').with(
:source_directories => '/home',
:repository => '/mnt/backup',
:encryption => 'none',
:type => 'borg',
:timeout => '5',
:excludes => [],
:job_schedule => {},
:job_verbosity => '1',
:borg_rsh => 'ssh'
) }
it { is_expected.to contain_exec('borg init filesystem').with(
:path => ['/usr/bin', '/usr/local/bin'],
:environment => [ 'BORG_RSH=ssh'],
:command => 'borg init --encryption none --lock-wait 5 /mnt/backup',
:unless => 'borg list --lock-wait 5 /mnt/backup'
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644'
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with_content(
/\[location\]\nsource_directories: \/home\nrepository: \/mnt\/backup\n\n/
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with_content(
/\[storage\]\ncompression: none\n\n/
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with_content(
/\[retention\]\n\n/
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with_content(
/\[consistency\]\nchecks: repository archives\ncheck_last: 1/
) }
it { is_expected.to contain_file('/etc/borgmatic/excludes.filesystem') }
it { is_expected.to_not contain_cron('borgbackup::configuration::filesystem') }
context "with encryption => foo" do
let(:params) { default_params.merge({ :encryption => 'foo' }) }
it { expect { catalogue }.to raise_error(Puppet::Error, /value foo not allowed for parameter encryption/) }
end
context "with encryption => repokey, timeout => 7, passphrase => <PASSWORD> and borg_rsh => ssh -i /tmp/privkey.pem" do
let(:params) { default_params.merge({ :encryption => 'repokey', :timeout => '7', :passphrase => '<PASSWORD>', :borg_rsh => 'ssh -i /tmp/privkey.pem' }) }
it { is_expected.to contain_exec('borg init filesystem').with(
:path => ['/usr/bin', '/usr/local/bin'],
:environment => [ 'BORG_PASSPHRASE=secret', 'BORG_RSH=ssh -i /tmp/privkey.pem'],
:returns => [ 0, 2],
:command => 'borg init --encryption repokey --lock-wait 7 /mnt/backup',
:unless => 'borg list --lock-wait 7 /mnt/backup'
) }
end
context "and with type => attic" do
let(:params) { default_params.merge( { :type => 'attic' } ) }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644'
) }
it { is_expected.to contain_file('/etc/atticmatic/excludes.filesystem') }
end
context "and with type => attic, passphrase => <PASSWORD> and a custom options hash" do
let(:params) { default_params.merge( {
:type => 'attic',
:passphrase => '<PASSWORD>',
:options => {
'compression' => 'lz4',
'keep_within' => '3H',
'keep_hourly' => '7',
'keep_daily' => '7',
'keep_weekly' => '5',
'keep_monthly' => '3',
'keep_yearly' => '1',
'prefix' => 'foo',
'checks' => 'archives'
}
} ) }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with_content(
/\[location\]\nsource_directories: \/home\nrepository: \/mnt\/backup\n\n/
) }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with_content(
/\[storage\]\nencryption_passphrase: secret\ncompression: lz4\n\n/
) }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with_content(
/\[retention\]\nkeep_within: 3H\nkeep_hourly: 7\nkeep_daily: 7\nkeep_weekly: 5\nkeep_monthly: 3\nkeep_yearly: 1\nprefix: foo\n\n/
) }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with_content(
/\[consistency\]\nchecks: archives\ncheck_last: 1/
) }
end
context "and with type => attic and excludes => [ '/home/a', '/home/b']" do
let(:params) { default_params.merge(
{
:type => 'attic',
:excludes => [ '/home/a', '/home/b']
}
) }
it { is_expected.to_not contain_cron('borgbackup::configuration::filesystem') }
it { is_expected.to contain_file('/etc/atticmatic/config.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644'
) }
it { is_expected.to contain_file('/etc/atticmatic/excludes.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644',
:content => /\/home\/a\n\/home\/b/
) }
end
context "and with excludes => [ /home/c, /home/d, /home/e], borg_rsh => ssh -i /tmp/privkey.pem, job_verbosity => 1 and job_schedule => { hour => *, minute => 10, weekday => * }" do
let(:params) { default_params.merge(
{
:excludes => [ '/home/c', '/home/d', '/home/e'],
:borg_rsh => 'ssh -i /tmp/privkey.pem',
:job_verbosity => '1',
:job_schedule => { 'hour' => '*', 'minute' => 10, 'weekday' => '*' }
}
) }
it { is_expected.to contain_cron('borgbackup::configuration::filesystem').with(
:user => 'root',
:environment => ['MAILTO=', 'PATH=/usr/bin:/bin:/usr/local/bin', 'BORG_RSH="ssh -i /tmp/privkey.pem"'],
:command => '/usr/local/bin/borgmatic --config /etc/borgmatic/config.filesystem --excludes /etc/borgmatic/excludes.filesystem -v 1 > /tmp/borgbackup.log 2>&1 || cat /tmp/borgbackup.log',
:hour => '*',
:minute => '10',
:weekday => '*'
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644'
) }
it { is_expected.to contain_file('/etc/borgmatic/excludes.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644',
:content => /\/home\/c\n\/home\/d\n\/home\/e/
) }
end
context "and with job_verbosity => '2', job_mailto => 'root@localhost' and job_schedule => { hour => 3, minute => 15, weekday => 4, month => 5, monthday => * }" do
let(:params) { default_params.merge(
{
:job_verbosity => '2',
:job_mailto => 'root@localhost',
:job_schedule => { 'hour' => 3, 'minute' => 15, 'weekday' => 4, 'month' => 5, 'monthday' => '*' }
}
) }
it { is_expected.to contain_cron('borgbackup::configuration::filesystem').with(
:user => 'root',
:environment => ['MAILTO=root@localhost', 'PATH=/usr/bin:/bin:/usr/local/bin', 'BORG_RSH="ssh"'],
:command => '/usr/local/bin/borgmatic --config /etc/borgmatic/config.filesystem --excludes /etc/borgmatic/excludes.filesystem -v 2 > /tmp/borgbackup.log 2>&1 || cat /tmp/borgbackup.log',
:hour => '3',
:minute => '15',
:weekday => '4',
:month => '5',
:monthday => '*'
) }
it { is_expected.to contain_file('/etc/borgmatic/config.filesystem').with(
:ensure => 'file',
:owner => 'root',
:group => 'root',
:mode => '0644'
) }
it { is_expected.to contain_file('/etc/borgmatic/excludes.filesystem') }
end
end
end
end
end
context 'unsupported operating system' do
describe 'with the required parameters on RedHat' do
let(:facts) do
{
:operatingsystem => 'RedHat',
}
end
let(:params) { { :source_directories => '/home', :repository => '/mnt/backup' } }
it { expect { catalogue }.to raise_error(Puppet::Error, /RedHat not supported/) }
end
end
context 'unsupported operating system release' do
describe 'with the required parameters on Ubuntu 12.04' do
let(:facts) do
{
:operatingsystem => 'Ubuntu',
:operatingsystemrelease => '12.04'
}
end
let(:params) { { :source_directories => '/home', :repository => '/mnt/backup' } }
it { expect { catalogue }.to raise_error(Puppet::Error, /Ubuntu 12.04 not supported/) }
end
end
end
<file_sep>/spec/classes/install_spec.rb
require 'spec_helper'
describe 'borgbackup::install' do
context "without any parameters" do
it { is_expected.to compile.with_all_deps }
it { is_expected.to have_package_resource_count(0) }
end
context "with package_name => [ 'python3-borgbackup', 'python3-atticmatic']" do
let (:params) { { :package_name => [ 'python3-borgbackup', 'python3-atticmatic'] } }
it { is_expected.to contain_package('python3-borgbackup').with_ensure('present') }
it { is_expected.to contain_package('python3-atticmatic').with_ensure('present') }
end
context "with package_name => 'borgbackup'" do
let (:params) { { :package_name => 'borgbackup' } }
it { is_expected.to contain_package('borgbackup').with_ensure('present') }
end
end
<file_sep>/spec/classes/config_spec.rb
require 'spec_helper'
describe 'borgbackup::config' do
it { is_expected.to contain_file('/etc/atticmatic').with(
:ensure => 'directory',
:owner => 'root',
:group => 'root',
:mode => '0755'
) }
it { is_expected.to contain_file('/etc/borgmatic').with(
:ensure => 'directory',
:owner => 'root',
:group => 'root',
:mode => '0755'
) }
end
<file_sep>/spec/classes/init_spec.rb
require 'spec_helper'
describe 'borgbackup' do
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
context "without any parameters" do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('borgbackup') }
it { is_expected.to contain_class('borgbackup::params') }
it { is_expected.to contain_class('borgbackup::install').with_package_name([ 'python3-borgbackup', 'python3-atticmatic']) }
it { is_expected.to contain_class('borgbackup::config') }
it { is_expected.to have_borgbackup__configuration_resource_count(0) }
end
context "with package_name => foobar" do
let(:params) { { :package_name => 'foobar' } }
it { is_expected.to contain_class('borgbackup::install').with_package_name('foobar') }
end
context "with configurations => { 'filesystem' => { 'source_directories' => '/home', 'repository' => '/var/backups', 'encryption' => 'none' } }" do
let(:params) do
{ :configurations => { 'filesystem' => { 'source_directories' => '/home', 'repository' => '/var/backups', 'encryption' => 'none' } } }
end
it { is_expected.to have_borgbackup__configuration_resource_count(1) }
it { is_expected.to contain_borgbackup__configuration('filesystem').with(
'source_directories' => '/home',
'repository' => '/var/backups',
'encryption' => 'none'
) }
end
context "with configurations => { 'filesystem' => { 'source_directories' => '/home', 'repository' => '/var/backups'}, 'database' => { 'source_directories' => '/var/lib/mysql', 'repository' => '/var/db_backups' } }" do
let(:params) do
{ :configurations =>
{ 'filesystem' => { 'source_directories' => '/home', 'repository' => '/var/backups' },
'database' => { 'source_directories' => '/var/lib/mysql', 'repository' => '/var/db_backups' }
}
}
end
it { is_expected.to have_borgbackup__configuration_resource_count(2) }
it { is_expected.to contain_borgbackup__configuration('filesystem').with(
'source_directories' => '/home',
'repository' => '/var/backups'
) }
it { is_expected.to contain_borgbackup__configuration('database').with(
'source_directories' => '/var/lib/mysql',
'repository' => '/var/db_backups'
) }
end
end
end
end
context 'unsupported operating system' do
describe 'without any parameters on RedHat' do
let(:facts) do
{
:operatingsystem => 'RedHat'
}
end
it { expect { catalogue }.to raise_error(Puppet::Error, /RedHat not supported/) }
end
end
context 'unsupported operating system release' do
describe 'borgbackup class without any parameters on Ubuntu 12.04' do
let(:facts) do
{
:operatingsystem => 'Ubuntu',
:operatingsystemrelease => '12.04'
}
end
it { expect { catalogue }.to raise_error(Puppet::Error, /Ubuntu 12.04 not supported/) }
end
end
end
| 3f10c43925a9f79deb0282d1bf3e6ac8c7970118 | [
"Ruby"
] | 5 | Ruby | cultuurnet/puppet-borgbackup | 0c92c9b74e7eb3dcef62b86df5c2092e3d342318 | 9f822db32e3a3dd10017b09ca8d3c481dd253c53 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Estoque;
import model.EstoqueDAO;
import services.DB;
/**
*
* @author 1050481723010
*/
public class main extends javax.swing.JFrame {
GerarOrcamento frameorcamento;
private String codigo, nomep, nomec, familia, origem, descricao, porte, distancia, tamanhoc, cor, floracao, qtd, preco;
public void updateDetalhes(){//----------------------------------------------------------erro aqui----
getRow();
// System.out.println(a.getNome());
lblNomeCientifico.setText(nomec);
lblNomePopular.setText(nomep);
}
public void updateTabela(){//aqui
limparTabela();//esse não
EstoqueDAO edao = new EstoqueDAO();
ArrayList<Estoque> lista = edao.lista();
DefaultTableModel model = (DefaultTableModel)Tabela.getModel();
Object[] linha = new Object[12];
for(int i = 0; i<lista.size();i++){
linha[0]=lista.get(i).getCod();
linha[1]=lista.get(i).getNome();
linha[2]=lista.get(i).getNcientifico();
linha[3]=lista.get(i).getFamilia();
linha[4]=lista.get(i).getOrigem();
linha[5]=lista.get(i).getPorte();
linha[6]=lista.get(i).getDisplantio();
linha[7]=lista.get(i).getTamcova();
linha[8]=lista.get(i).getCor();
linha[9]=lista.get(i).getFloracao();
linha[10]=lista.get(i).getQtd();
linha[11]=lista.get(i).getPreco();
model.addRow(linha);
}
}
public void getRow(){//-----------------------------------------------------não sei se funciona----
int linha = Tabela.getSelectedRow();
DefaultTableModel model = (DefaultTableModel) Tabela.getModel();
try{
codigo = model.getValueAt(linha, 0).toString();
nomep = model.getValueAt(linha, 1).toString();
nomec = model.getValueAt(linha, 2).toString();
familia = model.getValueAt(linha, 3).toString();
origem = model.getValueAt(linha, 4).toString();
// descricao = model.getValueAt(linha, 0).toString();
porte = model.getValueAt(linha, 5).toString();
distancia = model.getValueAt(linha, 6).toString();
tamanhoc = model.getValueAt(linha, 7).toString();
cor = model.getValueAt(linha, 8).toString();
floracao = model.getValueAt(linha, 9).toString();
qtd = model.getValueAt(linha, 10).toString();
preco = model.getValueAt(linha, 11).toString();
}catch(Exception e){}
}
/**
* Creates new form main
*/
public main() {
initComponents();
updateTabela();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
btnBuscar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txtCod = new javax.swing.JTextField();
lbp1 = new javax.swing.JLabel();
lblNome = new javax.swing.JLabel();
txtNome = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtOrigem = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtCor = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
Tabela = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
btnAddOrcamento = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
lblNomePopular = new javax.swing.JLabel();
lblNomeCientifico = new javax.swing.JLabel();
lblDescricao = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu3 = new javax.swing.JMenu();
mniVendedor = new javax.swing.JMenuItem();
mniCliente = new javax.swing.JMenuItem();
jMenu4 = new javax.swing.JMenu();
mniEstoque = new javax.swing.JMenuItem();
mniOrcamentos = new javax.swing.JMenuItem();
mniVendas = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Plantarum");
setBounds(new java.awt.Rectangle(0, 0, 1280, 720));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setResizable(false);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
btnBuscar.setText("Buscar");
btnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Pesquisar");
txtCod.setToolTipText("Codigo");
lbp1.setText("Codigo");
lblNome.setText("Nome");
jLabel5.setText("Origem");
jLabel6.setText("Cor");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(57, 57, 57))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(btnBuscar))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblNome))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtCod, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lbp1)
.addGap(0, 133, Short.MAX_VALUE))
.addComponent(txtNome, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtOrigem, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCor, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(11, 11, 11)
.addComponent(lbp1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtCod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtCor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnBuscar)
.addContainerGap())
);
Tabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"cod", "nome", "nome cientifico", "familia", "origem", "porte", "distancia plantio", "tamanho cova", "cor", "floracao", "qtd", "preco"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Float.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
Tabela.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
TabelaMouseClicked(evt);
}
});
jScrollPane1.setViewportView(Tabela);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setText("ESTOQUE");
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
btnAddOrcamento.setText("Adicionar ao Orcamento");
btnAddOrcamento.setEnabled(false);
btnAddOrcamento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddOrcamentoActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("Detalhes");
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setText("img");
lblNomePopular.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblNomePopular.setText("Nome Popular");
lblNomeCientifico.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblNomeCientifico.setText("Nome Científico");
lblDescricao.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblDescricao.setText("Descricao");
lblDescricao.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddOrcamento, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNomePopular, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNomeCientifico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblDescricao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblNomePopular)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblNomeCientifico)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddOrcamento)
.addContainerGap())
);
jMenu3.setText("Pessoas");
mniVendedor.setText("Vendedor");
mniVendedor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniVendedorActionPerformed(evt);
}
});
jMenu3.add(mniVendedor);
mniCliente.setText("Cliente");
mniCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniClienteActionPerformed(evt);
}
});
jMenu3.add(mniCliente);
jMenuBar1.add(jMenu3);
jMenu4.setText("Flora");
mniEstoque.setText("Editar estoque");
mniEstoque.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniEstoqueActionPerformed(evt);
}
});
jMenu4.add(mniEstoque);
mniOrcamentos.setText("Orcamentos");
mniOrcamentos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniOrcamentosActionPerformed(evt);
}
});
jMenu4.add(mniOrcamentos);
mniVendas.setText("Vendas");
mniVendas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniVendasActionPerformed(evt);
}
});
jMenu4.add(mniVendas);
jMenuBar1.add(jMenu4);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 846, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 654, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void mniVendasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniVendasActionPerformed
// TODO add your handling code here:
new FrameVenda().setVisible(true);
}//GEN-LAST:event_mniVendasActionPerformed
private void mniVendedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniVendedorActionPerformed
// TODO add your handling code here:
new FrameVendedor().setVisible(true);
}//GEN-LAST:event_mniVendedorActionPerformed
private void btnAddOrcamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddOrcamentoActionPerformed
// TODO add your handling code here:
try{
if(frameorcamento==null){
frameorcamento = new GerarOrcamento();//colocar código no parentese----
frameorcamento.setVisible(true);
}
frameorcamento.addProduto(Integer.parseInt(codigo), nomep, Float.parseFloat(preco),1);
}catch(Exception e){
System.out.println(e.toString());
}
}//GEN-LAST:event_btnAddOrcamentoActionPerformed
private void TabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TabelaMouseClicked
// TODO add your handling code here:
if(!btnAddOrcamento.isEnabled()){
btnAddOrcamento.setEnabled(true);
}
updateDetalhes();
}//GEN-LAST:event_TabelaMouseClicked
private void mniEstoqueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniEstoqueActionPerformed
// TODO add your handling code here:
new EditarEstoque().setVisible(true);
}//GEN-LAST:event_mniEstoqueActionPerformed
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
// TODO add your handling code here:
if(txtCod.getText().isEmpty()
&& txtNome.getText().isEmpty()
&& txtOrigem.getText().isEmpty()
&& txtCor.getText().isEmpty()){
updateTabela();//esse é útil
}
else{
limparTabela();
String sql = "SELECT [cod_planta], [nome_planta], [ncientifico_planta], "
+ "[familia_planta], [origem_planta], "
+ "[porte_planta], [displantio_planta], [tamcova_planta], "
+ "[cor_planta], [floracao_planta], [qtdestoque_planta], "
+ "[preco_planta] FROM [dbo].[estoque] "
+ "WHERE ";
sql += "[cod_planta] like '%"+txtCod.getText()+"%' and";
sql += "[nome_planta] like '%"+txtNome.getText()+"%' and";
sql += "[origem_planta] like '%"+txtOrigem.getText()+"%' and";
sql += "[cor_planta] like '%"+txtCor.getText()+"%'";
DB bd = new DB();
bd.getConnection();
try{
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
DefaultTableModel model = (DefaultTableModel) Tabela.getModel();
Object[] linha = new Object[12];
while(bd.rs.next()){
linha[0]=bd.rs.getInt(1);
linha[1]=bd.rs.getString(2);
linha[2]=bd.rs.getString(3);
linha[3]=bd.rs.getString(4);
linha[4]=bd.rs.getString(5);
linha[5]=bd.rs.getFloat(6);
linha[6]=bd.rs.getFloat(7);
linha[7]=bd.rs.getFloat(8);
linha[8]=bd.rs.getString(9);
linha[9]=bd.rs.getString(10);
linha[10]=bd.rs.getInt(11);
linha[11]=bd.rs.getFloat(12);
model.addRow(linha);
}
}catch(SQLException e){System.out.println(e.toString());}
finally{
bd.close();
}
}
}//GEN-LAST:event_btnBuscarActionPerformed
private void mniOrcamentosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniOrcamentosActionPerformed
// TODO add your handling code here:
new FrameOrcamento().setVisible(true);
}//GEN-LAST:event_mniOrcamentosActionPerformed
private void mniClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniClienteActionPerformed
// TODO add your handling code here:
new FrameCliente().setVisible(true);
}//GEN-LAST:event_mniClienteActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable Tabela;
private javax.swing.JButton btnAddOrcamento;
private javax.swing.JButton btnBuscar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblDescricao;
private javax.swing.JLabel lblNome;
private javax.swing.JLabel lblNomeCientifico;
private javax.swing.JLabel lblNomePopular;
private javax.swing.JLabel lbp1;
private javax.swing.JMenuItem mniCliente;
private javax.swing.JMenuItem mniEstoque;
private javax.swing.JMenuItem mniOrcamentos;
private javax.swing.JMenuItem mniVendas;
private javax.swing.JMenuItem mniVendedor;
private javax.swing.JTextField txtCod;
private javax.swing.JTextField txtCor;
private javax.swing.JTextField txtNome;
private javax.swing.JTextField txtOrigem;
// End of variables declaration//GEN-END:variables
private void limparTabela() {
DefaultTableModel model = (DefaultTableModel)Tabela.getModel();
while(model.getRowCount()>0){
model.removeRow(0);
}
}
}
<file_sep>package model;
import java.sql.SQLException;
import java.util.ArrayList;
import services.DB;
public class VendedorDAO implements DAO{
public Vendedor v = new Vendedor();
public DB bd = new DB();
private String sql, ret; // variáveis internas
public VendedorDAO(String usuario, String senha){
v.setNome(usuario);
v.setSenha(senha);
}
public VendedorDAO(){
}
/**
* Esse método retorna uma lista com todos os vendedores dentro do banco de dados
* @return lista do tipo vendedor
*/
public ArrayList<Vendedor> lista() {
ArrayList<Vendedor> lista = new ArrayList<>();
sql = "SELECT [cod_vendedor], [nome_vendedor], [cpf_vendedor], "
+ "[sal_vendedor], [senha_vendedor], [email_vendedor], "
+ "[endereco_vendedor], [cidade_vendedor] FROM [dbo].[vendedor]";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
Vendedor v;
while (bd.rs.next()) {
v = new Vendedor(bd.rs.getInt(1), bd.rs.getString(2), bd.rs.getString(3),
bd.rs.getDouble(4), bd.rs.getString(5), bd.rs.getString(6),
bd.rs.getString(7), bd.rs.getString(8));
lista.add(v);
}
return lista;
} catch (SQLException erro) {
System.out.println(erro.toString());
} finally {
bd.close();
}
return lista;
}
/**
* Grava o cadastro de um Vendedor
*
* @param v - o Vendedor a ser salvo
* @return String - mensagem de retorno
*/
public String salvar(Vendedor v) {
sql = "INSERT INTO [dbo].[vendedor]"
+ "([nome_vendedor], [cpf_vendedor], [sal_vendedor], "
+ "[senha_vendedor],[email_vendedor],[endereco_vendedor],"
+ "[cidade_vendedor]) VALUES(?,?,?,?,?,?,?)";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setString(1, v.getNome());
bd.st.setString(2, v.getCpf());
bd.st.setDouble(3, v.getSalario());
bd.st.setString(4, v.getSenha());
bd.st.setString(5, v.getEmail());
bd.st.setString(6, v.getEndereco());
bd.st.setString(7, v.getCidade());
bd.st.executeUpdate();
ret = "Sucesso na inclusão";
} catch (SQLException erro) {
ret = "Falha " + erro.toString();
} finally {
bd.close();
}
return ret;
}
/**
* Atualiza o cadastro de um vendedor
* @param v - Vendedor a ser atualizado
* @return String - Sucesso ou mensagem de erro
*/
public String update(Vendedor v) {
sql = "update vendedor set nome_vendedor=?, cpf_vendedor=?, sal_vendedor=?, senha_vendedor=?, email_vendedor =? where cod_vendedor=?";
try {
bd.st = bd.con.prepareStatement(sql);
bd.st.setString(1, v.getNome());
bd.st.setString(2, v.getCpf());
bd.st.setDouble(3, v.getSalario());
bd.st.setString(4, v.getSenha());
bd.st.setString(5, v.getEmail());
bd.st.setInt(6, v.getCod());
bd.st.executeUpdate();
ret = "Sucesso na alteração";
} catch (SQLException e) {
ret = "Falha " + e.toString();
}
finally {
bd.close();
}
return ret;
}
/**
* Função para localizar um determinado vendedor através do seu código
* @param codigo - codigo do vendedor a ser buscado
* @return Vendedor - Retorna o objeto do vendedor que será localizado; se null, o vendedor não foi encontrado.
*/
public Vendedor localizar(int codigo) {
sql = "select * from vendedor where cod_vendedor = ?";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, codigo);
bd.rs = bd.st.executeQuery();
if (bd.rs.next()) { // copia bd-->objeto
v.setCod(bd.rs.getInt(1));
v.setNome(bd.rs.getString(2));
v.setCpf(bd.rs.getString(3));
v.setSalario(bd.rs.getDouble(4));
v.setSenha(bd.rs.getString(5));
v.setEmail(bd.rs.getString(6));
v.setEndereco(bd.rs.getString(7));
v.setCidade(bd.rs.getString(8));
return v;
} else {
return null;
}
} catch (SQLException erro) {
return null;
} finally {
bd.close();
}
}
@Override
public String Excluir(int codigo) {
sql = "delete from vendedor where cod_vendedor=?";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, codigo);
int n = bd.st.executeUpdate();
if (n == 1) {
ret = "Exclusão realizada";
} else {
ret = "Código não localizado";
}
} catch (SQLException erro) {
ret = "Falha " + erro.toString();
} finally {
bd.close();
}
return ret;
}
@Override
public void listar() {
sql = "select * from vendedor";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
while (bd.rs.next()) {
System.out.println("[" + bd.rs.getInt(1) + "," + bd.rs.getString(2) + "," + bd.rs.getFloat(3) + ","
+ bd.rs.getInt(4) + "]");
}
} catch (SQLException erro) {
System.out.println(erro.toString());
} finally {
bd.close();
}
}
}
<file_sep>package model;
import java.sql.SQLException;
import java.util.ArrayList;
import services.DB;
public class OrcamentoDAO implements DAO{
// 1 2 3 4 5
// cod_orcamento data_orcamento num_pedido fk_vendedor fk_cliente
// cod data numpedido ven cli;
public Orcamento o = new Orcamento();
public DB bd = new DB();
private String sql, ret;
public ArrayList<Orcamento> lista(boolean venda) {
ArrayList<Orcamento> lista = new ArrayList<>();
sql = "SELECT [cod_orcamento], [data_orcamento], [fk_vendedor], [fk_cliente], "
+ "[venda] FROM [dbo].[orcamento]";
if(venda)
sql+=" where venda = 1";
else
sql+=" where venda = 0";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
Orcamento o;
while (bd.rs.next()) {
o = new Orcamento(bd.rs.getInt(1), bd.rs.getString(2),
bd.rs.getInt(3), bd.rs.getInt(4), venda);
lista.add(o);
}
return lista;
} catch (SQLException erro) {
System.out.println(erro.toString());
} finally {
bd.close();
}
return lista;
}
/**
* Grava o cadastro de um Orçamento
* @param o - o Orçamento a ser salvo
* @return String - mensagem de retorno
*/
public String salvar(Orcamento o) {
sql = "insert into orcamento values (?,?,?,?)";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, o.getCod());
bd.st.setString(2, o.getData());
bd.st.setInt(3, o.getVen());
bd.st.setInt(4, o.getCli());
bd.st.executeUpdate();
ret = "Sucesso na inclusão";
} catch (SQLException erro) {
ret = "Falha " + erro.toString();
} finally {
bd.close();
}
return ret;
}
/**
* Atualiza o cadastro de um Orçamento
* @param o - Orçamento a ser atualizado
* @return String - Sucesso ou mensagem de erro
*/
public String update(Orcamento o) {
sql = "update orcamento set data_orcamento=?, fk_vendedor=?, fk_cliente=? where cod_orcamento=?";
try {
bd.st = bd.con.prepareStatement(sql);
bd.st.setString(1, o.getData());
bd.st.setInt(2, o.getVen());
bd.st.setInt(3, o.getCli());
bd.st.setInt(4, o.getCod());
bd.st.executeUpdate();
ret = "Sucesso na alteração";
} catch (SQLException e) {
ret = "Falha " + e.toString();
}
finally {
bd.close();
}
return ret;
}
/**
* Função para localizar um determinado orcamento através do seu código
* @param codigo - codigo do orcamento a ser buscado
* @return Orcamento - Retorna o objeto do orcamento que será localizado; se null, o orcamento não foi encontrado.
*/
public Orcamento localizar(int codigo) {
sql = "select * from orcamento where cod_orcamento=?";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, codigo);
bd.rs = bd.st.executeQuery();
if (bd.rs.next()) { // copia bd-->objeto
o.setCod(bd.rs.getInt(1));
o.setData(bd.rs.getString(2));
o.setVen(bd.rs.getInt(3));
o.setCli(bd.rs.getInt(4));
return o;
} else {
return null;
}
} catch (SQLException erro) {
return null;
} finally {
bd.close();
}
}
@Override
public void listar() {
sql = "select * from orcamento";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
while (bd.rs.next()) {
System.out.println("[" + bd.rs.getInt(1) + ", " + bd.rs.getString(2) + ", " + bd.rs.getInt(4)+ ", "
+ bd.rs.getInt(5) + "]");
}
} catch (SQLException erro) {
System.out.println(erro.toString());
} finally {
bd.close();
}
}
@Override
public String Excluir(int codigo) {
sql = "delete from orcamento where cod_orcamento=?";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, codigo);
int n = bd.st.executeUpdate();
if (n == 1) {
ret = "Exclusão realizada";
} else {
ret = "Código não localizado";
}
} catch (SQLException erro) {
ret = "Falha " + erro.toString();
} finally {
bd.close();
}
return ret;
}
}
<file_sep>package model;
public class ItemOrcamento {
private int cod, compraitem, qtd;
public Orcamento orcamento;
public Estoque planta;
public ItemOrcamento(int cod, int compraitem, int qtd, Orcamento orcamento, Estoque planta) {
this.cod = cod;
this.compraitem = compraitem;
this.qtd = qtd;
this.orcamento = orcamento;
this.planta = planta;
}
public ItemOrcamento() {
}
public int getCod() {
return cod;
}
public void setCod(int cod) {
this.cod = cod;
}
public int getCompraitem() {
return compraitem;
}
public void setCompraitem(int compraitem) {
this.compraitem = compraitem;
}
public int getQtd() {
return qtd;
}
public void setQtd(int qtd) {
this.qtd = qtd;
}
public Orcamento getOrcamento() {
return orcamento;
}
public void setOrcamento(Orcamento orcamento) {
this.orcamento = orcamento;
}
public Estoque getPlanta() {
return planta;
}
public void setPlanta(Estoque planta) {
this.planta = planta;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import model.Cliente;
import model.ClienteDAO;
import services.DB;
/**
*
* @author Dario
*/
public class FrameCliente extends javax.swing.JFrame {
private int linha=1;
public void limparTabela(){
DefaultTableModel model = (DefaultTableModel)Tabela.getModel();
while(model.getRowCount()>0){
model.removeRow(0);
}
}
/**
* Creates new form Cliente
*/
public FrameCliente() {
initComponents();
updateTabela();
}
public void updateTabela(){
limparTabela();
ClienteDAO cdao = new ClienteDAO();
ArrayList<Cliente> lista = cdao.lista();
DefaultTableModel model = (DefaultTableModel)Tabela.getModel();
Object[] linha = new Object[7];
for(int i = 0; i<lista.size();i++){
linha[0]=lista.get(i).getCod();
linha[1]=lista.get(i).getNome();
linha[2]=lista.get(i).getCpf();
linha[3]=lista.get(i).getEmail();
linha[4]=lista.get(i).getContato();
linha[5]=lista.get(i).getEndereco();
linha[6]=lista.get(i).getCidade();
model.addRow(linha);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
Tabela = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtNome = new javax.swing.JTextField();
btnProcurar = new javax.swing.JButton();
btnAdd = new javax.swing.JButton();
btnExcluir = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
Tabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"codigo", "nome", "cpf", "email", "contato", "endereco", "cidade"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
Tabela.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
TabelaMouseClicked(evt);
}
});
jScrollPane1.setViewportView(Tabela);
jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jLabel2.setText("Nome");
btnProcurar.setText("Procurar");
btnProcurar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnProcurarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtNome)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(0, 119, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(btnProcurar)
.addContainerGap(48, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(120, 120, 120)
.addComponent(btnProcurar)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
btnAdd.setText("Adicionar");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnExcluir.setText("Excluir");
btnExcluir.setEnabled(false);
btnExcluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExcluirActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(btnAdd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdd)
.addComponent(btnExcluir))
.addGap(26, 26, 26))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
// TODO add your handling code here:
new CadastroCliente().setVisible(true);
}//GEN-LAST:event_btnAddActionPerformed
private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
// TODO add your handling code here:
DB bd = new DB();
bd.getConnection();
String sql = "delete from cliente where cod_cliente=?";
try{
bd.st = bd.con.prepareCall(sql);
bd.st.setInt(1, (int) Tabela.getValueAt(linha, 0));
bd.st.executeUpdate();
updateTabela();
} catch (SQLException ex) {
Logger.getLogger(FrameCliente.class.getName()).log(Level.SEVERE, null, ex);
}finally{
bd.close();
}
}//GEN-LAST:event_btnExcluirActionPerformed
private void TabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TabelaMouseClicked
// TODO add your handling code here:
if(!btnExcluir.isEnabled())
btnExcluir.setEnabled(true);
else
btnExcluir.setEnabled(false);
linha = Tabela.getSelectedRow();
}//GEN-LAST:event_TabelaMouseClicked
private void btnProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProcurarActionPerformed
// TODO add your handling code here:
if(txtNome.getText().isEmpty()){
updateTabela();
}
else{
limparTabela();
String sql = "SELECT [cod_cliente], [nome_cliente], [cpf_cliente], "
+ "[email_cliente], [contato_cliente], [endereco_cliente], "
+ "[cidade_cliente] FROM [dbo].[cliente]"
+ "WHERE [nome_cliente] like '"+txtNome.getText()+"%'";
DB bd = new DB();
bd.getConnection();
try{
System.out.println(sql);
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
// --------------------------------------------------------parei aqui---------------------
DefaultTableModel model = (DefaultTableModel) Tabela.getModel();
Object[] i = new Object[8];
while(bd.rs.next()){
i[0]=bd.rs.getInt(1);
i[1]=bd.rs.getString(2);
i[2]=bd.rs.getString(3);
i[3]=bd.rs.getString(4);
i[4]=bd.rs.getString(5);
i[5]=bd.rs.getString(6);
i[6]=bd.rs.getString(7);
model.addRow(i);
}
}catch(SQLException e){System.out.println(e.toString());}
finally{
bd.close();
}
}
}//GEN-LAST:event_btnProcurarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrameCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrameCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrameCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrameCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrameCliente().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable Tabela;
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnExcluir;
private javax.swing.JButton btnProcurar;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField txtNome;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import javax.swing.JOptionPane;
import model.Estoque;
import model.EstoqueDAO;
import services.DB;
/**
*
* @author Marquinhos
*/
public class AddEstoque extends javax.swing.JFrame {
/**
* Creates new form AddEstoque
*/
public AddEstoque() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
nomep = new javax.swing.JTextField();
nomec = new javax.swing.JTextField();
familia = new javax.swing.JTextField();
origem = new javax.swing.JTextField();
descricao = new javax.swing.JTextField();
porte = new javax.swing.JTextField();
displantio = new javax.swing.JTextField();
tamcova = new javax.swing.JTextField();
cor = new javax.swing.JTextField();
floracao = new javax.swing.JTextField();
qtd = new javax.swing.JTextField();
preco = new javax.swing.JTextField();
btnLimpar = new javax.swing.JButton();
btnSalvar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Nome:");
jLabel2.setText("Nome Científico:");
jLabel3.setText("Familia:");
jLabel4.setText("Origem:");
jLabel5.setText("Descricao:");
jLabel6.setText("Porte:");
jLabel7.setText("Distancia do plantio:");
jLabel8.setText("Tamanho da cova:");
jLabel9.setText("Cor:");
jLabel10.setText("Floracao:");
jLabel11.setText("Quantidade:");
jLabel12.setText("Preco");
btnLimpar.setText("Limpar");
btnLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLimparActionPerformed(evt);
}
});
btnSalvar.setText("Salvar");
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nomep, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
.addComponent(nomec)
.addComponent(familia)
.addComponent(origem)
.addComponent(descricao)
.addComponent(porte)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jLabel9)
.addComponent(jLabel10)
.addComponent(jLabel11)
.addComponent(jLabel12))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(displantio)
.addComponent(tamcova)
.addComponent(cor)
.addComponent(floracao, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
.addComponent(qtd)
.addComponent(preco))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnLimpar)
.addComponent(btnSalvar))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(nomep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLimpar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(nomec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSalvar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(familia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(origem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(descricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(porte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(displantio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(tamcova, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(cor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(floracao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(qtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(preco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
// TODO add your handling code here:
EstoqueDAO edao = new EstoqueDAO();
try{
Estoque e = new Estoque(nomep.getText(), nomec.getText(), familia.getText(),
origem.getText(), descricao.getText(),
Float.parseFloat(porte.getText()), Float.parseFloat(displantio.getText()),
Float.parseFloat(tamcova.getText()), cor.getText(), floracao.getText(),
Integer.parseInt(qtd.getText()), Float.parseFloat(preco.getText()));
edao.salvar(e);
JOptionPane.showMessageDialog(null, "Cadastrado com sucesso");
}catch(NullPointerException | NumberFormatException e){JOptionPane.showMessageDialog(null, e.toString());}
}//GEN-LAST:event_btnSalvarActionPerformed
private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
// TODO add your handling code here:
nomep.setText("");
nomec.setText("");
familia.setText("");
origem.setText("");
descricao.setText("");
porte.setText("");
displantio.setText("");
tamcova.setText("");
cor.setText("");
floracao.setText("");
qtd.setText("");
preco.setText("");
}//GEN-LAST:event_btnLimparActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddEstoque().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnLimpar;
private javax.swing.JButton btnSalvar;
private javax.swing.JTextField cor;
private javax.swing.JTextField descricao;
private javax.swing.JTextField displantio;
private javax.swing.JTextField familia;
private javax.swing.JTextField floracao;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JTextField nomec;
private javax.swing.JTextField nomep;
private javax.swing.JTextField origem;
private javax.swing.JTextField porte;
private javax.swing.JTextField preco;
private javax.swing.JTextField qtd;
private javax.swing.JTextField tamcova;
// End of variables declaration//GEN-END:variables
}
<file_sep>package model;
import java.sql.SQLException;
import java.util.ArrayList;
import services.DB;
public class ClienteDAO implements DAO{
public Cliente c = new Cliente();
public DB bd = new DB();
private String sql, ret;
// 1 2 3 4 5 6
// cod_cliente nome_cliente cpf_cliente email_cliente contato_cliente endereco_cliente
// cod nome cpf email contato endereco
public ArrayList<Cliente> lista() {
ArrayList<Cliente> lista = new ArrayList<>();
sql = "select * from cliente";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
Vendedor v;
while (bd.rs.next()) {
c = new Cliente(bd.rs.getInt(1), bd.rs.getString(2), bd.rs.getString(3), bd.rs.getString(4),
bd.rs.getString(5), bd.rs.getString(6), bd.rs.getString(7));
lista.add(c);
}
return lista;
} catch (SQLException erro) {
System.out.println(erro.toString());
} finally {
bd.close();
}
return lista;
}
/**
* Grava o cadastro de um Cliente.
* @param c - o Cliente a ser salvo.
* @return String - mensagem de sucesso ou falha.
*/
public String salvar(Cliente c) {
sql = "INSERT INTO [dbo].[cliente] ([nome_cliente], [cpf_cliente], "
+ "[email_cliente], [contato_cliente], [endereco_cliente], "
+ "[cidade_cliente]) VALUES (?,?,?,?,?,?)";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setString(1, c.getNome());
bd.st.setString(2, c.getCpf());
bd.st.setString(3, c.getEmail());
bd.st.setString(4, c.getContato());
bd.st.setString(5, c.getEndereco());
bd.st.setString(6, c.getCidade());
bd.st.executeUpdate();
ret = "Sucesso na inclusão";
} catch (SQLException erro) {
ret = "Falha " + erro.toString();
} finally {
bd.close();
}
return ret;
}
/**
* Atualiza o cadastro de um Cliente
* @param c - Cliente a ser atualizado
* @return String - Sucesso ou mensagem de erro
*/
public String update(Cliente c) {
sql = "update cliente set nome_cliente=?, cpf_cliente=?, email_cliente=?, contato_cliente=?, endereco_cliente=? where cod_cliente=?";
try {
bd.st = bd.con.prepareStatement(sql);
bd.st.setString(1, c.getNome());
bd.st.setString(2, c.getCpf());
bd.st.setString(3, c.getEmail());
bd.st.setString(4, c.getContato());
bd.st.setString(5, c.getEndereco());
bd.st.setInt(6, c.getCod());
bd.st.executeUpdate();
ret = "Sucesso na alteração";
} catch (SQLException e) {
ret = "Falha " + e.toString();
}
finally {
bd.close();
}
return ret;
}
/**
* Função para localizar um determinado Cliente através do seu código.
* @param codigo - codigo do Cliente a ser buscado.
* @return Cliente - Retorna o objeto do Cliente que será localizado; se null, o Cliente não foi encontrado.
*/
public Cliente localizar(int codigo) {
sql = "select * from cliente where cod_cliente=?";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, codigo);
bd.rs = bd.st.executeQuery();
if (bd.rs.next()) { // copia bd-->objeto
c.setCod(bd.rs.getInt(1));
c.setNome(bd.rs.getString(2));
c.setCpf(bd.rs.getString(3));
c.setEmail(bd.rs.getString(4));
c.setContato(bd.rs.getString(5));
c.setEndereco(bd.rs.getString(6));
return c;
} else {
return null;
}
} catch (SQLException erro) {
return null;
} finally {
bd.close();
}
}
@Override
public void listar() {
sql = "select * from cliente";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
while (bd.rs.next()) {
System.out.println("[" + bd.rs.getInt(1) + "," +
bd.rs.getString(2) + "," +
bd.rs.getString(3) + "," +
bd.rs.getString(4) + "," +
bd.rs.getString(5) + "," +
bd.rs.getString(6) + "]");
}
} catch (SQLException erro) {
System.out.println(erro.toString());
} finally {
bd.close();
}
}
@Override
public String Excluir(int codigo) {
sql = "delete from cliente where cod_cliente=?";
try {
bd.getConnection();
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, codigo);
int n = bd.st.executeUpdate();
if (n == 1) {
ret = "Exclusão realizada";
} else {
ret = "Código não localizado";
}
} catch (SQLException erro) {
ret = "Falha " + erro.toString();
} finally {
bd.close();
}
return ret;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import java.awt.HeadlessException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import model.Vendedor;
import model.VendedorDAO;
import services.DB;
/**
*
* @author Dario
*/
public class GerarOrcamento extends javax.swing.JFrame {
private int produtos=0;
private double total=0;
private Vendedor vorcamento;
private DB bd = new DB();
private final int GAP = 12;
public void updateTotal(){
total=0;
for(int i = 0;i <Tabela.getRowCount(); i++){
double preco = Double.parseDouble(Tabela.getValueAt(i, 2).toString());
int qtd = Integer.parseInt(Tabela.getValueAt(i, 3).toString());
total += preco * qtd;
}
// System.out.println(""+(double) Tabela.getValueAt(0, 3));
lblPrecoTotal.setText(""+total);
}
public void addProduto(int cod, String nome, float preco, int qtd){
//--------------------------------------criar vetor de labels para o código de cada produto
//criar vetor com todos os itens do painel para depois criar vetor de paineis com os itens dentro
DefaultTableModel model = (DefaultTableModel) Tabela.getModel();
Object[] linha = new Object[4];
linha[0] = cod;
linha[1] = nome;
linha[2] = preco;
linha[3] = qtd;
model.addRow(linha);
updateTotal();
}
public void setValues(){
bd.getConnection();
String sql = "Select cod_vendedor from vendedor";
try{
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
while(bd.rs.next()){
cbVendedor.addItem(bd.rs.getString(1));
}
}catch(SQLException e){
System.out.println(e.toString());
}
sql = "select cod_cliente from cliente";
try{
bd.st = bd.con.prepareStatement(sql);
bd.rs = bd.st.executeQuery();
while(bd.rs.next()){
cbCliente.addItem(bd.rs.getString(1));
}
}catch(SQLException e){
System.out.println(e.toString());
}
bd.close();
}
public GerarOrcamento(){
initComponents();
setValues();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
detalheorcamento = new javax.swing.JPanel();
chkVenda = new javax.swing.JCheckBox();
lblorcamento = new javax.swing.JLabel();
cbVendedor = new javax.swing.JComboBox<>();
cbCliente = new javax.swing.JComboBox<>();
chkVendedor = new javax.swing.JCheckBox();
chkCliente = new javax.swing.JCheckBox();
lblselecionar = new javax.swing.JLabel();
lblPrecoTotal = new javax.swing.JLabel();
btnSalvar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
Tabela = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
detalheorcamento.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
chkVenda.setText("Venda");
lblorcamento.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblorcamento.setText("Orçamento total");
lblorcamento.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
cbVendedor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Vendedor" }));
cbVendedor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbVendedorActionPerformed(evt);
}
});
cbCliente.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Cliente" }));
cbCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbClienteActionPerformed(evt);
}
});
chkVendedor.setText("Vendedor");
chkVendedor.setEnabled(false);
chkVendedor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkVendedorActionPerformed(evt);
}
});
chkCliente.setText("Cliente");
chkCliente.setEnabled(false);
chkCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkClienteActionPerformed(evt);
}
});
lblselecionar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblselecionar.setText("Selecionar");
lblselecionar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lblPrecoTotal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblPrecoTotal.setText("0");
lblPrecoTotal.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnSalvar.setText("Salvar");
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
javax.swing.GroupLayout detalheorcamentoLayout = new javax.swing.GroupLayout(detalheorcamento);
detalheorcamento.setLayout(detalheorcamentoLayout);
detalheorcamentoLayout.setHorizontalGroup(
detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblselecionar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblPrecoTotal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(detalheorcamentoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(detalheorcamentoLayout.createSequentialGroup()
.addGroup(detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(chkVendedor, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
.addComponent(cbVendedor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, detalheorcamentoLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(lblorcamento, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addGroup(detalheorcamentoLayout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(chkVenda)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnSalvar)
.addGap(44, 44, 44))
);
detalheorcamentoLayout.setVerticalGroup(
detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(detalheorcamentoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblselecionar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(chkVendedor)
.addComponent(chkCliente))
.addGap(49, 49, 49)
.addComponent(lblorcamento)
.addGap(41, 41, 41)
.addComponent(lblPrecoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(69, 69, 69)
.addGroup(detalheorcamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(chkVenda)
.addComponent(btnSalvar))
.addContainerGap(26, Short.MAX_VALUE))
);
Tabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Codigo", "Planta", "Preco", "Quantidade"
}
) {
boolean[] canEdit = new boolean [] {
false, false, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
Tabela.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
TabelaFocusLost(evt);
}
});
Tabela.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
TabelaKeyReleased(evt);
}
});
jScrollPane1.setViewportView(Tabela);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(detalheorcamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(detalheorcamento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void chkVendedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkVendedorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chkVendedorActionPerformed
private void chkClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkClienteActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chkClienteActionPerformed
private void cbVendedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbVendedorActionPerformed
// TODO add your handling code here:
if(cbVendedor.getSelectedItem()!= "Vendedor"){
chkVendedor.setSelected(true);
}else{chkVendedor.setSelected(false);}
}//GEN-LAST:event_cbVendedorActionPerformed
private void cbClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbClienteActionPerformed
// TODO add your handling code here:
if(cbCliente.getSelectedItem()!= "Cliente"){
chkCliente.setSelected(true);
}else{chkCliente.setSelected(false);}
}//GEN-LAST:event_cbClienteActionPerformed
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
// TODO add your handling code here:
if(chkVendedor.isSelected() && chkCliente.isSelected()){
String data = DateTimeFormatter.ofPattern("dd/MM/yyy").format(LocalDate.now());
bd.getConnection();
int linhas = Tabela.getRowCount();
int venda=0;
int idorcamento=1;
if(chkVenda.isSelected()){
venda =1;
}
String sql = "INSERT INTO [dbo].[orcamento] ([data_orcamento],"
+ "[fk_vendedor], [fk_cliente], [venda])"
+ "VALUES (?, ?, ?, ?)";
try{
bd.st = bd.con.prepareStatement(sql);
bd.st.setString(1, data);
bd.st.setInt(2, Integer.parseInt(cbVendedor.getSelectedItem().toString()));
bd.st.setInt(3, Integer.parseInt(cbCliente.getSelectedItem().toString()));
bd.st.setInt(4, venda);
bd.st.executeUpdate();
//pegar id do código do orçamento gerado
bd.st = bd.con.prepareStatement("SELECT [cod_orcamento] FROM [dbo].[orcamento]");
bd.rs = bd.st.executeQuery();
while(bd.rs.next()){
if(bd.rs.getInt(1)>idorcamento)
idorcamento = bd.rs.getInt(1);
}
System.out.println("até aqui tá ok1");
sql = "INSERT INTO [dbo].[item_orcamento] ([compra_iorcamento], "
+ "[qtdprod_iorcamento], [fk_orcamento], [fk_planta], [preco_iorcamento])\n" +
"VALUES (?, ?, ?, ?, ?)";
for(int i = 0; i < linhas; i++){
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, venda);
bd.st.setInt(2, Integer.parseInt(Tabela.getValueAt(i, 3).toString()));
bd.st.setInt(3, idorcamento);
bd.st.setInt(4, Integer.parseInt(Tabela.getValueAt(i, 0).toString()));
bd.st.setFloat(5, Float.parseFloat(Tabela.getValueAt(i, 2).toString()));
bd.st.executeUpdate();
}
if(chkVenda.isSelected()){
sql = "UPDATE [dbo].[estoque] SET [qtdestoque_planta] = [qtdestoque_planta]-? "
+ "WHERE [cod_planta] = ?";
DefaultTableModel model = (DefaultTableModel) Tabela.getModel();
for(int i = 0; i<Tabela.getRowCount(); i++){
bd.st = bd.con.prepareStatement(sql);
bd.st.setInt(1, Integer.parseInt(Tabela.getValueAt(i, 3).toString()));
bd.st.setInt(2, Integer.parseInt(Tabela.getValueAt(i, 0).toString()));
bd.st.executeUpdate();
}
}
JOptionPane.showMessageDialog(null, "Sucesso");
}catch(SQLException | HeadlessException | NumberFormatException e){
System.out.println(e.toString());
JOptionPane.showMessageDialog(null,e.toString());
}
finally{bd.close();}
}else{JOptionPane.showMessageDialog(null, "Selecione um vendedor e um cliente para salvar o orcamento");}
}//GEN-LAST:event_btnSalvarActionPerformed
private void TabelaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TabelaFocusLost
// TODO add your handling code here:
updateTotal();
}//GEN-LAST:event_TabelaFocusLost
private void TabelaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TabelaKeyReleased
// TODO add your handling code here:
updateTotal();
}//GEN-LAST:event_TabelaKeyReleased
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GerarOrcamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GerarOrcamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GerarOrcamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GerarOrcamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GerarOrcamento().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JTable Tabela;
private javax.swing.JButton btnSalvar;
private javax.swing.JComboBox<String> cbCliente;
private javax.swing.JComboBox<String> cbVendedor;
private javax.swing.JCheckBox chkCliente;
private javax.swing.JCheckBox chkVenda;
private javax.swing.JCheckBox chkVendedor;
private javax.swing.JPanel detalheorcamento;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblPrecoTotal;
private javax.swing.JLabel lblorcamento;
private javax.swing.JLabel lblselecionar;
// End of variables declaration//GEN-END:variables
}
<file_sep>package model;
public class Vendedor {
private int cod;
private String nome, cpf, senha, email, endereco, cidade;
private double salario;
public Vendedor() {
}
public Vendedor(int cod, String nome, String cpf, double salario, String senha, String email, String endereco, String cidade) {
this.cod = cod;
this.nome = nome;
this.cpf = cpf;
this.salario = salario;
this.senha = senha;
this.email = email;
this.endereco = endereco;
this.cidade = cidade;
}
public Vendedor(String nome, String cpf, double salario, String senha, String email, String endereco, String cidade) {
// this.cod = cod;
this.nome = nome;
this.cpf = cpf;
this.salario = salario;
this.senha = senha;
this.email = email;
this.endereco = endereco;
this.cidade = cidade;
}
public int getCod() {
return cod;
}
public void setCod(int cod) {
this.cod = cod;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public double getSalario() {
return salario;
}
public void setSalario(double salario) {
this.salario = salario;
}
public String getSenha(){
return senha;
}
public void setSenha(String senha){
this.senha = senha;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getEndereco(){
return endereco;
}
public void setEndereco(String endereco){
this.endereco = endereco;
}
public String getCidade(){
return cidade;
}
public void setCidade(String cidade){
this.cidade = cidade;
}
}
<file_sep>package model;
public class Cliente{
private int cod;
private String nome, cpf, email, contato, endereco, cidade;
public Cliente() {
}
public Cliente(String nome, String cpf, String email, String contato, String endereco, String cidade) {
// this.cod = cod;
this.nome = nome;
this.cpf = cpf;
this.email = email;
this.contato = contato;
this.endereco = endereco;
this.cidade = cidade;
}
public Cliente(int cod, String nome, String cpf, String email, String contato, String endereco, String cidade) {
this.cod = cod;
this.nome = nome;
this.cpf = cpf;
this.email = email;
this.contato = contato;
this.endereco = endereco;
this.cidade = cidade;
}
public int getCod() {
return cod;
}
public void setCod(int cod) {
this.cod = cod;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContato() {
return contato;
}
public void setContato(String contato) {
this.contato = contato;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCidade(){
return cidade;
}
public void setCidade(String cidade){
this.cidade = cidade;
}
}
| ca4ae3bb1eaf36e72addd0c4b84abcf83c8e21c6 | [
"Java"
] | 10 | Java | AlvesDario/Plantarum | 327ccb73b4abfd4dbff72fadc7ab1c403763ad84 | 6872ba4c473855c07c44609e141a3593e7bf3449 |
refs/heads/master | <repo_name>MahmoudGhor/IderHospital-Gateway<file_sep>/src/main/java/com/example/zuul_server/controllers/AuthController.java
package com.example.zuul_server.controllers;
import com.example.zuul_server.config.JwtTokenProvider;
import com.example.zuul_server.models.ConfirmationToken;
import com.example.zuul_server.models.User;
import com.example.zuul_server.repositories.ConfirmationTokenRepository;
import com.example.zuul_server.repositories.RoleRepository;
import com.example.zuul_server.repositories.UserRepository;
import com.example.zuul_server.services.CustomUserDetailsService;
import com.example.zuul_server.services.EmailSenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.AuthenticationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.springframework.http.ResponseEntity.ok;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private static final String TYPEMESSAGE = "message";
Logger logger = LoggerFactory.getLogger(AuthController.class);
@Autowired
private ConfirmationTokenRepository confirmationTokenRepository;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtTokenProvider jwtTokenProvider;
@Autowired
UserRepository users;
@Autowired
private EmailSenderService emailSenderService;
@Autowired
private RoleRepository roles;
@Autowired
private CustomUserDetailsService userService;
@PostMapping("/login")
public ResponseEntity login(@RequestBody AuthBody data){
try {
String username = data.getEmail();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
User user = this.users.findByEmail(username);
if (!user.isActivated()) {
return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
}
if (!user.isEnabled()) {
return new ResponseEntity(HttpStatus.FORBIDDEN);
}
String token = jwtTokenProvider.createToken(username, this.users.findByEmail(username).getRoles());
Map<Object, Object> model = new HashMap<>();
model.put("email", username);
model.put("token", token);
model.put("_id", user.getId());
model.put("firstName", user.getFirstName());
model.put("lastName", user.getLastName());
model.put("createdDate", user.getCreatedDate());
model.put("roles", user.getRoles());
model.put("activated", user.isActivated());
model.put("enabled", user.isEnabled());
model.put("password", user.getPassword());
return ok(model);
} catch (AuthenticationException e) {
throw e;
}
}
@SuppressWarnings("rawtypes")
@PostMapping("/register")
public ResponseEntity register(@RequestBody User user) {
User userExists = userService.findUserByEmail(user.getEmail());
if (userExists != null) {
return new ResponseEntity<String>("Vous Avez déja un compte", HttpStatus.FOUND);
}
user.setRoles(new HashSet<>());
user.getRoles().add(roles.findByRole("USER"));
userService.saveUser(user);
//sending confirmation mail
ConfirmationToken confirmationToken = new ConfirmationToken(user);
confirmationTokenRepository.save(confirmationToken);
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(user.getEmail());
mailMessage.setFrom("<EMAIL>");
mailMessage.setText("To confirm your account please click here : " + "http://localhost:8084/api/auth/confirm-account/" + confirmationToken.getConfirmationToken());
emailSenderService.sendEmail(mailMessage);
Map<Object, Object> model = new HashMap<>();
model.put(TYPEMESSAGE, "User registered successfully");
return ok(model);
}
@RequestMapping(value = "/confirm-account/{token}", method = {RequestMethod.GET})
public String confirmUserAccount(@PathVariable("token") String confirmationToken) {
ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);
Map<Object, Object> model = new HashMap<>();
if (token != null) {
User user = users.findByEmail(token.getUser().getEmail());
user.setId(token.getUser().getId());
user.setActivated(true);
users.save(user);
return htmlContent("Vous pouvez vous connectez avec votre compte désormais ...");
} else {
return htmlContent("Token de confirmation est invalide");
}
}
private String htmlContent(String content){
return "<html>\n" +
" <head>\n" +
" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">\n" +
" <style>\n" +
" a,a:focus,a:hover {\n" +
" color: #fff;\n" +
" }\n" +
" .btn-secondary,\n" +
" .btn-secondary:hover,\n" +
" .btn-secondary:focus {\n" +
" color: #333;\n" +
" text-shadow: none; /* Prevent inheritance from `body` */\n" +
" background-color: #fff;\n" +
" border: .05rem solid #fff;\n" +
" }\n" +
" body {\n" +
" display: -ms-flexbox;\n" +
" display: flex;\n" +
" color: #fff;\n" +
" text-shadow: 0 .05rem .1rem rgba(0, 0, 0, .5);\n" +
" box-shadow: inset 0 0 5rem rgba(0, 0, 0, .5);\n" +
" background-image: url('https://i.ibb.co/6Ff6yzQ/404.jpg');\n" +
" background-size: 100% 100%;\n" +
" }\n" +
" .cover-container {\n" +
" max-width: 42em;\n" +
" }\n" +
" .masthead {\n" +
" margin-bottom: 2rem;\n" +
" }\n" +
" .masthead-brand {\n" +
" margin-bottom: 0;\n" +
" }\n" +
" .nav-masthead .nav-link {\n" +
" padding: .25rem 0;\n" +
" font-weight: 700;\n" +
" color: rgba(255, 255, 255, .5);\n" +
" background-color: transparent;\n" +
" border-bottom: .25rem solid transparent;\n" +
" }\n" +
" .nav-masthead .nav-link:hover,\n" +
" .nav-masthead .nav-link:focus {\n" +
" border-bottom-color: rgba(255, 255, 255, .25);\n" +
" }\n" +
" .nav-masthead .nav-link + .nav-link {\n" +
" margin-left: 1rem;\n" +
" }\n" +
" .nav-masthead .active {\n" +
" color: #fff;\n" +
" border-bottom-color: #fff;\n" +
" }\n" +
" @media (min-width: 48em) {\n" +
" .masthead-brand {\n" +
" float: left;\n" +
" }\n" +
" .nav-masthead {\n" +
" float: right;\n" +
" }\n" +
" }\n" +
" .cover {\n" +
" padding: 0 1.5rem;\n" +
" }\n" +
" .cover .btn-lg {\n" +
" padding: .75rem 1.25rem;\n" +
" font-weight: 700;\n" +
" }\n" +
" .mastfoot {\n" +
" color: rgba(255, 255, 255, .5);\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
"<body>\n" +
" <div class=\"cover-container d-flex w-100 h-100 p-3 mx-auto flex-column\">\n" +
" <header class=\"masthead mb-auto\">\n" +
" <div class=\"inner\">\n" +
" <img src=\"https://i.ibb.co/D9tVXrj/biat.png\" class=\"img-fluid masthead-brand\" style=\" width:50px;height: 50px\"/>\n" +
" \n" +
" </div>\n" +
" </header>\n" +
" \n" +
" <main role=\"main\" class=\"inner cover\" style=\"margin-top : 150px\">\n" +
" <h1 class=\"cover-heading\">Validation de compte</h1>\n" +
" <p class=\"lead\">"+content+"</p>\n" +
" <p class=\"lead\" style=\"margin-top : 150px\">\n" +
" <a href=\"http://localhost:4200/login\" class=\"btn btn-lg btn-secondary\">Page Accueil</a>\n" +
" </p>\n" +
" </main>\n" +
" \n" +
" <footer class=\"mastfoot mt-auto\">\n" +
" <div class=\"inner\">\n" +
" \n" +
" </div>\n" +
" </footer>\n" +
" </div>\n" +
" </body>\n" +
"</html>";
}
}
| 4f6d833f897b1b55524b88741f0426a861b99565 | [
"Java"
] | 1 | Java | MahmoudGhor/IderHospital-Gateway | 1054fe93937fca70d842088b52fb1c87351b6492 | 87367fcd42393800f4d512d658673834b38f0e1b |
refs/heads/master | <file_sep>const { Bidder, BidProperty, Property } = require('../models')
const bcrypt = require('bcrypt')
class ControllerBidder {
static showRegistrationForm(req, res) {
let queries = req.query
res.render('bidders/bidder-register', { queries })
}
static register(req, res) {
let { name, phone, email, password } = req.body
Bidder
.create({
name: name,
phone: phone,
email: email,
password: <PASSWORD>
})
.then(success => {
Bidder.findOne({
where: {
email: email
}
})
.then(bidder => {
req.session.user = {
id: bidder.id,
email: bidder.email
}
res.redirect(`/?login=true`)
console.log(req.session)
})
})
.catch(err => res.redirect(`/bidder/register?error=${err.message}`))
}
static showLoginForm(req, res) {
let queries = req.query
res.render('bidders/bidder-login', { queries })
}
static login(req, res) {
let { email, password } = req.body
if (email.length < 1) {
res.redirect(`/bidder/login?error=Please input an email address!`)
return
} else if (password.length < 1) {
res.redirect(`/bidder/login?error=Please input your password!`)
return
}
Bidder
.findOne({
where: {
email: email
}
})
.then((user) => {
// res.send('AAA')
if (!user) {
res.redirect(`/bidder/login?error=Wrong email/password!`)
}
else {
if (bcrypt.compareSync(password, user.password)) {
req.session.user = {
id: user.id,
email: req.body.email
}
res.redirect(`/bidder/profile/${user.id}?login=true`)
}
else {
res.redirect(`/bidder/login?error=Wrong email/password!`)
}
}
})
.catch(err => res.redirect(`/bidder/login?error=${err.message}`))
}
static showProfile(req, res) {
let sess = req.session
let {profileId} = req.params
let queries = req.query
let bidder, properties
Bidder
.findByPk(profileId)
.then(bidderData => {
bidder = bidderData
// console.log("ini sess", sess);
return Property
.findAll({
where: {
SellerId: sess.user.id
},
include: Bidder
})
})
.then(properties => {
// res.send(properties[0].Bidders)
res.render('bidders/bidder-profile', { queries, bidder, sess, properties })
// properties = propertiesData
// // res.send (properties)
// res.render('bidders/bidder-profile', { queries, bidder, sess, properties })
})
.catch(err => res.redirect(`/bidder/profile?error=${err.message}`))
}
static logout(req, res) {
req.session.destroy(() => {
res.redirect('/')
})
}
}
module.exports = ControllerBidder
<file_sep>const express = require('express')
const app = express()
const session = require('express-session')
const port = 3000
const bidder = require('./routes/routeBidder')
const property = require('./routes/routeProperty')
const Property = require('./models').Property
const BidProperty = require('./models').BidProperty
app.use(express.urlencoded({extended: true}))
app.set('view engine', 'ejs')
app.use('/static', express.static('assets'))
app.use('/bidder/static', express.static('assets'))
app.use('/properties/static', express.static('assets'))
app.use(session({secret: 'rahasiawoy', saveUninitialized: true, resave: true}))
app.use('/', bidder)
app.use('/', property)
app.get('/', (req, res) => {
let sess = req.session
let queries = req.query
console.log("ini sess di home", sess);
res.render('home/home', {queries, sess})
})
app.get('/properties/:propertyId/makeBid', (req,res)=>{
let sess = req.session
let queries = req.query
if (!req.session.user) {
res.redirect(`/properties?error=Please log in first!`)
return
}
BidProperty.findAll({
where: {
PropertyId: req.params.propertyId
},
order:[
['bid', 'DESC']
]
})
.then(properties => {
Property.findOne({
where: {
id: req.params.propertyId
}
})
.then(property => {
let obj = {}
obj.highest = properties[0]
obj.bid = property
res.render('properties/makeBid', {obj, sess, queries})
// res.send(obj)
})
})
})
app.post('/properties/:propertyId/makeBid', (req,res)=>{
Property.findOne({
where: {
id: req.params.propertyId
}
})
.then(property => {
BidProperty.findAll({
where: {
PropertyId: req.params.propertyId
},
order: [
['bid', 'DESC']
]
})
.then(properties => {
if(req.body.bid <= property.startingPrice){
res.redirect(`/properties/${req.params.propertyId}/makeBid?error=Your bid have to be greater than starting price`)
} else if (properties.length !== 0 && req.body.bid <= properties[0].bid){
res.redirect(`/properties/${req.params.propertyId}/makeBid?error=Your bid have to be greater than highest bid`)
} else {
BidProperty.create({
PropertyId: req.params.propertyId,
SellerId: property.SellerId,
BidderId: req.session.user.id,
bid: req.body.bid,
status: 'Ongoing'
})
.then(()=> {
res.redirect(`/properties`)
})
}
})
})
})
app.listen(port, () => {
console.log(`listening to port ${port}`);
})
<file_sep>'use strict';
module.exports = (sequelize, DataTypes) => {
const Model = sequelize.Sequelize.Model
class Property extends Model {
setTimer(){
let today = new Date()
let timeLimit = new Date(this.timeLimit)
var delta = Math.abs(timeLimit - today) / 1000;
var days = Math.floor(delta / 86400);
delta -= days * 86400;
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
var seconds = delta % 60;
return `${days} Days: ${hours} Hours: ${minutes} Minutes Left`
}
}
Property.init({
latitude: DataTypes.STRING,
longitude: DataTypes.STRING,
startingPrice: DataTypes.INTEGER,
description: DataTypes.STRING,
timeLimit: DataTypes.DATE,
imageUrl: DataTypes.STRING,
SellerId: DataTypes.INTEGER
}, {sequelize})
Property.associate = function(models) {
// associations can be defined here
Property.belongsToMany(models.Bidder, { through: models.BidProperty})
};
return Property;
};
<file_sep>const { Bidder, BidProperty, Property } = require('./models')
Property.findByPk(3)
.then(property => {
console.log(property.timeLeft())
})
<file_sep>'use strict';
module.exports = (sequelize, DataTypes) => {
const Model = sequelize.Sequelize.Model
class BidProperty extends Model {
static findHighestBid(propertyId) {
return BidProperty.findAll({
where: {
PropertyId: propertyId
},
order: [
['bid', 'DESC']
]
})
.then(bids => {
return bids[0]
})
}
// static updateAllBidStatus() {
// return BidProperty
// .findAll()
// .then(bidProperties => {
// })
// }
}
BidProperty.init({
PropertyId: DataTypes.INTEGER,
SellerId: DataTypes.INTEGER,
BidderId: DataTypes.INTEGER,
bid: DataTypes.INTEGER,
status: DataTypes.STRING
}, {sequelize})
BidProperty.associate = function(models) {
// associations can be defined here
BidProperty.belongsTo(models.Bidder)
BidProperty.belongsTo(models.Property)
};
return BidProperty;
};
<file_sep># lelangproperti.github.io<file_sep>'use strict';
module.exports = (sequelize, DataTypes) => {
const Model = sequelize.Sequelize.Model
// const generateHash = require('../helpers/generateHash')
const bcrypt = require('bcrypt')
class Bidder extends Model {}
Bidder.init({
name: {
type: DataTypes.STRING,
validate: {
mustNotBeNull() {
if (this.name.length < 1) throw new Error("Name must not be empty")
}
}
},
email: {
type: DataTypes.STRING,
validate: {
mustNotBeNull() {
if (this.email.length < 1) throw new Error("Email address must not be empty!")
},
mustBeUnique() {
return Bidder
.findOne({
where: {
email: this.email
}
})
.then(row => {
console.log(row);
if (row) throw new Error("Email address already exists!")
})
}
}
},
phone: {
type: DataTypes.STRING,
validate: {
mustNotBeNull() {
if (this.phone.length < 1) throw new Error("Phone number must not be empty")
},
isNumeric: {
args: true,
msg: 'Invalid phone number'
}
}
},
password: {
type: DataTypes.STRING,
validate: {
mustNotBeNull() {
if (this.password.length < 1) throw new Error("Password must not be empty")
}
}
}
}, {
hooks: {
beforeCreate(bidder, options) {
let hash = bcrypt.hashSync(bidder.password, 5)
bidder.password = hash
}
},
sequelize
})
Bidder.associate = function (models) {
// associations can be defined here
Bidder.belongsToMany(models.Property, { through: models.BidProperty })
};
return Bidder;
};<file_sep>const { Bidder, BidProperty, Property } = require('../models')
class ControllerProperty {
static showAllProperties(req, res) {
let sess = req.session
let queries = req.query
Property
.findAll()
.then(properties => {
res.render('properties/properties', { properties, sess, queries })
})
.catch(err => res.redirect(`/properties?error=${err.message}`))
}
static showCreateForm(req, res) {
let sess = req.session
let queries = req.query
Property.findAll()
.then(properties => {
res.render('properties/createProperty', { properties, sess, queries })
})
.catch(err => res.redirect(`/properties/create?error=${err.message}`))
}
static create(req, res) {
Property.create({
latitude: req.body.latitude,
longitude: req.body.longitude,
startingPrice: req.body.startingPrice,
description: req.body.description,
timeLimit: req.body.timeLimit,
imageUrl: req.body.imageUrl,
SellerId: req.session.user.id
})
.then(() => {
res.redirect('/properties')
})
.catch(err => {
res.redirect(`/properties/create?error=${err.message}`)
})
}
static delete(req, res) {
let {profileId, propertyId} = req.params
Property.destroy({
where: {
id: propertyId
}
})
.then(() => {
res.redirect(`/bidder/profile/${profileId}`)
})
.catch(err => {
res.redirect(`/bidder/profile/${profileId}?error=${err.message}`)
})
}
}
module.exports = ControllerProperty
| 696bf3edfafa25549765aef077d85ad1cd11d06f | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | risanto/lelangproperti | ec23caf8a3f1870b68d788a29b8d9b3c85f8ca42 | 9b7bf487e732fc2888875b8a08cf30e566e1b555 |
refs/heads/master | <file_sep>#!/bin/bash
curl http://www.studierendenwerk-koblenz.de/api/speiseplan/speiseplan.xml -o /var/www/DatetimeMensa/dist/speiseplan.xml
<file_sep># Page with datetime and Uni-Koblenz Mensaplan

The plan is taken from `http://www.studierendenwerk-koblenz.de/api/speiseplan/speiseplan.xml`.
## Use as "new tab"-page in chrome
* Download an addon to change the new tab url, for example [New Tab Redirect](https://chrome.google.com/webstore/detail/new-tab-redirect/icpgjfneehieebagbmdbhnlpiopdcmna?hl=de)
* Change the url to point to `https://datetimemensa.cars10k.de`
* .. or host yourself
## Hosting manually
You need to:
1. host the assets
2. pull the `speiseplan.xml`
3. fix the links to the xml (see `index.html`)
### Host the assets
All you need is a static asset server, for example nginx or similiar. To host locally you could use something like the python http server:
```
# will start a local fileserver on port 8001
cd dist/
python -m http.server 8001
```
### Pull the plan
You can use the provided `pull_plan.sh` script to pull the `speiseplan.xml` file.
On my server i have setup a cronjob that runs every 30min between `9:00am` and `11:00am` because thats the timeframe where the plan usally gets updated.
### Fix the links
`src/index.html` contains a link to the xml that is beeing pulled (see the script tag at the bottom). If you want to host manually you should change that to match your server.
Recreate the optimized files after saving the url:
```
yarn install
yarn build
```
### Docker
```bash
docker build -t datetimemensa .
```
<file_sep>// Variables we need to display date & time
var calendarmonths = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
var weekdays = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];
var today = new Date;
/**
* UpdateTime()
*
* Takes the current date apart and sets the contents into their corresponding DOM elements.
*/
function updateTime() {
var date = new Date();
var minutes = date.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
document.querySelector('#hours').innerHTML = date.getHours();
document.querySelector('#minutes').innerHTML = minutes;
document.querySelector('#year').innerHTML = date.getUTCFullYear();
document.querySelector('#month').innerHTML = calendarmonths[date.getUTCMonth()];
document.querySelector('#weekday').innerHTML = weekdays[date.getUTCDay()];
document.querySelector('#day').innerHTML = date.getDate();
}
/**
* disableSubmitButton(btn)
*
* Submits the buttons form and disables itself. Also replaces the buttontext to match the current "loading" state
*
* @param {Object} btn - the Button that got clicked
*/
function disableSubmitButton(btn) {
btn.form.submit();
btn.disabled = true;
btn.innerHTML = 'Suche ...';
}
/**
* xhr(url, method, success)
*
* Executes a XMLHttpRequest of method +method+ to url +url+ and executes +success+ with the given response as param.
*
* @param {String} url - the URL to call
* @param {String} method - HTTP Method to use (GET/POST)
* @param {Function} success - callback function that gets executed on success
*/
function xhr(url, method, success) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
success(xhr.responseText);
}
}
// TODO handle errors!
}
/**
* buildMensaPlan(response_xml)
*
* Takes the xml of the mensa plan and builds the DOM elements to show it on the page.
*
* @param {String} response_xml - the xml response from the xhr call
*/
function buildMensaPlan(response_xml) {
var parser = new DOMParser();
var doc = parser.parseFromString(response_xml, 'text/xml');
var dates = doc.getElementsByTagName('Datum');
var dates_array = [].slice.call(dates); // convert HTMLCollection to Array
var weekday = today.getUTCDay();
if (weekday === 0 || weekday === 6) {
// its the weekend, show the plan for the next week already
dates_array = dates_array.slice(5, 10); // take days 5 - 10
} else {
dates_array = dates_array.slice(0, 5); // only take first 5 days
}
for (var i = 0; i < dates_array.length; i++) {
buildMensaDay(dates_array[i]);
}
document.querySelector("#start_date").innerHTML = dates_array[0].innerHTML.substring(0, 10);
document.querySelector("#end_date").innerHTML = dates_array[dates_array.length - 1].innerHTML.substring(0, 10);
}
/**
* buildMensaDay(day)
*
* Builds a single mensa day with a given +day+ object
*
* @param {Object} day - on day element from the xml
*/
function buildMensaDay(day) {
// parse menus
var menu1 = day.getElementsByTagName('menu1')[0]; // "Menü 1"
var menuv = day.getElementsByTagName('menuv')[0]; // "Vegetarisch"
var menuvegan = day.getElementsByTagName('menuvegan')[0]; // "Vegan"
var menue = day.getElementsByTagName('menue')[0]; // "Extratheke"
var menud = day.getElementsByTagName('menud')[0]; // "Vital"
var menub = day.getElementsByTagName('menub')[0]; // "Bistro"
var menua = day.getElementsByTagName('menua')[0]; // "Abendmensa"
// parse Zusätze
var zusatz1 = day.getElementsByTagName('zusatz1')[0]; // "Menü 1"
var zusatzv = day.getElementsByTagName('zusatzv')[0]; // "Vegetarisch"
var zusatzvegan = day.getElementsByTagName('zusatzvegan')[0]; // "Vegan"
var zusatze = day.getElementsByTagName('zusatze')[0]; // "Extratheke"
var zusatzd = day.getElementsByTagName('zusatzd')[0]; // "Vital"
var zusatzb = day.getElementsByTagName('zusatzb')[0]; // "Bistro"
var zusatza = day.getElementsByTagName('zusatza')[0]; // "Abendmensa"
var datestring = day.innerHTML.substring(0, 10); // date as string like "2017-01-03"
// parse date
var miliseconds = Date.parse(datestring);
var seconds = miliseconds / 1000;
var date = new Date(0); // 1970.01.01
date.setUTCSeconds(seconds);
var day_weekday = date.getDay();
// set text
setMenuText("#menu1_" + day_weekday, menu1, zusatz1);
setMenuText("#menuv_" + day_weekday, menuv, zusatzv);
setMenuText("#menuvegan_" + day_weekday, menuvegan, zusatzvegan);
setMenuText("#menue_" + day_weekday, menue, zusatze);
setMenuText("#menud_" + day_weekday, menud, zusatzd);
setMenuText("#menub_" + day_weekday, menub, zusatzb);
setMenuText("#menua_" + day_weekday, menua, zusatza);
// append extra class if date is today, used for different font color
if (datesEqual(today, date)) {
document.querySelector("#weekday_" + day_weekday).className += " white";
document.querySelector("#menu1_" + day_weekday).className += " white";
document.querySelector("#menuv_" + day_weekday).className += " white";
document.querySelector("#menuvegan_" + day_weekday).className += " white";
document.querySelector("#menue_" + day_weekday).className += " white";
document.querySelector("#menud_" + day_weekday).className += " white";
document.querySelector("#menub_" + day_weekday).className += " white";
document.querySelector("#menua_" + day_weekday).className += " white";
}
}
/**
* setMenuText(selector, menu, zusatz)
*
* Set +menu+ as content of +selector+
* Set +zusatz+ as title of +selector+
*
* @param {String} selector
* @param {Object} menu
* @param {Object} zusatz
*/
function setMenuText(selector, menu, zusatz) {
var element = document.querySelector(selector);
element.innerHTML = parseMensaMenu(menu, zusatz);
if (zusatz !== null && zusatz !== undefined && zusatz.textContent !== undefined && zusatz.textContent.length !== 0) {
element.setAttribute('title', 'Zusätze: ' + fixCommas(zusatz.textContent));
}
}
/**
* parseMensaMenu(food_text_node, zusatz_text_node)
*
* Returns the text from the food text node, minus the annoying parenthesis with the "zusatze".
*
* @param {Object} food_text_node - Whats on the menu?
* @param {Object} zusatz_text_node - Zusaetze for the menu
* @return {String} - The actual menu string
*/
function parseMensaMenu(food_text_node, zusatz_text_node) {
if (food_text_node !== undefined && food_text_node.textContent !== undefined) {
var text_node_content = food_text_node.textContent;
if (zusatz_text_node !== undefined && zusatz_text_node.textContent !== undefined) {
var zusatz_text_content = zusatz_text_node.textContent;
var zusaetze = zusatz_text_content.split(',');
var parenthesises = text_node_content.match(/\(([a-zA-Z]|\d|\s|,)*\)/g);
if (parenthesises !== null) {
// loop all found parenthesises
for (var i = 0; i < parenthesises.length; i++) {
var parenthesis = parenthesises[i];
var content = parenthesis.replace(/(\(|\))/g, '').split(',');
var replace_content = true;
// loop the split content for each parenthesis
for (var j = 0; j < content.length; j++) {
var element = content[j];
if (zusaetze.indexOf(element) === -1) {
replace_content = false;
}
}
// remove parenthesis from text if all elements in parenthesis are included in "zusaetze"
if (replace_content === true) {
text_node_content = text_node_content.replace(parenthesis, '');
}
}
}
}
return fixCommas(text_node_content);
}
}
/**
* fixCommas
*
* Replaces commas without a trailing whitespace with correct ones
* Replaces commas with leading whitespace with correct ones
*
* @param {String} string
*/
function fixCommas(string) {
return string.replace(/,(?!\s)/g, ', ').replace(/\s,/g, ',');
}
/**
* datesEqual(date1, date2)
*
* Checks if two given dates are equal based on year, month and day. FU javascript!
*
* @param {Date} date1 - the first date
* @param {Date} date2 - the second date
* @return {Boolean} true if equal
*/
function datesEqual(date1, date2) {
return (date1.getUTCFullYear() === date2.getUTCFullYear()) &&
(date1.getUTCMonth() === date2.getUTCMonth())
&& (date1.getDate() === date2.getDate())
}
<file_sep>FROM node:11.15-slim AS builder
WORKDIR /usr/src/app
COPY package.json .
COPY yarn.lock .
RUN yarn install
COPY . .
RUN yarn build
FROM nginx:1.17.6-alpine
COPY --from=builder /usr/src/app/dist /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY server.conf /etc/nginx/conf.d/
| 7069101a446b29ca488b399926706a4baa6c68c0 | [
"Markdown",
"JavaScript",
"Dockerfile",
"Shell"
] | 4 | Shell | cars10/datetime_mensa | 648c4f1261bd82f6e460828c7d1fc101449c4429 | 97405cd59966c3ff627ef0c5369b7f7dff96db1c |
refs/heads/master | <repo_name>kyn9x/evade<file_sep>/MoonWalkEvade/EvadeSpells/EvadeSpellManager.cs
using System.Collections.Generic;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using MoonWalkEvade.Utils;
using SharpDX;
namespace MoonWalkEvade.EvadeSpells
{
public static class EvadeSpellManager
{
public static bool ProcessFlash(Evading.MoonWalkEvade evade)
{
var castPos = GetBlinkCastPos(evade, Player.Instance.ServerPosition.To2D(), 425);
var slot = GetFlashSpellSlot();
if (!castPos.IsZero && slot != SpellSlot.Unknown && Player.Instance.Spellbook.GetSpell(slot).IsReady)
{
Player.Instance.Spellbook.CastSpell(slot, castPos.To3D());
return true;
}
return false;
}
public static SpellSlot GetFlashSpellSlot()
{
return Player.Instance.GetSpellSlotFromName("summonerflash");
}
public static Vector2 GetBlinkCastPos(Evading.MoonWalkEvade moonWalkEvade, Vector2 center, float maxRange)
{
var polygons = moonWalkEvade.ClippedPolygons.Where(p => p.IsInside(center)).ToArray();
var segments = new List<Vector2[]>();
foreach (var pol in polygons)
{
for (var i = 0; i < pol.Points.Count; i++)
{
var start = pol.Points[i];
var end = i == pol.Points.Count - 1 ? pol.Points[0] : pol.Points[i + 1];
var intersections =
Utils.Utils.GetLineCircleIntersectionPoints(center, maxRange, start, end)
.Where(p => p.IsInLineSegment(start, end))
.ToList();
if (intersections.Count == 0)
{
if (start.Distance(center, true) < maxRange.Pow() &&
end.Distance(center, true) < maxRange.Pow())
{
intersections = new[] { start, end }.ToList();
}
else
{
continue;
}
}
else if (intersections.Count == 1)
{
intersections.Add(center.Distance(start, true) > center.Distance(end, true)
? end
: start);
}
segments.Add(intersections.ToArray());
}
}
if (!segments.Any())
{
return Vector2.Zero;
}
const int maxdist = 2000;
const int division = 30;
var points = new List<Vector2>();
foreach (var segment in segments)
{
var dist = segment[0].Distance(segment[1]);
if (dist > maxdist)
{
segment[0] = segment[0].Extend(segment[1], dist / 2 - maxdist / 2f);
segment[1] = segment[1].Extend(segment[1], dist / 2 - maxdist / 2f);
dist = maxdist;
}
var step = maxdist / division;
var count = dist / step;
for (var i = 0; i < count; i++)
{
var point = segment[0].Extend(segment[1], i * step);
if (!Extensions.IsWall(point))
{
points.Add(point);
}
}
}
if (!points.Any())
{
return Vector2.Zero;
}
var evadePoint =
points.Where
(x => moonWalkEvade.IsPointSafe(x) && !Utils.Utils.IsWall(x)).OrderBy(x => x.Distance(Game.CursorPos)).
FirstOrDefault();
return evadePoint;
}
public static bool TryEvadeSpell(Evading.MoonWalkEvade.EvadeResult evadeResult,
Evading.MoonWalkEvade moonWalkEvadeInstance)
{
IEnumerable<EvadeSpellData> evadeSpells = EvadeMenu.MenuEvadeSpells.Where(evadeSpell =>
EvadeMenu.SpellMenu[evadeSpell.SpellName + "/enable"].Cast<CheckBox>().CurrentValue);
foreach (EvadeSpellData evadeSpell in evadeSpells.OrderBy(x =>
x.SpellName.ToLower().Contains("flash")).ThenBy(x => x.DangerValue))
{
int dangerValue =
EvadeMenu.MenuEvadeSpells.First(x => x.SpellName == evadeSpell.SpellName).DangerValue;
if (moonWalkEvadeInstance.GetDangerValue() < dangerValue)
continue;
if (evadeSpell.SpellName.ToLower().Contains("flash"))
{
return ProcessFlash(moonWalkEvadeInstance);
}
//dash
if (evadeSpell.Range != 0)
{
var evadePos = GetBlinkCastPos(moonWalkEvadeInstance, Player.Instance.Position.To2D(), evadeSpell.Range);
float castTime = evadeSpell.Delay;
if (evadeResult.TimeAvailable >= castTime && !evadePos.IsZero && moonWalkEvadeInstance.IsPointSafe(evadePos))
{
CastEvadeSpell(evadeSpell, evadePos);
return true;
}
}
//speed buff (spell or item)
if (evadeSpell.EvadeType == EvadeType.MovementSpeedBuff)
{
var playerPos = Player.Instance.Position.To2D();
float speed = Player.Instance.MoveSpeed;
speed += speed * evadeSpell.speedArray[Player.Instance.Spellbook.GetSpell(evadeSpell.Slot).Level - 1] / 100;
float maxTime = evadeResult.TimeAvailable - evadeSpell.Delay;
float maxTravelDist = speed * (maxTime / 1000);
var evadePoints = moonWalkEvadeInstance.GetEvadePoints(playerPos, maxTravelDist);
var evadePoint = evadePoints.OrderBy(x => !x.IsUnderTurret()).ThenBy(p => p.Distance(Game.CursorPos)).FirstOrDefault();
if (evadePoint != default(Vector2))
{
CastEvadeSpell(evadeSpell, evadeSpell.isItem ? Vector2.Zero : evadePoint);
return true;
}
}
//items
if (evadeSpell.isItem && evadeSpell.EvadeType != EvadeType.MovementSpeedBuff)
{
if (evadeResult.TimeAvailable >= evadeSpell.Delay)
CastEvadeSpell(evadeSpell, Vector2.Zero);
return true;
}
}
return false;
}
private static void CastEvadeSpell(EvadeSpellData evadeSpell, Vector2 evadePos)
{
bool isItem = evadePos.IsZero;
if (isItem)
{
Item.UseItem(evadeSpell.itemID);
return;
}
switch (evadeSpell.CastType)
{
case CastType.Position:
if (!evadeSpell.isReversed)
Player.Instance.Spellbook.CastSpell(evadeSpell.Slot, evadePos.To3D());
else
Player.Instance.Spellbook.CastSpell(evadeSpell.Slot,
evadePos.Extend(Player.Instance, evadePos.Distance(Player.Instance) + evadeSpell.Range).To3D());
break;
case CastType.Self:
Player.Instance.Spellbook.CastSpell(evadeSpell.Slot, Player.Instance);
break;
}
}
}
}<file_sep>/MoonWalkEvade/Evading/Collision.cs
using System;
using System.Collections.Generic;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using MoonWalkEvade.Skillshots.SkillshotTypes;
using MoonWalkEvade.Utils;
using SharpDX;
namespace MoonWalkEvade.Evading
{
internal static class Collision
{
private static Vector2 WindWallStartPosition = Vector2.Zero;
private static int WallCastTick;
public static void Init()
{
Obj_AI_Base.OnProcessSpellCast += (sender, args) =>
{
if (args.SData.Name == "YasuoWMovingWall" && sender.IsAlly)
{
WindWallStartPosition = sender.Position.To2D();
WallCastTick = Environment.TickCount;
}
};
}
static Geometry.Polygon GetDetailedPolygon(this Geometry.Polygon.Rectangle p)
{
Geometry.Polygon detailedRectangle = new Geometry.Polygon();
for (int i = 0; i < p.Points.Count; i += 2)
{
var point = p.Points[i];
var nextPoint = i == p.Points.Count - 1 ? p.Points[0] : p.Points[i + 1];
detailedRectangle.Add(nextPoint);
for (float scaling = 1; scaling >= 0; scaling -= 0.1f)
{
var detailedPoint = point + (nextPoint - point) * scaling;
detailedRectangle.Add(detailedPoint);
}
detailedRectangle.Add(point);
}
return detailedRectangle;
}
static Vector2 PointOnCircle(float radius, float angleInDegrees, Vector2 origin)
{
float x = origin.X + (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180));
float y = origin.Y + (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180));
return new Vector2(x, y);
}
static List<Vector2> GetHitboxCirclePoints(Obj_AI_Base unit)
{
var list = new List<Vector2>();
for (int i = 0; i < 360; i++)
{
list.Add(PointOnCircle(unit.BoundingRadius, i, unit.Position.To2D()));
}
return list;
}
/// <summary>
/// In case minions die after the volley passed through, still remember there was a collision before
/// </summary>
static List<Vector2> LastMinionPosArray = new List<Vector2>();
private static int LastMinionPosArrayTick;
/// <summary>
/// + minion hitbox
/// </summary>
public static Vector2[] GetCollisionPoints(this AsheW skillshot)
{
var collisions = new List<Vector2>();
if (Environment.TickCount - LastMinionPosArrayTick < 1000)
collisions.AddRange(LastMinionPosArray);
Vector2[] edges = skillshot.GetEdgePoints();
Vector2 rightEdge = edges[0];
Vector2 leftEdge = edges[1];
var triangle = new Geometry.Polygon();
triangle.Points.AddRange(new List<Vector2> { skillshot.RealStartPosition.To2D(), rightEdge, leftEdge});
if (EvadeMenu.CollisionMenu["minion"].Cast<CheckBox>().CurrentValue)
{
foreach (var minion in
EntityManager.MinionsAndMonsters.AlliedMinions.Where(x => !x.IsDead && x.IsValid && x.Health >= 100 &&
x.Distance(skillshot.RealStartPosition) < skillshot.OwnSpellData.Range))
{
if (GetHitboxCirclePoints(minion).Any(x => triangle.IsInside(x)))
{
LastMinionPosArray.Add(minion.Position.To2D());
LastMinionPosArrayTick = Environment.TickCount;
collisions.Add(minion.Position.To2D());
}
}
}
if (EvadeMenu.CollisionMenu["yasuoWall"].Cast<CheckBox>().CurrentValue && skillshot.Missile != null)
{
GameObject wall = null;
foreach (var gameObject in ObjectManager.Get<GameObject>().
Where(gameObject => gameObject.IsValid && System.Text.RegularExpressions.Regex.IsMatch(
gameObject.Name, "_w_windwall.\\.troy", System.Text.RegularExpressions.RegexOptions.IgnoreCase)))
{
wall = gameObject;
}
if (wall != null)
{
var level = wall.Name.Substring(wall.Name.Length - 6, 1);
var wallWidth = 300 + 50 * Convert.ToInt32(level);
var wallDirection = (wall.Position.To2D() - WindWallStartPosition).Normalized().Perpendicular();
var wallStart = wall.Position.To2D() + wallWidth / 2f * wallDirection;
var wallEnd = wallStart - wallWidth * wallDirection;
var wallPolygon = new Geometry.Polygon.Rectangle(wallStart, wallEnd, 75).GetDetailedPolygon();
collisions.AddRange(wallPolygon.Points.Where(wallPoint => triangle.IsInside(wallPoint)));
}
}
return collisions.ToArray();
}
public static Vector2 GetCollisionPoint(this LinearSkillshot skillshot)
{
if (!skillshot.OwnSpellData.MinionCollision || skillshot.Missile == null)
return Vector2.Zero;
var collisions = new List<Vector2>();
var currentSpellPos = skillshot.GetPosition().To2D();
var spellEndPos = skillshot.EndPosition;
var rect = new Geometry.Polygon.Rectangle(currentSpellPos, spellEndPos.To2D(), skillshot.OwnSpellData.Radius*2);
if (EvadeMenu.CollisionMenu["minion"].Cast<CheckBox>().CurrentValue)
{
bool useProj = EvadeMenu.CollisionMenu["useProj"].Cast<CheckBox>().CurrentValue;
foreach (var minion in
EntityManager.MinionsAndMonsters.AlliedMinions.Where(x => !x.IsDead && x.IsValid && x.Health >= 200 &&
x.Distance(skillshot.StartPosition) < skillshot.OwnSpellData.Range))
{
if (rect.IsInside(minion) && !useProj)
collisions.Add(minion.Position.To2D());
else if (useProj)
{
var proj = minion.Position.To2D()
.ProjectOn(skillshot.StartPosition.To2D(), skillshot.EndPosition.To2D());
if (proj.IsOnSegment && proj.SegmentPoint.Distance(minion) <= skillshot.OwnSpellData.Radius)
collisions.Add(proj.SegmentPoint);
}
}
}
if (EvadeMenu.CollisionMenu["yasuoWall"].Cast<CheckBox>().CurrentValue && skillshot.Missile != null)
{
GameObject wall = null;
foreach (var gameObject in ObjectManager.Get<GameObject>().
Where(gameObject => gameObject.IsValid && System.Text.RegularExpressions.Regex.IsMatch(
gameObject.Name, "_w_windwall.\\.troy", System.Text.RegularExpressions.RegexOptions.IgnoreCase)))
{
wall = gameObject;
}
if (wall != null)
{
var level = wall.Name.Substring(wall.Name.Length - 6, 1);
var wallWidth = 300 + 50*Convert.ToInt32(level);
var wallDirection = (wall.Position.To2D() - WindWallStartPosition).Normalized().Perpendicular();
var wallStart = wall.Position.To2D() + wallWidth/2f*wallDirection;
var wallEnd = wallStart - wallWidth*wallDirection;
var wallPolygon = new Geometry.Polygon.Rectangle(wallStart, wallEnd, 75);
var intersections = wallPolygon.GetIntersectionPointsWithLineSegment(skillshot.GetPosition().To2D(),
skillshot.EndPosition.To2D());
if (intersections.Length > 0)
{
float wallDisappearTime = WallCastTick + 250 + 3750 - Environment.TickCount;
collisions.AddRange(intersections.Where(intersec =>
intersec.Distance(currentSpellPos)/skillshot.OwnSpellData.MissileSpeed*1000 <
wallDisappearTime).ToList());
}
}
}
var result = collisions.Count > 0 ? collisions.
OrderBy(c => c.Distance(currentSpellPos)).ToList().First() : Vector2.Zero;
return result;
}
}
}
<file_sep>/Moon Walk Evade/EvadeMenu.cs
using System.Collections.Generic;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using Moon_Walk_Evade.EvadeSpells;
using Moon_Walk_Evade.Skillshots;
namespace Moon_Walk_Evade
{
internal static class MenuExtension
{
public static void AddStringList(this Menu m, string uniqueId, string displayName, string[] values, int defaultValue)
{
var mode = m.Add(uniqueId, new Slider(displayName, defaultValue, 0, values.Length - 1));
mode.DisplayName = displayName + ": " + values[mode.CurrentValue];
mode.OnValueChange += delegate (ValueBase<int> sender, ValueBase<int>.ValueChangeArgs args)
{
sender.DisplayName = displayName + ": " + values[args.NewValue];
};
}
}
internal class EvadeMenu
{
public static Menu MainMenu { get; private set; }
public static Menu SkillshotMenu { get; private set; }
public static Menu SpellMenu { get; private set; }
public static Menu DrawMenu { get; private set; }
public static Menu HotkeysMenu { get; private set; }
public static Menu CollisionMenu { get; private set; }
public static readonly Dictionary<string, EvadeSkillshot> MenuSkillshots = new Dictionary<string, EvadeSkillshot>();
public static readonly List<EvadeSpellData> MenuEvadeSpells = new List<EvadeSpellData>();
public static void CreateMenu()
{
if (MainMenu != null)
{
return;
}
MainMenu = EloBuddy.SDK.Menu.MainMenu.AddMenu("MoonWalkEvade", "MoonWalkEvade");
// Set up main menu
MainMenu.AddGroupLabel("General Settings");
MainMenu.Add("evadeMode", new ComboBox("Evade Mode", 1, "Smooth - Moon Walk Style", "Fast - EvadePlus Style"));
MainMenu.AddSeparator();
MainMenu.Add("fowDetection", new CheckBox("Enable FOW Detection"));
MainMenu.Add("processSpellDetection", new CheckBox("Enable Fast Spell Detection"));
MainMenu.Add("limitDetectionRange", new CheckBox("Limit Spell Detection Range"));
MainMenu.Add("recalculatePosition", new CheckBox("Allow Recalculation Of Evade Position", false));
MainMenu.Add("moveToInitialPosition", new CheckBox("Move To Desired Position After Evade", false));
MainMenu.AddSeparator();
MainMenu.Add("minComfortDist", new Slider("Minimum Comfort Distance To Enemies", 550, 0, 1000));
MainMenu.AddLabel("If possible");
MainMenu.AddSeparator(10);
MainMenu.Add("ignoreComfort", new Slider("Ignore Comfort Distance For X Enemies", 1, 1, 5));
MainMenu.AddSeparator();
MainMenu.AddGroupLabel("Humanizer");
MainMenu.Add("skillshotActivationDelay", new Slider("Reaction Delay", 0, 0, 400));
MainMenu.AddSeparator();
MainMenu.Add("extraEvadeRange", new Slider("Extra Evade Range", 0, 0, 300));
MainMenu.Add("randomizeExtraEvadeRange", new CheckBox("Randomize Extra Range", false));
var heroes = Program.DeveloperMode ? EntityManager.Heroes.AllHeroes : EntityManager.Heroes.Enemies;
var heroNames = heroes.Select(obj => obj.ChampionName).ToArray();
var skillshots =
SkillshotDatabase.Database.Where(s => heroNames.Contains(s.OwnSpellData.ChampionName)).ToList();
skillshots.AddRange(
SkillshotDatabase.Database.Where(
s =>
s.OwnSpellData.ChampionName == "AllChampions" &&
heroes.Any(obj => obj.Spellbook.Spells.Select(c => c.Name).Contains(s.OwnSpellData.SpellName))));
var evadeSpells =
EvadeSpellDatabase.Spells.Where(s => Player.Instance.ChampionName.Contains(s.ChampionName)).ToList();
evadeSpells.AddRange(EvadeSpellDatabase.Spells.Where(s => s.ChampionName == "AllChampions"));
SkillshotMenu = MainMenu.AddSubMenu("Skillshots");
foreach (var c in skillshots)
{
var skillshotString = c.ToString().ToLower();
if (MenuSkillshots.ContainsKey(skillshotString))
continue;
MenuSkillshots.Add(skillshotString, c);
SkillshotMenu.AddGroupLabel(c.DisplayText);
SkillshotMenu.Add(skillshotString + "/enable", new CheckBox("Dodge", c.OwnSpellData.EnabledByDefault));
SkillshotMenu.Add(skillshotString + "/draw", new CheckBox("Draw"));
var dangerous = new CheckBox("Dangerous", c.OwnSpellData.IsDangerous);
dangerous.OnValueChange += delegate (ValueBase<bool> sender, ValueBase<bool>.ValueChangeArgs args)
{
GetSkillshot(sender.SerializationId).OwnSpellData.IsDangerous = args.NewValue;
};
SkillshotMenu.Add(skillshotString + "/dangerous", dangerous);
var dangerValue = new Slider("Danger Value", c.OwnSpellData.DangerValue, 1, 5);
dangerValue.OnValueChange += delegate (ValueBase<int> sender, ValueBase<int>.ValueChangeArgs args)
{
GetSkillshot(sender.SerializationId).OwnSpellData.DangerValue = args.NewValue;
};
SkillshotMenu.Add(skillshotString + "/dangervalue", dangerValue);
SkillshotMenu.AddSeparator();
}
// Set up spell menu
SpellMenu = MainMenu.AddSubMenu("Evading Spells");
foreach (var e in evadeSpells)
{
var evadeSpellString = e.SpellName;
if (MenuEvadeSpells.Any(x => x.SpellName == evadeSpellString))
continue;
MenuEvadeSpells.Add(e);
SpellMenu.AddGroupLabel(evadeSpellString);
SpellMenu.Add(evadeSpellString + "/enable", new CheckBox("Use " + (!e.isItem ? e.Slot.ToString() : "")));
var dangerValueSlider = new Slider("Danger Value", e.DangerValue, 1, 5);
dangerValueSlider.OnValueChange += delegate (ValueBase<int> sender, ValueBase<int>.ValueChangeArgs args)
{
MenuEvadeSpells.First(x =>
x.SpellName.Contains(sender.SerializationId.Split('/')[0])).DangerValue = args.NewValue;
};
SpellMenu.Add(evadeSpellString + "/dangervalue", dangerValueSlider);
SpellMenu.AddSeparator();
}
DrawMenu = MainMenu.AddSubMenu("Drawings");
DrawMenu.Add("disableAllDrawings", new CheckBox("Disable All Drawings", false));
DrawMenu.Add("drawEvadePoint", new CheckBox("Draw Evade Point"));
DrawMenu.Add("drawEvadeStatus", new CheckBox("Draw Evade Status"));
DrawMenu.Add("drawSkillshots", new CheckBox("Draw Skillshots"));
DrawMenu.Add("drawDangerPolygon", new CheckBox("Draw Danger Polygon"));
HotkeysMenu = MainMenu.AddSubMenu("KeyBinds");
HotkeysMenu.Add("enableEvade", new KeyBind("Enable Evade", true, KeyBind.BindTypes.PressToggle, 'M'));
HotkeysMenu.Add("dodgeOnlyDangerousH", new KeyBind("Dodge Only Dangerous (Hold)", false, KeyBind.BindTypes.HoldActive));
HotkeysMenu.Add("dodgeOnlyDangerousT", new KeyBind("Dodge Only Dangerous (Toggle)", false, KeyBind.BindTypes.PressToggle));
HotkeysMenu.AddSeparator();
HotkeysMenu.Add("debugMode", new KeyBind("Debug Mode", false, KeyBind.BindTypes.PressToggle));
HotkeysMenu.Add("debugModeIntervall", new Slider("Debug Skillshot Creation Intervall", 1000, 0, 5000));
HotkeysMenu.AddStringList("debugMissile", "Selected Skillshot", SkillshotDatabase.Database.Select(x => x.OwnSpellData.SpellName).ToArray(), 0);
HotkeysMenu.Add("isProjectile", new CheckBox("Is Projectile?"));
CollisionMenu = MainMenu.AddSubMenu("Collision");
CollisionMenu.Add("minion", new CheckBox("Attend Minion Collision"));
CollisionMenu.Add("yasuoWall", new CheckBox("Attend Yasuo Wall"));
CollisionMenu.Add("useProj", new CheckBox("Use Spell Projection", false));
}
private static EvadeSkillshot GetSkillshot(string s)
{
return MenuSkillshots[s.ToLower().Split('/')[0]];
}
public static bool IsSkillshotEnabled(EvadeSkillshot skillshot)
{
var valueBase = SkillshotMenu[skillshot + "/enable"];
return (valueBase != null && valueBase.Cast<CheckBox>().CurrentValue) ||
HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
}
public static bool IsSkillshotDrawingEnabled(EvadeSkillshot skillshot)
{
var valueBase = SkillshotMenu[skillshot + "/draw"];
return (valueBase != null && valueBase.Cast<CheckBox>().CurrentValue) ||
HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
}
}
}<file_sep>/Moon Walk Evade/Skillshots/SkillshotTypes/MultiCircleSkillshot.cs
using System;
using System.Collections.Generic;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using SharpDX;
using Color = System.Drawing.Color;
namespace Moon_Walk_Evade.Skillshots.SkillshotTypes
{
class MultiCircleSkillshot : EvadeSkillshot
{
public MultiCircleSkillshot()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
private float distance { get; set; }
public Vector3 StartPosition { get; private set; }
public Vector3 EndPosition { get; private set; }
public Vector2 Direction { get; private set; }
public MissileClient Missile => SpawnObject as MissileClient;
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new MultiCircleSkillshot { OwnSpellData = OwnSpellData };
return newInstance;
}
public override void OnCreate(GameObject obj)
{
if (Missile == null)
{
StartPosition = Caster.Position;
EndPosition = CastArgs.End.Distance(StartPosition) < 700
? StartPosition.Extend(CastArgs.End, 700).To3D()
: EndPosition;
distance = CastArgs.End.Distance(Caster.Position);
Direction = (CastArgs.End.To2D() - Caster.Position.To2D()).Normalized();
}
}
public override void OnCreateObject(GameObject obj)
{
var missile = obj as MissileClient;
if (SpawnObject == null && missile != null)
{
if (missile.SData.Name == OwnSpellData.ObjectCreationName && missile.SpellCaster.Index == Caster.Index)
{
// Force skillshot to be removed
//IsValid = false;
}
}
}
public override bool OnDeleteMissile(GameObject obj)
{
return false;
}
public override void OnDeleteObject(GameObject obj)
{
}
public override Vector3 GetPosition()
{
return EndPosition;
}
public override void OnTick()
{
if (Environment.TickCount > TimeDetected + OwnSpellData.Delay + 5500)
IsValid = false;
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
if (!EvadeMenu.DrawMenu["drawDangerPolygon"].Cast<CheckBox>().CurrentValue)
ToPolygon().Draw(Color.White);
}
public override Geometry.Polygon ToRealPolygon()
{
return ToPolygon();
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
var endPolygon = new Geometry.Polygon();
List<Geometry.Polygon.Circle> circles = new List<Geometry.Polygon.Circle>();
for (int i = -30; i <= 30; i+=10)
{
var rotatedDirection = Direction.Rotated(i*(float) Math.PI/180);
var c = new Geometry.Polygon.Circle(StartPosition + rotatedDirection.To3D()*distance,
OwnSpellData.Radius + extrawidth);
circles.Add(c);
}
//var circlePointsList = circles.Select(x => x.Points.Where(circlePoint =>
// circles.Where(otherCircle => otherCircle != x).All(y => !y.IsInside(circlePoint))
//)).ToList();
var circlePointsList = circles.Select(x => x.Points);
foreach (var circlePoints in circlePointsList)
{
foreach (var p in circlePoints)
{
endPolygon.Add(p);
}
}
return endPolygon;
}
public override int GetAvailableTime(Vector2 pos)
{
return OwnSpellData.Delay - (Environment.TickCount - TimeDetected);
}
public override bool IsFromFow()
{
return Missile != null && !Missile.SpellCaster.IsVisible;
}
}
}
<file_sep>/Moon Walk Evade/Skillshots/SpellData.cs
using EloBuddy;
using SharpDX;
namespace Moon_Walk_Evade.Skillshots
{
public class SpellData
{
public string DisplayName { get; set; }
public string SpellName { get; set; }
public string ObjectCreationName { get; set; }
public SpellSlot Slot { get; set; }
public int Delay { get; set; }
public int Range { get; set; }
public int Radius { get; set; }
public float MissileSpeed { get; set; }
public int DangerValue { get; set; }
public bool IsDangerous { get; set; }
public string ChampionName { get; set; }
public string ToggleParticleName { get; set; }
public bool AddHitbox { get; set; }
public int ExtraMissiles { get; set; }
public bool EnabledByDefault { get; set; } = true;
public bool MinionCollision { get; set; } = false;
public bool IsGlobal => Range > 10000;
public float ConeAngle { get; set; }
public int RingRadius { get; set; } = 0;
public bool IsVeigarE => RingRadius > 0;
public bool IsPerpendicular { get; set; }
public int SecondaryRadius { get; set; }
public Vector2 Direction { get; set; }
public bool ForbidCrossing { get; set; }
public SpellData()
{
AddHitbox = true;
}
}
}<file_sep>/Moon Walk Evade/Skillshots/EvadeSkillshot.cs
using EloBuddy;
using EloBuddy.SDK;
using SharpDX;
namespace Moon_Walk_Evade.Skillshots
{
public abstract class EvadeSkillshot
{
public SpellDetector SpellDetector { get; set; }
public GameObject SpawnObject { get; set; }
public Obj_AI_Base Caster { get; set; }
public GameObjectProcessSpellCastEventArgs CastArgs { get; set; }
public EloBuddy.SpellData SData { get; set; }
public SpellData OwnSpellData { get; set; }
public GameObjectTeam Team { get; set; }
public bool IsActive { get; set; }
public bool IsValid { get; set; }
public bool CastComplete { get; set; }
public int TimeDetected { get; set; }
public bool IsProcessSpellCast => Caster != null;
public string DisplayText => $"{OwnSpellData.ChampionName} {OwnSpellData.Slot} - {OwnSpellData.DisplayName}";
public abstract Vector3 GetPosition();
/// <summary>
/// with missile
/// </summary>
public abstract void OnCreateObject(GameObject obj);
/// <summary>
/// with missile
/// </summary>
public virtual void OnDeleteObject(GameObject obj) { }
/// <summary>
/// obj == null ? procspellcast / no missile : objectcreate / missile
/// </summary>
public virtual void OnCreate(GameObject obj) { }
public virtual bool OnDeleteMissile(GameObject obj)
{
return true;
}
public virtual void OnDispose() { }
public abstract void OnDraw();
public abstract void OnTick();
/// <summary>
/// without missile
/// </summary>
/// <param name="sender"></param>
public virtual void OnSpellDetection(Obj_AI_Base sender) { }
public abstract Geometry.Polygon ToRealPolygon();
public abstract Geometry.Polygon ToPolygon(float extrawidth = 0);
/// <summary>
/// For Veigar E
/// </summary>
public virtual Geometry.Polygon ToInnerPolygon(float extrawidth = 0)
{
return new Geometry.Polygon();
}
/// <summary>
/// For Veigar E
/// </summary>
public virtual Geometry.Polygon ToOuterPolygon(float extrawidth = 0)
{
return new Geometry.Polygon();
}
public abstract int GetAvailableTime(Vector2 pos);
public abstract bool IsFromFow();
public abstract EvadeSkillshot NewInstance(bool debug = false);
public override string ToString()
{
return $"{OwnSpellData.ChampionName}_{OwnSpellData.Slot}_{OwnSpellData.DisplayName}";
}
}
}<file_sep>/MoonWalkEvade/Program.cs
using EloBuddy.SDK.Events;
using MoonWalkEvade.Skillshots;
using MoonWalkEvade.Utils;
using Collision = MoonWalkEvade.Evading.Collision;
namespace MoonWalkEvade
{
internal static class Program
{
public static bool DeveloperMode = false;
private static SpellDetector _spellDetector;
private static void Main(string[] args)
{
Loading.OnLoadingComplete += delegate
{
_spellDetector = new SpellDetector(DeveloperMode ? DetectionTeam.AnyTeam : DetectionTeam.EnemyTeam);
new Evading.MoonWalkEvade(_spellDetector);
EvadeMenu.CreateMenu();
Collision.Init();
Debug.Init(ref _spellDetector);
};
}
}
}
<file_sep>/MoonWalkEvade/Skillshots/SkillshotTypes/YasuoQ.cs
using EloBuddy;
using MoonWalkEvade.Utils;
namespace MoonWalkEvade.Skillshots.SkillshotTypes
{
public class YasuoQ : LinearSkillshot
{
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new YasuoQ { OwnSpellData = OwnSpellData };
return newInstance;
}
public override void OnSpellDetection(Obj_AI_Base sender)
{
_startPos = Caster.ServerPosition;
_endPos = _startPos.ExtendVector3(CastArgs.End, -OwnSpellData.Range);
}
}
}
<file_sep>/MoonWalkEvade/Evading/MoonWalkEvade.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Rendering;
using MoonWalkEvade.EvadeSpells;
using MoonWalkEvade.Skillshots;
using MoonWalkEvade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace MoonWalkEvade.Evading
{
public class MoonWalkEvade
{
#region Properties
public int ServerTimeBuffer => 80 + 45;
public bool EvadeEnabled => EvadeMenu.HotkeysMenu["enableEvade"].Cast<KeyBind>().CurrentValue;
public bool DodgeDangerousOnly => EvadeMenu.HotkeysMenu["dodgeOnlyDangerousH"].Cast<KeyBind>().CurrentValue ||
EvadeMenu.HotkeysMenu["dodgeOnlyDangerousT"].Cast<KeyBind>().CurrentValue;
public int ExtraEvadeRange => EvadeMenu.MainMenu["extraEvadeRange"].Cast<Slider>().CurrentValue;
public bool RandomizeExtraEvadeRange => EvadeMenu.MainMenu["randomizeExtraEvadeRange"].Cast<CheckBox>().CurrentValue;
public bool AllowRecalculateEvade => EvadeMenu.MainMenu["recalculatePosition"].Cast<CheckBox>().CurrentValue;
public bool RestorePosition => EvadeMenu.MainMenu["moveToInitialPosition"].Cast<CheckBox>().CurrentValue;
public bool DisableDrawings => EvadeMenu.DrawMenu["disableAllDrawings"].Cast<CheckBox>().CurrentValue;
public bool DrawEvadePoint => EvadeMenu.DrawMenu["drawEvadePoint"].Cast<CheckBox>().CurrentValue;
public bool DrawEvadeStatus => EvadeMenu.DrawMenu["drawEvadeStatus"].Cast<CheckBox>().CurrentValue;
public bool DrawDangerPolygon => EvadeMenu.DrawMenu["drawDangerPolygon"].Cast<CheckBox>().CurrentValue;
public int IgnoreAt => EvadeMenu.MainMenu["ignoreComfort"].Cast<Slider>().CurrentValue;
public int MinComfortDistance => EvadeMenu.MainMenu["minComfortDist"].Cast<Slider>().CurrentValue;
public int IssueOrderTickLimit => 0;
#endregion
#region Vars
public SpellDetector SpellDetector { get; private set; }
public PathFinding PathFinding { get; private set; }
public EvadeSkillshot[] Skillshots { get; private set; }
public Geometry.Polygon[] Polygons { get; private set; }
public List<Geometry.Polygon> ClippedPolygons { get; private set; }
public Vector2 LastIssueOrderPos;
private readonly Dictionary<EvadeSkillshot, Geometry.Polygon> _skillshotPolygonCache;
private EvadeResult LastEvadeResult;
private Text StatusText;
private int EvadeIssurOrderTime;
#endregion
public MoonWalkEvade(SpellDetector detector)
{
Skillshots = new EvadeSkillshot[] { };
Polygons = new Geometry.Polygon[] { };
ClippedPolygons = new List<Geometry.Polygon>();
PathFinding = new PathFinding(this);
StatusText = new Text("MoonWalkEvade", new Font("Euphemia", 10F, FontStyle.Bold)); //Calisto MT
_skillshotPolygonCache = new Dictionary<EvadeSkillshot, Geometry.Polygon>();
SpellDetector = detector;
SpellDetector.OnUpdateSkillshots += OnUpdateSkillshots;
SpellDetector.OnSkillshotActivation += OnSkillshotActivation;
SpellDetector.OnSkillshotDetected += OnSkillshotDetected;
SpellDetector.OnSkillshotDeleted += OnSkillshotDeleted;
Player.OnIssueOrder += PlayerOnIssueOrder;
Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast;
Dash.OnDash += OnDash;
Game.OnTick += Ontick;
Drawing.OnDraw += OnDraw;
}
private void OnUpdateSkillshots(EvadeSkillshot skillshot, bool remove, bool isProcessSpell)
{
CacheSkillshots();
DoEvade();
}
private void OnSkillshotActivation(EvadeSkillshot skillshot)
{
CacheSkillshots();
DoEvade();
}
private void OnSkillshotDetected(EvadeSkillshot skillshot, bool isProcessSpell)
{
//TODO: update
if (skillshot.ToPolygon().IsInside(Player.Instance))
{
LastEvadeResult = null;
}
}
private void OnSkillshotDeleted(EvadeSkillshot skillshot)
{
if (RestorePosition && !SpellDetector.DetectedSkillshots.Any())
{
if (AutoPathing.IsPathing && Player.Instance.IsWalking())
{
var destination = AutoPathing.Destination;
AutoPathing.StopPath();
Player.IssueOrder(GameObjectOrder.MoveTo, destination.To3DWorld(), false);
}
else if (LastEvadeResult != null && Player.Instance.IsMovingTowards(LastEvadeResult.EvadePoint))
{
Player.IssueOrder(GameObjectOrder.MoveTo, LastIssueOrderPos.To3DWorld(), false);
}
}
}
private void Ontick(EventArgs args)
{
if (!Player.Instance.IsWalking() && LastEvadeResult != null)
{
//MoveTo(LastEvadeResult.WalkPoint);
}
DoEvade();
}
private void PlayerOnIssueOrder(Obj_AI_Base sender, PlayerIssueOrderEventArgs args)
{
if (!sender.IsMe)
{
return;
}
if (args.Order == GameObjectOrder.AttackUnit)
{
LastIssueOrderPos =
(Player.Instance.Distance(args.Target, true) >
Player.Instance.GetAutoAttackRange(args.Target as AttackableUnit).Pow()
? args.Target.Position
: Player.Instance.Position).To2D();
}
else
{
LastIssueOrderPos = (args.Target != null ? args.Target.Position : args.TargetPosition).To2D();
}
CacheSkillshots();
switch (args.Order)
{
case GameObjectOrder.Stop:
if (DoEvade(null, args))
{
args.Process = false;
}
break;
case GameObjectOrder.HoldPosition:
if (DoEvade(null, args))
{
args.Process = false;
}
break;
case GameObjectOrder.AttackUnit:
if (DoEvade(null, args))
{
args.Process = false;
}
break;
default:
if (DoEvade(Player.Instance.GetPath(LastIssueOrderPos.To3DWorld(), true), args))
{
args.Process = false;
}
break;
}
}
private void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (!sender.IsMe)
{
return;
}
if (args.SData.Name == "summonerflash")
{
LastEvadeResult = null;
}
}
private void OnDash(Obj_AI_Base sender, Dash.DashEventArgs dashEventArgs)
{
if (!sender.IsMe || LastEvadeResult == null)
{
return;
}
LastEvadeResult = null;
Player.IssueOrder(GameObjectOrder.MoveTo, LastIssueOrderPos.To3DWorld(), false);
}
private void OnDraw(EventArgs args)
{
if (DisableDrawings)
{
return;
}
if (DrawEvadePoint && LastEvadeResult != null)
{
if (LastEvadeResult.IsValid && LastEvadeResult.EnoughTime && !LastEvadeResult.Expired())
{
Circle.Draw(new ColorBGRA(255, 0, 0, 255), Player.Instance.BoundingRadius, 25, LastEvadeResult.WalkPoint);
}
}
if (DrawEvadeStatus)
{
StatusText.Color = EvadeEnabled ? Color.White : Color.Red;
if (DodgeDangerousOnly) StatusText.Color = Color.DarkOrange;
StatusText.TextValue = "MoonWalkEvade ";
StatusText.Position = Player.Instance.Position.WorldToScreen() - new Vector2(StatusText.Bounding.Width / 2f, -25);
StatusText.Draw();
}
if (DrawDangerPolygon)
{
foreach (var pol in Geometry.ClipPolygons(SpellDetector.ActiveSkillshots.Select(c => c.ToPolygon())).ToPolygons())
{
pol.DrawPolygon(Color.White, 3);
}
}
}
public void CacheSkillshots()
{
Skillshots =
(DodgeDangerousOnly
? SpellDetector.ActiveSkillshots.Where(c => c.OwnSpellData.IsDangerous)
: SpellDetector.ActiveSkillshots).ToArray();
_skillshotPolygonCache.Clear();
Polygons = Skillshots.Select(c =>
{
var pol = c.ToPolygon();
_skillshotPolygonCache.Add(c, pol);
return pol;
}).ToArray();
ClippedPolygons = Geometry.ClipPolygons(Polygons).ToPolygons();
}
public bool IsPointSafe(Vector2 point)
{
return !_skillshotPolygonCache.Any(c =>
{
if (c.Key.OwnSpellData.IsVeigarE)
{
return c.Key.ToInnerPolygon().IsOutside(point) && c.Key.ToOuterPolygon().IsInside(point);
}
return c.Value.IsInside(point);
});
}
public bool IsPathSafe(Vector2[] path)
{
return IsPathSafeEx(path);
}
public bool IsPathSafe(Vector3[] path)
{
return IsPathSafe(path.ToVector2());
}
public bool IsHeroInDanger(AIHeroClient hero = null)
{
hero = hero ?? Player.Instance;
bool indanger = !IsPointSafe(hero.ServerPosition.To2D());
return indanger;
}
public int GetTimeAvailable(AIHeroClient hero = null)
{
hero = hero ?? Player.Instance;
var skillshots = Skillshots.Where(c => _skillshotPolygonCache[c].IsInside(hero.Position)).ToArray();
if (!skillshots.Any())
{
return short.MaxValue;
}
var times =
skillshots.Select(c => c.GetAvailableTime(hero.ServerPosition.To2D()))
.Where(t => t > 0)
.OrderByDescending(t => t);
return times.Any() ? times.Last() : short.MaxValue;
}
public int GetDangerValue(AIHeroClient hero = null)
{
hero = hero ?? Player.Instance;
var skillshots = Skillshots.Where(c => _skillshotPolygonCache[c].IsInside(hero.Position)).ToArray();
if (!skillshots.Any())
return 0;
var values = skillshots.Select(c => c.OwnSpellData.DangerValue).OrderByDescending(t => t);
return values.Any() ? values.First() : 0;
}
float GetShortesTimeAvailiableInInsidePath(Vector2[] path, EvadeSkillshot spell)
{
List<Vector2> detailedPath = new List<Vector2>();
var first = path.FirstOrDefault();
var last = path.LastOrDefault();
float shortestTime = spell.GetAvailableTime(Player.Instance.Position.To2D());
shortestTime = Math.Max(0, shortestTime - (Game.Ping + ServerTimeBuffer));
if (first == default(Vector2) || last == default(Vector2) || first == last)
return shortestTime;
detailedPath.Add(first);
detailedPath.Add(last);
foreach (Vector2 pathPoint in detailedPath.Where(x => spell.ToPolygon().IsInside(x)))
{
float maxTime = spell.GetAvailableTime(pathPoint);
float time = Math.Max(0, maxTime - (Game.Ping + ServerTimeBuffer));
shortestTime = Math.Min(shortestTime, time);
}
return shortestTime;
}
public bool IsPathSafeEx(Vector2[] path, AIHeroClient hero = null)
{
hero = hero ?? Player.Instance;
path = new[] { hero.Position.To2D(), LastIssueOrderPos };
var pathStart = path[0];
var pathEnd = path[1];
foreach (var pair in _skillshotPolygonCache)
{
EvadeSkillshot skillshot = pair.Key;
var polygon = pair.Value;
Func<Vector2, bool> isInside = point =>
{
if (skillshot.OwnSpellData.IsVeigarE)
{
return skillshot.ToInnerPolygon().IsOutside(point) && skillshot.ToOuterPolygon().IsInside(point);
}
return polygon.IsInside(point);
};
var intersections =
polygon.GetIntersectionPointsWithLineSegment(hero.Position.To2D(), pathEnd);
if (intersections.Length == 0 && isInside(hero.Position.To2D()) && isInside(pathEnd))
{
var time2 = skillshot.GetAvailableTime(pathEnd);
if (hero.WalkingTime(hero.Position.To2D(), pathEnd) >= time2 - Game.Ping)
{
//Chat.Print(Game.Time + " path unsafe");
return false;
}
}
else if (intersections.Length == 0 && !isInside(pathStart) && !isInside(pathEnd))
continue; //safe path for now => next skillshot
if (intersections.Length == 1)
{
bool beingInside = isInside(pathStart);
if (beingInside)
{
float skillshotTime = skillshot.GetAvailableTime(intersections[0]);
skillshotTime = Math.Max(0, skillshotTime - (Game.Ping + ServerTimeBuffer));
bool enoughTime = hero.WalkingTime(hero.Position.To2D(), intersections[0]) < skillshotTime;
if (!enoughTime)
{
//Chat.Print(Game.Time + " path unsafe");
return false;
}
}
else //being outside
{
float walkTimeToEdge = hero.WalkingTime(hero.Position.To2D(), intersections[0]);
float skillshotTime = skillshot.GetAvailableTime(intersections[0]);
skillshotTime = Math.Max(0, skillshotTime - (Game.Ping + ServerTimeBuffer));
float time = skillshotTime - walkTimeToEdge;
if (time > -100)
{
//Chat.Print(Game.Time + " path unsafe");
return false;
}
}
}
else if (intersections.Length >= 2) //cross
{
if (skillshot.OwnSpellData.ForbidCrossing)
return false;
var firstDangerPoint = intersections.Last();
var crossPoint = intersections.First();
var walkTimeToDangerStart = hero.WalkingTime(hero.Position.To2D(), firstDangerPoint);
var walkTimeToDangerEnd = hero.WalkingTime(hero.Position.To2D(), crossPoint);
float maxTime1 = skillshot.GetAvailableTime(firstDangerPoint);
float time1 = Math.Max(0, maxTime1 - Game.Ping + ServerTimeBuffer);
float time2 = GetShortesTimeAvailiableInInsidePath(new[] { pathStart, crossPoint }, skillshot);
bool dangerStartUnsafe = time1 - walkTimeToDangerStart > 0;
bool dangerEndUnsafe = walkTimeToDangerEnd > time2;
if (dangerStartUnsafe && dangerEndUnsafe)
{
//Chat.Print(Game.Time + " path unsafe");
return false;
}
}
}
return true;
}
public bool IsPathSafeEx(Vector2 end, AIHeroClient hero = null)
{
hero = hero ?? Player.Instance;
return IsPathSafeEx(hero.GetPath(end.To3DWorld(), true).ToVector2(), hero);
}
public bool CheckPathCollision(Obj_AI_Base unit, Vector2 movePos)
{
var path = unit.GetPath(Player.Instance.Position, movePos.To3D());
if (path.Length > 0)
{
if (movePos.Distance(path[path.Length - 1].To2D()) > 5 || path.Length > 2)
{
return true;
}
}
return false;
}
public Vector2[] GetSmoothEvadePoints(Vector2 movePos)
{
int posChecked = 0;
int maxPosToCheck = 50;
int posRadius = 50;
int radiusIndex = 0;
Vector2 heroPoint = Player.Instance.Position.To2D();
List<Vector2> posTable = new List<Vector2>();
while (posChecked < maxPosToCheck)
{
radiusIndex++;
int curRadius = radiusIndex * (2 * posRadius);
int curCircleChecks = (int)Math.Ceiling((2 * Math.PI * curRadius) / (2 * (double)posRadius));
for (int i = 1; i < curCircleChecks; i++)
{
posChecked++;
var cRadians = (2 * Math.PI / (curCircleChecks - 1)) * i; //check decimals
var pos = new Vector2((float)Math.Floor(heroPoint.X + curRadius * Math.Cos(cRadians)), (float)Math.Floor(heroPoint.Y + curRadius * Math.Sin(cRadians)));
posTable.Add(pos);
}
}
return posTable.ToArray();
}
public Vector2[] GetEvadePoints(Vector2 from, float moveRadius)
{
var playerPos = Player.Instance.Position.To2D();
var mode = EvadeMenu.MainMenu["evadeMode"].Cast<ComboBox>().CurrentValue;
if (mode == 1)
{
var polygons = ClippedPolygons.Where(p => p.IsInside(from)).ToArray();
var segments = new List<Vector2[]>();
foreach (var pol in polygons)
{
for (var i = 0; i < pol.Points.Count; i++)
{
var start = pol.Points[i];
var end = i == pol.Points.Count - 1 ? pol.Points[0] : pol.Points[i + 1];
var intersections =
Utils.Utils.GetLineCircleIntersectionPoints(from, moveRadius, start, end)
.Where(p => p.IsInLineSegment(start, end))
.ToList();
if (intersections.Count == 0)
{
if (start.Distance(from, true) < moveRadius.Pow() &&
end.Distance(from, true) < moveRadius.Pow())
{
intersections = new[] { start, end }.ToList();
}
else
{
continue;
}
}
else if (intersections.Count == 1)
{
intersections.Add(from.Distance(start, true) > from.Distance(end, true) ? end : start);
}
segments.Add(intersections.ToArray());
}
}
if (!segments.Any()) //not enough time
{
return new Vector2[] { };
}
const int maxdist = 3000;
const int division = 10;
var points = new List<Vector2>();
foreach (var segment in segments)
{
var dist = segment[0].Distance(segment[1]);
if (dist > maxdist)
{
segment[0] = segment[0].Extend(segment[1], dist / 2 - maxdist / 2f);
segment[1] = segment[1].Extend(segment[1], dist / 2 - maxdist / 2f);
dist = maxdist;
}
var step = maxdist / division;
var count = dist / step;
for (var i = 0; i < count; i++)
{
var point = segment[0].Extend(segment[1], i * step);
if (!Utils.Utils.IsWall(point) && IsPathSafeEx(point) &&
Player.Instance.GetPath(point.To3DWorld(), true).Length <= 2)
{
points.Add(point);
}
}
}
var orderedPoints = points.Where(IsPointSafe).Where(
p => DoesntCrossVeigarE(p, playerPos)).Where(x => !Utils.Utils.IsWall(x));
return orderedPoints.ToArray();
}
var evadePoints = GetSmoothEvadePoints(playerPos).Where(IsPointSafe).Where(
p => DoesntCrossVeigarE(p, playerPos)).Where(x => !Utils.Utils.IsWall(x));
return evadePoints.ToArray();
}
private bool DoesntCrossVeigarE(Vector2 p, Vector2 playerPos)
{
var veigarSkill = _skillshotPolygonCache.Keys.FirstOrDefault(x => x.OwnSpellData.IsVeigarE);
if (veigarSkill == null)
return true;
var pol1 = veigarSkill.ToInnerPolygon();
var pol2 = veigarSkill.ToOuterPolygon();
var inters1 = pol1.GetIntersectionPointsWithLineSegment(playerPos, p);
var inters2 = pol2.GetIntersectionPointsWithLineSegment(playerPos, p);
if (inters1.Any())
{
var nearestInter = inters1.OrderBy(x => x.Distance(playerPos)).First();
if (pol2.Points.Any(x => x.Distance(playerPos) < nearestInter.Distance(playerPos)))
return false;//not the closest point
}
if (inters2.Any())
{
var nearestInter = inters2.OrderBy(x => x.Distance(playerPos)).First();
if (pol1.Points.Any(x => x.Distance(playerPos) < nearestInter.Distance(playerPos)))
return false;//not the closest point
}
return inters1.Length + inters2.Length < 2;
}
public Vector2 GetClosestEvadePoint(Vector2 from)
{
var polygons = ClippedPolygons.Where(p => p.IsInside(from)).ToArray();
var polPoints =
polygons.Select(pol => pol.ToDetailedPolygon())
.SelectMany(pol => pol.Points)
.OrderByDescending(p => p.Distance(from, true));
return !polPoints.Any() ? Vector2.Zero : polPoints.Last();
}
int GetHeroesNearby(Vector2 p)
{
return EntityManager.Heroes.Enemies.Count(x => x.Distance(p) < MinComfortDistance && !x.IsDead && x.IsEnemy);
}
public EvadeResult CalculateEvade(Vector2 anchor)
{
var playerPos = Player.Instance.ServerPosition.To2D();
var maxTime = GetTimeAvailable();
var time = Math.Max(0, maxTime - (Game.Ping + ServerTimeBuffer));
var moveRadius = time / 1000F * Player.Instance.MoveSpeed;
var points = GetEvadePoints(playerPos, moveRadius);
if (!points.Any())
{
return new EvadeResult(this, GetClosestEvadePoint(playerPos), anchor, maxTime, time, true);
}
bool any = points.Any(x => GetHeroesNearby(x) > IgnoreAt);
var evadePoint =
any ?
points.Where(x => GetHeroesNearby(x) == 0).OrderBy(x => IsPathSafeEx(x)).
ThenBy(p => !p.IsUnderTurret()).ThenBy(p => p.Distance(Game.CursorPos)).FirstOrDefault()
:
points.OrderBy(x => IsPathSafeEx(x)).ThenBy(p => !p.IsUnderTurret()).ThenBy(p => p.Distance(Game.CursorPos))
.FirstOrDefault();
return new EvadeResult(this, evadePoint, anchor, maxTime, time,
!IsHeroInDanger() || GetTimeUnitlOutOfDangerArea(evadePoint) < time);
}
public bool IsHeroPathSafe(Vector3[] desiredPath, AIHeroClient hero = null)
{
hero = hero ?? Player.Instance;
var path = (desiredPath ?? hero.RealPath()).ToVector2();
return IsPathSafeEx(path, hero);
}
public bool MoveTo(Vector2 point, bool limit = true)
{
if (limit && EvadeIssurOrderTime + IssueOrderTickLimit >= Environment.TickCount)
{
return false;
}
EvadeIssurOrderTime = Environment.TickCount;
Player.IssueOrder(GameObjectOrder.MoveTo, point.To3DWorld(), false);
return true;
}
public bool MoveTo(Vector3 point, bool limit = true)
{
return MoveTo(point.To2D(), limit);
}
int GetTimeUnitlOutOfDangerArea(Vector2 evadePoint)
{
IEnumerable<Vector2> inters =
(from polygon in SpellDetector.ActiveSkillshots.Select(x => x.ToRealPolygon())
let intersections = polygon.GetIntersectionPointsWithLineSegment(Player.Instance.Position.To2D(), evadePoint)
.OrderBy(x => x.Distance(Player.Instance))
where intersections.Any()
select intersections.Last()).ToList();
if (inters.Any())
{
var farest = inters.OrderBy(x => x.Distance(Player.Instance)).Last();
return Player.Instance.WalkingTime(farest);
}
return int.MaxValue;
}
Vector2 GetExtendedEvade(Vector2 p)
{
float minExtension = 225;
float maxExtension = 300;
for (float i = minExtension; i <= maxExtension; i++)
{
var newP = Player.Instance.Position.Extend(p, Player.Instance.Distance(p) + i);
if (IsPointSafe(newP) && IsPathSafe(new[] { Player.Instance.Position.To2D(), newP }))
return newP;
}
return p;
}
public bool DoEvade(Vector3[] desiredPath = null, PlayerIssueOrderEventArgs args = null)
{
#region pre
if (!EvadeEnabled || Player.Instance.IsDead || Player.Instance.IsDashing())
{
LastEvadeResult = null;
AutoPathing.StopPath();
return false;
}
var hero = Player.Instance;
if (args != null && args.Order == GameObjectOrder.AttackUnit)
{
if (!hero.IsInAutoAttackRange((AttackableUnit)args.Target))
{
desiredPath = hero.GetPath(args.Target.Position, true);
}
}
#endregion pre
#region execute evade point movement
if (LastEvadeResult != null)
{
var isPathSafe = IsHeroPathSafe(desiredPath);
if (!IsHeroInDanger(hero) && isPathSafe)
{
LastEvadeResult = null;
AutoPathing.StopPath();
return false;
}
if (!hero.IsMovingTowards(LastEvadeResult.WalkPoint) || !isPathSafe)
{
AutoPathing.StopPath();
MoveTo(GetExtendedEvade(LastEvadeResult.WalkPoint.To2D()), false);
}
return true;
}
#endregion execute evade point movement
#region check evade
if (IsHeroInDanger(hero))
{
var evade = CalculateEvade(LastIssueOrderPos);
if (evade.IsValid && evade.EnoughTime)
{
if (LastEvadeResult == null ||
(LastEvadeResult.EvadePoint.Distance(evade.EvadePoint, true) > 500.Pow() &&
AllowRecalculateEvade))
{
LastEvadeResult = evade;
}
}
else if (!evade.EnoughTime)
{
return EvadeSpellManager.TryEvadeSpell(evade, this);
}
}
else if (!IsPathSafe(hero.RealPath()) || (desiredPath != null && !IsPathSafe(desiredPath)))
{
var evade = CalculateEvade(LastIssueOrderPos);
if (evade.IsValid)
{
LastEvadeResult = evade;
return true;
}
//LastEvadeResult = null;
return desiredPath != null;
}
#endregion check evade
else
{
AutoPathing.StopPath();
LastEvadeResult = null;
}
return false;
}
public class EvadeResult
{
private MoonWalkEvade _moonWalkEvade;
private int ExtraRange { get; set; }
public int Time { get; set; }
public Vector2 PlayerPos { get; set; }
public Vector2 EvadePoint { get; set; }
public Vector2 AnchorPoint { get; set; }
public int TimeAvailable { get; set; }
public int TotalTimeAvailable { get; set; }
public bool EnoughTime { get; set; }
public bool OutsideEvade => Environment.TickCount - OutsideEvadeTime <= 500;
public int OutsideEvadeTime { get; set; }
public bool IsValid => !EvadePoint.IsZero;
public Vector3 WalkPoint
{
get
{
var walkPoint = EvadePoint.Extend(PlayerPos, -80);
var newPoint = walkPoint.Extend(PlayerPos, -ExtraRange);
if (_moonWalkEvade.IsPointSafe(newPoint))
{
return newPoint.To3DWorld();
}
return walkPoint.To3DWorld();
}
}
public EvadeResult(MoonWalkEvade moonWalkEvade, Vector2 evadePoint, Vector2 anchorPoint, int totalTimeAvailable,
int timeAvailable,
bool enoughTime)
{
_moonWalkEvade = moonWalkEvade;
PlayerPos = Player.Instance.Position.To2D();
Time = Environment.TickCount;
EvadePoint = evadePoint;
AnchorPoint = anchorPoint;
TotalTimeAvailable = totalTimeAvailable;
TimeAvailable = timeAvailable;
EnoughTime = enoughTime;
// extra _moonWalkEvade range
if (_moonWalkEvade.ExtraEvadeRange > 0)
{
ExtraRange = (_moonWalkEvade.RandomizeExtraEvadeRange
? Utils.Utils.Random.Next(_moonWalkEvade.ExtraEvadeRange / 3, _moonWalkEvade.ExtraEvadeRange)
: _moonWalkEvade.ExtraEvadeRange);
}
}
public bool Expired(int time = 4000)
{
return Elapsed(time);
}
public bool Elapsed(int time)
{
return Elapsed() > time;
}
public int Elapsed()
{
return Environment.TickCount - Time;
}
}
}
}<file_sep>/MoonWalkEvade/Skillshots/SkillshotTypes/SummonerMark.cs
using System;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using MoonWalkEvade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace MoonWalkEvade.Skillshots.SkillshotTypes
{
public class SummonerMark : EvadeSkillshot
{
public SummonerMark()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
private Vector3 _castStartPos;
private Vector3 _castEndPos;
private Vector3 _endPos;
public Vector3 StartPosition
{
get
{
if (SpawnObject == null)
{
return _castStartPos;
}
return SpawnObject.Position;
}
}
public Vector3 EndPosition
{
get
{
if (SpawnObject == null)
{
return _castEndPos;
}
return _endPos;
}
}
public override Vector3 GetPosition()
{
return StartPosition;
}
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new SummonerMark {OwnSpellData = OwnSpellData};
return newInstance;
}
public override void OnCreate(GameObject obj)
{
if (obj == null)
{
_castStartPos = Caster.Position;
_castEndPos = _castStartPos.ExtendVector3(CastArgs.End, OwnSpellData.Range);
}
}
public override void OnCreateObject(GameObject obj)
{
var minion = obj as Obj_AI_Minion;
if (SpawnObject == null && minion != null)
{
if (minion.BaseSkinName == OwnSpellData.ObjectCreationName)
{
// Force skillshot to be removed
IsValid = false;
}
}
if (SpawnObject != null)
{
if (Utils.Utils.GetGameObjectName(obj) == OwnSpellData.ToggleParticleName &&
obj.Distance(SpawnObject, true) <= 300.Pow())
{
IsValid = false;
}
}
}
public override void OnTick()
{
if (SpawnObject == null)
{
if (Environment.TickCount > TimeDetected + OwnSpellData.Delay + 50)
IsValid = false;
}
else
{
//_endPos = (SpawnObject as Obj_AI_Minion).Path.LastOrDefault();
if (Environment.TickCount > TimeDetected + 9000)
IsValid = false;
}
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
Utils.Utils.Draw3DRect(StartPosition, EndPosition, OwnSpellData.Radius*2, Color.White);
}
public override Geometry.Polygon ToRealPolygon()
{
var halfWidth = OwnSpellData.Radius * 2 / 2;
var d1 = StartPosition.To2D();
var d2 = EndPosition.To2D();
var direction = (d1 - d2).Perpendicular().Normalized();
Vector3[] points =
{
(d1 + direction*halfWidth).To3DPlayer(),
(d1 - direction*halfWidth).To3DPlayer(),
(d2 - direction*halfWidth).To3DPlayer(),
(d2 + direction*halfWidth).To3DPlayer()
};
var p = new Geometry.Polygon();
p.Points.AddRange(points.Select(x => x.To2D()).ToList());
return p;
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
if (OwnSpellData.AddHitbox)
extrawidth += Player.Instance.BoundingRadius;
return new Geometry.Polygon.Rectangle(StartPosition, EndPosition.ExtendVector3(StartPosition, -extrawidth),
OwnSpellData.Radius*2 + extrawidth);
}
public override int GetAvailableTime(Vector2 pos)
{
var dist1 =
Math.Abs((EndPosition.Y - StartPosition.Y) * pos.X - (EndPosition.X - StartPosition.X) * pos.Y +
EndPosition.X * StartPosition.Y - EndPosition.Y * StartPosition.X) / (StartPosition.Distance(EndPosition));
var actualDist = Math.Sqrt(StartPosition.Distance(pos).Pow() - dist1.Pow());
var time = OwnSpellData.MissileSpeed > 0 ? (int)((actualDist / OwnSpellData.MissileSpeed) * 1000) : 0;
if (SpawnObject == null)
{
time += Math.Max(0, OwnSpellData.Delay - (Environment.TickCount - TimeDetected));
}
return time;
}
public override bool IsFromFow()
{
return SpawnObject != null && !SpawnObject.IsVisible;
}
}
}<file_sep>/AutoBuddy_BETA_Fixed/MyChampLogic/Malzahar.cs
using AutoBuddy.MainLogics;
using EloBuddy;
using EloBuddy.SDK;
namespace AutoBuddy.MyChampLogic
{
internal class Malzahar : IChampLogic
{
public float MaxDistanceForAA { get { return int.MaxValue; } }
public float OptimalMaxComboDistance { get { return AutoWalker.p.AttackRange; } }
public float HarassDistance { get { return AutoWalker.p.AttackRange; } }
public Spell.Active Q;
public Spell.Skillshot W, E, R;
public Malzahar()
{
skillSequence = new[] { 2, 3, 1, 3, 3, 4, 3, 2, 3, 2, 4, 2, 2, 1, 1, 4, 1, 1 };
ShopSequence =
"1027:Buy,3340:Buy,2003:StartHpPot,3070:Buy,1058:Buy,1011:Buy,3116:Buy,3020:Buy,1058:Buy,1026:Buy,3089:Buy,2003:StopHpPot,3136:Buy,3151:Buy,1058:Buy,3003:Buy,3108:Buy,3001:Buy";
}
public int[] skillSequence { get; private set; }
public LogicSelector Logic { get; set; }
public string ShopSequence { get; private set; }
public void Harass(AIHeroClient target)
{ }
public void Survi()
{ }
public void Combo(AIHeroClient target)
{ }
}
}
<file_sep>/MoonWalkEvade/Skillshots/SkillshotTypes/VeigarE.cs
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using MoonWalkEvade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace MoonWalkEvade.Skillshots.SkillshotTypes
{
class VeigarE : EvadeSkillshot
{
public VeigarE()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
public Vector3 StartPosition { get; set; }
public Vector3 EndPosition { get; set; }
public MissileClient Missile => SpawnObject as MissileClient;
private bool _missileDeleted;
public override Vector3 GetPosition()
{
return EndPosition;
}
/// <summary>
/// Creates an existing Class Object unlike the DataBase contains
/// </summary>
/// <returns></returns>
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new VeigarE { OwnSpellData = OwnSpellData };
if (debug)
{
bool isProjectile = EvadeMenu.HotkeysMenu["isProjectile"].Cast<CheckBox>().CurrentValue;
var newDebugInst = new VeigarE
{
OwnSpellData = OwnSpellData,
StartPosition = Debug.GlobalStartPos,
EndPosition = Debug.GlobalEndPos,
IsValid = true,
IsActive = true,
TimeDetected = Environment.TickCount,
SpawnObject = isProjectile ? new MissileClient() : null
};
return newDebugInst;
}
return newInstance;
}
public override void OnCreate(GameObject obj)
{
EndPosition = Missile?.EndPosition ?? CastArgs.End;
}
public override void OnCreateObject(GameObject obj)
{
var missile = obj as MissileClient;
if (SpawnObject == null && missile != null)
{
if (missile.SData.Name == OwnSpellData.ObjectCreationName && missile.SpellCaster.Index == Caster.Index)
{
// Force skillshot to be removed
IsValid = false;
}
}
}
public override bool OnDeleteMissile(GameObject obj)
{
if (Missile != null && obj.Index == Missile.Index && !string.IsNullOrEmpty(OwnSpellData.ToggleParticleName))
{
_missileDeleted = true;
return false;
}
return true;
}
public override void OnDeleteObject(GameObject obj)
{
if (Missile != null && _missileDeleted && !string.IsNullOrEmpty(OwnSpellData.ToggleParticleName))
{
var r = new Regex(OwnSpellData.ToggleParticleName);
if (r.Match(obj.Name).Success && obj.Distance(EndPosition, true) <= 100 * 100)
{
IsValid = false;
}
}
}
/// <summary>
/// check if still valid
/// </summary>
public override void OnTick()
{
if (Missile == null)
{
if (Environment.TickCount > TimeDetected + OwnSpellData.Delay + 3000)
IsValid = false;
}
else if (Missile != null)
{
if (Environment.TickCount > TimeDetected + 6000)
IsValid = false;
}
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
if (Missile != null && !_missileDeleted)
{
new Geometry.Polygon.Circle(EndPosition,
StartPosition.To2D().Distance(Missile.Position.To2D()) / (StartPosition.To2D().Distance(EndPosition.To2D())) * OwnSpellData.Radius).DrawPolygon(
Color.DodgerBlue);
}
ToPolygon().Draw(Color.White);
}
public override Geometry.Polygon ToRealPolygon()
{
return ToPolygon();
}
public override Geometry.Polygon ToInnerPolygon(float extrawidth = 0)
{
extrawidth = -20;
return new Geometry.Polygon.Circle(EndPosition, OwnSpellData.RingRadius + extrawidth);
}
public override Geometry.Polygon ToOuterPolygon(float extrawidth = 0)
{
extrawidth = 20;
return new Geometry.Polygon.Circle(EndPosition, OwnSpellData.RingRadius + OwnSpellData.Radius + extrawidth);
}
Vector2 PointOnCircle(float radius, float angleInDegrees, Vector2 origin)
{
float x = origin.X + (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180));
float y = origin.Y + (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180));
return new Vector2(x, y);
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
extrawidth = -20;
List<Vector2> points = new List<Vector2>();
int i = 0;
for (; i <= 360; i += 20)
{
points.Add(PointOnCircle(OwnSpellData.RingRadius + extrawidth, i, EndPosition.To2D()));
}
extrawidth = 20;
i -= 20;
for (; i >= 0; i -= 20)
{
points.Add(PointOnCircle(OwnSpellData.RingRadius + OwnSpellData.Radius + extrawidth, i, EndPosition.To2D()));
}
var poly = new Geometry.Polygon();
poly.Points.AddRange(points);
return poly;
}
public override int GetAvailableTime(Vector2 pos)
{
return Math.Max(0, OwnSpellData.Delay - (Environment.TickCount - TimeDetected));
}
public override bool IsFromFow()
{
return Missile != null && !Missile.SpellCaster.IsVisible;
}
}
}
<file_sep>/Moon Walk Evade/Skillshots/SkillshotTypes/ConeSkillshot.cs
using System;
using System.Collections.Generic;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using Moon_Walk_Evade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace Moon_Walk_Evade.Skillshots.SkillshotTypes
{
class ConeSkillshot : EvadeSkillshot
{
public ConeSkillshot()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
public Vector3 _startPos;
public Vector3 _endPos;
public MissileClient Missile => OwnSpellData.IsPerpendicular ? null : SpawnObject as MissileClient;
public Vector3 RealStartPosition
{
get
{
bool debugMode = EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
if (debugMode)
return Debug.GlobalStartPos;
if (Missile == null)
return _startPos;
return Missile.StartPosition;
}
}
public Vector3 StartPosition
{
get
{
bool debugMode = EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
if (Missile == null)
{
if (debugMode)
return Debug.GlobalStartPos;
return _startPos;
}
if (debugMode)//Simulate Position
{
float speed = OwnSpellData.MissileSpeed;
float timeElapsed = Environment.TickCount - TimeDetected - OwnSpellData.Delay;
float traveledDist = speed * timeElapsed / 1000;
return Debug.GlobalStartPos.Extend(Debug.GlobalEndPos, traveledDist).To3D();
}
return Missile.Position;
}
}
public Vector3 EndPosition
{
get
{
bool debugMode = EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
if (debugMode)
return Debug.GlobalEndPos;
if (Missile == null)
return _endPos;
return Missile.StartPosition.ExtendVector3(Missile.EndPosition, OwnSpellData.Range);
}
}
public override Vector3 GetPosition()
{
return StartPosition;
}
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new ConeSkillshot { OwnSpellData = OwnSpellData };
if (debug)
{
bool isProjectile = EvadeMenu.HotkeysMenu["isProjectile"].Cast<CheckBox>().CurrentValue;
var newDebugInst = new ConeSkillshot
{
OwnSpellData = OwnSpellData,
_startPos = Debug.GlobalStartPos,
_endPos = Debug.GlobalEndPos,
IsValid = true,
IsActive = true,
TimeDetected = Environment.TickCount,
SpawnObject = isProjectile ? new MissileClient() : null
};
return newDebugInst;
}
return newInstance;
}
public override void OnCreateObject(GameObject obj)
{
var missile = obj as MissileClient;
if (SpawnObject == null && missile != null)
{
if (missile.SData.Name == OwnSpellData.ObjectCreationName && missile.SpellCaster.Index == Caster.Index)
{
IsValid = false;
}
}
}
public override void OnSpellDetection(Obj_AI_Base sender)
{
_startPos = Caster.ServerPosition;
_endPos = _startPos.ExtendVector3(CastArgs.End, OwnSpellData.Range);
}
public override void OnTick()
{
if (Missile == null)
{
if (Environment.TickCount > TimeDetected + OwnSpellData.Delay + 250)
{
IsValid = false;
}
}
else if (Missile != null)
{
if (Environment.TickCount > TimeDetected + 6000)
{
IsValid = false;
}
}
if (EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue)
{
float speed = OwnSpellData.MissileSpeed;
float timeElapsed = Environment.TickCount - TimeDetected - OwnSpellData.Delay;
float traveledDist = speed * timeElapsed / 1000;
if (traveledDist >= Debug.GlobalStartPos.Distance(Debug.GlobalEndPos) - 50)
{
IsValid = false;
return;
}
}
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
if (!EvadeMenu.DrawMenu["drawDangerPolygon"].Cast<CheckBox>().CurrentValue)
{
ToPolygon().Draw(Color.White);
}
}
public override Geometry.Polygon ToRealPolygon()
{
return ToPolygon();
}
Vector2 RotateAroundPoint(Vector2 start, Vector2 end, float theta)
{
float px = end.X, py = end.Y;
float ox = start.X, oy = start.Y;
float x = (float)Math.Cos(theta) * (px - ox) - (float)Math.Sin(theta) * (py - oy) + ox;
float y = (float)Math.Sin(theta) * (px - ox) + (float)Math.Cos(theta) * (py - oy) + oy;
return new Vector2(x, y);
}
Vector2[] GetBeginEdgePoints(Vector2[] edges)
{
var endEdges = edges;
Vector2 direction = (EndPosition - RealStartPosition).To2D();
var perpVecStart = StartPosition.To2D() + direction.Normalized().Perpendicular();
var perpVecEnd = StartPosition.To2D() + direction.Normalized().Perpendicular() * 1500;
//right side is not the same?
var perpVecStart2 = StartPosition.To2D() + direction.Normalized().Perpendicular2();
var perpVecEnd2 = StartPosition.To2D() + direction.Normalized().Perpendicular2() * 1500;
Geometry.Polygon.Line leftEdgeLine = new Geometry.Polygon.Line(RealStartPosition.To2D(), endEdges[1]);
Geometry.Polygon.Line rightEdgeLine = new Geometry.Polygon.Line(RealStartPosition.To2D(), endEdges[0]);
var inters = leftEdgeLine.GetIntersectionPointsWithLineSegment(perpVecStart, perpVecEnd);
var inters2 = rightEdgeLine.GetIntersectionPointsWithLineSegment(perpVecStart2, perpVecEnd2);
Vector2 p1 = Vector2.Zero, p2 = Vector2.Zero;
if (inters.Any())
{
var closestInter = inters.OrderBy(x => x.Distance(StartPosition)).First();
p2 = closestInter;
}
if (inters2.Any())
{
var closestInter = inters2.OrderBy(x => x.Distance(StartPosition)).First();
p1 = closestInter;
}
if (!p1.IsZero && !p2.IsZero)
return new[] { p1, p2 };
return new[] { StartPosition.To2D(), StartPosition.To2D() };
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
List<Vector2> coneSegemnts = new List<Vector2>();
for (float i = -OwnSpellData.ConeAngle / 2f; i <= OwnSpellData.ConeAngle / 2f; i++)
{
coneSegemnts.Add(RotateAroundPoint(RealStartPosition.To2D(), EndPosition.To2D(), i * (float)Math.PI / 180));
}
if (Missile != null)
{
var beginPoints = GetBeginEdgePoints(new[] { coneSegemnts.First(), coneSegemnts.Last() });
coneSegemnts.Insert(0, beginPoints[0]);
coneSegemnts.Insert(0, beginPoints[1]);
}
else
coneSegemnts.Insert(0, RealStartPosition.To2D());
Geometry.Polygon polygon = new Geometry.Polygon();
polygon.Points.AddRange(coneSegemnts);
return polygon;
}
public override int GetAvailableTime(Vector2 pos)
{
var dist1 =
Math.Abs((EndPosition.Y - StartPosition.Y) * pos.X - (EndPosition.X - StartPosition.X) * pos.Y +
EndPosition.X * StartPosition.Y - EndPosition.Y * StartPosition.X) / StartPosition.Distance(EndPosition);
var actualDist = Math.Sqrt(StartPosition.Distance(pos).Pow() - dist1.Pow());
var time = OwnSpellData.MissileSpeed > 0 ? (int)(actualDist / OwnSpellData.MissileSpeed * 1000) : 0;
if (Missile == null)
{
return Math.Max(0, OwnSpellData.Delay - (Environment.TickCount - TimeDetected));
}
return time;
}
public override bool IsFromFow()
{
return Missile != null && !Missile.SpellCaster.IsVisible;
}
}
}
<file_sep>/EvadePlus/Program.cs
using EloBuddy.SDK.Events;
namespace EvadePlus
{
internal static class Program
{
public static bool DeveloperMode = false;
public static bool SdkDrawings = false;
private static SkillshotDetector _skillshotDetector;
private static EvadePlus _evade;
private static void Main(string[] args)
{
Loading.OnLoadingComplete += delegate
{
_skillshotDetector = new SkillshotDetector(DeveloperMode ? DetectionTeam.AnyTeam : DetectionTeam.EnemyTeam);
_evade = new EvadePlus(_skillshotDetector);
EvadeMenu.CreateMenu();
};
}
}
}
<file_sep>/Moon Walk Evade/Utils/Debug.cs
using System;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Rendering;
using Moon_Walk_Evade.Skillshots;
using Moon_Walk_Evade.Skillshots.SkillshotTypes;
using SharpDX;
namespace Moon_Walk_Evade.Utils
{
static class Debug
{
public static Vector3 GlobalEndPos = Vector3.Zero, GlobalStartPos = Vector3.Zero;
private static SpellDetector spellDetector;
public static int LastCreationTick;
public static void Init(ref SpellDetector detector)
{
spellDetector = detector;
Game.OnWndProc += GameOnOnWndProc;
Drawing.OnDraw += args =>
{
if (!GlobalEndPos.IsZero)
new Circle { Color = System.Drawing.Color.DodgerBlue, Radius = 100 }.Draw(GlobalEndPos);
if (!GlobalStartPos.IsZero)
new Circle { Color = System.Drawing.Color.Red, Radius = 100 }.Draw(GlobalStartPos);
};
Game.OnUpdate += GameOnOnUpdate;
}
private static EvadeSkillshot lastKSkillshot;
private static void GameOnOnUpdate(EventArgs args)
{
if (lastKSkillshot != null)
{
if (!lastKSkillshot.IsValid || !lastKSkillshot.IsActive)
{
lastKSkillshot = null;
return;
}
if (lastKSkillshot.GetType() == typeof(LinearSkillshot))
{
var skill = (LinearSkillshot)lastKSkillshot;
if (skill.StartPosition.Distance(Player.Instance) <= Player.Instance.BoundingRadius &&
Player.Instance.Position.To2D().ProjectOn(skill.StartPosition.To2D(), skill.EndPosition.To2D()).IsOnSegment && skill.Missile != null)
{
Chat.Print(Game.Time + " Hit");
lastKSkillshot = null;
}
}
}
if (!EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue)
return;
if (GlobalStartPos.IsZero || GlobalEndPos.IsZero)
return;
if (Environment.TickCount - LastCreationTick < EvadeMenu.HotkeysMenu["debugModeIntervall"].Cast<Slider>().CurrentValue)
return;
LastCreationTick = Environment.TickCount;
var skillshot =
SkillshotDatabase.Database[EvadeMenu.HotkeysMenu["debugMissile"].Cast<Slider>().CurrentValue];
if (skillshot.GetType() == typeof(CircularSkillshot) ||
skillshot.GetType() == typeof(MultiCircleSkillshot))
EvadeMenu.HotkeysMenu["isProjectile"].Cast<CheckBox>().CurrentValue = false;
var nSkillshot = skillshot.NewInstance(true);
spellDetector.AddSkillshot(nSkillshot);
lastKSkillshot = nSkillshot;
}
private static void GameOnOnWndProc(WndEventArgs args)
{
if (!EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue)
return;
if (args.Msg == 0x0201)//mouse down
{
GlobalEndPos = Game.CursorPos;
}
if (args.Msg == 0x0202)
{
GlobalStartPos = Game.CursorPos;
}
}
}
}
<file_sep>/Moon Walk Evade/Skillshots/SkillshotTypes/LinearSkillshot.cs
using System;
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using Moon_Walk_Evade.Evading;
using Moon_Walk_Evade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace Moon_Walk_Evade.Skillshots.SkillshotTypes
{
public class LinearSkillshot : EvadeSkillshot
{
public LinearSkillshot()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
public Vector3 _startPos;
public Vector3 _endPos;
private bool DoesCollide, CollisionChecked;
private Vector2 LastCollisionPos;
public MissileClient Missile => OwnSpellData.IsPerpendicular ? null : SpawnObject as MissileClient;
public Vector3 StartPosition
{
get
{
bool debugMode = EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
if (Missile == null)
{
if (debugMode)
return Debug.GlobalStartPos;
return _startPos;
}
if (debugMode)//Simulate Position
{
float speed = OwnSpellData.MissileSpeed;
float timeElapsed = Environment.TickCount - TimeDetected - OwnSpellData.Delay;
float traveledDist = speed * timeElapsed / 1000;
return Debug.GlobalStartPos.Extend(Debug.GlobalEndPos, traveledDist).To3D();
}
return Missile.Position;
}
}
public Vector3 EndPosition
{
get
{
bool debugMode = EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue;
if (debugMode)
return Debug.GlobalEndPos;
if (Missile == null)
{
return _endPos;
}
if (DoesCollide)
return LastCollisionPos.To3D();
return Missile.StartPosition.ExtendVector3(Missile.EndPosition, OwnSpellData.Range + 100);
}
}
public override Vector3 GetPosition()
{
return StartPosition;
}
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new LinearSkillshot { OwnSpellData = OwnSpellData };
if (debug)
{
bool isProjectile = EvadeMenu.HotkeysMenu["isProjectile"].Cast<CheckBox>().CurrentValue;
var newDebugInst = new LinearSkillshot
{
OwnSpellData = OwnSpellData, _startPos = Debug.GlobalStartPos,
_endPos = Debug.GlobalEndPos, IsValid = true, IsActive = true, TimeDetected = Environment.TickCount,
SpawnObject = isProjectile ? new MissileClient() : null
};
return newDebugInst;
}
return newInstance;
}
public override void OnCreateObject(GameObject obj)
{
var missile = obj as MissileClient;
if (SpawnObject == null && missile != null)
{
if (missile.SData.Name == OwnSpellData.ObjectCreationName && missile.SpellCaster.Index == Caster.Index)
{
IsValid = false;
}
}
}
public override void OnSpellDetection(Obj_AI_Base sender)
{
if (!OwnSpellData.IsPerpendicular)
{
_startPos = Caster.ServerPosition;
_endPos = _startPos.ExtendVector3(CastArgs.End, OwnSpellData.Range);
}
else
{
OwnSpellData.Direction = (CastArgs.End - CastArgs.Start).To2D().Normalized();
var direction = OwnSpellData.Direction;
_startPos = (CastArgs.End.To2D() - direction.Perpendicular() * OwnSpellData.SecondaryRadius).To3D();
_endPos = (CastArgs.End.To2D() + direction.Perpendicular() * OwnSpellData.SecondaryRadius).To3D();
}
}
public override void OnTick()
{
if (Missile == null)
{
if (Environment.TickCount > TimeDetected + OwnSpellData.Delay + 250)
{
IsValid = false;
return;
}
}
else if (Missile != null)
{
if (Environment.TickCount > TimeDetected + 6000)
{
IsValid = false;
return;
}
}
if (EvadeMenu.HotkeysMenu["debugMode"].Cast<KeyBind>().CurrentValue)
{
float speed = OwnSpellData.MissileSpeed;
float timeElapsed = Environment.TickCount - TimeDetected - OwnSpellData.Delay;
float traveledDist = speed * timeElapsed / 1000;
if (traveledDist >= Debug.GlobalStartPos.Distance(Debug.GlobalEndPos) - 50)
{
IsValid = false;
return;
}
}
if (!CollisionChecked)
{
Vector2 collision = this.GetCollisionPoint();
DoesCollide = !collision.IsZero;
LastCollisionPos = collision;
CollisionChecked = true;
}
else if (DoesCollide && !LastCollisionPos.ProjectOn(StartPosition.To2D(), EndPosition.To2D()).IsOnSegment)
DoesCollide = false;
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
Utils.Utils.Draw3DRect(StartPosition, EndPosition, OwnSpellData.Radius * 2, Color.White);
}
public override Geometry.Polygon ToRealPolygon()
{
var halfWidth = OwnSpellData.Radius;
var d1 = StartPosition.To2D();
var d2 = EndPosition.To2D();
var direction = (d1 - d2).Perpendicular().Normalized();
Vector3[] points =
{
(d1 + direction*halfWidth).To3DPlayer(),
(d1 - direction*halfWidth).To3DPlayer(),
(d2 - direction*halfWidth).To3DPlayer(),
(d2 + direction*halfWidth).To3DPlayer()
};
var p = new Geometry.Polygon();
p.Points.AddRange(points.Select(x => x.To2D()).ToList());
return p;
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
extrawidth = 20;
if (OwnSpellData.AddHitbox)
{
extrawidth += Player.Instance.HitBoxRadius();
}
return new Geometry.Polygon.Rectangle(StartPosition, EndPosition.ExtendVector3(StartPosition, -extrawidth), OwnSpellData.Radius + extrawidth);
}
public override int GetAvailableTime(Vector2 pos)
{
var dist1 =
Math.Abs((EndPosition.Y - StartPosition.Y) * pos.X - (EndPosition.X - StartPosition.X) * pos.Y +
EndPosition.X * StartPosition.Y - EndPosition.Y * StartPosition.X) / StartPosition.Distance(EndPosition);
var actualDist = Math.Sqrt(StartPosition.Distance(pos).Pow() - dist1.Pow());
var time = OwnSpellData.MissileSpeed > 0 ? (int) (actualDist / OwnSpellData.MissileSpeed * 1000) : 0;
if (Missile == null)
{
return Math.Max(0, OwnSpellData.Delay - (Environment.TickCount - TimeDetected));
}
return time;
}
public override bool IsFromFow()
{
return Missile != null && !Missile.SpellCaster.IsVisible;
}
}
}<file_sep>/Evade/Extensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using SharpDX;
using Color = System.Drawing.Color;
namespace Evade
{
static class Extensions
{
public static List<Vector2> GetWaypoints(this Obj_AI_Base unit)
{
var result = new List<Vector2>();
if (unit.IsVisible)
{
result.Add(unit.ServerPosition.To2D());
var path = unit.Path;
if (path.Length > 0)
{
var first = path[0].To2D();
if (first.Distance(result[0], true) > 40)
{
result.Add(first);
}
for (int i = 1; i < path.Length; i++)
{
result.Add(path[i].To2D());
}
}
}
else if (WaypointTracker.StoredPaths.ContainsKey(unit.NetworkId))
{
var path = WaypointTracker.StoredPaths[unit.NetworkId];
var timePassed = (Utils.TickCount - WaypointTracker.StoredTick[unit.NetworkId]) / 1000f;
if (path.PathLength() >= unit.MoveSpeed * timePassed)
{
result = CutPath(path, (int)(unit.MoveSpeed * timePassed));
}
}
return result;
}
public static List<Vector2> CutPath(this List<Vector2> path, float distance)
{
var result = new List<Vector2>();
var Distance = distance;
if (distance < 0)
{
path[0] = path[0] + distance * (path[1] - path[0]).Normalized();
return path;
}
for (var i = 0; i < path.Count - 1; i++)
{
var dist = path[i].Distance(path[i + 1]);
if (dist > Distance)
{
result.Add(path[i] + Distance * (path[i + 1] - path[i]).Normalized());
for (var j = i + 1; j < path.Count; j++)
{
result.Add(path[j]);
}
break;
}
Distance -= dist;
}
return result.Count > 0 ? result : new List<Vector2> { path.Last() };
}
}
internal static class WaypointTracker
{
public static readonly Dictionary<int, List<Vector2>> StoredPaths = new Dictionary<int, List<Vector2>>();
public static readonly Dictionary<int, int> StoredTick = new Dictionary<int, int>();
}
internal static class SGeometry
{
public static float PathLength(this List<Vector2> path)
{
var distance = 0f;
for (var i = 0; i < path.Count - 1; i++)
{
distance += path[i].Distance(path[i + 1]);
}
return distance;
}
}
public class SharpGeometry
{
public static Vector2[] CircleCircleIntersection(Vector2 center1, Vector2 center2, float radius1, float radius2)
{
var D = center1.Distance(center2);
//The Circles dont intersect:
if (D > radius1 + radius2 || (D <= Math.Abs(radius1 - radius2)))
{
return new Vector2[] {};
}
var A = (radius1*radius1 - radius2*radius2 + D*D)/(2*D);
var H = (float) Math.Sqrt(radius1*radius1 - A*A);
var Direction = (center2 - center1).Normalized();
var PA = center1 + A*Direction;
var S1 = PA + H*Direction.Perpendicular();
var S2 = PA - H*Direction.Perpendicular();
return new[] {S1, S2};
}
}
static class EnumerableExtensions
{
public static T MinOrDefault<T, R>(this IEnumerable<T> container, Func<T, R> valuingFoo) where R : IComparable
{
var enumerator = container.GetEnumerator();
if (!enumerator.MoveNext())
{
return default(T);
}
var minElem = enumerator.Current;
var minVal = valuingFoo(minElem);
while (enumerator.MoveNext())
{
var currVal = valuingFoo(enumerator.Current);
if (currVal.CompareTo(minVal) < 0)
{
minVal = currVal;
minElem = enumerator.Current;
}
}
return minElem;
}
}
static class LastCastedSpell
{
/// <summary>
/// The casted spells
/// </summary>
internal static readonly Dictionary<int, LastCastedSpellEntry> CastedSpells =
new Dictionary<int, LastCastedSpellEntry>();
/// <summary>
/// The last cast packet sent
/// </summary>
public static LastCastPacketSentEntry LastCastPacketSent;
/// <summary>
/// Initializes static members of the <see cref="LastCastedSpell"/> class.
/// </summary>
static LastCastedSpell()
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Hero_OnProcessSpellCast;
Spellbook.OnCastSpell += SpellbookOnCastSpell;
}
/// <summary>
/// Fired then a spell is casted.
/// </summary>
/// <param name="spellbook">The spellbook.</param>
/// <param name="args">The <see cref="SpellbookCastSpellEventArgs"/> instance containing the event data.</param>
static void SpellbookOnCastSpell(Spellbook spellbook, SpellbookCastSpellEventArgs args)
{
if (spellbook.Owner.IsMe)
{
LastCastPacketSent = new LastCastPacketSentEntry(
args.Slot, Utils.TickCount, (args.Target is Obj_AI_Base) ? args.Target.NetworkId : 0);
}
}
/// <summary>
/// Fired when the game processes the spell cast.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs"/> instance containing the event data.</param>
private static void Obj_AI_Hero_OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender is AIHeroClient)
{
var entry = new LastCastedSpellEntry(args.SData.Name, Utils.TickCount, ObjectManager.Player);
if (CastedSpells.ContainsKey(sender.NetworkId))
{
CastedSpells[sender.NetworkId] = entry;
}
else
{
CastedSpells.Add(sender.NetworkId, entry);
}
}
}
/// <summary>
/// Gets the last casted spell tick.
/// </summary>
/// <param name="unit">The unit.</param>
/// <returns></returns>
public static int LastCastedSpellT(this AIHeroClient unit)
{
return CastedSpells.ContainsKey(unit.NetworkId) ? CastedSpells[unit.NetworkId].Tick : (Utils.TickCount > 0 ? 0 : int.MinValue);
}
/// <summary>
/// Gets the last casted spell name.
/// </summary>
/// <param name="unit">The unit.</param>
/// <returns></returns>
public static string LastCastedSpellName(this AIHeroClient unit)
{
return CastedSpells.ContainsKey(unit.NetworkId) ? CastedSpells[unit.NetworkId].Name : string.Empty;
}
/// <summary>
/// Gets the last casted spell's target.
/// </summary>
/// <param name="unit">The unit.</param>
/// <returns></returns>
public static Obj_AI_Base LastCastedSpellTarget(this AIHeroClient unit)
{
return CastedSpells.ContainsKey(unit.NetworkId) ? CastedSpells[unit.NetworkId].Target : null;
}
/// <summary>
/// Gets the last casted spell.
/// </summary>
/// <param name="unit">The unit.</param>
/// <returns></returns>
public static LastCastedSpellEntry LastCastedspell(this AIHeroClient unit)
{
return CastedSpells.ContainsKey(unit.NetworkId) ? CastedSpells[unit.NetworkId] : null;
}
}
public class LastCastedSpellEntry
{
/// <summary>
/// The name
/// </summary>
public string Name;
/// <summary>
/// The target
/// </summary>
public Obj_AI_Base Target;
/// <summary>
/// The tick
/// </summary>
public int Tick;
/// <summary>
/// Initializes a new instance of the <see cref="LastCastedSpellEntry"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="tick">The tick.</param>
/// <param name="target">The target.</param>
public LastCastedSpellEntry(string name, int tick, Obj_AI_Base target)
{
Name = name;
Tick = tick;
Target = target;
}
}
public class LastCastPacketSentEntry
{
/// <summary>
/// The slot
/// </summary>
public SpellSlot Slot;
/// <summary>
/// The target network identifier
/// </summary>
public int TargetNetworkId;
/// <summary>
/// The tick
/// </summary>
public int Tick;
/// <summary>
/// Initializes a new instance of the <see cref="LastCastPacketSentEntry"/> class.
/// </summary>
/// <param name="slot">The slot.</param>
/// <param name="tick">The tick.</param>
/// <param name="targetNetworkId">The target network identifier.</param>
public LastCastPacketSentEntry(SpellSlot slot, int tick, int targetNetworkId)
{
Slot = slot;
Tick = tick;
TargetNetworkId = targetNetworkId;
}
}
static class MenuExtensions
{
public static void AddStringList(this Menu m, string uniqueId, string displayName, string[] values, int defaultValue)
{
var mode = m.Add(uniqueId, new Slider(displayName, defaultValue, 0, values.Length - 1));
mode.DisplayName = displayName + ": " + values[mode.CurrentValue];
mode.OnValueChange += delegate (ValueBase<int> sender, ValueBase<int>.ValueChangeArgs args)
{
sender.DisplayName = displayName + ": " + values[args.NewValue];
};
}
}
static class Utility
{
public static bool IsWall(this Vector3 position)
{
return NavMesh.GetCollisionFlags(position).HasFlag(CollisionFlags.Wall);
}
public static bool IsWall(this Vector2 position)
{
return position.To3D().IsWall();
}
public static bool PlayerWindingUp;
public static void OnPreAttack(AIHeroClient sender, Orbwalker.PreAttackArgs args)
{
if (sender.IsMe)
{
PlayerWindingUp = true;
}
}
}
static class Items
{
public static InventorySlot GetWardSlot()
{
var wardIds = new[] { 3340, 3350, 3361, 3154, 2045, 2049, 2050, 2044 };
return (from wardId in wardIds
where Item.CanUseItem(wardId)
select ObjectManager.Player.InventoryItems.FirstOrDefault(slot => slot.Id == (ItemId)wardId))
.FirstOrDefault();
}
}
}
<file_sep>/MoonWalkEvade/Skillshots/SkillshotTypes/CircularSkillshot.cs
using System;
using System.Text.RegularExpressions;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu.Values;
using MoonWalkEvade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace MoonWalkEvade.Skillshots.SkillshotTypes
{
public class CircularSkillshot : EvadeSkillshot
{
public CircularSkillshot()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
public Vector3 StartPosition { get; set; }
public Vector3 EndPosition { get; set; }
public MissileClient Missile => SpawnObject as MissileClient;
private bool _missileDeleted;
public override Vector3 GetPosition()
{
return EndPosition;
}
/// <summary>
/// Creates an existing Class Object unlike the DataBase contains
/// </summary>
/// <returns></returns>
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new CircularSkillshot { OwnSpellData = OwnSpellData };
if (debug)
{
bool isProjectile = EvadeMenu.HotkeysMenu["isProjectile"].Cast<CheckBox>().CurrentValue;
var newDebugInst = new CircularSkillshot
{
OwnSpellData = OwnSpellData,
StartPosition = Debug.GlobalStartPos,
EndPosition = Debug.GlobalEndPos,
IsValid = true,
IsActive = true,
TimeDetected = Environment.TickCount,
SpawnObject = isProjectile ? new MissileClient() : null
};
return newDebugInst;
}
return newInstance;
}
public override void OnCreate(GameObject obj)
{
if (Missile == null)
{
EndPosition = CastArgs.End;
}
else
{
EndPosition = Missile.EndPosition;
}
}
public override void OnCreateObject(GameObject obj)
{
var missile = obj as MissileClient;
if (SpawnObject == null && missile != null)
{
if (missile.SData.Name == OwnSpellData.ObjectCreationName && missile.SpellCaster.Index == Caster.Index)
{
// Force skillshot to be removed
IsValid = false;
}
}
}
public override bool OnDeleteMissile(GameObject obj)
{
if (Missile != null && obj.Index == Missile.Index && !string.IsNullOrEmpty(OwnSpellData.ToggleParticleName))
{
_missileDeleted = true;
return false;
}
return true;
}
public override void OnDeleteObject(GameObject obj)
{
if (Missile != null && _missileDeleted && !string.IsNullOrEmpty(OwnSpellData.ToggleParticleName))
{
var r = new Regex(OwnSpellData.ToggleParticleName);
if (r.Match(obj.Name).Success && obj.Distance(EndPosition, true) <= 100 * 100)
{
IsValid = false;
}
}
}
/// <summary>
/// check if still valid
/// </summary>
public override void OnTick()
{
if (Missile == null)
{
if (Environment.TickCount > TimeDetected + OwnSpellData.Delay + 250)
IsValid = false;
}
else if (Missile != null)
{
if (Environment.TickCount > TimeDetected + 6000)
IsValid = false;
}
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
if (Missile != null && !_missileDeleted)
new Geometry.Polygon.Circle(EndPosition,
StartPosition.To2D().Distance(Missile.Position.To2D()) / (StartPosition.To2D().Distance(EndPosition.To2D())) * OwnSpellData.Radius).DrawPolygon(
Color.DodgerBlue);
ToPolygon().DrawPolygon(Color.White);
}
public override Geometry.Polygon ToRealPolygon()
{
return ToPolygon();
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
extrawidth = 20;
if (OwnSpellData.AddHitbox)
{
extrawidth += Player.Instance.HitBoxRadius();
}
return new Geometry.Polygon.Circle(EndPosition, OwnSpellData.Radius + extrawidth);
}
public override int GetAvailableTime(Vector2 pos)
{
if (Missile == null)
{
return Math.Max(0, OwnSpellData.Delay - (Environment.TickCount - TimeDetected));
}
if (!_missileDeleted)
{
return (int) (Missile.Position.To2D().Distance(EndPosition.To2D()) / OwnSpellData.MissileSpeed * 1000);
}
return -1;
}
public override bool IsFromFow()
{
return Missile != null && !Missile.SpellCaster.IsVisible;
}
}
}<file_sep>/Moon Walk Evade/Skillshots/SkillshotTypes/CaitlynTrap.cs
using System;
using System.Linq;
using System.Text.RegularExpressions;
using EloBuddy;
using EloBuddy.SDK;
using Moon_Walk_Evade.Utils;
using SharpDX;
using Color = System.Drawing.Color;
namespace Moon_Walk_Evade.Skillshots.SkillshotTypes
{
class CaitlynTrap : EvadeSkillshot
{
public CaitlynTrap()
{
Caster = null;
SpawnObject = null;
SData = null;
OwnSpellData = null;
Team = GameObjectTeam.Unknown;
IsValid = true;
TimeDetected = Environment.TickCount;
}
public Vector3 EndPosition { get; set; }
public bool _missileDeleted;
public MissileClient Missile => SpawnObject as MissileClient;
public override Vector3 GetPosition()
{
return EndPosition;
}
/// <summary>
/// Creates an existing Class Object unlike the DataBase contains
/// </summary>
/// <returns></returns>
public override EvadeSkillshot NewInstance(bool debug = false)
{
var newInstance = new CaitlynTrap { OwnSpellData = OwnSpellData };
if (debug)
{
var newDebugInst = new CaitlynTrap
{
OwnSpellData = OwnSpellData,
EndPosition = Debug.GlobalEndPos,
IsValid = true,
IsActive = true,
TimeDetected = Environment.TickCount,
SpawnObject = null
};
return newDebugInst;
}
return newInstance;
}
public override void OnCreate(GameObject obj)
{
EndPosition = Missile?.EndPosition ?? CastArgs.End;
}
public override void OnCreateObject(GameObject obj)
{
var missile = obj as MissileClient;
if (SpawnObject == null && missile != null)
{
if (missile.SData.Name == OwnSpellData.ObjectCreationName && missile.SpellCaster.Index == Caster.Index)
{
// Force skillshot to be removed
IsValid = false;
}
}
}
public override bool OnDeleteMissile(GameObject obj)
{
if (Missile != null && obj.Index == Missile.Index && !string.IsNullOrEmpty(OwnSpellData.ToggleParticleName))
{
_missileDeleted = true;
return false;
}
return true;
}
public override void OnDeleteObject(GameObject obj)
{
if (Missile != null && _missileDeleted && !string.IsNullOrEmpty(OwnSpellData.ToggleParticleName))
{
var r = new Regex(OwnSpellData.ToggleParticleName);
if (r.Match(obj.Name).Success && obj.Distance(EndPosition, true) <= 100 * 100)
{
IsValid = false;
}
}
}
/// <summary>
/// check if still valid
/// </summary>
public override void OnTick()
{
if (EntityManager.Heroes.Allies.Any(x => x.Distance(EndPosition) <= 100 &&
x.HasBuff("caitlynyordletrapdebuff")) && IsValid)
IsValid = false;
if (Environment.TickCount >= TimeDetected + OwnSpellData.Delay + 90 * 1000)
IsValid = false;
}
public override void OnDraw()
{
if (!IsValid)
{
return;
}
ToPolygon().DrawPolygon(Color.White);
}
public override Geometry.Polygon ToRealPolygon()
{
return ToPolygon();
}
public override Geometry.Polygon ToPolygon(float extrawidth = 0)
{
extrawidth = 20;
if (OwnSpellData.AddHitbox)
{
extrawidth += Player.Instance.HitBoxRadius();
}
return new Geometry.Polygon.Circle(EndPosition, OwnSpellData.Radius + extrawidth);
}
public override int GetAvailableTime(Vector2 pos)
{
return Math.Max(0, OwnSpellData.Delay - (Environment.TickCount - TimeDetected));
}
public override bool IsFromFow()
{
return false;
}
}
}
| 78e5b0d8aa246a9d60265bc6b9ed90a12b3311ab | [
"C#"
] | 19 | C# | kyn9x/evade | b1a7a1072fbe7589895105e67be1fcb17739b11a | c2a210b98a7f2d14a81cec405cf07c98cdb5556f |
refs/heads/master | <file_sep>/***************************************************/
/* Nom: ClusterSearchManager.h
/* Description: ClusterSearchManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __ClusterSearchManager_H__
#define __ClusterSearchManager_H__
#include "AI\Pathfinding\ClusterSearch.h"
namespace crea
{
class Cluster;
class CREAENGINE_API MapStringClusterSearch : public map<string, ClusterSearch*> {};
class CREAENGINE_API ClusterSearchManager : public Singleton <ClusterSearchManager>
{
public:
ClusterSearchManager();
~ClusterSearchManager();
ClusterSearch* getClusterSearch(string _szName);
Map* getCurrentMap() { return m_pMap; }
void setCurrentMap(Map* _pMap) { m_pMap = _pMap; }
Cluster* getCurrentCluster() { return m_pCluster; }
void setCurrentCluster(Cluster* _pCluster) { m_pCluster = _pCluster; }
private:
MapStringClusterSearch m_ClusterSearches;
Map* m_pMap;
Cluster* m_pCluster;
};
}
#endif // __ClusterSearchManager_H__<file_sep>/***************************************************/
/* Nom: UserController.h
/* Description: UserController
/* Auteur: <NAME>
/***************************************************/
#ifndef __UserController_H_
#define __UserController_H_
#include "Core\Script.h"
#include "Core\Math.h"
using namespace crea;
class CharacterController;
class UserController : public Script
{
GameManager* m_pGM;
CharacterController* m_pCharacterController;
Vector2f m_vDirection;
public:
UserController();
virtual ~UserController();
inline void setCharacterController(CharacterController* _pCharacterController);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { return new UserController(*this); }
};
#endif
<file_sep>// Portions Copyright (C) <NAME>, 2001
#include "stdafx.h"
#include "Core\Msg.h"
namespace crea
{
Msg::Msg()
{
m_Name = -1;
m_Sender = INVALID_OBJECT_ID;
m_Receiver = INVALID_OBJECT_ID;
m_State = -1;
m_DeliveryTime = 0.0f;
}
Msg::Msg(float deliveryTime, int name, objectID sender, objectID receiver, int state)
{
SetDeliveryTime(deliveryTime);
SetMsgName(name);
SetSender(sender);
SetReceiver(receiver);
SetMsgState(state);
SetDelivered(false);
}
}
<file_sep>#include "stdafx.h"
#include "Scripts\FSMPeonGoTo.h"
#include "Scripts\Messages.h"
#include <string.h>
FSMPeonGoTo::FSMPeonGoTo(Vector2f _vTarget) : m_vTarget(_vTarget)
{
m_pPathNodeShape = (RectangleShape*)m_pGM->getShape("Rectangle", "m_pPathNodeShape");
Color* pBlueTransparent = m_pGM->getColor("BlueTransparent");
pBlueTransparent->setValues(0, 0, 255, 125);
m_pPathNodeShape->setColor(pBlueTransparent);
m_pPathNodeShape->setSize(10, 10);
m_pPathNodeShape->setOrigin(5, 5);
m_pPathNodeShapeOpen = (RectangleShape*)m_pGM->getShape("Rectangle", "m_pPathNodeShapeOpen");
Color* pGreenTransparent = m_pGM->getColor("GreenTransparent");
pGreenTransparent->setValues(0, 255, 0, 125);
m_pPathNodeShapeOpen->setColor(pGreenTransparent);
m_pPathNodeShapeOpen->setSize(32, 32);
m_pArrowShape = (ArrowShape*)m_pGM->getShape("Rectangle", "m_pArrowShape");
Color* pYellowTransparent = m_pGM->getColor("YellowTransparent");
pYellowTransparent->setValues(255, 255, 0, 125);
m_pArrowShape->setColor(pYellowTransparent);
m_pArrowShape->setOutlineColor(pYellowTransparent);
m_pArrowShape->setSize(32, 32*0.5f);
}
FSMPeonGoTo::~FSMPeonGoTo()
{
for (short i = 0; i < (short)m_vPath.size(); i++)
{
delete m_vPath[i];
}
m_vPath.clear();
}
bool FSMPeonGoTo::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
//OnMsg(MSG_Teleport)
//SetState(STATE_CompletedPath);
/////////////////////////////////////////////////////////////////
State(STATE_Init)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// A*
m_pMapSearch = m_pGM->getMapSearch(m_pEntity->getName());
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
OnUpdate
SetState(STATE_SearchPath);
/////////////////////////////////////////////////////////////////
State(STATE_SearchPath)
OnEnter
m_pMapSearch->setStartAndGoal(m_pEntity->getPosition(), m_vTarget);
m_pCharacterController->move(Vector2f(0.f, 0.f));
OnUpdate
MapSearch::SearchState s = m_pMapSearch->update(); // 1 iteration per frame!
m_pMapSearch->getOpenList(m_vOpenList);
//m_bHasOpenList = true;
if (s == MapSearch::SEARCH_STATE_SUCCEEDED)
{
SetState(STATE_FollowPath);
}
else if (s == MapSearch::SEARCH_STATE_FAILED)
{
SetState(STATE_SearchFailed);
}
OnExit
/////////////////////////////////////////////////////////////////
State(STATE_FollowPath)
OnEnter
m_bHasEdges = false;
m_pMapSearch->getSolution(m_vPath);
m_bHasPath = true;
for (VectorVector2f::iterator it = m_vPath.begin(); it != m_vPath.end(); ++it)
{
**it += Vector2f(16.f, 24.f); // Visual offset (top left to center, a bit lower)
}
m_pCharacterController->followPath(m_vPath);
OnUpdate
if (!m_pCharacterController->isFollowingPath())
{
SetState(STATE_CompletedPath);
}
OnExit
m_bHasPath = false;
/////////////////////////////////////////////////////////////////
State(STATE_SearchFailed)
OnEnter
OnUpdate
OnExit
/////////////////////////////////////////////////////////////////
State(STATE_CompletedPath)
OnEnter
OnUpdate
OnExit
EndStateMachine
}
bool FSMPeonGoTo::draw()
{
if (m_bHasPath)
{
for (VectorVector2f::iterator it = m_vPath.begin(); it != m_vPath.end(); ++it)
{
Vector2f p = **it;
m_pPathNodeShape->setPosition((float)p.getX(), (float)p.getY());
//m_pPathNodeShape->draw();
}
}
else if (m_bHasOpenList)
{
for (VectorVector2f::iterator it = m_vOpenList.begin(); it != m_vOpenList.end(); ++it)
{
Vector2f p = **it;
m_pPathNodeShapeOpen->setPosition((float)p.getX(), (float)p.getY());
//m_pPathNodeShapeOpen->draw();
}
m_bHasOpenList = false;
}
if (m_bHasEdges)
{
for (vector<Edge*>::iterator it = m_vEdges.begin(); it != m_vEdges.end(); ++it)
{
Edge* p = *it;
m_pArrowShape->setStartAndEnd((float)p->m_pStart->getX()*32+16, (float)p->m_pStart->getY() * 32 + 16, (float)p->m_pEnd->getX() * 32 + 16, (float)p->m_pEnd->getY() * 32 + 16);
m_pArrowShape->draw();
}
}
return true;
}<file_sep>#include "stdafx.h"
#include "Input\InputManager.h"
namespace crea
{
InputManager::InputManager()
{
}
InputManager::~InputManager()
{
}
InputManager* InputManager::getSingleton()
{
static InputManager instanceUnique;
return
&instanceUnique;
}
bool InputManager::update()
{
return true;
}
bool InputManager::isKeyPressed(Key _key)
{
return IFacade::get().isKeyPressed(_key);
}
bool InputManager::isMouseButtonPressed(Button _button)
{
return IFacade::get().isMouseButtonPressed(_button);
}
Vector2f InputManager::getMousePosition()
{
return IFacade::get().getMousePosition();
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Graphics\SpriteRenderer.h"
namespace crea
{
SpriteRenderer::SpriteRenderer()
{
m_pSprite = nullptr;
m_pTextureRect = nullptr;
GameManager* m_pGM = GameManager::getSingleton();
m_bActive = true;
}
SpriteRenderer::~SpriteRenderer()
{
}
bool SpriteRenderer::loadFromFileJSON(const string& _filename)
{
Json::Value root;
std::ifstream srStream(_filename, std::ifstream::binary);
if (srStream.fail())
{
cerr << "Can't open SpriteRenderer file: " << _filename << endl;
return false;
}
srStream >> root;
string szSprite = root["sprite"].asString();
Sprite* pSprite = m_pGM->getSprite(szSprite);
string szTexture = root["image"].asString();
Texture* pTexture = m_pGM->getTexture(szTexture);
pSprite->setTexture(pTexture);
setSprite(pSprite);
return true;
}
bool SpriteRenderer::init()
{
return true;
}
bool SpriteRenderer::update()
{
return true;
}
bool SpriteRenderer::draw()
{
if (m_pSprite && m_bActive)
{
// Set sprite position
Vector2f vPos = getEntity()->getPosition();
m_pSprite->setPosition(vPos.getX(), vPos.getY());
if (m_pTextureRect)
{
m_pSprite->setTextureRect(m_pTextureRect->getLeft(), m_pTextureRect->getTop(),
m_pTextureRect->getWidth(), m_pTextureRect->getHeight());
}
// Draw
m_pSprite->draw();
}
return true;
}
bool SpriteRenderer::quit()
{
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "AI\Steering\Behavior.h"
#include "AI\Steering\Steering.h"
#include "Core\Entity.h"
#include "Physics\Collider.h"
namespace crea
{
int Swarming::global_counter = 0;
Behavior::Behavior(Entity* _pEntity)
: m_pEntity(_pEntity), m_vDesiredVelocity(), m_vSteering(), m_vOffset()
{
m_pSteering = m_pEntity->getComponent<Steering>();
m_pVehicle = m_pEntity->getComponent<Vehicle>();
};
Vector2f& Seek::Update()
{
m_pSteering->setTarget(m_target);
m_pSteering->setTargetOffset(Vector2f(0.f, 0.f));
m_vDesiredVelocity = m_target->getPosition() - m_pEntity->getPosition();
m_vDesiredVelocity.normalize();
m_vDesiredVelocity *= m_pVehicle->getMaxSpeed();
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
return m_vSteering;
}
Vector2f& Flee::Update()
{
m_pSteering->setTarget(m_target);
m_pSteering->setTargetOffset(Vector2f(0.f, 0.f));
m_vDesiredVelocity = m_pEntity->getPosition() - m_target->getPosition();
m_vDesiredVelocity.normalize();
m_vDesiredVelocity *= m_pVehicle->getMaxSpeed();
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
return m_vSteering;
}
Vector2f& Pursuit::Update()
{
Vector2f posToTarget = m_pEntity->getPosition() - m_target->getPosition();
float v = m_pVehicle->getVelocity().length();
float t = m_fTimeMax;
if (v != 0.f)
{
t = min(m_fTimeMax, posToTarget.length() / v);
}
m_pSteering->setTarget(m_target);
m_pSteering->setTargetOffset(m_target->getVelocity() * t);
m_vDesiredVelocity = (m_target->getPosition() + m_target->getVelocity() * t) - m_pEntity->getPosition();
m_vDesiredVelocity.normalize();
m_vDesiredVelocity *= m_pVehicle->getMaxSpeed();
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
return m_vSteering;
}
Vector2f& Evasion::Update()
{
Vector2f posToTarget = m_pEntity->getPosition() - m_target->getPosition();
float v = m_pVehicle->getVelocity().length();
float t = m_fTimeMax;
if (v != 0.f)
{
t = min(m_fTimeMax, posToTarget.length() / v);
}
m_pSteering->setTarget(m_target);
m_pSteering->setTargetOffset(m_target->getVelocity() * t);
m_vDesiredVelocity = m_pEntity->getPosition() - (m_target->getPosition() + m_target->getVelocity() * t);
m_vDesiredVelocity.normalize();
m_vDesiredVelocity *= m_pVehicle->getMaxSpeed();
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
return m_vSteering;
}
Vector2f& Arrival::Update()
{
m_pSteering->setTarget(m_target);
m_pSteering->setTargetOffset(Vector2f(0.f, 0.f));
m_vDesiredVelocity = m_target->getPosition() - m_pEntity->getPosition();
float distance = m_vDesiredVelocity.length();
float rampedSpeed = m_pVehicle->getMaxSpeed() * (distance / m_fSlowingDistance);
float clippedSpeed = min(rampedSpeed, m_pVehicle->getMaxSpeed());
m_vDesiredVelocity.normalize();
m_vDesiredVelocity *= clippedSpeed;
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
return m_vSteering;
}
Vector2f& Wander::Update()
{
Vector2f direction = m_pVehicle->getVelocity();
direction.normalize();
Vector2f center = direction * m_radius;
float value = (float)(rand() % 360);
Vector2f r(sin(value*PI / 180.0f) * m_littleRadius, cos(value*PI / 180.0f) * m_littleRadius);
m_vR += r;
m_vR.normalize();
m_vR *= m_radius;
m_vSteering = center + m_vR;
return m_vSteering;
}
PathFollowing::PathFollowing(
Entity* _Entity,
Entity* _Target,
float _fSpeed,
VectorVector2f* _vPath)
: Behavior(_Entity), m_pTarget(_Target), m_fSpeed(_fSpeed), m_vPath(_vPath)
{
m_fDistanceToP1 = 0.f;
m_iIndexNext = 0;
m_fDistanceFromP0 = 0.0f;
m_fDistanceToP1 = 0.f;
m_fDistanceP0P1 = 0.f;
p0 = p1 = nullptr;
}
Vector2f& PathFollowing::Update()
{
m_fDistanceFromP0 += m_fSpeed * (float)TimeManager::getSingleton()->getFrameTime().asSeconds();
while (m_fDistanceFromP0 > m_fDistanceP0P1)
{
m_iIndexNext++;
if (m_iIndexNext == m_vPath->size())
{
// No more points, stay on last
m_iIndexNext--;
m_fDistanceFromP0 = m_fDistanceP0P1;
}
else
{
// next point
m_fDistanceFromP0 -= m_fDistanceP0P1;
p0 = m_vPath->at(m_iIndexNext - 1);
p1 = m_vPath->at(m_iIndexNext);
Vector2f p0p1 = *p0 - *p1;
m_fDistanceP0P1 = p0p1.length();
}
}
Vector2f targetPosition = MathTools::lerp(*p0, *p1, m_fDistanceFromP0 / m_fDistanceP0P1);
m_pTarget->setPosition(targetPosition);
// Seek on target
m_vDesiredVelocity = targetPosition - m_pEntity->getPosition();
m_vDesiredVelocity.normalize();
m_vDesiredVelocity *= m_pVehicle->getMaxSpeed();
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
return m_vSteering;
}
Vector2f& UnalignedCollisionAvoidance::Update()
{
Vector2f nextPosition = m_pEntity->getFuturePosition(m_fFutureTime);
Vector2f nextPosition2, diff;
m_vSteering = Vector2f(0.f, 0.f);
for (std::vector<Entity*>::iterator i = m_entities->begin(); i != m_entities->end(); i++)
{
if ((*i) != m_pEntity)
{
nextPosition2 = (*i)->getFuturePosition(m_fFutureTime);
diff = nextPosition - nextPosition2;
if (diff.length() < m_radius)
{
diff.normalize();
m_vSteering += diff;
}
}
}
m_vSteering.normalize();
m_vSteering *= m_pVehicle->getMaxSpeed();
return m_vSteering;
}
Vector2f& ObstacleAvoidance::Update()
{
Vector2f position = m_pEntity->getPosition();
Vector2f look = m_pVehicle->getVelocity();
look.normalize();
Vector2f right(look.getY(), -look.getX());
float distance = INFINITY;
float fleeDirection;
MapStringCollider* pStaticColliders = PhysicsManager::getSingleton()->getStaticColliders();
for (MapStringCollider::iterator it = pStaticColliders->begin(); it != pStaticColliders->end(); ++it)
{
Collider* pCollider = (Collider*)(it->second);
EnumColliderType type = pCollider->getColliderType();
if (type == Collider_Circle)
{
CircleCollider* pCircleCollider = (CircleCollider*)pCollider;
Vector2f obstaclePosition = pCircleCollider->getWorldCenter();
float fRadius = pCircleCollider->getRadius();
Vector2f vPositionToObstacle = obstaclePosition - position;
float r = vPositionToObstacle.dot(look);
float s = vPositionToObstacle.dot(right);
float speedPercent = m_pVehicle->getVelocity().length() / m_pVehicle->getMaxSpeed();
if (r > 0 // Obstacle in front
&& r - fRadius < m_farView * speedPercent // Obstacle in farView
&& r + fRadius < distance // Closest Obstacle
&& s - fRadius < m_radius // Obstacle in radius (left)
&& s + fRadius > -m_radius) // Obstacle in radius (right)
{
distance = r - fRadius;
fleeDirection = s;
}
}
}
if (distance == INFINITY)
{
m_vSteering = Vector2f(0.f, 0.f);
}
else
{
right *= m_pVehicle->getMaxForce();
if (fleeDirection > 0)
{
m_vSteering = -right;
}
else
{
m_vSteering = right;
}
}
return m_vSteering;
}
Vector2f& Separation::Update()
{
Vector2f direction;
float distance;
m_vSteering = Vector2f(0.f, 0.f);
for (std::vector<Entity*>::iterator i = m_entities->begin(); i != m_entities->end(); i++)
{
if ((*i) != m_pEntity)
{
direction = m_pEntity->getPosition() - (*i)->getPosition();
distance = direction.length();
if (distance <= m_distanceMax && distance != 0.0f)
{
direction.normalize();
m_vSteering += direction * 1 / distance;
}
}
}
m_vSteering.normalize();
m_vSteering *= m_pVehicle->getMaxForce();
return m_vSteering;
}
Vector2f& Cohesion::Update()
{
Vector2f direction, center = Vector2f(0.f, 0.f);
float distance;
int nbNeighbors = 0;
for (std::vector<Entity*>::iterator i = m_entities->begin(); i != m_entities->end(); i++)
{
if ((*i) != m_pEntity)
{
direction = m_pEntity->getPosition() - (*i)->getPosition();
distance = direction.length();
if (distance <= m_distanceMax)
{
center += (*i)->getPosition();
nbNeighbors++;
}
}
}
if (nbNeighbors)
{
center /= (float)nbNeighbors;
m_vSteering = center - m_pEntity->getPosition();
}
return m_vSteering;
}
Vector2f& Alignment::Update()
{
Vector2f direction;
float distance;
int nbNeighbors = 0;
m_vDesiredVelocity = Vector2f(0.f, 0.f);
for (std::vector<Entity*>::iterator i = m_entities->begin(); i != m_entities->end(); i++)
{
if ((*i) != m_pEntity)
{
direction = m_pEntity->getPosition() - (*i)->getPosition();
distance = direction.length();
if (distance <= m_distanceMax)
{
m_vDesiredVelocity += (*i)->getComponent<Vehicle>()->getVelocity();
nbNeighbors++;
}
}
}
if (nbNeighbors)
{
m_vDesiredVelocity /= (float)nbNeighbors;
m_vSteering = m_vDesiredVelocity - m_pVehicle->getVelocity();
}
return m_vSteering;
}
Vector2f& LeadFollowing::Update()
{
return m_vSteering;
}
Vector2f& Swarming::Update()
{
return m_vSteering;
}
Vector2f& FormationV::Update()
{
Vector2f forward(1.0f, 0.0f);
Vector2f right(0.0f, 1.0f);
if (m_bUseLeaderOrientation)
{
forward = m_leader->getOrientation();
bool bCanNormalize = forward.normalize();
right = Vector2f(forward.getY(), -forward.getX());
}
// For V shapes, add 1 unit per line to have an odd number
if (m_angle != 0.f && m_nbInLine % 2 == 0)
{
m_nbInLine++;
}
// Use minimum between nbInLine and max units
if (m_nbInLine > m_maxId)
{
m_nbInLine = m_maxId;
}
int id = m_bLeaderInvisible ? m_id + 1 : m_id;
int idInLine = id % m_nbInLine;
int leftOrRight = (idInLine % 2) ? -1 : 1;
int idRight = leftOrRight * ((idInLine + 1) / 2);
int idBack = id / m_nbInLine;
float fX = idRight * m_distanceMax;
float fY = abs(fX) * (float)tan(m_angle) + idBack * m_distanceMax; // Fleche + recul
Vector2f arrivalOffset = right * fX - forward * fY;
Vector2f arrivalPos = m_leader->getPosition() + arrivalOffset;
//Arrival
Vector2f target_offset = arrivalPos - m_pEntity->getPosition();
float distance = target_offset.length();
float max_speed = m_pVehicle->getMaxSpeed();
float ramped_speed = max_speed * (distance / m_slowingDistance);
float clipped_speed = (ramped_speed < max_speed) ? ramped_speed : max_speed;
Vector2f desired_velocity = target_offset * (clipped_speed / distance);
m_vSteering = desired_velocity - m_pEntity->getVelocity();
return m_vSteering;
}
Vector2f& FormationCircle::Update()
{
Vector2f forward(1.0f, 0.0f);
Vector2f right(0.0f, 1.0f);
if (m_bUseLeaderOrientation)
{
forward = m_leader->getOrientation();
forward.normalize();
right = Vector2f(forward.getY(), -forward.getX());
}
int idInCircle = m_id % m_nbInCircle;
int iCircle = m_id / m_nbInCircle;
int idMax = (m_maxAngle - m_minAngle) == 360.0f ? m_nbInCircle : m_nbInCircle - 1;
float angle = MathTools::lerp(MathTools::degreetoradian(m_minAngle), MathTools::degreetoradian(m_maxAngle), ((float)(idInCircle) / (float)(idMax)));
float distanceToLeader = m_minRadius + iCircle * m_distanceMax;
float fX = sin(angle) * distanceToLeader;
float fY = cos(angle) * distanceToLeader;
Vector2f arrivalOffset = right * fX + forward * fY;
Vector2f arrivalPos = m_leader->getPosition() + arrivalOffset;
//Arrival
Vector2f target_offset = arrivalPos - m_pEntity->getPosition();
float distance = target_offset.length();
float max_speed = m_pVehicle->getMaxSpeed();
float ramped_speed = max_speed * (distance / m_slowingDistance);
float clipped_speed = (ramped_speed < max_speed) ? ramped_speed : max_speed;
Vector2f desired_velocity = target_offset * (clipped_speed / distance);
m_vSteering = desired_velocity - m_pEntity->getVelocity();
return m_vSteering;
}
}<file_sep>/***************************************************/
/* Nom: Color.h
/* Description: Color
/* Auteur: <NAME>
/***************************************************/
#ifndef _Color_H
#define _Color_H
namespace crea
{
class CREAENGINE_API Color
{
public:
unsigned char m_r;
unsigned char m_g;
unsigned char m_b;
unsigned char m_a;
// constants
const static Color black;
const static Color white;
const static Color red;
const static Color green;
const static Color blue;
const static Color yellow;
const static Color magenta;
const static Color cyan;
const static Color transparent;
const static Color grey;
const static Color orange;
Color();
Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a);
virtual ~Color() {};
// public methods
void setValues(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a);
string ToString() const;
float getR() { return m_r * ONEOVER255; }
float getG() { return m_g * ONEOVER255; }
float getB() { return m_b * ONEOVER255; }
float getA() { return m_a * ONEOVER255; }
// comparison operators
bool operator== (const Color& _right) const;
bool operator!= (const Color& _right) const;
};
} // namespace crea
#endif // _Color_H<file_sep>#include "stdafx.h"
#include "AI\Steering\Vehicle.h"
#include "AI\Steering\Steering.h"
#include "Core\GameManager.h"
namespace crea
{
Vehicle::Vehicle() :
m_mass(1.0f),
m_vVelocity(Vector2f(0.0f, 0.0f)),
m_maxForce(100.0f),
m_maxSpeed(100.0f),
m_lastForce(Vector2f(0.0f, 0.0f)),
m_lastR(Vector2f(1.0f, 0.0f))
{
m_bUpdatePosition = true;
}
Vehicle::~Vehicle()
{
}
bool Vehicle::loadFromFileJSON(const string& _filename)
{
Json::Value root;
std::ifstream config_doc(_filename, std::ifstream::binary);
config_doc >> root;
m_mass = root["Mass"].asFloat();
m_maxForce = root["MaxForce"].asFloat();
m_maxSpeed = root["MaxSpeed"].asFloat();
return true;
}
bool Vehicle::init()
{
// Get Steering
m_pSteering = m_pEntity->getComponent<Steering>();
return true;
}
bool Vehicle::update()
{
if (m_pSteering == nullptr)
{
m_pSteering = m_pEntity->getComponent<Steering>();
}
Vector2f VehicleSteering = m_pSteering->getSteeringDirection();
float frameTime = (float)TimeManager::getSingleton()->getFrameTime().asSeconds();
if (!MathTools::zeroByEpsilon(VehicleSteering.lengthSq()))
{
Vector2f VehicleForce = MathTools::truncate(VehicleSteering, m_maxForce);
Vector2f acceleration = VehicleForce / m_mass;
m_vVelocity = MathTools::truncate(m_vVelocity + acceleration * frameTime, m_maxSpeed);
m_lastForce = VehicleForce;
}
else
{
m_lastForce = Vector2f(0.0f, 0.0f);
}
if (m_bUpdatePosition)
{
Vector2f position = m_pEntity->getPosition();
position += m_vVelocity * frameTime;
m_pEntity->setPosition(position);
}
return true;
}
bool Vehicle::draw()
{
return true;
}
bool Vehicle::quit()
{
return true;
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: GL3Facade.h
/* Description: GL3Facade
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Facade_H
#define _GL3Facade_H
#include "Graphics\IFacade.h"
#include "Graphics\GL3Color.h"
namespace crea
{
class GL3Facade
{
GLFWwindow* window;
string m_szWindowTitle;
GL3Color m_ClearColor;
// window
IntRect m_rWindowRect;
// Keyboard
int keysMap[KeyCount];
// Mouse
int m_iMousePosX;
int m_iMousePosY;
bool m_bMouseLeftButtonDown;
bool m_bMouseRightButtonDown;
// Depth test
bool m_bDepthTest;
private:
// Données membres
GL3Facade();
void setMousePosition(int _iX, int _iY) { m_iMousePosX = _iX; m_iMousePosY = _iY; }
void setMouseButtonsDown(bool _bLeftButtonDown, bool _bRightButtonDown) { m_bMouseLeftButtonDown = _bLeftButtonDown; m_bMouseRightButtonDown = _bRightButtonDown; }
bool setCursor(bool _bVisible);
public:
~GL3Facade();
void setWindowSize(int _width, int _height);
unsigned int getWindowWidth() { return m_rWindowRect.m_iW; }
unsigned int getWindowHeight() { return m_rWindowRect.m_iH; }
float getWindowAspect() { return m_rWindowRect.m_iW / (float)m_rWindowRect.m_iH; }
inline void setWindowTitle(const string& _windowTitle) { m_szWindowTitle = _windowTitle; }
// Renvoie l'instance du renderer
static GL3Facade& Instance();
// Initialise le renderer
virtual void initialize();
// Boucle de rendu
virtual bool update();
// Démarre le rendu de la scène
virtual void beginScene() const;
// Rendu d'un objet
virtual void draw(IDrawable& _o) const;
// Termine le rendu de la scène
virtual void endScene() const;
// Quitte le renderer
virtual void quit();
virtual Font* createFont(Font* _pFrom = nullptr);
virtual void destroyFont(Font* _pFont);
virtual Texture* createTexture(Texture* _pFrom = nullptr);
virtual void destroyTexture(Texture* _pTexture);
virtual Color* createColor(Color* _pFrom = nullptr);
virtual void destroyColor(Color* _pColor);
virtual Text* createText(Text* _pFrom = nullptr);
virtual void destroyText(Text* _pText);
virtual Sprite* createSprite(Sprite* _pFrom = nullptr);
virtual void destroySprite(Sprite* _pSprite);
virtual Shape* createShape(string _szType, Shape* _pFrom = nullptr);
virtual void destroyShape(Shape* _pShape);
virtual Shader* createShader(Shader* _pFrom = nullptr);
virtual void destroyShader(Shader* _pShader);
virtual Material* createMaterial(Material* _pFrom = nullptr);
virtual void destroyMaterial(Material* _pMaterial);
virtual bool isKeyPressed(Key _key);
virtual bool isMouseButtonPressed(Button _button);
virtual Vector2f getMousePosition();
virtual IntRect& getWindowRect() { return m_rWindowRect; }
virtual void setWindowRect(IntRect _rect) { m_rWindowRect = _rect; }
// Activate/deactivate Depth testing for 3D rendering
void setDepthTest(bool _bDepthTest);
};
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double _xPos, double _yPos);
void scroll_callback(GLFWwindow* window, double _xOffset, double _yOffset);
} // namespace crea
#endif // _GL3Facade_H
<file_sep>/***************************************************/
/* Nom: DX9Sprite.h
/* Description: DX9Sprite
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Sprite_H
#define _DX9Sprite_H
#include "Graphics\Sprite.h"
namespace crea
{
class DX9Sprite : public Sprite
{
LPD3DXSPRITE m_pSprite;
LPDIRECT3DTEXTURE9 m_pTexture;
RECT *m_pRect;
D3DXVECTOR2 *m_pCenter;
float m_fRotation;
D3DXVECTOR2 *m_pScaleCenter;
D3DXVECTOR2 *m_pScale;
D3DXVECTOR2 m_Position;
D3DCOLOR m_color;
public:
DX9Sprite::DX9Sprite()
{
//init translation
m_Position.x = 0.0f;
m_Position.y = 0.0f;
//init rectangle
m_pRect = nullptr;
//init center
m_pCenter = nullptr;
//init de la rotation
m_fRotation = 0.0f;
//init du centre de scale
m_pScaleCenter = nullptr;
//init du scale
m_pScale = nullptr;
//init color
m_color = D3DCOLOR_XRGB(255, 255, 255);
//init pointeur texture
m_pTexture = nullptr;
//creation du sprite
if (FAILED(D3DXCreateSprite(DX9Facade::Instance().m_pDevice, &m_pSprite)))
{
OutputDebugString("Failed to create Sprite.\n");
}
}
virtual DX9Sprite::~DX9Sprite()
{
SafeDelete(m_pRect);
SafeDelete(m_pCenter);
SafeDelete(m_pScaleCenter);
SafeDelete(m_pScale);
SafeRelease(m_pTexture);
SafeRelease(m_pSprite);
}
// Build 2D transformation matrix in XY plane. NULL arguments are treated as identity.
// Mout = Morig-1 * Ms * Mt
D3DXMATRIX* myMatrixTransformation2D
(D3DXMATRIX *pOut,
CONST D3DXVECTOR2* pOrigin,
CONST D3DXVECTOR2* pScaling,
CONST D3DXVECTOR2* pTranslation)
{
D3DXMATRIX Morig, Ms, Mt;
D3DXMatrixIdentity(pOut);
if (pOrigin)
{
D3DXMatrixTranslation(&Morig, pOrigin->x, pOrigin->y, 0.0f);
float fDet = 0.f;
D3DXMatrixInverse(pOut, &fDet, &Morig);
}
if (pScaling)
{
D3DXMatrixScaling(&Ms, pScaling->x, pScaling->y, 1.0f);
D3DXMatrixMultiply(pOut, pOut, &Ms);
}
if (pTranslation)
{
//cout << pTranslation->x << " " << pTranslation->y << endl;
D3DXMatrixTranslation(&Mt, pTranslation->x, pTranslation->y, 0.0f);
D3DXMatrixMultiply(pOut, pOut, &Mt);
}
return pOut;
}
virtual void draw()
{
m_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
// Build our matrix to rotate, scale and position our sprite
D3DXMATRIX mat;
// out, scaling centre, scaling rotation, scaling, rotation centre, rotation, translation
myMatrixTransformation2D(&mat, m_pScaleCenter, m_pScale, &m_Position);
// Tell the sprite about the matrix
m_pSprite->SetTransform(&mat);
// Draw the sprite
m_pSprite->Draw(m_pTexture, m_pRect, NULL, NULL, m_color);
// Thats it
m_pSprite->End();
}
virtual void setTexture(Texture* _pTexture)
{
DX9Texture* pTexture = (DX9Texture*)_pTexture;
m_pTexture = (LPDIRECT3DTEXTURE9)pTexture->getTexture();
}
virtual void setPosition(float _x, float _y)
{
m_Position.x = _x;
m_Position.y = _y;
}
virtual void setTextureRect(int _x, int _y, int _w, int _h)
{
if (!m_pRect)
m_pRect = new RECT();
m_pRect->left = _x;
m_pRect->top = _y;
m_pRect->bottom = _y + _h;
m_pRect->right = _x + _w;
}
virtual void setScale(float _x, float _y)
{
if (!m_pScale)
m_pScale = new D3DXVECTOR2();
m_pScale->x = _x;
m_pScale->y = _y;
}
virtual void setOrigin(float _x, float _y)
{
if (!m_pScaleCenter)
m_pScaleCenter = new D3DXVECTOR2(); // CB: why do we need (0,0), not nothing, nor (36, 36) in DirectX?
m_pScaleCenter->x = _x;
m_pScaleCenter->y = _y;
}
virtual Sprite* clone()
{
return new DX9Sprite(*this);
}
};
} // namespace crea
#endif // _DX9Sprite_H
<file_sep>/***************************************************/
/* Nom: Entity.h
/* Description: Entity
/* Auteur: <NAME>
/***************************************************/
#ifndef __Entity_H_
#define __Entity_H_
#include "Core\Transformable.h"
#include <list>
namespace crea
{
class Component;
class CREAENGINE_API Entity : public Transformable // Every entity is transformable
{
// Name
string m_szName;
objectID m_ID;
// Composite
Entity* m_pParent;
list<Entity*> m_pChildren;
// Composition
list<Component*> m_pComponents;
// Selection
bool m_bSelected;
public:
Entity();
Entity(Entity& _entity);
virtual ~Entity();
inline bool hasName(const string& _szName) { return (m_szName == _szName); }
inline void setName(const string& _szName) { m_szName = _szName; }
inline string& getName() { return m_szName; }
void SetID(objectID _id) { m_ID = _id; }
objectID GetID() { return m_ID; }
inline void setParent(Entity* _pEntity) { m_pParent = _pEntity; }
Entity* getEntity(const string& _szName);
Entity* getEntity(Entity* _pEntity);
bool removeEntity(Entity* _pEntity);
void addChild(Entity* _pEntity);
void removeChild(Entity* _pEntity);
void addComponent(Component* _pComponent);
void removeComponent(Component* _pComponent);
bool haveComponent(Component* _pComponent);
template<class T> T* getComponent();
template<class T> void getComponents(list<T*>& _v);
void selectEntities(FloatRect& _rect);
void unselectEntities();
bool getSelected() { return m_bSelected; }
bool loadFromFileJSON(const string& _filename);
bool init();
bool update();
bool draw();
void clear();
Entity* clone() { return new Entity(*this); }
void cloneComponents(Entity* _pEntity)
{
for (list<Component*>::iterator it = _pEntity->m_pComponents.begin(); it != _pEntity->m_pComponents.end(); ++it)
{
Component* pComponent = *it;
Component* pClonedComponent = pComponent->clone();
m_pComponents.push_back(pClonedComponent);
pClonedComponent->setEntity(this);
}
}
};
template<class T> T* Entity::getComponent()
{
for (list<Component*>::iterator it = m_pComponents.begin(); it != m_pComponents.end(); ++it)
{
Component* pComponent = *it;
T* ptr = dynamic_cast<T*>(pComponent);
if (ptr != nullptr)
{
return ptr;
}
else
{
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->getComponent<T>();
}
}
}
return nullptr;
}
template<class T> void Entity::getComponents(list<T*>& _l)
{
for (list<Component*>::iterator it = m_pComponents.begin(); it != m_pComponents.end(); ++it)
{
Component* pComponent = *it;
T* ptr = dynamic_cast<T*>(pComponent);
if (ptr != nullptr)
{
_l.push_back(ptr);
}
else
{
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->getComponents<T>(_l);
}
}
}
return;
}
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Scene\SceneSteering.h"
#include "Scene\SceneMenu.h"
#include "Scene\SceneGame.h"
#include "Scene\SceneMap.h"
#include "AI\Steering\Behavior.h"
#include <string>
SceneSteering::SceneSteering()
{
// AI Tools
m_bUseAITools = true;
m_pAITools = new AITools();
}
SceneSteering::~SceneSteering()
{
// AI Tools
delete m_pAITools;
}
bool SceneSteering::onInit()
{
m_pGM = GameManager::getSingleton();
m_rWindowRect = m_pGM->getWindowRect();
// Set Script factory
m_pCellsScriptFactory = new CellsScriptFactory;
m_pGM->setScriptFactory(m_pCellsScriptFactory);
// Load Map
m_pEntity3 = m_pGM->getEntity("MapSteering");
m_pGM->addEntity(m_pEntity3);
m_pMap = m_pGM->getMap("MapSteering.json"); // CB: TO CHANGE: Map id loaded after entity added to display Map first (order in tree matters)
m_pMap->loadFromFileJSON(string(DATAMAPPATH) + "MapSteering.json");
m_pMapRenderer = m_pGM->getMapRenderer("MapRenderer1");
m_pMapRenderer->setMap(m_pMap);
m_pEntity3->addComponent(m_pMapRenderer);
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onInit();
}
// Mouse Entity
m_pMouse = m_pGM->getEntity("mouse");
// Add it to root
m_pGM->addEntity(m_pMouse, nullptr);
// Target Entity
m_pTarget = m_pGM->getEntity("target");
// Add it to root
m_pGM->addEntity(m_pTarget, nullptr);
// Text
Color* pRed = m_pGM->getColor("Red");
pRed->setValues(255, 0, 0, 255);
m_pTextFPS = m_pGM->getText("fps");
m_pTextFPS->setFont(m_pGM->getFont("arial.ttf"));
m_pTextFPS->setColor(pRed);
m_pTextFPS->setCharacterSize(20);
m_pTextFPS->setString("fps");
TextRenderer* pTextRenderer = m_pGM->getTextRenderer("TextRenderer1");
pTextRenderer->setText(m_pTextFPS);
Entity* pEntityFPS = m_pGM->getEntity("text 1");
pEntityFPS->addComponent(pTextRenderer);
pEntityFPS->setPosition(Vector2f(1100, 0));
m_pGM->addEntity(pEntityFPS);
Entity* pEntityObstacle = m_pGM->getEntity("panel1");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("plant1");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("plant2");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("plant3");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("rock1");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("cactus1");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("hq1");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
pEntityObstacle = m_pGM->getEntity("mine1");
m_vObstacles.push_back(pEntityObstacle);
m_vPath.push_back(&pEntityObstacle->getPosition());
// n entity
m_iNbEntities = 2;
m_bKeyPressedAdd = false;
m_bKeyPressedSub = false;
// Steering mode
m_pTextSteeringMode = m_pGM->getText("steering");
m_pTextSteeringMode->setFont(m_pGM->getFont("arial.ttf"));
m_pTextSteeringMode->setColor(pRed);
m_pTextSteeringMode->setCharacterSize(20);
m_pTextSteeringMode->setString("steering mode");
TextRenderer* pTextRendererSteering = m_pGM->getTextRenderer("TextRenderer steering");
pTextRendererSteering->setText(m_pTextSteeringMode);
Entity* pEntitySteering = m_pGM->getEntity("text steering mode");
pEntitySteering->addComponent(pTextRendererSteering);
pEntitySteering->setPosition(Vector2f(0, 0));
m_pGM->addEntity(pEntitySteering);
m_iSteeringMode = 0;
m_pTextSteeringMode->setString("Seek/Flee");
createEntities();
setBehavior();
// FPS
Time frameTime = TimeManager::getSingleton()->getFrameTime();
m_pTextFPS->setString(to_string((int)(1 / frameTime.asSeconds())) + " fps");
m_pBalista = m_pGM->getEntity("balista1");
Steering* pSteeringBalista = m_pBalista->getComponent<Steering>();
pSteeringBalista->init();
pSteeringBalista->clearBehaviors();
pSteeringBalista->addBehavior(new Arrival(m_pBalista, m_pMouse, 100.0f), 1.0f);
pSteeringBalista->addBehavior(new ObstacleAvoidance(m_pBalista, 32.f, 100.f, &m_vObstacles), 1.0f);
return true;
}
bool SceneSteering::onUpdate()
{
m_pMouse->setPosition(InputManager::getSingleton()->getMousePosition());
// entities leaving the window
for (int i = 0; i < m_iNbEntities; i++)
{
Entity* pEntity = m_vEntities[i];
Vector2f vPos = pEntity->getPosition();
if (vPos.getX() < 0.f)
{
vPos.setX(900.f);
pEntity->setPosition(vPos);
}
else if (vPos.getX() > 900)
{
vPos.setX(0.f);
pEntity->setPosition(vPos);
}
if (vPos.getY() < 0.f)
{
vPos.setY((float)m_rWindowRect.getHeight());
pEntity->setPosition(vPos);
}
else if (vPos.getY() > m_rWindowRect.getHeight())
{
vPos.setY((float)0);
pEntity->setPosition(vPos);
}
}
if (m_pGM->isKeyPressed(Key::Num1))
{
m_pGM->setScene(new SceneMenu());
return true;
}
if (m_pGM->isKeyPressed(Key::Num2))
{
m_pGM->setScene(new SceneGame());
return true;
}
if (m_pGM->isKeyPressed(Key::Num3))
{
m_pGM->setScene(new SceneMap());
return true;
}
// Steering mode
if (m_pGM->isKeyPressed(Key::Numpad0))
{
m_iSteeringMode = 0;
m_pTextSteeringMode->setString("Seek/Flee");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad1))
{
m_iSteeringMode = 1;
m_pTextSteeringMode->setString("Pursuit/Evasion");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad2))
{
m_iSteeringMode = 2;
m_pTextSteeringMode->setString("Arrival");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad3))
{
m_iSteeringMode = 3;
m_pTextSteeringMode->setString("Wander");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad4))
{
m_iSteeringMode = 4;
m_pTextSteeringMode->setString("Pathfinding");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad5))
{
m_iSteeringMode = 5;
m_pTextSteeringMode->setString("Unaligned Collision Avoidance");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad6))
{
m_iSteeringMode = 6;
m_pTextSteeringMode->setString("Obstacle Avoidance");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad7))
{
m_iSteeringMode = 7;
m_pTextSteeringMode->setString("Separation");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad8))
{
m_iSteeringMode = 8;
m_pTextSteeringMode->setString("Cohesion");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::Numpad9))
{
m_iSteeringMode = 9;
m_pTextSteeringMode->setString("Alignment");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::F1))
{
m_iSteeringMode = 10;
m_pTextSteeringMode->setString("Formation L");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::F2))
{
m_iSteeringMode = 11;
m_pTextSteeringMode->setString("Formation V");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::F3))
{
m_iSteeringMode = 12;
m_pTextSteeringMode->setString("Formation Circle");
setBehavior();
}
if (m_pGM->isKeyPressed(Key::F4))
{
m_iSteeringMode = 13;
m_pTextSteeringMode->setString("Formation of formation");
setBehavior();
}
// Entities
if (m_pGM->isKeyPressed(Key::Add))
{
if (!m_bKeyPressedAdd && m_iNbEntities < 100)
{
m_pGM->unselectEntities();
deleteEntities();
m_iNbEntities += 10;
createEntities();
setBehavior();
}
m_bKeyPressedAdd = true;
}
else
{
m_bKeyPressedAdd = false;
}
if (m_pGM->isKeyPressed(Key::Subtract))
{
if (!m_bKeyPressedSub && m_iNbEntities > 10)
{
m_pGM->unselectEntities();
deleteEntities();
m_iNbEntities -= 10;
createEntities();
setBehavior();
}
m_bKeyPressedSub = true;
}
else
{
m_bKeyPressedSub = false;
}
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onUpdate();
}
return true;
}
bool SceneSteering::onDraw()
{
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onDraw();
}
return true;
}
bool SceneSteering::onQuit()
{
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onQuit();
}
m_pGM->clearAllData();
m_pGM->clearAllEntities();
delete m_pCellsScriptFactory;
return true;
}
void SceneSteering::deleteEntities()
{
for (int i = 0; i < m_iNbEntities; i++)
{
m_pGM->clearEntity(m_vEntities[i]);
}
m_vEntities.clear();
}
void SceneSteering::createEntities()
{
Entity* pEntityBase = m_pGM->getEntity("peonSteering");
Entity* pEntityCell1 = nullptr;
for (int i = 0; i < m_iNbEntities; i++)
{
std::string s = std::to_string(i);
pEntityCell1 = m_pGM->instanciate(s, pEntityBase);
m_pGM->addEntity(pEntityCell1);
m_vEntities.push_back(pEntityCell1); // Keep pointers on entities
// Position random
int x = rand() % 900;
int y = rand() % m_rWindowRect.getHeight();
pEntityCell1->setPosition(Vector2f((float)x, (float)y));
// Motion random
Vector2f dir((float)(rand() % 100), (float)(rand() % 100));
CharacterController* pCC = pEntityCell1->getComponent<CharacterController>();
pCC->move(dir);
pCC->setDirection(dir);
}
}
void SceneSteering::setBehavior()
{
for (int i = 0; i < m_iNbEntities; i++)
{
std::string s = std::to_string(i);
Steering* pSteering = m_vEntities[i]->getComponent<Steering>();
pSteering->init();
pSteering->clearBehaviors();
// Behavior
switch (m_iSteeringMode)
{
case 0:
if (i % 2 == 0) pSteering->addBehavior(new Seek(m_vEntities[i], m_pMouse), 1.0f);
else pSteering->addBehavior(new Flee(m_vEntities[i], m_pMouse), 1.0f);
break;
case 1:
if (i % 2 == 0) pSteering->addBehavior(new Pursuit(m_vEntities[i], m_pBalista, 1.0f), 1.0f);
else pSteering->addBehavior(new Evasion(m_vEntities[i], m_pBalista, 1.f), 1.0f);
break;
case 2: pSteering->addBehavior(new Arrival(m_vEntities[i], m_pMouse, 200.0f), 1.0f);
break;
case 3: pSteering->addBehavior(new Wander(m_vEntities[i], 100.f, 50.f, 10.0f), 1.0f);
break;
case 4: pSteering->addBehavior(new PathFollowing(m_vEntities[i], m_pTarget, 100.f, &m_vPath), 1.0f);
break;
case 5: pSteering->addBehavior(new UnalignedCollisionAvoidance(m_vEntities[i], 60.f, 1.0f, &m_vEntities), 1.0f);
break;
case 6:
pSteering->addBehavior(new ObstacleAvoidance(m_vEntities[i], 32.f, 100.f, &m_vObstacles), 1.0f);
break;
case 7:
pSteering->addBehavior(new Separation(m_vEntities[i], 60.f, &m_vEntities), 1.0f);
break;
case 8:
pSteering->addBehavior(new Cohesion(m_vEntities[i], 60.f, &m_vEntities), 1.0f);
break;
case 9:
pSteering->addBehavior(new Alignment(m_vEntities[i], 60.f, &m_vEntities), 1.0f);
break;
case 10:
pSteering->addBehavior(new FormationV(m_vEntities[i], m_pBalista, false, 10, i, m_iNbEntities, 60.0f, 100.0f, 0.0f), 1.0f);
break;
case 11:
pSteering->addBehavior(new FormationV(m_vEntities[i], m_pBalista, true, 10, i, m_iNbEntities, 60.0f, 100.0f, MathTools::degreetoradian(45.0f)), 1.0f);
break;
case 12:
pSteering->addBehavior(new FormationCircle(m_vEntities[i], m_pBalista, true, 10, i, m_iNbEntities, 60.0f, 100.0f, -180.0f, 180.0f, 60.0f), 1.0f);
break;
case 13:
if (i >= 23)
{
pSteering->addBehavior(new FormationCircle(m_vEntities[i], m_vEntities[2], false, 10, i - 23, 10, 60.0f, 100.0f, 0.0f, 360.0f, 60.0f), 1.f);
}
else if (i >= 13)
{
pSteering->addBehavior(new FormationCircle(m_vEntities[i], m_vEntities[1], false, 10, i - 13, 10, 60.0f, 100.0f, 0.0f, 360.0f, 60.0f), 1.f);
}
else if (i >= 3)
{
pSteering->addBehavior(new FormationCircle(m_vEntities[i], m_vEntities[0], false, 10, i - 3, 10, 60.0f, 100.0f, 0.0f, 360.0f, 60.0f), 1.f);
}
else
{
pSteering->addBehavior(new FormationV(m_vEntities[i], m_pBalista, false, 10, i, 3, 200.0f, 100.0f, MathTools::degreetoradian(-45.0f)), 1.f);
}
break;
}
}
}<file_sep>/**
* Header Material
*
* @author cbruneau
* @since 09/10/2019
* @version 2.0
*/
#ifndef GL3Material_H
#define GL3Material_H
#include "Graphics\Material.h"
namespace crea
{
class Shape;
class Texture;
class Entity;
struct TextureInfo
{
string name;
Texture* texture;
unsigned int id;
};
struct ColorUniform
{
string uniform;
Color color;
};
struct FloatUniform
{
string uniform;
float value;
};
struct MaterialInfo
{
ColorUniform ambient;
ColorUniform diffuse;
ColorUniform specular;
FloatUniform shininess;
};
struct AttenuationInfo
{
string constant;
string linear;
string quadratic;
};
struct CutOffInfo
{
string inner;
string outer;
};
struct LightInfo
{
string type;
string position;
string direction;
string ambient;
string diffuse;
string specular;
AttenuationInfo attenuation;
CutOffInfo cutOff;
};
struct LightsInfo
{
string nbDirLights;
string nbPointLights;
string nbSpotLights;
};
struct CameraInfo
{
string position;
string view;
string projection;
string normalMatrix;
};
struct ModelInfo
{
string model;
string normalMatrix;
};
class GL3Material : public Material
{
protected:
string m_szName;
bool m_bUseColor;
map<unsigned int, TextureInfo> m_textures;
string m_propertyTransform;
// MVP
string m_propertyModel;
string m_propertyView;
string m_propertyProjection;
// Material
MaterialInfo m_materialInfo;
bool m_bUseMaterialInfo = false;
// Light
map<unsigned int, LightInfo> m_lightInfos;
LightsInfo m_lightsInfo;
unsigned int m_nbDefaultLights = 0;
unsigned int m_nbDirLights = 0;
unsigned int m_nbPointLights = 0;
unsigned int m_nbSpotLights = 0;
bool m_bUseLightInfo = false;
// Camera
CameraInfo m_cameraInfo;
bool m_bUseCameraInfo = false;
// Model
ModelInfo m_modelInfo;
bool m_bUseModelInfo = false;
// Time
string m_time;
bool m_bUseTime = false;
public:
GL3Material();
virtual ~GL3Material();
virtual void setTexture(unsigned int _index, const string& _propertyName, Texture* _pTexture)
{
TextureInfo t;
t.texture = _pTexture;
t.name = _propertyName;
t.id = _index;
// Add to map
m_textures[_index] = t;
}
virtual Texture* getTexture(unsigned int _index) { return m_textures[_index].texture; }
virtual void setLightInfo(unsigned int _index, LightInfo _lightInfo)
{
// Add to map
m_lightInfos[_index] = _lightInfo;
}
virtual LightInfo getLightInfo(unsigned int _index) { return m_lightInfos[_index]; }
virtual bool loadFromFile(const string& _name);
virtual Asset* clone();
// apply the Material to a Shape
virtual bool applyShaderToShape(Shape* _pShape);
// use the Material
virtual void use(Entity* _pEntity = nullptr);
// unuse the Material
virtual void unuse();
};
}
#endif //GL3Material_H
<file_sep>/***************************************************/
/* Nom: SFMLLine.h
/* Description: SFMLLine
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLLine_H
#define _SFMLLine_H
#include "Graphics\Shape.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLLine : public LineShape
{
public:
sf::Vertex m_line[2];
virtual void draw()
{
sf::RenderWindow* pWin = SFMLFacade::Instance().m_pWindow;
pWin->draw(m_line, 2, sf::Lines);
}
virtual void setLine(float _x1, float _y1, float _x2, float _y2)
{
m_line[0].position = sf::Vector2f(_x1, _y1);
m_line[1].position = sf::Vector2f(_x2, _y2);
}
virtual void setColor(int _r, int _g, int _b, int _a)
{
m_line[0].color = m_line[1].color = sf::Color(_r, _g, _b, _a);
}
};
} // namespace crea
#endif // _SFMLLine_H<file_sep>/***************************************************/
/* Nom: SceneSteering.h
/* Description: SceneSteering
/* Auteur: <NAME>
/***************************************************/
#ifndef __SceneSteering_H_
#define __SceneSteering_H_
#include "Core\Scene.h"
#include "Tools\AITools.h"
#include "Scripts\CellsScriptFactory.h"
using namespace crea;
class SceneSteering : public Scene
{
GameManager* m_pGM;
IntRect m_rWindowRect;
Text* m_pTextFPS;
Clock frameClock;
Text* m_pTextSteeringMode;
int m_iSteeringMode;
// Steering
Entity* m_pEntity3;
Map* m_pMap;
MapRenderer* m_pMapRenderer;
// Entitites
int m_iNbEntities;
vector<Entity*> m_vEntities;
bool m_bKeyPressedAdd;
bool m_bKeyPressedSub;
// AI Tools
bool m_bUseAITools;
AITools* m_pAITools;
// Scripts
CellsScriptFactory* m_pCellsScriptFactory;
Entity* m_pMouse;
Entity* m_pTarget; // Used to target destination
Entity* m_pPeon;
Entity* m_pBalista;
// Obstacles
vector<Entity*> m_vObstacles;
VectorVector2f m_vPath;
public:
SceneSteering();
virtual ~SceneSteering();
virtual bool onInit();
virtual bool onUpdate();
virtual bool onDraw();
virtual bool onQuit();
void deleteEntities();
void createEntities();
void setBehavior();
};
#endif
<file_sep>/***************************************************/
/* Nom: Scene.h
/* Description: Scene
/* Auteur: <NAME>
/***************************************************/
#ifndef __Scene_H_
#define __Scene_H_
namespace crea
{
class CREAENGINE_API Scene
{
public:
Scene();
virtual ~Scene();
virtual bool onInit() = 0;
virtual bool onUpdate() = 0;
virtual bool onDraw() = 0;
virtual bool onQuit() = 0;
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: Node.h
/* Description: Node
/* Auteur: <NAME>
/***************************************************/
#ifndef __Node_H_
#define __Node_H_
#include <vector>
#include <map>
namespace crea
{
class CREAENGINE_API Node
{
// TileId
short m_nTileTerrainId;
short m_nTileCollisionId;
// TileIds Key: 0: Capability0, etc.
map<short, short> m_nTileCapabilityIds;
// Position
short m_nX;
short m_nY;
// Neighbors
vector<Node*> m_pChildren;
public:
Node();
Node(short _nX, short _nY) { m_nX = _nX; m_nY = _nY; }
virtual ~Node();
inline void setX(short _nX) { m_nX = _nX; }
inline short getX() { return m_nX; }
inline void setY(short _nY) { m_nY = _nY; }
inline short getY() { return m_nY; }
inline void setTileTerrainId(short _nTileTerrainId) { m_nTileTerrainId = _nTileTerrainId; }
inline short getTileTerrainId() { return m_nTileTerrainId; }
inline void setTileCollisionId(short _nTileCollisionId) { m_nTileCollisionId = _nTileCollisionId; }
inline short getTileCollisionId() { return m_nTileCollisionId; }
inline void setTileClearanceId(short _nTileClearanceId, short _nCapability) { m_nTileCapabilityIds[_nCapability] = _nTileClearanceId; }
inline short getTileClearanceId(short _nCapability) { return m_nTileCapabilityIds.find(_nCapability)->second; }
double getDistance(Node* _pNode) { short dx = m_nX - _pNode->getX(); short dy = m_nY - _pNode->getY(); return sqrt(dx*dx + dy * dy); }
void addChild(Node* _pNode);
bool update();
bool draw();
void clear();
};
} // namespace crea
#endif
<file_sep>// Portions Copyright (C) <NAME>, 2001
#include "stdafx.h"
#include "Core\MsgManager.h"
#include "Core\TimeManager.h"
namespace crea
{
MsgManager::MsgManager(void)
{
}
MsgManager::~MsgManager(void)
{
}
void MsgManager::update()
{
deliverDelayedMessages();
}
void MsgManager::sendMsg(float delay, int name, objectID sender, objectID receiver, int state, void* data)
{
if (delay <= 0.0f)
{ //Deliver immediately
Msg msg((float)g_time->getGameTime().asSeconds(), name, sender, receiver, state);
msg.SetMsgData(data);
routeMsg(msg);
}
else
{ //Check for duplicates - then store
MessageContainer::iterator i;
for (i = m_delayedMessages.begin(); i != m_delayedMessages.end(); ++i)
{
if ((*i)->IsDelivered() == false &&
(*i)->GetMsgName() == name &&
(*i)->GetReceiver() == receiver &&
(*i)->GetSender() == sender &&
(*i)->GetMsgState() == state)
{ //Already in list - don't add
return;
}
}
//Store in delivery list
float deliveryTime = delay + (float)g_time->getGameTime().asSeconds();
Msg * msg = new Msg(deliveryTime, name, sender, receiver, state);
msg->SetMsgData(data);
m_delayedMessages.push_back(msg);
}
}
void MsgManager::deliverDelayedMessages(void)
{
MessageContainer::iterator i;
for (i = m_delayedMessages.begin(); i != m_delayedMessages.end();)
{
float dtime = (*i)->GetDeliveryTime();
float ctime = (float)g_time->getGameTime().asSeconds();
if ((*i)->GetDeliveryTime() <= (float)g_time->getGameTime().asSeconds())
{ //Deliver and delete msg
Msg * msg = *i;
routeMsg(*msg);
delete(msg);
i = m_delayedMessages.erase(i);
}
if (i != m_delayedMessages.end())
i++;
}
}
void MsgManager::routeMsg(Msg & msg)
{
Entity* object = g_entitymanager->Find(msg.GetReceiver());
if (object != 0)
{
// deliver to all FSMs
list<StateMachine*> FSMs;
object->getComponents<StateMachine>(FSMs);
for (list<StateMachine*>::iterator it = FSMs.begin(); it != FSMs.end(); ++it)
{
StateMachine* pFSM = *it;
if (object->haveComponent(pFSM) // Make sure the FSM was not removed by previous FSM message...
&& msg.GetMsgState() < 0 ||
msg.GetMsgState() == pFSM->GetState())
{ //Scene was irrelevant or current state matches msg state (for msg scoping)
msg.SetDelivered(true);
pFSM->Process(EVENT_Message, &msg);
}
}
}
}
}
<file_sep>#include "stdafx.h"
#include "AI\Agent.h"
#include "Core\GameManager.h"
namespace crea
{
Agent::Agent() : m_iStrength(10), m_iDexterity(10), m_iIntelligence(10), m_iHealth(10)
{
}
Agent::~Agent()
{
}
bool Agent::loadFromFileJSON(const string&_filename)
{
Json::Value root;
std::ifstream config_doc(_filename, std::ifstream::binary);
config_doc >> root;
m_iStrength = root["Strength"].asInt();
m_iDexterity = root["Dexterity"].asInt();
m_iIntelligence = root["Intelligence"].asInt();
m_iHealth = root["Health"].asInt();
m_nSize = (short)root["Size"].asInt();
m_nCapability = (short)root["Capability"].asInt();
return true;
}
bool Agent::init()
{
return true;
}
bool Agent::update()
{
return true;
}
bool Agent::draw()
{
return true;
}
bool Agent::quit()
{
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Graphics\GL3Material.h"
namespace crea
{
GL3Material::GL3Material()
{
m_pShader = nullptr;
m_pColor = nullptr;
m_bUseColor = false;
}
GL3Material::~GL3Material()
{
if (m_pShader)
{
m_pShader->use();
if (!m_textures.empty())
{
for (unsigned int i = 0; i < m_textures.size(); ++i)
{
m_textures[i].texture->unbind(i);
}
}
m_pShader->unuse();
}
}
bool GL3Material::loadFromFile(const string& _name)
{
Json::Value root;
std::ifstream matFile(_name, std::ifstream::binary);
if (matFile.fail())
{
cerr << _name << " could not be found." << endl;
return false;
}
m_szName = _name;
matFile >> root;
matFile.close();
GameManager* pGM = GameManager::getSingleton();
// Shader
string szShader = root["shader"].asString();
if (!szShader.empty())
{
m_pShader = pGM->getShader(szShader);
}
// Color
Json::Value matColor = root["color"];
if (!matColor.isNull())
{
m_bUseColor = true;
m_pColor = new GL3Color(matColor["r"].asInt(), matColor["g"].asInt(), matColor["b"].asInt(), matColor["a"].asInt());
}
else
{
m_bUseColor = false;
}
// Textures
Json::Value matTextures = root["textures"];
if (!matTextures.isNull())
{
for (unsigned int i = 0; i < matTextures.size(); ++i)
{
Json::Value matTexture = matTextures[i];
Texture* texture = pGM->getTexture(matTexture["texture"].asString());
if (texture)
{
setTexture(matTexture["index"].asInt(), matTexture["propertyName"].asString(), texture);
Json::Value matTextureTransparency = matTexture["transparency"];
if (!matTextureTransparency.isNull())
{
texture->setTransparency(matTextureTransparency.asBool());
}
}
else
{
cerr << "No texture " << matTexture["texture"].asString() << " to set for material " << _name << endl;
}
}
}
// Transform
string szTransform = root["transform"].asString();
if (!szTransform.empty())
{
m_propertyTransform = szTransform;
}
// Model View Projection
string szModel = root["model"].asString();
if (!szModel.empty())
{
m_propertyModel = szModel;
}
string szView = root["view"].asString();
if (!szView.empty())
{
m_propertyView = szView;
}
string szProjection = root["projection"].asString();
if (!szProjection.empty())
{
m_propertyProjection = szProjection;
}
// MaterialInfo
Json::Value valueMaterialInfo = root["materialInfo"];
if (!valueMaterialInfo.isNull())
{
Json::Value ambientMaterial = valueMaterialInfo["ambient"];
if (!ambientMaterial.isNull())
{
m_materialInfo.ambient.uniform = ambientMaterial["uniform"].asString();
m_materialInfo.ambient.color = Color(ambientMaterial["r"].asInt(), ambientMaterial["g"].asInt(), ambientMaterial["b"].asInt(), 255);
}
Json::Value diffuseMaterial = valueMaterialInfo["diffuse"];
if (!diffuseMaterial.isNull())
{
m_materialInfo.diffuse.uniform = diffuseMaterial["uniform"].asString();
m_materialInfo.diffuse.color = Color(diffuseMaterial["r"].asInt(), diffuseMaterial["g"].asInt(), diffuseMaterial["b"].asInt(), 255);
}
Json::Value specularMaterial = valueMaterialInfo["specular"];
if (!specularMaterial.isNull())
{
m_materialInfo.specular.uniform = specularMaterial["uniform"].asString();
m_materialInfo.specular.color = Color(specularMaterial["r"].asInt(), specularMaterial["g"].asInt(), specularMaterial["b"].asInt(), 255);
}
Json::Value shininessMaterial = valueMaterialInfo["shininess"];
if (!shininessMaterial.isNull())
{
m_materialInfo.shininess.uniform = shininessMaterial["uniform"].asString();
m_materialInfo.shininess.value = shininessMaterial["value"].asFloat();
}
m_bUseMaterialInfo = true;
}
// LightsInfo
Json::Value valueLightsInfo = root["lightsInfo"];
if (!valueLightsInfo.isNull())
{
string szNbDirLights = valueLightsInfo["nbDirLights"].asString();
if (!szNbDirLights.empty())
{
m_lightsInfo.nbDirLights = szNbDirLights;
}
string szNbPointLights = valueLightsInfo["nbPointLights"].asString();
if (!szNbPointLights.empty())
{
m_lightsInfo.nbPointLights = szNbPointLights;
}
string szNbSpotLights = valueLightsInfo["nbSpotLights"].asString();
if (!szNbSpotLights.empty())
{
m_lightsInfo.nbSpotLights = szNbSpotLights;
}
m_nbDefaultLights = 0;
m_nbDirLights = 0;
m_nbPointLights = 0;
m_nbSpotLights = 0;
Json::Value lights = valueLightsInfo["lights"];
for (unsigned int i = 0; i < lights.size(); ++i)
{
Json::Value valueLightInfo = lights[i];
LightInfo lightInfo;
lightInfo.type = valueLightInfo["type"].asString();
lightInfo.ambient = valueLightInfo["ambient"].asString();
lightInfo.diffuse = valueLightInfo["diffuse"].asString();
lightInfo.specular = valueLightInfo["specular"].asString();
// None
if (lightInfo.type == "DEFAULTLIGHT")
{
m_nbDefaultLights++;
lightInfo.position = valueLightInfo["position"].asString();
}
// DirLight
if (lightInfo.type == "DIRLIGHT")
{
m_nbDirLights++;
lightInfo.direction = valueLightInfo["direction"].asString();
}
// Pointlight
if (lightInfo.type == "POINTLIGHT")
{
m_nbPointLights++;
lightInfo.position = valueLightInfo["position"].asString();
string szConstant = valueLightInfo["constant"].asString();
if (!szConstant.empty())
{
lightInfo.attenuation.constant = szConstant;
}
string szLinear = valueLightInfo["linear"].asString();
if (!szLinear.empty())
{
lightInfo.attenuation.linear = szLinear;
}
string szQuadratic = valueLightInfo["quadratic"].asString();
if (!szQuadratic.empty())
{
lightInfo.attenuation.quadratic = szQuadratic;
}
}
// Spotlight
if (lightInfo.type == "SPOTLIGHT")
{
m_nbSpotLights++;
lightInfo.position = valueLightInfo["position"].asString();
lightInfo.direction = valueLightInfo["direction"].asString();
string szConstant = valueLightInfo["constant"].asString();
if (!szConstant.empty())
{
lightInfo.attenuation.constant = szConstant;
}
string szLinear = valueLightInfo["linear"].asString();
if (!szLinear.empty())
{
lightInfo.attenuation.linear = szLinear;
}
string szQuadratic = valueLightInfo["quadratic"].asString();
if (!szQuadratic.empty())
{
lightInfo.attenuation.quadratic = szQuadratic;
}
lightInfo.cutOff.inner = valueLightInfo["inner"].asString();
lightInfo.cutOff.outer = valueLightInfo["outer"].asString();
}
setLightInfo(i, lightInfo);
m_bUseLightInfo = true;
}
}
// CameraInfo
Json::Value valueCameraInfo = root["cameraInfo"];
if (!valueCameraInfo.isNull())
{
m_cameraInfo.position = valueCameraInfo["position"].asString();
m_cameraInfo.view = valueCameraInfo["view"].asString();
m_cameraInfo.projection = valueCameraInfo["projection"].asString();
m_bUseCameraInfo = true;
}
// ModelInfo
Json::Value valueModelInfo = root["modelInfo"];
if (!valueModelInfo.isNull())
{
m_modelInfo.model = valueModelInfo["model"].asString();
m_modelInfo.normalMatrix = valueModelInfo["normalMatrix"].asString();
m_bUseModelInfo = true;
}
// Time
string szTime = root["time"].asString();
if (!szTime.empty())
{
m_time = szTime;
m_bUseTime = true;
}
return true;
}
Asset* GL3Material::clone()
{
GL3Material* pMaterial = new GL3Material();
*pMaterial = *this;
return pMaterial;
}
bool GL3Material::applyShaderToShape(Shape* _pShape)
{
if (_pShape)
{
// Color
if (m_bUseColor)
{
_pShape->setColor(m_pColor);
}
// Texture
if (m_pShader && !m_textures.empty())
{
m_pShader->use();
for (unsigned int i = 0; i < m_textures.size(); ++i)
{
m_pShader->setInt(m_textures[i].name.c_str(), i);
}
}
}
return true;
}
void GL3Material::use(Entity* _pEntity)
{
if (m_pShader)
{
if (!m_textures.empty())
{
for (unsigned int i = 0; i < m_textures.size(); ++i)
{
m_textures[i].texture->bind(i);
}
}
m_pShader->use();
// todo: integrate functions from 2019-2020 GL3 little by little
// pour le moment une entité a un transform et pas de glm::mat4 donc il faut la classe Matrix44
// Intégrer la lib de math?
if (_pEntity)
{
if (!m_propertyTransform.empty())
{
//glm::mat4 transform = _pEntity->getTransform()->getLocalToWorldMatrix();
//m_pShader->setMat4x4(m_propertyTransform, transform);
}
if (!m_propertyModel.empty())
{
//glm::mat4 model = _pEntity->getTransform()->getLocalToWorldMatrix();
//m_pShader->setMat4x4(m_propertyModel, model);
}
if (!m_propertyView.empty())
{
//glm::mat4 view = GameManager::getSingleton()->getMainCamera()->getViewMatrix();
//m_pShader->setMat4x4(m_propertyView, view);
}
if (!m_propertyProjection.empty())
{
//glm::mat4 projection = GameManager::getSingleton()->getMainCamera()->getProjectionMatrix();
//m_pShader->setMat4x4(m_propertyProjection, projection);
}
if (m_bUseMaterialInfo)
{
if (!m_materialInfo.ambient.uniform.empty())
{
//Color ambient = m_materialInfo.ambient.color;
//m_pShader->setVec3(m_materialInfo.ambient.uniform, glm::vec3(ambient.getR(), ambient.getG(), ambient.getB()));
}
if (!m_materialInfo.diffuse.uniform.empty())
{
//Color diffuse = m_materialInfo.diffuse.color;
//m_pShader->setVec3(m_materialInfo.diffuse.uniform, glm::vec3(diffuse.getR(), diffuse.getG(), diffuse.getB()));
}
if (!m_materialInfo.specular.uniform.empty())
{
//Color specular = m_materialInfo.specular.color;
//m_pShader->setVec3(m_materialInfo.specular.uniform, glm::vec3(specular.getR(), specular.getG(), specular.getB()));
}
if (!m_materialInfo.shininess.uniform.empty())
{
//m_pShader->setFloat(m_materialInfo.shininess.uniform, m_materialInfo.shininess.value);
}
}
if (m_bUseLightInfo)
{/*
m_pShader->setInt(m_lightsInfo.nbDirLights, m_nbDirLights);
m_pShader->setInt(m_lightsInfo.nbPointLights, m_nbPointLights);
m_pShader->setInt(m_lightsInfo.nbSpotLights, m_nbSpotLights);
for (unsigned int i = 0; i < m_lightInfos.size(); ++i)
{
Light* pLight = GameManager::getSingleton()->getLight(i);
assert(pLight);
LightInfo lightInfo = getLightInfo(i);
// All type
Color ambient = pLight->getAmbient();
m_pShader->setVec3(lightInfo.ambient, glm::vec3(ambient.getR(), ambient.getG(), ambient.getB()));
Color diffuse = pLight->getDiffuse();
m_pShader->setVec3(lightInfo.diffuse, glm::vec3(diffuse.getR(), diffuse.getG(), diffuse.getB()));
Color specular = pLight->getSpecular();
m_pShader->setVec3(lightInfo.specular, glm::vec3(specular.getR(), specular.getG(), specular.getB()));
// DefaultLight
if (pLight->getLightType() == DEFAULTLIGHT && lightInfo.type == "DEFAULTLIGHT")
{
m_pShader->setVec3(lightInfo.position, pLight->getEntity()->getTransform()->getPosition());
}
// DirLight
if (pLight->getLightType() == DIRLIGHT && lightInfo.type == "DIRLIGHT")
{
glm::vec3 dir = pLight->getEntity()->getTransform()->getForward();
m_pShader->setVec3(lightInfo.direction, dir);
}
// PointLight
if (pLight->getLightType() == POINTLIGHT && lightInfo.type == "POINTLIGHT")
{
m_pShader->setVec3(lightInfo.position, pLight->getEntity()->getTransform()->getPosition());
Attenuation attenuation = pLight->getAttenuation();
m_pShader->setFloat(lightInfo.attenuation.constant, attenuation.constant);
m_pShader->setFloat(lightInfo.attenuation.linear, attenuation.linear);
m_pShader->setFloat(lightInfo.attenuation.quadratic, attenuation.quadratic);
}
// SpotLight
if (pLight->getLightType() == SPOTLIGHT && lightInfo.type == "SPOTLIGHT")
{
m_pShader->setVec3(lightInfo.position, pLight->getEntity()->getTransform()->getPosition());
glm::vec3 dir = pLight->getEntity()->getTransform()->getForward();
m_pShader->setVec3(lightInfo.direction, dir);
Attenuation attenuation = pLight->getAttenuation();
m_pShader->setFloat(lightInfo.attenuation.constant, attenuation.constant);
m_pShader->setFloat(lightInfo.attenuation.linear, attenuation.linear);
m_pShader->setFloat(lightInfo.attenuation.quadratic, attenuation.quadratic);
CutOff cutOff = pLight->getCutOff();
m_pShader->setFloat(lightInfo.cutOff.inner, cutOff.inner);
m_pShader->setFloat(lightInfo.cutOff.outer, cutOff.outer);
}
}*/
}
if (m_bUseCameraInfo)
{/*
Camera* pCamera = GameManager::getSingleton()->getMainCamera();
m_pShader->setVec3(m_cameraInfo.position, pCamera->getEntity()->getTransform()->getPosition());
glm::mat4 view = GameManager::getSingleton()->getMainCamera()->getViewMatrix();
m_pShader->setMat4x4(m_cameraInfo.view, view);
glm::mat4 projection = GameManager::getSingleton()->getMainCamera()->getProjectionMatrix();
m_pShader->setMat4x4(m_cameraInfo.projection, projection);*/
}
if (m_bUseModelInfo)
{/*
glm::mat4 model = _pEntity->getTransform()->getLocalToWorldMatrix();
m_pShader->setMat4x4(m_modelInfo.model, model);
// Normal Matrix
glm::mat3 model3x3(model);
glm::mat3 normalMatrix = glm::transpose(glm::inverse(model3x3));
m_pShader->setMat3(m_modelInfo.normalMatrix, normalMatrix);*/
}
if (m_bUseTime)
{
//m_pShader->setFloat(m_time, (float) glfwGetTime());
}
}
}
}
void GL3Material::unuse()
{
if (m_pShader)
{
m_pShader->unuse();
}
}
} // namespace Crea<file_sep>/***************************************************/
/* Nom: FSMSteeringPeonLive.h
/* Description: FSMSteeringPeonLive
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMSteeringPeonLive_H_
#define __FSMSteeringPeonLive_H_
#include "AI\StateMachine.h"
#include "Scripts\CharacterController.h"
#include "FSMSteeringPeonGoTo.h"
#include "AI\Steering\Steering.h"
#include "AI\Steering\Vehicle.h"
using namespace crea;
class FSMSteeringPeonLive : public StateMachine
{
GameManager* m_pGM;
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
Steering* m_pSteering;
Vehicle* m_pVehicle;
FSMSteeringPeonGoTo* m_pFSMSteeringPeonGoTo;
vector<Entity*> m_pOthers;
Entity* m_pTarget;
Vector2f m_vTarget;
bool m_bPaused;
public:
FSMSteeringPeonLive();
virtual ~FSMSteeringPeonLive();
void setEntity(Entity* _p) { m_pEntity = _p; }
void setCharacterController(CharacterController* _p) { m_pCharacterController = _p; }
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
bool Move();
virtual Component* clone();
};
#endif
<file_sep>#include "stdafx.h"
#include "AI\PathFinding\MapSearchNode.h"
#include "AI\PathFinding\MapSearchManager.h"
#include "Data\Map.h"
#include "Data\Node.h"
#include <math.h>
namespace crea
{
bool MapSearchNode::IsSameState(MapSearchNode &rhs)
{
// same state in a search is simply when (x,y) are the same
return ((x == rhs.x) && (y == rhs.y));
}
// Here's the heuristic function that estimates the distance from a Node to the Goal.
float MapSearchNode::GoalDistanceEstimate(MapSearchNode &nodeGoal)
{
float dx = float(((float)x - (float)nodeGoal.x));
float dy = float(((float)y - (float)nodeGoal.y));
//return sqrt((dx*dx) + (dy*dy)); // Pythagore
return ((dx*dx) + (dy*dy)); // Simple Pythagore
//return (abs(dx) + abs(dy)); // Manhattan
//return max(abs(dx), abs(dy)); // Diagonal
}
bool MapSearchNode::IsGoal(MapSearchNode &nodeGoal)
{
return ((x == nodeGoal.x) && (y == nodeGoal.y));
}
// This generates the successors to the given Node. It uses a helper function called
// AddSuccessor to give the successors to the AStar class. The A* specific initialisation
// is done for each node internally, so here you just set the state information that
// is specific to the application
bool MapSearchNode::GetSuccessors(AStarSearch<MapSearchNode> *astarsearch, MapSearchNode *parent_node)
{
int parent_x = -1;
int parent_y = -1;
if (parent_node)
{
parent_x = parent_node->x;
parent_y = parent_node->y;
}
MapSearchNode NewNode;
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
Node* pParent = pMap->getNode(parent_x, parent_y);
bool bUseAA = pMap->getUseAA();
// AA*
Agent* pAgent = nullptr;
short nAgentSize = 0;
short nAgentCapability = 0;
pAgent = ((MapSearch*)astarsearch)->getCurrentAgent();
if (pAgent)
{
nAgentSize = pAgent->getSize();
nAgentCapability = pAgent->getCapability();
}
// push each possible move except allowing the search to go backwards
Node* pLeft = pMap->getNode(x - 1, y);
if (pLeft && (pLeft->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pLeft->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pLeft != pParent))
{
NewNode = MapSearchNode(x - 1, y);
astarsearch->AddSuccessor(NewNode);
}
Node* pUp = pMap->getNode(x, y - 1);
if (pUp && (pUp->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pUp->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pUp != pParent))
{
NewNode = MapSearchNode(x, y - 1);
astarsearch->AddSuccessor(NewNode);
}
Node* pRight = pMap->getNode(x + 1, y);
if (pRight && (pRight->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pRight->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pRight != pParent))
{
NewNode = MapSearchNode(x + 1, y);
astarsearch->AddSuccessor(NewNode);
}
Node* pDown = pMap->getNode(x, y + 1);
if (pDown && (pDown->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pDown->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pDown != pParent))
{
NewNode = MapSearchNode(x, y + 1);
astarsearch->AddSuccessor(NewNode);
}
// Diagonals
if (pUp && pLeft)
{
Node* pUpLeft = pMap->getNode(x - 1, y - 1);
if (pUpLeft && (pUpLeft->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pUpLeft->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pUpLeft != pParent)
&& (pUp->getTileCollisionId() == 0)
&& (pLeft->getTileCollisionId() == 0)
)
{
NewNode = MapSearchNode(x - 1, y - 1);
astarsearch->AddSuccessor(NewNode);
}
}
if (pDown && pRight)
{
Node* pDownRight = pMap->getNode(x + 1, y + 1);
if (pDownRight && (pDownRight->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pDownRight->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pDownRight != pParent)
&& (pDown->getTileCollisionId() == 0)
&& (pRight->getTileCollisionId() == 0)
)
{
NewNode = MapSearchNode(x + 1, y + 1);
astarsearch->AddSuccessor(NewNode);
}
}
if (pDown && pLeft)
{
Node* pDownLeft = pMap->getNode(x - 1, y + 1);
if (pDownLeft && (pDownLeft->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pDownLeft->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pDownLeft != pParent)
&& (pDown->getTileCollisionId() == 0)
&& (pLeft->getTileCollisionId() == 0)
)
{
NewNode = MapSearchNode(x - 1, y + 1);
astarsearch->AddSuccessor(NewNode);
}
}
if (pUp && pRight)
{
Node* pUpRight = pMap->getNode(x + 1, y - 1);
if (pUpRight && (pUpRight->getTileCollisionId() == 0)
&& (!bUseAA || bUseAA && pUpRight->getTileClearanceId(nAgentCapability) >= nAgentSize)
&& (pUpRight != pParent)
&& (pUp->getTileCollisionId() == 0)
&& (pRight->getTileCollisionId() == 0)
)
{
NewNode = MapSearchNode(x + 1, y - 1);
astarsearch->AddSuccessor(NewNode);
}
}
return true;
}
// given this node, what does it cost to move to successor.
float MapSearchNode::GetCost(MapSearchNode &successor)
{
// The G cost is 1.4 for diagonal move and 1.0 for horizontal or vertical move
float fDiagCoef = 1.0f;
int dx = successor.x - x;
int dy = successor.y - y;
if ((dx != 0) && (dy != 0))
{
fDiagCoef = 1.4f;
}
// And could depend on the friction
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
float friction = pMap->getFrictionAtPosition(pMap->getPixelsFromNodePosition(Vector2f((float)successor.x, (float)successor.y)));
return 1000.0f * friction + 100.0f * fDiagCoef;
}
}<file_sep>/***************************************************/
/* Nom: TimeManager.h
/* Description: TimeManager
/* Auteur: <NAME>
/***************************************************/
#ifndef _TimeManager_H
#define _TimeManager_H
#include <chrono>
using namespace std::chrono;
namespace crea
{
class CREAENGINE_API Time
{
double m_dTime;
public:
Time();
Time(double _dTime);
~Time();
Time& operator=(double _dTime);
Time& operator+=(Time& _Time);
bool operator>=(Time& _Time);
Time operator*(float _fTime);
int asMicroseconds();
int asMilliseconds();
double asSeconds();
void setAsMicroSeconds(int _iTime);
void setAsMilliSeconds(int _iTime);
void setAsSeconds(double _dTime);
};
class CREAENGINE_API Clock
{
high_resolution_clock::time_point m_t1;
Time m_elapsedTime;
public:
Clock();
~Clock();
Time getElapsedTime();
Time restart();
};
class CREAENGINE_API TimeManager
{
TimeManager();
Clock m_FrameClock;
Time m_FrameTime;
Clock m_GameClock;
Time m_GameTime;
public:
~TimeManager();
static TimeManager* getSingleton();
Time getFrameTime();
Time getGameTime();
void init();
void update();
};
} // namespace crea
#endif // _TimeManager_H<file_sep>/***************************************************/
/* Nom: SpriteRenderer.h
/* Description: SpriteRenderer
/* Auteur: <NAME>
/***************************************************/
#ifndef __SpriteRenderer_H_
#define __SpriteRenderer_H_
#include "Core\Component.h"
#include "Core\Math.h"
namespace crea
{
class CREAENGINE_API SpriteRenderer : public Component
{
Sprite* m_pSprite;
Material* m_pMaterial;
bool m_bShaderApplied;
IntRect* m_pTextureRect;
GameManager* m_pGM;
bool m_bActive;
public:
SpriteRenderer();
virtual ~SpriteRenderer();
inline void setSprite(Sprite* _pSprite) { m_pSprite = _pSprite; }
inline Sprite* getSprite() { return m_pSprite; }
inline void setMaterial(Material* _pMaterial) { m_pMaterial = _pMaterial; }
Material* getMaterial() { return m_pMaterial; }
void setTextureRect(IntRect* _pTextureRect) { m_pTextureRect = new IntRect(*_pTextureRect); }
inline void setActive(bool _bActive) { m_bActive = _bActive; }
bool loadFromFileJSON(const string& _filename);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone()
{
SpriteRenderer* p = new SpriteRenderer(*this);
p->m_pSprite = m_pSprite->clone();
if (m_pTextureRect)
{
p->m_pTextureRect = new IntRect(*m_pTextureRect);
}
return p;
}
};
} // namespace crea
#endif
<file_sep>/**
* Header Shader
*
* @author cbruneau
* @since 15/01/2018
* @version 2.0
*/
#ifndef SHADER_H
#define SHADER_H
namespace crea
{
class CREAENGINE_API Shader
{
public:
// the program ID
unsigned int shaderProgram;
// constructor reads and builds the shader
Shader();
virtual ~Shader();
virtual bool loadFromFile(const string& _name);
// use the shader
virtual void use();
// unuse the shader
virtual void unuse();
// utility uniform functions
// ------------------------------------------------------------------------
virtual void setBool(const std::string &name, bool value) const;
// ------------------------------------------------------------------------
virtual void setInt(const std::string &name, int value) const;
// ------------------------------------------------------------------------
void setFloat(const std::string &name, float value) const;
// ------------------------------------------------------------------------
virtual void setVec3(const std::string &name, float* vec3) const;
// ------------------------------------------------------------------------
virtual void setMat3(const std::string &name, float* mat3) const;
// ------------------------------------------------------------------------
virtual void setMat4x4(const std::string &name, float* mat4) const;
};
}
#endif
<file_sep>/**
* Header GL3Shader
*
* @author cbruneau
* @since 15/01/2018
* @version 2.0
*/
#ifndef GL3Shader_H
#define GL3Shader_H
#include "Graphics\Shader.h"
namespace crea
{
class GL3Shader : public Shader
{
public:
// the program ID
unsigned int shaderProgram;
// constructor reads and builds the GL3Shader
GL3Shader();
~GL3Shader();
virtual bool loadFromFile(const string& _name);
// use the GL3Shader
virtual void use();
// unuse the GL3Shader
virtual void unuse();
// utility uniform functions
// ------------------------------------------------------------------------
virtual void setBool(const std::string &name, bool value) const;
// ------------------------------------------------------------------------
virtual void setInt(const std::string &name, int value) const;
// ------------------------------------------------------------------------
virtual void setFloat(const std::string &name, float value) const;
// ------------------------------------------------------------------------
virtual void setVec3(const std::string &name, float* vec3) const;
// ------------------------------------------------------------------------
virtual void setMat3(const std::string &name, float* mat3) const;
// ------------------------------------------------------------------------
virtual void setMat4x4(const std::string &name, float* mat4) const;
};
}
#endif
<file_sep>/***************************************************/
/* Nom: TileSet.h
/* Description: TileSet
/* Auteur: <NAME>
/***************************************************/
#ifndef __TileSet_H_
#define __TileSet_H_
#include <vector>
#include "Core\Math.h"
namespace crea
{
class CREAENGINE_API Terrain
{
public:
string m_szName;
short m_nTile;
float m_fFriction;
};
class CREAENGINE_API TileInfo
{
public:
unsigned short m_nTerrain[4];
};
class CREAENGINE_API VectorTerrain : public vector<Terrain*> {};
class CREAENGINE_API MapTileInfo : public map<string, TileInfo*> {};
class CREAENGINE_API TileSet
{
public:
short m_nColumns;
short m_nFirstgid;
short m_nImageheight;
short m_nImagewidth;
short m_nMargin;
string m_szName;
short m_nSpacing;
short m_nTilecount;
short m_nTileheight;
short m_nTilewidth;
string m_szTransparentcolor;
Sprite* m_pSprite;
Vector2f m_vTileOffset;
VectorTerrain m_Terrains;
MapTileInfo m_TileInfos;
TileSet();
~TileSet();
float getFriction(unsigned short _nTileId, unsigned short _nQuad); // 0:TopLeft, 1: TopRight, 2: BottomLeft, 3: BottomRight
IntRect getTextureRect(int _iTileId)
{
int i = _iTileId - m_nFirstgid;
return IntRect(
(i % m_nColumns) * (m_nTilewidth + m_nMargin) + m_nMargin, // 1st margin
(i / m_nColumns) * (m_nTileheight + m_nSpacing) + m_nSpacing, // 1st spacing
m_nTilewidth,
m_nTileheight);
}
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Graphics\Animator.h"
#include "Core\GameManager.h"
#include "Core\TimeManager.h"
#include "Core\EntityManager.h"
#include "Graphics\Sprite.h"
namespace crea
{
Animator::Animator()
{
}
Animator::~Animator()
{
}
void Animator::setSprite(Sprite* _pSprite)
{
m_pSprite = _pSprite;
}
void Animator::setAnimation(Animation& animation)
{
m_pAnimation = &animation;
m_currentFrame = 0;
m_currentTime = 0.f;
}
void Animator::setFrameTime(Time& time)
{
m_frameTime = time;
}
Animation* Animator::getAnimation()
{
return m_pAnimation;
}
bool Animator::isPlaying()
{
return !m_isPaused;
}
Time Animator::getFrameTime()
{
return m_frameTime;
}
IntRect Animator::getFrame()
{
if (m_pAnimation)
{
return m_pAnimation->getFrame(m_currentFrame);
}
return IntRect();
}
void Animator::play()
{
m_isPaused = false;
}
void Animator::play(Animation& animation)
{
if (getAnimation() != &animation)
setAnimation(animation);
play();
}
void Animator::pause()
{
m_isPaused = true;
}
void Animator::stop()
{
m_isPaused = true;
m_currentFrame = 0;
m_currentTime = 0.f;
}
bool Animator::loadFromFileJSON(const string& _filename)
{
// TD Animation
Json::Value root;
std::ifstream srStream(_filename, std::ifstream::binary);
if (srStream.fail())
{
cerr << "Can't open SpriteRenderer file: " << _filename << endl;
return false;
}
srStream >> root;
string szSprite = root["sprite"].asString();
GameManager* pGM = GameManager::getSingleton();
m_pSprite = pGM->getSprite(szSprite);
return true;
}
bool Animator::init()
{
return true;
}
bool Animator::update()
{
// if sprite not set, try to get it from SpriteRenderer
if (!m_pSprite)
{
SpriteRenderer* pSr = getEntity()->getComponent<SpriteRenderer>();
if (pSr)
{
m_pSprite = pSr->getSprite();
}
}
// if not paused and we have a valid animation
if (!m_isPaused && m_pAnimation)
{
// add delta time
m_currentTime += (TimeManager::getSingleton()->getFrameTime()*m_pAnimation->getSpeed());
// Get the current animation frame
float fScaledTime = (float)(m_currentTime.asSeconds() / m_pAnimation->getDuration().asSeconds());
int iNumFrames = m_pAnimation->getSize();
m_currentFrame = (int)(fScaledTime * iNumFrames);
// If the animation is looping, calculate the correct frame
if (m_pAnimation->getLooping())
{
m_currentFrame %= iNumFrames;
}
else if (m_currentFrame >= iNumFrames) // If the current frame is greater than the number of frames
{
m_currentFrame = iNumFrames - 1; // Show last frame
}
}
if (m_pSprite && m_pAnimation)
{
m_pSprite->setTexture(m_pAnimation->getSpriteSheet());
IntRect rect = m_pAnimation->getFrame(m_currentFrame);
float fFlipH = (rect.getWidth() < 0) ? -1.0f : 1.0f;// width < 0 means flipH
float fFlipV = (rect.getHeight() < 0) ? -1.0f : 1.0f;// height < 0 means flipV
m_pSprite->setTextureRect(
rect.getLeft(),
rect.getTop(),
rect.getWidth()*(int)fFlipH,
rect.getHeight()*(int)fFlipV);
m_pSprite->setScale(fFlipH, fFlipV);
// CB: SpriteRenderer is already setting the position
}
return true;
}
bool Animator::draw()
{
return true;
}
bool Animator::quit()
{
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Graphics\IFacade.h"
namespace crea
{
IFacade* IFacade::s_Instance = NULL;
Plugin<IFacade> IFacade::s_Library;
} // namespace crea<file_sep>/***************************************************/
/* Nom: IFacade.h
/* Description: IFacade
/* Auteur: <NAME>
/***************************************************/
#ifndef _IFacade_H
#define _IFacade_H
#include "Core\Plugin.h"
#include "Graphics\IDrawable.h"
namespace crea
{
class Font;
class Texture;
class IntRect;
class LineShape;
class Shape;
class RectangleShape;
class CREAENGINE_API IFacade
{
public:
~IFacade()
{
destroy();
}
// Charge un renderer à partir d'une DLL
static void load(const std::string& DllName)
{
destroy();
s_Instance = s_Library.Load(DllName);
assert(s_Instance != NULL);
}
// Détruit le renderer
static void destroy()
{
//delete s_Instance;
s_Instance = NULL;
}
// Renvoie l'instance du renderer
static IFacade& get()
{
assert(s_Instance != NULL);
return *s_Instance;
}
// Initialise le renderer
virtual void initialize() = 0;
// Boucle de rendu
virtual bool update() = 0;
// Démarre le rendu de la scène
virtual void beginScene() const = 0;
// Rendu d'un objet
virtual void draw(IDrawable& _o) const = 0;
// Termine le rendu de la scène
virtual void endScene() const = 0;
// Quitte le renderer
virtual void quit() const = 0;
virtual Font* createFont(Font* _pFrom = nullptr) = 0;
virtual void destroyFont(Font* _pFont) = 0;
virtual Texture* createTexture(Texture* _pFrom = nullptr) = 0;
virtual void destroyTexture(Texture* _pTexture) = 0;
virtual Color* createColor(Color* _pFrom = nullptr) = 0;
virtual void destroyColor(Color* _pColor) = 0;
virtual Text* createText(Text* _pFrom = nullptr) = 0;
virtual void destroyText(Text* _pText) = 0;
virtual Sprite* createSprite(Sprite* _pFrom = nullptr) = 0;
virtual void destroySprite(Sprite* _pSprite) = 0;
virtual Shape* createShape(string _szType, Shape* _pFrom = nullptr) = 0;
virtual void destroyShape(Shape* _pShape) = 0;
virtual Shader* createShader(Shader* _pFrom = nullptr) = 0;
virtual void destroyShader(Shader* _pShader) = 0;
virtual Material* createMaterial(Material* _pFrom = nullptr) = 0;
virtual void destroyMaterial(Material* _pMaterial) = 0;
virtual bool isKeyPressed(Key _key) = 0;
virtual bool isMouseButtonPressed(Button _button) = 0;
virtual Vector2f getMousePosition() = 0;
virtual IntRect& getWindowRect() = 0;
virtual void setWindowRect(IntRect _rect) = 0;
protected:
IFacade()
{
s_Instance = NULL;
}
private:
// Données membres
static IFacade* s_Instance; // Instance du renderer chargée
static Plugin<IFacade> s_Library; // Helper pour manipuler la DLL
};
} // namespace crea
#endif // _IFacade_H<file_sep>/***************************************************/
/* Nom: Messages.h
/* Description: Messages
/* Auteur: <NAME>
/***************************************************/
#ifndef __Messages_H_
#define __Messages_H_
//Add new messages here
typedef enum {
MSG_NULL,
MSG_Randomize,
MSG_Timeout,
MSG_ChangeState,
MSG_Reset,
MSG_Kill,
MSG_Stop,
MSG_GoToWithGold,
MSG_GoToWithLumber,
MSG_GoTo,
MSG_Build,
MSG_Mine,
MSG_Harvest,
MSG_Die,
MSG_Boost,
MSG_Hit,
MSG_HitStop,
MSG_Seek,
MSG_Flee,
MSG_Pursuit,
MSG_Evasion,
MSG_Arrival,
MSG_Wander,
MSG_PathFollowing,
MSG_UCA,
MSG_CutWood,
MSG_PickupBranches,
MSG_ActionCompleted,
MSG_ToolUsed,
MSG_ToolBroken,
MSG_NewTool,
MSG_Think
} MSG_Name;
#endif
<file_sep>/***************************************************/
/* Nom: ShapeRenderer.h
/* Description: ShapeRenderer
/* Auteur: <NAME>
/***************************************************/
#ifndef __ShapeRenderer_H_
#define __ShapeRenderer_H_
#include "Core\Component.h"
namespace crea
{
class CREAENGINE_API ShapeRenderer : public Component
{
Shape* m_pShape;
public:
ShapeRenderer();
virtual ~ShapeRenderer();
inline void setShape(Shape* _pShape) { m_pShape = _pShape; }
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { return new ShapeRenderer(*this); }
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: SFMLText.h
/* Description: SFMLText
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLText_H
#define _SFMLText_H
#include "Graphics\Text.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLText : public Text
{
public:
sf::Text* m_pText;
SFMLText()
{
m_pText = new sf::Text;
}
virtual ~SFMLText()
{
delete m_pText;
}
virtual void draw()
{
sf::RenderWindow* pWin = SFMLFacade::Instance().m_pWindow;
pWin->draw(*m_pText);
}
virtual void setFont(Font* _pFont)
{
SFMLFont* pFont = (SFMLFont*)_pFont;
m_pText->setFont(pFont->m_font);
}
virtual void setColor(Color* _pColor)
{
SFMLColor* pColor = (SFMLColor*)_pColor;
m_pText->setFillColor(pColor->getColor());
}
virtual void setCharacterSize(int _iSize)
{
m_pText->setCharacterSize(_iSize);
}
virtual void setString(string _szString)
{
m_pText->setString(_szString);
}
virtual void setPosition(float _x, float _y)
{
m_pText->setPosition(_x, _y);
}
virtual void setTextureRect(int _x, int _y, int _w, int _h)
{
m_pText->setPosition((float)_x, (float)_y);
// CB: not handled with sfml...
cerr << "Text rect not possible for now..." << endl;
}
};
} // namespace crea
#endif // _SFMLText_H<file_sep>#include "stdafx.h"
#include "Scripts/UserController.h"
#include "Scripts/CharacterController.h"
// UserController
UserController::UserController()
{
m_pCharacterController = nullptr;
m_pGM = GameManager::getSingleton();
}
UserController::~UserController()
{
}
void UserController::setCharacterController(CharacterController* _pCharacterController)
{
m_pCharacterController = _pCharacterController;
}
bool UserController::init()
{
// Attention, ne marche que si CharacterController est avant le UserController
m_pCharacterController = getEntity()->getComponent<CharacterController>();
return true;
}
bool UserController::update()
{
// Preconditions
if (!m_pCharacterController)
{
return false;
}
if (!m_pEntity->getSelected())
{
return false;
}
// Default to no action
m_pCharacterController->setAction(kAct_Default);
// Directions
m_vDirection = Vector2f(0.f, 0.f);
if (m_pGM->isKeyPressed(Key::Up))
{
m_vDirection = Vector2f(0.f, -1.f);
m_pCharacterController->setDirection(kADir_Up);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Down))
{
m_vDirection = Vector2f(0.f, 1.f);
m_pCharacterController->setDirection(kADir_Down);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Left))
{
m_vDirection = Vector2f(-1.f, 0.f);
m_pCharacterController->setDirection(kADir_Left);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Right))
{
m_vDirection = Vector2f(1.f, 0.f);
m_pCharacterController->setDirection(kADir_Right);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Up) && m_pGM->isKeyPressed(Key::Right))
{
m_vDirection = Vector2f(1.f, -1.f);
m_pCharacterController->setDirection(kADir_UpRight);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Up) && m_pGM->isKeyPressed(Key::Left))
{
m_vDirection = Vector2f(-1.f, -1.f);
m_pCharacterController->setDirection(kADir_UpLeft);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Down) && m_pGM->isKeyPressed(Key::Right))
{
m_vDirection = Vector2f(1.f, 1.f);
m_pCharacterController->setDirection(kADir_DownRight);
m_pCharacterController->setAction(kAct_Walk);
}
if (m_pGM->isKeyPressed(Key::Down) && m_pGM->isKeyPressed(Key::Left))
{
m_vDirection = Vector2f(-1.f, 1.f);
m_pCharacterController->setDirection(kADir_DownLeft);
m_pCharacterController->setAction(kAct_Walk);
}
// Mouse control
if (m_pGM->isMouseButtonPressed(Button::MouseRight))
{
Vector2f vMousePosition = m_pGM->getMousePosition();
Vector2f vEntityPosition = getEntity()->getPosition();
m_vDirection = vMousePosition - vEntityPosition;
if (m_vDirection.length() > 10 && vMousePosition.getX() < 900)
{
m_pCharacterController->setDirection(m_vDirection);
m_pCharacterController->setAction(kAct_Walk);
}
else
{
m_vDirection = Vector2f(0.f, 0.f);
}
}
m_vDirection.normalize();
m_pCharacterController->move(m_vDirection);
//cout << m_vDirection.getX() << " " << m_vDirection.getY() << endl;
return true;
}
bool UserController::draw()
{
return true;
}
bool UserController::quit()
{
return true;
}
<file_sep>/***************************************************/
/* Nom: Map.h
/* Description: Map
/* Auteur: <NAME>
/***************************************************/
#ifndef __Map_H_
#define __Map_H_
#include <vector>
#include "TileSet.h"
namespace crea
{
class Node;
class Cluster;
class CREAENGINE_API Map
{
GameManager* m_pGM;
// Name
string m_szName;
// Dimensions
short m_nWidth;
short m_nHeight;
short m_nTileWidth;
short m_nTileHeight;
// Tilesets
vector<TileSet*> m_TileSet;
TileSet* m_pTerrainTileSet;
TileSet* m_pClearanceTileSet;
// Nodes
Node* **m_Grid; // Allocation dynamique
bool m_bIsGrid8;
// Clusters
short m_nClusterWidth;
short m_nClusterHeight;
short m_nNbClustersX;
short m_nNbClustersY;
Cluster* **m_Clusters;
bool m_bUseHPA;
bool m_bUseAStar;
bool m_bUseAA;
// Draw modes
bool m_bDisplayCollision;
// Tile index limits
int m_iMin;
int m_iMax;
int m_jMin;
int m_jMax;
void updateTileIndexLimits();
public:
Map();
~Map();
bool loadFromFileJSON(const string& _filename);
void findClearance();
void findClusters();
void setClusterSize(short _nClusterWidth, short _nClusterHeight);
void getClusterSize(short& _nClusterWidth, short& _nClusterHeight);
Cluster* getCluster(short _i, short _j) { return m_Clusters[_i][_j]; }
void getClusterIndexLimits(int& _iMin, int& _iMax, int& _jMin, int& _jMax) { _iMin = 0; _iMax = m_nNbClustersX; _jMin = 0; _jMax = m_nNbClustersY; }
void limitClusterIndex(short& _i, short& _j) { _i = _i < 0 ? 0 : _i; _i = _i > m_nNbClustersX ? m_nNbClustersX : _i; _j = _j < 0 ? 0 : _j; _j = _j > m_nNbClustersY ? m_nNbClustersY : _j; }
Node* getNodeInCluster(Cluster* _pCluster, short _i, short _j);
Cluster* getClusterFromNode(Node* _pNode);
inline void setName(const string& _szName) { m_szName = _szName; }
void setSize(short _nWidth, short _nHeight);
void getSize(short& _nWidth, short& _nHeight) { _nWidth = m_nWidth; _nHeight = m_nHeight; }
void getTileSize(short& _nWidth, short& _nHeight) { _nWidth = m_nTileWidth; _nHeight = m_nTileHeight; }
void setNode(short _i, short _j, Node* _pNode) { m_Grid[_i][_j] = _pNode; }
Node* getNode(short _i, short _j) { if (isInLimitTileIndex(_i, _j)) return nullptr; return m_Grid[_i][_j]; }
TileSet* getTileSet(short _gid);
Node* getNodeAtPosition(Vector2f _v);
Vector2f getNodePositionFromPixels(Vector2f _v);
Vector2f getPixelsFromNodePosition(Vector2f _v);
void getTileIndexLimits(int& _iMin, int& _iMax, int& _jMin, int& _jMax) { _iMin = m_iMin; _iMax = m_iMax; _jMin = m_jMin; _jMax = m_jMax; }
bool isInLimitTileIndex(short& _i, short& _j) { return (_i < m_iMin || _i > m_iMax || _j < m_jMin || _j > m_jMax); }
float getFrictionAtPosition(Vector2f _v);
unsigned short getQuadAtPosition(Vector2f& _v);
inline bool getUseAA() { return m_bUseAA; }
bool update();
bool draw();
void clear();
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: Samples
/* Description: Samples est une application de test
/* du CreaEngine
/* Il est basť sur le moteur CreaEngine qui utilise
/* le framework SFML.
/* Auteur: <NAME>
/***************************************************/
#include "stdafx.h"
#include "Core\GameManager.h"
#include "Core\SceneManager.h"
#include "Scene\SceneMenu.h"
using namespace crea;
int _tmain(int argc, _TCHAR* argv[])
{
GameManager* pGM = GameManager::getSingleton();
//pGM->setRendererType(Renderer_DX9);
pGM->setRendererType(Renderer_SFML);
//pGM->setRendererType(Renderer_GL3);
// todo: window do not have the size updated because the window is created first) but can't do it before because renderer not created...
//pGM->setWindowRect(IntRect(0, 0, 1152, 896));
pGM->setScene(new SceneMenu());
pGM->init();
pGM->update();
pGM->quit();
return 0;
}
<file_sep>/***************************************************/
/* Nom: SFMLColor.h
/* Description: SFMLColor
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLColor_H
#define _SFMLColor_H
#include "Graphics\Color.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLColor : public Color
{
public:
sf::Color getColor() { return sf::Color(m_r, m_g, m_b, m_a); }
SFMLColor()
{
}
virtual ~SFMLColor()
{
}
};
} // namespace crea
#endif // _SFMLColor_H<file_sep>/***************************************************/
/* Nom: Text.h
/* Description: Text
/* Auteur: <NAME>
/***************************************************/
#ifndef __Text_H_
#define __Text_H_
namespace crea
{
class CREAENGINE_API Text
{
public:
Text() {}
virtual ~Text() {}
virtual void draw() {}
virtual void setFont(Font* _pFont) {}
virtual void setColor(Color* _pColor) {}
virtual void setCharacterSize(int _iSize) {}
virtual void setString(string _szString) {}
virtual void setPosition(float _x, float _y) {}
virtual void setTextureRect(int _x, int _y, int _w, int _h) {}
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "AI\ActionTable.h"
namespace crea
{
ActionTable::ActionTable()
{
m_pGM = crea::GameManager::getSingleton();
}
ActionTable::~ActionTable()
{
// delete multimap
MapConditionAction::iterator ca_it = m_condActionMap.begin();
while (ca_it != m_condActionMap.end())
{
delete (*ca_it).second;
ca_it = m_condActionMap.erase(ca_it);
}
}
string* ActionTable::getAnimation(
unsigned char _ucAnimCond1,
unsigned char _ucAnimCond2,
unsigned short _unAction,
string* _pszActionDesc)
{
short keyDirCond = MERGE2CONDITIONS(_ucAnimCond1, _ucAnimCond2);
return getAnimation(keyDirCond, _unAction, _pszActionDesc);
}
string* ActionTable::getAnimation(
unsigned short _unAnimCond,
unsigned short _unAction,
string* _pszActionDesc)
{
MapConditionAction::iterator ca_it;
ActionAnimInfo* pAnimInfo = nullptr;
long keyDirCond = CREATE_KEY(_unAnimCond, _unAction);
ca_it = m_condActionMap.find(keyDirCond);
// Get list of actions for this animation condition
if (ca_it != m_condActionMap.end())
{
// Get number of animations listed for this action.
long nCount = m_condActionMap.count(keyDirCond);
// If only one action is listed, return the animation.
if (nCount == 1)
{
pAnimInfo = (ca_it->second);
if (_pszActionDesc)
{
*_pszActionDesc = pAnimInfo->szActionDesc;
}
return &pAnimInfo->szAnimFileName;
}
// Else pick randomly from a list of animations for this action.
else if (nCount > 1)
{
long nIndex = (long)(((float)rand() / (float)RAND_MAX) * (float)nCount);
for (long i = 0; i<nIndex; ++i, ++ca_it);// Position ca_it on nIndexth AnimInfoStruct
pAnimInfo = (ca_it->second);
if (pAnimInfo)
{
*_pszActionDesc = pAnimInfo->szActionDesc;
}
return &pAnimInfo->szAnimFileName;
}
}
// No animation was found for the specified eAnimCond and eAction, so get default animation
if (_unAnimCond != 0)
{
return getAnimation(0, _unAction, _pszActionDesc);
}
return nullptr;
}
bool ActionTable::addAnimation(
unsigned short _unAnimCond,
unsigned short _unAction,
string* _pszAnimFileName,
string* _pszActionDesc)
{
MapConditionAction::iterator ca_it;
long keyDirCond = CREATE_KEY(_unAnimCond, _unAction);
ActionAnimInfo* pAnimInfo = new ActionAnimInfo;
pAnimInfo->szAnimFileName = *_pszAnimFileName;
pAnimInfo->szActionDesc = (_pszActionDesc ? *_pszActionDesc : "");
m_condActionMap.insert(MapConditionAction::value_type(keyDirCond, pAnimInfo));
// Load animation
m_pGM->getAnimation(pAnimInfo->szAnimFileName);
return true;
}
bool ActionTable::init()
{
return true;
}
bool ActionTable::update()
{
return true;
}
bool ActionTable::draw()
{
return true;
}
bool ActionTable::quit()
{
return true;
}
bool ActionTable::loadFromFileJSON(const string& _filename)
{
Json::Value root;
std::ifstream config_doc(_filename, std::ifstream::binary);
config_doc >> root;
Json::Value conditions = root["conditions"];
for (unsigned int iCond = 0; iCond < conditions.size(); ++iCond)
{
Json::Value condition = conditions[iCond];
unsigned char ucCondition = condition["id"].asInt();
Json::Value actions = condition["actions"];
for (unsigned int iAct = 0; iAct < actions.size(); ++iAct)
{
Json::Value action = actions[iAct];
short unAction = action["id"].asInt();
Json::Value animations = action["animations"];
for (unsigned int iAnimation = 0; iAnimation < animations.size(); ++iAnimation)
{
Json::Value animation = animations[iAnimation];
unsigned char ucDir = iAnimation;
short unCondition = MERGE2CONDITIONS(ucDir, ucCondition);
addAnimation(unCondition, unAction, &animation.asString());
}
}
}
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Data\Node.h"
#include "Graphics\Sprite.h"
namespace crea
{
Node::Node()
{
m_nTileTerrainId = -1;
m_nTileCollisionId = -1;
}
Node::~Node()
{
// Do not delete children, as they are not allocated in Node
}
void Node::addChild(Node* _pNode)
{
m_pChildren.push_back(_pNode);
}
bool Node::update()
{
return true;
}
bool Node::draw()
{
return true;
}
void Node::clear()
{
m_pChildren.clear();
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: ClusterSearchNode.h
/* Description: ClusterSearchNode
/* Auteur: <NAME>
/***************************************************/
#ifndef ClusterSearchNode_H
#define ClusterSearchNode_H
#include "AStarSearch.h"
namespace crea
{
class CREAENGINE_API ClusterSearchNode // Cluster
{
public:
unsigned int x; // the (x,y) positions of the node
unsigned int y;
ClusterSearchNode(int _x = 0, int _y = 0) { x = _x; y = _y; }
//~ClusterSearchNode() { } // CB: do not surdefine dest as it crashes with templates (why?)
float GoalDistanceEstimate(ClusterSearchNode &nodeGoal);
bool IsGoal(ClusterSearchNode &nodeGoal);
bool GetSuccessors(AStarSearch<ClusterSearchNode> *astarsearch, ClusterSearchNode *parent_node);
float GetCost(ClusterSearchNode &successor);
bool IsSameState(ClusterSearchNode &rhs);
};
}
#endif<file_sep>#include "stdafx.h"
#include "Graphics\ShapeRenderer.h"
namespace crea
{
ShapeRenderer::ShapeRenderer()
{
m_pShape = nullptr;
}
ShapeRenderer::~ShapeRenderer()
{
}
bool ShapeRenderer::init()
{
return true;
}
bool ShapeRenderer::update()
{
return true;
}
bool ShapeRenderer::draw()
{
if (m_pShape)
{
m_pShape->draw();
}
return true;
}
bool ShapeRenderer::quit()
{
return true;
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: DX9Font.h
/* Description: DX9Font
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Font_H
#define _DX9Font_H
#include "Graphics\Font.h"
namespace crea
{
class DX9Font : public Font
{
LPD3DXFONT m_pFont;
string m_szFont;
int m_iHeight;
string getFontShortName(const string& _s)
{
int startPos = _s.rfind("/");
int endPos = _s.rfind(".");
return _s.substr(startPos + 1, endPos - startPos - 1);
}
public:
DX9Font()
{
m_pFont = nullptr;
m_szFont = "";
m_iHeight = 10;
}
virtual ~DX9Font() { SafeRelease(m_pFont); }
LPD3DXFONT getFont() { return m_pFont; }
virtual bool loadFromFile(const string& _file)
{
SafeRelease(m_pFont);
m_szFont = _file;
AddFontResourceEx(_file.c_str(), FR_PRIVATE, 0);
HRESULT hr = D3DXCreateFont(DX9Facade::Instance().m_pDevice, //D3D Device
m_iHeight, //Font height
0, //Font width
FW_NORMAL, //Font Weight
0, //MipLevels
false, //Italic
DEFAULT_CHARSET, //CharSet
OUT_DEFAULT_PRECIS, //OutputPrecision
DEFAULT_QUALITY, //Quality
DEFAULT_PITCH | FF_DONTCARE,//PitchAndFamily
getFontShortName(_file).c_str(),//pFacename,
&m_pFont); //ppFont
if (FAILED(hr))
{
OutputDebugString("Failed to create font.\n");
}
return true;
}
virtual void setFontSize(int _iSize)
{
if (m_iHeight != _iSize)
{
m_iHeight = _iSize;
loadFromFile(m_szFont);
}
}
};
} // namespace crea
#endif // _DX9Font_H
<file_sep>/***************************************************/
/* Nom: SceneManager.h
/* Description: SceneManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __SceneManager_H_
#define __SceneManager_H_
namespace crea
{
class Scene;
class CREAENGINE_API SceneManager
{
SceneManager();
protected:
Scene* m_pCurrentScene;
public:
virtual ~SceneManager();
static SceneManager* getSingleton();
bool update();
bool draw();
void setScene(Scene* s);
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "AI\Pathfinding\ClusterSearchManager.h"
namespace crea
{
ClusterSearch::ClusterSearch()
{
m_uiSearchState = (SearchState)AStarSearch<ClusterSearchNode>::SEARCH_STATE_NOT_INITIALISED;
}
ClusterSearch::~ClusterSearch()
{
}
bool ClusterSearch::setStartAndGoal(Vector2f _vStart, Vector2f _vGoal, bool _bFromPixels)
{
bool bAvailable = false;
if (m_uiSearchState == AStarSearch<ClusterSearchNode>::SEARCH_STATE_NOT_INITIALISED
|| m_uiSearchState == AStarSearch<ClusterSearchNode>::SEARCH_STATE_FAILED)
{
bAvailable = true;
}
if (m_uiSearchState == AStarSearch<ClusterSearchNode>::SEARCH_STATE_SUCCEEDED)
{
FreeSolutionNodes();
bAvailable = true;
}
if (bAvailable)
{
Map* pMap = ClusterSearchManager::getSingleton()->getCurrentMap();
if (_bFromPixels)
{
_vStart = pMap->getNodePositionFromPixels(_vStart);
_vGoal = pMap->getNodePositionFromPixels(_vGoal);
}
ClusterSearchNode nodeStart((int)_vStart.getX(), (int)_vStart.getY());
ClusterSearchNode nodeEnd((int)_vGoal.getX(), (int)_vGoal.getY());
// Set Start and goal states
SetStartAndGoalStates(nodeStart, nodeEnd);
m_uiSearchState = (SearchState)SearchStep();
}
return bAvailable;
}
ClusterSearch::SearchState ClusterSearch::update()
{
if (m_uiSearchState == AStarSearch<ClusterSearchNode>::SEARCH_STATE_SEARCHING)
{
// Step into search
m_uiSearchState = (SearchState)SearchStep();
}
return m_uiSearchState;
}
bool ClusterSearch::getSolution(VectorVector2f& _vSolution)
{
if (m_uiSearchState == AStarSearch<ClusterSearchNode>::SEARCH_STATE_SUCCEEDED)
{
Map* pMap = ClusterSearchManager::getSingleton()->getCurrentMap();
ClusterSearchNode* node = GetSolutionStart();
while (node)
{
Vector2f vNode = pMap->getPixelsFromNodePosition(Vector2f((float)node->x, (float)node->y));
_vSolution.push_back(new Vector2f(vNode));
node = GetSolutionNext();
}
return true;
}
return false;
}
float ClusterSearch::getSolutionLength()
{
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED)
{
float fDist = 0.0f;
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
ClusterSearchNode* node1 = GetSolutionStart();
ClusterSearchNode* node2 = GetSolutionNext();
while (node1 && node2)
{
fDist += node1->GetCost(*node2);
node1 = node2;
node2 = GetSolutionNext();
}
return fDist;
}
return 0.f;
}
}<file_sep>#include "stdafx.h"
#include "Scripts\FSMPeonLive.h"
#include "Scripts\Messages.h"
#include "Scripts\Actions.h"
#include <string.h>
FSMPeonLive::FSMPeonLive()
{
}
FSMPeonLive::~FSMPeonLive()
{
}
bool FSMPeonLive::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
OnMsg(MSG_Stop);
SetState(STATE_Idle);
OnMsg(MSG_GoToWithGold)
m_pTarget = m_pHQ;
m_vTarget = m_pTarget->getPosition() + Vector2f(20.f, 40.f);
//m_pCharacterController->setCondition(kACond_Gold);
SetState(STATE_GoTo);
OnMsg(MSG_GoToWithLumber)
m_pTarget = m_pHQ;
m_vTarget = m_pTarget->getPosition() + Vector2f(20.f, 40.f);
//m_pCharacterController->setCondition(kACond_Lumber);
SetState(STATE_GoTo);
OnMsg(MSG_GoTo)
m_pTarget = m_pHQ;
m_vTarget = m_pTarget->getPosition() + Vector2f(20.f, 40.f);
//m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_GoTo);
OnMsg(MSG_Build)
m_pTarget = m_pGM->getEntity("forge1");
m_vTarget = m_pTarget->getPosition() + Vector2f(0.f, 20.f);
SetState(STATE_GoTo);
OnMsg(MSG_Mine)
m_pTarget = m_pGM->getEntity("mine1");
m_vTarget = m_pTarget->getPosition() + Vector2f(-20.f, 20.f);
SetState(STATE_GoTo);
OnMsg(MSG_Harvest)
m_pTarget = m_pGM->getEntity("tree1");
m_vTarget = m_pTarget->getPosition() + Vector2f(0.f, 40.f);
SetState(STATE_GoTo);
OnMsg(MSG_CutWood)
m_pTarget = m_pGM->getEntity("lumbermill1");
m_vTarget = m_pTarget->getPosition() + Vector2f(-20.f, 20.f);
SetState(STATE_GoTo);
OnMsg(MSG_Kill)
SetState(STATE_Kill);
OnMsg(MSG_Hit)
SetState(STATE_Hit);
OnMsg(MSG_HitStop)
while (SetStateInHistory() == STATE_Hit);
OnMsg(MSG_ToolUsed)
m_iToolPV -= 1;
cout << m_pEntity->getName() << " tool used " << m_iToolPV << endl;
if (m_iToolPV == 0)
{
SendDelayedMsg(0.0f, MSG_ToolBroken, m_pEntity->GetID());
}
OnMsg(MSG_NewTool)
m_iToolPV = 2;
OnMsg(MSG_ToolBroken)
{
Blackboard* pBB = Blackboard::getSingleton();
if (_msg->GetSender() == m_pMiner->GetID())
{
pBB->setVariable("MinerHaveTool", "0");
}
else if (_msg->GetSender() == m_pLogger->GetID())
{
pBB->setVariable("LoggerHaveTool", "0");
}
}
///////////////////////////////////////////////////////////////
State(STATE_Init)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// Get SpriteRenderer
m_pSpriteRenderer = m_pEntity->getComponent<SpriteRenderer>();
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
// Get HQ
m_pHQ = m_pGM->getEntity("hq1");
m_pTree = m_pGM->getEntity("tree1");
m_pMiner = m_pGM->getEntity("miner");
m_pWoodCutter = m_pGM->getEntity("woodcutter");
m_pBlackSmith = m_pGM->getEntity("blacksmith");
m_pLogger = m_pGM->getEntity("logger");
// Get Blackboard
Blackboard* pBB = Blackboard::getSingleton();
// TD Behavior Tree
ActionGoTo* pActionGoToHQ = new ActionGoTo(this, MSG_GoTo);
ActionGoTo* pActionGoToTree = new ActionGoTo(this, MSG_Harvest);
ActionGoTo* pActionGoToLumberMill = new ActionGoTo(this, MSG_CutWood);
ActionGoTo* pActionGoToMine = new ActionGoTo(this, MSG_Mine);
ActionGoTo* pActionGoToForge = new ActionGoTo(this, MSG_Build);
ActionSetCondition* pActionSetConditionDefault = new ActionSetCondition(m_pCharacterController, kACond_Default);
ActionSetCondition* pActionSetConditionGold = new ActionSetCondition(m_pCharacterController, kACond_Gold);
ActionSetCondition* pActionSetConditionLumber = new ActionSetCondition(m_pCharacterController, kACond_Lumber);
PreCondition* pPreConditionHqHaveNoGold = new PreCondition(pBB, "HqHaveGold", "0");
PreCondition* pPreConditionHqHaveGold = new PreCondition(pBB, "HqHaveGold", "1");
Effect* pEffectHqHaveNoGold = new Effect(pBB, "HqHaveGold", "0");
Effect* pEffectHqHaveGold = new Effect(pBB, "HqHaveGold", "1");
PreCondition* pPreConditionHqHaveNoLogs = new PreCondition(pBB, "HqHaveLogs", "0");
PreCondition* pPreConditionHqHaveLogs = new PreCondition(pBB, "HqHaveLogs", "1");
Effect* pEffectHqHaveNoLogs = new Effect(pBB, "HqHaveLogs", "0");
Effect* pEffectHqHaveLogs = new Effect(pBB, "HqHaveLogs", "1");
PreCondition* pPreConditionHqHaveNoFireWood = new PreCondition(pBB, "HqHaveFireWood", "0");
PreCondition* pPreConditionHqHaveFireWood = new PreCondition(pBB, "HqHaveFireWood", "1");
Effect* pEffectHqHaveNoFireWood = new Effect(pBB, "HqHaveFireWood", "0");
Effect* pEffectHqHaveFireWood = new Effect(pBB, "HqHaveFireWood", "1");
PreCondition* pPreConditionHqHaveNoTool = new PreCondition(pBB, "HqHaveTool", "0");
PreCondition* pPreConditionHqHaveTool = new PreCondition(pBB, "HqHaveTool", "1");
Effect* pEffectHqHaveNoTool = new Effect(pBB, "HqHaveTool", "0");
Effect* pEffectHqHaveTool = new Effect(pBB, "HqHaveTool", "1");
PreCondition* pPreConditionMinerHaveNoTool = new PreCondition(pBB, "MinerHaveTool", "0");
PreCondition* pPreConditionMinerHaveTool = new PreCondition(pBB, "MinerHaveTool", "1");
Effect* pEffectMinerHaveNoTool = new Effect(pBB, "MinerHaveTool", "0");
Effect* pEffectMinerHaveTool = new Effect(pBB, "MinerHaveTool", "1");
PreCondition* pPreConditionLoggerHaveNoTool = new PreCondition(pBB, "LoggerHaveTool", "0");
PreCondition* pPreConditionLoggerHaveTool = new PreCondition(pBB, "LoggerHaveTool", "1");
Effect* pEffectLoggerHaveNoTool = new Effect(pBB, "LoggerHaveTool", "0");
Effect* pEffectLoggerHaveTool = new Effect(pBB, "LoggerHaveTool", "1");
PreCondition* pPreConditionCutterHaveNoTool = new PreCondition(pBB, "CutterHaveTool", "0");
PreCondition* pPreConditionCutterHaveTool = new PreCondition(pBB, "CutterHaveTool", "1");
Effect* pEffectCutterHaveNoTool = new Effect(pBB, "CutterHaveTool", "0");
Effect* pEffectCutterHaveTool = new Effect(pBB, "CutterHaveTool", "1");
PreCondition* pPreConditionCutterHaveWood = new PreCondition(pBB, "CutterHaveWood", "1");
Effect* pEffectCutterHaveWood = new Effect(pBB, "CutterHaveWood", "1");
ActionSendMsg* pUseTool = new ActionSendMsg(this, MSG_ToolUsed);
ActionSendMsg* pNewTool = new ActionSendMsg(this, MSG_NewTool);
// Hide2Secs
FilterTimer* pWait2secs = new FilterTimer(Time(2));
ActionWait* pActionWait = new ActionWait();
pWait2secs->addChild(pActionWait);
ActionActivateSpriteRenderer* pActionDisplay = new ActionActivateSpriteRenderer(m_pSpriteRenderer, true);
ActionActivateSpriteRenderer* pActionHide = new ActionActivateSpriteRenderer(m_pSpriteRenderer, false);
bt::Sequence* pHide2Secs = new bt::Sequence();
pHide2Secs->addChild(pActionHide);
pHide2Secs->addChild(pWait2secs);
pHide2Secs->addChild(pActionDisplay);
// Pickup Tool
bt::Sequence* pPickupTool = new bt::Sequence();
pPickupTool->addChild(pActionGoToHQ);
pPickupTool->addChild(pHide2Secs);
pPickupTool->addChild(pNewTool);
// Miner
if (m_pEntity->getName() == "miner")
{
// Get Gold
bt::Sequence* pGetGold = new bt::Sequence();
pGetGold->addChild(pActionGoToMine);
pGetGold->addChild(pHide2Secs);
pGetGold->addChild(pUseTool);
// Drop in HQ
bt::Sequence* pDropInHQ = new bt::Sequence();
pDropInHQ->addChild(pActionGoToHQ);
pDropInHQ->addChild(pHide2Secs);
// Mining
bt::Sequence* pMining = new bt::Sequence();
pMining->addChild(pActionSetConditionDefault);
pMining->addChild(pGetGold);
pMining->addChild(pActionSetConditionGold);
pMining->addChild(pDropInHQ);
pMining->addChild(pActionSetConditionDefault);
// Get Tool
bt::Sequence* pGetTool = new bt::Sequence();
pGetTool->addChild(pPreConditionHqHaveTool);
pGetTool->addChild(pPickupTool);
pGetTool->addChild(pEffectHqHaveNoTool);
pGetTool->addChild(pEffectMinerHaveTool);
// Have Tool
bt::Selector* pHaveTool = new bt::Selector();
pHaveTool->addChild(pPreConditionMinerHaveTool);
pHaveTool->addChild(pGetTool);
// Goal HQ have Gold
bt::Sequence* pGoalHQHaveGold = new bt::Sequence();
pGoalHQHaveGold->addChild(pHaveTool);
pGoalHQHaveGold->addChild(pMining);
pGoalHQHaveGold->addChild(pEffectHqHaveGold);
m_bt.setRootBehavior(pGoalHQHaveGold);
// Tests
pBB->setVariable("MinerHaveTool", "1");
SendDelayedMsg(0.0f, MSG_NewTool, m_pEntity->GetID());
}
// Logger
if (m_pEntity->getName() == "logger")
{
// Chop 3 Secs
FilterTimer* pChop3secs = new FilterTimer(Time(3));
ActionSetAction* pActionChop = new ActionSetAction(m_pCharacterController, kAct_Chop);
pChop3secs->addChild(pActionChop);
// Get Lumber
bt::Sequence* pGetLumber = new bt::Sequence();
pGetLumber->addChild(pActionGoToTree);
pGetLumber->addChild(pChop3secs);
pGetLumber->addChild(pUseTool);
// Drop in HQ
bt::Sequence* pDropInHQ = new bt::Sequence();
pDropInHQ->addChild(pActionGoToHQ);
pDropInHQ->addChild(pHide2Secs);
// Logging
bt::Sequence* pLogging = new bt::Sequence();
pLogging->addChild(pActionSetConditionDefault);
pLogging->addChild(pGetLumber);
pLogging->addChild(pActionSetConditionLumber);
pLogging->addChild(pDropInHQ);
pLogging->addChild(pActionSetConditionDefault);
// Get Tool
bt::Sequence* pGetTool = new bt::Sequence();
pGetTool->addChild(pPreConditionHqHaveTool);
pGetTool->addChild(pPickupTool);
pGetTool->addChild(pEffectHqHaveNoTool);
pGetTool->addChild(pEffectLoggerHaveTool);
// Have Tool
bt::Selector* pHaveTool = new bt::Selector();
pHaveTool->addChild(pPreConditionLoggerHaveTool);
pHaveTool->addChild(pGetTool);
// Goal HQ have Gold
bt::Sequence* pGoalHQHaveGold = new bt::Sequence();
pGoalHQHaveGold->addChild(pHaveTool);
pGoalHQHaveGold->addChild(pLogging);
pGoalHQHaveGold->addChild(pEffectHqHaveLogs);
m_bt.setRootBehavior(pGoalHQHaveGold);
// Tests
pBB->setVariable("LoggerHaveTool", "1");
SendDelayedMsg(0.0f, MSG_NewTool, m_pEntity->GetID());
}
// WoodCutter
if (m_pEntity->getName() == "woodcutter")
{
// Get FireWood
bt::Sequence* pGetFireWood = new bt::Sequence();
pGetFireWood->addChild(pActionGoToLumberMill);
pGetFireWood->addChild(pHide2Secs);
// Drop in HQ
bt::Sequence* pDropInHQ = new bt::Sequence();
pDropInHQ->addChild(pActionGoToHQ);
pDropInHQ->addChild(pHide2Secs);
// Cutting
bt::Sequence* pCutting = new bt::Sequence();
pCutting->addChild(pActionSetConditionLumber);
pCutting->addChild(pGetFireWood);
pCutting->addChild(pActionSetConditionGold);
pCutting->addChild(pDropInHQ);
pCutting->addChild(pActionSetConditionDefault);
// Get Tool
bt::Sequence* pGetTool = new bt::Sequence();
pGetTool->addChild(pPreConditionCutterHaveTool);
pGetTool->addChild(pPickupTool);
pGetTool->addChild(pEffectCutterHaveTool);
// Have Tool
bt::Selector* pHaveTool = new bt::Selector();
pHaveTool->addChild(pPreConditionCutterHaveTool);
pHaveTool->addChild(pGetTool);
// Pickup Logs
bt::Sequence* pPickupLogs = new bt::Sequence();
pPickupLogs->addChild(pActionSetConditionDefault);
pPickupLogs->addChild(pActionGoToHQ);
pPickupLogs->addChild(pHide2Secs);
pPickupLogs->addChild(pActionSetConditionLumber);
// Get Logs
bt::Sequence* pGetLogs = new bt::Sequence();
pGetLogs->addChild(pPreConditionHqHaveLogs);
pGetLogs->addChild(pPickupLogs);
pGetLogs->addChild(pEffectHqHaveNoLogs);
pGetLogs->addChild(pEffectCutterHaveWood);
// Pickup Branches
bt::Sequence* pPickupBranches = new bt::Sequence();
pPickupBranches->addChild(pActionSetConditionDefault);
pPickupBranches->addChild(pActionGoToTree);
pPickupBranches->addChild(pHide2Secs);
pPickupBranches->addChild(pActionSetConditionLumber);
// Get Branches
bt::Sequence* pGetBranches = new bt::Sequence();
pGetBranches->addChild(pPickupBranches);
pGetLogs->addChild(pEffectCutterHaveWood);
// Have Wood
bt::Selector* pHaveWood = new bt::Selector();
pHaveWood->addChild(pPreConditionCutterHaveWood);
pHaveWood->addChild(pGetLogs);
pHaveWood->addChild(pGetBranches);
// Goal HQ have FireWood
bt::Sequence* pGoalHQHaveFireWood = new bt::Sequence();
pGoalHQHaveFireWood->addChild(pHaveTool);
pGoalHQHaveFireWood->addChild(pHaveWood);
pGoalHQHaveFireWood->addChild(pCutting);
pGoalHQHaveFireWood->addChild(pEffectHqHaveFireWood);
m_bt.setRootBehavior(pGoalHQHaveFireWood);
// Tests
pBB->setVariable("CutterHaveTool", "1");
SendDelayedMsg(0.0f, MSG_NewTool, m_pEntity->GetID());
}
// BlackSmith
if (m_pEntity->getName() == "blacksmith")
{
// Pickup fireWood and Gold
bt::Sequence* pPickupFireWoodAndGold = new bt::Sequence();
pPickupFireWoodAndGold->addChild(pActionGoToHQ);
pPickupFireWoodAndGold->addChild(pHide2Secs);
// Forge Tool
bt::Sequence* pForgeTool = new bt::Sequence();
pForgeTool->addChild(pActionGoToForge);
pForgeTool->addChild(pHide2Secs);
// Drop in HQ
bt::Sequence* pDropInHQ = new bt::Sequence();
pDropInHQ->addChild(pActionGoToHQ);
pDropInHQ->addChild(pHide2Secs);
// Forging
bt::Sequence* pForging = new bt::Sequence();
pForging->addChild(pActionSetConditionDefault);
pForging->addChild(pPickupFireWoodAndGold);
pForging->addChild(pActionSetConditionGold);
pForging->addChild(pForgeTool);
pForging->addChild(pActionSetConditionGold);
pForging->addChild(pDropInHQ);
pForging->addChild(pActionSetConditionDefault);
// Goal HQ Have Tool
bt::Sequence* pGoalHQHaveTool = new bt::Sequence();
pGoalHQHaveTool->addChild(pPreConditionHqHaveGold);
pGoalHQHaveTool->addChild(pPreConditionHqHaveFireWood);
pGoalHQHaveTool->addChild(pForging);
pGoalHQHaveTool->addChild(pEffectHqHaveTool);
m_bt.setRootBehavior(pGoalHQHaveTool);
}
m_pEntity->addComponent(&m_bt);
///////////////////////////////////////////////////////////////
State(STATE_Idle)
OnEnter
m_pCharacterController->setAction(kAct_Default);
m_pCharacterController->move(Vector2f(0.f, 0.f));
///////////////////////////////////////////////////////////////
State(STATE_GoTo)
OnEnter
m_pFSMPeonGoTo = new FSMPeonGoTo(m_vTarget);
m_pEntity->addComponent(m_pFSMPeonGoTo);
m_pFSMPeonGoTo->Initialize(m_pEntity);
OnUpdate
//m_pFSMPeonGoTo->Update();
/*
if (m_pFSMPeonGoTo->GetState() == FSMPeonGoTo::STATE_CompletedPath)
{
SetState(STATE_Idle);
}*/
OnExit
m_pEntity->removeComponent(m_pFSMPeonGoTo);
delete m_pFSMPeonGoTo;
m_pFSMPeonGoTo = nullptr;
///////////////////////////////////////////////////////////////
State(STATE_Hit)
OnEnter
// CB: a hit is a temporary death...
SendDelayedMsgToMe(0.5f, MSG_HitStop);
m_condition = m_pCharacterController->getCondition();
OnUpdate
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Die);
OnExit
m_pCharacterController->setCondition(m_condition);
m_pCharacterController->setAction(kAct_Default);
///////////////////////////////////////////////////////////////
State(STATE_Kill)
OnEnter
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Chop);
///////////////////////////////////////////////////////////////
State(STATE_Build)
OnEnter
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Chop);
///////////////////////////////////////////////////////////////
State(STATE_Mine)
OnEnter
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Chop);
SetState(STATE_GoTo);
///////////////////////////////////////////////////////////////
State(STATE_Harvest)
OnUpdate
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Chop);
EndStateMachine
}
<file_sep>/***************************************************/
/* Nom: FSMPeonLive.h
/* Description: FSMPeonLive
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMPeonLive_H_
#define __FSMPeonLive_H_
#include "AI\StateMachine.h"
#include "Scripts\CharacterController.h"
#include "FSMPeonGoTo.h"
using namespace crea;
//Add new states here
enum StatesFSMPeonLive {
STATE_Init,
STATE_Idle,
STATE_GoTo,
STATE_GetResource,
STATE_DropResource,
STATE_Hit,
STATE_Build,
STATE_Mine,
STATE_Harvest,
STATE_Kill
};
class FSMPeonLive : public StateMachine
{
GameManager* m_pGM;
Entity* m_pEntity;
CharacterController* m_pCharacterController;
SpriteRenderer* m_pSpriteRenderer;
Agent* m_pAgent;
FSMPeonGoTo* m_pFSMPeonGoTo;
Entity* m_pMine;
Entity* m_pHQ;
Entity* m_pTarget;
Vector2f m_vTarget;
Entity* m_pTree;
Entity* m_pMiner;
Entity* m_pWoodCutter;
Entity* m_pBlackSmith;
Entity* m_pLogger;
EnumAnimCondition m_condition;
bt::BehaviorTree m_bt;
short m_iToolPV;
public:
FSMPeonLive();
virtual ~FSMPeonLive();
void setEntity(Entity* _p) { m_pEntity = _p; }
void setCharacterController(CharacterController* _p) { m_pCharacterController = _p; }
inline FSMPeonGoTo* getFSMPeonGoTo() { return m_pFSMPeonGoTo; }
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone() { return new FSMPeonLive(*this); }
};
#endif
<file_sep>/***************************************************/
/* Nom: SFMLFacade.h
/* Description: SFMLFacade
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLFacade_H
#define _SFMLFacade_H
#include "Graphics\IFacade.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLFacade
{
// window
IntRect m_rWindowRect;
private:
// Données membres
SFMLFacade();
public:
~SFMLFacade();
// Renvoie l'instance du renderer
static SFMLFacade& Instance();
// Initialise le renderer
virtual void initialize();
// Boucle de rendu
virtual bool update();
// Démarre le rendu de la scène
virtual void beginScene() const;
// Rendu d'un objet
virtual void draw(IDrawable& _o) const;
// Termine le rendu de la scène
virtual void endScene() const;
// Quitte le renderer
virtual void quit() const;
virtual Font* createFont(Font* _pFrom = nullptr);
virtual void destroyFont(Font* _pFont);
virtual Texture* createTexture(Texture* _pFrom = nullptr);
virtual void destroyTexture(Texture* _pTexture);
virtual Color* createColor(Color* _pFrom = nullptr);
virtual void destroyColor(Color* _pColor);
virtual Text* createText(Text* _pFrom = nullptr);
virtual void destroyText(Text* _pText);
virtual Sprite* createSprite(Sprite* _pFrom = nullptr);
virtual void destroySprite(Sprite* _pSprite);
virtual Shape* createShape(string _szType, Shape* _pFrom = nullptr);
virtual void destroyShape(Shape* _pShape);
virtual Shader* createShader(Shader* _pFrom = nullptr);
virtual void destroyShader(Shader* _pShader);
virtual Material* createMaterial(Material* _pFrom = nullptr);
virtual void destroyMaterial(Material* _pMaterial);
virtual bool isKeyPressed(Key _key);
virtual bool isMouseButtonPressed(Button _button);
virtual Vector2f getMousePosition();
virtual IntRect& getWindowRect() { return m_rWindowRect; }
virtual void setWindowRect(IntRect _rect) { m_rWindowRect = _rect; }
sf::RenderWindow* m_pWindow;
};
} // namespace crea
#endif // _SFMLFacade_H<file_sep>#include "stdafx.h"
#include "Scripts\FSMPeon.h"
#include "Scripts\Messages.h"
#include <string.h>
//Add new states here
enum States {
STATE_Spawn,
STATE_Live,
STATE_Die,
};
FSMPeon::FSMPeon()
{
}
FSMPeon::~FSMPeon()
{
}
bool FSMPeon::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
OnMsg(MSG_Reset)
SetState(STATE_Spawn);
OnMsg(MSG_Die)
SetState(STATE_Die);
OnMsg(MSG_Hit)
m_iLife -= 1;
m_pAgent->setHealth(m_iLife);
if (m_iLife <= 0)
{
SetState(STATE_Die);
}
if (m_pFSMPeonLive)
{
m_pFSMPeonLive->States(_event, _msg, _state); // CB: propagate msg to sub-state
}
OnMsg(MSG_Boost)
m_pAgent->setDexterity(m_pAgent->getDexterity()+1);
///////////////////////////////////////////////////////////////
State(STATE_Spawn)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
m_iLife = m_pAgent->getHealth();
OnUpdate
SetState(STATE_Live);
///////////////////////////////////////////////////////////////
State(STATE_Live)
OnEnter
m_pFSMPeonLive = new FSMPeonLive();
m_pEntity->addComponent(m_pFSMPeonLive);
m_pFSMPeonLive->Initialize(m_pEntity);
OnUpdate
//m_pFSMPeonLive->Update(); // CBruneau: not necessary as it was added as a component
if (m_iLife <= 0)
{
SetState(STATE_Die);
}
OnExit
m_pEntity->removeComponent(m_pFSMPeonLive);
delete m_pFSMPeonLive;
m_pFSMPeonLive = nullptr;
///////////////////////////////////////////////////////////////
State(STATE_Die)
OnEnter
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Die);
EndStateMachine
}<file_sep>#include "stdafx.h"
#include "Graphics\Color.h"
namespace crea
{
const Color Color::black(0, 0, 0, 255);
const Color Color::white(255, 255, 255, 255);
const Color Color::red(255, 0, 0, 255);
const Color Color::green(0, 255, 0, 255);
const Color Color::blue(0, 0, 255, 255);
const Color Color::yellow(255, 255, 0, 255);
const Color Color::magenta(255, 0, 255, 255);
const Color Color::cyan(0, 255, 255, 255);
const Color Color::transparent(0, 0, 0, 0);
const Color Color::grey(51, 76, 76, 255);
const Color Color::orange(255, 127, 51, 255);
Color::Color()
: m_r(255), m_g(255), m_b(255), m_a(255)
{
}
Color::Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a)
: m_r(_r), m_g(_g), m_b(_b), m_a(_a)
{
}
void Color::setValues(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a)
{
m_r = _r;
m_g = _g;
m_b = _b;
m_a = _a;
}
string Color::ToString() const
{
string toString("(");
toString += to_string(m_r);
toString += ", ";
toString += to_string(m_g);
toString += ", ";
toString += to_string(m_b);
toString += ", ";
toString += to_string(m_a);
toString += ")";
return toString;
}
bool Color::operator== (const Color& _right) const
{
return ((m_r == _right.m_r)
&& (m_g == _right.m_g)
&& (m_b == _right.m_b)
&& (m_a == _right.m_a));
}
bool Color::operator!= (const Color& _right) const
{
return ((m_r != _right.m_r)
|| (m_g != _right.m_g)
|| (m_b != _right.m_b)
|| (m_a != _right.m_a));
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Tools\AITools.h"
#include "Scene\SceneMenu.h"
#include "Scene\SceneMap.h"
#include "Core\SceneManager.h"
#include "Scripts\Messages.h"
#include <string>
AITools::AITools()
{
}
AITools::~AITools()
{
}
bool AITools::onInit()
{
m_pGM = GameManager::getSingleton();
Color* pRed = m_pGM->getColor("Red");
pRed->setValues(255, 0, 0, 255);
Color* pBlue = m_pGM->getColor("Blue");
pBlue->setValues(0, 0, 255, 255);
Color* pBlack = m_pGM->getColor("Black");
pBlack->setValues(0, 0, 0, 255);
Color* pTransparent = m_pGM->getColor("Transparent");
pTransparent->setValues(0, 0, 0, 0);
Color* pRedTransparent = m_pGM->getColor("RedTransparent");
pRedTransparent->setValues(255, 0, 0, 125);
Color* pGreenTransparent = m_pGM->getColor("GreenTransparent");
pGreenTransparent->setValues(0, 255, 0, 255);
Color* pBlueTransparent = m_pGM->getColor("BlueTransparent");
pBlueTransparent->setValues(0, 0, 255, 125);
// Selection
m_bSelection = false;
m_pSelectionShape = (RectangleShape*)m_pGM->getShape("Rectangle", "SelectionShape");
m_pSelectionShape->setOutlineColor(pBlue);
m_pSelectionShape->setColor(pTransparent);
m_pSelectionShape->setOutlineThickness(1.f);
// Commands
Texture* pCommandsTexture = m_pGM->getTexture("debug/Commands.png");
m_pCommandsSprite = m_pGM->getSprite("Commands");
m_pCommandsSprite->setTexture(pCommandsTexture);
m_rCommandWindow = FloatRect(896, 640, 256, 256);
m_pCommandsSprite->setPosition(m_rCommandWindow.m_fX, m_rCommandWindow.m_fY);
// Diagnostics
m_pTextFPS = m_pGM->getText("fps");
m_pTextFPS->setFont(m_pGM->getFont("arial.ttf"));
m_pTextFPS->setColor(pRed);
m_pTextFPS->setCharacterSize(14);
m_pTextFPS->setString("fps:");
m_pTextFPS->setPosition(900, 0);
m_pTextCommand = m_pGM->getText("Command");
m_pTextCommand->setFont(m_pGM->getFont("arial.ttf"));
m_pTextCommand->setColor(pRed);
m_pTextCommand->setCharacterSize(14);
m_pTextCommand->setString("Last command:");
m_pTextCommand->setPosition(900, 20);
m_pTextDiagnostics = m_pGM->getText("Diagnostics");
m_pTextDiagnostics->setFont(m_pGM->getFont("arial.ttf"));
m_pTextDiagnostics->setColor(pBlue);
m_pTextDiagnostics->setCharacterSize(14);
m_pTextDiagnostics->setPosition(-100.f, -100.f);
m_fCommandDisplayTime = 1.0f;
// Grid
m_pMap = m_pGM->getMapRenderer("MapRenderer1")->getMap();
m_pMap->getSize(m_nWidth, m_nHeight);
m_pMap->getTileSize(m_nTileWidth, m_nTileHeight);
m_pMap->getTileIndexLimits(m_iMin, m_iMax, m_jMin, m_jMax);
m_pNodeShape = (RectangleShape*)m_pGM->getShape("Rectangle", "NodeShape");
m_pNodeShape->setOutlineColor(pBlack);
m_pNodeShape->setColor(pTransparent);
m_pNodeShape->setOutlineThickness(0.5f);
m_pNodeShape->setSize(m_nTileWidth, m_nTileHeight);
m_pLineShape = (LineShape*)m_pGM->getShape("Line", "m_pLineShape");
m_pLineShape->setColor(pBlack);
// CharacterController
//m_pCharacterController = (CharacterController*) m_pGM->getScript("CharacterController");
m_pCharacterController = nullptr;
m_pathToHQ.push_back(Vector2f(645.f, 125.f));
m_pathToHQ.push_back(Vector2f(513.f, 97.f));
m_pathToHQ.push_back(Vector2f(383.f, 97.f));
m_pathToHQ.push_back(Vector2f(185.f, 130.f));
m_pathToMine.push_back(Vector2f(185.f, 130.f));
m_pathToMine.push_back(Vector2f(352.f, 191.f));
m_pathToMine.push_back(Vector2f(608.f, 191.f));
m_pathToMine.push_back(Vector2f(645.f, 125.f));
// Collisions
m_pBoxColliderShape = (RectangleShape*)m_pGM->getShape("Rectangle", "BoxColliderShape");
m_pBoxColliderShape->setOutlineColor(pRed);
m_pBoxColliderShape->setColor(pTransparent);
m_pBoxColliderShape->setOutlineThickness(1.0f);
m_pCircleColliderShape = (CircleShape*)m_pGM->getShape("Circle", "CircleColliderShape");
m_pCircleColliderShape->setOutlineColor(pRed);
m_pCircleColliderShape->setColor(pTransparent);
m_pCircleColliderShape->setOutlineThickness(1.0f);
m_pCollisionNodeShape = (RectangleShape*)m_pGM->getShape("Rectangle", "CollisionNodeShape");
m_pCollisionNodeShape->setColor(pRedTransparent);
m_pCollisionNodeShape->setSize(m_nTileWidth, m_nTileHeight);
// Cluster
m_pClusterShape = (RectangleShape*)m_pGM->getShape("Rectangle", "ClusterShape");
m_pClusterShape->setOutlineColor(pBlue);
m_pClusterShape->setColor(pTransparent);
m_pClusterShape->setOutlineThickness(2.0f);
m_pMap->getClusterSize(m_nClusterWidth, m_nClusterHeight);
m_pClusterShape->setSize(m_nClusterWidth, m_nClusterHeight);
m_pMap->getClusterIndexLimits(m_iClusterMin, m_iClusterMax, m_jClusterMin, m_jClusterMax);
m_pEntranceShape = (RectangleShape*)m_pGM->getShape("Rectangle", "EntranceShape");
m_pEntranceShape->setOutlineColor(pBlue);
m_pEntranceShape->setColor(pBlueTransparent);
m_pEntranceShape->setSize(m_nTileWidth, m_nTileHeight);
m_pTransitionShape = (ArrowShape*)m_pGM->getShape("Arrow", "TransitionShape");
m_pTransitionShape->setOutlineColor(pGreenTransparent);
m_pTransitionShape->setColor(pGreenTransparent);
m_pTransitionShape->setSize(m_nTileWidth, m_nTileHeight*0.5f);
m_pEdgeShape = (ArrowShape*)m_pGM->getShape("Arrow", "EdgeShape");
m_pEdgeShape->setOutlineColor(pRed);
m_pEdgeShape->setColor(pRedTransparent);
m_pEdgeShape->setSize(m_nTileWidth, m_nTileHeight*0.5f);
//Steering
m_pTarget = (LineShape*)m_pGM->getShape("Line", "Target");
m_pTarget->setColor(pGreenTransparent);
m_pSteeringLine = (LineShape*)m_pGM->getShape("Line", "Steering");
m_pSteeringLine->setColor(pBlue);
m_pForceLine = (LineShape*)m_pGM->getShape("Line", "Force");
m_pForceLine->setColor(pBlack);
m_pVelocityLine = (LineShape*)m_pGM->getShape("Line", "Velocity");
m_pVelocityLine->setColor(pRed);
return true;
}
bool AITools::isButton(int _i, Vector2f& _vMousePosition)
{
int i = _i % 5;
int j = _i / 5;
FloatRect r(m_rCommandWindow.m_fX + i * 46, m_rCommandWindow.m_fY + j * 38, 46.f, 38.f);
if (r.contains(_vMousePosition))
{
return true;
}
return false;
}
bool AITools::onUpdate()
{
// FPS
Time frameTime = TimeManager::getSingleton()->getFrameTime();
m_pTextFPS->setString(to_string((int)(1 / frameTime.asSeconds())) + " fps");
// Selection
if (m_pGM->isMouseButtonPressed(Button::MouseLeft))
{
if (!m_bSelection) // just pressed
{
m_vStartSelection = m_pGM->getMousePosition();
}
m_bSelection = true;
}
else
{
if (m_bSelection) // just released
{
m_vEndSelection = m_pGM->getMousePosition();
m_pGM->unselectEntities();
m_pGM->selectEntities(m_vStartSelection, m_vEndSelection);
}
m_bSelection = false;
}
// Command
if (m_pGM->isMouseButtonPressed(Button::MouseRight))
{
if (!m_bCommand) // just pressed
{
m_eCommandType = Command_Invalid;
Vector2f vMousePosition = m_pGM->getMousePosition();
if (m_rCommandWindow.contains(vMousePosition))
{
if (isButton(0, vMousePosition))
{
m_eCommandType = Command_Reset;
}
else if (isButton(1, vMousePosition))
{
m_eCommandType = Command_Kill;
}
else if (isButton(2, vMousePosition))
{
m_eCommandType = Command_Stop;
}
else if (isButton(3, vMousePosition))
{
m_eCommandType = Command_GoToHQ;
}
else if (isButton(4, vMousePosition))
{
m_eCommandType = Command_GoTo;
}
else if (isButton(5, vMousePosition))
{
m_eCommandType = Command_Build;
}
else if (isButton(6, vMousePosition))
{
m_eCommandType = Command_Mine;
}
else if (isButton(7, vMousePosition))
{
m_eCommandType = Command_Harvest;
}
else if (isButton(8, vMousePosition))
{
m_eCommandType = Command_Die;
}
else if (isButton(9, vMousePosition))
{
m_eCommandType = Command_Boost;
}
else if (isButton(10, vMousePosition))
{
m_eCommandType = Command_GoToHQWithLumber;
}
}
}
m_bCommand = true;
}
else
{
if (m_bCommand) // just released
{
// Restart the command display timer
m_CommandDisplayClock.restart();
// Do the command
ListEntity* pSelectedEntities = m_pGM->getSelectedEntities();
for (ListEntity::iterator i = pSelectedEntities->begin(); i != pSelectedEntities->end(); ++i)
{
Entity* pEntity = (Entity*)*i;
// CharacterController
m_pCharacterController = pEntity->getComponent<CharacterController>();
if (m_pCharacterController)
{
if (m_eCommandType == Command_Reset)
{
m_pTextCommand->setString("Reset");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Reset, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Default);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Kill)
{
m_pTextCommand->setString("Kill");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Kill, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Chop);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Stop)
{
m_pTextCommand->setString("Stop");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Stop, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Idle);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_GoToHQ)
{
m_pTextCommand->setString("GoToWithGold");
MsgManager::getSingleton()->sendMsg(0.f, MSG_GoToWithGold, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Walk);
//m_pCharacterController->setCondition(kACond_Gold);
}
else if (m_eCommandType == Command_GoTo)
{
m_pTextCommand->setString("GoTo");
MsgManager::getSingleton()->sendMsg(0.f, MSG_GoTo, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Walk);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Build)
{
m_pTextCommand->setString("Build");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Build, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Chop);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Mine)
{
m_pTextCommand->setString("Mine");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Mine, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Chop);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Harvest)
{
m_pTextCommand->setString("Harvest");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Harvest, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Chop);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Die)
{
m_pTextCommand->setString("Die");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Hit, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Die);
//m_pCharacterController->setCondition(kACond_Default);
}
else if (m_eCommandType == Command_Boost)
{
m_pTextCommand->setString("Boost");
MsgManager::getSingleton()->sendMsg(0.f, MSG_Boost, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Idle);
}
else if (m_eCommandType == Command_GoToHQWithLumber)
{
m_pTextCommand->setString("GoToWithLumber");
MsgManager::getSingleton()->sendMsg(0.f, MSG_GoToWithLumber, 0, pEntity->GetID(), -1);
//m_pCharacterController->setAction(kAct_Walk);
//m_pCharacterController->setCondition(kACond_Lumber);
}
else
{
m_pTextCommand->setString("?");
}
}
}
m_eCommandType = Command_Invalid;
}
m_bCommand = false;
}
return true;
}
bool AITools::onDraw()
{
// todo : temporary
return true;
// Selection
if (m_pGM->isMouseButtonPressed(Button::MouseLeft))
{
Vector2f vMousePosition = m_pGM->getMousePosition();
m_pSelectionShape->setPosition(m_vStartSelection.getX(), m_vStartSelection.getY());
m_pSelectionShape->setSize(vMousePosition.getX() - m_vStartSelection.getX(), vMousePosition.getY() - m_vStartSelection.getY());
m_pSelectionShape->draw();
}
// Diagnostics
ListEntity* pSelectedEntities = m_pGM->getSelectedEntities();
for (ListEntity::iterator i = pSelectedEntities->begin(); i != pSelectedEntities->end(); ++i)
{
Entity* pEntity = (Entity*)*i;
Vector2f position = pEntity->getPosition();
m_pTextDiagnostics->setPosition(position.getX() + 36, position.getY() - 50);
string szDiagnostics;
szDiagnostics += pEntity->getName();
Agent* pAgent = pEntity->getComponent<Agent>();
if (pAgent)
{
// Stats
szDiagnostics += "\nHea: ";
szDiagnostics += to_string(pAgent->getHealth());
szDiagnostics += " Str: ";
szDiagnostics += to_string(pAgent->getStrength());
szDiagnostics += " Int: ";
szDiagnostics += to_string(pAgent->getIntelligence());
szDiagnostics += " Dex: ";
szDiagnostics += to_string(pAgent->getDexterity());
}
// CharacterController
m_pCharacterController = pEntity->getComponent<CharacterController>();
if (m_pCharacterController)
{
szDiagnostics += "\nAct°: ";
szDiagnostics += to_string(m_pCharacterController->getAction());
szDiagnostics += " Condit°: ";
szDiagnostics += to_string(m_pCharacterController->getCondition());
szDiagnostics += " Direct°: ";
szDiagnostics += to_string(m_pCharacterController->getDirection());
}
m_pTextDiagnostics->setString(szDiagnostics);
m_pTextDiagnostics->draw();
// Steering
m_pSteering = pEntity->getComponent<Steering>();
if (m_pSteering)
{
Vector2f start = pEntity->getPosition();
Entity* pTarget = m_pSteering->getTarget();
if (pTarget)
{
Vector2f end = pTarget->getPosition() + m_pSteering->getTargetOffset();
m_pTarget->setStartAndEnd(start.getX(), start.getY(), end.getX(), end.getY());
m_pTarget->draw();
}
Vector2f steeringend = start + m_pSteering->getSteeringDirection();
m_pSteeringLine->setStartAndEnd(start.getX(), start.getY(), steeringend.getX(), steeringend.getY());
m_pSteeringLine->draw();
m_pVehicle = pEntity->getComponent<Vehicle>();
if (m_pVehicle)
{
Vector2f forceend = start + m_pVehicle->getLastForce();
m_pForceLine->setStartAndEnd(start.getX(), start.getY(), forceend.getX(), forceend.getY());
m_pForceLine->draw();
Vector2f velocityend = start + m_pVehicle->getVelocity();
m_pVelocityLine->setStartAndEnd(start.getX(), start.getY(), velocityend.getX(), velocityend.getY());
m_pVelocityLine->draw();
}
}
}
// Commands
if (!pSelectedEntities->empty())
{
m_pCommandsSprite->draw();
}
// FPS
m_pTextFPS->draw();
if (m_CommandDisplayClock.getElapsedTime().asSeconds() < m_fCommandDisplayTime)
{
m_pTextCommand->draw();
}
/*
// Grid (slow drawing)
for (short i = m_iMin; i <= m_iMax; i++)
{
for (short j = m_jMin; j <= m_jMax; j++)
{
m_pNodeShape->setPosition((float)i*m_nTileWidth, (float)j*m_nTileHeight);
m_pNodeShape->draw();
}
}
*/
// Grid (fast drawing)
m_pLineShape->setScale(1.0f, (float)(m_jMax + 1)*m_nTileHeight);
for (short i = m_iMin; i <= m_iMax; i++)
{
m_pLineShape->setPosition((float)i*m_nTileWidth, (float)m_jMin);
m_pLineShape->draw();
}
m_pLineShape->setScale((float)(m_iMax + 1)*m_nTileWidth, 1.f);
for (short j = m_jMin; j <= m_jMax; j++)
{
m_pLineShape->setPosition((float)m_iMin, (float)j*m_nTileHeight);
m_pLineShape->draw();
}
// Collision nodes
for (short i = m_iMin; i <= m_iMax; i++)
{
for (short j = m_jMin; j <= m_jMax; j++)
{
if (m_pMap->getNode(i, j)->getTileCollisionId() == 9)
{
m_pCollisionNodeShape->setPosition((float)i*m_nTileWidth, (float)j*m_nTileHeight);
m_pCollisionNodeShape->draw();
}
}
}
// Collisions
MapStringCollider* pStaticColliders = PhysicsManager::getSingleton()->getStaticColliders();
DisplayCollider(pStaticColliders);
MapStringCollider* pDynamicColliders = PhysicsManager::getSingleton()->getDynamicColliders();
DisplayCollider(pDynamicColliders);
// Cluster
short nVariableClusterWidth, nVariableClusterHeigth;
for (short i = m_iClusterMin; i < m_iClusterMax; i++)
{
for (short j = m_jClusterMin; j < m_jClusterMax; j++)
{
Cluster* pCluster = m_pMap->getCluster(i, j);
pCluster->getSize(nVariableClusterWidth, nVariableClusterHeigth);
m_pClusterShape->setPosition((float)i*m_nClusterWidth*m_nTileWidth, (float)j*m_nClusterHeight*m_nTileHeight);
m_pClusterShape->setSize((float)nVariableClusterWidth*m_nTileWidth, (float)nVariableClusterHeigth*m_nTileHeight);
m_pClusterShape->draw();
// Entrances
vector<Entrance*>* vEntrances = pCluster->getEntrances();
for (size_t e = 0; e < vEntrances->size(); e++)
{
Entrance* pEntrance = (*vEntrances)[e];
m_pEntranceShape->setPosition((float)pEntrance->m_pStart->getX()*m_nTileWidth, (float)pEntrance->m_pStart->getY()*m_nTileHeight);
m_pEntranceShape->draw();
m_pEntranceShape->setPosition((float)pEntrance->m_pEnd->getX()*m_nTileWidth, (float)pEntrance->m_pEnd->getY()*m_nTileHeight);
m_pEntranceShape->draw();
}
}
}
for (short i = m_iClusterMin; i < m_iClusterMax; i++)
{
for (short j = m_jClusterMin; j < m_jClusterMax; j++)
{
Cluster* pCluster = m_pMap->getCluster(i, j);
// Transitions
vector<Transition*>* vTransitions = pCluster->getTransitions();
for (size_t t = 0; t < vTransitions->size(); t++)
{
Transition* pTransition = (*vTransitions)[t];
m_pTransitionShape->setStartAndEnd(
(float)(pTransition->m_pStart->getX() + 0.5f)*m_nTileWidth, (float)(pTransition->m_pStart->getY() + 0.5f)*m_nTileWidth,
(float)(pTransition->m_pEnd->getX() + 0.5f)*m_nTileHeight, (float)(pTransition->m_pEnd->getY() + 0.5f)*m_nTileHeight
);
m_pTransitionShape->draw();
}
// Edges
vector<Edge*>* vEdges = pCluster->getEdges();
for (size_t t = 0; t < vEdges->size(); t++)
{
Edge* pEdge = (*vEdges)[t];
m_pEdgeShape->setStartAndEnd(
(float)(pEdge->m_pStart->getX() + 0.5f)*m_nTileWidth, (float)(pEdge->m_pStart->getY() + 0.5f)*m_nTileWidth,
(float)(pEdge->m_pEnd->getX() + 0.5f)*m_nTileHeight, (float)(pEdge->m_pEnd->getY() + 0.5f)*m_nTileHeight
);
m_pEdgeShape->draw();
}
}
}
return true;
}
bool AITools::onQuit()
{
return true;
}
void AITools::DisplayCollider(MapStringCollider* _pColliders)
{
for (MapStringCollider::iterator it = _pColliders->begin(); it != _pColliders->end(); ++it)
{
Collider* pCollider = (Collider*)(it->second);
EnumColliderType type = pCollider->getColliderType();
if (type == Collider_Box)
{
BoxCollider* pBoxCollider = (BoxCollider*)pCollider;
Vector2f position = pBoxCollider->getOrigin();
Vector2f size = pBoxCollider->getSize();
m_pBoxColliderShape->setPosition(position.getX(), position.getY());
m_pBoxColliderShape->setSize(size.getX(), size.getY());
m_pBoxColliderShape->draw();
}
else if (type == Collider_Circle)
{
CircleCollider* pCircleCollider = (CircleCollider*)pCollider;
Vector2f position = pCircleCollider->getWorldCenter();
float radius = pCircleCollider->getRadius();
m_pCircleColliderShape->setPosition(position.getX() - radius, position.getY() - radius);
m_pCircleColliderShape->setRadius(radius);
m_pCircleColliderShape->draw();
}
}
}<file_sep>#include "stdafx.h"
#include "AI\Pathfinding\ClusterSearchManager.h"
namespace crea
{
ClusterSearchManager::ClusterSearchManager()
{
m_pMap = nullptr;
m_pCluster = nullptr;
}
ClusterSearchManager::~ClusterSearchManager()
{
MapStringClusterSearch::iterator it = m_ClusterSearches.begin();
while (it != m_ClusterSearches.end()) {
delete (*it).second;
it = m_ClusterSearches.erase(it);
}
}
ClusterSearch* ClusterSearchManager::getClusterSearch(string _szName)
{
MapStringClusterSearch::iterator it = m_ClusterSearches.find(_szName);
if (it == m_ClusterSearches.end())
{
ClusterSearch* pClusterSearch = new ClusterSearch();
m_ClusterSearches[_szName] = pClusterSearch;
return pClusterSearch;
}
else
{
return it->second;
}
}
}<file_sep>#include "stdafx.h"
#include "AI\Pathfinding\MapSearch.h"
#include "AI\Pathfinding\MapSearchNode.h"
#include "AI\Pathfinding\MapSearchManager.h"
#include "Data\Node.h"
namespace crea
{
MapSearch::MapSearch()
{
m_uiSearchState = (SearchState)AStarSearch<MapSearchNode>::SEARCH_STATE_NOT_INITIALISED;
}
MapSearch::~MapSearch()
{
}
bool MapSearch::setStartAndGoal(Vector2f _vStart, Vector2f _vGoal)
{
bool bAvailable = false;
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_NOT_INITIALISED)
{
bAvailable = true;
}
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED)
{
FreeSolutionNodes();
bAvailable = true;
}
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_FAILED)
{
bAvailable = true;
}
if (bAvailable)
{
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
Vector2f vStart = pMap->getNodePositionFromPixels(_vStart);
Vector2f vGoal = pMap->getNodePositionFromPixels(_vGoal);
MapSearchNode nodeStart((int)vStart.getX(), (int)vStart.getY());
MapSearchNode nodeEnd((int)vGoal.getX(), (int)vGoal.getY());
// Set Start and goal states
SetStartAndGoalStates(nodeStart, nodeEnd);
m_uiSearchState = (SearchState)SearchStep();
}
return bAvailable;
}
MapSearch::SearchState MapSearch::update()
{
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SEARCHING)
{
// Step into search
m_uiSearchState = (SearchState)SearchStep();
}
return m_uiSearchState;
}
bool MapSearch::getSolution(VectorVector2f& _vSolution)
{
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED)
{
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
MapSearchNode* node = GetSolutionStart();
while (node)
{
Vector2f vNode = pMap->getPixelsFromNodePosition(Vector2f((float)node->x, (float)node->y));
_vSolution.push_back(new Vector2f(vNode));
node = GetSolutionNext();
}
return true;
}
return false;
}
bool MapSearch::getOpenList(VectorVector2f& _vOpenList)
{
if (m_uiSearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SEARCHING)
{
_vOpenList.clear();
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
MapSearchNode* node = this->GetOpenListStart();
while (node)
{
Vector2f vNode = pMap->getPixelsFromNodePosition(Vector2f((float)node->x, (float)node->y));
_vOpenList.push_back(new Vector2f(vNode));
node = GetOpenListNext();
}
return true;
}
return false;
}
}<file_sep>/***************************************************/
/* Nom: IDrawable.h
/* Description: IDrawable
/* Auteur: <NAME>
/***************************************************/
#ifndef _IDrawable_H
#define _IDrawable_H
namespace crea
{
class CREAENGINE_API IDrawable
{
public:
IDrawable()
{
}
~IDrawable()
{
}
virtual void draw() = 0;
};
} // namespace crea
#endif // _IDrawable_H<file_sep>/***************************************************/
/* Nom: SFMLSprite.h
/* Description: SFMLSprite
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLSprite_H
#define _SFMLSprite_H
#include "Graphics\Sprite.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLSprite : public Sprite
{
public:
sf::Sprite m_sprite;
SFMLSprite()
{
}
virtual ~SFMLSprite()
{
}
virtual void draw()
{
sf::RenderWindow* pWin = SFMLFacade::Instance().m_pWindow;
pWin->draw(m_sprite);
}
virtual void setTexture(Texture* _pTexture)
{
m_sprite.setTexture(*((SFMLTexture*)_pTexture)->m_pTexture);
}
virtual void setPosition(float _x, float _y)
{
m_sprite.setPosition(_x, _y);
}
virtual void setTextureRect(int _x, int _y, int _w, int _h)
{
m_sprite.setTextureRect(sf::IntRect(_x, _y, _w, _h));
}
virtual void setScale(float _x, float _y)
{
m_sprite.setScale(_x, _y);
}
virtual void setOrigin(float _x, float _y)
{
m_sprite.setOrigin(_x, _y);
}
virtual Sprite* clone()
{
return new SFMLSprite(*this);
}
};
} // namespace crea
#endif // _SFMLSprite_H<file_sep>/***************************************************/
/* Nom: SceneGame.h
/* Description: SceneGame
/* Auteur: <NAME>
/***************************************************/
#ifndef __SceneGame_H_
#define __SceneGame_H_
#include "Core\Scene.h"
using namespace crea;
class SceneGame : public Scene
{
GameManager* m_pGM;
Entity* m_pEntity1;
Sprite* m_pSprite1;
SpriteRenderer* m_pSpriteRenderer;
public:
SceneGame();
virtual ~SceneGame();
virtual bool onInit();
virtual bool onUpdate();
virtual bool onDraw();
virtual bool onQuit();
};
#endif
<file_sep>/***************************************************/
/* Nom: GL3Graphics.h
/* Description: GL3Graphics
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Graphics_H
#define _GL3Graphics_H
#include "GL3Facade.h"
#include "Graphics\IGraphics.h"
#include "Graphics\IFont.h"
#include "Graphics\Texture.h"
#include "Graphics\Text.h"
#include "Graphics\Sprite.h"
namespace crea
{
} // namespace crea
#endif // _GL3Graphics_H
<file_sep>/***************************************************/
/* Nom: ScenePlanning.h
/* Description: ScenePlanning
/* Auteur: <NAME>
/***************************************************/
#ifndef __ScenePlanning_H_
#define __ScenePlanning_H_
#include "Core\Scene.h"
#include "Tools\AITools.h"
#include "Scripts\CellsScriptFactory.h"
using namespace crea;
class ScenePlanning : public Scene
{
GameManager* m_pGM;
IntRect m_rWindowRect;
// MapGoap
Entity* m_pEntity4;
Map* m_pMap;
MapRenderer* m_pMapRenderer;
// AI Tools
bool m_bUseAITools;
AITools* m_pAITools;
// Scripts
CellsScriptFactory* m_pCellsScriptFactory;
public:
ScenePlanning();
virtual ~ScenePlanning();
virtual bool onInit();
virtual bool onUpdate();
virtual bool onDraw();
virtual bool onQuit();
};
#endif
<file_sep>/***************************************************/
/* Nom: FSMBalistaLive.h
/* Description: FSMBalistaLive
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMBalistaLive_H_
#define __FSMBalistaLive_H_
#include "AI\StateMachine.h"
#include "Scripts\CharacterController.h"
#include "FSMBalistaGoTo.h"
using namespace crea;
class FSMBalistaLive : public StateMachine
{
GameManager* m_pGM;
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
Steering* m_pSteering;
Vehicle* m_pVehicle;
FSMBalistaGoTo* m_pFSMBalistaGoTo;
Vector2f m_vTarget;
bool m_bPaused;
public:
FSMBalistaLive();
virtual ~FSMBalistaLive();
void setEntity(Entity* _p) { m_pEntity = _p; }
void setCharacterController(CharacterController* _p) { m_pCharacterController = _p; }
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone() { return new FSMBalistaLive(*this); }
bool Move();
};
#endif
<file_sep>#include "stdafx.h"
#include "AI\Pathfinding\MapSearchManager.h"
#include "Data\Node.h"
namespace crea
{
MapSearchManager::MapSearchManager()
{
m_pCurrentMap = nullptr;
}
MapSearchManager::~MapSearchManager()
{
MapStringMapSearch::iterator it = m_MapSearches.begin();
while (it != m_MapSearches.end()) {
delete (*it).second;
it = m_MapSearches.erase(it);
}
}
MapSearch* MapSearchManager::getMapSearch(string _szName)
{
MapStringMapSearch::iterator it = m_MapSearches.find(_szName);
if (it == m_MapSearches.end())
{
MapSearch* pMapSearch = new MapSearch();
m_MapSearches[_szName] = pMapSearch;
return pMapSearch;
}
else
{
return it->second;
}
}
}<file_sep>/***************************************************/
/* Nom: DataManager.h
/* Description: DataManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __DATAMANAGER_H_
#define __DATAMANAGER_H_
#include <map>
using namespace std;
#define DATAFONTPATH "data/Font/"
#define DATATEXTUREPATH "data/Image/"
#define DATAMAPPATH "data/Map/"
#define DATAAGENTPATH "data/Agent/"
#define DATAANIMATIONPATH "data/Animation/"
#define DATAMATERIALPATH "data/Material/"
#define DATASHADERPATH "data/Shader/"
namespace crea
{
class Font;
class Texture;
class Color;
class Text;
class Sprite;
class Shape;
class Map;
class Agent;
class Animation;
class ActionTable;
class Vehicle;
class Material;
class Shader;
class CREAENGINE_API MapStringFont : public map<string, Font*> {};
class CREAENGINE_API MapStringTexture : public map<string, Texture*> {};
class CREAENGINE_API MapStringColor : public map<string, Color*> {};
class CREAENGINE_API MapStringText : public map<string, Text*> {};
class CREAENGINE_API MapStringSprite : public map<string, Sprite*> {};
class CREAENGINE_API MapStringShape : public map<string, Shape*> {};
class CREAENGINE_API MapStringMap : public map<string, Map*> {};
class CREAENGINE_API MapStringAgent : public map<string, Agent*> {};
class CREAENGINE_API MapStringAnimation : public map<string, Animation*> {};
class CREAENGINE_API MapStringActionTable : public map<string, ActionTable*> {};
class CREAENGINE_API MapStringVehicle : public map<string, Vehicle*> {};
class CREAENGINE_API MapStringMaterial : public map<string, Material*> {};
class CREAENGINE_API MapStringShader : public map<string, Shader*> {};
class CREAENGINE_API DataManager
{
MapStringFont m_pFonts;
MapStringTexture m_pTextures;
MapStringColor m_pColors;
MapStringText m_pTexts;
MapStringSprite m_pSprites;
MapStringShape m_pShapes;
MapStringMap m_pMaps;
MapStringAgent m_pAgents;
MapStringAnimation m_pAnimations;
MapStringActionTable m_pActionTables;
MapStringVehicle m_pVehicles;
MapStringMaterial m_pMaterials;
int materialInstanceCount = 0;
MapStringShader m_pShaders;
bool m_bIsCleared;
DataManager();
public:
virtual ~DataManager();
static DataManager* getSingleton();
Font* getFont(const string& _szName, bool _bCloned = false);
Texture* getTexture(const string& _szName, bool _bCloned = false);
Color* getColor(const string& _szName, bool _bCloned = false);
Text* getText(const string& _szName, bool _bCloned = false);
Sprite* getSprite(const string& _szName, bool _bCloned = false);
Shape* getShape(const string& _szType, const string& _szName, bool _bCloned = false);
Map* getMap(const string& _szName, bool _bCloned = false);
Agent* getAgent(const string& _szName, bool _bCloned = false);
Animation* getAnimation(const string& _szName, bool _bCloned = false);
ActionTable* getActionTable(const string& _szName, bool _bCloned = false);
Vehicle* getVehicle(const string& _szName, bool _bCloned = false);
Material* getMaterial(const string& _szName, bool _bCloned = false);
Shader* getShader(const string& _szName, bool _bCloned = false);
void clear();
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Tools\Logger.h"
namespace crea
{
ILogger* ILogger::s_Instance = NULL;
ILogger::~ILogger()
{
s_Instance = nullptr;
}
void ILogger::SetLogger(ILogger* Logger)
{
if (s_Instance)
{
delete s_Instance;
}
s_Instance = Logger;
}
void ILogger::Log(const char* Format, ...)
{
// Formatage du message dans une chaîne de caractère
char sBuffer[512];
va_list Params;
va_start(Params, Format);
vsprintf_s(sBuffer, 512, Format, Params);
va_end(Params);
// Loggization
s_Instance->Write(sBuffer);
}
template <class T> ILogger& ILogger::operator <<(const T& ToLog)
{
std::ostringstream Stream;
Stream << ToLog;
Write(Stream.str());
// On n'oublie pas de toujours renvoyer notre instance, pour pouvoir chaîner les appels à <<
return Log();
}
ILogger& ILogger::Log()
{
return *s_Instance;
}
} // namespace crea<file_sep>/***************************************************/
/* Nom: GL3Shape.h
/* Description: GL3Shape
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Shape_H
#define _GL3Shape_H
#include "Graphics\Shape.h"
namespace crea
{
struct VertexPosition
{
float x;
float y;
float z;
};
struct VertexColor
{
float r;
float g;
float b;
};
struct VertexUV
{
float u;
float v;
};
struct VertexNormal
{
float x;
float y;
float z;
};
class GL3Shape : public Shape
{
protected:
GL3Color m_color;
unsigned int VAO, VBO, VCO, VDO, VNO, EBO;
unsigned int m_nbVertices;
unsigned int m_nbIndices;
VertexPosition* m_pVerticesPositions;
unsigned int* m_pIndices;
VertexColor* m_pVerticesColors;
VertexUV* m_pVerticesUV;
VertexNormal* m_pVerticesNormal;
bool m_bFlipHorizontal = false;
bool m_bFlipVertical = false;
bool m_updated = true;
void send()
{
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
// Position buffer
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, m_nbVertices * sizeof(VertexPosition), m_pVerticesPositions, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_nbIndices * sizeof(unsigned int), m_pIndices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// VertexColor buffer
if (m_pVerticesColors)
{
glBindBuffer(GL_ARRAY_BUFFER, VCO);
glBufferData(GL_ARRAY_BUFFER, m_nbVertices * sizeof(VertexColor), m_pVerticesColors, GL_STATIC_DRAW);
// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
// uv buffer
if (m_pVerticesUV)
{
glBindBuffer(GL_ARRAY_BUFFER, VDO);
glBufferData(GL_ARRAY_BUFFER, m_nbVertices * sizeof(VertexUV), m_pVerticesUV, GL_STATIC_DRAW);
// texture coord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
// normals buffer
if (m_pVerticesNormal)
{
glBindBuffer(GL_ARRAY_BUFFER, VNO);
glBufferData(GL_ARRAY_BUFFER, m_nbVertices * sizeof(VertexNormal), m_pVerticesNormal, GL_STATIC_DRAW);
// normal attribute
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(3);
}
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// remember: do NOT unbind the EBO while a VAO is active as the bound element buffer object IS stored in the VAO; keep the EBO bound.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
}
public:
GL3Shape()
{
m_updated = true;
m_nbVertices = 0;
m_nbIndices = 0;
m_pVerticesPositions = nullptr;
m_pIndices = nullptr;
m_pVerticesColors = nullptr;
m_pVerticesNormal = nullptr;
m_color.setValues(0, 0, 255, 255);
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &VCO);
glGenBuffers(1, &VDO);
glGenBuffers(1, &VNO);
glGenBuffers(1, &EBO);
}
virtual ~GL3Shape()
{
if (m_pVerticesColors)
{
delete m_pVerticesColors;
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &VCO);
glDeleteBuffers(1, &VDO);
glDeleteBuffers(1, &VNO);
glDeleteBuffers(1, &EBO);
}
void setVerticesPositions(VertexPosition _verticesPositions[], unsigned int _size)
{
assert(_size <= m_nbVertices);
for (unsigned int i = 0; i < _size; i++)
{
m_pVerticesPositions[i] = _verticesPositions[i];
}
m_updated = true;
}
void setVerticesIndices(unsigned int _indices[], unsigned int _size)
{
assert(_size <= m_nbIndices);
for (unsigned int i = 0; i < _size; i++)
{
m_pIndices[i] = _indices[i];
}
m_updated = true;
}
virtual void setColor(Color* _color)
{
GL3Color* pColor = (GL3Color*)_color;
m_color = *pColor;
if (m_nbVertices == 0)
return;
if (!m_pVerticesColors)
{
m_pVerticesColors = new VertexColor[m_nbVertices];
}
float r = m_color.getR();
float g = m_color.getG();
float b = m_color.getB();
for (unsigned int i = 0; i < m_nbVertices; i++)
{
m_pVerticesColors[i].r = r;
m_pVerticesColors[i].g = g;
m_pVerticesColors[i].b = b;
}
m_updated = true;
}
void setVerticesColors(Color _colors[], unsigned int _size)
{
GL3Color* pColor = (GL3Color*) &(_colors[0]);
m_color = *pColor;
if (m_nbVertices == 0)
return;
if (!m_pVerticesColors)
{
m_pVerticesColors = new VertexColor[m_nbVertices];
}
for (unsigned int i = 0; i < m_nbVertices; i++)
{
pColor = (GL3Color*) &(_colors[i]);
m_pVerticesColors[i].r = pColor->getR();
m_pVerticesColors[i].g = pColor->getG();
m_pVerticesColors[i].b = pColor->getB();
}
m_updated = true;
}
void setVerticesUV(VertexUV _uvs[], unsigned int _size)
{
if (m_nbVertices == 0)
return;
if (!m_pVerticesUV)
{
m_pVerticesUV = new VertexUV[m_nbVertices];
}
VertexUV uv;
for (unsigned int i = 0; i < m_nbVertices; i++)
{
uv = _uvs[i];
m_pVerticesUV[i].u = uv.u;
m_pVerticesUV[i].v = uv.v;
}
m_updated = true;
}
void setVerticesNormals(VertexNormal _normals[], unsigned int _size)
{
if (m_nbVertices == 0)
return;
if (!m_pVerticesNormal)
{
m_pVerticesNormal = new VertexNormal[m_nbVertices];
}
VertexNormal n;
for (unsigned int i = 0; i < m_nbVertices; i++)
{
n = _normals[i];
m_pVerticesNormal[i].x = n.x;
m_pVerticesNormal[i].y = n.y;
m_pVerticesNormal[i].z = n.z;
}
m_updated = true;
}
virtual void draw()
{
if (m_updated)
{
send();
m_updated = false;
}
}
virtual void setOutlineColor(Color* _pColor)
{
}
virtual void setOutlineThickness(float _fPixels)
{
}
virtual void setPosition(float _x, float _y)
{
}
virtual void setRotation(float _angle)
{
}
virtual void setScale(float _x, float _y)
{
}
virtual void setOrigin(float _x, float _y)
{
}
};
class GL3RectangleShape : public GL3Shape
{
protected:
VertexPosition m_vertices[4];
unsigned int m_indices[4];
glm::vec2 position = glm::vec2(0.f, 0.f);
glm::vec2 origin = glm::vec2(0.f, 0.f);
glm::vec2 size = glm::vec2(1.f, 1.f);
glm::vec2 scale = glm::vec2(1.f, 1.f);
glm::vec2 textureSize = glm::vec2(64.f, 64.f);
glm::vec2 displaySize = glm::vec2(128.f, 128.f);
glm::vec2 windowSize = glm::vec2(1280.f, 800.f);
public:
GL3RectangleShape()
{
// 1 ___ 3
// |\ |
// | \ |
// 0|__\|2
m_nbVertices = 4;
m_pVerticesPositions = &m_vertices[0];
setSize(1.f, 1.f);
m_nbIndices = 4;
m_pIndices = &m_indices[0];
unsigned int i[] = { 0, 2, 1, 3 };
setVerticesIndices(i, 4);
// Color
Color b(Color::blue);
setColor(&b);
// UV
VertexUV uv[] = {
{ 0.0f, 0.0f },// bottom left
{ 0.0f, 1.0f },// top left
{ 1.0f, 0.0f },// bottom right
{ 1.0f, 1.0f }// top right
};
setVerticesUV(uv, 4);
}
virtual ~GL3RectangleShape()
{
}
virtual void draw()
{
GL3Shape::draw();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLE_STRIP, m_nbIndices, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void updateVertices()
{
float posX = 2 * (position.x - origin.x) / windowSize.x - 1.f;
float offsetX = 2 * size.x * displaySize.x / windowSize.x;
float posY = -2 * (position.y - origin.y) / windowSize.y + 1.f;
float offsetY = - 2 * size.y * displaySize.y / windowSize.y;
if (!m_bFlipHorizontal)
{
VertexPosition v[] = {
{ posX, posY + offsetY }, // bottom left
{ posX, posY }, // top left
{ posX + offsetX, posY + offsetY }, // bottom right
{ posX + offsetX, posY }, // top right
};
setVerticesPositions(v, 4);
}
else
{
VertexPosition v[] = {
{ posX + offsetX, posY + offsetY }, // bottom left
{ posX + offsetX, posY }, // top left
{ posX, posY + offsetY }, // bottom right
{ posX, posY }, // top right
};
setVerticesPositions(v, 4);
}
}
virtual void setSize(float _x, float _y)
{
size = glm::vec2(_x, _y);
updateVertices();
}
virtual void setPosition(float _x, float _y)
{
position = glm::vec3(_x, _y, 0.f);
updateVertices();
}
virtual void setScale(float _x, float _y)
{
if (scale != glm::vec2(_x, _y))
{
if (m_bFlipHorizontal && _x > 0.f
|| !m_bFlipHorizontal && _x < 0.f) // Flip horizontal
{
m_bFlipHorizontal = !m_bFlipHorizontal;
}
scale = glm::vec2(_x, _y);
updateVertices();
}
}
virtual void setOrigin(float _x, float _y)
{
origin = glm::vec2(_x, _y);
updateVertices();
}
void setTextureSize(int _x, int _y)
{
textureSize = glm::vec2(_x, _y);
}
void setDisplaySize(int _x, int _y)
{
displaySize = glm::vec2(_x, _y);
}
void setWindowSize(int _x, int _y)
{
windowSize = glm::vec2(_x, _y);
}
GL3RectangleShape& operator= (const GL3RectangleShape& _rs)
{
setColor((Color*)&_rs.m_color);
position = _rs.position;
origin = _rs.origin;
size = _rs.size;
scale = _rs.scale;
textureSize = _rs.textureSize;
displaySize = _rs.displaySize;
windowSize = _rs.windowSize;
updateVertices();
return *this;
}
};
class GL3CircleShape : public GL3Shape
{
// todo: GL3CircleShape
public:
GL3CircleShape()
{
}
~GL3CircleShape()
{
}
virtual void setRadius(float _r)
{
}
void setNbPoints(int _iNbPoints)
{
}
void setSize(float _fSize, int _iNbSides = 20)
{
}
void draw()
{
}
};
class GL3ArrowShape : public GL3Shape
{
// todo: GL3ArrowShape
public:
GL3ArrowShape()
{
}
~GL3ArrowShape()
{
}
virtual void draw()
{
}
virtual void setSize(float _x, float _y)
{
}
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd)
{
}
};
class GL3LineShape : public GL3Shape
{
// todo: GL3LineShape
public:
GL3LineShape()
{
}
~GL3LineShape()
{
}
virtual void draw()
{
}
virtual void setSize(float _x, float _y)
{
}
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd)
{
}
};
} // namespace crea
#endif // _GL3Shape_H<file_sep>// Portions Copyright (C) <NAME>, 2001
#ifndef __MSGMANAGER_H__
#define __MSGMANAGER_H__
#include <list>
namespace crea
{
class Msg;
typedef std::list<Msg*> MessageContainer;
class CREAENGINE_API MsgManager : public Singleton <MsgManager>
{
public:
MsgManager(void);
~MsgManager(void);
void update();
void sendMsg(float delay, int name, objectID sender, objectID receiver, int state, void* data = NULL);
private:
MessageContainer m_delayedMessages;
void deliverDelayedMessages(void);
void routeMsg(Msg & msg);
};
}
#endif // __MSGMANAGER_H__<file_sep>#ifndef _CREAIMPORT_H
#define _CREAIMPORT_H
namespace crea
{
# ifdef CREAENGINE_EXPORTS
# define CREAENGINE_API __declspec(dllexport)
# else
# define CREAENGINE_API __declspec(dllimport)
# endif
} // namespace crea
#define INVALID_OBJECT_ID 0
typedef unsigned int objectID;
namespace crea
{
#define g_time TimeManager::getSingleton()
#define g_entitymanager EntityManager::getSingleton()
#define g_msgmanager MsgManager::getSingleton()
#define g_debuglog DebugLog::getSingleton()
}
#include "Tools\json\json.h"
#include "Core\Singleton.h"
#include "Core\GameManager.h"
#include "Core\SceneManager.h"
#include "Core\EntityManager.h"
#include "Core\Entity.h"
#include "Core\Scene.h"
#include "Core\Math.h"
#include "Core\Script.h"
#include "Core\ScriptFactory.h"
#include "Core\PhysicsManager.h"
#include "Core\MsgManager.h"
#include "Core\Msg.h"
#include "Data\Asset.h"
#include "Data\DataManager.h"
#include "Data\Node.h"
#include "Data\Map.h"
#include "Data\Animation.h"
#include "Graphics\Shader.h"
#include "Graphics\Color.h"
#include "Graphics\Material.h"
#include "Graphics\Font.h"
#include "Graphics\Text.h"
#include "Graphics\Texture.h"
#include "Graphics\Sprite.h"
#include "Graphics\Shape.h"
#include "Graphics\SpriteRenderer.h"
#include "Graphics\TextRenderer.h"
#include "Graphics\MapRenderer.h"
#include "Graphics\Animator.h"
#include "AI\Agent.h"
#include "AI\ActionTable.h"
#include "AI\StateMachine.h"
#include "AI\Pathfinding\MapSearchNode.h"
#include "AI\Pathfinding\MapSearch.h"
#include "AI\Pathfinding\MapSearchManager.h"
#include "AI\Pathfinding\ClusterSearchNode.h"
#include "AI\Pathfinding\ClusterSearch.h"
#include "AI\Pathfinding\ClusterSearchManager.h"
#include "AI\Pathfinding\Cluster.h"
#include "AI\Steering\Steering.h"
#include "AI\Steering\Vehicle.h"
#include "AI\Planning\Action.h"
#include "AI\Planning\Planner.h"
#include "AI\Planning\WorldState.h"
#include "AI\BehaviorTree\Behavior.h"
#include "AI\BehaviorTree\BehaviorTree.h"
#include "AI\BehaviorTree\Blackboard.h"
#include "Physics\Collider.h"
# endif // _CREAIMPORT_H<file_sep>/***************************************************/
/* Nom: MapRenderer.h
/* Description: MapRenderer
/* Auteur: <NAME>
/***************************************************/
#ifndef __MapRenderer_H_
#define __MapRenderer_H_
#include "Core\Component.h"
namespace crea
{
class Map;
class CREAENGINE_API MapRenderer : public Component
{
Map* m_pMap;
public:
MapRenderer();
virtual ~MapRenderer();
inline void setMap(Map* _pMap) { m_pMap = _pMap; }
inline Map* getMap() { return m_pMap; }
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { return new MapRenderer(*this); }
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: SceneMap.h
/* Description: SceneMap
/* Auteur: <NAME>
/***************************************************/
#ifndef __SceneMap_H_
#define __SceneMap_H_
#include "Core\Scene.h"
#include "Tools\AITools.h"
#include "Scripts\CellsScriptFactory.h"
using namespace crea;
class SceneMap : public Scene
{
GameManager* m_pGM;
// Map
Entity* m_pEntity3;
Map* m_pMap;
MapRenderer* m_pMapRenderer;
// AI Tools
bool m_bUseAITools;
AITools* m_pAITools;
// Scripts
CellsScriptFactory* m_pCellsScriptFactory;
public:
SceneMap();
virtual ~SceneMap();
virtual bool onInit();
virtual bool onUpdate();
virtual bool onDraw();
virtual bool onQuit();
};
#endif
<file_sep>// stdafx.h : fichier Include pour les fichiers Include système standard,
// ou les fichiers Include spécifiques aux projets qui sont utilisés fréquemment,
// et sont rarement modifiés
//
#pragma once
#include <stdio.h>
#include <tchar.h>
#include <cassert>
#include <iostream>
using namespace std;
#pragma warning( disable: 4251 )
// Constants
#define ONEOVER255 0.00392156862745f
#include <algorithm>
// Windows
//#include <Windows.h>
//#include <Windowsx.h>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
// GLAD / GLFW
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// JSON
#include "json.h"
// stb_image
#include <stb_image.h>
// assimp
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
// glm
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// FreeType
#include "ft2build.h"
#include "freetype/freetype.h"
#include "CreaImport.h"
#define SafeDelete(pObject) if(pObject != NULL) {delete pObject; pObject=NULL;}
#include "Graphics\GL3Facade.h"
#include "Graphics\GL3Font.h"
#include "Graphics\GL3Texture.h"
#include "Graphics\GL3Color.h"
#include "Graphics\GL3Text.h"
#include "Graphics\GL3Sprite.h"
#include "Graphics\GL3Shape.h"
#include "Graphics\GL3Shader.h"
#include "Graphics\GL3Material.h"
<file_sep>// Singleton class as authored by <NAME> in the book Game Programming Gems
// Portions Copyright (C) <NAME>, 2001
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <assert.h>
namespace crea
{
template <typename T>
class Singleton
{
public:
Singleton(void)
{
assert(ms_Singleton == nullptr);
int offset = (int)(T*)1 - (int)(Singleton <T> *)(T*)1;
ms_Singleton = (T*)((int)this + offset);
}
~Singleton(void) { assert(ms_Singleton != nullptr); ms_Singleton = nullptr; }
static T* getSingleton(void) { if (ms_Singleton != nullptr) return (ms_Singleton); else return new T; }
static bool doesSingletonExist(void) { return (ms_Singleton != nullptr); }
private:
static T* ms_Singleton;
};
template <typename T> T* Singleton <T>::ms_Singleton = nullptr;
}
#endif // __SINGLETON_H__<file_sep>/***************************************************/
/* Nom: Behavior.h
/* Description: Behavior
/* Auteur: <NAME>
/***************************************************/
#ifndef __BT_BEHAVIOR_H_
#define __BT_BEHAVIOR_H_
#include <vector>
namespace bt
{
// ============================================================================
enum Status
/**
* Return values of and valid states for Behaviors.
*/
{
BH_INVALID,
BH_SUCCESS,
BH_FAILURE,
BH_RUNNING,
BH_ABORTED,
};
class CREAENGINE_API Behavior
/**
* Base class for actions, conditions and composites.
*/
{
public:
virtual Status update() = 0;
virtual void onInitialize() {}
virtual void onTerminate(Status) {}
Behavior()
: m_eStatus(BH_INVALID)
{
}
virtual ~Behavior()
{
}
Status tick()
{
if (m_eStatus != BH_RUNNING)
{
onInitialize();
}
m_eStatus = update();
if (m_eStatus != BH_RUNNING)
{
onTerminate(m_eStatus);
}
return m_eStatus;
}
void reset()
{
m_eStatus = BH_INVALID;
}
void abort()
{
onTerminate(BH_ABORTED);
m_eStatus = BH_ABORTED;
}
bool isTerminated() const
{
return m_eStatus == BH_SUCCESS || m_eStatus == BH_FAILURE;
}
bool isRunning() const
{
return m_eStatus == BH_RUNNING;
}
Status getStatus() const
{
return m_eStatus;
}
virtual Behavior* clone() = 0;
private:
Status m_eStatus;
};
// ============================================================================
class CREAENGINE_API Decorator : public Behavior
{
protected:
Behavior * m_pChild;
public:
Decorator() {}
Decorator(Behavior* child) : m_pChild(child) {}
void addChild(Behavior* _pChild) { m_pChild = _pChild; }
};
// ============================================================================
class CREAENGINE_API Composite : public Behavior
{
protected:
typedef std::vector<Behavior*> Behaviors;
Behaviors m_Children;
public:
void addChild(Behavior* child) { m_Children.push_back(child); }
void removeChild(Behavior* _behavior)
{
auto a = std::remove_if(m_Children.begin(), m_Children.end(),
[=](Behavior* p) { return p == _behavior; });
m_Children.erase(a);
}
void clearChildren()
{
for (int i = 0; i < (int)m_Children.size(); i++)
{
Behavior* p = m_Children.back();
delete(p);
m_Children.pop_back();
}
m_Children.clear();
};
};
class CREAENGINE_API Sequence : public Composite
{
protected:
virtual ~Sequence()
{
}
virtual void onInitialize()
{
m_CurrentChild = m_Children.begin();
}
virtual Status update()
{
// Keep going until a child Behavior says it's running.
for (;;)
{
Status s = (*m_CurrentChild)->tick();
// If the child fails, or keeps running, do the same.
if (s != BH_SUCCESS)
{
return s;
}
// Hit the end of the array, job done!
if (++m_CurrentChild == m_Children.end())
{
return BH_SUCCESS;
}
}
}
virtual void onTerminate(Status s)
{
if (m_CurrentChild != m_Children.end())
{
(*m_CurrentChild)->onTerminate(s);
}
}
virtual Behavior* clone()
{
Sequence* p = new Sequence(*this);
for (int i = 0; i < (int)m_Children.size(); i++)
{
Behavior* pChild = m_Children[i];
p->addChild(pChild->clone());
}
return p;
}
Behaviors::iterator m_CurrentChild;
};
// ============================================================================
class CREAENGINE_API Selector : public Composite
{
protected:
virtual ~Selector()
{
}
virtual void onInitialize()
{
m_Current = m_Children.begin();
}
virtual Status update()
{
// Keep going until a child Behavior says its running.
for (;;)
{
Status s = (*m_Current)->tick();
// If the child succeeds, or keeps running, do the same.
if (s != BH_FAILURE)
{
return s;
}
// Hit the end of the array, it didn't end well...
if (++m_Current == m_Children.end())
{
return BH_FAILURE;
}
}
}
virtual Behavior* clone()
{
Selector* p = new Selector(*this);
for (int i = 0; i < (int)m_Children.size(); i++)
{
Behavior* pChild = m_Children[i];
p->addChild(pChild->clone());
}
return p;
}
Behaviors::iterator m_Current;
};
// ----------------------------------------------------------------------------
class CREAENGINE_API Parallel : public Composite
{
public:
enum Policy
{
RequireOne,
RequireAll,
};
Parallel(Policy forSuccess, Policy forFailure)
: m_eSuccessPolicy(forSuccess)
, m_eFailurePolicy(forFailure)
{
}
virtual ~Parallel() {}
protected:
Policy m_eSuccessPolicy;
Policy m_eFailurePolicy;
virtual Status update()
{
size_t iSuccessCount = 0, iFailureCount = 0;
for (Behaviors::iterator it = m_Children.begin(); it != m_Children.end(); ++it)
{
Behavior& b = **it;
if (!b.isTerminated())
{
b.tick();
}
if (b.getStatus() == BH_SUCCESS)
{
++iSuccessCount;
if (m_eSuccessPolicy == RequireOne)
{
return BH_SUCCESS;
}
}
if (b.getStatus() == BH_FAILURE)
{
++iFailureCount;
if (m_eFailurePolicy == RequireOne)
{
return BH_FAILURE;
}
}
}
if (m_eFailurePolicy == RequireAll && iFailureCount == m_Children.size())
{
return BH_FAILURE;
}
if (m_eSuccessPolicy == RequireAll && iSuccessCount == m_Children.size())
{
return BH_SUCCESS;
}
return BH_RUNNING;
}
virtual void onTerminate(Status)
{
for (Behaviors::iterator it = m_Children.begin(); it != m_Children.end(); ++it)
{
Behavior& b = **it;
if (b.isRunning())
{
b.abort();
}
}
}
};
class CREAENGINE_API Monitor : public Parallel
{
public:
Monitor()
: Parallel(Parallel::RequireOne, Parallel::RequireOne)
{
}
void addCondition(Behavior* condition)
{
m_Children.insert(m_Children.begin(), condition);
}
void addAction(Behavior* action)
{
m_Children.push_back(action);
}
};
// ============================================================================
class CREAENGINE_API ActiveSelector : public Selector
{
protected:
virtual void onInitialize()
{
m_Current = m_Children.end();
}
virtual Status update()
{
Behaviors::iterator previous = m_Current;
Selector::onInitialize();
Status result = Selector::update();
if (previous != m_Children.end() && m_Current != previous)
{
(*previous)->onTerminate(BH_ABORTED);
}
return result;
}
};
}
#endif //__BT_Behavior_H_
<file_sep>/***************************************************/
/* Nom: Steering.h
/* Description: Steering
/* Auteur: <NAME>
/***************************************************/
#ifndef __Steering_H_
#define __Steering_H_
#include "Core\Component.h"
#include "Core\Math.h"
#include "Core\GameManager.h"
#include "Graphics\Shape.h"
namespace crea
{
// Predefinitions
class GameManager;
class Behavior;
class CREAENGINE_API PairFloatBehavior : public pair<float, Behavior*>
{
public:
PairFloatBehavior(float _f, Behavior* _p);
~PairFloatBehavior();
};
class CREAENGINE_API Steering : public Component
{
Vector2f steer();
protected:
GameManager * m_pGM;
// Collider
Collider* m_pCollider;
// Target
Entity* m_pTarget;
Vector2f m_vTargetOffset;
std::vector<PairFloatBehavior*> m_behaviors; // All the behaviors and their weight associated
Vector2f m_vSteeringDirection;
public:
Steering();
virtual ~Steering();
void setCollider(Collider* _pCollider);
void setTarget(Entity* _pEntity) { m_pTarget = _pEntity; }
Entity* getTarget() { return m_pTarget; }
void setTargetOffset(Vector2f _vOffset) { m_vTargetOffset = _vOffset; }
Vector2f getTargetOffset() { return m_vTargetOffset; }
void addBehavior(Behavior* _behavior, float _weight);
void removeBehavior(Behavior* _behavior);
void clearBehaviors();
Vector2f getSteeringDirection() { return m_vSteeringDirection; }
string asString();
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone()
{
Steering* p = new Steering(*this);
m_behaviors.clear();
return p;
} // CB: to do: keep behaviors (instanciate new PairFloatBehavior for each behavior)
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Scene\SceneGame.h"
#include "Scene\SceneMenu.h"
#include "Core\SceneManager.h"
SceneGame::SceneGame()
{
}
SceneGame::~SceneGame()
{
}
bool SceneGame::onInit()
{
m_pGM = GameManager::getSingleton();
// Sprite
m_pSprite1 = m_pGM->getSprite("LocoRotux");
m_pSprite1->setTexture(m_pGM->getTexture("image.png"));
//m_pSprite1->setTextureRect(0, 0, 16, 16);
// SpriteRenderer
m_pSpriteRenderer = m_pGM->getSpriteRenderer("LocoRotuxSR");
m_pSpriteRenderer->setSprite(m_pSprite1);
// Entity
m_pEntity1 = m_pGM->getEntity("sprite 1");
m_pEntity1->setName(string("sprite 1"));
m_pEntity1->setPosition(Vector2f(800, 300));
m_pEntity1->addComponent(m_pSpriteRenderer);
m_pGM->addEntity(m_pEntity1);
return true;
}
bool SceneGame::onUpdate()
{
// Get direction from keyboard
if (m_pGM->isKeyPressed(Key::Num1))
{
m_pGM->setScene(new SceneMenu());
return true;
}
return true;
}
bool SceneGame::onDraw()
{
return true;
}
bool SceneGame::onQuit()
{
m_pGM->clearAllEntities();
return true;
}
<file_sep>/***************************************************/
/* Nom: Font.h
/* Description: Font
/* Auteur: <NAME>
/***************************************************/
#ifndef _Font_H
#define _Font_H
namespace crea
{
class CREAENGINE_API Font
{
public:
Font() {}
virtual ~Font() {}
virtual bool loadFromFile(const string& _file) { return false; }
virtual void setFontSize(int _iSize) {}
};
} // namespace crea
#endif // _Font_H<file_sep>/***************************************************/
/* Nom: FSMSteeringPeonGoTo.h
/* Description: FSMSteeringPeonGoTo
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMSteeringPeonGoTo_H_
#define __FSMSteeringPeonGoTo_H_
#include "AI\StateMachine.h"
#include "AI\Pathfinding\MapSearchManager.h"
#include "Scripts\CharacterController.h"
using namespace crea;
class FSMSteeringPeonGoTo : public StateMachine
{
GameManager* m_pGM;
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
MapSearch* m_pMapSearch;
Vector2f m_vTarget;
VectorVector2f m_vPath;
Vector2f* m_pPathTarget;
Steering* m_pSteering;
Vehicle* m_pVehicle;
Entity* m_pTarget;
bool GoTo(Vector2f& _vTargetPosition);
public:
FSMSteeringPeonGoTo(Vector2f _vTarget);
virtual ~FSMSteeringPeonGoTo();
void setEntity(Entity* _p) { m_pEntity = _p; }
void setCharacterController(CharacterController* _p) { m_pCharacterController = _p; }
inline VectorVector2f* getPath() { return &m_vPath; }
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone() { return new FSMSteeringPeonGoTo(*this); }
enum States {
STATE_Init,
STATE_SearchPath,
STATE_FollowPath,
STATE_SearchFailed,
STATE_CompletedPath
};
};
#endif
<file_sep>/***************************************************/
/* Nom: SceneMenu.h
/* Description: SceneMenu
/* Auteur: <NAME>
/***************************************************/
#ifndef __SceneMenu_H_
#define __SceneMenu_H_
#include "Core\Scene.h"
using namespace crea;
class SceneMenu : public Scene
{
GameManager* m_pGM;
Entity* m_pEntity1;
Text* m_pText;
TextRenderer* m_pTextRenderer;
public:
SceneMenu();
virtual ~SceneMenu();
virtual bool onInit();
virtual bool onUpdate();
virtual bool onDraw();
virtual bool onQuit();
};
#endif
<file_sep>/***************************************************/
/* Nom: FSMSteeringPeon.h
/* Description: FSMSteeringPeon
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMSteeringPeon_H_
#define __FSMSteeringPeon_H_
#include "AI\StateMachine.h"
#include "Scripts\CharacterController.h"
#include "Scripts\FSMSteeringPeonLive.h"
using namespace crea;
class FSMSteeringPeon : public StateMachine
{
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
bool m_bPaused;
int m_iLife;
FSMSteeringPeonLive* m_pFSMSteeringPeonLive;
public:
FSMSteeringPeon();
virtual ~FSMSteeringPeon();
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone();
};
#endif
<file_sep>/***************************************************/
/* Nom: Asset.h
/* Description: Asset
/* Auteur: <NAME>
/***************************************************/
#ifndef __Asset_H_
#define __Asset_H_
namespace crea
{
class CREAENGINE_API Asset
{
public:
Asset();
virtual ~Asset();
virtual bool loadFromFile(const string& _name) = 0;
virtual Asset* clone() = 0;
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: Component.h
/* Description: Component
/* Auteur: <NAME>
/***************************************************/
#ifndef __Component_H_
#define __Component_H_
namespace crea
{
class CREAENGINE_API Component
{
protected:
// Name
string m_szName;
Entity* m_pEntity; // The entity this component is attached to.
public:
Component();
virtual ~Component();
inline bool hasName(const string& _szName) { return (m_szName == _szName); }
inline void setName(const string& _szName) { m_szName = _szName; }
inline void setEntity(Entity* _pEntity) { m_pEntity = _pEntity; }
inline Entity* getEntity() { return m_pEntity; }
virtual bool init() = 0;
virtual bool update() = 0;
virtual bool draw() = 0;
virtual bool quit() = 0;
virtual Component* clone() = 0;
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Graphics\GL3Texture.h"
namespace crea
{
bool GL3Texture::m_flipVerticallyOnLoad = true;
GL3Texture::GL3Texture()
: m_texture(0),
m_transparency(false),
m_data(nullptr),
m_width(0),
m_height(0),
m_nrChannels(0)
{
glGenTextures(1, &m_texture);
}
GL3Texture::~GL3Texture()
{
glDeleteTextures(1, &m_texture);
if (m_data)
{
stbi_image_free(m_data);
}
}
bool GL3Texture::loadFromFile(const string& _name)
{
// texture
// -------
glBindTexture(GL_TEXTURE_2D, m_texture);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
stbi_set_flip_vertically_on_load(m_flipVerticallyOnLoad); // tell stb_image.h to flip loaded texture's on the y-axis.
m_data = stbi_load(_name.c_str(), &m_width, &m_height, &m_nrChannels, 0);
if (!m_data)
{
std::cout << "Failed to load texture" << std::endl;
return false;
}
m_name = _name;
send();
glGenerateMipmap(GL_TEXTURE_2D);
return true;
}
void GL3Texture::send()
{
if (m_data)
{
GLenum format = GL_RGB;
if (m_nrChannels == 1)
format = GL_RED;
else if (m_nrChannels == 4)
format = GL_RGBA;
glTexImage2D(GL_TEXTURE_2D, 0, format, m_width, m_height, 0, format, GL_UNSIGNED_BYTE, m_data);
}
}
void GL3Texture::bind(unsigned int _channel)
{
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0 + _channel);
glBindTexture(GL_TEXTURE_2D, m_texture);
if (m_nrChannels == 4)
{
glEnable(GL_BLEND);// you enable blending function
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
void GL3Texture::unbind(unsigned int _channel)
{
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0 + _channel);
glBindTexture(GL_TEXTURE_2D, 0);
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Scripts\FSMHQ.h"
#include "Scripts\Messages.h"
#include <string.h>
//Add new states here
enum States {
STATE_Spawn,
STATE_Think,
STATE_PerformAction,
STATE_Idle,
};
enum PreconditionAndEffects {
HqHaveGold,
HqHaveFirewood,
HqHaveTool,
HqHaveLogs,
HqHaveMoreGold,
WoodCutterHaveLogs,
WoodCutterHaveBranches,
WoodCutterHaveFirewood,
BlackSmithHaveGold,
BlackSmithHaveFirewood,
MinerHaveTool,
WoodCutterHaveTool,
BlackSmithHaveTool,
LoggerHaveTool,
};
FSMHQ::FSMHQ()
: m_initState("initState"), m_goalState("goalState")
{
}
FSMHQ::~FSMHQ()
{
}
bool FSMHQ::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
OnMsg(MSG_ActionCompleted)
{
if (_msg->GetSender() == m_pMiner->GetID())
{
// mining
m_initState.setVariable(HqHaveGold, true);
}
else if (_msg->GetSender() == m_pWoodCutter->GetID())
{
if (m_initState.getVariable(WoodCutterHaveLogs) == false)
{
// pickupLogs
if (m_initState.getVariable(HqHaveLogs) == true)
{
m_initState.setVariable(HqHaveLogs, false);
m_initState.setVariable(WoodCutterHaveLogs, true);
}
}
// Drop FireWood
if (m_initState.getVariable(WoodCutterHaveFirewood) == true)
{
// cutting
m_initState.setVariable(HqHaveFirewood, true);
m_initState.setVariable(WoodCutterHaveFirewood, false);
}
}
else if (_msg->GetSender() == m_pBlackSmith->GetID())
{
if (m_initState.getVariable(BlackSmithHaveGold) == false
|| m_initState.getVariable(BlackSmithHaveFirewood) == false
)
{
// pickupGold
if (m_initState.getVariable(HqHaveGold) == true)
{
m_initState.setVariable(HqHaveGold, false);
m_initState.setVariable(BlackSmithHaveGold, true);
}
// pickupFirewood
if (m_initState.getVariable(HqHaveFirewood) == true)
{
m_initState.setVariable(HqHaveFirewood, false);
m_initState.setVariable(BlackSmithHaveFirewood, true);
}
}
else
{
// forging
m_initState.setVariable(HqHaveTool, true);
}
}
else if (_msg->GetSender() == m_pLogger->GetID())
{
// logging
m_initState.setVariable(HqHaveLogs, true);
}
SetState(STATE_Think);
}
OnMsg(MSG_ToolBroken)
{
if (_msg->GetSender() == m_pMiner->GetID())
{
m_initState.setVariable(MinerHaveTool, false);
}
else if (_msg->GetSender() == m_pWoodCutter->GetID())
{
m_initState.setVariable(WoodCutterHaveTool, false);
}
else if (_msg->GetSender() == m_pBlackSmith->GetID())
{
// Do not lose tool for BlackSmith
//m_initState.setVariable(BlackSmithHaveTool, false);
}
else if (_msg->GetSender() == m_pLogger->GetID())
{
m_initState.setVariable(LoggerHaveTool, false);
}
}
OnMsg(MSG_Think)
SetState(STATE_Think);
///////////////////////////////////////////////////////////////
State(STATE_Spawn)
OnEnter
// Get Entity
m_pEntity = getEntity();
m_pGM = GameManager::getSingleton();
m_pMiner = m_pGM->getEntity("miner");
m_pWoodCutter = m_pGM->getEntity("woodcutter");
m_pBlackSmith = m_pGM->getEntity("blacksmith");
m_pLogger = m_pGM->getEntity("logger");
// Miner
goap::Action pickupToolMiner("pickupToolMiner", 1);
pickupToolMiner.setPrecondition(HqHaveTool, true);
pickupToolMiner.setPrecondition(MinerHaveTool, false);
pickupToolMiner.setEffect(HqHaveTool, false);
pickupToolMiner.setEffect(MinerHaveTool, true);
m_actionsPossible.push_back(pickupToolMiner);
goap::Action mining("mining", 1);
//mining.setPrecondition(HqHaveGold, false);
mining.setPrecondition(MinerHaveTool, true);
mining.setEffect(HqHaveGold, true);
mining.setEffect(HqHaveMoreGold, true);
m_actionsPossible.push_back(mining);
// WoodCutter
goap::Action pickupToolWoodCutter("pickupToolWoodCutter", 1);
pickupToolWoodCutter.setPrecondition(HqHaveTool, true);
pickupToolWoodCutter.setPrecondition(WoodCutterHaveTool, false);
pickupToolWoodCutter.setEffect(HqHaveTool, false);
pickupToolWoodCutter.setEffect(WoodCutterHaveTool, true);
m_actionsPossible.push_back(pickupToolWoodCutter);
goap::Action pickupLogs("pickupLogs", 1);
pickupLogs.setPrecondition(HqHaveLogs, true);
pickupLogs.setPrecondition(WoodCutterHaveLogs, false);
pickupLogs.setEffect(HqHaveLogs, false);
pickupLogs.setEffect(WoodCutterHaveLogs, true);
m_actionsPossible.push_back(pickupLogs);
goap::Action pickupBranches("pickupBranches", 10);
pickupBranches.setPrecondition(HqHaveLogs, false);
pickupBranches.setPrecondition(WoodCutterHaveBranches, false);
pickupBranches.setEffect(WoodCutterHaveBranches, true);
m_actionsPossible.push_back(pickupBranches);
goap::Action cutting("cutting", 1);
cutting.setPrecondition(WoodCutterHaveLogs, true);
cutting.setPrecondition(WoodCutterHaveTool, true);
cutting.setEffect(WoodCutterHaveLogs, false);
cutting.setEffect(HqHaveFirewood, true);
m_actionsPossible.push_back(cutting);
goap::Action cuttingBranches("cuttingBranches", 10);
cuttingBranches.setPrecondition(WoodCutterHaveBranches, true);
cuttingBranches.setPrecondition(WoodCutterHaveTool, true);
cuttingBranches.setEffect(WoodCutterHaveBranches, false);
cuttingBranches.setEffect(HqHaveFirewood, true);
m_actionsPossible.push_back(cuttingBranches);
// BlackSmith
goap::Action pickupToolBlackSmith("pickupToolBlackSmith", 1);
pickupToolBlackSmith.setPrecondition(HqHaveTool, true);
pickupToolBlackSmith.setPrecondition(BlackSmithHaveTool, false);
pickupToolBlackSmith.setEffect(HqHaveTool, false);
pickupToolBlackSmith.setEffect(BlackSmithHaveTool, true);
m_actionsPossible.push_back(pickupToolBlackSmith);
goap::Action pickupGold("pickupGold", 1);
pickupGold.setPrecondition(HqHaveGold, true);
pickupGold.setPrecondition(BlackSmithHaveGold, false);
pickupGold.setEffect(HqHaveGold, false);
pickupGold.setEffect(BlackSmithHaveGold, true);
m_actionsPossible.push_back(pickupGold);
goap::Action pickupFirewood("pickupFirewood", 1);
pickupFirewood.setPrecondition(HqHaveFirewood, true);
pickupFirewood.setPrecondition(BlackSmithHaveFirewood, false);
pickupFirewood.setEffect(HqHaveFirewood, false);
pickupFirewood.setEffect(BlackSmithHaveFirewood, true);
m_actionsPossible.push_back(pickupFirewood);
goap::Action forging("forging", 1);
forging.setPrecondition(BlackSmithHaveFirewood, true);
forging.setPrecondition(BlackSmithHaveGold, true);
forging.setPrecondition(BlackSmithHaveTool, true);
forging.setPrecondition(HqHaveTool, false);
forging.setEffect(BlackSmithHaveFirewood, false);
forging.setEffect(BlackSmithHaveGold, false);
forging.setEffect(HqHaveTool, true);
m_actionsPossible.push_back(forging);
// Logger
goap::Action pickupToolLogger("pickupToolLogger", 1);
pickupToolLogger.setPrecondition(HqHaveTool, true);
pickupToolLogger.setPrecondition(LoggerHaveTool, false);
pickupToolLogger.setEffect(HqHaveTool, false);
pickupToolLogger.setEffect(LoggerHaveTool, true);
m_actionsPossible.push_back(pickupToolLogger);
goap::Action logging("logging", 1);
logging.setPrecondition(HqHaveLogs, false);
logging.setPrecondition(LoggerHaveTool, true);
logging.setEffect(HqHaveLogs, true);
m_actionsPossible.push_back(logging);
// Init State
m_initState.setVariable(HqHaveGold, false);
m_initState.setVariable(HqHaveFirewood, false);
m_initState.setVariable(HqHaveTool, false);
m_initState.setVariable(HqHaveLogs, false);
m_initState.setVariable(WoodCutterHaveLogs, false);
m_initState.setVariable(BlackSmithHaveGold, false);
m_initState.setVariable(BlackSmithHaveFirewood, false);
m_initState.setVariable(MinerHaveTool, true);
m_initState.setVariable(WoodCutterHaveTool, true);
m_initState.setVariable(BlackSmithHaveTool, true);
m_initState.setVariable(LoggerHaveTool, true);
m_initState.setVariable(HqHaveMoreGold, false);
m_initState.setVariable(WoodCutterHaveBranches, false);
m_initState.setVariable(WoodCutterHaveFirewood, false);
// Goal State
//m_goalState.setVariable(HqHaveTool, true); // TD Planning, Q4
m_goalState.setVariable(HqHaveMoreGold, true); // TD Planning, Q5
OnUpdate
SetState(STATE_Think);
///////////////////////////////////////////////////////////////
State(STATE_Think)
OnEnter
m_actionsToDo.clear();
try {
m_actionsToDo = m_planner.plan(m_initState, m_goalState, m_actionsPossible);
if (m_actionsToDo.empty())
{
std::cout << "Goal achieved!\n";
m_initState.setVariable(HqHaveMoreGold, false);
SendDelayedMsgToMe(0.5f, MSG_Think);
}
else
{
std::cout << "Found a path!\n";
for (std::vector<goap::Action>::reverse_iterator rit = m_actionsToDo.rbegin(); rit != m_actionsToDo.rend(); ++rit) {
std::cout << rit->name() << std::endl;
}
SetState(STATE_PerformAction);
}
}
catch (const std::exception&) {
std::cout << "Sorry, could not find a path!\n";
}
OnUpdate
OnExit
///////////////////////////////////////////////////////////////
State(STATE_PerformAction)
OnEnter
if (!m_actionsToDo.empty())
{
// Send orders
goap::Action actionToDo = m_actionsToDo.back();
m_actionsToDo.pop_back();
if (actionToDo.name() == "mining")
{
SendDelayedMsg(0.5f, MSG_Mine, m_pMiner->GetID());
}
else if (actionToDo.name() == "cutting")
{
m_initState.setVariable(WoodCutterHaveFirewood, true);
SendDelayedMsg(0.5f, MSG_CutWood, m_pWoodCutter->GetID());
}
else if (actionToDo.name() == "cuttingBranches")
{
SendDelayedMsg(0.5f, MSG_CutWood, m_pWoodCutter->GetID());
}
else if (actionToDo.name() == "pickupBranches")
{
m_initState.setVariable(WoodCutterHaveFirewood, true);
SendDelayedMsg(0.5f, MSG_PickupBranches, m_pWoodCutter->GetID());
}
else if (actionToDo.name() == "forging")
{
SendDelayedMsg(0.5f, MSG_Build, m_pBlackSmith->GetID());
}
else if (actionToDo.name() == "logging")
{
SendDelayedMsg(0.5f, MSG_Harvest, m_pLogger->GetID());
}
else if (actionToDo.name() == "pickupLogs")
{
SendDelayedMsg(0.5f, MSG_GoTo, m_pWoodCutter->GetID());
}
else if (actionToDo.name() == "pickupGold")
{
SendDelayedMsg(0.5f, MSG_GoTo, m_pBlackSmith->GetID());
}
else if (actionToDo.name() == "pickupFirewood")
{
SendDelayedMsg(0.5f, MSG_GoTo, m_pBlackSmith->GetID());
}
else if (actionToDo.name() == "pickupToolMiner")
{
m_initState.setVariable(HqHaveTool, false);
m_initState.setVariable(MinerHaveTool, true);
SendDelayedMsg(0.5f, MSG_NewTool, m_pMiner->GetID());
SendDelayedMsgToMe(0.5f, MSG_Think);
}
SetState(STATE_Idle);
}
else
{
SetState(STATE_Think);
}
///////////////////////////////////////////////////////////////
State(STATE_Idle)
OnEnter
EndStateMachine
}<file_sep>/***************************************************/
/* Nom: ClusterSearch.h
/* Description: ClusterSearch
/* Auteur: <NAME>
/***************************************************/
#ifndef __ClusterSearch_H__
#define __ClusterSearch_H__
#include "AI\Pathfinding\AStarSearch.h"
#include "AI\Pathfinding\ClusterSearchNode.h"
namespace crea
{
class CREAENGINE_API ClusterSearch : public AStarSearch<ClusterSearchNode>
{
public:
enum SearchState
{
SEARCH_STATE_NOT_INITIALISED,
SEARCH_STATE_SEARCHING,
SEARCH_STATE_SUCCEEDED,
SEARCH_STATE_FAILED,
SEARCH_STATE_OUT_OF_MEMORY,
SEARCH_STATE_INVALID
};
ClusterSearch();
~ClusterSearch();
bool setStartAndGoal(Vector2f _vStart, Vector2f _vGoal, bool _bFromPixels = true);
SearchState update();
bool getSolution(VectorVector2f& _vSolution);
float getSolutionLength();
private:
SearchState m_uiSearchState;
};
}
#endif // __ClusterSearch_H__<file_sep>/***************************************************/
/* Nom: Behavior.h
/* Description: Behavior
/* Auteur: <NAME>
/***************************************************/
#ifndef __BEHAVIOR_H_
#define __BEHAVIOR_H_
#include "Core\Math.h"
#include <vector>
#include <random>
namespace crea
{
class Entity;
class Steering;
class Vehicle;
class CREAENGINE_API Behavior
{
protected:
Entity * m_pEntity;
Steering* m_pSteering;
Vehicle* m_pVehicle; // CB: change this for RigidBody
Vector2f m_vDesiredVelocity;
Vector2f m_vSteering;
Vector2f m_vOffset;
public:
Behavior(Entity* _Entity);
virtual ~Behavior() { }
void setOffset(Vector2f& _offset) { m_vOffset = _offset; };
Entity* getEntity() { return m_pEntity; }
virtual Vector2f& Update() = 0;
virtual string asString() = 0;
};
class CREAENGINE_API Seek : public Behavior
{
Entity* m_target;
public:
Seek(Entity* _Entity, Entity* _target) : Behavior(_Entity), m_target(_target) { };
Entity* getTarget() { return m_target; }
Vector2f& Update();
virtual string asString() { return "Seek"; }
};
class CREAENGINE_API Flee : public Behavior
{
Entity* m_target;
public:
Flee(Entity* _Entity, Entity* _target) : Behavior(_Entity), m_target(_target) { };
Entity* getTarget() { return m_target; }
Vector2f& Update();
virtual string asString() { return "Flee"; }
};
class CREAENGINE_API Pursuit : public Behavior
{
Entity* m_target;
float m_fTimeMax;
public:
Pursuit(Entity* _Entity, Entity* _target, float _fTimeMax) : Behavior(_Entity), m_target(_target), m_fTimeMax(_fTimeMax) { };
Vector2f& Update();
virtual string asString() { return "Pursuit"; }
};
class CREAENGINE_API Evasion : public Behavior
{
Entity* m_target;
float m_fTimeMax;
public:
Evasion(Entity* _Entity, Entity* _target, float _fTimeMax) : Behavior(_Entity), m_target(_target), m_fTimeMax(_fTimeMax) { };
Vector2f& Update();
virtual string asString() { return "Evasion"; }
};
class CREAENGINE_API Arrival : public Behavior
{
Entity* m_target;
float m_fSlowingDistance;
public:
Arrival(Entity* _Entity, Entity* _target, float _fSlowingDistance) : Behavior(_Entity), m_target(_target), m_fSlowingDistance(_fSlowingDistance) { };
Vector2f& Update();
virtual string asString() { return "Arrival"; }
};
class CREAENGINE_API Wander : public Behavior
{
float m_distance;
float m_radius;
float m_littleRadius;
Vector2f m_vR = Vector2f(0.f, 0.f);
public:
Wander(Entity* _Entity, float _distance, float _radius, float _littleRadius)
: Behavior(_Entity), m_distance(_distance), m_radius(_radius), m_littleRadius(_littleRadius)
{
m_vR = Vector2f(m_radius, 0.f);
};
Vector2f& Update();
virtual string asString() { return "Wander"; }
};
class CREAENGINE_API PathFollowing : public Behavior
{
Entity* m_pTarget;
float m_fSpeed;
VectorVector2f* m_vPath;
float m_fDistanceFromP0;
float m_fDistanceToP1;
float m_fDistanceP0P1;
unsigned int m_iIndexNext;
Vector2f* p0, *p1;
public:
PathFollowing(Entity* _Entity, Entity* _Target, float _fSpeed, VectorVector2f* _vPath);
Vector2f& Update();
virtual string asString() { return "PathFollowing"; }
};
class CREAENGINE_API UnalignedCollisionAvoidance : public Behavior
{
float m_radius;
float m_fFutureTime;
vector<Entity*>* m_entities;
public:
UnalignedCollisionAvoidance(Entity* _Entity, float radius, float _fFutureTime, std::vector<Entity*>* entities)
: Behavior(_Entity), m_radius(radius), m_fFutureTime(_fFutureTime), m_entities(entities) { };
Vector2f& Update();
virtual string asString() { return "UCA"; }
};
class CREAENGINE_API ObstacleAvoidance : public Behavior
{
float m_radius;
float m_farView;
vector<Entity*>* m_obstacles;
public:
ObstacleAvoidance(Entity* _Entity, float radius, float farView, std::vector<Entity*>* obstacles)
: Behavior(_Entity), m_radius(radius), m_farView(farView), m_obstacles(obstacles) { };
Vector2f& Update();
virtual string asString() { return "ObstacleAvoidance"; }
};
class CREAENGINE_API Separation : public Behavior
{
float m_distanceMax;
vector<Entity*>* m_entities;
public:
Separation(Entity* _Entity, float distanceMax, std::vector<Entity*>* entities)
: Behavior(_Entity), m_distanceMax(distanceMax), m_entities(entities) { };
Vector2f& Update();
virtual string asString() { return "Separation"; }
};
class CREAENGINE_API Cohesion : public Behavior
{
float m_distanceMax;
vector<Entity*>* m_entities;
public:
Cohesion(Entity* _Entity, float distanceMax, std::vector<Entity*>* entities)
: Behavior(_Entity), m_distanceMax(distanceMax), m_entities(entities) { };
Vector2f& Update();
virtual string asString() { return "Cohesion"; }
};
class CREAENGINE_API Alignment : public Behavior
{
float m_distanceMax;
vector<Entity*>* m_entities;
public:
Alignment(Entity* _Entity, float distanceMax, std::vector<Entity*>* entities)
: Behavior(_Entity), m_distanceMax(distanceMax), m_entities(entities) { };
Vector2f& Update();
virtual string asString() { return "Alignment"; }
};
class CREAENGINE_API LeadFollowing : public Behavior
{
Entity* m_leader;
float m_distance;
float m_angle;
float m_distanceFlee;
float m_distanceArrive;
public:
LeadFollowing(Entity* _Entity, Entity* _leader, float _distance, float _angle, float _distanceFlee, float _distanceArrive)
: Behavior(_Entity), m_leader(_leader), m_distance(_distance), m_angle(_angle), m_distanceFlee(_distanceFlee), m_distanceArrive(_distanceArrive) { };
Vector2f& Update();
virtual string asString() { return "LeadFollowing"; }
};
class CREAENGINE_API Swarming : public Behavior
{
Entity* m_target;
float m_fSwarmDistanceSquare;
int m_iIndex;
static int global_counter;
public:
Swarming(Entity* _entity, int _iIndex, Entity* _target, float _fSwarmDistance)
: Behavior(_entity), m_iIndex(_iIndex), m_target(_target),
m_fSwarmDistanceSquare(_fSwarmDistance*_fSwarmDistance)
{
global_counter++;
};
Vector2f& Update();
virtual string asString() { return "Swarming"; }
};
class CREAENGINE_API FormationV : public Behavior
{
Entity* m_leader;
bool m_bUseLeaderOrientation, m_bLeaderInvisible;
unsigned int m_id, m_maxId, m_nbInLine;
float m_distanceMax, m_slowingDistance;
float m_angle;
public:
FormationV(Entity* _entity, Entity* _leader, bool _bUseLeaderOrientation,
unsigned int _nbInLine, unsigned int _id, unsigned int _maxId,
float _distanceMax, float _slowingDistance,
float _angle, bool _bLeaderInvisible = true)
: Behavior(_entity), m_leader(_leader), m_bUseLeaderOrientation(_bUseLeaderOrientation),
m_nbInLine(_nbInLine), m_id(_id), m_maxId(_maxId),
m_distanceMax(_distanceMax), m_slowingDistance(_slowingDistance),
m_angle(_angle),
m_bLeaderInvisible(_bLeaderInvisible)
{};
Vector2f& Update();
virtual string asString() { return "FormationV"; }
};
class CREAENGINE_API FormationCircle : public Behavior
{
Entity* m_leader;
bool m_bUseLeaderOrientation;
unsigned int m_id, m_maxId, m_nbInCircle;
float m_distanceMax, m_slowingDistance;
float m_minAngle, m_maxAngle, m_minRadius;
public:
FormationCircle(Entity* _entity, Entity* _leader, bool _bUseLeaderOrientation,
unsigned int _nbInCircle, unsigned int _id, unsigned int _maxId,
float _distanceMax, float _slowingDistance,
float _minAngle, float _maxAngle, float _minRadius)
: Behavior(_entity), m_leader(_leader), m_bUseLeaderOrientation(_bUseLeaderOrientation),
m_nbInCircle(_nbInCircle), m_id(_id), m_maxId(_maxId),
m_distanceMax(_distanceMax), m_slowingDistance(_slowingDistance),
m_minAngle(_minAngle), m_maxAngle(_maxAngle), m_minRadius(_minRadius)
{};
Vector2f& Update();
virtual string asString() { return "FormationCircle"; }
};
}
#endif<file_sep>#include "stdafx.h"
#include "Core\SceneManager.h"
#include "Core\Scene.h"
namespace crea
{
SceneManager::SceneManager()
{
m_pCurrentScene = nullptr;
}
SceneManager::~SceneManager()
{
if (m_pCurrentScene)
{
m_pCurrentScene->onQuit();
delete m_pCurrentScene;
}
}
SceneManager* SceneManager::getSingleton()
{
static SceneManager instanceUnique;
return
&instanceUnique;
}
bool SceneManager::update()
{
if (m_pCurrentScene)
return m_pCurrentScene->onUpdate();
return false;
}
bool SceneManager::draw()
{
if (m_pCurrentScene)
return m_pCurrentScene->onDraw();
return false;
}
void SceneManager::setScene(Scene* _s)
{
if (m_pCurrentScene)
{
m_pCurrentScene->onQuit();
delete m_pCurrentScene;
}
m_pCurrentScene = _s;
m_pCurrentScene->onInit();
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Data\Animation.h"
namespace crea
{
Animation::Animation() : m_texture(NULL), m_duration(1.0), m_bLooping(true), m_fSpeed(1.0f), m_iTranslationSpeed(0)
{
}
void Animation::addFrame(IntRect rect)
{
m_frames.push_back(rect);
}
void Animation::setSpriteSheet(Texture& texture)
{
m_texture = &texture;
}
void Animation::adjustToTranslationSpeed(float _fTranslationSpeed)
{
if (m_iTranslationSpeed)
{
m_fSpeed = _fTranslationSpeed / m_iTranslationSpeed;
}
}
bool Animation::loadFromFileJSON(const string& _filename)
{
m_szName = _filename;
Json::Value root;
std::ifstream config_doc(_filename, std::ifstream::binary);
config_doc >> root;
Json::Value spritesheet = root["spritesheet"];
setSpriteSheet(*DataManager::getSingleton()->getTexture(spritesheet.asString()));
Json::Value frames = root["frames"];
for (unsigned int iFrame = 0; iFrame < frames.size(); ++iFrame)
{
Json::Value frame = frames[iFrame];
addFrame(IntRect(frame["x"].asInt(), frame["y"].asInt(), frame["w"].asInt(), frame["h"].asInt()));
}
Json::Value loop = root["loop"];
if (loop.isBool())
{
m_bLooping = loop.asBool();
}
Json::Value multiframes = root["multiframes"];
for (unsigned int imultiFrame = 0; imultiFrame < multiframes.size(); ++imultiFrame)
{
Json::Value multiframe = multiframes[imultiFrame];
for (int i = 0; i < multiframe["frames"].asInt(); i++)
{
addFrame(IntRect(multiframe["x"].asInt() + i * multiframe["offsetx"].asInt(),
multiframe["y"].asInt() + i * multiframe["offsety"].asInt(),
multiframe["w"].asInt(),
multiframe["h"].asInt()));
}
}
// Translation Speed
Json::Value translationspeed = root["translationspeed"];
m_iTranslationSpeed = translationspeed.asInt();
return true;
}
} // namespace crea<file_sep>/***************************************************/
/* Nom: SFMLTexture.h
/* Description: SFMLTexture
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLTexture_H
#define _SFMLTexture_H
#include "Graphics\Texture.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLTexture : public Texture
{
public:
sf::Texture* m_pTexture;
SFMLTexture()
{
m_pTexture = new sf::Texture;
}
virtual ~SFMLTexture()
{
delete m_pTexture;
}
virtual inline void setTransparency(bool _transparency) { /*todo: handletransparency for SFML*/ }
virtual inline bool getTransparency() { return false; }
virtual bool loadFromFile(const string& _file)
{
return m_pTexture->loadFromFile(_file);
}
virtual void bind(unsigned int _channel) {}
virtual void unbind(unsigned int _channel) {}
};
} // namespace crea
#endif // _SFMLTexture_H<file_sep>/***************************************************/
/* Nom: PhysicsManager.h
/* Description: PhysicsManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __PhysicsManager_H_
#define __PhysicsManager_H_
namespace crea
{
class Collider;
class CREAENGINE_API Collision2D
{
public:
Collider * m_pCollider;
Collider* m_pOtherCollider;
bool m_bUpdated;
};
typedef void(Script::*onCollisionFcn)(Collision2D& _coll);
class CREAENGINE_API MapStringCollider : public map<string, Collider*> {};
class CREAENGINE_API MapColliderCollision2D : public multimap<Collider*, Collision2D*> {};
class CREAENGINE_API PhysicsManager
{
MapStringCollider m_StaticColliders;
MapStringCollider m_DynamicColliders;
MapColliderCollision2D m_Collisions2D;
Map* m_pCurrentMap; // Physics materials
PhysicsManager();
void callFunction(Collider* _pCollider, Collision2D* _pCollision, onCollisionFcn _fcn);
bool onEnterCollision(Collider* _pCollider, Collider* _pOtherCollider);
bool onUpdateCollision(Collision2D* _pCollision);
bool onExitCollision(Collision2D* _pCollision);
bool prepareCleanup();
bool cleanupCollisions();
public:
virtual ~PhysicsManager();
static PhysicsManager* getSingleton();
void addStaticCollider(const string& _szName, Collider* _pCollider);
void addDynamicCollider(string& _szName, Collider* _pCollider);
Collider* getStaticCollider(const string& _szName, bool _bCloned = false);
Collider* getDynamicCollider(const string& _szName, bool _bCloned = false);
bool isColliding(Collider* _pCollider, bool _bWithStatic = true, bool _bWithDynamic = false, bool _bWithTrigger = false);
void setCurrentMap(Map* _pMap);
Map* getCurrentMap();
MapStringCollider* getStaticColliders() { return &m_StaticColliders; }
MapStringCollider* getDynamicColliders() { return &m_DynamicColliders; }
bool updateCollision(Collider* _pCollider, Collider* _pOtherCollider);
bool clearCollisions();
bool init();
bool update();
bool draw();
void clear();
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
namespace crea
{
DX9Facade::DX9Facade()
: m_rWindowRect(0, 0, 1280, 800)
{
m_iR = 0;
m_iG = 0;
m_iB = 0;
m_szWindowName = "Application DirectX9";
ZeroMemory(&m_abKeys, sizeof(m_abKeys));
m_iMousePosX = -1;
m_iMousePosY = -1;
m_bMouseLeftButtonDown = false;
m_bMouseRightButtonDown = false;
}
DX9Facade::~DX9Facade()
{
}
// Renvoie l'instance du renderer
DX9Facade& DX9Facade::Instance()
{
static DX9Facade s_Instance;
return s_Instance;
}
//-----------------------------------------------------------------------------
// Name: initD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT DX9Facade::initD3D(HWND hWnd)
{
// Create the D3D object, which is needed to create the D3DDevice
if (NULL == (m_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
return E_FAIL;
// Set up the structure used to create the D3DDevice
ZeroMemory(&m_d3dpp, sizeof(m_d3dpp));
m_d3dpp.Windowed = TRUE;
m_d3dpp.BackBufferHeight = m_rWindowRect.getHeight();
m_d3dpp.BackBufferWidth = m_rWindowRect.getWidth();
m_d3dpp.hDeviceWindow = hWnd;
m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
m_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
m_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
//m_d3dpp.EnableAutoDepthStencil = true;
//m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
// Create the Direct3D device
if (FAILED(m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&m_d3dpp, &m_pDevice)))
{
return E_FAIL;
}
// Device state would normally be set here
return S_OK;
}
bool DX9Facade::setCursor(bool _bVisible)
{
if (_bVisible)
{
// Turn off window cursor
SetCursor(NULL);
m_pDevice->ShowCursor(TRUE);
return true; // prevent Windows from setting cursor to window class cursor
}
else
{
//SetCursor(LoadCursor(NULL, IDC_ARROW));
}
return false;
}
void DX9Facade::initialize()
{
// Register the window class
WNDCLASSEX wc =
{
sizeof(WNDCLASSEX),
CS_CLASSDC,
MsgProc,
0L,
0L,
GetModuleHandle(NULL),
LoadIcon(NULL, IDI_INFORMATION),
LoadCursor(NULL, IDC_ARROW),
(HBRUSH) GetStockObject(WHITE_BRUSH),
NULL,
"DX9Facade",
LoadIcon(NULL, IDI_INFORMATION)
};
RegisterClassEx(&wc);
RECT wr = { 0, 0, m_rWindowRect.getWidth(), m_rWindowRect.getHeight() }; // set the size, but not the position
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size
// Create the application's window
HWND hWnd = CreateWindow("DX9Facade", m_szWindowName,
WS_OVERLAPPEDWINDOW,
m_rWindowRect.getLeft(), m_rWindowRect.getTop(),
wr.right - wr.left, // width of the window
wr.bottom - wr.top, // height of the window
NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (SUCCEEDED(initD3D(hWnd)))
{
// Show the window
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
// Cursor
SetCursor(LoadCursor(NULL, IDC_ARROW)); // CB: Have to force it...
}
else
{
cerr << "initD3D failed..." << endl;
}
ZeroMemory(&msg, sizeof(msg));
}
bool DX9Facade::update()
{
// Enter the message loop
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else return true;
}
return false;
}
void DX9Facade::beginScene() const
{
m_pDevice->Clear(0, NULL, D3DCLEAR_TARGET/* | D3DCLEAR_ZBUFFER| D3DCLEAR_STENCIL*/, D3DCOLOR_XRGB(m_iR, m_iG, m_iB), 1.0f, 0x00);
m_pDevice->BeginScene();
}
// Rendu d'un objet
void DX9Facade::draw(IDrawable& _o) const
{
}
void DX9Facade::endScene() const
{
m_pDevice->EndScene();
m_pDevice->Present(NULL, NULL, NULL, NULL);
}
void DX9Facade::quit()
{
UnregisterClass("DX9Facade", GetModuleHandle(NULL)); // CB: to do, keep the instance to unregister it
//release le device
SafeRelease(m_pDevice);
//release l'interface DX9
SafeRelease(m_pD3D);
}
void DX9Facade::keyDown(WPARAM _wParam, bool _bDown)
{
short nVirtKey = 0;
switch (_wParam)
{
case 'A': m_abKeys[Key::A] = _bDown; break;
case 'B': m_abKeys[Key::B] = _bDown; break;
case 'C': m_abKeys[Key::C] = _bDown; break;
case 'D': m_abKeys[Key::D] = _bDown; break;
case 'E': m_abKeys[Key::E] = _bDown; break;
case 'F': m_abKeys[Key::F] = _bDown; break;
case 'G': m_abKeys[Key::G] = _bDown; break;
case 'H': m_abKeys[Key::H] = _bDown; break;
case 'I': m_abKeys[Key::I] = _bDown; break;
case 'J': m_abKeys[Key::J] = _bDown; break;
case 'K': m_abKeys[Key::K] = _bDown; break;
case 'L': m_abKeys[Key::L] = _bDown; break;
case 'M': m_abKeys[Key::M] = _bDown; break;
case 'N': m_abKeys[Key::N] = _bDown; break;
case 'O': m_abKeys[Key::O] = _bDown; break;
case 'P': m_abKeys[Key::P] = _bDown; break;
case 'Q': m_abKeys[Key::Q] = _bDown; break;
case 'R': m_abKeys[Key::R] = _bDown; break;
case 'S': m_abKeys[Key::S] = _bDown; break;
case 'T': m_abKeys[Key::T] = _bDown; break;
case 'U': m_abKeys[Key::U] = _bDown; break;
case 'V': m_abKeys[Key::V] = _bDown; break;
case 'W': m_abKeys[Key::W] = _bDown; break;
case 'X': m_abKeys[Key::X] = _bDown; break;
case 'Y': m_abKeys[Key::Y] = _bDown; break;
case 'Z': m_abKeys[Key::Z] = _bDown; break;
case '0': m_abKeys[Key::Num0] = _bDown; break;
case '1': m_abKeys[Key::Num1] = _bDown; break;
case '2': m_abKeys[Key::Num2] = _bDown; break;
case '3': m_abKeys[Key::Num3] = _bDown; break;
case '4': m_abKeys[Key::Num4] = _bDown; break;
case '5': m_abKeys[Key::Num5] = _bDown; break;
case '6': m_abKeys[Key::Num6] = _bDown; break;
case '7': m_abKeys[Key::Num7] = _bDown; break;
case '8': m_abKeys[Key::Num8] = _bDown; break;
case '9': m_abKeys[Key::Num9] = _bDown; break;
case VK_ESCAPE: m_abKeys[Key::Escape] = _bDown; break;
case VK_CONTROL:
nVirtKey = GetKeyState(VK_LCONTROL);
if ((nVirtKey & 0xff00)) m_abKeys[Key::LControl] = _bDown;
nVirtKey = GetKeyState(VK_RCONTROL);
if ((nVirtKey & 0xff00)) m_abKeys[Key::RControl] = _bDown;
break;
case VK_SHIFT:
nVirtKey = GetKeyState(VK_LSHIFT);
if ((nVirtKey & 0xff00))
m_abKeys[Key::LShift] = _bDown;
nVirtKey = GetKeyState(VK_RSHIFT);
if ((nVirtKey & 0xff00))
m_abKeys[Key::RShift] = _bDown;
break;
case VK_LMENU: m_abKeys[Key::LAlt] = _bDown; break; // CB: ne semble pas fonctionner
case VK_LWIN: m_abKeys[Key::LSystem] = _bDown; break; // CB: semble �tre la touche windows (� droite?)
case VK_RCONTROL: m_abKeys[Key::RControl] = _bDown; break;
case VK_RMENU: m_abKeys[Key::RAlt] = _bDown; break; // CB: ne semble pas fonctionner
case VK_RWIN: m_abKeys[Key::RSystem] = _bDown; break; // CB: ?
case VK_MENU: m_abKeys[Key::Menu] = _bDown; break; // Alt gr
//case ?: m_abKeys[Key::LBracket] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::RBracket] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::SemiColon] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Comma] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Period] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Quote] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Slash] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::BackSlash] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Tilde] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Equal] = _bDown; break; // CB: � v�rifier...
//case ?: m_abKeys[Key::Dash] = _bDown; break; // CB: � v�rifier...
case VK_SPACE: m_abKeys[Key::Space] = _bDown; break;
case VK_RETURN: m_abKeys[Key::Return] = _bDown; break;
case VK_BACK: m_abKeys[Key::BackSpace] = _bDown; break;
case VK_TAB: m_abKeys[Key::Tab] = _bDown; break;
case VK_PRIOR: m_abKeys[Key::PageUp] = _bDown; break;
case VK_NEXT: m_abKeys[Key::PageDown] = _bDown; break;
case VK_END: m_abKeys[Key::End] = _bDown; break;
case VK_HOME: m_abKeys[Key::Home] = _bDown; break;
case VK_INSERT: m_abKeys[Key::Insert] = _bDown; break;
case VK_DELETE: m_abKeys[Key::Delete] = _bDown; break;
case VK_ADD: m_abKeys[Key::Add] = _bDown; break;
case VK_SUBTRACT: m_abKeys[Key::Subtract] = _bDown; break;
case VK_MULTIPLY: m_abKeys[Key::Multiply] = _bDown; break;
case VK_DIVIDE: m_abKeys[Key::Divide] = _bDown; break;
case VK_LEFT: m_abKeys[Key::Left] = _bDown; break;
case VK_RIGHT: m_abKeys[Key::Right] = _bDown; break;
case VK_UP: m_abKeys[Key::Up] = _bDown; break;
case VK_DOWN: m_abKeys[Key::Down] = _bDown; break;
case VK_NUMPAD0: m_abKeys[Key::Numpad0] = _bDown; break;
case VK_NUMPAD1: m_abKeys[Key::Numpad1] = _bDown; break;
case VK_NUMPAD2: m_abKeys[Key::Numpad2] = _bDown; break;
case VK_NUMPAD3: m_abKeys[Key::Numpad3] = _bDown; break;
case VK_NUMPAD4: m_abKeys[Key::Numpad4] = _bDown; break;
case VK_NUMPAD5: m_abKeys[Key::Numpad5] = _bDown; break;
case VK_NUMPAD6: m_abKeys[Key::Numpad6] = _bDown; break;
case VK_NUMPAD7: m_abKeys[Key::Numpad7] = _bDown; break;
case VK_NUMPAD8: m_abKeys[Key::Numpad8] = _bDown; break;
case VK_NUMPAD9: m_abKeys[Key::Numpad9] = _bDown; break;
case VK_F1: m_abKeys[Key::F1] = _bDown; break;
case VK_F2: m_abKeys[Key::F2] = _bDown; break;
case VK_F3: m_abKeys[Key::F3] = _bDown; break;
case VK_F4: m_abKeys[Key::F4] = _bDown; break;
case VK_F5: m_abKeys[Key::F5] = _bDown; break;
case VK_F6: m_abKeys[Key::F6] = _bDown; break;
case VK_F7: m_abKeys[Key::F7] = _bDown; break;
case VK_F8: m_abKeys[Key::F8] = _bDown; break;
case VK_F9: m_abKeys[Key::F9] = _bDown; break;
case VK_F10: m_abKeys[Key::F10] = _bDown; break;
case VK_F11: m_abKeys[Key::F11] = _bDown; break;
case VK_F12: m_abKeys[Key::F12] = _bDown; break;
case VK_F13: m_abKeys[Key::F13] = _bDown; break;
case VK_F14: m_abKeys[Key::F14] = _bDown; break;
case VK_F15: m_abKeys[Key::F15] = _bDown; break;
case VK_PAUSE: m_abKeys[Key::Pause] = _bDown; break;
default:
cerr << "Key not recognized: " << _wParam << endl;
break;
}
}
LRESULT WINAPI DX9Facade::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
DX9Facade::Instance().quit();
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
DX9Facade::Instance().keyDown(wParam, true);
return 0;
case WM_KEYUP:
DX9Facade::Instance().keyDown(wParam, false);
return 0;
case WM_MOUSEMOVE:
{
// Retrieve mouse screen position
int x = (short)LOWORD(lParam);
int y = (short)HIWORD(lParam);
DX9Facade::Instance().setMousePosition(x, y); //CB: Bug: returns 1263*760 on a 1280*800 window (1134x855 on a 1152x896)
// Check to see if the left button is held down:
bool bLeftButtonDown = (wParam & MK_LBUTTON) ? true : false;
// Check if right button down:
bool bRightButtonDown = (wParam & MK_RBUTTON) ? true : false;
DX9Facade::Instance().setMouseButtonsDown(bLeftButtonDown, bRightButtonDown);
return 0;
}
case WM_LBUTTONDOWN:
DX9Facade::Instance().setMouseLButtonDown(true);
return 0;
case WM_RBUTTONDOWN:
DX9Facade::Instance().setMouseRButtonDown(true);
return 0;
case WM_LBUTTONUP:
DX9Facade::Instance().setMouseLButtonDown(false);
return 0;
case WM_RBUTTONUP:
DX9Facade::Instance().setMouseRButtonDown(false);
return 0;
case WM_PAINT:
ValidateRect(hWnd, NULL);
return 0;
case WM_SETCURSOR:
return DX9Facade::Instance().setCursor(false);
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
Font* DX9Facade::createFont(Font* _pFrom)
{
return (_pFrom ? new DX9Font(*(DX9Font*)_pFrom) : new DX9Font);
}
void DX9Facade::destroyFont(Font* _pFont)
{
delete ((DX9Font*)_pFont);
}
Texture* DX9Facade::createTexture(Texture* _pFrom)
{
return (_pFrom ? new DX9Texture(*(DX9Texture*)_pFrom) : new DX9Texture);
}
void DX9Facade::destroyTexture(Texture* _pTexture)
{
delete ((DX9Texture*)_pTexture);
}
Color* DX9Facade::createColor(Color* _pFrom)
{
return (_pFrom ? new DX9Color(*(DX9Color*)_pFrom) : new DX9Color);
}
void DX9Facade::destroyColor(Color* _pColor)
{
delete ((DX9Color*)_pColor);
}
Text* DX9Facade::createText(Text* _pFrom)
{
return (_pFrom ? new DX9Text(*(DX9Text*)_pFrom) : new DX9Text);
}
void DX9Facade::destroyText(Text* _pText)
{
delete ((DX9Text*)_pText);
}
Sprite* DX9Facade::createSprite(Sprite* _pFrom)
{
return (_pFrom ? new DX9Sprite(*(DX9Sprite*)_pFrom) : new DX9Sprite);
}
void DX9Facade::destroySprite(Sprite* _pSprite)
{
delete ((DX9Sprite*)_pSprite);
}
Shape* DX9Facade::createShape(string _szType, Shape* _pFrom)
{
if (_szType == "Default")
{
return (_pFrom ? new DX9Shape(*(DX9Shape*)_pFrom) : new DX9Shape);
}
else if (_szType == "Rectangle")
{
return (_pFrom ? new DX9RectangleShape(*(DX9RectangleShape*)_pFrom) : new DX9RectangleShape);
}
else if (_szType == "Circle")
{
return (_pFrom ? new DX9CircleShape(*(DX9CircleShape*)_pFrom) : new DX9CircleShape);
}
else if (_szType == "Arrow")
{
return (_pFrom ? new DX9ArrowShape(*(DX9ArrowShape*)_pFrom) : new DX9ArrowShape);
}
else if (_szType == "Line")
{
return (_pFrom ? new DX9LineShape(*(DX9LineShape*)_pFrom) : new DX9LineShape);
}
return nullptr;
}
void DX9Facade::destroyShape(Shape* _pShape)
{
delete _pShape;
}
Shader* DX9Facade::createShader(Shader* _pFrom)
{
// todo: implement DX9 shaders
return nullptr;
}
void DX9Facade::destroyShader(Shader* _pShader)
{
// todo: implement DX9 shaders
}
Material* DX9Facade::createMaterial(Material* _pFrom)
{
// todo: implement DX9 materials
return nullptr;
}
void DX9Facade::destroyMaterial(Material* _pMaterial)
{
// todo: implement DX9 materials
}
bool DX9Facade::isKeyPressed(Key _key)
{
if (m_abKeys[_key])
{
return true;
}
return false;
}
bool DX9Facade::isMouseButtonPressed(Button _button)
{
if (_button == MouseLeft)
{
return m_bMouseLeftButtonDown;
}
else if (_button == MouseRight)
{
return m_bMouseRightButtonDown;
}
else
{
cerr << "Mouse button not recognized: " << _button << endl;
}
return false;
}
Vector2f DX9Facade::getMousePosition()
{
return Vector2f((float)m_iMousePosX, (float)m_iMousePosY); // Get position relative to window
}
extern "C" __declspec(dllexport) DX9Facade* StartPlugin()
{
return &DX9Facade::Instance();
}
} // namespace crea<file_sep>/***************************************************/
/* Nom: GL3Text.h
/* Description: GL3Text
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Text_H
#define _GL3Text_H
#include "Graphics\Text.h"
namespace crea
{
class GL3Text : public Text
{
GL3Font* m_pFont;
RECT *m_pRect;
GL3Color m_color;
string m_szText;
float m_fSize;
public:
GL3Text()
{
//init rectangle
m_pRect = new RECT();
//init color
m_color.setValues(255, 255, 255, 100);
//font
m_pFont = nullptr;
m_fSize = 20.f;
}
virtual ~GL3Text()
{
SafeDelete(m_pRect);
// SafeDelete(m_pFont); // Font not allocated in GL3Text
}
virtual void draw()
{
assert(m_pFont); // A font must be set
m_pFont->renderText(m_szText.c_str(), (float)m_pRect->left, (float)m_pRect->top, m_fSize, glm::vec3(m_color.getR(), m_color.getG(), m_color.getB()));
}
virtual void setFont(Font* _pFont)
{
m_pFont = (GL3Font*)_pFont;
}
virtual void setColor(Color* _pColor)
{
m_color.setValues(_pColor->m_r, _pColor->m_g, _pColor->m_b, _pColor->m_a);
}
virtual void setCharacterSize(int _iSize)
{
m_fSize = (float)_iSize;
}
virtual void setString(string _szString)
{
m_szText = _szString;
}
virtual void setPosition(float _x, float _y)
{
m_pRect->left = (LONG)_x;
m_pRect->top = (LONG)_y;
m_pRect->bottom = (LONG)_y+100; // todo: size is not handled for text in GL3
m_pRect->right = (LONG)_x+300;
}
virtual void setTextureRect(int _x, int _y, int _w, int _h)
{
m_pRect->left = _x;
m_pRect->top = _y;
m_pRect->bottom = _y + _h;
m_pRect->right = _x + _w;
}
};
} // namespace crea
#endif // _GL3Text_H
<file_sep>/***************************************************/
/* Nom: StateMachine.h
/* Description: StateMachine
/* Auteur: <NAME>
/***************************************************/
// Portions Copyright (C) <NAME>, 2001
#ifndef __STATEMCH_H__
#define __STATEMCH_H__
#include <assert.h>
#include "Core\Msg.h"
#include "Core\EntityManager.h"
#include "Core\DebugLog.h"
#include "Core\TimeManager.h"
#include <deque>
#define MAX_STATES_IN_STACK 20
namespace crea
{
//Scene Machine Language Macros (put these keywords in the file USERTYPE.DAT in the same directory as MSDEV.EXE)
#define BeginStateMachine if( _state < 0 ) { char statename[64] = "STATE_Global"; if(0) {
#define EndStateMachine return( true ); } } else { assert( 0 && "Invalid Scene" ); return( false ); } return( false );
#define State(a) return( true ); } } else if( a == _state ) { char statename[64] = #a; if(0) {
#define OnMsg(a) return( true ); } else if( EVENT_Message == _event && _msg && a == _msg->GetMsgName() ) { g_debuglog->LogStateMachineEvent( m_Owner->GetID(), _msg, statename, #a, true );
#define OnOtherMsg() return( true ); } else {
#define OnEvent(a) return( true ); } else if( a == _event ) { g_debuglog->LogStateMachineEvent( m_Owner->GetID(), _msg, statename, #a, true );
#define OnUpdate OnEvent( EVENT_Update )
#define OnEnter OnEvent( EVENT_Enter )
#define OnExit OnEvent( EVENT_Exit )
enum StateMachineEvent {
EVENT_INVALID,
EVENT_Update,
EVENT_Message,
EVENT_Enter,
EVENT_Exit
};
typedef enum {
NO_MSG_SCOPING,
SCOPE_TO_THIS_STATE
} MSG_Scope;
class CREAENGINE_API StateMachine : public Script
{
public:
StateMachine();
virtual ~StateMachine();
void Initialize(Entity* _pOwner);
void Update(void);
void SetState(unsigned int newScene);
int SetStateInHistory();
void SendMsg(int name, objectID receiver, void* data = NULL);
void SendDelayedMsg(float delay, int name, objectID receiver, void* data = NULL);
void SendDelayedMsgToMe(float delay, int name, MSG_Scope scope = NO_MSG_SCOPING);
int GetState(void) { return(m_currentState); }
double GetTimeInState(void) { return(g_time->getGameTime().asSeconds() - m_timeOnEnter); }
void SetCCReceiver(objectID id) { m_ccMessagesToAgent = id; }
void ClearCCReceiver(void) { m_ccMessagesToAgent = 0; }
objectID GetCCReceiver(void) { return(m_ccMessagesToAgent); }
void Process(StateMachineEvent event, Msg * msg);
// TD FSM: inherit StateMachine from Script
virtual bool init() { Initialize(getEntity()); return true; }
virtual bool update() { Update(); return true; }
virtual bool draw() { return true; }
virtual bool quit() { return true; }
protected:
Entity * m_Owner;
private:
unsigned int m_currentState;
unsigned int m_nextState;
bool m_stateChange;
double m_timeOnEnter;
objectID m_ccMessagesToAgent;
std::deque<unsigned int> m_stack;
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state) = 0;
virtual Component* clone() = 0;
};
}
#endif // __STATEMCH_H__<file_sep>/***************************************************/
/* Nom: ScriptFactory.h
/* Description: ScriptFactory
/* Auteur: <NAME>
/***************************************************/
#ifndef _ScriptFactory_H
#define _ScriptFactory_H
namespace crea
{
class CREAENGINE_API ScriptFactory {
public:
ScriptFactory()
{
}
virtual ~ScriptFactory()
{
}
virtual Script* create(const string& _szName) = 0;
};
} // namespace crea
#endif // _ScriptFactory_H<file_sep>/***************************************************/
/* Nom: SFMLFont.h
/* Description: SFMLFont
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLFont_H
#define _SFMLFont_H
#include "Graphics\Font.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLFont : public Font
{
public:
sf::Font m_font;
SFMLFont() {}
virtual ~SFMLFont() {}
virtual bool loadFromFile(const string& _file)
{
return m_font.loadFromFile(_file);
}
virtual void setFontSize(int _iSize)
{
// Todo: setFontSize SFML
}
};
} // namespace crea
#endif // _SFMLFont_H<file_sep>/***************************************************/
/* Nom: Shape.h
/* Description: Shape
/* Auteur: <NAME>
/***************************************************/
#ifndef _Shape_H
#define _Shape_H
namespace crea
{
class CREAENGINE_API Shape
{
public:
Shape() {}
virtual ~Shape() {}
virtual void draw() { assert(false); }
virtual void setColor(Color* _pColor) { assert(false); }
virtual void setOutlineColor(Color* _pColor) { assert(false); }
virtual void setOutlineThickness(float _fPixels) { assert(false); }
virtual void setPosition(float _x, float _y) { assert(false); }
virtual void setRotation(float _angle) { assert(false); }
virtual void setScale(float _x, float _y) { assert(false); }
virtual void setOrigin(float _x, float _y) { assert(false); }
};
class CREAENGINE_API RectangleShape : public Shape
{
public:
RectangleShape() {}
// Todo: add const copie and operator= on all RectangleShape
//RectangleShape(const RectangleShape& _other);
//virtual RectangleShape& operator=(const RectangleShape& _other);
~RectangleShape() {}
virtual void setSize(float _x, float _y) { assert(false); }
};
class CREAENGINE_API CircleShape : public Shape
{
public:
CircleShape() {}
// Todo: add const copie and operator= on CircleShape
//CircleShape(const CircleShape& _other);virtual CircleShape& operator=(const CircleShape& _other);
//virtual CircleShape& operator=(const CircleShape& _other);
~CircleShape() {}
virtual void setRadius(float _r) { assert(false); }
};
class CREAENGINE_API ArrowShape : public Shape
{
public:
ArrowShape() {}
~ArrowShape() {}
// Todo: add const copie and operator= on ArrowShape
virtual void setSize(float _x, float _y) { assert(false); }
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd) { assert(false); }
};
class CREAENGINE_API LineShape : public Shape
{
public:
LineShape() {}
~LineShape() {}
// Todo: add const copie and operator= on LineShape
virtual void setSize(float _x, float _y) { assert(false); }
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd) { assert(false); }
};
} // namespace crea
#endif // _Shape_H<file_sep>/***************************************************/
/* Nom: BehaviorTree.h
/* Description: BehaviorTree
/* Auteur: <NAME>
/***************************************************/
#ifndef __BehaviorTree_H_
#define __BehaviorTree_H_
#include "Core\Component.h"
namespace bt
{
// Predefinitions
class Behavior;
class CREAENGINE_API BehaviorTree : public crea::Component
{
protected:
Behavior * m_pRoot;
public:
BehaviorTree();
virtual ~BehaviorTree();
void setRootBehavior(Behavior* _pRoot);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone()
{
BehaviorTree* p = new BehaviorTree(*this);
// CB: copy tree structure...
p->m_pRoot = m_pRoot->clone();
return p;
}
};
} // namespace crea
#endif
<file_sep>/**
* Header Material
*
* @author cbruneau
* @since 09/10/2019
* @version 2.0
*/
#ifndef Material_H
#define Material_H
namespace crea
{
class CREAENGINE_API Material : public Asset
{
protected:
Shader* m_pShader;
Color* m_pColor;
public:
Material() {}
virtual ~Material() {};
inline void setShader(Shader* _pShader) { m_pShader = _pShader; }
inline Shader* getShader() { return m_pShader; }
inline void setColor(Color* _pColor) { m_pColor = _pColor; }
inline Color* getColor() { return m_pColor; }
virtual void setTexture(unsigned int _index, const string& _propertyName, Texture* _pTexture) {};
virtual Texture* getTexture(unsigned int _index) { return nullptr; }
virtual bool loadFromFile(const string& _name) { return false; }
virtual Asset* clone() { return new Material(*this); }
// apply the Material to a Shape
virtual bool applyShaderToShape(Shape* _pShape) { return false; }
// use the Material
virtual void use(Entity* _pEntity = nullptr) {}
// unuse the Material
virtual void unuse() {}
};
}
#endif
<file_sep>/***************************************************/
/* Nom: Msg.h
/* Description: Msg
/* Auteur: <NAME>
/***************************************************/
// Portions Copyright (C) <NAME>, 2001
#ifndef __MSG_H__
#define __MSG_H__
namespace crea
{
class Msg
{
public:
Msg(void);
Msg(float deliveryTime, int name, objectID sender, objectID receiver, int state = -1);
~Msg(void) {}
int GetMsgName(void) { return(m_Name); }
void SetMsgName(int name) { m_Name = name; }
objectID GetSender(void) { return(m_Sender); }
void SetSender(objectID sender) { m_Sender = sender; }
objectID GetReceiver(void) { return(m_Receiver); }
void SetReceiver(objectID receiver) { m_Receiver = receiver; }
int GetMsgState(void) { return(m_State); }
void SetMsgState(int state) { m_State = state; }
void* GetMsgData(void) { return(m_Data); }
void SetMsgData(void* data) { m_Data = data; }
float GetDeliveryTime(void) { return(m_DeliveryTime); }
void SetDeliveryTime(float time) { m_DeliveryTime = time; }
bool IsDelivered(void) { return(m_Delivered); }
void SetDelivered(bool value) { m_Delivered = value; }
private:
int m_Name; //Message name
objectID m_Sender; //Object that sent the message
objectID m_Receiver; //Object that will get the message
int m_State; //Scene in which the receiver is allowed get the message (-1 means any state)
float m_DeliveryTime; //Time at which to send the message
bool m_Delivered; //Whether the message has been delivered
void* m_Data;
};
}
#endif // __MSG_H__<file_sep>/***************************************************/
/* Nom: DX9Color.h
/* Description: DX9Color
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Color_H
#define _DX9Color_H
#include "Graphics\Color.h"
namespace crea
{
class DX9Color : public Color
{
public:
D3DCOLOR getColor() { return D3DCOLOR_RGBA(m_r, m_g, m_b, m_a); }
DX9Color()
{
}
virtual ~DX9Color()
{
}
};
} // namespace crea
#endif // _DX9Color_H<file_sep>/***************************************************/
/* Nom: Sprite.h
/* Description: Sprite
/* Auteur: <NAME>
/***************************************************/
#ifndef _Sprite_H
#define _Sprite_H
namespace crea
{
class CREAENGINE_API Sprite
{
public:
Sprite() {}
virtual ~Sprite() {}
virtual void draw() {}
virtual void setTexture(Texture* _pTexture) {}
virtual void setPosition(float _x, float _y) {}
virtual void setTextureRect(int _x, int _y, int _w, int _h) {}
virtual void setScale(float _x, float _y) {}
virtual void setOrigin(float _x, float _y) {}
virtual Sprite* clone() { return new Sprite(*this); }
};
} // namespace crea
#endif // _Sprite_H<file_sep>/***************************************************/
/* Nom: GameManager.h
/* Description: GameManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __GameManager_H_
#define __GameManager_H_
#include "SceneManager.h"
#include "EntityManager.h"
#include "Data\DataManager.h"
#include "Input\InputManager.h"
#include "Core\Math.h"
#include "AI\Agent.h"
#include "Core\Script.h"
#include "Core\PhysicsManager.h"
#include "AI\Pathfinding\MapSearchManager.h"
#include "AI\Pathfinding\ClusterSearchManager.h"
#include "Graphics\IFacade.h"
namespace crea
{
class Collider;
class LoggerFile;
enum EnumRendererType
{
Renderer_Invalid = -1,
Renderer_SFML = 0,
Renderer_DX9 = 1,
Renderer_GL3 = 2,
Renderer_Max,
};
class CREAENGINE_API GameManager
{
GameManager();
// Renderer
IFacade* m_pRenderer;
EnumRendererType m_rendererType;
LoggerFile* m_pLogger;
bool m_bContinueMainLoop = true;
public:
~GameManager();
static GameManager* getSingleton();
void setRendererType(EnumRendererType _rendererType);
inline IFacade* getRenderer() { return m_pRenderer; }
IntRect getWindowRect() { return m_pRenderer->getWindowRect(); }
void setWindowRect(IntRect _rect) { m_pRenderer->setWindowRect(_rect); }
inline void setScene(Scene* s)
{
SceneManager::getSingleton()->setScene(s);
EntityManager::getSingleton()->init();
}
// Input
inline bool isKeyPressed(Key _key) { return InputManager::getSingleton()->isKeyPressed(_key); }
inline bool isMouseButtonPressed(Button _button) { return InputManager::getSingleton()->isMouseButtonPressed(_button); }
inline Vector2f getMousePosition() { return InputManager::getSingleton()->getMousePosition(); }
// Data
inline Font* getFont(const string& _szName) { return DataManager::getSingleton()->getFont(_szName); }
inline Texture* getTexture(const string& _szName) { return DataManager::getSingleton()->getTexture(_szName); }
inline Color* getColor(const string& _szName) { return DataManager::getSingleton()->getColor(_szName); }
inline Text* getText(const string& _szName) { return DataManager::getSingleton()->getText(_szName); }
inline Sprite* getSprite(const string& _szName) { return DataManager::getSingleton()->getSprite(_szName); }
inline Shape* getShape(const string& _szType, const string& _szName) { return DataManager::getSingleton()->getShape(_szType, _szName); }
inline Map* getMap(const string& _szName) { return DataManager::getSingleton()->getMap(_szName); }
inline Agent* getAgent(const string& _szName) { return DataManager::getSingleton()->getAgent(_szName); }
inline Animation* getAnimation(const string& _szName) { return DataManager::getSingleton()->getAnimation(_szName); }
inline ActionTable* getActionTable(const string& _szName) { return DataManager::getSingleton()->getActionTable(_szName); }
inline Animator* getAnimator(const string& _szName) { return EntityManager::getSingleton()->getAnimator(_szName); }
inline Script* getScript(const string& _szName) { return EntityManager::getSingleton()->getScript(_szName); }
inline void setScriptFactory(ScriptFactory* _pScriptFactory) { return EntityManager::getSingleton()->setScriptFactory(_pScriptFactory); }
inline MapRenderer* getMapRenderer(const string& _szName) { return EntityManager::getSingleton()->getMapRenderer(_szName); }
inline TextRenderer* getTextRenderer(const string& _szName) { return EntityManager::getSingleton()->getTextRenderer(_szName); }
inline SpriteRenderer* getSpriteRenderer(const string& _szName) { return EntityManager::getSingleton()->getSpriteRenderer(_szName); }
inline Entity* getEntity(const string& _szName) { return EntityManager::getSingleton()->getEntity(_szName); }
inline void addEntity(Entity* _pEntity, Entity* _pParent = nullptr) { EntityManager::getSingleton()->addEntity(_pEntity, _pParent); }
inline void clearAllData() { DataManager::getSingleton()->clear(); }
inline void clearAllEntities() { EntityManager::getSingleton()->clear(); }
inline void clearEntity(Entity* _pEntity) { EntityManager::getSingleton()->clearEntity(_pEntity); }
inline Entity* getEntityByModel(const string& _szName) { return EntityManager::getSingleton()->getEntityByModel(_szName); }
inline void addEntityByModel(const string& _szName, Entity* _pEntity) { EntityManager::getSingleton()->addEntityByModel(_szName, _pEntity); }
inline void clearCollisions() { PhysicsManager::getSingleton()->clearCollisions(); }
inline Entity* instanciate(string _szName, Entity* _pEntity) { return EntityManager::getSingleton()->instanciate(_szName, _pEntity); }
inline Steering* getSteering(string _szName) { return EntityManager::getSingleton()->getSteering(_szName); }
inline Vehicle* getVehicle(string _szName) { return DataManager::getSingleton()->getVehicle(_szName); }
inline Material* getMaterial(string _szName, bool _bCloned = false) { return DataManager::getSingleton()->getMaterial(_szName, _bCloned); }
inline Shader* getShader(string _szName) { return DataManager::getSingleton()->getShader(_szName); }
// Selection
inline void selectEntities(Vector2f _vStart, Vector2f _vEnd) { EntityManager::getSingleton()->selectEntities(_vStart, _vEnd); }
inline void unselectEntities() { EntityManager::getSingleton()->unselectEntities(); }
inline ListEntity* getSelectedEntities() { return EntityManager::getSingleton()->getSelectedEntities(); }
// Physics
inline Collider* getStaticCollider(const string& _szName) { return PhysicsManager::getSingleton()->getStaticCollider(_szName); }
inline Collider* getDynamicCollider(const string& _szName) { return PhysicsManager::getSingleton()->getDynamicCollider(_szName); }
// A*
inline MapSearch* getMapSearch(string _szName) { return MapSearchManager::getSingleton()->getMapSearch(_szName); }
inline ClusterSearch* getClusterSearch(string _szName) { return ClusterSearchManager::getSingleton()->getClusterSearch(_szName); }
void init();
void update();
void quit();
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: Script.h
/* Description: Script
/* Auteur: <NAME>
/***************************************************/
#ifndef _Script_H
#define _Script_H
#include "Core\Component.h"
#include "Core\PhysicsManager.h"
namespace crea
{
class CREAENGINE_API Script : public Component
{
public:
Script()
{
}
virtual ~Script()
{
}
virtual bool init() = 0;
virtual bool update() = 0;
virtual bool draw() = 0;
virtual bool quit() = 0;
virtual void onCollisionEnter2D(Collision2D& _coll) {}
virtual void onCollisionStay2D(Collision2D& _coll) {}
virtual void onCollisionExit2D(Collision2D& _coll) {}
virtual Component* clone() = 0;
};
} // namespace crea
#endif // _Script_H<file_sep>#include "stdafx.h"
#include "Graphics\SFMLFacade.h"
#include "Graphics\SFMLFont.h"
#include "Graphics\SFMLTexture.h"
#include "Graphics\SFMLColor.h"
#include "Graphics\SFMLText.h"
#include "Graphics\SFMLSprite.h"
#include "Graphics\SFMLLine.h"
#include "Graphics\SFMLShape.h"
namespace crea
{
SFMLFacade::SFMLFacade()
: m_rWindowRect(0, 0, 1280, 800)
{
m_pWindow = nullptr;
}
SFMLFacade::~SFMLFacade()
{
if (m_pWindow)
{
delete m_pWindow;
m_pWindow = nullptr;
}
}
// Renvoie l'instance du renderer
SFMLFacade& SFMLFacade::Instance()
{
static SFMLFacade s_Instance;
return s_Instance;
}
void SFMLFacade::initialize()
{
m_pWindow = new sf::RenderWindow(sf::VideoMode((unsigned int)m_rWindowRect.getWidth(), (unsigned int)m_rWindowRect.getHeight()), "Application SFML");
}
bool SFMLFacade::update()
{
if (m_pWindow->isOpen())
{
sf::Event event;
while (m_pWindow->pollEvent(event))
{
if (event.type == sf::Event::Closed)
m_pWindow->close();
}
return true;
}
return false;
}
void SFMLFacade::beginScene() const
{
m_pWindow->clear();
}
// Rendu d'un objet
void SFMLFacade::draw(IDrawable& _o) const
{
//m_pWindow->draw(_o);
}
void SFMLFacade::endScene() const
{
m_pWindow->display();
}
void SFMLFacade::quit() const
{
}
Font* SFMLFacade::createFont(Font* _pFrom)
{
return (_pFrom ? new SFMLFont(*(SFMLFont*)_pFrom) : new SFMLFont);
}
void SFMLFacade::destroyFont(Font* _pFont)
{
delete _pFont;
}
Texture* SFMLFacade::createTexture(Texture* _pFrom)
{
return (_pFrom ? new SFMLTexture(*(SFMLTexture*)_pFrom) : new SFMLTexture);
}
void SFMLFacade::destroyTexture(Texture* _pTexture)
{
delete _pTexture;
}
Color* SFMLFacade::createColor(Color* _pFrom)
{
return (_pFrom ? new SFMLColor(*(SFMLColor*)_pFrom) : new SFMLColor);
}
void SFMLFacade::destroyColor(Color* _pColor)
{
delete _pColor;
}
Text* SFMLFacade::createText(Text* _pFrom)
{
return (_pFrom ? new SFMLText(*(SFMLText*)_pFrom) : new SFMLText);
}
void SFMLFacade::destroyText(Text* _pText)
{
delete _pText;
}
Sprite* SFMLFacade::createSprite(Sprite* _pFrom)
{
return (_pFrom ? new SFMLSprite(*(SFMLSprite*)_pFrom) : new SFMLSprite);
}
void SFMLFacade::destroySprite(Sprite* _pSprite)
{
delete _pSprite;
}
Shape* SFMLFacade::createShape(string _szType, Shape* _pFrom)
{
if(_szType == "Default")
{
return (_pFrom ? new SFMLShape(*(SFMLShape*)_pFrom) : new SFMLShape);
}
else if (_szType == "Rectangle")
{
return (_pFrom ? new SFMLRectangleShape(*(SFMLRectangleShape*)_pFrom) : new SFMLRectangleShape);
}
else if (_szType == "Circle")
{
return (_pFrom ? new SFMLCircleShape(*(SFMLCircleShape*)_pFrom) : new SFMLCircleShape);
}
else if (_szType == "Arrow")
{
return (_pFrom ? new SFMLArrowShape(*(SFMLArrowShape*)_pFrom) : new SFMLArrowShape);
}
else if (_szType == "Line")
{
return (_pFrom ? new SFMLLineShape(*(SFMLLineShape*)_pFrom) : new SFMLLineShape);
}
return nullptr;
}
void SFMLFacade::destroyShape(Shape* _pShape)
{
delete _pShape;
}
Shader* SFMLFacade::createShader(Shader* _pFrom)
{
// todo: implement SFML shaders
return nullptr;
}
void SFMLFacade::destroyShader(Shader* _pShader)
{
// todo: implement SFML shaders
}
Material* SFMLFacade::createMaterial(Material* _pFrom)
{
// todo: implement SFML materials
return nullptr;
}
void SFMLFacade::destroyMaterial(Material* _pMaterial)
{
// todo: implement SFML materials
}
bool SFMLFacade::isKeyPressed(Key _key)
{
if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)_key)) // Key mapping is the same as SFML
{
return true;
}
return false;
}
bool SFMLFacade::isMouseButtonPressed(Button _button)
{
if (sf::Mouse::isButtonPressed((sf::Mouse::Button)_button)) // Mouse mapping is the same as SFML
{
return true;
}
return false;
}
Vector2f SFMLFacade::getMousePosition()
{
sf::Vector2i vMousePosition = sf::Mouse::getPosition(*m_pWindow); // Get position relative to window
return Vector2f((float) vMousePosition.x, (float)vMousePosition.y);
}
extern "C" __declspec(dllexport) SFMLFacade* StartPlugin()
{
return &SFMLFacade::Instance();
}
} // namespace crea<file_sep>/***************************************************/
/* Nom: GL3Color.h
/* Description: GL3Color
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Color_H
#define _GL3Color_H
#include "Graphics\Color.h"
namespace crea
{
class GL3Color : public Color
{
unsigned char m_r;
unsigned char m_g;
unsigned char m_b;
unsigned char m_a;
public:
GL3Color(
unsigned char _r,
unsigned char _g,
unsigned char _b,
unsigned char _a)
{
m_r = _r;
m_g = _g;
m_b = _b;
m_a = _a;
}
float getR() const { return m_r * ONEOVER255; }
float getG() const { return m_g * ONEOVER255; }
float getB() const { return m_b * ONEOVER255; }
float getA() const { return m_a * ONEOVER255; }
GL3Color()
{
}
virtual ~GL3Color()
{
}
virtual void setValues(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a)
{
m_r = _r;
m_g = _g;
m_b = _b;
m_a = _a;
}
};
} // namespace crea
#endif // _GL3Color_H<file_sep>#include "stdafx.h"
#include "Physics\Collider.h"
namespace crea
{
Collider::Collider(EnumColliderType _eColliderType)
{
m_bIsColliding = false;
m_bIsTrigger = false;
m_eColliderType = _eColliderType;
}
Collider::~Collider()
{
}
// Is the collider colliding with the given one
bool Collider::isColliding(Collider* _pCollider, bool _bWithTrigger)
{
if (m_bIsTrigger && !_bWithTrigger)
{
return false;
}
if (m_eColliderType == Collider_Box)
{
if (_pCollider->m_eColliderType == Collider_Box)
{
m_bIsColliding = collisionBoxBox(this, _pCollider);
}
else if (_pCollider->m_eColliderType == Collider_Circle)
{
m_bIsColliding = collisionBoxCircle(this, _pCollider);
}
}
else if (m_eColliderType == Collider_Circle)
{
if (_pCollider->m_eColliderType == Collider_Box)
{
m_bIsColliding = collisionBoxCircle(_pCollider, this);
}
else if (_pCollider->m_eColliderType == Collider_Circle)
{
m_bIsColliding = collisionCircleCircle(_pCollider, this);
}
}
_pCollider->m_bIsColliding = m_bIsColliding;
return m_bIsColliding;
}
Collider* Collider::loadFromFileJSON(const string& _filename)
{
Json::Value root;
std::ifstream config_doc(_filename, std::ifstream::binary);
config_doc >> root;
string szType = root["type"].asString();
if (szType == "Circle")
{
CircleCollider* pCircleCollider = new CircleCollider;
pCircleCollider->getCenter() = Vector2f(root["x"].asFloat(), root["y"].asFloat());
pCircleCollider->getRadius() = root["radius"].asFloat();
return pCircleCollider;
}
else if (szType == "Box")
{
BoxCollider* pBoxCollider = new BoxCollider;
pBoxCollider->getOrigin() = Vector2f(root["x"].asFloat(), root["y"].asFloat());
pBoxCollider->getSize() = Vector2f(root["w"].asFloat(), root["h"].asFloat());
return pBoxCollider;
}
return nullptr;
}
bool Collider::init()
{
return true;
}
bool Collider::update()
{
return true;
}
bool Collider::draw()
{
return true;
}
bool Collider::quit()
{
return true;
}
bool Collider::collisionBoxBox(Collider* _pCollider1, Collider* _pCollider2)
{
Entity* pEntity1 = _pCollider1->getEntity();
Entity* pEntity2 = _pCollider2->getEntity();
Vector2f vPos1 = pEntity1 ? pEntity1->getPosition() : Vector2f(0.f, 0.f);
Vector2f vPos2 = pEntity2 ? pEntity2->getPosition() : Vector2f(0.f, 0.f);
BoxCollider* pBox1 = (BoxCollider*)_pCollider1;
BoxCollider* pBox2 = (BoxCollider*)_pCollider2;
Vector2f vWorldMin1 = vPos1 + pBox1->getMin();
Vector2f vWorldMax1 = vPos1 + pBox1->getMax();
Vector2f vWorldMin2 = vPos2 + pBox2->getMin();
Vector2f vWorldMax2 = vPos2 + pBox2->getMax();
for (char i = 0; i < 2; i++)
{
if (vWorldMax1.get(i) < vWorldMin2.get(i))
{
return false;
}
else if (vWorldMin1.get(i) > vWorldMax2.get(i))
{
return false;
}
}
return true;
}
bool Collider::collisionBoxCircle(Collider* _pCollider1, Collider* _pCollider2)
{
Entity* pEntity1 = _pCollider1->getEntity();
Entity* pEntity2 = _pCollider2->getEntity();
Vector2f vPos1 = pEntity1 ? pEntity1->getPosition() : Vector2f(0.f, 0.f);
Vector2f vPos2 = pEntity2 ? pEntity2->getPosition() : Vector2f(0.f, 0.f);
BoxCollider* pBox1 = (BoxCollider*)_pCollider1;
CircleCollider* pCircle2 = (CircleCollider*)_pCollider2;
Vector2f vWorldMin1 = vPos1 + pBox1->getMin();
Vector2f vWorldMax1 = vPos1 + pBox1->getMax();
Vector2f vWorldCenter2 = vPos2 + pCircle2->getCenter();
float fRadius = pCircle2->getRadius();
float s, d = 0;
//find the square of the distance
//from the sphere to the box
for (char i = 0; i<2; i++)
{
if (vWorldCenter2.get(i) < vWorldMin1.get(i))
{
s = vWorldCenter2.get(i) - vWorldMin1.get(i);
d += s * s;
}
else if (vWorldCenter2.get(i) > vWorldMax1.get(i))
{
s = vWorldCenter2.get(i) - vWorldMax1.get(i);
d += s * s;
}
}
return d <= (fRadius*fRadius);
}
bool Collider::collisionCircleCircle(Collider* _pCollider1, Collider* _pCollider2)
{
Entity* pEntity1 = _pCollider1->getEntity();
Entity* pEntity2 = _pCollider2->getEntity();
Vector2f vPos1 = pEntity1 ? pEntity1->getPosition() : Vector2f(0.f, 0.f);
Vector2f vPos2 = pEntity2 ? pEntity2->getPosition() : Vector2f(0.f, 0.f);
CircleCollider* pCircle1 = (CircleCollider*)_pCollider1;
CircleCollider* pCircle2 = (CircleCollider*)_pCollider2;
Vector2f vWorldCenter1 = vPos1 + pCircle1->getCenter();
Vector2f vWorldCenter2 = vPos2 + pCircle2->getCenter();
float fRadius1 = pCircle1->getRadius();
float fRadius2 = pCircle2->getRadius();
float fDistSq = vWorldCenter1.distSq(vWorldCenter2);
float fRadiuses = fRadius1 + fRadius2;
if (fDistSq < (fRadiuses*fRadiuses))
{
return true;
}
return false;
}
BoxCollider::BoxCollider()
: Collider(Collider_Box)
{
}
BoxCollider::~BoxCollider()
{
}
CircleCollider::CircleCollider()
: Collider(Collider_Circle), m_fRadius(0.f)
{
}
CircleCollider::~CircleCollider()
{
}
Component* CircleCollider::clone()
{
Collider* pCollider = new CircleCollider(*this);
// TODO: CB: Patch, make sure the circleCollider is dynamic...
string s = this->m_szName + to_string(EntityManager::getSingleton()->getNewObjectID());
PhysicsManager::getSingleton()->addDynamicCollider(s, pCollider);
return pCollider;
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: Collider.h
/* Description: Collider
/* Auteur: <NAME>
/***************************************************/
#ifndef __Collider_H_
#define __Collider_H_
#include "Core\Component.h"
#include "Core\Math.h"
namespace crea
{
enum EnumColliderType
{
Collider_Invalid = -1,
Collider_Box = 0,
Collider_Circle,
};
class CircleCollider;
class BoxCollider;
class CREAENGINE_API Collider : public Component
{
bool collisionBoxBox(Collider* _pCollider1, Collider* _pCollider2);
bool collisionBoxCircle(Collider* _pCollider1, Collider* _pCollider2);
bool collisionCircleCircle(Collider* _pCollider1, Collider* _pCollider2);
protected:
EnumColliderType m_eColliderType;
bool m_bIsColliding;
bool m_bIsTrigger;
public:
Collider(EnumColliderType _eColliderType = Collider_Circle);
virtual ~Collider();
EnumColliderType getColliderType() { return m_eColliderType; }
bool& getIsTrigger() { return m_bIsTrigger; }
virtual bool isColliding(Collider* _pCollider, bool _bWithTrigger = false);
static Collider* loadFromFileJSON(const string& _filename);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() = 0;
};
class CREAENGINE_API BoxCollider : public Collider
{
Vector2f m_vOrigin;
Vector2f m_vSize;
public:
BoxCollider();
virtual ~BoxCollider();
inline Vector2f& getOrigin() { return m_vOrigin; }
inline Vector2f& getSize() { return m_vSize; }
inline float getMinX() { return m_vOrigin.getX(); }
inline float getMinY() { return m_vOrigin.getY(); }
inline float getMaxX() { return m_vOrigin.getX() + m_vSize.getX(); }
inline float getMaxY() { return m_vOrigin.getY() + m_vSize.getY(); }
inline Vector2f getMin() { return Vector2f(getMinX(), getMinY()); }
inline Vector2f getMax() { return Vector2f(getMaxX(), getMaxY()); }
virtual Component* clone() { return new BoxCollider(*this); }
};
class CREAENGINE_API CircleCollider : public Collider
{
Vector2f m_vCenter;
float m_fRadius;
public:
CircleCollider();
virtual ~CircleCollider();
inline Vector2f& getCenter() { return m_vCenter; }
// TODO: CB: for now, no rotation but to modify when Transformable with rotation
inline Vector2f getWorldCenter() { return (m_pEntity ? m_pEntity->getPosition() + m_vCenter : m_vCenter); }
inline float& getRadius() { return m_fRadius; }
virtual Component* clone();
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Core\Scene.h"
namespace crea
{
Scene::Scene()
{
}
Scene::~Scene()
{
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "AI\Steering\Steering.h"
#include "AI\Steering\Behavior.h"
#include "Physics\Collider.h"
#include "Core\PhysicsManager.h"
namespace crea
{
PairFloatBehavior::PairFloatBehavior(float _f, Behavior* _p) : pair<float, Behavior*>(_f, _p) {}
PairFloatBehavior::~PairFloatBehavior() { delete this->second; }
Steering::Steering() :
m_pTarget(nullptr), m_vSteeringDirection(0.f, 0.f)
{
m_pGM = GameManager::getSingleton();
m_pCollider = nullptr;
}
Steering::~Steering()
{
clearBehaviors();
}
void Steering::setCollider(Collider* _pCollider)
{
m_pCollider = _pCollider;
}
void Steering::addBehavior(Behavior* _behavior, float _weight)
{
m_behaviors.push_back(new PairFloatBehavior(_weight, _behavior));
};
void Steering::removeBehavior(Behavior* _behavior)
{
if (m_behaviors.empty())
return;
auto a = std::remove_if(m_behaviors.begin(), m_behaviors.end(),
[=](PairFloatBehavior* p) { return p->second == _behavior; });
m_behaviors.erase(a);
};
void Steering::clearBehaviors()
{
for (int i = 0; i < (int)m_behaviors.size(); i++)
{
PairFloatBehavior* p = m_behaviors.back();
delete(p);
m_behaviors.pop_back();
}
m_behaviors.clear();
};
Vector2f Steering::steer()
{
Vector2f steeringDirection;
for (int i = 0; i < (int)m_behaviors.size(); i++)
{
PairFloatBehavior* t = m_behaviors[i];
Behavior* b = (Behavior*)t->second;
Vector2f v = b->Update();
steeringDirection += (v * t->first);
}
return steeringDirection;
}
string Steering::asString()
{
stringstream stream;
string szSteering("");
Vector2f steeringDirection;
for (int i = 0; i < (int)m_behaviors.size(); i++)
{
PairFloatBehavior* t = m_behaviors[i];
Behavior* b = (Behavior*)t->second;
szSteering += t->second->asString();
szSteering += " ";
stream << fixed << setprecision(1) << t->first;
szSteering += stream.str();
}
return szSteering;
}
bool Steering::init()
{
m_pTarget = nullptr;
return true;
}
bool Steering::update()
{
m_vSteeringDirection = steer();
return true;
}
bool Steering::draw()
{
return true;
}
bool Steering::quit()
{
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Scene\SceneMenu.h"
#include "Scene\SceneGame.h"
#include "Core\SceneManager.h"
#include "Core\GameManager.h"
#include "Data\DataManager.h"
#include "Core\EntityManager.h"
#include "Core\Entity.h"
#include "Graphics\SpriteRenderer.h"
SceneMenu::SceneMenu()
{
}
SceneMenu::~SceneMenu()
{
}
bool SceneMenu::onInit()
{
m_pGM = GameManager::getSingleton();
// Color
Color* pRed = m_pGM->getColor("Red");
pRed->setValues(255, 0, 0, 255);
// Text
Text* m_pText = m_pGM->getText("text 1");
m_pText->setFont(m_pGM->getFont("arial.ttf"));
m_pText->setColor(pRed);
m_pText->setCharacterSize(20);
m_pText->setString("MENU. Press 1 to display Menu, 2 to display Game...");
// TextRenderer
m_pTextRenderer = m_pGM->getTextRenderer("FontTR");
m_pTextRenderer->setText(m_pText);
// Entity
m_pEntity1 = m_pGM->getEntity("text 1 Entity");
m_pEntity1->setName(string("text 1"));
m_pEntity1->addComponent(m_pTextRenderer);
m_pGM->addEntity(m_pEntity1);
return true;
}
bool SceneMenu::onUpdate()
{
// Get direction from keyboard
if (m_pGM->isKeyPressed(Key::Num2))
{
m_pGM->setScene(new SceneGame());
return true;
}
return true;
}
bool SceneMenu::onDraw()
{
return true;
}
bool SceneMenu::onQuit()
{
m_pGM->clearAllEntities();
return true;
}
<file_sep># AI-Project
Artificial Intelligence Framework developped at Creajeux by <NAME>
This project started in 2015 as a way to centralize the development of the AI engine made during the course AI that I gave to 3rd year students.
Then it got bigger with the integration of DirectX as base graphics engine.
It also allows me to test a Git repositery.
<file_sep>#include "stdafx.h"
#include "Data\Asset.h"
namespace crea
{
Asset::Asset()
{
}
Asset::~Asset()
{
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: Animation.h
/* Description: Animation
/* Auteur: <NAME>
/***************************************************/
#ifndef __Animation_H_
#define __Animation_H_
#include <vector>
namespace crea
{
class IntRect;
class CREAENGINE_API Animation
{
public:
Animation();
void addFrame(IntRect rect);
void setSpriteSheet(Texture& texture);
inline void setSpeed(float _fSpeed) { m_fSpeed = _fSpeed; }
inline Texture* getSpriteSheet() { return m_texture; }
inline size_t getSize() { return m_frames.size(); }
inline IntRect& getFrame(std::size_t n) { return m_frames[n]; }
inline string getName() { return m_szName; }
inline Time& getDuration() { return m_duration; }
inline bool getLooping() { return m_bLooping; }
inline float getSpeed() { return m_fSpeed; }
void adjustToTranslationSpeed(float _fTranslationSpeed);
bool loadFromFileJSON(const string& _filename);
virtual Animation* clone()
{
Animation* pAnimation = new Animation(*this);
return pAnimation;
}
private:
string m_szName;
vector<IntRect> m_frames;
Texture* m_texture;
Time m_duration;
bool m_bLooping;
float m_fSpeed;
int m_iTranslationSpeed;
};
} // namespace crea
#endif // __Animation_H_<file_sep>/***************************************************/
/* Nom: FSMHQ.h
/* Description: FSMHQ
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMHQ_H_
#define __FSMHQ_H_
#include "AI\StateMachine.h"
#include "AI\Planning\Planner.h"
#include "AI\Planning\WorldState.h"
using namespace crea;
class FSMHQ : public StateMachine
{
GameManager* m_pGM;
Entity* m_pEntity;
Entity* m_pMiner;
Entity* m_pWoodCutter;
Entity* m_pBlackSmith;
Entity* m_pLogger;
vector<goap::Action> m_actionsPossible;
goap::Planner m_planner;
goap::WorldState m_initState;
goap::WorldState m_goalState;
vector<goap::Action> m_actionsToDo;
public:
FSMHQ();
virtual ~FSMHQ();
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone() { return new FSMHQ(*this); }
};
#endif
<file_sep>/***************************************************/
/* Nom: Cluster.h
/* Description: Cluster
/* Auteur: <NAME>
/***************************************************/
#ifndef __Cluster_H_
#define __Cluster_H_
#include <vector>
namespace crea
{
class CREAENGINE_API Edge
{
public:
Node * m_pStart;
Node* m_pEnd;
float m_fDistance;
};
class CREAENGINE_API Entrance
{
public:
Node * m_pStart;
Node* m_pEnd;
Entrance* m_pSymm;
};
class CREAENGINE_API Transition
{
public:
Node * m_pStart;
Node* m_pEnd;
Edge* m_pEdge;
};
class CREAENGINE_API Cluster
{
// Position
short m_nX;
short m_nY;
// Size
short m_nClusterWidth;
short m_nClusterHeight;
// Neighbors
Cluster* m_pTopCluster;
Cluster* m_pBottomCluster;
Cluster* m_pLeftCluster;
Cluster* m_pRightCluster;
// Entrances
vector<Entrance*>* m_pEntrances;
// Transitions
vector<Transition*>* m_pTransitions;
// Edges
vector<Edge*>* m_pEdges;
public:
Cluster();
virtual ~Cluster();
// Pre-processing
void setPosition(short _nX, short _nY) { m_nX = _nX; m_nY = _nY; }
void getPosition(short& _nX, short& _nY) { _nX = m_nX; _nY = m_nY; }
void setSize(short _nClusterWidth, short _nClusterHeight) { m_nClusterWidth = _nClusterWidth; m_nClusterHeight = _nClusterHeight; }
void getSize(short& _nClusterWidth, short& _nClusterHeight) { _nClusterWidth = m_nClusterWidth; _nClusterHeight = m_nClusterHeight; }
bool isInCluster(short _i, short _j);
void addTopCluster(Cluster* _pCluster) { m_pTopCluster = _pCluster; }
void addBottomCluster(Cluster* _pCluster) { m_pBottomCluster = _pCluster; }
void addLeftCluster(Cluster* _pCluster) { m_pLeftCluster = _pCluster; }
void addRightCluster(Cluster* _pCluster) { m_pRightCluster = _pCluster; }
void findEntrances();
void findTransitions();
void findEdges(bool _bidirectional = true);
vector<Entrance*>* getEntrances() { return m_pEntrances; }
vector<Transition*>* getTransitions() { return m_pTransitions; }
vector<Edge*>* getEdges() { return m_pEdges; }
// Online search
bool getEdgesFromNode(Node* _pNode, vector<Edge*>& _edges);
bool update();
bool draw();
void clear();
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: EntityManager.h
/* Description: EntityManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __EntityManager_H_
#define __EntityManager_H_
#include <map>
#include <list>
using namespace std;
namespace crea
{
// Prédéfinitions
class Entity;
class TextRenderer;
class SpriteRenderer;
class MapRenderer;
class Animator;
class Vector2f;
class Script;
class ScriptFactory;
class Steering;
class CREAENGINE_API MapStringTextRenderer : public map<string, TextRenderer*> {};
class CREAENGINE_API MapStringSpriteRenderer : public map<string, SpriteRenderer*> {};
class CREAENGINE_API MapStringMapRenderer : public map<string, MapRenderer*> {};
class CREAENGINE_API MapStringAnimator : public map<string, Animator*> {};
class CREAENGINE_API MapStringScript : public map<string, Script*> {};
class CREAENGINE_API MapStringSteering : public map<string, Steering*> {};
class CREAENGINE_API ListEntity : public list<Entity*> {};
class CREAENGINE_API MapObjectIDEntity : public map<objectID, Entity*> {};
class CREAENGINE_API MapModelEntity : public map<string, Entity*> {};
class CREAENGINE_API EntityManager
{
Entity* m_pRoot;
MapStringTextRenderer m_pTextRenderers;
MapStringSpriteRenderer m_pSpriteRenderers;
MapStringMapRenderer m_pMapRenderers;
MapStringAnimator m_pAnimators;
MapStringScript m_pScripts;
MapStringSteering m_pSteerings;
ScriptFactory* m_pScriptFactory;
ListEntity m_pSelectedEntities;
EntityManager();
objectID nextFreeID;
MapObjectIDEntity m_Entities;
MapModelEntity m_EntitiesByModel;
public:
virtual ~EntityManager();
static EntityManager* getSingleton();
Entity* getEntity(const string& _szName);
Entity* getEntityByModel(const string& _szName);
void addEntityByModel(const string& _szName, Entity* _pEntity);
void addEntity(Entity* _pEntity, Entity* _pParent = nullptr);
Entity* instanciate(string& _szName, Entity* _pEntity);
void clearEntity(Entity* _pEntity);
TextRenderer* getTextRenderer(const string& _szName, bool _bCloned = false);
SpriteRenderer* getSpriteRenderer(const string& _szName, bool _bCloned = false);
MapRenderer* getMapRenderer(const string& _szName, bool _bCloned = false);
Animator* getAnimator(const string& _szName, bool _bCloned = false);
Script* getScript(const string& _szName, bool _bCloned = false);
Steering* getSteering(string _szName, bool _bCloned = false);
inline void setScriptFactory(ScriptFactory* _pScriptFactory) { m_pScriptFactory = _pScriptFactory; }
void selectEntities(Vector2f _vStart, Vector2f _vEnd);
void addSelectedEntity(Entity* _pEntity);
void unselectEntities();
inline ListEntity* getSelectedEntities() { return &m_pSelectedEntities; }
void Store(Entity& _agent);
void Remove(objectID _id);
Entity* Find(objectID _id);
objectID getNewObjectID();
bool init();
bool update();
bool draw();
void clear();
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: Animator.h
/* Description: Animator
/* Auteur: <NAME>
/***************************************************/
#ifndef __Animator_H_
#define __Animator_H_
#include "Core\Component.h"
#include "Core\Math.h"
#include "Core\TimeManager.h"
#include "Graphics\SpriteRenderer.h"
#include "Data\Animation.h"
namespace crea
{
class CREAENGINE_API Animator : public Component
{
Sprite* m_pSprite;
Animation* m_pAnimation;
Time m_frameTime;
Time m_currentTime;
int m_currentFrame;
bool m_isPaused;
public:
Animator();
virtual ~Animator();
void setSprite(Sprite* _pSprite);
void setAnimation(Animation& animation);
void setFrameTime(Time& time);
Animation* getAnimation();
Time getFrameTime();
IntRect getFrame();
bool isPlaying();
void play();
void play(Animation& animation);
void pause();
void stop();
bool loadFromFileJSON(const string& _filename);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone()
{
Animator* pAnimator = new Animator(*this);
pAnimator->m_pSprite = nullptr;
if (pAnimator->m_pAnimation)
pAnimator->m_pAnimation = m_pAnimation->clone();
/*
if (pAnimator->m_pSprite)
pAnimator->m_pSprite = m_pSprite->clone();
if (pAnimator->m_pAnimation)
pAnimator->m_pAnimation = m_pAnimation->clone();
*/
return pAnimator;
}
};
} // namespace crea
#endif
<file_sep>/***************************************************/
/* Nom: DX9Texture.h
/* Description: DX9Texture
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Texture_H
#define _DX9Texture_H
#include "Graphics\Texture.h"
namespace crea
{
class DX9Texture : public Texture
{
LPDIRECT3DTEXTURE9 m_pTexture;
public:
LPDIRECT3DTEXTURE9 getTexture() { return m_pTexture; }
DX9Texture() { m_pTexture = nullptr; }
virtual ~DX9Texture() { SafeRelease(m_pTexture); }
virtual inline void setTransparency(bool _transparency) { /*todo: handletransparency for DX9*/ }
virtual inline bool getTransparency() { return false; }
virtual bool loadFromFile(const string& _file)
{
if (FAILED(D3DXCreateTextureFromFile(DX9Facade::Instance().m_pDevice, _file.c_str(), &m_pTexture)))
{
cerr << "Failed to load texture Sprite." << endl;
return false;
}
return true;
}
virtual void bind(unsigned int _channel) {}
virtual void unbind(unsigned int _channel) {}
};
} // namespace crea
#endif // _DX9Texture_H
<file_sep>#include "stdafx.h"
#include "Scripts\FSMBalistaLive.h"
#include "Scripts\Messages.h"
#include <string.h>
//Add new states here
enum States {
STATE_Init,
STATE_Idle,
STATE_GoTo,
STATE_GetResource,
STATE_DropResource,
STATE_Hit,
STATE_Build,
STATE_Mine,
STATE_Harvest,
STATE_Kill,
STATE_Steer
};
FSMBalistaLive::FSMBalistaLive()
{
}
FSMBalistaLive::~FSMBalistaLive()
{
}
bool FSMBalistaLive::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
OnMsg(MSG_Stop)
m_pCharacterController->setAction(kAct_Default);
m_bPaused = true;
OnMsg(MSG_GoTo)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_GoTo);
m_bPaused = false;
OnMsg(MSG_Kill)
SetState(STATE_Kill);
OnMsg(MSG_Hit)
SetState(STATE_Hit);
OnMsg(MSG_HitStop)
SetStateInHistory();
///////////////////////////////////////////////////////////////
State(STATE_Init)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
// Get Steering
m_pSteering = m_pEntity->getComponent<Steering>();
m_pSteering->init();
// Get Vehicle
m_pVehicle = m_pEntity->getComponent<Vehicle>();
m_pVehicle->setUpdatePosition(false); //The characterController will update the position
OnUpdate
SetState(STATE_Steer);
///////////////////////////////////////////////////////////////
State(STATE_Idle)
OnEnter
m_bPaused = false;
OnUpdate
// Mouse control
if (m_pGM->isMouseButtonPressed(Button::MouseRight))
{
m_vTarget = m_pGM->getMousePosition();
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_GoTo);
}
///////////////////////////////////////////////////////////////
State(STATE_GoTo)
OnEnter
m_pFSMBalistaGoTo = new FSMBalistaGoTo(m_vTarget);
m_pEntity->addComponent(m_pFSMBalistaGoTo);
m_pFSMBalistaGoTo->Initialize(getEntity());
OnUpdate
if (!m_bPaused)
{
//m_pFSMBalistaGoTo->Update();
if (m_pFSMBalistaGoTo->GetState() == FSMBalistaGoTo::STATE_CompletedPath)
{
SetState(STATE_Idle);
}
else if (m_pFSMBalistaGoTo->GetState() == FSMBalistaGoTo::STATE_SearchFailed)
{
SetState(STATE_Idle);
}
}
else
{
m_pCharacterController->move(Vector2f(0.f, 0.f));
}
OnExit
m_pEntity->removeComponent(m_pFSMBalistaGoTo);
delete m_pFSMBalistaGoTo;
m_pFSMBalistaGoTo = nullptr;
///////////////////////////////////////////////////////////////
State(STATE_Hit)
OnEnter
// CB: a hit is a temporary death...
SendDelayedMsgToMe(0.5f, MSG_HitStop);
OnUpdate
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Die);
OnExit
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Default);
///////////////////////////////////////////////////////////////
State(STATE_Kill)
OnEnter
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Chop);
///////////////////////////////////////////////////////////////
State(STATE_Hit)
OnEnter
// CB: a hit is a temporary death...
SendDelayedMsgToMe(0.5f, MSG_HitStop);
OnUpdate
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Die);
OnExit
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Default);
///////////////////////////////////////////////////////////////
State(STATE_Steer)
OnEnter
OnUpdate
Move();
EndStateMachine
}
bool FSMBalistaLive::Move()
{
bool bMoving = true;
Vector2f vVelocity = m_pVehicle->getVelocity();
// CB: adjust velocity with dexterity
int iDexterity = m_pAgent->getDexterity() / 5;
if (vVelocity.length() > 10)
{
m_pCharacterController->setAction(kAct_Walk);
m_pCharacterController->move(vVelocity * (float)iDexterity);
m_pCharacterController->setDirection(vVelocity);
}
else
{
bMoving = false;
vVelocity = Vector2f(0.f, 0.0f);
m_pCharacterController->move(vVelocity);// do not move
// but do not change direction
}
return bMoving;
}
<file_sep>/***************************************************/
/* Nom: CharacterController.h
/* Description: CharacterController
/* Auteur: <NAME>
/***************************************************/
#ifndef __CharacterController_H_
#define __CharacterController_H_
#include "Core\Script.h"
#include "Core\Math.h"
#include "Core\GameManager.h"
using namespace crea;
enum EnumCharacterDirection
{
kADir_Invalid = -1,
kADir_Up,
kADir_UpRight,
kADir_Right,
kADir_DownRight,
kADir_Down,
kADir_DownLeft,
kADir_Left,
kADir_UpLeft,
};
enum EnumAnimCondition
{
kACond_Invalid = -1,
kACond_Default = 0,
kACond_Lumber,
kACond_Gold,
};
enum EnumAction
{
kAct_Invalid = -1,
kAct_Default = 0,
kAct_Idle,
kAct_Walk,
kAct_Die,
kAct_Chop,
};
class CharacterController : public crea::Script
{
GameManager* m_pGM;
Agent* m_pAgent;
Vehicle* m_pVehicle;
// Velocity
Vector2f m_vMotion;
float m_fVelocityMax;
// Animation
Animator* m_pAnimator;
ActionTable* m_pActionTable;
EnumCharacterDirection m_eDirection;
EnumAnimCondition m_eCondition;
EnumAction m_eAction;
Animation* m_pCurrentAnimation;
bool m_bAlive;
bool m_bMoving;
bool shouldFollowPath = false;
vector<Vector2f*> m_path;
vector<Vector2f*>::iterator m_previousIt;
vector<Vector2f*>::iterator m_nextIt;
Vector2f m_offset;
// Collider
Collider* m_pCollider;
bool m_isColliding = false;
public:
CharacterController();
virtual ~CharacterController();
void setActionTable(ActionTable* _pActionTable);
void setAnimator(Animator* _pAnimator);
void setCondition(EnumAnimCondition _eCondition);
void setAction(EnumAction _eAction);
void setDirection(EnumCharacterDirection _eDirection);
void setDirection(Vector2f _vDirection);
EnumAnimCondition getCondition() { return m_eCondition; }
EnumAction getAction() { return m_eAction; }
EnumCharacterDirection getDirection() { return m_eDirection; }
void move(Vector2f _vMotion);
void followPath(vector<Vector2f*>& _path, const Vector2f& _offset = Vector2f(0.f, 0.f));
bool stupidSwordman(Vector2f& _position, Vector2f& _direction, float _speed);
inline bool isFollowingPath() { return shouldFollowPath; }
inline void setFollowingPath(bool _bFollowingPath) { shouldFollowPath = _bFollowingPath; }
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual void onCollisionEnter2D(Collision2D& _coll);
virtual void onCollisionExit2D(Collision2D& _coll);
virtual Component* clone() { return new CharacterController(*this); }
};
#endif
<file_sep>#include "stdafx.h"
#include "AI\BehaviorTree\BehaviorTree.h"
#include "AI\BehaviorTree\Behavior.h"
namespace bt
{
BehaviorTree::BehaviorTree()
: m_pRoot(nullptr)
{
}
BehaviorTree::~BehaviorTree()
{
}
void BehaviorTree::setRootBehavior(Behavior* _pRoot)
{
m_pRoot = _pRoot;
}
bool BehaviorTree::init()
{
return true;
}
bool BehaviorTree::update()
{
if (m_pRoot)
{
m_pRoot->tick();
return true;
}
return false;
}
bool BehaviorTree::draw()
{
return true;
}
bool BehaviorTree::quit()
{
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Scene\ScenePlanning.h"
#include "Scene\SceneMenu.h"
#include "Scene\SceneGame.h"
#include "Scene\SceneMap.h"
#include "Scene\SceneSteering.h"
#include "AI\Steering\Behavior.h"
#include <string>
ScenePlanning::ScenePlanning()
{
// AI Tools
m_bUseAITools = true;
m_pAITools = new AITools();
}
ScenePlanning::~ScenePlanning()
{
// AI Tools
delete m_pAITools;
}
bool ScenePlanning::onInit()
{
m_pGM = GameManager::getSingleton();
m_rWindowRect = m_pGM->getWindowRect();
// Set Script factory
m_pCellsScriptFactory = new CellsScriptFactory;
m_pGM->setScriptFactory(m_pCellsScriptFactory);
// Load Map
m_pEntity4 = m_pGM->getEntity("MapPlanning");
m_pGM->addEntity(m_pEntity4);
m_pMap = m_pGM->getMap("MapPlanning.json"); // CB: TO CHANGE: Map id loaded after entity added to display Map first (order in tree matters)
m_pMap->loadFromFileJSON(string(DATAMAPPATH) + "MapPlanning.json");
m_pMapRenderer = m_pGM->getMapRenderer("MapRenderer1");
m_pMapRenderer->setMap(m_pMap);
m_pEntity4->addComponent(m_pMapRenderer);
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onInit();
}
// TD BT
Blackboard* pBB = Blackboard::getSingleton();
pBB->setVariable("HqHaveGold", "0");
pBB->setVariable("HqHaveFirewood", "0");
pBB->setVariable("HqHaveTool", "0");
pBB->setVariable("HqHaveLogs", "0");
pBB->setVariable("HqHaveMoreGold", "0");
return true;
}
bool ScenePlanning::onUpdate()
{
if (m_pGM->isKeyPressed(Key::Num1))
{
m_pGM->setScene(new SceneMenu());
return true;
}
if (m_pGM->isKeyPressed(Key::Num2))
{
m_pGM->setScene(new SceneGame());
return true;
}
if (m_pGM->isKeyPressed(Key::Num3))
{
m_pGM->setScene(new SceneMap());
return true;
}
if (m_pGM->isKeyPressed(Key::Num4))
{
m_pGM->setScene(new SceneSteering());
return true;
}
if (m_pGM->isKeyPressed(Key::Escape))
{
return false;
}
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onUpdate();
}
return true;
}
bool ScenePlanning::onDraw()
{
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onDraw();
}
return true;
}
bool ScenePlanning::onQuit()
{
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onQuit();
}
m_pGM->clearAllData();
m_pGM->clearAllEntities();
delete m_pCellsScriptFactory;
return true;
}
<file_sep>/***************************************************/
/* Nom: Math.h
/* Description: Math
/* Auteur: <NAME>
/***************************************************/
#ifndef _Math_H
#define _Math_H
namespace crea
{
// constants
#define PI 3.14159265f
#define EPSILON 0.00001f
#define ONEOVER128 0.0078125f
#define ONEOVER255 0.00392156862745f
// Macros
#define MIN(a, b) (a<b ? a : b)
#define MAX(a, b) (a>b ? a : b)
class CREAENGINE_API Vector2f
{
float m_fX;
float m_fY;
public:
Vector2f()
{
m_fX = 0.f;
m_fY = 0.f;
}
Vector2f(float _fX, float _fY)
{
m_fX = _fX;
m_fY = _fY;
}
~Vector2f()
{
}
inline void setX(float _fX) { m_fX = _fX; }
inline void setY(float _fY) { m_fY = _fY; }
inline float getX() { return m_fX; }
inline float getY() { return m_fY; }
inline float get(char _index) { return (_index == 0 ? m_fX : m_fY); }
inline void addX(float _fX) { m_fX += _fX; }
inline void addY(float _fY) { m_fY += _fY; }
inline float dist(Vector2f& _v) { return sqrt((_v.m_fX - m_fX) * (_v.m_fX - m_fX) + (_v.m_fY - m_fY) * (_v.m_fY - m_fY)); }
inline float distSq(Vector2f& _v) { return ((_v.m_fX - m_fX) * (_v.m_fX - m_fX) + (_v.m_fY - m_fY) * (_v.m_fY - m_fY)); }
inline float length() const { return sqrt((m_fX * m_fX) + (m_fY * m_fY)); }
inline float lengthSq() const { return (m_fX * m_fX) + (m_fY * m_fY); }
inline bool normalize() { float l = length(); if (!l) return false; m_fX /= l; m_fY /= l; return true; }
inline float dot(const Vector2f& _v) const { return m_fX * _v.m_fX + m_fY * _v.m_fY; }
inline float angle(const Vector2f& _v) const { float fLength = length() * _v.length(); return acosf(dot(_v) / fLength); } // radians
bool isLeft(const Vector2f& _v) const { return (bool)((m_fX*_v.m_fY - m_fY * _v.m_fX) > 0.0f); }
inline Vector2f operator-() { return Vector2f(-m_fX, -m_fY); }
inline Vector2f operator+(Vector2f& _v) { return Vector2f(m_fX + _v.m_fX, m_fY + _v.m_fY); }
inline Vector2f operator-(Vector2f& _v) { return Vector2f(m_fX - _v.m_fX, m_fY - _v.m_fY); }
inline Vector2f& operator+=(Vector2f& _v) { m_fX += _v.m_fX; m_fY += _v.m_fY; return *this; }
inline Vector2f& operator-=(Vector2f& _v) { m_fX -= _v.m_fX; m_fY -= _v.m_fY; return *this; }
inline Vector2f operator*(float _f) { return Vector2f(m_fX * _f, m_fY * _f); }
inline Vector2f& operator*=(float _f) { m_fX *= _f; m_fY *= _f; return *this; }
inline Vector2f operator/(float _f) { assert(_f); return Vector2f(m_fX / _f, m_fY / _f); }
inline Vector2f& operator/=(float _f) { assert(_f); m_fX /= _f; m_fY /= _f; return *this; }
};
class CREAENGINE_API IntRect
{
public:
int m_iX;
int m_iY;
int m_iW;
int m_iH;
IntRect()
{
m_iX = 0;
m_iY = 0;
m_iW = 0;
m_iH = 0;
}
IntRect(int _x, int _y, int _w, int _h)
{
m_iX = _x;
m_iY = _y;
m_iW = _w;
m_iH = _h;
}
~IntRect()
{
}
inline int getLeft() const { return m_iX; }
inline int getTop() const { return m_iY; }
inline int getWidth() const { return m_iW; }
inline int getHeight() const { return m_iH; }
bool operator!=(const IntRect& _r)
{
if (_r.m_iX != m_iX || _r.m_iY != m_iY || _r.m_iW != m_iW || _r.m_iH != m_iH)
{
return true;
}
return false;
}
bool contains(Vector2f& _v)
{
if (_v.getX() > m_iX && _v.getX() < m_iX + m_iW && _v.getY() > m_iY && _v.getY() < m_iY + m_iH)
{
return true;
}
return false;
}
};
class CREAENGINE_API FloatRect
{
public:
float m_fX;
float m_fY;
float m_fW;
float m_fH;
FloatRect()
{
}
FloatRect(float _x, float _y, float _w, float _h)
{
m_fX = _x;
m_fY = _y;
m_fW = _w;
m_fH = _h;
}
~FloatRect()
{
}
FloatRect(Vector2f _vStart, Vector2f _vEnd)
{
float x1 = _vStart.getX();
float y1 = _vStart.getY();
float x2 = _vEnd.getX();
float y2 = _vEnd.getY();
m_fX = x1;
m_fY = y1;
m_fW = x2 - x1;
m_fH = y2 - y1;
if (m_fW < 0.f)
{
m_fX = x2;
m_fW = -m_fW;
}
if (m_fH < 0.f)
{
m_fY = y2;
m_fH = -m_fH;
}
}
bool contains(Vector2f& _v)
{
if (_v.getX() > m_fX && _v.getX() < m_fX + m_fW && _v.getY() > m_fY && _v.getY() < m_fY + m_fH)
{
return true;
}
return false;
}
};
class CREAENGINE_API MathTools
{
public:
static Vector2f truncate(Vector2f _vector, float lengthLimit) {
float length = _vector.length();
if (length > lengthLimit) {
_vector.normalize();
return _vector * lengthLimit;
}
else return _vector;
}
static bool zeroByEpsilon(float _value) { return _value > -EPSILON && _value < EPSILON; }
static float lerp(float a, float b, float f) { return a * (1 - f) + b * f; }
static Vector2f lerp(Vector2f& a, Vector2f& b, float f) { return a * (1 - f) + b * f; }
static float degreetoradian(float a) { return a * 0.01745329251945f; }
static float radiantodegreee(float a) { return a * 57.29577951471995f; }
};
} // namespace crea
#endif // _ICore_H<file_sep>#include "stdafx.h"
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
namespace crea
{
GL3Facade::GL3Facade()
: m_rWindowRect(0, 0, 1280, 800),
keysMap{
GLFW_KEY_Q, ///< The A key in AZERTY
GLFW_KEY_B, ///< The B key
GLFW_KEY_C, ///< The C key
GLFW_KEY_D, ///< The D key
GLFW_KEY_E, ///< The E key
GLFW_KEY_F, ///< The F key
GLFW_KEY_G, ///< The G key
GLFW_KEY_H, ///< The H key
GLFW_KEY_I, ///< The I key
GLFW_KEY_J, ///< The J key
GLFW_KEY_K, ///< The K key
GLFW_KEY_L, ///< The L key
GLFW_KEY_SEMICOLON, ///< The M key in AZERTY
GLFW_KEY_N, ///< The N key
GLFW_KEY_O, ///< The O key
GLFW_KEY_P, ///< The P key
GLFW_KEY_A, ///< The Q key in AZERTY
GLFW_KEY_R, ///< The R key
GLFW_KEY_S, ///< The S key
GLFW_KEY_T, ///< The T key
GLFW_KEY_U, ///< The U key
GLFW_KEY_V, ///< The V key
GLFW_KEY_Z, ///< The W key in AZERTY
GLFW_KEY_X, ///< The X key
GLFW_KEY_Y, ///< The Y key
GLFW_KEY_W, ///< The Z key in AZERTY
GLFW_KEY_0, ///< The 0 key
GLFW_KEY_1, ///< The 1 key
GLFW_KEY_2, ///< The 2 key
GLFW_KEY_3, ///< The 3 key
GLFW_KEY_4, ///< The 4 key
GLFW_KEY_5, ///< The 5 key
GLFW_KEY_6, ///< The 6 key
GLFW_KEY_7, ///< The 7 key
GLFW_KEY_8, ///< The 8 key
GLFW_KEY_9, ///< The 9 key
GLFW_KEY_ESCAPE, ///< The Escape key
GLFW_KEY_LEFT_CONTROL, ///< The left Control key
GLFW_KEY_LEFT_SHIFT, ///< The left Shift key
GLFW_KEY_LEFT_ALT, ///< The left Alt key
GLFW_KEY_LEFT_SUPER, ///< The left OS specific key: window (Windows and Linux), apple (MacOS X), ...
GLFW_KEY_RIGHT_CONTROL, ///< The right Control key
GLFW_KEY_RIGHT_SHIFT, ///< The right Shift key
GLFW_KEY_RIGHT_ALT, ///< The right Alt key
GLFW_KEY_RIGHT_SUPER, ///< The right OS specific key: window (Windows and Linux), apple (MacOS X), ...
GLFW_KEY_MENU, ///< The Menu key
GLFW_KEY_LEFT_BRACKET, ///< The [ key
GLFW_KEY_RIGHT_BRACKET, ///< The ] key
GLFW_KEY_M, ///< The ; key in AZERTY
GLFW_KEY_COMMA, ///< The , key
GLFW_KEY_PERIOD, ///< The . key
GLFW_KEY_APOSTROPHE, ///< The ' key
GLFW_KEY_SLASH, ///< The / key
GLFW_KEY_BACKSLASH, ///< The \ key
GLFW_KEY_UNKNOWN, ///< The ~ key
GLFW_KEY_EQUAL, ///< The = key
GLFW_KEY_MINUS, ///< The - key
GLFW_KEY_SPACE, ///< The Space key
GLFW_KEY_ENTER, ///< The Return key
GLFW_KEY_BACKSPACE, ///< The Backspace key
GLFW_KEY_TAB, ///< The Tabulation key
GLFW_KEY_PAGE_UP, ///< The Page up key
GLFW_KEY_PAGE_DOWN, ///< The Page down key
GLFW_KEY_END, ///< The End key
GLFW_KEY_HOME, ///< The Home key
GLFW_KEY_INSERT, ///< The Insert key
GLFW_KEY_DELETE, ///< The Delete key
GLFW_KEY_KP_ADD, ///< The + key
GLFW_KEY_KP_SUBTRACT, ///< The - key
GLFW_KEY_KP_MULTIPLY, ///< The * key
GLFW_KEY_KP_DIVIDE, ///< The / key
GLFW_KEY_LEFT, ///< Left arrow
GLFW_KEY_RIGHT, ///< Right arrow
GLFW_KEY_UP, ///< Up arrow
GLFW_KEY_DOWN, ///< Down arrow
GLFW_KEY_KP_0, ///< The numpad 0 key
GLFW_KEY_KP_1, ///< The numpad 1 key
GLFW_KEY_KP_2, ///< The numpad 2 key
GLFW_KEY_KP_3, ///< The numpad 3 key
GLFW_KEY_KP_4, ///< The numpad 4 key
GLFW_KEY_KP_5, ///< The numpad 5 key
GLFW_KEY_KP_6, ///< The numpad 6 key
GLFW_KEY_KP_7, ///< The numpad 7 key
GLFW_KEY_KP_8, ///< The numpad 8 key
GLFW_KEY_KP_9, ///< The numpad 9 key
GLFW_KEY_F1, ///< The F1 key
GLFW_KEY_F2, ///< The F2 key
GLFW_KEY_F3, ///< The F3 key
GLFW_KEY_F4, ///< The F4 key
GLFW_KEY_F5, ///< The F5 key
GLFW_KEY_F6, ///< The F6 key
GLFW_KEY_F7, ///< The F7 key
GLFW_KEY_F8, ///< The F8 key
GLFW_KEY_F9, ///< The F9 key
GLFW_KEY_F10, ///< The F10 key
GLFW_KEY_F11, ///< The F11 key
GLFW_KEY_F12, ///< The F12 key
GLFW_KEY_F13, ///< The F13 key
GLFW_KEY_F14, ///< The F14 key
GLFW_KEY_F15, ///< The F15 key
GLFW_KEY_PAUSE, ///< The Pause key
}
{
m_ClearColor.setValues(0, 0, 0, 255);
m_szWindowTitle = "Application OpenGL3";
m_iMousePosX = -1;
m_iMousePosY = -1;
m_bMouseLeftButtonDown = false;
m_bMouseRightButtonDown = false;
m_bDepthTest = false;
}
GL3Facade::~GL3Facade()
{
}
void GL3Facade::setWindowSize(int _width, int _height)
{
m_rWindowRect.m_iW = _width;
m_rWindowRect.m_iH = _height;
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, m_rWindowRect.m_iW, m_rWindowRect.m_iH);
}
// Renvoie l'instance du renderer
GL3Facade& GL3Facade::Instance()
{
static GL3Facade s_Instance;
return s_Instance;
}
bool GL3Facade::setCursor(bool _bVisible)
{
if (_bVisible)
{
// Turn off window cursor
SetCursor(NULL);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
return true; // prevent Windows from setting cursor to window class cursor
}
else
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
return false;
}
void GL3Facade::setDepthTest(bool _bDepthTest)
{
m_bDepthTest = _bDepthTest;
if (m_bDepthTest)
{
glEnable(GL_DEPTH_TEST);
}
else
{
glDisable(GL_DEPTH_TEST);
}
}
void GL3Facade::initialize()
{
// Initialise GLFW
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
return;
}
glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We don't want the old OpenGL
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
// Open a window and create its OpenGL context
window = glfwCreateWindow(m_rWindowRect.m_iW, m_rWindowRect.m_iH, m_szWindowTitle.c_str(), NULL, NULL);
if (window == NULL) {
cout << "Failed to create GLFW window" << endl;
glfwTerminate();
return;
}
glfwMakeContextCurrent(window); // Initialize GLEW
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
// tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return;
}
// configure global opengl state
// -----------------------------
//glEnable(GL_CULL_FACE);
//glCullFace(GL_BACK);
}
bool GL3Facade::update()
{
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
return true;
}
return false;
}
void GL3Facade::beginScene() const
{
glClearColor(m_ClearColor.getR(), m_ClearColor.getG(), m_ClearColor.getB(), m_ClearColor.getA());
if (m_bDepthTest)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
}
else
{
glClear(GL_COLOR_BUFFER_BIT);
}
}
// Rendu d'un objet
void GL3Facade::draw(IDrawable& _o) const
{
}
void GL3Facade::endScene() const
{
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
void GL3Facade::quit()
{
UnregisterClass("GL3Facade", GetModuleHandle(NULL)); // CB: to do, keep the instance to unregister it
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
}
Font* GL3Facade::createFont(Font* _pFrom)
{
return (_pFrom ? new GL3Font(*(GL3Font*)_pFrom) : new GL3Font);
}
void GL3Facade::destroyFont(Font* _pFont)
{
delete ((GL3Font*)_pFont);
}
Texture* GL3Facade::createTexture(Texture* _pFrom)
{
return (_pFrom ? new GL3Texture(*(GL3Texture*)_pFrom) : new GL3Texture);
}
void GL3Facade::destroyTexture(Texture* _pTexture)
{
delete ((GL3Texture*)_pTexture);
}
Color* GL3Facade::createColor(Color* _pFrom)
{
return (_pFrom ? new GL3Color(*(GL3Color*)_pFrom) : new GL3Color);
}
void GL3Facade::destroyColor(Color* _pColor)
{
delete ((GL3Color*)_pColor);
}
Text* GL3Facade::createText(Text* _pFrom)
{
return (_pFrom ? new GL3Text(*(GL3Text*)_pFrom) : new GL3Text);
}
void GL3Facade::destroyText(Text* _pText)
{
delete ((GL3Text*)_pText);
}
Sprite* GL3Facade::createSprite(Sprite* _pFrom)
{
return (_pFrom ? new GL3Sprite(*(GL3Sprite*)_pFrom) : new GL3Sprite);
}
void GL3Facade::destroySprite(Sprite* _pSprite)
{
delete ((GL3Sprite*)_pSprite);
}
Shape* GL3Facade::createShape(string _szType, Shape* _pFrom)
{
if (_szType == "Default")
{
return (_pFrom ? new GL3Shape(*(GL3Shape*)_pFrom) : new GL3Shape);
}
else if (_szType == "Rectangle")
{
return (_pFrom ? new GL3RectangleShape(*(GL3RectangleShape*)_pFrom) : new GL3RectangleShape);
}
else if (_szType == "Circle")
{
return (_pFrom ? new GL3CircleShape(*(GL3CircleShape*)_pFrom) : new GL3CircleShape);
}
else if (_szType == "Arrow")
{
return (_pFrom ? new GL3ArrowShape(*(GL3ArrowShape*)_pFrom) : new GL3ArrowShape);
}
else if (_szType == "Line")
{
return (_pFrom ? new GL3LineShape(*(GL3LineShape*)_pFrom) : new GL3LineShape);
}
return nullptr;
}
void GL3Facade::destroyShape(Shape* _pShape)
{
delete _pShape;
}
Shader* GL3Facade::createShader(Shader* _pFrom)
{
return (_pFrom ? new GL3Shader(*(GL3Shader*)_pFrom) : new GL3Shader);
}
void GL3Facade::destroyShader(Shader* _pShader)
{
delete _pShader;
}
Material* GL3Facade::createMaterial(Material* _pFrom)
{
return (_pFrom ? new GL3Material(*(GL3Material*)_pFrom) : new GL3Material);
}
void GL3Facade::destroyMaterial(Material* _pMaterial)
{
delete _pMaterial;
}
bool GL3Facade::isKeyPressed(Key _key)
{
return (glfwGetKey(window, keysMap[_key]) == GLFW_PRESS);
}
bool GL3Facade::isMouseButtonPressed(Button _button)
{
if (_button == MouseLeft)
{
return m_bMouseLeftButtonDown;
}
else if (_button == MouseRight)
{
return m_bMouseRightButtonDown;
}
else
{
cerr << "Mouse button not recognized: " << _button << endl;
}
return false;
}
Vector2f GL3Facade::getMousePosition()
{
return Vector2f((float)m_iMousePosX, (float)m_iMousePosY); // Get position relative to window
}
extern "C" __declspec(dllexport) GL3Facade* StartPlugin()
{
return &GL3Facade::Instance();
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int _width, int _height)
{
GL3Facade* pGL3Facade = (GL3Facade*) GameManager::getSingleton()->getRenderer();
pGL3Facade->setWindowSize(_width, _height);
}
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double _xPos, double _yPos)
{
// todo: handle mouse move
//InputManager::getSingleton()->setMousePosition(_xPos, _yPos);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double _xOffset, double _yOffset)
{
// todo: handle mouse scroll
//InputManager::getSingleton()->setMouseScroll(_xOffset, _yOffset);
}
} // namespace crea<file_sep>/***************************************************/
/* Nom: Actions.h
/* Description: Actions
/* Auteur: <NAME>
/***************************************************/
#ifndef __Actions_H_
#define __Actions_H_
#include "AI\BehaviorTree\Behavior.h"
#include "Scene\ScenePlanning.h"
class ActionSendMsg : public bt::Behavior
{
protected:
FSMPeonLive * m_pFSM;
int m_MSG_type;
public:
ActionSendMsg(FSMPeonLive* _pFSM, int _MSG_type)
: m_pFSM(_pFSM), m_MSG_type(_MSG_type)
{
}
virtual void onInitialize()
{
m_pFSM->SendDelayedMsgToMe(0.0f, m_MSG_type);
}
virtual bt::Status update()
{
return bt::BH_SUCCESS;
}
virtual Behavior* clone()
{
return new ActionSendMsg(*this);
}
};
class ActionGoTo : public bt::Behavior
{
protected:
FSMPeonLive* m_pFSM;
int m_MSG_Goto_type;
public:
ActionGoTo(FSMPeonLive* _pFSM, int _MSG_Goto_type)
: m_pFSM(_pFSM), m_MSG_Goto_type(_MSG_Goto_type)
{
}
virtual void onInitialize()
{
m_pFSM->SendDelayedMsgToMe(0.0f, m_MSG_Goto_type);
}
virtual bt::Status update()
{
if (m_pFSM->GetState() == STATE_GoTo)
{
// tester arrivée
if (m_pFSM->getFSMPeonGoTo()->GetState() == FSMPeonGoTo::STATE_CompletedPath)
{
return bt::BH_SUCCESS;
}
else if(m_pFSM->getFSMPeonGoTo()->GetState() == FSMPeonGoTo::STATE_SearchFailed)
{
return bt::BH_FAILURE;
}
return bt::BH_RUNNING;
}
return bt::BH_FAILURE;
}
virtual Behavior* clone()
{
return new ActionGoTo(*this);
}
};
class ActionSetCondition : public bt::Behavior
{
protected:
CharacterController* m_pCC;
EnumAnimCondition m_eCondition;
public:
ActionSetCondition(CharacterController* _pCC, EnumAnimCondition _eCondition)
: m_pCC(_pCC), m_eCondition(_eCondition)
{ }
virtual void onInitialize()
{
m_pCC->setCondition(m_eCondition);
}
virtual bt::Status update()
{
return bt::BH_SUCCESS;
}
virtual Behavior* clone()
{
return new ActionSetCondition(*this);
}
};
class ActionSetAction : public bt::Behavior
{
protected:
CharacterController * m_pCC;
EnumAction m_eAction;
public:
ActionSetAction(CharacterController* _pCC, EnumAction _eAction)
: m_pCC(_pCC), m_eAction(_eAction)
{ }
virtual void onInitialize()
{
m_pCC->setAction(m_eAction);
}
virtual bt::Status update()
{
return bt::BH_RUNNING;
}
virtual Behavior* clone()
{
return new ActionSetAction(*this);
}
};
class PreCondition : public bt::Behavior
{
protected:
Blackboard * m_pBB;
string m_variable;
string m_value;
public:
PreCondition(Blackboard* _pBB, const string& _variable, const string& _value)
: m_pBB(_pBB), m_variable(_variable), m_value(_value)
{ }
virtual bt::Status update()
{
/*
if (m_variable == "HqHaveLogs")
{
cout << "Precond: " << m_variable << " " << m_value << endl;
}*/
if (m_pBB->getVariable(m_variable) == m_value)
{
return bt::BH_SUCCESS;
}
else
{
return bt::BH_FAILURE;
}
}
virtual Behavior* clone()
{
return new PreCondition(*this);
}
};
class Effect : public bt::Behavior
{
protected:
Blackboard * m_pBB;
string m_variable;
string m_value;
public:
Effect(Blackboard* _pBB, const string& _variable, const string& _value)
: m_pBB(_pBB), m_variable(_variable), m_value(_value)
{ }
virtual bt::Status update()
{
cout << "Effect: " << m_variable << " " << m_value << endl;
m_pBB->setVariable(m_variable, m_value);
return bt::BH_SUCCESS;
}
virtual Behavior* clone()
{
return new Effect(*this);
}
};
class FilterIsEntity : public bt::Decorator
{
FSMPeonLive * m_pFSM;
Entity* m_pEntity;
public:
FilterIsEntity(FSMPeonLive* _pFSM, Entity* _pEntity)
: m_pFSM(_pFSM), m_pEntity(_pEntity)
{}
virtual bt::Status update()
{
if (m_pFSM->getEntity() == m_pEntity)
{
return m_pChild->tick();
}
else
{
return bt::BH_FAILURE;
}
}
virtual Behavior* clone()
{
return new FilterIsEntity(*this);
}
};
class FilterTimer : public bt::Decorator
{
Time m_timeMax;
Clock m_timer;
public:
FilterTimer(Time _timeMax)
: m_timeMax(_timeMax)
{}
virtual void onInitialize()
{
m_timer.restart();
}
virtual bt::Status update()
{
if (m_timer.getElapsedTime().asSeconds() > m_timeMax.asSeconds())
{
m_pChild->abort();
return bt::BH_SUCCESS;
}
else
{
return m_pChild->tick();
}
}
virtual Behavior* clone()
{
return new FilterTimer(*this);
}
};
class ActionWait : public bt::Behavior
{
protected:
public:
ActionWait()
{ }
virtual bt::Status update()
{
return bt::BH_RUNNING;
}
virtual Behavior* clone()
{
return new ActionWait(*this);
}
};
class ActionActivateSpriteRenderer : public bt::Behavior
{
protected:
SpriteRenderer* m_pSpriteRenderer;
bool m_bActive;
public:
ActionActivateSpriteRenderer(SpriteRenderer* _pSpriteRenderer, bool _bActive)
: m_pSpriteRenderer(_pSpriteRenderer), m_bActive(_bActive)
{ }
virtual void onInitialize()
{
m_pSpriteRenderer->setActive(m_bActive);
}
virtual bt::Status update()
{
return bt::BH_SUCCESS;
}
virtual Behavior* clone()
{
return new ActionActivateSpriteRenderer(*this);
}
};
#endif
<file_sep>#include "stdafx.h"
#include "Scene\SceneGame.h"
#include "Scene\SceneMenu.h"
#include "Core\SceneManager.h"
SceneGame::SceneGame()
{
}
SceneGame::~SceneGame()
{
}
bool SceneGame::onInit()
{
m_pGM = GameManager::getSingleton();
// Set Script factory
m_pCellsScriptFactory = new CellsScriptFactory;
m_pGM->setScriptFactory(m_pCellsScriptFactory);
/*
// Sprite
m_pSprite1 = m_pGM->getSprite("loco");
m_pSprite1->setTexture(m_pGM->getTexture("image.png"));
m_pSprite1->setPosition(300, 150);
// SpriteRenderer
m_pSpriteRenderer = m_pGM->getSpriteRenderer("locoSpriteRenderer");
m_pSpriteRenderer->setSprite(m_pSprite1);
// Entity
m_pEntity1 = m_pGM->getEntity("locoEntity");
m_pEntity1->setName(string("sprite 1"));
m_pEntity1->addComponent(m_pSpriteRenderer);
m_pGM->addEntity(m_pEntity1);
*/
Entity* pEntity = m_pGM->getEntity("test");
string n = "Peon/peon1.ent";
Entity* pModel = m_pGM->getEntityByModel(n);
if (pModel)
{
pEntity->cloneComponents(pModel);
}
else
{
pEntity->loadFromFileJSON(DATAAGENTPATH + n);
m_pGM->addEntityByModel(n, pEntity);
}
pEntity->setPosition(Vector2f((float)200, (float)200));
m_pGM->addEntity(pEntity);
pEntity->selectEntities(FloatRect(0, 0, 300, 300));
return true;
}
bool SceneGame::onUpdate()
{
// Get direction from keyboard
if (m_pGM->isKeyPressed(Key::Num1))
{
m_pGM->setScene(new SceneMenu());
return true;
}
return true;
}
bool SceneGame::onDraw()
{
return true;
}
bool SceneGame::onQuit()
{
m_pGM->clearAllEntities();
return true;
}
<file_sep>// Portions Copyright (C) <NAME>, 2001
#include "stdafx.h"
#include "AI\StateMachine.h"
namespace crea
{
StateMachine::StateMachine()
{
m_currentState = 0;
m_stateChange = false;
m_nextState = false;
m_timeOnEnter = 0.0f;
m_ccMessagesToAgent = 0;
m_stack.push_back(m_currentState);
}
StateMachine::~StateMachine()
{
}
void StateMachine::Initialize(Entity* _pOwner)
{
m_Owner = _pOwner;
Process(EVENT_Enter, 0);
}
void StateMachine::Update(void)
{
Process(EVENT_Update, 0);
}
void StateMachine::Process(StateMachineEvent event, Msg * msg)
{
if (event == EVENT_Message && msg && GetCCReceiver() > 0)
{ // CC this message
SendMsg(msg->GetMsgName(), GetCCReceiver());
}
if (States(event, msg, m_currentState) == false)
{ // Current state didn't handle msg, try Global state (-1)
States(event, msg, -1);
}
// Check for a state change
int safetyCount = 10;
while (m_stateChange && (--safetyCount >= 0))
{
assert(safetyCount > 0 && "StateMachine::Process - Scenes are flip-flopping in an infinite loop.");
m_stateChange = false;
// Let the last state clean-up
States(EVENT_Exit, 0, m_currentState);
// Set the new state
m_currentState = m_nextState;
// Add the state to the stack
m_stack.push_back(m_currentState);
if (m_stack.size() > MAX_STATES_IN_STACK)
{
m_stack.pop_front();
}
// Remember the time we entered this state
m_timeOnEnter = g_time->getGameTime().asSeconds();
// Let the new state initialize
States(EVENT_Enter, 0, m_currentState);
}
}
void StateMachine::SetState(unsigned int newState)
{
m_stateChange = true;
m_nextState = newState;
}
int StateMachine::SetStateInHistory()
{
// Can't set previous state if only 1 state in queue
if (m_stack.size() == 1)
return false;
m_stateChange = true;
m_stack.pop_back();
m_nextState = m_stack.back();
return m_nextState;
}
void StateMachine::SendMsg(int name, objectID receiver, void* data)
{
g_msgmanager->sendMsg(0, name, m_Owner->GetID(), receiver, -1, data);
}
void StateMachine::SendDelayedMsg(float delay, int name, objectID receiver, void* data)
{
g_msgmanager->sendMsg(delay, name, m_Owner->GetID(), receiver, -1, data);
}
void StateMachine::SendDelayedMsgToMe(float delay, int name, MSG_Scope scope)
{
if (scope == SCOPE_TO_THIS_STATE) {
g_msgmanager->sendMsg(delay, name, m_Owner->GetID(), m_Owner->GetID(), m_currentState);
}
else {
g_msgmanager->sendMsg(delay, name, m_Owner->GetID(), m_Owner->GetID(), -1);
}
}
}
<file_sep>/***************************************************/
/* Nom: SFMLGraphics.h
/* Description: SFMLGraphics
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLGraphics_H
#define _SFMLGraphics_H
#include "SFMLFacade.h"
#include "Graphics\IGraphics.h"
#include "Graphics\IFont.h"
#include "Graphics\Texture.h"
#include "Graphics\Text.h"
#include "Graphics\Sprite.h"
#include <SFML/Graphics.hpp>
namespace crea
{
} // namespace crea
#endif // _SFMLGraphics_H<file_sep>/***************************************************/
/* Nom: CreaEngine
/* Description: CreaEngine est un moteur développé à Creajeux
/* dans le cadre des cours "Engine" (C++, Graphique, Physique, IA)
/* Il est basé sur SFML mais en plugin de sorte de pouvoir
/* plus tard remplacer SFML par n'importe quel autre renderer
/* (DirectX9, Vulkan, etc.)
/*
/* Auteur: <NAME>
/***************************************************/
01/2016: Dévelopement du framework sur base SFML (TD Design Pattern, Visual Studio 2013).
09/2016: Portage sur Visual Studio 2015
Intégration des plugins CreaSFML et CreaDirectX
10/2016: Refactoring de l'architecture
Module Animation
Chargement map (JSON)
11/2017 Chargement des animations (Action Table)
Physics module (collision, friction)
Movement module (CharacterControl et User Control)
Agent module (Attributes)
12/2017 FSM
Msg
01/2017 Steering and swarming
02/2017 Formation
Sélection
03/2017 BehaviorTree
09/2017 VS2017
10/2017 OpenGL3
11/2017 Script integration (UserController and CharacterController as scripts)
04/2018 integration of modifications from 2017-2018 (Shape)
04/2019 integration of modifications from 2018-2019 (DXShape)
Doing:
- OpenGL3 integration (following https://learnopengl.com/)
*** 07/2020 Ajout de GL3Shader et GL3Material
mais il faut décommenter les fonctions dans Material::use qui nécessite une adaptation de Transform pour utiliser des Mat4 (LibMath?)
J'ai intégré LibMath mais ça oblige à l'intégrer dans chaque solution et vu que le moteur est 2D only pour le moment,
il vaut mieux simplement intégrer la position et l'orientation du transform dans un glm::mat4 sans passer par la LibMath
*** 11/2020
Ajout de la fonction clone pour héritage Material. Il faudrait faire hériter aussi les autres assets.
Le SpriteRenderer possède un Material non utilisé. Pourtant c'est lui qui devrait le posséder mais comme en SFML il n'y en a pas, impossible de le mettre dans SpriteRenderer.
To do:
- MEMORY MANAGER!!!
- regrouper les interfaces dans IGraphics.h et Math.h?
- système de prefab
- ajouter offset (ou hotspot) sur un objet
- dans le CharacterController, ajouter une réponse aux collisions autre que bloquer le perso
- bug: la souris ne retourne pas 1280*800 au coin en bas à droite
- Selection: pour le moment la sélection se fait sur tous les sprites dans SceneGame. Il faudrait faire un système générique de sélection (component?)
qui pourrait être configuré dans le Gamecode (ex: texture, entité sélectionnable).
- Steering: faire la classe Vehicle
- SelectEntities: should not be able to select root!
- .anm: change -W to Flip parameter
- table d'action: vérifier chargement de la table, bug si ordre des anims différent que ordre de l'EnumAction...
Removed:
- DataManager: regrouper les différentes map dans 1 map de maps? ex: au lieu de GetTexture() GetData("Texture", ...)
- EntityManager: comme pour DataManager...
Implique que tous les assets dérivent d'un même type (Asset?) or ce n'est pas le cas. (A REVERIFIER parceque ça fonctionne ds les TDs)<file_sep>/***************************************************/
/* Nom: DX9Renderer.h
/* Description: DX9Renderer
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Renderer_H
#define _DX9Renderer_H
#include "IFacade.h"
#include <d3d9.h>
#include <d3dx9.h>
namespace crea
{
class DX9Renderer
{
public:
~DX9Renderer();
// Renvoie l'instance du renderer
static DX9Renderer& Instance();
// Initialise le renderer
virtual void Initialize();
// Boucle de rendu
virtual bool Update();
// Démarre le rendu de la scène
virtual void BeginScene() const;
// Termine le rendu de la scène
virtual void EndScene() const;
// Quitte le renderer
virtual void Quit() const;
private:
// Données membres
DX9Renderer();
// Instance du renderer chargée
LPDIRECT3DDEVICE9 m_Device;
};
} // namespace crea
#endif // _DX9Renderer_H<file_sep>/***************************************************/
/* Nom: ActionTable.h
/* Description: ActionTable
/* Auteur: <NAME>
/***************************************************/
#ifndef __ActionTable_H_
#define __ActionTable_H_
#include "Core\Component.h"
namespace crea
{
#define MERGE2CONDITIONS(condition1, condition2) (condition1 << 8) | condition2 // A condition is given as 8 bits (char)
#define CREATE_KEY(condition, action) (condition << 16) | action // Then the condition and action (short) are combined
class CREAENGINE_API ActionAnimInfo
{
public:
string szAnimFileName;
string szActionDesc;
};
class CREAENGINE_API MapConditionAction : public std::multimap<long, ActionAnimInfo*> {};
class CREAENGINE_API ActionTable : public Component
{
crea::GameManager* m_pGM;
protected:
MapConditionAction m_condActionMap;
public:
ActionTable();
virtual ~ActionTable();
string* getAnimation(
unsigned char _ucAnimCond1,
unsigned char _ucAnimCond2,
unsigned short _unAction,
string* _pszActionDesc = nullptr);
string* getAnimation(
unsigned short _unAnimCond,
unsigned short _unAction,
string* _pszActionDesc = nullptr);
bool addAnimation(
unsigned short _unAnimCond,
unsigned short _unAction,
string* _pszAnimFileName,
string* _pszActionDesc = nullptr);
bool loadFromFileJSON(const string& _filename);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { return this; } // CB: no need to clone the ActionTable!
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "DX9Renderer.h"
namespace crea
{
DX9Renderer::DX9Renderer()
{
}
DX9Renderer::~DX9Renderer()
{
}
// Renvoie l'instance du renderer
DX9Renderer& DX9Renderer::Instance()
{
static DX9Renderer s_Instance;
return s_Instance;
}
void DX9Renderer::Initialize()
{
// a compléter
}
bool DX9Renderer::Update()
{
// a compléter
return true;
}
void DX9Renderer::BeginScene() const
{
m_Device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0x00008080, 1.0f, 0x00);
m_Device->BeginScene();
}
void DX9Renderer::EndScene() const
{
m_Device->EndScene();
m_Device->Present(NULL, NULL, NULL, NULL);
}
void DX9Renderer::Quit() const
{
}
extern "C" __declspec(dllexport) DX9Renderer* StartPlugin()
{
return &DX9Renderer::Instance();
}
} // namespace crea<file_sep>/***************************************************/
/* Nom: DX9Shape.h
/* Description: DX9Shape
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Shape_H
#define _DX9Shape_H
#include "Graphics\Shape.h"
namespace crea
{
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)
// A structure for our custom vertex type
struct CUSTOMVERTEX
{
FLOAT x, y, z, rhw; // The transformed position for the vertex
DWORD color; // The vertex color
};
#define D3DCOLOR_ISVISIBLE(color) ((color>>24)&0xff)
class DX9Shape : public Shape
{
protected:
D3DXVECTOR2 * m_pOrigin;
float m_fRotation;
D3DXVECTOR2 *m_pScale;
D3DXVECTOR2 m_position;
D3DCOLOR m_color;
D3DCOLOR m_outlineColor;
float m_outlinePixels;
LPDIRECT3DDEVICE9 m_pD3DDevice;
bool m_bUpdateVertices;
bool m_bUseColor;
bool m_bUseOutline;
public:
DX9Shape()
{
m_pOrigin = nullptr;
m_fRotation = 0.f;
m_pScale = nullptr;
m_position = D3DXVECTOR2(0.0f, 0.0f);
m_color = D3DCOLOR_XRGB(255, 255, 255);
m_outlineColor = D3DCOLOR_XRGB(255, 255, 255);
m_outlinePixels = 1;
m_pD3DDevice = nullptr;
m_pD3DDevice = DX9Facade::Instance().m_pDevice;
m_bUpdateVertices = true;
m_bUseColor = false;
m_bUseOutline = false;
}
virtual ~DX9Shape()
{
if (m_pOrigin)
delete m_pOrigin;
if (m_pScale)
delete m_pScale;
}
virtual void draw() { }
virtual void setColor(Color* _pColor)
{
DX9Color* pColor = (DX9Color*)_pColor;
m_color = pColor->getColor();
m_bUpdateVertices = true;
m_bUseColor = true;
}
virtual void setOutlineColor(Color* _pColor)
{
DX9Color* pColor = (DX9Color*)_pColor;
m_outlineColor = pColor->getColor();
m_bUpdateVertices = true;
m_bUseOutline = true;
}
virtual void setOutlineThickness(float _fPixels)
{
// todo: use m_outlinePixels
m_outlinePixels = _fPixels;
m_bUpdateVertices = true;
}
virtual void setPosition(float _x, float _y)
{
m_position = D3DXVECTOR2(_x, _y);
m_bUpdateVertices = true;
}
virtual void setRotation(float _angle)
{
m_fRotation = _angle;
}
virtual void setScale(float _x, float _y)
{
if (!m_pScale)
{
m_pScale = new D3DXVECTOR2;
}
*m_pScale = D3DXVECTOR2(_x, _y);
}
virtual void setOrigin(float _x, float _y)
{
if (!m_pOrigin)
{
m_pOrigin = new D3DXVECTOR2;
}
*m_pOrigin = D3DXVECTOR2(_x, _y);
}
};
class DX9RectangleShape : public DX9Shape
{
protected:
CUSTOMVERTEX m_vertices[9];// 4 + 5 to for linestrip to close the quad
D3DXVECTOR2 m_points[4];
LPDIRECT3DVERTEXBUFFER9 m_pVB; // Vertex buffer
public:
DX9RectangleShape()
{
m_pVB = nullptr;
if (FAILED(m_pD3DDevice->CreateVertexBuffer(9 * sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT, &m_pVB, NULL)))
{
return;
}
setSize(100.f, 100.f);
}
virtual ~DX9RectangleShape()
{
//release le vertex buffer
if (m_pVB)
m_pVB->Release();
}
virtual void draw()
{
if (m_bUpdateVertices)
{
m_bUpdateVertices = false;
// Build our matrix to rotate, scale and position our sprite
D3DXMATRIX mat;
// out, scaling centre, scaling rotation, scaling, rotation centre, rotation, translation
D3DXMatrixTransformation2D(&mat, m_pOrigin, 0.f, m_pScale, m_pOrigin, m_fRotation, &m_position);
// Fill vertex array with transformed points and color
D3DXVECTOR4 vout;
for (int i = 0; i < 4; i++)
{
D3DXVec2Transform(&vout, &m_points[i], &mat);
m_vertices[i].x = vout.x;
m_vertices[i].y = vout.y;
m_vertices[i].z = 0.0f;
m_vertices[i].rhw = 1.0f;
m_vertices[i].color = m_color;
}
if (D3DCOLOR_ISVISIBLE(m_outlineColor))
{
for (int i = 4; i < 9; i++)
{
m_vertices[i] = m_vertices[i - 4];
m_vertices[i].color = m_outlineColor;
}
}
// Copy vertex array to vertex buffer
VOID* pVertices;
if (FAILED(m_pVB->Lock(0, sizeof(m_vertices), (void**)&pVertices, 0)))
return;
memcpy(pVertices, m_vertices, sizeof(m_vertices));
m_pVB->Unlock();
}
// Alpha
// alpha * sourceColor + dest Color * (1-alpha)
m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
m_pD3DDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DRS_DESTBLENDALPHA);
// Draw
m_pD3DDevice->SetStreamSource(0, m_pVB, 0, sizeof(CUSTOMVERTEX));
m_pD3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
if (m_bUseColor)
{
m_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2);
}
// Outline
if (m_bUseOutline)
{
m_pD3DDevice->DrawPrimitive(D3DPT_LINESTRIP, 4, 4);
}
}
virtual void setSize(float _x, float _y)
{
m_points[0] = D3DXVECTOR2(0.0f, 0.0f);
m_points[1] = D3DXVECTOR2(_x, 0.0f);
m_points[2] = D3DXVECTOR2(_x, _y);
m_points[3] = D3DXVECTOR2(0.0f, _y);
m_bUpdateVertices = true;
}
};
class DX9CircleShape : public DX9Shape
{
CUSTOMVERTEX* m_vertices;
D3DXVECTOR2* m_points;
int m_iNbPoints;
int m_iNbTriangles;
LPDIRECT3DVERTEXBUFFER9 m_pVB; // Vertex buffer
public:
DX9CircleShape()
{
m_points = nullptr;
m_vertices = nullptr;
m_pVB = nullptr;
setSize(100.f);
}
~DX9CircleShape()
{
if (m_points)
delete[] m_points;
if (m_vertices)
delete[] m_vertices;
//release le vertex buffer
m_pVB->Release();
}
virtual void setRadius(float _r)
{
setSize(_r);
}
void setNbPoints(int _iNbPoints)
{
if (_iNbPoints == m_iNbPoints)
{
return;
}
if (m_points)
delete[] m_points;
if (m_vertices)
delete[] m_vertices;
//release le vertex buffer
if (m_pVB)
m_pVB->Release();
m_iNbPoints = _iNbPoints;
m_points = new D3DXVECTOR2[m_iNbPoints];
m_vertices = new CUSTOMVERTEX[2 * m_iNbPoints];
if (FAILED(m_pD3DDevice->CreateVertexBuffer(2 * m_iNbPoints * sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT, &m_pVB, NULL)))
{
m_iNbPoints = 0;
return;
}
}
void setSize(float _fSize, int _iNbSides = 20)
{
m_iNbTriangles = _iNbSides;
setNbPoints(_iNbSides + 2);
// Set vertices
// Origin +
// 5 6
//
// 4 0 1
//
// 3 2
float theta = 2 * 3.14f / m_iNbTriangles;
// First is center
m_points[0] = D3DXVECTOR2(_fSize, _fSize) + D3DXVECTOR2(0.f, 0.f);
// then around
D3DXVECTOR2 p;
for (int i = 0; i <= m_iNbTriangles; ++i)
{
m_points[i + 1] = D3DXVECTOR2(_fSize, _fSize) + D3DXVECTOR2(_fSize*cos(i*theta), _fSize*sin(i*theta));
}
m_bUpdateVertices = true;
}
void draw()
{
if (m_bUpdateVertices)
{
m_bUpdateVertices = false;
// Build our matrix to rotate, scale and position our sprite
D3DXMATRIX mat;
// out, scaling centre, scaling rotation, scaling, rotation centre, rotation, translation
D3DXMatrixTransformation2D(&mat, m_pOrigin, 0.f, m_pScale, m_pOrigin, m_fRotation, &m_position);
// Fill vertex array with transformed points and color
D3DXVECTOR4 vout;
for (int i = 0; i <= m_iNbPoints; i++)
{
D3DXVec2Transform(&vout, &m_points[i], &mat);
m_vertices[i].x = vout.x;
m_vertices[i].y = vout.y;
m_vertices[i].z = 0.0f;
m_vertices[i].rhw = 1.0f;
m_vertices[i].color = m_color;
}
if (D3DCOLOR_ISVISIBLE(m_outlineColor))
{
for (int i = m_iNbPoints + 1; i < 2 * m_iNbPoints; i++)
{
m_vertices[i] = m_vertices[i - m_iNbPoints];
m_vertices[i].color = m_outlineColor;
}
}
// Copy vertex array to vertex buffer
VOID* pVertices;
if (FAILED(m_pVB->Lock(0, 2 * m_iNbPoints * sizeof(CUSTOMVERTEX), (void**)&pVertices, 0)))
return;
memcpy(pVertices, m_vertices, 2 * m_iNbPoints * sizeof(CUSTOMVERTEX));
m_pVB->Unlock();
}
// Alpha
// alpha * sourceColor + dest Color * (1-alpha)
m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
m_pD3DDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DRS_DESTBLENDALPHA);
// Draw
m_pD3DDevice->SetStreamSource(0, m_pVB, 0, sizeof(CUSTOMVERTEX));
m_pD3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
if (m_bUseColor)
{
m_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, m_iNbTriangles);
}
// Outline
if (m_bUseOutline)
{
m_pD3DDevice->DrawPrimitive(D3DPT_LINESTRIP, m_iNbPoints+1, m_iNbPoints-2);
}
}
};
class DX9ArrowShape : public DX9Shape
{
CUSTOMVERTEX m_vertices[7];// 3 + 4 for linestrip to close the triangle
D3DXVECTOR2 m_points[3];
LPDIRECT3DVERTEXBUFFER9 m_pVB; // Vertex buffer public:
public:
DX9ArrowShape()
{
m_pVB = nullptr;
if (FAILED(m_pD3DDevice->CreateVertexBuffer(7 * sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT, &m_pVB, NULL)))
{
return;
}
m_points[0] = D3DXVECTOR2(0.0f, 0.5f);
m_points[1] = D3DXVECTOR2(0.0f, -0.5f);
m_points[2] = D3DXVECTOR2(1.0f, 0.0f);
}
~DX9ArrowShape()
{
//release le vertex buffer
if (m_pVB)
m_pVB->Release();
}
virtual void draw()
{
if (m_bUpdateVertices)
{
m_bUpdateVertices = false;
// Build our matrix to rotate, scale and position our sprite
D3DXMATRIX mat;
// out, scaling centre, scaling rotation, scaling, rotation centre, rotation, translation
D3DXMatrixTransformation2D(&mat, m_pOrigin, 0.f, m_pScale, m_pOrigin, m_fRotation, &m_position);
// Fill vertex array with transformed points and color
D3DXVECTOR4 vout;
for (int i = 0; i < 3; i++)
{
D3DXVec2Transform(&vout, &m_points[i], &mat);
m_vertices[i].x = vout.x;
m_vertices[i].y = vout.y;
m_vertices[i].z = 0.0f;
m_vertices[i].rhw = 1.0f;
m_vertices[i].color = m_color;
}
if (D3DCOLOR_ISVISIBLE(m_outlineColor))
{
for (int i = 3; i < 7; i++)
{
m_vertices[i] = m_vertices[i - 3];
m_vertices[i].color = m_outlineColor;
}
}
// Copy vertex array to vertex buffer
VOID* pVertices;
if (FAILED(m_pVB->Lock(0, sizeof(m_vertices), (void**)&pVertices, 0)))
return;
memcpy(pVertices, m_vertices, sizeof(m_vertices));
m_pVB->Unlock();
}
// Alpha
// alpha * sourceColor + dest Color * (1-alpha)
m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
m_pD3DDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DRS_DESTBLENDALPHA);
// Draw
m_pD3DDevice->SetStreamSource(0, m_pVB, 0, sizeof(CUSTOMVERTEX));
m_pD3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
if (m_bUseColor)
{
m_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 3);
}
// Outline
if (m_bUseOutline)
{
m_pD3DDevice->DrawPrimitive(D3DPT_LINESTRIP, 3, 3);
}
}
virtual void setSize(float _x, float _y)
{
setScale(_x, _y);
m_bUpdateVertices = true;
}
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd)
{
float dx = _xEnd - _xStart;
float dy = _yEnd - _yStart;
Vector2f v(dx, dy);
Vector2f right(1.0f, 0.f);
float fAngle = right.angle(v);
fAngle = dy > 0.f ? fAngle : -fAngle;
setPosition(_xStart, _yStart);
m_pScale->x = v.length();
setRotation(fAngle);
m_bUpdateVertices = true;
}
};
class DX9LineShape : public DX9Shape
{
CUSTOMVERTEX m_vertices[9];// 4 + 5 for linestrip to close the rectangle
D3DXVECTOR2 m_points[4];
LPDIRECT3DVERTEXBUFFER9 m_pVB; // Vertex buffer public:
public:
DX9LineShape()
{
m_pVB = nullptr;
if (FAILED(m_pD3DDevice->CreateVertexBuffer(9 * sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT, &m_pVB, NULL)))
{
return;
}
m_points[0] = D3DXVECTOR2(0.0f, 1.0f);
m_points[1] = D3DXVECTOR2(0.0f, 0.0f);
m_points[2] = D3DXVECTOR2(1.0f, 0.0f);
m_points[3] = D3DXVECTOR2(1.0f, 1.0f);
}
~DX9LineShape()
{
//release le vertex buffer
if (m_pVB)
m_pVB->Release();
}
virtual void draw()
{
if (m_bUpdateVertices)
{
m_bUpdateVertices = false;
// Build our matrix to rotate, scale and position our sprite
D3DXMATRIX mat;
// out, scaling centre, scaling rotation, scaling, rotation centre, rotation, translation
D3DXMatrixTransformation2D(&mat, m_pOrigin, 0.f, m_pScale, m_pOrigin, m_fRotation, &m_position);
// Fill vertex array with transformed points and color
D3DXVECTOR4 vout;
for (int i = 0; i < 4; i++)
{
D3DXVec2Transform(&vout, &m_points[i], &mat);
m_vertices[i].x = vout.x;
m_vertices[i].y = vout.y;
m_vertices[i].z = 0.0f;
m_vertices[i].rhw = 1.0f;
m_vertices[i].color = m_color;
}
if (D3DCOLOR_ISVISIBLE(m_outlineColor))
{
for (int i = 4; i < 9; i++)
{
m_vertices[i] = m_vertices[i - 4];
m_vertices[i].color = m_outlineColor;
}
}
// Copy vertex array to vertex buffer
VOID* pVertices;
if (FAILED(m_pVB->Lock(0, sizeof(m_vertices), (void**)&pVertices, 0)))
return;
memcpy(pVertices, m_vertices, sizeof(m_vertices));
m_pVB->Unlock();
}
// Alpha
// alpha * sourceColor + dest Color * (1-alpha)
m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
m_pD3DDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DRS_DESTBLENDALPHA);
// Draw
m_pD3DDevice->SetStreamSource(0, m_pVB, 0, sizeof(CUSTOMVERTEX));
m_pD3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
if (m_bUseColor)
{
m_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 4);
}
// Outline
if (m_bUseOutline)
{
m_pD3DDevice->DrawPrimitive(D3DPT_LINESTRIP, 4, 4);
}
}
virtual void setSize(float _x, float _y)
{
setScale(_x, _y);
m_bUpdateVertices = true;
}
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd)
{
float dx = _xEnd - _xStart;
float dy = _yEnd - _yStart;
Vector2f v(dx, dy);
Vector2f right(1.0f, 0.f);
float fAngle = right.angle(v);
fAngle = dy > 0.f ? fAngle : -fAngle;
setPosition(_xStart, _yStart);
m_pScale->x = v.length();
setRotation(fAngle);
m_bUpdateVertices = true;
}
};
} // namespace crea
#endif // _DX9Shape_H<file_sep>/***************************************************/
/* Nom: TextRenderer.h
/* Description: TextRenderer
/* Auteur: <NAME>
/***************************************************/
#ifndef __TextRenderer_H_
#define __TextRenderer_H_
#include "Core\Component.h"
namespace crea
{
class CREAENGINE_API TextRenderer : public Component
{
Text* m_pText;
public:
TextRenderer();
virtual ~TextRenderer();
inline void setText(Text* _pText) { m_pText = _pText; }
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { TextRenderer* p = new TextRenderer(*this); p->m_pText = IFacade::get().createText(m_pText); return p; }
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "AI\PathFinding\ClusterSearchNode.h"
#include "AI\PathFinding\ClusterSearchManager.h"
#include "Data\Map.h"
#include "Data\Node.h"
#include <math.h>
namespace crea
{
bool ClusterSearchNode::IsSameState(ClusterSearchNode &rhs)
{
// same state in a search is simply when (x,y) are the same
return ((x == rhs.x) && (y == rhs.y));
}
// Here's the heuristic function that estimates the distance from a Node to the Goal.
float ClusterSearchNode::GoalDistanceEstimate(ClusterSearchNode &nodeGoal)
{
float xd = float(((float)x - (float)nodeGoal.x));
float yd = float(((float)y - (float)nodeGoal.y));
//return sqrt((xd*xd) + (yd*yd)); // Pythagore
return ((xd*xd) + (yd*yd)); // Simple Pythagore
//return (abs(xd) + abs(yd)); // Manhattan
//return max(abs(xd), abs(yd)); // Diagonal
}
bool ClusterSearchNode::IsGoal(ClusterSearchNode &nodeGoal)
{
return ((x == nodeGoal.x) && (y == nodeGoal.y));
}
// This generates the successors to the given Node. It uses a helper function called
// AddSuccessor to give the successors to the AStar class. The A* specific initialisation
// is done for each node internally, so here you just set the state information that
// is specific to the application
bool ClusterSearchNode::GetSuccessors(AStarSearch<ClusterSearchNode> *astarsearch, ClusterSearchNode *parent_node)
{
int parent_x = -1;
int parent_y = -1;
if (parent_node)
{
parent_x = parent_node->x;
parent_y = parent_node->y;
}
ClusterSearchNode NewNode;
Map* pMap = ClusterSearchManager::getSingleton()->getCurrentMap();
Cluster* pCluster = ClusterSearchManager::getSingleton()->getCurrentCluster();
// push each possible move except allowing the search to go backwards
Node* pLeft = pCluster->isInCluster(x - 1, y) ? pMap->getNode(x - 1, y) : nullptr;
if (pLeft && (pLeft->getTileCollisionId() == 0)
&& !((parent_x == x - 1) && (parent_y == y))
)
{
NewNode = ClusterSearchNode(x - 1, y);
astarsearch->AddSuccessor(NewNode);
}
Node* pUp = pCluster->isInCluster(x, y - 1) ? pMap->getNode(x, y - 1) : nullptr;
if (pUp && (pUp->getTileCollisionId() == 0)
&& !((parent_x == x) && (parent_y == y - 1))
)
{
NewNode = ClusterSearchNode(x, y - 1);
astarsearch->AddSuccessor(NewNode);
}
Node* pRight = pCluster->isInCluster(x + 1, y) ? pMap->getNode(x + 1, y) : nullptr;
if (pRight && (pRight->getTileCollisionId() == 0)
&& !((parent_x == x + 1) && (parent_y == y))
)
{
NewNode = ClusterSearchNode(x + 1, y);
astarsearch->AddSuccessor(NewNode);
}
Node* pDown = pCluster->isInCluster(x, y + 1) ? pMap->getNode(x, y + 1) : nullptr;
if (pDown && (pDown->getTileCollisionId() == 0)
&& !((parent_x == x) && (parent_y == y + 1))
)
{
NewNode = ClusterSearchNode(x, y + 1);
astarsearch->AddSuccessor(NewNode);
}
// Diagonals
Node* pUpLeft = pCluster->isInCluster(x - 1, y - 1) ? pMap->getNode(x - 1, y - 1) : nullptr;
if (pUpLeft && (pUpLeft->getTileCollisionId() == 0)
&& !((parent_x == x - 1) && (parent_y == y - 1))
&& pUp && (pUp->getTileCollisionId() == 0)
&& pLeft && (pLeft->getTileCollisionId() == 0)
)
{
NewNode = ClusterSearchNode(x - 1, y - 1);
astarsearch->AddSuccessor(NewNode);
}
Node* pDownRight = pCluster->isInCluster(x + 1, y + 1) ? pMap->getNode(x + 1, y + 1) : nullptr;
if (pDownRight && (pDownRight->getTileCollisionId() == 0)
&& !((parent_x == x + 1) && (parent_y == y + 1))
&& pDown && (pDown->getTileCollisionId() == 0)
&& pRight && (pRight->getTileCollisionId() == 0)
)
{
NewNode = ClusterSearchNode(x + 1, y + 1);
astarsearch->AddSuccessor(NewNode);
}
Node* pDownLeft = pCluster->isInCluster(x - 1, y + 1) ? pMap->getNode(x - 1, y + 1) : nullptr;
if (pDownLeft && (pMap->getNode(x - 1, y + 1)->getTileCollisionId() == 0)
&& !((parent_x == x - 1) && (parent_y == y + 1))
&& pDown && (pDown->getTileCollisionId() == 0)
&& pLeft && (pLeft->getTileCollisionId() == 0)
)
{
NewNode = ClusterSearchNode(x - 1, y + 1);
astarsearch->AddSuccessor(NewNode);
}
Node* pUpRight = pCluster->isInCluster(x + 1, y - 1) ? pMap->getNode(x + 1, y - 1) : nullptr;
if (pUpRight && (pMap->getNode(x + 1, y - 1)->getTileCollisionId() == 0)
&& !((parent_x == x + 1) && (parent_y == y - 1))
&& pUp && (pUp->getTileCollisionId() == 0)
&& pRight && (pRight->getTileCollisionId() == 0)
)
{
NewNode = ClusterSearchNode(x + 1, y - 1);
astarsearch->AddSuccessor(NewNode);
}
return true;
}
// given this node, what does it cost to move to successor.
float ClusterSearchNode::GetCost(ClusterSearchNode &successor)
{
float fDistance = 1.0f;
// The G cost is 1.4 for diagonal move and 1.0 for horizontal or vertical move
int dx = successor.x - x;
int dy = successor.y - y;
if ((dx != 0) && (dy != 0))
{
fDistance = 1.4f;
}
return fDistance * 100.f;
}
}<file_sep>#include "stdafx.h"
#include "Graphics\MapRenderer.h"
#include "Core\GameManager.h"
#include "Data\Map.h"
namespace crea
{
MapRenderer::MapRenderer()
{
m_pMap = nullptr;
}
MapRenderer::~MapRenderer()
{
}
bool MapRenderer::init()
{
return true;
}
bool MapRenderer::update()
{
return true;
}
bool MapRenderer::draw()
{
if (m_pMap)
{
m_pMap->draw();
}
return true;
}
bool MapRenderer::quit()
{
return true;
}
} // namespace crea
<file_sep>// Portions Copyright (C) <NAME>, 2001
#ifndef __DEBUGLOG_H__
#define __DEBUGLOG_H__
#include "Core\Singleton.h"
#include <list>
namespace crea
{
class Msg;
class LogEntry
{
public:
LogEntry();
~LogEntry() {}
objectID m_owner;
bool m_handled;
double m_timestamp;
char m_statename[64];
char m_eventmsgname[64];
//msg only info
objectID m_receiver;
objectID m_sender;
};
class CREAENGINE_API DebugLog : public Singleton <DebugLog>
{
public:
DebugLog(void);
~DebugLog(void);
void LogStateMachineEvent(objectID id, Msg* _msg, char* statename, char* eventmsgname, bool handled);
private:
std::list<LogEntry*> m_log;
};
}
#endif // __DEBUGLOG_H__<file_sep>/***************************************************/
/* Nom: Vehicle.h
/* Description: Vehicle
/* Auteur: <NAME>
/***************************************************/
#ifndef __Vehicle_H_
#define __Vehicle_H_
#include "Core\Component.h"
#include "Core\Math.h"
namespace crea
{
// Predefinitions
class Steering;
class CREAENGINE_API Vehicle : public Component
{
protected:
Steering * m_pSteering;
// Locomotion
float m_mass;
float m_maxForce;
float m_maxSpeed;
Vector2f m_vVelocity;
//last force to render
Vector2f m_lastForce;
Vector2f m_lastR;
bool m_bUpdatePosition;
public:
Vehicle();
virtual ~Vehicle();
bool loadFromFileJSON(const string& _filename);
float getMass() { return m_mass; }
Vector2f getVelocity() { return m_vVelocity; }
float getMaxForce() { return m_maxForce; }
float getMaxSpeed() { return m_maxSpeed; }
Vector2f getLastForce() { return m_lastForce; }
Vector2f getLastR() { return m_lastR; }
void setMass(float _mass) { m_mass = _mass; }
void setVelocity(Vector2f _velocity) { m_vVelocity = _velocity; }
void setMaxForce(float _maxForce) { m_maxForce = _maxForce; }
void setMaxSpeed(float _maxSpeed) { m_maxSpeed = _maxSpeed; }
void setLastR(Vector2f _lastR) { m_lastR = _lastR; }
void setUpdatePosition(bool _bUpdatePosition) { m_bUpdatePosition = _bUpdatePosition; }
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { Vehicle* p = new Vehicle(*this); m_pSteering = nullptr; return p; }
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Scripts\FSMBalista.h"
#include "Scripts\Messages.h"
#include <string.h>
//Add new states here
enum States {
STATE_Spawn,
STATE_Live,
STATE_Die,
};
FSMBalista::FSMBalista()
{
}
FSMBalista::~FSMBalista()
{
}
bool FSMBalista::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
OnMsg(MSG_Reset)
SetState(STATE_Spawn);
OnMsg(MSG_Die)
SetState(STATE_Die);
OnMsg(MSG_Hit)
m_iLife -= 20;
if (m_iLife <= 0)
{
SetState(STATE_Die);
}
if (m_pFSMBalistaLive)
{
m_pFSMBalistaLive->States(_event, _msg, _state); // CB: propagate msg to sub-state
}
OnMsg(MSG_Boost)
m_pAgent->setDexterity(m_pAgent->getDexterity()+1);
OnOtherMsg()
if (m_pFSMBalistaLive)
{
m_pFSMBalistaLive->States(_event, _msg, _state); // CB: propagate msg to sub-state
}
///////////////////////////////////////////////////////////////
State(STATE_Spawn)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
m_iLife = 100;
OnUpdate
SetState(STATE_Live);
///////////////////////////////////////////////////////////////
State(STATE_Live)
OnEnter
m_pFSMBalistaLive = new FSMBalistaLive();
m_pEntity->addComponent(m_pFSMBalistaLive);
m_pFSMBalistaLive->Initialize(getEntity());
OnUpdate
if (m_iLife <= 0)
{
SetState(STATE_Die);
}
OnExit
m_pEntity->removeComponent(m_pFSMBalistaLive);
delete m_pFSMBalistaLive;
m_pFSMBalistaLive = nullptr;
///////////////////////////////////////////////////////////////
State(STATE_Die)
OnUpdate
m_pCharacterController->setCondition(kACond_Default);
m_pCharacterController->setAction(kAct_Die);
EndStateMachine
}<file_sep>// Portions Copyright (C) <NAME>, 2001
#include "stdafx.h"
#include "Core\DebugLog.h"
#include "Core\TimeManager.h"
#define MAX_DEBUG_LOG_SIZE 100
namespace crea
{
LogEntry::LogEntry()
{
m_owner = INVALID_OBJECT_ID;
m_handled = false;
m_timestamp = -1.0;
strcpy_s(m_statename, "");
strcpy_s(m_eventmsgname, "");
m_receiver = INVALID_OBJECT_ID;
m_sender = INVALID_OBJECT_ID;
}
DebugLog::DebugLog()
{
}
DebugLog::~DebugLog()
{
}
void DebugLog::LogStateMachineEvent(objectID id, Msg* _msg, char* statename, char* eventmsgname, bool handled)
{
LogEntry * entry = new LogEntry();
entry->m_owner = id;
entry->m_handled = handled;
entry->m_timestamp = g_time->getGameTime().asSeconds();
strcpy_s(entry->m_statename, statename);
strcpy_s(entry->m_eventmsgname, eventmsgname);
if (_msg) {
entry->m_receiver = _msg->GetReceiver();
entry->m_sender = _msg->GetSender();
}
m_log.push_back(entry);
if (m_log.size() > MAX_DEBUG_LOG_SIZE) {
delete(m_log.front());
m_log.erase(m_log.begin());
}
}
}<file_sep>/***************************************************/
/* Nom: GL3Texture.h
/* Description: GL3Texture
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Texture_H
#define _GL3Texture_H
#include "Graphics\Texture.h"
namespace crea
{
class GL3Texture : public Texture
{
protected:
string m_name;
unsigned int m_texture;
bool m_transparency;
unsigned char* m_data;
int m_width, m_height, m_nrChannels;
static bool m_flipVerticallyOnLoad;
void send();
public:
GL3Texture();
virtual ~GL3Texture();
inline void setID(unsigned int _id) { m_texture = _id; }
inline unsigned int getID() { return m_texture; }
inline void setTransparency(bool _transparency) { m_transparency = _transparency; send(); }
inline bool getTransparency() { return m_transparency; }
static void flipVerticallyOnLoad(bool _flipVerticallyOnLoad) { m_flipVerticallyOnLoad = _flipVerticallyOnLoad; }
inline int getWidth() { return m_width; }
inline int getHeight() { return m_height; }
inline int getChannels() { return m_nrChannels; }
virtual bool loadFromFile(const string& _name);
// use the texture
virtual void bind(unsigned int _channel);
virtual void unbind(unsigned int _channel);
};
} // namespace crea
#endif // _GL3Texture_H
<file_sep>#include "stdafx.h"
#include "Scripts\FSMSteeringPeonGoTo.h"
#include "Scripts\Messages.h"
#include <string.h>
#include "AI\Steering\Behavior.h"
FSMSteeringPeonGoTo::FSMSteeringPeonGoTo(Vector2f _vTarget) : m_vTarget(_vTarget)
{
}
FSMSteeringPeonGoTo::~FSMSteeringPeonGoTo()
{
for (short i = 0; i < (short)m_vPath.size(); i++)
{
delete m_vPath[i];
}
m_vPath.clear();
}
bool FSMSteeringPeonGoTo::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
//OnMsg(MSG_Teleport)
//SetState(STATE_CompletedPath);
/////////////////////////////////////////////////////////////////
State(STATE_Init)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// A*
m_pMapSearch = m_pGM->getMapSearch(m_pEntity->getName());
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
// Get Steering
m_pSteering = m_pEntity->getComponent<Steering>();
// Get Vehicle
m_pVehicle = m_pEntity->getComponent<Vehicle>();
OnUpdate
SetState(STATE_SearchPath);
/////////////////////////////////////////////////////////////////
State(STATE_SearchPath)
OnEnter
m_pMapSearch->setStartAndGoal(m_pEntity->getPosition(), m_vTarget);
m_pCharacterController->move(Vector2f(0.f, 0.f));
OnUpdate
MapSearch::SearchState s = m_pMapSearch->update();
if (s == MapSearch::SEARCH_STATE_SUCCEEDED)
{
SetState(STATE_FollowPath);
}
else if (s == MapSearch::SEARCH_STATE_FAILED)
{
SetState(STATE_SearchFailed);
}
OnExit
/////////////////////////////////////////////////////////////////
State(STATE_FollowPath)
OnEnter
m_pMapSearch->getSolution(m_vPath);
m_pPathTarget = m_vPath[m_vPath.size()-1];
m_pTarget = m_pGM->getEntity("target");
m_pTarget->setPosition(*m_vPath[0]);
m_pSteering->setTarget(m_pTarget);
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new PathFollowing(getEntity(), m_pTarget, 50.f, &m_vPath), 1.0f);
OnUpdate
if (GoTo(*m_pPathTarget))
{
SetState(STATE_CompletedPath);
}
OnExit
m_pSteering->clearBehaviors();
/////////////////////////////////////////////////////////////////
State(STATE_SearchFailed)
OnEnter
OnUpdate
OnExit
/////////////////////////////////////////////////////////////////
State(STATE_CompletedPath)
OnEnter
OnUpdate
OnExit
EndStateMachine
}
bool FSMSteeringPeonGoTo::GoTo(Vector2f& _vTargetPosition)
{
bool bArrived = false;
Vector2f vVelocity = m_pVehicle->getVelocity();
Vector2f vDistanceLeft = _vTargetPosition - m_pEntity->getPosition();
if (vDistanceLeft.length() > 10)
{
m_pCharacterController->setAction(kAct_Walk);
}
else
{
bArrived = true;
vVelocity = Vector2f(0.f, 0.0f);
}
// CB: adjust velocity with dexterity
int iDexterity = m_pAgent->getDexterity() / 10;
m_pCharacterController->move(vVelocity * (float)iDexterity);
return bArrived;
}<file_sep>#include "stdafx.h"
#include <algorithm>
#include "Core\Entity.h"
#include "Core\Component.h"
#include "AI\Agent.h"
namespace crea
{
Entity::Entity()
{
m_pParent = nullptr;
m_szName = "Entity";
m_ID = 0;
}
Entity::Entity(Entity& _entity)
{
m_pParent = nullptr;
m_szName = _entity.m_szName + " Instance";
m_ID = -1;
// Components
for (list<Component*>::iterator it = _entity.m_pComponents.begin(); it != _entity.m_pComponents.end(); ++it)
{
Component* p = (*it)->clone();
p->setEntity(this);
addComponent(p);
}
// Children
for (list<Entity*>::iterator it = _entity.m_pChildren.begin(); it != _entity.m_pChildren.end(); ++it)
{
addChild((*it)->clone());
}
}
Entity::~Entity()
{
clear();
}
void Entity::addChild(Entity* _pEntity)
{
m_pChildren.push_back(_pEntity);
_pEntity->setParent(this);
}
void Entity::removeChild(Entity* _pEntity)
{
_pEntity->setParent(nullptr);
m_pChildren.remove(_pEntity);
}
void Entity::addComponent(Component* _pComponent)
{
_pComponent->setEntity(this);
m_pComponents.push_back(_pComponent);
}
void Entity::removeComponent(Component* _pComponent)
{
_pComponent->setEntity(nullptr);
auto a = std::remove_if(m_pComponents.begin(), m_pComponents.end(),
[=](Component* p) { return p == _pComponent; });
m_pComponents.erase(a);
}
bool Entity::haveComponent(Component* _pComponent)
{
return (std::find(m_pComponents.begin(), m_pComponents.end(), _pComponent) != m_pComponents.end());
}
bool Entity::init()
{
// Components
for (list<Component*>::iterator it = m_pComponents.begin(); it != m_pComponents.end(); ++it)
{
(*it)->init();
}
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->init();
}
return true;
}
bool Entity::update()
{
// Components
for (list<Component*>::iterator it = m_pComponents.begin(); it != m_pComponents.end(); ++it)
{
(*it)->update();
}
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->update();
}
return true;
}
bool Entity::draw()
{
// Components
for (list<Component*>::iterator it = m_pComponents.begin(); it != m_pComponents.end(); ++it)
{
(*it)->draw();
}
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->draw();
}
return true;
}
void Entity::clear()
{
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
delete (*it);
}
m_pChildren.clear();
// Components
for (list<Component*>::iterator it = m_pComponents.begin(); it != m_pComponents.end(); ++it)
{
//delete (*it);// CB: the components are destroyed by managers...
}
m_pComponents.clear();
}
Entity* Entity::getEntity(const string& _szName)
{
if (hasName(_szName))
{
return this;
}
else
{
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
Entity* pEntity = (*it)->getEntity(_szName);
if (pEntity)
{
return pEntity;
}
}
}
return nullptr;
}
Entity* Entity::getEntity(Entity* _pEntity)
{
if (_pEntity == this)
{
return this;
}
else
{
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
Entity* pEntity = (*it)->getEntity(_pEntity);
if (pEntity)
{
return pEntity;
}
}
}
return nullptr;
}
bool Entity::removeEntity(Entity* _pEntity)
{
if (_pEntity->m_pParent != nullptr)
{
_pEntity->m_pParent->removeChild(_pEntity);
return true;
}
return false;
}
void Entity::selectEntities(FloatRect& _rect)
{
if (_rect.contains(getPosition()))
{
m_bSelected = true;
EntityManager::getSingleton()->addSelectedEntity(this);
}
else
{
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->selectEntities(_rect);
}
}
}
void Entity::unselectEntities()
{
m_bSelected = false;
// Children
for (list<Entity*>::iterator it = m_pChildren.begin(); it != m_pChildren.end(); ++it)
{
(*it)->unselectEntities();
}
}
bool Entity::loadFromFileJSON(const string& _filename)
{
Json::Value root;
std::ifstream entityStream(_filename, std::ifstream::binary);
if (entityStream.fail())
{
cerr << "Can't open Entity file: " << _filename << endl;
return false;
}
// Parse file
entityStream >> root;
crea::GameManager* pGM = crea::GameManager::getSingleton();
// Components
Json::Value components = root["components"];
for (unsigned int iComponent = 0; iComponent < components.size(); ++iComponent)
{
Json::Value component = components[iComponent];
string szType = component["type"].asString();
if (szType == "SpriteRenderer")
{
string szName = component["name"].asString();
SpriteRenderer* pSpriteRenderer = pGM->getSpriteRenderer(szName);
pSpriteRenderer->loadFromFileJSON(DATAAGENTPATH + szName);
addComponent(pSpriteRenderer);
}
else if (szType == "Agent")
{
string szName = component["name"].asString();
Agent* pAgent = pGM->getAgent(szName);
pAgent->loadFromFileJSON(DATAAGENTPATH + szName);
addComponent(pAgent);
}
else if (szType == "Animator")
{
string szName = component["name"].asString();
Animator* pAnimator = pGM->getAnimator(szName);
pAnimator->loadFromFileJSON(DATAAGENTPATH + szName);
addComponent(pAnimator);
}
else if (szType == "ActionTable")
{
string szName = component["name"].asString();
ActionTable* pActionTable = pGM->getActionTable(szName);
addComponent(pActionTable);
}
else if (szType == "Script")
{
string szName = component["name"].asString();
Script* pScript = pGM->getScript(szName);
addComponent(pScript);
}
else if (szType == "Collider")
{
string szName = component["name"].asString();
Collider* pCollider = pGM->getDynamicCollider(szName);
addComponent(pCollider);
}
else if (szType == "Steering")
{
string szName = component["name"].asString();
Steering* pSteering = pGM->getSteering(szName);
addComponent(pSteering);
}
else if (szType == "Vehicle")
{
string szName = component["name"].asString();
Vehicle* pVehicle = pGM->getVehicle(szName);
addComponent(pVehicle);
}
}
return true;
}
} // namespace crea
<file_sep>// stdafx.h : fichier Include pour les fichiers Include système standard,
// ou les fichiers Include spécifiques aux projets qui sont utilisés fréquemment,
// et sont rarement modifiés
//
#pragma once
#include <stdio.h>
#include <tchar.h>
#include <cassert>
#include <iostream>
using namespace std;
#pragma warning( disable: 4251 )
// Windows
#include <Windows.h>
#include <Windowsx.h>
#include "CreaImport.h"
// TODO: faites référence ici aux en-têtes supplémentaires nécessaires au programme
#include <d3d9.h>
#include <d3dx9.h>
#define SafeRelease(pInterface) if(pInterface != NULL) {pInterface->Release(); pInterface=NULL;}
#define SafeDelete(pObject) if(pObject != NULL) {delete pObject; pObject=NULL;}
#include "Graphics\DX9Facade.h"
#include "Graphics\DX9Font.h"
#include "Graphics\DX9Texture.h"
#include "Graphics\DX9Color.h"
#include "Graphics\DX9Text.h"
#include "Graphics\DX9Sprite.h"
#include "Graphics\DX9Shape.h"<file_sep>/***************************************************/
/* Nom: CellsScriptFactory.h
/* Description: CellsScriptFactory
/* Auteur: <NAME>
/***************************************************/
#ifndef __CellsScriptFactory_H_
#define __CellsScriptFactory_H_
#include "Core\Script.h"
#include "CharacterController.h"
#include "UserController.h"
#include "FSMPeon.h"
#include "Scripts\FSMSteeringPeon.h"
#include "FSMBalista.h"
#include "Scripts\FSMHQ.h"
class CellsScriptFactory : public ScriptFactory
{
virtual Script* create(const string& _szName)
{
if (_szName == "CharacterController")
{
return new CharacterController;
}
else if (_szName == "CharacterControllerBalista")
{
return new CharacterController;
}
else if (_szName == "CharacterControllerSteeringPeon")
{
return new CharacterController;
}
else if (_szName == "UserController")
{
return new UserController;
}
else if (_szName == "FSMPeon")
{
return new FSMPeon;
}
else if (_szName == "FSMBalista")
{
return new FSMBalista;
}
else if (_szName == "FSMSteeringPeon")
{
return new FSMSteeringPeon;
}
else if (_szName == "FSMHQ")
{
return new FSMHQ;
}
return nullptr;
}
};
#endif
<file_sep>/***************************************************/
/* Nom: Transformable.h
/* Description: Transformable
/* Auteur: <NAME>
/***************************************************/
#ifndef _Transformable_H
#define _Transformable_H
#include "Core\Math.h"
#include "Core\TimeManager.h"
namespace crea
{
class FloatRect;
class Vector2f;
class CREAENGINE_API Transform
{
Vector2f m_vPosition;
Vector2f m_vOrientation;
public:
Transform()
{
}
~Transform()
{
}
void move(Vector2f& _v) { m_vPosition += _v; }
void setPosition(Vector2f& _v) { m_vPosition = _v; }
Vector2f& getPosition() { return m_vPosition; }
void setOrientation(Vector2f& _v) { m_vOrientation = _v; }
Vector2f& getOrientation() { return m_vOrientation; }
virtual FloatRect transformRect(const FloatRect&) { return FloatRect(); };
};
class CREAENGINE_API Transformable
{
Transform m_Transform;
Vector2f m_vVelocity;
Vector2f m_vAngularVelocity;
public:
Transformable()
{
}
~Transformable()
{
}
Transform& getTransform() { return m_Transform; }
void move(Vector2f& _v)
{
float frameTime = (float)TimeManager::getSingleton()->getFrameTime().asSeconds();
if (frameTime)
{
m_vVelocity = _v;
m_vVelocity /= frameTime;
}
m_Transform.move(_v);
}
void setPosition(Vector2f& _v)
{
float frameTime = (float)TimeManager::getSingleton()->getFrameTime().asSeconds();
if (frameTime)
{
m_vVelocity = Vector2f(_v - getPosition());
m_vVelocity /= frameTime;
}
m_Transform.setPosition(_v);
}
Vector2f& getPosition() { return m_Transform.getPosition(); }
Vector2f& getVelocity() { return m_vVelocity; }
void setOrientation(Vector2f& _v)
{
float frameTime = (float)TimeManager::getSingleton()->getFrameTime().asSeconds();
if (frameTime)
{
m_vAngularVelocity = Vector2f(_v - getOrientation());
m_vAngularVelocity /= frameTime;
}
m_Transform.setOrientation(_v);
}
Vector2f& getOrientation() { return m_Transform.getOrientation(); }
Vector2f& getAngularVelocity() { return m_vAngularVelocity; }
Vector2f getFuturePosition(float _seconds) { return m_Transform.getPosition() + m_vVelocity * _seconds; }
};
} // namespace crea
#endif // _Transformable_H<file_sep>#include "stdafx.h"
#include "Data\TileSet.h"
#include <string>
namespace crea
{
TileSet::TileSet()
{
}
TileSet::~TileSet()
{
VectorTerrain::iterator it = m_Terrains.begin();
while (it != m_Terrains.end()) {
delete (*it);
it = m_Terrains.erase(it);
}
MapTileInfo::iterator itTile = m_TileInfos.begin();
while (itTile != m_TileInfos.end()) {
delete (*itTile).second;
itTile = m_TileInfos.erase(itTile);
}
}
float TileSet::getFriction(unsigned short _nTileId, unsigned short _nQuad)
{
TileInfo* pTileInfo = m_TileInfos[to_string(_nTileId)];
if (pTileInfo)
{
unsigned short nTerrain = pTileInfo->m_nTerrain[_nQuad];
return m_Terrains[nTerrain]->m_fFriction;
}
return 0.f; // Default to no friction
}
}<file_sep>/***************************************************/
/* Nom: AITools.h
/* Description: AITools
/* Auteur: <NAME>
/***************************************************/
#ifndef __AITools_H_
#define __AITools_H_
#include "Core\Scene.h"
#include "Scripts\CharacterController.h"
using namespace crea;
enum EnumCommandType
{
Command_Invalid = -1,
Command_Reset = 0,
Command_Kill,
Command_Stop,
Command_GoToHQ,
Command_GoTo,
Command_Build,
Command_Mine,
Command_Harvest,
Command_Die,
Command_Boost,
Command_GoToHQWithLumber
};
class AITools
{
GameManager* m_pGM;
// Selection
bool m_bSelection;
Vector2f m_vStartSelection;
Vector2f m_vEndSelection;
RectangleShape* m_pSelectionShape;
// Command
FloatRect m_rCommandWindow;
bool m_bCommand;
EnumCommandType m_eCommandType;
Sprite* m_pCommandsSprite;
// Diagnostic
Text* m_pTextFPS;
Text* m_pTextCommand;
Text* m_pTextDiagnostics;
Clock m_CommandDisplayClock;
float m_fCommandDisplayTime;
// Grid
Map* m_pMap;
short m_nWidth;
short m_nHeight;
short m_nTileWidth;
short m_nTileHeight;
RectangleShape* m_pNodeShape;
LineShape* m_pLineShape;
// Tile index limits
int m_iMin;
int m_iMax;
int m_jMin;
int m_jMax;
bool isButton(int _i, Vector2f& _vMousePosition);
// CharacterController
CharacterController* m_pCharacterController;
vector<Vector2f> m_pathToHQ;
vector<Vector2f> m_pathToMine;
// Collisions
RectangleShape* m_pBoxColliderShape;
CircleShape* m_pCircleColliderShape;
RectangleShape* m_pCollisionNodeShape;
void DisplayCollider(MapStringCollider* _pColliders);
// Cluster
RectangleShape* m_pClusterShape;
RectangleShape* m_pEntranceShape;
ArrowShape* m_pTransitionShape;
ArrowShape* m_pEdgeShape;
int m_iClusterMin;
int m_iClusterMax;
int m_jClusterMin;
int m_jClusterMax;
short m_nClusterWidth;
short m_nClusterHeight;
// Steering
LineShape* m_pTarget;
LineShape* m_pSteeringLine;
LineShape* m_pForceLine;
LineShape* m_pVelocityLine;
Steering* m_pSteering;
Vehicle* m_pVehicle;
public:
AITools();
virtual ~AITools();
virtual bool onInit();
virtual bool onUpdate();
virtual bool onDraw();
virtual bool onQuit();
};
#endif
<file_sep>#include "stdafx.h"
#include "Core\TimeManager.h"
namespace crea
{
Time::Time()
{
m_dTime = 0.0;
}
Time::Time(double _dTime)
{
m_dTime = _dTime;
}
Time::~Time()
{
}
Time& Time::operator=(double _dTime) { m_dTime = _dTime; return *this; }
Time& Time::operator+=(Time& _Time) { m_dTime += _Time.m_dTime; return *this; }
bool Time::operator>=(Time& _Time) { return m_dTime >= _Time.m_dTime; }
Time Time::operator*(float _f) { return Time(m_dTime*_f); }
int Time::asMicroseconds() { return (int)(m_dTime * 1E6); }
int Time::asMilliseconds() { return (int)(m_dTime * 1E3); }
double Time::asSeconds() { return (double)m_dTime; }
void Time::setAsMicroSeconds(int _iTime) { m_dTime = _iTime * 1E-6; }
void Time::setAsMilliSeconds(int _iTime) { m_dTime = _iTime * 1E-3; }
void Time::setAsSeconds(double _dTime) { m_dTime = _dTime; }
Clock::Clock()
{
m_t1 = high_resolution_clock::now();
}
Clock::~Clock()
{
}
Time Clock::getElapsedTime()
{
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - m_t1);
return time_span.count();
}
Time Clock::restart()
{
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - m_t1);
m_t1 = t2;
return time_span.count();
}
TimeManager::TimeManager()
{
}
TimeManager::~TimeManager()
{
}
TimeManager* TimeManager::getSingleton()
{
static TimeManager instanceUnique;
return
&instanceUnique;
}
Time TimeManager::getFrameTime()
{
return m_FrameTime;
}
Time TimeManager::getGameTime()
{
return m_GameClock.getElapsedTime();
}
void TimeManager::init()
{
m_FrameClock.restart();
m_GameClock.restart();
}
void TimeManager::update()
{
m_FrameTime = m_FrameClock.restart();
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Data\DataManager.h"
#include "Graphics\Color.h"
namespace crea
{
DataManager::DataManager()
{
m_bIsCleared = false;
}
DataManager::~DataManager()
{
clear();
}
DataManager* DataManager::getSingleton()
{
static DataManager instanceUnique;
return
&instanceUnique;
}
Font* DataManager::getFont(const string& _szName, bool _bCloned)
{
MapStringFont::iterator it = m_pFonts.find(_szName);
if (it == m_pFonts.end())
{
Font* pFont = IFacade::get().createFont();
if (!pFont->loadFromFile(DATAFONTPATH + _szName))
{
delete pFont;
cerr << "Unable to open font" << endl;
return nullptr;
}
m_pFonts[_szName] = pFont;
return pFont;
}
else
{
if (_bCloned)
{
return IFacade::get().createFont(it->second);
}
else
{
return it->second;
}
}
}
Texture* DataManager::getTexture(const string& _szName, bool _bCloned)
{
MapStringTexture::iterator it = m_pTextures.find(_szName);
if (it == m_pTextures.end())
{
Texture* pTexture = IFacade::get().createTexture();
if (!pTexture->loadFromFile(DATATEXTUREPATH + _szName))
{
delete pTexture;
cerr << "Unable to open Texture" << endl;
return nullptr;
}
m_pTextures[_szName] = pTexture;
return pTexture;
}
else
{
if (_bCloned)
{
return IFacade::get().createTexture(it->second);
}
else
{
return it->second;
}
}
}
Color* DataManager::getColor(const string& _szName, bool _bCloned)
{
MapStringColor::iterator it = m_pColors.find(_szName);
if (it == m_pColors.end())
{
Color* pColor = IFacade::get().createColor(); // Create a default Color if none exist
m_pColors[_szName] = pColor;
return pColor;
}
else
{
if (_bCloned)
{
return IFacade::get().createColor(it->second);
}
else
{
return it->second;
}
}
return nullptr;
}
Text* DataManager::getText(const string& _szName, bool _bCloned)
{
MapStringText::iterator it = m_pTexts.find(_szName);
if (it == m_pTexts.end())
{
Text* pText = IFacade::get().createText(); // Create a default Text if none exist
m_pTexts[_szName] = pText;
return pText;
}
else
{
if (_bCloned)
{
return IFacade::get().createText(it->second);
}
else
{
return it->second;
}
}
return nullptr;
}
Sprite* DataManager::getSprite(const string& _szName, bool _bCloned)
{
MapStringSprite::iterator it = m_pSprites.find(_szName);
if (it == m_pSprites.end())
{
Sprite* pSprite = IFacade::get().createSprite(); // Create a default Sprite if none exist
m_pSprites[_szName] = pSprite;
return pSprite;
}
else
{
if (_bCloned)
{
return IFacade::get().createSprite(it->second);
}
else
{
return it->second;
}
}
return nullptr;
}
Shape* DataManager::getShape(const string& _szType, const string& _szName, bool _bCloned)
{
MapStringShape::iterator it = m_pShapes.find(_szName);
if (it == m_pShapes.end())
{
Shape* pShape = IFacade::get().createShape(_szType); // Create a default Shape if none exist
m_pShapes[_szName] = pShape;
return pShape;
}
else
{
if (_bCloned)
{
return IFacade::get().createShape(_szType, it->second);
}
else
{
return it->second;
}
}
return nullptr;
}
Map* DataManager::getMap(const string& _szName, bool _bCloned)
{
MapStringMap::iterator it = m_pMaps.find(_szName);
if (it == m_pMaps.end())
{
Map* pMap = new Map();
m_pMaps[_szName] = pMap;
return pMap;
}
else
{
if (_bCloned)
{
return new Map(*it->second);
}
else
{
return it->second;
}
}
}
Agent* DataManager::getAgent(const string& _szName, bool _bCloned)
{
MapStringAgent::iterator it = m_pAgents.find(_szName);
if (it == m_pAgents.end())
{
Agent* pAgent = new Agent();
m_pAgents[_szName] = pAgent;
return pAgent;
}
else
{
if (_bCloned)
{
return new Agent(*it->second);
}
else
{
return it->second;
}
}
}
Animation* DataManager::getAnimation(const string& _szName, bool _bCloned)
{
MapStringAnimation::iterator it = m_pAnimations.find(_szName);
if (it == m_pAnimations.end())
{
Animation* pAnimation = new Animation();
if (!pAnimation->loadFromFileJSON(DATAANIMATIONPATH + _szName))
{
delete pAnimation;
cerr << "Unable to open Animation" << endl;
return nullptr;
}
m_pAnimations[_szName] = pAnimation;
return pAnimation;
}
else
{
if (_bCloned)
{
return new Animation(*it->second);
}
else
{
return it->second;
}
}
}
ActionTable* DataManager::getActionTable(const string& _szName, bool _bCloned)
{
MapStringActionTable::iterator it = m_pActionTables.find(_szName);
if (it == m_pActionTables.end())
{
ActionTable* pActionTable = new ActionTable(); // Create a default ActionTable if none exist
if (!pActionTable->loadFromFileJSON(DATAANIMATIONPATH + _szName))
{
delete pActionTable;
cerr << "Unable to open ActionTable" << endl;
return nullptr;
}
m_pActionTables[_szName] = pActionTable;
return pActionTable;
}
else
{
if (_bCloned)
{
//return new ActionTable(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
Vehicle* DataManager::getVehicle(const string& _szName, bool _bCloned)
{
MapStringVehicle::iterator it = m_pVehicles.find(_szName);
if (it == m_pVehicles.end())
{
Vehicle* pVehicle = new Vehicle(); // Create a default Vehicle if none exist
if (!pVehicle->loadFromFileJSON(DATAAGENTPATH + _szName))
{
delete pVehicle;
cerr << "Unable to open Vehicle" << endl;
return nullptr;
}
m_pVehicles[_szName] = pVehicle;
return pVehicle;
}
else
{
if (_bCloned)
{
//return new Vehicle(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
Material* DataManager::getMaterial(const string& _szName, bool _bCloned)
{
MapStringMaterial::iterator it = m_pMaterials.find(_szName);
if (it == m_pMaterials.end())
{
Material* pMaterial = IFacade::get().createMaterial(); // Create a default Material if none exist
if (!pMaterial->loadFromFile(DATAMATERIALPATH + _szName))
{
delete pMaterial;
cerr << "Unable to open Material" << endl;
return nullptr;
}
m_pMaterials[_szName] = pMaterial;
return pMaterial;
}
else
{
if (_bCloned)
{
Material* pMaterial = (Material*)it->second->clone();
m_pMaterials[_szName + to_string(++materialInstanceCount)] = pMaterial;
return pMaterial;
}
else
{
return it->second;
}
}
return nullptr;
}
Shader* DataManager::getShader(const string& _szName, bool _bCloned)
{
MapStringShader::iterator it = m_pShaders.find(_szName);
if (it == m_pShaders.end())
{
Shader* pShader = IFacade::get().createShader(); // Create a default Shader if none exist
if (!pShader->loadFromFile(DATASHADERPATH + _szName))
{
delete pShader;
cerr << "Unable to open Shader" << endl;
return nullptr;
}
m_pShaders[_szName] = pShader;
return pShader;
}
else
{
if (_bCloned)
{
//return new Shader(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
void DataManager::clear()
{
if (!m_bIsCleared)
{
m_bIsCleared = true;
}
else
{
return;
}
MapStringFont::iterator itFont = m_pFonts.begin();
while (itFont != m_pFonts.end()) {
delete (*itFont).second;
itFont = m_pFonts.erase(itFont);
}
// Clean Materials before textures
MapStringMaterial::iterator itMaterial = m_pMaterials.begin();
while (m_pMaterials.size()) {
delete (*itMaterial).second;
itMaterial = m_pMaterials.erase(itMaterial);
}
MapStringTexture::iterator itTexture = m_pTextures.begin();
while (itTexture != m_pTextures.end()) {
delete (*itTexture).second;
itTexture = m_pTextures.erase(itTexture);
}
MapStringColor::iterator itColor = m_pColors.begin();
while (itColor != m_pColors.end()) {
delete (*itColor).second;
itColor = m_pColors.erase(itColor);
}
MapStringText::iterator itText = m_pTexts.begin();
while (itText != m_pTexts.end()) {
delete (*itText).second;
itText = m_pTexts.erase(itText);
}
MapStringSprite::iterator itSprite = m_pSprites.begin();
while (itSprite != m_pSprites.end()) {
delete (*itSprite).second;
itSprite = m_pSprites.erase(itSprite);
}
MapStringShape::iterator itShape = m_pShapes.begin();
while (itShape != m_pShapes.end()) {
delete (*itShape).second;
itShape = m_pShapes.erase(itShape);
}
MapStringMap::iterator itMap = m_pMaps.begin();
while (itMap != m_pMaps.end()) {
delete (*itMap).second;
itMap = m_pMaps.erase(itMap);
}
MapStringAgent::iterator itAgent = m_pAgents.begin();
while (itAgent != m_pAgents.end()) {
delete (*itAgent).second;
itAgent = m_pAgents.erase(itAgent);
}
MapStringAnimation::iterator itAnimation = m_pAnimations.begin();
while (itAnimation != m_pAnimations.end()) {
delete (*itAnimation).second;
itAnimation = m_pAnimations.erase(itAnimation);
}
MapStringActionTable::iterator itActionTable = m_pActionTables.begin();
while (m_pActionTables.size()) {
delete (*itActionTable).second;
itActionTable = m_pActionTables.erase(itActionTable);
}
MapStringVehicle::iterator itVehicle = m_pVehicles.begin();
while (m_pVehicles.size()) {
delete (*itVehicle).second;
itVehicle = m_pVehicles.erase(itVehicle);
}
MapStringShader::iterator itShader = m_pShaders.begin();
while (m_pShaders.size()) {
delete (*itShader).second;
itShader = m_pShaders.erase(itShader);
}
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: FSMBalista.h
/* Description: FSMBalista
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMBalista_H_
#define __FSMBalista_H_
#include "AI\StateMachine.h"
#include "Scripts\CharacterController.h"
#include "Scripts\FSMBalistaLive.h"
using namespace crea;
class FSMBalista : public StateMachine
{
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
bool m_bPaused;
int m_iLife;
FSMBalistaLive* m_pFSMBalistaLive;
public:
FSMBalista();
virtual ~FSMBalista();
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone() { return new FSMBalista(*this); }
};
#endif
<file_sep>/***************************************************/
/* Nom: GL3Sprite.h
/* Description: GL3Sprite
/* Auteur: <NAME>
/***************************************************/
#ifndef _GL3Sprite_H
#define _GL3Sprite_H
#include "Graphics\Sprite.h"
#include "Graphics\GL3Shape.h"
#include "Graphics\GL3Material.h"
namespace crea
{
class GL3Sprite : public Sprite
{
GL3Material* m_pMaterial;
GL3RectangleShape m_quad;
IntRect m_textureRect;
bool m_bShaderApplied = false;
Texture* m_pTexture = nullptr;
public:
GL3Sprite::GL3Sprite()
{
// Clone the sprite material
m_pMaterial = (GL3Material*)GameManager::getSingleton()->getMaterial("sprite.mat", true);
m_textureRect.m_iW = 0;
m_textureRect.m_iH = 0;
}
virtual GL3Sprite::~GL3Sprite()
{
}
virtual void draw()
{
// Pre Draw
if (m_pMaterial != nullptr)
{
// Apply shader on shape
if (!m_bShaderApplied)
{
if (m_pMaterial)
m_pMaterial->setTexture(0, "texture1", m_pTexture);
m_pMaterial->applyShaderToShape(&m_quad);
m_bShaderApplied = true;
}
// Use our shader on Entity
m_pMaterial->use();
}
m_quad.draw();
// Post Draw
if (m_pMaterial != nullptr)
{
// Unset shader
m_pMaterial->unuse();
}
}
virtual void setTexture(Texture* _pTexture)
{
// update quad with new texture sizes and window sizes
if (m_pTexture != _pTexture)
{
m_pTexture = _pTexture;
GL3Texture* pTexture = (GL3Texture*)m_pTexture;
m_quad.setTextureSize(pTexture->getWidth(), pTexture->getHeight());
//When texture changes, adjust display size but also make sure to reset texture rect...
m_quad.setDisplaySize(pTexture->getWidth(), pTexture->getHeight());
m_textureRect = IntRect (0, 0, 1, 1);
GameManager* pGM = GameManager::getSingleton();
IntRect r = pGM->getWindowRect();
m_quad.setWindowSize(r.getWidth(), r.getHeight());
m_bShaderApplied = false; // to reapply texture
}
}
Texture* getTexture()
{
return m_pTexture;
}
virtual void setPosition(float _x, float _y)
{
// todo: sprite position (GL3)
//m_Position.x = _x;
//m_Position.y = _y;
m_quad.setPosition(_x, _y);
}
virtual void setTextureRect(int _x, int _y, int _w, int _h)
{
IntRect _rect(_x, _y, _w, _h);
if (m_textureRect != _rect)
{
m_textureRect = _rect;
float w = (float)m_textureRect.m_iW;
float h = (float)m_textureRect.m_iH;
//m_quad.setSize(w, h);
GL3Texture* pTexture = (GL3Texture*)m_pTexture;
if (pTexture)
{
w = (float)pTexture->getWidth();
h = (float)pTexture->getHeight();
}
FloatRect rectNormalised;
rectNormalised.m_fX = _rect.m_iX / w;
rectNormalised.m_fY = _rect.m_iY / h;
rectNormalised.m_fW = _rect.m_iW / w;
rectNormalised.m_fH = _rect.m_iH / h;
// UV
VertexUV uv[] = {
{ rectNormalised.m_fX , 1 - rectNormalised.m_fY - rectNormalised.m_fH},// bottom left
{ rectNormalised.m_fX, 1 - rectNormalised.m_fY},// top left
{ rectNormalised.m_fX + rectNormalised.m_fW, 1 - rectNormalised.m_fY - rectNormalised.m_fH },// bottom right
{ rectNormalised.m_fX + rectNormalised.m_fW, 1 - rectNormalised.m_fY }// top right
};
m_quad.setVerticesUV(uv, 4);
m_quad.setDisplaySize(_rect.m_iW, _rect.m_iH);
}
}
virtual void setScale(float _x, float _y)
{
// todo: sprite scale (GL3)
//m_pScale->x = _x;
//m_pScale->y = _y;
m_quad.setScale(_x, _y);
}
virtual void setOrigin(float _x, float _y)
{
// todo: sprite origin (GL3)
//m_pScaleCenter->x = _x;
//m_pScaleCenter->y = _y;
m_quad.setOrigin(_x, _y);
}
virtual GL3Sprite* clone()
{
GL3Sprite* pSprite = new GL3Sprite();
// Material is already a clone
pSprite->setTexture(this->m_pTexture);
//todo: ici il faudrait cloner le quad correctement!
pSprite->m_quad = this->m_quad;
return pSprite;
}
};
} // namespace crea
#endif // _GL3Sprite_H
<file_sep>-inclure glad.h
- ajouter glad.c au projet
- Appeller cette fonction dans l'init:
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGL())
{
std::cout << "Can't load OpenGL function pointers with GLAD" << endl;
return;
}
- mais les fonctions glBegin, etc. ne sont plus reconnues?<file_sep>/***************************************************/
/* Nom: ILogger.h
/* Description: ILogger
/* Auteur: <NAME>
/***************************************************/
#ifndef _ILogger_H
#define _ILogger_H
#include <fstream>
namespace crea
{
class CREAENGINE_API ILogger
{
public:
virtual ~ILogger();
static void SetLogger(ILogger* Logger);
static void Log(const char* Format, ...);
static ILogger& Log();
template <class T> ILogger& operator <<(const T& ToLog);
private:
virtual void Write(const std::string& Message) = 0;
static ILogger* s_Instance;
};
// Logger in console
class CREAENGINE_API LoggerDebug : public ILogger
{
virtual void Write(const std::string& Message)
{
OutputDebugString((Message + '\n').c_str());
}
};
// Logger in MsgBox
class CREAENGINE_API LoggerMsgBox : public ILogger
{
virtual void Write(const std::string& Message)
{
MessageBox(NULL, Message.c_str(), "CreaEngine", MB_OK);
}
};
// Logger in a file
class CREAENGINE_API LoggerFile : public ILogger
{
public:
LoggerFile(const std::string& Filename = "Output.log") : m_File(Filename)
{
if (m_File.fail())
{
cerr << "Can't open "<< Filename << endl;
}
}
virtual LoggerFile::~LoggerFile()
{
m_File.close();
}
private:
virtual void Write(const std::string& Message)
{
m_File << Message;
}
std::ofstream m_File;
};
} // namespace crea
#endif // _ILogger_H<file_sep>#include "stdafx.h"
#include "Core\PhysicsManager.h"
#include "Physics\Collider.h"
namespace crea
{
PhysicsManager::PhysicsManager()
{
m_pCurrentMap = nullptr;
}
PhysicsManager::~PhysicsManager()
{
clear();
}
PhysicsManager* PhysicsManager::getSingleton()
{
static PhysicsManager instanceUnique;
return
&instanceUnique;
}
void PhysicsManager::addStaticCollider(const string& _szName, Collider* _pCollider)
{
_pCollider->setName(_szName);
m_StaticColliders[_szName] = _pCollider;
}
void PhysicsManager::addDynamicCollider(string& _szName, Collider* _pCollider)
{
_pCollider->setName(_szName);
m_DynamicColliders[_szName] = _pCollider;
}
bool PhysicsManager::isColliding(Collider* _pCollider, bool _bWithStatic, bool _bWithDynamic, bool _bWithTrigger)
{
bool bIsColliding = false;
// With static collisions
if (_bWithStatic)
{
MapStringCollider::iterator it = m_StaticColliders.begin();
while (it != m_StaticColliders.end())
{
Collider* pCollider = (Collider*)(it->second);
if (_pCollider != pCollider && pCollider->isColliding(_pCollider, _bWithTrigger))
{
updateCollision(_pCollider, pCollider);
bIsColliding = true;
}
++it;
}
}
// With dynamic collisions
if (_bWithDynamic)
{
MapStringCollider::iterator it = m_DynamicColliders.begin();
while (it != m_DynamicColliders.end())
{
Collider* pCollider = (Collider*)(it->second);
if (_pCollider != pCollider && pCollider->isColliding(_pCollider, _bWithTrigger))
{
updateCollision(_pCollider, pCollider);
bIsColliding = true;
}
++it;
}
}
return bIsColliding;
}
Collider* PhysicsManager::getStaticCollider(const string& _szName, bool _bCloned)
{
MapStringCollider::iterator it = m_StaticColliders.find(_szName);
if (it == m_StaticColliders.end())
{
Collider* pCollider = Collider::loadFromFileJSON(DATAAGENTPATH + _szName); // Create a default Collider if none exist
if (!pCollider)
{
cerr << "Unable to open Collider file" << endl;
return nullptr;
}
m_StaticColliders[_szName] = pCollider;
return pCollider;
}
else
{
if (_bCloned)
{
//return new Collider(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
Collider* PhysicsManager::getDynamicCollider(const string& _szName, bool _bCloned)
{
MapStringCollider::iterator it = m_DynamicColliders.find(_szName);
if (it == m_DynamicColliders.end())
{
Collider* pCollider = Collider::loadFromFileJSON(DATAAGENTPATH + _szName); // Create a default Collider if none exist
if (!pCollider)
{
cerr << "Unable to open Collider file" << endl;
return nullptr;
}
pCollider->setName(_szName);
m_DynamicColliders[_szName] = pCollider;
return pCollider;
}
else
{
if (_bCloned)
{
//return new Collider(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
void PhysicsManager::setCurrentMap(Map* _pMap)
{
m_pCurrentMap = _pMap;
}
Map* PhysicsManager::getCurrentMap()
{
return m_pCurrentMap;
}
void PhysicsManager::callFunction(Collider* _pCollider, Collision2D* _pCollision, onCollisionFcn _fcn)
{
Entity* pEntity = _pCollider->getEntity();
if (pEntity)
{
list<Script*> scripts;
pEntity->getComponents<Script>(scripts);
// and call callback function on all scripts
for (list<Script*>::iterator it = scripts.begin(); it != scripts.end(); ++it)
{
Script* pScript = (Script*)*it;
(pScript->*_fcn)(*_pCollision);
}
}
}
bool PhysicsManager::onEnterCollision(Collider* _pCollider, Collider* _pOtherCollider)
{
Collision2D* pCollision = new Collision2D();
pCollision->m_pCollider = _pCollider;
pCollision->m_pOtherCollider = _pOtherCollider;
pCollision->m_bUpdated = true;
m_Collisions2D.insert(MapColliderCollision2D::value_type(_pCollider, pCollision));
// For 1st collider
callFunction(_pCollider, pCollision, &Script::onCollisionEnter2D);
// For 2nd collider
callFunction(_pOtherCollider, pCollision, &Script::onCollisionEnter2D);
return true;
}
bool PhysicsManager::onUpdateCollision(Collision2D* _pCollision)
{
// For 1st collider
callFunction(_pCollision->m_pCollider, _pCollision, &Script::onCollisionStay2D);
// For 2nd collider
callFunction(_pCollision->m_pOtherCollider, _pCollision, &Script::onCollisionStay2D);
return true;
}
bool PhysicsManager::onExitCollision(Collision2D* _pCollision)
{
// For 1st collider
callFunction(_pCollision->m_pCollider, _pCollision, &Script::onCollisionExit2D);
// For 2nd collider
callFunction(_pCollision->m_pOtherCollider, _pCollision, &Script::onCollisionExit2D);
return true;
}
bool PhysicsManager::updateCollision(Collider* _pCollider, Collider* _pOtherCollider)
{
// CB: todo: use of a multimap is not so nice (2 places to call new Collision2D)
MapColliderCollision2D::iterator it = m_Collisions2D.find(_pCollider);
if (it == m_Collisions2D.end())
{
// no collision with this collider yet
onEnterCollision(_pCollider, _pOtherCollider);
}
else
{
long count = m_Collisions2D.count(_pCollider);
for (long i = 0; i < count; ++i, ++it)
{
Collision2D* pCollision = (Collision2D*)it->second;
if (pCollision->m_pOtherCollider == _pOtherCollider)
{
onUpdateCollision(pCollision);
pCollision->m_bUpdated = true;
return true;
}
}
// no collision with this pair yet...
onEnterCollision(_pCollider, _pOtherCollider);
}
return true;
}
bool PhysicsManager::prepareCleanup()
{
long count = m_Collisions2D.size();
MapColliderCollision2D::iterator it = m_Collisions2D.begin();
for (long i = 0; i < count; ++i)
{
Collision2D* pCollision = (Collision2D*)it->second;
pCollision->m_bUpdated = false;
++it;
}
return true;
}
bool PhysicsManager::cleanupCollisions()
{
long count = m_Collisions2D.size();
MapColliderCollision2D::iterator it = m_Collisions2D.begin();
for (long i = 0; i < count; ++i)
{
Collision2D* pCollision = (Collision2D*)it->second;
if (pCollision->m_bUpdated == true)
{
++it;
}
else
{
onExitCollision(pCollision);
delete (*it).second;
count--;
it = m_Collisions2D.erase(it);
}
}
return true;
}
bool PhysicsManager::clearCollisions()
{
MapColliderCollision2D::iterator it = m_Collisions2D.begin();
while (it != m_Collisions2D.end()) {
delete (it->second);
it = m_Collisions2D.erase(it);
}
return true;
}
bool PhysicsManager::init()
{
return true;
}
bool PhysicsManager::update()
{
// Prepare cleanup
prepareCleanup();
// Check dynamic-static collisions
MapStringCollider::iterator it = m_DynamicColliders.begin();
while (it != m_DynamicColliders.end())
{
Collider* pCollider = (Collider*)(it->second);
if (isColliding(pCollider, true, false, true)) // with static, not dynamic, with trigger!
{
// resolution
//return true;
}
++it;
}
// Cleanup old collisions
cleanupCollisions();
return true;
}
bool PhysicsManager::draw()
{
return true;
}
void PhysicsManager::clear()
{
// Static
MapStringCollider::iterator itStatic = m_StaticColliders.begin();
while (itStatic != m_StaticColliders.end()) {
delete (itStatic->second);
itStatic = m_StaticColliders.erase(itStatic);
}
// Dynamic
MapStringCollider::iterator itDynamic = m_DynamicColliders.begin();
while (itDynamic != m_DynamicColliders.end()) {
delete (itDynamic->second);
itDynamic = m_DynamicColliders.erase(itDynamic);
}
m_pCurrentMap = nullptr;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Scene\SceneMap.h"
#include "Scene\SceneMenu.h"
#include "Scene\SceneGame.h"
SceneMap::SceneMap()
{
// AI Tools
m_bUseAITools = true;
m_pAITools = new AITools();
}
SceneMap::~SceneMap()
{
// AI Tools
delete m_pAITools;
}
bool SceneMap::onInit()
{
m_pGM = GameManager::getSingleton();
// Set Script factory
m_pCellsScriptFactory = new CellsScriptFactory;
m_pGM->setScriptFactory(m_pCellsScriptFactory);
// Load Map
m_pEntity3 = m_pGM->getEntity("map2");
m_pGM->addEntity(m_pEntity3);
m_pMap = m_pGM->getMap("map2.json"); // CB: TO CHANGE: map id loaded after entity added to display map first (order in tree matters)
m_pMap->loadFromFileJSON(string(DATAMAPPATH) + "map2.json");
m_pMapRenderer = m_pGM->getMapRenderer("MapRenderer1");
m_pMapRenderer->setMap(m_pMap);
m_pEntity3->addComponent(m_pMapRenderer);
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onInit();
}
return true;
}
bool SceneMap::onUpdate()
{
if (m_pGM->isKeyPressed(Key::Num1))
{
m_pGM->setScene(new SceneMenu());
return true;
}
if (m_pGM->isKeyPressed(Key::Num2))
{
m_pGM->setScene(new SceneGame());
return true;
}
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onUpdate();
}
return true;
}
bool SceneMap::onDraw()
{
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onDraw();
}
return true;
}
bool SceneMap::onQuit()
{
// AI Tools
if (m_bUseAITools)
{
m_pAITools->onQuit();
}
m_pGM->clearAllData();
m_pGM->clearAllEntities();
delete m_pCellsScriptFactory;
return true;
}
<file_sep>/***************************************************/
/* Nom: DX9Text.h
/* Description: DX9Text
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Text_H
#define _DX9Text_H
#include "Graphics\Text.h"
namespace crea
{
class DX9Text : public Text
{
DX9Font* m_pDX9Font;
LPD3DXFONT m_pFont;
RECT *m_pRect;
D3DCOLOR m_color;
string m_szText;
public:
DX9Text()
{
//init rectangle
m_pRect = nullptr;
//init color
m_color = D3DCOLOR_XRGB(255, 255, 255);
//font
m_pDX9Font = nullptr;
m_pFont = nullptr;
}
virtual ~DX9Text()
{
SafeDelete(m_pRect);
SafeRelease(m_pFont);
}
virtual void draw()
{
assert(m_pFont); // A font must be set
m_pFont->DrawText(NULL, m_szText.c_str(), -1, m_pRect, 0, m_color); // todo: CB: pass a sprite as 1st param to improve speed x4
}
virtual void setFont(Font* _pFont)
{
m_pDX9Font = (DX9Font*)_pFont;
m_pFont = m_pDX9Font->getFont();
}
virtual void setColor(Color* _pColor)
{
DX9Color* pColor = (DX9Color*)_pColor;
m_color = pColor->getColor();
}
virtual void setCharacterSize(int _iSize)
{
assert(m_pDX9Font); // A font must be set as it requires reload of font...
m_pDX9Font->setFontSize(_iSize);
}
virtual void setString(string _szString)
{
m_szText = _szString;
}
virtual void setPosition(float _x, float _y)
{
if (!m_pRect)
m_pRect = new RECT();
m_pRect->left = (LONG)_x;
m_pRect->top = (LONG)_y;
m_pRect->bottom = (LONG)_y+100; // todo: valeurs hardcodées, calculer rect?
m_pRect->right = (LONG)_x+300;
// CB: commented to fix a bug for multiple text displayed in the same frame using the same text
// CB: get size when only position is given (DrawText with CALCRECT)
//m_pFont->DrawText(NULL, m_szText.c_str(), -1, m_pRect, DT_CALCRECT, m_color);
}
virtual void setTextureRect(int _x, int _y, int _w, int _h)
{
if (!m_pRect)
m_pRect = new RECT();
m_pRect->left = _x;
m_pRect->top = _y;
m_pRect->bottom = _y + _h;
m_pRect->right = _x + _w;
}
};
} // namespace crea
#endif // _DX9Text_H
<file_sep>/***************************************************/
/* Nom: Blackboard.h
/* Description: Blackboard
/* Auteur: <NAME>
/***************************************************/
#ifndef __Blackboard_H_
#define __Blackboard_H_
namespace crea
{
class CREAENGINE_API Blackboard : public Singleton <Blackboard>
{
protected:
// Blackboard
map<string, string> m_variables;
public:
Blackboard() {}
~Blackboard() {}
void setVariable(const string& _variable, const string& _value) { m_variables[_variable] = _value; }
string getVariable(const string& _variable) { return m_variables[_variable]; }
};
}
#endif
<file_sep>#include "stdafx.h"
#include "Core\EntityManager.h"
#include "Core\Entity.h"
#include <string>
namespace crea
{
EntityManager::EntityManager()
{
m_pRoot = new Entity();
m_pRoot->setName(string("root"));
m_pScriptFactory = nullptr;
nextFreeID = 1;
}
EntityManager::~EntityManager()
{
clear();
delete m_pRoot;
m_pRoot = nullptr;
}
EntityManager* EntityManager::getSingleton()
{
static EntityManager instanceUnique;
return
&instanceUnique;
}
Entity* EntityManager::getEntity(const string& _szName)
{
Entity* pEntity = nullptr;
pEntity = m_pRoot->getEntity(_szName);
if (!pEntity)
{
pEntity = new Entity();
pEntity->setName(_szName);
pEntity->SetID(getNewObjectID());
Store(*pEntity);
}
return pEntity;
}
Entity* EntityManager::getEntityByModel(const string& _szName)
{
MapModelEntity::iterator it = m_EntitiesByModel.find(_szName);
if (it != m_EntitiesByModel.end())
{
return it->second;
}
return nullptr;
}
void EntityManager::addEntityByModel(const string& _szName, Entity* _pEntity)
{
m_EntitiesByModel[_szName] = _pEntity;
}
void EntityManager::addEntity(Entity* _pEntity, Entity* _pParent)
{
if (_pParent)
{
_pParent->addChild(_pEntity);
}
else
{
m_pRoot->addChild(_pEntity);
}
}
Entity* EntityManager::instanciate(string& _szName, Entity* _pEntity)
{
Entity* pEntity = nullptr;
pEntity = m_pRoot->getEntity(_szName);
if (!pEntity)
{
pEntity = _pEntity->clone();
pEntity->init();
pEntity->setName(_szName);
pEntity->SetID(getNewObjectID());
Store(*pEntity);
}
else
{
cout << "Name: " << _szName << " already exists, can't instanciate Entity." << endl;
}
return pEntity;
}
void EntityManager::clearEntity(Entity* _pEntity)
{
m_pRoot->removeEntity(_pEntity);
delete _pEntity;
}
TextRenderer* EntityManager::getTextRenderer(const string& _szName, bool _bCloned)
{
MapStringTextRenderer::iterator it = m_pTextRenderers.find(_szName);
if (it == m_pTextRenderers.end())
{
TextRenderer* pTextRenderer = new TextRenderer(); // Create a default TextRenderer if none exist
m_pTextRenderers[_szName] = pTextRenderer;
return pTextRenderer;
}
else
{
if (_bCloned)
{
//return new TextRenderer(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
SpriteRenderer* EntityManager::getSpriteRenderer(const string& _szName, bool _bCloned)
{
MapStringSpriteRenderer::iterator it = m_pSpriteRenderers.find(_szName);
if (it == m_pSpriteRenderers.end())
{
SpriteRenderer* pSpriteRenderer = new SpriteRenderer(); // Create a default SpriteRenderer if none exist
m_pSpriteRenderers[_szName] = pSpriteRenderer;
return pSpriteRenderer;
}
else
{
if (_bCloned)
{
//return new SpriteRenderer(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
MapRenderer* EntityManager::getMapRenderer(const string& _szName, bool _bCloned)
{
MapStringMapRenderer::iterator it = m_pMapRenderers.find(_szName);
if (it == m_pMapRenderers.end())
{
MapRenderer* pMapRenderer = new MapRenderer(); // Create a default MapRenderer if none exist
m_pMapRenderers[_szName] = pMapRenderer;
return pMapRenderer;
}
else
{
if (_bCloned)
{
//return new MapRenderer(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
Animator* EntityManager::getAnimator(const string& _szName, bool _bCloned)
{
MapStringAnimator::iterator it = m_pAnimators.find(_szName);
if (it == m_pAnimators.end())
{
Animator* pAnimator = new Animator(); // Create a default Animator if none exist
m_pAnimators[_szName] = pAnimator;
return pAnimator;
}
else
{
if (_bCloned)
{
//return new Animator(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
Script* EntityManager::getScript(const string& _szName, bool _bCloned)
{
MapStringScript::iterator it = m_pScripts.find(_szName);
if (it == m_pScripts.end())
{
if (m_pScriptFactory)
{
Script* pScript = m_pScriptFactory->create(_szName); // Create a Script using the factory (should be set first using setScriptFactory)
m_pScripts[_szName] = pScript;
return pScript;
}
}
else
{
if (_bCloned)
{
//return new Script(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
Steering* EntityManager::getSteering(string _szName, bool _bCloned)
{
MapStringSteering::iterator it = m_pSteerings.find(_szName);
if (it == m_pSteerings.end())
{
Steering* pSteering = new Steering(); // Create a default Steering if none exist
m_pSteerings[_szName] = pSteering;
return pSteering;
}
else
{
if (_bCloned)
{
//return new Steering(it->second); // CB is it useful to clone?
}
else
{
return it->second;
}
}
return nullptr;
}
void EntityManager::selectEntities(Vector2f _vStart, Vector2f _vEnd)
{
FloatRect rect(_vStart, _vEnd);
m_pRoot->selectEntities(rect);
}
void EntityManager::unselectEntities()
{
m_pRoot->unselectEntities();
m_pSelectedEntities.clear();
}
void EntityManager::addSelectedEntity(Entity* _pEntity)
{
m_pSelectedEntities.push_back(_pEntity);
}
void EntityManager::Store(Entity& _entity)
{
if (Find(_entity.GetID()) == 0) {
m_Entities[_entity.GetID()] = &_entity;
}
else {
assert(!"EntityManager::Store - Object ID already represented in database.");
}
}
void EntityManager::Remove(objectID _id)
{
MapObjectIDEntity::iterator it = m_Entities.find(_id);
if (it != m_Entities.end())
{
m_Entities.erase(it);
}
return;
}
Entity* EntityManager::Find(objectID _id)
{
MapObjectIDEntity::iterator it = m_Entities.find(_id);
if (it != m_Entities.end())
{
return it->second;
}
return(0);
}
objectID EntityManager::getNewObjectID()
{
return(nextFreeID++);
}
bool EntityManager::init()
{
return m_pRoot->init();
}
bool EntityManager::update()
{
return m_pRoot->update();
}
bool EntityManager::draw()
{
return m_pRoot->draw();
}
void EntityManager::clear()
{
MapStringTextRenderer::iterator itTextRenderer = m_pTextRenderers.begin();
while (m_pTextRenderers.size()) {
delete (*itTextRenderer).second;
itTextRenderer = m_pTextRenderers.erase(itTextRenderer);
}
MapStringSpriteRenderer::iterator itSpriteRenderer = m_pSpriteRenderers.begin();
while (m_pSpriteRenderers.size()) {
delete (*itSpriteRenderer).second;
itSpriteRenderer = m_pSpriteRenderers.erase(itSpriteRenderer);
}
MapStringMapRenderer::iterator itMapRenderer = m_pMapRenderers.begin();
while (m_pMapRenderers.size()) {
delete (*itMapRenderer).second;
itMapRenderer = m_pMapRenderers.erase(itMapRenderer);
}
MapStringAnimator::iterator itAnimator = m_pAnimators.begin();
while (m_pAnimators.size()) {
delete (*itAnimator).second;
itAnimator = m_pAnimators.erase(itAnimator);
}
MapStringScript::iterator itScript = m_pScripts.begin();
while (m_pScripts.size()) {
delete (*itScript).second;
itScript = m_pScripts.erase(itScript);
}
MapStringSteering::iterator itSteering = m_pSteerings.begin();
while (m_pSteerings.size()) {
delete (*itSteering).second;
itSteering = m_pSteerings.erase(itSteering);
}
if (m_pRoot)
{
m_pRoot->clear();
}
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: Agent.h
/* Description: Agent
/* Auteur: <NAME>
/***************************************************/
#ifndef __Agent_H_
#define __Agent_H_
#include "Core\Component.h"
namespace crea
{
class CREAENGINE_API Agent : public Component
{
int m_iStrength;
int m_iDexterity;
int m_iIntelligence;
int m_iHealth;
short m_nSize; // Unit size (ex: 2 is a 2*2 nodes unit)
short m_nCapability; // Unit capability (ex: 0 is a Ground unit)
public:
Agent();
virtual ~Agent();
inline void setStrength(int _iStength) { m_iStrength = _iStength; }
inline void setDexterity(int _iDexterity) { m_iDexterity = _iDexterity; }
inline void setIntelligence(int _iIntelligence) { m_iIntelligence = _iIntelligence; }
inline void setHealth(int _iHealth) { m_iHealth = _iHealth; }
inline void setSize(short _iSize) { m_nSize = _iSize; }
inline void setCapability(short _iCapability) { m_nCapability = _iCapability; }
inline int getStrength() const { return m_iStrength; }
inline int getDexterity() const { return m_iDexterity; }
inline int getIntelligence() const { return m_iIntelligence; }
inline int getHealth() const { return m_iHealth; }
inline short getSize() const { return m_nSize; }
inline short getCapability() const { return m_nCapability; }
bool loadFromFileJSON(const string&_filename);
virtual bool init();
virtual bool update();
virtual bool draw();
virtual bool quit();
virtual Component* clone() { return new Agent(*this); }
};
} // namespace crea
#endif
<file_sep>#include "stdafx.h"
#include "Scripts\CharacterController.h"
CharacterController::CharacterController()
{
m_pGM = crea::GameManager::getSingleton();
m_pActionTable = nullptr;
m_pAnimator = nullptr;
m_pCollider = nullptr;
}
CharacterController::~CharacterController()
{
}
void CharacterController::setActionTable(crea::ActionTable* _pActionTable)
{
m_pActionTable = _pActionTable;
}
void CharacterController::setAnimator(crea::Animator* _pAnimator)
{
m_pAnimator = _pAnimator;
}
void CharacterController::setCondition(EnumAnimCondition _eCondition)
{
m_eCondition = _eCondition;
}
void CharacterController::setAction(EnumAction _eAction)
{
m_eAction = _eAction;
// CB: should be given by the action table or the animation?
if (m_eAction == kAct_Die)
{
m_bAlive = false;
m_bMoving = false;
}
else if (m_eAction == kAct_Chop) // CB: Not sure Chop should be in engine... Static instead?
{
m_bAlive = true;
m_bMoving = false;
}
else
{
m_bAlive = true;
m_bMoving = true;
}
}
void CharacterController::setDirection(EnumCharacterDirection _eDirection)
{
m_eDirection = _eDirection;
}
void CharacterController::setDirection(Vector2f _vDirection)
{
int iDirection = 0;
Vector2f vRight(0.f, -1.f);
float fAngle = vRight.angle(_vDirection);
if (_vDirection.getX() > 0)
{
iDirection = (int)(0.5f + fAngle * 4 / 3.14f);
setDirection((EnumCharacterDirection)iDirection);
}
else
{
iDirection = 8 - (int)(0.5f + fAngle * 4 / 3.14f);
iDirection = (iDirection == 8) ? 0 : iDirection;
setDirection((EnumCharacterDirection)iDirection);
}
m_pEntity->setOrientation(_vDirection);
}
// Move the controller by a vector, only constrained by collisions
void CharacterController::move(crea::Vector2f _vMotion)
{
m_vMotion = _vMotion;
}
void CharacterController::followPath(vector<Vector2f*>& _path, const Vector2f& _offset)
{
m_path.clear();
m_path.assign(_path.begin(), _path.end());
m_nextIt = m_path.end();
shouldFollowPath = true;
m_offset = _offset;
}
bool CharacterController::stupidSwordman(Vector2f& _position, Vector2f& _direction, float _speed)
{
bool isEndOfPath = true;
if (m_nextIt == m_path.end())
{
m_previousIt = m_nextIt = m_path.begin();
}
float distance = _speed * (float)crea::TimeManager::getSingleton()->getFrameTime().asSeconds();
_direction = **m_nextIt - _position;
while (m_nextIt != m_path.end() && _direction.length() < distance)
{
distance -= _direction.length();
m_previousIt = m_nextIt;
m_nextIt++;
if (m_nextIt != m_path.end())
{
_direction = **m_nextIt - **m_previousIt;
_position = **m_previousIt;
}
else
{
_direction = Vector2f(0.f, 0.f);
isEndOfPath = false;
}
}
if (m_nextIt != m_path.end())
{
_direction.normalize();
_position += _direction * distance;
}
return isEndOfPath;
}
bool CharacterController::init()
{
m_pActionTable = getEntity()->getComponent<crea::ActionTable>();
m_pAnimator = getEntity()->getComponent<crea::Animator>();
m_pCollider = getEntity()->getComponent<Collider>();
m_pAgent = m_pEntity->getComponent<Agent>();
m_pVehicle = m_pEntity->getComponent<Vehicle>();
m_bAlive = true;
m_bMoving = false;
m_eDirection = kADir_Down;
m_eCondition = kACond_Default;
m_eAction = kAct_Default;
m_pCurrentAnimation = m_pGM->getAnimation(*m_pActionTable->getAnimation(m_eDirection, m_eCondition, m_eAction, nullptr));
m_fVelocityMax = 100.f;
return true;
}
bool CharacterController::update()
{
// Preconditions
if (!m_pCollider || !m_pAnimator || !m_pActionTable)
{
return false;
}
if (shouldFollowPath)
{
// Stupid swordman algorithm
Vector2f position = m_pEntity->getPosition();
shouldFollowPath = stupidSwordman(position, m_vMotion, m_fVelocityMax);
m_vMotion *= m_fVelocityMax;
setDirection(m_vMotion);
setAction(kAct_Walk);
}
m_pCurrentAnimation = m_pGM->getAnimation(*m_pActionTable->getAnimation(m_eDirection, m_eCondition, m_eAction));
//m_pCurrentAnimation = m_pGM->getAnimation(*m_pActionTable->getAnimation(kADir_Left, kACond_Default, kAct_Walk, nullptr));
m_pAnimator->play(*m_pCurrentAnimation);
m_pCurrentAnimation->setSpeed(1.0f); // Play full speed by default
if (m_bMoving)
{
// Friction
float fSpeedFactor = 1.f;
Map* pCurrentMap = PhysicsManager::getSingleton()->getCurrentMap();
if (pCurrentMap)
{
fSpeedFactor = 1 - pCurrentMap->getFrictionAtPosition(getEntity()->getPosition());
}
// Move
float speed = min(m_vMotion.length(), m_fVelocityMax);
m_vMotion.normalize();
m_vMotion *= (speed * m_pAgent->getDexterity()*0.1f);
Vector2f vAdjustedMotion = m_vMotion * fSpeedFactor;
m_pEntity->move(vAdjustedMotion * (float)crea::TimeManager::getSingleton()->getFrameTime().asSeconds());
// Collision
// // Todo: à vérifier pourquoi on ne décolle pas avec le booléen
//if (m_isColliding)
/*if (PhysicsManager::getSingleton()->isColliding(m_pCollider))
{
// Revert move
m_pEntity->move(-vAdjustedMotion * (float)crea::TimeManager::getSingleton()->getFrameTime().asSeconds());
m_vMotion = vAdjustedMotion = Vector2f(0.f, 0.f);
m_eAction = kAct_Idle;
}*/
// Adjust anim speed to velocity
// Todo: Translationspeed should be adjusted in Animator, not Animation
// because an animation is shared between instances, not Animator
m_pCurrentAnimation->adjustToTranslationSpeed(2 * vAdjustedMotion.length());
}
// update AnimatedSprite
//m_pAnimator->update();
return true;
}
bool CharacterController::draw()
{
return true;
}
bool CharacterController::quit()
{
return true;
}
void CharacterController::onCollisionEnter2D(Collision2D& _coll)
{
m_isColliding = true;
return;
}
void CharacterController::onCollisionExit2D(Collision2D& _coll)
{
m_isColliding = false;
return;
}
<file_sep>/***************************************************/
/* Nom: FSMPeonGoTo.h
/* Description: FSMPeonGoTo
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMPeonGoTo_H_
#define __FSMPeonGoTo_H_
#include "AI\StateMachine.h"
#include "AI\Pathfinding\MapSearchManager.h"
#include "Scripts\CharacterController.h"
using namespace crea;
class FSMPeonGoTo : public StateMachine
{
GameManager* m_pGM;
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
MapSearch* m_pMapSearch;
Vector2f m_vTarget;
VectorVector2f m_vPath;
RectangleShape* m_pPathNodeShape;
bool m_bHasPath = false;
VectorVector2f m_vOpenList;
RectangleShape* m_pPathNodeShapeOpen;
bool m_bHasOpenList = false;
vector<Edge*> m_vEdges;
ArrowShape* m_pArrowShape;
bool m_bHasEdges = false;
public:
FSMPeonGoTo(Vector2f _vTarget);
virtual ~FSMPeonGoTo();
void setEntity(Entity* _p) { m_pEntity = _p; }
void setCharacterController(CharacterController* _p) { m_pCharacterController = _p; }
inline VectorVector2f* getPath() { return &m_vPath; }
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
enum States {
STATE_Init,
STATE_SearchPath,
STATE_FollowPath,
STATE_SearchFailed,
STATE_CompletedPath
};
virtual bool draw();
virtual Component* clone() { return new FSMPeonGoTo(*this); }
};
#endif
<file_sep>#include "stdafx.h"
#include "Graphics\TextRenderer.h"
#include "Core\GameManager.h"
namespace crea
{
TextRenderer::TextRenderer()
{
m_pText = nullptr;
}
TextRenderer::~TextRenderer()
{
}
bool TextRenderer::init()
{
return true;
}
bool TextRenderer::update()
{
return true;
}
bool TextRenderer::draw()
{
if (m_pText)
{
Vector2f vPos = getEntity()->getPosition();
m_pText->setPosition(vPos.getX(), vPos.getY());
/*
if (m_pTextureRect)
{
m_pText->setTextureRect(m_pTextureRect->getLeft(), m_pTextureRect->getTop(),
m_pTextureRect->getWidth(), m_pTextureRect->getHeight());
}*/
m_pText->draw();
}
return true;
}
bool TextRenderer::quit()
{
return true;
}
} // namespace crea
<file_sep>#include "stdafx.h"
#include "Graphics\GL3Shader.h"
namespace crea
{
GL3Shader::GL3Shader()
{
}
GL3Shader::~GL3Shader()
{
glDeleteProgram(shaderProgram);
}
bool GL3Shader::loadFromFile(const string& _name)
{
// Read .shader file
ifstream shaderFile;
string shaderNames;
size_t pos = _name.rfind('/');
string directory = _name.substr(0, ++pos);
// open files
shaderFile.open(_name);
stringstream shaderStream;
// read file's buffer contents into streams
shaderStream << shaderFile.rdbuf();
// close file handlers
shaderFile.close();
// convert stream into string
shaderNames = shaderStream.str();
pos = shaderNames.find('\n');
string vertexShaderFileName = directory + shaderNames.substr(0, pos);
string fragmentShaderFileName = directory + shaderNames.substr(pos + 1, string::npos);
// build and compile our shader program
// ------------------------------------
// vertex shader
ifstream vShaderFile;
ifstream vertexShaderFile(vertexShaderFileName);
if (vertexShaderFile.fail())
{
cout << "Can't open vertex shader file : " << vertexShaderFileName << std::endl;
return false;
}
//extract .vs code
stringstream vertexShaderStream;
string vertexShaderString;
vertexShaderStream << vertexShaderFile.rdbuf();
vertexShaderString = vertexShaderStream.str();
const char* vertexShaderCode = vertexShaderString.c_str();
vertexShaderFile.close();
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderCode, NULL);
glCompileShader(vertexShader);
// check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// fragment shader
ifstream fragmentShaderFile(fragmentShaderFileName);
if (fragmentShaderFile.fail())
{
cout << "Can't open fragment shader file : " << fragmentShaderFileName << std::endl;
return false;
}
//extract .fs code
stringstream fragmentShaderStream;
string fragmentShaderString;
fragmentShaderStream << fragmentShaderFile.rdbuf();
fragmentShaderString = fragmentShaderStream.str();
const char* fragmentShaderCode = fragmentShaderString.c_str();
fragmentShaderFile.close();
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderCode, NULL);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// link shaders
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return true;
}
void GL3Shader::use()
{
glUseProgram(shaderProgram);
}
void GL3Shader::unuse()
{
glUseProgram(0);
}
// utility uniform functions
// ------------------------------------------------------------------------
void GL3Shader::setBool(const std::string &name, bool value) const
{
glUniform1i(glGetUniformLocation(shaderProgram, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void GL3Shader::setInt(const std::string &name, int value) const
{
glUniform1i(glGetUniformLocation(shaderProgram, name.c_str()), value);
}
// ------------------------------------------------------------------------
void GL3Shader::setFloat(const std::string &name, float value) const
{
glUniform1f(glGetUniformLocation(shaderProgram, name.c_str()), value);
}
// ------------------------------------------------------------------------
void GL3Shader::setVec3(const std::string &name, float* vec3) const
{
glUniform3fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, vec3);
}
// ------------------------------------------------------------------------
void GL3Shader::setMat3(const std::string &name, float* mat3) const
{
glUniformMatrix3fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, mat3);
}
// ------------------------------------------------------------------------
void GL3Shader::setMat4x4(const std::string &name, float* mat4) const
{
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, mat4);
}
} // namespace Crea<file_sep>/***************************************************/
/* Nom: FSMPeon.h
/* Description: FSMPeon
/* Auteur: <NAME>
/***************************************************/
#ifndef __FSMPeon_H_
#define __FSMPeon_H_
#include "AI\StateMachine.h"
#include "Scripts\CharacterController.h"
#include "Scripts\FSMPeonLive.h"
using namespace crea;
class FSMPeon : public StateMachine
{
Entity* m_pEntity;
CharacterController* m_pCharacterController;
Agent* m_pAgent;
bool m_bPaused;
int m_iLife;
FSMPeonLive* m_pFSMPeonLive;
public:
FSMPeon();
virtual ~FSMPeon();
virtual bool States(StateMachineEvent _event, Msg* _msg, int _state);
virtual Component* clone() { return new FSMPeon(*this); }
};
#endif
<file_sep>#include "stdafx.h"
#include "Graphics\Shader.h"
namespace crea
{
Shader::Shader()
{
}
Shader::~Shader()
{
}
bool Shader::loadFromFile(const string& _name)
{
return true;
}
void Shader::use()
{
}
void Shader::unuse()
{
}
// utility uniform functions
// ------------------------------------------------------------------------
void Shader::setBool(const std::string &name, bool value) const
{
}
// ------------------------------------------------------------------------
void Shader::setInt(const std::string &name, int value) const
{
}
// ------------------------------------------------------------------------
void Shader::setFloat(const std::string &name, float value) const
{
}
// ------------------------------------------------------------------------
void Shader::setVec3(const std::string &name, float* vec3) const
{
}
// ------------------------------------------------------------------------
void Shader::setMat3(const std::string &name, float* mat3) const
{
}
// ------------------------------------------------------------------------
void Shader::setMat4x4(const std::string &name, float* mat4) const
{
}
} // namespace Crea<file_sep>#include "stdafx.h"
#include "Scripts\FSMSteeringPeonLive.h"
#include "Scripts\Messages.h"
#include <string.h>
#include "AI\Steering\Behavior.h"
//Add new states here
enum States {
STATE_Init,
STATE_Idle,
STATE_Seek,
STATE_Flee,
STATE_Pursuit,
STATE_Evasion,
STATE_Arrival,
STATE_Wander,
STATE_PathFollowingIdle,
STATE_PathFollowing,
STATE_UCA
};
FSMSteeringPeonLive::FSMSteeringPeonLive()
{
}
FSMSteeringPeonLive::~FSMSteeringPeonLive()
{
}
bool FSMSteeringPeonLive::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
OnMsg(MSG_Stop)
m_pCharacterController->setAction(kAct_Default);
m_bPaused = true;
OnMsg(MSG_GoTo)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Seek);
m_bPaused = false;
OnMsg(MSG_Seek)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Seek);
m_bPaused = false;
OnMsg(MSG_Flee)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Flee);
m_bPaused = false;
OnMsg(MSG_Pursuit)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Pursuit);
m_bPaused = false;
OnMsg(MSG_Evasion)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Evasion);
m_bPaused = false;
OnMsg(MSG_Arrival)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Arrival);
m_bPaused = false;
OnMsg(MSG_Wander)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_Wander);
m_bPaused = false;
OnMsg(MSG_PathFollowing)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_PathFollowingIdle);
m_bPaused = false;
OnMsg(MSG_UCA)
m_pCharacterController->setCondition(kACond_Default);
SetState(STATE_UCA);
m_bPaused = false;
///////////////////////////////////////////////////////////////
State(STATE_Init)
OnEnter
// Get Game Manager
m_pGM = GameManager::getSingleton();
// Get Entity
m_pEntity = this->m_Owner;
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
// Get Steering
m_pSteering = m_pEntity->getComponent<Steering>();
m_pSteering->init();
// Get Vehicle
m_pVehicle = m_pEntity->getComponent<Vehicle>();
m_pVehicle->setUpdatePosition(false); //The characterController will update the position
OnUpdate
SetState(STATE_Idle);
///////////////////////////////////////////////////////////////
State(STATE_Idle)
OnEnter
m_bPaused = false;
m_pCharacterController->setCondition(kACond_Default);
OnUpdate
Move();
///////////////////////////////////////////////////////////////
State(STATE_Seek)
OnEnter
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Seek(getEntity(), m_pGM->getEntity("mouse")), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
///////////////////////////////////////////////////////////////
State(STATE_Flee)
OnEnter
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Flee(getEntity(), m_pGM->getEntity("mouse")), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
///////////////////////////////////////////////////////////////
State(STATE_Pursuit)
OnEnter
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Pursuit(getEntity(), m_pGM->getEntity("mouse"), 0.5f), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
///////////////////////////////////////////////////////////////
State(STATE_Evasion)
OnEnter
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Evasion(getEntity(), m_pGM->getEntity("mouse"), 0.5f), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
///////////////////////////////////////////////////////////////
State(STATE_Arrival)
OnEnter
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Arrival(getEntity(), m_pGM->getEntity("mouse"), 100.0f), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
///////////////////////////////////////////////////////////////
State(STATE_Wander)
OnEnter
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Wander(getEntity(), 200.0f, 100.0f, 10.0f), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
///////////////////////////////////////////////////////////////
State(STATE_PathFollowingIdle)
OnEnter
m_bPaused = false;
m_pCharacterController->setCondition(kACond_Default);
OnUpdate
m_pCharacterController->move(Vector2f(0.f, 0.0f));
m_pVehicle->setVelocity(Vector2f(0.f, 0.0f));
if (InputManager::getSingleton()->isMouseButtonPressed(MouseRight))
{
m_pTarget = m_pGM->getEntity("mouse");
m_vTarget = m_pTarget->getPosition();
SetState(STATE_PathFollowing);
}
///////////////////////////////////////////////////////////////
State(STATE_PathFollowing)
OnEnter
m_pFSMSteeringPeonGoTo = new FSMSteeringPeonGoTo(m_vTarget);
getEntity()->addComponent(m_pFSMSteeringPeonGoTo);
m_pFSMSteeringPeonGoTo->Initialize(getEntity());
OnUpdate
m_pFSMSteeringPeonGoTo->Update();
if (m_pFSMSteeringPeonGoTo->GetState() == FSMSteeringPeonGoTo::STATE_CompletedPath)
{
SetState(STATE_PathFollowingIdle);
}
OnExit
getEntity()->removeComponent(m_pFSMSteeringPeonGoTo);
delete m_pFSMSteeringPeonGoTo;
m_pFSMSteeringPeonGoTo = nullptr;
///////////////////////////////////////////////////////////////
State(STATE_UCA)
OnEnter
m_pOthers.clear();
Entity* pOther = m_pGM->getEntity("balista1");
m_pOthers.push_back(pOther);
m_pSteering->clearBehaviors();
m_pSteering->addBehavior(new Seek(getEntity(), m_pGM->getEntity("mouse")), 1.0f);
m_pSteering->addBehavior(new UnalignedCollisionAvoidance(getEntity(), 32.0f, 1.0f, &m_pOthers), 1.0f);
OnUpdate
Move();
OnExit
m_pSteering->clearBehaviors();
EndStateMachine
}
bool FSMSteeringPeonLive::Move()
{
bool bMoving = true;
Vector2f vVelocity = m_pVehicle->getVelocity();
if (vVelocity.length() > 1)
{
m_pCharacterController->setAction(kAct_Walk);
}
else
{
bMoving = false;
vVelocity = Vector2f(0.f, 0.0f);
}
// CB: adjust velocity with dexterity
int iDexterity = m_pAgent->getDexterity() / 5;
m_pCharacterController->move(vVelocity * (float)iDexterity);
m_pCharacterController->setDirection(vVelocity);
return bMoving;
}
Component* FSMSteeringPeonLive::clone()
{
FSMSteeringPeonLive* p = new FSMSteeringPeonLive(*this);
return p;
}
<file_sep>#include "stdafx.h"
#include "Core\GameManager.h"
#include "Core\TimeManager.h"
#include "Tools\Logger.h"
namespace crea
{
GameManager::GameManager()
{
m_pRenderer = nullptr;
}
GameManager::~GameManager()
{
// Do not delete renderer as it will be deleted on it's own (or before GameManager...)
//delete m_pRenderer;
}
GameManager* GameManager::getSingleton()
{
static GameManager instanceUnique;
return
&instanceUnique;
}
void GameManager::setRendererType(EnumRendererType _rendererType)
{
assert(_rendererType > Renderer_Invalid && _rendererType < Renderer_Max);
m_rendererType = _rendererType;
if (m_rendererType == Renderer_DX9)
{
#ifdef _DEBUG
IFacade::load("CreaDirectX9-d.dll");
#else
IFacade::load("CreaDirectX9.dll");
#endif
}
else if (m_rendererType == Renderer_SFML)
{
#ifdef _DEBUG
IFacade::load("CreaSFML-d.dll");
#else
IFacade::load("CreaSFML.dll");
#endif
}
else if (m_rendererType == Renderer_GL3)
{
#ifdef _DEBUG
IFacade::load("CreaOpenGL3-d.dll");
#else
IFacade::load("CreaOpenGL3.dll");
#endif
}
else
{
cerr << "Renderer type not defined yet..." << endl;
}
m_pRenderer = &IFacade::get();
m_pRenderer->initialize();
}
void GameManager::init()
{
m_pLogger = new LoggerFile("CreaEngine.log");
ILogger::SetLogger(m_pLogger);
ILogger::Log("GameManager::init()\n");
TimeManager::getSingleton()->init();
PhysicsManager::getSingleton()->init();
}
void GameManager::update()
{
while (m_bContinueMainLoop && m_pRenderer->update())
{
// Time
TimeManager::getSingleton()->update();
InputManager::getSingleton()->update();
m_bContinueMainLoop = SceneManager::getSingleton()->update();
EntityManager::getSingleton()->update();
PhysicsManager::getSingleton()->update();
MsgManager::getSingleton()->update();
// Draw
m_pRenderer->beginScene();
EntityManager::getSingleton()->draw();
SceneManager::getSingleton()->draw();
m_pRenderer->endScene();
}
}
void GameManager::quit()
{
// Clear managers
DataManager::getSingleton()->clear();
EntityManager::getSingleton()->clear();
PhysicsManager::getSingleton()->clear();
ILogger::Log("GameManager::quit()\n");
m_pRenderer->quit();
delete m_pLogger;
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: MapSearch.h
/* Description: MapSearch
/* Auteur: <NAME>
/***************************************************/
#ifndef __MapSearch_H__
#define __MapSearch_H__
#include "AI\Pathfinding\AStarSearch.h"
#include "AI\Pathfinding\MapSearchNode.h"
namespace crea
{
class CREAENGINE_API VectorVector2f : public vector<Vector2f*> {};
class CREAENGINE_API MapSearch : public AStarSearch<MapSearchNode>
{
public:
enum SearchState
{
SEARCH_STATE_NOT_INITIALISED,
SEARCH_STATE_SEARCHING,
SEARCH_STATE_SUCCEEDED,
SEARCH_STATE_FAILED,
SEARCH_STATE_OUT_OF_MEMORY,
SEARCH_STATE_INVALID
};
MapSearch();
~MapSearch();
bool setStartAndGoal(Vector2f _vStart, Vector2f _vGoal);
SearchState update();
bool getSolution(VectorVector2f& _vSolution);
bool getOpenList(VectorVector2f& _vOpenList);
// AA*
Agent* getCurrentAgent() { return m_pAgent; }
void setCurrentAgent(Agent* _pAgent) { m_pAgent = _pAgent; }
private:
SearchState m_uiSearchState;
Agent* m_pAgent;
};
}
#endif // __MapSearch_H__<file_sep>#include "stdafx.h"
#include "Data\Map.h"
#include "Data\Node.h"
#include "Graphics\Sprite.h"
namespace crea
{
Map::Map()
{
m_nWidth = 0;
m_nHeight = 0;
m_nTileWidth = 0;
m_nTileHeight = 0;
m_bIsGrid8 = false;
m_pTerrainTileSet = nullptr;
m_pGM = crea::GameManager::getSingleton();
m_Clusters = nullptr;
m_bUseHPA = false;
m_bUseAStar = false;
m_bUseAA = false;
}
Map::~Map()
{
clear();
m_nWidth = 0;
m_nHeight = 0;
}
// Remove path
string getFileName(const string& _fullName, const string& _fromName)
{
size_t s = _fullName.size();
int quotePos = _fullName.rfind(_fromName, s); //finds last quote mark
return _fullName.substr(quotePos + _fromName.size(), s - quotePos);
}
bool Map::loadFromFileJSON(const string& _filename)
{
Json::Value root;
std::ifstream mapStream(_filename, std::ifstream::binary);
if (mapStream.fail())
{
cerr << "Can't open map file: " << _filename << endl;
return false;
}
setName(_filename);
// Parse file
mapStream >> root;
float version = root.get("version", 0).asFloat();
if (version < 1.0f || version > 1.2f)
{
cerr << "Can't parse map if version < 1.0 or > 1.2" << endl;
return false;
}
int iWidth = root.get("width", 10).asInt();
int iHeight = root.get("height", 10).asInt();
// Create all nodes
setSize(iWidth, iHeight);
m_nTileWidth = root.get("tilewidth", 10).asInt();
m_nTileHeight = root.get("tileheight", 10).asInt();
updateTileIndexLimits();
//Tilesets (load tilesets first as layers will refer to them...)
Json::Value tilesets = root["tilesets"];
for (unsigned int iTileset = 0; iTileset < tilesets.size(); ++iTileset)
{
Json::Value tileset = tilesets[iTileset];
if (version == 1.2f)
{
string source = tileset.get("source", "none").asString();
if (source != "none")
{
cerr << "Can't parse map if tileset not embeded in map (version 1.2) " << endl;
return false;
}
}
// Create a tileset
TileSet* pTileSet = new TileSet();
pTileSet->m_nColumns = tileset["columns"].asInt();
pTileSet->m_nFirstgid = tileset["firstgid"].asInt();
string image = getFileName(tileset["image"].asString(), "Image/");
pTileSet->m_nImageheight = tileset["imageheight"].asInt();
pTileSet->m_nImagewidth = tileset["imagewidth"].asInt();
pTileSet->m_nMargin = tileset["margin"].asInt();
pTileSet->m_szName = tileset["name"].asString();
pTileSet->m_nSpacing = tileset["spacing"].asInt();
pTileSet->m_nTilecount = tileset["tilecount"].asInt();
pTileSet->m_nTileheight = tileset["tileheight"].asInt();
pTileSet->m_nTilewidth = tileset["tilewidth"].asInt();
pTileSet->m_vTileOffset = Vector2f((float)tileset["tileoffset"]["x"].asInt(), (float)tileset["tileoffset"]["y"].asInt());
if (pTileSet->m_szName == "Terrain")
{
m_pTerrainTileSet = pTileSet;
}
else if (pTileSet->m_szName == "Clearance")
{
m_pClearanceTileSet = pTileSet;
}
// terrain
Json::Value terrains = tileset["terrains"];
for (unsigned int iTerrain = 0; iTerrain < terrains.size(); ++iTerrain)
{
Json::Value terrain = terrains[iTerrain];
Terrain* pTerrain = new Terrain();
pTerrain->m_szName = terrain["name"].asString();
pTerrain->m_nTile = terrain["tile"].asInt();
if (version == 1.0f)
{
pTerrain->m_fFriction = terrain["properties"]["Friction"].asFloat();
}
else if (version == 1.2f)
{
Json::Value properties = terrain["properties"];
for (unsigned int iProperties = 0; iProperties < properties.size(); ++iProperties)
{
Json::Value property = properties[iProperties];
string name = property["name"].asString();
if (name == "friction")
{
pTerrain->m_fFriction = property["value"].asFloat();
}
}
}
pTileSet->m_Terrains.push_back(pTerrain);
}
// Load Image and create sprite
pTileSet->m_pSprite = m_pGM->getSprite(pTileSet->m_szName);
pTileSet->m_pSprite->setTexture(m_pGM->getTexture(image));
// origin of a tile at lower left in Tiled, upper left in SFML. Move Origin to center
pTileSet->m_pSprite->setOrigin(-pTileSet->m_vTileOffset.getX(), pTileSet->m_nTileheight - pTileSet->m_vTileOffset.getY());
// Tiles
if (pTileSet->m_nTilecount > 1)
{
Json::Value tiles = tileset["tiles"];
if (version == 1.0f)
{
for (unsigned int i = 0; i < tiles.size(); ++i)
{
string tilenumber = tiles.getMemberNames()[i];
Json::Value tile = tiles[tilenumber];
Json::Value tileinfo = tile["terrain"];
TileInfo* pTileInfo = new TileInfo;
for (unsigned int iTerrain = 0; iTerrain < 4; iTerrain++)
{
pTileInfo->m_nTerrain[iTerrain] = tileinfo[iTerrain].asInt();
}
pTileSet->m_TileInfos[tilenumber] = pTileInfo;
}
}
else if (version == 1.2f)
{
for (unsigned int i = 0; i < tiles.size(); ++i)
{
Json::Value tile = tiles[i];
string tilenumber = tile["id"].asString();
Json::Value tileinfo = tile["terrain"];
TileInfo* pTileInfo = new TileInfo;
for (unsigned int iTerrain = 0; iTerrain < 4; iTerrain++)
{
pTileInfo->m_nTerrain[iTerrain] = tileinfo[iTerrain].asInt();
}
pTileSet->m_TileInfos[tilenumber] = pTileInfo;
}
}
}
m_TileSet.push_back(pTileSet);
}
// Layers
Json::Value layers = root["layers"];
for (unsigned int iLayer = 0; iLayer < layers.size(); ++iLayer)
{
Json::Value layer = layers[iLayer];
int iHeight = layer["height"].asInt();
int iWidth = layer["width"].asInt();
int iX = layer["x"].asInt();
int iY = layer["y"].asInt();
string type = layer["type"].asString();
if (type == "tilelayer")
{
string szLayerName = layer["name"].asString();
bool bIsTerrain = (szLayerName == "Terrain");
bool bIsCollisionTiles = (szLayerName == "CollisionTiles");
bool bIsClearanceGround = (szLayerName == "ClearanceGround");
if (version == 1.2f)
{
bool isEntity = false;
Json::Value properties = layer["properties"];
for (unsigned int iProperty = 0; iProperty < properties.size(); ++iProperty)
{
Json::Value property = properties[iProperty];
string szEntityName = property["name"].asString();
if (szEntityName == "UseHPA")
{
m_bUseHPA = property["value"].asBool();
}
else if (szEntityName == "UseAStar")
{
m_bUseAStar = property["value"].asBool();
}
else if (szEntityName == "UseAA")
{
m_bUseAA = property["value"].asBool();
}
}
}
// TD A*
if (m_bUseAStar && bIsCollisionTiles)
{
MapSearchManager::getSingleton()->setCurrentMap(this);
}
Json::Value data = layer["data"];
for (short i = 0; i < iWidth; i++)
{
for (short j = 0; j < iHeight; j++)
{
short nIndex = (short)data[j*iWidth + i].asInt();
if (bIsTerrain)
{
m_Grid[i][j]->setTileTerrainId(nIndex);
}
else if (bIsCollisionTiles)
{
m_Grid[i][j]->setTileCollisionId(nIndex);
}
else if (bIsClearanceGround && m_pClearanceTileSet)
{
m_Grid[i][j]->setTileClearanceId(nIndex == 0 ? 0 : nIndex - m_pClearanceTileSet->m_nFirstgid + 1, 0);
}
}
}
}
// TD Agents
if (type == "objectgroup")
{
string szLayerName = layer["name"].asString();
if (szLayerName == "Entities")
{
Json::Value objects = layer["objects"];
for (unsigned int iObject = 0; iObject < objects.size(); ++iObject)
{
Json::Value object = objects[iObject];
int iPersoHeight = object["height"].asInt();
int iPersoWidth = object["width"].asInt();
int iPersoX = object["x"].asInt();
int iPersoY = object["y"].asInt();
int iRotation = object["rotation"].asInt();
int iId = object["id"].asInt();
int iGId = object["gid"].asInt();
string szName = object["name"].asString();
string szType = object["type"].asString();
bool bVisible = object["visible"].asBool();
// Create entity
// A sprite is a gid linked to a tileset that is loaded before in function
TileSet* pTileSet = getTileSet(iGId);
Entity* pEntity = m_pGM->getEntity(szName);
pEntity->setPosition(Vector2f((float)iPersoX, (float)iPersoY));
m_pGM->addEntity(pEntity);
// Properties
if (version == 1.0f)
{
Json::Value entityName = object["properties"]["Entity"];
if (entityName.isString())
{
pEntity->loadFromFileJSON(DATAAGENTPATH + entityName.asString());
}
else
{
SpriteRenderer* pSpriteRenderer = new crea::SpriteRenderer();
pSpriteRenderer->setSprite(pTileSet->m_pSprite);
IntRect iRect = pTileSet->getTextureRect(iGId);
pSpriteRenderer->setTextureRect(&iRect);
pEntity->addComponent(pSpriteRenderer);
}
}
else if (version == 1.2f)
{
bool isEntity = false;
Json::Value properties = object["properties"];
for (unsigned int iProperty = 0; iProperty < properties.size(); ++iProperty)
{
Json::Value property = properties[iProperty];
Json::Value propertyName = property["name"];
string szPropertyName = propertyName.asString();
if (szPropertyName == "Entity")
{
isEntity = true;
Json::Value entityType = property["type"];
if (propertyName.isString())
{
Json::Value entityValue = property["value"];
string entityFileName = entityValue.asString();
Entity* pModel = m_pGM->getEntityByModel(entityFileName);
if (pModel)
{
pEntity->cloneComponents(pModel);
}
else
{
pEntity->loadFromFileJSON(DATAAGENTPATH + entityFileName);
m_pGM->addEntityByModel(entityFileName, pEntity);
}
}
}
}
// if it's not an entity, make it visible
if (!isEntity)
{
SpriteRenderer* pSpriteRenderer = new crea::SpriteRenderer();
pSpriteRenderer->setSprite(pTileSet->m_pSprite);
IntRect iRect = pTileSet->getTextureRect(iGId);
pSpriteRenderer->setTextureRect(&iRect);
pEntity->addComponent(pSpriteRenderer);
}
}
}
}
else if (szLayerName == "Collisions")
{
PhysicsManager::getSingleton()->setCurrentMap(this);
Json::Value objects = layer["objects"];
for (unsigned int iObject = 0; iObject < objects.size(); ++iObject)
{
Json::Value object = objects[iObject];
int iColliderHeight = object["height"].asInt();
int iColliderWidth = object["width"].asInt();
int iColliderX = object["x"].asInt();
int iColliderY = object["y"].asInt();
int iRotation = object["rotation"].asInt();
int iId = object["id"].asInt();
string szName = object["name"].asString();
string szType = object["type"].asString();
bool bVisible = object["visible"].asBool();
bool bEllipse = object["ellipse"].asBool();
if (bEllipse)
{
// CircleCollider
CircleCollider* pCircleCollider = new CircleCollider();
float fRadius = iColliderWidth * 0.5f;
pCircleCollider->getCenter() = Vector2f((float)iColliderX + fRadius, (float)iColliderY + fRadius);
pCircleCollider->getRadius() = fRadius;
if (szType.find("trigger") != string::npos)
{
pCircleCollider->getIsTrigger() = true;
}
PhysicsManager::getSingleton()->addStaticCollider(szName, pCircleCollider);
}
else
{
// BoxCollider
BoxCollider* pBoxCollider = new BoxCollider();
pBoxCollider->getOrigin() = Vector2f((float)iColliderX, (float)iColliderY);
pBoxCollider->getSize() = Vector2f((float)iColliderWidth, (float)iColliderHeight);
if (szType.find("trigger") != string::npos)
{
pBoxCollider->getIsTrigger() = true;
}
PhysicsManager::getSingleton()->addStaticCollider(szName, pBoxCollider);
}
}
}
}
}
// Terrain Tileset must be set (make sure the name of the tileset is "Terrain")
if (m_pTerrainTileSet == nullptr)
{
cerr << "Terrain Tileset must be set! make sure the name of the tileset is \"Terrain\"" << endl;
return false;
}
assert(m_pTerrainTileSet != nullptr);
// Clusters
if (m_bUseHPA)
{
findClusters();
}
if (m_bUseAA)
{
findClearance();
}
return true;
}
//
void Map::findClearance()
{
int capability = 0;
for (short i = 0; i < m_nWidth; i++)
{
for (short j = 0; j < m_nHeight; j++)
{
Node* pNode = getNode(i, j);
int clearance = 0;
if (pNode->getTileCollisionId() == 0)
{
clearance = 1;
bool bClear = true;
while (bClear)
{
// Expand down
if (j + clearance == m_nHeight)
{
bClear = false;
}
else
{
for (short di = i; bClear && di <= i + clearance && di < m_nWidth; di++)
{
Node* pNode = getNode(di, j + clearance);
if (pNode->getTileCollisionId() != 0)
{
bClear = false;
}
}
}
// Expand right
if (!bClear || i + clearance == m_nWidth)
{
bClear = false;
}
else
{
for (short dj = j; bClear && dj <= j + clearance && dj < m_nHeight; dj++)
{
Node* pNode = getNode(i + clearance, dj);
if (pNode->getTileCollisionId() != 0)
{
bClear = false;
}
}
if (bClear)
{
clearance++;
}
}
}
}
// Test pour vérifier concordance p/r au fichier
short oldClearance = pNode->getTileClearanceId(capability);
if (oldClearance != clearance)
{
cout << pNode->getX() << " " << pNode->getY() << " old clearance: " << oldClearance << "clearance: " << clearance << endl;
}
pNode->setTileClearanceId(clearance, capability);
}
}
}
void Map::findClusters()
{
// Create all clusters
setClusterSize(10, 10);
// Find entrances in each clusters
for (short i = 0; i < m_nNbClustersX; i++)
{
for (short j = 0; j < m_nNbClustersY; j++)
{
Cluster* pCluster = m_Clusters[i][j];
pCluster->findEntrances();
}
}
// Find transitions in each clusters
for (short i = 0; i < m_nNbClustersX; i++)
{
for (short j = 0; j < m_nNbClustersY; j++)
{
Cluster* pCluster = m_Clusters[i][j];
pCluster->findTransitions();
}
}
// Find edges in each clusters
for (short i = 0; i < m_nNbClustersX; i++)
{
for (short j = 0; j < m_nNbClustersY; j++)
{
Cluster* pCluster = m_Clusters[i][j];
pCluster->findEdges();
}
}
}
void Map::setClusterSize(short _nClusterWidth, short _nClusterHeight)
{
m_nClusterWidth = _nClusterWidth;
m_nClusterHeight = _nClusterHeight;
// TD HPA
m_nNbClustersX = (m_nWidth / _nClusterWidth) + (m_nWidth % _nClusterWidth > 0.f ? 1 : 0);
m_nNbClustersY = (m_nHeight / _nClusterHeight) + (m_nHeight % _nClusterHeight > 0.f ? 1 : 0);
m_Clusters = new Cluster**[m_nNbClustersX];
for (short i = 0; i < m_nNbClustersX; i++)
{
m_Clusters[i] = new Cluster*[m_nNbClustersY];
for (short j = 0; j < m_nNbClustersY; j++)
{
Cluster* pCluster = new Cluster();
pCluster->setPosition(i, j);
short iSize = (i == m_nNbClustersX - 1) ? m_nWidth % m_nClusterWidth : m_nClusterWidth;
short jSize = (j == m_nNbClustersY - 1) ? m_nHeight % m_nClusterHeight : m_nClusterHeight;
pCluster->setSize(iSize, jSize);
m_Clusters[i][j] = pCluster;
}
}
// Set Neighbors
for (short i = 0; i < m_nNbClustersX; i++)
{
for (short j = 0; j < m_nNbClustersY; j++)
{
if (j != 0)
{
m_Clusters[i][j]->addTopCluster(m_Clusters[i][j - 1]); // top node
}
if (i != m_nNbClustersX - 1)
{
m_Clusters[i][j]->addRightCluster(m_Clusters[i + 1][j]); // right node
}
if (j != m_nHeight - 1)
{
m_Clusters[i][j]->addBottomCluster(m_Clusters[i][j + 1]); // bottom node
}
if (i != 0)
{
m_Clusters[i][j]->addLeftCluster(m_Clusters[i - 1][j]); // left node
}
}
}
}
void Map::getClusterSize(short& _nClusterWidth, short& _nClusterHeight)
{
_nClusterWidth = m_nClusterWidth;
_nClusterHeight = m_nClusterHeight;
}
Node* Map::getNodeInCluster(Cluster* _pCluster, short _i, short _j)
{
short nX, nY;
_pCluster->getPosition(nX, nY);
return getNode(nX*m_nClusterWidth + _i, nY*m_nClusterHeight + _j);
}
Cluster* Map::getClusterFromNode(Node* _pNode)
{
return getCluster(_pNode->getX() / m_nClusterWidth, _pNode->getY() / m_nClusterHeight);
}
void Map::setSize(short _nWidth, short _nHeight)
{
clear();
m_nWidth = _nWidth;
m_nHeight = _nHeight;
m_Grid = new Node**[m_nWidth];
for (short i = 0; i < m_nWidth; i++)
{
m_Grid[i] = new Node*[m_nHeight];
for (short j = 0; j < m_nHeight; j++)
{
m_Grid[i][j] = new Node(i, j);
}
}
// Set Neighbors
for (short i = 0; i < m_nWidth; i++)
{
for (short j = 0; j < m_nHeight; j++)
{
if (j != 0)
{
m_Grid[i][j]->addChild(m_Grid[i][j - 1]); // top node
}
if (m_bIsGrid8 && j != 0 && i != m_nWidth - 1)
{
m_Grid[i][j]->addChild(m_Grid[i + 1][j - 1]); // top-right node
}
if (i != m_nWidth - 1)
{
m_Grid[i][j]->addChild(m_Grid[i + 1][j]); // right node
}
if (m_bIsGrid8 && i != m_nWidth - 1 && j != m_nHeight - 1)
{
m_Grid[i][j]->addChild(m_Grid[i + 1][j + 1]); // bottom-right node
}
if (j != m_nHeight - 1)
{
m_Grid[i][j]->addChild(m_Grid[i][j + 1]); // bottom node
}
if (m_bIsGrid8 && i != 0 && j != m_nHeight - 1)
{
m_Grid[i][j]->addChild(m_Grid[i - 1][j + 1]); // bottom-left node
}
if (i != 0)
{
m_Grid[i][j]->addChild(m_Grid[i - 1][j]); // left node
}
if (m_bIsGrid8 && i != 0 && j != 0)
{
m_Grid[i][j]->addChild(m_Grid[i - 1][j - 1]); // top-left node
}
}
}
}
TileSet* Map::getTileSet(short _gid)
{
TileSet* pTileSet = nullptr;
for (short i = 0; i < (short)m_TileSet.size(); i++)
{
pTileSet = m_TileSet[i];
if (_gid >= pTileSet->m_nFirstgid && _gid < pTileSet->m_nFirstgid + pTileSet->m_nTilecount)
{
return pTileSet;
}
}
return pTileSet;
}
Node* Map::getNodeAtPosition(Vector2f _v)
{
int i = (int)_v.getX() / m_nTileWidth;
int j = (int)_v.getY() / m_nTileHeight;
if (i >= 0 && i < m_nWidth && j >= 0 && j < m_nHeight)
return m_Grid[i][j];
else
return nullptr;
}
Vector2f Map::getNodePositionFromPixels(Vector2f _v)
{
int i = (int)_v.getX() / m_nTileWidth;
int j = (int)_v.getY() / m_nTileHeight;
if (i >= 0 && i < m_nWidth && j >= 0 && j < m_nHeight)
return Vector2f((float)i, (float)j);
else
return Vector2f(0.f, 0.f);
}
Vector2f Map::getPixelsFromNodePosition(Vector2f _v)
{
int i = (int)_v.getX() * m_nTileWidth;
int j = (int)_v.getY() * m_nTileHeight;
return Vector2f((float)i, (float)j);
}
void Map::updateTileIndexLimits()
{
// Camera/Window restriction
IntRect r = m_pGM->getWindowRect();
m_iMin = (int)r.getLeft() / m_nTileWidth;
m_iMax = (int)(r.getLeft() + r.getWidth()) / m_nTileWidth;
m_jMin = (int)r.getTop() / m_nTileHeight;
m_jMax = (int)(r.getTop() + r.getHeight()) / m_nTileHeight;
// Protection if map smaller than window
m_iMax = MIN(m_iMax, m_nWidth - 1);
m_jMax = MIN(m_jMax, m_nHeight - 1);
}
float Map::getFrictionAtPosition(Vector2f _v)
{
Node* pNode = getNodeAtPosition(_v);
if (pNode)
{
unsigned short nTerrain = pNode->getTileTerrainId() - 1;
unsigned short nQuad = getQuadAtPosition(_v);
return m_pTerrainTileSet->getFriction(nTerrain, nQuad);
}
else
{
return 0.0f; // No friction outside map...
}
}
unsigned short Map::getQuadAtPosition(Vector2f& _v)
{
float i = _v.getX() / m_nTileWidth;
float j = _v.getY() / m_nTileHeight;
float di = i - (int)i;
float dj = j - (int)j;
if (di < 0.5f && dj < 0.5f)
return 0;
else if (di >= 0.5f && dj < 0.5f)
return 1;
else if (di < 0.5f && dj >= 0.5f)
return 2;
else
return 3;
}
bool Map::update()
{
for (short i = 0; i < m_nWidth; i++)
{
for (short j = 0; j < m_nHeight; j++)
{
m_Grid[i][j]->update();
}
}
return true;
}
bool Map::draw()
{
int tileid = 0, w = 0, h = 0, x = 0, y = 0;
// Camera/Window restriction
IntRect r = m_pGM->getWindowRect();
int iMin = (int)r.getLeft() / m_nTileWidth;
int iMax = (int)(r.getLeft() + r.getWidth()) / m_nTileWidth;
int jMin = (int)r.getTop() / m_nTileHeight;
int jMax = (int)(r.getTop() + r.getHeight()) / m_nTileHeight;
// Protection if map smaller than window
iMax = MIN(iMax, m_nWidth - 1);
jMax = MIN(jMax, m_nHeight - 1);
TileSet* pTileSet = m_pTerrainTileSet;
for (short i = iMin; i <= iMax; i++)
{
Node** line = m_Grid[i];
for (short j = jMin; j <= jMax; j++)
{
Node* pNode = line[j];
tileid = pNode->getTileTerrainId(); // -1; // 30 -> 29
IntRect iRect = pTileSet->getTextureRect(tileid);
pTileSet->m_pSprite->setTextureRect(iRect.getLeft(), iRect.getTop(), iRect.getWidth(), iRect.getHeight());
pTileSet->m_pSprite->setPosition((float)i*pTileSet->m_nTilewidth, (float)(j + 1)*pTileSet->m_nTileheight);
pTileSet->m_pSprite->draw();
}
}
return true;
}
void Map::clear()
{
// Grid
for (short i = 0; i < m_nWidth; i++)
{
for (short j = 0; j < m_nHeight; j++)
{
delete m_Grid[i][j];
}
delete[] m_Grid[i];
}
delete[] m_Grid;
// Tilesets
TileSet* pTileSet = nullptr;
for (short i = 0; i < (short)m_TileSet.size(); i++)
{
pTileSet = m_TileSet[i];
delete pTileSet;
}
m_TileSet.clear();
m_pTerrainTileSet = nullptr;
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: DX9Facade.h
/* Description: DX9Facade
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Facade_H
#define _DX9Facade_H
#include "Graphics\IFacade.h"
namespace crea
{
class DX9Facade
{
D3DPRESENT_PARAMETERS m_d3dpp;
int m_iR, m_iG, m_iB;
LPCTSTR m_szWindowName;
// window
IntRect m_rWindowRect;
// Keyboard
bool m_abKeys[101];
// Mouse
int m_iMousePosX;
int m_iMousePosY;
bool m_bMouseLeftButtonDown;
bool m_bMouseRightButtonDown;
MSG msg;
private:
// Donn�es membres
DX9Facade();
HRESULT initD3D(HWND hWnd);
void keyDown(WPARAM _wParam, bool _bDown);
static LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
void setMousePosition(int _iX, int _iY) { m_iMousePosX = _iX; m_iMousePosY = _iY; }
void setMouseButtonsDown(bool _bLeftButtonDown, bool _bRightButtonDown) { m_bMouseLeftButtonDown = _bLeftButtonDown; m_bMouseRightButtonDown = _bRightButtonDown; }
void setMouseLButtonDown(bool _bLeftButtonDown) { m_bMouseLeftButtonDown = _bLeftButtonDown; }
void setMouseRButtonDown(bool _bRightButtonDown) { m_bMouseRightButtonDown = _bRightButtonDown; }
bool setCursor(bool _bVisible);
public:
~DX9Facade();
// Renvoie l'instance du renderer
static DX9Facade& Instance();
// Initialise le renderer
virtual void initialize();
// Boucle de rendu
virtual bool update();
// D�marre le rendu de la sc�ne
virtual void beginScene() const;
// Rendu d'un objet
virtual void draw(IDrawable& _o) const;
// Termine le rendu de la sc�ne
virtual void endScene() const;
// Quitte le renderer
virtual void quit();
virtual Font* createFont(Font* _pFrom = nullptr);
virtual void destroyFont(Font* _pFont);
virtual Texture* createTexture(Texture* _pFrom = nullptr);
virtual void destroyTexture(Texture* _pTexture);
virtual Color* createColor(Color* _pFrom = nullptr);
virtual void destroyColor(Color* _pColor);
virtual Text* createText(Text* _pFrom = nullptr);
virtual void destroyText(Text* _pText);
virtual Sprite* createSprite(Sprite* _pFrom = nullptr);
virtual void destroySprite(Sprite* _pSprite);
virtual Shape* createShape(string _szType, Shape* _pFrom = nullptr);
virtual void destroyShape(Shape* _pShape);
virtual Shader* createShader(Shader* _pFrom = nullptr);
virtual void destroyShader(Shader* _pShader);
virtual Material* createMaterial(Material* _pFrom = nullptr);
virtual void destroyMaterial(Material* _pMaterial);
virtual bool isKeyPressed(Key _key);
virtual bool isMouseButtonPressed(Button _button);
virtual Vector2f getMousePosition();
virtual IntRect& getWindowRect() { return m_rWindowRect; }
virtual void setWindowRect(IntRect _rect) { m_rWindowRect = _rect; }
LPDIRECT3DDEVICE9 m_pDevice;
LPDIRECT3D9 m_pD3D;
};
} // namespace crea
#endif // _DX9Facade_H
<file_sep>/***************************************************/
/* Nom: DX9Graphics.h
/* Description: DX9Graphics
/* Auteur: <NAME>
/***************************************************/
#ifndef _DX9Graphics_H
#define _DX9Graphics_H
#include "DX9Facade.h"
#include "Graphics\IGraphics.h"
#include "Graphics\Font.h"
#include "Graphics\Texture.h"
#include "Graphics\Text.h"
#include "Graphics\Sprite.h"
namespace crea
{
} // namespace crea
#endif // _DX9Graphics_H
<file_sep>/***************************************************/
/* Nom: Cells
/* Description: Cells est une application de test
/* du module d'IA développé à Creajeux
/* Il est basé sur le moteur CreaEngine qui utilise
/* le framework SFML.
/* Auteur: <NAME>
/***************************************************/
#include "stdafx.h"
#include "Core\GameManager.h"
#include "Core\SceneManager.h"
#include "Scene\SceneSteering.h"
#include "Scene\ScenePlanning.h"
#include "Scene\SceneMap.h"
#include "Scene\SceneGame.h"
using namespace crea;
int _tmain(int argc, _TCHAR* argv[])
{
GameManager* pGM = GameManager::getSingleton();
//pGM->setRendererType(Renderer_DX9);
//pGM->setRendererType(Renderer_SFML);
pGM->setRendererType(Renderer_GL3);
pGM->setWindowRect(IntRect(0, 0, 1152, 896));
pGM->setScene(new ScenePlanning());
pGM->init();
pGM->update();
pGM->quit();
return 0;
}
<file_sep>/***************************************************/
/* Nom: Plugin.h
/* Description: Plugin
/* Auteur: <NAME>
/***************************************************/
#ifndef _IPlugin_H
#define _IPlugin_H
#include <windows.h>
namespace crea
{
template <class T>
class Plugin
{
public:
//----------------------------------------------------------
// Constructeur par défaut
//----------------------------------------------------------
inline Plugin() :
m_Library(NULL)
{
}
//----------------------------------------------------------
// Destructeur
//----------------------------------------------------------
inline ~Plugin()
{
if (m_Library)
FreeLibrary(m_Library);
}
//----------------------------------------------------------
// Charge la DLL et récupère un pointeur sur l'objet
//----------------------------------------------------------
T* Load(const std::string& Filename)
{
// Chargement de la bibliothèque dynamique
m_Library = LoadLibrary(Filename.c_str());
if (!m_Library)
{
cerr << "Cannot load library " << Filename.c_str() << endl;
}
assert(m_Library); // Impossible de charger la bibliothèque dynamique
// Récupération de la fonction
PtrFunc Function = reinterpret_cast<PtrFunc>(GetProcAddress(m_Library, "StartPlugin"));
assert(Function); // Impossible de trouver la fonction 'StartPlugin'
return Function();
}
private:
//----------------------------------------------------------
// Types
//----------------------------------------------------------
typedef T* (*PtrFunc)();
//----------------------------------------------------------
// Données membres
//----------------------------------------------------------
HMODULE m_Library; // Handle de la DLL
};
} // namespace crea
#endif // _IPlugin_H<file_sep>#include "stdafx.h"
#include "Core\Component.h"
namespace crea
{
Component::Component()
{
}
Component::~Component()
{
}
} // namespace crea
<file_sep>// Definitions
#ifndef MAPSEARCHNODE_H
#define MAPSEARCHNODE_H
#include "AStarSearch.h"
namespace crea
{
class CREAENGINE_API MapSearchNode
{
public:
unsigned int x; // the (x,y) positions of the node
unsigned int y;
MapSearchNode(int _x = 0, int _y = 0) { x = _x; y = _y; }
//~MapSearchNode() { } // CB: do not surdefine dest as it crashes with templates (why?)
float GoalDistanceEstimate(MapSearchNode &nodeGoal);
bool IsGoal(MapSearchNode &nodeGoal);
bool GetSuccessors(AStarSearch<MapSearchNode> *astarsearch, MapSearchNode *parent_node);
float GetCost(MapSearchNode &successor);
bool IsSameState(MapSearchNode &rhs);
};
}
#endif<file_sep>#include "stdafx.h"
#include "AI\Pathfinding\Cluster.h"
namespace crea
{
Cluster::Cluster()
{
m_pTopCluster = nullptr;
m_pBottomCluster = nullptr;
m_pLeftCluster = nullptr;
m_pRightCluster = nullptr;
m_pEntrances = new vector<Entrance*>();
m_pTransitions = new vector<Transition*>();
m_pEdges = new vector<Edge*>();
}
Cluster::~Cluster()
{
for (size_t e = 0; e < m_pEntrances->size(); e++)
{
Entrance* pEntrance = (*m_pEntrances)[e];
delete pEntrance;
}
delete m_pEntrances;
for (size_t t = 0; t < m_pTransitions->size(); t++)
{
Transition* pTransition = (*m_pTransitions)[t];
delete pTransition;
}
delete m_pEntrances;
for (size_t e = 0; e < m_pEdges->size(); e++)
{
Edge* pEdge = (*m_pEdges)[e];
delete pEdge;
}
delete m_pEdges;
}
bool Cluster::update()
{
return true;
}
bool Cluster::draw()
{
return true;
}
void Cluster::clear()
{
}
void Cluster::findEntrances()
{
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
short nWidth, nHeigth;
// Top line
Entrance* pEntrance = nullptr;
Entrance* pEntranceSymm = nullptr;
if (m_pTopCluster)
{
short j = 0;
// E appartient à la bordure de c1 et c2
for (int i = 0; i < m_nClusterWidth; i++)
{
m_pTopCluster->getSize(nWidth, nHeigth);
// E appartient à c1, symm(E) appartient à c2
Node* pNode1 = pMap->getNodeInCluster(this, i, j);
Node* pNode2 = pMap->getNodeInCluster(m_pTopCluster, i, nHeigth - 1);
// E n'a pas d'obstacles
if (pNode1->getTileCollisionId() == 0 && pNode2->getTileCollisionId() == 0)
{
// E s'étend des 2 côtés
if (!pEntrance)
{
// Start entrance
pEntrance = new Entrance;
pEntrance->m_pStart = pNode1;
pEntrance->m_pEnd = pNode1;
m_pEntrances->push_back(pEntrance);
// Set symmetric
pEntranceSymm = new Entrance;
pEntranceSymm->m_pStart = pNode2;
pEntranceSymm->m_pEnd = pNode2;
m_pTopCluster->m_pEntrances->push_back(pEntranceSymm);
pEntrance->m_pSymm = pEntranceSymm;
pEntranceSymm->m_pSymm = pEntrance;
}
else
{
pEntrance->m_pEnd = pNode1;
pEntranceSymm->m_pEnd = pNode2;
}
}
else
{
pEntrance = nullptr;
pEntranceSymm = nullptr;
}
}
}
// Left line
pEntrance = nullptr;
pEntranceSymm = nullptr;
if (m_pLeftCluster)
{
short i = 0;
// E appartient à la bordure de c1 et c2
for (int j = 0; j < m_nClusterHeight; j++)
{
m_pLeftCluster->getSize(nWidth, nHeigth);
// E appartient à c1, symm(E) appartient à c2
Node* pNode1 = pMap->getNodeInCluster(this, i, j);
Node* pNode2 = pMap->getNodeInCluster(m_pLeftCluster, nWidth - 1, j);
// E n'a pas d'obstacles
if (pNode1->getTileCollisionId() == 0 && pNode2->getTileCollisionId() == 0)
{
// E s'étend des 2 côtés
if (!pEntrance)
{
// Start entrance
pEntrance = new Entrance;
pEntrance->m_pStart = pNode1;
pEntrance->m_pEnd = pNode1;
m_pEntrances->push_back(pEntrance);
// Set symmetric
pEntranceSymm = new Entrance;
pEntranceSymm->m_pStart = pNode2;
pEntranceSymm->m_pEnd = pNode2;
m_pLeftCluster->m_pEntrances->push_back(pEntranceSymm);
pEntrance->m_pSymm = pEntranceSymm;
pEntranceSymm->m_pSymm = pEntrance;
}
else
{
pEntrance->m_pEnd = pNode1;
pEntranceSymm->m_pEnd = pNode2;
}
}
else
{
pEntrance = nullptr;
pEntranceSymm = nullptr;
}
}
}
}
void Cluster::findTransitions()
{
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
for (size_t e = 0; e < m_pEntrances->size(); e++)
{
Entrance* pEntrance = (*m_pEntrances)[e];
double distance = pEntrance->m_pStart->getDistance(pEntrance->m_pEnd);
if (distance < 5.0) // < 6 tiles means < 5 in distance
{
Transition* t = new Transition;
t->m_pStart = pMap->getNode(
(short)((pEntrance->m_pEnd->getX() + pEntrance->m_pStart->getX()) * 0.5f),
(short)((pEntrance->m_pEnd->getY() + pEntrance->m_pStart->getY()) * 0.5f));
t->m_pEnd = pMap->getNode(
(short)((pEntrance->m_pSymm->m_pEnd->getX() + pEntrance->m_pSymm->m_pStart->getX()) * 0.5f),
(short)((pEntrance->m_pSymm->m_pEnd->getY() + pEntrance->m_pSymm->m_pStart->getY()) * 0.5f));
t->m_pEdge = new Edge;
t->m_pEdge->m_pStart = t->m_pStart;
t->m_pEdge->m_pEnd = t->m_pEnd;
t->m_pEdge->m_fDistance = 1.0f;
m_pTransitions->push_back(t);
}
else
{
Transition* t1 = new Transition;
t1->m_pStart = pEntrance->m_pStart;
t1->m_pEnd = pEntrance->m_pSymm->m_pStart;
t1->m_pEdge = new Edge;
t1->m_pEdge->m_pStart = t1->m_pStart;
t1->m_pEdge->m_pEnd = t1->m_pEnd;
t1->m_pEdge->m_fDistance = 1.0f;
m_pTransitions->push_back(t1);
Transition* t2 = new Transition;
t2->m_pStart = pEntrance->m_pEnd;
t2->m_pEnd = pEntrance->m_pSymm->m_pEnd;
t2->m_pEdge = new Edge;
t2->m_pEdge->m_pStart = t2->m_pStart;
t2->m_pEdge->m_pEnd = t2->m_pEnd;
t2->m_pEdge->m_fDistance = 1.0f;
m_pTransitions->push_back(t2);
}
}
}
void Cluster::findEdges(bool _bidirectional)
{
GameManager* pGM = GameManager::getSingleton();
ClusterSearchManager* pClusterSearchManager = ClusterSearchManager::getSingleton();
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
pClusterSearchManager->setCurrentMap(pMap);
ClusterSearch* pClusterSearch = pGM->getClusterSearch("Cluster::findEdges");
for (unsigned int t1 = 0; t1 < m_pTransitions->size(); t1++)
{
Transition* pTransition1 = (*m_pTransitions)[t1];
for (unsigned int t2 = t1 + 1; t2 < m_pTransitions->size(); t2++)
{
Transition* pTransition2 = (*m_pTransitions)[t2];
bool bEdgeOnSameNode = false;
bool bEdgeAlreadyFound = false;
// Make sure Edges not Starting on same node
if (pTransition1->m_pStart == pTransition2->m_pStart)
{
bEdgeOnSameNode = true;
}
else
{
// Make sure Edge not already found
for (unsigned int e = 0; e < m_pEdges->size() && !bEdgeAlreadyFound; e++)
{
Edge* pEdge = (*m_pEdges)[e];
if (pEdge->m_pStart == pTransition1->m_pStart
&& pEdge->m_pEnd == pTransition2->m_pStart)
{
bEdgeAlreadyFound = true;
}
}
}
if (!bEdgeOnSameNode && !bEdgeAlreadyFound)
{
// Edge from transition start to others transition start in cluster
Node* p1 = pTransition1->m_pStart;
Node* p2 = pTransition2->m_pStart;
unsigned int count = 1;
while ((!_bidirectional && count <= 1) || (_bidirectional && count <= 2)) // For bidirectional transitions or not
{
count++;
// Pathfinding in cluster!
pClusterSearchManager->setCurrentCluster(this);
ClusterSearch::SearchState s;
pClusterSearch->setStartAndGoal(
Vector2f(p1->getX(), p1->getY()),
Vector2f(p2->getX(), p2->getY()),
false // not from pixels as we already have indexes!
);
do
{
s = pClusterSearch->update();
} while (s == MapSearch::SEARCH_STATE_SEARCHING);
if (s == MapSearch::SEARCH_STATE_SUCCEEDED)
{
Edge* pIntraEdge = new Edge;
pIntraEdge->m_pStart = p1;
pIntraEdge->m_pEnd = p2;
pIntraEdge->m_fDistance = pClusterSearch->getSolutionLength(); // result of pathfinding!
m_pEdges->push_back(pIntraEdge);
// Debug
cout << "Cluster: " << this->m_nX << ", " << this->m_nY
<< " Start: " << pIntraEdge->m_pStart->getX() << ", " << pIntraEdge->m_pStart->getY()
<< " end: " << pIntraEdge->m_pEnd->getX() << ", " << pIntraEdge->m_pEnd->getY()
<< " distance: " << pIntraEdge->m_fDistance << endl;
}
if (_bidirectional)
{
p1 = pTransition2->m_pStart;
p2 = pTransition1->m_pStart;
}
}
}
}
}
}
bool Cluster::isInCluster(short _i, short _j)
{
short dx = m_pLeftCluster ? _i - m_nX * m_pLeftCluster->m_nClusterWidth : _i - m_nX * m_nClusterWidth;
short dy = m_pTopCluster ? _j - m_nY * m_pTopCluster->m_nClusterHeight : _j - m_nY * m_nClusterHeight;
return (dx >= 0 && dx < m_nClusterWidth && dy >= 0 && dy < m_nClusterHeight);
}
// Online search
bool Cluster::getEdgesFromNode(Node* _pNode, vector<Edge*>& _edges)
{
GameManager* pGM = GameManager::getSingleton();
ClusterSearchManager* pClusterSearchManager = ClusterSearchManager::getSingleton();
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
bool bNodeOnTransition = false;
// Find node on transitions (inter-edge)
for (unsigned int t1 = 0; t1 < m_pTransitions->size(); t1++)
{
Transition* pTransition1 = (*m_pTransitions)[t1];
if (pTransition1->m_pStart == _pNode)
{
// Return precomputed intra-edges and inter-edge
_edges.push_back(pTransition1->m_pEdge);
bNodeOnTransition = true;
}
}
if (bNodeOnTransition)
{
// Find node on edges (intra-edge)
for (unsigned int e1 = 0; e1 < m_pEdges->size(); e1++)
{
Edge* pEdge = (*m_pEdges)[e1];
if (pEdge->m_pStart == _pNode)
{
// Return precomputed intra-edges and inter-edge
_edges.push_back(pEdge);
}
}
}
else
{
ClusterSearch* pClusterSearch = pGM->getClusterSearch("Cluster::findEdges");
// Find new edges (Start or Goal)
for (unsigned int t1 = 0; t1 < m_pTransitions->size(); t1++)
{
Transition* pTransition1 = (*m_pTransitions)[t1];
// Pathfinding in cluster!
pClusterSearchManager->setCurrentCluster(this);
ClusterSearch::SearchState s;
pClusterSearch->setStartAndGoal(
Vector2f(_pNode->getX(), _pNode->getY()),
Vector2f(pTransition1->m_pStart->getX(), pTransition1->m_pStart->getY()),
false // not from pixels as we already have indexes!
);
do
{
s = pClusterSearch->update();
} while (s == MapSearch::SEARCH_STATE_SEARCHING);
if (s == MapSearch::SEARCH_STATE_SUCCEEDED)
{
Edge* pIntraEdge = new Edge;
pIntraEdge->m_pStart = _pNode;
pIntraEdge->m_pEnd = pTransition1->m_pStart;
pIntraEdge->m_fDistance = pClusterSearch->getSolutionLength(); // result of pathfinding!
_edges.push_back(pIntraEdge);
// Debug
cout << "Cluster: " << this->m_nX << ", " << this->m_nY
<< " Start: " << pIntraEdge->m_pStart->getX() << ", " << pIntraEdge->m_pStart->getY()
<< " end: " << pIntraEdge->m_pEnd->getX() << ", " << pIntraEdge->m_pEnd->getY()
<< " distance: " << pIntraEdge->m_fDistance << endl;
}
}
}
return true;
}
} // namespace crea
<file_sep>/***************************************************/
/* Nom: Texture.h
/* Description: Texture
/* Auteur: <NAME>
/***************************************************/
#ifndef __Texture_H
#define __Texture_H
namespace crea
{
class CREAENGINE_API Texture
{
public:
Texture() {}
virtual ~Texture() {}
virtual inline void setTransparency(bool _transparency) { }
virtual inline bool getTransparency() { return false; }
virtual bool loadFromFile(const string& _file) { return false; }
virtual void bind(unsigned int _channel) {}
virtual void unbind(unsigned int _channel) {}
};
} // namespace crea
#endif // __Texture_H<file_sep>#include "stdafx.h"
#include "Scripts\FSMBalistaGoTo.h"
#include "Scripts\Messages.h"
#include <string.h>
FSMBalistaGoTo::FSMBalistaGoTo(Vector2f _vTarget) : m_vTarget(_vTarget)
{
m_pPathNodeShape = new RectangleShape;
Color* pBlueTransparent = m_pGM->getColor("BlueTransparent");
pBlueTransparent->setValues(0, 0, 255, 125);
m_pPathNodeShape->setColor(pBlueTransparent);
m_pPathNodeShape->setSize(10, 10);
m_pPathNodeShape->setOrigin(5, 5);
m_pPathNodeShapeOpen = new RectangleShape;
Color* pGreenTransparent = m_pGM->getColor("GreenTransparent");
pGreenTransparent->setValues(0, 255, 0, 125);
m_pPathNodeShapeOpen->setColor(pGreenTransparent);
m_pPathNodeShapeOpen->setSize(32, 32);
}
FSMBalistaGoTo::~FSMBalistaGoTo()
{
for (short i = 0; i < (short)m_vPath.size(); i++)
{
delete m_vPath[i];
}
m_vPath.clear();
delete m_pPathNodeShape;
delete m_pPathNodeShapeOpen;
}
bool FSMBalistaGoTo::States(StateMachineEvent _event, Msg* _msg, int _state)
{
BeginStateMachine
//OnMsg(MSG_Teleport)
//SetState(STATE_CompletedPath);
/////////////////////////////////////////////////////////////////
State(STATE_Init)
OnEnter
// Get Entity
m_pEntity = getEntity();
// Get CharacterController
m_pCharacterController = m_pEntity->getComponent<CharacterController>();
// A*
m_pMapSearch = m_pGM->getMapSearch("FSMBalistaGoTo");
// Get Agent
m_pAgent = m_pEntity->getComponent<Agent>();
// Set current agent for AA*
m_pMapSearch->setCurrentAgent(m_pAgent);
OnUpdate
SetState(STATE_SearchPath);
/////////////////////////////////////////////////////////////////
State(STATE_SearchPath)
OnEnter
Map* pMap = MapSearchManager::getSingleton()->getCurrentMap();
// Reduce to a size 1 for start position (middle of upper-left node)
Vector2f start = m_pEntity->getPosition() - Vector2f(16.f, 16.f);
// Handle target on a size 1 tile
Vector2f goal = m_vTarget;
Node* pNode = pMap->getNodeAtPosition(goal);
if (!pNode)
{
SetState(STATE_SearchFailed);
}
else
{
Node* pRight = pMap->getNode(pNode->getX() + 1, pNode->getY());
Node* pDown = pMap->getNode(pNode->getX(), pNode->getY() + 1);
if (!pRight || pRight->getTileCollisionId() == 9)
{
goal -= Vector2f(32.f, 0.f);
}
if (!pDown || pDown->getTileCollisionId() == 9)
{
goal -= Vector2f(0.f, 32.f);
}
m_pMapSearch->setStartAndGoal(start, goal);
m_pCharacterController->move(Vector2f(0.f, 0.f));
}
OnUpdate
MapSearch::SearchState s = m_pMapSearch->update();
m_pMapSearch->getOpenList(m_vOpenList);
m_bHasOpenList = true;
if (s == MapSearch::SEARCH_STATE_SUCCEEDED)
{
SetState(STATE_FollowPath);
}
else if (s == MapSearch::SEARCH_STATE_FAILED)
{
SetState(STATE_SearchFailed);
}
OnExit
/////////////////////////////////////////////////////////////////
State(STATE_FollowPath)
OnEnter
m_pMapSearch->getSolution(m_vPath);
m_bHasPath = true;
for (VectorVector2f::iterator it = m_vPath.begin(); it != m_vPath.end(); ++it)
{
**it += Vector2f(32.f, 32.f); // Visual offset (top left to center)
}
m_pCharacterController->followPath(m_vPath);
OnUpdate
if (!m_pCharacterController->isFollowingPath())
{
SetState(STATE_CompletedPath);
}
OnExit
m_pCharacterController->move(Vector2f(0.f, 0.f));
m_bHasPath = false;
/////////////////////////////////////////////////////////////////
State(STATE_SearchFailed)
OnEnter
OnUpdate
OnExit
/////////////////////////////////////////////////////////////////
State(STATE_CompletedPath)
OnEnter
OnUpdate
OnExit
EndStateMachine
}
bool FSMBalistaGoTo::draw()
{
if (m_bHasPath)
{
for (VectorVector2f::iterator it = m_vPath.begin(); it != m_vPath.end(); ++it)
{
Vector2f p = **it;
m_pPathNodeShape->setPosition((float)p.getX(), (float)p.getY());
m_pPathNodeShape->draw();
}
}
else if (m_bHasOpenList)
{
for (VectorVector2f::iterator it = m_vOpenList.begin(); it != m_vOpenList.end(); ++it)
{
Vector2f p = **it;
m_pPathNodeShapeOpen->setPosition((float)p.getX(), (float)p.getY());
m_pPathNodeShapeOpen->draw();
}
m_bHasOpenList = false;
}
return true;
}<file_sep>/***************************************************/
/* Nom: SFMLShape.h
/* Description: SFMLShape
/* Auteur: <NAME>
/***************************************************/
#ifndef _SFMLShape_H
#define _SFMLShape_H
#include "Graphics\Shape.h"
#include <SFML/Graphics.hpp>
namespace crea
{
class SFMLShape : public Shape
{
public:
sf::Shape* m_pShape;
SFMLShape() { m_pShape = nullptr; }
virtual ~SFMLShape() { }
virtual void draw()
{
sf::RenderWindow* pWin = SFMLFacade::Instance().m_pWindow;
pWin->draw(*m_pShape);
}
virtual void setColor(Color* _pColor)
{
m_pShape->setFillColor(((SFMLColor*)_pColor)->getColor());
}
virtual void setOutlineColor(Color* _pColor)
{
m_pShape->setOutlineColor(((SFMLColor*)_pColor)->getColor());
}
virtual void setOutlineThickness(float _fPixels)
{
m_pShape->setOutlineThickness(_fPixels);
}
virtual void setPosition(float _x, float _y)
{
m_pShape->setPosition(_x, _y);
}
virtual void setRotation(float _angle)
{
m_pShape->setRotation(_angle);
}
virtual void setScale(float _x, float _y)
{
m_pShape->setScale(_x, _y);
}
virtual void setOrigin(float _x, float _y)
{
m_pShape->setOrigin(_x, _y);
}
};
class SFMLRectangleShape : public SFMLShape
{
public:
SFMLRectangleShape()
{
m_pShape = new sf::RectangleShape;
}
~SFMLRectangleShape()
{
delete m_pShape;
}
virtual void setSize(float _x, float _y)
{
((sf::RectangleShape*)m_pShape)->setSize(sf::Vector2f(_x, _y));
}
};
class SFMLCircleShape : public SFMLShape
{
public:
SFMLCircleShape()
{
m_pShape = new sf::CircleShape;
}
~SFMLCircleShape()
{
delete m_pShape;
}
virtual void setRadius(float _r)
{
((sf::CircleShape*)m_pShape)->setRadius(_r);
}
};
class SFMLArrowShape : public SFMLShape
{
public:
SFMLArrowShape()
{
sf::ConvexShape* pArrow = new sf::ConvexShape(3);
pArrow->setPoint(0, sf::Vector2f(0.0f, 0.0f));
pArrow->setPoint(1, sf::Vector2f(0.0f, 1.0f));
pArrow->setPoint(2, sf::Vector2f(1.0f, 0.5f));
m_pShape = pArrow;
}
~SFMLArrowShape()
{
delete m_pShape;
}
virtual void setSize(float _x, float _y)
{
m_pShape->setScale(sf::Vector2f(_x, _y));
}
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd)
{
float dx = _xEnd - _xStart;
float dy = _yEnd - _yStart;
Vector2f v(dx, dy);
Vector2f right(1.0f, 0.f);
float fAngle = right.angle(v)*180/3.14f;
fAngle = dy > 0.f ? fAngle : -fAngle;
sf::ConvexShape* pArrow = (sf::ConvexShape*) m_pShape;
pArrow->setPosition(_xStart, _yStart);
sf::Vector2f scale = pArrow->getScale();
scale.x = v.length();
pArrow->setScale(scale);
pArrow->setOrigin(0.0f, 0.5f);
pArrow->setRotation(fAngle);
}
};
class SFMLLineShape : public SFMLShape
{
public:
SFMLLineShape()
{
m_pShape = new sf::RectangleShape;
setSize(1, 1);
}
~SFMLLineShape()
{
delete m_pShape;
}
virtual void setSize(float _x, float _y)
{
((sf::RectangleShape*)m_pShape)->setSize(sf::Vector2f(_x, _y));
}
virtual void setStartAndEnd(float _xStart, float _yStart, float _xEnd, float _yEnd)
{
float dx = _xEnd - _xStart;
float dy = _yEnd - _yStart;
Vector2f v(dx, dy);
Vector2f right(1.0f, 0.f);
float fAngle = right.angle(v) * 180 / 3.14f;
fAngle = dy > 0.f ? fAngle : -fAngle;
sf::ConvexShape* pArrow = (sf::ConvexShape*) m_pShape;
pArrow->setPosition(_xStart, _yStart);
sf::Vector2f scale = pArrow->getScale();
scale.x = v.length();
pArrow->setScale(scale);
pArrow->setRotation(fAngle);
}
};
} // namespace crea
#endif // _SFMLShape_H<file_sep>/***************************************************/
/* Nom: MapSearchManager.h
/* Description: MapSearchManager
/* Auteur: <NAME>
/***************************************************/
#ifndef __MapSearchManager_H__
#define __MapSearchManager_H__
#include "Core\Singleton.h"
#include "AI\Pathfinding\MapSearch.h"
#include "AI\Pathfinding\MapSearchNode.h"
namespace crea
{
class CREAENGINE_API MapStringMapSearch : public map<string, MapSearch*> {};
class CREAENGINE_API MapSearchManager : public Singleton <MapSearchManager>
{
public:
MapSearchManager();
~MapSearchManager();
MapSearch* getMapSearch(string _szName);
// A*
Map* getCurrentMap() { return m_pCurrentMap; }
void setCurrentMap(Map* _pCurrentMap) { m_pCurrentMap = _pCurrentMap; }
private:
MapStringMapSearch m_MapSearches;
Map* m_pCurrentMap;
};
}
#endif // __MapSearchManager_H__ | 26d8503d36699b800ecf8743b08f46806d763988 | [
"Markdown",
"C",
"Text",
"C++"
] | 178 | C++ | ColinBruneau/AI-Project | 036e86d82fc689a9744acf4c284749ea82ba34f9 | b72bdaf041cbad6e90b45407273eb53818bf673e |
refs/heads/master | <file_sep> addEventListener("click", function(event) {
if (Math.random() < 0.5) {
var star = document.createElement("div");
star.className = "star";
star.style.left = (event.pageX - 4) + "px";
star.style.top = (event.pageY - 4) + "px";
document.body.appendChild(star);
}
else {
var star2 = document.createElement("span");
star2.className = "star2";
star2.style.left = (event.pageX - 4) + "px";
star2.style.top = (event.pageY - 4) + "px";
document.body.appendChild(star2);
}
});<file_sep>var gulp = require('gulp'),
browserSync = require('browser-sync'),
uglify = require('gulp-uglify'), // Минификация JS
csso = require('gulp-csso'), // Минификация CSS
imagemin = require('gulp-imagemin'); // Минификация изображений
gulp.task('browser-sync', function () {
var files = [
'./**/*.html',
'./css/**/*.css',
'./images/**/*' ,
'./js/**/*.js'
];
browserSync.init(files, {
server: {
baseDir: './'
}
});
});
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
gulp.task('sass', function () {
return gulp.src('./sass/**/*.sass')
.pipe(plumber({ errorHandler: notify.onError("Error in styles: <%= error.message %>") }))
.pipe(sass())
.pipe(csso()) // минифицируем css, полученный на предыдущем шаге
.pipe(gulp.dest('./css'));
});
gulp.task('images', function() {
gulp.src('./images/**/*') // берем любые файлы в папке и ее подпапках
.pipe(imagemin()) // оптимизируем изображения для веба
.pipe(gulp.dest('./images-optimize//')) // результат пишем по указанному адресу
});
gulp.task('watch', function () {
gulp.watch('./sass/**/*.sass', ['sass']);
});
gulp.task('default', ['browser-sync', 'watch']);
function asd(asd) {
return asd.length;
} | ec1fd6d82c02d1aa6db09ea71343c495b0609d23 | [
"JavaScript"
] | 2 | JavaScript | GrishaZel/grishazel.github.io | 95bcf218b059cd8fc019b133099967b3366edfc0 | d5541ff6c69102e1a8a56085a9a0559d77de014e |
refs/heads/master | <repo_name>aashnisshah/extrendsions<file_sep>/popup.js
var settings = {
base_url: 'http://api.whatthetrend.com/api/v2/trends.json',
twitter_base_url: 'https://twitter.com/hashtag/',
twitter_base_url_end: '?src=tren'
}
document.addEventListener('DOMContentLoaded', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.whatthetrend.com/api/v2/trends/locations/top.json?place_type_code=12');
xhr.send();
xhr.onload = function() {
var json = xhr.responseText; // Response
json = json.replace(/^[^(]*\(([\S\s]+)\);?$/, '$1'); // Turn JSONP in JSON
json = JSON.parse(json); // Parse JSON
// process the data and display the information
var selected_trend = process(json);
display(selected_trend);
};
});
/* this function will randomly select one of the trends and
* return that trend to the html page
*/
function process(json) {
// get size
var num_trends = json.trends.length;
// select random number
var selected_num = Math.floor(Math.random() * (num_trends));
// return trend
return json.trends[selected_num] || null;
}
/* this function will display the trend information onto the
* html page
*/
function display(trend) {
if(trend) {
var trendName = document.getElementById('trend-name');
trendName.innerText = trend.name;
if(trend.description) {
var trendDescription = document.getElementById('trend-description');
trendDescription.innerText = trend.description.text;
} else {
var trendDescription = document.getElementById('trend-description');
trendDescription.innerText = 'There is no description for this trend yet';
}
if(trend.place_name) {
var trendLocation = document.getElementById('trend-location');
trendLocation.innerText = 'This trend comes from ' + trend.place_name;
} else {
var trendLocation = document.getElementById('trend-description');
trendLocation.innerText = 'There is no location associated to this trend';
}
var trendTweets = document.getElementById('trend-tweets');
trendTweets.innerHTML = 'Search for ' + trend.name + ' on Twitter';
// need to remove the # from the start of the tweet or the search
// link will break
var trendNoHashtag = trend.name.substring(0,1) == '#' ?
trend.name.substring(1,trend.name.length) :
trend.name;
trendTweets.href = settings.twitter_base_url +
trendNoHashtag +
settings.twitter_base_url_end;
} else {
var trendName = document.getElementById('trend-name');
trendName.innerText = 'Error trying to load trending topics. Please try again.';
}
}
/* this eventListener allows us to create a new tab when we click on
* a link in a chrome extension
*/
window.addEventListener('click',function(e){
if(e.target.href!==undefined){
chrome.tabs.create({url:e.target.href})
}
})
<file_sep>/README.md
# extrendsions
A chrome extension showing the latest trends, with some information on why they are trends
This is a simple chrome plugin that displays a randomly selected top trend, then displays that information. The trends are pulled from the WhatTheTrend api, which gets them from Twitter's API. It currently pulls in the top trends from all over the world, and where possible, will include a description on why that trend is trending.
##How to Use the Plugin
1. Download this project
2. Visit chrome://extensions in your Chrome browser
3. Ensure **Developer Mode** is checked
4. Click on **Load unpacked extension..**
5. Navigate to where these files are on your computer and select them
6. Click on the icon and stay up to date with all your trends!
##Shout out to:
1. WhatTheTrend for the trend API: http://www.whatthetrend.com/api
2. Downloadicons for the trend icon: http://downloadicons.net/trends-icon-65367 | d5418a01a5ddc84bba978a15db206c61798c17ab | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | aashnisshah/extrendsions | ecab0d7203413b03940fc3b08d8fe7d17cf1519b | 700537d1e3aec3724776588ee900da023028f018 |
refs/heads/master | <repo_name>kittpa/fufezan-lab-advanced_python_2020-21_HD<file_sep>/Exercises/Ex_02/homework_paulkittner_02.py
import argparse
import plotly.io as pio
pio.renderers.default = "browser"
import csv
from collections import deque
import pandas as pd
import requests
import plotly.graph_objects as go
import re
class Protein_attributions():
"""
A cool class containting all the functions need to solve this problem
"""
def __init__(self, entry_identifier):
self.entry_identifier = entry_identifier
self.protein_name = None
self.seq = None
self.hydro_dict = None
def get_sequence(self):
'''
A function get the sequence of the given Protein from uniport via its unique identity code.
If will pull the fasta file from uniport and save as is, as a .csv file
It will proceed to open the file and extract the protein sequence within in the fasta file,
along with its name.
:param entry_identifier: the identity code of the protein you would like to analyse
(the specific position in the uniport databank)
:param protein_name: The name of the protein you want to analyse
:return:
seq: The sequence of the protein
'''
url = 'https://www.uniprot.org/uniprot/' + self.entry_identifier + '.fasta?fil=reviewed:yes'
r = requests.get(url)
seq = ""
seq_list = []
protein_csv = '../data/' + self.entry_identifier + '.fasta'
with open(protein_csv, 'wb') as file:
file.write(r.content)
file.close()
with open(protein_csv) as file:
file_dict = csv.reader(file, delimiter="\n")
for line in file_dict:
if ">" not in line[0]:
seq = seq + line[0]
else:
protein_name = re.search('HUMAN(.+?)OS=', str(line))
if protein_name:
self.protein_name = (protein_name.group(1))
seq_list.append(seq)
seq = ""
self.seq = seq
return seq
def get_hydropathy_dict(self, file):
"""
This will load the hyrdopathy csv file.
It will pull the amino acid names alond with their pi value
and zip them together in a dict.
:param file: file location of the csv containing all the protein attributes
:return: returns a dic with aa_names and aa_pi_value pairs
"""
df = pd.read_csv(file)
aa_names = df['1-letter code'].tolist()
aa_pi_values = df['hydropathy index (Kyte-Doolittle method)'].to_numpy()
hydropathy = dict(zip(aa_names, aa_pi_values))
self.hydro_dict = hydropathy
print(hydropathy)
return hydropathy
def calc_hydro_avg(self, window_length):
'''
will smoothen the hydro values, by caluclating
the average of hydro values over a given window_length
:param seq: The sequence of the selected protein
:param hyrdo_dict: dictonary with the aas single letter names and their corresponing hydropathy
:param window_length: The length the stride should look at the as
:return:
avg_hydro: average hydropathy for every AS at their position
'''
avg_hydro = []
window_entries = deque([], window_length)
print(self.seq)
for aminoacid in self.seq:
hydropathy_value = self.hydro_dict[aminoacid]
window_entries.append(hydropathy_value)
avg_hydro.append(sum(window_entries) /len(window_entries))
print(avg_hydro)
return avg_hydro
def plot_hydro_avg(self, hydro_avg, window_length):
'''
This function will make a nice plot out of the protein hydrop.
With beeing the hyrdop. and x the location of the aa in the protein
:param sequence: The sequence of the selected protein
:param hydro_avg: average hydropathy for every AS at their position
:param window_length: The length the stride should look at the as
:return: the bar plot
'''
data = []
data.append(
go.Bar(
x = list(range(len(self.seq))),
y = hydro_avg
)
)
fig = go.Figure(data=data)
title = self.protein_name + ' average amino acid hydropathy over ' + str(window_length) + ' aas'
fig.update_layout(
title_text=title,
title_x=0.5,
title_font_size=42,
font_size=18)
fig.update_layout(
xaxis_title="Position in the sequence",
yaxis_title="Hydropathy",
)
fig.update_layout(template='plotly_dark')
fig.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--entry_identifier", help="The identity of the Protein (position in uniport ds)", type=str, default="NaN", required=True)
parser.add_argument("--protein_name", help="Name of the protein", type=str, default="NaN", required=True)
parser.add_argument("--window_length", help="Length of the sliding window.", type=int, required=True)
parser.add_argument("--directory_aa_prop", help="where is the file @ bro?",type=str, required=True)
args = parser.parse_args()
as_prop = args.directory_aa_prop
entry_identifier = args.entry_identifier
window_length = args.window_length
# protein_name = args.protein_name
p1 = Protein_attributions("P32249")
dict_aa_prop = p1.get_hydropathy_dict(as_prop)
hydro_avg = p1.calc_hydro_avg(window_length)
p1.plot_hydro_avg(hydro_avg, window_length)
# python homework_paulkittner_02.py --entry_identifier "P32249" --protein_name "human_gpcr" --window_length 5 --directory_aa_prop "./data/amino_acid_properties.csv"<file_sep>/Exercises/Ex_01/homework_day1.py
import collections
import csv
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
import re
import pandas as pd
human = "data/human.fasta"
bacteria = "data/bacteria.fasta" #(Prochlorococcus marinus)
archea = "data/archea.fasta" #(N(atronomonas salsuginis)
plantae = "data/plantae.fasta" #(Arabidopsis thaliana)
animalia = "data/animalia.fasta" #(Mus musculus)
def aa_counter(data):
'''
Function to go over every input line, decide wether its a name or not,
count the aas in the sequence and its length for each protein.
:param data: fasta data sequence
:return:
collections.Counter(counted_values) : total counted aas in the genome
names : names of all the ind. proteins
counts : aas counts of all the ind. proteins
'''
counted_values = ""
names = []
counts = []
with open(data) as file:
file_dict = csv.reader(file)
for line in file_dict:
if ">" in line[0]:
names.append(line)
length = ''
else:
counted_values += line[0]
length += line[0]
counts.append(collections.Counter(length))
return collections.Counter(counted_values), names, counts
def plot_aminoacid_histogram(as_counter):
'''
Function to plot the amounts of aas discovered in the given genome
:param as_counter: total aas count
:return: histogram
'''
# aminoacids = ['G', 'P', 'A', 'V', 'L', 'I', 'M', 'C', 'F', 'Y', 'W', 'H', 'K', 'R', 'Q', 'N', 'E', 'D', 'S', 'T']
# bad weil hard code:
# besser wenn so:
aminoacids=list(as_counter.keys())
aminoacid_count = []
for aminoacid in aminoacids:
aminoacid_count.append(as_counter[aminoacid])
plt.figure(figsize=(10, 6))
plt.grid(color='w', linestyle='--', linewidth=1, zorder=0)
ax = plt.axes()
ax.set_facecolor("#ADDFFF")
ax.set_axisbelow(True)
plt.bar(aminoacids, aminoacid_count, width=0.7, color='#0000A0', zorder=1)
plt.xlabel('1-Letter name for the amino acids', fontsize=14)
plt.ylabel('Count of the amino acids (#)', fontsize=14)
plt.title('Amino Acid Distribution', fontsize=20)
plt.tight_layout();
def create_csv(aas):
with open('Hausaufgabe1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["aa, count"])
for key, value in aas.items():
writer.writerow([key, value])
def calc_protein_attributs(full_names, as_counts, organism):
'''
:param full_names: the list with the full names taken from the fasta set
:param as_counts: The amino acid counts for each protein
:param organism: the name of the inspected organism
:return: Dataframe with all the protein names, their aas count and total length
'''
protein_names = []
amino_acid_count = []
empty_counter = collections.Counter('')
protein_length = []
organism_names = {'human': 'HUMAN(.+?)OS=', 'plantae': 'ARATH(.+?)OS=', 'archea': '9EURY(.+?)OS=',
'animalia': 'MOUSE(.+?)OS=', 'bacteria': 'PROMT(.+?)OS='}
keys = list(organism_names.keys())
values = list(organism_names.values())
str_to_search = (values[keys.index(organism)])
for i in range(0, len(full_names)):
protein_name = re.search(str_to_search, str(full_names[i]))
if protein_name:
protein_names.append(protein_name.group(1))
for i in range(1, len(as_counts)):
if as_counts[i] == empty_counter:
amino_acid_count.append(as_counts[i - 1])
protein_length.append(sum(as_counts[i - 1].values()))
amino_acid_count.append(as_counts[int(len(as_counts)) - 1])
protein_length.append(sum(as_counts[int(len(as_counts)) - 1].values()))
protein_info = {'name': protein_names, 'AS count': amino_acid_count, 'length': protein_length}
protein_attributs_df = pd.DataFrame(protein_info)
return protein_attributs_df
if __name__ == '__main__':
aas, full_names, as_counts = aa_counter(human)
plot_aminoacid_histogram(aas)
plt.show()
protein_attributs_df = calc_protein_attributs(full_names, as_counts, 'human')
longest_protein = protein_attributs_df.sort_values('length', axis=0, ascending=False).head(1)
shortest_protein = protein_attributs_df.sort_values('length', axis=0, ascending=True).head(1)
print('the longest protein of the organism is:\n', longest_protein, '\n',
'the shortest protein of the oragnism is:\n', shortest_protein, )
| 0113ada9edb8548ad1ff370c71b3e799e96d4458 | [
"Python"
] | 2 | Python | kittpa/fufezan-lab-advanced_python_2020-21_HD | d675bf9d2ae53d849b5d74b1ecdc2a87f8e5b451 | 85a7f0a7a9fd3f2bc054f66f1c8165c77463715b |
refs/heads/main | <file_sep><?php
session_start();
if(!isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !==true) {
header("location: login.php");
exit();
}
?>
<?php
//include config file
require_once "../config.php";
// macn : specializedCode tencn: specializedName
$macn = $tencn = "";
$macn_err = $tencn_err = "";
//processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// validate specialized code
if(empty(trim($_POST["macn"]))){
$macn_err="Please enter a specialized code.";
}elseif (strlen(trim($_POST["macn"])) !== 5){
$macn_err="Please enter a valid specialized code.";
}else{
$macn = trim($_POST["macn"]);
}
//validate specializedName
if(empty(trim($_POST["tencn"]))) {
$tencn_err = "Please enter a specialized name.";
}else {
$tencn = trim($_POST["tencn"]);
}
//check input errors before inserting in database
if(empty($macn_err) && empty($tencn_err)){
//prepare an insert statement
$sql="INSERT INTO chuyennganh (macn,tencn) VALUES (?,?)";
global $mysqli;
if($stmt=$mysqli->prepare($sql)){
//bind variables to the prepared statement as parameters
$stmt->bind_param("ss",$param_macn,$param_tencn);
//set parameters
$param_macn = $macn;
$param_tencn = $tencn;
//attempt to execute the prepared statement
if($stmt->execute()){
//records created successfully.rect to landing page
header("location: specialized.php");
exit();
}else{
echo "Oops! Something went wrong.Please try again later.";
}
}$stmt->close();
}
global $mysqli;
$mysqli->close();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-ml-12">
<h2 class="mt-5">Create Specialized</h2>
<p>Please fill this form and submit to add specialized record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label for="#">Specialized code</label>
<input type="text" name="macn" class="form-control
<?php echo (!empty($macn_err)) ? 'is-invalid' : '';?>"
value="<?php echo $macn;?>">
<span class="invalid-feedback"><?php echo $macn_err;?></span>
</div>
<div class="form-group">
<label for="#">Specialized name</label>
<textarea name="tencn" class="form-control
<?php echo (!empty($tencn_err)) ? 'is-invalid' : '';?>"
value="<?php echo $tencn;?>"></textarea>
<span class="invalid-feedback"><?php echo $tencn_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<a href="specialized.php" class="btn btn-secondary m1-2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html><file_sep><?php
session_start();
if(!isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !==true) {
header("location:login.php");
exit();
}
?>
<?php
//include config file
require_once "../config.php";
$mabd = $tenbd = $diachi = "";
$mabd_err = $tenbd_err = $diachi_err = "";
//processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate mabd
if(empty(trim($_POST["mabd"]))){
$mabd_err = "Please enter a Reader code.";
}elseif(strlen(trim($_POST["mabd"])) !== 5){
$mabd_err = "Please enter a valid Reader code.";
}else{
$mabd = trim($_POST["mabd"]);
}
//validate tenbd
$input_tenbd=trim($_POST["tenbd"]);
if(empty($input_tenbd)){
$name_err="Please enter a Reader name.";
}elseif (!filter_var($input_tenbd,FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err="Please enter a valid Reader name.";
}else{
$name=$input_tenbd;
}
//validate address
if(empty(trim($_POST["diachi"]))){
$address_err="Please enter an address.";
}else{
$address=trim($_POST["diachi"]);
}
//check input errors before inserting in database
if(empty($mabd_err) && empty($tenbd_err) && empty($diachi_err)){
//prepared an insert statement
$sql = "INSERT INTO bandoc(mabd,tenbd,diachi) value (?,?,?)";
global $mysqli;
if($stmt =$mysqli->prepare($sql)){
//bind variables to the prepared statement as parameter
$stmt->bind_param("sss",$param_mabd,$param_tenbd,$param_diachi);
//set parameters
$param_mabd = $mabd;
$param_tenbd = $tenbd;
$param_diachi = $diachi;
if($stmt->execute()){
header("location: manage_readers.php");
exit();
}else{
echo "Oops! Something went wrong.Please try again later.";
}
}
//close statement
$stmt->close();
}
//close connection
global $mysqli;
$mysqli->close();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-ml-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label for="#">Reader Code</label>
<input type="text" name="mabd" class="form-control
<?php echo (!empty($mabd_err)) ? 'is-invalid' : '';?>" value="<?php echo $mabd;?>">
<span class="invalid-feedback"><?php echo $mabd_err;?></span>
</div>
<div class="form-group">
<label for="#">Reader Name</label>
<textarea name="tenbd" class="form-control
<?php echo (!empty($tenbd_err)) ? 'is-invalid' : '';?>" value="<?php echo $tenbd;?>"></textarea>
<span class="invalid-feedback"><?php echo $tenbd_err;?></span>
</div>
<div class="form-group">
<label for="#">Address</label>
<input type="text" name="diachi" class="form-control
<?php echo (!empty($diachi_err)) ? 'is-invalid' : '';?>" value="<?php echo $diachi;?>">
<span class="invalid-feedback"><?php echo $diachi_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<a href="manage_readers.php" class="btn btn-secondary m1-2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
if(!isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !==true){
header("location: login.php");
exit();
}
?>
<?php
//process delete operation after confimation
if(isset($_POST["macn"]) && !empty($_POST["macn"])) {
//include config file
require_once "../config.php";
//prepare a delete statement
$sql = "DELETE FROM chuyennganh WHERE macn = ?";
global $mysqli;
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("s", $param_macn);
$param_macn = trim($_POST["macn"]);
if ($stmt->execute()) {
header("location: specialized.php");
exit();
} else {
echo "Oops! Something went wrong.Please try again later.";
}
}
$stmt->close();
$mysqli->close();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Delete Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Delete Specialized</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="alert alert-danger">
<input type="hidden" name="macn" value="<?php echo trim($_GET["macn"]); ?>">
<p>Are you sure you want to delete this specialized ?</p>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
<a href="specialized.php" class="btn btn-secondary m1-2">No</a>
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
if(!isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !==true){
header("location:login.php");
exit();
}
?>
<?php
require_once "../config.php";
$macn=$tencn="";
$macn_err=$tencn_err="";
if(isset($_POST["macn"]) && !empty($_POST["macn"])){
//validate
if(empty(trim($_POST["macn"]))){
$name_err="Please enter a specialized code.";
}elseif (strlen($_POST["macn"]) !== 5){
$name_err="Please enter a specialized code.";
}else{
$name=trim($_POST["macn"]);
}
if(empty(trim($_POST["tencn"]))){
$tencn_err="please enter an specialized name.";
}else{
$address=trim($_POST["tencn"]);
}
if(empty($macn_err) && empty($tencn_err)){
$sql="update chuyennganh set tencn=? where macn=?";
global $mysqli;
if($stmt=$mysqli->prepare($sql)){
$stmt->bind_param("ss",$param_tencn,$param_macn);
$param_macn = $macn;
$param_tencn = $tencn;
if($stmt->execute()){
header("location:specialized.php");
exit();
}else{
echo "Oops! Something went wrong.Please try again later.";
}
}
$stmt->close();
}
global $mysqli;
$mysqli->close();
}else{
//check existence of id parameter before processing further
if(isset($_GET["macn"]) && !empty(trim($_GET["macn"]))){
$sql="select * from chuyennganh where macn=?";
global $mysqli;
if($stmt=$mysqli->prepare($sql)){
$stmt->bind_param("i",$param_macn);
$param_macn = $macn;
if($stmt->execute()){
$result=$stmt->get_result();
if($result->num_rows==1){
/* fetch result row as an assoclative array.Since the result set contains only are row,
we dont't need to use while loop
*/
$row=$result->fetch_array(MYSQLI_ASSOC);
//retrieve individual field value
$macn=$row["macn"];
$tencn=$row["tencn"];
}
}else{
echo "Oops! Something went wrong.Please try again later.";
}
}
$stmt->close();
$mysqli->close();
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Update Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Update Specialized</h2>
<p>Please edit the input values and submit to update the specialized.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER["REQUEST_URI"]));?>" method="post">
<div class="form-group">
<label for="#">Specialized Code</label>
<input type="text" name="macn" class="form-control
<?php echo (!empty($macn_err)) ? 'is-invalid' : '';?>" value="<?php echo $macn;?>">
<span class="invalid-feedback"><?php echo $macn_err;?></span>
</div>
<div class="form-group">
<label for="#">Specialized Name</label>
<textarea name="tencn" class="form-control
<?php echo (!empty($tencn_err)) ? 'is-invalid' : '';?>" value="<?php echo $tencn;?>"></textarea>
<span class="invalid-feedback"><?php echo $tencn_err;?></span>
</div>
<!--<input type="hidden" name="macn" value="<?php echo $macn?>"/>-->
<input type="submit" class="btn btn-primary" value="Submit">
<a href="specialized.php" class="btn btn-secondary m1-2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
| 95c92a9556da5fa1a13d80e2dc201bf93e8a31d1 | [
"PHP"
] | 4 | PHP | Thanhdat230/php_library | 0c894ee2c64923ccc30dbda12020bae7e633ef34 | 5d3a325fc512065f37c4ad4301052cc0051f251e |
refs/heads/master | <repo_name>SergeRodriguez/json_the_cat<file_sep>/breedFetcher.js
const request = require("request");
const fetchBreedDescription = function(argument1, _callback) {
const URL = "https://api.thecatapi.com/v1/breeds/search?q=" + argument1;
request(URL, (error, response, content) => {
if (error) {
_callback("URL is wrong");
} else {
const data = JSON.parse(content);
if (!data[0]) {
_callback("The requested breed is not found.");
} else {
_callback(error, data[0].description.trim());
}
}
});
};
module.exports = { fetchBreedDescription }; | 609a7dae9394b67bc4ca03956c2578b8550e05ea | [
"JavaScript"
] | 1 | JavaScript | SergeRodriguez/json_the_cat | 995d6a0d037b2b90a5f6afca6cf607464d5dcfc9 | 3a4c944ab2dc1db13724a50b3955dd4798f61a56 |
refs/heads/master | <repo_name>karlgz/banking-app-exp<file_sep>/README.md
# Banking Client's App - Java GUI
<hr>
This is a simple example of some basic actions in banking written in Java. It has client's modification capabilities, deposit and withdraw functions. The GUI is written using JavaAWT tools. This is also a work in progress so I'm going to add more capabilities in the future. Feel free to poke around or make any suggestions on your own.
<br><hr>Constructive input is welcomed. Happy coding!<br>
<br>~bishop
<file_sep>/bankingTransactions/src/bankingTransactions/Manager.java
package bankingTransactions;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Manager {
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
public static void main(String[] args) {
JLabel masterLabel, balanceLabel, nameLabel, addressLabel, cityLabel,
accountNum, relatedAccs, lastnameLabel;
JTextField entry;
JButton deposit, withdraw, changeAccountNumber;
Account customer = new Account("CustomerFirst", "CustomerLast","CustAddress",
"CustCountry", "CustCity");
customer.setAccountBalance(456322.75);
JFrame frame = new JFrame("Basic Account Management");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(6,1));
frame.setSize(400, 200);
masterLabel = new JLabel("Deposit/Withdraw");
balanceLabel = new JLabel("Balance: $" + customer.getAccountBalance());
entry = new JTextField();
deposit = new JButton("Deposit");
withdraw = new JButton("Withdraw");
changeAccountNumber = new JButton("Change Details");
accountNum = new JLabel("Account numebr: " + customer.getAccountNumber());
relatedAccs = new JLabel("Connected accounts: " + customer.getRelatedAccounts());
nameLabel = new JLabel("Name: " + customer.getFirstname());
lastnameLabel = new JLabel("Lastname: " + customer.getLastname());
addressLabel = new JLabel("Address: " + customer.getAddress());
cityLabel = new JLabel("City: " + customer.getCity());
changeAccountNumber.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String choice = JOptionPane.showInputDialog("Type 1 for name, 2 for lastname, 3 for address, 4 for city");
if (isNumeric(choice)){
int c = Integer.parseInt(choice);
if (c == 1){
String first = JOptionPane.showInputDialog("Choose a new name");
customer.setFirstname(first);
JOptionPane.showMessageDialog(null, "First name changed successfully");
nameLabel.setText(customer.getFirstname());
} else if (c == 2){
String last = JOptionPane.showInputDialog("Choose a new lastname");
customer.setLastname(last);
JOptionPane.showMessageDialog(null, "Lastname changed successfully");
lastnameLabel.setText(customer.getLastname());
} else if (c == 3){
String addr = JOptionPane.showInputDialog("Choose a new address");
customer.setAddress(addr);
JOptionPane.showMessageDialog(null, "Address changed successfully");
addressLabel.setText(customer.getAddress());
} else if (c == 4){
String cty = JOptionPane.showInputDialog("Choose a new city");
customer.setCity(cty);
JOptionPane.showMessageDialog(null, "City changed successfully");
cityLabel.setText(customer.getCity());
} else {
JOptionPane.showMessageDialog(null, "Not able to process this request.");
return;
}
JOptionPane.showMessageDialog(null, "Operation Completed.");
} else {
JOptionPane.showMessageDialog(null, "Operation Cancelled.");
}
}
});
deposit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String value = entry.getText();
if (isNumeric(value)){
customer.deposit(Double.parseDouble(value));
balanceLabel.setText("Balance: $" + customer.getAccountBalance()+"");
entry.setText("");
} else {
entry.setText("");
JOptionPane.showMessageDialog(null, "Operation Cancelled.");
}
}
});
withdraw.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String value = entry.getText();
if (isNumeric(value)){
customer.withdraw(Double.parseDouble(value));
if (customer.getAccountBalance() <= 0){
customer.setAccountBalance(0);
balanceLabel.setText("Balance: $" + customer.getAccountBalance());
entry.setText("");
} else {
balanceLabel.setText("Balance: $" + customer.getAccountBalance());
entry.setText("");
}
} else {
entry.setText("");
JOptionPane.showMessageDialog(null, "Operation Cancelled.");
}
}
});
frame.add(masterLabel); // row 1, pos 1
frame.add(entry); // row 1, pos 2
frame.add(deposit); // row 2, pos 1
frame.add(withdraw); // row 2, pos 2
frame.add(balanceLabel); // row 3, pos 1
frame.add(relatedAccs); // row 3, pos 2
frame.add(nameLabel); // row 4, pos 1
frame.add(lastnameLabel); // row 4, pos 2
frame.add(accountNum); // row 5, pos 1
frame.add(changeAccountNumber); // row 5, pos 2
frame.add(addressLabel); // row 6, pos 1
frame.add(cityLabel); // row 6, pos 2
frame.setVisible(true);
}
}
| 9e8a1910c7c67561153d820665498df2988f3058 | [
"Markdown",
"Java"
] | 2 | Markdown | karlgz/banking-app-exp | a80ee2a7d1976f841a7c4c4519ff723f1a7e9082 | 47c5bbcbfc24ae8343dbe20e04dd6b04ef11ed07 |
refs/heads/master | <repo_name>ChristofferKarlborg/Projectvt18<file_sep>/src/main/java/utilities/SeatClass.java
package utilities;
public enum SeatClass {
FIRST_CLASS ("First Class"),
BUSINESS_CLASS ("Business Class"),
ECONOMY_CLASS ("Economy Class");
private final String classOfSeat;
private SeatClass(String classOfSeat) {
this.classOfSeat = classOfSeat;
}
public String asString() {
return this.classOfSeat;
}
}
<file_sep>/src/main/java/service/AccountService.java
package service;
import dataaccess.dao.AccountDao;
import dataaccess.daoimpl.AccountDaoImpl;
import dataaccess.exceptions.UserDoesNotExistException;
import entities.Account;
import service.exception.InvalidPasswordException;
import service.exception.InvalidUserNameException;
import service.exception.ValidationException;
public class AccountService {
private static AccountService instance = null;
private AccountDao dao = new AccountDaoImpl();
public static AccountService getInstance() {
if (instance == null) {
instance = new AccountService();
}
return instance;
}
public void createNewAccount(String email, String rawTextPassword, String username) throws ValidationException{
if( ! validateNewAccount(email, rawTextPassword, username))
throw new ValidationException();
//TODO: Implement some form of actual password hashing apart from messagedigest;
dao.createAccount(new Account( username, email, rawTextPassword));
}
private boolean validateNewAccount(String email, String rawTextPassword, String username){
return ( ! emailIsInUse(email) || ! usernameIsInUse(username) || ! rawTextPasswordIsInvalid(rawTextPassword) );
}
private boolean rawTextPasswordIsInvalid(String password) {
return password.length()<10 ? true:false;
}
private boolean emailIsInUse(String Email){
try {
dao.findAccountByEmail(Email);
return true;
}catch(UserDoesNotExistException e){
return false;
}
}
private boolean usernameIsInUse(String username) {
try {
dao.findAccountByUserName(username);
return true;
}catch(UserDoesNotExistException e){
return false;
}
}
public Account getAccountByEmail(String email) throws UserDoesNotExistException {
return dao.findAccountByEmail(email);
}
// public Account checkCredentials(String email, String password)
// throws InvalidUserNameException, InvalidPasswordException {
//
// try {
// //Is there an account with that email?
// Account foundAccount = dao.findAccountByEmail(email);
//
// //Does that account have that password!
// if( foundAccount.comparePassword(email)) {
// return foundAccount;
//
// }else {
// //Wrong password
// throw new InvalidPasswordException();
// }
//
// } catch (UserDoesNotExistException e) {
// //No account registered to that email
// throw new InvalidUserNameException();
//
// }
//
// }
}
<file_sep>/src/main/java/dataaccess/daoimpl/CompanyDaoImpl.java
package dataaccess.daoimpl;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import dataaccess.dao.AccountDao;
import dataaccess.dao.CompanyDao;
import dataaccess.dao.FlightDao;
import dataaccess.exceptions.IncorrectAmountOfQueryResultsException;
import dataaccess.exceptions.UserDoesNotExistException;
import entities.Account;
import entities.Company;
import entities.Flight;
import utilities.SimpleGenericCrud;
public class CompanyDaoImpl implements CompanyDao {
private SimpleGenericCrud<Company> crudDao = new SimpleGenericCrud(Company.class);
private AccountDao accDao = new AccountDaoImpl();
private FlightDao flightDao = new FlightDaoImpl();
private Session session = crudDao.session;
@Override
public void createCompany(Company newCompany) {
crudDao.createEntity(newCompany);
}
@Override
public Company findCompanyById(int companyId) throws IncorrectAmountOfQueryResultsException {
return crudDao.findEntityById(companyId);
}
@Override
public void updateCompany(Company companyToUpdate) throws UserDoesNotExistException {
crudDao.updateEntity(companyToUpdate);
}
@Override
public void removeCompany(Company companyToRemove) throws UserDoesNotExistException {
crudDao.removeEntity(companyToRemove);
}
@Override
public Company findByName(String companyName) throws IncorrectAmountOfQueryResultsException {
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Company> criteria = builder.createQuery( Company.class );
Root<Company> root = criteria.from( Company.class );
criteria.select(root).where(builder.equal(root.get("companyName"), companyName));
// Execute Query
List<Company> CompanyList = crudDao.executeQueryThenCommit(crit -> {
return session.createQuery(crit).setMaxResults(1).getResultList();
}, criteria);
// Check result size and return
if (CompanyList.size() != 1) {
throw new IncorrectAmountOfQueryResultsException("Amount of users returned from DB should be 1, is : " + CompanyList.size() );
}
return CompanyList.get(0);
}
public void closeConnection() {
crudDao.closeConnection();
}
}
<file_sep>/src/test/java/tests/Test_SeatDao.java
package tests;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import dataaccess.dao.SeatDao;
import dataaccess.daoimpl.SeatDaoImpl;
import dataaccess.exceptions.EntityDoesNotExistsException;
import dataaccess.exceptions.IncorrectAmountOfQueryResultsException;
import entities.Seat;
import utilities.SeatClass;
public class Test_SeatDao {
private static SeatDao dao = new SeatDaoImpl();
@Test(expected = IncorrectAmountOfQueryResultsException.class)
public void test_SeatCanBeDeleted() throws IncorrectAmountOfQueryResultsException {
// Arrange
Seat seat1 = new Seat(SeatClass.FIRST_CLASS);
dao.createSeat(seat1);
// Act
try {
dao.removeSeat(seat1);
// Assert
dao.findSeatById(seat1.getId());
} catch (EntityDoesNotExistsException e) {
e.printStackTrace();
}
fail();
}
@Test
public void test_SeatCanBeUpdated() {
// Arrange
Seat seat2 = new Seat(SeatClass.BUSINESS_CLASS);
Seat tmpSeat = null;
dao.createSeat(seat2);
// Act
try {
seat2.setType(SeatClass.ECONOMY_CLASS);
dao.updateSeat(seat2);
tmpSeat = dao.findSeatById(seat2.getId());
} catch (Exception e) {
e.printStackTrace();
}
// Assert
assertTrue(tmpSeat.getType() == SeatClass.ECONOMY_CLASS);
}
@Test
public void test_SeatCanBeFoundByFlightId() {
// Arrange
Seat seat3 = new Seat(SeatClass.FIRST_CLASS);
seat3.setFlight(1234);
dao.createSeat(seat3);
dao.createSeat(seat3);
// Act
List<Seat> seatList = dao.findSeatByFlightId(1234);
// Assert
for (Seat seat : seatList) {
assertTrue(seat.getFlight() == 1234);
}
}
@Test
public void test_SeatCanBeFoundBySeatId() {
// Arrange
Seat seat4 = new Seat(SeatClass.FIRST_CLASS);
int id = -1;
dao.createSeat(seat4);
//Act
try {
id = dao.findSeatById(seat4.getId()).getId();
} catch (IncorrectAmountOfQueryResultsException e) {
fail();
}
//Assert
assertTrue(id == seat4.getId());
}
}
<file_sep>/src/main/java/dataaccess/dao/AccountDao.java
package dataaccess.dao;
import dataaccess.exceptions.IncorrectAmountOfQueryResultsException;
import dataaccess.exceptions.UserDoesNotExistException;
import entities.Account;
public interface AccountDao {
//CRUD
public void createAccount(Account newAccount);
public Account findAccountById(int accountId) throws IncorrectAmountOfQueryResultsException;
public void updateAccount(Account accountToUpdate) throws UserDoesNotExistException;
public void removeAccount(Account accountToRemove) throws UserDoesNotExistException;
public Account findAccountByEmail(String accountEmail) throws UserDoesNotExistException;
public Account findAccountByUserName(String userName) throws UserDoesNotExistException;
}
<file_sep>/src/main/java/api/FlightApi.java
package api;
public class FlightApi {
//TODO: Class stub
}
<file_sep>/src/main/java/utilities/SimpleGenericCrud.java
package utilities;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import dataaccess.exceptions.IncorrectAmountOfQueryResultsException;
import dataaccess.exceptions.UserDoesNotExistException;
public class SimpleGenericCrud<T extends EntityIdAccess> {
//Get session from utilities and open it
public Session session = HibernateUtilities.getSessionFactory().openSession();
//Class literal, to be used of instanciating the criteria
private Class<T> genericClass;
//Constructor
public SimpleGenericCrud( Class<T> genericClass) {
super();
this.genericClass = genericClass;
}
//Create
public void createEntity(T newObj) {
executeQueryThenCommit((T s) -> {
session.save(s);
}, newObj);
}
//Search
public T findEntityById(int entityId) throws IncorrectAmountOfQueryResultsException {
// Build Criteria
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery( genericClass );
Root<T> root = criteria.from( genericClass );
criteria.select(root).where(builder.equal(root.get("id"), entityId));
// Execute Query
List<T> entityList = executeQueryThenCommit(crit -> {
return session.createQuery(crit).setMaxResults(1).getResultList();
}, criteria);
// Check result size and return
if (entityList.size() != 1) {
throw new IncorrectAmountOfQueryResultsException("Amount of users returned from DB should be 1, is : " + entityList.size() );
}
return entityList.get(0);
}
public List<T> findByFieldValue(String nameOfField, String fieldValue) {
// Build Criteria
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery( genericClass );
Root<T> root = criteria.from( genericClass );
criteria.select(root).where(builder.equal(root.get(nameOfField), fieldValue));
// Execute Query
List<T> entityList = executeQueryThenCommit(crit -> {
return session.createQuery(crit).getResultList();
}, criteria);
return entityList;
}
public T findByFieldValueSingleResult(String nameOfField, String fieldValue) throws IncorrectAmountOfQueryResultsException{
//Get the result from the ordinary method
List<T> result = findByFieldValue(nameOfField, fieldValue);
//Three cases, too many results, one, or none at all;
if(result.size() > 1) {
throw new IncorrectAmountOfQueryResultsException(" Too many results " + result.size() + " returned, 1 expected");
}else if(result.size() == 0) {
throw new IncorrectAmountOfQueryResultsException(" Could not find entity");
}
else{
return result.get(0);
}
}
//Update
public void updateEntity(T entityToUpdate) throws UserDoesNotExistException {
try {
// Find the existing Entity
T persistentEntity = findEntityById(entityToUpdate.getId());
// Update
executeQueryThenCommit(Entity -> {
session.update(Entity);
}, persistentEntity);
} catch (IncorrectAmountOfQueryResultsException e) {
// TODO: handle exception
}
}
//Delete
public void removeEntity(T entityToRemove) {
try {
// Find the existing Entity
T persistentEntity = findEntityById(entityToRemove.getId());
// Update
executeQueryThenCommit(Entity -> {
session.delete(Entity);
}, persistentEntity);
} catch (IncorrectAmountOfQueryResultsException e) {
// TODO: handle exception
}
}
// By using these methods, we avoid surrounding each function with opening and closing the transaction
public <T> void executeQueryThenCommit(Consumer<T> statement, T parameter) {
session.beginTransaction();
statement.accept(parameter);
session.getTransaction().commit();
}
public <T, R> R executeQueryThenCommit(Function<T, R> statement, T parameter) {
session.beginTransaction();
R result = statement.apply(parameter);
session.getTransaction().commit();
return result;
}
public void closeConnection() {
this.session.close();
}
}
<file_sep>/src/main/java/dataaccess/exceptions/IncorrectAmountOfQueryResultsException.java
package dataaccess.exceptions;
public class IncorrectAmountOfQueryResultsException extends Exception {
public IncorrectAmountOfQueryResultsException(String message) {
super(message);
}
}
<file_sep>/src/main/java/dataaccess/exceptions/EntityDoesNotExistsException.java
package dataaccess.exceptions;
public class EntityDoesNotExistsException extends Exception {
public EntityDoesNotExistsException(String message) {
super(message);
}
public EntityDoesNotExistsException() {
}
}
<file_sep>/src/main/java/dataaccess/dao/SeatDao.java
package dataaccess.dao;
import java.util.List;
import dataaccess.exceptions.EntityDoesNotExistsException;
import dataaccess.exceptions.IncorrectAmountOfQueryResultsException;
import entities.Seat;
public interface SeatDao {
// CRUD
public void createSeat(Seat newSeat);
public Seat findSeatById(int seatId) throws IncorrectAmountOfQueryResultsException;
public void updateSeat(Seat seatToUpdate) throws EntityDoesNotExistsException;
public void removeSeat(Seat seatToRemove) throws EntityDoesNotExistsException;
// Other
public List<Seat> findSeatByFlightId(int flightId);
}
<file_sep>/src/main/java/entities/Ticket.java
package entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import utilities.EntityIdAccess;
@Entity
public class Ticket implements EntityIdAccess{
@Id
@GeneratedValue
private int id;
private int seatId;
private Integer customerId = null;
public Ticket(int seatId) {
this.seatId = seatId;
}
public int getId() {
return id;
}
public int getSeatId() {
return seatId;
}
public int getCustomerId() {
return customerId;
}
public void setSeatId(int seatId) {
this.seatId = seatId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + customerId;
result = prime * result + id;
result = prime * result + seatId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Ticket other = (Ticket) obj;
if (customerId != other.customerId)
return false;
if (id != other.id)
return false;
if (seatId != other.seatId)
return false;
return true;
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Project_VT18</groupId>
<artifactId>Project_VT18</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Project_vt18</name>
<packaging>war</packaging>
<properties>
<jersey.version>2.26</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>9.0.6.v20130930</jetty.version>
</properties>
<build>
<!-- <sourceDirectory>src</sourceDirectory> -->
<finalName>ProjectVt18</finalName>
<testResources>
<testResource>
<directory>src/test/resources/</directory>
<includes>
<include>hibernate.cfg.xml</include>
</includes>
</testResource>
<testResource>
<directory>src/main/resources/</directory>
<excludes>
<exclude>hibernate.cfg.xml</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<properties>
<property>
<name>listener</name>
<value>tests.InMemoryDbTestUtility</value>
</property>
</properties>
<excludes>
<exclude>**/Test_HsqlDB.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<filesets>
<fileset>
<directory>${basedir}/</directory>
<includes>
<include>database.dat.properties</include>
<include>database.dat.script</include>
</includes>
</fileset>
</filesets>
</configuration>
</plugin>
<!-- Restful api -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<contextPath>/</contextPath>
<webApp>
<contextPath>/</contextPath>
<webInfIncludeJarPattern>.*/.*jersey-[^/]\.jar$</webInfIncludeJarPattern>
</webApp>
<war>${project.build.directory}/${project.build.finalName}.war</war>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeScope>compile</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.22.0-GA</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
<!-- JWT authorization -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<!-- For testing purposes -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Restful api -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-bundle</artifactId>
<type>pom</type>
<scope>test</scope>
</dependency>
</dependencies>
</project><file_sep>/src/main/java/service/FlightService.java
package service;
import java.time.ZonedDateTime;
import java.util.GregorianCalendar;
import java.util.List;
import dataaccess.dao.FlightDao;
import dataaccess.dao.SeatDao;
import dataaccess.dao.TicketDao;
import dataaccess.daoimpl.FlightDaoImpl;
import dataaccess.daoimpl.SeatDaoImpl;
import dataaccess.daoimpl.TicketDaoImpl;
import entities.Flight;
import entities.Seat;
import entities.Ticket;
import service.exception.ValidationException;
public class FlightService {
private static FlightService instance = null;
private FlightDao flightDao = new FlightDaoImpl();
private SeatDao seatDao = new SeatDaoImpl();
private TicketDao ticketDao = new TicketDaoImpl();
public static FlightService getInstance() {
if (instance == null) {
instance = new FlightService();
}
return instance;
}
//TODO: move transactions over to services, to prevent what is basically autocommit
//Get the flight, the seats and add them to the DB
public void registerNewFlight(Flight newFlight, List<Seat> seats ) throws ValidationException{
//TODO: Doublecheck how this will handle null values
//Just throw an exception, fine turning the error message and validation can be done on the front end
if( newFlight.getDeparture().isAfter(ZonedDateTime.now())
|| newFlight.getArrivalTime().isBefore(ZonedDateTime.now())
|| newFlight.getDestination().equals(newFlight.getStartLocation())
|| ! newFlight.noFieldIsNull()
|| newFlight.getId() != 0
|| newFlight.getDelayed() != 0
){
throw new ValidationException();
}
}
public List<Flight> getAllFlights() {
return flightDao.getAllFlights();
}
public List<Flight> getFlightByStartAndDestionation(String start, String destination) {
return flightDao.findFlightByStartAndDestination(start, destination);
}
public List<Flight> getFlightByStart(String start) {
return flightDao.findFlightByStartingPosition(start);
}
public List<Flight> getFlightByDestination(String destination) {
return flightDao.findFlightByDestination(destination);
}
public List<Flight> getFlightByCompany(int companyID){
return flightDao.findFlightByCompanyID(companyID);
}
public List<Seat> getFlightSeats(int flightId){
return seatDao.findSeatByFlightId(flightId);
}
}
<file_sep>/src/main/java/utilities/EntityIdAccess.java
package utilities;
public interface EntityIdAccess {
public int getId();
}
<file_sep>/src/main/java/api/AccountApi.java
package api;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import api.filter.AuthorizationRequired;
import dataaccess.exceptions.UserDoesNotExistException;
import datatransfer.AccountCreationEntity;
import entities.Account;
import service.AccountService;
import service.exception.ValidationException;
@Path("account")
public class AccountApi {
private static AccountService service = new AccountService();
@GET
public Response get() {
//Testing
System.out.println("Contact");
return Response.ok().build();
}
@GET
@Path("email/{email}")
@AuthorizationRequired
public Response get(@PathParam("email") String email) {
System.out.println("in api");
try {
Account foundAccount = service.getAccountByEmail(email);
return Response.ok().entity(foundAccount).build();
} catch (UserDoesNotExistException e) {
return Response.status(400).build();
}
}
// Create account
@POST
@Path("new")
public Response create(AccountCreationEntity account) {
try {
service.createNewAccount(account.getEmail(), account.getPlaintextPassword(), account.getUsername());
} catch (ValidationException e) {
return Response.status(400).build();
}
return Response.status(200).build();
}
}
<file_sep>/src/test/java/tests/Test_CompanyDao.java
package tests;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import dataaccess.dao.CompanyDao;
import dataaccess.dao.FlightDao;
import dataaccess.dao.AccountDao;
import dataaccess.daoimpl.CompanyDaoImpl;
import dataaccess.daoimpl.FlightDaoImpl;
import dataaccess.daoimpl.AccountDaoImpl;
import dataaccess.exceptions.IncorrectAmountOfQueryResultsException;
import dataaccess.exceptions.UserDoesNotExistException;
import entities.Company;
import entities.Flight;
import entities.Account;
import utilities.HibernateUtilities;
public class Test_CompanyDao {
private static CompanyDao dao = new CompanyDaoImpl();
@BeforeClass
public static void setUp() {
dao.createCompany(new Company( "Acme1" ));
dao.createCompany(new Company( "Acme2" ));
dao.createCompany(new Company( "Acme3" ));
dao.createCompany(new Company( "Acme4" ));
}
@Test
public void companyCanBeFoundByName() {
Company companyToBefound = null;
try {
companyToBefound = dao.findByName("Acme1");
} catch (IncorrectAmountOfQueryResultsException e) {
System.out.println(e.getMessage());
fail();
}
assertTrue("Name is " + companyToBefound.getCompanyName() + ", Should be Acme1",companyToBefound.getCompanyName().equals("Acme1"));
}
@Test
public void gettingNonExistantCompanyCausesException() {
Company companyToBefound;
try {
companyToBefound = dao.findByName("Acme111");
fail();
} catch (IncorrectAmountOfQueryResultsException e) {
}
}
@Test
public void companyCanBeUpdated() {
Company companyToUpdate = null;
try {
//Get object
companyToUpdate = dao.findByName("Acme3");
companyToUpdate.setCompanyName("Acme33");
//Perform update
dao.updateCompany(companyToUpdate);
//Get the updated version From DB
Company updatedCompany = dao.findCompanyById(companyToUpdate.getId());
//Assert that the update has been done
assertTrue(updatedCompany.getCompanyName().equals("Acme33"));
//The type of exception doesn't matter really, it's a fail anyhow
} catch (Exception e) {
System.out.println(e.getStackTrace());
fail();
}
}
@Test
public void companyCanBeDeleted() {
Company companyToRemove = null;
try {
//Get object
companyToRemove = dao.findByName("Acme2");
//Perform delete
dao.removeCompany(companyToRemove);
//Attempt to get the company, this should cause an exception
Company updatedCompany = dao.findCompanyById(companyToRemove.getId());
fail();
} catch (IncorrectAmountOfQueryResultsException e) {
//Success
} catch (UserDoesNotExistException e) {
//The user did not exist when attempting removal
e.printStackTrace();
fail();
}
}
}
| 3c068afcce59454a7c6a7303dfdd58e082741ed4 | [
"Java",
"Maven POM"
] | 16 | Java | ChristofferKarlborg/Projectvt18 | 60ef1955e7b5981afb899f64fe150e429b2a1dd3 | ffdf0daafddb68acaaee5ac68b855767395a3da8 |
refs/heads/main | <file_sep># Kattis
My solutions to some kattis problems
<file_sep>import re
r, c = map(int, input().split())
if r == 1:
mainLine = input()
elif r == 2:
topLine = input()
mainLine = input()
elif r == 3:
topLine = input()
mainLine = input()
bottomLine = input()
newMainLine = mainLine
squareRootRanges = []
fractionRanges = []
fraction = re.compile("=+")
squareRootStart = re.compile(r"\\/")
squareRootBody = re.compile("_+")
if r >= 2:
for match in re.finditer(squareRootBody, topLine):
squareRootRanges.append((match.start(), match.end()))
startIndex = 0
while True:
match = re.search(fraction, mainLine[startIndex:])
if match is None:
break
startIndex = match.end() + 1
newFrac = '(' + topLine[match.start():match.end()] + ')' + '/' + '(' + bottomLine[match.start():match.end()] + ')'
newMainLine = newMainLine[:match.start()] + newFrac + newMainLine[match.end():]
print(newMainLine) | ad279d6177b34b7eeff9d2f34efecd51f9f2642c | [
"Markdown",
"Python"
] | 2 | Markdown | WhiteFireWisp/Kattis | e332708146e25552888047f3b8a10e4d7c76dcd8 | 82b68d5222884c81f281d5b24be1132fc5e200ab |
refs/heads/master | <repo_name>danielsan80/cqrs-es-ws<file_sep>/www/src/AppBundle/Controller/DefaultController.php
<?php
namespace AppBundle\Controller;
use Broadway\UuidGenerator\Rfc4122\Version4Generator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Shop\Product\Command\CreateProduct;
use Shop\Product\Command\DeleteProduct;
use Shop\Product\Command\UpdateProduct;
use Shop\Product\ReadModel\Product;
use Shop\Product\ValueObject\ProductId;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
/**
* @Route("/products", name="create_product")
* @Method({"POST"})
*/
public function createAction(Request $request)
{
$uuidGenerator = new Version4Generator();
$productId = new ProductId($uuidGenerator->generate());
$createProduct = new CreateProduct(
$productId,
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$this->get('broadway.command_handling.simple_command_bus')->dispatch($createProduct);
return new JsonResponse(['product_id' => (string)$productId], 201);
}
/**
* @Route("products/{id}", name="get_product")
* @Method({"GET"})
*/
public function getAction(Request $request)
{
/** @var Product $productReadModel */
$productReadModel = $this->get('shop.product.read_model.repository')->find(new ProductId($request->get('id')));
return new JsonResponse($productReadModel->serialize());
}
/**
* @Route("/products/{id}", name="update_product")
* @Method({"PUT"})
*/
public function updateAction(Request $request)
{
$productId = new ProductId($request->get('id'));
$updateProduct = new UpdateProduct(
$productId,
'5707055029609',
'Nome prodotto: Scaaarpe più belle',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake1.png',
'Brand prodotto: Super Scaaaarpe più belle',
new \DateTimeImmutable()
);
$this->get('broadway.command_handling.simple_command_bus')->dispatch($updateProduct);
return new JsonResponse($this->generateUrl('get_product', ['id' => (string)$productId]), 204);
}
/**
* @Route("products/{id}", name="delete_product")
* @Method({"DELETE"})
*/
public function deleteAction(Request $request)
{
$productId = new ProductId($request->get('id'));
$deleteProduct = new DeleteProduct(
$productId,
new \DateTimeImmutable()
);
$this->get('broadway.command_handling.simple_command_bus')->dispatch($deleteProduct);
return new JsonResponse(['product_id' => (string)$productId], 200);
}
}
<file_sep>/www/tests/Shop/Order/Command/CheckoutTest.php
<?php
namespace Tests\Shop\Command;
use Broadway\CommandHandling\CommandHandler;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventHandling\EventBus;
use Broadway\EventStore\EventStore;
use Shop\Order\Command\Checkout;
use Shop\Order\Event\OrderConfirmed;
use Shop\Order\Event\OrderCreated;
use Shop\Order\Event\OrderPaymentRequested;
use Shop\Order\Repository;
use Shop\Order\ValueObject\OrderId;
use Shop\Order\ValueObject\OrderItem;
use Shop\Order\OrderCommandHandler;
use Shop\Product\ValueObject\ProductId;
class CheckoutTest extends CommandHandlerScenarioTestCase
{
/**
* @test
*/
public function should_checkout_an_order()
{
$orderId = new OrderId('00000000-0000-0000-0000-000000000321');
$totalCost = 100;
$checkout = new Checkout(
$orderId,
$totalCost,
new \DateTimeImmutable('2017-02-14')
);
$orderItem1 = new OrderItem(
new ProductId('00000000-0000-0000-0000-000000000322'),
5
);
$orderItem2 = new OrderItem(
new ProductId('00000000-0000-0000-0000-000000000323'),
2
);
$this->scenario
->withAggregateId($orderId)
->given([
new OrderCreated(
$orderId,
$totalCost,
[$orderItem1, $orderItem2],
new \DateTimeImmutable('2017-02-13')
)
])
->when($checkout)
->then(
[
new OrderPaymentRequested(
$checkout->getOrderId(),
$checkout->getTotalCost(),
$checkout->getRequestedAt()
)
]
);
}
/**
* @test
* @expectedException \Shop\Order\Exception\CheckoutDenied
*/
public function should_not_checkout_an_order_if_order_is_confirmed()
{
$orderId = new OrderId('00000000-0000-0000-0000-000000000321');
$totalCost = 100;
$checkout = new Checkout(
$orderId,
$totalCost,
new \DateTimeImmutable('2017-02-14')
);
$orderItem1 = new OrderItem(
new ProductId('00000000-0000-0000-0000-000000000322'),
5
);
$this->scenario
->withAggregateId($orderId)
->given([
new OrderConfirmed(
$orderId,
new \DateTimeImmutable('2017-02-14')
)
])
->when($checkout);
}
/**
* Create a command handler for the given scenario test case.
*
* @param EventStore $eventStore
* @param EventBus $eventBus
*
* @return CommandHandler
*/
protected function createCommandHandler(EventStore $eventStore, EventBus $eventBus)
{
$repository = new Repository($eventStore, $eventBus);
return new OrderCommandHandler($repository);
}
}
<file_sep>/www/src/Shop/Service/Mailer.php
<?php
namespace Shop\Service;
interface Mailer
{
public function send($from, $to, $message);
}
<file_sep>/www/tests/Shop/Product/Command/UpdateProductTest.php
<?php
namespace Tests\Shop\Command;
use Broadway\CommandHandling\CommandHandler;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventHandling\EventBus;
use Broadway\EventStore\EventStore;
use Shop\Product\Command\UpdateProduct;
use Shop\Product\Event\ProductCreated;
use Shop\Product\Event\ProductUpdated;
use Shop\Product\ProductCommandHandler;
use Shop\Product\Repository;
use Shop\Product\ValueObject\ProductId;
class UpdateProductTest extends CommandHandlerScenarioTestCase
{
/**
* @test
*/
public function should_update_a_product()
{
$productId = new ProductId('00000000-0000-0000-0000-000000000321');
$productCreated = new ProductCreated(
$productId,
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$updateProduct = new UpdateProduct(
$productId,
'5707055029609',
'Nome prodotto: Scaaarpe più belle',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake11.png',
'Brand prodotto: Super Scaaaarpe più belle',
new \DateTimeImmutable('2017-03-14')
);
$this->scenario
->withAggregateId($productId)
->given([$productCreated])
->when($updateProduct)
->then(
[
new ProductUpdated(
$updateProduct->getProductId(),
$updateProduct->getBarcode(),
$updateProduct->getName(),
$updateProduct->getImageurl(),
$updateProduct->getBrand(),
$updateProduct->getCreatedAt()
)
]
);
}
/**
* Create a command handler for the given scenario test case.
*
* @param EventStore $eventStore
* @param EventBus $eventBus
*
* @return CommandHandler
*/
protected function createCommandHandler(EventStore $eventStore, EventBus $eventBus)
{
$repository = new Repository($eventStore, $eventBus);
return new ProductCommandHandler($repository);
}
}
<file_sep>/www/tests/Shop/Product/Command/DeleteProductTest.php
<?php
namespace Tests\Shop\Command;
use Broadway\CommandHandling\CommandHandler;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventHandling\EventBus;
use Broadway\EventStore\EventStore;
use Shop\Product\Command\DeleteProduct;
use Shop\Product\Event\ProductCreated;
use Shop\Product\Event\ProductDeleted;
use Shop\Product\ProductCommandHandler;
use Shop\Product\Repository;
use Shop\Product\ValueObject\ProductId;
class DeleteProductTest extends CommandHandlerScenarioTestCase
{
/**
* @test
*/
public function should_delete_a_product()
{
$productId = new ProductId('00000000-0000-0000-0000-000000000321');
$productCreated = new ProductCreated(
$productId,
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$deleteProduct = new DeleteProduct(
$productId,
new \DateTimeImmutable('2017-03-14')
);
$this->scenario
->withAggregateId($productId)
->given([$productCreated])
->when($deleteProduct)
->then(
[
new ProductDeleted(
$productId,
new \DateTimeImmutable('2017-03-14')
)
]
);
}
/**
* Create a command handler for the given scenario test case.
*
* @param EventStore $eventStore
* @param EventBus $eventBus
*
* @return CommandHandler
*/
protected function createCommandHandler(EventStore $eventStore, EventBus $eventBus)
{
$repository = new Repository($eventStore, $eventBus);
return new ProductCommandHandler($repository);
}
}
<file_sep>/www/src/Shop/Product/Command/UpdateProduct.php
<?php
namespace Shop\Product\Command;
class UpdateProduct extends CreateProduct
{
}
<file_sep>/www/src/Shop/Service/Process/Mailer.php
<?php
namespace Shop\Service\Process;
use Broadway\Processor\Processor;
use Shop\Order\Event\OrderConfirmed;
/**
* Class Mailer
*
* @package Soisy\Domain\Common\Service
*/
class Mailer extends Processor
{
private $mailer;
public function __construct(\Shop\Service\Mailer $mailer)
{
$this->mailer = $mailer;
}
public function handleOrderConfirmed(OrderConfirmed $event)
{
$message = 'Order ' . (string)$event->getOrderId() . ' confirmed.';
$this->mailer->send('<EMAIL>', '<EMAIL>', $message);
}
}
<file_sep>/www/tests/Shop/Product/ValueObject/ProductIdTest.php
<?php
namespace Tests\Shop\Product\ValueObject;
use Shop\Product\ValueObject\ProductId;
class ProductIdTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function should_accept_valid_uuid()
{
$productId = new ProductId('00000000-0000-0000-0000-000000000321');
$this->assertEquals('00000000-0000-0000-0000-000000000321', $productId);
}
/**
* @test
* @expectedException \Assert\InvalidArgumentException
*/
public function should_not_accept_not_valid_uuid()
{
new ProductId('-0000-0000-0000-000000000321');
}
}
<file_sep>/www/src/Shop/Payment/Command/Pay.php
<?php
namespace Shop\Payment\Command;
use Shop\Order\ValueObject\OrderId;
use Shop\Payment\ValueObject\PaymentId;
class Pay
{
/**
* @var PaymentId
*/
private $paymentId;
/**
* @var OrderId
*/
private $orderId;
private $totalCost;
/**
* @var \DateTimeImmutable
*/
private $requestedAt;
public function __construct(PaymentId $paymentId, OrderId $orderId, $totalCost, \DateTimeImmutable $requestedAt)
{
$this->paymentId = $paymentId;
$this->orderId = $orderId;
$this->totalCost = $totalCost;
$this->requestedAt = $requestedAt;
}
/**
* @return PaymentId
*/
public function getPaymentId()
{
return $this->paymentId;
}
/**
* @return OrderId
*/
public function getOrderId()
{
return $this->orderId;
}
/**
* @return mixed
*/
public function getTotalCost()
{
return $this->totalCost;
}
/**
* @return \DateTimeImmutable
*/
public function getRequestedAt()
{
return $this->requestedAt;
}
}
<file_sep>/www/vendor/broadway/broadway-bundle/test/DependencyInjection/Extension/ReadModelExtensionTest.php
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) <EMAIL> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\Bundle\BroadwayBundle\DependencyInjection\Extension;
use Broadway\Bundle\BroadwayBundle\DependencyInjection\BroadwayExtension;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class ReadModelExtensionTest extends AbstractExtensionTestCase
{
/**
* {@inheritdoc}
*/
protected function getContainerExtensions()
{
return [
new BroadwayExtension(),
];
}
/**
* @test
*/
public function it_sets_in_memory_as_default_read_model_repository_factory()
{
$this->load([]);
$this->assertContainerBuilderHasAlias(
'broadway.read_model.repository_factory',
'broadway.read_model.in_memory.repository_factory'
);
}
/**
* @test
*/
public function it_sets_elasticsearch_parameters()
{
$options = [
'hosts' => [
'localhost:9200',
],
];
$this->load([
'read_model' => [
'repository' => 'elasticsearch',
'elasticsearch' => $options,
],
]);
$this->assertContainerBuilderHasServiceDefinitionWithArgument(
'broadway.elasticsearch.client',
0,
$options
);
}
/**
* @test
*/
public function it_sets_in_memory_as_read_model_repository_factory()
{
$this->load(
[
'read_model' => [
'repository' => 'in_memory',
],
]
);
$this->assertContainerBuilderHasAlias(
'broadway.read_model.repository_factory',
'broadway.read_model.in_memory.repository_factory'
);
}
}
<file_sep>/www/tests/Shop/Order/Command/CreateOrderTest.php
<?php
namespace Tests\Shop\Command;
use Broadway\CommandHandling\CommandHandler;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventHandling\EventBus;
use Broadway\EventStore\EventStore;
use Shop\Order\Command\CreateOrder;
use Shop\Order\Event\OrderCreated;
use Shop\Order\Repository;
use Shop\Order\ValueObject\OrderId;
use Shop\Order\ValueObject\OrderItem;
use Shop\Order\OrderCommandHandler;
use Shop\Product\ValueObject\ProductId;
class CreateOrderTest extends CommandHandlerScenarioTestCase
{
/**
* @test
*/
public function should_create_an_order()
{
$orderItem1 = new OrderItem(
new ProductId('00000000-0000-0000-0000-000000000322'),
5
);
$orderItem2 = new OrderItem(
new ProductId('00000000-0000-0000-0000-000000000323'),
2
);
$createOrder = new CreateOrder(
new OrderId('00000000-0000-0000-0000-000000000321'),
100,
[$orderItem1, $orderItem2],
new \DateTimeImmutable('2017-02-14')
);
$this->scenario
->given([])
->when($createOrder)
->then(
[
new OrderCreated(
$createOrder->getOrderId(),
$createOrder->getTotalCost(),
$createOrder->getItems(),
$createOrder->getCreatedAt()
)
]
);
}
/**
* Create a command handler for the given scenario test case.
*
* @param EventStore $eventStore
* @param EventBus $eventBus
*
* @return CommandHandler
*/
protected function createCommandHandler(EventStore $eventStore, EventBus $eventBus)
{
$repository = new Repository($eventStore, $eventBus);
return new OrderCommandHandler($repository);
}
}
<file_sep>/www/src/Shop/Product/Command/DeleteProduct.php
<?php
namespace Shop\Product\Command;
use Shop\Product\ValueObject\ProductId;
class DeleteProduct
{
/**
* @var ProductId
*/
private $productId;
/**
* @var \DateTimeImmutable
*/
private $deletedAt;
public function __construct(ProductId $productId, \DateTimeImmutable $deletedAt)
{
$this->productId = $productId;
$this->deletedAt = $deletedAt;
}
/**
* @return ProductId
*/
public function getProductId()
{
return $this->productId;
}
/**
* @return \DateTimeImmutable
*/
public function getDeletedAt(): \DateTimeImmutable
{
return $this->deletedAt;
}
}
<file_sep>/www/src/Shop/Product/Event/ProductUpdated.php
<?php
namespace Shop\Product\Event;
use Shop\Product\ValueObject\ProductId;
class ProductUpdated extends ProductCreated
{
/**
* @param array $data
*
* @return mixed The object instance
*/
public static function deserialize(array $data)
{
return new self(
new ProductId($data['productId']),
$data['barcode'],
$data['name'],
$data['imageUrl'],
$data['brand'],
new \DateTimeImmutable($data['updatedAt'])
);
}
/**
* @return array
*/
public function serialize()
{
return [
'productId' => (string)$this->productId,
'name' => $this->name,
'barcode' => $this->barcode,
'imageUrl' => $this->imageUrl,
'brand' => $this->brand,
'updatedAt' => $this->createdAt->format('Y-m-d\TH:i:s.uP')
];
}
}
<file_sep>/www/src/Shop/Order/Event/OrderConfirmed.php
<?php
namespace Shop\Order\Event;
use Broadway\Serializer\Serializable;
use Shop\Order\ValueObject\OrderId;
class OrderConfirmed implements Serializable
{
private $orderId;
private $confirmedAt;
/**
* @var
*/
private $totalCost;
public function __construct(OrderId $orderId, \DateTimeImmutable $confirmedAt)
{
$this->orderId = $orderId;
$this->confirmedAt = $confirmedAt;
}
/**
* @return OrderId
*/
public function getOrderId(): OrderId
{
return $this->orderId;
}
/**
* @return \DateTimeImmutable
*/
public function getConfirmedAt(): \DateTimeImmutable
{
return $this->confirmedAt;
}
/**
* @return mixed
*/
public function getTotalCost()
{
return $this->totalCost;
}
/**
* @return mixed The object instance
*/
public static function deserialize(array $data)
{
return new self(
new OrderId($data['orderId']),
new \DateTimeImmutable($data['confirmedAt'])
);
}
/**
* @return array
*/
public function serialize()
{
return [
'orderId' => (string)$this->orderId,
'confirmedAt' => $this->confirmedAt->format('Y-m-d\TH:i:s.uP')
];
}
}
<file_sep>/www/tests/Utils/Processor/Scenario.php
<?php
namespace Tests\Utils\Processor;
use Broadway\CommandHandling\Testing\TraceableCommandBus;
use Broadway\Domain\DomainMessage;
use Broadway\EventHandling\EventListener;
use Broadway\Domain\Metadata;
/**
* Class Scenario
*/
class Scenario
{
protected $processor;
protected $playhead;
protected $traceableCommandBus;
protected $testCase;
/**
* Scenario constructor.
*
* @param \PHPUnit_Framework_TestCase $testCase
* @param TraceableCommandBus $traceableCommandBus
* @param EventListener $processor
*/
public function __construct(
\PHPUnit_Framework_TestCase $testCase,
TraceableCommandBus $traceableCommandBus,
EventListener $processor
) {
$this->testCase = $testCase;
$this->traceableCommandBus = $traceableCommandBus;
$this->processor = $processor;
$this->playhead = -1;
}
/**
* @param array $events
*
* @return Scenario
*/
public function given(array $events = [])
{
foreach ($events as $given) {
$this->processor->handle($this->createDomainMessageForEvent($given));
}
return $this;
}
/**
* @param mixed $event
*
* @return Scenario
*/
public function when($event)
{
$this->traceableCommandBus->record();
$this->processor->handle($this->createDomainMessageForEvent($event));
return $this;
}
/**
* @param array $commands
*
* @return Scenario
*/
public function then(array $commands)
{
$this->testCase->assertEquals($commands, $this->traceableCommandBus->getRecordedCommands());
return $this;
}
/**
* @param $event
*
* @return DomainMessage
*/
private function createDomainMessageForEvent($event)
{
$this->playhead++;
return DomainMessage::recordNow(1, $this->playhead, new Metadata([]), $event);
}
}
<file_sep>/www/src/Shop/Product/ReadModel/Product.php
<?php
namespace Shop\Product\ReadModel;
use Broadway\ReadModel\Identifiable;
use Broadway\Serializer\Serializable;
use Shop\Product\ValueObject\ProductId;
/**
* Class User
*
* @package Soisy\Domain\IdentityAccess\ReadModel
*/
class Product implements Identifiable, Serializable
{
/**
* @var ProductId
*/
private $productId;
/**
* @var string
*/
private $barcode;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $imageUrl;
/**
* @var string
*/
private $brand;
/**
* @var \DateTimeImmutable
*/
private $createdAt;
/**
* @var \DateTimeImmutable
*/
private $updatedAt;
/**
* @return string
*/
public function getId()
{
return $this->productId;
}
/**
* @return ProductId
*/
public function getProductId(): ProductId
{
return $this->productId;
}
/**
* @param ProductId $productId
*/
public function setProductId(ProductId $productId)
{
$this->productId = $productId;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name)
{
$this->name = $name;
}
/**
* @return \DateTimeImmutable
*/
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
/**
* @param \DateTimeImmutable $createdAt
*/
public function setCreatedAt(\DateTimeImmutable $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @param \DateTimeImmutable $updatedAt
*/
public function setUpdatedAt(\DateTimeImmutable $updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return string
*/
public function getBarcode(): string
{
return $this->barcode;
}
/**
* @param string $barcode
*/
public function setBarcode(string $barcode)
{
$this->barcode = $barcode;
}
/**
* @return string
*/
public function getImageUrl(): string
{
return $this->imageUrl;
}
/**
* @param string $imageUrl
*/
public function setImageUrl(string $imageUrl)
{
$this->imageUrl = $imageUrl;
}
/**
* @return string
*/
public function getBrand(): string
{
return $this->brand;
}
/**
* @param string $brand
*/
public function setBrand(string $brand)
{
$this->brand = $brand;
}
/**
* @return mixed The object instance
*/
public static function deserialize(array $data)
{
$product = new Product();
$product->setProductId(new ProductId($data['productId']));
$product->setBarcode($data['barcode']);
$product->setName($data['name']);
$product->setImageUrl($data['imageUrl']);
$product->setBrand($data['brand']);
$product->setCreatedAt(new \DateTimeImmutable($data['createdAt']));
if (isset($data['updatedAt'])) {
$product->setUpdatedAt(new \DateTimeImmutable($data['updatedAt']));
}
return $product;
}
/**
* @return array
*/
public function serialize()
{
return [
'productId' => (string)$this->productId,
'barcode' => $this->barcode,
'name' => $this->name,
'imageUrl' => $this->imageUrl,
'brand' => $this->brand,
'createdAt' => $this->createdAt->format('Y-m-d\TH:i:s.uP'),
'updatedAt' => $this->updatedAt ? $this->updatedAt->format('Y-m-d\TH:i:s.uP') : null,
];
}
}
<file_sep>/www/vendor/broadway/broadway-bundle/test/DependencyInjection/Extension/EventStoreExtensionTest.php
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) <EMAIL> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\Bundle\BroadwayBundle\DependencyInjection\Extension;
use Broadway\Bundle\BroadwayBundle\DependencyInjection\BroadwayExtension;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class EventStoreExtensionTest extends AbstractExtensionTestCase
{
/**
* {@inheritdoc}
*/
protected function getContainerExtensions()
{
return [
new BroadwayExtension(),
];
}
/**
* @test
*/
public function it_has_in_memory_as_default_event_store()
{
$this->load([]);
$this->assertTrue(
$this->container->hasDefinition('broadway.event_store.in_memory')
);
$this->assertContainerBuilderHasAlias(
'broadway.event_store',
'broadway.event_store.in_memory'
);
}
/**
* @test
*/
public function it_sets_dbal_parameters()
{
$this->load([
'event_store' => [
'dbal' => [
'enabled' => true,
'connection' => 'my_connection',
'table' => 'my_events_table',
'use_binary' => true,
],
],
]);
$this->assertContainerBuilderHasParameter('broadway.event_store.dbal.connection', 'my_connection');
$this->assertContainerBuilderHasParameter('broadway.event_store.dbal.table', 'my_events_table');
$this->assertContainerBuilderHasParameter('broadway.event_store.dbal.use_binary', true);
}
/**
* @test
*/
public function disabling_dbal_event_store_does_not_load_its_definitions()
{
$this->load([
'event_store' => [
'dbal' => [
'enabled' => false,
],
],
]);
$this->assertContainerBuilderNotHasService('broadway.event_store.dbal');
}
}
<file_sep>/www/src/Shop/Payment/Event/PaymentDone.php
<?php
namespace Shop\Payment\Event;
use Broadway\Serializer\Serializable;
use Shop\Order\ValueObject\OrderId;
use Shop\Payment\ValueObject\PaymentId;
class PaymentDone implements Serializable
{
/**
* @var PaymentId
*/
private $paymentId;
/**
* @var OrderId
*/
private $orderId;
/**
* @var \DateTimeImmutable
*/
private $doneAt;
public function __construct(PaymentId $paymentId, OrderId $orderId, \DateTimeImmutable $doneAt)
{
$this->paymentId = $paymentId;
$this->orderId = $orderId;
$this->doneAt = $doneAt;
}
/**
* @return PaymentId
*/
public function getPaymentId()
{
return $this->paymentId;
}
/**
* @return OrderId
*/
public function getOrderId()
{
return $this->orderId;
}
/**
* @return \DateTimeImmutable
*/
public function getDoneAt()
{
return $this->doneAt;
}
/**
* @return mixed The object instance
*/
public static function deserialize(array $data)
{
return new self(
new PaymentId($data['paymentId']),
new OrderId($data['orderId']),
new \DateTimeImmutable($data['doneAt'])
);
}
/**
* @return array
*/
public function serialize()
{
return [
'paymentId' => (string)$this->paymentId,
'orderId' => (string)$this->orderId,
'doneAt' => $this->doneAt->format('Y-m-d\TH:i:s.uP')
];
}
}
<file_sep>/www/tests/Shop/Order/Process/CheckoutProcessTest.php
<?php
namespace Tests\Shop\Order\Process;
use Broadway\CommandHandling\Testing\TraceableCommandBus;
use Broadway\UuidGenerator\UuidGeneratorInterface;
use Shop\Order\Command\ConfirmOrder;
use Shop\Order\Event\OrderPaymentRequested;
use Shop\Order\Process\CheckoutProcess;
use Shop\Order\ValueObject\OrderId;
use Shop\Payment\Command\Pay;
use Shop\Payment\Event\PaymentDone;
use Shop\Payment\ValueObject\PaymentId;
use Tests\Utils\Processor\ProcessorScenarioTestCase;
class CheckoutProcessTest extends ProcessorScenarioTestCase
{
/**
* @test
*/
public function should_pay_on_order_payment_request()
{
$totalCost = 100;
$this->scenario
->when(
new OrderPaymentRequested(
new OrderId('00000000-0000-0000-0000-000000000321'),
$totalCost,
new \DateTimeImmutable('2017-06-14')
)
)
->then([
new Pay(
new PaymentId('00000000-0000-0000-0000-000000000421'),
new OrderId('00000000-0000-0000-0000-000000000321'),
$totalCost,
new \DateTimeImmutable('2017-06-14')
),
]);
}
/**
* @test
*/
public function should_confirm_order_on_order_payment_done()
{
$this->scenario
->when(
new PaymentDone(
new PaymentId('00000000-0000-0000-0000-000000000421'),
new OrderId('00000000-0000-0000-0000-000000000321'),
new \DateTimeImmutable('2017-06-14')
)
)
->then([
new ConfirmOrder(
new OrderId('00000000-0000-0000-0000-000000000321'),
new PaymentId('00000000-0000-0000-0000-000000000421'),
new \DateTimeImmutable('2017-06-14')
),
]);
}
/**
* @param TraceableCommandBus $traceableCommandBus
*
* @return mixed
*/
protected function createProcessor(TraceableCommandBus $traceableCommandBus)
{
/** @var UuidGeneratorInterface $uuidGeneratorStub */
$uuidGeneratorStub = $this->prophesize(\Broadway\UuidGenerator\UuidGeneratorInterface::class);
$uuidGeneratorStub->generate()->willReturn('00000000-0000-0000-0000-000000000421');
return new CheckoutProcess($traceableCommandBus, $uuidGeneratorStub->reveal());
}
}
<file_sep>/www/src/Shop/Order/Repository.php
<?php
namespace Shop\Order;
use Broadway\EventHandling\EventBus;
use Broadway\EventSourcing\AggregateFactory\PublicConstructorAggregateFactory;
use Broadway\EventSourcing\EventSourcingRepository;
use Broadway\EventStore\EventStore;
class Repository extends EventSourcingRepository
{
public function __construct(
EventStore $eventStore,
EventBus $eventBus
) {
parent::__construct(
$eventStore,
$eventBus,
'\Shop\Order\Aggregate\Order',
new PublicConstructorAggregateFactory());
}
}
<file_sep>/www/tests/Shop/Product/Command/CreateProductTest.php
<?php
namespace Tests\Shop\Command;
use Broadway\CommandHandling\CommandHandler;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventHandling\EventBus;
use Broadway\EventStore\EventStore;
use Shop\Product\Command\CreateProduct;
use Shop\Product\Event\ProductCreated;
use Shop\Product\ProductCommandHandler;
use Shop\Product\Repository;
use Shop\Product\ValueObject\ProductId;
class CreateProductTest extends CommandHandlerScenarioTestCase
{
/**
* @test
*/
public function should_create_a_product()
{
$createProduct = new CreateProduct(
new ProductId('00000000-0000-0000-0000-000000000321'),
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$this->scenario
->given([])
->when($createProduct)
->then(
[
new ProductCreated(
$createProduct->getProductId(),
$createProduct->getBarcode(),
$createProduct->getName(),
$createProduct->getImageurl(),
$createProduct->getBrand(),
$createProduct->getCreatedAt()
)
]
);
}
/**
* Create a command handler for the given scenario test case.
*
* @param EventStore $eventStore
* @param EventBus $eventBus
*
* @return CommandHandler
*/
protected function createCommandHandler(EventStore $eventStore, EventBus $eventBus)
{
$repository = new Repository($eventStore, $eventBus);
return new ProductCommandHandler($repository);
}
}
<file_sep>/www/src/Shop/Order/ValueObject/OrderId.php
<?php
namespace Shop\Order\ValueObject;
use Assert\Assertion;
class OrderId
{
/**
* @var string
*/
private $uuid;
/**
* ProductId constructor.
*
* @param string $uuid
*/
public function __construct(string $uuid)
{
Assertion::uuid($uuid);
$this->uuid = $uuid;
}
public function __toString()
{
return $this->uuid;
}
}
<file_sep>/www/vendor/broadway/broadway-bundle/test/DependencyInjection/Configuration/SagaConfigurationTest.php
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) <EMAIL> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\Bundle\BroadwayBundle\DependencyInjection\Configuration;
use Broadway\Bundle\BroadwayBundle\DependencyInjection\Configuration;
use Broadway\Bundle\BroadwayBundle\TestCase;
use Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait;
class SagaConfigurationTest extends TestCase
{
use ConfigurationTestCaseTrait;
/**
* @inheritdoc
*/
protected function getConfiguration()
{
return new Configuration();
}
/**
* @test
*/
public function it_does_not_set_defaults()
{
$this->assertProcessedConfigurationEquals([], [], 'saga');
}
/**
* @test
*/
public function it_sets_in_memory_as_default_state_repository()
{
$this->assertProcessedConfigurationEquals(
[
'broadway' => [
'saga' => [],
],
],
[
'saga' => [
'repository' => 'in_memory',
'mongodb' => [
'storage_suffix' => null,
'connection' => [
'dsn' => null,
'database' => null,
'options' => [],
],
],
],
],
'saga'
);
}
/**
* @test
*/
public function only_in_memory_and_mongodb_are_valid_state_repositories()
{
$this->assertConfigurationIsInvalid(
[
'broadway' => [
'saga' => [
'repository' => 'false_name',
],
],
],
'The value "false_name" is not allowed for path "broadway.saga.repository". Permissible values: "in_memory", "mongodb"'
);
}
/**
* @test
*/
public function it_processes_saga_configuration_with_mongodb_repository()
{
$this->assertProcessedConfigurationEquals(
[
'broadway' => [
'saga' => [
'repository' => 'mongodb',
'mongodb' => [
'connection' => [
'dsn' => 'mongodb://192.168.127.12:27018/awesome',
'database' => 'my_database',
'options' => [
'connectTimeoutMS' => 50,
],
],
'storage_suffix' => 'my_suffix',
],
],
],
],
[
'saga' => [
'repository' => 'mongodb',
'mongodb' => [
'connection' => [
'dsn' => 'mongodb://192.168.127.12:27018/awesome',
'database' => 'my_database',
'options' => [
'connectTimeoutMS' => 50,
],
],
'storage_suffix' => 'my_suffix',
],
],
],
'saga'
);
}
/**
* @test
*/
public function it_processes_saga_configuration_with_in_memory_repository()
{
$this->assertProcessedConfigurationEquals(
[
'broadway' => [
'saga' => [
'repository' => 'in_memory',
],
],
],
[
'saga' => [
'repository' => 'in_memory',
'mongodb' => [
'storage_suffix' => null, // @todo remove this as it is not related to in memory repository
'connection' => [
'dsn' => null,
'database' => null,
'options' => [],
],
],
],
],
'saga'
);
}
}
<file_sep>/www/src/Shop/Product/Aggregate/Product.php
<?php
namespace Shop\Product\Aggregate;
use Broadway\EventSourcing\EventSourcedAggregateRoot;
use Shop\Product\Command\CreateProduct;
use Shop\Product\Command\DeleteProduct;
use Shop\Product\Command\UpdateProduct;
use Shop\Product\Event\ProductCreated;
use Shop\Product\Event\ProductDeleted;
use Shop\Product\Event\ProductUpdated;
class Product extends EventSourcedAggregateRoot
{
private $id;
public static function create(CreateProduct $command)
{
$product = new self();
$product->apply(
new ProductCreated(
$command->getProductId(),
$command->getBarcode(),
$command->getName(),
$command->getImageurl(),
$command->getBrand(),
$command->getCreatedAt()
)
);
return $product;
}
public function update(UpdateProduct $command)
{
$this->apply(new ProductUpdated(
$command->getProductId(),
$command->getBarcode(),
$command->getName(),
$command->getImageurl(),
$command->getBrand(),
$command->getCreatedAt()
));
}
public function delete(DeleteProduct $command)
{
$this->apply(new ProductDeleted(
$command->getProductId(),
$command->getDeletedAt()
)
);
}
protected function applyProductCreated(ProductCreated $event)
{
$this->id = $event->getProductId();
}
/**
* @return string
*/
public function getAggregateRootId()
{
return $this->id;
}
}
<file_sep>/www/src/Shop/Order/Aggregate/Order.php
<?php
namespace Shop\Order\Aggregate;
use Broadway\EventSourcing\EventSourcedAggregateRoot;
use Shop\Order\Command\Checkout;
use Shop\Order\Command\CreateOrder;
use Shop\Order\Event\OrderConfirmed;
use Shop\Order\Event\OrderCreated;
use Shop\Order\Event\OrderPaymentRequested;
use Shop\Order\Exception\CheckoutDenied;
use Shop\Product\Command\CreateProduct;
use Shop\Product\Command\DeleteProduct;
use Shop\Product\Command\UpdateProduct;
use Shop\Product\Event\ProductCreated;
use Shop\Product\Event\ProductDeleted;
use Shop\Product\Event\ProductUpdated;
class Order extends EventSourcedAggregateRoot
{
private $id;
/**
* @var \DateTimeImmutable
*/
private $confirmedAt;
public static function create(CreateOrder $command)
{
$product = new self();
$product->apply(
new OrderCreated(
$command->getOrderId(),
$command->getTotalCost(),
$command->getItems(),
$command->getCreatedAt()
)
);
return $product;
}
public function checkout(Checkout $command)
{
if($this->confirmedAt) {
throw new CheckoutDenied();
}
$this->apply(new OrderPaymentRequested(
$command->getOrderId(),
$command->getTotalCost(),
$command->getRequestedAt()
));
}
protected function applyOrderCreated(OrderCreated $event)
{
$this->id = $event->getOrderId();
}
protected function applyOrderConfirmed(OrderConfirmed $event)
{
$this->confirmedAt = $event->getConfirmedAt();
}
/**
* @return string
*/
public function getAggregateRootId()
{
return $this->id;
}
}
<file_sep>/www/tests/Shop/Order/ValueObject/OrderIdTest.php
<?php
namespace Tests\Shop\Order\ValueObject;
use Shop\Order\ValueObject\OrderId;
class OrderIdTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function should_accept_valid_uuid()
{
$orderId = new OrderId('00000000-0000-0000-0000-000000000321');
$this->assertEquals('00000000-0000-0000-0000-000000000321', $orderId);
}
/**
* @test
* @expectedException \Assert\InvalidArgumentException
*/
public function should_not_accept_not_valid_uuid()
{
new OrderId('-0000-0000-0000-000000000321');
}
}
<file_sep>/www/src/Shop/Product/Command/CreateProduct.php
<?php
namespace Shop\Product\Command;
use Shop\Product\ValueObject\ProductId;
class CreateProduct
{
private $productId;
private $barcode;
private $name;
private $imageUrl;
private $brand;
/**
* @var \DateTimeImmutable
*/
private $createdAt;
public function __construct(ProductId $productId, $barcode, $name, $imageUrl, $brand, \DateTimeImmutable $createdAt)
{
$this->productId = $productId;
$this->barcode = $barcode;
$this->name = $name;
$this->imageUrl = $imageUrl;
$this->brand = $brand;
$this->createdAt = $createdAt;
}
public function getProductId()
{
return $this->productId;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getBarcode()
{
return $this->barcode;
}
/**
* @return string
*/
public function getBrand()
{
return $this->brand;
}
/**
* @return mixed
*/
public function getImageUrl()
{
return $this->imageUrl;
}
/**
* @return \DateTimeImmutable
*/
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
}
<file_sep>/www/src/Shop/Product/Event/ProductDeleted.php
<?php
namespace Shop\Product\Event;
use Broadway\Serializer\Serializable;
use Shop\Product\ValueObject\ProductId;
class ProductDeleted implements Serializable
{
/**
* @var ProductId
*/
private $productId;
/**
* @var \DateTimeImmutable
*/
private $deletedAt;
public function __construct(ProductId $productId, \DateTimeImmutable $deletedAt)
{
$this->productId = $productId;
$this->deletedAt = $deletedAt;
}
/**
* @return ProductId
*/
public function getProductId()
{
return $this->productId;
}
/**
* @return \DateTimeImmutable
*/
public function getDeletedAt(): \DateTimeImmutable
{
return $this->deletedAt;
}
/**
* @return mixed The object instance
*/
public static function deserialize(array $data)
{
return new self(
new ProductId($data['productId']),
new \DateTimeImmutable($data['deletedAt'])
);
}
/**
* @return array
*/
public function serialize()
{
return [
'productId' => (string)$this->productId,
'deletedAt' => $this->deletedAt->format('Y-m-d\TH:i:s.uP')
];
}
}
<file_sep>/www/vendor/broadway/broadway-bundle/test/BroadwayBundleTest.php
<?php
namespace Broadway\Bundle\BroadwayBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class BroadwayBundleTest extends TestCase
{
/**
* @test
*/
public function it_builds_the_bundle()
{
$container = new ContainerBuilder();
$bundle = new BroadwayBundle();
$bundle->build($container);
$container->compile();
}
}
<file_sep>/www/src/Shop/Order/OrderCommandHandler.php
<?php
namespace Shop\Order;
use Broadway\CommandHandling\SimpleCommandHandler;
use Shop\Order\Aggregate\Order;
use Shop\Order\Command\Checkout;
use Shop\Order\Command\CreateOrder;
class OrderCommandHandler extends SimpleCommandHandler
{
/**
* @var \Broadway\Repository\Repository
*/
private $repository;
public function __construct(\Broadway\Repository\Repository $repository)
{
$this->repository = $repository;
}
public function handleCreateOrder(CreateOrder $command)
{
$product = Order::create($command);
$this->repository->save($product);
}
public function handleCheckout(Checkout $command)
{
/** @var Order $order */
$order = $this->repository->load($command->getOrderId());
$order->checkout($command);
$this->repository->save($order);
}
}
<file_sep>/www/vendor/broadway/read-model-elasticsearch/README.md
broadway/read-model-elasticsearch
=================================
Elasticsearch read model implementation for [broadway/broadway](https://github.com/broadway/broadway)
using [elastic/elasticsearch-php](https://github.com/elastic/elasticsearch-php)
[](https://travis-ci.org/broadway/read-model-elasticsearch)
## Installation
```
$ composer require broadway/read-model-elasticsearch
```
## License
MIT, see LICENSE.
<file_sep>/www/src/Shop/Product/ProductCommandHandler.php
<?php
namespace Shop\Product;
use Broadway\CommandHandling\SimpleCommandHandler;
use Shop\Product\Aggregate\Product;
use Shop\Product\Command\CreateProduct;
use Shop\Product\Command\DeleteProduct;
use Shop\Product\Command\UpdateProduct;
class ProductCommandHandler extends SimpleCommandHandler
{
/**
* @var \Broadway\Repository\Repository
*/
private $repository;
public function __construct(\Broadway\Repository\Repository $repository)
{
$this->repository = $repository;
}
public function handleCreateProduct(CreateProduct $command)
{
$product = Product::create($command);
$this->repository->save($product);
}
public function handleUpdateProduct(UpdateProduct $command)
{
/** @var Product $product */
$product = $this->repository->load($command->getProductId());
$product->update($command);
$this->repository->save($product);
}
public function handleDeleteProduct(DeleteProduct $command)
{
/** @var Product $product */
$product = $this->repository->load($command->getProductId());
$product->delete($command);
$this->repository->save($product);
}
}
<file_sep>/www/src/Shop/Order/Exception/CheckoutDenied.php
<?php
namespace Shop\Order\Exception;
class CheckoutDenied extends \DomainException
{
}
<file_sep>/www/tests/Shop/Product/Projector/ProductProjectorTest.php
<?php
namespace Tests\Shop\Product\ValueObject;
use Broadway\ReadModel\InMemory\InMemoryRepository;
use Broadway\ReadModel\Projector;
use Broadway\ReadModel\Testing\ProjectorScenarioTestCase;
use Shop\Product\Event\ProductCreated;
use Shop\Product\Event\ProductDeleted;
use Shop\Product\Event\ProductUpdated;
use Shop\Product\Projector\ProductProjector;
use Shop\Product\ReadModel\Product;
use Shop\Product\ValueObject\ProductId;
class ProductProjectorTest extends ProjectorScenarioTestCase
{
/**
* @test
*/
public function should_create_a_product()
{
$productCreated = new ProductCreated(
new ProductId('00000000-0000-0000-0000-000000000321'),
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$product = new Product();
$product->setProductId($productCreated->getProductId());
$product->setBarcode($productCreated->getBarcode());
$product->setName($productCreated->getName());
$product->setImageUrl($productCreated->getImageUrl());
$product->setBrand($productCreated->getBrand());
$product->setCreatedAt($productCreated->getCreatedAt());
$this->scenario
->given([])
->when($productCreated)
->then([$product]);
}
/**
* @test
*/
public function should_update_a_product()
{
$productId = new ProductId('00000000-0000-0000-0000-000000000321');
$productCreated = new ProductCreated(
$productId,
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$productUpdated = new ProductUpdated(
$productId,
'5707055029609',
'Nome prodotto: Scaaarpe più belle',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake1.png',
'Brand prodotto: Super Scaaaarpe più belle',
new \DateTimeImmutable('2017-03-14')
);
$product = new Product();
$product->setProductId($productCreated->getProductId());
$product->setBarcode('5707055029609');
$product->setName('Nome prodotto: Scaaarpe più belle');
$product->setImageUrl('http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake1.png');
$product->setBrand('Brand prodotto: Super Scaaaarpe più belle');
$product->setCreatedAt(new \DateTimeImmutable('2017-02-14'));
$product->setUpdatedAt(new \DateTimeImmutable('2017-03-14'));
$this->scenario
->given([$productCreated])
->when($productUpdated)
->then([$product]);
}
/**
* @test
*/
public function should_delete_a_product()
{
$productId = new ProductId('00000000-0000-0000-0000-000000000321');
$productCreated = new ProductCreated(
$productId,
'5707055029608',
'Nome prodotto: Scaaarpe',
'http://static.politifact.com.s3.amazonaws.com/subjects/mugs/fake.png',
'Brand prodotto: Super Scaaaarpe',
new \DateTimeImmutable('2017-02-14')
);
$productDeleted = new ProductDeleted(
$productId,
new \DateTimeImmutable('2017-03-14')
);
$this->scenario
->given([$productCreated])
->when($productDeleted)
->then([]);
}
/**
* @return Projector
*/
protected function createProjector(InMemoryRepository $repository)
{
return new ProductProjector($repository);
}
}
<file_sep>/www/src/Shop/Payment/ValueObject/PaymentId.php
<?php
namespace Shop\Payment\ValueObject;
use Assert\Assertion;
class PaymentId
{
/**
* @var string
*/
private $uuid;
/**
* ProductId constructor.
*
* @param string $uuid
*/
public function __construct(string $uuid)
{
Assertion::uuid($uuid);
$this->uuid = $uuid;
}
public function __toString()
{
return $this->uuid;
}
}
<file_sep>/www/vendor/broadway/broadway-bundle/test/DependencyInjection/CompilerPass/DefineDBALEventStoreConnectionCompilerPassTest.php
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) <EMAIL> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\Bundle\BroadwayBundle\DependencyInjection\Configuration\CompilerPass;
use Broadway\Bundle\BroadwayBundle\DependencyInjection\DefineDBALEventStoreConnectionCompilerPass;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
class DefineDBALEventStoreConnectionCompilerPassTest extends AbstractCompilerPassTestCase
{
/**
* {@inheritdoc}
*/
protected function registerCompilerPass(ContainerBuilder $container)
{
$container->addCompilerPass(new DefineDBALEventStoreConnectionCompilerPass('broadway'));
}
/**
* @test
*/
public function it_aliases_the_dbal_connection()
{
$this->container->setParameter('broadway.event_store.dbal.connection', 'default');
$this->container->setDefinition('doctrine.dbal.default_connection', new Definition());
$this->compile();
$this->assertContainerBuilderHasAlias(
'broadway.event_store.dbal.connection',
'doctrine.dbal.default_connection'
);
}
/**
* @test
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Invalid broadway config: DBAL connection "default" not found
*/
public function it_throws_when_connection_not_defined()
{
$this->container->setParameter('broadway.event_store.dbal.connection', 'default');
$this->compile();
}
}
<file_sep>/README.md
# Cqrs Event sourcing workshop
Requisiti
=
- Vagrant (> 1.8.x) con plugin HostManager (vagrant plugin install vagrant-hostmanager)
- Virtualbox (>= 5.1.28)
Configurazione del progetto
===========================
Scaricare la box al seguente indirizzo: https://drive.google.com/open?id=0B4Ycwv0y_vu3b2lqODBxS3V5eG8
e salvarla nel PATH/ROOT/DEL/PROGETTO
```
cd PATH/ROOT/DEL/PROGETTO
vagrant box add new-cqrs-es-ws new-cqrs-es-ws.box
vagrant box list -> dovrebbe mostrare la box appena aggiunta
vagrant up --provider=virtualbox
vagrant ssh
cd /var/www
```
Per lanciare i test:
```
cd /var/www
vendor/bin/phpunit -c ./ --colors
```
<file_sep>/www/tests/Utils/Processor/ProcessorScenarioTestCase.php
<?php
namespace Tests\Utils\Processor;
use Broadway\CommandHandling\Testing\TraceableCommandBus;
use PHPUnit_Framework_TestCase as TestCase;
/**
* Class ProcessorScenarioTestCase
*/
abstract class ProcessorScenarioTestCase extends TestCase
{
/**
* @var Scenario
*/
protected $scenario;
public function setUp()
{
$this->scenario = $this->createScenario();
}
/**
* @return Scenario
*/
protected function createScenario()
{
$traceableCommandBus = new TraceableCommandBus();
$process = $this->createProcessor($traceableCommandBus);
return new Scenario($this, $traceableCommandBus, $process);
}
/**
* @param TraceableCommandBus $traceableCommandBus
*
* @return mixed
*/
abstract protected function createProcessor(TraceableCommandBus $traceableCommandBus);
}
<file_sep>/www/src/Shop/Product/Event/ProductCreated.php
<?php
namespace Shop\Product\Event;
use Broadway\Serializer\Serializable;
use Shop\Product\ValueObject\ProductId;
class ProductCreated implements Serializable
{
protected $productId;
protected $barcode;
/**
* @var string
*/
protected $name;
protected $imageUrl;
protected $brand;
protected $createdAt;
/**
* ProductCreated constructor.
*
* @param $productId
* @param string $barcode
* @param string $name
* @param string $imageUrl
* @param string $brand
* @param \DateTimeImmutable $createdAt
*/
public function __construct(
ProductId $productId,
string $barcode,
string $name,
string $imageUrl,
string $brand,
\DateTimeImmutable $createdAt
) {
$this->productId = $productId;
$this->barcode = $barcode;
$this->name = $name;
$this->imageUrl = $imageUrl;
$this->brand = $brand;
$this->createdAt = $createdAt;
}
public function getProductId()
{
return $this->productId;
}
/**
* @return \DateTimeImmutable
*/
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getBarcode()
{
return $this->barcode;
}
/**
* @return mixed
*/
public function getBrand()
{
return $this->brand;
}
/**
* @return string
*/
public function getImageUrl(): string
{
return $this->imageUrl;
}
/**
* @param array $data
*
* @return mixed The object instance
*/
public static function deserialize(array $data)
{
return new self(
new ProductId($data['productId']),
$data['barcode'],
$data['name'],
$data['imageUrl'],
$data['brand'],
new \DateTimeImmutable($data['createdAt'])
);
}
/**
* @return array
*/
public function serialize()
{
return [
'productId' => (string)$this->productId,
'name' => $this->name,
'barcode' => $this->barcode,
'imageUrl' => $this->imageUrl,
'brand' => $this->brand,
'createdAt' => $this->createdAt->format('Y-m-d\TH:i:s.uP')
];
}
}
<file_sep>/www/src/Shop/Order/Process/CheckoutProcess.php
<?php
namespace Shop\Order\Process;
use Broadway\Processor\Processor;
use Broadway\UuidGenerator\UuidGeneratorInterface;
use Shop\Order\Command\ConfirmOrder;
use Shop\Order\Event\OrderPaymentRequested;
use Shop\Payment\Command\Pay;
use Shop\Payment\Event\PaymentDone;
use Shop\Payment\ValueObject\PaymentId;
class CheckoutProcess extends Processor
{
/**
* @var \Broadway\CommandHandling\CommandBus
*/
private $commandBus;
/**
* @var UuidGeneratorInterface
*/
private $uuidGenerator;
public function __construct(\Broadway\CommandHandling\CommandBus $commandBus, UuidGeneratorInterface $uuidGenerator)
{
$this->commandBus = $commandBus;
$this->uuidGenerator = $uuidGenerator;
}
public function handleOrderPaymentRequested(OrderPaymentRequested $event)
{
$this->commandBus->dispatch(new Pay(
new PaymentId($this->uuidGenerator->generate()),
$event->getOrderId(),
$event->getTotalCost(),
$event->getRequestedAt()
));
}
public function handlePaymentDone(PaymentDone $event)
{
$this->commandBus->dispatch(new ConfirmOrder(
$event->getOrderId(),
$event->getPaymentId(),
$event->getDoneAt()
));
}
}
<file_sep>/www/tests/Shop/Service/Process/MailerTest.php
<?php
namespace Tests\Shop\Service\Process;
use Shop\Order\Event\OrderConfirmed;
use Shop\Order\ValueObject\OrderId;
use Shop\Service\Mailer;
class MailerTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function should_send_email_on_order_confirmation()
{
$orderConfirmed = new OrderConfirmed(
new OrderId('00000000-0000-0000-0000-000000000321'),
new \DateTimeImmutable('2017-02-14')
);
/** @var Mailer $mailer */
$mailer = $this->prophesize(Mailer::class);
$mailer->send(
'<EMAIL>',
'<EMAIL>', 'Order ' . (string)$orderConfirmed->getOrderId() . ' confirmed.'
)->shouldBeCalled();
$mailerProcessor = new \Shop\Service\Process\Mailer($mailer->reveal());
$mailerProcessor->handleOrderConfirmed($orderConfirmed);
}
}
<file_sep>/www/vendor/broadway/broadway-bundle/test/DependencyInjection/Extension/SagaExtensionTest.php
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) <EMAIL> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\Bundle\BroadwayBundle\DependencyInjection\Extension;
use Broadway\Bundle\BroadwayBundle\DependencyInjection\BroadwayExtension;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class SagaExtensionTest extends AbstractExtensionTestCase
{
/**
* {@inheritdoc}
*/
protected function getContainerExtensions()
{
return [
new BroadwayExtension(),
];
}
/**
* @test
*/
public function it_does_not_configure_saga_by_default()
{
$this->load([]);
$this->assertContainerBuilderNotHasService('broadway.saga.state.state_manager');
$this->assertContainerBuilderNotHasService('broadway.saga.state.repository');
}
/**
* @test
*/
public function it_aliases_the_in_memory_saga_state_repository()
{
$this->load([
'saga' => [
'repository' => 'in_memory',
],
]);
$this->assertContainerBuilderHasAlias(
'broadway.saga.state.repository',
'broadway.saga.state.in_memory_repository'
);
}
/**
* @test
*/
public function it_uses_the_configured_storage_suffix_for_mongodb_saga_storage()
{
$this->load([
'saga' => [
'repository' => 'mongodb',
'mongodb' => [
'storage_suffix' => 'foo_suffix'
]
]
]);
$this->assertContainerBuilderHasParameter('broadway.saga.mongodb.storage_suffix', 'foo_suffix');
}
/**
* @test
*/
public function it_defaults_to_empty_string_when_no_storage_suffix_is_configured()
{
$this->load(['saga' => [
'repository' => 'mongodb',
]]);
$this->assertContainerBuilderHasParameter('broadway.saga.mongodb.storage_suffix', '');
}
/**
* @test
*/
public function it_uses_configured_connection_details()
{
$dsn = 'mongodb://192.168.3.11:27018/awesome';
$options = [
'connectTimeoutMS' => 50
];
$this->load([
'saga' => [
'repository' => 'mongodb',
'mongodb' => [
'connection' => [
'dsn' => $dsn,
'database' => 'my_database',
'options' => $options,
],
],
],
]);
$this->assertContainerBuilderHasServiceDefinitionWithArgument(
'broadway.saga.state.mongodb_connection',
0,
$dsn
);
$this->assertContainerBuilderHasServiceDefinitionWithArgument(
'broadway.saga.state.mongodb_connection',
1,
$options
);
}
}
<file_sep>/www/src/Shop/Product/Projector/ProductProjector.php
<?php
namespace Shop\Product\Projector;
use Broadway\ReadModel\Projector;
use Broadway\ReadModel\Repository;
use Shop\Product\Event\ProductCreated;
use Shop\Product\Event\ProductDeleted;
use Shop\Product\Event\ProductUpdated;
use Shop\Product\ReadModel\Product;
class ProductProjector extends Projector
{
private $repository;
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
protected function applyProductCreated(ProductCreated $event)
{
$product = new Product();
$product->setProductId($event->getProductId());
$product->setBarcode($event->getBarcode());
$product->setName($event->getName());
$product->setImageUrl($event->getImageUrl());
$product->setBrand($event->getBrand());
$product->setCreatedAt($event->getCreatedAt());
$this->repository->save($product);
}
protected function applyProductUpdated(ProductUpdated $event)
{
/** @var Product $product */
$product = $this->repository->find($event->getProductId());
$product->setBarcode($event->getBarcode());
$product->setName($event->getName());
$product->setImageUrl($event->getImageUrl());
$product->setBrand($event->getBrand());
$product->setUpdatedAt($event->getCreatedAt());
$this->repository->save($product);
}
protected function applyProductDeleted(ProductDeleted $event)
{
/** @var Product $product */
$product = $this->repository->find($event->getProductId());
$this->repository->remove((string)$product->getId());
}
}
<file_sep>/www/src/Shop/Order/Command/ConfirmOrder.php
<?php
namespace Shop\Order\Command;
use Shop\Order\ValueObject\OrderId;
use Shop\Payment\ValueObject\PaymentId;
class ConfirmOrder
{
/**
* @var OrderId
*/
private $orderId;
private $paymentId;
/**
* @var \DateTimeImmutable
*/
private $confirmedAt;
public function __construct(OrderId $orderId, PaymentId $paymentId, \DateTimeImmutable $confirmedAt)
{
$this->orderId = $orderId;
$this->paymentId = $paymentId;
$this->confirmedAt = $confirmedAt;
}
/**
* @return OrderId
*/
public function getOrderId(): OrderId
{
return $this->orderId;
}
/**
* @return PaymentId
*/
public function getPaymentId(): PaymentId
{
return $this->paymentId;
}
/**
* @return \DateTimeImmutable
*/
public function getConfirmedAt(): \DateTimeImmutable
{
return $this->confirmedAt;
}
}
<file_sep>/www/src/Shop/Order/Command/CreateOrder.php
<?php
namespace Shop\Order\Command;
use Shop\Order\ValueObject\OrderId;
class CreateOrder
{
/**
* @var OrderId
*/
private $orderId;
private $totalCost;
/**
* @var array
*/
private $items;
/**
* @var \DateTimeImmutable
*/
private $createdAt;
public function __construct(OrderId $orderId, $totalCost, array $items, \DateTimeImmutable $createdAt)
{
$this->orderId = $orderId;
$this->totalCost = $totalCost;
$this->items = $items;
$this->createdAt = $createdAt;
}
/**
* @return OrderId
*/
public function getOrderId()
{
return $this->orderId;
}
/**
* @return mixed
*/
public function getTotalCost()
{
return $this->totalCost;
}
/**
* @return array
*/
public function getItems()
{
return $this->items;
}
/**
* @return \DateTimeImmutable
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}
<file_sep>/www/src/Shop/Order/Command/Checkout.php
<?php
namespace Shop\Order\Command;
use Shop\Order\ValueObject\OrderId;
class Checkout
{
/**
* @var OrderId
*/
private $orderId;
private $totalCost;
/**
* @var \DateTimeImmutable
*/
private $requestedAt;
public function __construct(OrderId $orderId, $totalCost, \DateTimeImmutable $requestedAt)
{
$this->orderId = $orderId;
$this->totalCost = $totalCost;
$this->requestedAt = $requestedAt;
}
/**
* @return OrderId
*/
public function getOrderId()
{
return $this->orderId;
}
/**
* @return mixed
*/
public function getTotalCost()
{
return $this->totalCost;
}
/**
* @return \DateTimeImmutable
*/
public function getRequestedAt()
{
return $this->requestedAt;
}
}
<file_sep>/www/src/Shop/Order/ValueObject/OrderItem.php
<?php
namespace Shop\Order\ValueObject;
use Shop\Product\ValueObject\ProductId;
class OrderItem
{
/**
* @var ProductId
*/
private $productId;
private $quantity;
public function __construct(ProductId $productId, $quantity)
{
$this->productId = $productId;
$this->quantity = $quantity;
}
/**
* @return ProductId
*/
public function getProductId()
{
return $this->productId;
}
/**
* @return mixed
*/
public function getQuantity()
{
return $this->quantity;
}
}
| 8f7049aa77d0314eac679f9a8e9b76f3d7843b02 | [
"Markdown",
"PHP"
] | 47 | PHP | danielsan80/cqrs-es-ws | 8a3bc718f608210a442ebf460117ab90fa8a49a5 | 54f44c8c064906a931f4b031146022ee3f8c6df0 |
refs/heads/master | <repo_name>DavidBetteridge/SQLServerFreeSpace<file_sep>/README.md
# SQL Server Free Space Viewer
This tool allows you to visualise the free space in a SQL server database.

First run the collect data option. This will examine each of the GAM pages in your database to determine the number of unallocated extents. This information will then be written to a binary file using protobuf.
Once the data file has been generated the view data option can be used. This will plot a graph showing the space used in each GAM.
Each red line in the graph represents 100 extents. The higher the line the more data has been allocated.
Green shows the unallocated space.
White means the GAM doesn't exist. This can appear at the end of the graph.
Glossary:
* Page - 8K worth of data
* Extent - A set of 8 pages.
* GAM - 4GB worth of pages.
Limitations:
* Only databases with single files are supported.
<file_sep>/Form1.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ProtoBuf;
namespace DisplayFreeSpace
{
public partial class Form1 : Form
{
private const int GAM_SIZE = 511232;
private string currentRead = "";
private Data data = new Data();
public Form1()
{
InitializeComponent();
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
private void Form1_Load(object sender, EventArgs e)
{
this.data.Extents = new bool[5000000];
this.hScrollBar1.Minimum = 0;
this.hScrollBar1.Maximum = this.data.Extents.Length;
//LoadAndStoreData();
LoadData();
}
private void LoadAndStoreData()
{
var sb = new SqlConnectionStringBuilder();
sb.InitialCatalog = "S2C1_UKPortal";
sb.DataSource = "HD08";
sb.IntegratedSecurity = true;
using (var cn = new SqlConnection(sb.ToString()))
{
cn.Open();
cn.InfoMessage += Cn_InfoMessage;
using (var cmd = new SqlCommand())
{
cmd.Connection = cn;
cmd.CommandText = "DBCC TRACEON(3604)";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
ReadGAMPage(cn, cmd, 2);
for (int gamNumber = 1; gamNumber <= 75; gamNumber++)
{
ReadGAMPage(cn, cmd, gamNumber * GAM_SIZE);
}
}
}
using (var file = File.Create(@"c:\temp\allocations.bin"))
{
Serializer.Serialize(file, this.data);
}
}
private void LoadData()
{
using (var file = File.OpenRead(@"c:\temp\allocations.bin"))
{
this.data = Serializer.Deserialize<Data>(file);
}
}
private void ReadGAMPage(SqlConnection cn, SqlCommand cmd, int pageNumber)
{
cmd.CommandText = "DBCC PAGE(0, 1," + pageNumber + ",3)";
this.currentRead = "";
cmd.ExecuteNonQuery();
//Skip till we reach
//GAM: Extent Alloc Status @0x00000000154DA0C2
var allLines = this.currentRead
.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Where(l => l.StartsWith("("))
.ToList();
foreach (var line in allLines)
{
//(1:0) -(1:32072) = ALLOCATED
//(1:32080) - = NOT ALLOCATED
var bits = line.Replace(" ", "").Split('-');
var bits2 = bits[1].Split('=');
var from = bits[0];
var to = bits2[0];
var fromPage = from.Replace("(", "").Replace(")", "").Split(':')[1];
var toPage = fromPage;
if (!string.IsNullOrWhiteSpace(to))
{
toPage = to.Replace("(", "").Replace(")", "").Split(':')[1];
}
for (int extentNumber = int.Parse(fromPage) / 8; extentNumber <= (int.Parse(toPage) / 8); extentNumber++)
{
this.data.Extents[extentNumber] = (bits2[1] == "ALLOCATED");
}
}
}
private void Cn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError info in e.Errors)
{
currentRead += info.Message;
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
var allocatedBrush = new SolidBrush(Color.Red);
var unallocatedBrush = new SolidBrush(Color.Green);
var currentFrameSize = 0;
var windowSize = 100;
var frameAllocated = 0;
var nextX = 0;
var midPoint = 500 - (windowSize / 2);
for (int i = this.hScrollBar1.Value; i < this.hScrollBar1.Value + (1000 * windowSize); i++)
{
currentFrameSize++;
if (this.data.Extents[i]) frameAllocated++;
if (currentFrameSize == windowSize)
{
g.DrawLine(Pens.Green, nextX, 500, nextX, 500 - windowSize);
g.DrawLine(Pens.Red, nextX, midPoint + (frameAllocated / 2), nextX, midPoint - (frameAllocated / 2));
currentFrameSize = 0;
frameAllocated = 0;
nextX++;
}
if (i * 8 % GAM_SIZE <= 10)
{
g.DrawLine(Pens.Black, nextX - 1, 500, nextX - 1, 500 - windowSize - 25);
}
if (i * 8 % GAM_SIZE == 0)
{
g.DrawString("Gam: " + ((i * 8) / GAM_SIZE), this.Font, new SolidBrush(Color.Black), nextX, 500 - windowSize - 25);
}
}
}
private void hScrollBar1_ValueChanged(object sender, EventArgs e)
{
this.Invalidate();
}
}
}
<file_sep>/ViewData.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace DisplayFreeSpace
{
public partial class ViewData : UserControl
{
public ViewData()
{
InitializeComponent();
this.txtStorageFile1.Text = @"c:\temp\allocations.bin";
this.txtStorageFile2.Text = @"c:\temp\now.bin";
}
private void cmdCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void cmdOK_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(this.txtStorageFile1.Text))
{
MessageBox.Show("Please enter the location of the storage file", "View Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.txtStorageFile1.Focus();
return;
}
if (!File.Exists(this.txtStorageFile1.Text))
{
MessageBox.Show("The first storage file does not exist.", "View Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.txtStorageFile1.Focus();
return;
}
if (!string.IsNullOrWhiteSpace(this.txtStorageFile2.Text) && !File.Exists(this.txtStorageFile2.Text))
{
MessageBox.Show("The second storage file does not exist.", "View Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.txtStorageFile2.Focus();
return;
}
var frm = new MainForm(this.txtStorageFile1.Text, this.txtStorageFile2.Text);
frm.ShowDialog();
}
}
}
<file_sep>/MainForm.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ProtoBuf;
namespace DisplayFreeSpace
{
public partial class MainForm : Form
{
private const int GAM_SIZE = 511232;
private const int WINDOW_SIZE = 100;
private const int BOTTOM_OF_TOP_GRAPH = 200;
private const int BOTTOM_OF_LOWER_GRAPH = 400;
private string path1;
private string path2;
private Data data1 = new Data();
private Data data2 = new Data();
public MainForm(string path1, string path2)
{
InitializeComponent();
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.path1 = path1;
this.path2 = path2;
}
private void Form1_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
using (var file = File.OpenRead(this.path1))
{
this.data1 = Serializer.Deserialize<Data>(file);
}
if (!string.IsNullOrWhiteSpace(this.path2))
{
using (var file = File.OpenRead(this.path2))
{
this.data2 = Serializer.Deserialize<Data>(file);
}
}
this.hScrollBar1.Minimum = 0;
this.hScrollBar1.Maximum = this.data1.Extents.Length - (this.ClientSize.Width * WINDOW_SIZE);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
var allocatedBrush = new SolidBrush(Color.Red);
var unallocatedBrush = new SolidBrush(Color.Green);
var currentFrameSize1 = 0;
var frameAllocated1 = 0;
var nextX1 = 0;
var currentFrameSize2 = 0;
var frameAllocated2 = 0;
var nextX2 = 0;
var midPoint = BOTTOM_OF_LOWER_GRAPH - (WINDOW_SIZE / 2);
var midPoint2 = BOTTOM_OF_TOP_GRAPH - (WINDOW_SIZE / 2);
g.FillRectangle(new SolidBrush(Color.LightGray), 0, BOTTOM_OF_LOWER_GRAPH - WINDOW_SIZE - 25, this.ClientSize.Width, 25);
g.FillRectangle(Brushes.LightGray, 0, BOTTOM_OF_TOP_GRAPH - WINDOW_SIZE - 25, this.ClientSize.Width, 25);
for (int i = this.hScrollBar1.Value; i < this.hScrollBar1.Value + (this.ClientSize.Width * WINDOW_SIZE); i++)
{
// File 1
currentFrameSize1++;
DrawFile1(g, ref currentFrameSize1, WINDOW_SIZE, ref frameAllocated1, ref nextX1, midPoint, i);
// File2
currentFrameSize2++;
DrawFile2(g, ref currentFrameSize2, WINDOW_SIZE, ref frameAllocated2, ref nextX2, midPoint2, i);
}
var titleFont = new Font(this.Font.FontFamily, 12, FontStyle.Regular);
g.DrawLine(Pens.Black, 0, BOTTOM_OF_LOWER_GRAPH, this.ClientSize.Width, BOTTOM_OF_LOWER_GRAPH);
g.DrawLine(Pens.Black, 0, BOTTOM_OF_LOWER_GRAPH - WINDOW_SIZE, this.ClientSize.Width, BOTTOM_OF_LOWER_GRAPH - WINDOW_SIZE);
g.DrawLine(Pens.Black, 0, BOTTOM_OF_LOWER_GRAPH - WINDOW_SIZE - 25, this.ClientSize.Width, BOTTOM_OF_LOWER_GRAPH - WINDOW_SIZE - 25);
g.DrawString(this.path1, titleFont, new SolidBrush(Color.Black), 5, BOTTOM_OF_LOWER_GRAPH - WINDOW_SIZE - 55);
g.DrawLine(Pens.Black, 0, BOTTOM_OF_TOP_GRAPH, this.ClientSize.Width, BOTTOM_OF_TOP_GRAPH);
g.DrawLine(Pens.Black, 0, BOTTOM_OF_TOP_GRAPH - WINDOW_SIZE, this.ClientSize.Width, BOTTOM_OF_TOP_GRAPH - WINDOW_SIZE);
g.DrawLine(Pens.Black, 0, BOTTOM_OF_TOP_GRAPH - WINDOW_SIZE - 25, this.ClientSize.Width, BOTTOM_OF_TOP_GRAPH - WINDOW_SIZE - 25);
g.DrawString(this.path2, titleFont, new SolidBrush(Color.Black), 5, BOTTOM_OF_TOP_GRAPH - WINDOW_SIZE - 55);
}
private void DrawFile1(Graphics g, ref int currentFrameSize, int windowSize, ref int frameAllocated, ref int nextX, int midPoint, int i)
{
if (i < this.data1.Extents.Length)
{
if (this.data1.Extents[i]) frameAllocated++;
if (currentFrameSize == windowSize)
{
g.DrawLine(Pens.Green, nextX, BOTTOM_OF_LOWER_GRAPH, nextX, BOTTOM_OF_LOWER_GRAPH - windowSize);
g.DrawLine(Pens.Red, nextX, midPoint + (frameAllocated / 2), nextX, midPoint - (frameAllocated / 2));
currentFrameSize = 0;
frameAllocated = 0;
nextX++;
}
}
else
{
if (currentFrameSize == windowSize)
{
currentFrameSize = 0;
frameAllocated = 0;
nextX++;
}
}
if (i * 8 % GAM_SIZE <= 10)
{
g.DrawLine(Pens.Black, nextX - 1, BOTTOM_OF_LOWER_GRAPH, nextX - 1, BOTTOM_OF_LOWER_GRAPH - windowSize - 25);
}
if (i * 8 % GAM_SIZE == 0)
{
g.DrawString("Gam: " + ((i * 8) / GAM_SIZE), this.Font, new SolidBrush(Color.Black), nextX, BOTTOM_OF_LOWER_GRAPH - windowSize - 20);
}
}
private void DrawFile2(Graphics g, ref int currentFrameSize, int windowSize, ref int frameAllocated, ref int nextX, int midPoint, int i)
{
if (i < this.data2.Extents.Length)
{
if (this.data2.Extents[i]) frameAllocated++;
if (currentFrameSize == windowSize)
{
g.DrawLine(Pens.Green, nextX, BOTTOM_OF_TOP_GRAPH, nextX, BOTTOM_OF_TOP_GRAPH - windowSize);
g.DrawLine(Pens.Red, nextX, midPoint + (frameAllocated / 2), nextX, midPoint - (frameAllocated / 2));
currentFrameSize = 0;
frameAllocated = 0;
nextX++;
}
}
else
{
if (currentFrameSize == windowSize)
{
currentFrameSize = 0;
frameAllocated = 0;
nextX++;
}
}
if (i * 8 % GAM_SIZE <= 10)
{
g.DrawLine(Pens.Black, nextX - 1, BOTTOM_OF_TOP_GRAPH, nextX - 1, BOTTOM_OF_TOP_GRAPH - windowSize - 25);
}
if (i * 8 % GAM_SIZE == 0)
{
g.DrawString("Gam: " + ((i * 8) / GAM_SIZE), this.Font, new SolidBrush(Color.Black), nextX, BOTTOM_OF_TOP_GRAPH - windowSize - 20);
}
}
private void hScrollBar1_ValueChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void MainForm_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
}
}
<file_sep>/SideMenu.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace DisplayFreeSpace
{
public partial class SideMenu : UserControl
{
private Color ButtonSelected = Color.FromArgb(161, 189, 227);
private Color MouseOverButton = Color.FromArgb(218, 218, 218);
private Color MouseOverSelectedButton = Color.FromArgb(122, 163, 219);
public event EventHandler<string> ButtonClicked;
public SideMenu()
{
InitializeComponent();
panel1.BackColor = Color.FromArgb(242, 242, 242);
// Select this control
this.lblCollect.Tag = "SELECTED";
this.lblCollect.BackColor = ButtonSelected;
}
private void Button_MouseEnter(object sender, EventArgs e)
{
var lbl = sender as Label;
if (lbl == null) return;
if ((string)lbl.Tag == "SELECTED")
{
lbl.BackColor = MouseOverSelectedButton;
}
else
lbl.BackColor = MouseOverButton;
}
private void Button_MouseLeave(object sender, EventArgs e)
{
var lbl = sender as Label;
if (lbl == null) return;
if ((string)lbl.Tag == "SELECTED")
{
lbl.BackColor = ButtonSelected;
}
else
lbl.BackColor = panel1.BackColor;
}
private void Button_Clicked(object sender, EventArgs e)
{
var lbl = sender as Label;
if (lbl == null) return;
// De-select the other controls
foreach (var ctl in this.panel1.Controls)
{
var l = ctl as Label;
if (l != null)
{
l.Tag = "";
l.BackColor = this.panel1.BackColor;
}
}
// Select this control
lbl.Tag = "SELECTED";
lbl.BackColor = ButtonSelected;
// Tell the world
ButtonClicked?.Invoke(lbl, lbl.Name);
}
}
}
<file_sep>/Collect.cs
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using ProtoBuf;
using System.Threading.Tasks;
namespace DisplayFreeSpace
{
public partial class Collect : UserControl
{
private const int GAM_SIZE = 511232;
private string currentRead = "";
private Data data = new Data();
public Collect()
{
InitializeComponent();
}
private void Collect_Load(object sender, EventArgs e)
{
this.txtDatabaseName.Text = "S2C1_UKPortal";
this.txtDatabaseServerName.Text = "HD08";
this.txtStorageFile.Text = @"c:\temp\now.bin";
this.lblProgress.Visible = false;
}
private void cmdCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private async void cmdOK_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(this.txtDatabaseName.Text))
{
MessageBox.Show("Please enter the database name", "Collect Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.txtDatabaseName.Focus();
return;
}
if (string.IsNullOrWhiteSpace(this.txtDatabaseServerName.Text))
{
MessageBox.Show("Please enter the database server name", "Collect Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.txtDatabaseServerName.Focus();
return;
}
if (string.IsNullOrWhiteSpace(this.txtStorageFile.Text))
{
MessageBox.Show("Please enter the location for the storage file", "Collect Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.txtStorageFile.Focus();
return;
}
lblProgress.Visible = true;
var sb = new SqlConnectionStringBuilder();
sb.InitialCatalog = this.txtDatabaseName.Text;
sb.DataSource = this.txtDatabaseServerName.Text; ;
sb.IntegratedSecurity = true;
lblProgress.Text = "Connecting to the database";
using (var cn = new SqlConnection(sb.ToString()))
{
await cn.OpenAsync();
cn.InfoMessage += Cn_InfoMessage;
using (var cmd = new SqlCommand())
{
this.lblProgress.Text = $"Setting trace flag.";
cmd.Connection = cn;
cmd.CommandText = "DBCC TRACEON(3604)";
cmd.CommandType = CommandType.Text;
await cmd.ExecuteNonQueryAsync();
this.lblProgress.Text = $"Calculating number of GAM intervals";
cmd.CommandText = "SELECT total_page_count FROM sys.dm_db_file_space_usage";
var totalIntervalCount = (long)(await cmd.ExecuteScalarAsync());
totalIntervalCount = totalIntervalCount / 511232;
this.data.Extents = new bool[(totalIntervalCount+1) * 511232 / 8];
this.lblProgress.Text = $"Getting data for GAM interval 0 of {totalIntervalCount}.";
await ReadGAMPage(cn, cmd, 2);
for (int gamNumber = 1; gamNumber <= totalIntervalCount; gamNumber++)
{
this.lblProgress.Text = $"Getting data for GAM interval {gamNumber} of {totalIntervalCount}.";
await ReadGAMPage(cn, cmd, gamNumber * GAM_SIZE);
}
}
}
lblProgress.Text = "Creating storage file";
using (var file = File.Create(this.txtStorageFile.Text))
{
Serializer.Serialize(file, this.data);
}
lblProgress.Visible = false;
MessageBox.Show("Complete", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async Task ReadGAMPage(SqlConnection cn, SqlCommand cmd, int pageNumber)
{
cmd.CommandText = "DBCC PAGE(0, 1," + pageNumber + ",3)";
this.currentRead = "";
await cmd.ExecuteNonQueryAsync();
//Skip till we reach
//GAM: Extent Alloc Status @0x00000000154DA0C2
var allLines = this.currentRead
.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Where(l => l.StartsWith("("))
.ToList();
foreach (var line in allLines)
{
//(1:0) -(1:32072) = ALLOCATED
//(1:32080) - = NOT ALLOCATED
var bits = line.Replace(" ", "").Split('-');
var bits2 = bits[1].Split('=');
var from = bits[0];
var to = bits2[0];
var fromPage = from.Replace("(", "").Replace(")", "").Split(':')[1];
var toPage = fromPage;
if (!string.IsNullOrWhiteSpace(to))
{
toPage = to.Replace("(", "").Replace(")", "").Split(':')[1];
}
for (int extentNumber = int.Parse(fromPage) / 8; extentNumber <= (int.Parse(toPage) / 8); extentNumber++)
{
this.data.Extents[extentNumber] = (bits2[1] == "ALLOCATED");
}
}
}
private void Cn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError info in e.Errors)
{
currentRead += info.Message;
}
}
}
}
<file_sep>/Data.cs
using ProtoBuf;
namespace DisplayFreeSpace
{
[ProtoContract]
public class Data
{
[ProtoMember(1)]
public bool[] Extents;
}
}
<file_sep>/WelcomeForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DisplayFreeSpace
{
public partial class WelcomeForm : Form
{
public WelcomeForm()
{
InitializeComponent();
}
private void sideMenu1_ButtonClicked(object sender, string e)
{
switch (e.ToUpper())
{
case "LBLCOLLECT":
collect1.Visible = true;
viewData1.Visible = false;
break;
case "LBLVIEW":
collect1.Visible = false;
viewData1.Visible = true;
break;
default:
break;
}
}
private void collect1_Load(object sender, EventArgs e)
{
}
}
}
| 8f869c06c4ea51082a363c7f98ade4088e9572bb | [
"Markdown",
"C#"
] | 8 | Markdown | DavidBetteridge/SQLServerFreeSpace | f94e843b626970b603bee87b154f84c862a3d077 | 5bb7a3aac4c6e64493126f9bad5d9bd064bb5605 |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, forkJoin } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class DetailService {
constructor(private http: HttpClient) {}
getFilms(urls: string[]): Observable<any> {
const responses = [];
urls.forEach(url => {
const response = this.http.get(url)
.pipe(catchError(this.handleError));
responses.push(response);
});
return forkJoin(responses);
}
private handleError(error: HttpErrorResponse) {
console.error(error);
return Observable.throw(error || 'Server error');
}
}<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatCardModule } from '@angular/material/card';
import { MatListModule } from '@angular/material/list';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { AppComponent } from './app.component';
import { CharactersComponent } from './components/characters/characters.component';
import { DetailComponent } from './components/characters/detail/detail.component';
@NgModule({
declarations: [
AppComponent,
CharactersComponent,
DetailComponent,
],
imports: [
BrowserModule,
HttpClientModule,
MatToolbarModule,
MatCardModule,
MatListModule,
MatIconModule,
MatProgressSpinnerModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import {
Component,
Input,
OnInit,
OnChanges,
SimpleChanges } from '@angular/core';
import { DetailService } from '../../../services/detail.service';
@Component({
selector: 'detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.scss'],
providers: [DetailService]
})
export class DetailComponent implements OnInit, OnChanges {
@Input() data: any;
@Input() status: Status;
character: any;
films: any;
constructor(private detailService: DetailService) { }
ngOnInit(): void {
this.status = {
loading: false,
success: false,
error: false
}
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.data && changes.data.currentValue) {
this.character = changes.data.currentValue;
this.films = [];
this.getFilms(this.character.films);
}
}
getFilms(urls: string[]): void {
this.detailService.getFilms(urls)
.subscribe(data => {
if (data) {
this.status = {
loading: false,
success: true,
error: false
}
this.films = data;
}
});
}
}
interface Status {
loading: boolean;
success: boolean;
error: boolean;
}
<file_sep><header>
<mat-toolbar color="primary">
<mat-toolbar-row class="app-title">GALAXYDEX</mat-toolbar-row>
<mat-toolbar-row class="app-subtitle">An Exhaustive Data Resource From a Galaxy Far, Far Away</mat-toolbar-row>
</mat-toolbar>
</header>
<section class="container">
<characters></characters>
</section>
<footer>Created by <NAME> courtesy of the Star Wars API</footer>
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class CharactersService {
constructor(private http: HttpClient) {}
getCharacters(): Observable<any> {
return this.http.get('assets/characters.json');
}
getCharacterData(url): Observable<any> {
return this.http.get(url)
.pipe(catchError(this.handleError));
}
private handleError(error: HttpErrorResponse) {
console.error(error);
return Observable.throw(error || 'Server error');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { CharactersService } from '../../services/characters.service';
@Component({
selector: 'characters',
templateUrl: './characters.component.html',
styleUrls: ['./characters.component.scss'],
providers: [CharactersService]
})
export class CharactersComponent implements OnInit {
status: Status;
characters: any;
characterData: any;
selectedCharacter: string;
constructor(private charactersService: CharactersService) { }
ngOnInit() {
this.status = {
loading: false,
success: false,
error: false
}
this.charactersService.getCharacters()
.subscribe(data => {
this.characters = data.characters;
});
}
handleClick(character: Character) {
if (this.selectedCharacter !== character.name) {
this.selectedCharacter = character.name;
this.getCharacterData(character.url);
}
}
getCharacterData(url: string) {
this.status = {
loading: true,
success: false,
error: false
};
this.charactersService.getCharacterData(url)
.subscribe(data => {
if (data) {
this.characterData = data;
}
}, err => {
this.status = {
loading: false,
success: false,
error: true
}
});
}
}
interface Status {
loading: boolean;
success: boolean;
error: boolean;
}
interface Character {
name: string;
url: string;
}
| 6f2764c57a02fa62803e9fb690796dcb9db56269 | [
"TypeScript",
"HTML"
] | 6 | TypeScript | graigjanssen/GalaxyDex | 781f44ca67ed98dd21494cfd70276d820dd34034 | fbc0204a05951c26035193c4389b289b68a744b4 |
refs/heads/master | <repo_name>ItsPriyesh/Pro_android<file_sep>/app/src/main/java/io/prolabs/pro/algo/UserXp.java
package io.prolabs.pro.algo;
/**
* Created by Edmund on 2015-03-07.
*/
public class UserXp {
private double totalXp;
public UserXp(double totalXp) {
this.totalXp = totalXp;
}
public double getTotalXp() {
return totalXp;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/algo/XpCalculator.java
package io.prolabs.pro.algo;
/**
* Created by Edmund on 2015-03-07.
*/
public interface XpCalculator {
UserXp calculateXp(FullUserStats stats);
}<file_sep>/app/src/main/java/io/prolabs/pro/ui/common/BaseToolBarActivity.java
package io.prolabs.pro.ui.common;
import android.graphics.Typeface;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import io.prolabs.pro.R;
public class BaseToolBarActivity extends ActionBarActivity {
@InjectView(R.id.toolbar)
protected Toolbar toolbar;
@InjectView(R.id.toolbarTitle)
protected TextView toolbarTitle;
private ActionBar actionBar;
@Override
public void setContentView(int layoutResId) {
super.setContentView(layoutResId);
ButterKnife.inject(this);
toolbarTitle.setTypeface(Typeface.createFromAsset(getAssets(), "ZonaPro-Bold.otf"));
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void setToolbarTitle(String title) {
toolbarTitle.setText(title);
}
protected void disableToolbarElevation() {
toolbar.setElevation(0);
}
protected void showToolbarBackButton() {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/ui/profile/LanguagesFragment.java
package io.prolabs.pro.ui.profile;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.squareup.otto.Subscribe;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.ButterKnife;
import butterknife.InjectView;
import io.prolabs.pro.R;
import io.prolabs.pro.algo.FullUserStats;
import io.prolabs.pro.eventing.GitHubDataAggregator;
import io.prolabs.pro.models.github.Language;
import io.prolabs.pro.models.github.Repo;
import timber.log.Timber;
public class LanguagesFragment extends Fragment {
private static final long UPDATE_LANG_DELAY = 1000;
@InjectView(R.id.languageList)
ListView languageListView;
private GitHubDataAggregator gitHubAggregator;
private volatile boolean updating = false;
private volatile Map<Repo, List<Language>> languagesByRepo = new HashMap<>();
public LanguagesFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_languages, container, false);
ButterKnife.inject(this, view);
gitHubAggregator = GitHubDataAggregator.getInstance();
gitHubAggregator.register(this);
return view;
}
@Subscribe
public synchronized void receivedStats(FullUserStats stats) {
Map<Repo, List<Language>> receivedLanguages = stats.getLanguagesByRepo();
languagesByRepo = receivedLanguages;
if (!updating) {
updating = true;
new Handler().postDelayed(this::updateUI, UPDATE_LANG_DELAY);
}
}
private synchronized void updateUI() {
Map<String, Long> displayedLanguages = new HashMap<>();
for (List<Language> langs : languagesByRepo.values()) {
for (Language lang : langs) {
String name = lang.getName();
long bytes = lang.getBytes();
Timber.i("Adding language: " + lang.getName());
long bytesToAdd = bytes;
if (displayedLanguages.containsKey(name)) {
bytesToAdd += displayedLanguages.get(name);
}
displayedLanguages.put(name, bytesToAdd);
}
}
languageListView.setAdapter(
new LanguageAdapter(getActivity(), displayedLanguages));
updating = false;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/eventing/LanguagesReceived.java
package io.prolabs.pro.eventing;
import java.util.List;
import io.prolabs.pro.models.github.Language;
import io.prolabs.pro.models.github.Repo;
/**
* Created by Edmund on 2015-03-07.
*/
public class LanguagesReceived {
private Repo repo;
private List<Language> languages;
public LanguagesReceived(Repo repo, List<Language> languages) {
this.repo = repo;
this.languages = languages;
}
public Repo getRepo() {
return repo;
}
public List<Language> getLanguages() {
return languages;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/eventing/GistsReceived.java
package io.prolabs.pro.eventing;
import java.util.List;
import io.prolabs.pro.models.github.Gist;
/**
* Created by Edmund on 2015-03-08.
*/
public class GistsReceived {
private List<Gist> gists;
public List<Gist> getGists() {
return gists;
}
public GistsReceived(List<Gist> gists) {
this.gists = gists;
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'retrolambda'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "io.prolabs.pro"
minSdkVersion 15
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
retrolambda {
jvmArgs '-noverify'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Google
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.google.code.gson:gson:2.3.+'
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:support-v4:21.0.3'
compile group: 'com.google.guava', name: 'guava', version: '18.0'
// Square
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.squareup:otto:1.3.6'
compile 'com.jakewharton.timber:timber:2.7.1'
compile 'com.jakewharton:butterknife:6.1.0'
compile 'com.squareup.picasso:picasso:2.5.0'
// Other
compile 'com.orhanobut:hawk:1.4-SNAPSHOT'
compile 'de.hdodenhof:circleimageview:1.2.2'
compile 'com.melnykov:floatingactionbutton:1.2.0'
compile 'org.scribe:scribe:1.3.7'
compile 'io.reactivex:rxandroid:0.24.0'
}
<file_sep>/app/src/main/java/io/prolabs/pro/api/github/GitHubApi.java
package io.prolabs.pro.api.github;
import android.util.Base64;
import com.orhanobut.hawk.Hawk;
import com.squareup.okhttp.OkHttpClient;
import io.prolabs.pro.ProApp;
import io.prolabs.pro.models.github.GitHubUser;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
public class GitHubApi {
public static final int MAX_REPOS_PER_PAGE = 100;
private static final String BASE_URL = "https://api.github.com";
private static final String ACCEPT_HEADER_NAME = "Accept";
private static final String ACCEPT_HEADER_VALUE = "application/vnd.github.v3+json";
private static final String AUTH_HEADER_NAME = "Authorization";
private static GitHubService gitHubService = null;
private static String AUTH_HEADER_VALUE;
private static GitHubUser currentUser;
public static GitHubService getService(String username, String password) {
if (gitHubService == null) {
generateAuthValue(username, password);
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(new OkHttpClient()))
.setRequestInterceptor(request -> {
request.addHeader(ACCEPT_HEADER_NAME, ACCEPT_HEADER_VALUE);
request.addHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE);
})
.setEndpoint(BASE_URL)
.build();
gitHubService = restAdapter.create(GitHubService.class);
}
return gitHubService;
}
public static void deleteService() {
gitHubService = null;
}
public static GitHubService getService(String authKey) {
if (gitHubService == null) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(new OkHttpClient()))
.setRequestInterceptor(request -> {
request.addHeader(ACCEPT_HEADER_NAME, ACCEPT_HEADER_VALUE);
request.addHeader(AUTH_HEADER_NAME, authKey);
})
.setEndpoint(BASE_URL)
.build();
gitHubService = restAdapter.create(GitHubService.class);
}
return gitHubService;
}
public static GitHubService getService() {
if (gitHubService != null) return gitHubService;
else throw new IllegalAccessError("An authorized GitHub service has not been created");
}
private static String generateAuthValue(String username, String password) {
AUTH_HEADER_VALUE = "Basic " + Base64.encodeToString(
String.format("%s:%s", username, password).getBytes(), Base64.NO_WRAP);
return AUTH_HEADER_VALUE;
}
public static GitHubUser getCurrentUser() {
return currentUser;
}
public static void setCurrentUser(GitHubUser user) {
currentUser = user;
}
public static void saveCurrentAuth(GitHubUser user) {
setCurrentUser(user);
Hawk.put(ProApp.GITHUB_USER, user);
Hawk.put(ProApp.GITHUB_AUTH_KEY, AUTH_HEADER_VALUE);
}
public static void clearCurrentAuth() {
Hawk.remove(ProApp.GITHUB_AUTH_KEY);
Hawk.remove(ProApp.GITHUB_USER);
}
}<file_sep>/app/src/main/java/io/prolabs/pro/eventing/CodeWeeksReceived.java
package io.prolabs.pro.eventing;
import java.util.List;
import io.prolabs.pro.models.github.CodeWeek;
import io.prolabs.pro.models.github.Repo;
/**
* Created by Edmund on 2015-03-08.
*/
public class CodeWeeksReceived {
private List<CodeWeek> codeWeeks;
private Repo repo;
public CodeWeeksReceived(Repo repo, List<CodeWeek> codeWeeks) {
this.codeWeeks = codeWeeks;
this.repo = repo;
}
public List<CodeWeek> getCodeWeeks() {
return codeWeeks;
}
public Repo getRepo() {
return repo;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/ui/main/MainActivity.java
package io.prolabs.pro.ui.main;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.prolabs.pro.R;
import io.prolabs.pro.api.github.GitHubApi;
import io.prolabs.pro.models.github.GitHubUser;
import io.prolabs.pro.ui.common.BaseToolBarActivity;
import io.prolabs.pro.ui.profile.ProfileActivity;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import static io.prolabs.pro.utils.CallbackUtils.callback;
public class MainActivity extends BaseToolBarActivity {
@InjectView(R.id.drawer_layout)
DrawerLayout drawerLayout;
@InjectView(R.id.profile_pic)
CircleImageView circleImageView;
@InjectView(R.id.username)
TextView username;
@InjectView(R.id.name)
TextView name;
private ActionBarDrawerToggle drawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setToolbarTitle("Pro");
drawerToggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
drawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.primary_dark));
drawerLayout.setDrawerListener(drawerToggle);
GitHubApi.getService().getAuthUser(callback(
gitHubUser -> {
Picasso.with(MainActivity.this).load(gitHubUser.getAvatarUrl()).into(circleImageView);
username.setText(gitHubUser.getUsername());
name.setText(gitHubUser.getName());
},
error -> {
// Do nothing
}
));
}
private void setupHeader(GitHubUser user) {
Picasso.with(MainActivity.this).load(user.getAvatarUrl()).into(circleImageView);
username.setText(user.getUsername());
name.setText(user.getName());
}
@SuppressWarnings("unused")
@OnClick(R.id.header)
public void openProfile() {
startActivity(new Intent(this, ProfileActivity.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("unused")
@OnItemClick(R.id.drawer_list)
public void onNavItemClicked(int position) {
switch (position) {
}
drawerLayout.closeDrawers();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START | Gravity.LEFT)) {
drawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/ui/settings/SettingsFragment.java
package io.prolabs.pro.ui.settings;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v4.app.ActivityCompat;
import io.prolabs.pro.R;
import io.prolabs.pro.api.github.GitHubApi;
import io.prolabs.pro.ui.SplashActivity;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference logout = findPreference("logout");
logout.setOnPreferenceClickListener(pref -> {
new AlertDialog.Builder(getActivity())
.setMessage("Are you sure you want to logout?")
.setPositiveButton("Yes", (dialog, id) -> logout())
.setNegativeButton("No", (dialog, id) -> dialog.dismiss())
.create().show();
return true;
});
}
private void logout() {
GitHubApi.clearCurrentAuth();
GitHubApi.deleteService();
startActivity(new Intent(getActivity(), SplashActivity.class));
ActivityCompat.finishAffinity(getActivity());
}
}<file_sep>/app/src/main/java/io/prolabs/pro/ui/profile/InfoFragment.java
package io.prolabs.pro.ui.profile;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import io.prolabs.pro.R;
import io.prolabs.pro.Tips;
import io.prolabs.pro.algo.FullUserStats;
import io.prolabs.pro.algo.UserXp;
import io.prolabs.pro.algo.XpCalculator;
import io.prolabs.pro.algo.XpCalculators;
import io.prolabs.pro.api.github.GitHubApi;
import io.prolabs.pro.eventing.GitHubDataAggregator;
import io.prolabs.pro.eventing.GitHubRequester;
import io.prolabs.pro.models.github.GitHubUser;
import io.prolabs.pro.models.github.Repo;
import io.prolabs.pro.ui.common.SwipeDismissTouchListener;
import io.prolabs.pro.utils.GitHubUtils;
import io.prolabs.pro.utils.ViewUtils;
public class InfoFragment extends Fragment {
private static final long UPDATE_XP_DELAY = 1000;
@InjectView(R.id.xpCardView)
CardView xpCard;
@InjectView(R.id.generalInfoCard)
CardView generalInfoCard;
@InjectView(R.id.tipsContainer)
ViewGroup tipsContainer;
@InjectView(R.id.publicReposCount)
TextView publicReposText;
@InjectView(R.id.privateReposCount)
TextView privateReposText;
@InjectView(R.id.totalStarsCount)
TextView totalStarsText;
@InjectView(R.id.xpValue)
TextView xpTextView;
private List<Repo> repos = new ArrayList<>();
private XpCalculator xpCalculator;
private volatile boolean updating = false;
private volatile FullUserStats currentStats;
public InfoFragment() {
// Required empty public constructor
}
public static long roundToSignificantFigures(double num) {
if (num == 0) {
return 0;
}
final double d = Math.ceil(Math.log10(num < 0 ? -num : num));
final int n = (int) Math.ceil(d / 2);
final int power = n - (int) d;
final double magnitude = Math.pow(10, power);
final long shifted = Math.round(num * magnitude);
return (long) (shifted / magnitude);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_info, container, false);
ButterKnife.inject(this, view);
GitHubUser user = GitHubApi.getCurrentUser();
publicReposText.setText(String.valueOf(user.getPublicRepoCount()));
privateReposText.setText(String.valueOf(user.getPrivateReposCount()));
xpCalculator = XpCalculators.SIMPLE;
GitHubDataAggregator aggregator = GitHubDataAggregator.getInstance();
aggregator.register(this);
CardView cardView = createTipCard();
cardView.setOnTouchListener(getListener(cardView));
tipsContainer.addView(cardView);
return view;
}
private CardView createTipCard() {
int margin = ViewUtils.dpToPx(16, getActivity());
LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
containerParams.setMargins(margin, 0, margin, margin);
CardView.LayoutParams cardParams = new CardView.LayoutParams(
CardView.LayoutParams.MATCH_PARENT, CardView.LayoutParams.WRAP_CONTENT);
cardParams.setMargins(margin, margin, margin, margin);
CardView cardView = new CardView(getActivity());
cardView.setLayoutParams(containerParams);
cardView.setClickable(true);
cardView.setOnTouchListener(getListener(cardView));
TextView tipText = new TextView(getActivity());
tipText.setLayoutParams(cardParams);
tipText.setText(Tips.getRandomTip());
cardView.addView(tipText);
return cardView;
}
private SwipeDismissTouchListener getListener(CardView cardView) {
return new SwipeDismissTouchListener(
cardView,
null,
new SwipeDismissTouchListener.DismissCallbacks() {
@Override
public boolean canDismiss(Object token) {
return true;
}
@Override
public void onDismiss(View view, Object token) {
tipsContainer.removeView(cardView);
tipsContainer.addView(createTipCard());
}
});
}
@Subscribe
public synchronized void updateStats(FullUserStats stats) {
if (!updating) {
updating = true;
new Handler().postDelayed(this::updateUI, UPDATE_XP_DELAY);
}
currentStats = stats;
}
private void updateUI() {
List<Repo> repoList = new ArrayList<>(currentStats.getRepos());
totalStarsText.setText(String.valueOf(GitHubUtils.getTotalStars(repoList)));
UserXp currentXp = xpCalculator.calculateXp(currentStats);
long rounded = roundToSignificantFigures(currentXp.getTotalXp());
xpTextView.setText(String.valueOf(rounded));
updating = false;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/ui/settings/SettingsActivity.java
package io.prolabs.pro.ui.settings;
import android.os.Bundle;
import io.prolabs.pro.R;
import io.prolabs.pro.ui.common.BaseToolBarActivity;
public class SettingsActivity extends BaseToolBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setToolbarTitle("Settings");
showToolbarBackButton();
getFragmentManager().beginTransaction()
.add(R.id.container, new SettingsFragment())
.commit();
}
}<file_sep>/app/src/main/java/io/prolabs/pro/eventing/GitHubRequester.java
package io.prolabs.pro.eventing;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
import java.util.HashSet;
import java.util.List;
import io.prolabs.pro.api.github.GitHubApi;
import io.prolabs.pro.models.github.CodeWeek;
import io.prolabs.pro.models.github.GitHubUser;
import io.prolabs.pro.models.github.Language;
import io.prolabs.pro.models.github.Repo;
import io.prolabs.pro.utils.GitHubUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import timber.log.Timber;
import static io.prolabs.pro.utils.CallbackUtils.callback;
/**
* Created by Edmund on 2015-03-07.
*/
public class GitHubRequester {
private static GitHubRequester instance = new GitHubRequester();
private final Bus bus = new Bus(ThreadEnforcer.MAIN);
private GitHubRequester() {
}
public static GitHubRequester getInstance() {
return instance;
}
void register(Object obj) {
bus.register(obj);
}
private void requestCodeWeeksForRepo(final Repo repo) {
GitHubUser currentUser = GitHubApi.getCurrentUser();
GitHubApi.getService().getCodeFrequency(currentUser.getUsername(), repo.getName(), callback(
(jsonElement) -> {
List<CodeWeek> codeWeeks = GitHubUtils.parseCodeFrequencyResponse(jsonElement);
bus.post(new CodeWeeksReceived(repo, codeWeeks));
},
error -> Timber.i("Failed to retrieve codeweeks for repo: " + repo.getName() + ": " + error.getMessage())
));
}
public void requestAllStats() {
requestGists();
GitHubApi.getService().getRepos(GitHubApi.MAX_REPOS_PER_PAGE, callback(
repos -> {
bus.post(new ReposReceived(new HashSet<>(repos)));
for (Repo repo : repos) {
requestLanguageForRepo(repo);
requestCodeWeeksForRepo(repo);
requestCommitHistoryForRepo(repo);
}
},
this::logError)
);
}
public void requestCommitHistoryForRepo(Repo repo) {
GitHubUser user = GitHubApi.getCurrentUser();
GitHubApi.getService().getCommitActivity(user.getUsername(), repo.getName(), callback(
commitActivity -> bus.post(new CommitsReceived(repo, commitActivity)),
error -> Timber.i("Failed to retrieve commit history for " + repo.getName() + ": " + error.getMessage()))
);
}
public void requestLanguageForRepo(final Repo repo) {
GitHubUser user = GitHubApi.getCurrentUser();
if (user == null) {
return;
}
GitHubApi.getService().getLanguages(user.getUsername(), repo.getName(), callback(
jsonElement -> {
List<Language> languages = GitHubUtils.parseLanguageResponse(jsonElement);
bus.post(new LanguagesReceived(repo, languages));
for (Language language : languages)
Timber.i("Language received: " + language.getName() + " : " + language.getBytes());
},
error -> logRepoError(repo, error)
));
}
public void requestGists() {
GitHubApi.getService().getGists(callback(
gists -> bus.post(new GistsReceived(gists)),
this::logError
));
}
private boolean is404(Throwable error) {
// return error.getKind() == RetrofitError.Kind.HTTP &&
// error.getResponse().getStatus() == 404;
return false;
}
private void logError(Throwable error) {
Timber.i(error.getMessage());
}
private void logRepoError(Repo repo, Throwable error) {
if (!is404(error))
Timber.i("Failed to get repo: " + repo.getName());
else
Timber.i("Private repo could not be downloaded: " + repo.getName());
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/Tips.java
package io.prolabs.pro;
/**
* Created by Edmund on 2015-03-08.
*/
public class Tips {
public static final String[] TIPS = {
"Try to commit at least once every day!",
"Code something new every once in a while!",
"Try new languages!",
"Spread the word! The more forks and stars, the better!",
"Open your sources! We don't analyze private repositories!"
};
public static String getRandomTip() {
return TIPS[(int) (Math.floor(Math.random() * TIPS.length))];
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/algo/FullUserStats.java
package io.prolabs.pro.algo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.prolabs.pro.models.github.CodeWeek;
import io.prolabs.pro.models.github.CommitActivity;
import io.prolabs.pro.models.github.Language;
import io.prolabs.pro.models.github.Repo;
/**
* Created by Edmund on 2015-03-07.
*/
public class FullUserStats {
private final Map<? extends Repo, ? extends List<CommitActivity>> commits;
private final Map<Repo, List<CodeWeek>> weeksOfCodeByRepo;
private final Map<Repo, List<Language>> languagesByRepo;
private final Set<Repo> repos;
public FullUserStats(Map<? extends Repo, ? extends List<CommitActivity>> commits, Map<Repo, List<CodeWeek>> weeksOfCode, Map<Repo, List<Language>> languagesByRepo, Set<Repo> repos) {
this.commits = commits;
this.weeksOfCodeByRepo = weeksOfCode;
this.languagesByRepo = languagesByRepo;
this.repos = repos;
}
public FullUserStats() {
this.commits = new HashMap<>();
this.repos = new HashSet<>();
this.weeksOfCodeByRepo = new HashMap<>();
this.languagesByRepo = new HashMap<>();
}
public FullUserStats setWeeksOfCode(Map<Repo, List<CodeWeek>> weeksOfCode) {
return new FullUserStats(commits, weeksOfCode, languagesByRepo, repos);
}
public FullUserStats addWeeksOfCode(Repo repo, List<CodeWeek> codeWeeks) {
Map<Repo, List<CodeWeek>> newWeeks = new HashMap<>();
newWeeks.putAll(weeksOfCodeByRepo);
newWeeks.put(repo, codeWeeks);
return setWeeksOfCode(newWeeks);
}
public Map<Repo, List<Language>> getLanguagesByRepo() {
return languagesByRepo;
}
public FullUserStats setLanguagesByRepo(Map<Repo, List<Language>> languagesByRepo) {
return new FullUserStats(commits, weeksOfCodeByRepo, languagesByRepo, repos);
}
public FullUserStats addLanguagesByRepo(Repo repo, List<Language> languages) {
Map<Repo, List<Language>> newLanguagesByRepo = new HashMap<>();
newLanguagesByRepo.putAll(languagesByRepo);
newLanguagesByRepo.put(repo, languages);
return setLanguagesByRepo(newLanguagesByRepo);
}
public Set<Repo> getRepos() {
return repos;
}
public FullUserStats setRepos(Set<Repo> repos) {
return new FullUserStats(commits, weeksOfCodeByRepo, languagesByRepo, repos);
}
public Map<? extends Repo, ? extends List<CommitActivity>> getCommits() {
return commits;
}
public FullUserStats addCommits(Repo repo, List<CommitActivity> activity) {
Map<Repo, List<CommitActivity>> newWeeks = new HashMap<>();
newWeeks.putAll(commits);
newWeeks.put(repo, activity);
return setCommits(newWeeks);
}
public FullUserStats setCommits(Map<Repo, List<CommitActivity>> commits) {
return new FullUserStats(commits, weeksOfCodeByRepo, languagesByRepo, repos);
}
public Map<Repo, List<CodeWeek>> getWeeksOfCodeByRepo() {
return weeksOfCodeByRepo;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/eventing/ReposReceived.java
package io.prolabs.pro.eventing;
import java.util.Set;
import io.prolabs.pro.models.github.Repo;
/**
* Created by Edmund on 2015-03-08.
*/
public class ReposReceived {
private Set<Repo> repos;
public Set<Repo> getRepos() {
return repos;
}
public ReposReceived(Set<Repo> repos) {
this.repos = repos;
}
}
<file_sep>/app/src/main/java/io/prolabs/pro/models/github/Language.java
package io.prolabs.pro.models.github;
import android.support.annotation.NonNull;
public class Language implements Comparable<Language> {
private String name;
private int bytes;
public Language(String name, int bytes) {
this.name = name;
this.bytes = bytes;
}
public String getName() {
return name;
}
public int getBytes() {
return bytes;
}
@Override
public int compareTo(Language language) {
return language.bytes - this.bytes;
}
public boolean equals(@NonNull Language other) {
return name.equals(other.name);
}
}
| 001339721b8f6148a251bb9d10e1292e854c0cc9 | [
"Java",
"Gradle"
] | 18 | Java | ItsPriyesh/Pro_android | e603cbdbf5a6931c2ffd37f44dad38738e19f25a | b50bf395dd3278059f90a825257d432f0e2aad13 |
refs/heads/master | <file_sep>var chatCanvas;
var ctx;
var message;
var text
var stream;
var language=
{
langs:["en","rus"],
current:0,
buttonName:"en"
};
function switchLanguage()
{
language.current+=1;
if (language.current>language.langs.length-1) language.current=0;
language.buttonName=language.langs[language.current];
}
var container;
var dialog;
//buttondown indicator
var ctrl=false; //cntrl
var shift=false;
var initChat = function(){
chatCanvas = document.getElementById('chatCanvas');
ctx = chatCanvas.getContext('2d');
chatCanvas.width=format.width*format.length+70;
container = new Container({ctx:ctx});
container.update();
initControlPanel2();
initWebSocket();
window.addEventListener(
"keydown",
function (e)
{
if (e.keyCode==17)
{
ctrl=true;
}
if (e.keyCode==16)
{
shift=true;
}
},
true
);
window.addEventListener(
"keyup",
function (e)
{
if (state.login)
{
if (e.keyCode>47 && e.keyCode<223 || e.keyCode==32)
{
sendMsg({type:"add",name:username,value:{code:e.keyCode, shift:shift, language:language.buttonName}});
updateFrame();
}
else if (e.keyCode==8)
{
sendMsg({type:"rmv",name:username,value: {full:ctrl}})
updateFrame();
}else if (e.keyCode==13)
{
if (ctrl)
{
var command = getCommand(container.self.text);
if (command)
{
sendMsg(command)
}
}
}
if (e.keyCode==17)
{
ctrl=false;
}
if (e.keyCode==16)
{
shift=false;
if (ctrl)
{
switchLanguage();
updateFrame();
}
}
}
else
{
if (e.keyCode>47 && e.keyCode<223 || e.keyCode==32)
{
readMsg({type:"add",value:{code:e.keyCode, shift:shift, language:language.buttonName}});
updateFrame();
}
else if (e.keyCode==8)
{
readMsg({type:"rmv",value: {full:ctrl}})
updateFrame();
}else if (e.keyCode==13)
{
if (ctrl)
{
var command = getCommand(container.empty.text);
if (command)
{
sendMsg(command)
}
}
}
if (e.keyCode==17)
{
ctrl=false;
}
if (e.keyCode==16)
{
shift=false;
if (ctrl)
{
switchLanguage();
updateFrame();
}
}
}
},
true);
}
function sendMsg(message)
{
socket.send(JSON.stringify(message));
}
function readMsg(msg)
{
switch (msg.type)
{
case "new" :
{
container.new(new TextStream(msg.name,"",ctx));
break;
}
case "add" :
{
container.add(msg);
break;
}
case "rmv" :
{
container.remove(msg);
break;
}
case "set" :
{
container.changeParams(msg);
break;
}
}
updateFrame();
};
function getCommand(text)
{
var tree = text.split(' ');
if (tree[0] && tree[0][0]=='-')
{
if (tree[0]=='-set')
{
if (tree[1])
if ((tree[1]=="color" || tree[1]=="bgcolor") && tree.length==3)
{
if (tree[2] && isColor(tree[2]))
{
temp = {type:"set",name:username}
temp.value={};
temp.value[tree[1]]=tree[2];
return temp;
}
}else if (tree[1]=="size")
{
if (tree[2])
{
var regex = new RegExp('[0-9]{1,2}');
if (regex.exec(tree[2]) && tree[2]<20 && tree[2]>10) return {type:"set",name:username,value:{size:tree[2]}}
}
}else if (tree[1]=="name")
{
username=tree[2];
container.self.author=username;
updateFrame();
}
}else if (!state.login && tree[0]=='-login' && tree.length==2)
{
if (tree[1] && tree[1].length<16)
{
username=tree[1];
state.login=true;
return {type:"new",name:tree[1],value:{}}
}
}
}
}
function isColor(text)
{
var regex = new RegExp('#[0-f]{6}','i');
return regex.exec(text);
}
var state={login:false};
var username;
function updateFrame()
{
ctx.fillStyle="#160000";
ctx.fillRect(0, 0, chatCanvas.width, chatCanvas.height)
container.update();
panel2.draw(ctx);
}
var panel2;
function initControlPanel2()
{
//fill panel
panel2 = new ControlPanel([
new Button({
x:chatCanvas.width-50,
y:chatCanvas.height-50,
width:50,
height:50,
name:"language",
action: function()
{
if (language.buttonName=="en")
{
language.buttonName="rus";
}else if (language.buttonName=="rus")
{
language.buttonName="en";
}
},
text : language
}),
new Button({
x:format.xAlign+format.width*format.length,
y:format.yAlign+5,
width:30,
height:30,
name: "upBtn",
action : function()
{
container.moveUp();
updateFrame();
},
text :
{
buttonName:"∧"
}
}),
new Button({
x:format.xAlign+format.width*format.length,
y:format.yAlign+format.height*format.max-25,
width:30,
height:30,
name: "downBtn",
action : function()
{
container.moveDown();
updateFrame();
},
text :{
buttonName:"∨"
}
})
]);
//add listener
chatCanvas.addEventListener("mousedown",function (e)
{
var mouseAction = panel2.checkIntersect(e,true);
if (mouseAction.mousepress)
{
updateFrame();
}
else
{
dialogHandler(e);
}
});
chatCanvas.addEventListener("mousemove",function (e)
{
if (panel2.checkIntersect(e).mouseover) updateFrame();
});
updateFrame();
}
var align ={
type:["left","right","center"],
i:0,
next : function()
{
var i=align.i+1;
if (i>=align.type.length)
{
i=0;
};
return i;
},
nextI: function()
{
align.i+=1;
if (align.i>=align.type.length)
{
align.i=0;
};
return align.i;
}
}
function dialogHandler(e)
{
var createDialog = container.contains(e);
if (createDialog)
{
dialog = new MyDialog({
x:createDialog.x,
y:createDialog.y,
width:200,
height:30,
texts:
createDialog.name==username?
[
{
name:"nothing",
text:{
buttonName:align.type[align.next()]
},
action: function()
{
var next= align.type[align.nextI()];
sendMsg({type:"set",name:username,value:{textAlign:next}});
}
}
]
:
[
{
name:"to top",
text:{
buttonName:"to top"
},
action: function()
{
container.setToTop(createDialog.name);
updateFrame();
}
},
{
name:"listen",
text:{
buttonName:"listen"
},
action: function()
{
container.listenTo(createDialog.name);
}
}
],
ctx: ctx
})
panel2.setDialog(dialog);
updateFrame();
}
else{
if (dialog && dialog.active && !dialog.Intersect(e))
{
dialog.active=false;
updateFrame();
}
}
}
var socket;
function initWebSocket()
{
socket = new WebSocket("ws://pechbich.fvds.ru:3000/chat");
socket.onopen = function()
{
};
socket.onclose = function(event)
{
if (event.wasClean)
{
alert('Connection closed');
}
else
{
alert('Connection break'); // например, "убит" процесс сервера
}
alert('Code: ' + event.code + 'reason: ' + event.reason);
};
socket.onmessage = function(event)
{
msg = JSON.parse(event.data);
readMsg(msg);
};
socket.onerror = function(error)
{
alert("Error " + error.message);
};
}
function decode(value)
{
var dict;
switch(value.language)
{
case "en":
{
dict=englishCode;
break;
}
case "rus":
{
dict=russianCode;
break;
}
};
return getSymbol(dict,value);
}
function getSymbol(dictionary, value)
{
var char = dictionary.main[value.code];
if (char)
{
if (value.shift) char = char.toUpperCase();
}
else
{
char = dictionary.special[value.shift][value.code];
}
return char;
}
var symbolCode=
{
};
var englishCode =
{
main:
{
65 : "a" ,
66 : "b" ,
67 : "c" ,
68 : "d" ,
69 : "e" ,
70 : "f" ,
71 : "g" ,
72 : "h" ,
73 : "i" ,
74 : "j" ,
75 : "k" ,
76 : "l" ,
77 : "m" ,
78 : "n" ,
79 : "o" ,
80 : "p" ,
81 : "q" ,
82 : "r" ,
83 : "s" ,
84 : "t" ,
85 : "u" ,
86 : "v" ,
87 : "w" ,
88 : "x" ,
89 : "y" ,
90 : "z" ,
},
special:
{
false:
{
192 : "`",
32 : " " ,
48 : "0" ,
49 : "1" ,
50 : "2" ,
51 : "3" ,
52 : "4" ,
53 : "5" ,
54 : "6" ,
55 : "7" ,
56 : "8" ,
57 : "9" ,
191 : "/",
186 : ";" ,
188 : "," ,
190 : "." ,
222 : "'" ,
219 : "\[" ,
221 : "\]",
189 : "-",
107 : "+",
187 : "="
},
true:
{
192 : "~",
32 : " " ,
48 : ")" ,
49 : "!" ,
50 : "@" ,
51 : "#" ,
52 : "$" ,
53 : "%" ,
54 : "^" ,
55 : "&" ,
56 : "*" ,
57 : "(",
191 : "/",
186 : ":" ,
188 : "\<",
190 : ">" ,
222 : '\"' ,
219 : "\{" ,
221 : "\}",
189 : "_",
107 : "+",
187 : "+"
}
}
};
var russianCode=
{
main :{
192 : "ё",
65 : "ф" ,
66 : "и" ,
67 : "с" ,
68 : "в" ,
69 : "у" ,
70 : "а" ,
71 : "п" ,
72 : "р" ,
73 : "ш" ,
74 : "о" ,
75 : "л" ,
76 : "д" ,
77 : "ь" ,
78 : "т" ,
79 : "щ" ,
80 : "з" ,
81 : "й" ,
82 : "к" ,
83 : "ы" ,
84 : "е" ,
85 : "г" ,
86 : "м" ,
87 : "ц" ,
88 : "ч" ,
89 : "н" ,
90 : "я" ,
186 : "ж" ,
188 : "б" ,
190 : "ю" ,
222 : "э" ,
219 : "х" ,
221 : "ъ"
},
special:
{
false:
{
32 : " " ,
48 : "0" ,
49 : "1" ,
50 : "2" ,
51 : "3" ,
52 : "4" ,
53 : "5" ,
54 : "6" ,
55 : "7" ,
56 : "8" ,
57 : "9" ,
190 : "." ,
189 : "-",
107 : "+",
187 : "="
},
true:
{
32 : " " ,
48 : ")" ,
49 : "!" ,
50 : '"' ,
51 : "№" ,
52 : ";" ,
53 : "%" ,
54 : ":" ,
55 : "?" ,
56 : "*" ,
57 : "(",
191 : "/",
189 : "_",
107 : "+",
187 : "+"
}
}
}
<file_sep>window.onload = function (){
initGame();
initChat();
}<file_sep>
var myCanvas;
var context;
var xmlhttp;
var controlPanel;
var hero;
var initGame = function () {
myCanvas = document.getElementById('myCanvas');
context = myCanvas.getContext('2d');
xmlhttp = getXmlHttp()
controlPanel = initControlPanel(xmlhttp);
hero = new Hero(50,50,10,10);
myCanvas.addEventListener("mousemove",function (e) {
controlPanel.checkIntersect(e);
})
myCanvas.addEventListener("mousedown",function (e) {
controlPanel.checkIntersect(e,true);
})
updateScreen();
};
var paused = true;
function Spin() {
var id = setInterval(frame, 100);
function frame() {
if (!paused)
{
sendRequestXY("OLOLO");
}
}
}
document.addEventListener("DOMContentLoaded", Spin);
function updateScreen()
{
context.fillStyle = "#000000";
context.fillRect(0, 0, myCanvas.width, myCanvas.height);
controlPanel.draw(context);
hero.drawBounds(context);
hero.draw(context);
}
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function initControlPanel() {
var buttonLeft = new Button({x:10, y:70, width:50, heigth:50, name:"left"});
function moveleft() {
sendRequest("1000");
}
buttonLeft.setAction(moveleft);
var buttonRight = new Button({x:130, y:70, width:50, heith:50, name:"right"});
function moveright() {
sendRequest("0001");
}
buttonRight.setAction(moveright);
var buttonDown = new Button({x:70, y:70, width:50, heigth:50, name:"down"});
function movedown() {
sendRequest("0100");
};
buttonDown.setAction(movedown);
var buttonUp = new Button({x:70, y:10, width:50, heigth:50, name:"up"});
function moveup() {
sendRequest("0010");
};
buttonUp.setAction(moveup);
var buttonStart = new Button ({x:50,y:250,width:50,heigth:35, name:"start"});
buttonStart.setAction(function(){
if (!paused)
{
paused=!paused;
this.SetText("pause")
}else
{
paused=!paused;
this.SetText("start")
}
});
buttonStart.SetText("start");
var controlPanel = new ControlPanel([buttonLeft, buttonUp, buttonDown, buttonRight, buttonStart]);
return controlPanel;
}
function sendRequest(control)
{
xmlhttp.open("GET", "http://pechbich.fvds.ru/go/"+control, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
}
}
}
xmlhttp.send(null);
}
function sendRequestXY(control)
{
xmlhttp.open("GET", "http://pechbich.fvds.ru/go/"+control, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
applyResponse(xmlhttp.responseText);
}
}
}
xmlhttp.send(null);
}
function applyResponse(response)
{
response = response.split(';');
hero.move(parseInt( response[0]),parseInt(response[1]));
}
var Hero = (function() {
function Hero(x,y,width,height)
{
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.color="#00ffff";
this.boundX=150;
this.boundY=150;
this.boundWidth=250;
this.boundHeight=250;
this.checkBounds();
}
Hero.prototype.draw = function(canvasContext)
{
canvasContext.fillStyle=this.color;
canvasContext.fillRect(this.x,this.y,this.width,this.height);
};
Hero.prototype.drawBounds = function(ctx)
{
ctx.fillStyle = "#101010";
ctx.fillRect(this.boundX,this.boundY,this.boundWidth,this.boundHeight);
ctx.beginPath();
ctx.lineWidth="1";
ctx.strokeStyle="#ffff00";
ctx.rect(this.boundX,this.boundY,this.boundWidth,this.boundHeight);
ctx.stroke()
};
Hero.prototype.setColor = function(color)
{
this.color=color;
};
Hero.prototype.move = function(dx,dy)
{
this.x=dx*10;
this.y=dy*10;
this.checkBounds();
updateScreen();
};
Hero.prototype.checkBounds = function()
{
if (this.x<this.boundX)
{
this.x=this.boundX+this.boundWidth-this.width;
this.color="#FF00FF";
}else if (this.x+this.width>this.boundX+this.boundWidth)
{
this.x=this.boundX;
this.color="#FFFF00";
}
if (this.y<this.boundY)
{
this.y=this.boundY+this.boundHeight-this.height;
this.color="#00FFFF";
}else if (this.y+this.height>this.boundY+this.boundHeight)
{
this.y=this.boundY;
this.color="#0000FF";
}
};
return Hero;
}())
<file_sep>var ControlPanel = (function () {
function ControlPanel(buttonList) {
this.map=new Array();
this.dialog;
for (var i=0; i<buttonList.length;i++)
{
this.map.push(buttonList[i]);
}
}
ControlPanel.prototype.draw = function (canvasContext)
{
this.map.forEach(x=> x.draw(canvasContext));
if (this.dialog && this.dialog.active) this.dialog.draw();
};
ControlPanel.prototype.setDialog = function (dialog)
{
this.dialog=dialog;
};
ControlPanel.prototype.checkIntersect = function (e,type) {
if (this.dialog && this.dialog.active)
{
this.dialog.Intersect(e,type);
this.map.forEach(x=> x.Intersect(e,type));
var mouseover = this.map.some(x=>x.mouseoverChanges) || this.dialog.some(x=>x.mouseoverChange);
var mousepress = this.map.some(x=> x.actionChange);
var dialogpress = this.dialog.some(x=>x.actionChange);
}
else
{
this.map.forEach(x=> x.Intersect(e,type));
var mouseover = this.map.some(x=>x.mouseoverChanges);
var mousepress = this.map.some(x=> x.actionChange);
}
return {
mouseover:mouseover,
mousepress:mousepress,
dialogpress:dialogpress
}
};
ControlPanel.prototype.setMouseActions = function(canvas,params)
{
canvas.addEventListener("mousedown",params.mousedown);
canvas.addEventListener("mousmove",params.mousemove);
};
ControlPanel.prototype.deactivateDialog = function()
{
this.dialog.active=false;
}
return ControlPanel;
}());
var Button = (function () {
function Button(params) {
this.x = params.x;
this.y = params.y;
this.height = params.height;
this.width = params.width;
this.name = params.name;
this.mouseover=false;
this.text=params.text;
this.action = params.action;
}
Button.prototype.draw = function (canvasContext) {
//check mouseover and change color
canvasContext.fillStyle="#ffffff";
//draw button
canvasContext.fillRect(this.x, this.y, this.width, this.height);
canvasContext.fillStyle="#101010";
canvasContext.strokeRect(this.x, this.y, this.width, this.height);
if (this.text.buttonName)
{
canvasContext.font="20px monospace";
canvasContext.fillStyle="#000000";
canvasContext.fillText(this.text.buttonName, this.x+this.width/2-(this.text.buttonName.length/2)*12,this.y+this.height/2+4);
}
if (this.mouseover)
{
ctx.beginPath();
ctx.lineWidth="2";
ctx.strokeStyle="#000000";
ctx.rect(this.x+4,this.y+4,this.width-8,this.height-8);
ctx.stroke()
}
};
Button.prototype.setAction = function (f) {
this.action = f;
};
Button.prototype.Intersect = function (e,type) {
if (e.layerX > this.x && e.layerX < (this.x + this.width) && e.layerY > this.y && e.layerY < (this.y + this.height)) {
if (!this.mouseover)
{
this.mouseover=true;
this.mouseoverChanges=true;
}else{
this.mouseoverChanges=false;
}
if (type)
{
this.action();
this.actionChange=true;
}else{
this.actionChange=false;
}
return true;
}else
{
if (this.mouseover)
{
this.mouseover=false;
this.mouseoverChanges=true;
}else{
this.mouseoverChanges=false;
}
return false;
}
};
Button.prototype.SetText = function(text)
{
this.text=text;
};
return Button;
}());
var Indicator = (function(){
function Indicator(params)
{
this.centerX=params.centerX;
this.centerY=params.centerY;
this.radius=params.radius;
this.color=params.color;
this.text =params.text;
this.condition = params.condition;
}
Indicator.prototype.draw = function (context)
{
context.beginPath();
context.fillStyle = this.condition?this.color.true:this.color.false;
context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
if (this.text)
{
context.font="20px monospace";
context.fillStyle="#000000";
context.fillText(this.text, this.x-this.text.length*7,this.y+this.radius);
}
};
Indicator.prototype.Intersect = function(e,type)
{
};
return Indicator;
}());
var HitBox = (function()
{
function HitBox(params)
{
this.x=params.x;
this.y=params.y;
this.width=params.width;
this.height=params.height;
this.action=params.action;
}
HitBox.prototype.contains = function(e)
{
return e.centerX > this.x &&
e.centerX < (this.x + this.width) &&
e.centerY > this.y &&
e.centerY < (this.y + this.height);
};
return HitBox;
}());
var MyDialog = (function()
{
function MyDialog(params)
{
this.x=params.x;
this.y=params.y;
this.width=params.width;
this.height=params.height;
this.buttons=new Array();
this.active=true;
var i=0;
for (var button in params.texts)
{
this.buttons.push(new Button(
{
x:this.x,
y:this.y+i*this.height,
width:this.width,
height:this.height,
name:params.texts[button].name,
text:params.texts[button].text,
action:params.texts[button].action
}));
i++;
}
this.ctx=params.ctx;
}
MyDialog.prototype.draw = function()
{
for (var i=0;i<this.buttons.length;i++)
{
this.buttons[i].draw(this.ctx);
}
};
MyDialog.prototype.Intersect = function(e,type)
{
for (var i=0;i<this.buttons.length;i++)
{
this.buttons[i].Intersect(e,type);
}
};
MyDialog.prototype.some = function (callback)
{
var temp = this.buttons.some(callback);
return temp;
}
return MyDialog;
}())<file_sep>var ctx;
function sliderchage()
{
window.getElementById("showsize").value=window.getElementById("size")
}
var width=0;
var height=0;
var canvasOffset={
x:0,
y:0
};
function mousePosition(e)
{
return {
x : e.pageX - canvasOffset.x,
y : e.pageY - canvasOffset.y
};
}
window.onload = function(){
var canvas = document.getElementById("game");
width=canvas.width;
height=canvas.height;
canvasOffset={
x:canvas.offsetLeft,
y:canvas.offsetTop
}
ctx = canvas.getContext("2d");
ctx.fillStyle="#cccccc";
ctx.fillRect(0,0,width,height);
initWebSocket();
canvas.addEventListener("mousedown",function(e){
if (!online || isTurn())
{
if (gameIsOn())
{
game.start=true;
for (i=0;i<size;i++)
{
for (j=0;j<size;j++)
{
if (field[i][j].intersect(mousePosition(e)))
{
if (field[i][j].owner==0)
{
if (online)
{
sendData(i,j);
}
else
{
step(i,j,turn?1:2)
}
}
return;
}
}
}
}
}
},true);
canvas.addEventListener("mousemove",function(e)
{
if (gameIsOn())
{
var up=false;
for (i=0;i<size;i++)
{
for (j=0;j<size;j++)
{
if (field[i][j].intersect(mousePosition(e)))
{
if (!field[i][j].over)
{
field[i][j].over=true;
up=true;
}
}else{
if (field[i][j].over)
{
up=true;
field[i][j].over=false;
}
}
}
}
if (up) updateFrame();
}
})
}
function isTurn()
{
return (turn?1:2)==yourSide;
}
function gameIsOn()
{
return game.create;
}
var game={
create:false,
finished:true,
name:"",
opponent:"",
turn:1,
}
var turn=true;
var isWaitGame=false;
lobbyName="";
function waitGame()
{
turn=false;
isWaitGame=true;
lobbyName=document.getElementById("lobbyName").value;
yourSide=2;
}
function userRequestNewGame(size)
{
if (!game.create || game.finished)
{
createGame(size);
}
};
var online;
function offlineGame()
{
online=false;
turn=true;
newGame();
}
function createGame(gameSize)
{
if (online==undefined) online=true;
turn=true;
lobbyName=document.getElementById("lobbyName").value;
newGame();
if (!isWaitGame) sendMap();
};
function newGame()
{
size = parseInt(document.getElementById('size').value);
hexoidResize(size);
game.create=true;
game.finished=false;
initPlace(ctx);
updateFrame();
points={1:0,2:0};
}
function sendMap()
{
yourSide=1;
msg = {
type:"map",
lobbyName:lobbyName,
size:field.length,
value:field.map(x=>x.map(y=>y.type))
}
socket.send(JSON.stringify(msg));
}
var hexoid={
width:20,
};
hexoid.height=hexoid.width*13/15;
function hexoidResize(value)
{
hexoid.height=(height-10)/value/2;
hexoid.width=hexoid.height*15/13;
globalParams={
0:{
x:-hexoid.width,
y:0,
},
1:{
x:-hexoid.width/2,
y:hexoid.height
},
2:{
x:hexoid.width/2,
y:hexoid.height
},
3:{
x:hexoid.width,
y:0
},
4:{
x:hexoid.width/2,
y:-hexoid.height
},
5:{
x:-hexoid.width/2,
y:-hexoid.height
}
};
}
var socket;
var name="111";
function sendData(i,j)
{
socket.send(JSON.stringify({type:"step",lobbyName:lobbyName,x:i,y:j,side:turn?1:2}));
}
var lastStepPointer;
function readMsg(msg)
{
if (msg.type && msg.type=="map" && isWaitGame && lobbyName==msg.lobbyName)
{
size=msg.size;
createGame(msg.size);
for (i=0;i<size;i++)
{
for (j=0;j<size;j++)
{
field[i][j].type=msg.value[i][j];
}
}
isWaitGame=false;
}else if (msg.type=="step" && msg.lobbyName==lobbyName)
{
step(msg.x,msg.y,msg.side);
}
checkWin();
updateFrame();
}
function initWebSocket()
{
socket = new WebSocket("ws://pechbich.fvds.ru:3000/chat");
socket.onopen = function()
{
};
socket.onclose = function(event)
{
if (event.wasClean)
{
alert('Connection closed');
}
else
{
alert('Connection break'); // например, "убит" процесс сервера
}
alert('Code: ' + event.code + 'reason: ' + event.reason);
};
socket.onmessage = function(event)
{
msg = JSON.parse(event.data);
readMsg(msg);
};
socket.onerror = function(error)
{
alert("Error " + error.message);
};
}
var size=10;
var field =[];
var pathFinder;
var turn=true;
var pointCounter;
function initPlace(ctx)
{
field=[];
map = createMap(size);
for (var i=0;i<size;i++)
{
field[i]=[];
for (var j=0;j<size;j++)
{
field[i][j]=new Place({x:width/2+(i+j-size+1)*(1.5*hexoid.width), y:height/2+(j-i)*(hexoid.height),ctx,type:map[i][j]});
}
}
pathFinder = new PathFinder();
pointCounter=new PointCounter(field)
field.forEach(x=>x.forEach(y=>y.draw()));
}
function createEmptyMap(size)
{
var map=[];
for (var i=0;i<size;i++)
{
map[i]=[];
for (var j=0;j<size;j++)
{
map[i][j]=0;
}
}
return map;
}
var k=5
function createMap(size)
{
chaoses=[];
var map = createEmptyMap(size);
var placers =[];
alert(document.getElementById('bomb').value);
if (document.getElementById('bomb').checked)
{
bombs = new BombHandler(field);
placers.push(new BombPlacer(map));
}
if (document.getElementById('randomn').checked) placers.push(new ChaosPlacer(map));
if (document.getElementById('stone').checked) placers.push(new StonePlacer(map));
if (document.getElementById('portal').checked) placers.push(new PortalPlacer(map));
for (i in placers)
{
placers[i].place();
}
return map;
}
function updateFrame()
{
drawBackGround();
drawCurrentSide();
drawPoints();
field.forEach(x=>x.forEach(y=>y.draw()));
}
function drawCurrentSide()
{
ctx.fillStyle="black";
ctx.fillRect(15,15,50,50);
ctx.fillStyle = (turn==1?"blue":"red");
ctx.fillRect(20,20,40,40);
}
function drawBackGround()
{
ctx.fillStyle = "#5050a0";
ctx.fillRect(0,0,width,height);
ctx.fillStyle = "#d02020";
ctx.fillRect(0,height/2,width/2,height/2);
ctx.fillStyle = "#d02020";
ctx.fillRect(width/2,0,width/2,height/2);
}
function drawPoints()
{
ctx.fillStyle = "#ffffff";
ctx.font= "30px Arial";
ctx.fillText(points[1],50,150);
ctx.fillText(points[2],width-150,150);
}
var bombs;
function step(i,j,side)
{
field[i][j].select(side);
if (lastStepPointer) lastStepPointer.lastStep=false;
lastStepPointer=field[i][j];
lastStepPointer.lastStep=true;
if (turn)
{
turn=false;
}else{
turn=true;
}
var newPoints = checkChaos(i,j);
i=newPoints.x;
j=newPoints.y;
if (bombs) bombs.update(side);
checkWin();
points[side]+=pointCounter.count(newPoints.x,newPoints.y,side);
updateFrame();
}
var points={
1:0,
2:0
}
var PointCounter = (function()
{
function PointCounter(field)
{
this.field = field
}
PointCounter.prototype.count = function(x,y,type)
{
this.path = [];
this.counted=[];
this.map = this.field.map(x=>x.map(y=>y.type));
this.c=1;
this.type=type;
this.path.push({x:x,y:y});
this.counted.push({x:x,y:y});
this.next(x,y);
return this.c;
}
PointCounter.prototype.next = function(x,y)
{
for (m in move)
{
nextX = move[m].x+x;
nextY = move[m].y+y;
if (nextX>=0 && nextX<this.field.length && nextY>=0 && nextY<this.field.length)
{
if (this.path.find(x=>(x.x==nextX && x.y==nextY)) || this.counted.find(x=>(x.x==nextX &&x.y==nextY)))
{
}
else{
if (this.map[nextX][nextY]==this.type || this.map[nextX][nextY]==5)
{
this.path.push({x:nextX,y:nextY});
this.counted.push({x:nextX,y:nextY})
this.next(nextX,nextY);
this.c+=1;
}
}
}
}
this.path.pop();
}
return PointCounter;
}());
var chaoses;
function checkChaos(x,y)
{
chaoses=find(field,7)
var radius=1;
for (c in chaoses)
{
for (var i=-radius;i<=radius;i++)
{
for (var j=-radius;j<=radius;j++)
{
if (i*j<radius && !(i==0 && j==0))
{
if (x==chaoses[c].x+i && y==chaoses[c].y+j)
{
return activateChaos(c,x,y);
}
}
}
}
}
return {x:x,y:y};
}
function checkOwnerOfChaos(c,arr)
{
var first=0;
var second=0;
for (var i=0;i<arr.length;i++)
{
if (arr[i]==1 || arr[i]==5)
{
first++;
}
if (arr[i]==2 || arr[i]==5)
{
second++;
}
if (first==4 && second!=4) field[chaoses[c].x][chaoses[c].y].type=1;
else if (first!=4 && second==4) field[chaoses[c].x][chaoses[c].y].type=2;
}
}
var clock=[2,3,4,5,6,1]
function activateChaos(с,x,y)
{
var arr=[];
var radius=1;
var returnPointer=0;
for (var m in move)
{
rx=move[m].x+chaoses[c].x;
ry=move[m].y+chaoses[c].y;
arr.push(field[rx][ry].type)
if (x==rx && y==ry){
returnPointer=arr.length;
}
}
//checkOwnerOfChaos(c,arr);
var k=0;
for (var i=0;i<6;i++)
{
rx=move[clock[i]].x+chaoses[c].x;
ry=move[clock[i]].y+chaoses[c].y;
field[rx][ry].type=arr[k]
k++;
if (returnPointer==k) returnPointer={x:rx,y:ry};
}
return returnPointer;
}
function randomSort(arr)
{
var newArr=new Array();
for (var i =0;i<6;i++)
{
c=Math.round(Math.random()*(6-i));
newArr.push(arr[c]);
arr=remove(arr,c);
}
return newArr;
}
function clockSort(arr)
{
var temp=arr[5];
var temp2;
for (var i=0;i<6;i++)
{
if (i==0){
temp=arr[i];
arr[i]=arr[5];
}else{
temp2=arr[i];
arr[i]=temp;
temp=temp2;
}
}
}
function find(field,type)
{
var arr = new Array();
for (var i=0;i<field.length;i++)
{
for (var j=0;j<field[i].length;j++)
{
if (field[i][j].type==type)
{
arr.push({x:i,y:j});
}
}
}
return arr;
}
function remove(arr, index){
var newArr=new Array();
for (var i=0;i<arr.length;i++)
{
if (i!=index){
newArr.push(arr[i]);
}
}
return newArr;
}
function hexRadiusAction(radius,x,y,action)
{
for (i=-radius;i<=radius;i++)
{
for (j=-radius;j<=radius;j++)
{
if (i*j<radius)
{
action(x+i,y+j)
}
}
}
}
function checkWin()
{
var tempField=field.map(x=>x.map(y=>{if (y.owner==0){return y.type} else{ return y.owner}}));
pathFinder.setMap(tempField);
pathFinder.findWay(1);
if (pathFinder.complete==1)
{
alert("1 win");
game.finished=true;
createGame(Math.round(Math.random()*27+3))
}
pathFinder.findWay(2);
if (pathFinder.complete==2)
{
alert("2 win");
game.finished=true;
createGame(Math.round(Math.random()*27+3))
}
}
var globalParams={
0:{
x:-hexoid.width,
y:0,
},
1:{
x:-hexoid.width/2,
y:hexoid.height
},
2:{
x:hexoid.width/2,
y:hexoid.height
},
3:{
x:hexoid.width,
y:0
},
4:{
x:hexoid.width/2,
y:-hexoid.height
},
5:{
x:-hexoid.width/2,
y:-hexoid.height
}
};
var BombHandler = (function()
{
function BombHandler(field)
{
this.field = field;
this.explodeRadius=2;
this.stepRadius=1;
}
BombHandler.prototype.update = function(side)
{
var bombs=find(this.field,6)
for (bomb in bombs)
{
for (i=-this.stepRadius;i<=this.stepRadius;i++)
{
for (j=-this.stepRadius;j<=this.stepRadius;j++)
{
if (i*j<this.stepRadius)
{
if (this.field[bombs[bomb].x+i][bombs[bomb].y+j].type==1
|| this.field[bombs[bomb].x+i][bombs[bomb].y+j].type==2)
{
this.explode(bombs,bomb,side)
return this.field;
}
}
}
}
}
};
BombHandler.prototype.explode = function(bombs,bomb,side)
{
for (i=-this.explodeRadius;i<=this.explodeRadius;i++)
{
for (j=-this.explodeRadius;j<=this.explodeRadius;j++)
{
if (i*j<this.explodeRadius)
{
var x=bombs[bomb].x+i;
var y=bombs[bomb].y+j;
if (x>=0 && x<size && y>=0 && y<size)
{
if (this.field[x][y].type==1 || this.field[x][y].type==2)
{
points[side]+=1;
}
this.field[x][y].type=0;
this.field[x][y].owner=0;
}
}
}
}
this.field[bombs[bomb].x][bombs[bomb].y].type=5;
bombs = remove(bombs,bomb);
};
return BombHandler;
}())
var ChaosPlacer = (function()
{
function ChaosPlacer(map)
{
this.map=map;
this.count=Math.round(map.length**2/80);
this.radius=1;
}
ChaosPlacer.prototype.place = function()
{
var i=0;
var stop=0;
while(i<this.count && stop<5)
{
var x=Math.round(Math.random()*this.map.length);
var y=Math.round(Math.random()*this.map.length);
if (this.isAbleToPlace(x,y))
{
this.map[x][y]=7;
i++;
stop=0;
chaoses.push({x:x,y:y});
}else{
stop++;
}
}
}
ChaosPlacer.prototype.isAbleToPlace = function(x,y)
{
for (i=-this.radius;i<=this.radius;i++)
{
for (j=-this.radius;j<=this.radius;j++)
{
if (i*j<this.radius)
{
if (x<=1|| x>=this.map.length-2 || y<=1 || y>=this.map.length-2 ||
(x+i>0 && x+i<this.map.length && y+j>0&& y+j<this.map.length && this.map[x+i][y+j]==7)) return false;
}
}
}
return true;
}
return ChaosPlacer;
}());
var PortalPlacer = (function()
{
function PortalPlacer(map)
{
this.map=map;
this.count=Math.round(map.length**2/20);
this.radius=3;
}
PortalPlacer.prototype.place = function()
{
var i=0;
var stop=0;
while(i<this.count && stop<5)
{
var x=Math.round(Math.random()*this.map.length);
var y=Math.round(Math.random()*this.map.length);
if (this.isAbleToPlace(x,y))
{
this.map[x][y]=5;
i++;
stop=0;
}else{
stop++;
}
}
}
PortalPlacer.prototype.isAbleToPlace = function(x,y)
{
for (i=-this.radius;i<=this.radius;i++)
{
for (j=-this.radius;j<=this.radius;j++)
{
if (i*j<this.radius)
{
if (x<=1|| x>=this.map.length-2 || y<=1 || y>=this.map.length-2 ||
(x+i>0 && x+i<this.map.length && y+j>0&& y+j<this.map.length && this.map[x+i][y+j]==5)) return false;
}
}
}
return true;
}
return PortalPlacer;
}())
var StonePlacer = (function()
{
function StonePlacer(map)
{
this.map=map;
this.count=Math.round(map.length**2/33);
this.radius=3;
}
StonePlacer.prototype.place = function()
{
var i=0;
var stop=0;
while(i<this.count&& stop<5)
{
var x=Math.round(Math.random()*this.map.length);
var y=Math.round(Math.random()*this.map.length);
if (this.isAbleToPlace(x,y))
{
this.map[x][y]=4;
i++;
stop=0;
}else{
stop++;
}
}
}
StonePlacer.prototype.isAbleToPlace = function(x,y)
{
for (i=-this.radius;i<=this.radius;i++)
{
for (j=-this.radius;j<=this.radius;j++)
{
if (i*j<this.radius)
{
if (x<=1|| x>=this.map.length-2 || y<=1 || y>=this.map.length-2 ||
(x+i>0 && x+i<this.map.length && y+j>0&& y+j<this.map.length && this.map[x+i][y+j]==4)) return false;
}
}
}
return true;
}
return StonePlacer;
}());
var BombPlacer = (function()
{
function BombPlacer(map)
{
this.map=map;
this.count=Math.round(map.length**2/160);
this.radius=4
}
BombPlacer.prototype.place = function()
{
var i=0;
var stop=0;
while(i<this.count && stop<5)
{
var x=Math.round(Math.random()*this.map.length);
var y=Math.round(Math.random()*this.map.length);
if (this.isAbleToPlace(x,y))
{
this.map[x][y]=6;
i++;
stop=0;
}else{
stop++;
}
}
};
BombPlacer.prototype.isAbleToPlace = function(x,y)
{
for (i=-this.radius;i<=this.radius;i++)
{
for (j=-this.radius;j<=this.radius;j++)
{
if (i*j<this.radius)
{
if (x<=1|| x>=this.map.length-2 || y<=1 || y>=this.map.length-2 ||
(x+i>0 && x+i<this.map.length && y+j>0&& y+j<this.map.length && this.map[x+i][y+j]==6)) return false;
}
}
}
return true;
}
return BombPlacer;
}())
hex=
{
0:new Image(),
1:new Image(),
2:new Image(),
3:new Image(),
4:new Image(),
5:new Image(),
6:new Image(),
7:new Image()
}
hex[0].src='std.png';
hex[5].src='portal.png';
hex[4].src='stone.png';
hex[1].src='blue.png'
hex[2].src='red.png';
hex[6].src='bomb.png';
hex[7].src='chaos.png';
var Place = (function()
{
function Place(params)
{
this.x=params.x;
this.y=params.y;
this.ctx = params.ctx;
this.color="#606060"
this.side=params.side;
this.owner=0;
this.type=params.type;
this.lastStep=false;
}
Place.prototype.setColor =function()
{
if (this.type!=4)
{
switch (this.type)
{
default:{
this.ctx.fillStyle=this.color;
break;
};
case 5:{
this.ctx.fillStyle="#d0d0d0";
break;
}
}
}else{
this.ctx.fillStyle="#000000";
}
};
Place.prototype.draw6 = function()
{
this.ctx.beginPath();
var first=true;
for(place in globalParams)
{
if (first)
{
first=false;
this.ctx.moveTo(this.x+globalParams[place].x,this.y+globalParams[place].y);
}else{
this.ctx.lineTo(this.x+globalParams[place].x,this.y+globalParams[place].y);
}
}
this.ctx.closePath();
this.ctx.fill();
this.ctx.stroke();
};
Place.prototype.drawImg= function()
{
this.ctx.drawImage(hex[this.type],this.x-hexoid.width,this.y-hexoid.height,hexoid.width*2,hexoid.height*2);
}
Place.prototype.draw = function()
{
this.drawImg();
if (this.lastStep)
{
if (this.owner==1)
{
this.ctx.fillStyle = "rgba(50,50,200,0.4)"
}else
{
this.ctx.fillStyle = "rgba(200,100,50,0.4)"
}
this.draw6();
}
if (this.over)
{
this.ctx.fillStyle = "rgba(100,100,100,0.4)"
this.draw6();
}
};
Place.prototype.intersect = function(e)
{
return (this.type==0 && (Math.pow(e.x-this.x,2)+Math.pow(e.y-this.y,2))<Math.pow(hexoid.height,2) )
};
Place.prototype.select = function(side)
{
if (this.type==0)
{
this.type=side;
return true;
}
return false;
};
return Place;
}());
move={
1:{
x:1,
y:0
},
2:{
x:0,
y:1
},
3:{
x:-1,
y:1
},
4:{
x:-1,
y:0
},
5:{
x:0,
y:-1
},
6:{
x:1,
y:-1
}
};
var move2=
{
1:{
x:1,
y:0
},
2:{
x:-1,
y:0
},
3:{
x:0,
y:-1
},
4:{
x:0,
y:1
},
5:{
x:-1,
y:1
},
6:{
x:1,
y:-1
},
7:{
x:-2,
y:0
},
8:{
x:-1,
y:-1,
},
9:{
x:0,
y:-2
},
10:{
x:1,
y:-2
},
11:{
x:2,
y:-2
},
12:{
x:2,
y:-1
},
13:{
x:2,
y:0,
},
14:{
x:1,
y:1
},
15:{
x:0,
y:2
},
16:{
x:-1,
y:2
},
17:{
x:-2,
y:2,
},
18:{
x:-2,
y:1
}
};
var PathFinder = (function()
{
function PathFinder(params)
{
this.trace=new Array();
}
PathFinder.prototype.setMap = function(map)
{
this.map = map;
};
PathFinder.prototype.findWay = function(team)
{
this.trace=new Array();
this.complete=false;
switch (team)
{
case 1:
{
j=0;
for (i=0;i<this.map.length;i++)
{
if (this.map[i][j]==team || this.map[i][j]==5) this.goNext(i,j,team);
}
break;
}
case 2:
{
i=0;
for (j=0;j<this.map.length;j++)
{
if (this.map[i][j]==team || this.map[i][j]==5) this.goNext(i,j,team);
}
break;
}
}
};
PathFinder.prototype.goNext = function(x,y,team)
{
c=(team==1?y:x);
if (c==this.map.length-1 || 5==this.map.length-1)
{
this.complete=team;
}
this.trace.push(x+y*size);
for (var key in move)
{
var newX=x+move[key].x;
var newY=y+move[key].y;
if (newX>=0 && newY>=0 && newX<this.map.length && newY<this.map.length)
{
if (this.map[newX][newY]==team || this.map[newX][newY]==5)
{
if (!(this.trace.find(k=>k==newX+newY*size)))
{
this.goNext(newX,newY,team);
}
}
}
}
this.trace.pop()
};
return PathFinder;
}());<file_sep>
var myCanvas;
var context;
var xmlhttp;
var controlPanel;
var hero;
window.onload = function () {
myCanvas = document.getElementById('myCanvas');
context = myCanvas.getContext('2d');
xmlhttp = getXmlHttp()
controlPanel = initControlPanel(xmlhttp);
hero = new Hero(50,50,10,10);
myCanvas.addEventListener("mousemove",function (e) {
controlPanel.checkIntersect(e);
})
myCanvas.addEventListener("mousedown",function (e) {
controlPanel.checkIntersect(e,true);
})
updateScreen();
};
var paused = true;
function Spin() {
var id = setInterval(frame, 100);
function frame() {
if (!paused)
{
sendRequestXY("OLOLO");
}
}
}
document.addEventListener("DOMContentLoaded", Spin);
function updateScreen()
{
context.fillStyle = "#000000";
context.fillRect(0, 0, myCanvas.width, myCanvas.height);
controlPanel.draw(context);
hero.drawBounds(context);
hero.draw(context);
}
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function initControlPanel() {
var buttonLeft = new Button(10, 70, 50, 50);
function moveleft() {
sendRequest("1000");
}
buttonLeft.setAction(moveleft);
var buttonRight = new Button(130, 70, 50, 50);
function moveright() {
sendRequest("0001");
}
buttonRight.setAction(moveright);
var buttonDown = new Button(70, 70, 50, 50);
function movedown() {
sendRequest("0100");
};
buttonDown.setAction(movedown);
var buttonUp = new Button(70, 10, 50, 50);
function moveup() {
sendRequest("0010");
};
buttonUp.setAction(moveup);
var buttonStart = new Button (50,250,250,50);
buttonStart.setAction(function(){
if (!paused)
{
paused=!paused;
this.SetText("pause")
}else
{
paused=!paused;
this.SetText("start")
}
});
buttonStart.SetText("start");
var controlPanel = new ControlPanel(buttonLeft, buttonUp, buttonDown, buttonRight, buttonStart);
return controlPanel;
}
function sendRequest(control)
{
xmlhttp.open("GET", "http://pechbich.fvds.ru/go/"+control, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
}
}
}
xmlhttp.send(null);
}
function sendRequestXY(control)
{
xmlhttp.open("GET", "http://pechbich.fvds.ru/go/"+control, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
applyResponse(xmlhttp.responseText);
}
}
}
xmlhttp.send(null);
}
function applyResponse(response)
{
response = response.split(';');
hero.move(parseInt( response[0]),parseInt(response[1]));
}
var ControlPanel = (function () {
function ControlPanel(left, up, down, right,start) {
this.map = new Map();
this.map.set('left', left);
this.map.set('up', up);
this.map.set('down', down);
this.map.set('right', right);
this.map.set('start',start);
}
ControlPanel.prototype.draw = function (canvasContext) {
this.map.forEach(function (x) { return x.draw(canvasContext); });
};
ControlPanel.prototype.checkIntersect = function (e,type) {
this.map.forEach(function (x) { return x.Intersect(e,type); });
};
return ControlPanel;
}());
var Button = (function () {
function Button(x, y, height, width) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.mouseover=false;
this.text="";
}
Button.prototype.draw = function (canvasContext) {
if (this.canvasContext===undefined || this.canvasContext===null)
{
this.canvasContext=canvasContext;
}
if (this.mouseover)
{
this.canvasContext.fillStyle="#ff00ff";
}else
{
this.canvasContext.fillStyle="#00ff00";
}
this.canvasContext.fillRect(this.x, this.y, this.width, this.height);
if (this.text!="")
{
this.canvasContext.font="20px Georgia";
this.canvasContext.fillText(this.text, this.x,this.y);
}
};
Button.prototype.setAction = function (f) {
this.action = f;
};
Button.prototype.Action = function () {
this.action();
};
Button.prototype.Intersect = function (e,type) {
if (e.clientX > this.x && e.clientX < (this.x + this.width) && e.clientY > this.y && e.clientY < (this.y + this.height)) {
if (!this.mouseover)
{
this.mouseover=true;
updateScreen();
}
if (type)
{
this.Action();
}
}else
{
if (this.mouseover)
{
this.mouseover=false;
updateScreen();
}
}
};
Button.prototype.SetText =function(text)
{
this.text=text;
}
return Button;
}());
var Hero = (function() {
function Hero(x,y,width,height)
{
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.color="#00ffff";
this.boundX=150;
this.boundY=150;
this.boundWidth=250;
this.boundHeight=250;
this.checkBounds();
}
Hero.prototype.draw = function(canvasContext)
{
canvasContext.fillStyle=this.color;
canvasContext.fillRect(this.x,this.y,this.width,this.height);
};
Hero.prototype.drawBounds = function(ctx)
{
ctx.beginPath();
ctx.lineWidth="1";
ctx.strokeStyle="#ffff00";
ctx.rect(this.boundX,this.boundY,this.boundWidth,this.boundHeight);
ctx.stroke()
};
Hero.prototype.setColor = function(color)
{
this.color=color;
};
Hero.prototype.move = function(dx,dy)
{
this.x=dx*10;
this.y=dy*10;
//this.checkBounds();
updateScreen();
};
Hero.prototype.checkBounds = function()
{
if (this.x<this.boundX)
{
this.x=this.boundX+this.boundWidth-this.width;
}else if (this.x+this.width>this.boundX+this.boundWidth)
{
this.x=this.boundX;
}
if (this.y<this.boundY)
{
this.y=this.boundY+this.boundHeight-this.height;
}else if (this.y+this.height>this.boundY+this.boundHeight)
{
this.y=this.boundY;
}
};
return Hero;
}())
<file_sep>window.onload = function () {
var myCanvas = document.getElementById('myCanvas'), context = myCanvas.getContext('2d');
context.fillRect(0, 0, myCanvas.width, myCanvas.height);
var xmlhttp = getXmlHttp()
var controlPanel = initControlPanel(xmlhttp);
controlPanel.draw(context);
myCanvas.addEventListener("mousemove",function (e) {
controlPanel.checkIntersect(e);
})
myCanvas.addEventListener("mousedown",function (e) {
controlPanel.checkIntersect(e,true);
})
};
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function initControlPanel(xmlhttp) {
var buttonLeft = new Button(60, 70, 50, 50);
function moveleft() {
xmlhttp.open("GET", "1000", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
buttonLeft.setAction(moveleft);
var buttonRight = new Button(180, 70, 50, 50);
function moveright() {
xmlhttp.open("GET", "0001", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
buttonRight.setAction(moveright);
var buttonDown = new Button(120, 70, 50, 50);
function movedown() {
xmlhttp.open("GET", "0100", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
buttonDown.setAction(movedown);
var buttonUp = new Button(120, 10, 50, 50);
function moveup() {
xmlhttp.open("GET", "0010", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
buttonUp.setAction(moveup);
var controlPanel = new ControlPanel(buttonLeft, buttonUp, buttonDown, buttonRight);
return controlPanel;
}
var ControlPanel = (function () {
function ControlPanel(left, up, down, right) {
this.map = new Map();
this.map.set('left', left);
this.map.set('up', up);
this.map.set('down', down);
this.map.set('right', right);
}
ControlPanel.prototype.draw = function (canvasContext) {
this.map.forEach(function (x) { return x.draw(canvasContext); });
};
ControlPanel.prototype.checkIntersect = function (e,type) {
this.map.forEach(function (x) { return x.Intersect(e,type); });
};
return ControlPanel;
}());
var Button = (function () {
function Button(x, y, height, width) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.mouseover=false;
}
Button.prototype.draw = function (canvasContext) {
if (this.canvasContext===undefined || this.canvasContext===null)
{
this.canvasContext=canvasContext;
}
if (this.mouseover)
{
this.canvasContext.fillStyle="#ff00ff";
}else
{
this.canvasContext.fillStyle="#00ff00";
}
this.canvasContext.fillRect(this.x, this.y, this.width, this.height);
};
Button.prototype.setAction = function (f) {
this.action = f;
};
Button.prototype.Action = function () {
this.action();
};
Button.prototype.Intersect = function (e,type) {
if (e.clientX > this.x && e.clientX < (this.x + this.width) && e.clientY > this.y && e.clientY < (this.y + this.height)) {
this.mouseover=true;
if (type)
{
//this.Action();
alert("button pressed");
}
}else
{
this.mouseover=false
}
this.draw();
};
return Button;
}());
| f9466fe8563b7326368fdc32d5cc9321e65a1c10 | [
"JavaScript",
"TypeScript"
] | 7 | JavaScript | merdovash/PermanentChat | 322397343b8c9790366d0a1553e3b4f4af804cde | 128044b7cbe44866b265de5a809dd5bb343f319a |
refs/heads/main | <repo_name>bdotwong/rep_calculator<file_sep>/max_rep_calculator.py
from prettytable import PrettyTable
def calculator():
list = PrettyTable()
r = int(input('How many reps did you do? \n'))
w = int(input('How much weight did you lift in lbs? \n' ))
print(f"You lifted {w} lbs for {r} reps ")
# To add a column
# Syntax:- pretty.add_column(fieldname, column, align='c'/'r'/'l',valign='t'/'m'/'b')
# Here,valign:- desired vertical alignment for new columns -"t" for top, "m" for middle and "b" for bottom
# Here, align:- desired alignment for this column - "l" forleft, "c" for centre and "r" for right
# pretty.add_column('Names',['Rahul','Modi','Arvind','Sonia','<NAME>'],align='l',valign='t')
# pretty.add_column('Item',['Egg','Bread','Spam','Bacon','Butter'],valign='b')
# pretty.add_column('Rating',['7','3','9','2','10'],valign='m')
eplay = w * (1 + (r/30))
lombardi = w * (r**0.10)
conner= w * (1 +(r/40))
list.field_names = ["Formula", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]
percentages_eplay = ["eplay",]
percentages_lombardi = ["lombardi",]
percentages_conner = ["conner",]
for i in range(1, 11, 1):
percentages_eplay.append(round((i*0.1*eplay),2))
for i in range(1, 11, 1):
percentages_lombardi.append(round((i*0.1*lombardi),2))
for i in range(1, 11, 1):
percentages_conner.append(round((i*0.1*conner),2))
#percentage(eplay_max)
#percentage(lombardi_max)
#percentage(conner_max)
list.add_row(percentages_eplay)
list.add_row(percentages_lombardi)
list.add_row(percentages_conner)
#list.add_column("eplay", "lombardi", "conner")
print(list)
while True:
choice =input("Would you like to calculate your max rep? 'yes' or 'no'? \n")
if choice.lower() == "yes":
calculator()
elif choice.lower() == 'no':
break
else:
print("Please pick a valid choice")
#calculator()
| 028c5c3e434d807e96261a803dece85b3209f71f | [
"Python"
] | 1 | Python | bdotwong/rep_calculator | fa43102d37d8e4ae228354d007c9cb699faff5c3 | d14652a3087e6270dfbc447e0ef41ee37dbc654f |
refs/heads/master | <file_sep>import java.util.Vector;
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.io.*;
/**
* FeedForward with Backpropagation Artificial Neural Network
* This class can be use to create a FeedForward with Backpropagation
* neural network, the parameters values of the network are customizable,
* also the number of neurons and the number of hidden layers are defined
* by the user when creating the neural network object.
*
* <b> Note: </b> This class needs the Neuron class.
*
* @author <NAME>
* @version 1.0
* @since July-2016
*
*/
public class NeuralNetwork {
private double lambda;
private double eta;
private double momentum;
private Vector<Vector<Neuron>> neuralNetwork;
private int numInputNeurons;
private int numOutputNeurons;
private int numHiddenNeurons;
private int epochLimit;
//Constructor
public NeuralNetwork(Double l, Double e, Double a, int epochs, int inNeurons, int numHiddenLayers, int hiddenNeurons, int outNeurons, boolean addHiddenBias) {
this.lambda = l;
this.eta = e;
this.momentum = a;
this.epochLimit = epochs;
this.numInputNeurons = inNeurons;
this.numOutputNeurons = outNeurons;
this.numHiddenNeurons = hiddenNeurons;
this.neuralNetwork = new Vector<Vector<Neuron>>();
Vector<Neuron> inputLayer = new Vector<Neuron>();
for (int i=0; i<inNeurons; i++) {
Neuron n = new Neuron(hiddenNeurons);
inputLayer.add(n);
}
neuralNetwork.add(inputLayer);
Vector<Neuron> hiddenLayer = new Vector<Neuron>();
if(addHiddenBias) {
hiddenLayer.add(new Neuron(true, numOutputNeurons));
}
for(int i=0; i<numHiddenLayers; i++) {
for(int j=0; j<hiddenNeurons; j++) {
Neuron n;
if((j+1) < hiddenNeurons) {
n = new Neuron(numHiddenNeurons);
} else {
n = new Neuron(numOutputNeurons);
}
hiddenLayer.add(n);
}
neuralNetwork.add(hiddenLayer);
}
Vector<Neuron> outputLayer = new Vector<Neuron>();
for (int i=0; i<outNeurons; i++) {
Neuron n = new Neuron();
outputLayer.add(n);
}
neuralNetwork.add(outputLayer);
}
//METHODS
public void printNetwork() {
System.out.println("Lambda: " + this.lambda);
System.out.println("Eta: " + this.eta);
System.out.println("Momentum: " + this.momentum);
System.out.println("Neural Network... ");
System.out.println("Input Layer: ");
for(int i=0; i<neuralNetwork.get(0).size(); i++) {
neuralNetwork.get(0).get(i).print();
System.out.print(" ");
}
System.out.println();
System.out.println("Hidden Layers: ");
for(int i=1; i<neuralNetwork.size()-1; i++) {
for(int j=0; j<neuralNetwork.get(i).size(); j++) {
neuralNetwork.get(i).get(j).print();
System.out.print(" ");
}
System.out.println();
}
System.out.println("Output Layer: ");
for(int i=0; i<neuralNetwork.get(neuralNetwork.size()-1).size(); i++) {
neuralNetwork.get(neuralNetwork.size()-1).get(i).print();
System.out.print(" ");
}
System.out.println();
}
public void saveToFile(String fname) throws IOException {
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
BufferedWriter out = new BufferedWriter(new FileWriter(fname + "_networkConfig_"+timeLog+".txt"));
out.write("Lambda: " + this.lambda);
out.write("Eta: " + this.eta);
out.write("Momentum: " + this.momentum);
out.write("Neural Network... ");
out.write("Input Layer: ");
for(int i=0; i<neuralNetwork.get(0).size(); i++) {
Double v = neuralNetwork.get(0).get(i).getValue();
Double h = neuralNetwork.get(0).get(i).getH();
out.write("V: " + v + " H: " + h);
out.write(" ");
}
out.write("\n");
out.write("Hidden Layers: ");
for(int i=1; i<neuralNetwork.size()-1; i++) {
for(int j=0; j<neuralNetwork.get(i).size(); j++) {
Double v = neuralNetwork.get(i).get(j).getValue();
Double h = neuralNetwork.get(i).get(j).getH();
out.write("V: " + v + " H: " + h);
out.write(" ");
}
out.write("\n");
}
out.write("Output Layer: ");
for(int i=0; i<neuralNetwork.get(neuralNetwork.size()-1).size(); i++) {
Double v = neuralNetwork.get(neuralNetwork.size()-1).get(i).getValue();
Double h = neuralNetwork.get(neuralNetwork.size()-1).get(i).getH();
out.write("V: " + v + " H: " + h);
out.write(" ");
}
out.write("\n");
out.close();
}
public void saveErrorsToFile(Vector<Double> errors) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("errors.txt", true));
for(int i=0; i<errors.size(); i++) {
out.write(errors.get(i) + " ");
}
out.write("\n");
out.close();
}
public void trainNetwork(String trainingFilename, String targetDataFilename) throws IOException {
File file = new File(trainingFilename);
File targetFile = new File(targetDataFilename);
for(int epoch=0; epoch<this.epochLimit; epoch++) {
System.out.println("Epoch number: " + (epoch+1));
//read file and pass each row through training process
try {
Scanner inputFile = new Scanner(file);
Scanner targetData = new Scanner(targetFile);
while(inputFile.hasNext() && targetData.hasNext()) {
String line = inputFile.nextLine();
String data[] = line.split(",");
Vector<Double> inputs = new Vector<Double>();
String targetLine = targetData.nextLine();
String outputs[] = targetLine.split(",");
Vector<Double> targets = new Vector<Double>();
for(int i=0; i<data.length; i++) {
inputs.add(Double.parseDouble(data[i]));
//System.out.println("Data input #" + i + ": " + inputs.get(i));
}
for(int i=0; i<outputs.length; i++) {
targets.add(Double.parseDouble(outputs[i]));
//System.out.println("Data input #" + i + ": " + inputs.get(i));
}
feedForward(inputs); //predict output
Vector<Double> outputErrors = new Vector<Double>();
outputErrors = calculateErrors(targets); //calculate errors
saveErrorsToFile(outputErrors); //save errors to file for later analysis
backPropagation(outputErrors); //learning part
}
} catch (FileNotFoundException e) {
System.out.println("Training file not found.");
}
//run network through validation data and check validation error
}
//read training examples
//send each example to forward and backpropagation
//feedforward
//calculate output
//calculate error;
//backpropagation
//calculate local gradient
//calculate change of weights
//update weights
//
//calculate training epoch error;
//validation forward
//calculate validation error;
}
/**
* This method is used to make the Neural Network go through the
* Feed Forward process one time with the training sample that was
* received as parameter.
*
* @param trainingSample This is a vector with the input values for each neuron. (Values must be a Double)
*/
public void feedForward(Vector<Double> trainingSample) {
for(int i=0; i<trainingSample.size(); i++) {
neuralNetwork.get(0).get(i).setValue(trainingSample.get(i));
}
//All layers will use the same activation function, if a layer uses another activation function
//modifications to this for has to be made
for(int i=1; i<neuralNetwork.size(); i++) {
int adjust = 0;
for(int j=0; j<neuralNetwork.get(i).size(); j++) {
double tmpV = 0;
if(neuralNetwork.get(i).get(j).getBiasNeuron()) {
adjust++;
neuralNetwork.get(i).get(j).setValue(1.0);
neuralNetwork.get(i).get(j).setH(1.0);
} else {
for(int k=0; k<neuralNetwork.get(i-1).size(); k++) {
tmpV += (neuralNetwork.get(i-1).get(k).getValue() * neuralNetwork.get(i-1).get(k).getWeight(j-adjust));
}
neuralNetwork.get(i).get(j).setValue(tmpV);
neuralNetwork.get(i).get(j).calculateH(1, this.lambda);
}
}
}
}
/**
*
*
*
*
*/
public Vector<Double> predictValue(Vector<Double> inputs) {
for(int i=0; i<inputs.size(); i++) {
this.neuralNetwork.get(0).get(i).setValue(inputs.get(i));
}
//All layers will use the same activation function, if a layer uses another activation function
//modifications to this for has to be made
for(int i=1; i<this.neuralNetwork.size(); i++) {
int adjust = 0;
for(int j=0; j<this.neuralNetwork.get(i).size(); j++) {
double tmpV = 0;
if(this.neuralNetwork.get(i).get(j).getBiasNeuron()) {
adjust++;
neuralNetwork.get(i).get(j).setValue(1.0);
neuralNetwork.get(i).get(j).setH(1.0);
} else {
for(int k=0; k<this.neuralNetwork.get(i-1).size(); k++) {
tmpV += (this.neuralNetwork.get(i-1).get(k).getValue() * this.neuralNetwork.get(i-1).get(k).getWeight(j-adjust));
}
this.neuralNetwork.get(i).get(j).setValue(tmpV);
this.neuralNetwork.get(i).get(j).calculateH(1, this.lambda);
}
}
}
Vector<Double> predictedOutput = new Vector<Double>();
for(int i=0; i<this.neuralNetwork.get(this.neuralNetwork.size()-1).size(); i++) {
predictedOutput.add(this.neuralNetwork.get(this.neuralNetwork.size()-1).get(i).getValue());
}
return predictedOutput;
}
/**
*
*
*/
public Vector<Double> calculateErrors(Vector<Double> target) {
Vector<Double> tmp = new Vector<Double>();
for(int i=0; i<target.size(); i++) {
tmp.add(target.get(i) - neuralNetwork.get(neuralNetwork.size()-1).get(i).getValue());
}
return tmp;
}
/**
*
*
*
*/
public Vector<Double> getOutputValues() {
Vector<Double> tmp = new Vector<Double>();
for(int i=0; i<neuralNetwork.get(neuralNetwork.size()-1).size(); i++) {
tmp.add(neuralNetwork.get(neuralNetwork.size()-1).get(i).getH());
}
return tmp;
}
/**
*
*
*
*/
public void backPropagation(Vector<Double> errors) {
//First do the back propagation in the last layer
Vector<Double> localGradientsOutputLayer = new Vector<Double>();
for(int i=0; i<neuralNetwork.get(neuralNetwork.size()-1).size(); i++) {
Double opt = neuralNetwork.get(neuralNetwork.size()-1).get(i).getH();
localGradientsOutputLayer.add(this.lambda*opt*(1.0-opt)*errors.get(i));
}
for(int i=0; i<neuralNetwork.get(neuralNetwork.size()-2).size(); i++) {
Vector<Double> weights = neuralNetwork.get(neuralNetwork.size()-2).get(i).getWeights();
Vector<Double> prevDeltaWeights = neuralNetwork.get(neuralNetwork.size()-2).get(i).getPreviousDeltaWeights();
Vector<Double> newWeights = new Vector<Double>();
Vector<Double> newPrevDeltaWeights = new Vector<Double>();
for( int j=0; j<neuralNetwork.get(neuralNetwork.size()-1).size(); j++) {
Double deltaWeight = this.eta*neuralNetwork.get(neuralNetwork.size()-2).get(i).getH()*localGradientsOutputLayer.get(j)
+ this.momentum*prevDeltaWeights.get(j);
newWeights.add(weights.get(j)+deltaWeight);
newPrevDeltaWeights.add(deltaWeight);
}
neuralNetwork.get(neuralNetwork.size()-2).get(i).setWeights(newWeights);
neuralNetwork.get(neuralNetwork.size()-2).get(i).setPreviousDeltaWeights(newPrevDeltaWeights);
}
//Back propagation learning in the rest of the layers
Vector<Double> prevGradients = localGradientsOutputLayer;
for(int i=neuralNetwork.size()-2; i>0; i--) {
Vector<Double> localGradients = new Vector<Double>();
for(int j=0; j<neuralNetwork.get(i).size(); j++) {
Double sum = 0.0;
Vector<Double> neuronWeights = neuralNetwork.get(i).get(j).getWeights();
for(int k=0; k<neuronWeights.size(); k++) {
sum += prevGradients.get(k)*neuronWeights.get(k);
}
Double opt = neuralNetwork.get(i).get(j).getH();
localGradients.add(this.lambda*opt*(1.0-opt)*sum);
}
for(int j=0; j<neuralNetwork.get(i-1).size(); j++) {
Vector<Double> weights = neuralNetwork.get(i-1).get(j).getWeights();
Vector<Double> prevDeltaWeights = neuralNetwork.get(i-1).get(j).getPreviousDeltaWeights();
Vector<Double> newWeights = new Vector<Double>();
Vector<Double> newPrevDeltaWeights = new Vector<Double>();
int adjust = 0;
for(int k=0; k<neuralNetwork.get(i).size(); k++) {
if(!neuralNetwork.get(i).get(k).getBiasNeuron()) {
Double deltaWeight = this.eta*localGradients.get(k)*neuralNetwork.get(i-1).get(j).getH()
+ this.momentum*prevDeltaWeights.get(k-adjust);
newPrevDeltaWeights.add(deltaWeight);
newWeights.add(weights.get(j)+deltaWeight);
} else {
adjust++;
}
}
neuralNetwork.get(i-1).get(j).setWeights(newWeights);
neuralNetwork.get(i-1).get(j).setPreviousDeltaWeights(newPrevDeltaWeights);
}
prevGradients = localGradients;
}
}
//SETTERS
public void setLambda(double l) {
this.lambda = l;
}
public void setMomentum(double a) {
this.momentum = a;
}
public void setEta(double e) {
this.eta = e;
}
public void setNeuralNetwork(Vector<Vector<Neuron>> nn) {
this.neuralNetwork = nn;
}
public void setNumInputNeurons(int i) {
this.numInputNeurons = i;
}
public void setNumOutputNeurons(int i) {
this.numOutputNeurons = i;
}
public void setNumHiddenNeurons(int i) {
this.numHiddenNeurons = i;
}
//GETTERS
public double getLambda() {
return this.lambda;
}
public double getMomentum() {
return this.momentum;
}
public double getEta() {
return this.eta;
}
public Vector<Vector<Neuron>> getNeuralNetwork() {
return this.neuralNetwork;
}
public int getNumInputNeurons() {
return this.numInputNeurons;
}
public int getNumOutputNeurons() {
return this.numOutputNeurons;
}
public int getNumHiddenNeurons() {
return this.numHiddenNeurons;
}
}
<file_sep># Neural-Network-Java
Here you can find the classes for a FeedForward with Back-propagation learning Neural Network. Developed from scratch in Java.
| 283fcb40b0158989caced21b1fba5e8b975d9416 | [
"Markdown",
"Java"
] | 2 | Java | HugoLG/Neural-Network-Java | 63194671f65d7218e58061f3795a40875000b8e1 | 6fc7d3ecd0cde622334f6cd40a055a8156d4f728 |
refs/heads/master | <repo_name>jacquescrocker/resque-honeybadger<file_sep>/lib/resque/failure/honeybadger.rb
module Resque
module Failure
# A Resque failure backend that sends exception data to honeybadger.io
class Honeybadger < Base
# Configures the failure backend. At a minimum you will need to set
# an api_key.
#
# @example Setting your API Key and enabling SSL:
# Resque::Failure::Honeybadger.configure do |config|
# config.api_key = '<KEY>'
# end
def self.configure(&block)
::Honeybadger.configure(&block)
end
def count
# We can't get the total # of errors from Hoptoad so we fake it
# by asking Resque how many errors it has seen.
Stat[:failed]
end
def save
::Honeybadger.notify_or_ignore(exception,
:parameters => {
:payload_class => payload['class'].to_s,
:payload_args => payload['args'].inspect
}
)
end
end
end
end
<file_sep>/lib/resque-honeybadger.rb
require 'resque'
require 'honeybadger'
require 'resque/failure/honeybadger'
<file_sep>/resque-honeybadger.gemspec
spec = Gem::Specification.new do |s|
s.name = 'resque-honeybadger'
s.version = '0.2.0'
s.date = Time.now.strftime('%Y-%m-%d')
s.summary = 'A Resque failure backend for honeybadger.io'
s.homepage = 'http://github.com/lantins/resque-honeybadger'
s.authors = ['<NAME>']
s.email = '<EMAIL>'
s.has_rdoc = false
s.files = %w(LICENSE Rakefile README.md HISTORY.md)
s.files += Dir.glob('{test/*,lib/**/*}')
s.require_paths = ['lib']
s.add_dependency('resque', '>= 1.8.0')
s.add_dependency('honeybadger')
s.description = <<-EOL
resque-honeybadger provides a Resque failure backend that sends exceptions
raised by jobs to honeybadger.io.
EOL
end<file_sep>/README.md
resque-honeybadger
==================
resque-honeybadger provides a [Resque][re] failure backend that sends exceptions
raised by jobs to [honeybadger.io][hb]
Install & Quick Start
---------------------
Before you jump into code, you'll need a honeybadger.io account.
To install:
$ gem install resque-honeybadger
### Example: Single Failure Backend
Using only the honeybadger failure backend:
require 'resque'
require 'resque-honeybadger'
Resque::Failure::Honeybadger.configure do |config|
config.api_key = '<KEY>'
end
Resque::Failure.backend = Resque::Failure::Honeybadger
### Example: Multiple Failure Backends
Using both the redis and honeybadger failure backends:
require 'resque'
require 'resque-honeybadger'
require 'resque/failure/multiple'
require 'resque/failure/redis'
Resque::Failure::Honeybadger.configure do |config|
config.api_key = '<KEY>'
end
Resque::Failure::Multiple.classes = [Resque::Failure::Redis, Resque::Failure::Honeybadger]
Resque::Failure.backend = Resque::Failure::Multiple
Configuration Options
---------------------
**Required**
* `api_key` - your honeybadger.io api key.
Note on Patches/Pull Requests
-----------------------------
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future
version unintentionally.
* Commit, do not mess with the version. (if you want to have your own
version, that is fine but bump version in a commit by itself I can ignore
when I pull)
* Send me a pull request. Bonus points for topic branches.
Forked by
------
<NAME> :: <http://railsjedi.com> :: @railsjedi
Original Author
------
<NAME> :: [http://lividpenguin.com][lp] :: @lantins
[re]: http://github.com/defunkt/resque
[lp]: http://lividpenguin.com
[hb]: http://honeybadger.io | e14d60578f27c3f5de1ffa4b367a505af11bd4ed | [
"Markdown",
"Ruby"
] | 4 | Ruby | jacquescrocker/resque-honeybadger | da822a38b43296790ab217c7ff8b93281af4cb08 | eeeb5f827b97611f3da059febeec175178efc09c |
refs/heads/master | <repo_name>cnctechnology/milling-cycles<file_sep>/de/Fraeszyklen.h
0 BEGIN PGM Fraeszyklen MM
1 BLK FORM 0.1 Z X+0 Y+0 Z-20
2 BLK FORM 0.2 X+150 Y+150 Z+5
3 TOOL CALL 10 Z S1592 F796
4 * - Planen PMK D80
5 CYCL DEF 232 PLANFRAESEN ~
Q389=+2 ;STRATEGIE ~
Q225=+0 ;STARTPUNKT 1. ACHSE ~
Q226=+0 ;STARTPUNKT 2. ACHSE ~
Q227=+5 ;STARTPUNKT 3. ACHSE ~
Q386=+0 ;ENDPUNKT 3. ACHSE ~
Q218=+150 ;1. SEITEN-LAENGE ~
Q219=+150 ;2. SEITEN-LAENGE ~
Q202=+2 ;MAX. ZUSTELL-TIEFE ~
Q369=+0.2 ;AUFMASS TIEFE ~
Q370=+1 ;MAX. UEBERLAPPUNG ~
Q207= AUTO ;VORSCHUB FRAESEN ~
Q385=+500 ;VORSCHUB SCHLICHTEN ~
Q253= MAX ;VORSCHUB VORPOS. ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q357=+2 ;SI.-ABSTAND SEITE ~
Q204=+100 ;2. SICHERHEITS-ABST.
6 CYCL CALL M3 M25
7 M5 M9
8 TOOL CALL 11 Z S2500 F500
9 * - AK VHM SF D20
10 L X-12 Y+50 FMAX M3 M25
11 L Z+2
12 L Z-10 F AUTO
13 APPR CT X+10 Y+30 CCA90 R+10 RL
14 L Y+85
15 CR X+30 Y+105 R+20 DR+
16 L Y+135
17 CHF 10
18 L X+90
19 L X+144.45 Y+80.55
20 L X+113.7 Y+10
21 L X+85
22 CR X+55 R+15
23 L X+10 Y+10
24 RND R10
25 L Y+30
26 DEP CT CCA90 R+10
27 L Z+2
28 L Z+100 FMAX
29 M5 M9
30 TOOL CALL 2 Z S8000 F1500
31 * - Tasche 1 bis 4 mit LLF D6
32 CYCL DEF 252 KREISTASCHE ~
Q215=+0 ;BEARBEITUNGS-UMFANG ~
Q223=+40 ;KREISDURCHMESSER ~
Q368=+0.2 ;AUFMASS SEITE ~
Q207= AUTO ;VORSCHUB FRAESEN ~
Q351=+1 ;FRAESART ~
Q201=-5 ;TIEFE ~
Q202=+5 ;ZUSTELL-TIEFE ~
Q369=+0.2 ;AUFMASS TIEFE ~
Q206=+150 ;VORSCHUB TIEFENZ. ~
Q338=+0 ;ZUST. SCHLICHTEN ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q203=+0 ;KOOR. OBERFLAECHE ~
Q204=+100 ;2. SICHERHEITS-ABST. ~
Q370=+1 ;BAHN-UEBERLAPPUNG ~
Q366=+1 ;EINTAUCHEN ~
Q385=+500 ;VORSCHUB SCHLICHTEN
33 CYCL CALL POS X+70 Y+100 Z+0 FMAX M3 M25
34 CYCL DEF 253 NUTENFRAESEN ~
Q215=+0 ;BEARBEITUNGS-UMFANG ~
Q218=+40 ;NUTLAENGE ~
Q219=+12 ;NUTBREITE ~
Q368=+0.2 ;AUFMASS SEITE ~
Q374=+135 ;DREHLAGE ~
Q367=+2 ;NUTLAGE ~
Q207= AUTO ;VORSCHUB FRAESEN ~
Q351=+1 ;FRAESART ~
Q201=-3 ;TIEFE ~
Q202=+5 ;ZUSTELL-TIEFE ~
Q369=+0.2 ;AUFMASS TIEFE ~
Q206=+150 ;VORSCHUB TIEFENZ. ~
Q338=+0 ;ZUST. SCHLICHTEN ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q203=+0 ;KOOR. OBERFLAECHE ~
Q204=+100 ;2. SICHERHEITS-ABST. ~
Q366=+1 ;EINTAUCHEN ~
Q385=+500 ;VORSCHUB SCHLICHTEN
35 CYCL CALL POS X+115 Y+95 Z+0 FMAX
36 CYCL DEF 253 NUTENFRAESEN ~
Q215=+0 ;BEARBEITUNGS-UMFANG ~
Q218=+60 ;NUTLAENGE ~
Q219=+14 ;NUTBREITE ~
Q368=+0.2 ;AUFMASS SEITE ~
Q374=+66.5 ;DREHLAGE ~
Q367=+2 ;NUTLAGE ~
Q207= AUTO ;VORSCHUB FRAESEN ~
Q351=+1 ;FRAESART ~
Q201=-3 ;TIEFE ~
Q202=+3 ;ZUSTELL-TIEFE ~
Q369=+0.2 ;AUFMASS TIEFE ~
Q206=+150 ;VORSCHUB TIEFENZ. ~
Q338=+0 ;ZUST. SCHLICHTEN ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q203=+0 ;KOOR. OBERFLAECHE ~
Q204=+100 ;2. SICHERHEITS-ABST. ~
Q366=+1 ;EINTAUCHEN ~
Q385=+500 ;VORSCHUB SCHLICHTEN
37 CYCL CALL POS X+100 Y+25 Z+0 FMAX
38 CYCL DEF 251 RECHTECKTASCHE ~
Q215=+0 ;BEARBEITUNGS-UMFANG ~
Q218=+20 ;1. SEITEN-LAENGE ~
Q219=+50 ;2. SEITEN-LAENGE ~
Q220=+5 ;ECKENRADIUS ~
Q368=+0.2 ;AUFMASS SEITE ~
Q224=+10 ;DREHLAGE ~
Q367=+0 ;TASCHENLAGE ~
Q207= AUTO ;VORSCHUB FRAESEN ~
Q351=+1 ;FRAESART ~
Q201=-4 ;TIEFE ~
Q202=+5 ;ZUSTELL-TIEFE ~
Q369=+0.2 ;AUFMASS TIEFE ~
Q206=+150 ;VORSCHUB TIEFENZ. ~
Q338=+0 ;ZUST. SCHLICHTEN ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q203=+0 ;KOOR. OBERFLAECHE ~
Q204=+100 ;2. SICHERHEITS-ABST. ~
Q370=+1 ;BAHN-UEBERLAPPUNG ~
Q366=+1 ;EINTAUCHEN ~
Q385=+500 ;VORSCHUB SCHLICHTEN
39 CYCL CALL POS X+30 Y+50 Z+0 FMAX
40 CYCL DEF 200 BOHREN ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q201=-10 ;TIEFE ~
Q206= AUTO ;VORSCHUB TIEFENZ. ~
Q202=+5 ;ZUSTELL-TIEFE ~
Q210=+0 ;VERWEILZEIT OBEN ~
Q203=+0 ;KOOR. OBERFLAECHE ~
Q204=+100 ;2. SICHERHEITS-ABST. ~
Q211=+0 ;VERWEILZEIT UNTEN
41 CYCL DEF 220 MUSTER KREIS ~
Q216=+70 ;MITTE 1. ACHSE ~
Q217=+50 ;MITTE 2. ACHSE ~
Q244=+30 ;TEILKREIS-DURCHM. ~
Q245=+0 ;STARTWINKEL ~
Q246=+360 ;ENDWINKEL ~
Q247=+90 ;WINKELSCHRITT ~
Q241=+4 ;<NAME> ~
Q200=+2 ;SICHERHEITS-ABST. ~
Q203=+0 ;KOOR. OBERFLAECHE ~
Q204=+100 ;2. SICHERHEITS-ABST. ~
Q301=+1 ;FAHREN AUF S. HOEHE ~
Q365=+1 ;VERFAHRART
42 TOOL CALL 4 Z S2500 F500
43 * - <NAME>
44 L X+0 R0
45 L X-2 Y-2 FMAX M3 M25
46 L Z-10 F AUTO
47 L Y+100
48 L Y+150
49 L IX+10
50 L Y+100
51 L IX+10
52 L Y+140
53 L IX+10
54 L Y+150
55 L X+150
56 L IX-10
57 L X+100
58 L IY-10
59 L X+150
60 L IY-10
61 L X+115
62 L Y+125
63 L X+150
64 L IY-10
65 L X+130
66 L X+140 IY-10
67 L X+150 IY-10
68 L X+160
69 L IX+10
70 L Y+0
71 L X+150
72 L Y+60
73 L IX-5 IY-10
74 L Y+40
75 L IX-5
76 L Y+0
77 L IX-5
78 L Y+0
79 L Y+15
80 L IX-5
81 L Y+0
82 L X+70
83 L IY+5
84 L IY-5
85 L X+0
86 L Y+30
87 * - Schluss
88 L Z+2 R0
89 L Z+100 FMAX M5 M9
90 M5 M9
91 TOOL CALL 0 Z
92 M2
93 END PGM Fraeszyklen MM
<file_sep>/README.md
# milling-cycles
A CNC program for milling cycles.
| 4a3dca543a8765933dbe0f013976bd95b8c8bc65 | [
"Markdown",
"C"
] | 2 | C | cnctechnology/milling-cycles | 53fcd629e7a02383017bc3d04e62524ec910ea3c | 3effc09da2bad503d2f10001a38380d1e717544d |
refs/heads/master | <file_sep>
/**
*
* @author (<NAME>)
* @version (01 November 2015)
*/
public interface Binatang
{
public String suara();
}
<file_sep>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Write a description of class CaesarCipher here.
*
* @author (<NAME>)
* @version (06 November 2015)
*/
public class CaesarCipher
{
private int shift;
public CaesarCipher(int shift){
this.shift = shift;
}
public void enkripsi(String sumber, String sasaran) throws IOException {
FileInputStream masukan = null;
FileOutputStream keluaran = null;
// Deklarasi variabel
try {
// Object stream untuk masukkan
masukan = new FileInputStream(sumber);
keluaran = new FileOutputStream(sasaran);
// Coba baca dari stream
int karakter = masukan.read();
// Selama masih ada data yang masih bisa dibaca
while (karakter != -1) {
karakter +=shift;
keluaran.write(karakter);
karakter = masukan.read();
}
keluaran.flush();
}
catch (IOException kesalahan) {
System.out.printf("Terjadi kesalahan: %s", kesalahan);
}
finally {
// Tutup stream masukan
if (masukan != null)
masukan.close();
if (keluaran != null)
keluaran.close();
}
}
public void dekripsi(String sumber, String sasaran) throws IOException {
FileInputStream masukan = null;
FileOutputStream keluaran = null;
// Deklarasi variabel
try {
// Object stream untuk masukkan
masukan = new FileInputStream(sumber);
keluaran = new FileOutputStream(sasaran);
// Coba baca dari stream
int karakter = masukan.read();
while (karakter != -1) {
karakter -= shift;
keluaran.write(karakter);
karakter = masukan.read();
}
keluaran.flush();
}
catch (IOException kesalahan) {
System.out.printf("Terjadi kesalahan: %s", kesalahan);
}
finally {
// Tutup stream masukan
if (masukan != null)
masukan.close();
if (keluaran != null)
keluaran.close();
}
}
public static void main(String[] args){
try{
CaesarCipher baru = new CaesarCipher(3);
baru.enkripsi("yeni.txt","enkripsi.txt");
baru.dekripsi("yeni.txt","dekripsi.txt");
}
catch(IOException kesalahan){
System.out.printf("eror %s",kesalahan);
}
}
}
<file_sep>import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Utama {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Yeni:");
String pesan = input.nextLine();
Client kirim = new Client();
kirim.chat(pesan);
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
<file_sep>
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.String;
public class Utama {
public static void main(String[] args) throws IOException {
new AKeAt().aKeAt("sumber.txt", "sasaran.txt");
}
}
<file_sep>------------------------------------------------------------------------
PARKING PROJECT
------------------------------------------------------------------------
PROJECT TITLE:PARKING
PURPOSE OF PROJECT:Final project in Data Communication class
VERSION or DATE:
AUTHORS:<NAME>
<file_sep>
/**
* @author (<NAME>)
* @version (01 November 2015)
*/
public interface Kendaraan {
public String tipe();
public String plat();
}
<file_sep>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.String;
/**
* @author (<NAME>)
* @version (11 November 2015)
*/
public class Merge
{
public void merge(String file1, String file2, String file3,String sasaran ) throws IOException {
// Deklarasi variabel
FileInputStream file_1 = null;
FileInputStream file_2 = null;
FileInputStream file_3 = null;
FileInputStream masukan = null;
FileOutputStream keluaran = null;
try {
file_1 = new FileInputStream(file1);
keluaran = new FileOutputStream(sasaran);
int karakter = file_1.read();
while (karakter != -1) {
keluaran.write(karakter);
karakter = file_1.read();
}
file_2 = new FileInputStream(file2);
keluaran = new FileOutputStream(sasaran,true);
karakter = file_2.read();
while (karakter != -1) {
keluaran.write(karakter);
karakter = file_2.read();
}
file_3 = new FileInputStream(file3);
keluaran = new FileOutputStream(sasaran,true);
karakter = file_3.read();
while (karakter != -1) {
keluaran.write(karakter);
karakter = file_3.read();
}
keluaran.flush();
}
catch (IOException kesalahan) {
System.out.printf("Terjadi kesalahan: %s", kesalahan);
}
finally {
// Tutup stream masukan
if (masukan != null)
masukan.close();
if (keluaran != null)
keluaran.close();
if (file_1 != null)
file_1.close();
if (file_2 != null)
file_2.close();
if (file_3 != null)
file_3.close();
if (keluaran != null)
keluaran.close();
}
}
}
| 9882a4f7630677a9c6734b1f65f073ab577bd4d1 | [
"Java",
"Text"
] | 7 | Java | yenisaragih/StrukturData-2015 | d55a9c72a70596cc0b9207e67a6d3a415599d476 | 2588aa28b9a44fc179f0199e1a5c502d112365d2 |
refs/heads/master | <repo_name>Ivanvv/EnyimMemcached<file_sep>/Enyim.Caching/Memcached/Protocol/Binary/Status.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Enyim.Caching.Memcached.Protocol.Binary
{
public enum Status
{
ClientError = -1, // Error on client
NoError = 0x0000, // No error
KeyNotFound = 0x0001, // Key not found
KeyExists = 0x0002, // Key exists
ValueTooLarge = 0x0003, // Value too large
InvalidArguments = 0x0004, // Invalid arguments
ItemNotStored = 0x0005, // Item not stored
IncrDecrNonNumeric = 0x0006, // Incr/Decr on non-numeric value.
VBucketOnAnotherServer = 0x0007, // The vbucket belongs to another server
AuthenticationError = 0x0008, // Authentication error
AuthenticationContinue = 0x0009, // Authentication continue
UnknownCommand = 0x0081, // Unknown command
OutOfMemory = 0x0082, // Out of memory
NotSupported = 0x0083, // Not supported
InternalError = 0x0084, // Internal error
Busy = 0x0085, // Busy
TemporaryFailure = 0x0086, // Temporary failure
};
}
| 73849478de7fd4b38a15e75dab297f441bf5b824 | [
"C#"
] | 1 | C# | Ivanvv/EnyimMemcached | 4267baeb00fb03e2aaa961fbe871474309e92356 | e2aeabe39e3917a40088d3425275f4c1848b2fd0 |
refs/heads/master | <repo_name>sct-pipeline/multiparametric-fixed-fov<file_sep>/2_extract_metrics.sh
#!/bin/bash
#
# This script extracts metrics.
#
# NB: add the flag "-x" after "!/bin/bash" for full verbose of commands.
# <NAME> 2018-01-30
# Exit if user presses CTRL+C (Linux) or CMD+C (OSX)
trap "echo Caught Keyboard Interrupt within script. Exiting now.; exit" INT
# Create results folder
if [ ! -d ${PATH_RESULTS} ]; then
mkdir ${PATH_RESULTS}
fi
# mt
# ==============================================================================
cd mt
# compute MTR in WM in each level prescribed by METRICS_VERT_LEVEL
sct_extract_metric -i mtr.nii.gz -l 51 -method map -vert ${METRICS_VERT_LEVEL} -perlevel 1 -o ${PATH_RESULTS}/mtr_in_WM.xls
## compute MTR in WM and average across level(s) prescribed by METRICS_VERT_LEVEL
# sct_extract_metric -i mtr.nii.gz -l 51 -method map -vert ${METRICS_VERT_LEVEL} -perlevel 0 -o ${PATH_RESULTS}/mtr_in_WM.xls
## compute MTR in the dorsal columns in each level prescribed by METRICS_VERT_LEVEL
# sct_extract_metric -i mtr.nii.gz -l 53 -method map -vert ${METRICS_VERT_LEVEL} -perlevel 1 -o ${PATH_RESULTS}/mtr_in_DC.xls
## compute MTR in WM between slices 5 and 15 and averaged across slices
# sct_extract_metric -i mtr.nii.gz -l 51 -method map -z 5:15 -perslice 0 -o ${PATH_RESULTS}/mtr_in_WM_z5-15.xls
cd ..
<file_sep>/run_process.sh
#!/bin/bash
#
# This is a wrapper to processing scripts, that loops across subjects.
#
# Usage:
# ./run_process.sh <script> <path_data>
# script: the script to run
# path_data: the absolute path that contains all subject folders
#
# Example:
# ./run_process.sh extract_metrics.sh /Users/julien/data/spine_generic/
#
# Add the flag "-x" after "!/bin/bash" for full verbose of commands.
# <NAME> 2018-07-20
# Exit if user presses CTRL+C (Linux) or CMD+C (OSX)
trap "echo Caught Keyboard Interrupt within script. Exiting now.; exit" INT
# # Fetch OS type (used to open QC folder)
# if uname -a | grep -i darwin > /dev/null 2>&1; then
# # OSX
# export OPEN_CMD="open"
# elif uname -a | grep -i linux > /dev/null 2>&1; then
# # Linux
# export OPEN_CMD="xdg-open"
# fi
# Build color coding (cosmetic stuff)
Color_Off='\033[0m' # Text Reset
Green='\033[0;92m' # Green
Red='\033[0;91m' # Red
On_Black='\033[40m' # Black
# Load config file
if [ -e "parameters.sh" ]; then
source parameters.sh
else
printf "\n${Red}${On_Black}ERROR: The file parameters.sh was not found. You need to create one for this pipeline to work. Please see README.md.${Color_Off}\n\n"
exit 1
fi
# Build syntax for process execution
CMD=`pwd`/$1
# Go to path data folder that encloses all subjects' folders
cd ${PATH_DATA}
# If the variable SUBJECTS does not exist (commented), get list of all subject
# folders from current directory
if [ -z ${SUBJECTS} ]; then
echo "Processing all subjects present in: $PATH_DATA."
SUBJECTS=`ls -d */`
else
echo "Processing subjects specified in parameters.sh."
fi
# Loop across subjects
for subject in ${SUBJECTS[@]}; do
# Display stuff
printf "${Green}${On_Black}\n===============================\n\
PROCESSING SUBJECT: ${subject}\n===============================\n\
${Color_Off}"
# Go to subject folder
cd ${subject}
# Run process
$CMD
# Go back to parent folder
cd ..
done
<file_sep>/parameters_template.sh
#!/bin/bash
# Configuration file for your study.
# Copy this file and rename it as `parameters.sh`, then modify the variables
# according to your needs.
# Path to working directory, which contains data results, qc, etc. (do not add "/" at the end).
# This path should be absolute (i.e. should start with "/"). Example: PATH_DATA="/Users/bob/experiments"
export PATH_MAIN="/Users/julien/data/rainville_lumbar"
# Path to the folder which contains all data
export PATH_DATA="${PATH_MAIN}/data"
# List of subjects to analyse. If you want to analyze all subjects in the
# PATH_DATA folder, then comment this variable.
export SUBJECTS=(
"slbp_001p"
"SLBP_002"
"slbp_004"
"slbp_005"
"slbp_006"
)
# vertebral or disc level where FOV is centered. Uncomment the appropriate
# variable and assign value:
# export MIDFOV_DISC=X
# export MIDFOV_VERT=X
# Vertebral levels to compute MRI metrics from
export METRICS_VERT_LEVEL="3,4,5"
# Path where to save results (do not add "/" at the end).
export PATH_RESULTS="${PATH_MAIN}/results"
# Path where to save QC results (do not add "/" at the end).
export PATH_QC="${PATH_MAIN}/qc"
<file_sep>/1_process_data.sh
#!/bin/bash
#
# Process data
#
# Author: <NAME>
# Build color coding (cosmetic stuff)
Color_Off='\033[0m'
Green='\033[0;92m'
Red='\033[0;91m'
On_Black='\033[40m'
# mt
# ==============================================================================
cd mt
# Check if manual segmentation already exists
if [ -e "mt1_seg_manual.nii.gz" ]; then
file_seg="mt1_seg_manual.nii.gz"
else
# Segment cord
sct_propseg -i mt1.nii.gz -c t2
# sct_deepseg_sc -i mt1.nii.gz -c t2s # alternative algorithm if propseg does not work well
file_seg="mt1_seg.nii.gz"
# Check segmentation results and do manual corrections if necessary
fsleyes mt1.nii.gz -cm greyscale mt1_seg.nii.gz -cm red -a 70.0 &
printf "${Green}${On_Black}\nFSLeyes will now open. Check the segmentation. If necessary, manually adjust the segmentation and then save it as: mt1_seg_manual.nii.gz. Close FSLeyes when you're finished, go back to the Terminal and press any key to continue...${Color_Off}"
read -p ""
# check if segmentation was modified
if [ -e "mt1_seg_manual.nii.gz" ]; then
file_seg="mt1_seg_manual.nii.gz"
fi
fi
# Create mask
sct_create_mask -i mt1.nii.gz -p centerline,${file_seg} -size 35mm
# Crop data for faster processing
sct_crop_image -i mt1.nii.gz -m mask_mt1.nii.gz -o mt1_crop.nii.gz
# Register mt0->mt1
# Tips: here we only use rigid transformation because both images have very similar sequence parameters. We don't want to use SyN/BSplineSyN to avoid introducing spurious deformations.
sct_register_multimodal -i mt0.nii.gz -d mt1_crop.nii.gz -param step=1,type=im,algo=rigid,slicewise=1,metric=CC -x spline
# Register mt1->t1w
sct_register_multimodal -i t1w.nii.gz -d mt1_crop.nii.gz -param step=1,type=im,algo=rigid,slicewise=1,metric=CC -x spline
# Two scenarii depending if the FOV is centered at a disc or mid-vertebral body
if [ ! -z ${MIDFOV_DISC} ]; then
# create disc label in the middle of the S-I direction at the center of the cord
sct_label_utils -i ${file_seg} -create-seg -1,$MIDFOV_DISC -o label_disc.nii.gz
# Register template->mt1
sct_register_to_template -i mt1_crop.nii.gz -s ${file_seg} -ldisc label_disc.nii.gz -ref subject -c t2 -param step=1,type=seg,algo=centermass:step=2,type=im,algo=syn,metric=CC,slicewise=0,smooth=0,iter=3 -qc ${PATH_QC}
elif [ ! -z ${MIDFOV_VERT} ]; then
# create vert label in the middle of the S-I direction at the center of the cord
sct_label_utils -i ${file_seg} -create-seg -1,$MIDFOV_VERT -o label_vert.nii.gz
# Register template->t1w
sct_register_to_template -i mt1_crop.nii.gz -s ${file_seg} -l label_vert.nii.gz -ref subject -c t2 -param step=1,type=seg,algo=centermass:step=2,type=im,algo=syn,metric=CC,slicewise=0,smooth=0,iter=3 -qc ${PATH_QC}
else
printf "${Red}${On_Black}\nERROR: Neither MIDFOV_DISC nor MIDFOV_VERT field is active. Please see README.md. Exiting.\n\n${Color_Off}"
exit 1
fi
# Rename warping field for clarity
mv warp_template2anat.nii.gz warp_template2mt.nii.gz
# Warp template
sct_warp_template -d mt1_crop.nii.gz -w warp_template2mt.nii.gz
# Compute MTR
sct_compute_mtr -mt0 mt0_reg.nii.gz -mt1 mt1_crop.nii.gz
# Go back to parent folder
cd ..
<file_sep>/README.md
# multiparametric-fixed-fov
Processing pipeline (multi-subjects) for processing multi-parametric data when
FOV is systematically centered at a particular disc or mid-vertebral level. This prior
knowledge enables us to bypass the registration between the template and an anatomical data (typically T1 or T2), from which we can get the vertebral level information.
This pipeline will loop across all subjects (or only the subjects that you have specified) located under the `data` folder and
results will be concatenated into single csv files where each row will correspond to
a subject. The files will be output in the `data` folder.
The following metric is output:
- **mt**: MTR in WM in whole WM and sub-tracts, averaged across slices
In future versions of this pipeline, the following example metrics will be added:
- **dmri**: FA, MD, etc. in whole WM and sub-tracts, averaged across slices
- **mt**: MTsat in whole WM and sub-tracts, averaged across slices
## Dependencies
This pipeline was tested on [SCT v3.2.4](https://github.com/neuropoly/spinalcordtoolbox/releases/tag/v3.2.4). This pipeline also relies on [FSLeyes](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FSLeyes) for active quality control (QC).
## File structure
~~~
data
|- 001
|- 002
|- 003
|- mt
|- mt1.nii.gz
|- mt0.nii.gz
|- t1w.nii.gz
~~~
## How to run
- Organize your data as indicated above
- Download (or `git clone`) this repository.
- Go to the repository folder: `cd multiparametric-fixed-fov`
- Copy the file `parameters_template.sh` and rename it as `parameters.sh`.
- Edit the file `parameters.sh` and modify the variables according to your needs:
- `PATH_DATA`: Absolute path to the DATA folder. E.g.: `/Users/bob/data`
- `SUBJECTS`: List of subjects to analyze. If you want to analyze all subjects
in the `PATH_DATA` folder, then comment this variable.
- `METRICS_VERT_LEVEL`: Vertebral levels to compute MRI metrics from. For example, if you want to extract metrics from levels 2, 3, 4 and 5, set this variable as `METRICS_VERT_LEVEL="2,3,4,5"`.
- `PATH_RESULTS`: Path where results will be stored. Default is: `$PATH_DATA/results`
- Superior-Inferior (S-I) location of the center of FOV: Uncomment **only one**
of the following variables, depending if the FOV is centered at a disc or at
a mid-vertebral level, and replace `X` with the value corresponding to your
acquisition setup. For example, if the MRI volume is centered at the
mid-T10 vertebral level, then uncomment `MIDFOV_VERT` and set the value to
`17` (see figure below):
- `MIDFOV_DISC=X`
- `MIDFOV_VERT=X`:

- Once the file `parameters.sh` is configured, you can run the pipeline as follows:
- Process data: Will do most of the processing. A QC folder will be generated to check template registration.
~~~
./run_process.sh 1_process_data.sh
~~~
- Compute metrics: Extract metrics within specified labels and levels.
~~~
./run_process.sh 2_extract_metrics.sh
~~~
## Contributors
<NAME>
| f6b810c1c8d957313e8d21c564e76dbcbe7991d4 | [
"Markdown",
"Shell"
] | 5 | Shell | sct-pipeline/multiparametric-fixed-fov | cc1abdbf2bd84c76d7de6a5a249f166dbf3fc7e3 | 57e060a3fa9aeeb6c684370ebc1df06f4dba3031 |
refs/heads/master | <repo_name>xzjxx/learngit<file_sep>/socket/DataBase/ConDB.java
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import Common.User;
public class ConDB {
private String driverName; //驱动名
private static String dbURL; //连接数据库的URL地址
private static String userName; //数据库的用户名
private static String root; //数据库的密码
private Connection con; //数据库连接对象
private PreparedStatement pstm; //数据库预编译处理对象
public ConDB(){
driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=sqltestdb";
userName="sa";
root="6<PASSWORD>";
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
System.out.println("加载数据库驱动程序失败!");
e.printStackTrace();
}
}
public void getCon(){
try {
con=DriverManager.getConnection(dbURL,userName,root);
} catch (SQLException e) {
System.out.println("获取数据库连接失败!");
e.printStackTrace();
}
if(con!=null)
System.out.println("连接数据库成功!");
}
//对象数组。如:String[] obj = new String[]{"宾桀锋","201321173083"};
public void doPstm(String sql,Object[] params){
if(sql!=null && !sql.equals(""))
{
if(con==null)
getCon();
try {
pstm=con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
if(params==null){
params=new Object[0];
}
for(int i=0;i<params.length;i++){
pstm.setObject(i+1,params[i]);
}
pstm.execute();
} catch (SQLException e) {
System.out.println("调用DB类中doPstm方法时出错!");
e.printStackTrace();
}
}
}
public ResultSet getRs(){
try {
return pstm.getResultSet();
} catch (SQLException e) {
System.out.println("DB类中的getRs()方法出错!");
e.printStackTrace();
return null;
}
}
public int getUpdate(){
try {
return pstm.getUpdateCount();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
//检查用户是否存在和密码是否正确
//0:用户不存在;1:密码正确;2:密码错误
public int CheckUser(User u) {
int b=0;
String userid=null,password=null;
Object []params=null;
String sql="select * from UserTable ";
doPstm(sql, params);
ResultSet rs=getRs();
try {
while(rs.next())
{
//检测输入的用户名是否存在以及密码是否正确
userid=rs.getString("userid");
password=rs.getString("password");
if(userid.equals(u.userid))
{
b=2;
if(password.equals(u.passwd))
b=1;
}
}
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
//closed();
return b;
}
}
//将注册的新用户增加到数据库
public void InsertUser(User u)
{
System.out.println("新增用户");
Object []params={u.userid,u.passwd,u.online};
String sql="insert into UserTable values(?,?,?)";
doPstm(sql, params);
ResultSet rs=getRs();
}
//返回所有账户
public ResultSet AllUser() {
String userid=null,password=null;
Object []params=null;
String sql="select * from UserTable ";
doPstm(sql, params);
ResultSet rs=getRs();
return rs;
}
//修改用户在线状态
public void updata(User u) {
String userid=null,password=null,online=null;
Object []params= {u.userid,u.passwd,u.online,u.userid};
String sql="update UserTable set userid=?,password=?,online=? where userid=?";
doPstm(sql, params);
}
public void closed(){
try{
if(pstm!=null)
pstm.close();
}catch(Exception e){
System.out.println("关闭pstm对象失败!");
}
try{
if(con!=null)
con.close();
}catch(Exception e){
System.out.println("关闭con对象失败!");
}
}
}
<file_sep>/socket/DataBase/Main.java
package DataBase;
import java.sql.*;
import Common.User;
public class Main {
/*public static void main(String[] args) {
User u=new User();
u.setUserID("123456789");
u.setPasswd("<PASSWORD>");
Condb(u);
}*/
public static boolean Condb(User u) {
boolean b=false;
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=sqltestdb";
String userName="sa";
String root="654123";
try {
Class.forName(driverName);//加载驱动程序
Connection dbCon=DriverManager.getConnection(dbURL,userName,root);
System.out.println("连接数据库成功");
//创建statement类对象,用来执行sql语句
Statement statement=dbCon.createStatement();
//要执行的select语句
String sql="select* from UserTable";
//ResultSet类用来存放获取的结果集
ResultSet rs=statement.executeQuery(sql);
System.out.println("结果:");
dbCon.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_READ_ONLY);
String userid=null,password=null;
while(rs.next())
{
userid=rs.getString("userid");
password=rs.getString("password");
if(userid.equals(u.userid))
{
if(password.equals(u.passwd))
b=true;
System.out.println(userid+"\t"+password);
}
}
PreparedStatement psql;
ResultSet res;
//预处理添加数据,其中有两个参数
psql=dbCon.prepareStatement("insert into UserTable(userid,password)"
+"values(?,?)");
psql.setString(1, "123456789");
psql.setString(2, "654123");
psql.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}finally {
return b;
}
}
}<file_sep>/socket/ChatLogin/Login.java
package ChatLogin;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.sql.*;
import java.util.*;
import javax.swing.JOptionPane;
import ChatClient.ChatClient;
import Common.User;
import DataBase.*;
import javafx.application.Application;
import javafx.event.*;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.scene.image.*;
import javafx.scene.input.KeyCode;
import javafx.fxml.*;
public class Login
{
static File file=new File("Y:\\LasterUser.txt");
private Stage LoginStage; //登录面板
private BorderPane pane=new BorderPane();
private VBox vbox;
private Image image;//图片
private ComboBox userComboBox; //用户名组合框
PasswordField pf;//密码文本框
private HBox hbox;
Button loginbt;
Button registerbt;
public Login(){
LoginStage=new Stage();
pane=new BorderPane();
vbox=new VBox(15);
image=new Image("image/image1.gif");
userComboBox = new ComboBox();
pf=new PasswordField();
hbox=new HBox(15);
loginbt=new Button("登录");
registerbt=new Button("注册");
Scene scene= new Scene(Loginpane(),430,700);
scene.setOnKeyPressed(e->{
if(e.getCode()==KeyCode.ENTER)
{
presslogin();
}
});
LoginStage.setTitle("多人聊天室");
LoginStage.setScene(scene);
LoginStage.setResizable(false);//窗体不能调整
LoginStage.show();
}
//登录界面
private BorderPane Loginpane()
{
//设置中间界面(包括用户名,密码等)
VBox vbox=new VBox(15);
vbox.setPadding(new Insets(100,100,100,100));//设置边距
//vbox.setStyle("-fx-background-color:pink");
vbox.getChildren().addAll(new ImageView(image));
//读取文件,将最近登录的三个用户添加进用户名组合框
readFileString();
userComboBox.setEditable(true);
userComboBox.setOnAction((Event ev) -> {
userComboBox.getSelectionModel().getSelectedItem().toString();
});
vbox.getChildren().addAll(new Label("用户名:"),userComboBox);//将用户名组合框添加进pane
//设置“记住密码”可选按钮属性
vbox.getChildren().addAll(new Label("密码:"),pf);//将密码文本框和“记住密码”可选按钮添加进pane
pane.setTop(vbox);
//设置按钮界面
HBox hbox=new HBox(15);
hbox.setPadding(new Insets(15,15,15,15));
hbox.setSpacing(10);
Label label=new Label(" ");//为了设置按钮间距
Label label1=new Label(" ");//为了设置按钮间距
hbox.getChildren().addAll(label,loginbt,label1,registerbt);//将按钮添加到pane
//登录按钮驱动程序
loginbt.setOnAction(e->{
presslogin();
});
//注册按钮驱动程序
registerbt.setOnAction(e->{
new Register();//进入注册界面
LoginStage.close();//关闭登录界面
});
hbox.setFillHeight(true);
pane.setCenter(hbox);
pane.setStyle("-fx-background-image:url(image/背景.jpg)");
return pane;
}
//发送按钮和enter
public void presslogin() {
User u=new User();
u.setUserID(userComboBox.getValue().toString());//从用户名组合框中获取用户名
u.setPasswd(pf.getText());//从密码文本框中获取密码
//将用户信息进行检查
int n=new ConDB().CheckUser(u);//调用数据库检查用户信息函数
if(n==1)
{
//验证成功,更改数据库用户状态,并进入用户端
LoginFile(u.userid);//将登入成功用户写入文件
u.setonline("yes");//将用户状态改为上线
new ConDB().updata(u);
new ChatClient(u);
//new Client();
LoginStage.close();
}
if(n==2){
//密码错误,显示提示窗口
JOptionPane.showMessageDialog(null,"密码错误","提示",
JOptionPane.ERROR_MESSAGE);
}
if(n==0)
{
//用户名不存在,显示提示窗口
JOptionPane.showMessageDialog(null,"用户名不存在。","提示",
JOptionPane.ERROR_MESSAGE);
}
}
//登录用户写入文件
public void LoginFile(String userid)
{
try {
if(!file.exists())
file.createNewFile();
FileWriter w = new FileWriter(file,true);
List<String> linelist=Collections.emptyList();//创建一个List对象,并初始化为空(不占内存)
linelist=java.nio.file.Files.readAllLines(Paths.get(file.getPath()),
StandardCharsets.UTF_8);
//将登录成功的用户写入文件,如果与上一个登录成功的用户相等,则不写入
if(linelist.size()>=1)
{
if(!userid.equals(linelist.get(linelist.size()-1)))
{
w.write(userid+"\n");
w.flush();//刷新
w.close();//关闭
}
else
System.out.println("当前用户与前一用户相等");
}
else
{
w.write(userid+"\n");
w.flush();//刷新
w.close();//关闭
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
//用户文本框处显示最近登录的3个用户的用户名(少于的3个的显示2个或者1个)
public void readFileString() {
List<String> linelist=Collections.emptyList();//创建一个List对象,并初始化为空(不占内存)
try {
if(!file.exists())
file.createNewFile();
linelist=java.nio.file.Files.readAllLines(Paths.get(file.getPath()),
StandardCharsets.UTF_8);
//输出最近登录的不一样的三个用户
if(linelist.size()!=0)
{
int count=1;
userComboBox.getItems().add(linelist.get(linelist.size()-1));//将最近登录的第一个用户添加到组合框
for(int i=linelist.size()-2;i>=0;i--)
{
for(int j=linelist.size()-1;j>i;j--)
{
if(count>2)
break;//如果超过三个就退出,因为只需要显示三个不同的用户
if(!linelist.get(i).equals(linelist.get(j)))
{
if(j==i+1)
{
userComboBox.getItems().add(linelist.get(i));
count++;
break;
}
}
else
break;
}
}
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
System.out.println("失败");
}
}
}
<file_sep>/socket/ChatClient/ChatClient.java
package ChatClient;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import ChatFriend.ChatRoom;
import Common.User;
public class ChatClient {
int flag=0;
public ChatClient(User u) {
try {
Socket socket = new Socket("172.16.17.32",8888);
//Socket socket = new Socket("127.0.0.1",8888);
System.out.println("我是客户端O(∩_∩)O~");
ChatRoom chr = new ChatRoom(u); //打开聊天室好友界面
// 启动收消息的线程
new Thread(new ClientRecieveThread(socket, chr)).start();
// 启动发消息的线程
new Thread(new ClientSendThread(socket, chr)).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}<file_sep>/socket/ChatFriend/ChatRoom.java
package ChatFriend;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import javax.swing.JOptionPane;
import java.io.*;
import Common.User;
import DataBase.ConDB;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class ChatRoom {
private Stage stage;
private BorderPane borderpane;
private BorderPane dispalypane;
private GridPane friendpane;//好友列表显示界面
private Image image;
private GridPane textpane;//存放聊天窗口和输入窗口的面板,竖直放置
public TextArea displayArea=new TextArea();
private TextArea inputArea=new TextArea();
private Button sendbutton;//发送按钮
public OutputStream ops; //输出信息流
private String iputMsg; //在对话框输入的内容
public String sendMsg; //传给服务端的内容
private User u;
public ChatRoom(User u)
{
stage=new Stage();
borderpane=new BorderPane();
dispalypane=new BorderPane();
friendpane=new GridPane();
image=new Image("image/头像.gif");
textpane=new GridPane();
sendbutton=new Button("发送");
this.u=u;
borderpane.setLeft(FriendPane(u.getUserID()));
borderpane.setCenter(TextPane(u));
borderpane.setTop(new Label(""));
borderpane.setRight(new Label(" "));
borderpane.setStyle("-fx-background-image:url(image/背景.jpg)");
Scene scene= new Scene(borderpane,1000,600);
/*scene.setOnKeyPressed(e->{
if(e.getCode()==KeyCode.ENTER)
{
presssend();
}
});*/
stage.setTitle("欢迎进入多人聊天室");
stage.setScene(scene);
//stage.setResizable(false);//窗体不能调整
stage.show();
//关闭窗口触发下线,要更改用户在线信息
stage.setOnCloseRequest(e->{
u.setonline("no");
new ConDB().updata(u);
});
}
private GridPane FriendPane(String userid)
{
//friendpane.setAlignment(Pos.TOP_LEFT);
HBox userbox=new HBox(5);
Label userlabel=new Label(userid);
userbox.getChildren().addAll(new ImageView(image),userlabel);
friendpane.add(userbox,0,1);
//”在线列表“标题设置
HBox hbox=new HBox(10);
//hbox.setPadding(new Insets(20,20,20,20));//设置边距
hbox.setStyle("-fx-border-color:pink");
Label label=new Label("在线列表");
label.setAlignment(Pos.CENTER);
label.setFont(new Font("Monospaced",25));
hbox.getChildren().add(label);
friendpane.add(hbox,0,2);
friendpane.add(setOnlinelist(),0,3);
return friendpane;
}
public VBox setOnlinelist() {
//在线列表显示
VBox vbox=new VBox(5);
vbox.setPadding(new Insets(0,0,500,20));//设置边距
vbox.setStyle("-fx-border-color:pink");
List<Label> lists=Collections.emptyList();
int i=0;
String useridrs=null,online=null;
try {
ResultSet rs=new ConDB().AllUser();
while(rs.next())
{
useridrs=rs.getString("userid");
online=rs.getString("online");
Label label1 = null;
Font font=new Font("Monospaced",18);
if(!useridrs.equals(u.userid)) {
label1=new Label(useridrs);
label1.setFont(font);
label1.setContentDisplay(ContentDisplay.LEFT);
//label1.setStyle("-fx-border-color:black");
if(online.equals("yes"))
{
label1.setTextFill(Color.RED);//在线设为红色
}
else
{
label1.setTextFill(Color.GRAY);//离线设为灰色
}
vbox.getChildren().add(label1);
}
}
} catch (SQLException e) {
// TODO 自动生成的 catch 块
System.out.println("错误");
}
return vbox;
}
private GridPane TextPane(User u){
//创建显示面板
//TextArea displayArea=new TextArea();//创建一个文本区域
displayArea.setEditable(false);//不可编辑的
displayArea.setWrapText(true);//可拆到下一行
displayArea.setFont(Font.font("Times",20));//设置字体
dispalypane.setCenter(displayArea);
textpane.add(dispalypane,0,1);
Label inputlabel=new Label("输入框");
//加入"输入框"label
textpane.add(inputlabel,0,2);
textpane.add(inputArea,0,3);
//设置输入面板属性
inputArea.setEditable(true);//不可编辑的
inputArea.setWrapText(true);//可拆到下一行
//在面板里加入发送按钮
textpane.add(sendbutton,0,4);
//发送按钮触发程序
sendbutton.setOnAction(e->{
try {
iputMsg=inputArea.getText();//获取输入框中的文本
if(iputMsg.isEmpty())
{
JOptionPane.showMessageDialog(null,"发送内容不能为空!","提示",
JOptionPane.ERROR_MESSAGE);
}
else
{
sendMsg=u.getUserID()+":"+iputMsg+"\n";//传给服务端的消息要加入换行符,服务端才能知道什么时候结束接收
//点击发送后,输入面板要清空
inputArea.clear();
iputMsg=null;
//要每点击一次发送就要将内容写入输出流中
ops.write(sendMsg.getBytes());
ops.flush();
}
} catch (IOException e1) {
e1.printStackTrace();
}
});
return textpane;
}
public TextArea getArea() {
return displayArea;
}
public String getUserid() {
return u.userid;
}
}
| 8fb7f448ec2c2ebb37b0ce3e0b7b01609e39e2d6 | [
"Java"
] | 5 | Java | xzjxx/learngit | 625251532147fb2d1a43d5ce31bb345c072f23ac | e36482befeb1b20a8ae68245c94c5d0bdc74fbd1 |
refs/heads/master | <repo_name>WillGreen98/Project-Euler<file_sep>/Tasks 1-99/Task 05/Task-5.py
# Task 5 - Python
# Smallest Multiple
import math
import time
from functools import reduce
def gcd(a, b):
if b == 0: return a
else: return gcd(b, math.fmod(a, b))
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
time_start = time.time()
smallest_multiple = (int(reduce(lcm, range(1, 20, 1))))
print("Answer: {0} => Calculated in: {1}".format(smallest_multiple, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 21/Task-21.py
# Task 21 - Python
# Amicable Numbers
import time
from functools import reduce
def d(n):
return sorted(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))[:-1]
def amicable_numbers_check(m, n):
return "{0} & {1} => {2}".format(m, n, sum(d(m)) == n and n != m)
def d_calculate():
total = 0
def main():
time_start = time.time()
print(d(220))
print(d(284))
print(amicable_numbers_check(220, 284))
amicable_numbers = d_calculate()
print("Answer: {0} => Calculated in: {1}".format(amicable_numbers, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 22/Task-22.py
# Task 22 - Python
# Name Scores
import time
import string
names_list = sorted(open("pe22_data_set.txt").read().replace("", '').split(','))
def letter_value(name):
return sum(string.ascii_uppercase.index(i) + 1 for i in name.strip('"'))
def name_score():
return sum(key * letter_value(value) for key, value in enumerate(names_list, 1))
def main():
time_start = time.time()
name_score_value = name_score()
print("Answer: {0} => Calculated in: {1}".format(name_score_value, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 19/Task-19.py
# Task 19 - Python
# Counting Sundays
import time
import calendar
def date_checker():
number_sundays = 0
calendar.setfirstweekday(6)
for year in range(1901, 2001, 1):
for month in range(1, 13, 1):
if calendar.weekday(year, month, 1) == calendar.SUNDAY:
number_sundays += 1
return number_sundays
def main():
time_start = time.time()
counting_sundays = date_checker()
print("Answer: {0} => Calculated in: {1}".format(counting_sundays, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 10/Task-10.py
# Task 10 - Python
# Summations Of Primes
import math
import time
is_prime = lambda num_to_check: all(num_to_check % i for i in range(3, int(math.sqrt(num_to_check)) + 1, 2))
def sum_of_primes(upper_bound):
fp_c = 2
summation = 0
eratosthenes_sieve = ((upper_bound + 1) * [True])
while math.pow(fp_c, 2) < upper_bound:
if is_prime(eratosthenes_sieve[fp_c]):
multiple = fp_c * 2
while multiple < upper_bound:
eratosthenes_sieve[multiple] = False
multiple += fp_c
fp_c += 1
for i in range(fp_c, upper_bound + 1):
if eratosthenes_sieve[i]:
summation += 1
return summation
def main():
time_start = time.time()
prime_sum = sum_of_primes(11)
print("Answer: {0} => Calculated in: {1}".format(prime_sum, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 24/Task-24.py
# Task 24 - Python
# Lexicographic Permutations
import time
import string
from itertools import permutations
def lexicographical_permutations_cheeky(index):
return ''.join(list(permutations(string.digits))[index])
def permutation(data):
lexi_temp = []
for head in range(len(data)):
lp = data[:head] + data[head + 1:]
for tail in permutation(lp):
lexi_temp.append(data[head:head + 1] + tail)
return lexi_temp
def main():
time_start = time.time()
millionth_lexi_perm = permutation(string.digits)
cheeky_lexi_perm = lexicographical_permutations_cheeky(999999)
spicy_lexi_perm = divmod(999999, 362880)
print("Answer: {0} => Calculated in: {1}".format(millionth_lexi_perm, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 07/Task-7.py
# Task 7 - Python
# 10001st Prime
import math
import time
primes = []
def is_prime(n):
# Task 3 lambda done correctly accoring to PEP8
if n % 2 == 0 and n > 2: return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def prime(n):
i = 2
while n > 0:
if is_prime(i):
n -= 1
if n == 0: return i
i += 1
return -1
def main():
time_start = time.time()
nth_prime = prime(10001)
print("Answer: {0} => Calculated in: {1}".format(nth_prime, (time.time() - time_start)))
if __name__ == '__main__':
main()
<file_sep>/Tasks 1-99/Task 09/Task-9.py
# Task 9 - Python
# Special Pythagorean Triplet
import math
import time
num_to_check = 1000
def pythagorean_triple():
for a in range(1, num_to_check):
for b in range(1, num_to_check):
for c in range(1, num_to_check):
if((a + b + c) == num_to_check) and ((math.pow(a, 2)) + math.pow(b, 2) == math.pow(c, 2)):
print("A: {0} B: {1} C :{2}".format(a, b, c))
return a * b * c
def main():
time_start = time.time()
triple = pythagorean_triple()
print("Answer: {0} => Calculated in: {1}".format(triple, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 11/Task-11.py
# Task 11 - Python
# Largest Product In Grid
import time
grid = [list(map(int, line.split())) for line in open('pe11_data_set.txt').readlines()]
def largest_four_sum():
x = max(grid[row][col] * grid[row][col + 1] * grid[row][col + 2] * grid[row][col + 3] for row in range(20) for col in range(17))
y = max(grid[row][col] * grid[row + 1][col] * grid[row + 2][col] * grid[row + 3][col] for row in range(17) for col in range(20))
xy_bottom_left_up = max(grid[row][col] * grid[row + 1][col + 1] * grid[row + 2][col + 2] * grid[row + 3][col + 3] for row in range(17) for col in range(17))
xy_top_left_down = max(grid[row][col] * grid[row - 1][col + 1] * grid[row - 2][col + 2] * grid[row - 3][col + 3] for row in range(3, 20) for col in range(17))
return max(x, y, xy_bottom_left_up, xy_top_left_down)
def main():
time_start = time.time()
largest_sum = largest_four_sum()
print("Answer: {0} => Calculated in: {1}".format(largest_sum, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 12/Task-12.py
# Task 12 - Python
# Highly Divisible Triangular Number
import time
triangular_nth = lambda n: (n * (n + 1)) / 2
def triangular_number():
num_to_check = 1
while triangular_nth(num_to_check) <= 500:
num_to_check += 1
return num_to_check
def main():
time_start = time.time()
triangular_num = triangular_number()
print("Answer: {0} => Calculated in: {1}".format(triangular_num, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 20/Task-20.py
# Task 20 - Python
# Factorial Digit Sum
import time
from functools import reduce
# Cheeky
# import math
# print(math.factorial(100))
def factorial_finder(number):
return reduce(lambda a, b: a * b, range(1, number + 1))
def main():
time_start = time.time()
factorial_hundred = factorial_finder(100)
print("Answer: {0} => Calculated in: {1}".format(factorial_hundred, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 18/Task-18.py
# Task 18 - Python
# Maximum path sum I
import math
import time
triangle = [list(map(int, line.split())) for line in open('pe18_data_set.txt').readlines()]
def path():
# Dynamic Methods for Bottom-Up
for row in range(len(triangle) - 1, 0, -1):
for col in range(0, row):
triangle[row - 1][col] += max(triangle[row][col], triangle[row][col + 1])
return triangle[0][0]
def main():
time_start = time.time()
max_route = path()
print("Answer: {0} => Calculated in: {1}".format(max_route, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 02/Task-2.py
# Task 2 - Python
# Sum of even fib nums
import time
nums = {}
def fibonacci(fib_limit):
a, b = 1, 1
for i in range(1, fib_limit):
a, b = b, a + b
return a
# Memoize / Caching because of recursion limit being < 4000000
def fibonacci_gen(fib_limit, i):
if i not in nums:
nums[i] = fib_limit(i)
return nums[i]
def sum_even_fib():
sum = 0
for i in range(35):
fib_num = fibonacci_gen(fibonacci, i)
if fib_num % 2 == 0:
sum += fib_num
return sum
def main():
time_start = time.time()
fib_sum = sum_even_fib()
print("Answer: {0} => Calculated in: {1}".format(fib_sum, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 14/Task-14.py
# Task 14 - Python
# Longest Collatz sequence
import time
collatz_rule = lambda n: n / 2 if n % 2 == 0 else ((3 * n) + 1)
def collatz_seq():
cache = [0, 0]
for i in range(1000000):
num = collatz_rule(i)
if num > cache[0]:
cache[0] = num
cache[1] = i
return cache[0], "contains Collatz terms:", cache[1]
def main():
time_start = time.time()
collatz_sequence = collatz_seq()
print("Answer: {0} => Calculated in: {1}".format(collatz_sequence, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 17/Task-17.py
# Task 17 - Python
# Number letter counts
import time
num_ln = {ln: len(number) for (ln, number) in {
"Units": {1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"},
"Tens": {10: "Ten", 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty", 90: "Ninety"},
"Extra": {'and': "and", 100: "Hundred", 1000: "Thousand"}}.items()}
def count_letters():
total = 0
for i in range(1, 1000, 1):
digit_units = (i % 10)
digit_tens = (((i % 100) - digit_units) / 10)
digit_hundreds = (((i % 1000) - (digit_tens * 10) - digit_units) / 100)
if digit_hundreds != 0:
total += num_ln['Units'][digit_hundreds] + num_ln['Extra'][1000]
if digit_tens != 0 or digit_units != 0:
total += num_ln['Extra']["and"]
if digit_tens == 0 or digit_tens == 1:
total += num_ln['Units'][(num_ln["Units"][digit_units] * 10) + digit_units]
else: total += num_ln['Tens'][digit_tens] + num_ln["Units"][digit_tens]
return total
def main():
time_start = time.time()
letters_count = count_letters()
print("Answer: {0} => Calculated in: {1}".format(letters_count, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 23/Task-23.py
# Task 23 - Python
# Non-Abundant Sums
import time
def is_abundant(n):
yield lambda n: sum(filter(lambda j: n % j == 0, range(1, n/2 + 1))) > n
def is_perfect(n):
yield sum([i for i in range(1, n + 1) if n % i == 0]) == 2 * n
abundants_yield = list(i for i in range(1, 28123) if is_abundant(i))
def non_abundant_sums():
abundant_sum = 1
for i in range(12, 28123):
for abundant_number in abundants_yield:
if abundant_number >= i and not is_perfect(abundant_number) and is_abundant(i + abundant_number):
abundant_sum += i
return abundant_sum
def main():
time_start = time.time()
non_abundant_sum = non_abundant_sums()
print("Answer: {0} => Calculated in: {1}".format(non_abundant_sum, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 16/Task-16.py
# Task 16 - Python
# Power Digit Sum
import math
import time
def pds():
return sum([int(num) for num in str(int(math.pow(2, 1000)))])
def main():
time_start = time.time()
pds_value = pds()
print("Answer: {0} => Calculated in: {1}".format(pds_value, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 15/Task-15.py
# Task 15 - Python
# Lattice Paths
import time
from functools import reduce
binomial = lambda grid_size: reduce(lambda hoz, vert: hoz * vert, range(1, grid_size + 1), 1)
def path_route_finder(grid_size_to_check):
# As size is perfect cube - I have limited calculations instead of n & m
size = grid_size_to_check
if grid_size_to_check == 0: return 1
return binomial(2*size) // binomial(size) // binomial(size)
def main():
time_start = time.time()
route_num = path_route_finder(20)
print("Answer: {0} => Calculated in: {1}".format(route_num, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/README.md
# Project-Euler
I am attempting to tackle the infamous problem-sets of the Project Euler.
## Programming Approaches
* Code
* Programmatic
* Cheeky uses of built-in Python Modules
* Utilisation of Theoretical & Conceptual Maths
E.g A `brute-force` `for` loop of +- 1 compared to a defined Summation<file_sep>/Tasks 1-99/Task 03/Task-3.py
# Task 3 - Python
# Largest Prime Factor
import math
import time
modulo = lambda x, y: x % y == 0
def lpf():
fp_c = 2
num_to_check = 600851475143
while math.pow(fp_c, 2) < num_to_check:
if modulo(num_to_check, fp_c):
num_to_check //= fp_c
fp_c += 1
return num_to_check
def main():
time_start = time.time()
lowest_prime = lpf()
print("Answer: {0} => Calculated in: {1}".format(lowest_prime, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 04/Task-4.py
# Task 4 - Python
# Largest Palindrome Product
import time
palindromes = []
def palindrome_check(number):
return bool(str(number) == str("{0}".format(number)[::-1]))
def largestPalindrome():
for i in range(100, 999, 1):
for j in range(100, 999, 1):
product = i * j # Mathematically = xyz * abc
if palindrome_check(product):
palindromes.append(product)
return max(palindromes)
def main():
time_start = time.time()
largest_palindrome = largestPalindrome()
print("Answer: {0} => Calculated in: {1}".format(largest_palindrome, (time.time() - time_start)))
if __name__ == '__main__':
main()<file_sep>/Tasks 1-99/Task 06/Task-6.py
# Task 6 - Python
# Sum Square Difference
import math
import time
def square_values():
# Sqaure Individually
total_i = 0
for i in range(0, 101, 1):
product = math.pow(i, 2)
total_i += product
# Sqaure as a sum
total_s = 0
for j in range(0, 101, 1):
total_s += j
product = math.pow(total_s, 2)
return product, "-", total_i, "= ", product - total_i
def main():
time_start = time.time()
sqaure_products = square_values()
print("Answer: {0} => Calculated in: {1}".format(sqaure_products, (time.time() - time_start)))
if __name__ == '__main__':
main()
<file_sep>/Tasks 1-99/Task 08/Task-8.py
# Task 8 - Python
# Largest Product In A Series
import time
from functools import reduce
number = [[int, line.split()] for line in open('pe08_data_set.txt').readlines()]
def lps():
return (max([reduce(lambda sum, x:
sum * x, [int(x)
for x in number[i:i + 5]])
for i in range(len(number) - 5)]))
def main():
time_start = time.time()
largest_product = lps()
print("Answer: {0} => Calculated in: {1}".format(largest_product, (time.time() - time_start)))
if __name__ == '__main__':
main()
<file_sep>/Tasks 1-99/Task 01/Task-1.py
# Task 1 - Python
# Multiples of 3 and 5
import math
import time
def mul_three_five():
count_T = 0
for i in range(int(math.pow(10, 3))):
if i % 3 == 0 or i % 5 == 0:
count_T += i
return count_T
def main():
time_start = time.time()
count_T = mul_three_five()
print("Answer: {0} => Calculated in: {1}".format(count_T, (time.time() - time_start)))
if __name__ == '__main__':
main() | b1bfe80be3955977af7670a69db9fdae36a6ffe6 | [
"Markdown",
"Python"
] | 24 | Python | WillGreen98/Project-Euler | 933caf03a1f2c191749445bd3c481117ce510b49 | e0dc52aa57c6b1d5f2be9be51cf1b76a722a8420 |
refs/heads/master | <repo_name>voronianski/swapi-graphql-react-app<file_sep>/src/components/__tests__/ErrorDetails.spec.js
import React from "react";
import { shallow, mount } from "enzyme";
import ErrorDetails from "../ErrorDetails";
describe("ErrorDetails component", () => {
it("should render passed error text", () => {
const errorText = "Oops!";
const wrapper = shallow(<ErrorDetails text={errorText} />);
expect(wrapper.find(".error-details-text").text()).toEqual(errorText);
});
it("should render giphy image", () => {
const wrapper = mount(<ErrorDetails />);
expect(
wrapper
.find(".error-details-image")
.getDOMNode()
.getAttribute("src")
).toContain("giphy");
});
});
<file_sep>/src/components/History.js
import React from "react";
import { connect } from "react-redux";
import Title from "./Title";
import VisitedPersons from "./VisitedPersons";
export const History = ({ personIds }) => {
return (
<div className="history">
<Title text="History" />
<div className="mt3 mb3">
<VisitedPersons ids={personIds} />
</div>
</div>
);
};
const mapStateToProps = state => ({
personIds: state.visitedPersons
});
export default connect(mapStateToProps)(History);
<file_sep>/src/components/__tests__/Header.spec.js
import React from "react";
import { shallow } from "enzyme";
import Header from "../Header";
describe("Header component", () => {
it("should include logo", () => {
const wrapper = shallow(<Header />);
expect(wrapper.exists(".header-logo")).toEqual(true);
});
it("should include navigation bar", () => {
const wrapper = shallow(<Header />);
expect(wrapper.exists(".header-nav")).toEqual(true);
});
it("should include 'Search' navigation link", () => {
const wrapper = shallow(<Header />);
const searchLink = wrapper.find("NavLink").at(0);
expect(searchLink.prop("to")).toEqual("/");
expect(searchLink.prop("children")).toEqual("Search");
});
it("should include 'History' navigation link", () => {
const wrapper = shallow(<Header />);
const historyLink = wrapper.find("NavLink").at(1);
expect(historyLink.prop("to")).toEqual("/history");
expect(historyLink.prop("children")).toEqual("History");
});
});
<file_sep>/src/components/__tests__/Person.spec.js
import React from "react";
import { shallow, mount } from "enzyme";
import { MockedProvider } from "react-apollo/test-utils";
import { Person } from "../Person";
describe("Person component", () => {
it("should call addVisitedPerson on render", () => {
const props = {
match: { params: { id: "123" } },
addVisitedPerson: jest.fn()
};
shallow(<Person {...props} />);
expect(props.addVisitedPerson.mock.calls.length).toBe(1);
expect(props.addVisitedPerson.mock.calls[0][0]).toBe(props.match.params.id);
});
it("should include PersonDetails", () => {
const props = {
match: { params: { id: "123" } },
addVisitedPerson: () => {}
};
const wrapper = mount(
<MockedProvider mocks={[]} addTypename={false}>
<Person {...props} />
</MockedProvider>
);
expect(wrapper.exists("PersonDetails")).toEqual(true);
});
});
<file_sep>/src/components/__tests__/Title.spec.js
import React from "react";
import { shallow } from "enzyme";
import Title from "../Title";
describe("Title component", () => {
it("should render proper title text", () => {
const titleText = "Super title!";
const wrapper = shallow(<Title text={titleText} />);
expect(wrapper.find(".title-text").text()).toEqual(titleText);
});
});
<file_sep>/src/utils/session.js
const personIdsKey = "person-ids";
const getPersonIds = () => {
let ids = [];
try {
const idsString = window.sessionStorage.getItem(personIdsKey);
if (idsString) {
ids = JSON.parse(idsString);
}
} catch (err) {
console.error(`Failed to parse "${personIdsKey}" from sessionStorage`, err);
}
return ids;
};
const savePersonIds = (ids = []) => {
sessionStorage.setItem(personIdsKey, JSON.stringify(ids));
};
export default {
getPersonIds,
savePersonIds
};
<file_sep>/src/store/actions/index.spec.js
import * as actions from "./index";
import * as types from "./types";
describe("visited persons actions", () => {
it("addVisitedPerson should create ADD_VISITED_PERSON action", () => {
const id = "12345";
const expectedAction = {
type: types.ADD_VISITED_PERSON,
id
};
expect(actions.addVisitedPerson(id)).toEqual(expectedAction);
});
it("populateVisitedPersons should create POPULATE_VISITED_PERSONS action", () => {
const ids = ["12345", "67890"];
const expectedAction = {
type: types.POPULATE_VISITED_PERSONS,
ids
};
expect(actions.populateVisitedPersons(ids)).toEqual(expectedAction);
});
});
<file_sep>/src/components/__tests__/PersonLink.spec.js
import React from "react";
import { shallow } from "enzyme";
import PersonLink from "../PersonLink";
import emojis from "../../utils/emojis";
const person = {
id: "123",
name: "Luke",
gender: "MALE"
};
describe("PersonLink component", () => {
it("should render proper link", () => {
const wrapper = shallow(<PersonLink person={person} />);
const link = wrapper.find("Link");
expect(link.prop("to")).toEqual(`/person/${person.id}`);
expect(link.prop("children")).toEqual(person.name);
});
it("should render proper gender emoji", () => {
const wrapper = shallow(<PersonLink person={person} />);
const emojiText = `${emojis.getByGender(person.gender)} `;
expect(wrapper.find(".person-link-emoji").text()).toEqual(emojiText);
});
});
<file_sep>/src/store/reducers/index.js
import { combineReducers } from "redux";
import visitedPersons from "./visitedPersons";
export default combineReducers({
visitedPersons
});
<file_sep>/README.md
# swapi-graphql-react-app
[](https://travis-ci.org/voronianski/swapi-graphql-react-app)
> Single-page app that allows to search for all human characters in Star Wars saga.
[<img src="https://graphcms.com/assets/cms/OG_Twitter-Blog-Swapi.png" alt="Powered by GraphCMS" width="450" />](https://graphiql.graphcms.com/simple/v1/swapi)
### [Demo](https://swapi-graphql-react-app.surge.sh)
## What's inside?
- [React v16](https://reactjs.org/)
- [React-router v4](https://reacttraining.com/react-router/)
- [Apollo-client v2](https://www.apollographql.com/docs/react/)
- [Redux v4](https://redux.js.org/)
- [Basscss v7](http://basscss.com/v7/)
## Development
This project was created with [create-react-app](https://facebook.github.io/create-react-app/docs/getting-started).
```bash
npm i
npm test
npm start
```
---
**MIT Licensed**
<file_sep>/src/utils/emojis.js
function getByGender(gender) {
if (gender === "MALE") {
return "💁♂️";
}
if (gender === "FEMALE") {
return "💁♀️";
}
}
export default {
getByGender
};
<file_sep>/src/utils/relatedPersons.spec.js
import relatedPersonsUtil from "./relatedPersons";
describe("relatedPersons util", () => {
it("should handle empty data", () => {
expect(relatedPersonsUtil()).toEqual([]);
});
it("should handle toPerson without films", () => {
const toPerson = { id: "1" };
const allPersons = [{ id: "2", films: [{ id: "10" }] }];
expect(relatedPersonsUtil(toPerson, allPersons)).toEqual([]);
});
it("should handle allPersons without films", () => {
const toPerson = { id: "1", films: [{ id: "10" }] };
const allPersons = [{ id: "2" }];
expect(relatedPersonsUtil(toPerson, allPersons)).toEqual([]);
});
it("should not return related without consecutive episodes in toPerson", () => {
const toPerson = {
id: "1",
films: [{ id: "10", episodeId: 1 }, { id: "12", episodeId: 3 }]
};
const allPersons = [
{
id: "2",
films: [{ id: "10", episodeId: 1 }, { id: "11", episodeId: 2 }]
},
{
id: "3",
films: [{ id: "11", episodeId: 2 }, { id: "12", episodeId: 3 }]
}
];
expect(relatedPersonsUtil(toPerson, allPersons)).toEqual([]);
});
it("should not return related without consecutive episodes in allPersons", () => {
const toPerson = {
id: "1",
films: [{ id: "10", episodeId: 1 }, { id: "11", episodeId: 2 }]
};
const allPersons = [
{
id: "2",
films: [{ id: "10", episodeId: 1 }, { id: "12", episodeId: 3 }]
},
{
id: "3",
films: [{ id: "11", episodeId: 2 }]
}
];
expect(relatedPersonsUtil(toPerson, allPersons)).toEqual([]);
});
it("should return related with only 2 consecutive episodes in toPerson", () => {
const toPerson = {
id: "1",
films: [{ id: "10", episodeId: 1 }, { id: "11", episodeId: 2 }]
};
const allPersons = [
{
id: "2",
films: [{ id: "10", episodeId: 1 }, { id: "11", episodeId: 2 }]
},
{
id: "3",
films: [{ id: "11", episodeId: 2 }, { id: "12", episodeId: 3 }]
}
];
expect(relatedPersonsUtil(toPerson, allPersons).length).toEqual(1);
});
it("should return related with all consecutive episodes in toPerson", () => {
const toPerson = {
id: "1",
films: [
{ id: "10", episodeId: 1 },
{ id: "11", episodeId: 2 },
{ id: "12", episodeId: 3 }
]
};
const allPersons = [
{
id: "2",
films: [{ id: "10", episodeId: 1 }, { id: "11", episodeId: 2 }]
},
{
id: "3",
films: [{ id: "11", episodeId: 2 }, { id: "12", episodeId: 3 }]
}
];
expect(relatedPersonsUtil(toPerson, allPersons).length).toEqual(2);
});
});
<file_sep>/src/components/__tests__/VisitedPersons.spec.js
import React from "react";
import { mount } from "enzyme";
import wait from "waait";
import { MemoryRouter } from "react-router-dom";
import { MockedProvider } from "react-apollo/test-utils";
import VisitedPersons, { VisitedPersonsQuery } from "../VisitedPersons";
const personIds = ["123", "456"];
const setup = mock => {
const mocks = mock ? [mock] : [];
const wrapper = mount(
<MockedProvider mocks={mocks} addTypename={false}>
<MemoryRouter>
<VisitedPersons ids={personIds} />
</MemoryRouter>
</MockedProvider>
);
return wrapper;
};
describe("VisitedPersons component", () => {
it("should render loading state", () => {
const wrapper = setup();
expect(wrapper.exists("Loading")).toEqual(true);
});
it("should render error state", async () => {
const wrapper = setup({
request: {
query: VisitedPersonsQuery,
variables: { personIds }
},
result: {
errors: [{ message: "Error!" }]
}
});
await wait(0);
wrapper.update();
expect(wrapper.exists("ErrorDetails")).toEqual(true);
});
it("should render empty state", async () => {
const wrapper = setup({
request: {
query: VisitedPersonsQuery,
variables: { personIds }
},
result: {
data: {
allPersons: []
}
}
});
await wait(0);
wrapper.update();
expect(wrapper.find(".visited-persons-empty").text()).toEqual(
"You did not visit any person yet..."
);
expect(wrapper.find(".visited-persons-link").length).toEqual(0);
});
it("should render success state", async () => {
const wrapper = setup({
request: {
query: VisitedPersonsQuery,
variables: { personIds }
},
result: {
data: {
allPersons: [
{
id: "123",
name: "Luke",
gender: "MALE"
},
{
id: "456",
name: "Leia",
gender: "FEMALE"
}
]
}
}
});
await wait(0);
wrapper.update();
expect(wrapper.exists(".visited-persons")).toEqual(true);
expect(wrapper.find(".visited-persons-link").length).toEqual(2);
});
});
<file_sep>/src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { ApolloClient } from "apollo-client";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloProvider } from "react-apollo";
import { Provider as ReduxProvider } from "react-redux";
import App from "./components/App";
import configureStore from "./store/configureStore";
import { populateVisitedPersons } from "./store/actions";
import sessionUtil from "./utils/session";
import "./styles.css";
const apolloClient = new ApolloClient({
link: new HttpLink({
uri: "https://api.graphcms.com/simple/v1/swapi"
}),
cache: new InMemoryCache()
});
const store = configureStore();
const savedPersonIds = sessionUtil.getPersonIds();
store.dispatch(populateVisitedPersons(savedPersonIds));
store.subscribe(() => {
const { visitedPersons } = store.getState();
sessionUtil.savePersonIds(visitedPersons);
});
ReactDOM.render(
<ApolloProvider client={apolloClient}>
<ReduxProvider store={store}>
<App />
</ReduxProvider>
</ApolloProvider>,
document.getElementById("root")
);
<file_sep>/src/store/actions/index.js
import { ADD_VISITED_PERSON, POPULATE_VISITED_PERSONS } from "./types";
export const addVisitedPerson = personId => ({
type: ADD_VISITED_PERSON,
id: personId
});
export const populateVisitedPersons = personIds => ({
type: POPULATE_VISITED_PERSONS,
ids: personIds
});
<file_sep>/src/components/PersonLink.js
import React from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import emojis from "../utils/emojis";
const PersonLink = ({ person }) => (
<div className="person-link bg-darken-1 relative py1 px2 mb2 rounded">
<span className="person-link-emoji">
{emojis.getByGender(person.gender)}{" "}
</span>
<Link to={`/person/${person.id}`} className="h5 caps bold purple">
{person.name}
</Link>
</div>
);
PersonLink.propTypes = {
person: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
gender: PropTypes.string.isRequired
})
};
export default PersonLink;
<file_sep>/src/store/actions/types.js
export const ADD_VISITED_PERSON = "ADD_VISITED_PERSON";
export const POPULATE_VISITED_PERSONS = "POPULATE_VISITED_PERSONS";
<file_sep>/src/components/ErrorDetails.js
import React from "react";
import PropTypes from "prop-types";
const ErrorDetails = ({ text }) => (
<div className="error-details center">
<img
src="https://media.giphy.com/media/l2JJnE17UfKTwCb3G/giphy.gif"
alt="crashing gif"
className="error-details-image rounded"
width="100%"
/>
<div className="error-details-text h5 mt1 bold red">{text}</div>
</div>
);
ErrorDetails.propTypes = {
text: PropTypes.string
};
ErrorDetails.defaultProps = {
text: "Error!"
};
export default ErrorDetails;
<file_sep>/src/components/Search.js
import React, { Component } from "react";
import { withApollo } from "react-apollo";
import gql from "graphql-tag";
import qs from "querystring";
import Title from "./Title";
import PersonLink from "./PersonLink";
import ErrorDetails from "./ErrorDetails";
export const SearchQuery = gql`
query SearchQuery($searchText: String!) {
allPersons(
filter: {
name_contains: $searchText
AND: { species_some: { name: "Human" } }
}
) {
id
name
gender
}
}
`;
class Search extends Component {
constructor(props) {
super();
this.state = {
searchText: this.urlQuery(props).text || "",
searchResults: [],
searching: false,
searchError: null
};
}
componentDidMount() {
this.executeSearch();
}
handleChange(event) {
this.setState({
searchText: event.target.value
});
}
handleSearch(event) {
event.preventDefault();
this.executeSearch();
}
handleClearSearch() {
this.setState({
searchText: "",
searchResults: []
});
this.props.history.push({
pathname: this.props.match.path
});
}
urlQuery(props) {
props = props || this.props;
if (!props.location) {
return {};
}
return qs.parse(props.location.search.slice(1));
}
async executeSearch() {
const { searchText, searching } = this.state;
if (!searchText || searching) {
return;
}
try {
this.setState({
searching: true,
searchError: null
});
const { data } = await this.props.client.query({
query: SearchQuery,
variables: { searchText }
});
this.setState({
searching: false,
searchResults: data.allPersons
});
this.props.history.push({
pathname: this.props.match.path,
search: `?text=${searchText}`
});
} catch (err) {
this.setState({
searching: false,
searchError: err
});
}
}
render() {
return (
<div className="search">
<Title text="Search" />
<form
className="search-form mt3 mb3"
onSubmit={event => this.handleSearch(event)}
>
<input
type="text"
name="searchText"
className="search-form-field field block col-12"
placeholder="🔎 Type any Star Wars human character name here..."
value={this.state.searchText}
onChange={event => this.handleChange(event)}
/>
<button
type="submit"
className="search-form-btn btn btn-primary mt2"
disabled={this.state.searching}
>
{this.state.searching ? "Searching..." : "Search"}
</button>
{this.state.searchText ? (
<button
type="button"
className="search-form-clear-btn btn btn-outline blue mt2 ml2"
onClick={() => this.handleClearSearch()}
disabled={this.state.searching}
>
Clear
</button>
) : null}
</form>
{this.state.searchError ? (
<ErrorDetails text="Oops! Something went wrong while searching for your query..." />
) : null}
{this.state.searchResults.length ? (
<div className="search-results">
{this.state.searchResults.map(person => (
<div key={person.id} className="search-results-link">
<PersonLink person={person} />
</div>
))}
</div>
) : null}
</div>
);
}
}
export default withApollo(Search);
<file_sep>/src/store/reducers/visitedPersons.spec.js
import visitedPersons from "./visitedPersons";
import * as types from "../actions/types";
describe("visitedPersons reducer", () => {
it("should handle initial state", () => {
expect(visitedPersons(undefined, {})).toEqual([]);
});
it("should handle ADD_VISITED_PERSON and add ids on top", () => {
expect(
visitedPersons([], {
type: types.ADD_VISITED_PERSON,
id: "123"
})
).toEqual(["123"]);
expect(
visitedPersons(["123"], {
type: types.ADD_VISITED_PERSON,
id: "456"
})
).toEqual(["456", "123"]);
expect(
visitedPersons(["456", "123"], {
type: types.ADD_VISITED_PERSON,
id: "123"
})
).toEqual(["123", "456"]);
});
it("should handle POPULATE_VISITED_PERSONS", () => {
expect(
visitedPersons([], {
type: types.POPULATE_VISITED_PERSONS,
ids: ["123", "456"]
})
).toEqual(["123", "456"]);
});
});
<file_sep>/src/store/configureStore.js
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import rootReducer from "./reducers";
export default function configureStore(preloadedState) {
const middlewares = [];
if (process.env.NODE_ENV !== "production") {
middlewares.push(logger);
}
const middlewareEnhancer = applyMiddleware(...middlewares);
const store = createStore(rootReducer, preloadedState, middlewareEnhancer);
return store;
}
| 364ccd00eb770d97a60c9d279b1f3ccf55cafeaa | [
"JavaScript",
"Markdown"
] | 21 | JavaScript | voronianski/swapi-graphql-react-app | 3556f700e43dc0960fa730442c25b7980f20929e | 795c33353edcfa85a5fae4d2018923daf131723d |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.javatechie.spring.ws.api.controller;
import com.javatechie.spring.ws.api.model.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;
/**
*
* @author Marin
*/
@Controller
public class ChatController {
@MessageMapping("/chat.register")
@SendTo("/topic/public")
public Message register(@Payload Message message,SimpMessageHeaderAccessor headerAccessor){
headerAccessor.getSessionAttributes().put("username", message.getSender());
return message;
}
@MessageMapping("/chat.send")
@SendTo("/topic/public")
public Message sendMessage(@Payload Message message ){
return message;
}
}
| 9f74759756aa63dc7fa2d1e8380574636db722c3 | [
"Java"
] | 1 | Java | mmikleusevic/Atos_zadaci | d5f4d18f0ec5b6e79186db60c46ca673c4498248 | d20b067a0235d39791e948d216ea2363498056c6 |
refs/heads/main | <file_sep>-- task4
SELECT
c.COMPANY_NAME,
s.SALES_DATE,
p.PRODUCT_NAME,
p.product_code,
sum(s.volume) as sum_volume
FROM sales s
INNER JOIN company AS c ON c.company_number == s.COMPANY_CODE
INNER JOIN (
SELECT
sum(s.VOLUME) as sum_vol,
p.PRODUCT_CODE as product_code,
p.product_name as product_name
From products p
LEFT JOIN sales as s on s.product_code == p.product_code
) AS p ON s.product_code == p.product_code
where p.sum_vol != 0<file_sep># KBC
sqlite tasks
<file_sep>-- task2
SELECT
c.company_number,
c.company_name,
p.product_code,
CASE
WHEN (SELECT COUNT(*) from sales where product_code = p.product_code) = 0 THEN "No sells"
WHEN (SELECT SUM(volume) from sales where product_code = p.product_code) <= 4000 THEN "Lows sells"
WHEN (SELECT SUM(volume) from sales where product_code = p.product_code) BETWEEN 4001 and 200000 THEN "Medium sells"
WHEN (SELECT SUM(volume) from sales where product_code = p.product_code) > 200000 THEN "Hign sells"
END as sells
from company c
INNER JOIN bridge as b ON b.company_code == c.company_number
INNER JOIN products AS p ON p.product_code == b.product_code
WHERE
(p.END_DATE is NULL AND b.END_DATE is NULL) OR
(p.END_DATE > Date() and b.END_DATE > Date())<file_sep>-- task 1
SELECT DISTINCT
c.company_name,
c.company_number,
p.product_code
FROM company c
INNER JOIN bridge AS b ON b.company_code == c.company_number
INNER JOIN products AS p ON p.product_code == b.product_code
WHERE
p.end_date is NULL OR p.end_date > DATE()
ORDER BY company_name;<file_sep>--task 5
SELECT
CAST((select SUM(volume) from sales WHERE currency = "EUR") as FLOAT) / CAST(SUM(s.volume) as FLOAT) * 100
FROM sales s
| 78b4523c4f2b12b547feb7ff234483cedc1fd83e | [
"Markdown",
"SQL"
] | 5 | SQL | LeonPCZ/KBC | d373a8771eac1d12828d2feb5c1302e74256d31f | 6efb7644a174b5b2b6d6101524870ba10dac1d35 |
refs/heads/master | <repo_name>aburd/issues-tracker<file_sep>/src/layouts/PageLayout/PageLayout.js
import React from 'react'
import PropTypes from 'prop-types'
import { IndexLink } from 'react-router'
import './PageLayout.scss'
import { SETTINGS } from '../../config'
export const PageLayout = ({ children }) => (
<div className='container text-center'>
<IndexLink to='/' activeClassName='page-layout__nav-item--active'>
<h1>{SETTINGS.title}</h1>
</IndexLink>
<div className='page-layout__viewport'>
{children}
</div>
</div>
)
PageLayout.propTypes = {
children: PropTypes.node,
}
export default PageLayout
<file_sep>/src/routes/404/components/404.js
import React from 'react'
import { Link } from 'react-router'
import komaruNeko from '../assets/neko.jpg'
export const FourZeroFour = () => (
<div>
<h1>404</h1>
<h3>あれ?そのページが見つかりませんでしたね、、</h3>
<img src={komaruNeko} /> <br />
<Link to='/'>ホームに戻る</Link>
</div>
)
export default FourZeroFour
<file_sep>/src/routes/Issues/containers/IssuesContainer.js
import { connect } from 'react-redux'
import {
getIssues,
issuesClear,
setRepo,
setEndpoint,
setCurrentIssue
} from '../modules/issues'
/* This is a container component. Notice it does not contain any JSX,
nor does it import React. This component is **only** responsible for
wiring in the actions and state necessary to render a presentational
component - in this case, the issues: */
import Issues from '../components/Issues'
/* Object of action creators (can also be function that returns object).
Keys will be passed as props to presentational components. Here we are
implementing our wrapper around increment; the component doesn't care */
const mapDispatchToProps = {
setRepo : (repo) => setRepo(repo),
setEndpoint : (endpoint) => setEndpoint(endpoint),
setCurrentIssue : (issueNumber) => setCurrentIssue(issueNumber),
getIssues : (url) => getIssues(url),
issuesClear : () => issuesClear()
}
const mapStateToProps = (state) => ({
loading : state.issues.loading,
page : state.issues.page,
data : state.issues.data,
paginationLinks : state.issues.paginationLinks,
repo : state.issues.repo,
endpoint : state.issues.endpoint
})
/* Note: mapStateToProps is where you should use `reselect` to create selectors, ie:
import { createSelector } from 'reselect'
const issues = (state) => state.issues
const tripleCount = createSelector(issues, (count) => count * 3)
const mapStateToProps = (state) => ({
issues: tripleCount(state)
})
Selectors can compute derived data, allowing Redux to store the minimal possible state.
Selectors are efficient. A selector is not recomputed unless one of its arguments change.
Selectors are composable. They can be used as input to other selectors.
https://github.com/reactjs/reselect */
export default connect(mapStateToProps, mapDispatchToProps)(Issues)
<file_sep>/src/routes/404/modules/Issue.js
import Request from 'superagent'
// ------------------------------------
// Constants
// ------------------------------------
export const SET_LOADING = 'SET_LOADING'
export const ISSUES_SET = 'ISSUES_SET'
export const ISSUES_CHANGE_PAGE = 'ISSUES_CHANGE_PAGE'
export const ISSUES_CLEAR = 'ISSUES_CLEAR'
// ------------------------------------
// Actions
// ------------------------------------
export function changePage (value = 1) {
return {
type : ISSUES_CHANGE_PAGE,
payload : value
}
}
export function issuesClear () {
return {
type : ISSUES_CLEAR
}
}
/* This is a thunk, meaning it is a function that immediately
returns a function for lazy evaluation. It is incredibly useful for
creating async actions, especially when combined with redux-thunk! */
export const getInitialIssues = (url) => {
return (dispatch, getState) => {
dispatch({
type : SET_LOADING,
payload : true
})
return Request
.get(url)
.end((err, res) => {
if (err) {
throw new Error('An error occured loading the REST API:', err)
} else {
dispatch({
type : 'ISSUES_SET',
payload : res.body
})
dispatch({
type : SET_LOADING,
payload : false
})
}
})
}
}
export const actions = {
changePage,
getInitialIssues
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[SET_LOADING] : (state, action) => {
return Object.assign({}, state, {
loading: action.payload
})
},
[ISSUES_CHANGE_PAGE] : (state, action) => {
return Object.assign({}, state, {
page: action.payload
})
},
[ISSUES_SET] : (state, action) => {
return Object.assign({}, state, {
data: action.payload
})
},
[ISSUES_CLEAR] : (state, action) => {
return Object.assign({}, state, {
data: []
})
}
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
loading: false,
page: 0,
data: []
}
export default function issuesReducer (state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
<file_sep>/src/routes/Issues/components/PaginationBar/index.js
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import { Pagination, PaginationItem } from 'reactstrap'
import './PaginationBar.scss'
const makePaginationBar = (props) => {
// console.log('makePaginationBar running...')
// console.log('Location:', props.location)
const { currentPage, location, setEndpoint, paginationLinks } = props
const getPrev = (currentPage) => {
const pageNumber = parseInt(currentPage)
const newPage = parseInt(pageNumber - 1)
return (newPage < 1)
? 1
: newPage
}
const getNext = (currentPage) => {
const pageNumber = parseInt(currentPage)
const newPage = parseInt(pageNumber + 1)
return (newPage > 100)
? 1
: newPage
}
const handlePaginationClick = (newEndpoint) => () => {
setEndpoint(newEndpoint)
}
return (
<Pagination>
{paginationLinks.first &&
<PaginationItem>
<Link
className='page-link'
to={{ pathname: location.pathname, query: { page: 1 } }}
onClick={handlePaginationClick(paginationLinks.first)}
>
<span aria-hidden='true'>«</span>
</Link>
</PaginationItem>
}
{paginationLinks.prev &&
<PaginationItem>
<Link
className='page-link'
to={{ pathname: location.pathname, query: { page: getPrev(currentPage) } }}
onClick={handlePaginationClick(paginationLinks.prev)}
>
Prev
</Link>
</PaginationItem>
}
{paginationLinks.next &&
<PaginationItem>
<Link
className='page-link'
to={{ pathname: location.pathname, query: { page: getNext(currentPage) } }}
onClick={handlePaginationClick(paginationLinks.next)}
>
Next
</Link>
</PaginationItem>
}
{paginationLinks.last &&
<PaginationItem>
<Link
className='page-link'
to={{ pathname: location.pathname, query: { page: parseInt(paginationLinks.last.match(/page=(\d+)/)[1]) } }}
onClick={handlePaginationClick(paginationLinks.last)}
>
<span aria-hidden='true'>»</span>
</Link>
</PaginationItem>
}
</Pagination>
)
}
export const PaginationBar = (props) => {
console.log(props.location)
if (props.location === undefined) {
return null
} else {
return makePaginationBar(props)
}
}
makePaginationBar.propTypes = {
currentPage: PropTypes.number,
location: PropTypes.object,
setEndpoint: PropTypes.func,
paginationLinks: PropTypes.object
}
export default PaginationBar
<file_sep>/src/routes/Issue/components/Issue.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { browserHistory } from 'react-router'
import { Container, Row, Col, Badge, Button } from 'reactstrap'
import ReactMarkdown from 'react-markdown'
import moment from 'moment'
import URL from 'url-parse'
import Loader from '../../../components/Loader'
import { SETTINGS as settings, REPOS as repos } from '../../../config.js'
import './Issue.scss'
class Issue extends Component {
constructor (props) {
super(props)
this.state = {}
}
componentWillMount () {
/*
Get and Set Initial data for any future usage in the component
*/
const { setRepo, getIssue, setEndpoint, location } = this.props
const currentRepo = repos[this.props.params.name]
if (currentRepo !== {} && currentRepo !== undefined) {
const pathnameParts = location.pathname.split('/')
const issueNumber = pathnameParts[pathnameParts.length - 1]
setRepo(currentRepo)
// Set state for endpoint
const endpoint = new URL(`${settings.apiBase}/repos/${currentRepo.url}/issues/${issueNumber}`, true)
setEndpoint(endpoint)
// Use endpoint to get data from GithubAPI
getIssue(endpoint.href)
}
}
componentWillUpdate (newProps, props) {
// Compare the changes in location to prevent infinite rerendering
if (this.props.location !== newProps.location) {
this.props.getIssue(newProps.endpoint.href)
}
}
componentWillUnmount () {
this.props.issueClear()
}
render () {
const { loading, data } = this.props
const renderIssue = (loading, data) => {
const {
title,
user,
body,
created_at,
number
} = data
const createdAt = moment(created_at)
if (loading || !title) {
return <Loader />
} else {
return (
<Container className='issue-detail'>
<Row>
<Col>
<div className="button-container text-right">
<Button size='sm' onClick={browserHistory.goBack} color='secondary' outline>
Go back
</Button>
</div>
</Col>
</Row>
<Row>
<Col>
<div className='title'>
<h5>{title} <Badge>#{number}</Badge></h5>
</div>
</Col>
</Row>
<Row>
<Col>
<div className='block-title'>
<div className='avatar'>
<a href={user.url}>
<img
src={user.avatar_url}
alt={`${user.login}'s github avatar'`}
/>
</a>
</div>
<div className='time'>
<strong>{user.login}</strong> opened this issue ({createdAt.fromNow()})
</div>
</div>
</Col>
</Row>
<Row>
<Col>
<ReactMarkdown
className='body text-left'
source={body !== '' ? body : '*No description given*'}
/>
</Col>
</Row>
<Row>
<Col>
<div className="button-container text-center">
<Button onClick={browserHistory.goBack} color='secondary' outline>
Go back
</Button>
</div>
</Col>
</Row>
</Container>
)
}
}
return (
<div>
{renderIssue(loading, data)}
</div>
)
}
}
Issue.propTypes = {
loading: PropTypes.bool,
location: PropTypes.object,
getIssue: PropTypes.func,
setRepo: PropTypes.func,
setEndpoint: PropTypes.func,
issueClear: PropTypes.func,
data: PropTypes.object,
params: PropTypes.shape({
name: PropTypes.string,
number: PropTypes.string
})
// issuesEndpoint: PropTypes.object
}
export default Issue
<file_sep>/src/components/RepoLinks/index.js
import React from 'react'
import { Link } from 'react-router'
import { REPOS } from '../../config'
import './RepoLinks.scss'
const makeIssueLinks = () => {
return Object.keys(REPOS).map((repoName, i) => {
const repo = REPOS[repoName]
return (
<Link
key={`repo$-${repo.name}-${i}`}
to={`/issues/${repoName}`}
className='list-group-item repo-link'
activeClassName='route--active'
>
{repo.name}
</Link>
)
})
}
export default () => {
return (
<div className='list-group'>
{makeIssueLinks()}
</div>
)
}
<file_sep>/src/config.js
export const SETTINGS = {
title: 'Github Issues Tracker',
apiBase: 'https://api.github.com'
}
export const REPOS = {
protractor: {
url: 'angular/protractor',
name: 'Angular-Protractor'
},
'react-redux-starter-kit': {
url: 'davezuko/react-redux-starter-kit',
name: 'React-Redux-Starter-Kit'
},
'brave' : {
url: 'brave/browser-laptop',
name: 'Brave Browser'
},
'atom': {
url: 'atom/atom',
name: 'Atom'
}
}
<file_sep>/src/routes/Issues/components/Issues.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import URL from 'url-parse'
import Loader from '../../../components/Loader'
import IssueListItem from './IssueListItem'
import PaginationBar from './PaginationBar'
import { Container, Row, Col } from 'reactstrap'
import { SETTINGS as settings, REPOS as repos } from '../../../config.js'
class Issues extends Component {
constructor (props) {
super(props)
this.state = {}
}
componentWillMount () {
/*
Get and Set Initial data for any future usage in the component
*/
const { setRepo, getIssues, setEndpoint, location } = this.props
const currentRepo = repos[this.props.params.name]
if (currentRepo !== {} && currentRepo !== undefined) {
setRepo(currentRepo)
// Set state for endpoint
const endpoint = new URL(`${settings.apiBase}/repos/${currentRepo.url}/issues`, true)
endpoint.query['page'] = location.query.page || 1
endpoint.query['per_page'] = 10
setEndpoint(endpoint)
// Use endpoint to get data from GithubAPI
getIssues(endpoint.toString())
}
}
componentWillUpdate (newProps, props) {
// Compare the changes in location to prevent infinite rerendering
if (this.props.location !== newProps.location) {
this.props.getIssues(newProps.endpoint.toString())
}
}
componentWillUnmount () {
this.props.issuesClear()
}
render () {
console.log('render called')
const {
loading,
repo,
location,
data,
setEndpoint,
paginationLinks,
setCurrentIssue
} = this.props
const renderIssues = () => {
if (loading) {
return <Loader />
} else {
const currentPage = location.query.page || 1
return (
<div>
<Container>
<Row>
<Col><h3>{repo.name}</h3></Col>
</Row>
<Row>
<Col>
<PaginationBar
currentPage={currentPage}
location={location}
setEndpoint={setEndpoint}
paginationLinks={paginationLinks}
/>
</Col>
</Row>
<Row>
<Col>
<ul id='issues-list' className='list-group text-left'>
{data.map((issue, i) => (
<IssueListItem
key={'Issue-' + i}
pathname={location.pathname}
issue={issue}
setCurrentIssue={setCurrentIssue}
/>
))}
</ul>
</Col>
</Row>
<Row>
<Col>
<PaginationBar
currentPage={currentPage}
location={location}
setEndpoint={setEndpoint}
paginationLinks={paginationLinks}
/>
</Col>
</Row>
</Container>
</div>
)
}
}
return (
<div>
{renderIssues()}
</div>
)
}
}
Issues.propTypes = {
loading: PropTypes.bool,
repo: PropTypes.object,
location: PropTypes.object,
params: PropTypes.object,
paginationLinks: PropTypes.object,
setRepo: PropTypes.func,
setEndpoint: PropTypes.func,
setCurrentIssue: PropTypes.func,
getIssues: PropTypes.func,
issuesClear: PropTypes.func,
data: PropTypes.array
}
export default Issues
| 8b9cc08311d23f8c8f0ff03e4be92bf1bf7406df | [
"JavaScript"
] | 9 | JavaScript | aburd/issues-tracker | 04c2b3f67fd46a8fcb0ca17c7e0fc3f6d8c73be1 | d540121a336c0138b3cc5aedd0875914cb4a8b72 |
refs/heads/main | <repo_name>jungseokhong/nano-network-setup<file_sep>/rc.local
#!/bin/sh -e
sh -c 'echo 255 > /sys/devices/pwm-fan/target_pwm'
exit 0
<file_sep>/README.md
# nano-network-setup
## create hotspot so we can connect via wifi to he nano
/etc/NetworkManager/system-connections/Hotspot
## create host nicknam
/etc/host
## to turn nano fan on boot
/etc/rc.local
| 2b0bbffbc84a86b1baaaf4eba8cc7e8476710592 | [
"Markdown",
"Shell"
] | 2 | Shell | jungseokhong/nano-network-setup | dd8d33372b6b22631d099a32e6c1170ea97a28ed | c63353e41e4314ce0973b397cdd8d586d92bb672 |
refs/heads/master | <repo_name>zCoLtX45z/Capstone_PPP<file_sep>/CapstonePowerPlay/Assets/Scripts/PingServer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PingServer : NetworkBehaviour {
void Start () {
if(isLocalPlayer)
InvokeRepeating("CmdPingFunction", 10, 30);
}
[Command]
private void CmdPingFunction()
{
Debug.Log("Called Ping");
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Photon/InLobby.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class InLobby : MonoBehaviour {
[SerializeField]
private GameObject NextCanvas;
private bool Search = false;
// Update is called once per frame
void Update () {
if (Search && !NextCanvas.activeSelf)
{
if (PhotonNetwork.IsConnectedAndReady && PhotonNetwork.InLobby)
{
NextCanvas.SetActive(true);
Search = false;
}
}
}
public void GetReady()
{
Search = true;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerInGameMusic.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInGameMusic : MonoBehaviour {
private PlayerSoundSettings PS;
private AudioSource Src;
public float MusicVol;
// Use this for initialization
void Start () {
Src = GetComponent<AudioSource>();
PS = FindObjectOfType<PlayerSoundSettings>();
if (PS)
MusicVol = PS.musicVol;
else
MusicVol = 0.1f;
}
// Update is called once per frame
void Update () {
Src.volume = MusicVol;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/InGameSoundSettings.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InGameSoundSettings : MonoBehaviour {
public float musicVol;
public float SoundFXVol;
public float VoiceVol;
public Slider musicSlider;
public Slider SoundFXSlider;
public Slider voiceSlider;
private PlayerSoundSettings PS;
private PlayerInGameMusic PGM;
private HoverBoardSounds HV;
private BallSoundManager BS;
private DietySound DS;
private PlayerVoiceLine PV;
// Use this for initialization
void Start()
{
PS = FindObjectOfType<PlayerSoundSettings>();
PGM = FindObjectOfType<PlayerInGameMusic>();
HV = FindObjectOfType<HoverBoardSounds>();
BS = FindObjectOfType<BallSoundManager>();
DS = FindObjectOfType<DietySound>();
PV = FindObjectOfType<PlayerVoiceLine>();
musicVol = PS.musicVol;
musicSlider.value = musicVol;
SoundFXVol = PS.SoundFXVol;
SoundFXSlider.value = SoundFXVol;
VoiceVol = PS.VoiceVol;
voiceSlider.value = VoiceVol;
}
// Update is called once per frame
void Update()
{
if (musicSlider != null)
{
musicVol = musicSlider.value;
PGM.MusicVol = musicVol;
}
if (SoundFXSlider != null)
{
SoundFXVol = SoundFXSlider.value;
HV.HovVol = SoundFXVol;
BS.bounceVol = SoundFXVol;
}
if (voiceSlider != null)
{
VoiceVol = voiceSlider.value;
DS.dietyVol = VoiceVol;
PV.voiceVol = VoiceVol;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ShieldCollision.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShieldCollision : MonoBehaviour {
[SerializeField]
private Shove PlayerShove;
public Shove GetPlayer()
{
return PlayerShove;
}
void OnCollisionEnter(Collision c)
{
Debug.Log("collided with: " + c.gameObject.name + " " + "tag: " + c.gameObject.tag);
if (c.gameObject.tag == "Shield")
{
Debug.Log(c.gameObject.name + " has tag Shield");
Vector3 dir = c.gameObject.transform.position - gameObject.transform.position;
PlayerShove.CollideWithPlayer(c.gameObject.GetComponent<ShieldCollision>().GetPlayer(), dir);
}
else if (c.gameObject.tag == "Team 1" || c.gameObject.tag == "Team 2")
{
Debug.Log(c.gameObject.name + " has tag Player");
Vector3 dir = c.gameObject.transform.position - gameObject.transform.position;
PlayerShove.ShovePlayer(c.gameObject.GetComponent<Shove>(), dir);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/SmoothHoverSelectorUITransition.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SmoothHoverSelectorUITransition : MonoBehaviour {
//[SerializeField]
//private RectTransform start;
//[SerializeField]
//private RectTransform settings;
[SerializeField]
private RectTransform[] buttonGroup;
[SerializeField]
private RectTransform selectedRect;
private Transform target;
[SerializeField]
private float acceleration;
public bool allow = false;
private bool set;
public void SwitchSelected(Transform button)
{
target = button;
}
private void FixedUpdate()
{
if(target != null)
selectedRect.localPosition += new Vector3(0, (target.localPosition.y - selectedRect.localPosition.y) / acceleration, 0);
}
//public void MovePosition(bool up)
//{
// if (!allow)
// allow = !allow;
// set = up;
//}
//private void FixedUpdate()
//{
// if (allow)
// {
// if (set)
// {
// //Debug.Log("ON START");
// selectedRect.localPosition += new Vector3(0, (start.localPosition.y - selectedRect.localPosition.y) / acceleration, 0);
// }
// else
// {
// //Debug.Log("ON Settings");
// selectedRect.localPosition += new Vector3(0, (settings.localPosition.y - selectedRect.localPosition.y) / acceleration, 0);
// }
// }
//}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerCamera180LockScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class PlayerCamera180LockScript : MonoBehaviour
{
private Cinemachine.CinemachineFreeLook playerVirtualCamera;
// Use this for initialization
void Start()
{
playerVirtualCamera = transform.GetComponent<Cinemachine.CinemachineFreeLook>();
}
// Update is called once per frame
void Update()
{
//if ((player))
if (playerVirtualCamera.m_XAxis.Value >= 90 && playerVirtualCamera.m_XAxis.Value <= 270)
{
if (playerVirtualCamera.m_XAxis.Value >= 90 && playerVirtualCamera.m_XAxis.Value < 181)
{
//90
playerVirtualCamera.m_XAxis.Value = 90.0f;
}
else if (playerVirtualCamera.m_XAxis.Value <= 270 && playerVirtualCamera.m_XAxis.Value > 179)
{
// 270
playerVirtualCamera.m_XAxis.Value = 270.0f;
// Debug.Log("Entered2");
}
}
////////////////////////////////////////////////////////
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/BallSoundManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallSoundManager : MonoBehaviour {
private AudioSource audioSrc;
public AudioClip bounce;
public float bounceVol;
private PlayerSoundSettings PS;
//private float minVol = 0.2f;
//private float maxVol = 1f;
// Use this for initialization
void Start () {
PS = FindObjectOfType<PlayerSoundSettings>();
audioSrc = GetComponent<AudioSource>();
if (PS)
bounceVol = PS.SoundFXVol;
else
audioSrc.volume = 0.1f;
}
// Update is called once per frame
void Update () {
audioSrc.volume = bounceVol;
}
private void OnCollisionEnter(Collision coll)
{
//float vol = Random.Range(minVol, maxVol);
audioSrc.PlayOneShot(bounce, bounceVol);
}
}
<file_sep>/CapstonePowerPlay/Assets/SpeedStrip.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedStrip : MonoBehaviour
{
[SerializeField]
private float LifeTime = 7.0f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/ChangeTags.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeTags : MonoBehaviour {
[SerializeField]
private List<GameObject> ChangeTagList = new List<GameObject>();
public void ChangeObjectTags(string tag)
{
foreach (GameObject g in ChangeTagList)
{
g.tag = tag;
}
}
public void ChangeObjectTags(List<GameObject> gameObjectList ,string tag)
{
foreach (GameObject g in gameObjectList)
{
g.tag = tag;
}
}
public void ChangeObjectTags(GameObject[] gameObjectArray, string tag)
{
foreach (GameObject g in gameObjectArray)
{
g.tag = tag;
}
}
public void ChangeObjectTags(GameObject g, string tag)
{
g.tag = tag;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/NetPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
public class NetPlayer : MonoBehaviour {
// Player Components
[SerializeField]
private Chat ChatSystem;
[SerializeField]
private PhotonView PV;
// Spawninng Player Object
[SerializeField]
private GameObject PlayerObject;
// Player Team
private int TeamNum = 0;
// Player and Other Player
// [HideInInspector]
public NetPlayer LocalPlayer;
[HideInInspector]
public NetPlayer[] PlayerList = null;
// Team Select Canvas
[SerializeField]
private Canvas StartingCanvas;
[SerializeField]
private Canvas LoadingCanvas;
[SerializeField]
private InGameMenu ArenaMenu;
[HideInInspector]
public bool ConfirmTeam = false;
// Player Indetifiers
//[HideInInspector]
public string CodeNumbers = "";
public string DisplayName = "";
public string PlayerCode = "";
// Player Child Components
private hoverBoardScript HBS;
private BallHandling BH;
public GameObject ChildPlayer;
private PlayerColor PC;
[HideInInspector]
public bool ReadyToSetPlayer = false;
private bool SetPlayerBool = false;
private bool SetUpThePlayers = false;
private bool PC_SetLocalSent = false;
// Variables
private bool SkipTeamSelect = false;
private bool LoadingScreenOn = true;
// Player Spawn Points
private GameSetup GS;
private Transform SpawnPoint;
[SerializeField]
private CameraRotation cRotScript = null;
[SerializeField]
private CameraModeMedium cmm;
private BallSteal BS;
// Use this for initialization
void Start ()
{
GS = FindObjectOfType<GameSetup>();
if (!PV)
PV = GetComponent<PhotonView>();
if (PV.IsMine)
{
DisplayName = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
PV.RPC("RPC_UpdateDisplayName", RpcTarget.AllBuffered, DisplayName);
gameObject.name = PhotonNetwork.LocalPlayer.NickName;
CodeNumbers = "#" + gameObject.name.Split('#')[1];
PV.RPC("RPC_UpdateCode", RpcTarget.AllBuffered, CodeNumbers);
PV.RPC("RPC_ChangeName", RpcTarget.All, gameObject.name, CodeNumbers);
}
PlayerCode = gameObject.name.Split('#')[0] + CodeNumbers;
if (PV.IsMine)
{
SetPlayerList();
if ((int)PhotonNetwork.LocalPlayer.CustomProperties["Team"] != -1)
{
TeamNum = (int)PhotonNetwork.LocalPlayer.CustomProperties["Team"];
UpdateTeamNum(TeamNum);
SkipTeamSelect = true;
}
else
StartingCanvas.gameObject.SetActive(true);
}
else
{
StartingCanvas.gameObject.SetActive(false);
LoadingCanvas.gameObject.SetActive(false);
}
}
// Update is called once per frame
void Update()
{
if (PV.IsMine)
{
if (SkipTeamSelect)
{
//p.CmdChangeName(p.gameObject.name, p.CodeNumbers);
//PV.RPC("RPC_ChangeName", RpcTarget.All, gameObject.name, CodeNumbers);
// Set player Team
TeamNum = (int)PhotonNetwork.LocalPlayer.CustomProperties["Team"];
// Spawn player character
//Debug.Log("Spawning player Skip");
SkipTeamSelect = false;
StartingCanvas.gameObject.SetActive(false);
SpawnPlayer();
}
//Debug.Log(" IT IS MINE");
else if (StartingCanvas.gameObject.activeSelf)
{
if (PlayerList == null)
SetPlayerList();
//if (PhotonNetwork.IsMasterClient)
//{
// foreach (NetPlayer p in PlayerList)
// {
// p.CmdChangeName(p.gameObject.name, p.CodeNumbers);
// p.PV.RPC("RPC_ChangeName", RpcTarget.All, p.gameObject.name, p.CodeNumbers);
// }
//}
if (PV.IsMine)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
if (ConfirmTeam)
{
if (TeamNum == 0)
{
ConfirmTeam = false;
}
else
{
UpdateTeamNum(TeamNum);
StartingCanvas.gameObject.SetActive(false);
//CmdSpawnPlayer();
Debug.Log("Spawning player Starting Canvas");
//PV.RPC("RPC_SpawnPlayer", RpcTarget.All);
SpawnPlayer();
}
}
}
}
else if (!SetPlayerBool)
{
SetPlayerList();
if (!SetUpThePlayers)
{
if (PhotonNetwork.CurrentRoom.PlayerCount == PlayerList.Length)
{
SetUpThePlayers = true;
foreach (NetPlayer NP in PlayerList)
{
if (!NP.ReadyToSetPlayer)
{
SetUpThePlayers = false;
break;
}
}
}
//else
//{
// Debug.Log("Current Players: " + PhotonNetwork.CurrentRoom.PlayerCount + ", Current Net Players: " + PlayerList.Length);
//}
}
if (SetUpThePlayers)
{
// Set Local Player for everyone
if (!PC_SetLocalSent)
{
//Debug.Log("Set Player Child Player");
PC_SetLocalSent = true;
PC.SetUpPlayer(this);
}
PlayerColor[] PlayerColorList = FindObjectsOfType<PlayerColor>();
if (PhotonNetwork.CurrentRoom.PlayerCount == PlayerColorList.Length)
{
//Debug.Log("Final Set Players Check");
bool FinalSetPlayers = true;
foreach (PlayerColor P in PlayerColorList)
{
P.LocalPlayer = this;
if (!P.PlayerLocalSet)
{
FinalSetPlayers = false;
break;
}
}
if (FinalSetPlayers)
{
//Debug.Log("Final Set Players Do");
PC.FinalPlayerSet(PV.ViewID, DisplayName);
SetPlayerBool = true;
foreach (PlayerColor P in PlayerColorList)
{
P.SetTeamNum(P.TeamNum);
}
}
}
else
{
Debug.Log("Current Players: " + PhotonNetwork.CurrentRoom.PlayerCount + ", Current PlayerColor Players: " + PlayerList.Length);
}
}
}
else if (LoadingScreenOn)
{
// In case GS wasn't grabbed by this point
if (!GS)
GS = FindObjectOfType<GameSetup>();
SpawnPoint = GS.GrabSpawnPoint(PV.ViewID);
if (SpawnPoint != null)
{
ChildPlayer.transform.position = SpawnPoint.position;
ChildPlayer.transform.rotation = SpawnPoint.rotation;
LoadingScreenOn = false;
LoadingCanvas.gameObject.SetActive(false);
//if (TeamNum == 1)
// Debug.Log("Spawn Point Selected(Team 1): " + SpawnPoint.name);
//else if (TeamNum == 2)
// Debug.Log("Spawn Point Selected(Team 2): " + SpawnPoint.name);
}
// spawn ball
FindObjectOfType<ballHandler>().SpawnBall();
}
else if (ArenaMenu.gameObject.activeSelf)
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
if (HBS != null)
{
HBS.BoardHasControl = false;
}
if(cmm != null)
cmm.changeIsAllowed = false;
if (cmm != null)
cmm.changeIsAllowed = false;
if (cRotScript != null)
cRotScript.allow = false;
else
PV.RPC("RPC_GetPlayerComponents", RpcTarget.AllBuffered);
if(BH != null)
{
if(!BH.isPaused)
BH.isPaused = true;
}
if (BS != null)
{
if (!BS.isPaused)
BS.isPaused = true;
}
if (Input.GetKeyDown(KeyCode.Escape))
{
ArenaMenu.gameObject.SetActive(false);
}
}
else
{
if (PV.IsMine)
{
if (BH != null)
{
if(BH.isPaused)
BH.isPaused = false;
}
if (BS != null)
{
if (BS.isPaused)
BS.isPaused = false;
}
if (!PC.SetPlayerTag)
{
PC.ResetPNT();
}
// Turn Loading Screen Off
if (LoadingCanvas.gameObject.activeSelf)
LoadingCanvas.gameObject.SetActive(false);
if (Input.GetKeyDown(KeyCode.T) || Input.GetKeyDown(KeyCode.RightShift))
{
if (!ChatSystem.GetEnabled())
ChatSystem.ToggleChat();
}
if (ChatSystem.GetEnabled() && HBS != null)
{
HBS.BoardHasControl = false;
}
else if (!ChatSystem.GetEnabled() && HBS != null)
{
HBS.BoardHasControl = true;
}
if (!ChatSystem.GetEnabled() && Input.GetKeyDown(KeyCode.Escape))
{
ArenaMenu.gameObject.SetActive(true);
}
// If the curser should be active or not
if (ChatSystem.GetEnabled())
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
if (cmm != null)
cmm.changeIsAllowed = false;
if (cRotScript != null)
cRotScript.allow = false;
else
PV.RPC("RPC_GetPlayerComponents", RpcTarget.AllBuffered);
}
else
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
if (cmm != null)
cmm.changeIsAllowed = true;
if (cRotScript != null)
{
if (cmm.isFreeCam == true)
cRotScript.allow = true;
}
else
PV.RPC("RPC_GetPlayerComponents", RpcTarget.AllBuffered); ;
}
}
}
}
}
[PunRPC]
public void RPC_UpdateDisplayName(string name)
{
DisplayName = name;
}
[PunRPC]
private void RPC_GetPlayerComponents()
{
BH = ChildPlayer.GetComponent<BallHandling>();
BS = ChildPlayer.GetComponent<BallSteal>();
HBS = ChildPlayer.GetComponent<hoverBoardScript>();
PC = ChildPlayer.GetComponent<PlayerColor>();
ChildPlayer.transform.SetParent(this.transform);
cRotScript = ChildPlayer.GetComponentInChildren<CameraRotation>();
cmm = ChildPlayer.GetComponentInChildren<CameraModeMedium>();
}
[PunRPC]
public void RPC_UpdateCode(string code)
{
CodeNumbers = code;
}
[PunRPC]
public void RPC_UpdateTeamNum(int i)
{
TeamNum = i;
}
public void UpdateTeamNum(int i)
{
PV.RPC("RPC_UpdateTeamNum", RpcTarget.AllBuffered, i);
}
//[PunRPC]
public void SpawnPlayer()
{
SetPlayerList();
int spawnPicker = Random.Range(0, GameSetup.GS.playerSpawns.Length);
ChildPlayer = PhotonNetwork.Instantiate("PhotonPlayer", GameSetup.GS.playerSpawns[spawnPicker].transform.position, GameSetup.GS.playerSpawns[spawnPicker].transform.rotation);
ChildPlayer.transform.SetParent(transform);
ChildPlayer.name = PlayerCode;
//NetworkServer.SpawnWithClientAuthority(GO, connectionToClient);
if (ChildPlayer != null)
{
//ParentChild(GO);
//Debug.Log("GO != null");
PV.RPC("RPC_ParentChild", RpcTarget.All, ChildPlayer.GetPhotonView().ViewID, PV.ViewID);
ReadyToSetPlayer = true;
//PV.RPC("RPC_UpdateReady", RpcTarget.AllBuffered, ReadyToSetPlayer);
// Set Components
PV.RPC("RPC_GetPlayerComponents", RpcTarget.AllBuffered);
}
}
[PunRPC]
private void RPC_UpdateReady(bool ready)
{
ReadyToSetPlayer = ready;
}
private void SetPlayer(GameObject spawningObject)
{
Debug.Log("setting up player");
PlayerColor PC = spawningObject.GetComponent<PlayerColor>();
PC.LocalPlayer = LocalPlayer;
PC.SetUpPlayer1(this);
HBS = spawningObject.GetComponent<hoverBoardScript>();
BH = spawningObject.GetComponent<BallHandling>();
BS = spawningObject.GetComponent<BallSteal>();
Debug.Log("finished setting up player");
}
public void SetPlayerList()
{
PlayerList = FindObjectsOfType<NetPlayer>();
if (PV.IsMine)
{
LocalPlayer = this;
foreach (NetPlayer p in PlayerList)
{
p.LocalPlayer = this;
if (p.PC != null)
p.PC.LocalPlayer = this;
}
}
}
[PunRPC]
private void RPC_ParentChild(int child, int parent)
{
ParentChild(PhotonView.Find(child).gameObject, PhotonView.Find(parent).gameObject);
}
private void ParentChild(GameObject child, GameObject parent)
{
child.transform.SetParent(parent.transform);
child.GetComponent<PlayerColor>().ParentPlayer = this;
parent.GetComponent<NetPlayer>().ChildPlayer = child;
ReadyToSetPlayer = true;
}
public void ConfirmTeamPlacement()
{
ConfirmTeam = true;
}
[PunRPC]
public void RPC_ChangeTeam(int i)
{
TeamNum = i;
}
public int GetTeamNum()
{
return TeamNum;
}
[PunRPC]
private void RPC_ChangeName(string name, string code)
{
ChangeName(name, code);
}
private void ChangeName(string name, string code)
{
gameObject.name = name;
CodeNumbers = code;
// this.GetComponentInChildren<TextMesh>().text = name;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/BallHandling.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallHandling : MonoBehaviour {
private PlayerVoiceLine PVL;
// Set Shoot force
[SerializeField]
public float ShootForce = 200;
[SerializeField]
public float PassForce;
// Get Force Direction from camera
[SerializeField]
private Camera Cam;
private Vector3 Direction;
[SerializeField]
private PlayerSoftlockPassSight softLockScript;
// Target for passes
private GameObject Target;
// Target position for passes
//private Vector3 TargetPosition;
// Hand to where the ball goes
[SerializeField]
private Transform Hand;
public Ball ball;
private Ball FindBall;
private float FindBallDistance = 10;
// get from input manager
private float PassShootAxis = 0;
//OLD SYNCVAR
public bool canHold = true;
// can hold timer
public float canHoldTimer = 1;
// Layer the player can pass on
[SerializeField]
private LayerMask HitLayer;
// player's tag
private string playerTag;
// Reference fake ball
[SerializeField]
public GameObject FakeBall;
[SerializeField]
private PlayerColor PC;
// Animator
[SerializeField]
private AnimationController AnimationControl;
// Player has control
[HideInInspector]
public bool HasControl = true;
//effects
public ParticleSystem PassEffectBlue;
public ParticleSystem PassEffectRed;
//photon variables
private PhotonView PV;
public bool isPaused;
// Use this for initialization
void Start() {
PVL = FindObjectOfType<PlayerVoiceLine>();
canHold = true;
playerTag = transform.root.tag;
PV = GetComponent<PhotonView>();
}
// Update is called once per frame
void Update()
{
if (PC.LocalPlayer == PC.ParentPlayer && HasControl)
{
//if (ball != null)
//{
// if (ball.BH != this)
// {
// //ball.MakeBallDisapear();
// ball.BH = this;
// ball.UpdateBH(this);
// }
// else if (ball.Hand != Hand)
// {
// ball.Hand = Hand;
// ball.UpdateHand(this);
// }
// else
// {
// ball.Held = true;
// ball.UpdateHeld(true);
// }
//}
PassShootAxis = Input.GetAxis("PassShoot");
//Debug.Log("Pass / Shoot Axis: " + PassShootAxis);
//Debug.Log("ball = " + ball);
if (ball != null)
{
if (!isPaused)
{
if (!ball.GetThrown())
{
if (PassShootAxis < -0.1)
{
// PASS
// Get Target from Targeting Script
if (softLockScript.target != null)
Target = softLockScript.target.gameObject;
//Debug.Log("target: " + Target);
//TargetPosition = softLockScript.targetPosition;
if (Target != null)
{
//Debug.Log("jadaadadadadadad");
//Debug.Log(gameObject.name + " Passes");
// Debug.Log("target: " + Target.name);
Pass(Target, ball.gameObject, Hand.position, this.gameObject);
AnimationControl.PassAnimation();
ball = null;
}
}
else if (PassShootAxis > 0.1)
{
// SHOOT
//Debug.Log(gameObject.name + " Shoots");
//RaycastHit RH;
Vector3 direction = Cam.transform.position + Cam.transform.forward * 100 - Hand.position;
//if(Physics.Raycast(Cam.transform.position, Cam.transform.forward, out RH, 100, HitLayer))
//{
// direction = RH.collider.
//}
//else
//{
//}
//Debug.DrawLine(Cam.transform.position + Cam.transform.forward * 100, Hand.position, Color.blue, 6f);
//Debug.DrawRay(Hand.position, Cam.transform.position + Cam.transform.forward * 100 - Hand.position, Color.red, 3.75f);
Shoot(ball.gameObject, Hand.position, direction.normalized * ShootForce, this.gameObject);
AnimationControl.PassAnimation();
ball = null;
}
}
}
}
if (!canHold)
{
if (canHoldTimer > 0)
canHoldTimer -= Time.deltaTime;
else if (canHoldTimer <= 0)
{
canHoldTimer = 1;
canHold = true;
}
}
if (FindBall == null)
{
FindBall = FindObjectOfType<Ball>();
}
else
{
if (!FindBall.Held)
{
if (!FindBall.GetThrown())
{
FindBallDistance = (FindBall.transform.position - transform.position).magnitude;
if (FindBallDistance <= FindBall.PickUpRadius)
{
PVL.PlayBallPickup();
FindBall.PickUp(gameObject);
}
}
}
}
}
else if (PC.LocalPlayer != PC.ParentPlayer)
{
if (!canHold)
{
if (canHoldTimer > 0)
canHoldTimer -= Time.deltaTime;
else if (canHoldTimer <= 0)
{
canHoldTimer = 1;
canHold = true;
}
}
if (FindBall == null)
{
FindBall = FindObjectOfType<Ball>();
}
else
{
if (!FindBall.Held)
{
if (!FindBall.GetThrown())
{
FindBallDistance = (FindBall.transform.position - transform.position).magnitude;
if (FindBallDistance <= FindBall.PickUpRadius)
{
FindBall.SlowDown();
}
}
}
}
}
}
//[PunRPC]
//public void RPC_ResetTime(int id)
//{
// canHoldTimer
//}
public void SetHand(Transform T)
{
Hand = T;
}
public Transform ReturnHand()
{
return Hand;
}
public void Pass(GameObject Target, GameObject ballObject, Vector3 HandPos, GameObject WhoThrew)
{
PVL.PlayShoot();
PV.RPC("RPC_PlayPassEffect", RpcTarget.All);
//RpcPass(Target, ballObject, HandPos, WhoThrew);
RPC_Pass(Target.GetPhotonView().ViewID, ballObject.GetPhotonView().ViewID, HandPos, WhoThrew.GetPhotonView().ViewID);
//PV.RPC("RPC_Pass", RpcTarget.AllBuffered, Target.GetPhotonView().ViewID, ballObject.GetPhotonView().ViewID, HandPos, WhoThrew.GetPhotonView().ViewID);
}
//[PunRPC]
private void RPC_Pass(int Target, int ballObject, Vector3 HandPos, int WhoThrew)
{
Ball temp = PhotonView.Find(ballObject).gameObject.GetComponent<Ball>();
temp.SetPass(true, PhotonView.Find(Target).gameObject, PassForce, HandPos, PhotonView.Find(WhoThrew).gameObject);
//TurnOnFakeBall(false);
}
private void Shoot(GameObject ballObject, Vector3 HandPos, Vector3 Direction, GameObject WhoThrew)
{
PVL.PlayShoot();
//TurnOnFakeBall(false);
//PV.RPC("RPC_PlayPassEffect", RpcTarget.All);
RPC_Shoot(Direction, ballObject.GetPhotonView().ViewID, HandPos, WhoThrew.GetPhotonView().ViewID);
//Debug.Log("Direction: " + Direction + " ballObject: " + ballObject + " HandPos: " + HandPos + " WhoThrew: " + WhoThrew);
//Debug.Log("PV: " + PV);
//PV.RPC("RPC_Shoot", RpcTarget.All, Direction, ballObject.GetPhotonView().ViewID, HandPos, WhoThrew.GetPhotonView().ViewID);
}
//[PunRPC]
private void RPC_Shoot(Vector3 Direction, int ballObject, Vector3 HandPos, int WhoThrew)
{
Ball temp = PhotonView.Find(ballObject).gameObject.GetComponent<Ball>();
temp.Shoot(Direction, playerTag, HandPos, PhotonView.Find(WhoThrew).gameObject);
//TurnOnFakeBall(false);
}
public void SetBall(GameObject ballObject)
{
//RpcSetBall(ballObject);
PV.RPC("RPC_SetBall", RpcTarget.All, ballObject.GetPhotonView().ViewID);
}
[PunRPC]
public void RPC_SetBall(int ballObjectb)
{
Ball b = PhotonView.Find(ballObjectb).GetComponent<Ball>();
ball = b;
}
//public void TurnOnFakeBall(bool b)
//{
// //RpcTurnOnFakeBall(gameObject, b);
// PV.RPC("RPC_TurnOnFakeBall", RpcTarget.All, gameObject.GetPhotonView().ViewID, b);
//}
//[PunRPC]
//public void RPC_TurnOnFakeBall(int playerObject, bool b)
//{
// BallHandling bh = PhotonView.Find(playerObject).gameObject.GetComponent<BallHandling>();
// bh.FakeBall.SetActive(b);
//}
/// <summary>
/// /passing effects
/// </summary>
[PunRPC]
public void RPC_PlayPassEffect()
{
if (PC.LocalPlayer == PC.ParentPlayer)
{
if (PassEffectBlue != null)
PassEffectBlue.Play();
}
else
{
if (PC.LocalPlayer.GetTeamNum() == PC.ParentPlayer.GetTeamNum())
{
if (PassEffectBlue != null)
PassEffectBlue.Play();
}
else
{
if (PassEffectRed != null)
PassEffectRed.Play();
}
}
}
public void Steal(GameObject TargetHand, GameObject ballObject, Vector3 HandPos, GameObject WhoThrew)
{
//Debug.Log("CmdSteal");
//RpcSteal(TargetHand, ballObject, HandPos, WhoThrew);
PV.RPC("RPC_Steal", RpcTarget.All, TargetHand.GetPhotonView().ViewID, ballObject.GetPhotonView().ViewID, HandPos, WhoThrew.GetPhotonView().ViewID);
}
[PunRPC]
private void RPC_Steal(int TargetHand, int ballObject, Vector3 HandPos, int WhoThrew)
{
//Debug.Log("RpcSteal");
Ball temp = (PhotonView.Find(ballObject).gameObject.GetComponent<Ball>());
temp.thiefTransform = PhotonView.Find(TargetHand).gameObject.transform;
temp.stolenInProgress = true;
temp.SetSteal(true, PhotonView.Find(TargetHand).gameObject, PassForce, HandPos, PhotonView.Find(WhoThrew).gameObject);
//TurnOnFakeBall(false);
}
public void DropBall()
{
if (ball != null)
{
float randomX = Random.Range(-1f, 1f);
float randomZ = Random.Range(-1f, 1f);
Vector3 DropPower = new Vector3(randomX, 1, randomZ) * ShootForce * 0.1f;
Shoot(ball.gameObject, Hand.position, DropPower, this.gameObject);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/IKControl.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IKControl : MonoBehaviour {
[SerializeField]
private AnimationController AC;
[SerializeField]
private PlayerColor PC;
[SerializeField]
private GameObject Avatar;
[SerializeField]
private Animator Animator;
[SerializeField]
private Transform LookAtPos;
[SerializeField]
private Transform LeftShoulderHint;
[SerializeField]
private Transform RightShoulderHint;
//[SyncVar]
private Vector3 TargetPosition;
//photon variables
[SerializeField]
private PhotonView PV;
// Use this for initialization
public void UpdateTargetPosition(Vector3 pos)
{
//RpcUpdateTargetPosition(pos);
PV.RPC("RPC_UpdateTargetPosition", RpcTarget.All, pos);
}
[PunRPC]
public void RPC_UpdateTargetPosition(Vector3 pos)
{
TargetPosition = pos;
}
private void OnAnimatorIK(int layerIndex)
{
if (Avatar.activeSelf)
{
if (PC.LocalPlayer == PC.ParentPlayer)
{
TargetPosition = LookAtPos.position;
AC.UpdateTargetPosition(TargetPosition);
}
Animator.SetLookAtPosition(AC.LookPos);
Animator.SetLookAtWeight(1);
AnimatorClipInfo[] clipInfo = Animator.GetCurrentAnimatorClipInfo(layerIndex);
//Debug.Log("Clip: " + clipInfo[0].clip);
if ("" + clipInfo[0].clip == "Pass (UnityEngine.AnimationClip)" || "" + clipInfo[0].clip == "Shoot (UnityEngine.AnimationClip)")
{
//Debug.Log("Clip Passed Enter ");
Animator.SetIKPosition(AvatarIKGoal.RightHand, TargetPosition);
Animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
Animator.SetIKPosition(AvatarIKGoal.LeftHand, TargetPosition);
Animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, 1);
//Animator.SetIKHintPosition(AvatarIKHint.)
}
else
{
Animator.SetIKPosition(AvatarIKGoal.RightHand, TargetPosition);
Animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 0);
Animator.SetIKPosition(AvatarIKGoal.LeftHand, TargetPosition);
Animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, 0);
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ScoreTracker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreTracker : MonoBehaviour {
private float team1Score;
private float team2Score;
[SerializeField]
public List<Text> t1Scoring = new List<Text>();
[SerializeField]
public List<Text> t2Scoring = new List<Text>();
[SerializeField]
public List<RectTransform> t1Logo = new List<RectTransform>();
[SerializeField]
public List<RectTransform> t2Logo = new List<RectTransform>();
[SerializeField]
public GameObject[] scoreCanvases;
// Use this for initialization
void Start () {
//t1Scoring = transform.GetChild(0).GetComponent<Text>();
//t2Scoring = transform.GetChild(1).GetComponent<Text>();
for (int i = 0; i < scoreCanvases.Length; i++)
{
//Debug.Log("i: " + i);
t1Scoring.Add(scoreCanvases[i].transform.GetChild(0).GetComponent<Text>());
t2Scoring.Add(scoreCanvases[i].transform.GetChild(1).GetComponent<Text>());
t1Logo.Add(scoreCanvases[i].transform.GetChild(2).GetComponent<RectTransform>());
t2Logo.Add(scoreCanvases[i].transform.GetChild(3).GetComponent<RectTransform>());
}
team1Score = 0;
team2Score = 0;
//for (int i = 0; i < t1Scoring.Count; i++)
//{
// t1Scoring[i].text = "Team1: " + team1Score.ToString();
// t2Scoring[i].text = "Team2: " + team2Score.ToString();
//}
}
public void AddScoreToTeam1(float score)
{
team1Score += score;
//for (int i = 0; i < t1Scoring.Count; i++)
//{
// t1Scoring[i].text = "Team1: " + team1Score.ToString();
//}
}
public void AddScoreToTeam2(float score)
{
team2Score += score;
//for (int i = 0; i < t1Scoring.Count; i++)
//{
// t2Scoring[i].text = "Team2: " + team2Score.ToString();
//}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/hoverBoardScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hoverBoardScript : MonoBehaviour
{
public Rigidbody m_body;
public float m_deadZone = 0.1f;
public float m_forwardAcl = 100.0f;
public float m_backwardAcl = 25.0f;
public float m_currThrust = 0.0f;
public float m_turnStrength = 10f;
public float m_currTurn = 0.0f;
public LayerMask m_layerMask;
public float m_maxHoverForce = 9.0f;
public float m_minHoverForce = 0.0f;
public float m_hoverHeight = 2.0f;
public GameObject[] m_hoverPoints;
[SerializeField]
private PIDController[] PIDHoverPoints;
// PID Controller
[SerializeField]
private float Kp = 1.1f;
[SerializeField]
private float Ki = 0.0f;
[SerializeField]
private float Kd = 0.0f;
private bool[] ToggleStabilizers;
private int StabalizersActive = 0;
//private bool AutoStabalize = true;
// Maximum
[SerializeField]
private float MaxSpeed = 10;
public float Speed;
[SerializeField]
private float MaxTurnAdjustPercent = 50f;
private float CurrentAdjust = 0;
[SerializeField]
private float SpeedDeadZone = 5f;
[SerializeField]
private float FallAssistForce = 10000f; // higher means the character falls faster
[SerializeField]
private float RiseAssistForce = 0f; // higher means the character rises faster
[SerializeField]
private float JumpForce = 400;
[SerializeField]
private float SpeedBoostLinearPercent = 50f;
[SerializeField]
private float SpeedBoostTurnPercent = 25f;
[SerializeField]
private float SprintBoostLinearPercent = 50f;
private float sprintMultiplier = 1;
[SerializeField]
private float AdditiveAcceleration = 5;
private float AccelerationMultiplier = 1;
//
[HideInInspector]
public float BoostPaddBoostLinearPercent = 0f;
//
[HideInInspector]
public bool SpeedBoosted = false;
// Can stick to walls
private bool CanStick = true;
private bool Flipping = false;
private bool OnGround = true;
// Animator
[SerializeField]
private AnimationController AnimationControl;
// Player has control or not
[HideInInspector]
public bool BoardHasControl = true;
//marcstuff
//public GameObject camGurl1;
//public GameObject camGurl2;
// Speed Ratio for Cmd Send
private float CurrentSpeedRatio = 0;
private float LastSpeedRatio = 0;
private bool LastTimeOnGround = false;
// Turn Acceleration
[SerializeField]
private float TurnPercentAcceleration = 50;
[SerializeField]
private float MaxTurnPercentAcceleration = 300;
private float AccelerationAmount = 100;
private float PreviousTurnSpeed;
private float TurnSpeed;
public bool roundStarted = false;
// Use this for initialization
void Start ()
{
Physics.gravity = new Vector3(0, -100, 0);
if (!m_body)
m_body = GetComponent<Rigidbody>();
//m_layerMask = 1 << LayerMask.NameToLayer("Characters");
//m_layerMask = ~m_layerMask;
if (PIDHoverPoints.Length > 0)
{
float KAdjust = m_maxHoverForce / m_hoverHeight;
ToggleStabilizers = new bool[PIDHoverPoints.Length];
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
ToggleStabilizers[i] = true;
PIDHoverPoints[i].setGains(Kp * KAdjust, Ki * KAdjust, Kd * KAdjust);
PIDHoverPoints[i].EnableClamp(m_minHoverForce, m_maxHoverForce);
//PIDHoverPoints[i].transform.localPosition = new Vector3(PIDHoverPoints[i].transform.localPosition.x, 0, PIDHoverPoints[i].transform.localPosition.z);
}
}
}
// Update is called once per frame
void Update()
{
if (BoardHasControl)
{
if (roundStarted)
{
// Previous Turn Direction
PreviousTurnSpeed = TurnSpeed;
//main thrust
m_currThrust = 0.0f;
float aclAxis = Input.GetAxis("Vertical");
if (aclAxis > m_deadZone)
{
m_currThrust = aclAxis * m_forwardAcl;
}
else if (aclAxis < -m_deadZone)
{
m_currThrust = aclAxis * m_backwardAcl;
}
Speed = m_body.velocity.magnitude;
//turning
m_currTurn = 0.0f;
float turnAxis = Input.GetAxis("Horizontal");
if (Mathf.Abs(turnAxis) > m_deadZone)
{
m_currTurn = turnAxis * 4;
}
// Turning Accelerationn
if (PreviousTurnSpeed * m_currTurn <= 0)
{
//Debug.Log("Set Turn Acceleration to Base");
AccelerationAmount = 100;
}
else if (PreviousTurnSpeed > m_currTurn && AccelerationAmount > 100)
{
//Debug.Log("Lower Turn Acceleration");
AccelerationAmount -= Time.deltaTime * TurnPercentAcceleration;
}
if (AccelerationAmount < MaxTurnPercentAcceleration)
{
//Debug.Log("Raise Turn Acceleration");
AccelerationAmount += Time.deltaTime * TurnPercentAcceleration;
}
else
{
//Debug.Log("Set Turn Acceleration to Max");
AccelerationAmount = MaxTurnPercentAcceleration;
}
TurnSpeed = m_currTurn;
m_currTurn *= AccelerationAmount / 100;
// Adjust turning height adjustment
CurrentAdjust = Speed < SpeedDeadZone ? 0.0f
: Speed < MaxSpeed ? m_hoverHeight * MaxTurnAdjustPercent * (Speed - SpeedDeadZone) / ((MaxSpeed - SpeedDeadZone) * 100f)
: m_hoverHeight * MaxTurnAdjustPercent / (100f);
}
else
{
transform.GetComponent<Rigidbody>().velocity = Vector3.zero;
Speed = 0;
m_currThrust = 0;
m_currTurn = 0;
AccelerationAmount = 0;
PreviousTurnSpeed = 0;
}
}
else
{
m_currTurn = 0;
m_currThrust = 0;
}
if (Input.GetKey(KeyCode.LeftShift))
{
sprintMultiplier = 1 + (SprintBoostLinearPercent / 100) + BoostPaddBoostLinearPercent;
}
else
{
sprintMultiplier = 1 + BoostPaddBoostLinearPercent;
}
if (BoardHasControl)
{
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.Space))
{
CanStick = false;
if (Input.GetKeyDown(KeyCode.Space) && OnGround)
{
Jump();
OnGround = false;
}
if (Input.GetKey(KeyCode.LeftControl))
{
Flipping = true;
FlipCharacter();
}
}
else
{
CanStick = true;
Flipping = false;
}
}
// Update animator
CurrentSpeedRatio = Mathf.Abs(Speed / MaxSpeed);
if (LastSpeedRatio <= 0.01f && CurrentSpeedRatio >= 0.01)
AnimationControl.UpdateSpeedRatio(LastSpeedRatio);
else if (LastSpeedRatio <= 0.75f && CurrentSpeedRatio >= 0.75)
AnimationControl.UpdateSpeedRatio(LastSpeedRatio);
else if (LastSpeedRatio >= 0.75f && CurrentSpeedRatio <= 0.75)
AnimationControl.UpdateSpeedRatio(LastSpeedRatio);
else if (LastSpeedRatio >= 0.01f && CurrentSpeedRatio <= 0.01)
AnimationControl.UpdateSpeedRatio(LastSpeedRatio);
if (LastTimeOnGround != OnGround)
AnimationControl.UpdateGrounded1(OnGround);
LastSpeedRatio = CurrentSpeedRatio;
LastTimeOnGround = OnGround;
}
void FixedUpdate()
{
// Non PID Controllers
//Hover force
if (m_hoverPoints.Length > 0)
{
RaycastHit hit;
for (int i = 0; i < m_hoverPoints.Length; i++)
{
var hoverPoint = m_hoverPoints[i];
if (Physics.Raycast(hoverPoint.transform.position, -transform.up, out hit, m_hoverHeight + 0.3f, m_layerMask))
{
// Debug.DrawRay(hoverPoint.transform.position, -hoverPoint.transform.up * hit.distance, Color.red);
m_body.AddForceAtPosition(Vector3.up * m_maxHoverForce * (1.0f - (hit.distance / m_hoverHeight)), hoverPoint.transform.position);
//Debug.Log(hoverPoint.name + ", Force: " + (Vector3.up * m_hoverForce * (1.0f - (hit.distance / m_hoverHeight))).y + ", Distance: " + hit.distance);
}
else
{
if (!Input.GetKey(KeyCode.Space))
{
if (transform.position.y > hoverPoint.transform.position.y)
{
m_body.AddForceAtPosition(hoverPoint.transform.up * m_maxHoverForce, hoverPoint.transform.position);
// Debug.DrawRay(hoverPoint.transform.position, -hoverPoint.transform.up * hit.distance, Color.black);
}
else
{
m_body.AddForceAtPosition(hoverPoint.transform.up * -m_maxHoverForce, hoverPoint.transform.position);
//Debug.DrawRay(hoverPoint.transform.position, -hoverPoint.transform.up * hit.distance, Color.blue);
}
}
}
}
}
StabalizersActive = 0;
int FallingStabalizers = 0;
// PID controllers
if (PIDHoverPoints.Length > 0)
{
RaycastHit hit;
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
PIDController temp = PIDHoverPoints[i];
if (Physics.Raycast(temp.gameObject.transform.position, -transform.up, out hit, m_hoverHeight + 1.3f, m_layerMask) && CanStick && !Flipping)
{
OnGround = true;
StabalizersActive++;
if (!ToggleStabilizers[i])
{
ToggleStabilizers[i] = true;
temp.WipeErrors();
}
// This changes the target hieght when turning,NOTE all left and right PID points on the controller MUST be names and changed here
float TargetAdjustHeight = (temp.name == "frontLeft" || temp.name == "centerLeft" || temp.name == "backLeft") && m_currTurn < 0f ? -CurrentAdjust
: (temp.name == "frontLeft" || temp.name == "centerLeft" || temp.name == "backLeft") && m_currTurn > 0f ? CurrentAdjust
: (temp.name == "frontRight" || temp.name == "centerRight" || temp.name == "backRight") && m_currTurn < 0f ? CurrentAdjust
: (temp.name == "frontRight" || temp.name == "centerRight" || temp.name == "backRight") && m_currTurn > 0f ? -CurrentAdjust
: 0f;
temp.step(m_hoverHeight + TargetAdjustHeight, hit.distance);
m_body.AddForceAtPosition(temp.gameObject.transform.up * temp.getOutput(), temp.gameObject.transform.position);
// Debug.DrawRay(temp.gameObject.transform.position, -temp.gameObject.transform.up * hit.distance, Color.red);
// Debug.Log(temp.gameObject.name + ", Force: " + (temp.gameObject.transform.up * m_maxHoverForce * (1.0f - (hit.distance / m_hoverHeight))).y + ", Distance: " + hit.distance);
}
else if (!Flipping)
{
if (Input.GetMouseButton(1) || StabalizersActive <= 3)
{
if (ToggleStabilizers[i])
{
ToggleStabilizers[i] = false;
temp.WipeErrors();
}
if (Mathf.Abs(transform.position.y - temp.gameObject.transform.position.y) > m_deadZone)
{
FallingStabalizers++;
temp.step(transform.position.y, temp.gameObject.transform.position.y);
m_body.AddForceAtPosition(temp.gameObject.transform.up * temp.getOutput(), temp.gameObject.transform.position);
}
if (!Input.GetKey(KeyCode.Space))
{
m_body.AddForceAtPosition(Vector3.up * FallAssistForce, temp.gameObject.transform.position);
}
else
{
m_body.AddForceAtPosition(Vector3.up * RiseAssistForce, temp.gameObject.transform.position);
}
}
}
}
if (StabalizersActive == PIDHoverPoints.Length)
{
m_body.useGravity = false;
}
else
{
m_body.useGravity = true;
}
}
//forward
if (Mathf.Abs(m_currThrust) > 0)
{
AccelerationMultiplier = Mathf.Abs(5 * (MaxSpeed * sprintMultiplier - Speed) / (MaxSpeed * sprintMultiplier));
if (AccelerationMultiplier < 1)
{
AccelerationMultiplier = 1;
}
if (AccelerationMultiplier > AdditiveAcceleration)
{
AccelerationMultiplier = AdditiveAcceleration;
}
if (Speed > MaxSpeed * sprintMultiplier)
{
AccelerationMultiplier = -AccelerationMultiplier;
}
if (!SpeedBoosted)
{
m_body.AddForce(transform.forward * m_currThrust * Time.fixedDeltaTime * AccelerationMultiplier, ForceMode.Acceleration);
}
else
{
m_body.AddForce(transform.forward * m_currThrust * Time.fixedDeltaTime * (100 + SpeedBoostLinearPercent) * AccelerationMultiplier / 100, ForceMode.Acceleration);
}
}
//turn
float SpeedTurnAdjust = Speed < .25f * MaxSpeed ? 1
: Speed < 0.6f * MaxSpeed ? 1 - Speed / MaxSpeed
: Speed <= MaxSpeed ? .4f
: Speed > MaxSpeed && Speed / MaxSpeed - 1 > 0.2f ? Speed / MaxSpeed - 1
: 0.2f;
if (!SpeedBoosted)
RotateHoverBoard(m_currTurn * m_turnStrength * SpeedTurnAdjust);
else
RotateHoverBoard(m_currTurn * m_turnStrength * SpeedTurnAdjust * (100 + SpeedBoostTurnPercent) / 100);
}
public void RotateHoverBoard(float TurnAmount)
{
m_body.AddRelativeTorque(Vector3.up * TurnAmount);
}
void OnDrawGizmos()
{
}
public void IsSpeedBoosted(bool b)
{
SpeedBoosted = b;
}
public void ChangeKp(float kp)
{
Kp = kp;
if (Kp < 0f)
Kp = 0f;
float KAdjust = m_maxHoverForce / m_hoverHeight;
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
PIDHoverPoints[i].setGains(Kp * KAdjust, Ki * KAdjust, Kd * KAdjust);
}
}
public void ChangeKi(float ki)
{
Ki = ki;
if (Ki < 0f)
Ki = 0f;
float KAdjust = m_maxHoverForce / m_hoverHeight;
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
PIDHoverPoints[i].setGains(Kp * KAdjust, Ki * KAdjust, Kd * KAdjust);
}
}
public void ChangeKd(float kd)
{
Kd = kd;
if (Kd < 0f)
Kd = 0f;
float KAdjust = m_maxHoverForce / m_hoverHeight;
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
PIDHoverPoints[i].setGains(Kp * KAdjust, Ki * KAdjust, Kd * KAdjust);
}
}
public void FlipCharacter()
{
//Debug.Log("Trying to flip character");
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
PIDController temp = PIDHoverPoints[i];
// error is based on angle
float ZAngle = transform.eulerAngles.z;
if (ZAngle < 0)
{
ZAngle += 360;
}
if (ZAngle < 180)
{
ZAngle = 360 - ZAngle;
}
float XAngle = transform.eulerAngles.x;
if (XAngle < 0)
{
XAngle += 360;
}
if (XAngle < 180)
{
XAngle = 360 - XAngle;
}
if (temp.name == "frontLeft" || temp.name == "centerLeft" || temp.name == "backLeft" || temp.name == "frontRight" || temp.name == "centerRight" || temp.name == "backRight")
{
temp.step(360, ZAngle);
}
if (temp.name == "frontCenter" || temp.name == "backCenter")
{
temp.step(360, XAngle);
}
float TargetAdjustHeight = (temp.name == "frontLeft" || temp.name == "centerLeft" || temp.name == "backLeft") && transform.eulerAngles.z < 180 ? temp.getOutput()
: (temp.name == "frontLeft" || temp.name == "centerLeft" || temp.name == "backLeft") && transform.eulerAngles.z >= 180 ? -temp.getOutput()
: (temp.name == "frontRight" || temp.name == "centerRight" || temp.name == "backRight") && transform.eulerAngles.z < 180 ? -temp.getOutput()
: (temp.name == "frontRight" || temp.name == "centerRight" || temp.name == "backRight") && transform.eulerAngles.z >= 180 ? temp.getOutput()
: (temp.name == "frontCenter") && transform.eulerAngles.x < 180 ? -temp.getOutput()
: (temp.name == "frontCenter") && transform.eulerAngles.x < 180 ? temp.getOutput()
: (temp.name == "backCenter") && transform.eulerAngles.x < 180 ? temp.getOutput()
: (temp.name == "backCenter") && transform.eulerAngles.x < 180 ? -temp.getOutput()
: 0f;
if (ZAngle < 300)
{
if (temp.name == "frontLeft" || temp.name == "centerLeft" || temp.name == "backLeft" || temp.name == "frontRight" || temp.name == "centerRight" || temp.name == "backRight")
m_body.AddForceAtPosition(temp.gameObject.transform.up * TargetAdjustHeight, temp.gameObject.transform.position);
}
if (XAngle < 300)
{
if (temp.name == "frontCenter" || temp.name == "backCenter")
m_body.AddForceAtPosition(temp.gameObject.transform.up * TargetAdjustHeight, temp.gameObject.transform.position);
}
//Debug.DrawRay(temp.gameObject.transform.position, -temp.gameObject.transform.up * TargetAdjustForce, Color.red);
}
if (Physics.Raycast(transform.position, transform.up, 1, m_layerMask))
{
m_body.AddForce(-transform.up * 8000);
}
}
public void Jump()
{
float XAngle = transform.eulerAngles.x * Mathf.PI / 180;
//float YAngle = transform.eulerAngles.y * Mathf.PI / 180;
float ZAngle = transform.eulerAngles.z * Mathf.PI / 180;
float TargetAdjustForceX = -JumpForce * Mathf.Sin(XAngle);
float TargetAdjustForceY = JumpForce * Mathf.Cos(XAngle);
float TargetAdjustForceZ = JumpForce * Mathf.Sin(ZAngle);
float ForwardJumpMultiplier = Speed < 0.1f * MaxSpeed ? 0
: 1f;
//Debug.Log("Forces(Right, Up, Forward): " + TargetAdjustForceZ + " / " + TargetAdjustForceY + " / " + TargetAdjustForceX * ForwardJumpMultiplier);
//Debug.Log("Trying to jump character");
for (int i = 0; i < PIDHoverPoints.Length; i++)
{
PIDController temp = PIDHoverPoints[i];
m_body.AddForceAtPosition(temp.transform.up * TargetAdjustForceY, temp.gameObject.transform.position, ForceMode.Impulse);
m_body.AddForceAtPosition(-temp.transform.right * TargetAdjustForceX * ForwardJumpMultiplier, temp.gameObject.transform.position, ForceMode.Impulse);
m_body.AddForceAtPosition(temp.transform.forward * TargetAdjustForceZ, temp.gameObject.transform.position, ForceMode.Impulse);
}
AnimationControl.JumpAnimation();
}
public float GetMaxSpeed()
{
return MaxSpeed;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerColor.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerColor : MonoBehaviourPun
{
[SerializeField]
private GameObject BluePlayer;
[SerializeField]
private GameObject RedPlayer;
[SerializeField]
private BallHandling BH;
[SerializeField]
private Transform RedHand;
[SerializeField]
private Transform BlueHand;
[SerializeField]
private GameObject RedFakeBall;
[SerializeField]
private GameObject BlueFakeBall;
[SerializeField]
private TextMesh TextName;
[SerializeField]
private PlayerNameTag PNT;
public int TeamNum = 0;
public NetPlayer LocalPlayer;
public NetPlayer ParentPlayer;
[SerializeField]
private ComponentsToDisable CD;
[SerializeField]
private PlayerSoftlockPassSight pSLPS;
[SerializeField]
private ChangeTags CT;
//photon variables
[SerializeField]
private PhotonView PV;
private string Code = "None";
// Setting up players
[HideInInspector]
public bool PlayerLocalSet = false;
[HideInInspector]
public bool SetPlayerTag = false;
[HideInInspector]
public bool SetLocalPlayerCalled = false;
public GameObject ParentObject;
public string DisplayName = "";
// Pick if your team is blue and enemy is red OR is your team color is set with team number
[SerializeField]
private bool SetColorByTeamNum = true;
private void Start()
{
DisplayName = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
}
[PunRPC]
private void RPC_UpdateLocalSet(bool ready)
{
PlayerLocalSet = ready;
}
//void Start()
//{
//}
///ATTEMPTING TO SYNCH DATA ACROSS SERVER
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
Debug.Log("Writing data");
//stream.SendNext(TeamNum);
}
else
{
//TeamNum = (int)stream.ReceiveNext();
}
}
public void SetUpPlayer1(NetPlayer parent)
{
PV = GetComponent<PhotonView>();
Debug.Log("PV: S" + PV);
Debug.Log("SetUpPlayer Called");
SetUpPlayer(parent);
//if (PV.IsMine)
//{
// PV.RPC("RPC_UpdateTag", RpcTarget.AllBuffered);
//}
}
//[PunRPC]
//public void RPC_SetUpPlayer()
//{
// //Debug.Log("parent player is " + ParentPlayer);
// ParentPlayer = GetComponentInParent<NetPlayer>();
// Debug.Log("parent player is " + ParentPlayer);
// LocalPlayer = ParentPlayer.LocalPlayer;
// TeamNum = ParentPlayer.GetTeamNum();
// SetTeamNum(TeamNum);
// //PV.RPC("RPC_SetTeamNum", RpcTarget.All, TeamNum);
// TextName.text = ParentPlayer.name;
// if(LocalPlayer == ParentPlayer)
// {
// TextName.gameObject.SetActive(false);
// }
// if (LocalPlayer.GetTeamNum() != ParentPlayer.GetTeamNum())
// {
// TextName.gameObject.SetActive(false);
// }
//}
public void ResetPNT()
{
PNT.ForceStart();
SetPlayerTag = true;
}
public void FinalPlayerSet(int ParentIndex, string displayName)
{
PNT.ForceStart();
PV.RPC("RPC_SetUpPlayer", RpcTarget.AllBuffered, ParentIndex, displayName);
}
[PunRPC]
private void RPC_SetUpPlayer(int ParentIndex, string displayName)
{
//Debug.LogError("Dummy Error");
ParentObject = PhotonView.Find(ParentIndex).gameObject;
if (ParentPlayer == null)
ParentPlayer = ParentObject.GetComponent<NetPlayer>();
if (LocalPlayer == null)
LocalPlayer = ParentPlayer.LocalPlayer;
//ParentPlayer = GetComponentInParent<NetPlayer>();
//if (LocalPlayer == null && ParentPlayer.LocalPlayer != null)
// LocalPlayer = ParentPlayer.LocalPlayer;
//SetTeamNum(TeamNum);
TextName.text = displayName;
PNT.ForceStart();
if (LocalPlayer == ParentPlayer)
{
TextName.gameObject.SetActive(false);
}
if (LocalPlayer.GetTeamNum() != ParentPlayer.GetTeamNum())
{
TextName.gameObject.SetActive(false);
}
SetTeamNum(TeamNum);
}
public void SetUpPlayer(NetPlayer ParentNetObject)
{
ParentPlayer = ParentNetObject;
if (LocalPlayer == null && ParentPlayer.LocalPlayer != null)
LocalPlayer = ParentPlayer.LocalPlayer;
PV.RPC("RPC_UpdateLocalPlayer", RpcTarget.AllBuffered, ParentNetObject.GetComponent<PhotonView>().ViewID);
gameObject.name = ParentPlayer.name.Split('#')[0];
Code = ParentPlayer.CodeNumbers;
UpdateName(gameObject.name);
PV.RPC("RPC_UpdateCode", RpcTarget.All, Code);
TeamNum = ParentPlayer.GetTeamNum();
transform.GetComponentInChildren<LookAtPostionFollow>().UnParent();
PV.RPC("RPC_UpdateTeamNum", RpcTarget.All, TeamNum);
//PV.RPC("RPC_SetUpPlayer", RpcTarget.AllBuffered);
//SetTeamNum(TeamNum);
if (DisplayName == "")
DisplayName = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
TextName.text = DisplayName;
if (LocalPlayer == ParentPlayer)
{
TextName.gameObject.SetActive(false);
}
if (LocalPlayer.GetTeamNum() != ParentPlayer.GetTeamNum())
{
TextName.gameObject.SetActive(false);
}
if (LocalPlayer != null && SetLocalPlayerCalled)
{
PlayerLocalSet = true;
PV.RPC("RPC_UpdateLocalSet", RpcTarget.AllBuffered, PlayerLocalSet);
}
}
[PunRPC]
private void RPC_UpdateLocalPlayer(int PV_Index_Parent)
{
SetLocalPlayer(PhotonView.Find(PV_Index_Parent).gameObject);
}
private void SetLocalPlayer(GameObject LP)
{
ParentObject = LP;
ParentPlayer = LP.GetComponent<NetPlayer>();
LocalPlayer = ParentPlayer.LocalPlayer;
if (transform.parent == null || transform.parent != ParentObject.transform)
{
transform.SetParent(ParentObject.transform);
}
SetLocalPlayerCalled = true;
}
public void SetTeamNum(int team)
{
if (LocalPlayer == null)
LocalPlayer = ParentPlayer.LocalPlayer;
CD.LocalPlayer = LocalPlayer;
CD.ParentPlayer = ParentPlayer;
TeamNum = team;
//
if (TeamNum == 1)
{
transform.tag = "Team 1";
//CT.ChangeObjectTags("Team 1");
pSLPS.enabled = true;
pSLPS.SetChanges();
}
else if (TeamNum == 2)
{
transform.tag = "Team 2";
//CT.ChangeObjectTags("Team 2");
pSLPS.enabled = true;
pSLPS.SetChanges();
}
//
if (SetColorByTeamNum)
{
if (LocalPlayer.GetTeamNum() == 1)
{
//print("Set Blue Avatar - Local != Parent");
SetBlueActive();
}
else
{
//print("Set Red Avatar - Local != Parent");
SetRedActive();
}
}
else
{
if (LocalPlayer == ParentPlayer)
{
//print("Set Blue Avatar - Local = Parent");
SetBlueActive();
//
// Debug.Log("call set changes");
//
}
else
{
if (LocalPlayer.GetTeamNum() == TeamNum)
{
//print("Set Blue Avatar - Local != Parent");
SetBlueActive();
}
else
{
//print("Set Red Avatar - Local != Parent");
SetRedActive();
}
}
}
PV.RPC("RPC_UpdateTag", RpcTarget.All, gameObject.tag);
CD.ForcedStart2();
}
[PunRPC]
public void RPC_UpdateTeamNum(int Team)
{
TeamNum = Team;
}
public void UpdateName(string name)
{
PV.RPC("RPC_UpdateName", RpcTarget.AllBuffered, name);
}
[PunRPC]
public void RPC_UpdateName(string name)
{
gameObject.name = name;
}
[PunRPC]
public void RPC_UpdateCode(string code)
{
Code = code;
NetPlayer[] Players = FindObjectsOfType<NetPlayer>();
foreach (NetPlayer NP in Players)
{
string parentCode = NP.CodeNumbers;
if (Code == code)
{
transform.SetParent(NP.gameObject.transform);
break;
}
}
}
public string GetCode()
{
return Code;
}
[PunRPC]
public void RPC_UpdateTag(string ThisTag)
{
this.tag = ThisTag;
//CT.ChangeObjectTags(ThisTag);
}
public void SetBlueActive()
{
BluePlayer.SetActive(true);
RedPlayer.SetActive(false);
BH.SetHand(BlueHand);
BH.FakeBall = BlueFakeBall;
}
public void SetRedActive()
{
BluePlayer.SetActive(false);
RedPlayer.SetActive(true);
BH.SetHand(RedHand);
BH.FakeBall = RedFakeBall;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Item.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Item : MonoBehaviour {
private Mesh ItemMesh;
[SerializeField]
private MeshFilter ItemMeshFilter;
[SerializeField]
private Texture ItemSprite;
[SerializeField]
private Behaviour[] DisableBehaviours;
[SerializeField]
private GameObject[] DisableObjects;
[SerializeField]
private Collider[] DisableColliders;
[SerializeField]
private MeshRenderer[] MeshRenderers;
[SerializeField]
private BoxCollider PlacingCollider;
public Vector3 BoxSize;
public Vector3 BoxOffset;
// Item ID
[SerializeField]
private string ItemID;
public int ItemType = -1;
public bool isPlacing = true;
private void Update()
{
if (!isPlacing)
{
if (PhotonNetwork.IsMasterClient)
{
FindObjectOfType<ItemManager>().AddItemToList(ItemType);
}
isPlacing = true;
}
}
public string GetITemID()
{
return ItemID;
}
public BoxCollider GetCollider()
{
return PlacingCollider;
}
public Mesh GetMesh()
{
ItemMesh = ItemMeshFilter.sharedMesh;
return ItemMesh;
}
public Texture GetSprite()
{
return ItemSprite;
}
public void Place(Vector3 pos, Vector3 normal)
{
transform.position = pos;
transform.up = normal;
}
public void Disable()
{
foreach (Behaviour b in DisableBehaviours)
{
b.enabled = false;
}
foreach (GameObject g in DisableObjects)
{
g.SetActive(false);
}
foreach (Collider c in DisableColliders)
{
c.enabled = false;
}
}
public void Enable()
{
foreach (Behaviour b in DisableBehaviours)
{
b.enabled = true;
}
foreach (GameObject g in DisableObjects)
{
g.SetActive(true);
}
}
public void ChangeMaterials(Material mat)
{
foreach (MeshRenderer MR in MeshRenderers)
{
MR.material = mat;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ballHandler.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ballHandler : MonoBehaviour {
[SerializeField]
private GameObject ball;
[SerializeField]
private Transform ballSpawn;
// Use this for initialization
void Start ()
{
ballSpawn = GameObject.FindGameObjectWithTag("ballSpawn").GetComponent<Transform>();
//if (isServer)
//if(PhotonNetwork.IsMasterClient)
//{
// SpawnBall();
//}
}
//// Update is called once per frame
//void Update ()
// {
// //if(Input.GetKeyDown(KeyCode.J))
// //{
// // SpawnBall();
// //}
//}
public void SpawnBall()
{
if (PhotonNetwork.IsMasterClient)
{
//Debug.Log("spawning ball");
PhotonNetwork.Instantiate("Prefabs/Ultra Ball", ballSpawn.position, ballSpawn.rotation);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Checker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class Checker : MonoBehaviour {
[SerializeField]
private CinemachineTargetGroup.Target battery;
[SerializeField]
private CinemachineTargetGroup.Target follow;
[SerializeField]
CinemachineTargetGroup group;
[SerializeField]
List <CinemachineTargetGroup.Target> targets = new List<CinemachineTargetGroup.Target>();
[SerializeField]
List<GameObject> players = new List<GameObject>();
private int numberOfPlayers;
[SerializeField]
private GameObject virtualCam;
bool started = false;
//private List<GameObject> playerObject = new List<GameObject>();
GameObject[] goals;
// Use this for initialization
void Start () {
//GameObject[] playerObjects;
// set angle of camera
virtualCam.transform.eulerAngles = new Vector3(40, 0, 0);
//goals = FindObjectsOfType</*name of the goal script*/>
/*
GameObject[] goals;
goals = GameObject.FindGameObjectsWithTag("Goal");
foreach (GameObject inGameGoals in goals)
{
}
follow.target =
//Debug.Log("player target : " + follow.target);
follow.weight = 1;
targets.Add(follow);
*/
/*
// find all objects with Player as the tag, and place them in a list
playerObjects = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject gamePlayers in playerObjects)
{
players.Add(gamePlayers);
follow.target = gamePlayers.transform;
//Debug.Log("player target : " + follow.target);
follow.weight = 1;
targets.Add(follow);
group.m_Targets = targets.ToArray();
}
*/
}
// Update is called once per frame
void Update () {
/*
for (int i = 0; i < goals.Length; i++)
{
if ((goals[i].transform.position - ))
}
*/
if(!started)
{
GameObject startingPlayer = GameObject.FindGameObjectWithTag("Player");
players.Add(startingPlayer);
follow.target = startingPlayer.transform;
follow.weight = 1;
targets.Add(follow);
group.m_Targets = targets.ToArray();
started = true;
}
// if battery doesn't exist check for battery until battery exists
if (!battery.target)
{
//Debug.Log("enterd1");
// if battery is found place it in group list
if (GameObject.FindGameObjectWithTag("Battery"))
{
Debug.Log("enterd2");
battery.target = GameObject.FindGameObjectWithTag("Battery").transform;
battery.weight = 1;
targets.Add(battery);
group.m_Targets = targets.ToArray();
}
else
{
Debug.Log("battery not found!!!");
}
}
// Debug.Log("Targets . count = " + targets.Count);
// resize list depending if the there's a spot inn list that is void
//for (int i = 0; i < targets.Count; i++)
numberOfPlayers = GameObject.FindGameObjectsWithTag("Player").Length;
Debug.Log("numberOfPlayer" + numberOfPlayers);
Debug.Log("player.Count" + players.Count);
/*
for(int l= 0; l < numberOfPlayers; l++)
{
GameObject current = GameObject.FindGameObjectsWithTag("Player")[l];
Debug.Log("current: " + current);
}
*/
if (numberOfPlayers > players.Count)
{
// bool pop = false;
Debug.Log("number of players exceed the amount of targets!");
int numberMatch = 0;
for (int l = 0; l < numberOfPlayers; l++)
{
GameObject current = GameObject.FindGameObjectsWithTag("Player")[l];
for (int p = 0; p < players.Count; p++)
{
// find excluded object
// Debug.Log("current: " + current);
//for (int x = 0; x < players.Count; x++)
// {
// if (current != players[x])
// {
// Debug.Log("kop");
// Debug.Log("current: " + current + "players[p]" + players[p]);
// numberMatch = numberMatch + 1;
// }
// }
//if (current != players[p])
//{
// Debug.Log("kop");
// Debug.Log("current: " + current + "players[p]" + players[p]);
//numberMatch = numberMatch + 1;
// }
if (current == players[p])
{
numberMatch = 0;
break;
}
else
{
numberMatch = numberMatch +1;
}
Debug.Log("num: " +numberMatch);
if (numberMatch == numberOfPlayers - 1)
{
numberMatch = 0;
Debug.Log("inputed!");
Debug.Log("numberMatch: " + numberMatch + " " + "current: " + current);
players.Add(current);
follow.target = current.transform;
follow.weight = 1;
targets.Add(follow);
group.m_Targets = targets.ToArray();
// break;
}
/*if (numberMatch == numberOfPlayers - 1)
{
numberMatch = 0;
}
*/
}
}
}
for (int i =players.Count - 1; i >= 0; i--)
{
if(players[i]== null)
{
players.RemoveAt(i);
}
}
for (int i = targets.Count - 1; i >= 0; i--)
{
if (targets[i].target == null)
{
//Debug.Log("It entered " + i);
targets.RemoveAt(i);
}
}
/*
for (int i = group.m_Targets.Length - 1; i >= 0; i--)
{
if(group.m_Targets[i])
{
}
}
*/
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ItemManager.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemManager : MonoBehaviour {
[SerializeField]
private int MaxWallItemCount = 1;
[SerializeField]
private int MaxSpeedStripItemCount = 1;
[SerializeField]
private float MaxSpeedStripTimeOut;
private float SpeedStripTimeOut;
[SerializeField]
private float MaxWallTimeOut;
private float WallTimeOut;
// item type int = 1
private Queue<GameObject> SpeedStripItemQueue = new Queue<GameObject>();
// item type int = 2
private Queue<GameObject> WallItemQueue = new Queue<GameObject>();
// item type int = 1
private Queue<GameObject> SpeedStripItemDestroyQueue = new Queue<GameObject>();
// item type int = 2
private Queue<GameObject> WallItemDestroyQueue = new Queue<GameObject>();
[SerializeField]
private PhotonView PV;
// Update is called once per frame
void Update () {
if (PhotonNetwork.IsMasterClient)
{
if (SpeedStripItemDestroyQueue.Count != 0)
{
if (SpeedStripTimeOut < MaxSpeedStripTimeOut)
{
SpeedStripTimeOut += Time.deltaTime;
}
else
{
SpeedStripTimeOut = 0;
GameObject TempPV = SpeedStripItemDestroyQueue.Dequeue();
//PhotonView.Destroy(TempPV.gameObject);
PV.RPC("RPC_Destroy", RpcTarget.All, TempPV.GetComponent<PhotonView>().ViewID);
//if (TempPV != null)
//{
// SpeedStripItemDestroyQueue.Enqueue(TempPV);
//}
}
}
if (WallItemDestroyQueue.Count != 0)
{
if (WallTimeOut < MaxWallTimeOut)
{
WallTimeOut += Time.deltaTime;
}
else
{
WallTimeOut = 0;
GameObject TempPV = WallItemDestroyQueue.Dequeue();
PV.RPC("RPC_Destroy", RpcTarget.All, TempPV.GetComponent<PhotonView>().ViewID);
}
}
}
}
public void AddItemToList(int item)
{
PV.RPC("RPC_AddItemToList", RpcTarget.MasterClient, item);
}
[PunRPC]
private void RPC_AddItemToList(int ItemID)
{
Item[] TempArray = FindObjectsOfType<Item>();
List<Item> DesiredItem = new List<Item>();
foreach (Item item in TempArray)
{
if(item.ItemType == ItemID)
{
DesiredItem.Add(item);
}
}
// filter items we want
foreach (Item item in DesiredItem)
{
// speed
if(item.ItemType == 1)
{
if(!SpeedStripItemQueue.Contains(item.gameObject))
{
SpeedStripItemQueue.Enqueue(item.gameObject);
}
}
//wall
else if (item.ItemType == 2)
{
if (!WallItemQueue.Contains(item.gameObject))
{
WallItemQueue.Enqueue(item.gameObject);
}
}
}
if (ItemID == 1)
{
if (SpeedStripItemQueue.Count > MaxSpeedStripItemCount)
{
SpeedStripItemDestroyQueue.Enqueue(SpeedStripItemQueue.Dequeue());
}
}
else if (ItemID == 2)
{
if (WallItemQueue.Count > MaxWallItemCount)
{
WallItemDestroyQueue.Enqueue(WallItemQueue.Dequeue());
}
}
}
[PunRPC]
private void RPC_Destroy(int ItemID)
{
Destroy(PhotonView.Find(ItemID).gameObject);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/LobbyPlayerInfoResetPos.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LobbyPlayerInfoResetPos : MonoBehaviour {
private RectTransform rectTransform;
void Start () {
rectTransform = transform.GetComponent<RectTransform>();
rectTransform.localPosition = new Vector3(rectTransform.localPosition.x, rectTransform.localPosition.y, 0);
rectTransform.eulerAngles = new Vector3(rectTransform.eulerAngles.x, 180, rectTransform.eulerAngles.z);
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/SwapRoomUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
public class SwapRoomUI : MonoBehaviourPunCallbacks {
[SerializeField]
private GameObject LobbyUI;
[SerializeField]
private GameObject RoomUI;
public override void OnJoinedRoom()
{
LobbyUI.SetActive(false);
RoomUI.SetActive(true);
base.OnJoinedRoom();
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/TestCharacterMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestCharacterMovement : MonoBehaviour {
public float distance;
public Vector3 displacement = new Vector3(0, 0, 0);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//transform.Translate(Vector3.forward * Time.deltaTime);
//transform.Translate(Vector3.up * Time.deltaTime, Space.World);
if (Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(Vector3.forward * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(-Vector3.forward * Time.deltaTime);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/OutOfBoundsCheck.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OutOfBoundsCheck : MonoBehaviour {
[SerializeField]
private hoverBoardScript PlayerBoard;
//void OnCollisionStay(Collision c)
//{
// if (c.gameObject.tag == "OutOfBounds")
// {
// PlayerBoard.FlipCharacter();
// }
//}
void OnTriggerStay(Collider c)
{
if (c.gameObject.tag == "OutOfBounds")
{
PlayerBoard.FlipCharacter();
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/musicMenu.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class musicMenu : MonoBehaviour {
private AudioSource Src;
public AudioClip[] music;
private float musicVolume = 1f;
// Use this for initialization
void Start () {
Src = GetComponent<AudioSource>();
//if (!Src.playOnAwake)
//{
// Src.clip = music[0];
// Src.Play();
//}
}
// Update is called once per frame
void Update () {
Src.volume = musicVolume;
//if (!Src.isPlaying)
//{
// Src.clip = music[Random.Range(0, music.Length)];
// Src.Play();
//}
}
public void SetVolume(float vol)
{
musicVolume = vol;
}
//void PlayNextSong()
//{
// Debug.Log("playmusicisCalled");
// Src.clip = music[Random.Range(0, music.Length)];
// Src.Play();
// Invoke("PlayNextSong", Src.clip.length);
//}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/RuneSpawn.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class RuneSpawn : NetworkBehaviour {
[SerializeField]
private GameObject[] Runes;
GameObject myInstantiatedObject;
// Use this for initialization
void Start () {
CmdSpawnRune();
}
Vector3 RandomCircle(Vector3 center, float radius)
{
float ang = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.y = center.y + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.z = center.z;
return pos;
}
[Command]
void CmdSpawnRune()
{
Vector3 center = transform.position;
Vector3 pos = RandomCircle(center, 5.0f);
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, center - pos);
myInstantiatedObject = Instantiate(Runes[Random.Range(0, 3)], pos, rot);
NetworkServer.Spawn(myInstantiatedObject);
//RpcSpawner();
}
[ClientRpc]
void RpcSpawner()
{
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlacingItemsTOTC.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlacingItemsTOTC : MonoBehaviour
{
// Placing Script
[SerializeField]
private Placing PlacingScript;
[SerializeField]
private Transform PlacingTransform;
// Player Components
[SerializeField]
private hoverBoardScript HBS;
[SerializeField]
private BallHandling BH;
[SerializeField]
private RunePickups RP;
[SerializeField]
private PlayerColor PC;
private PlayerVoiceLine PVL;
// Item Slots
[SerializeField]
private ItemSlot[] ItemSlots;
// Variables
private bool PlacingItems = false;
private int CurrentSlot = 0;
private int MaxSlots = 0;
private Item ActiveItem;
[SerializeField]
private float PickUpTime = 0.2f;
private float PickUpTimer = 0;
private bool PickedUpItem = false;
//photon variables
private PhotonView PV;
private ItemManager IM;
// Use this for initialization
void Start ()
{
PVL = FindObjectOfType<PlayerVoiceLine>();
PV = GetComponent<PhotonView>();
MaxSlots = ItemSlots.Length;
foreach (ItemSlot IS in ItemSlots)
{
IS.SetImage();
}
IM = FindObjectOfType<ItemManager>();
}
// Update is called once per frame
void Update () {
if (PC.LocalPlayer != PC.ParentPlayer)
{
return;
}
if (Input.GetKeyDown(KeyCode.Tab))
{
// Toggle placing items
PlacingItems = !PlacingItems;
// Check if the player HAS items to place
if (PlacingItems)
{
bool HasItems = false;
foreach (ItemSlot IS in ItemSlots)
{
if (IS.ItemHeld)
{
HasItems = true;
break;
}
}
PlacingItems = HasItems;
}
}
if (Input.GetKeyDown(KeyCode.Escape))
{
PlacingItems = false;
}
if (PlacingItems)
{
BH.HasControl = false;
if (MaxSlots > 0)
{
ActiveItem = ItemSlots[CurrentSlot].GetItemRef();
if (ActiveItem != null)
{
PlacingScript.UpdatePlacement(ActiveItem, ActiveItem.transform.localScale.x);
if (ItemSlots[CurrentSlot].ItemHeld)
{
//PlacingScript.SetMesh(ActiveItem.GetMesh());
//PlacingTransform.localScale = ActiveItem.transform.localScale;
}
else
{
int initialInt = CurrentSlot;
while (ItemSlots[CurrentSlot].ItemHeld == false)
{
CurrentSlot++;
if (CurrentSlot == MaxSlots)
{
CurrentSlot = 0;
}
if (initialInt == CurrentSlot)
{
break;
}
}
ActiveItem = ItemSlots[CurrentSlot].GetItemRef();
if (ItemSlots[CurrentSlot].ItemHeld)
{
//PlacingScript.SetMesh(ActiveItem.GetMesh());
//PlacingTransform.localScale = ActiveItem.transform.localScale;
}
}
if (!ItemSlots[CurrentSlot].ItemHeld)
{
PlacingItems = false;
}
}
else
{
int initialInt = CurrentSlot;
while (ItemSlots[CurrentSlot].ItemHeld == false)
{
CurrentSlot++;
if (CurrentSlot == MaxSlots)
{
CurrentSlot = 0;
}
if (initialInt == CurrentSlot)
{
break;
}
}
ActiveItem = ItemSlots[CurrentSlot].GetItemRef();
}
}
//if (Input.GetKeyDown(KeyCode.E))
//{
// // Switch Item
// CurrentSlot++;
// if (CurrentSlot == MaxSlots)
// {
// CurrentSlot = 0;
// }
// if (ItemSlots[CurrentSlot].ItemHeld == false)
// {
// int initialInt = CurrentSlot;
// while (ItemSlots[CurrentSlot].ItemHeld == false)
// {
// CurrentSlot++;
// if (CurrentSlot == MaxSlots)
// {
// CurrentSlot = 0;
// }
// if (initialInt == CurrentSlot)
// {
// break;
// }
// }
// }
// if (MaxSlots > 0)
// {
// ActiveItem = ItemSlots[CurrentSlot].GetItemRef();
// PlacingScript.SetMesh(ActiveItem.GetMesh());
// PlacingTransform.localScale = ActiveItem.transform.localScale;
// }
//}
if (Input.GetKeyDown(KeyCode.Q))
{
// place item
bool canPlace = PlacingScript.UpdatePlacement(ActiveItem, ActiveItem.transform.localScale.x);
if (canPlace)
{
PVL.PlayAbility();
PlacingItems = false;
PlacingScript.PlaceItem();
//ActiveItem.transform.parent = null;
//ActiveItem.transform.position = PlacingScript.ObjectPosition;
//ActiveItem.transform.up = PlacingScript.ObjectNormal;
//ActiveItem.transform.forward = PlacingScript.OffsetDirection;
//CmdSpawnItem(ActiveItem.GetITemID(), PlacingScript.ItemWorldPosition, PlacingScript.ItemWorldRotation);
PV.RPC("RPC_SpawnItem", RpcTarget.MasterClient, ActiveItem.GetITemID(), PlacingScript.ItemWorldPosition, PlacingScript.ItemWorldRotation);
ItemSlots[CurrentSlot].RemoveItem();
}
}
}
else
{
BH.HasControl = true;
PlacingTransform.gameObject.SetActive(false);
}
if (PickedUpItem)
{
PickUpTimer += Time.deltaTime;
if (PickUpTimer >= PickUpTime)
{
PickUpTimer = 0;
PickedUpItem = false;
}
}
}
[PunRPC]
private void RPC_SpawnItem(string itemID, Vector3 Pos, Quaternion Rotation)
{
//GameObject temp = Instantiate(item);
//temp.transform.position = Pos;
//temp.transform.rotation = Rotation;
//if (temp != null)
//NetworkServer.Spawn(item);
GameObject temp = (PhotonNetwork.Instantiate(itemID, Pos, Rotation, 0, null));
temp.GetComponent<Item>().isPlacing = false;
//IM.AddItemToList(.GetComponent<Item>().ItemType);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "BlueRune" || other.gameObject.tag == "RedRune" || other.gameObject.tag == "GreenRune" || other.gameObject.tag == "Rune")
{
if (PickedUpItem == false)
{
Rune tempRune = other.GetComponent<Rune>();
foreach (ItemSlot IS in ItemSlots)
{
if (IS.ItemHeld == false)
{
PickedUpItem = true;
IS.SetItem(tempRune.GetItemPrefab());
break;
}
}
tempRune.TurnOffRune();
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Photon/PhotonRoom2.cs
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PhotonRoom2 : MonoBehaviourPunCallbacks, IInRoomCallbacks
{
public static PhotonRoom2 room;
private PhotonView PV;
public bool IsGameLoaded;
public int CurrentScene;
//player info
private Player[] photonPlayers;
public int PlayersInRoom;
public int MyNumberInRoom;
public int playerInGame;
//Delayed Start
private bool readyToCount;
private bool readyToStart;
public float startingTime;
private float lessThanMaxPlayers;
private float atMaxPlayer;
private float timeToStart;
private void Awake()
{
if (PhotonRoom2.room == null)
{
PhotonRoom2.room = this;
}
else
{
if (PhotonRoom2.room != this)
{
Destroy(PhotonRoom2.room.gameObject);
PhotonRoom2.room = this;
}
}
DontDestroyOnLoad(this.gameObject);
}
public override void OnEnable()
{
base.OnEnable();
PhotonNetwork.AddCallbackTarget(this);
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}
public override void OnDisable()
{
base.OnDisable();
PhotonNetwork.RemoveCallbackTarget(this);
SceneManager.sceneLoaded -= OnSceneFinishedLoading;
}
// Use this for initialization
void Start()
{
PV = GetComponent<PhotonView>();
readyToCount = false;
readyToStart = false;
lessThanMaxPlayers = startingTime;
atMaxPlayer = 6;
timeToStart = startingTime;
}
// Update is called once per frame
void Update()
{
if (MultiplayerSettings.MPS.DelayStart)
{
if (PlayersInRoom == 1)
{
RestartTimer();
}
if (!IsGameLoaded)
{
if (readyToStart)
{
atMaxPlayer -= Time.deltaTime;
lessThanMaxPlayers = atMaxPlayer;
timeToStart = atMaxPlayer;
}
else if (readyToCount)
{
bool AllPlayersReady = true;
foreach (Player P in PhotonNetwork.PlayerList)
{
if (!(bool)P.CustomProperties["ReadyInRoom"])
{
AllPlayersReady = false;
break;
}
}
if (AllPlayersReady)
{
lessThanMaxPlayers -= Time.deltaTime;
timeToStart = lessThanMaxPlayers;
}
else
{
timeToStart = 0;
}
}
Debug.Log("time to start :" + timeToStart);
if (timeToStart <= 0)
{
StartGame();
}
}
}
}
[PunRPC]
public void RPC_ChangeTeam(Player P)
{
}
public override void OnJoinedRoom()
{
Debug.Log("joined a room");
base.OnJoinedRoom();
photonPlayers = PhotonNetwork.PlayerList;
PlayersInRoom = photonPlayers.Length;
MyNumberInRoom = PlayersInRoom;
PhotonNetwork.NickName = MyNumberInRoom.ToString();
if (MultiplayerSettings.MPS.DelayStart)
{
Debug.Log("players in room out of max players possible(" + PlayersInRoom + ":" + MultiplayerSettings.MPS.MaxPlayers + ")");
if (PlayersInRoom > 1)
{
readyToCount = true;
}
if (PlayersInRoom == MultiplayerSettings.MPS.MaxPlayers)
{
bool AllPlayersReady = true;
foreach(Player P in PhotonNetwork.PlayerList)
{
if (!(bool)P.CustomProperties["ReadyInRoom"])
{
AllPlayersReady = false;
break;
}
}
readyToStart = AllPlayersReady;
if (!PhotonNetwork.IsMasterClient)
return;
PhotonNetwork.CurrentRoom.IsOpen = false;
}
}
else
{
//StartGame();
}
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
base.OnPlayerEnteredRoom(newPlayer);
Debug.Log("A new player has joined the room");
// Set Player Properties
ExitGames.Client.Photon.Hashtable CustomHash = new ExitGames.Client.Photon.Hashtable();
CustomHash.Add("Team", -1);
CustomHash.Add("ReadyInRoom", true);
CustomHash.Add("RoomID", PhotonNetwork.CurrentRoom.Name);
newPlayer.SetCustomProperties(CustomHash);
photonPlayers = PhotonNetwork.PlayerList;
PlayersInRoom++;
if (MultiplayerSettings.MPS.DelayStart)
{
if (PlayersInRoom > 1)
{
readyToCount = true;
}
if (PlayersInRoom == MultiplayerSettings.MPS.MaxPlayers)
{
readyToStart = true;
if (!PhotonNetwork.IsMasterClient)
return;
PhotonNetwork.CurrentRoom.IsOpen = false;
}
}
}
void StartGame()
{
IsGameLoaded = true;
if (!PhotonNetwork.IsMasterClient)
return;
if (MultiplayerSettings.MPS.DelayStart)
{
PhotonNetwork.CurrentRoom.IsOpen = false;
}
PhotonNetwork.LoadLevel(MultiplayerSettings.MPS.MultiplayerScene);
}
void RestartTimer()
{
lessThanMaxPlayers = startingTime;
timeToStart = startingTime;
atMaxPlayer = 6;
readyToCount = false;
readyToStart = false;
}
void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
CurrentScene = scene.buildIndex;
if (CurrentScene == MultiplayerSettings.MPS.MultiplayerScene)
{
IsGameLoaded = true;
if (MultiplayerSettings.MPS.DelayStart)
{
PV.RPC("RPC_LoadedGameScene", RpcTarget.MasterClient);
}
else
{
RPC_CreatePlayer();
}
}
}
[PunRPC]
private void RPC_LoadedGameScene()
{
playerInGame++;
if (playerInGame == PhotonNetwork.PlayerList.Length)
{
PV.RPC("RPC_CreatePlayer", RpcTarget.All);
}
}
[PunRPC]
void RPC_CreatePlayer()
{
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PhotonNetworkPlayer"), transform.position, Quaternion.identity, 0);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/BobberScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BobberScript : MonoBehaviour
{
[HideInInspector]
public bool Sinking = false;
[SerializeField]
private float speed = 10;
private Vector3 InitialPosition;
// Use this for initialization
void Start ()
{
InitialPosition = transform.localPosition;
}
// Update is called once per frame
void Update ()
{
if (!Sinking && transform.localPosition.y > -0.1f)
{
Debug.Log("floating");
// Move back to resting position
transform.Translate(0, -speed * Time.deltaTime, 0);
}
//if (transform.localPosition.y < 0)
//{
// Debug.Log("floating");
// transform.localPosition = new Vector3(transform.localPosition.x, 0.1f, transform.localPosition.z);
//}
// Check if balls go to neverland
if (transform.localPosition.x != InitialPosition.x || transform.localPosition.z != InitialPosition.z)
{
transform.localPosition = new Vector3(InitialPosition.x, transform.localPosition.y, InitialPosition.z);
}
}
public void OnTriggerStay(Collider c)
{
if(c.gameObject.tag == "Ground")
{
Debug.Log("Bobber Trigger");
Sinking = true;
// Move Up
transform.Translate(0, speed * Time.deltaTime, 0);
}
}
public void OnTriggerExit(Collider c)
{
if (c.gameObject.tag == "Ground")
{
Sinking = false;
Debug.Log("bobber exit");
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/SetBallLookAtVcamVar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class SetBallLookAtVcamVar : MonoBehaviour {
private Transform lookatBall;
private CinemachineVirtualCamera vCam;
// Use this for initialization
void Start () {
vCam = transform.GetComponent<CinemachineVirtualCamera>();
lookatBall = GameObject.FindGameObjectWithTag("Ball").transform;
vCam.m_LookAt = lookatBall;
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/TargetVisual.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TargetVisual : MonoBehaviour {
//[SerializeField]
//private Text textTarget = null;
[SerializeField]
private RawImage targetReticle = null;
[SerializeField]
private PlayerSoftlockPassSight softLockScript = null;
[SerializeField]
private Camera thisPlayerCam = null;
[SerializeField]
private BallHandling ballHandlingScript = null;
// Use this for initialization
void Start () {
//ballHandlingScript = GetComponentInParent<BallHandling>();
}
// Update is called once per frame
void Update () {
//Debug.Log("ballHandle hold" + ballHandlingScript.canHold);
// Debug.Log("softLockScript.target: " + softLockScript.target);
if (softLockScript.target != null && ballHandlingScript.ball != null)
{
//Debug.Log("TargetReticle is active");
if(targetReticle.enabled == false)
{
targetReticle.enabled = true;
}
Vector3 targetPos = thisPlayerCam.WorldToScreenPoint(new Vector3(softLockScript.targetPosition.x,
softLockScript.targetPosition.y, softLockScript.targetPosition.z));
//textTarget.transform.position = targetPos;
targetReticle.transform.position = targetPos;
}
else
{
//Debug.Log("TargetReticle is NOT active");
targetReticle.enabled = false;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerInTeamUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerInTeamUI : MonoBehaviour {
[SerializeField]
private NetPlayer N_Player;
[SerializeField]
private Text[] PlayerNameList;
private NetPlayer[] PlayerList = null;
private List<NetPlayer> PlayersOnTeam = new List<NetPlayer>();
[SerializeField]
private int TeamNum = 0;
[SerializeField]
private int MaxPlayers = 4;
[SerializeField]
private GameObject IsFullImage;
// Use this for initialization
void Start () {
if (MaxPlayers > 8)
{
Debug.LogWarning("Can't have more then 8 players on a team");
MaxPlayers = 8;
}
}
// Update is called once per frame
void Update () {
N_Player.SetPlayerList();
PlayerList = N_Player.PlayerList;
FindPlayersOnTeam();
UpdateListOfPlayers();
}
private void FindPlayersOnTeam()
{
if (PlayerList != null)
{
foreach (NetPlayer p in PlayerList)
{
if (p.GetTeamNum() == TeamNum && !PlayersOnTeam.Contains(p))
{
if (PlayersOnTeam.Count < MaxPlayers)
{
PlayersOnTeam.Add(p);
}
else
{
p.RPC_ChangeTeam(0);
}
}
if (p.GetTeamNum() != TeamNum && PlayersOnTeam.Contains(p))
{
PlayersOnTeam.Remove(p);
}
}
}
}
private void UpdateListOfPlayers()
{
foreach(Text t in PlayerNameList)
{
t.text = "";
}
for(int i = 0; i < PlayersOnTeam.Count; i++)
{
PlayerNameList[i].text = PlayersOnTeam[i].name;
}
if (IsFullImage != null)
{
if (PlayersOnTeam.Count >= MaxPlayers)
{
IsFullImage.SetActive(true);
}
else
{
IsFullImage.SetActive(false);
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Thrusters.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Thrusters : MonoBehaviour
{
[SerializeField]
private hoverBoardScript HBS;
[SerializeField]
private float thisSpeed;
[SerializeField]
private ParticleSystem[] lowThrust;
[SerializeField]
private ParticleSystem[] midThrust;
[SerializeField]
private ParticleSystem[] highThrust;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
thisSpeed = HBS.Speed;
if(thisSpeed < 20)
{
playLowThrust();
}
if(thisSpeed < 20 && thisSpeed < 30)
{
playMidThrust();
}
if(thisSpeed < 30)
{
playHighThrust();
}
}
public void playLowThrust()
{
foreach (ParticleSystem PS in lowThrust)
{
PS.Play();
}
}
public void playMidThrust()
{
foreach (ParticleSystem PS in midThrust)
{
PS.Play();
}
}
public void playHighThrust()
{
foreach (ParticleSystem PS in highThrust)
{
PS.Play();
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Abilities.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Abilities : MonoBehaviour
{
[SerializeField]
private Rigidbody Rb;
[SerializeField]
private GameObject SpeedStrip;
[SerializeField]
private float CurrentEnergy;
private float SpeedStripCost = 33;
private float MaxEnergy = 100;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(Rb.velocity.z > 1 && CurrentEnergy < MaxEnergy)
{
CurrentEnergy += Time.deltaTime * 2;
}
if(CurrentEnergy > MaxEnergy)
{
CurrentEnergy = MaxEnergy;
}
if(Input.GetKeyDown(KeyCode.C) && CurrentEnergy >= SpeedStripCost)
{
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/RoundManager.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class RoundManager : MonoBehaviour {
[SerializeField]
private float maxRoundTime;
private float roundTime;
private bool allowTime;
[SerializeField]
private Text textTime;
private PhotonView PV;
[SerializeField]
private float maxIntroTime;
private float introTimer;
private bool allowCountDown;
[SerializeField]
private Text textCountDown;
[SerializeField]
private float maxRoundNumber = 3;
private float roundNumber = 0;
private GameObject ball;
//private GameObject net;
private netSpawner nSPawner;
private ballHandler bHandler;
[SerializeField]
private GameObject ballSpawnLocation;
[SerializeField]
private GameObject drawGameText;
[SerializeField]
private GameObject winGameText;
[SerializeField]
private GameObject loseGameText;
private Scoring scoring;
[SerializeField]
private Transform[] spawnLocationsTeam1;
[SerializeField]
private Transform[] spawnLocationsTeam2;
[SerializeField]
private GameObject[] objectGroup_Round1;
[SerializeField]
private GameObject[] objectGroup_Round2;
[SerializeField]
private GameObject[] objectGroup_Round3;
private Transform localPlayer;
[SerializeField]
private GameObject readyObject;
[SerializeField]
private GameObject goObject;
[SerializeField]
private hoverBoardScript HBS;
private DietySound DS;
private PlayerVoiceLine PVL;
private void Start()
{
PV = GetComponent<PhotonView>();
nSPawner = FindObjectOfType<netSpawner>();
bHandler = FindObjectOfType<ballHandler>();
scoring = FindObjectOfType<Scoring>();
DS = FindObjectOfType<DietySound>();
PVL = FindObjectOfType<PlayerVoiceLine>();
// set round 1 level layout
for (int i = objectGroup_Round1.Length - 1; i >= 0; i--)
{
objectGroup_Round1[i].SetActive(true);
}
for (int i = objectGroup_Round2.Length - 1; i >= 0; i--)
{
objectGroup_Round2[i].SetActive(false);
}
for (int i = objectGroup_Round3.Length - 1; i >= 0; i--)
{
objectGroup_Round3[i].SetActive(false);
}
readyObject.SetActive(true);
Invoke("GO", 2);
}
public void AllowTime(bool allow)
{
allowTime = allow;
}
public void ResetTime()
{
roundTime = maxRoundTime;
}
public void ResetIntroTimer()
{
introTimer = maxIntroTime;
}
public void BeginCountdown()
{
PV.RPC("RPC_BeginCountdown", RpcTarget.AllBuffered);
}
[PunRPC]
public void RPC_BeginCountdown()
{
ball = FindObjectOfType<Ball>().gameObject;
ball.GetComponent<Ball>().hasBeenPickedUpBefore = true;
//Debug.Log("net: " + net.name);
nSPawner.CallMoveNetUp();
ResetIntroTimer();
ResetTime();
allowCountDown = true;
//DS.PlayDietyNetSpawn();
}
private void BeginMatch()
{
PV.RPC("RPC_BeginMatch", RpcTarget.AllBuffered);
}
[PunRPC]
public void RPC_BeginMatch()
{
ResetTime();
AllowTime(true);
}
// Update is called once per frame
void Update () {
if(!PVL)
{
PVL = FindObjectOfType<PlayerVoiceLine>();
}
if(scoring == null)
{
scoring = FindObjectOfType<Scoring>();
}
if(allowTime)
{
if(roundTime > 0)
{
roundTime -= Time.deltaTime;
textTime.text = Mathf.Ceil(roundTime).ToString();
}
else
{
//if (PhotonNetwork.IsMasterClient)
//{
NextRound();
allowTime = false;
//
}
}
if(allowCountDown)
{
introTimer -= Time.deltaTime;
textCountDown.text = Mathf.Ceil(introTimer).ToString();
if(introTimer <= 0)
{
DS.PlayDietyNetSpawn();
allowCountDown = false;
BeginMatch();
textCountDown.text = "";
}
}
}
public void NextRound()
{
PV.RPC("RPC_ResetRound", RpcTarget.All);
}
/* One end
* one repositioning*/
[PunRPC]
public void RPC_ResetRound()
{
// Debug.Log("Reseting round");
roundNumber++;
if(roundNumber >= maxRoundNumber)
{
// Debug.Log("End");
PV.RPC("RPC_End", RpcTarget.All);
}
else
{
if (HBS == null)
{
//Debug.Log("HBS = null");
hoverBoardScript[] hbsArray = FindObjectsOfType(typeof(hoverBoardScript)) as hoverBoardScript[];
for (int i = 0; i < hbsArray.Length; i++)
{
if (hbsArray[i].enabled)
{
Debug.Log("found one hbs");
HBS = hbsArray[i];
if (HBS != null)
{
Debug.Log("hbs has con is false");
HBS.roundStarted = false;
//HBS.GetComponent<Rigidbody>().velocity = Vector3.zero;
//HBS.Speed = 0;
//HBS.m_currThrust = 0;
//HBS.m_currTurn = 0;
}
}
}
}
else
{
// gbs disable ability to move
Debug.Log("disallow board move");
HBS.roundStarted = false;
HBS.GetComponent<Rigidbody>().velocity = Vector3.zero;
HBS.Speed = 0;
HBS.m_currThrust = 0;
}
//roundCallText.text = "Round " + (roundNumber + 1);
// round 2
if (roundNumber == 1)
{
for (int i = objectGroup_Round1.Length - 1; i >= 0; i--)
{
objectGroup_Round1[i].SetActive(false);
}
for (int i = objectGroup_Round2.Length - 1; i >= 0; i--)
{
objectGroup_Round2[i].SetActive(true);
}
for (int i = objectGroup_Round3.Length - 1; i >= 0; i--)
{
objectGroup_Round3[i].SetActive(false);
}
}
// round 3
if (roundNumber == 2)
{
for (int i = objectGroup_Round1.Length - 1; i >= 0; i--)
{
objectGroup_Round1[i].SetActive(false);
}
for (int i = objectGroup_Round2.Length - 1; i >= 0; i--)
{
objectGroup_Round2[i].SetActive(false);
}
for (int i = objectGroup_Round3.Length - 1; i >= 0; i--)
{
objectGroup_Round3[i].SetActive(true);
}
}
// Debug.Log("Destroy ball");
PhotonNetwork.Destroy(ball.gameObject);
ball = null;
bHandler.SpawnBall();
ball = FindObjectOfType<Ball>().gameObject;
nSPawner.CallMoveNetDown();
textTime.text = "";
// Debug.Log("ResetPos");
if(PhotonNetwork.IsMasterClient)
{
PV.RPC("ResetPlayerPositions", RpcTarget.All);
}
}
}
[PunRPC]
public void RPC_End()
{
// Debug.Log("End_RPC");
if (scoring == null)
{
scoring = FindObjectOfType<Scoring>();
}
if (scoring != null)
{
if (scoring.team1Score > scoring.team2Score)
{
ShowTheWinner(1);
}
else if (scoring.team1Score < scoring.team2Score)
{
ShowTheWinner(2);
}
else
{
ShowTheWinner(0);
}
}
}
public void ShowTheWinner(int teamNum)
{
// Debug.Log("show the winner");
Transform localPlayer = null;
foreach (GameObject player in GameObject.FindGameObjectsWithTag("Team 1"))
{
if (player.GetComponent<hoverBoardScript>().isActiveAndEnabled)
{
// Debug.Log(player.name + " is the local player");
localPlayer = player.transform;
}
}
if (localPlayer == null)
{
foreach (GameObject player in GameObject.FindGameObjectsWithTag("Team 2"))
{
if (player.GetComponent<hoverBoardScript>().isActiveAndEnabled)
{
// Debug.Log(player.name + " is the local player");
localPlayer = player.transform;
}
}
}
if (teamNum == 0)
{
drawGameText.SetActive(true);
}
else if (localPlayer.GetComponent<PlayerColor>().TeamNum == teamNum)
{
// win
if(PVL)
{
PVL.PlayWin();
}
winGameText.SetActive(true);
}
else
{
// lose
if(PVL)
{
PVL.PlaydietyLoose();
}
loseGameText.SetActive(true);
}
Invoke("ReturnToMenu", 5);
}
public void ReturnToMenu()
{
//Debug.Log("Return to Menu");
//PhotonNetwork.Disconnect();
//PhotonNetwork.LoadLevel(0);
StartCoroutine(DisconnectAndLoad());
}
IEnumerator DisconnectAndLoad()
{
PhotonNetwork.Disconnect();
while (PhotonNetwork.IsConnected)
yield return null;
SceneManager.LoadScene(0);
}
//[SerializeField]
private List<Transform> team1Players = new List<Transform>();
//[SerializeField]
private List<Transform> team2Players = new List<Transform>();
[PunRPC]
public void ResetPlayerPositions()
{
foreach (GameObject team1 in GameObject.FindGameObjectsWithTag("Team 1"))
{
team1Players.Add(team1.transform);
}
foreach (GameObject team2 in GameObject.FindGameObjectsWithTag("Team 2"))
{
team2Players.Add(team2.transform);
}
for (int i = 0; i < team1Players.Count; i++)
{
team1Players[i].position = spawnLocationsTeam1[i].position;
team1Players[i].rotation = spawnLocationsTeam1[i].rotation;
//if(localPlayer == null)
//{
// localPlayer = GameObject.FindObjectOfType<CameraModeMedium>().transform;
//}
//if(team1Players[i].GetComponent<PhotonView>().IsMine)
//{
// //Debug.Log("ALeratatatatatat");
// localPlayer.eulerAngles = Vector3.zero;
// localPlayer.GetComponent<CameraRotation>().GrabRot();
//}
}
for (int i = team1Players.Count - 1; i >= 0; i--)
{
team1Players.RemoveAt(i);
}
for (int i = 0; i < team2Players.Count; i++)
{
team2Players[i].position = spawnLocationsTeam2[i].position;
team2Players[i].rotation = spawnLocationsTeam2[i].rotation;
//if (localPlayer == null)
//{
// localPlayer = GameObject.FindObjectOfType<CameraModeMedium>().transform;
//}
//if (team2Players[i].GetComponent<PhotonView>().IsMine)
//{
// // Debug.Log("ALeratatatatatat");
// localPlayer.eulerAngles = new Vector3(0, 180, 0);
// localPlayer.GetComponent<CameraRotation>().GrabRot();
//}
}
for (int i = team2Players.Count - 1; i >= 0; i--)
{
team2Players.RemoveAt(i);
}
Invoke("GO", 2);
}
private void GO()
{
DS.PlayDietyWelcome();
readyObject.SetActive(false);
goObject.SetActive(true);
// free players
if (HBS == null)
{
// Debug.Log("HBS = null");
hoverBoardScript[] hbsArray = FindObjectsOfType(typeof(hoverBoardScript)) as hoverBoardScript[];
for (int i = 0; i < hbsArray.Length; i++)
{
if (hbsArray[i].enabled)
{
// Debug.Log("found one hbs");
HBS = hbsArray[i];
if (HBS != null)
{
//Debug.Log("hbs has con is true");
HBS.roundStarted = true;
}
}
}
}
else
{
// hbs enable ability to move
//Debug.Log("allow board move");
HBS.roundStarted = true;
}
Invoke("EraseRoundCall", 1);
}
private void EraseRoundCall()
{
goObject.SetActive(false);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/VirtualCamFOVTransition.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class VirtualCamFOVTransition : MonoBehaviour {
[SerializeField]
private Camera cameraObject;
[SerializeField]
private hoverBoardScript hbs;
private float currentNumber = 0;
[SerializeField]
private float deadZone;
[SerializeField]
private float fovTransiSpeed;
[SerializeField]
private float minFOV = 40;
[SerializeField]
private float maxFOV = 60;
[SerializeField]
private float boostMultiplication = 2;
private void Start()
{
if (cameraObject == null)
{
cameraObject = transform.GetComponent<Camera>();
}
currentNumber = minFOV;
}
// Update is called once per frame
void Update()
{
//float tempNumberSet = Mathf.Clamp((((hbs.Speed) - 23) / 100 * 50) + 40, 40, 60);
float tempNumberSet = Mathf.Clamp((((hbs.Speed) - 23) * boostMultiplication) + minFOV, minFOV, maxFOV);
// Debug.Log("tempNumberSet: " + tempNumberSet);
//Debug.Log("tempNumberSet: " + tempNumberSet + " greater: " + (tempNumberSet - deadZone));
if (currentNumber < tempNumberSet - deadZone)
{
currentNumber += Time.deltaTime * fovTransiSpeed;
}
else if (currentNumber > tempNumberSet + deadZone)
{
currentNumber -= Time.deltaTime * fovTransiSpeed;
}
// Debug.Log("current number: " + currentNumber);
if (cameraObject != null)
cameraObject.fieldOfView = Mathf.Clamp(currentNumber, 40, 60);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerSoundSettings.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerSoundSettings : MonoBehaviour {
public float musicVol;
public float SoundFXVol;
public float VoiceVol;
public Slider musicSlider;
public Slider SoundFXSlider;
public Slider voiceSlider;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(musicSlider != null)
{ musicVol = musicSlider.value; }
if (SoundFXSlider != null)
{ SoundFXVol = SoundFXSlider.value; }
if(voiceSlider != null)
{ VoiceVol = voiceSlider.value; }
}
}
<file_sep>/CapstonePowerPlay/Assets/Ragdoll.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Ragdoll : NetworkBehaviour
{
[SerializeField]
private ParticleSystem PS;
[SerializeField]
private ParticleSystem PS1;
void Awake ()
{
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.O))
{
CmdPlayGetUpEffects();
}
}
[Command]
public void CmdPlayGetUpEffects()
{
PS.Play();
PS1.Play();
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/LookAtPostionFollow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtPostionFollow : MonoBehaviour {
// Use this for initialization
[SerializeField]
private Transform lookatPoint;
[SerializeField]
private Transform player;
[SerializeField]
private string layerMask;
//[SerializeField]
//private float speedTransition;
[SerializeField]
CameraKeepOnPosition ckp;
//[SerializeField]
private PlayerColor playerColour;
//void Start () {
// //UnParent();
// }
public void UnParent()
{
// Debug.Log("Unparent 1: LookAtPositionFollow");
playerColour = gameObject.GetComponentInParent<PlayerColor>();
transform.parent = null;
ckp.UnParent();
}
// Update is called once per frame
void Update () {
if (transform.parent == null && lookatPoint != null)
{
if (transform.childCount == 0)
{
float distance = (lookatPoint.position - transform.position).magnitude;
transform.position = lookatPoint.position;
//transform.position = Vector3.MoveTowards(transform.position, lookatPoint.position, speedTransation * distance);
//Debug.Log("layerMask: " + layerMask);
RaycastHit hit;
if (Physics.Raycast(player.position, player.TransformDirection(Vector3.down), out hit, Mathf.Infinity))
{
// Debug.DrawRay(player.position, player.TransformDirection(Vector3.down));
if (hit.transform.gameObject.layer == LayerMask.NameToLayer(layerMask))
{
//// Debug.Log("Hit object with same layer");
Vector3 inverseTPoint = transform.InverseTransformPoint(transform.position + hit.normal);
float angleX = Mathf.Atan2(inverseTPoint.z, inverseTPoint.y) * Mathf.Rad2Deg;
transform.Rotate(angleX, 0, 0);
inverseTPoint = transform.InverseTransformPoint(transform.position + hit.normal);
float angleZ = -Mathf.Atan2(inverseTPoint.x, inverseTPoint.y) * Mathf.Rad2Deg;
transform.Rotate(0, 0, angleZ);
}
}
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ResetBallState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ResetBallState : NetworkBehaviour {
[SerializeField]
private Ball ball;
public BallHandling PlayerHolding = null;
// Update is called once per frame
void Update () {
if (PlayerHolding != null)
{
if (PlayerHolding.ball == null)
{
PlayerHolding.ball = ball;
}
}
}
[Command]
public void CmdSetPlayerHolding(GameObject bhObject)
{
RpcSetPlayerHolding(bhObject);
}
[ClientRpc]
public void RpcSetPlayerHolding(GameObject bhObject)
{
BallHandling bh = bhObject.GetComponent<BallHandling>();
PlayerHolding = bh;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerNameTag.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
public class PlayerNameTag : MonoBehaviour {
[SerializeField]
private float OneTimeScaleDistance = 5;
[SerializeField]
private TextMesh TM;
[SerializeField]
private PhotonView PV;
[SerializeField]
private bool KeepScale = false;
private Transform LocalPlayerObject;
private bool Started = false;
private float distance;
private float scale;
public void ForceStart()
{
if (PV.IsMine)
{
PlayerNameTag[] PlayerList = FindObjectsOfType<PlayerNameTag>();
foreach(PlayerNameTag PNT in PlayerList)
{
PNT.SetLocalPlayer(gameObject.transform);
}
Started = true;
}
}
private void Update()
{
if (Started)
{
if (KeepScale)
{
distance = (LocalPlayerObject.position - transform.position).magnitude;
scale = distance > OneTimeScaleDistance ? distance / OneTimeScaleDistance
: 1;
transform.localScale = new Vector3(scale, scale, scale);
}
transform.LookAt(-LocalPlayerObject.position);
}
}
public void SetLocalPlayer(Transform local)
{
LocalPlayerObject = local;
Started = true;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Player_Camera_ProxyFade.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Camera_ProxyFade : MonoBehaviour {
[SerializeField]
private Transform playerTransform = null;
[SerializeField]
private Transform cameraTransform = null;
[SerializeField]
private float maxDistance = 1.5f;
[SerializeField]
private Renderer playerRenderer = null;
[SerializeField]
private Material fadingMaterial = null;
[SerializeField]
private Material standardMaterial = null;
[SerializeField]
private float distanceFadeOffSet = 0.0f;
// can only fade mats if their renderin mode is eitehr fade or transparent
// change the mat to an exact copy of the mat with the only rendering mode being change back and fourth between Opaque and Fade/Transperant
// Update is called once per frame
void Update () {
//Debug.Log("distance between camera and obj: " + (cameraTransform.position - playerTransform.position).magnitude);
float distance = (cameraTransform.position - playerTransform.position).magnitude;
if (playerRenderer.material.color.a < 1)
{
Debug.Log("Within range");
playerRenderer.material = fadingMaterial;
}
else
{
Debug.Log("Out of range");
playerRenderer.material = standardMaterial;
}
playerRenderer.material.color = new Color(playerRenderer.material.color.r, playerRenderer.material.color.g, playerRenderer.material.color.b,/**/ Mathf.Clamp((distance / maxDistance) - distanceFadeOffSet, 0, 1)/**/);
Debug.Log("mat a: " + playerRenderer.material.color.a);
// change this to see the distance between player and their camera
///
//if(Input.GetKeyDown(KeyCode.Q))
//{
// Debug.Log("Q has been pressed");
// // set the material to fade
// playerRenderer.material = new Material(Shader.Find("Fade"));
//}
//if(Input.GetKey(KeyCode.R))
//{
// Debug.Log("R is being pressed");
// FadeOut();
//}
//if(Input.GetKey(KeyCode.T))
//{
// Debug.Log("T is being pressed");
// FadeIn();
//}
}
private void FadeOut()
{
if(playerRenderer.material.color.a>0)
{
Debug.Log("fading");
playerRenderer.material.color = new Color(playerRenderer.material.color.r, playerRenderer.material.color.g, playerRenderer.material.color.b, playerRenderer.material.color.a - Time.deltaTime / 2);
}
Debug.Log("playerRenderer.material.color.a : " + playerRenderer.material.color.a);
}
private void FadeIn()
{
if (playerRenderer.material.color.a < 1)
{
Debug.Log("fading");
playerRenderer.material.color = new Color(playerRenderer.material.color.r, playerRenderer.material.color.g, playerRenderer.material.color.b, playerRenderer.material.color.a + Time.deltaTime / 2);
}
Debug.Log("playerRenderer.material.color.a : " + playerRenderer.material.color.a);
}
}
<file_sep>/CapstonePowerPlay/Assets/DoorScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class DoorScript : NetworkBehaviour {
RunePickups picks;
Animator anim;
public bool doorOpen;
public GameObject myplayer;
// Use this for initialization
void Start () {
doorOpen = false;
anim = GetComponent<Animator>();
// picks = GetComponent<RunePickups>();
}
// Update is called once per frame
void Update () {
if(doorOpen)
{
CmdOpenDoor();
}
// if (!myplayer)
// {
// myplayer = GameObject.FindGameObjectWithTag("Team 1");
// //picks = GetComponent<RunePickups>();
// }
// else
// {
// picks = GetComponent<RunePickups>();
// }
//if(picks.Opendoor)
// {
// Debug.Log("DoorOpening");
// anim.SetBool("RuneMatch", true);
// }
}
[Command]
public void CmdOpenDoor()
{
RpcOpenDoor();
}
[ClientRpc]
public void RpcOpenDoor()
{
anim.SetBool("RuneMatch", true);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/netSpawner.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class netSpawner : MonoBehaviour
{
[SerializeField]
private Transform netSpawn;
[SerializeField]
private GameObject netPrefab;
private PhotonView PV;
private GameObject net;
[SerializeField]
private bool moveNetUp = false;
[SerializeField]
private float netHeight;
[SerializeField]
private float acceleration;
private float releaseNetTime;
// Use this for initialization
void Start ()
{
PV = GetComponent<PhotonView>();
CallSpawnNet();
}
private void CallSpawnNet()
{
//if(PhotonNetwork.IsMasterClient)
// PV.RPC("RPC_SpawnNet", RpcTarget.MasterClient);
SpawnNet();
}
// [PunRPC]
public void SpawnNet()
{
//Debug.Log("SpawnNet");
if (PhotonNetwork.IsMasterClient)
{
net = PhotonNetwork.InstantiateSceneObject("NetObject", netSpawn.position, netSpawn.rotation);
}
}
public void CallMoveNetUp()
{
PV.RPC("RPC_MoveNetUp", RpcTarget.AllBuffered);
}
[PunRPC]
public void RPC_MoveNetUp()
{
if (PhotonNetwork.IsMasterClient)
{
moveNetUp = true;
releaseNetTime = 2;
}
}
private void Update()
{
if (net != null)
{
if (moveNetUp)
{
if (releaseNetTime <= 0)
{
net.transform.position += new Vector3(0, (netHeight - net.transform.position.y) / acceleration, 0);
if (net.transform.position.y >= 67)
{
moveNetUp = false;
}
}
else
{
releaseNetTime -= Time.deltaTime;
}
}
}
}
public void CallMoveNetDown()
{
PV.RPC("RPC_MoveNetDown", RpcTarget.AllBuffered);
}
[PunRPC]
public void RPC_MoveNetDown()
{
if (PhotonNetwork.IsMasterClient)
{
moveNetUp = false;
net.transform.position = new Vector3(net.transform.position.x, 45, net.transform.position.z);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Scoring.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Scoring : MonoBehaviour
{
[SerializeField]
private Text scoreDisplay;
[SerializeField]
public int team1Score = 0;
[SerializeField]
public int team2Score = 0;
private bool scored = false;
[SerializeField]
private float maxTimeUntilScoreReset;
private float timeUntilScoreReset;
private ScoreTracker sTracker;
[SerializeField]
private Transform localPlayer;
//effects//
[SerializeField]
private ParticleSystem GoalEffects;
private AudioSource Src;
public AudioClip Score;
private PlayerSoundSettings PS;
private PhotonView PV;
private void Start()
{
PS = FindObjectOfType<PlayerSoundSettings>();
PV = GetComponent<PhotonView>();
Src = GetComponent<AudioSource>();
Src.volume = PS.VoiceVol;
sTracker = GameObject.FindGameObjectWithTag("ScoreUI").GetComponent<ScoreTracker>();
GoalEffects = GetComponentInChildren<ParticleSystem>();
if (localPlayer == null)
{
SortScoreBoard();
}
HandleScoreCanvas();
}
public void HandleScoreCanvas()
{
for (int i = 0; i < sTracker.scoreCanvases.Length; i++)
{
sTracker.t1Scoring[i].text = team1Score.ToString();
sTracker.t2Scoring[i].text = team2Score.ToString();
}
}
[PunRPC]
public void RPC_Team1Score()
{
PlayGoaleffect();
Team1Score();
}
public void Team1Score()
{
//Debug.Log("scored 1");
team1Score++;
HandleScoreCanvas();
}
public void PlayGoaleffect()
{
GoalEffects.Play();
}
[PunRPC]
public void RPC_Team2Score()
{
// Debug.Log("scored 2");
PlayGoaleffect();
Team2Score();
}
public void Team2Score()
{
team2Score++;
HandleScoreCanvas();
}
private void Update()
{
if(scored)
{
timeUntilScoreReset -= Time.deltaTime;
if(timeUntilScoreReset <= 0)
{
scored = false;
}
}
if (localPlayer == null)
{
SortScoreBoard();
}
}
private void SortScoreBoard()
{
foreach (GameObject player in GameObject.FindGameObjectsWithTag("Team 1"))
{
if (player.GetComponent<hoverBoardScript>().isActiveAndEnabled)
{
//Debug.Log(player.name + " is the local player");
localPlayer = player.transform;
//if (player.GetComponent<PlayerColor>().TeamNum == 1)
//{
// for (int i = 0; i < sTracker.scoreCanvases.Length; i++)
// {
// // sTracker.t1Scoring[i].color = Color.green;
// //sTracker.t2Scoring[i].color = Color.red;
// }
//}
return;
}
}
foreach (GameObject player in GameObject.FindGameObjectsWithTag("Team 2"))
{
if (player.GetComponent<hoverBoardScript>().isActiveAndEnabled)
{
localPlayer = player.transform;
if (player.GetComponent<PlayerColor>().TeamNum == 2)
{
//Debug.Log("TeamNum = 2");
for (int i = 0; i < sTracker.scoreCanvases.Length; i++)
{
//sTracker.t1Scoring[i].color = Color.red;
float tempX = sTracker.t1Scoring[i].rectTransform.position.x;
sTracker.t1Scoring[i].rectTransform.position = sTracker.t2Scoring[i].rectTransform.position;
//sTracker.t2Scoring[i].color = Color.green;
sTracker.t2Scoring[i].rectTransform.position = new Vector3(tempX, sTracker.t1Scoring[i].rectTransform.position.y, sTracker.t1Scoring[i].rectTransform.position.z);
}
for (int i = 0; i < sTracker.t1Logo.Count; i++)
{
// Debug.Log("stracker check n." + i);
float tempX = sTracker.t1Logo[i].position.x;
sTracker.t1Logo[i].position = sTracker.t2Logo[i].position;
sTracker.t2Logo[i].position = new Vector3(tempX, sTracker.t2Logo[i].position.y, sTracker.t2Logo[i].position.z);
}
}
return;
}
}
}
private void OnTriggerEnter(Collider c)
{
if (PhotonNetwork.IsMasterClient)
{
if (c.gameObject.tag == "Ball_Score_Trigger" && !scored)
{
if (c.transform.parent.GetComponent<Ball>().WhoTossedTheBall != null)
{
int teamScored = c.transform.parent.GetComponent<Ball>().WhoTossedTheBall.GetComponent<PlayerColor>().TeamNum;
//Debug.Log("Ball has triggered the net");
if (teamScored == 1)
{
Src.PlayOneShot(Score, 1f);
//Debug.Log("Team1 Scored!");
//CmdTeam1Score();
PV.RPC("RPC_Team1Score", RpcTarget.AllBuffered);
timeUntilScoreReset = maxTimeUntilScoreReset;
scored = true;
}
else if (teamScored == 2)
{
Src.PlayOneShot(Score, 1f);
//Debug.Log("Team2 Scored!");
//CmdTeam2Score();
PV.RPC("RPC_Team2Score", RpcTarget.AllBuffered);
timeUntilScoreReset = maxTimeUntilScoreReset;
scored = true;
}
}
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/HoverBoardSounds.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HoverBoardSounds : MonoBehaviour {
private AudioSource Src;
public AudioClip Hover;
private hoverBoardScript HV;
private PlayerSoundSettings PS;
public float HovVol = 0.3f;
private float minPitch = 1f;
private float maxPitch = 2f;
// Use this for initialization
void Start () {
HV = FindObjectOfType<hoverBoardScript>();
Src = GetComponent<AudioSource>();
PS = FindObjectOfType<PlayerSoundSettings>();
if (PS)
HovVol = PS.SoundFXVol;
else
HovVol = 0.1f;
}
// Update is called once per frame
void Update () {
Src.volume = HovVol;
if (HV.Speed < 10)
Src.pitch = minPitch;
else
Src.pitch = maxPitch;
}
public void SetVol(float vol)
{
HovVol = vol;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/RuneSpawnManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class RuneSpawnManager : MonoBehaviour {
[SerializeField]
private List<RuneSpawnQueue> RuneSpawns = new List<RuneSpawnQueue>();
// Use this for initialization
void Start () {
if (PhotonNetwork.IsMasterClient)
{
foreach(RuneSpawnQueue RSQ in RuneSpawns)
{
RSQ.SpawnRune();
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Placing.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Placing : MonoBehaviour {
// Pre set variables
[SerializeField]
private Material PlacingMaterialRed;
[SerializeField]
private Material PlacingMaterialBlue;
[SerializeField]
private Transform LookDirection;
[SerializeField]
private Transform LookDirectionOffset;
[SerializeField]
private Transform ItemLookDirection;
[SerializeField]
private float PlaceDistance = 5;
[SerializeField]
private LayerMask PlaceLayers;
[SerializeField]
private MeshFilter ChildMesh;
[SerializeField]
private MeshRenderer ChildMeshRenderer;
[SerializeField]
private Transform ChildTransform;
[SerializeField]
private Transform MeshTransform;
[SerializeField]
private BoxCollider ChildCollider;
[SerializeField]
private PlacingTrigger PT;
// Post set variables
private Mesh ObjectMesh = null;
// Running variables
private bool MeshSet = false;
private RaycastHit LookHit;
private RaycastHit LookHitOffset;
[HideInInspector]
public Vector3 ObjectPosition = Vector3.zero;
[HideInInspector]
public Vector3 ObjectNormal = Vector3.zero;
[HideInInspector]
public Vector3 TurnOffset = Vector3.zero;
[HideInInspector]
public Vector3 OffsetDirection = Vector3.zero;
[HideInInspector]
public Vector3 ItemWorldPosition = Vector3.zero;
[HideInInspector]
public Quaternion ItemWorldRotation = Quaternion.identity;
[SerializeField]
private float ObjectTurnOffset = 90;
private Item PlaceholderItem = null;
public void ChangePlaceDistance(float dist)
{
PlaceDistance = dist;
}
public void TurnSettingBoolOff()
{
MeshSet = false;
}
public void SetMesh(Mesh meshObject)
{
ObjectMesh = meshObject;
if (ObjectMesh != null)
MeshSet = true;
}
public Vector3 GetPlacePosition()
{
return ChildTransform.position;
}
public void PlaceItem()
{
Destroy(PlaceholderItem.gameObject);
PlaceholderItem = null;
}
public bool UpdatePlacement(Item item, float MeshScale = 1)
{
if (Physics.Raycast(LookDirection.position, LookDirection.forward, out LookHit, PlaceDistance, PlaceLayers))
{
if (Physics.Raycast(LookDirectionOffset.position, LookDirectionOffset.forward, out LookHitOffset, PlaceDistance, PlaceLayers))
{
// Reset the trigger
//PT.ResetPT();
Debug.DrawRay(LookDirection.position, LookDirection.forward * LookHit.distance, Color.blue);
Debug.DrawRay(LookDirectionOffset.position, LookDirectionOffset.forward * LookHitOffset.distance, Color.green);
Debug.DrawLine(LookHit.point, LookHitOffset.point, Color.yellow);
Debug.DrawRay(ObjectPosition, ObjectNormal, Color.black);
// Find where you are looking
ObjectPosition = LookHit.point;
ObjectNormal = LookHit.normal;
OffsetDirection = (LookHit.point - LookHitOffset.point).normalized;
TurnOffset = MeshTransform.eulerAngles;
ChildTransform.position = ObjectPosition;
//ChildTransform.up = ObjectNormal;
//ChildTransform.forward = OffsetDirection;
ItemLookDirection.localPosition = Vector3.zero;
ItemLookDirection.position += OffsetDirection;
Debug.DrawLine(LookHit.point, ItemLookDirection.position, Color.red);
ChildTransform.LookAt(ItemLookDirection, ObjectNormal);
ItemWorldPosition = ChildTransform.position;
ItemWorldRotation = ChildTransform.rotation;
// Spawn Temp Item
if (PlaceholderItem == null)
{
PlaceholderItem = Instantiate(item, ChildTransform);
PlaceholderItem.Disable();
}
/// Set the mesh to the desired mesh
//ChildMesh.mesh = ObjectMesh;
/// Set the mesh and collider to fit each other
ChildCollider.size = PlaceholderItem.BoxSize;
ChildCollider.center = PlaceholderItem.BoxOffset;
MeshTransform.localPosition = Vector3.zero;
/// Turn on object
ChildTransform.gameObject.SetActive(true);
/// Make sure the item isn't always in the ground
MeshTransform.localPosition += new Vector3(0, ChildCollider.size.y / 2 + 0.1f, 0);
///
if (PT.TriggerActive || PT.InGround)
{
if (PlaceholderItem != null)
PlaceholderItem.ChangeMaterials(PlacingMaterialRed);
return false;
}
else
{
if (PlaceholderItem != null)
PlaceholderItem.ChangeMaterials(PlacingMaterialBlue);
return true;
}
}
return false;
}
else
{
if (PlaceholderItem != null)
PlaceholderItem.ChangeMaterials(PlacingMaterialRed);
Debug.DrawRay(LookDirection.position, LookDirection.forward * LookHit.distance, Color.red);
return false;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/RoomLayoutGroup.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
public class RoomLayoutGroup : MonoBehaviourPunCallbacks
{
[SerializeField]
private RectTransform RT;
[SerializeField]
private RoomListing RoomPrefab;
private List<RoomListing> RoomListings = new List<RoomListing>();
private List<RoomInfo> RoomList = new List<RoomInfo>();
private bool Detoir = false;
private void Update()
{
if (Detoir)
{
if (PhotonNetwork.IsConnectedAndReady && PhotonNetwork.InLobby)
{
print("RefreshRoomlist Called, " + PhotonNetwork.CountOfRooms + " Room Count, Players: " + PhotonNetwork.CountOfPlayersOnMaster);
OnRecievedRoomListUpdate();
OnRoomListUpdate(RoomList);
Detoir = false;
}
}
}
public void RefreshRoomlist()
{
if (PhotonNetwork.IsConnectedAndReady && PhotonNetwork.InLobby)
{
print("RefreshRoomlist Called, " + PhotonNetwork.CountOfRooms + " Room Count, Players: " + PhotonNetwork.CountOfPlayersOnMaster);
OnRecievedRoomListUpdate();
OnRoomListUpdate(RoomList);
}
else
{
Detoir = true;
}
}
public void OnRecievedRoomListUpdate()
{
print("OnRecievedRoomListUpdate Called");
PhotonNetwork.GetCustomRoomList(PhotonNetwork.CurrentLobby, "");
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
print("OnRoomListUpdate Called");
RoomList = roomList;
foreach (RoomInfo RoomInfomation in RoomList)
{
int Index = RoomListings.FindIndex(x => x.RoomName == RoomInfomation.Name);
if (Index == -1)
{
if (RoomInfomation.IsVisible && RoomInfomation.PlayerCount < RoomInfomation.MaxPlayers)
{
RoomListing temp = Instantiate(RoomPrefab);
RectTransform TempRect = temp.GetComponent<RectTransform>();
TempRect.SetParent(RT, false);
RoomListings.Add(temp);
temp.Updated = true;
//temp.UpdateInfo(Room.);
Index = RoomListings.Count - 1;
}
}
if (Index != -1)
{
RoomListing RL = RoomListings[Index];
RL.SetRoomIdentifier(RoomInfomation.Name);
string RoomName = (string)RoomInfomation.CustomProperties["RoomNameKey"];
string RoomType = (string)RoomInfomation.CustomProperties["RoomTypeKey"];
int RoomPing = PhotonNetwork.GetPing();
RL.UpdateInfo(RoomName, RoomType, RoomPing, RoomInfomation.PlayerCount, RoomInfomation.MaxPlayers);
}
}
base.OnRoomListUpdate(roomList);
RemoveOldRooms();
}
private void RemoveOldRooms()
{
print("RemoveOldRooms Called");
List<RoomListing> removeRooms = new List<RoomListing>();
foreach (RoomListing rl in RoomListings)
{
if (!rl.Updated)
{
removeRooms.Add(rl);
}
else
{
rl.Updated = false;
}
}
int roomCount = removeRooms.Count;
while (removeRooms.Count > 0 || roomCount > 0)
{
roomCount--;
RoomListing temp = removeRooms[removeRooms.Count - 1];
if (temp != null)
{
removeRooms.Remove(temp);
Destroy(temp.gameObject, 0.1f);
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/GameSetup.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class GameSetup : MonoBehaviour {
public static GameSetup GS;
public GameObject[] playerSpawns;
public GameObject[] BlueSpawns;
public GameObject[] RedSpawns;
// Use this for initialization
void Start()
{
if (playerSpawns.Length == 0)
{
BlueSpawns = GameObject.FindGameObjectsWithTag("BlueSpawn");
RedSpawns = GameObject.FindGameObjectsWithTag("RedSpawn");
playerSpawns = GameObject.FindGameObjectsWithTag("playerSpawn");
}
}
private void OnEnable()
{
if (GameSetup.GS == null)
{
GameSetup.GS = this;
}
}
public Transform GrabSpawnPoint(int viewID)
{
Transform ReturnTransform = null;
// Figure out who is asking
NetPlayer ThisPlayer = PhotonView.Find(viewID).GetComponent<NetPlayer>();
// Find All Players
NetPlayer[] Players = FindObjectsOfType<NetPlayer>();
// Find players on players team
List<NetPlayer> TeamPlayers = new List<NetPlayer>();
foreach(NetPlayer NP in Players)
{
if (NP.GetTeamNum() == ThisPlayer.GetTeamNum())
{
TeamPlayers.Add(NP);
}
}
// find the players by view id
List<NetPlayer> TeamPlayersByViewID = new List<NetPlayer>();
for (int I = 0; I < TeamPlayers.Count; I++)
{
NetPlayer temp = null;
// Find Next Lower Player
foreach(NetPlayer NP in TeamPlayers)
{
// If the temp is null
if (temp == null)
{
// Add current player if it is not contained
if (!TeamPlayersByViewID.Contains(NP))
temp = NP;
}
// If the NP is lower then the temp
if (temp != null && temp.GetTeamNum() > NP.GetTeamNum() && !TeamPlayersByViewID.Contains(NP))
{
temp = NP;
}
}
// Add player to list
if (!TeamPlayersByViewID.Contains(temp))
{
TeamPlayersByViewID.Add(temp);
}
}
// All the players should be sorted
int index = TeamPlayersByViewID.IndexOf(ThisPlayer);
if (index == -1)
{
index = Random.Range(0, 3);
}
// Set the return transform
if (ThisPlayer.GetTeamNum() == 1)
ReturnTransform = BlueSpawns[index].transform;
if (ThisPlayer.GetTeamNum() == 2)
ReturnTransform = RedSpawns[index].transform;
//else
//{
// Debug.Log("No Spawn Selected");
//}
return ReturnTransform;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ScriptsCamera/CameraModeMedium.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraModeMedium : MonoBehaviour {
[SerializeField]
private LookAtBall lookAtBall = null;
[SerializeField]
private CameraRotation cameraRotation = null;
public bool isFreeCam = false;
public bool changeIsAllowed = false;
// Use this for initialization
void Start () {
lookAtBall = transform.GetComponent<LookAtBall>();
cameraRotation = transform.GetComponent<CameraRotation>();
isFreeCam = true;
lookAtBall.allow = false;
cameraRotation.allow = true;
changeIsAllowed = true;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.C))
{
if (changeIsAllowed)
{
ChangeCameraMode();
}
}
}
public void ChangeCameraMode()
{
if (isFreeCam == false)
{
cameraRotation.GrabRot();
isFreeCam = true;
lookAtBall.allow = false;
cameraRotation.allow = true;
lookAtBall.hardLock = false;
}
else
{
isFreeCam = false;
lookAtBall.allow = true;
cameraRotation.allow = false;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ScriptsCamera/CameraKeepOnPosition.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraKeepOnPosition : MonoBehaviour {
[SerializeField]
private Transform cameraLookAtPosition;
[SerializeField]
private float maxRotSpeed = 1;
[SerializeField]
private Transform player;
private float currentRotSpeed;
private float rotStep;
[SerializeField]
private float acceleration;
[SerializeField]
private CameraRotation camRot;
public void UnParent()
{
transform.parent = null;
if (player.GetComponent<PlayerColor>().TeamNum == 2)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
}
// Update is called once per frame
void Update () {
if (transform.parent == null)
{
transform.position = cameraLookAtPosition.position;
float angle = Quaternion.Angle(transform.rotation, cameraLookAtPosition.rotation);
currentRotSpeed = angle * acceleration;
rotStep = currentRotSpeed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, cameraLookAtPosition.rotation, rotStep);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/LookAtBall.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtBall : MonoBehaviour
{
private Transform lookatBall;
[SerializeField]
private BallHandling thisPlayerBallHandling;
public bool allow = false;
//public List<Transform> players = new List<Transform>();
private CameraModeMedium cMM;
[SerializeField]
private Transform upRotationRootObj;
[SerializeField]
private float maxAngle;
[SerializeField]
private float speedRot;
public bool hardLock = false;
[SerializeField]
private Transform blueHandTransform;
[SerializeField]
private Transform redHandTransform;
// Use this for initialization
void Start()
{
if (GameObject.FindGameObjectWithTag("Ball") != null)
lookatBall = GameObject.FindGameObjectWithTag("Ball").transform;
cMM = transform.GetComponent<CameraModeMedium>();
}
// Update is called once per frame
void Update()
{
if (lookatBall != null)
{
if (allow)
{
if (lookatBall.parent != blueHandTransform && lookatBall.parent != redHandTransform)
{
if (!hardLock)
{
Vector3 direction = lookatBall.position - transform.position;
float angle = Vector3.Angle(direction, transform.forward);
if (angle >= maxAngle)
{
Quaternion rot = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, speedRot * angle * Time.deltaTime);
}
else
hardLock = true;
}
else
{
transform.LookAt(lookatBall, upRotationRootObj.up);
}
}
else
{
Debug.Log("Else");
cMM.ChangeCameraMode();
}
}
}
else
{
if (GameObject.FindGameObjectWithTag("Ball") != null)
lookatBall = GameObject.FindGameObjectWithTag("Ball").transform;
}
}
}<file_sep>/CapstonePowerPlay/Assets/Scripts/MenuSoundFXs.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuSoundFXs : MonoBehaviour {
private AudioSource Src;
public AudioClip interact;
public AudioClip start;
public float menuFXVol = 1f;
// Use this for initialization
void Start () {
Src = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
Src.volume = menuFXVol;
}
public void PlayInt()
{
Src.clip = interact;
Src.Play();
}
public void PlayStart()
{
Src.clip = start;
Src.Play();
}
public void SetVolume(float vol)
{
menuFXVol = vol;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PIDController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PIDController : MonoBehaviour {
// PID Gains
[SerializeField]
private float Kp = 1.0f;
[SerializeField]
private float Ki = 0.0f;
[SerializeField]
private float Kd = 0.0f;
// Errors
private float cumError = 0, prevError = 0, output;
// Clamp Seetings
public bool isClamp = false;
[SerializeField]
private float min = 0.0f;
[SerializeField]
private float max = 1.0f;
public void setGains(float kp, float ki, float kd)
{
Kp = kp;
Ki = ki;
Kd = kd;
}
public void step(float targetValue, float currentValue)
{
float error = targetValue - currentValue;
cumError += error;
float slope = error - prevError;
output = (Kp * error) + (Ki * cumError) + (Kd * slope);
if (isClamp)
{
output = Mathf.Clamp(output, min, max);
}
prevError = error;
}
public float getOutput()
{
return output;
}
public void EnableClamp(float minValue, float maxValue)
{
isClamp = true;
min = minValue;
max = maxValue;
}
public void WipeErrors()
{
cumError = 0f;
prevError = 0f;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerSoftlockPassSight.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSoftlockPassSight : MonoBehaviour
{
// the max angle that a teamate must be in between, in order to be an eligable target for passing
[SerializeField]
private float softLockAngle = 40f;
// distance between player and target
[SerializeField]
private float distanceToTarget;
// list of teamates in game
[SerializeField]
private List<GameObject> listOfTeamates = new List<GameObject>();
// direction from the player
private Vector3 directionFromPlayer;
// current angle
[SerializeField]
private float angle = 0;
// target of passing
[SerializeField]
public Transform target;
[SerializeField]
public Vector3 targetPosition;
// accepted target list, the group of targets that are elligable to be targeted
[SerializeField]
private List<GameObject> currentAcceptedTargets = new List<GameObject>();
// the smallest angle between the player's forward vector and another object
private float currentClossestAngle;
// current angle between a target and the player
private float currentAngle;
// team gameobject tag
[SerializeField]
public string teamTag;
// list containing main player object and children
[SerializeField]
private List<GameObject> playerAndChildren = new List<GameObject>();
// the max distance for a teamate must be within, in order to be an eligable target for passing
[SerializeField]
private float maxDistance = 0.0f;
// player gameObject
[SerializeField]
public GameObject player;
private bool passed = false;
public void SetChanges()
{
Debug.Log("changes setting");
//set player object (parent object that this script is attached to)
//player = transform.parent.gameObject;
// get the tag of the player
teamTag = player.tag;
//Debug.Log("teamTag = " + teamTag);
//Debug.Log("Player name: " + player.name);
// set soft lock angle (to be removed)
softLockAngle = 20f;
// find all objects with the same tag as the player (used to see which is a temate, may change in future)
foreach (GameObject playerObj in GameObject.FindGameObjectsWithTag(teamTag))
{
if (playerObj != transform.gameObject)
{
listOfTeamates.Add(playerObj);
}
}
// find the player's gameObject and remove it from teamate list.
for (int i = listOfTeamates.Count - 1; i >= 0; --i)
{
if (listOfTeamates[i].gameObject == player.transform.gameObject)
{
listOfTeamates.RemoveAt(i);
listOfTeamates.TrimExcess();
break;
}
}
// add player gameObject to the list
playerAndChildren.Add(player.transform.gameObject);
// add all children to main player gameObject to this list
foreach (Transform child in player.transform)
{
playerAndChildren.Add(child.gameObject);
//child is your child transform
}
// unchiled this gameObject
// transform.parent = null;
/// if you don't want any distance restrictions (ill advised) the use this
/// maxDistance = Mathf.Infinity;
///
passed = true;
}
// Update is called once per frame
void Update()
{
if (passed)
{
// problem the host sees itself as a teamate
//Debug.Log("listofteamates count: " + listOfTeamates.Count);
if (listOfTeamates.Count <= 0)
{
//Debug.Log("no teamates");
// find all objects with the same tag as the player (used to see which is a temate, may change in future)
//Debug.Log("Team tag: " + teamTag);
foreach (GameObject playerObj in GameObject.FindGameObjectsWithTag(teamTag))
{
if (playerObj != transform.gameObject)
{
listOfTeamates.Add(playerObj);
}
}
// find the player's gameObject and remove it from teamate list.
for (int i = listOfTeamates.Count - 1; i >= 0; --i)
{
if (listOfTeamates[i].gameObject == player)
{
listOfTeamates.RemoveAt(i);
listOfTeamates.TrimExcess();
break;
}
}
}
else
{
// Debug.Log("has teamates");
// check every teamates within the list
for (int i = 0; i < listOfTeamates.Count; i++)
{
// find direction from player
directionFromPlayer = (listOfTeamates[i].transform.position + ((new Vector3(listOfTeamates[i].transform.up.x, listOfTeamates[i].transform.up.y, listOfTeamates[i].transform.up.z) / 4) * 3)) - transform.position;
// get current angle between the current teamate and the player
angle = Vector3.Angle(directionFromPlayer, transform.forward);
// set distance to target
distanceToTarget = directionFromPlayer.magnitude;
// create RaycastHit
RaycastHit tempHit = new RaycastHit();
// send out raycast to the current teamate being referenced
if (Physics.Raycast(transform.position, directionFromPlayer, out tempHit, Mathf.Infinity))
{
//Debug.Log("tempHit has hit: " + tempHit.transform.name + " tempHit should hit: " + listOfTeamates[i]);
// if the raycast hits is target
if (tempHit.transform.gameObject == listOfTeamates[i])
{
// if target is within angle
if (angle < softLockAngle /*just added distance check->*/&& distanceToTarget < maxDistance)
{
// number of passes without succes of finding the current teammate being referenced from listOfTeamates
int tempNumberOfCurrentAcceptedTargetPasses = 0;
//Debug.DrawRay(new Vector3(transform.position.x, transform.position.y, transform.position.z), directionFromPlayer, Color.blue);
// if the currentAcceptedTargets list have anyting in the list
if (currentAcceptedTargets.Count > 0)
{
// check every object in currentAcceptedTargets
for (int j = 0; j < currentAcceptedTargets.Count; j++)
{
// if it equals to the current teammate being referenced from listOfTeamates
if (currentAcceptedTargets[j] == listOfTeamates[i])
{
break;
}
// if it does NOT equals to the current teammate being referenced from listOfTeamates
else
{
// add another pass
tempNumberOfCurrentAcceptedTargetPasses++;
}
// if there is no object in currentAcceptedTargets that equals the teammate being referenced from listOfTeamates
if (tempNumberOfCurrentAcceptedTargetPasses >= currentAcceptedTargets.Count)
{
// add the teammate being referenced from listOfTeamates to currentAcceptedTargets
currentAcceptedTargets.Add(listOfTeamates[i].gameObject);
}
}
}
// if there is noting in currentAccpeted target list
else
{
// add the teammate being referenced from listOfTeamates to currentAcceptedTargets
currentAcceptedTargets.Add(listOfTeamates[i].gameObject);
}
}
// if the target is NOT within angle
else
{
// check every object within currentAcceptedTargets list
for (int j = 0; j < currentAcceptedTargets.Count; j++)
{
// if it equals to the gameObject referenced in listOfTeamates
if (currentAcceptedTargets[j] == listOfTeamates[i])
{
//Debug.Log("removing: " + currentAcceptedTargets[j] + " from acceptableTargets by target not being in view of the angle");
// remove the gameObject referenced in listOfTeamates from currentAcceptedTargets
currentAcceptedTargets.Remove(currentAcceptedTargets[j]);
currentAcceptedTargets.TrimExcess();
// just added...
break;
}
}
// Debug.DrawRay(transform.position, directionFromPlayer, Color.red);
}
}
// if the raycast does not hit intended target
else
{
// check every object within currentAcceptedTargets list
for (int j = 0; j < currentAcceptedTargets.Count; j++)
{
// if it equals to the gameObject referenced in listOfTeamates
if (currentAcceptedTargets[j] == listOfTeamates[i])
{
// Debug.Log("removing: " + currentAcceptedTargets[j] + " from acceptableTargets by raycast not connecting");
// remove the gameObject referenced in listOfTeamates from currentAcceptedTargets
currentAcceptedTargets.Remove(currentAcceptedTargets[j]);
currentAcceptedTargets.TrimExcess();
// just added...
break;
}
}
//Debug.DrawRay(transform.position, directionFromPlayer, Color.red);
}
}
}
// reset closest angle to the max of 360 degrees (may change later in favour of a localy instantiated value in update)
currentClossestAngle = 360;
// current target reset (may change later in favour of a localy instantiated value in update)
target = null;
targetPosition = Vector3.zero;
// check every object in currentAcceptedTargets, (eligable targets)
for (int i = 0; i < currentAcceptedTargets.Count; i++)
{
Vector3 currentObjectDirection;
// check the direction of the current checked object of currentAcceptedTargets list and the player
currentObjectDirection = currentAcceptedTargets[i].transform.position - transform.position;
// set the current angle between the current checked object of currentAcceptedTargets list and the player
currentAngle = Vector3.Angle(currentObjectDirection, transform.forward);
// if the currentClossestAngle variable is less than the currentAngle variable
if (currentAngle <= currentClossestAngle)
{
// set currentClossestAngle as the currentAngle;
currentClossestAngle = currentAngle;
// set the target as the currently checked gameObject in the currentAcceptedTargets list
target = currentAcceptedTargets[i].transform;
//Debug.Log("Target set as: " + target);
// set target position to center the players
targetPosition = target.position + ((new Vector3(target.up.x, target.up.y, target.up.z) / 4) * 3);
}
}
// if there is an elidgable target to pass too
if (target != null)
{
// draw ray
//Vector3 targetObjectDirection = target.transform.position - transform.position;
// Debug.DrawRay(new Vector3(transform.position.x, transform.position.y, transform.position.z), targetObjectDirection, Color.yellow);
}
//
// Section is to check for new players, who've joined after the awake
//
// number of temate to check, minus because of player
int tempNumberCheck = -1;
// lsit of gathered obj
List<GameObject> newTeamateSearch = new List<GameObject>();
// check if a new teamate has entered the game
//Debug.Log("TeamTag: " + teamTag);
foreach (GameObject playerObj in GameObject.FindGameObjectsWithTag(teamTag))
{
// add current playerObj into the newTeamateSearch list
newTeamateSearch.Add(playerObj);
// add one to tempNumberCheck
tempNumberCheck++;
}
// if there is more gameObejcts with the same tag as the player that is not in the listOfTeamates list
if (tempNumberCheck > listOfTeamates.Count)
{
//Debug.Log("tempNumberCheck > listOfTeamates");
// for every object in newTeamateSearch
for (int i = newTeamateSearch.Count - 1; i >= 0; --i)
{
// number of for loop passes for loop j
int numberOfPasses = 0;
// check every object in lisst of temates
for (int j = listOfTeamates.Count - 1; j >= 0; --j)
{
// changed
// if the referenced gameObject of the listOfTeamates list, does NOT equale the referenced object in newTeamateSearch list
if (listOfTeamates[j] != newTeamateSearch[i])
{
// add one to numberOfPasses
numberOfPasses++;
}
// if the referenced gameObject of the listOfTeamates list, does equale the referenced object in newTeamateSearch list
else
{
// exit loop
break;
}
// if numberOfPasses surpass the number of objects in listOfTeamates and the current referenced object in newTeamateSearch list does not equal to the player
// the new teamate has been found
if (numberOfPasses >= listOfTeamates.Count && newTeamateSearch[i] != player)
{
// Debug.Log("added: " + newTeamateSearch[i].name);
// add the newly discoverd teamate into the listOfTeamates list variable
listOfTeamates.Add(newTeamateSearch[i]);
}
}
// Debug.Log("number of passes: " + numberOfPasses);
}
}
for (int i = newTeamateSearch.Count - 1; i >= 0; i--)
{
newTeamateSearch[i] = null;
newTeamateSearch.TrimExcess();
}
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/SetupLocalPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Photon.Pun;
public class SetupLocalPlayer : MonoBehaviour {
// [SyncVar(hook = "OnChangeName")]
public string pname = "player";
//[SyncVar]
public Color playerColor = Color.white;
private PhotonView PV;
private void OnGUI()
{
//if (isLocalPlayer)
// pname = GUI.TextField(new Rect(25, Screen.height - 40, 100, 30), pname);
//if(GUI.Button(new Rect(130,Screen.height - 40,80,30),"Change"))
//{
// CmdChangeName(pname);
//}
}
[PunRPC]
public void RPC_ChangeName(string newName)
{
ChangeName(newName);
}
public void ChangeName(string newName)
{
gameObject.name = pname;
//this.GetComponentInChildren<TextMesh>().text = pname;
}
private void Start()
{
PV = GetComponent<PhotonView>();
if (PV.IsMine/*isLocalPlayer*/)
{
Renderer[] rends = GetComponentsInChildren<Renderer>();
foreach (Renderer r in rends)
r.material.color = playerColor;
}
}
private void Update()
{
//if (isLocalPlayer)
//{
// this.GetComponentInChildren<TextMesh>().text = pname;
//}
}
//public override void OnStartLocalPlayer()
//{
// //CmdChangeName(pname);
// //base.OnStartLocalPlayer();
//}
private void OnChangeName(string newName)
{
pname = newName;
gameObject.name = pname;
//CmdChangeName(pname);
PV.RPC("RPC_ChangeName", RpcTarget.All, pname);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Rune.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class Rune : MonoBehaviour {
[SerializeField]
private Item ItemPrefab;
//[SerializeField]
public PhotonView PV;
[SerializeField]
private string RuneID;
public RuneSpawnQueue parentRuneSpawn;
public string GetRuneID()
{
return RuneID;
}
public Item GetItemPrefab()
{
return ItemPrefab;
}
public void DestroyRune()
{
PhotonNetwork.Destroy(PV);
}
public void TurnOffRune()
{
PV.RPC("RPC_TurnOffRune", RpcTarget.All);
}
[PunRPC]
void RPC_TurnOffRune()
{
gameObject.SetActive(false);
parentRuneSpawn.CallAcivateRandomRune();
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Follow_And_Look.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Follow_And_Look : MonoBehaviour {
[SerializeField]
private Transform Target;
//[SerializeField]
//private Transform LookAtTarget;
private Transform T;
// Use this for initialization
void Start()
{
T = transform;
}
// Update is called once per frame
void Update()
{
T.position = Target.position;
//T.rotation = Target.rotation;
//T.rotation = Quaternion.Euler(new Vector3(T.rotation.x, Target.rotation.y * 180 / Mathf.PI, T.rotation.z));
}
}
<file_sep>/CapstonePowerPlay/Assets/MenuCamFolder/Scripts/DollyManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class DollyManager : MonoBehaviour {
[SerializeField]
private Transform[] c_DollyCarts;
[SerializeField]
private Transform[] l_DollyCarts;
/*
* 0 = Null to start
* 1 = Start To menu
* 2 = Menu to lobby list
* 3 = lobby list To lobby
*/
[SerializeField]
Cinemachine.CinemachineVirtualCamera[] c_virtualCameras;
/*
* 0 = Null to start
* 1 = Start To menu
* 2 = Menu to lobby list
* 3 = lobby list To lobby
*/
[SerializeField]
private int lowPriority;
[SerializeField]
private int highPriority;
private void Start()
{
for (int i = 0; i < c_virtualCameras.Length; i++)
{
c_virtualCameras[i].Priority = lowPriority;
}
c_virtualCameras[0].Priority = highPriority;
}
public void Null_And_Start(bool forwards)
{
if(forwards)
{
ForwardMovement(0);
}
else
{
BackwardMovement(0);
}
}
public void Start_And_Menu(bool forwards)
{
if (forwards)
{
ForwardMovement(1);
}
else
{
BackwardMovement(1);
}
}
public void Menu_And_Play(bool forwards)
{
if (forwards)
{
ForwardMovement(2);
}
else
{
BackwardMovement(2);
}
}
public void Menu_And_Setting(bool forwards)
{
if (forwards)
{
ForwardMovement(3);
}
else
{
BackwardMovement(3);
}
}
private void ForwardMovement(int trackInteger)
{
for (int i = 0; i < c_DollyCarts.Length; i++)
{
c_virtualCameras[i].Priority = lowPriority;
}
DollyModifier dollyMod = c_DollyCarts[trackInteger].GetComponent<DollyModifier>();
c_DollyCarts[trackInteger].GetComponent<Cinemachine.CinemachineDollyCart>().m_Position = 0;
l_DollyCarts[trackInteger].GetComponent<Cinemachine.CinemachineDollyCart>().m_Position = 0;
dollyMod.reachedSpeedMax = false;
dollyMod.reachedSpeedMaxRev = false;
c_virtualCameras[trackInteger].Priority = highPriority;
dollyMod.reverse = false;
dollyMod.allowMovement = true;
dollyMod = l_DollyCarts[trackInteger].GetComponent<DollyModifier>();
dollyMod.reachedSpeedMax = false;
dollyMod.reachedSpeedMaxRev = false;
c_virtualCameras[trackInteger].Priority = highPriority;
dollyMod.reverse = false;
dollyMod.allowMovement = true;
}
private void BackwardMovement(int trackInteger)
{
for (int i = 0; i < c_DollyCarts.Length; i++)
{
c_virtualCameras[i].Priority = lowPriority;
}
DollyModifier dollyMod = c_DollyCarts[trackInteger].GetComponent<DollyModifier>();
dollyMod.reachedSpeedMax = false;
dollyMod.reachedSpeedMaxRev = false;
c_virtualCameras[trackInteger].Priority = highPriority;
dollyMod.reverse = true;
dollyMod.allowMovement = true;
dollyMod = l_DollyCarts[trackInteger].GetComponent<DollyModifier>();
dollyMod.reachedSpeedMax = false;
dollyMod.reachedSpeedMaxRev = false;
c_virtualCameras[trackInteger].Priority = highPriority;
dollyMod.reverse = true;
dollyMod.allowMovement = true;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Ball.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Ball : MonoBehaviour
{
[SerializeField]
private Transform Handle;
[SerializeField]
public BallHandling BH;
//OLD SYNC VAR
public GameObject WhoTossedTheBall = null;
[SerializeField]
public Transform Hand;
//OLD SYNC VAR
public bool Held = false;
private Rigidbody RB;
public SphereCollider HardCol;
private float timer = 0;
[SerializeField]
private bool isInPassing = false;
private GameObject passedTarget;
//[SerializeField]
//private float RotSpeed = 0.5f;
[SerializeField]
private float maxDegree = 50;
// Who threw the ball (based on tag string)
public string teamTag;
[SerializeField]
private float KonstantForce = 900.0f;
public float PickUpRadius = 9;
private float CanBeCaughtTimer = 1;
private bool Thrown = false;
//private float SlerpRatio = 0;
[SerializeField]
private float maxTimePass = 2.0f;
private float timePassTimer = 0.0f;
// Physical Components
[SerializeField]
private GameObject ChildObject;
[SerializeField]
private SphereCollider SoftCol;
//UI Elements
[SerializeField]
private RectTransform UiCanvas;
//PHOTON VARIABLES
private PhotonView PV;
// Net Spawner Script
private netSpawner nSpawner;
public bool hasBeenPickedUpBefore;
private RoundManager rTimerScript;
[SerializeField]
private bool inPlay = false;
[SerializeField]
private Animation animFloat = null;
private float maxMass;
[SerializeField]
private float maxIncreaseAcceleration = 1;
// Use this for initialization
void Start()
{
PV = GetComponent<PhotonView>();
Handle = GetComponent<Transform>();
RB = GetComponent<Rigidbody>();
maxMass = RB.mass;
nSpawner = FindObjectOfType<netSpawner>();
rTimerScript = FindObjectOfType<RoundManager>();
SoftCol.radius = PickUpRadius;
animFloat = transform.GetChild(0).GetComponent<Animation>();
}
private void Update()
{
if (timer > 0)
{
timer -= Time.deltaTime;
Held = false;
}
if (RB.mass < maxMass)
{
RB.mass += Time.deltaTime / maxIncreaseAcceleration;
}
else if (RB.mass > maxMass)
{
RB.mass = maxMass;
}
if (Thrown)
{
if (BH != null || Hand != null || Held)
ResetBall();
CanBeCaughtTimer -= Time.deltaTime;
if (CanBeCaughtTimer <= 0)
{
Thrown = false;
CanBeCaughtTimer = 0.2f;
}
}
if (isInPassing)
{
if (RB.useGravity)
RB.useGravity = false;
timePassTimer += Time.deltaTime;
if (timePassTimer >= maxTimePass)
{
timePassTimer = 0;
isInPassing = false;
RB.useGravity = true;
}
Vector3 forwardVector = transform.forward;
float lengthOfForwardV = forwardVector.magnitude;
Vector3 posOffset = (new Vector3(passedTarget.transform.up.x, passedTarget.transform.up.y, passedTarget.transform.up.z) / 4) * 3;
float angle = Mathf.Acos(Vector3.Dot(transform.forward, ((passedTarget.transform.position + posOffset) - transform.position)) / (Mathf.Abs(lengthOfForwardV * ((passedTarget.transform.position + posOffset) - transform.position).magnitude)));
angle *= 180 / Mathf.PI;
angle = Mathf.Abs(angle);
Vector3 lookPos = (passedTarget.transform.position + posOffset) - transform.position;
Vector3 direction = lookPos.normalized;
if (angle <= maxDegree)
{
RB.AddForce(direction * KonstantForce, ForceMode.Force);
}
else
{
RB.AddForce(direction * KonstantForce / 2, ForceMode.Force);
}
}
if (!Held)
{
if (RB.useGravity == false)
{
if (!isInPassing)
{
gameObject.layer = 10;
if (inPlay)
RB.useGravity = true;
}
}
}
if (Held && !Thrown)
{
transform.localPosition = Vector3.zero;
RB.useGravity = false;
if (RB.mass != maxMass)
{
RB.mass = maxMass;
}
}
else if (UiCanvas.localPosition != Vector3.zero)
{
UiCanvas.localPosition = Vector3.zero;
}
if (stolenInProgress)
{
if ((thiefTransform.position - transform.position).magnitude <= thiefCatchDistance)
{
CatchThief();
}
}
}
public void SlowDown(float Rate = 4)
{
RB.velocity = RB.velocity / Rate;
}
public bool stolenInProgress;
public Transform thiefTransform;
[SerializeField]
private float thiefCatchDistance;
private void CatchThief()
{
gameObject.layer = 2;
HardCol.isTrigger = true;
Held = true;
// Set who has the the ball
BH = thiefTransform.GetComponent<BallHandling>();
SetBallHandling(BH.gameObject);
if (BH.canHold)
{
Hand = BH.ReturnHand();
UpdateHandTransform(BH.gameObject);
BH.SetBall(gameObject);
}
else
{
BH = null;
}
stolenInProgress = false;
thiefTransform = null;
}
private void OnCollisionEnter(Collision c)
{
if (!inPlay)
{
inPlay = true;
animFloat.enabled = false;
transform.GetChild(0).transform.localPosition = Vector3.zero;
}
if (Thrown)
{
if (c.gameObject.tag == "Default" || c.gameObject.tag == "Ground")
{
isInPassing = false;
RB.useGravity = true;
}
}
}
[PunRPC]
private void RPC_OnTriggerEnter()
{
if (!inPlay)
{
inPlay = true;
animFloat.enabled = false;
transform.GetChild(0).transform.localPosition = Vector3.zero;
}
gameObject.layer = 2;
HardCol.isTrigger = true;
Held = true;
}
[PunRPC]
private void RPC_SetPlayerBH(int Code)
{
GameObject pc = PhotonView.Find(Code).gameObject;
Debug.Log("PC: " + pc.name);
BH = pc.GetComponent<BallHandling>();
if (BH.canHold)
{
BH.ball = this;
Hand = BH.ReturnHand();
transform.SetParent(Hand);
Debug.Log("the parent is: " + transform.parent);
transform.localPosition = Vector3.zero;
BH.canHold = false;
BH.canHoldTimer = 1;
Held = true;
RB.useGravity = false;
RB.isKinematic = true;
RB.detectCollisions = false;
HardCol.isTrigger = true;
}
}
public void PickUp(GameObject c)
{
if (!hasBeenPickedUpBefore)
{
rTimerScript.BeginCountdown();
}
PV.RPC("RPC_OnTriggerEnter", RpcTarget.All);
PlayerColor pc = c.GetComponent<PlayerColor>();
PV.RPC("RPC_SetPlayerBH", RpcTarget.AllViaServer, c.GetPhotonView().ViewID);
}
private void OnTriggerExit(Collider other)
{
if (!stolenInProgress && (other.tag == "Team 1" || other.tag == "Team 2"))
{
PV.RPC("RPC_OnTriggerExit", RpcTarget.All);
}
}
[PunRPC]
private void RPC_OnTriggerExit()
{
if (!inPlay)
{
inPlay = true;
animFloat.enabled = false;
transform.GetChild(0).transform.localPosition = Vector3.zero;
}
HardCol.isTrigger = false;
timer = 1;
}
public void ShootBall(Vector3 power, string tag, Vector3 HandPos, GameObject WhoThrew)
{
Shoot(power, tag, HandPos, WhoThrew);
}
public void Shoot(Vector3 power, string tag, Vector3 HandPos, GameObject WhoThrew)
{
PV.RPC("RPC_Shoot", RpcTarget.All, power, tag, HandPos, WhoThrew.GetPhotonView().ViewID);
}
[PunRPC]
public void RPC_Shoot(Vector3 power, string tag, Vector3 HandPos, int WhoThrew)
{
RB.mass = 5;
transform.SetParent(null);
Thrown = true;
CanBeCaughtTimer = 0.15f;
RB.useGravity = false;
RB.isKinematic = false;
RB.detectCollisions = true;
RB.velocity = Vector3.zero;
RB.angularVelocity = Vector3.zero;
transform.position = HandPos;
RB.AddForce(power, ForceMode.Impulse);
teamTag = tag;
gameObject.layer = 10;
Held = false;
WhoTossedTheBall = PhotonView.Find(WhoThrew).gameObject;
Hand = null;
BH = null;
HardCol.isTrigger = false;
}
public void SetPass(bool Passing, GameObject Target, float Force, Vector3 HandPos, GameObject WhoThrew)
{
PV.RPC("RPC_SetPass", RpcTarget.All, Passing, Target.GetPhotonView().ViewID, Force, HandPos, WhoThrew.GetPhotonView().ViewID);
}
[PunRPC]
public void RPC_SetPass(bool Passing, int Target, float Force, Vector3 HandPos, int WhoThrew)
{
transform.SetParent(null);
Thrown = true;
CanBeCaughtTimer = 0.15f;
passedTarget = PhotonView.Find(Target).gameObject;
isInPassing = true;
RB.useGravity = false;
RB.isKinematic = false;
RB.detectCollisions = true;
transform.position = HandPos;
Held = false;
WhoTossedTheBall = PhotonView.Find(WhoThrew).gameObject;
Hand = null;
BH = null;
HardCol.isTrigger = false;
RB.velocity = Vector3.zero;
RB.angularVelocity = Vector3.zero;
transform.LookAt(PhotonView.Find(Target).gameObject.transform);
RB.AddForce(Force * transform.forward, ForceMode.Impulse);
teamTag = tag;
gameObject.layer = 10;
}
public void SetSteal(bool Passing, GameObject Target, float Force, Vector3 HandPos, GameObject WhoThrew)
{
PV.RPC("RPC_SetSteal", RpcTarget.All, Passing, Target.GetPhotonView().ViewID, Force, HandPos, WhoThrew.GetPhotonView().ViewID);
}
[PunRPC]
public void RPC_SetSteal(bool Passing, int Target, float Force, Vector3 HandPos, int WhoThrew)
{
Thrown = true;
ResetBall();
passedTarget = PhotonView.Find(Target).gameObject;
transform.parent = null;
Handle.parent = null;
isInPassing = true;
RB.velocity = Vector3.zero;
RB.angularVelocity = Vector3.zero;
float distance = (transform.position - PhotonView.Find(Target).gameObject.transform.position).magnitude;
transform.LookAt(PhotonView.Find(Target).gameObject.transform);
RB.AddForce(transform.up * Force, ForceMode.Impulse);
Held = false;
WhoTossedTheBall = PhotonView.Find(WhoThrew).gameObject;
Hand = null;
BH = null;
}
public bool GetThrown()
{
return Thrown;
}
public void TurnOnBall(bool b)
{
PV.RPC("RPC_TurnOnBall", RpcTarget.All, b);
}
[PunRPC]
public void RPC_TurnOnBall(bool b)
{
gameObject.SetActive(b);
}
private void UpdateHandTransform(GameObject HandParent)
{
PV.RPC("RPC_UpdateHandTransform", RpcTarget.All, HandParent.GetPhotonView().ViewID);
}
[PunRPC]
private void RPC_UpdateHandTransform(int HandParent)
{
BallHandling bh = PhotonView.Find(HandParent).gameObject.GetComponent<BallHandling>();
Hand = bh.ReturnHand();
}
private void SetBallHandling(GameObject bhObject)
{
PV.RPC("RPC_SetBallHandling", RpcTarget.All, bhObject.GetPhotonView().ViewID);
}
[PunRPC]
private void RPC_SetBallHandling(int bhObject)
{
BH = PhotonView.Find(bhObject).gameObject.GetComponent<BallHandling>();
}
public void UpdateBH(BallHandling bh)
{
BH = bh;
PlayerColor pc = BH.GetComponent<PlayerColor>();
PV.RPC("RPC_UpdateBH", RpcTarget.All, pc.GetCode());
}
[PunRPC]
public void RPC_UpdateBH(string Code)
{
PlayerColor[] Players = FindObjectsOfType<PlayerColor>();
foreach (PlayerColor pc in Players)
{
if (pc.GetCode() == Code)
{
BH = pc.GetComponent<BallHandling>();
break;
}
}
}
public void UpdateHand(BallHandling bh)
{
BH = bh;
PlayerColor pc = BH.GetComponent<PlayerColor>();
PV.RPC("RPC_UpdateHand", RpcTarget.All, pc.GetCode());
}
[PunRPC]
public void RPC_UpdateHand(string Code)
{
PlayerColor[] Players = FindObjectsOfType<PlayerColor>();
foreach (PlayerColor pc in Players)
{
if (pc.GetCode() == Code)
{
Hand = pc.GetComponent<BallHandling>().ReturnHand();
transform.SetParent(Hand);
//Debug.Log("the parent is: " + transform.parent);
transform.localPosition = Vector3.zero;
break;
}
}
}
public void UpdateHeld(bool IsHeld)
{
PV.RPC("RPC_UpdateHeld", RpcTarget.All, IsHeld);
}
[PunRPC]
public void RPC_UpdateHeld(bool IsHeld)
{
Held = IsHeld;
}
public void ResetBall()
{
PV.RPC("RPC_ResetBall", RpcTarget.All);
}
[PunRPC]
public void RPC_ResetBall()
{
print("Ball Reset");
if (BH != null)
BH.ReturnHand().DetachChildren();
Held = false;
BH = null;
Hand = null;
transform.parent = null;
Debug.Log("unParetning Ball shoot. old parent: " + transform.parent);
transform.SetParent(null);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/BallSteal.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallSteal : MonoBehaviour
{
// the max angle that a teamate must be in between, in order to be an eligable target for passing
[SerializeField]
private float stealMaxAngle = 40f;
// the max distance for a teamate must be within, in order to be an eligable target for passing
[SerializeField]
private float maxDistance = 0.0f;
// distance between player and target
[SerializeField]
private float distanceToTarget;
// direction from the player
private Vector3 directionFromPlayer;
// current angle
[SerializeField]
private float angle = 0;
// target of passing
[SerializeField]
public GameObject target;
// current angle between a target and the player
private float currentAngle;
[SerializeField]
private int teamNum;
[SerializeField]
private Transform ballTransform;
[SerializeField]
private Ball ballScript;
// player gameObject
[SerializeField]
public GameObject player;
[SerializeField]
private Transform playerHandTransform;
private BallHandling bH;
private PhotonView PV;
private PlayerColor PC;
public bool isPaused;
// Use this for initialization
void Start()
{
PC = GetComponent<PlayerColor>();
PV = GetComponent<PhotonView>();
player = gameObject;
teamNum = player.GetComponent<PlayerColor>().TeamNum;
bH = transform.GetComponent<BallHandling>();
if (ballTransform == null)
{
if (GameObject.FindGameObjectWithTag("Ball") != null)
{
ballTransform = GameObject.FindGameObjectWithTag("Ball").transform;
if (ballTransform != null)
{
ballScript = ballTransform.GetComponent<Ball>();
}
}
}
}
// Update is called once per frame
void Update()
{
if (teamNum == 0)
{
teamNum = player.GetComponent<PlayerColor>().TeamNum;
}
else
{
if (ballTransform == null)
{
if(GameObject.FindGameObjectWithTag("Ball") != null)
ballTransform = GameObject.FindGameObjectWithTag("Ball").transform;
if (ballTransform != null)
{
if (ballScript == null)
{
ballScript = ballTransform.GetComponent<Ball>();
}
}
}
if (ballScript == null)
{
if (FindObjectOfType<Ball>())
ballScript = FindObjectOfType<Ball>();
if (ballScript != null)
{
if (ballTransform == null)
{
ballTransform = ballScript.transform;
}
}
}
if (PC.LocalPlayer == PC.ParentPlayer)
{
if (ballTransform != null)
{
if (ballScript.Hand && target == null)
{
if (ballScript.BH != null)
{
//Debug.Log("BH");
if (ballScript.BH.gameObject != null)
{
// Debug.Log("BH.gameObject");
if (ballScript.BH.gameObject.GetComponent<PlayerColor>() != null)
{
// Debug.Log("BH.gameObject.GET<PlayerColor>");
if (ballScript.BH.gameObject.GetComponent<PlayerColor>().TeamNum != teamNum)
{
// Debug.Log("BH.gameObject.GET<PlayerColor>(). teamNum");
target = ballScript.BH.gameObject;
}
}
}
}
}
if (ballScript.Hand == false)
{
target = null;
}
// Debug.Log("TeamNum: " + teamNum);
if (bH.ball == null)
{
//Debug.Log("Can steal");
if (target != null)
{
// Debug.Log("Target has been selected");
directionFromPlayer = target.transform.position - transform.position;
distanceToTarget = directionFromPlayer.magnitude;
angle = Vector3.Angle(directionFromPlayer, transform.forward);
if (distanceToTarget < maxDistance && angle < stealMaxAngle)
{
//Debug.Log("In range and in view");
//steal
if (Input.GetMouseButtonDown(0) && !isPaused)
{
// ballScript.DropBall();
BallHandling BH = target.GetComponent<BallHandling>();
Debug.Log("BH.tag: " + target.tag);
BH.Pass(player.gameObject, ballTransform.gameObject, playerHandTransform.position, target);
PV.RPC("RPC_DisableBallOfTarget", RpcTarget.AllBuffered, target.GetPhotonView().ViewID);
}
}
}
}
}
}
}
}
[PunRPC]
public void RPC_DisableBallOfTarget(int viewId)
{
BallHandling BH = PhotonView.Find(viewId).GetComponent<BallHandling>();
BH.ball = null;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/CameraLookAtTransition.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class CameraLookAtTransition : MonoBehaviour {
//[SerializeField]
private Transform playerLookAtPoint;
//[SerializeField]
private Transform ballLookAtPoint;
//[SerializeField]
private bool lookAtBall;
//[SerializeField]
private CinemachineFreeLook vFreeCam;
[SerializeField]
private CinemachineVirtualCamera vCam;
//[SerializeField]
private CinemachineCollider collCineMachine;
[SerializeField]
private float transoitionAngleSpeed;
private VirtualCamVarSet varSet;
private void Start()
{
lookAtBall = false;
vFreeCam = transform.GetComponent<CinemachineFreeLook>();
collCineMachine = transform.GetComponent<CinemachineCollider>();
if (GameObject.FindGameObjectWithTag("Ball") != null)
ballLookAtPoint = GameObject.FindGameObjectWithTag("Ball").transform;
playerLookAtPoint = vFreeCam.LookAt;
varSet = transform.GetComponent<VirtualCamVarSet>();
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.C))
{
Switch(lookAtBall);
}
if(lookAtBall)
{
if (collCineMachine.m_Strategy != CinemachineCollider.ResolutionStrategy.PreserveCameraDistance)
{
vFreeCam.m_XAxis.m_InputAxisName = "";
vFreeCam.m_YAxis.m_InputAxisName = "";
collCineMachine.m_Strategy = CinemachineCollider.ResolutionStrategy.PreserveCameraDistance;
varSet.SetLookAtBallVar();
vFreeCam.m_Priority = 50;
vCam.m_Priority = 51;
}
//Vector3 directionFromPlayer = ((ballLookAtPoint.position - playerLookAtPoint.position));
//vFreeCam.m_XAxis.Value = AngleXValueSet(directionFromPlayer);
//vFreeCam.m_YAxis.Value = AngleYValueSet(directionFromPlayer);
}
else
{
if (collCineMachine.m_Strategy != CinemachineCollider.ResolutionStrategy.PreserveCameraHeight)
{
vFreeCam.m_Priority = 51;
vCam.m_Priority = 50;
vFreeCam.m_XAxis.m_InputAxisName = "Mouse X";
vFreeCam.m_YAxis.m_InputAxisName = "Mouse Y";
collCineMachine.m_Strategy = CinemachineCollider.ResolutionStrategy.PreserveCameraHeight;
varSet.SetFreeCamVars();
}
}
}
public void Switch(bool lookAtBool)
{
lookAtBall = !lookAtBool;
//if (lookAtBall)
// vFreeCam.LookAt = ballLookAtPoint;
//else
// vFreeCam.LookAt = playerLookAtPoint;
}
private float AngleXValueSet(Vector3 directionFromPlayer)
{
//X
float upX = playerLookAtPoint.up.x;
float upY = playerLookAtPoint.up.y;
float upZ = playerLookAtPoint.up.z;
if (upX < 0)
upX = -upX;
if (upY < 0)
upY = -upY;
if (upZ < 0)
upZ = -upZ;
float dX = directionFromPlayer.x * upX;
float dY = directionFromPlayer.y * upY;
float dZ = directionFromPlayer.z * upZ;
directionFromPlayer = new Vector3((directionFromPlayer.x - dX), (directionFromPlayer.y - dY), (directionFromPlayer.z - dZ));
float angleX = Vector3.Angle(directionFromPlayer, playerLookAtPoint.forward);
Vector3 nVector3 = new Vector3(playerLookAtPoint.forward.x, playerLookAtPoint.forward.y, playerLookAtPoint.forward.z);
if (nVector3.x < 0)
nVector3 = new Vector3(-playerLookAtPoint.forward.x, playerLookAtPoint.forward.y, playerLookAtPoint.forward.z);
if (nVector3.y < 0)
nVector3 = new Vector3(playerLookAtPoint.forward.x, -playerLookAtPoint.forward.y, playerLookAtPoint.forward.z);
if (nVector3.z < 0)
nVector3 = new Vector3(playerLookAtPoint.forward.x, playerLookAtPoint.forward.y, -playerLookAtPoint.forward.z);
Vector3 cross = Vector3.Cross(directionFromPlayer.normalized, nVector3);
// crossX
if (cross.x > 0 && playerLookAtPoint.up.x > 0)
{
Debug.Log("x > 0");
angleX = -angleX;
}
else if (cross.x < 0 && playerLookAtPoint.up.x < 0)
{
Debug.Log("x < 0");
angleX = -angleX;
}
//crossY
else if (cross.y > 0 && playerLookAtPoint.up.y > 0)
{
Debug.Log("y > 0");
angleX = -angleX;
}
else if (cross.y < 0 && playerLookAtPoint.up.y < 0)
{
Debug.Log("y < 0");
angleX = -angleX;
}
// crossZ
else if (cross.z > 0 && playerLookAtPoint.up.z > 0)
{
Debug.Log("z > 0");
angleX = -angleX;
}
else if (cross.z < 0 && playerLookAtPoint.up.z < 0)
{
Debug.Log("z < 0");
angleX = -angleX;
}
return angleX;
}
private float AngleYValueSet(Vector3 directionFromPlayer)
{
// max: 1 +
// min: 0
/*
/|
/ |
/ |
/\ / |
/ \ / |
/ \ / |
/ \ / |
/ \ / |
/ \/ |
<---------------------|
\ /\ |
\ / \ |
\ / \ |
\ / \ |
\ / \ |
\/ \ |
\ |
\ |
\|
*/
float rightX = playerLookAtPoint.right.x;
float rightY = playerLookAtPoint.right.y;
float rightZ = playerLookAtPoint.right.z;
if (rightX < 0)
rightX = -rightX;
if (rightY < 0)
rightY = -rightY;
if (rightZ < 0)
rightZ = -rightZ;
float dX = directionFromPlayer.x * rightX;
float dY = directionFromPlayer.y * rightY;
float dZ = directionFromPlayer.z * rightZ;
directionFromPlayer = new Vector3((directionFromPlayer.x - dX), (directionFromPlayer.y - dY), (directionFromPlayer.z - dZ));
float angleY = Vector3.Angle(directionFromPlayer, playerLookAtPoint.up);
Debug.Log("angleY: " + angleY);
float yValue = (angleY / 180);
//Debug.Log("yValue: " + yValue);
return yValue;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ballSpawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ballSpawner : MonoBehaviour
{
public GameObject ballPrefab;
public Transform ballSpawn;
public float timer;
private bool spawned = false;
// Use this for initialization
void Start ()
{
timer = 5;
}
// Update is called once per frame
void Update ()
{
timer -= Time.deltaTime;
if(timer < 0 && !spawned)
{
SpawnBall();
spawned = true;
}
}
public void SpawnBall()
{
GameObject tempBall = Instantiate(ballPrefab, ballSpawn.position, ballSpawn.rotation);
tempBall.transform.parent = null;
//NetworkServer.Spawn(tempBall);
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/PlayerNetwork.cs
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PlayerNetwork : MonoBehaviour {
public static PlayerNetwork Instance;
public string PlayerName;
// Use this for initialization
void Awake () {
Instance = this;
PlayerName = "Player-" + PhotonNetwork.LocalPlayer.ActorNumber + "#" + Random.Range(1000, 99999);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Chat.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Chat : MonoBehaviour
{
// Colors
[SerializeField]
private Color AllChatColor;
[SerializeField]
private Color TeamChatColor;
[SerializeField]
private Color ConsoleColor;
// Chat Queues
private Queue<ChatEntry> EveryEntry = new Queue<ChatEntry>(); // Entry List 0 - Does not include console logs
private Queue<ChatEntry> GlobalChatEntries = new Queue<ChatEntry>(); // Entry List 1
private Queue<ChatEntry> TeamChatEntries = new Queue<ChatEntry>(); // Entry List 2
private Queue<ChatEntry> ConsoleEntries = new Queue<ChatEntry>(); // Entry List 3
// Ui Elements
[SerializeField]
private ChatEntry ChatEntryPrefab;
[SerializeField]
private GameObject AllChatInput;
[SerializeField]
private InputField AllChatInputText;
[SerializeField]
private Text AllChatName;
[SerializeField]
private GameObject TeamChatInput;
[SerializeField]
private InputField TeamChatInputText;
[SerializeField]
private Text TeamChatName;
[SerializeField]
private GameObject ConsoleInput;
[SerializeField]
private InputField ConsoleInputText;
[SerializeField]
private Text ConsoleChatName;
[SerializeField]
private RawImage PlayerNameBackground;
[SerializeField]
private RectTransform ScrollContentStartingPoint;
[SerializeField]
private List<Behaviour> UiObjectsToDisableAfterTime = new List<Behaviour>();
[SerializeField]
private List<Behaviour> UiObjectsToDisableOnExit = new List<Behaviour>();
[SerializeField]
private GameObject ChatParent;
// Player Elements
[SerializeField]
private NetPlayer NP;
// Other Player Chats
private Chat[] ChatList;
// Bool Checks
private bool EnabledChat = false;
// Variables
[SerializeField]
private float TimeToDiableElements = 10;
private float DisableTimer = 0;
private bool timerActive = false;
[SerializeField]
private float ContentSpacing = 3;
[SerializeField]
private int MaxEntries = 15;
[SerializeField]
private bool EraseConsoleEntries = false;
private int EntryList = 0; // The entry that will be shown in the text box
private int EntryCount = 0;
//ConsoleVariables
[SerializeField]
private bool IgnoreLogs = true;
[SerializeField]
private bool IgnoreWarnings = false;
[SerializeField]
private bool IgnoreErrors = false;
[SerializeField]
private bool IgnoreCopies = true;
//photon
private PhotonView PV;
void Awake()
{
PV = GetComponent<PhotonView>();
}
void Start()
{
AllChatName.text = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
TeamChatName.text = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
ConsoleChatName.text = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
}
// Update is called once per frame
void Update () {
if (PV.IsMine)
{
if (EnabledChat)
{
UpdateDisplay();
if (Input.GetKeyDown(KeyCode.Escape))
{
ToggleChat();
}
if (Input.GetKeyDown(KeyCode.Tab) && !Input.GetKey(KeyCode.LeftShift))
{
ToggleMessege();
}
if (Input.GetKey(KeyCode.LeftShift))
{
if (Input.GetKeyDown(KeyCode.Tab))
{
ToggleEntries();
}
}
}
else if (timerActive)
{
DisableTimer += Time.deltaTime;
if (DisableTimer > TimeToDiableElements)
{
DisableTimer = 0;
timerActive = false;
DisableComponents();
}
}
//Application.logMessageReceived += LogCall;
}
// Limit the number of entries
if (EveryEntry.Count > MaxEntries)
{
ChatEntry temp = EveryEntry.Dequeue();
if (!GlobalChatEntries.Contains(temp) && !TeamChatEntries.Contains(temp) && !ConsoleEntries.Contains(temp))
{
Destroy(temp.gameObject);
}
}
if (GlobalChatEntries.Count > MaxEntries)
{
ChatEntry temp = GlobalChatEntries.Dequeue();
if (!EveryEntry.Contains(temp) && !TeamChatEntries.Contains(temp) && !ConsoleEntries.Contains(temp))
{
Destroy(temp.gameObject);
}
}
if (TeamChatEntries.Count > MaxEntries)
{
ChatEntry temp = TeamChatEntries.Dequeue();
if (!GlobalChatEntries.Contains(temp) && !EveryEntry.Contains(temp) && !ConsoleEntries.Contains(temp))
{
Destroy(temp.gameObject);
}
}
if (EraseConsoleEntries)
{
if (ConsoleEntries.Count > MaxEntries)
{
ChatEntry temp = ConsoleEntries.Dequeue();
if (!GlobalChatEntries.Contains(temp) && !TeamChatEntries.Contains(temp) && !EveryEntry.Contains(temp))
{
Destroy(temp.gameObject);
}
}
}
}
private void LogCall(string logString, string stackTrace, LogType type)
{
if (type == LogType.Error)
{
if(!IgnoreErrors)
CreateConsoleEntry("Error", " -LogString- " + logString + " -StackTrace- " + stackTrace);
}
else if (type == LogType.Log)
{
if(!IgnoreLogs)
CreateConsoleEntry("Log", " -LogString- " + logString + " -StackTrace- " + stackTrace);
}
else if (type == LogType.Warning)
{
if (!IgnoreWarnings)
CreateConsoleEntry("Warning", " -LogString- " + logString + " -StackTrace- " + stackTrace);
}
else if (type == LogType.Assert)
{
CreateConsoleEntry("Assert", " -LogString- " + logString + " -StackTrace- " + stackTrace);
}
else if (type == LogType.Exception)
{
CreateConsoleEntry("Exception", " -LogString- " + logString + " -StackTrace- " + stackTrace);
}
}
public bool GetEnabled()
{
return EnabledChat;
}
public void CreateGlobalEntry(string text)
{
//print("Create Entry Global");
//CmdCreateEntry(gameObject.name, text, "All", this.gameObject);
PV.RPC("RPC_CreateEntry", RpcTarget.All, NP.DisplayName, text, "All", PV.ViewID);
}
public void CreateTeamEntry(string text)
{
//print("Create Entry Team");
//CmdCreateEntry(gameObject.name, text, "Team" + NP.GetTeamNum(), this.gameObject);
PV.RPC("RPC_CreateEntry", RpcTarget.All, NP.DisplayName, text, "Team" + NP.GetTeamNum(), PV.ViewID);
}
public void CreateConsoleEntry(string text)
{
CreateConsoleEntry(NP.DisplayName, text);
}
public void EnterEntry(ChatEntry Entry)
{
ChatEntry temp = Instantiate(Entry, ScrollContentStartingPoint);
//Debug.Log("Enter Entry");
if (temp.EntryType == "All")
{
//Debug.Log("Enter Entry ALL");
if (!GlobalChatEntries.Contains(temp))
{
//Debug.Log("Enter Entry ALL in");
EveryEntry.Enqueue(temp);
GlobalChatEntries.Enqueue(temp);
RefreshUi();
}
}
else if (temp.EntryType == "Team1")
{
//Debug.Log("Enter Entry Team1");
if (NP.GetTeamNum() == 1)
{
if (!TeamChatEntries.Contains(temp))
{
//Debug.Log("Enter Entry Team1 in");
EveryEntry.Enqueue(temp);
TeamChatEntries.Enqueue(temp);
RefreshUi();
}
}
else
{
Destroy(temp);
}
}
else if (temp.EntryType == "Team2")
{
//Debug.Log("Enter Entry Team2");
if (NP.GetTeamNum() == 2)
{
if (!TeamChatEntries.Contains(temp))
{
//Debug.Log("Enter Entry Team2 in");
EveryEntry.Enqueue(temp);
TeamChatEntries.Enqueue(temp);
RefreshUi();
}
}
else
{
Destroy(temp);
}
}
else
{
Destroy(temp);
}
UpdateDisplay();
}
public void BroadcastEntry(ChatEntry Entry, Chat WhoBroadcasted)
{
//Debug.Log("Broadcast Entry");
ChatList = FindObjectsOfType<Chat>();
foreach (Chat c in ChatList)
{
if (c != WhoBroadcasted)
c.EnterEntry(Entry);
c.UpdateDisplay();
}
}
public void RefreshUi()
{
if (NP.LocalPlayer == NP)
{
EnableUI();
EnableComponents();
DisableUI();
}
}
public void ReEnterChat(string text)
{
if (text == "")
{
//ToggleMessege();
}
else
{
ToggleChat();
}
}
private void TurnOffAllEntries()
{
foreach(ChatEntry c in EveryEntry)
{
c.gameObject.SetActive(false);
}
foreach(ChatEntry c in ConsoleEntries)
{
c.gameObject.SetActive(false);
}
}
public void UpdateDisplay()
{
int count = 0;
//CheckForNewEntries();
TurnOffAllEntries();
if (EntryList == 0)
{
count = EveryEntry.Count;
foreach (ChatEntry c in EveryEntry)
{
count--;
RectTransform rt = c.GetComponent<RectTransform>();
if (rt.transform.parent != ScrollContentStartingPoint)
{
rt.parent = ScrollContentStartingPoint;
}
rt.localPosition = new Vector3(rt.localPosition.x, -count * (ContentSpacing), 0);
c.gameObject.SetActive(true);
}
}
else if (EntryList == 1)
{
count = GlobalChatEntries.Count;
foreach (ChatEntry c in GlobalChatEntries)
{
count--;
RectTransform rt = c.GetComponent<RectTransform>();
if (rt.transform.parent != ScrollContentStartingPoint)
{
rt.parent = ScrollContentStartingPoint;
}
rt.localPosition = new Vector3(rt.localPosition.x, -count * (ContentSpacing), 0);
c.gameObject.SetActive(true);
}
}
else if (EntryList == 2)
{
count = TeamChatEntries.Count;
foreach (ChatEntry c in TeamChatEntries)
{
count--;
RectTransform rt = c.GetComponent<RectTransform>();
if (rt.transform.parent != ScrollContentStartingPoint)
{
rt.parent = ScrollContentStartingPoint;
}
rt.localPosition = new Vector3(rt.localPosition.x, -count * (ContentSpacing), 0);
c.gameObject.SetActive(true);
}
}
else if (EntryList == 3)
{
count = ConsoleEntries.Count;
foreach (ChatEntry c in ConsoleEntries)
{
count--;
RectTransform rt = c.GetComponent<RectTransform>();
if (rt.transform.parent != ScrollContentStartingPoint)
{
rt.parent = ScrollContentStartingPoint;
}
rt.localPosition = new Vector3(rt.localPosition.x, -count * (ContentSpacing + 30 * 2), 0);
c.gameObject.SetActive(true);
}
}
}
private void CheckForNewEntries()
{
ChatEntry[] CEList = ChatParent.GetComponentsInChildren<ChatEntry>();
foreach(ChatEntry c in CEList)
{
if (!EveryEntry.Contains(c) && c.EntryType != "Console")
{
if (c.EntryType == "All")
EveryEntry.Enqueue(c);
else if (NP.GetTeamNum() == c.EntryPerson.GetComponent<NetPlayer>().GetTeamNum())
EveryEntry.Enqueue(c);
}
else if (NP.GetTeamNum() == 1)
{
if (c.EntryPerson.GetComponent<NetPlayer>().GetTeamNum() == 1)
{
if (!TeamChatEntries.Contains(c))
{
TeamChatEntries.Enqueue(c);
}
}
}
else if (NP.GetTeamNum() == 2)
{
if (c.EntryPerson.GetComponent<NetPlayer>().GetTeamNum() == 2)
{
if (!TeamChatEntries.Contains(c))
{
TeamChatEntries.Enqueue(c);
}
}
}
}
}
public void CreateConsoleEntry(string name, string text)
{
if (IgnoreCopies)
{
bool CompleteCommand = true;
foreach (ChatEntry c in ConsoleEntries)
{
if (c.EntryText == name + ": " + text)
{
CompleteCommand = false;
break;
}
}
if (CompleteCommand)
{
ChatEntry temp = Instantiate(ChatEntryPrefab, ScrollContentStartingPoint);
EntryCount++;
temp.CreateMessege(name + ": " + text, ConsoleColor, "Console", EntryCount, gameObject);
ConsoleEntries.Enqueue(temp);
if (EntryList != 3)
{
temp.gameObject.SetActive(false);
}
}
}
}
[PunRPC]
public void RPC_CreateEntry(string name, string text, string entryType, int WhoEnteredViewID)
{
if (text != "")
{
if (entryType != "Console")
{
print("Create Entry RPC");
GameObject playerWhoMadeText = PhotonView.Find(WhoEnteredViewID).gameObject;
CreateEntry(name, text, entryType, playerWhoMadeText);
}
}
}
public void CreateEntry(string name, string text, string entryType, GameObject WhoEntered)
{
print("Create Entry");
ChatEntry temp = Instantiate(ChatEntryPrefab, ScrollContentStartingPoint);
if (entryType == "All")
{
EntryCount++;
temp.CreateMessege(name + ": " + text, AllChatColor, entryType, EntryCount, gameObject);
GlobalChatEntries.Enqueue(temp);
EveryEntry.Enqueue(temp);
if (EntryList != 0)
{
temp.gameObject.SetActive(false);
}
BroadcastEntry(temp, WhoEntered.GetComponent<Chat>());
}
else if (entryType == "Team1")
{
if (NP.GetTeamNum() == 1)
{
EntryCount++;
temp.CreateMessege(name + ": " + text, TeamChatColor, entryType, EntryCount, gameObject);
TeamChatEntries.Enqueue(temp);
EveryEntry.Enqueue(temp);
if (EntryList != 1)
{
temp.gameObject.SetActive(false);
}
BroadcastEntry(temp, WhoEntered.GetComponent<Chat>());
}
}
else if (entryType == "Team2")
{
if (NP.GetTeamNum() == 2)
{
EntryCount++;
temp.CreateMessege(name + ": " + text, TeamChatColor, entryType, EntryCount, gameObject);
TeamChatEntries.Enqueue(temp);
EveryEntry.Enqueue(temp);
if (EntryList != 2)
{
temp.gameObject.SetActive(false);
}
BroadcastEntry(temp, WhoEntered.GetComponent<Chat>());
}
}
else if (entryType == "Console")
{
EntryCount++;
temp.CreateMessege(name + ": " + text, ConsoleColor, entryType, EntryCount, gameObject);
ConsoleEntries.Enqueue(temp);
if (EntryList != 3)
{
temp.gameObject.SetActive(false);
}
}
}
public void EnterChat(bool b = true)
{
if (EnabledChat == false && b == true)
{
EnableComponents();
}
else if (EnabledChat == true && b == false)
{
DisableComponents();
}
EnabledChat = b;
}
public void ToggleChat()
{
if (EnabledChat == false)
{
EnableUI();
EnableComponents();
UpdateDisplay();
TeamChatInputText.ActivateInputField();
}
else
{
DisableUI();
timerActive = true;
}
EnabledChat = !EnabledChat;
}
private void EnableComponents()
{
DisableTimer = 0;
timerActive = true;
PlayerNameBackground.gameObject.SetActive(true);
ChatParent.SetActive(true);
foreach (Behaviour b in UiObjectsToDisableAfterTime)
{
b.enabled = true;
}
}
private void DisableComponents()
{
timerActive = false;
ChatParent.SetActive(false);
foreach (Behaviour b in UiObjectsToDisableAfterTime)
{
b.enabled = false;
}
}
private void EnableUI()
{
foreach (Behaviour b in UiObjectsToDisableOnExit)
{
b.enabled = true;
}
TeamChatInput.SetActive(true);
}
private void DisableUI()
{
foreach (Behaviour b in UiObjectsToDisableOnExit)
{
b.enabled = false;
}
AllChatInput.SetActive(false);
TeamChatInput.SetActive(false);
ConsoleInput.SetActive(false);
}
public void ToggleEntries()
{
EntryList++;
if (EntryList == 4)
{
EntryList = 0;
}
if (EntryList == 0)
{
foreach (ChatEntry CE in ConsoleEntries)
{
CE.gameObject.SetActive(false);
}
foreach (ChatEntry CE in EveryEntry)
{
CE.gameObject.SetActive(true);
}
}
if (EntryList == 1)
{
foreach (ChatEntry CE in EveryEntry)
{
CE.gameObject.SetActive(false);
}
foreach (ChatEntry CE in GlobalChatEntries)
{
CE.gameObject.SetActive(true);
}
}
if (EntryList == 2)
{
foreach (ChatEntry CE in GlobalChatEntries)
{
CE.gameObject.SetActive(false);
}
foreach (ChatEntry CE in TeamChatEntries)
{
CE.gameObject.SetActive(true);
}
}
if (EntryList == 3)
{
foreach (ChatEntry CE in TeamChatEntries)
{
CE.gameObject.SetActive(false);
}
foreach (ChatEntry CE in ConsoleEntries)
{
CE.gameObject.SetActive(true);
}
}
UpdateDisplay();
}
// Toggle type of messege you are writing
private void ToggleMessege()
{
if (AllChatInput.activeSelf)
{
string tempMsg = AllChatInputText.text;
AllChatInputText.text = "";
AllChatInput.SetActive(false);
TeamChatInput.SetActive(true);
TeamChatInputText.text = tempMsg;
TeamChatInputText.ActivateInputField();
}
else if (TeamChatInput.activeSelf)
{
string tempMsg = TeamChatInputText.text;
TeamChatInputText.text = "";
ConsoleInput.SetActive(true);
TeamChatInput.SetActive(false);
ConsoleInputText.text = tempMsg;
ConsoleInputText.ActivateInputField();
}
else if (ConsoleInput.activeSelf)
{
string tempMsg = ConsoleInputText.text;
ConsoleInputText.text = "";
ConsoleInput.SetActive(false);
AllChatInput.SetActive(true);
AllChatInputText.text = tempMsg;
AllChatInputText.ActivateInputField();
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/SwipeCredits.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SwipeCredits : MonoBehaviour {
[SerializeField]
private int numberOfCreditSections;
// [SerializeField]
//private Vector2 targetPosition;
[SerializeField]
private float acceleration;
[SerializeField]
private Transform slide;
private int currentSlide = 0;
[SerializeField]
private float distanceBetweenObjs;
private bool directionIsRight;
private float xTarget;
[SerializeField]
private GameObject nextButton;
[SerializeField]
private GameObject prevButton;
public void DirectionRight(bool right)
{
directionIsRight = right;
if(directionIsRight)
{
xTarget -= distanceBetweenObjs;
currentSlide++;
}
else
{
xTarget += distanceBetweenObjs;
currentSlide--;
}
Debug.Log("is it right: " + directionIsRight);
}
private void FixedUpdate()
{
if(nextButton.activeInHierarchy)
{
if(currentSlide == (numberOfCreditSections - 1))
{
nextButton.SetActive(false);
}
}
else
{
if(currentSlide != (numberOfCreditSections - 1))
{
nextButton.SetActive(true);
}
}
if (prevButton.activeInHierarchy)
{
if (currentSlide == 0)
{
prevButton.SetActive(false);
}
}
else
{
if (currentSlide != 0)
{
prevButton.SetActive(true);
}
}
slide.localPosition += new Vector3(((xTarget - slide.localPosition.x) / acceleration), 0, 0);
//selectedRect.localPosition += new Vector3(0, (target.localPosition.y - selectedRect.localPosition.y) / acceleration, 0);
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/InGameMenu.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Photon.Pun;
using Photon.Realtime;
public class InGameMenu : MonoBehaviourPunCallbacks {
[SerializeField]
private PhotonView PV;
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
SceneManager.LoadScene(0);
}
public void CloseGame()
{
Application.Quit();
}
private void OnApplicationQuit()
{
PhotonNetwork.LeaveRoom();
PhotonNetwork.LeaveLobby();
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ThirdPersonController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(Rigidbody))]
//[RequireComponent(typeof(ConfigurableJoint))]
public class ThirdPersonController : NetworkBehaviour {
// Serielized
// Movement
[SerializeField]
private float AccerationForce = 100000;
[SerializeField]
public float MaxVelocity = 20;
[SerializeField]
private float TurningForce = 10000;
[SerializeField]
private float MaxAngularVelocity = 180;
[SerializeField]
private float JumpForce = 250;
[SerializeField]
private float SpeedSlow = 80;
[SerializeField]
private float TurnSlow = 200;
// Character Attributes
[SerializeField]
private float PlayerMass = 80;
[SerializeField]
private float FloatDistance = 0.2f;
[SerializeField]
private LayerMask GroundLayer;
[SerializeField]
private Transform Feet;
[SerializeField]
private Spring CharacterSpring;
// Not Serielized
// Player components
private Rigidbody RB;
private Transform Trans;
//private ConfigurableJoint CJ;
// Active attributes
private float Speed = 0;
private float AngularSpeed = 0;
private float Acceleration = 0;
private float TurningAcceleration = 0;
private bool onGround = true;
// Recieved attributes
private float MoveAxis = 0;
private float TurnAxis = 0;
private float JumpAxis = 0;
public GameObject camGurl;
public GameObject camGurl2;
void Start () {
//Physics.gravity = new Vector3(0, -9.81f, 0);
Cursor.lockState = CursorLockMode.Locked;
RB = GetComponent<Rigidbody>();
RB.mass = PlayerMass;
//CJ = GetComponent<ConfigurableJoint>();
//CJ.connectedAnchor = new Vector3(0, FloatDistance, 0);
Trans = transform;
//local player camera
if(isLocalPlayer)
{
camGurl.SetActive(true);
camGurl2.SetActive(true);
}
else
{
camGurl.SetActive(false);
camGurl2.SetActive(false);
}
}
// Update is called once per frame
void Update () {
//local player control
if (isLocalPlayer)
{
// Get Axis of Movement
MoveAxis = Input.GetAxis("Move");
TurnAxis = Input.GetAxis("Turn");
//Debug.Log("Move Axis: " + MoveAxis);
//Debug.Log("Turn Axis: " + TurnAxis);
// Accelerate/ Deccelerate
// Speed
if (MoveAxis > 0.1f || MoveAxis < -0.1)
{
if (Mathf.Abs(Speed) <= MaxVelocity)
{
Acceleration = MoveAxis * AccerationForce * Time.deltaTime / PlayerMass;
}
else
{
Acceleration = 0;
}
}
else
{
Acceleration = 0;
if (Mathf.Abs(Speed) > 5f)
{
Speed -= Speed * SpeedSlow * Time.deltaTime / 100;
}
else if (Mathf.Abs(Speed) > 1f)
{
Speed -= Speed * 95 * Time.deltaTime / 100;
}
else if (Mathf.Abs(Speed) > 0.1f)
{
Speed -= Speed * 99 * Time.deltaTime / 100;
}
else
Speed = 0;
}
// Turning
if (TurnAxis > 0.1f || TurnAxis < -0.1)
{
if (Mathf.Abs(AngularSpeed) <= MaxAngularVelocity)
{
TurningAcceleration = TurnAxis * TurningForce * Time.deltaTime * 180 / PlayerMass;
}
else
{
TurningAcceleration = 0;
}
}
else
{
TurningAcceleration = 0;
if (Mathf.Abs(AngularSpeed) > 10)
{
AngularSpeed -= AngularSpeed * TurnSlow * Time.deltaTime / 100;
}
else
{
AngularSpeed = 0;
}
}
// Move Player
Speed += Acceleration * Time.deltaTime;
if (Speed > MaxVelocity)
{
Speed = MaxVelocity;
}
else if (Speed < -MaxVelocity)
{
Speed = -MaxVelocity;
}
//Debug.Log("Speed: " + Speed + " Acceleration: " + Acceleration);
Trans.position += Trans.forward * Speed * Time.deltaTime;
// Turn Player
AngularSpeed += TurningAcceleration;
if (AngularSpeed > MaxAngularVelocity)
{
AngularSpeed = MaxAngularVelocity;
}
else if (AngularSpeed < -MaxAngularVelocity)
{
AngularSpeed = -MaxAngularVelocity;
}
//Debug.Log("Angular Speed: " + AngularSpeed + " Angular Acceleration: " + TurningAcceleration);
Trans.Rotate(0, AngularSpeed * Time.deltaTime, 0);
// Jump
JumpAxis = Input.GetAxis("Jump");
onGround = Physics.Raycast(Feet.position, Vector3.down, FloatDistance + 0.3f, GroundLayer);
//Debug.Log("Jump Axis: " + JumpAxis);
if (onGround)
{
CharacterSpring.enabled = true;
Debug.Log("ON GROUND");
}
else
{
CharacterSpring.enabled = false;
Debug.Log("NOT ON GROUND");
}
if (JumpAxis > 0.1f && onGround)
{
RB.AddForce(Trans.up * JumpForce, ForceMode.Impulse);
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/AutoRotation.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoRotation : MonoBehaviour {
// Adjustables
[SerializeField]
private float RotationForce = 50;
// Components
[SerializeField]
private hoverBoardScript HBS;
[SerializeField]
private Transform Cam;
[SerializeField]
private Transform HelperSpaceCam;
// Hiddenn variables
[HideInInspector]
public bool IsActive = true;
private bool PlayerSetActive = true;
private Vector3 DirectionHelper;
private Vector3 DirectionCam;
private string Rotate = "No";
private string LastRotate = "Null";
// Update is called once per frame
void Update () {
// Set if the player wants autorotation on
if (Input.GetKeyDown(KeyCode.Z))
{
PlayerSetActive = !PlayerSetActive;
}
// If the players autorotation is active, rotatte
if (IsActive && PlayerSetActive)
{
HelperSpaceCam.position = Cam.position;
HelperSpaceCam.localPosition -= new Vector3(0, HelperSpaceCam.localPosition.y, 0);
LastRotate = Rotate;
// Camera is left of the player
if (HelperSpaceCam.localPosition.x < 0)
{
Rotate = "Right";
}
// Camera is right of the player
else if (HelperSpaceCam.localPosition.x > 0)
{
Rotate = "Left";
}
if (LastRotate == "Left" && Rotate == "Right")
Rotate = "No";
else if (LastRotate == "Right" && Rotate == "Left")
Rotate = "No";
LastRotate = Rotate;
if (Rotate == "Right")
{
HBS.RotateHoverBoard(RotationForce);
}
else if (Rotate == "Left")
{
HBS.RotateHoverBoard(-RotationForce);
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/VirtualCamVarSet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class VirtualCamVarSet : MonoBehaviour {
[SerializeField]
private float positionDampingFreeCam;
[SerializeField]
private float rotationDampingFreeCam;
//
[SerializeField]
private float positionDampingBallCam;
[SerializeField]
private float rotationDampingBallCam;
//[SerializeField]
//private float lookAtSoftDampingHeightFreeCam;
//[SerializeField]
//private float lookAtSoftDampingWidthFreeCam;
//[SerializeField]
//private float lookAtHardDampingHeightFreeCam;
//[SerializeField]
//private float lookAtHardDampingWidthFreeCam;
[SerializeField]
private Transform pCameraObject;
[SerializeField]
private LayerMask lMask;
[SerializeField]
private Transform lookAtTransform;
// rig transposer 0
CinemachineTransposer transposerVirtualCamera_Rig0;
// rig transposer 1
CinemachineTransposer transposerVirtualCamera_Rig1;
// rig transposer 2
CinemachineTransposer transposerVirtualCamera_Rig2;
CinemachineFreeLook freeLookVirtualCamera;
[SerializeField]
private float[] heightsFree;
[SerializeField]
private float[] radiusFree;
[SerializeField]
private float[] heightsBall;
[SerializeField]
private float[] radiusBall;
// Use this for initialization
void Start () {
freeLookVirtualCamera = transform.GetComponent<CinemachineFreeLook>();
transposerVirtualCamera_Rig0 = freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineTransposer>();
transposerVirtualCamera_Rig1 = freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineTransposer>();
transposerVirtualCamera_Rig2 = freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineTransposer>();
pCameraObject.parent = null;
gameObject.AddComponent<CinemachineCollider>().m_CollideAgainst = lMask;
SetFreeCamVars();
}
public void SetFreeCamVars()
{
//// Top Rig
// position damping
transposerVirtualCamera_Rig0.m_XDamping = positionDampingFreeCam;
transposerVirtualCamera_Rig0.m_YDamping = positionDampingFreeCam;
transposerVirtualCamera_Rig0.m_ZDamping = positionDampingFreeCam;
//rotation damping
transposerVirtualCamera_Rig0.m_PitchDamping = rotationDampingFreeCam;
transposerVirtualCamera_Rig0.m_YawDamping = rotationDampingFreeCam;
transposerVirtualCamera_Rig0.m_RollDamping = rotationDampingFreeCam;
//// look at damping
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneHeight = lookAtSoftDampingHeight;
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneWidth = lookAtSoftDampingWidth;
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneHeight = lookAtHardDampingHeight;
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = lookAtHardDampingWidth;
//// Middle Rig
//position damping
transposerVirtualCamera_Rig1.m_XDamping = positionDampingFreeCam;
transposerVirtualCamera_Rig1.m_YDamping = positionDampingFreeCam;
transposerVirtualCamera_Rig1.m_ZDamping = positionDampingFreeCam;
//rotation damping
transposerVirtualCamera_Rig1.m_PitchDamping = rotationDampingFreeCam;
transposerVirtualCamera_Rig1.m_YawDamping = rotationDampingFreeCam;
transposerVirtualCamera_Rig1.m_RollDamping = rotationDampingFreeCam;
//// look at damping
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneHeight = lookAtSoftDampingHeight;
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneWidth = lookAtSoftDampingWidth;
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneHeight = lookAtHardDampingHeight;
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = lookAtHardDampingWidth;
//// Bottom Rig
// position damping
transposerVirtualCamera_Rig2.m_XDamping = positionDampingFreeCam;
transposerVirtualCamera_Rig2.m_YDamping = positionDampingFreeCam;
transposerVirtualCamera_Rig2.m_ZDamping = positionDampingFreeCam;
//rotation damping
transposerVirtualCamera_Rig2.m_PitchDamping = rotationDampingFreeCam;
transposerVirtualCamera_Rig2.m_YawDamping = rotationDampingFreeCam;
transposerVirtualCamera_Rig2.m_RollDamping = rotationDampingFreeCam;
//// look at damping
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneHeight = lookAtSoftDampingHeight;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneWidth = lookAtSoftDampingWidth;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneHeight = lookAtHardDampingHeight;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = lookAtHardDampingWidth;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = 0.1f;
//// orbit
try
{
//top
freeLookVirtualCamera.m_Orbits[0].m_Height = heightsFree[0];
freeLookVirtualCamera.m_Orbits[0].m_Radius = radiusFree[0];
}
catch
{
Debug.LogWarning("Out of range exception '0'");
}
try
{
// middle
freeLookVirtualCamera.m_Orbits[1].m_Height = heightsFree[1];
freeLookVirtualCamera.m_Orbits[1].m_Radius = radiusFree[1];
}
catch
{
Debug.LogWarning("Out of range exception '1'");
}
try
{
// bottom
freeLookVirtualCamera.m_Orbits[2].m_Height = heightsFree[2];
freeLookVirtualCamera.m_Orbits[2].m_Radius = radiusFree[2];
}
catch
{
Debug.LogWarning("Out of range exception '2'");
}
}
public void SetLookAtBallVar()
{
//// Top Rig
// position damping
transposerVirtualCamera_Rig0.m_XDamping = positionDampingBallCam;
transposerVirtualCamera_Rig0.m_YDamping = positionDampingBallCam;
transposerVirtualCamera_Rig0.m_ZDamping = positionDampingBallCam;
//rotation damping
transposerVirtualCamera_Rig0.m_PitchDamping = rotationDampingBallCam;
transposerVirtualCamera_Rig0.m_YawDamping = rotationDampingBallCam;
transposerVirtualCamera_Rig0.m_RollDamping = rotationDampingBallCam;
//// look at damping
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneHeight = lookAtSoftDampingHeight;
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneWidth = lookAtSoftDampingWidth;
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneHeight = lookAtHardDampingHeight;
//freeLookVirtualCamera.GetRig(0).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = lookAtHardDampingWidth;
//// Middle Rig
//position damping
transposerVirtualCamera_Rig1.m_XDamping = positionDampingBallCam;
transposerVirtualCamera_Rig1.m_YDamping = positionDampingBallCam;
transposerVirtualCamera_Rig1.m_ZDamping = positionDampingBallCam;
//rotation damping
transposerVirtualCamera_Rig1.m_PitchDamping = rotationDampingBallCam;
transposerVirtualCamera_Rig1.m_YawDamping = rotationDampingBallCam;
transposerVirtualCamera_Rig1.m_RollDamping = rotationDampingBallCam;
//// look at damping
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneHeight = lookAtSoftDampingHeight;
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneWidth = lookAtSoftDampingWidth;
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneHeight = lookAtHardDampingHeight;
//freeLookVirtualCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = lookAtHardDampingWidth;
//// Bottom Rig
// position damping
transposerVirtualCamera_Rig2.m_XDamping = positionDampingBallCam;
transposerVirtualCamera_Rig2.m_YDamping = positionDampingBallCam;
transposerVirtualCamera_Rig2.m_ZDamping = positionDampingBallCam;
//rotation damping
transposerVirtualCamera_Rig2.m_PitchDamping = rotationDampingBallCam;
transposerVirtualCamera_Rig2.m_YawDamping = rotationDampingBallCam;
transposerVirtualCamera_Rig2.m_RollDamping = rotationDampingBallCam;
//// look at damping
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneHeight = lookAtSoftDampingHeight;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_SoftZoneWidth = lookAtSoftDampingWidth;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneHeight = lookAtHardDampingHeight;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = lookAtHardDampingWidth;
//freeLookVirtualCamera.GetRig(2).GetCinemachineComponent<CinemachineComposer>().m_DeadZoneWidth = 0.1f;
//// orbit
//top
freeLookVirtualCamera.m_Orbits[0].m_Height = heightsBall[0];
freeLookVirtualCamera.m_Orbits[0].m_Radius = radiusBall[0];
// middle
freeLookVirtualCamera.m_Orbits[1].m_Height = heightsBall[1];
freeLookVirtualCamera.m_Orbits[1].m_Radius = radiusBall[1];
// bottom
freeLookVirtualCamera.m_Orbits[2].m_Height = heightsBall[2];
freeLookVirtualCamera.m_Orbits[2].m_Radius = radiusBall[2];
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/RuneSpawnQueue.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class RuneSpawnQueue : MonoBehaviour {
[SerializeField]
private Rune[] RunePrefabs;
[HideInInspector]
public List<Rune> SpawnedRunes = new List<Rune>();
private GameObject currentSpawnedRune;
private bool runeDisabled;
[SerializeField]
private PhotonView PV;
public void SpawnRune()
{
if (PhotonNetwork.IsMasterClient)
{
for (int i = 0; i < RunePrefabs.Length; i++)
{
SpawnedRunes.Add(PhotonNetwork.Instantiate(RunePrefabs[i].GetRuneID(), transform.position, transform.rotation).GetComponent<Rune>());
PV.RPC("RPC_AddToRune", RpcTarget.Others, SpawnedRunes[i].GetComponent<PhotonView>().ViewID, i);
SpawnedRunes[i].GetComponent<Rune>().parentRuneSpawn = this;
SpawnedRunes[i].gameObject.SetActive(false);
}
AcivateRandomRune();
}
}
[PunRPC]
private void RPC_AddToRune(int id, int i)
{
SpawnedRunes.Add(PhotonView.Find(id).GetComponent<Rune>());
SpawnedRunes[i].GetComponent<Rune>().parentRuneSpawn = this;
SpawnedRunes[i].gameObject.SetActive(false);
}
public void CallAcivateRandomRune()
{
if(PhotonNetwork.IsMasterClient)
Invoke("AcivateRandomRune", 7);
}
private void AcivateRandomRune()
{
if (PhotonNetwork.IsMasterClient)
{
int rng = Random.Range(0, SpawnedRunes.Count);
PV.RPC("RPC_ActivateRandomRune", RpcTarget.All, SpawnedRunes[rng].PV.ViewID);
}
}
[PunRPC]
private void RPC_ActivateRandomRune(int id)
{
// PhotonView.Find(id).GetComponent<RuneSpawnQueue>().SpawnedRunes[number].gameObject.SetActive(true);
PhotonView.Find(id).gameObject.SetActive(true);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlacingTrigger.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlacingTrigger : MonoBehaviour {
[HideInInspector]
public bool TriggerActive = false;
[HideInInspector]
public bool InGround = false;
//[HideInInspector]
//public Vector3 CollisionPos = Vector3.zero;
private void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Ground" || other.gameObject.tag == "Player" || other.gameObject.tag == "Team 1" || other.gameObject.tag == "Team 2" || other.gameObject.tag == "Object" || other.gameObject.tag == "BoostPad")
{
//Debug.Log(other.gameObject.name + "P Hit - Trigger");
TriggerActive = true;
if (other.gameObject.tag == "Ground")
{
InGround = true;
}
else
{
InGround = false;
}
}
else
{
TriggerActive = false;
InGround = false;
}
}
private void OnTriggerExit(Collider other)
{
TriggerActive = false;
InGround = false;
}
//void OnCollisionEnter(Collision collision)
//{
// if (collision.gameObject.tag == "Ground" || collision.gameObject.tag == "Object" || collision.gameObject.tag == "BoostPad")
// {
// Debug.Log(collision.gameObject.name + "P Hit - Collision");
// TriggerActive = true;
// if (collision.gameObject.tag == "Ground")
// {
// InGround = true;
// }
// else
// {
// InGround = false;
// }
// }
// else
// {
// TriggerActive = false;
// }
//}
public void ResetPT()
{
TriggerActive = false;
InGround = false;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/InfluenceRotation.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InfluenceRotation : MonoBehaviour {
// restricts rotation of child y axis
private Transform lookatPoint;
// Use this for initialization
void Start () {
if(lookatPoint == null)
{
lookatPoint = transform.GetChild(0);
}
}
// Update is called once per frame
void Update () {
//Vector3 dir =child.position - (child.position + child.up);
//child.up = Vector3.Cross(dir, child.up);
//if (lookatPoint != null)
//lookatPoint.up = Vector3.Normalize(Vector3.Cross(transform.forward, transform.right));
//float x = ((transform.forward.y * transform.right.z) - (transform.forward.z * transform.right.y));
//float y = ((transform.forward.z * transform.right.x) - (transform.forward.x * transform.right.z));
//float z = ((transform.forward.x * transform.right.y) - (transform.forward.y * transform.right.x));
//lookatPoint.up = new Vector3(Mathf.Clamp(x, -1, 1), Mathf.Clamp(y, -1, 1), Mathf.Clamp(z, -1, 1)).normalized;
//Debug.Log("lookatPoint.up: " + lookatPoint.up);
//if (lookatPoint.up.y <= -0.8f)
// lookatPoint.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, 0, transform.rotation.eulerAngles.z);
lookatPoint.up = Vector3.Cross(transform.forward, transform.right);
//lookatPoint.localEulerAngles = new Vector3(lookatPoint.localEulerAngles.x, Vector3.Dot(transform.forward, transform.right), lookatPoint.localEulerAngles.z);
//lookatPoint.up = new Vector3(Mathf.Clamp(lookatPoint.up.x, -1, 1), Mathf.Clamp(lookatPoint.up.y, -1, 1), Mathf.Clamp(lookatPoint.up.z, -1, 1));
//lookatPoint.right = new Vector3(Mathf.Clamp(lookatPoint.right.x, -1, 1), Mathf.Clamp(lookatPoint.right.y, -1, 1), Mathf.Clamp(lookatPoint.right.z, -1, 1));
//lookatPoint.forward = new Vector3(Mathf.Clamp(lookatPoint.forward.x, -1, 1), Mathf.Clamp(lookatPoint.forward.y, -1, 1), Mathf.Clamp(lookatPoint.forward.z, -1, 1));
//lookatPoint.localRotation = Quaternion.Euler(lookatPoint.localulerAngles)
//lookatPoint.rotation = Quaternion.LookRotation(transform.forward);
//lookatPoint.up = Vector3.ProjectOnPlane(transform.forward, transform.right).normalized;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Follow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Follow : MonoBehaviour {
[SerializeField]
private float XOffset = 0;
[SerializeField]
private float YOffset = 0;
[SerializeField]
private float ZOffset = 0;
[SerializeField]
private Transform Target;
private Transform T;
private Vector3 Offset;
// Use this for initialization
void Start () {
T = transform;
Offset = new Vector3(XOffset, YOffset, ZOffset);
}
// Update is called once per frame
void Update () {
T.position = Target.position + Offset;
T.rotation = Target.rotation;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ScriptsCamera/CameraRotation.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRotation : MonoBehaviour {
[SerializeField]
private float rotSpeed;
[HideInInspector]
public float yaw;
[HideInInspector]
public float pit;
private Vector3 rotRef;
public bool allow = false;
private float xRot = 0;
private float yRot = 0;
// Update is called once per frame
void Update() {
if (allow)
{
yaw = rotSpeed * Input.GetAxis("Mouse X");
pit = (rotSpeed * -Input.GetAxis("Mouse Y"));
rotRef += (new Vector3(pit, yaw, 0));
rotRef = new Vector3(Mathf.Clamp(rotRef.x, -80, 80), rotRef.y, rotRef.z);
transform.localEulerAngles = rotRef + new Vector3(xRot,yRot,0);
}
}
public void GrabRot()
{
yaw = 0;
pit = 0;
xRot = transform.localEulerAngles.x;
yRot = transform.localEulerAngles.y;
rotRef = Vector3.zero;
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/PlayerRoomUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
public class PlayerRoomUI : MonoBehaviourPun
{
[SerializeField]
private Text NameText;
[SerializeField]
private InputField DisplayNameIF;
private string DisplayName = "";
private string DisplayNameInitial = "";
bool SetDisplayNameBool = false;
private string PlayerName;
public string PlayerIdentifier
{
get
{
return PlayerName;
}
set
{
PlayerName = value;
}
}
private void Start()
{
DisplayName = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
DisplayNameInitial = DisplayName;
}
private void Update()
{
if (DisplayNameIF.isFocused)
{
DisplayNameIF.image.color = Color.black;
}
else
{
//if (SetDisplayNameBool && DisplayNameInitial != DisplayName)
//{
// SetDisplayNameBool = false;
// Debug.Log("Set Name " + DisplayName);
// ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
// hash = PhotonNetwork.LocalPlayer.CustomProperties;
// hash.Remove("DisplayName");
// hash.Add("DisplayName", DisplayName);
// PhotonNetwork.LocalPlayer.SetCustomProperties(hash);
//}
DisplayNameIF.image.color = Color.clear;
}
}
public void ActivateIF()
{
DisplayNameIF.gameObject.SetActive(true);
}
public void SetName(string Name)
{
NameText.text = Name;
}
public void MakeIFBlank()
{
DisplayNameIF.text = "";
}
public void SetName()
{
if (DisplayName == "")
NameText.text = PlayerName;
else
NameText.text = DisplayName;
}
public void SetDisplayName(string name)
{
DisplayName = name;
Debug.Log("Set DisplayName " + DisplayName);
ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
hash = PhotonNetwork.LocalPlayer.CustomProperties;
hash.Remove("DisplayName");
hash.Add("DisplayName", DisplayName);
PhotonNetwork.LocalPlayer.SetCustomProperties(hash);
Debug.Log("Set DisplayName (Hash)" + (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"]);
//SetDisplayNameBool = true;
}
public string GetDisplayName()
{
return DisplayName;
}
public void MakeNameBlank()
{
DisplayNameIF.image.color = Color.black;
}
}
<file_sep>/CapstonePowerPlay/Assets/MenuCamFolder/Scripts/ButtonCallToDollyManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonCallToDollyManager : MonoBehaviour {
public enum ButtonEfect
{
Start, Play, Setting
}
public ButtonEfect bFect;
[SerializeField]
private DollyManager dManager;
private void Start()
{
dManager = FindObjectOfType<DollyManager>();
}
public void CallEffect()
{
if(bFect == ButtonEfect.Start)
{
StartToMenuButton();
}
else if (bFect == ButtonEfect.Play)
{
PlayToLobbyButton();
}
else if (bFect == ButtonEfect.Setting)
{
LobbyButton();
}
}
public void StartToMenuButton()
{
dManager.Start_And_Menu(true);
}
public void PlayToLobbyButton()
{
dManager.Menu_And_Play(true);
}
public void LobbyButton()
{
dManager.Menu_And_Setting(true);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerVoiceLine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerVoiceLine : MonoBehaviour {
private PlayerSoundSettings PS;
private AudioSource Src;
public AudioClip[] ballPickup;
public AudioClip[] ability;
public AudioClip[] win;
public AudioClip[] dietyloose;
public AudioClip Ball;
public float voiceVol;
// Use this for initialization
void Start () {
//Src = GetComponents<AudioSource>();
Src = GetComponent<AudioSource>();
PS = FindObjectOfType<PlayerSoundSettings>();
if (PS)
voiceVol = PS.VoiceVol;
else
voiceVol = 0.1f;
}
// Update is called once per frame
void Update () {
//foreach(AudioSource src in Src)
//{
// src.volume = voiceVol;
//}
Src.volume = voiceVol;
}
public void PlaydietyLoose()
{
Src.clip = dietyloose[Random.Range(0, dietyloose.Length)];
Src.Play();
}
public void PlayBallPickup()
{
Src.clip = ballPickup[Random.Range(0, ballPickup.Length)];
Src.Play();
}
public void PlayAbility()
{
Src.clip = ability[Random.Range(0, ability.Length)];
Src.Play();
}
public void PlayWin()
{
Src.clip = win[Random.Range(0, win.Length)];
Src.Play();
}
public void PlayShoot()
{
Src.clip = Ball;
Src.Play();
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ChatEntry.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChatEntry : MonoBehaviour {
[SerializeField]
private Text MessegeText;
[SerializeField]
private LayoutElement Layout;
[SerializeField]
private RectTransform MessegeRectTransfrom;
[SerializeField]
private ContentSizeFitter CSF;
[HideInInspector]
public float TextHeight;
[HideInInspector]
public float TimeOfEntry;
[HideInInspector]
public string EntryType;
[HideInInspector]
public string EntryText;
[HideInInspector]
public int EntryNumber;
[HideInInspector]
public GameObject EntryPerson;
public void CreateMessege(string text, Color TextColor, string type, int EntryNum, GameObject WhoEntered)
{
EntryText = text;
MessegeText.text = text;
MessegeText.color = TextColor;
TextHeight = MessegeRectTransfrom.rect.height;
TimeOfEntry = Time.time;
EntryType = type;
EntryNumber = EntryNum;
EntryPerson = WhoEntered;
}
}
<file_sep>/CapstonePowerPlay/Assets/RunePickups.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RunePickups : MonoBehaviour {
public int red;
public int blue;
public int green;
public bool insureOneType = true;
float pickupTimer = 0.5f;
DoorScript Door;
public bool Opendoor = false;
private PhotonView PV;
// Use this for initialization
void Start ()
{
PV = GetComponent<PhotonView>();
Door = FindObjectOfType<DoorScript>();
}
// // Update is called once per frame
// void Update() {
// pickupTimer -= Time.deltaTime;
// if (red >= 3 || blue >= 3 ||green >= 3)
// {
// if(gameObject.tag == "Team 1")
// {
// Debug.Log("team1door");
// Opendoor = true;
// Door.CmdOpenDoor();
// }
// if(gameObject.tag == "Team 2")
// {
// Debug.Log("team2door");
// Opendoor = true;
// Door.CmdOpenDoor();
// }
// }
//}
private void OnTriggerEnter(Collider r)
{
if (pickupTimer <= 0.0f)
{
if (r.gameObject.tag == "RedRune")
{
red++;
if (insureOneType)
{
blue = 0;
green = 0;
}
pickupTimer = 0.5f;
//Destroy(r.gameObject);
}
if (r.gameObject.tag == "BlueRune")
{
blue++;
if (insureOneType)
{
red = 0;
green = 0;
}
pickupTimer = 0.5f;
}
if (r.gameObject.tag == "GreenRune")
{
green++;
if (insureOneType)
{
red = 0;
blue = 0;
}
pickupTimer = 0.5f;
}
}
}
public void DestroyRune(GameObject rune)
{
try
{
PV.RPC("RPC_DestroyRune", RpcTarget.All, rune);
}
catch
{
Debug.Log("Silly Photon Error Here 2");
}
}
[PunRPC]
void RPC_DestroyRune(GameObject rune)
{
Destroy(rune);
}
}
<file_sep>/CapstonePowerPlay/Assets/MenuCamFolder/Scripts/DollyModifier.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class DollyModifier : MonoBehaviour {
[SerializeField]
private float m_maxSpeed;
[SerializeField]
private float m_speed;
//[SerializeField]
// private float slowDownModifier;
//[SerializeField]
//private float trackSlowDownDistanceModifier;
//[SerializeField]
//private float trackSpeedUpDistanceModifier;
//[SerializeField]
private float trackLength;
[SerializeField]
private CinemachineDollyCart cameraDollyCart;
[SerializeField]
private CinemachineSmoothPath path;
[SerializeField]
private int currentTrackNumber;
[SerializeField]
private float fAcceleration = 10;
[SerializeField]
private float bAcceleration = 10;
public bool reachedSpeedMax;
public bool reachedSpeedMaxRev;
public bool allowMovement;
public bool reverse;
private void Start()
{
cameraDollyCart = transform.GetComponent<CinemachineDollyCart>();
//m_speed = m_maxSpeed;
//cameraDollyCart.m_Speed = m_speed;
cameraDollyCart.m_Path = path;
trackLength = path.PathLength;
}
// Update is called once per frame
void Update () {
if (allowMovement)
{
if (!reverse)
{
if (m_speed >= m_maxSpeed)
{
reachedSpeedMax = true;
}
if (!reachedSpeedMax)
{
m_speed +=(fAcceleration * Time.deltaTime);
m_speed = Mathf.Clamp(m_speed, 0, m_maxSpeed);
}
else
{
m_speed = Mathf.Clamp((cameraDollyCart.m_Path.PathLength - cameraDollyCart.m_Position), 0, m_maxSpeed);
}
}
else
{
if(m_speed <= -m_maxSpeed)
{
reachedSpeedMaxRev = true;
}
if (!reachedSpeedMaxRev)
{
m_speed -= (bAcceleration * Time.deltaTime);
m_speed = Mathf.Clamp(m_speed, -m_maxSpeed, 0);
}
else
{
//Debug.Log("achieved reverse max speed");
m_speed = Mathf.Clamp((0 - cameraDollyCart.m_Position), -m_maxSpeed, 0);
}
//Debug.Log("Speed rev: " + (0 - cameraDollyCart.m_Position));
}
cameraDollyCart.m_Speed = m_speed;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ComponentsToDisable.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComponentsToDisable : MonoBehaviour {
public Behaviour[] DisabledComponents;
//[HideInInspector]
public NetPlayer LocalPlayer;
public NetPlayer ParentPlayer;
[SerializeField]
private PhotonView PV;
// Use this for initialization
private void Start()
{
//Debug.Log("disbaling behaviors");
ForcedStart1();
}
public void ForcedStart1()
{
if (PhotonNetwork.InRoom)
PV.RPC("RPC_ForcedStart", RpcTarget.AllBuffered);
}
[PunRPC]
public void RPC_ForcedStart () {
if(!PV.IsMine)
{
for(int i = 0; i < DisabledComponents.Length; i++)
{
DisabledComponents[i].enabled = false;
}
}
// added by andre.
else
{
gameObject.layer = 2;
}
}
public void ForcedStart2()
{
if (LocalPlayer.PlayerCode != ParentPlayer.PlayerCode)
{
for (int i = 0; i < DisabledComponents.Length; i++)
{
DisabledComponents[i].enabled = false;
}
}
// added by andre.
else
{
gameObject.layer = 2;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/DoorSpawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class DoorSpawner : NetworkBehaviour {
[SerializeField]
private Transform doorSpawn;
[SerializeField]
private GameObject doorPrefab;
// Use this for initialization
void Start()
{
CmdSpawnNet();
}
[Command]
public void CmdSpawnNet()
{
GameObject TempNet;
TempNet = Instantiate(doorPrefab, doorSpawn.position, doorSpawn.rotation);
NetworkServer.Spawn(TempNet);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/myHostMigration.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class myHostMigration : NetworkMigrationManager {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ItemSlot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ItemSlot : MonoBehaviour {
private Item HeldItem = null;
[HideInInspector]
public bool ItemHeld = false;
[SerializeField]
private Texture NullSprite;
[SerializeField]
private RawImage ImageSlot;
public void SetImage(Texture sprite)
{
ImageSlot.texture = sprite;
}
public void SetImage()
{
ImageSlot.texture = NullSprite;
}
public void SetItem(Item item)
{
HeldItem = item;
SetImage(item.GetSprite());
if (HeldItem != null)
ItemHeld = true;
}
public Item GetItemRef()
{
return HeldItem;
}
public void RemoveItem()
{
SetImage();
HeldItem = null;
ItemHeld = false;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/UniversalGoalScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UniversalGoalScript : MonoBehaviour {
private string team1Tag;
private string team2Tag;
private ScoreTracker sTracker;
// Use this for initialization
void Start () {
// temp team1
team1Tag = "Player";
// temp team2
team2Tag = "tempTag";
sTracker = FindObjectOfType<ScoreTracker>();
}
private void OnCollisionEnter(Collision c)
{
if (c.gameObject.tag == "Ball")
{
string tempString = c.transform.GetComponent<Ball>().teamTag;
if (tempString == team1Tag)
{
Debug.Log("team1Scored");
sTracker.AddScoreToTeam1(1);
}
else if (tempString == team2Tag)
{
Debug.Log("team2Scored");
sTracker.AddScoreToTeam2(1);
}
else
{
Debug.LogError("Ball collided with goal, but the team tag variable does not match the tags of either team!");
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/LobbyNetwork.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
using System.IO;
public class LobbyNetwork : MonoBehaviourPunCallbacks, IInRoomCallbacks {
[SerializeField]
private PhotonView PV;
private string RoomIdentifier = "None";
// Use this for initialization
void Start () {
if (!PhotonNetwork.InLobby && !PhotonNetwork.InRoom)
{
PhotonNetwork.OfflineMode = false;
PhotonNetwork.LocalPlayer.NickName = PlayerNetwork.Instance.PlayerName;
PhotonNetwork.AutomaticallySyncScene = true;
//PhotonNetwork.GameVersion = "1";
print("Connecting to Server...");
PhotonNetwork.ConnectUsingSettings();
}
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}
public override void OnConnected()
{
print("Connected");
}
public override void OnDisconnected(DisconnectCause cause)
{
print("Disconnected Cause: " + cause);
}
public override void OnConnectedToMaster()
{
print("Connected to Master.");
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
print("Connected to Lobby.");
print(PhotonNetwork.CurrentLobby);
}
public override void OnLeftLobby()
{
print("Left Lobby.");
base.OnLeftLobby();
}
public override void OnLeftRoom()
{
print("Left Room.");
base.OnLeftRoom();
}
private void OnFailedToConnectToPhoton()
{
print("Connected to Master: Invalid AppID or Network Issues");
}
private void OnConnectionFail()
{
print("Connected to Master: Invalid Region or Maxed out CCU");
}
private void OnApplicationQuit()
{
print("Closing Game.");
if (PhotonNetwork.InRoom)
PhotonNetwork.LeaveRoom();
if (PhotonNetwork.InLobby)
PhotonNetwork.LeaveLobby();
}
public void SetRoom(RoomListing DesiredRoom)
{
RoomIdentifier = DesiredRoom.RoomListingInfo.RoomIdentifier;
}
public void JoinPhotonRoom()
{
if (RoomIdentifier != "None")
{
print("RoomID: RoomIdentifier Attempted.");
PhotonNetwork.JoinRoom(RoomIdentifier);
}
else
{
print("No RoomID - Cannot Rejoin.");
}
}
public void LeavePhotonRoom()
{
if (PhotonNetwork.InRoom)
{
PhotonNetwork.LeaveRoom();
PhotonNetwork.JoinLobby();
}
}
private void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
//print(scene.name + ": OnSceneFinhishedLoadingCalled");
if (scene.name == "DustinScene" || scene.name == "Marcscene" || scene.name == "MarcsceneDup")
{
//print("RPC_CreatePlayer" + ": Attempted");
//PhotonNetwork.Instantiate("PhotonPrefabs/PhotonNetworkPlayer", transform.position, Quaternion.identity, 0);
if (PhotonNetwork.IsMasterClient)
PV.RPC("RPC_CreatePlayer", RpcTarget.All);
}
}
[PunRPC]
private void RPC_CreatePlayer()
{
//print("RPC_CreatePlayer" + ": Called");
PhotonNetwork.Instantiate("PhotonPrefabs/PhotonNetworkPlayer", transform.position, Quaternion.identity, 0);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PlayerControlPhysics.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(Rigidbody))]
public class PlayerControlPhysics : NetworkBehaviour
{
// Adjustables
[SerializeField]
private float JumpForce = 50;
[SerializeField]
private float MoveForce = 150;
[SerializeField]
private float TurnTorque = 150;
[SerializeField]
private float PlayerMass = 80;
[SerializeField]
private float FloatDistance = 0.2f;
[SerializeField]
private float MaxSpeed = 20f;
//[SerializeField]
//private float MaxSpin = 80f;
[SerializeField]
private Spring CharacterSpring;
// Body Parts
[SerializeField]
private LayerMask GroundLayer;
[SerializeField]
private Transform Feet;
private bool onGround = true;
// Recieved attributes
private float MoveAxis = 0;
private float TurnAxis = 0;
private float JumpAxis = 0;
// Marcs Stuff
public GameObject camGurl;
public GameObject camGurl2;
// Bobbers
[SerializeField]
private GameObject Bobbers;
// Rigidbody
private Rigidbody RB;
//[SerializeField]
//private Rigidbody MeshRB;
private Transform Trans;
// Use this for initialization
void Start () {
//MaxSpin *= Mathf.PI / 180;
Physics.gravity = new Vector3(0, -20, 0);
Cursor.lockState = CursorLockMode.Locked;
RB = GetComponent<Rigidbody>();
RB.mass = PlayerMass;
Trans = transform;
//local player camera
if (isLocalPlayer)
{
camGurl.SetActive(true);
camGurl2.SetActive(true);
}
else
{
camGurl.SetActive(false);
camGurl2.SetActive(false);
}
}
// Update is called once per frame
void FixedUpdate () {
//local player control
if (isLocalPlayer)
{
// Get Axis of Movement
MoveAxis = Input.GetAxis("Move");
TurnAxis = Input.GetAxis("Turn");
//Debug.Log("Move Axis: " + MoveAxis);
//Debug.Log("Turn Axis: " + TurnAxis);
// Moving
if (Mathf.Abs(MoveAxis) < 0.1f)
{
MoveAxis = 0;
}
//RB.AddForce(MoveAxis * MoveForce * Feet.forward, ForceMode.Force);
Trans.Translate(0, 0, MoveAxis * MoveForce *Time.fixedDeltaTime);
//Vector3 temp = MoveAxis * MoveForce * Vector3.forward;
//Debug.Log("Vector: " + temp);
//Debug.Log("Move Force: " + MoveAxis * MoveForce * Vector3.forward);
//Debug.Log("Move Force Quantity: " + MoveForce);
// Turning
if (Mathf.Abs(TurnAxis) < 0.1f)
{
TurnAxis = 0;
}
//RB.AddTorque(TurnAxis * Trans.up * TurnTorque, ForceMode.Force);
Trans.Rotate(TurnAxis * Trans.up * TurnTorque * Time.deltaTime);
Bobbers.transform.Rotate(TurnAxis * Trans.up * TurnTorque * Time.deltaTime);
//MeshRB.AddTorue(TurnAxis * Feet.up * TurnTorque, ForceMode.Force);
//Debug.Log("Turn Force: " + TurnAxis * Trans.up * TurnTorque);
//Debug.Log("Turn Torque Quantity: " + TurnTorque);
// Jump
JumpAxis = Input.GetAxis("Jump");
onGround = Physics.Raycast(Feet.position, -Feet.up, FloatDistance + 0.3f, GroundLayer);
//Debug.Log("Jump Axis: " + JumpAxis);
if (onGround)
{
CharacterSpring.enabled = true;
//Debug.Log("ON GROUND");
}
else
{
CharacterSpring.enabled = false;
//Debug.Log("NOT ON GROUND");
}
if (JumpAxis > 0.1f && onGround)
{
RB.AddForce(Trans.up * JumpForce, ForceMode.Impulse);
}
}
if (RB.velocity.magnitude > MaxSpeed)
{
RB.velocity = RB.velocity / (RB.velocity.magnitude - MaxSpeed + 1);
}
//if (Mathf.Abs(RB.angularVelocity.y) > MaxSpin)
//{
// RB.angularVelocity = RB.angularVelocity / (Mathf.Abs(RB.angularVelocity.y) - MaxSpeed + 1);
//}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Shove.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shove : MonoBehaviour {
// Player Components
[SerializeField]
private MeshRenderer ShieldBlue;
[SerializeField]
private MeshRenderer ShieldRed;
[SerializeField]
private hoverBoardScript Hoverboard;
private float CurrentSpeed = 0;
private float MaxSpeed = 0;
[SerializeField]
private Rigidbody PlayerRigidBody;
[SerializeField]
private PlayerColor PC;
// Shield Components
//[SyncVar(hook = "ChangeOpacity")]
public float ShieldOpacity = 0;
//[SyncVar(hook = "ChangeShielding")]
public float ShieldStrength = 0;
private float StrengthTimer = 0;
[SerializeField]
private float MaxShieldStrength = 3f;
[SerializeField]
private float MaxShieldOpacity = 3f;
[SerializeField]
private float MaxShoveForce = 50;
[SerializeField]
private float MinSpeedToDropBallPercent = 0.5f;
//photon variables
private PhotonView PV;
// Use this for initialization
void Start ()
{
PV = GetComponent<PhotonView>();
if (PC.LocalPlayer == PC.ParentPlayer)
{
MaxSpeed = Hoverboard.GetMaxSpeed();
}
}
// Update is called once per frame
void Update () {
if (PC.LocalPlayer == PC.ParentPlayer)
{
CurrentSpeed = Hoverboard.Speed;
float opacity = MaxShieldOpacity - Mathf.Abs(MaxSpeed - CurrentSpeed) * MaxShieldOpacity / MaxSpeed;
if (opacity > MaxShieldOpacity)
{
opacity = MaxShieldOpacity;
}
float shieldStrenth = CurrentSpeed > MaxSpeed ? 1
: 1 - (MaxSpeed - CurrentSpeed) / MaxSpeed;
if (shieldStrenth > 1)
{
StrengthTimer += Time.deltaTime;
float extraShieldStrenth = shieldStrenth + StrengthTimer / 5;
shieldStrenth += extraShieldStrenth;
if (shieldStrenth > MaxShieldStrength)
{
shieldStrenth = MaxShieldStrength;
}
float extraOpacity = (1 - MaxShieldOpacity) * (MaxShieldStrength - shieldStrenth) / MaxShieldStrength;
opacity += extraOpacity;
}
else
{
StrengthTimer = 0;
}
if (opacity > 1)
{
opacity = 1;
}
//CmdUpdateShield(opacity, shieldStrenth);
if (PhotonNetwork.InRoom)
PV.RPC("RPC_UpdateShield", RpcTarget.All, opacity, shieldStrenth);
}
}
[PunRPC]
private void RPC_UpdateShield(float Opacity, float Shielding)
{
//Debug.Log("Updated Shield: " + Opacity + ", " + Shielding);
ShieldOpacity = Opacity;
ShieldStrength = Shielding;
ChangeOpacity(ShieldOpacity);
ChangeShielding(ShieldStrength);
}
private void ChangeOpacity(float Opacity)
{
ShieldBlue.material.SetFloat("Vector1_2C301F3A", 1 - Opacity);
ShieldRed.material.SetFloat("Vector1_2C301F3A", 1 - Opacity);
}
private void ChangeShielding(float Strength)
{
ShieldStrength = Strength;
}
public void ShovePlayer(Shove OtherPlayer, Vector3 Direction)
{
//Debug.Log("Shove with player");
if (PC.LocalPlayer == PC.ParentPlayer)
{
Debug.Log("PC.LocalPlayer == PC.ParentPlayer = " + (PC.LocalPlayer == PC.ParentPlayer));
ShovePlayer(OtherPlayer.gameObject, Direction);
}
}
public void CollideWithPlayer(Shove OtherPlayer, Vector3 Direction)
{
if (PC.LocalPlayer == PC.ParentPlayer)
{
//CmdCollidePlayer(OtherPlayer.gameObject, Direction);
if (PhotonNetwork.InRoom)
PV.RPC("RPC_CollidePlayer", RpcTarget.All, OtherPlayer.gameObject.GetPhotonView().ViewID, Direction);
}
}
[PunRPC]
private void RPC_CollidePlayer(GameObject player, Vector3 Direction)
{
Shove shove = player.GetComponent<Shove>();
if (shove.ShieldStrength / (ShieldStrength + 0.1f) < 0.8f && ShieldStrength > 0.4f)
{
BallHandling bh = player.GetComponent<BallHandling>();
bh.DropBall();
shove.LaunchPlayer(MaxShoveForce, Direction);
}
else
{
shove.LaunchPlayer(MaxShoveForce * 0.5f, Direction);
LaunchPlayer(MaxShoveForce * 0.5f, Direction);
}
}
private void ShovePlayer(GameObject player, Vector3 Direction)
{
//Debug.Log("CmdShovePlayer Called");
//RpcShovePlayer(player, Direction);
if (PhotonNetwork.InRoom)
PV.RPC("RPC_ShovePlayer", RpcTarget.All, player.GetPhotonView().ViewID, Direction);
}
[PunRPC]
private void RPC_ShovePlayer(int player, Vector3 Direction)
{
// Debug.Log("RpcShovePlayer Called");
Shove shove = PhotonView.Find(player).GetComponent<Shove>();
shove.LaunchPlayer(MaxShoveForce, Direction);
BallHandling bh = PhotonView.Find(player).GetComponent<BallHandling>();
bh.DropBall();
}
public void LaunchPlayer(float Force, Vector3 Direction)
{
// Debug.Log("Launch Player called");
PlayerRigidBody.AddForce(Force * Direction, ForceMode.Impulse);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/goalPad.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class goalPad : MonoBehaviour {
//private BatteryScript BS;
//public void OnTriggerEnter(Collider c)
//{
// if(c.gameObject.tag == "battery")
// {
// Debug.Log("placing batt");
// BS.placeBatt();
// BS.energydrain();
// Destroy(c.gameObject);
// }
//}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/SendInfo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class SendInfo : MonoBehaviourPun {
//private void OnSerializeNetworkView(PhotonStream stream, PhotonMessageInfo info)
//{
//}
}
<file_sep>/CapstonePowerPlay/Assets/MenuCamFolder/Scripts/FollowTrack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowTrack : MonoBehaviour {
[SerializeField]
private Transform followTransform = null;
private void Update()
{
transform.position = followTransform.position;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/UI_TrackAndScale.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UI_TrackAndScale : MonoBehaviour {
[SerializeField]
private RectTransform RT;
private PlayerColor Target = null;
private PlayerColor[] Targets = null;
[SerializeField]
private float ReferenceDistance = 5;
[SerializeField]
private float MaxScale = 10;
[SerializeField]
private bool UseMaxScale = false;
private Vector3 Direction;
private Vector3 DefaultScale = Vector3.one;
private Vector3 NewScale = Vector3.one;
// Use this for initialization
void Start () {
FindTarget();
DefaultScale = RT.localScale;
if (DefaultScale == Vector3.zero)
{
DefaultScale = Vector3.one;
}
}
// Update is called once per frame
void Update () {
if (Target == null)
{
FindTarget();
}
else
{
Direction = Target.transform.position - transform.position;
RT.LookAt(Target.transform);
if (Direction.magnitude > ReferenceDistance)
{
if (!UseMaxScale)
{
NewScale = DefaultScale * Direction.magnitude / ReferenceDistance;
}
else
{
if (Direction.magnitude / ReferenceDistance > MaxScale)
{
NewScale = DefaultScale * MaxScale;
}
else
{
NewScale = DefaultScale * Direction.magnitude / ReferenceDistance;
}
}
}
else
{
NewScale = DefaultScale;
}
RT.localScale = NewScale;
}
}
private void FindTarget()
{
Targets = FindObjectsOfType<PlayerColor>();
if (Targets != null)
{
foreach (PlayerColor pc in Targets)
{
if (pc.ParentPlayer == pc.LocalPlayer)
{
Target = pc;
break;
}
}
if (Target == null)
{
// Debug.Log("No Target Found");
}
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ScriptsCamera/CameraCollision.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraCollision : MonoBehaviour {
public float minDistance = 1.0f;
public float maxDistance = 4.0f;
public float smoothTransitionSpeed = 10.0f;
[SerializeField]
private float distanceMultiplier;
Vector3 dollyDir;
public Vector3 dollyDirAdjusted;
public float distance;
[SerializeField]
private LayerMask layerMask;
// Use this for initialization
void Start () {
dollyDir = transform.localPosition.normalized;
distance = transform.localPosition.magnitude;
}
// Update is called once per frame
void Update () {
Vector3 desiredCameraPos = transform.parent.TransformPoint(dollyDir * maxDistance);
RaycastHit hit;
if(Physics.Linecast(transform.parent.position, desiredCameraPos, out hit, layerMask))
{
if (hit.transform.tag != "Shield" && hit.transform.tag != "Team 1" && hit.transform.tag != "Team 2")
{
distance = Mathf.Clamp((hit.distance * distanceMultiplier), minDistance, maxDistance);
}
}
else
{
distance = maxDistance;
}
transform.localPosition = Vector3.Lerp(transform.localPosition, dollyDir * distance, Time.deltaTime * smoothTransitionSpeed);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ScoreBoard.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreBoard : MonoBehaviour {
//orange
[SerializeField]
private RectTransform orangeTeamBar;
[SerializeField]
private RectTransform maxOrangeBarSizeRect;
[SerializeField]
private RectTransform orangeResource1Bar;
[SerializeField]
private RectTransform maxOrangeResource1BarSizeRect;
[SerializeField]
private RectTransform orangeResource2Bar;
[SerializeField]
private RectTransform maxOrangeResource2BarSizeRect;
[SerializeField]
private RectTransform orangeResource3Bar;
[SerializeField]
private RectTransform maxOrangeResource3BarSizeRect;
[SerializeField]
private float orangeScore = 0;
[SerializeField]
private float orangeRes1Score = 0;
[SerializeField]
private float orangeRes2Score = 0;
[SerializeField]
private float orangeRes3Score = 0;
// purple
[SerializeField]
private RectTransform purpleTeamBar;
[SerializeField]
private RectTransform maxPurpleBarSizeRect;
[SerializeField]
private RectTransform purpleResource1Bar;
[SerializeField]
private RectTransform maxPurpleResource1BarSizeRect;
[SerializeField]
private RectTransform purpleResource2Bar;
[SerializeField]
private RectTransform maxPurpleResource2BarSizeRect;
[SerializeField]
private RectTransform purpleResource3Bar;
[SerializeField]
private RectTransform maxPurpleResource3BarSizeRect;
[SerializeField]
private float purpleScore = 0;
[SerializeField]
private float purpleRes1Score = 0;
[SerializeField]
private float purpleRes2Score = 0;
[SerializeField]
private float purpleRes3Score = 0;
[SerializeField]
private int roundNumber;
[SerializeField]
private Text roundText;
[SerializeField]
private float timer;
[SerializeField]
private Image clock;
[SerializeField]
private float batteryCharge;
[SerializeField]
private RectTransform batteryChargeBar;
[SerializeField]
private RectTransform maxBatteryChargeSizeRect;
// Use this for initialization
void Start () {
//maxBarSize = maxBarSizeRect.sizeDelta.x;
timer = 60;
roundNumber = 1;
}
// Update is called once per frame
void Update ()
{
/*
if(orangeScore > 100)
{
orangeScore = 100;
}
if (purpleScore > 100)
{
purpleScore = 100;
}
if (Input.GetKeyDown(KeyCode.K))
{
orangeScore += 10;
}
if (Input.GetKeyDown(KeyCode.L))
{
purpleScore += 10;
}
if(Input.GetKeyDown(KeyCode.O))
{
orangeScore = 0;
purpleScore = 0;
}
*/
roundText.text = roundNumber.ToString();
// to be change later!!!!! not decided
timer -= Time.deltaTime;
clock.fillAmount = timer / 60;
if(timer <= 0)
{
timer = 60;
roundNumber++;
}
// battery charge
batteryChargeBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, batteryCharge * maxBatteryChargeSizeRect.sizeDelta.y / 100);
//bar changes
PurpleBars();
OrangeBars();
}
void PurpleBars()
{
//score
purpleTeamBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, purpleScore * maxPurpleBarSizeRect.sizeDelta.x / 100);
//res1
purpleResource1Bar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, purpleRes1Score * maxPurpleResource1BarSizeRect.sizeDelta.x / 100);
//res2
purpleResource2Bar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, purpleRes2Score * maxPurpleResource2BarSizeRect.sizeDelta.x / 100);
//res3
purpleResource3Bar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, purpleRes3Score * maxPurpleResource3BarSizeRect.sizeDelta.x / 100);
}
void OrangeBars()
{
// score
orangeTeamBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, orangeScore * maxOrangeBarSizeRect.sizeDelta.x / 100);
// res1
orangeResource1Bar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, orangeRes1Score * maxOrangeResource1BarSizeRect.sizeDelta.x / 100);
//res2
orangeResource2Bar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, orangeRes2Score * maxOrangeResource2BarSizeRect.sizeDelta.x / 100);
// res3
orangeResource3Bar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, orangeRes3Score * maxOrangeResource3BarSizeRect.sizeDelta.x / 100);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/LookBackwardsDetector.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LookBackwardsDetector : MonoBehaviour {
//private Cinemachine.CinemachineFreeLook playerVirtualCamera;
public bool lookingBackwards;
[SerializeField]
private GameObject antiCrosshair;
[SerializeField]
private GameObject playerObject;
[SerializeField]
private GameObject cameraObject;
// Use this for initialization
void Start () {
//playerVirtualCamera = transform.GetComponent<Cinemachine.CinemachineFreeLook>();
//antiCrosshair = GameObject.FindGameObjectWithTag("antiCrosshair");
antiCrosshair.SetActive(false);
}
// Update is called once per frame
void Update() {
// Debug.Log("PlayerObj: " + playerObject.transform.localEulerAngles.y);
// Debug.Log("CameraObj: " + cameraObject.transform.localEulerAngles.y);
//if(playerObject.transform.eulerAngles.y)
//if (playerObject.transform.localEulerAngles.y <= cameraObject.transform.localEulerAngles.y - 90 && playerObject.transform.localEulerAngles.y >= cameraObject.transform.localEulerAngles.y + 90)
/*
float playerAngleTemp = 0;
float cameraAngleTemp = 0;
bool pBool = false;
bool cBool = false;
if (playerObject.transform.localEulerAngles.y > 180)
{
playerAngleTemp = playerObject.transform.localEulerAngles.y - 180;
pBool = true;
}
if (cameraObject.transform.localEulerAngles.y > 180)
{
cameraAngleTemp = playerObject.transform.localEulerAngles.y - 180;
cBool = true;
}
// both
if (cBool && pBool)
{
Debug.Log("both");
if ((180 - cameraAngleTemp) - playerAngleTemp <= 90)
{
lookingBackwards = true;
}
}
//p
else if (!cBool && pBool)
{
Debug.Log("p");
if ((180 - cameraObject.transform.localEulerAngles.y) - playerAngleTemp <= 90)
{
lookingBackwards = true;
}
}
//c
else if (cBool && !pBool)
{
Debug.Log("c");
if ((180 - cameraAngleTemp) - playerObject.transform.localEulerAngles.y <= 90)
{
lookingBackwards = true;
}
}
// none
else
{
Debug.Log("none");
if ((180 - cameraObject.transform.localEulerAngles.y) - playerObject.transform.localEulerAngles.y <= 90)
{
lookingBackwards = true;
}
}
*/
//Debug.Log(cameraObject.transform.localEulerAngles.y);
if (cameraObject.transform.localEulerAngles.y >= 90 && cameraObject.transform.localEulerAngles.y <= 270)
{
lookingBackwards = true;
}
else
{
lookingBackwards = false;
}
////////////////////////////////////////////////////////
if (lookingBackwards)
{
antiCrosshair.SetActive(true);
}
else
{
antiCrosshair.SetActive(false);
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/PhotonRoom.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
public class PhotonRoom : MonoBehaviourPunCallbacks, IPunObservable {
[SerializeField]
private int MaxTeamPlayers = 6;
private int Team1Players = 0;
private int Team2Players = 0;
private int QueuePlayers = 0;
[SerializeField]
private Text RoomText;
[SerializeField]
private Text RoomType;
[SerializeField]
private RectTransform Team1Content;
[SerializeField]
private RectTransform Team2Content;
[SerializeField]
private RectTransform QueueContent;
[SerializeField]
private PlayerRoomUI RPU_Prefab;
[SerializeField]
private Button ReadyButton;
[SerializeField]
private Text ReadyButtonText;
[SerializeField]
private Text CountDownText;
private List<PlayerRoomUI> PlayerRoomUIList = new List<PlayerRoomUI>();
private List<Player> Team1PlayerList = new List<Player>();
private List<Player> Team2PlayerList = new List<Player>();
private List<Player> QueuePlayerList = new List<Player>();
private Player[] RoomPlayerList;
// Local player variables
private bool ChangedTeam = false;
private bool ChangedReady = false;
private bool ChangedDisplayName = false;
private int TeamNum = -1;
private int TeamNumOld = -1;
private bool IsReady = false;
private bool IsReadyOld = false;
private string DisplayName = "";
private string DisplayNameOld = "";
// Game starts to play
private bool StartGame = false;
private bool StartedGame = false;
[SerializeField]
private float StartTime = 3;
private float StartTimer = 0;
// Photon
[SerializeField]
private PhotonView PV;
[SerializeField]
private MenuSoundFXs MSF;
[SerializeField]
private GameObject loadingImage;
private void Awake()
{
if (PhotonNetwork.InRoom)
{
RoomText.text = (string)PhotonNetwork.CurrentRoom.CustomProperties["RoomNameKey"];
RoomType.text = (string)PhotonNetwork.CurrentRoom.CustomProperties["RoomTypeKey"];
RoomPlayerList = PhotonNetwork.PlayerList;
for (int i = 0; i < RoomPlayerList.Length; i++)
{
Player P = RoomPlayerList[i];
if (P.ActorNumber == PhotonNetwork.LocalPlayer.ActorNumber)
{
// Set new custom properties for each player
ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
hash.Add("Team", -1);
hash.Add("ReadyToPlay", false);
hash.Add("RoomIndentifier", PhotonNetwork.CurrentRoom.Name);
DisplayName = "Player " + P.ActorNumber;
DisplayNameOld = DisplayName;
hash.Add("DisplayName", DisplayName);
P.SetCustomProperties(hash);
}
}
}
if (ReadyButton.enabled)
{
ReadyButton.enabled = false;
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
// If new Data, send
if (ChangedTeam || ChangedReady || ChangedDisplayName)
{
ChangedTeam = false;
ChangedReady = false;
ChangedDisplayName = false;
stream.SendNext(TeamNum);
stream.SendNext(IsReady);
stream.SendNext(PhotonNetwork.LocalPlayer.ActorNumber);
stream.SendNext(DisplayName);
}
}
else
{
// When packets arrive, change
int ChangedNum = (int)stream.ReceiveNext();
bool ChangedReady = (bool)stream.ReceiveNext();
int ChangedActor = (int)stream.ReceiveNext();
string ChangedDisplayName = (string)stream.ReceiveNext();
Player ChangedPlayer = null;
foreach(Player P in RoomPlayerList)
{
if (P.ActorNumber == ChangedActor)
{
ChangedPlayer = P;
break;
}
}
if (ChangedPlayer != null)
{
ExitGames.Client.Photon.Hashtable hash = ChangedPlayer.CustomProperties;
hash.Remove("Team");
hash.Remove("ReadyToPlay");
hash.Remove("DisplayName");
hash.Add("Team", ChangedNum);
hash.Add("ReadyToPlay", ChangedReady);
hash.Add("DisplayName", ChangedDisplayName);
ChangedPlayer.SetCustomProperties(hash);
print("Changed Player (Team / ActorNum / DisplayName): (" + ChangedNum + " / " + ChangedActor + " / " + ChangedDisplayName + ")");
}
}
}
void Update()
{
CheckLocalPlayer();
CheckPlayerTeam();
UpdateLists();
CheckStartGame();
}
[PunRPC]
private void RPC_UpdateStartGameTimer(string Countdown)
{
CountDownText.text = Countdown;
}
private void CheckStartGame()
{
if (PhotonNetwork.IsMasterClient)
{
if (CheckIfReady())
{
if (!ReadyButton.enabled)
{
ReadyButton.enabled = true;
ReadyButtonText.text = "Play";
}
if (StartGame)
{
if (StartTimer < StartTime)
{
string tempText = Mathf.CeilToInt(3 - StartTimer) + "";
StartTimer += Time.deltaTime;
PV.RPC("RPC_UpdateStartGameTimer", RpcTarget.All, tempText);
}
else
{
if (!StartedGame)
{
PhotonNetwork.CurrentRoom.IsVisible = false;
StartedGame = true;
// Start The Game
PV.RPC("RPC_UpdateStartGameTimer", RpcTarget.All, "");
PV.RPC("RPC_ActivateLoading", RpcTarget.All);
// Update Room Started Bool
PV.RPC("RPC_SetRoomProperty", RpcTarget.All, "StartedGame", true);
// Load scene and spawn player in
if ((string)PhotonNetwork.CurrentRoom.CustomProperties["RoomTypeKey"] == "Custom")
{
LoadArena(5);
}
else if ((string)PhotonNetwork.CurrentRoom.CustomProperties["RoomTypeKey"] == "TrainingRoom")
{
LoadArena(3);
}
}
}
}
else
{
StartTimer = 0;
PV.RPC("RPC_UpdateStartGameTimer", RpcTarget.All, "");
}
}
else
{
if (ReadyButton.enabled)
{
ReadyButton.enabled = false;
ReadyButtonText.text = "Pause";
}
}
}
}
[PunRPC]
private void RPC_ActivateLoading()
{
loadingImage.SetActive(true);
}
[PunRPC]
private void RPC_SetRoomProperty(string key, object value)
{
PhotonNetwork.CurrentRoom.CustomProperties[key] = value;
}
void LoadArena(int scene)
{
if (!PhotonNetwork.IsMasterClient)
{
Debug.LogError("PhotonNetwork : Trying to Load a level but we are not the master Client");
Debug.Log("Scene " + scene + " Attempted to be Loaded");
}
else
{
//Debug.Log("Scene " + scene + " Loaded");
PhotonNetwork.LoadLevel(scene);
}
}
[PunRPC]
private void RPC_PlayStartSound()
{
MSF.PlayStart();
}
public void ToggleStartGame()
{
StartGame = !StartGame;
PV.RPC("RPC_PlayStartSound", RpcTarget.All);
}
private bool CheckIfReady()
{
bool IsReady = true;
foreach (Player P in RoomPlayerList)
{
if (!(bool)P.CustomProperties["ReadyToPlay"])
{
IsReady = false;
break;
}
}
return IsReady;
}
private void CheckPlayerTeam()
{
foreach (Player P in RoomPlayerList)
{
object value;
if (P.CustomProperties.TryGetValue("Team", out value))
{
if ((int)value == -1)
{
QueuePlayerList.Add(P);
if (Team1PlayerList.Contains(P))
{
Team1PlayerList.Remove(P);
}
if (Team2PlayerList.Contains(P))
{
Team2PlayerList.Remove(P);
}
}
else if ((int)value == 1)
{
Team1PlayerList.Add(P);
if (QueuePlayerList.Contains(P))
{
QueuePlayerList.Remove(P);
}
if (Team2PlayerList.Contains(P))
{
Team2PlayerList.Remove(P);
}
}
else if ((int)value == 2)
{
Team2PlayerList.Add(P);
if (QueuePlayerList.Contains(P))
{
QueuePlayerList.Remove(P);
}
if (Team1PlayerList.Contains(P))
{
Team1PlayerList.Remove(P);
}
}
}
}
}
public void SetUpdateDisplayName()
{
Debug.Log("Set Display name " + (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"]);
ChangedDisplayName = true;
}
private void UpdateLists()
{
List<PlayerRoomUI> NewPlayerRoomUIList = new List<PlayerRoomUI>();
for(int i = 1; i <= RoomPlayerList.Length; i++)
{
if (PlayerRoomUIList.Count < i)
{
PlayerRoomUI temp = Instantiate(RPU_Prefab);
int Team = (int)RoomPlayerList[i - 1].CustomProperties["Team"];
RectTransform rt = temp.GetComponent<RectTransform>();
temp.PlayerIdentifier ="Player " + RoomPlayerList[i - 1].ActorNumber;
temp.SetName(DisplayName);
if (Team == -1)
{
rt.SetParent(QueueContent, false);
}
else if (Team == 1)
{
rt.SetParent(Team1Content, false);
}
else if (Team == 2)
{
rt.SetParent(Team2Content, false);
}
NewPlayerRoomUIList.Add(temp);
}
else
{
PlayerRoomUI temp = PlayerRoomUIList[i - 1];
int Team = (int)RoomPlayerList[i - 1].CustomProperties["Team"];
RectTransform rt = temp.GetComponent<RectTransform>();
temp.PlayerIdentifier = "Player " + RoomPlayerList[i - 1].ActorNumber;
if (!ChangedDisplayName || RoomPlayerList[i - 1].ActorNumber != PhotonNetwork.LocalPlayer.ActorNumber)
{
temp.SetName((string)RoomPlayerList[i - 1].CustomProperties["DisplayName"]);
}
if (RoomPlayerList[i - 1].ActorNumber == PhotonNetwork.LocalPlayer.ActorNumber)
temp.ActivateIF();
if (Team == -1)
{
rt.SetParent(QueueContent, false);
}
else if (Team == 1)
{
rt.SetParent(Team1Content, false);
}
else if (Team == 2)
{
rt.SetParent(Team2Content, false);
}
}
}
if (NewPlayerRoomUIList.Count > 0)
PlayerRoomUIList.AddRange(NewPlayerRoomUIList);
List<PlayerRoomUI> RemovePlayerRoomUIList = new List<PlayerRoomUI>();
RoomPlayerList = PhotonNetwork.PlayerList;
if (PlayerRoomUIList.Count > RoomPlayerList.Length)
{
foreach (PlayerRoomUI RPU in PlayerRoomUIList)
{
int actorNum;
if (int.TryParse(RPU.PlayerIdentifier.Split(' ')[1], out actorNum))
{
bool RemovePlayer = true;
foreach (Player P in RoomPlayerList)
{
if (P.ActorNumber == actorNum)
{
RemovePlayer = false;
break;
}
}
if (RemovePlayer)
{
RemovePlayerRoomUIList.Add(RPU);
}
}
}
}
if (RemovePlayerRoomUIList.Count > 0)
{
foreach(PlayerRoomUI RPU in RemovePlayerRoomUIList)
{
if (PlayerRoomUIList.Contains(RPU))
{
PlayerRoomUIList.Remove(RPU);
Destroy(RPU.gameObject, 0.1f);
}
}
}
}
private void CheckLocalPlayer()
{
// Checks for New Data
TeamNumOld = TeamNum;
TeamNum = (int)PhotonNetwork.LocalPlayer.CustomProperties["Team"];
IsReadyOld = IsReady;
IsReady = (bool)PhotonNetwork.LocalPlayer.CustomProperties["ReadyToPlay"];
DisplayNameOld = DisplayName;
DisplayName = (string)PhotonNetwork.LocalPlayer.CustomProperties["DisplayName"];
if (TeamNum != TeamNumOld)
{
ChangedTeam = true;
PV.TransferOwnership(PhotonNetwork.LocalPlayer.ActorNumber);
}
else if (IsReady != IsReadyOld)
{
ChangedReady = true;
PV.TransferOwnership(PhotonNetwork.LocalPlayer.ActorNumber);
}
else if (DisplayName != DisplayNameOld)
{
ChangedDisplayName = true;
PV.TransferOwnership(PhotonNetwork.LocalPlayer.ActorNumber);
}
}
public override void OnJoinedRoom()
{
RoomText.text = (string)PhotonNetwork.CurrentRoom.CustomProperties["RoomNameKey"];
RoomType.text = (string)PhotonNetwork.CurrentRoom.CustomProperties["RoomTypeKey"];
base.OnJoinedRoom();
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
// Set new custom properties for each new player
ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
hash.Add("Team", -1);
hash.Add("ReadyToPlay", false);
hash.Add("RoomIndentifier", PhotonNetwork.CurrentRoom.Name);
newPlayer.SetCustomProperties(hash);
base.OnPlayerEnteredRoom(newPlayer);
// Update PlayerList
RoomPlayerList = PhotonNetwork.PlayerList;
}
public void ChangeToTeam1()
{
ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
hash = PhotonNetwork.LocalPlayer.CustomProperties;
int Team = (int)hash["Team"];
if (Team != 1)
{
hash.Remove("Team");
hash.Add("Team", 1);
PhotonNetwork.LocalPlayer.CustomProperties = hash;
}
bool IsReady = (bool)PhotonNetwork.LocalPlayer.CustomProperties["ReadyToPlay"];
if (!IsReady)
{
hash.Remove("ReadyToPlay");
hash.Add("ReadyToPlay", true);
PhotonNetwork.LocalPlayer.CustomProperties = hash;
}
}
public void ChangeToTeam2()
{
ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
hash = PhotonNetwork.LocalPlayer.CustomProperties;
int Team = (int)hash["Team"];
if (Team != 2)
{
hash.Remove("Team");
hash.Add("Team", 2);
PhotonNetwork.LocalPlayer.CustomProperties = hash;
}
bool IsReady = (bool)PhotonNetwork.LocalPlayer.CustomProperties["ReadyToPlay"];
if (!IsReady)
{
hash.Remove("ReadyToPlay");
hash.Add("ReadyToPlay", true);
PhotonNetwork.LocalPlayer.CustomProperties = hash;
}
}
public void ChangeToQueue()
{
ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable();
hash = PhotonNetwork.LocalPlayer.CustomProperties;
int Team = (int)hash["Team"];
if (Team != -1)
{
hash.Remove("Team");
hash.Add("Team", -1);
PhotonNetwork.LocalPlayer.CustomProperties = hash;
}
bool IsReady = (bool)PhotonNetwork.LocalPlayer.CustomProperties["ReadyToPlay"];
if (IsReady)
{
hash.Remove("ReadyToPlay");
hash.Add("ReadyToPlay", false);
PhotonNetwork.LocalPlayer.CustomProperties = hash;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/CreateRoom.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
public class CreateRoom : MonoBehaviourPunCallbacks
{
[SerializeField]
private InputField RoomInputField;
private string RoomName;
private string RoomIdentifier;
[SerializeField]
private RoomLayoutGroup RLG;
private bool Detoir = false;
private void Update()
{
if (Detoir)
{
DetoirJoinRoom();
}
}
public void CreatePhotonRoom()
{
if (PhotonNetwork.IsConnectedAndReady)
{
RoomName = RoomInputField.text;
int RoomNum = PhotonNetwork.CountOfRooms + 1;
int RndInt = Random.Range(1000, 99999);
RoomIdentifier = PlayerNetwork.Instance.name + "'s Room#" + RoomNum;
RoomOptions RO = new RoomOptions() { IsVisible = true, IsOpen = true, MaxPlayers = 12 };
RO.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable();
RO.CustomRoomProperties.Add("RoomNameKey", RoomName);
RO.CustomRoomProperties.Add("RoomTypeKey", "Custom");
RO.CustomRoomProperties.Add("StartedGame", false);
RO.CustomRoomProperties.Add("RoomNumber", RoomNum);
RO.CustomRoomProperties.Add("RoomIdentifier", RoomName + RndInt);
RO.CustomRoomPropertiesForLobby = new string[3];
RO.CustomRoomPropertiesForLobby[0] = "RoomNameKey";
RO.CustomRoomPropertiesForLobby[1] = "RoomTypeKey";
RO.CustomRoomPropertiesForLobby[2] = "RoomNum";
if (RoomName == "")
{
RoomName = PlayerNetwork.Instance.name + "'s Room";
}
if (PhotonNetwork.CreateRoom(RoomIdentifier, RO, TypedLobby.Default))
{
print("Create Room Request Sent.");
}
else
{
print("Create Room Request Failed to Send.");
}
}
}
public void CreatePhotonTrainingRoom()
{
if (PhotonNetwork.IsConnectedAndReady)
{
RoomName = RoomInputField.text;
int RoomNum = PhotonNetwork.CountOfRooms + 1;
int RndInt = Random.Range(1000, 99999);
RoomIdentifier = PlayerNetwork.Instance.name + "'s Training Room#" + RoomNum;
RoomOptions RO = new RoomOptions() { IsVisible = true, IsOpen = true, MaxPlayers = 12 };
RO.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable();
RO.CustomRoomProperties.Add("RoomNameKey", RoomName);
RO.CustomRoomProperties.Add("RoomTypeKey", "TrainingRoom");
RO.CustomRoomProperties.Add("StartedGame", false);
RO.CustomRoomProperties.Add("RoomNumber", RoomNum);
RO.CustomRoomProperties.Add("RoomIdentifier", RoomName + RndInt);
RO.CustomRoomPropertiesForLobby = new string[3];
RO.CustomRoomPropertiesForLobby[0] = "RoomNameKey";
RO.CustomRoomPropertiesForLobby[1] = "RoomTypeKey";
RO.CustomRoomPropertiesForLobby[2] = "RoomNum";
if (RoomName == "")
{
RoomName = PlayerNetwork.Instance.name + "'s Training Room";
}
if (PhotonNetwork.CreateRoom(RoomIdentifier, RO, TypedLobby.Default))
{
print("Create Room Request Sent.");
}
else
{
print("Create Room Request Failed to Send.");
}
}
}
private void OnPhotonCreateRoomFailed(object[] CodeAndMessege)
{
print("Room Failed Error: " + CodeAndMessege[1]);
}
public override void OnCreatedRoom()
{
print("Room Created.");
if (PhotonNetwork.IsConnectedAndReady && PhotonNetwork.InLobby)
{
print("Room Attempted. (OCR)");
PhotonNetwork.JoinRoom(RoomIdentifier);
}
else
{
print("Room Join Detoir.");
Detoir = true;
}
//if (PhotonNetwork.GetCustomRoomList(TypedLobby.Default, ""))
//{
// print("Finding Room Created.");
//}
}
private void DetoirJoinRoom()
{
if (PhotonNetwork.IsConnectedAndReady && PhotonNetwork.InLobby)
{
Detoir = false;
print("Room Attempted. (DJR)");
PhotonNetwork.JoinRoom(RoomIdentifier);
}
}
//public override void OnRoomListUpdate(List<RoomInfo> roomList)
//{
// foreach (RoomInfo RI in roomList)
// {
// if (RI.Name == RoomIdentifier)
// {
// print("Found Room Created.");
// RoomInfo CreatedRoom = RI;
// }
// }
//}
public override void OnJoinRoomFailed(short returnCode, string message)
{
print("Failed to Join Room: " + message + ", " + returnCode);
//base.OnJoinRoomFailed(returnCode, message);
}
public override void OnJoinedRoom()
{
print("Room Joined.");
if (PhotonNetwork.IsMasterClient)
{
Room Current = PhotonNetwork.CurrentRoom;
Current.MaxPlayers = 12;
RoomIdentifier = Current.Name;
}
base.OnJoinedRoom();
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/Older Projects/Space Brawler/LoadScenes.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadScenes : MonoBehaviour {
private bool ShortcutsActive = false;
private void Update()
{
if (ShortcutsActive)
{
if (Input.GetKeyDown(KeyCode.Backspace))
{
LeaveGame();
}
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
if (Input.GetKeyDown(KeyCode.T))
{
LoadTitle();
}
}
}
public void SetShortCuts(bool Active = true)
{
ShortcutsActive = Active;
}
public void LoadMain()
{
SceneManager.LoadScene("Main");
}
public void LoadCalibration()
{
SceneManager.LoadScene("Ship Calibration");
}
public void LoadTitle()
{
SceneManager.LoadScene("Title");
}
public void LoadAcknowledgements() // Credits
{
SceneManager.LoadScene("Acknowledge");
}
public void LoadTest()
{
Debug.Log("Loading Test");
SceneManager.LoadScene("TestGeneric");
}
public void LeaveGame()
{
Application.Quit();
}
public void LoadControls()
{
SceneManager.LoadScene("Controls");
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/DietySound.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DietySound : MonoBehaviour {
public AudioClip[] welcome;
public AudioClip[] NetSpawn;
public AudioClip[] Loose;
private AudioSource Src;
public float dietyVol;
private PlayerSoundSettings PS;
// Use this for initialization
void Awake () {
Src = GetComponent<AudioSource>();
PS = FindObjectOfType<PlayerSoundSettings>();
if (PS)
dietyVol = PS.VoiceVol;
else
dietyVol = 0.1f;
}
// Update is called once per frame
void Update () {
Src.volume = dietyVol;
}
public void PlayDietyWelcome()
{
Src.clip = welcome[Random.Range(0, welcome.Length)];
Src.Play();
}
public void PlayDietyNetSpawn()
{
Src.clip = NetSpawn[Random.Range(0, NetSpawn.Length)];
Src.Play();
}
public void PlaydietyLoose()
{
Src.clip = Loose[Random.Range(0, Loose.Length)];
Src.Play();
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/Spring.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spring : MonoBehaviour {
// Joints
[SerializeField]
private GameObject JointOne;
[SerializeField]
private GameObject JointTwo;
// Custumizables
[SerializeField]
private float VerticeLength = 1;
[SerializeField]
private float MaxLength = 1;
[SerializeField]
private float SpringDamper = 0.7f;
[SerializeField]
private float SpringForceModulus = 1;
[SerializeField]
private bool AttachedToPlayer = false;
// Active Variables
private Vector3 displacement;
private float distance;
private float force;
// gameobject attributes
private Rigidbody RB1;
private Rigidbody RB2;
// Use this for initialization
void Start () {
displacement = JointOne.transform.position - JointTwo.transform.position;
distance = displacement.magnitude;
RB1 = JointOne.GetComponent<Rigidbody>();
RB2 = JointTwo.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
displacement = JointOne.transform.position - JointTwo.transform.position;
distance = displacement.magnitude;
if (distance > VerticeLength + MaxLength)
distance = VerticeLength + MaxLength;
force = SpringForceModulus * (distance - VerticeLength) * SpringDamper;
if (AttachedToPlayer)
{
RB1.AddForce(force * Vector3.up, ForceMode.Force);
}
RB2.AddForce(-force * Vector3.up, ForceMode.Force);
//Debug.Log("Force to Player " + -force);
}
}
<file_sep>/CapstonePowerPlay/Assets/Resources/Scripts/PhotonScripts/RoomListing.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
public class RoomListing : MonoBehaviour {
public struct RoomInfo
{
public string RoomName;
public string RoomIdentifier;
public string RoomType;
public float RoomPing;
public int RoomCount;
public int RoomMaxCount;
}
public RoomInfo RoomListingInfo;
[SerializeField]
private Text RoomNameText;
public string RoomName
{
get { return RoomListingInfo.RoomName; }
set { RoomListingInfo.RoomName = value; }
}
[SerializeField]
private Text RoomTypeText;
public string RoomType
{
get { return RoomListingInfo.RoomType; }
set { RoomListingInfo.RoomType = value; }
}
[SerializeField]
private Text RoomPingText;
public float RoomPing
{
get { return RoomListingInfo.RoomPing; }
set { RoomListingInfo.RoomPing = value; }
}
[SerializeField]
private Text RoomCountText;
public int RoomCount
{
get { return RoomListingInfo.RoomCount; }
set { RoomListingInfo.RoomCount = value; }
}
public int RoomMaxCount
{
get { return RoomListingInfo.RoomMaxCount; }
set { RoomListingInfo.RoomMaxCount = value; }
}
public bool Updated
{
get;
set;
}
[PunRPC]
public void RPC_UpdateRoom(string name, string type, float ping, int count, int maxCount)
{
UpdateInfo(name, type, ping, count, maxCount);
}
public void UpdateRoom()
{
RoomNameText.text = RoomListingInfo.RoomName;
RoomTypeText.text = RoomListingInfo.RoomType;
RoomPingText.text = "" + Mathf.Round(RoomListingInfo.RoomPing);
RoomCountText.text = "" + RoomListingInfo.RoomCount + " / " + RoomListingInfo.RoomMaxCount;
}
public void UpdateInfo(string name, string type ,float ping, int count, int maxCount)
{
RoomListingInfo.RoomName = name;
RoomListingInfo.RoomPing = ping;
RoomListingInfo.RoomType = type;
RoomListingInfo.RoomCount = count;
RoomListingInfo.RoomMaxCount = maxCount;
UpdateRoom();
}
public void SetRoomIdentifier(string identifier)
{
RoomListingInfo.RoomIdentifier = identifier;
}
public RoomInfo GetRoomInfo()
{
return RoomListingInfo;
}
public void SetLobbyNetworkRoom()
{
LobbyNetwork LN = FindObjectOfType<LobbyNetwork>();
LN.SetRoom(this);
}
}
<file_sep>/CapstonePowerPlay/Assets/MenuCamFolder/Scripts/PlayerToMenuInteraction.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerToMenuInteraction : MonoBehaviour {
private Camera menuCamera;
private bool allowInteraction = false;
public bool triggerInteraction;
// Use this for initialization
void Start () {
menuCamera = transform.GetComponent<Camera>();
}
// Update is called once per frame
void Update () {
if (allowInteraction)
{
RaycastHit hit;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = menuCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Transform objectHit = hit.transform;
hit.transform.GetComponent<ButtonCallToDollyManager>().CallEffect();
allowInteraction = false;
}
}
}
if (!triggerInteraction)
{
RaycastHit hit;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = menuCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
//Debug.Log("Hit: " + hit.transform.gameObject.name);
Transform objectHit = hit.transform;
hit.transform.GetComponent<ButtonCallToDollyManager>().CallEffect();
allowInteraction = false;
}
}
}
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "MenuTrigger")
{
if(!triggerInteraction)
allowInteraction = true;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/SpeedBoostEffect.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedBoostEffect : MonoBehaviour {
private hoverBoardScript hBS;
[SerializeField]
private float speedBoost;
[SerializeField]
private float maxTime;
private float timeLeft;
private bool boosting;
private void Start()
{
hBS = transform.GetComponent<hoverBoardScript>();
hBS.BoostPaddBoostLinearPercent = 0;
}
// create boost pad linear percentage in hover board script
// private hoverBoardScript tpControler;
private void Update()
{
if(timeLeft > 0 && boosting)
{
timeLeft -= Time.deltaTime;
}
else if(timeLeft <= 0 && boosting)
{
boosting = false;
// hbs boost is set to 0
hBS.BoostPaddBoostLinearPercent = 0;
}
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "BoostPad")
{
//Debug.Log("Boosting");
timeLeft = maxTime;
boosting = true;
// hbs boost is set to speedBoost
hBS.BoostPaddBoostLinearPercent = speedBoost;
}
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/PhotonTransform.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PhotonTransform : MonoBehaviourPun, IPunObservable {
[SerializeField]
private float SmoothingPositionPercent = 0.1f;
[SerializeField]
private float SmoothingRotationPercent = 0.9f;
[SerializeField]
private int PhotonSendRate = 60;
[SerializeField]
private int PhotonSerializeRate = 30;
[SerializeField]
private Transform PT;
[SerializeField]
private PhotonView PV;
private Vector3 TargetPosition = Vector3.zero;
private Quaternion TargetRotation = Quaternion.identity;
void Awake()
{
PhotonNetwork.SendRate = PhotonSendRate;
PhotonNetwork.SerializationRate = PhotonSerializeRate;
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
if (transform.parent == null)
{
stream.SendNext(PT.position);
stream.SendNext(PT.rotation);
}
}
else
{
TargetPosition = (Vector3)stream.ReceiveNext();
TargetRotation = (Quaternion)stream.ReceiveNext();
}
}
// Use this for initialization
void Start () {
TargetPosition = PT.position;
TargetRotation = PT.rotation;
}
// Update is called once per frame
void Update () {
if (transform.parent == null)
{
if (PV.IsMine)
{
// Local Player
}
else
{
// Smooth Player
SmoothMovement();
}
}
}
private void SmoothMovement()
{
//print("Smoothing Movement");
PT.position = Vector3.Lerp(PT.position, TargetPosition, SmoothingPositionPercent);
PT.rotation = Quaternion.Lerp(PT.rotation, TargetRotation, SmoothingPositionPercent);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/CamControl1st.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamControl1st : MonoBehaviour {
// Camera
[SerializeField] private Camera Cam;
// Camera Settings
[SerializeField] private float cameraSpeedY = 2.0f;
[SerializeField] private float cameraSpeedx = 2.0f;
// Private
private float yaw = 0.0f;
private float pitch = 0.0f;
private Transform Trans;
private void Start () {
//Error Check
if (!Cam)
Debug.LogError("No Camera Found(CamControl1st: " + gameObject.name + ")");
// Init
Trans = transform;
}
// Update is called once per frame
private void FixedUpdate () {
yaw = cameraSpeedx * Input.GetAxis("Mouse X");
pitch = cameraSpeedY * Input.GetAxis("Mouse Y");
Trans.Rotate(new Vector3(0.0f, 1.0f, 0.0f) * yaw);
Cam.transform.Rotate(new Vector3(1.0f, 0.0f, 0.0f) * -pitch);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/AnimationController.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationController : MonoBehaviour {
// Player Components
[SerializeField]
private Animator BlueAnimator;
[SerializeField]
private Animator RedAnimator;
[SerializeField]
private GameObject BlueAvatar;
[SerializeField]
private GameObject RedAvatar;
[SerializeField]
private hoverBoardScript HoverBoard;
[SerializeField]
private PlayerColor PC;
// Animation Components
//[SyncVar(hook = "PassAnimation")]
private bool Pass = false;
//[SyncVar(hook = "JumpAnimation")]
private bool Jump = false;
//[SyncVar(hook = "UpdateGrounded")]
private bool Grounded = true;
//[SyncVar(hook = "UpdateSpeedRatio")]
private float SpeedRatio = 0;
[SerializeField]
private Transform LookAtPosition;
[HideInInspector]
public Vector3 LookPos;
[SerializeField]
private PhotonView PV;
public void UpdateTargetPosition(Vector3 pos)
{
//RpcUpdateTargetPosition(pos);
if (PhotonNetwork.InRoom)
PV.RPC("RPC_UpdateTargetPosition", RpcTarget.All, pos);
}
[PunRPC]
public void RPC_UpdateTargetPosition(Vector3 pos)
{
LookPos = pos;
}
public void PassAnimation()
{
//RpcPassAnimation();
if (PhotonNetwork.InRoom)
PV.RPC("RPC_PassAnimation", RpcTarget.All);
}
[PunRPC]
public void RPC_PassAnimation()
{
Pass = true;
PassAnimation(Pass);
}
private void PassAnimation(bool pass)
{
Pass = pass;
if (Pass == true)
{
if (RedAvatar.activeSelf)
{
RedAnimator.SetTrigger("Pass");
}
else if (BlueAvatar.activeSelf)
{
BlueAnimator.SetTrigger("Pass");
}
}
Pass = false;
}
public void JumpAnimation()
{
//RpcJumpAnimation();
if (PhotonNetwork.InRoom)
PV.RPC("RPC_JumpAnimation", RpcTarget.All);
}
[PunRPC]
public void RPC_JumpAnimation()
{
Jump = true;
JumpAnimation(Jump);
}
private void JumpAnimation(bool jump)
{
Jump = jump;
if (Jump == true)
{
if (RedAvatar.activeSelf)
{
RedAnimator.SetTrigger("Jump");
}
else if (BlueAvatar.activeSelf)
{
BlueAnimator.SetTrigger("Jump");
}
}
Jump = false;
}
public void UpdateSpeedRatio1(float ratio)
{
//RpcUpdateSpeedRatio(ratio);
if (PhotonNetwork.InRoom)
PV.RPC("RPC_UpdateSpeedRatio", RpcTarget.All, ratio);
}
[PunRPC]
public void RPC_UpdateSpeedRatio(float ratio)
{
SpeedRatio = ratio;
UpdateSpeedRatio(SpeedRatio);
}
public void UpdateSpeedRatio(float ratio)
{
SpeedRatio = ratio;
if (RedAvatar.activeSelf)
{
RedAnimator.SetFloat("SpeedRatio", SpeedRatio);
}
else if (BlueAvatar.activeSelf)
{
BlueAnimator.SetFloat("SpeedRatio", SpeedRatio);
}
}
private void UpdateGrounded(bool grounded)
{
Grounded = grounded;
if (RedAvatar.activeSelf)
{
RedAnimator.SetBool("Grounded", Grounded);
}
else if (BlueAvatar.activeSelf)
{
BlueAnimator.SetBool("Grounded", Grounded);
}
}
public void UpdateGrounded1(bool grounded)
{
//RpcUpdateGrounded(Grounded);
if (PhotonNetwork.InRoom)
PV.RPC("RPC_UpdateGrounded", RpcTarget.All, grounded);
}
[PunRPC]
public void RPC_UpdateGrounded(bool grounded)
{
Grounded = grounded;
UpdateGrounded(Grounded);
}
public GameObject ReturnBlueAvatar()
{
return BlueAvatar;
}
public GameObject ReturnRedAvatar()
{
return RedAvatar;
}
public Animator ReturnBlueAnimator()
{
return BlueAnimator;
}
public Animator ReturnRedAnimator()
{
return RedAnimator;
}
public Transform ReturnLookPos()
{
return LookAtPosition;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ApplyInputUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ApplyInputUI : MonoBehaviour {
[SerializeField]
private InputField Input;
[SerializeField]
private hoverBoardScript HB;
public void ChangeHoverBoardKp(string newStr)
{
HB.ChangeKp(float.Parse(newStr));
}
public void ChangeHoverBoardKi(string newStr)
{
HB.ChangeKi(float.Parse(newStr));
}
public void ChangeHoverBoardKd(string newStr)
{
HB.ChangeKd(float.Parse(newStr));
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/KeepNetRotation.cs
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeepNetRotation : MonoBehaviour {
[SerializeField]
private Animator AN;
//[SyncVar(hook = "UpdateRotation")]
private bool IsRotating = false;
private NetPlayer[] NetPlayerList;
private hoverBoardScript[] HoverboardList;
private PhotonView PV;
private void Start()
{
PV = GetComponent<PhotonView>();
}
// Update is called once per frame
void Update () {
if (!IsRotating)
{
NetPlayerList = FindObjectsOfType<NetPlayer>();
HoverboardList = FindObjectsOfType<hoverBoardScript>();
if (NetPlayerList.Length > 0)
{
if (HoverboardList.Length > 0)
{
if (NetPlayerList.Length == HoverboardList.Length)
{
if (PhotonNetwork.IsMasterClient)
//CmdUpdateRotation(true);
PV.RPC("RPC_UpdateRotation", RpcTarget.AllBuffered, IsRotating);
}
}
}
}
else
{
if (!AN.GetBool("Rotate"))
{
AN.SetBool("Rotate", IsRotating);
}
}
}
[PunRPC]
private void RPC_UpdateRotation(bool rotating)
{
IsRotating = rotating;
}
private void UpdateRotation(bool rotating)
{
IsRotating = rotating;
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/ResizeCanvases.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResizeCanvases : MonoBehaviour {
void Update () {
transform.localScale = new Vector3(Screen.width, Screen.height, 1);
}
}
<file_sep>/CapstonePowerPlay/Assets/Scripts/KeepUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class KeepUp : MonoBehaviour
{
[SerializeField]
private bool LockX = false;
[SerializeField]
private bool LockY = false;
[SerializeField]
private bool LockZ = false;
[SerializeField]
private bool LockROTX = false;
[SerializeField]
private bool LockROTY = false;
[SerializeField]
private bool LockROTZ = false;
[SerializeField]
private Transform _player;
[SerializeField]
private bool LookAtTarget = false;
[SerializeField]
private Transform LookAt;
// Update is called once per frame
void Update ()
{
if(LockX)
{
transform.position = new Vector3(_player.position.x, transform.position.y, transform.position.z);
}
if(LockY)
{
transform.position = new Vector3(transform.position.x, _player.position.y, transform.position.z);
}
if (LockZ)
{
transform.position = new Vector3(transform.position.x, transform.position.y, _player.position.z);
}
if (LockROTY)
{
transform.rotation.eulerAngles.Set(transform.rotation.eulerAngles.x, _player.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
}
if (LockROTX)
{
transform.rotation.eulerAngles.Set(_player.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
}
if (LockROTZ)
{
transform.rotation.eulerAngles.Set(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, _player.rotation.eulerAngles.z);
}
if (LookAtTarget)
{
transform.LookAt(LookAt);
}
}
}
| 0d7068b95f628a6067667b38faa31c7acec4b1d2 | [
"C#"
] | 112 | C# | zCoLtX45z/Capstone_PPP | 28b59c4a70e77f038d3c20266ebe0a0b32f89381 | 398975d5af72f762650232817d85a5df769d94ff |
refs/heads/master | <file_sep># STEMNightsBarGraph
Shiny app that will plot a bar graph for number of m&m's in individual package
<file_sep>require(shiny)
require(ggplot2)
require(plyr)
# Define UI for application that draws a histogram
shinyUI <- fluidPage(
# Application title
titlePanel("Hello Kids!"),
sidebarLayout(
sidebarPanel(
numericInput("numYellow", label = h3("# of Yellow M&Ms"), value = 1),
numericInput("numBlue", label = h3("# of Blue M&Ms"), value = 1),
numericInput("numBrown", label = h3("# of Brown M&Ms"), value = 1),
numericInput("numGreen", label = h3("# of Green M&Ms"), value = 1),
numericInput("numOrange", label = h3("# of Orange M&Ms"), value = 1),
numericInput("numRed", label = h3("# of Red M&Ms"), value = 1),
actionButton("goButton", "Go!", class = "btn-primary")
),
# Show a plot of the generated distribution
mainPanel(plotOutput("distPlot"))
)
)
# Define server logic required to draw a histogram
shinyServer <- function(input, output){
require(ggplot2)
require(reshape2)
d <- data.frame(Yellow=c(0),
Blue=c(0),
Brown=c(0),
Green=c(0),
Orange=c(0),
Red=c(0))
write.csv(x = d, file="colordata.csv", row.names = FALSE)
observeEvent(input$goButton, {
d <- read.csv("colordata.csv", header=TRUE)
d <- rbind(d,c(input$numYellow, input$numBlue, input$numBrown, input$numGreen, input$numOrange, input$numRed))
write.csv(x = d, file="colordata.csv", row.names = FALSE)
})
output$distPlot <- renderPlot({
input$goButton
d <- read.csv("colordata.csv", header=TRUE)
d <- melt(d)
d <- rep(d$variable, d$value)
# draw the histogram with the specified number of bins
ggplot() + geom_bar(aes(x=d)) +
labs(x="M&M Color") + theme(axis.title.y = element_text(size = rel(1.8), angle = 90)) +
theme(axis.title.x = element_text(size = rel(1.8), angle = 00))
})
}
shinyApp(ui = shinyUI, server = shinyServer)
| d64eae8972653afc0cad4486b9cffca609c2a449 | [
"Markdown",
"R"
] | 2 | Markdown | nulloa/STEMNightsBarGraph | 84abc8644e144d3eeafb55787a379f6bf54ea77f | 819ac3a83c9adc2503ff8a0e2fb10a9af34f5e01 |
refs/heads/master | <repo_name>usamaimtiaz32/Horizontal-and-vertical<file_sep>/app/src/main/java/com/example/bookhotells/Details.java
package com.example.bookhotells;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class Details extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
}
public void Back(View view) {
Intent intent=new Intent(Details.this, Search.class);
startActivity(intent);
}
}
| 2ffa24b564d7673aefd43a55e1586f6516b7c76d | [
"Java"
] | 1 | Java | usamaimtiaz32/Horizontal-and-vertical | a729817cb682536e965dcf40d4bae59bb69d0b7d | 3b5dfe9c82ffb89939b888aff37f28e444a61f54 |
refs/heads/master | <repo_name>kestkest/demo<file_sep>/shpfy.py
# coding: utf-8
import json
from django.shortcuts import redirect, render
from django.core.urlresolvers import reverse
from django.contrib.auth import login, logout
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponse
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from accounts.registration import ShopifyUserRegistration
from leads.models import Lead, LeadOrder, Multilead
from automailer.coupon_model import Coupon
from accounts.utils import check_spf as check_site_spf
from accounts.models import NewUser as User, Site, Tariff, YMLFile, YMLOffer, WidgetsConf
from profile.views import LeadForm, Leadlist, EmailTemplate, Autocast
from django.utils.decorators import decorator_from_middleware, method_decorator
from middleware import LoginProtection
from profile.views import TRACKER_CODE
from profile.celery.yml import upload_yml_file
from lib.core.acl import role_required, permission_required
from lxml import etree
import string
import random
import shopify
import datetime
import logging
shopify_logger = logging.getLogger('shopify.request')
@method_decorator(decorator_from_middleware(LoginProtection), name='dispatch')
class LoginView(View):
http_method_names = ['get']
def get(self, request):
try:
shop = request.GET.get('shop')
redirect_uri = request.build_absolute_uri(reverse('shopify_app:finalize'))
if 'https' not in redirect_uri:
redirect_uri = redirect_uri.replace('http', 'https')
permission_url = shopify.Session(shop.strip()).create_permission_url(settings.SHOPIFY_API_SCOPE, redirect_uri)
return redirect(permission_url)
except:
return JsonResponse({'status': 'error',
'error': _(u'Некорректное имя магазина')})
@method_decorator(decorator_from_middleware(LoginProtection), name='dispatch')
class FinalizeView(View):
http_method_names = ['get']
def get(self, request):
shop = request.GET.get('shop')
tariff = Tariff.objects(name='Shopify')
if not tariff:
Tariff(name='Shopify', emails_limit=5000, leads_limit=999999999, sites_limit=1,
forms_limit=30, alerts_limit=5000, scopes=[u'leads', u'email', u'automailer',
u'widgets', u'reports', u'analytics',
u'lists', u'smm', u'alerts']).save()
try:
shopify_session = shopify.Session(shop)
access_token = shopify_session.request_token(request.GET)
except:
return JsonResponse({'status': 'error',
'error': _(u'Некорретные данные запроса')})
with shopify.Session.temp(shop, access_token):
current_shop = shopify.Shop.current()
site_name = 'https://' + current_shop.domain
site = Site.objects(domain=site_name).first()
if site:
# Login request
charge = shopify.RecurringApplicationCharge.current()
try:
status = charge.attributes['status']
if status == 'declined' or status == 'frozen':
site.update(is_active=False)
return render(request, 'shopify_info.html', {'store_url': site.domain + '/admin/apps'})
# charge is fine case
if status == 'accepted':
charge.activate()
if not site.is_active:
site.update(is_active=True)
user = User.objects(sites__in=[str(site.id)]).first()
if not user.is_active:
user.update(is_active=True)
except AttributeError:
# current() возвращает None
# Согласно документации, данная ситуация возникает в случае если спустя 48 часов после выставления счета магазин его не оплачивает
# В случае с тестовым магазином данный случай протестировать нереально.
# Также это кейс возможен в случае отказа от платежа при установке и последющей попытке зайти в сервис
site.update(shopify_token=access_token) # Токен обновляется на случай если, магазин удалил наше приложение и установил заново
charge = shopify.RecurringApplicationCharge()
charge.price = 29
charge.name = 'LeadHit installation charge'
if current_shop.attributes['plan_name'] == 'affiliate':
charge.test = True
# Также такой случай возможен в случае удаления и последующей установки магазином нашего приложения
# Ниже обрабатывается именно этот случай
site_added = site.time_added
trial_expire_date = site_added + datetime.timedelta(days=30)
now = datetime.datetime.now()
if now < trial_expire_date:
trial_days_left = (trial_expire_date - now).days
charge.trial_days = trial_days_left
return_url = request.build_absolute_uri(reverse('shopify_app:process_charge'))
if 'https' not in return_url:
return_url = return_url.replace('http', 'https')
charge.return_url = return_url + '?shop=' + site_name
charge.save()
confirmation_url = charge.attributes['confirmation_url']
return redirect(confirmation_url)
user = User.objects.get(sites=str(site.id), role='master')
if not user.is_active:
user.update(is_active=True)
site.update(shopify_token=access_token)
if not request.user.is_anonymous:
logout(request)
return_url = request.build_absolute_uri(reverse('shopify_app:process_charge'))
self.check_or_update_tracker(request, str(site.id))
login(request, user)
return redirect('/?site_id={}'.format(site.id))
else:
# Registration request
username = current_shop.email
password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))
phone = current_shop.phone
tariff_name = 'Shopify'
host = ''.join([request.scheme, '://', request.get_host()])
registration = ShopifyUserRegistration(username, password, phone, tariff_name, site_name, host)
user, site = registration.register()
site.update(shopify_token=access_token)
yml_file = YMLFile.objects.get(site=site)
# create the default coupon for a site
Coupon(
code='LeadHit10OFF',
text='Get a discount!',
categories={},
instruction='Paste this code on the checkout page to get a discount',
fit_to_random=True,
yml_file=yml_file,
site=site,
ignore_availability=False,
universal=True).save()
charge = shopify.RecurringApplicationCharge()
charge.price = 29
charge.name = 'LeadHit app installation'
charge.trial_days = 30
if current_shop.attributes['plan_name'] == 'affiliate':
charge.test = True
return_url = request.build_absolute_uri(reverse('shopify_app:process_charge'))
if 'https' not in return_url:
return_url = return_url.replace('http', 'https')
charge.return_url = return_url + '?shop=' + site_name
charge.save()
# getting charge confirmation_url after saving
confirmation_url = charge.attributes['confirmation_url']
return redirect(confirmation_url)
def check_or_update_tracker(self, request, site_id):
script_url = request.build_absolute_uri(reverse('shopify_app:site_tracker')) + '?site_id={}'.format(site_id)
script_url = script_url.replace('http://', 'https://')
script_tag = shopify.ScriptTag.find(src=script_url)
if not script_tag:
script_tag = shopify.ScriptTag()
script_tag.src = script_url
script_tag.event = 'onload'
script_tag.save()
# @method_decorator(decorator_from_middleware(LoginProtection), name='dispatch')
class ProcessChargeView(View):
http_method_names = ['get', 'options']
def get(self, request):
shop = request.GET.get('shop')
charge_id = request.GET.get('charge_id')
site = Site.objects(domain=shop).first()
if not site:
response = render(request, 'shopify_info.html', {'store_url': shop + '/admin/apps', 'message': 'Unknown error occurred. Send us feedback at <EMAIL>'})
response['Access-Control-Allow-Origin'] = '*'
return response
yml_file = YMLFile.objects.get(site=site)
with shopify.Session.temp(shop, site.shopify_token):
charge = shopify.RecurringApplicationCharge.find(charge_id)
webhook = shopify.Webhook()
webhook.topic = 'app/uninstalled'
webhook.address = 'https://service.leadhit.ru/shopify/app_delete/'
webhook.save()
if charge.attributes['status'] == 'accepted':
charge.activate()
redirect_uri = request.build_absolute_uri(reverse('shopify_app:login'))
redirect_uri = redirect_uri.replace('http', 'https') + '?shop=' + shop + '&charge_id=' + charge_id
response = redirect(redirect_uri)
upload_yml_file.apply_async(args=[yml_file, 'force'])
autocasts = Autocast.objects(site=site)
for a in autocasts:
a.sender = u'<EMAIL>'
a.save()
else:
response = render(request, 'shopify_info.html', {
'store_admin': site.domain + '/admin/apps'
})
site.is_active = False
site.save()
response['Access-Control-Allow-Origin'] = '*'
return response
def options(self, request):
response = HttpResponse('')
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'GET'
response['Access-Control-Allow-Headers'] = 'x-shopify-web'
return response
class SiteTrackerView(View):
http_method_names = ['get']
def get(self, request):
site_id = request.GET.get('site_id', '')
code = TRACKER_CODE.format(site_id=site_id)
return HttpResponse(code, content_type='application/javascript')
@method_decorator(decorator_from_middleware(LoginProtection), name='dispatch')
class FakeYMLView(View):
def get(self, request):
site = Site.objects.get(domain=request.GET.get('site'))
shop = site.domain.replace('https://', '')
access_token = site.shopify_token
with shopify.Session.temp(shop, access_token):
shopify_shop_obj = shopify.Shop.current()
shop_collects = shopify.Collect.find()
shop_products = shopify.Product.find()
shop_categories = shopify.SmartCollection.find()
shop_categories += shopify.CustomCollection.find()
yml_file = generate_yml_file(shopify_shop_obj, shop_categories, shop_products, shop_collects)
return HttpResponse(yml_file, content_type='text/xml')
def generate_yml_file(shopify_shop, shop_categories, products, collects):
now = str(datetime.datetime.now()).rsplit(':', 1)[0]
# setup root element
root = etree.Element('yml_catalog', date=now)
# setup shop subelement and it`s subelements 'name', 'company', 'url' and 'currency'
shop = etree.SubElement(root, 'shop')
shop_name = etree.SubElement(shop, 'name')
shop_name.text = shopify_shop.attributes.get('name')
shop_company = etree.SubElement(shop, 'company')
shop_company.text = shopify_shop.attributes.get('name')
shop_url = etree.SubElement(shop, 'url')
shop_url.text = 'https://' + shopify_shop.attributes.get('domain')
shop_currencies = etree.SubElement(shop, 'currencies')
shop_single_currency = etree.SubElement(shop_currencies, 'currency', id=shopify_shop.attributes.get('currency', 'USD'))
offers = etree.SubElement(shop, 'offers')
categories = {category.id: category for category in shop_categories}
categories_tag = etree.SubElement(shop, 'categories')
for category in categories:
cat_obj = categories[category]
cur_category = etree.SubElement(categories_tag, 'category', id=str(cat_obj.id))
cur_category.text = cat_obj.attributes['title']
default_category = etree.SubElement(categories_tag, 'category', id='Main')
# data for yml offers to add
products = {product.id: product for product in products}
processed_products = set()
shop_domain = shopify_shop.attributes['domain']
currencyId = shopify_shop.attributes.get('currency', 'USD')
for category in shop_categories:
category_products = category.products()
for product in category_products:
add_yml_offer(parent_element=offers, product=product, category=category, shop_domain=shop_domain, currencyId=currencyId)
processed_products.add(product.id)
# removing processed products belonging to any category
# products having no category stay in products dict and get assigned the default category
for processed_product in processed_products:
if processed_product in products:
del products[processed_product]
for prd_id in products:
product = products[prd_id]
add_yml_offer(parent_element=offers, product=product, category=None, shop_domain=shop_domain, currencyId=currencyId)
return etree.tostring(root, pretty_print=True)
def add_yml_offer(parent_element=None, product=None, category=None, shop_domain=None, currencyId=None):
if not category:
# offers with no category get assigned "Main" category
add_offer(parent_element=parent_element, product=product, category=category, shop_domain=shop_domain, currencyId=currencyId)
else:
add_offer(based_on_category=False, parent_element=parent_element, product=product, category=category, shop_domain=shop_domain, currencyId=currencyId)
add_offer(parent_element=parent_element, product=product, category=category, shop_domain=shop_domain, currencyId=currencyId)
def add_offer(based_on_category=True, parent_element=None, product=None, category=None, shop_domain=None, currencyId=None):
for variant in product.variants:
availability = 'true' if variant.inventory_quantity else 'false'
cur_product = etree.SubElement(parent_element, 'offer', parent_id=str(product.id), id=str(variant.id), available=availability)
name = product.attributes['title'] if variant.title == 'Default Title' else product.attributes['title'] + ', ' + variant.title
product_name = etree.SubElement(cur_product, 'name')
product_name.text = name
product_url = etree.SubElement(cur_product, 'url')
if based_on_category and category:
product_url.text = 'https://' + shop_domain + '/collections/' + category.handle + '/products/' + product.attributes['handle']
else:
product_url.text = 'https://' + shop_domain + '/products/' + product.attributes['handle']
product_price = etree.SubElement(cur_product, 'price')
product_price.text = variant.attributes['price']
product_currency = etree.SubElement(cur_product, 'currencyId')
product_currency.text = currencyId
if product.attributes.get('image'):
product_picture = etree.SubElement(cur_product, 'picture')
image_url = product.attributes['image'].attributes['src']
if '?v=' in image_url:
image_url = image_url[:image_url.find('?v=')]
product_picture.text = image_url
product_category = etree.SubElement(cur_product, 'categoryId')
if category:
product_category.text = str(category.id)
else:
product_category.text = 'Main'
@role_required(('master', 'manager'))
def get_or_set_site_settings(request):
site = request.site
if request.method == 'GET':
return JsonResponse({
'logo_url': site.logo_url,
'cart_url': site.domain
})
if request.method == 'POST':
attr = request.POST.get('attr')
value = request.POST.get('value')
setattr(site, attr, value)
site.save()
return JsonResponse({'status': 'success', 'msg': 'site settings have been updated'})
def check_spf(request):
site = request.site
check_site_spf(site)
if site.spf_correct and 'shopify' in get_store_second_level_domain(site.domain):
site.spf_correct = False
site.save()
return JsonResponse({'spf_correct': site.spf_correct})
@csrf_exempt
def delete_shop(request):
shopify_logger.info(request.path + '\n' + request.body + '\n' + '*' * 50)
return HttpResponse(status=200)
@csrf_exempt
def customer_redact(request):
shopify_logger.info(request.path + '\n' + request.body + '\n' + '*' * 50)
return HttpResponse(status=200)
@csrf_exempt
def get_customer_data(request):
""" request payload
{
"shop_id":22747251,
"shop_domain":"lead-test.myshopify.com",
"customer":{"id":688988520501,"email":"<EMAIL>","phone":null},"orders_requested":[589347782709,589486522421,589545340981]
}
"""
data = json.loads(request.body)
try:
site = Site.objects.get(domain='https://' + data['shop_domain'])
lead = Lead.objects.get(site=site, email=data['customer']['email'])
# orders = list(LeadOrder.objects(lead=lead))
orders = [
{'cart_sum': order.cart_sum,
'time_submitted': order.time_added,
'order_id': order.order_id} for order in LeadOrder.objects(lead=lead)]
except:
return JsonResponse({})
return JsonResponse({'email': lead.email, 'orders': orders})
@csrf_exempt
def app_delete(request):
'''
Gets triggered by our application removal.
Deactivates user if none of his sites have our app installed
'''
body = json.loads(request.body)
site_domain = 'https://' + body['domain']
site = Site.objects(domain=site_domain).first()
if site is None:
return HttpResponse(status=200)
site.is_active = False
site.save()
user = User.objects(sites__in=[str(site.id)]).first()
no_active_sites = not any(site.is_active for site in Site.objects(id__in=user.sites))
if no_active_sites:
user.is_active = False
user.save()
return HttpResponse(status=200)
def get_store_second_level_domain(address):
return address.strip('/').split('.')[-2]
<file_sep>/chart.py
# coding: utf-8
from __future__ import division
import datetime
import json
import copy
import itertools
import hashlib
from mongoengine import Q
from leadhit_common.functions import get_minimal_url
from django.conf import settings
from django.utils.translation import ugettext, ugettext_lazy as _
from bson import ObjectId
from bson.dbref import DBRef
from accounts.models import YMLOffer, YMLFile
from automailer.models import Autocast
from leads.models import Lead, TraffSource, LeadEvent, LeadOrder, Multilead, CartItem
from analytics.utils.helpers import Period, validate_time_period, get_sum_orders_by_week
from analytics.forms import WidgetStatForm, StatForm
from analytics.utils.helpers import humanize_form_errors
from accounts.models import WidgetsConf
from emails.models import Message, Email, UnsubscribedEmail
from widgets.helpers import get_recommendations_widgets
db = settings.DB
widgets_with_conversion = ('New_Smart_final', 'wish_list')
class Chart(object):
"""
Base Chart class. Contains bwish_listasic chart settings and a 'period' helper.
Each subclass has to declare 'events' attribute in order to set proper settings for axes and graphs.
The 'events' attr is declared this way:
events = {
{event1: {name: event1_name, verbose_name: event1_verbose_name, color: event1_color}}
{event2: {name: event2_name, verbose_name: event2_verbose_name, color: event2_color}}
}
"""
def __init__(self):
self.period = Period()
self.chart_settings = {
"type": "serial",
"theme": "light",
"marginRight": 80,
"autoMarginOffset": 20,
"marginTop": 7,
"synchronizeGrid": True,
"legend": {
"useGraphSettings": True,
},
"mouseWheelZoomEnabled": True,
"categoryAxis": {
"parseDates": True,
"axisColor": "#DADADA",
"minorGridEnabled": True,
"minPeriod": 'mm'
},
"chartScrollbar": {},
"chartCursor": {
"cursorPosition": "mouse",
"pan": True,
},
"export": {
"enabled": True,
"position": "bottom-right"
},
# This is a path to the static files used by amcharts. It depends on a webpack configuration of the 'CopyWebpackPlugin' plugin.
"path": "/static/dist/amcharts",
# Since we only use 'dates' in our stats categoryField value is set to 'date' by default
"categoryField": "date",
# valueAxes list depends on "events" and gets generated depending on event's values.
# Is set to None to avoid caching.
"valueAxes": None,
# The graph list depends on "events" and gets generated depending on event's values
# Is set to None to avoid caching
"graphs": None,
"dataDateFormat": "YYYY-MM-DD HH:NN",
}
# Axes options.
# In case of multiple graphs we instantiate multiple axes e.g chart_settings['valueAxes'] = [axis1_settings, axis2_settings, etc]
# Values:
# id - has to be set in case of multiple graphs. Axis id is used by a certain graph e.g. graph['valueAxis'] = axis['id']
# title and axisColor are self explanatory.
self.axis_settins = {
"id": None,
"axisColor": '#787978',
"axisThickness": 2,
"axisAlpha": 1,
"position": "left",
"title": None,
}
# Graph's options.
# Values to be set:
# valueAxis - binds graph to a particular axis (relevant if multiple axes are set),
# title - this attr gets named after event's verbose name,
# valueField - a field from dataProvider object to get data from
# lineColor - graph color :)
self.graph_settings = {
"valueAxis": None,
"balloonText": "[[value]]",
"bullet": "round",
"bulletBorderAlpha": 1,
"bulletColor": "#FFFFFF",
"hideBulletsCount": 50,
"title": None,
"valueField": None,
"useLineColorForBulletBorder": True,
"balloon": {
"drop": True
},
"bulletSize": 3,
"lineThickness": 2,
"lineColor": None,
"fillAlphas": 0,
}
def generate_graphs_and_axes(self, events):
axis_offset = 0
axis_counter = 0
axis_placement = 'left'
axes = []
graphs = []
for event in events:
axis = self.axis_settins.copy()
graph = self.graph_settings.copy()
axis_placement = 'left' if axis_counter % 2 == 0 else 'right'
axis_offset = axis_counter / 2 * 40
if axis_counter >= 2:
axis["gridAlpha"] = 0
event_data = self.events.get(event)
axis["id"] = event_data["name"]
axis["axisColor"] = event_data["color"]
axis["position"] = axis_placement
axis["offset"] = axis_offset
graph["id"] = event_data["name"]
graph["valueField"] = event_data["name"]
graph["title"] = event_data["verbose_name"]
graph["lineColor"] = event_data["color"]
graph["valueAxis"] = axis["id"]
axis_counter += 1
axes.append(axis)
graphs.append(graph)
return {'axes': axes, 'graphs': graphs}
def get_data(self):
raise NotImplementedError("get_data is not implemented yet")
def validate_input(self, data):
raise NotImplementedError("validate_input is not implemented yet")
def get_relevant_events(self, options):
raise NotImplementedError("Should be implemented to generate graphs and axes")
class WidgetsChart(Chart):
events = {
'fill': {'name': 'fill', 'verbose_name': ugettext(u'Заполнения'), 'color': '#35b54b'},
'view': {'name': 'view', 'verbose_name': ugettext(u'Показы'), 'color': '#787978'},
'popup_view': {'name': 'popup_view', 'verbose_name': ugettext(u'Показы всплывающего окна'), 'color': '#2491c5'},
'close': {'name': 'close', 'verbose_name': ugettext(u'Закрытия'), 'color': "#bd3c3c"},
# conversion is a computed event: fill_count * 100 / popup_view
'conversion': {'name': 'conversion', 'verbose_name': ugettext(u'Конверсия в среднем за период (%)'), 'color': '#4070a0'},
'popup_view_3s': {'name': 'popup_view_3s', 'verbose_name': ugettext(u'Показы всплывающего окна 3 сек.'), 'color': '#ffff00'},
'popup_view_10s': {'name': 'popup_view_10s', 'verbose_name': ugettext(u'Показ всплывающего окна 10 сек.'), 'color': '#66ff66'},
'click': {'name': 'click', 'verbose_name': ugettext(u'Клики'), 'color': '#00b359'},
}
disabled_graphs = ('conversion', 'close', 'popup_view_10s', 'popup_view_3s')
def validate_input(self, options):
widget_id = options['widget_id']
aggregate_period = options['aggregate_period']
if options['period'] != 'custom':
self.period = Period.from_def_ranges(options['period'])
start = self.period.start
end = self.period.end
else:
form = WidgetStatForm(options)
if not form.is_valid():
return {'status': 'error', 'errors': humanize_form_errors(form)}
form_data = form.cleaned_data
if not form_data['start']:
form.errors['start'] = [_(u"Обязательное поле")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if not form_data['end']:
form.errors['end'] = [_(u"Обязательное поле")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
start = form_data['start']
end = form_data['end'].replace(hour=23, minute=59, second=59)
if start.date() > datetime.datetime.now().date():
form.errors['start'] = [_(u"Начало периода не может быть позже текущего дня.")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if end.date() > datetime.datetime.now().date():
form.errors['end'] = [_(u"Конец периода не может быть позже текущего дня.")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if start > end:
form.errors["start"] = [_(u'Начало периода не должно быть больше конца периода.')]
return {'status': 'error', 'errors': humanize_form_errors(form)}
return {
"status": "ok",
"wid": widget_id,
"start": start,
"end": end,
"aggregate_period": aggregate_period,
"group_by_visits": options["group_by_visits"],
"single_axis": options["single_axis"],
}
def get_relevant_events(self, options):
site = ObjectId(self.request.site_id)
lead_events = db.lead_events.find(
{
"init_by": options["wid"],
"time_added": {
"$gte": options["start"],
"$lte": options["end"],
},
'site': DBRef("sites", site),
"category": "widgets",
"event_type": {"$in": self.events.keys()}
}).distinct("event_type")
aggr_events = db.aggregated_events.find(
{
"init_by": options["wid"],
"time_added": {
"$gte": options["start"],
"$lte": options["end"],
},
'site': DBRef("sites", site),
"category": "widgets",
"event_type": {"$in": self.events.keys()}
}).distinct("event_type")
return list(set(lead_events) | set(aggr_events))
def get_data(self, options):
relevant_events = self.get_relevant_events(options)
data = self.build_query_and_get_data(relevant_events, options)
widget_type = self.get_widget_type(options['wid'])
if widget_type in widgets_with_conversion:
relevant_events.append(self.events['conversion']['name'])
graph_data = self.build_graph_data(data, conversion=True)
total_values_per_event = self.get_total_per_event(graph_data, conversion=True)
else:
graph_data = self.build_graph_data(data)
total_values_per_event = self.get_total_per_event(graph_data)
graphs_and_axes = self.generate_graphs_and_axes(relevant_events)
self.chart_settings["graphs"] = graphs_and_axes['graphs']
if options['single_axis'] == 'false':
self.chart_settings["valueAxes"] = graphs_and_axes["axes"]
else:
self.chart_settings['valueAxes'] = [self.axis_settins]
if options['aggregate_period'] == 'hour':
self.chart_settings["categoryAxis"]["minPeriod"] = 'mm'
if options['aggregate_period'] == 'day':
self.chart_settings["categoryAxis"]["minPeriod"] = 'DD'
if options['aggregate_period'] == 'month':
self.chart_settings["categoryAxis"]["minPeriod"] = 'MM'
return {
"status": "ok",
"graph": graph_data,
'options': self.chart_settings,
'total_values_per_event': total_values_per_event,
'start': options['start'].date().strftime('%d-%m-%Y'),
'end': options['end'].date().strftime('%d-%m-%Y'),
'disabled_graphs': self.disabled_graphs,
}
def build_graph_data(self, data, **options):
graph_data = []
if options.get('conversion'):
for period in data:
temp = {}
temp['date'] = period
for event in data[period]:
if event['event_type'] not in temp:
temp[event['event_type']] = event['count']
else:
temp[event['event_type']] += event['count']
temp["conversion"] = round(temp.get('fill', 0) * 100 / temp.get("popup_view", 1), 2)
graph_data.append(temp)
else:
for period in data:
temp = {}
temp['date'] = period
for event in data[period]:
if event['event_type'] not in temp:
temp[event['event_type']] = event['count']
else:
temp[event['event_type']] += event['count']
graph_data.append(temp)
graph_data = sorted(graph_data, key=lambda x: x["date"])
return graph_data
def get_widget_type(self, wid):
site = ObjectId(self.request.site_id)
widgets_confs = WidgetsConf.objects.get(site=site)
json_conf = json.loads(widgets_confs.config)['widgets']
widget_type = json_conf[wid]['type']
return widget_type
def get_total_per_event(self, graph_data, **options):
if not graph_data:
return {}
total_values_per_event = {}
for date in graph_data:
for event in date:
if event == 'date':
continue
event_name = self.events.get(event)['verbose_name']
if event_name not in total_values_per_event:
total_values_per_event[event_name] = date[event]
else:
total_values_per_event[event_name] += date[event]
if options.get('conversion'):
conversion_name = self.events['conversion']['verbose_name']
fill = total_values_per_event.get(self.events.get('fill')['verbose_name'], 0)
popup_view = total_values_per_event[self.events.get('popup_view')['verbose_name']]
total_values_per_event[conversion_name] = round(fill / popup_view * 100, 2)
return total_values_per_event
return total_values_per_event
def build_query_and_get_data(self, relevant_events, options):
site = ObjectId(self.request.site_id)
aggr_period = options['aggregate_period']
group_by_periods = {
'hour': {
'all_events': {
'year': {'$substr': ['$time_added', 0, 4]},
'month': {'$substr': ['$time_added', 5, 2]},
'day': {'$substr': ['$time_added', 8, 2]},
'hour': {'$substr': ['$time_added', 11, 2]},
'event_type': '$event_type'
},
'unique_events': {
'year': {'$substr': ['$time_added', 0, 4]},
'month': {'$substr': ['$time_added', 5, 2]},
'day': {'$substr': ['$time_added', 8, 2]},
'hour': {'$substr': ['$time_added', 11, 2]},
'event_type': '$_id.event_type'
},
}
}
concat_by_periods = {
'hour': {
'$concat': ['$_id.year', '-', '$_id.month', '-', '$_id.day', ' ', '$_id.hour', ':00']
},
'day': {
'$concat': ['$_id.year', '-', '$_id.month', '-', '$_id.day']
},
'month': {
'$concat': ['$_id.year', '-', '$_id.month']
}
}
day_grouping = copy.deepcopy(group_by_periods['hour'])
# here we just remove grouping by hour
del day_grouping['all_events']['hour']
del day_grouping['unique_events']['hour']
group_by_periods['day'] = day_grouping
month_grouping = copy.deepcopy(group_by_periods['day'])
# here we just remove grouping by day
del month_grouping['all_events']['day']
del month_grouping['unique_events']['day']
group_by_periods['month'] = day_grouping
if options['group_by_visits'] == 'false':
match_stage = {
"$match": {
"init_by": options["wid"],
'site': DBRef("sites", site),
"time_added": {
"$gte": options["start"],
"$lte": options["end"],
},
"category": "widgets",
"event_type": {"$in": relevant_events}
}
}
project_stage = {
'$project': {
'event_type': 1,
'time_added': 1,
'count': 1
}
}
group_stage = {
'$group': {
'_id': group_by_periods[aggr_period]['all_events'],
'count': {'$sum': 1}
}
}
group_stage_aggregated = {
'$group': {
'_id': group_by_periods[aggr_period]['all_events'],
'count': {'$sum': '$count'}
}
}
second_group_stage = {
'$group': {
'_id': concat_by_periods[aggr_period],
'events': {'$push': {'event_type': '$_id.event_type', 'count': '$count'}}
},
}
lead_events = db.lead_events.aggregate([match_stage, project_stage, group_stage, second_group_stage])
aggregated_events = db.aggregated_events.aggregate([match_stage, project_stage, group_stage_aggregated, second_group_stage])
data = {}
for item in lead_events:
data[item['_id']] = item['events']
for item in aggregated_events:
if item['_id'] not in data:
data[item['_id']] = item['events']
else:
data[item['_id']].extend(item['events'])
return data
else:
match_stage = {
"$match": {
'site': DBRef("sites", site),
"init_by": options["wid"],
"time_added": {
"$gte": options["start"],
"$lte": options["end"],
},
"category": "widgets",
"event_type": {"$in": relevant_events},
"visit": {"$exists": True}
}
}
sort_stage = {
"$sort": {
"time_added": 1
}
}
first_group_stage = {
"$group": {
"_id": {"visit": "$visit", "event_type": "$event_type"},
"time_added": {"$first": "$time_added"},
}
}
second_group_stage = {
'$group': {
'_id': group_by_periods[aggr_period]['unique_events'],
'count': {'$sum': 1}
}
}
third_group_stage = {
'$group': {
'_id': concat_by_periods[aggr_period],
'events': {'$push': {'event_type': '$_id.event_type', 'count': '$count'}}
}
}
lead_events = db.lead_events.aggregate([match_stage, sort_stage, first_group_stage,
second_group_stage, third_group_stage])
data = {}
for item in lead_events:
data[item['_id']] = item['events']
return data
class LeadsChart(Chart):
events = {
'leads_added': {'name': 'leads_added', 'verbose_name': ugettext(u'Появилось клиентов'), 'color': '#168de2'},
}
def validate_input(self, options):
if options['period'] != 'custom':
self.period = Period.from_def_ranges(options['period'])
start = self.period.start
end = self.period.end
else:
form = StatForm(options)
if not form.is_valid():
return {'status': 'error', 'errors': humanize_form_errors(form)}
form_data = form.cleaned_data
if not form_data['period_start']:
form.errors['period_start'] = [_(u"Обязательное поле")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if not form_data['period_end']:
form.errors['period_end'] = [_(u"Обязательное поле")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
start = form_data['period_start']
end = form_data['period_end'].replace(hour=23, minute=59, second=59)
if start.date() > datetime.datetime.now().date():
form.errors['period_start'] = [_(u"Начало периода не может быть позже текущего дня.")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if end.date() > datetime.datetime.now().date():
form.errors['period_end'] = [_(u"Конец периода не может быть позже текущего дня.")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if start > end:
form.errors["period_start"] = [_(u'Начало периода не должно быть больше конца периода.')]
return {'status': 'error', 'errors': humanize_form_errors(form)}
self.period.start = start
self.period.end = end
return {
'status': 'ok',
'start': start,
'end': end,
'source': options['source']
}
def get_data(self, options, site=None):
data = self.build_query_and_get_data(options, site=site)
graphs_and_axes = self.generate_graphs_and_axes(['leads_added'])
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
total_leads_added = sum([item['leads_added'] for item in data])
return {
'status': 'ok',
'chart_settings': self.chart_settings,
'step': self.period.step,
'total_leads_added': total_leads_added
}
def build_query_and_get_data(self, options, site=None):
# ugly adhoc should have been reworked
site = site if site else self.request.site
data = []
start = options['start']
end = options['end']
if options['source'] == 'all':
dates = Lead.objects(time_added__gte=start,
time_added__lte=end,
site=self.request.site).order_by('time_added').values_list('time_added')
else:
source = TraffSource.objects.get(name=options['source'])
dates = Lead.objects(time_added__gte=start,
time_added__lte=end,
source__in=source.domains,
site=self.request.site).values_list('time_added')
if self.period.step == 'day':
dates = [time_added.date().strftime('%Y-%m-%d') for time_added in dates]
temp_dict = {}
for date in dates:
if date not in temp_dict:
temp_dict[date] = 1
else:
temp_dict[date] += 1
data = [{'date': k, 'leads_added': v} for k, v in temp_dict.iteritems()]
data = sorted(data, key=lambda item: item['date'])
else:
self.chart_settings['categoryAxis']['minPeriod'] = 'mm'
dates = [time_added.strftime("%Y-%m-%d %H:00") for time_added in dates]
temp_dict = {}
for date in dates:
if date not in temp_dict:
temp_dict[date] = 1
else:
temp_dict[date] += 1
data = [{'date': k, 'leads_added': v} for k, v in temp_dict.iteritems()]
data = sorted(data, key=lambda item: item['date'])
return data
class FunnelChart(object):
def __init__(self):
self.chart_settings = {
"type": "funnel",
"theme": "light",
"balloon": {
"fixedPosition": True
},
"valueField": "value", # Event value
"titleField": "title", # Event name
"marginRight": 240,
"marginLeft": 50,
"startX": -500,
"depth3D": 100,
"angle": 25,
"outlineAlpha": 1,
"outlineColor": "#FFFFFF",
"outlineThickness": 2,
"labelPosition": "right",
"balloonText": "[[title]]: [[value]] [[description]]",
"export": {
"enabled": True
},
"path": "/static/dist/amcharts",
"fontSize": 14,
"descriptionField": "description"
}
class EmailCampaignsChart(FunnelChart):
def validate_input(self, options):
ids = options.getlist('ids[]')
query = {}
if not ids:
return {'status': 'empty'}
query['ids'] = ids
if options['mailing_type'] == 'autocast':
query['mailing_type'] = 'autocast'
if options['period'] != 'custom':
self.period = Period.from_def_ranges(options['period'])
query['start'] = self.period.start
query['end'] = self.period.end
query['status'] = 'ok'
else:
# WidgetStatForm has only two fields (start, end) which is useful in this case
form = WidgetStatForm(options)
if not form.is_valid():
return {'status': 'error', 'errors': humanize_form_errors(form)}
form_data = form.cleaned_data
start = form_data['start']
end = form_data['end'].replace(hour=23, minute=59, second=59)
if start.date() > datetime.datetime.now().date():
form.errors['start'] = [_(u"Начало периода не может быть позже текущего дня.")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if end.date() > datetime.datetime.now().date():
form.errors['end'] = [_(u"Конец периода не может быть позже текущего дня.")]
return {'status': 'error', 'errors': humanize_form_errors(form)}
if start > end:
form.errors["start"] = [_(u'Начало периода не должно быть больше конца периода.')]
return {'status': 'error', 'errors': humanize_form_errors(form)}
query['start'] = start
query['end'] = end
query['status'] = 'ok'
if options['mailing_type'] == 'campaign':
query['mailing_type'] = 'campaign'
query['status'] = 'ok'
return query
def get_data(self, options):
if options['status'] == 'empty':
self.chart_settings['dataProvider'] = []
return {'chart_settings': self.chart_settings}
ids = options['ids']
if options['mailing_type'] == 'autocast':
start = options['start']
end = options['end']
autocasts = Autocast.objects(id__in=ids)
messages = [acast.message for acast in autocasts]
messages = []
for autocast in autocasts:
messages.append(DBRef('messages', autocast.message.id))
if autocast.cases:
messages.extend([DBRef('messages', case.message.id) for case in autocast.cases[1:]])
match_stage = {
"$match": {
"message": {"$in": messages},
"time_added": {
"$gte": start,
"$lte": end
}
}
}
emails = list(db.emails.aggregate([match_stage]))
total_sent = len(emails)
total_opened = len([email for email in emails if email['opened']])
total_clicked = len([email for email in emails if email['clicked']])
else:
messages = Message.objects(id__in=ids)
total_sent = Email.objects(message__in=messages).count()
total_opened = Message.objects(id__in=ids).sum('opens')
total_clicked = Message.objects(id__in=ids).sum('clicks')
if not total_sent:
dataProvider = []
else:
opens_desc = '({:.3g}%)'.format(total_opened / total_sent * 100)
clicks_desc = '({:.3g}%)'.format(total_clicked / total_sent * 100)
dataProvider = [{
'title': _(u"Всего писем отправлено"),
'value': total_sent,
}, {
'title': _(u"Всего писем открыто"),
'value': total_opened,
'description': opens_desc
}, {
'title': _(u"Всего переходов по письмам"),
'value': total_clicked,
'description': clicks_desc
}]
# These are slices colours in the descending order
colors = ["#525263", "#337ab7", "#00b359", "#bd3c3c"]
self.chart_settings["colors"] = colors
self.chart_settings['dataProvider'] = dataProvider
return {
'chart_settings': self.chart_settings
}
class RecommendationsChart(Chart):
def __init__(self):
super(RecommendationsChart, self).__init__()
self.events = {
'visits': {'name': 'visits', 'verbose_name':
ugettext(u'Кликнуло на виджет рекомендаций'), 'color': '#168de2'},
'orders': {'name': 'orders', 'verbose_name':
ugettext(u'Заказов после клика на виджет рекомендаций'), 'color': '#009ca6'},
'sum_orders': {'name': 'sum_orders', 'verbose_name':
ugettext(u'Сумма заказов после клика на виджет рекомендаций'), 'color': '#555555'},
}
def validate_input(self, options):
recommendations_analytics_startdate = settings.RECOMMENDATIONS_ANALYTICS_ACTIVE_DATE
if options.get('period') != 'custom':
options = replace_period_with_dates(options)
result = validate_time_period(options['period_start'], options['period_end'])
if result['status'] == 'error':
return result
else:
if result['start'] < recommendations_analytics_startdate:
result['start'] = recommendations_analytics_startdate
result['message'] = _(u'Начало периода для данной статистики может быть только с ') + \
recommendations_analytics_startdate.strftime('%d-%m-%Y')
if result['end'] < recommendations_analytics_startdate:
result['end'] = recommendations_analytics_startdate.replace(hour=23, minute=59, second=59)
return {
'status': result['status'],
'start': result['start'],
'end': result['end'],
'message': result.get('message'),
'widget_option': options['widget_option'],
'site_id': options['site_id']
}
def get_data(self, options):
self.period.start = options['start']
self.period.end = options['end']
data = self.build_query_and_get_data(options)
graphs_and_axes = self.generate_graphs_and_axes(['visits', 'orders', 'sum_orders'])
graphs_and_axes['graphs'][0]['type'] = 'column'
graphs_and_axes['graphs'][0]['fillAlphas'] = '0.7'
graphs_and_axes['graphs'][0]['hidden'] = True
graphs_and_axes['graphs'][1]['fillAlphas'] = '0.7'
graphs_and_axes['graphs'][1]['type'] = 'column'
graphs_and_axes['axes'][2]['position'] = 'right'
graphs_and_axes['graphs'][2]['balloon'] = {'drop': False}
self.chart_settings['valueAxes'] = [graphs_and_axes['axes'][0], graphs_and_axes['axes'][2]]
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend']['fontSize'] = 13
if options['start'].day != options['end'].day:
del self.chart_settings['categoryAxis']['minPeriod']
unique_clicked_visits = sum([item['visits'] for item in data])
triggered_orders = sum([item['orders'] for item in data])
sum_triggered_orders = sum([item['sum_orders'] for item in data])
conversion_rate = (triggered_orders / unique_clicked_visits * 100) if unique_clicked_visits else 0
return {
'status': 'ok',
'chart_settings': self.chart_settings,
'step': self.period.step,
'start': self.period.start.strftime('%d-%m-%Y'),
'end': self.period.end.strftime('%d-%m-%Y'),
'message': options['message'],
'unique_clicked_visits': unique_clicked_visits,
'triggered_orders': triggered_orders,
'sum_triggered_orders': round(sum_triggered_orders, 2),
'conversion_rate': round(conversion_rate, 2),
}
def build_query_and_get_data(self, options):
data = []
if options['widget_option'] != 'all':
recommend_widgets_ids = [options['widget_option']]
else:
recommend_widgets_ids = get_recommendations_widgets(options['site_id']).keys()
pipeline = [
{
'$match': {
'time_added': {'$gte': options['start'], '$lte': options['end']},
'event_type': 'click', 'init_by': {'$in': recommend_widgets_ids},
'visit': {'$exists': 'true'}
}
},
{
'$group': {
'_id': '$visit',
'earliest_click_time': {'$min': '$time_added'}
}
},
]
req_clicks = list(LeadEvent.objects.aggregate(*pipeline))
req_visits = {}
for visit in req_clicks:
req_visits[visit['_id']] = {'click_time': visit['earliest_click_time']}
req_orders = LeadOrder.objects(lead_visit__in=req_visits.keys())
for order in req_orders:
ref_visit = DBRef('visits', ObjectId(order.lead_visit.id))
if order.time_added > req_visits[ref_visit]['click_time']:
req_visits[ref_visit]['completed_order'] = req_visits[ref_visit].get('completed_order', 0) + 1
if order['cart_sum']:
req_visits[ref_visit]['sum_orders'] = req_visits[ref_visit].get('sum_orders', 0) + order['cart_sum']
agg_func_param = '%Y-%m-%d'
if self.period.step == 'hour':
agg_func_param = '%Y-%m-%d %H:00'
req_visits = sorted(req_visits.values(), key=lambda y: y['click_time'])
for dt, grp in itertools.groupby(req_visits, key=lambda x: x['click_time'].strftime(agg_func_param)):
temp = {'date': dt, 'visits': 0, 'orders': 0, 'sum_orders': 0}
for el in grp:
temp['visits'] += 1
temp['orders'] += el.get('completed_order', 0)
temp['sum_orders'] += float(el.get('sum_orders', 0))
data.append(temp)
return data
class EmailDynamicsChart(Chart):
def __init__(self):
super(EmailDynamicsChart, self).__init__()
self.events = {
'new_multileads': {'name': 'new_multileads', 'verbose_name': ugettext(u'Количество новых клиентов'),
'color': '#009ca6'},
'unsubscribed': {'name': 'unsubscribed', 'verbose_name':
ugettext(u'Количество клиентов, отписавшихся от всех рассылок'), 'color': '#555555'},
'coef': {'name': 'coef', 'verbose_name':
ugettext(u'Количество отписавшихся клиентов / количество новых'), 'color': '#bd3c3c'},
}
def validate_input(self, options):
if options.get('period') != 'custom':
options = replace_period_with_dates(options)
result = validate_time_period(options['period_start'], options['period_end'])
return result
def get_data(self, options):
self.period.start = options['start']
self.period.end = options['end']
data, total_new, total_unsubscribed = self.build_query_and_get_data(options)
graphs_and_axes = self.generate_graphs_and_axes(['new_multileads', 'unsubscribed', 'coef'])
graphs_and_axes['graphs'][0]['type'] = 'column'
graphs_and_axes['graphs'][0]['fillAlphas'] = '0.7'
graphs_and_axes['graphs'][1]['fillAlphas'] = '0.7'
graphs_and_axes['graphs'][1]['type'] = 'column'
graphs_and_axes['axes'][2]['position'] = 'right'
self.chart_settings['valueAxes'] = [graphs_and_axes['axes'][0], graphs_and_axes['axes'][2]]
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend']['fontSize'] = 13
if options['start'].day != options['end'].day:
del self.chart_settings['categoryAxis']['minPeriod']
else:
self.chart_settings['categoryAxis']['minPeriod'] = 'hh'
return {
'status': 'ok',
'chart_settings': self.chart_settings,
'step': self.period.step,
'start': self.period.start.strftime('%d-%m-%Y'),
'end': self.period.end.strftime('%d-%m-%Y'),
'message': options.get('message'),
'new_multileads': total_new,
'unsubscribed': total_unsubscribed,
'coef': round(float(total_unsubscribed) / total_new, 3) if total_new else None,
}
def build_query_and_get_data(self, options):
data = []
unsubscribed_quantity_by_date = {}
multileads_quantity_by_date = {}
total_unsubscribed = 0
total_new = 0
agg_func_param = '%Y-%m-%d'
if self.period.step == 'hour':
agg_func_param = '%Y-%m-%d %H:00'
pipeline = [{'$project': {'date': {'$dateToString': {'format': agg_func_param, 'date': '$time_added' } } } },
{'$group': {'_id': '$date', 'quantity': {'$sum': 1}}},
{'$sort': {'_id': 1}},
{'$project': {'date': '$_id', 'quantity': 1, '_id': 0}}]
unsubscribed = list(UnsubscribedEmail.objects(site=str(options['site_id']), time_added__gte=options['start'],
time_added__lte=options['end'], status='all').aggregate(*pipeline))
new_multileads = list(Multilead.objects(site=options['site_id'], time_added__gte=options['start'],
time_added__lte=options['end']).aggregate(*pipeline))
for x in unsubscribed:
unsubscribed_quantity_by_date[x['date']] = x['quantity']
for y in new_multileads:
multileads_quantity_by_date[y['date']] = y['quantity']
for dt in sorted(list(set(multileads_quantity_by_date.keys() + unsubscribed_quantity_by_date.keys()))):
count_unsubscribed = unsubscribed_quantity_by_date.get(dt, 0)
count_new = multileads_quantity_by_date.get(dt, 0)
total_new += count_new
total_unsubscribed += count_unsubscribed
coef = round(float(count_unsubscribed) / count_new, 3) if count_new else None
data.append({'date': dt, 'unsubscribed': count_unsubscribed, 'new_multileads': count_new, 'coef': coef})
return data, total_new, total_unsubscribed
class VisitsChart(Chart):
def __init__(self):
super(VisitsChart, self).__init__()
self.events = {
'visits': {'name': 'visits', 'verbose_name': ugettext(u'Визиты'), 'color': '#258cbb'},
}
def validate_input(self, post_data):
p = Period()
options = {'site': post_data['site_id']}
options['aggr_condition'] = post_data['aggr_condition']
if post_data.get('initial'):
options.update({
'period_start': p.start,
'period_end': p.end,
'source': 'all',
'step': 'day'
})
return options
form = StatForm(post_data)
if not form.is_valid():
return {'error': humanize_form_errors(form)}
form_data = form.cleaned_data
options['source'] = form_data['source']
period = form_data['period']
if period != 'custom':
p = Period.from_def_ranges(period)
else:
if not form_data['period_start']:
form.errors['period_start'] = [ugettext(u'Введите дату.')]
return {'error': humanize_form_errors(form), 'status': 'error'}
if not form_data['period_end']:
form.errors['period_end'] = [ugettext(u'Введите дату.')]
return {'error': humanize_form_errors(form), 'status': 'error'}
if form_data['period_start'].date() > datetime.now().date():
form.errors['period_start'] = [ugettext(u"Начало периода не может быть позже текущего дня.")]
return {'error': humanize_form_errors(form), 'status': 'error'}
if form_data['period_end'].date() > datetime.now().date():
form.errors['period_end'] = [ugettext(u"Конец периода не может быть позже текущего дня.")]
return {'error': humanize_form_errors(form), 'status': 'error'}
if form_data['period_start'] > form_data['period_end']:
form.errors['period_start'] = [ugettext(u'Начало периода не должно быть больше конца периода.')]
return {'error': humanize_form_errors(form), 'status': 'error'}
p.set_start_and_end(form_data['period_start'], form_data['period_end'])
options.update({'period_end': p.end,
'period_start': p.start,
'step': p.step,
'status': 'ok'
})
return options
def get_visits_data(self, options):
match_stage = {
'$match': {
'site': DBRef('sites', ObjectId(options['site'])),
'start': {'$gte': options['period_start']},
'end': {'$lte': options['period_end']},
}
}
group_stage = {
'$group': {
'_id': {'$dateToString': {'format': '%Y-%m-%d %H:00', 'date': '$start'}},
'total': {'$sum': 1}
}
}
unique_leads_group_stage = {
'$group': {
'_id': '$lead',
'start': {'$first': '$start'}
}
}
if options['source'] == 'rest':
all_regexes = [{'referrer': {'$regex': regex}} for src in TraffSource.objects() for regex in src.regexp_list if regex]
match_stage['$match']['$nor'] = all_regexes
if options['source'] != 'all' and options['source'] != 'rest':
traff_source = TraffSource.objects(name=options['source']).first()
if traff_source.kind == 'main':
regex_query = self.get_regex_query(traff_source)
if regex_query:
match_stage['$match']['$or'] = regex_query
else:
regexp_list = [regex.decode('string_escape') for regex in traff_source.regexp_list]
regex_query = [{'referrer': {'$regex': regex}} for regex in regexp_list]
match_stage['$match']['$or'] = regex_query
if options['aggr_condition'] == 'visits':
visits = list(db.visits.aggregate([match_stage, group_stage]))
if options['aggr_condition'] == 'leads':
visits = list(db.visits.aggregate([match_stage, unique_leads_group_stage, group_stage]))
visits = [{'date': visit['_id'], 'visits': visit['total']} for visit in visits]
visits = sorted(visits, key=lambda x: x['date'])
total = sum([i['visits'] for i in visits])
return {
'data': {
'graph': visits,
'total_per_period': total
}
}
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_visits_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data['data']['graph']
self.chart_settings['marginLeft'] = 20
self.chart_settings['marginRight'] = 20
self.chart_settings['legend'] = None
return {'chart_settings': self.chart_settings, 'total_visits': data['data']['total_per_period']}
def get_regex_query(self, traff_source):
sources_ids = [ObjectId(_id) for _id in traff_source.sources_list]
sources = TraffSource.objects(id__in=sources_ids)
regexp_list = []
for source in sources:
for regex in source.regexp_list:
regexp_list.append(regex.decode('string_escape'))
regex_query = []
for regex in regexp_list:
regex_query.append({'referrer': {'$regex': regex}})
return regex_query
class SalesFunnelChart(FunnelChart):
def __init__(self, site_id=None):
super(SalesFunnelChart, self).__init__()
self.store_managers = list(Lead.objects(site=site_id, status='manager').values_list('id'))
def validate_input(self, options):
options = copy.deepcopy(options)
result = validate_date_range(options)
options.update(result)
return options
def get_conversion(self, x, y):
if not y:
return ': 0'
return ': {}%'.format(round(x / y * 100, 2))
def get_data(self, options):
site_id = ObjectId(options['site_id'])
site_ref = DBRef('sites', site_id)
start = options['start']
end = options['end']
visited_pages_query = {
'site': site_ref,
'date': {
'$gte': start,
'$lte': end
},
}
norm_visits = list(db.visits.find({
'site': site_ref,
'start': {'$gte': start},
'end': {'$lte': end}
}))
norm_visits_leads = set([visit['lead'] for visit in norm_visits])
incognito_visits = list(db.incognito_pageviews.find(visited_pages_query))
lead_visits = list(db.lead_visited_pages.find(visited_pages_query))
unique_incognito = set((visit['lead'] for visit in incognito_visits))
unique_leads = set((visit['lead'] for visit in lead_visits))
all_visitors = list(unique_incognito)
all_visitors.extend(unique_leads)
try:
yml_file = YMLFile.objects.get(site=site_id)
offers_hashes = set([offer.url_hash for offer in YMLOffer.objects(site=site_id)])
except YMLFile.DoesNotExist:
yml_file = YMLFile()
offers_hashes = []
leads_visited_offers = set()
for visit in incognito_visits:
url_hash = hashlib.md5(get_minimal_url(visit['page'], yml_file.significant_params, regex=yml_file.offer_regex)).hexdigest()[:12]
if url_hash in offers_hashes:
leads_visited_offers.add(visit['lead'])
for visit in lead_visits:
url_hash = hashlib.md5(get_minimal_url(visit['page'], yml_file.significant_params, regex=yml_file.offer_regex)).hexdigest()[:12]
if url_hash in offers_hashes:
leads_visited_offers.add(visit['lead'])
cart_items = db.cart_items.find({
'site': site_ref,
'lead': {'$in': all_visitors},
'time_added': {
'$gte': start,
'$lte': end
}
})
unique_leads_added_to_cart = set((cart_item['lead'] for cart_item in cart_items))
orders = db.lead_orders.find({
'site': site_ref,
'lead.$id': {'$nin': self.store_managers},
# 'lead': {'$in': all_visitors},
'time_added': {
'$gte': start,
'$lte': end
}
})
unique_leads_made_orders = set((order['lead'] for order in orders))
total_visits = len(norm_visits_leads)
total_offer_views = len(leads_visited_offers)
total_additions_to_cart = len(unique_leads_added_to_cart)
total_orders_made = len(unique_leads_made_orders)
conversion_msg = ugettext(u'Конверсия')
abs_conversion_msg = ugettext(u'Абсолютная конверсия')
self.chart_settings['dataProvider'] = [
{
'title': ugettext(u'Посетило сайт'),
'real_value': total_visits,
'value': 10
},
{
'title': ugettext(u'Страницы товаров посмотрело'),
'real_value': total_offer_views,
'value': 9,
'description': conversion_msg + self.get_conversion(total_offer_views, total_visits)
},
{
'title': ugettext(u'Добавило в корзину'),
'real_value': total_additions_to_cart,
'value': 8,
'description': conversion_msg + self.get_conversion(total_additions_to_cart, total_offer_views)
}, {
'title': ugettext(u'Сделало заказ'),
'real_value': total_orders_made,
'value': 7,
'description': conversion_msg + self.get_conversion(total_orders_made, total_additions_to_cart) \
+ '\n' + abs_conversion_msg + self.get_conversion(total_orders_made, total_visits)
}
]
self.chart_settings['balloonText'] = '[[title]]: [[real_value]]\n[[description]]'
self.chart_settings['labelText'] = '[[title]]: [[real_value]]'
self.chart_settings['colors'] = ['#ff4b00', '#15bbff', '#ffd800', '#49dc3a']
self.chart_settings['neckWidth'] = 30
del self.chart_settings['depth3D']
del self.chart_settings['angle']
carts_abandoned = total_additions_to_cart - total_orders_made
offers_views_lost = total_offer_views - total_additions_to_cart
no_offers_viewed = total_visits - total_offer_views
if not total_visits:
self.chart_settings['dataProvider'] = []
carts_abandoned = 0
offers_views_lost = 0
no_offers_viewed = 0
return {
'chart_settings': self.chart_settings,
'carts_abandoned': carts_abandoned,
'offers_views_lost': offers_views_lost,
'no_offers_viewed': no_offers_viewed
}
class SalesBarChart(Chart):
def __init__(self, site_id=None):
super(SalesBarChart, self).__init__()
self.store_managers = list(Lead.objects(site=site_id, status='manager').values_list('id'))
def validate_input(self, options):
options = copy.deepcopy(options)
options['status'] = 'ok'
return options
def get_rec_widgets_based_orders(self, options):
period = Period.from_def_ranges(options['period'])
rec_widgets_ids = get_recommendations_widgets(options['site_id']).keys()
pipeline = [
{
'$match': {
'time_added': {'$gte': period.start, '$lte': period.end},
'event_type': 'click',
'init_by': {'$in': rec_widgets_ids},
'visit': {'$exists': 'true'},
'lead.$id': {'$nin': self.store_managers}
}
},
{
'$group': {
'_id': '$visit',
'earliest_click_time': {'$min': '$time_added'}
}
},
]
events = {visit['_id']: visit['earliest_click_time'] for visit in db.lead_events.aggregate(pipeline)}
orders = LeadOrder.objects(lead_visit__in=events.keys())
result = []
for order in orders:
ref_visit = DBRef('visits', ObjectId(order.lead_visit.id))
if order.time_added > events[ref_visit]:
result.append(order.id)
return result
def get_data(self, options):
rec_orders = self.get_rec_widgets_based_orders(options)
period = Period.from_def_ranges(options['period'])
query = Q(site=options['site_id'], time_added__gte=period.start, time_added__lte=period.end, lead__nin=self.store_managers)
query &= (Q(mass_email__exists=True) | Q(trigger_email__exists=True))
email_orders = LeadOrder.objects(query).values_list('id')
leadhit_based_orders = set(rec_orders)
leadhit_based_orders.update(set(email_orders))
all_orders = LeadOrder.objects(site=options['site_id'], time_added__gte=period.start, time_added__lte=period.end, lead__nin=self.store_managers)
all_orders = {order.id: {'time_added': order.time_added, 'cart_sum': order.cart_sum} for order in all_orders}
store_made_orders_ids = set(all_orders.keys())
store_made_orders_ids.difference_update(leadhit_based_orders)
orders_dict = {}
agg_func_param = '%Y-%m-%d'
if options['period'] == 'day':
agg_func_param = '%Y-%m-%d %H:00'
for order in all_orders:
date = all_orders[order]['time_added'].strftime(agg_func_param)
cart_sum = float(all_orders[order]['cart_sum'] or 0)
if date not in orders_dict:
orders_dict[date] = {}
if order in store_made_orders_ids:
orders_dict[date]['store'] = cart_sum
else:
orders_dict[date]['leadhit'] = cart_sum
else:
if order in store_made_orders_ids:
if 'store' not in orders_dict[date]:
orders_dict[date]['store'] = cart_sum
else:
orders_dict[date]['store'] += cart_sum
else:
if 'leadhit' not in orders_dict[date]:
orders_dict[date]['leadhit'] = cart_sum
else:
orders_dict[date]['leadhit'] += cart_sum
dataProvider = []
for date in orders_dict:
tmp_obj = {
'date': date,
}
if 'store' in orders_dict[date]:
tmp_obj['store'] = orders_dict[date]['store']
if 'store' in orders_dict[date] and 'leadhit' in orders_dict[date]:
tmp_obj['leadhit'] = orders_dict[date]['store'] + orders_dict[date]['leadhit']
tmp_obj['raw_leadhit'] = orders_dict[date]['leadhit']
if 'store' not in orders_dict[date] and 'leadhit' in orders_dict[date]:
tmp_obj['leadhit'] = orders_dict[date]['leadhit']
tmp_obj['raw_leadhit'] = orders_dict[date]['leadhit']
dataProvider.append(tmp_obj)
dataProvider.sort(key=lambda x: x['date'])
self.chart_settings['dataProvider'] = dataProvider
self.chart_settings['valueAxes'] = [{'position': 'left'}]
if options['period'] != 'day':
del self.chart_settings['categoryAxis']['minPeriod']
else:
self.chart_settings['categoryAxis']['minPeriod'] = 'hh'
self.chart_settings['chartCursor']['cursorColor'] = '#6ba7ba'
income_msg = ugettext(u'Сумма заказов')
leadhit_income_msg = ugettext(u'Сумма заказов с')
self.chart_settings['graphs'] = [
{
'balloonText': income_msg + ': [[store]]',
'fillAlphas': 0.9,
'lineAlpha': 0.2,
'title': income_msg,
'type': 'column',
'valueField': 'store',
'fillColors': '#7c8387'
},
{
'balloonText': leadhit_income_msg + ' <b>LeadHit</b>: [[leadhit]]',
'fillAlphas': 0.95,
'lineAlpha': 0.2,
'title': leadhit_income_msg + ' LeadHit',
'type': 'column',
'clustered': False,
'columnWidth': 0.5,
'valueField': 'leadhit',
'fillColors': '#fbe916',
}
]
store_orders_count = len(store_made_orders_ids)
store_orders_sum = sum([item['store'] for item in dataProvider if item.get('store')])
leadhit_orders_count = len(leadhit_based_orders)
leadhit_orders_sum = sum([item['raw_leadhit'] for item in dataProvider if item.get('raw_leadhit')])
all_orders_count = len(all_orders)
all_orders_sum = leadhit_orders_sum + store_orders_sum
return {
'chart_settings': self.chart_settings,
'store_orders_count': store_orders_count,
'store_orders_sum': store_orders_sum,
'leadhit_orders_count': leadhit_orders_count,
'leadhit_orders_sum': leadhit_orders_sum,
'all_orders_count': all_orders_count,
'all_orders_sum': all_orders_sum,
}
class LeadsDiscoveryChart(Chart):
def __init__(self):
super(LeadsDiscoveryChart, self).__init__()
self.events = {
'store': {'name': 'store', 'verbose_name': ugettext(u'Лидов найдено'), 'color': 'wheat'},
'leadhit': {'name': 'leadhit', 'verbose_name': ugettext(u'Лидов найдено с'), 'color': 'yellow'}
}
def validate_input(self, options):
options = copy.deepcopy(options)
options['status'] = 'ok'
return options
def get_lh_forms(self, site):
LH_FORM_ACTIONS = ('lh_dp', 'lh_banner', 'lh_banner_mobile')
query = {
'site': site,
'$or': [
{'action': {'$in': LH_FORM_ACTIONS}},
{'subscription': True}
]
}
site_forms = db.forms.find(query)
site_forms = set([DBRef('forms', form['_id']) for form in site_forms])
return site_forms
def get_leads_ids_and_refs(self, site, period):
multi = list(db.multileads.find({
'site': site,
'time_added': {
'$gte': period.start,
'$lte': period.end
}
}, {'_id': 1}))
leads = list(db.leads.find({
'site': site,
'multilead': {'$in': [DBRef('multileads', m['_id']) for m in multi]},
'time_added': {
'$gte': period.start,
'$lte': period.end
}
}, {'_id': 1, 'multilead': 1}))
leads_ids = [lead['_id'] for lead in leads]
leads_refs = [DBRef('leads', lead) for lead in leads_ids]
leads_multileads_dict = {DBRef('leads', lead['_id']): lead['multilead'] for lead in leads}
return {
'leads_ids': leads_ids,
'leads_refs': leads_refs,
'leads_multileads_dict': leads_multileads_dict
}
def get_filled_forms(self, site, leads_refs):
match_stage = {
'$match': {
'site': site,
'lead': {'$in': leads_refs}
}
}
group_stage = {
'$group': {
'_id': '$lead',
'forms': {'$push': {'form_dbref': '$leadform', 'submitted_time': '$submitted_time'}}
}
}
unwind_stage = {
'$unwind': '$forms'
}
sort_stage = {
'$sort': {
'forms': 1
}
}
second_group_stage = {
'$group': {
'_id': '$_id',
'filled_forms': {'$push': '$forms'}
}
}
pipeline = [match_stage, group_stage, unwind_stage, sort_stage, second_group_stage]
# forms is a list of objects where '_id' is lead_id and 'filled_forms' is a sorted list of forms that given lead filled
forms = list(db.leads_filled_forms.aggregate(pipeline))
return forms
def get_data(self, options):
period = Period.from_def_ranges(options['period'])
site = DBRef('sites', ObjectId(options['site_id']))
options['site'] = site
agg_func_param = '%Y-%m-%d'
if period.step == 'hour':
self.chart_settings['categoryAxis']['minPeriod'] = 'hh'
agg_func_param = '%Y-%m-%d %H:00'
else:
del self.chart_settings['categoryAxis']['minPeriod']
relevant_site_forms = self.get_lh_forms(site)
leads = self.get_leads_ids_and_refs(site, period)
forms = self.get_filled_forms(site, leads['leads_refs'])
leads_multileads_dict = leads['leads_multileads_dict']
processed_multileads = set()
data = {}
for lead in forms:
multilead_dbref = leads_multileads_dict[lead['_id']]
first_form = lead['filled_forms'][0]
# no multilead case
if not multilead_dbref:
pass
if multilead_dbref in processed_multileads:
continue
processed_multileads.add(multilead_dbref)
form_submission_date = first_form['submitted_time'].strftime(agg_func_param)
leadhit = first_form['form_dbref'] in relevant_site_forms
if form_submission_date not in data:
data[form_submission_date] = {}
if not leadhit:
data[form_submission_date]['leadhit'] = 0
data[form_submission_date]['store'] = 1
else:
data[form_submission_date]['leadhit'] = 1
data[form_submission_date]['store'] = 0
else:
if not leadhit:
data[form_submission_date]['store'] += 1
else:
data[form_submission_date]['leadhit'] += 1
processed_data = []
for date in data:
store = data[date].get('store', 0)
leadhit = data[date].get('leadhit', 0)
obj = {'date': date}
if store:
obj['store'] = store
if store and leadhit:
obj['leadhit'] = leadhit + store
obj['raw_leadhit'] = leadhit
if not store and leadhit:
obj['raw_leadhit'] = leadhit
obj['leadhit'] = leadhit
processed_data.append(obj)
processed_data.sort(key=lambda x: x['date'])
self.chart_settings['dataProvider'] = processed_data
self.chart_settings['valueAxes'] = [{'position': 'left'}]
self.chart_settings['chartCursor']['cursorColor'] = '#6ba7ba'
income_msg = ugettext(u'Лидов найдено')
leadhit_income_msg = ugettext(u'Лидов найдено с')
self.chart_settings['graphs'] = [
{
'balloonText': income_msg + ': [[store]]',
'fillAlphas': 0.9,
'lineAlpha': 0.2,
'title': income_msg,
'type': 'column',
'valueField': 'store',
'fillColors': '#7c8387'
},
{
'balloonText': leadhit_income_msg + ' <b>LeadHit</b>: [[leadhit]]',
'fillAlphas': 0.95,
'lineAlpha': 0.2,
'title': leadhit_income_msg + ' LeadHit',
'type': 'column',
'clustered': False,
'columnWidth': 0.5,
'valueField': 'leadhit',
'fillColors': '#fb8c9d',
}
]
store_leads = sum([date['store'] for date in processed_data if date.get('store')])
leadhit_leads = sum([date['raw_leadhit'] for date in processed_data if date.get('raw_leadhit')])
if not (leadhit_leads + store_leads):
percentage = ' 0%'
else:
percentage = ' {}%'.format((round(leadhit_leads / store_leads * 100, 2)))
return {
'chart_settings': self.chart_settings,
'store_leads': store_leads,
'leadhit_leads': leadhit_leads,
'leads_diff': percentage
}
def validate_date_range(options):
result = {
'status': 'ok'
}
if options['period'] != 'custom':
period = Period.from_def_ranges(options['period'])
result['start'] = period.start
result['end'] = period.end
else:
form = WidgetStatForm(options)
if not form.is_valid():
result['status'] = 'error'
result['errors'] = humanize_form_errors(form)
else:
form_data = form.cleaned_data
start = form_data['start']
end = form_data['end'].replace(hour=23, minute=59, second=59)
if start.date() > datetime.datetime.now().date():
form.errors['start'] = [_(u"Начало периода не может быть позже текущего дня.")]
result['status'] = 'error'
result['errors'] = humanize_form_errors(form)
if end.date() > datetime.datetime.now().date():
form.errors['end'] = [_(u"Конец периода не может быть позже текущего дня.")]
result['status'] = 'error'
result['errors'] = humanize_form_errors(form)
if start > end:
form.errors["start"] = [_(u'Начало периода не должно быть больше конца периода.')]
result['status'] = 'error'
result['errors'] = humanize_form_errors(form)
result['start'] = start
result['end'] = end
return result
class AverageRevenuePerVisitorChart(Chart):
def __init__(self):
super(AverageRevenuePerVisitorChart, self).__init__()
self.events = {
'arpv': {'name': 'arpv', 'verbose_name': 'ARPV', 'color': '#258cbb'},
}
def get_arpv_data(self, options):
data_by_weeks = get_sum_orders_by_week(
options['period_start'], options['period_end'], options['site_id']
)
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
match_stage_current_week = {
'$match': {
'site': DBRef('sites', options['site_id']),
'start': {
'$gte': datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
'$lte': datetime.datetime.combine(values['end'], datetime.datetime.max.time())
}
}
}
group_unique_leads_stage = {
'$group': {
'_id': '$lead',
'start': {'$first': '$start'}
}
}
visitors = len(
list(db.visits.aggregate([match_stage_current_week, group_unique_leads_stage]))
)
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'arpv': round(
float(values.get('revenue', 0)) / visitors, 2
) if visitors else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_arpv_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class AverageRevenuePerUserChart(Chart):
def __init__(self):
super(AverageRevenuePerUserChart, self).__init__()
self.events = {
'arpu': {'name': 'arpu', 'verbose_name': 'ARPU', 'color': '#258cbb'},
}
def get_arpu_data(self, options):
data_by_weeks = get_sum_orders_by_week(
options['period_start'], options['period_end'], options['site_id']
)
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
current_week_visitors = db.visits.find({
"start": {
'$gte': datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
'$lte': datetime.datetime.combine(values['end'], datetime.datetime.max.time())
},
"site": DBRef('sites', options['site_id'])
}).distinct('lead')
current_week_multileads = len(db.leads.find({
"_id": {'$in': [lead.id for lead in current_week_visitors]},
}).distinct('multilead'))
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'arpu': round(
float(values.get('revenue', 0)) / current_week_multileads, 2
) if current_week_multileads else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_arpu_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class AverageRevenuePerPayingUserChart(Chart):
def __init__(self):
super(AverageRevenuePerPayingUserChart, self).__init__()
self.events = {
'arppu': {'name': 'arppu', 'verbose_name': 'ARPPU', 'color': '#258cbb'},
}
def get_arppu_data(self, options):
period_start = options['period_start']
period_end = options['period_end']
date_list = [period_start.date() + datetime.timedelta(days=x) for x
in xrange((period_end - period_start).days + 1)]
data_by_weeks = {}
for id_grp, grp in itertools.groupby(date_list, key=lambda x: x.isocalendar()[:2]):
current_week = list(grp)
data_by_weeks[id_grp] = {'start': min(current_week), 'end': max(current_week)}
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
week_orders = LeadOrder.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time())
)
solvent_leads = week_orders.no_dereference().values_list('lead')
solvent_multileads = Lead.objects(
id__in=[x.id for x in solvent_leads]
).no_dereference().scalar('multilead', 'id')
solvent_multileads = {x[0] if x[0] else x[1] for x in solvent_multileads}
week_unique_customers = len(solvent_multileads)
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'arppu': round(
float(week_orders.sum('cart_sum')) / week_unique_customers, 2
) if week_unique_customers else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_arppu_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class CartAbandonmentRateChart(Chart):
def __init__(self):
super(CartAbandonmentRateChart, self).__init__()
self.events = {
'car': {'name': 'car', 'verbose_name': 'Cart abandonment rate', 'color': '#258cbb'},
}
def get_car_data(self, options):
period_start = options['period_start']
period_end = options['period_end']
date_list = [period_start.date() + datetime.timedelta(days=x) for x
in xrange((period_end - period_start).days + 1)]
data_by_weeks = {}
for id_grp, grp in itertools.groupby(date_list, key=lambda x: x.isocalendar()[:2]):
current_week = list(grp)
data_by_weeks[id_grp] = {'start': min(current_week), 'end': max(current_week)}
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
week_orders_number = LeadOrder.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time())
).count()
week_baskets_number = len(CartItem.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time()),
order_id__exists=True
).distinct('order_id'))
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'car': round(
float(week_baskets_number - week_orders_number) / week_baskets_number * 100, 2
) if week_orders_number else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_car_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class AverageCheckChart(Chart):
def __init__(self):
super(AverageCheckChart, self).__init__()
self.events = {
'average_check': {'name': 'average_check', 'verbose_name': 'Average check', 'color': '#258cbb'},
}
def get_graph_data(self, options):
period_start = options['period_start']
period_end = options['period_end']
date_list = [period_start.date() + datetime.timedelta(days=x) for x
in xrange((period_end - period_start).days + 1)]
data_by_weeks = {}
for id_grp, grp in itertools.groupby(date_list, key=lambda x: x.isocalendar()[:2]):
current_week = list(grp)
data_by_weeks[id_grp] = {'start': min(current_week), 'end': max(current_week)}
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
week_orders = LeadOrder.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time())
)
week_orders_number = week_orders.count()
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'average_check': round(
float(week_orders.sum('cart_sum')) / week_orders_number, 2
) if week_orders_number else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_graph_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class PurchaseFrequencyChart(Chart):
def __init__(self):
super(PurchaseFrequencyChart, self).__init__()
self.events = {
'purchase_frequency': {'name': 'purchase_frequency', 'verbose_name': 'Purchase frequency', 'color': '#258cbb'},
}
def get_graph_data(self, options):
period_start = options['period_start']
period_end = options['period_end']
date_list = [period_start.date() + datetime.timedelta(days=x) for x
in xrange((period_end - period_start).days + 1)]
data_by_weeks = {}
for id_grp, grp in itertools.groupby(date_list, key=lambda x: x.isocalendar()[:2]):
current_week = list(grp)
data_by_weeks[id_grp] = {'start': min(current_week), 'end': max(current_week)}
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
week_orders = LeadOrder.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time())
)
solvent_leads = week_orders.no_dereference().values_list('lead')
solvent_multileads = Lead.objects(
id__in=[x.id for x in solvent_leads]
).no_dereference().scalar('multilead', 'id')
solvent_multileads = {x[0] if x[0] else x[1] for x in solvent_multileads}
week_unique_customers = len(solvent_multileads)
week_orders_number = week_orders.count()
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'purchase_frequency': round(
float(week_orders_number) / week_unique_customers, 2
) if week_unique_customers else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_graph_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class PaidOrdersRateChart(Chart):
def __init__(self):
super(PaidOrdersRateChart, self).__init__()
self.events = {
'paid_orders_rate': {'name': 'paid_orders_rate', 'verbose_name': 'Paid orders rate', 'color': '#258cbb'},
}
def get_graph_data(self, options):
period_start = options['period_start']
period_end = options['period_end']
date_list = [period_start.date() + datetime.timedelta(days=x) for x
in xrange((period_end - period_start).days + 1)]
data_by_weeks = {}
for id_grp, grp in itertools.groupby(date_list, key=lambda x: x.isocalendar()[:2]):
current_week = list(grp)
data_by_weeks[id_grp] = {'start': min(current_week), 'end': max(current_week)}
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
week_orders = LeadOrder.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time())
)
week_orders_number = week_orders.count()
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'paid_orders_rate': round(
float(week_orders(status='paid').count()) / week_orders_number * 100, 2
) if week_orders_number else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_graph_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
class RepeatCustomerRateChart(Chart):
def __init__(self):
super(RepeatCustomerRateChart, self).__init__()
self.events = {
'rcr': {'name': 'rcr', 'verbose_name': 'Repeat customer rate', 'color': '#258cbb'},
}
def get_rcr_data(self, options):
period_start = options['period_start']
period_end = options['period_end']
date_list = [period_start.date() + datetime.timedelta(days=x) for x
in xrange((period_end - period_start).days + 1)]
data_by_weeks = {}
for id_grp, grp in itertools.groupby(date_list, key=lambda x: x.isocalendar()[:2]):
current_week = list(grp)
data_by_weeks[id_grp] = {'start': min(current_week), 'end': max(current_week)}
data = []
for isoweek, values in sorted(data_by_weeks.items(), key=lambda x: (x[0], x[1])):
solvent_leads = LeadOrder.objects(
site=DBRef('sites', options['site_id']),
time_added__gte=datetime.datetime.combine(values['start'], datetime.datetime.min.time()),
time_added__lte=datetime.datetime.combine(values['end'], datetime.datetime.max.time())
).no_dereference().values_list('lead')
solvent_multileads = Lead.objects(
id__in=[x.id for x in solvent_leads]
).no_dereference().values_list('multilead', 'id')
solvent_multileads = {x[1]: x[0] if x[0] else x[1] for x in solvent_multileads}
solvent_multileads_counter = {}
for lead in solvent_leads:
multilead = solvent_multileads[lead.id]
solvent_multileads_counter[multilead] = solvent_multileads_counter.get(multilead, 0) + 1
total_solvent_multileads = len(solvent_multileads_counter)
total_repeat_multileads = len(
[value for value in solvent_multileads_counter.values() if value > 1]
)
data.append({
'date': values['start'].strftime('%d.%m') + '-' + values['end'].strftime('%d.%m'),
'rcr': round(
float(total_repeat_multileads) / total_solvent_multileads * 100, 2
) if total_solvent_multileads else 0
})
return data
def get_data(self, options):
graphs_and_axes = self.generate_graphs_and_axes(self.events.keys())
data = self.get_rcr_data(options)
self.chart_settings['valueAxes'] = graphs_and_axes['axes']
self.chart_settings['graphs'] = graphs_and_axes['graphs']
self.chart_settings['dataProvider'] = data
self.chart_settings['legend'] = None
self.chart_settings['categoryAxis']['parseDates'] = False
return {'chart_settings': self.chart_settings}
def replace_period_with_dates(options):
if options.get('period'):
options = copy.deepcopy(options)
period = Period.from_def_ranges(options['period'])
options['period_start'] = period.start.strftime('%d-%m-%Y')
options['period_end'] = period.end.strftime('%d-%m-%Y')
return options<file_sep>/views.py
# coding: utf-8
import json
from copy import deepcopy
from datetime import datetime, timedelta
from django.conf import settings
from django.http import JsonResponse
from django.urls import reverse
from django.views.generic import View, TemplateView
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext, get_language
from bson import DBRef
from bson.objectid import ObjectId
from automailer.models import Autocast
from accounts.models import WidgetsConf
from emails.models import Message
from lib.core.acl import role_required, permission_required
from lib.mongoengine_utils import Pagination
from forms import StatForm
from models import TraffSource
from utils.helpers import (
Period as P,
process_autocasts_query_timeframe,
humanize_form_errors,
validate_time_period,
get_messages_and_msg_to_autocast_dict
)
from .chart import (
WidgetsChart,
LeadsChart,
EmailCampaignsChart,
RecommendationsChart,
EmailDynamicsChart,
VisitsChart,
SalesFunnelChart,
SalesBarChart,
LeadsDiscoveryChart,
AverageRevenuePerVisitorChart,
AverageRevenuePerUserChart,
AverageRevenuePerPayingUserChart,
CartAbandonmentRateChart,
AverageCheckChart,
PurchaseFrequencyChart,
PaidOrdersRateChart,
RepeatCustomerRateChart
)
from .celery import tasks
from lib.helpers import generate_redis_result_key
from widgets.helpers import get_recommendations_widgets
db = settings.DB
def get_widgets(site_id):
site = ObjectId(site_id)
widgets = []
widgets_configs = WidgetsConf.objects(site=site)
for widgets_config in widgets_configs:
json_config = json.loads(widgets_config.config)['widgets']
for w_id in json_config.keys():
name = json_config[w_id]['name']
w_type = json_config[w_id]['type']
widgets.append({'id': w_id, 'name': name, 'type': w_type})
return widgets
class Analytics(TemplateView):
template_name = "analytics/index.html"
def post(self, request):
sections = {
'visits': {
'label': ugettext(u'По визитам'),
'link': reverse('analytics.visits')
},
'leads': {
'label': ugettext(u'По клиентам'),
'link': reverse('analytics.leads')
},
'emails': {
'label': ugettext(u'По рассылкам'),
'link': reverse('analytics.emails')
},
'widgets': {
'label': ugettext(u'По виджетам'),
'link': reverse('analytics.widgets')
},
'recommendations': {
'label': ugettext(u'По рекомендациям'),
'link': reverse('analytics.recommendations')
},
'emails_dynamics': {
'label': ugettext(u'По динамике email\'ов'),
'link': reverse('analytics.emails_dynamics')
},
'autocasts': {
'label': ugettext(u'По авторассылкам'),
'link': reverse('analytics.autocasts')
},
'sales_funnel': {
'label': ugettext(u'По воронке продаж'),
'link': reverse('analytics.sales_funnel')
},
'shop_kpi': {
'label': ugettext(u'KPI'),
'link': reverse('analytics.shop_kpi')
},
}
return JsonResponse({
'sections': sections
})
class VisitsDataMixin(object):
def process_form(self, post_data):
p = P()
options = {'site': self.request.site_id}
options['aggr_condition'] = post_data['aggr_condition']
if post_data.get('initial'):
options.update({
'period_start': p.start,
'period_end': p.end,
'source': 'all',
'step': 'day'
})
return options
form = StatForm(post_data)
if not form.is_valid():
return {'error': humanize_form_errors(form)}
form_data = form.cleaned_data
options['source'] = form_data['source']
period = form_data['period']
if period != 'custom':
p = P.from_def_ranges(period)
else:
if not form_data['period_start']:
form.errors['period_start'] = [ugettext(u'Введите дату.')]
return {'error': humanize_form_errors(form)}
if not form_data['period_end']:
form.errors['period_end'] = [ugettext(u'Введите дату.')]
return {'error': humanize_form_errors(form)}
if form_data['period_start'].date() > datetime.now().date():
form.errors['period_start'] = [ugettext(u"Начало периода не может быть позже текущего дня.")]
return {'error': humanize_form_errors(form)}
if form_data['period_end'].date() > datetime.now().date():
form.errors['period_end'] = [ugettext(u"Конец периода не может быть позже текущего дня.")]
return {'error': humanize_form_errors(form)}
if form_data['period_start'] > form_data['period_end']:
form.errors['period_start'] = [ugettext(u'Начало периода не должно быть больше конца периода.')]
return {'error': humanize_form_errors(form)}
p.set_start_and_end(form_data['period_start'], form_data['period_end'])
options.update({'period_end': p.end,
'period_start': p.start,
'step': p.step
})
return options
def get_data(self, options):
match_stage = {
'$match': {
'site': DBRef('sites', ObjectId(options['site'])),
'start': {'$gte': options['period_start']},
'end': {'$lte': options['period_end']},
}
}
group_stage = {
'$group': {
'_id': {'$dateToString': {'format': '%Y-%m-%d %H:00', 'date': '$start'}},
'total': {'$sum': 1}
}
}
unique_leads_group_stage = {
'$group': {
'_id': '$lead',
'start': {'$first': '$start'}
}
}
if options['source'] == 'rest':
all_regexes = [{'referrer': {'$regex': regex}} for src in TraffSource.objects() for regex in src.regexp_list if regex]
match_stage['$match']['$nor'] = all_regexes
if options['source'] != 'all' and options['source'] != 'rest':
traff_source = TraffSource.objects(name=options['source']).first()
if traff_source.kind == 'main':
regex_query = self.get_regex_query(traff_source)
if regex_query:
match_stage['$match']['$or'] = regex_query
else:
regexp_list = [regex.decode('string_escape') for regex in traff_source.regexp_list]
regex_query = [{'referrer': {'$regex': regex}} for regex in regexp_list]
match_stage['$match']['$or'] = regex_query
if options['aggr_condition'] == 'visits':
visits = list(db.visits.aggregate([match_stage, group_stage]))
if options['aggr_condition'] == 'leads':
visits = list(db.visits.aggregate([match_stage, unique_leads_group_stage, group_stage]))
visits = [{'date': visit['_id'], 'visits': visit['total']} for visit in visits]
visits = sorted(visits, key=lambda x: x['date'])
total = sum([i['visits'] for i in visits])
return JsonResponse({
'data': {
'graph': visits,
'total_per_period': total
}
})
def get_regex_query(self, traff_source):
sources_ids = [ObjectId(_id) for _id in traff_source.sources_list]
sources = TraffSource.objects(id__in=sources_ids)
regexp_list = []
for source in sources:
for regex in source.regexp_list:
regexp_list.append(regex.decode('string_escape'))
regex_query = []
for regex in regexp_list:
regex_query.append({'referrer': {'$regex': regex}})
return regex_query
class VisitStatView(VisitsDataMixin, TemplateView):
template_name = "analytics/visits.html"
@method_decorator(permission_required('analytics'))
def post(self, request):
options = self.process_form(request.POST)
if options.get('error'):
return JsonResponse(options)
return self.get_data(options)
def get_context_data(self):
system_sources = TraffSource.objects(site=None)
user_sources = TraffSource.objects(site=self.request.site)
return {"data": {"system_sources": system_sources,
"user_sources": user_sources
}
}
@method_decorator(permission_required('analytics'), name="dispatch")
class WidgetsView(TemplateView):
template_name = "analytics/widgets.html"
def get_context_data(self, **kwargs):
context = super(WidgetsView, self).get_context_data(**kwargs)
widgets = get_widgets(self.request.site_id)
config = WidgetsConf.objects(site=self.request.site).first()
if config:
tests = json.loads(config.config)['testcases']
testcases = {}
[testcases.update(test) for test in tests]
context.update({'testcases': testcases})
context.update({'widgets': widgets})
return context
@method_decorator(role_required('master'), name="dispatch")
@method_decorator(permission_required('analytics'), name="dispatch")
class WidgetStatsView(WidgetsChart, TemplateView):
template_name = "analytics/widget_stats.html"
def post(self, request, **kwargs):
result = self.validate_input(self.request.POST)
if result['status'] == 'error':
return JsonResponse(result)
return JsonResponse(self.get_data(result))
@method_decorator(permission_required('analytics'), name="dispatch")
class LeadsStatsView(LeadsChart, TemplateView):
template_name = 'analytics/leads.html'
def post(self, request, **kwargs):
result = self.validate_input(self.request.POST)
if result['status'] == 'error':
return JsonResponse(result)
return JsonResponse(self.get_data(result, site=self.request.site))
def get_context_data(self):
context = super(LeadsStatsView, self).get_context_data()
system_sources = TraffSource.objects(site=None)
user_sources = TraffSource.objects(site=self.request.site)
context.update({
"data": {
"system_sources": system_sources,
"user_sources": user_sources
}
})
return context
class EmailCampaignStatsView(EmailCampaignsChart, TemplateView):
template_name = "analytics/emails.html"
def get_context_data(self):
context = super(EmailCampaignStatsView, self).get_context_data()
raw_autocasts = Autocast.objects(site=self.request.site).values_list('id', 'name', 'time_added')
sorted_autocasts = sorted(raw_autocasts, key=lambda x: x[2], reverse=True)
autocasts = [{'id': str(message[0]), 'name': message[1]} for message in sorted_autocasts]
raw_messages = Message.objects(
site=self.request.site, internal__in=(False, None)
).values_list('id', 'name', 'sent')
sorted_messages = sorted(raw_messages, key=lambda x: x[2], reverse=True)
mass_messages = [{'id': str(message[0]), 'name': message[1]} for message in sorted_messages]
context.update({
"autocasts": autocasts,
"email_campaigns": mass_messages
})
return context
def post(self, request):
result = self.validate_input(request.POST)
if result['status'] == 'error':
return JsonResponse(result)
data = self.get_data(result)
return JsonResponse(data)
class EmailsSentStatsView(View):
def get_data(self, request):
messages = Message.object(site=request.site)
match_stage = {
'$match': {
'message': {'$in': [DBRef('messages', message.id) for message in messages]}
}
}
group_stage = {
'$group': {
'_id': {
'$dateToString': {
'format': "%Y-%m-%d %H:%mm",
'date': "$time_added"
}
},
'count': {
'$sum': 1
}
}
}
emails = db.emails.aggregate([match_stage, group_stage])
return emails
@method_decorator(permission_required('analytics'), name="dispatch")
class RecommendationsStatsView(RecommendationsChart, TemplateView):
template_name = "analytics/recommendations.html"
def get_context_data(self, **kwargs):
context = super(RecommendationsStatsView, self).get_context_data(**kwargs)
context.update({'widgets': get_recommendations_widgets(self.request.site.id)})
return context
def post(self, request):
options = deepcopy(self.request.POST)
options['site_id'] = self.request.site.id
result = self.validate_input(options)
if result['status'] == 'error':
return JsonResponse(result)
return JsonResponse(self.get_data(result))
@method_decorator(permission_required('analytics'), name="dispatch")
class EmailDynamicsStatsView(EmailDynamicsChart, TemplateView):
template_name = "analytics/emails_dynamics.html"
def post(self, request):
options = deepcopy(self.request.POST)
result = self.validate_input(options)
if result['status'] == 'error':
return JsonResponse(result)
result['site_id'] = self.request.site.id
return JsonResponse(self.get_data(result))
class DashBoardView(VisitsChart, TemplateView):
template_name = 'analytics/dashboard.html'
def post(self, request):
site = request.site
if request.POST.get('init'):
dashboard_settings = site.interface_configuration.dashboard
data = {
'site_id': str(site.id),
'period': dashboard_settings['default_period']
}
elif request.POST.get('set_default_period'):
period = request.POST.get('default_period')
site.interface_configuration.dashboard['default_period'] = period
site.save()
data = {'status': 'success'}
else:
graph = request.POST.get('graph')
if graph == 'visits':
chart = VisitsChart()
if graph == 'sales_funnel':
chart = SalesFunnelChart(site_id=site.id)
if graph == 'sales_bar':
chart = SalesBarChart(site_id=site.id)
if graph == 'recommendations':
chart = RecommendationsChart()
if graph == 'emails':
chart = EmailDynamicsChart()
if graph == 'leads_discovery':
chart = LeadsDiscoveryChart()
result = chart.validate_input(request.POST)
result.update({'site_id': site.id})
if result.get('status') == 'error':
return JsonResponse(result)
result_key = generate_redis_result_key()
tasks.fetch_chart_data.apply_async(args=[chart, result, result_key], kwargs={'language': get_language()})
data = {'result_key': result_key}
return JsonResponse(data)
class AutocastsStatsView(TemplateView):
template_name = 'analytics/autocasts.html'
def get_context_data(self, **kwargs):
context = super(AutocastsStatsView, self).get_context_data(**kwargs)
context['autocasts'] = Autocast.objects(site=self.request.site).count()
return context
def post(self, request):
booleans_dict = {
'false': False,
'true': True
}
include_test_emails = booleans_dict[request.POST.get('test_emails')]
include_archived = booleans_dict[request.POST.get('show_archived')]
date_format = '%Y-%m-%d'
start = request.POST.get('period_start')
end = request.POST.get('period_end')
if start:
start = datetime.strptime(start, date_format)
if end:
end = datetime.strptime(end, date_format)
start, end, errors = process_autocasts_query_timeframe(start, end, request.site)
if errors.values():
return JsonResponse({'status': 'error', 'errors': errors, 'data': [], 'recordsTotal': 0})
autocasts = Autocast.objects(site=request.site, message__exists=True)
if not include_archived:
autocasts = autocasts(archived__ne=True)
message_ids, messages_to_autocasts_dict = get_messages_and_msg_to_autocast_dict(autocasts)
message_ids = [DBRef('messages', mid) for mid in message_ids]
match = {
'$match': {
'message': {'$in': message_ids},
'lead_id': {'$ne': 'None'},
'time_added': {'$gte': start, '$lte': end}
}
}
match_test_emails = deepcopy(match)
match_test_emails['$match']['lead_id'] = 'None'
group = {
'$group': {
'_id': '$message',
'recipients_count': {'$sum': 1},
'delivered': {'$sum': {'$cond': [{'$eq': ['$status', 'delivered']}, 1, 0]}},
'opened': {'$sum': {'$cond': [{'$eq': ['$opened', True]}, 1, 0]}},
'clicked': {'$sum': {'$cond': [{'$eq': ['$clicked', True]}, 1, 0]}},
'unsubscribed': {'$sum': {'$cond': [{'$eq': ['$unsubscribed', True]}, 1, 0]}},
}
}
project = {
'$project': {
'recipients_count': 1,
'delivered': 1,
'clicked': 1,
'opened': 1,
'unsubscribed': 1,
'delivered_percentage': {'$cond': [{'$eq': ['$recipients_count', 0]}, 0, {'$divide': ['$delivered', '$recipients_count']}]},
'opened_percentage': {'$cond': [{'$eq': ['$delivered', 0]}, 0, {'$divide': ['$opened', '$delivered']}]},
'clicked_percentage': {'$cond': [{'$eq': ['$opened', 0]}, 0, {'$divide': ['$clicked', '$opened']}]},
'unsubscribed_percentage': {'$cond': [{'$eq': ['$delivered', 0]}, 0, {'$divide': ['$unsubscribed', '$delivered']}]}
}
}
aggregated_data = db.emails.aggregate([match, group, project])
aggregated_data = {item['_id'].id: item for item in aggregated_data}
if include_test_emails:
test_emails_aggrgegated_data = db.emails.aggregate([match_test_emails, group, project])
test_emails_aggrgegated_data = {item['_id'].id: item for item in test_emails_aggrgegated_data}
data = []
for key in messages_to_autocasts_dict:
autocast = messages_to_autocasts_dict[key]['autocast']
formatted_data = {
'id': str(autocast.id),
'name': autocast.name,
'message_name': autocast.message.name,
'cases': autocast.cases,
'archived': autocast.archived,
}
autocast_aggr_data = aggregated_data.get(key, {})
stats = {
'recipients_count': {
'real': autocast_aggr_data.get('recipients_count', 0),
},
'delivered_emails': {
'real': autocast_aggr_data.get('delivered', 0),
'percentage': '{:.3g}%'.format(autocast_aggr_data.get('delivered_percentage', 0) * 100)
},
'opened_emails': {
'real': autocast_aggr_data.get('opened', 0),
'percentage': '{:.3g}%'.format(autocast_aggr_data.get('opened_percentage', 0) * 100)
},
'clicked_emails': {
'real': autocast_aggr_data.get('clicked', 0),
'percentage': '{:.3g}%'.format(autocast_aggr_data.get('clicked_percentage', 0) * 100)
},
'unsubscribed': {
'real': autocast_aggr_data.get('unsubscribed', 0),
'percentage': '{:.3g}%'.format(autocast_aggr_data.get('unsubscribed_percentage', 0) * 100)
}
}
if include_test_emails:
autocast_test_data_aggregated = test_emails_aggrgegated_data.get(key, {})
stats['recipients_count']['test'] = autocast_test_data_aggregated.get('recipients_count', 0)
stats['delivered_emails']['test'] = autocast_test_data_aggregated.get('delivered', 0)
stats['opened_emails']['test'] = autocast_test_data_aggregated.get('opened', 0)
stats['clicked_emails']['test'] = autocast_test_data_aggregated.get('clicked', 0)
formatted_data.update(stats)
if autocast.cases:
cases = []
for case in autocast.cases:
msg_id = case.message.id
case_data = {
'name': case.name,
'message_name': case.message.name
}
case_aggr_data = aggregated_data.get(msg_id, {})
case_data.update({
'name': case.name,
'message_name': case.message.name,
'recipients_count': {
'real': case_aggr_data.get('recipients_count', 0),
},
'delivered_emails': {
'real': case_aggr_data.get('delivered', 0),
'percentage': '{:.3g}%'.format(case_aggr_data.get('delivered_percentage', 0) * 100)
},
'opened_emails': {
'real': case_aggr_data.get('opened', 0),
'percentage': '{:.3g}%'.format(case_aggr_data.get('opened_percentage', 0) * 100)
},
'clicked_emails': {
'real': case_aggr_data.get('clicked', 0),
'percentage': '{:.3g}%'.format(case_aggr_data.get('clicked_percentage', 0) * 100)
},
'unsubscribed': {'real': 0}
})
if include_test_emails:
case_test_data_aggregated = test_emails_aggrgegated_data.get(msg_id, {})
case_data['recipients_count']['test'] = case_test_data_aggregated.get('recipients_count', 0)
case_data['delivered_emails']['test'] = case_test_data_aggregated.get('delivered', 0)
case_data['opened_emails']['test'] = case_test_data_aggregated.get('opened_emails', 0)
case_data['clicked_emails']['test'] = case_test_data_aggregated.get('clicked', 0)
cases.append(case_data)
for case in cases[1:]:
formatted_data['recipients_count']['real'] += case['recipients_count']['real']
formatted_data['delivered_emails']['real'] += case['delivered_emails']['real']
formatted_data['opened_emails']['real'] += case['opened_emails']['real']
formatted_data['clicked_emails']['real'] += case['clicked_emails']['real']
if include_test_emails and key in aggregated_data:
for case in cases[1:]:
formatted_data['recipients_count']['test'] += case['recipients_count']['test']
formatted_data['delivered_emails']['test'] += case['delivered_emails']['test']
formatted_data['opened_emails']['test'] += case['opened_emails']['test']
formatted_data['clicked_emails']['test'] += case['clicked_emails']['test']
formatted_data['cases'] = cases
data.append(formatted_data)
sort_fields = [
lambda x: x['name'],
lambda x: x['recipients_count']['real'],
lambda x: x['delivered_emails']['real'],
lambda x: x['opened_emails']['real'],
lambda x: x['clicked_emails']['real'],
lambda x: x['unsubscribed']['real'],
]
sort_directions = {
'asc': False,
'desc': True
}
per_page = int(request.POST['length'])
page = int(int(request.POST['start']) / per_page) + 1
sort_direction = sort_directions[request.POST['order[0][dir]']]
field = sort_fields[int(request.POST['order[0][column]'])]
data.sort(key=field, reverse=sort_direction)
autocasts_list = Pagination(iterable=data, page=page, per_page=per_page)
return JsonResponse({
'data': autocasts_list.items,
'status': 'ok',
'recordsTotal': autocasts_list.total,
'recordsFiltered': autocasts_list.total,
'draw': request.POST['draw'],
})
class SalesFunnelStatsView(SalesFunnelChart, TemplateView):
template_name = 'analytics/sales_funnel.html'
def post(self, request):
result = self.validate_input(request.POST)
if result['status'] == 'error':
return JsonResponse(result)
return JsonResponse(self.get_data(result))
class ShopKPIView(TemplateView):
template_name = 'analytics/shops_kpi.html'
def post(self, request):
validation_result = validate_time_period(request.POST.get('period_start'),
request.POST.get('period_end'), date_format='%d.%m.%Y')
if validation_result['status'] == 'error':
return JsonResponse(validation_result)
period_start = validation_result['start']
period_end = validation_result['end']
current_week, current_day = datetime.now().isocalendar()[1:]
if (period_end - period_start).days < 6:
if not(period_start.isocalendar()[1:] == (current_week, 1) and
period_end.isocalendar()[1] == current_week and period_end.isocalendar()[2] >= current_day):
return JsonResponse({
'status': 'error',
'errors': {ugettext(u'Период'): [ugettext(u'Минимальный период для выбора составляет 7 дней')]}
})
result_key = generate_redis_result_key()
tasks.get_shop_metrics.apply_async(
args=[self.request.site_id, period_start, period_end, result_key]
)
return JsonResponse({'result_key': result_key})
class ShopKPIGraphDataView(AverageRevenuePerVisitorChart, View):
def post(self, request):
validation_result = validate_time_period(request.POST.get('period_start'),
request.POST.get('period_end'), date_format='%d.%m.%Y')
if validation_result['status'] == 'error':
return JsonResponse(validation_result)
period_start = validation_result['start']
period_end = validation_result['end']
current_week, current_day = datetime.now().isocalendar()[1:]
if (period_end - period_start).days < 6:
if not(period_start.isocalendar()[1:] == (current_week, 1) and
period_end.isocalendar()[1] == current_week and period_end.isocalendar()[2] >= current_day):
return JsonResponse({
'status': 'error',
'errors': {ugettext(u'Период'): [ugettext(u'Минимальный период для выбора составляет 7 дней')]}
})
period_start = period_start - timedelta(days=period_start.weekday())
period_end = period_end + timedelta(days=6 - period_end.weekday())
graph_type = request.POST.get('graph_type')
charts = {
'arpv': AverageRevenuePerVisitorChart,
'arpu': AverageRevenuePerUserChart,
'arppu': AverageRevenuePerPayingUserChart,
'car': CartAbandonmentRateChart,
'average_check': AverageCheckChart,
'purchase_frequency': PurchaseFrequencyChart,
'paid_orders_rate': PaidOrdersRateChart,
'rcr': RepeatCustomerRateChart
}
chart = charts[graph_type]()
result_key = generate_redis_result_key()
tasks.fetch_chart_data.apply_async(
args=[
chart,
{
'period_start': period_start,
'period_end': period_end,
'site_id': self.request.site.id
},
result_key
]
)
return JsonResponse({'result_key': result_key})
| 16aff77e3ed71f4b85f846f3886a9b8bc862ed8f | [
"Python"
] | 3 | Python | kestkest/demo | 833f80802a96caeea7daea111a3cd37f561fb6cb | ced22c0e52309b952819e76b81796f8393f83152 |
refs/heads/master | <file_sep>$(document).ready(function() {
// Append body to tiles board, needs board and pointer
$('body').append('<div id="board"</div> <div id="pointer"</div>');
$('pointer').hide(); // Only see when tile is selected
// global vars
var xCoordinate;
var yCoordinate;
var tiles = [];
var clickTile = 'true';
var clickedRow = -1;
var clickedCol = -1;
var swappingTiles = 0;
// Array of 49ers tiles images
var images = ["url('images/1.jpg')","url('images/2.jpg')","url('images/3.jpg')",
"url('images/4.jpg')","url('images/5.jpg')","url('images/6.jpg')",
"url('images/7.jpg')","url('images/8.jpg')"];
// iterate through all 8 images, prepping to randomize, i and j are row and columns
for (i = 0; i < 8; i++) {
tiles[i]= [];
for (j = 0; j < 8; j++) {
tiles[i][j] = -1;
}
}
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
do {tiles[i][j] = Math.floor(Math.random() * 8);}
while (matches(i, j));
// creating new tile divs with specified row/col coords
$('#board').append('<div class="tile" id="tile_'+ i + '_'+ j +'"></div>');
// giving new divs top and left px's so they are positioned and attaching images
$('#tile_' + i + '_'+ j).css( {"top":(i * 80) + 10 + "px", "left": (j * 80) + 10 + "px",
"background": images[tiles[i][j]]} );
};
};
// clicking on a tile functionality
$(document).on("click",".tile", function() {
if (clickTile = 'true') {
yCoordinate = $(this).position().top; // $this is the current 'click' retrieving current coordinates
xCoordinate = $(this).position().left; // same here except left because it is along the x axis
$('#pointer').show();
$('#pointer').css("top", yCoordinate - 5).css("left", xCoordinate - 5); // pointer no longer hidden, giving it a position
if (clickedRow == -1) { // allowing pointer to highlight every div thats clicked
clickedRow = (yCoordinate - 10) / 80;
clickedCol = (xCoordinate - 10) / 80;
}
else { // when tile is clicked that matches, tileSwap called in, pointer hidden
yCoordinate = (yCoordinate - 10) / 80;
xCoordinate = (xCoordinate - 10) / 80;
if ((Math.abs(clickedRow - yCoordinate) == 1 &&
clickedCol == xCoordinate) || (Math.abs(clickedCol - xCoordinate) == 1 &&
clickedRow == yCoordinate)) {
$("#pointer").hide();
clickTile = "switch";
tileSwap();
}
else {
clickedRow = yCoordinate;
clickedCol = xCoordinate;
}
}
}
});
function tileSwap() {
var yOffset = clickedRow - yCoordinate;
var xOffset = clickedCol - xCoordinate;
// adding 'switch' class, giving opposite direction to both tiles
$("#tile_" + clickedRow + "_" + clickedCol).addClass("switch").attr("dir", "-1");
$("#tile_"+yCoordinate+"_"+xCoordinate).addClass("switch").attr("dir", "1");
// looping over both tiles and adding animation for switch class
$.each($(".switch"), function() {
swappingTiles++;
$(this).animate( {
left: "+=" + xOffset * 80 * $(this).attr("dir"),
top: "+=" + yOffset * 80 * $(this).attr("dir")
},{
duration: 500,
complete: function(){
swappedMatches();
}
}).removeClass("switch");
});
$("#tile_" + clickedRow + "_" + clickedCol).attr("id", "temp");
$("#tile_" + yCoordinate + "_" + xCoordinate).attr("id","tile_" + clickedRow +"_"+ clickedCol);
$("#temp").attr("id","tile_"+ yCoordinate +"_"+ xCoordinate);
var temp = tiles[clickedRow][clickedCol];
tiles[clickedRow][clickedCol] = tiles[yCoordinate][xCoordinate];
tiles[yCoordinate][xCoordinate] = temp;
}
// This is the replacing matched tiles logic
function replaceTiles() {
var tilesReplaced = 0;
for (i = 0; i < 8; i++) {
if (tiles[0][i] == -1) {
tiles[0][i] = Math.floor(Math.random() * 8);
$('#board').append('<div class = "tile" id = "tile_0_'+ i +'"></div>');
$('#tile_0_' + i).css({"top": "10px", "left": (i * 80) + 10 + "px", "width":"70px",
"height":"70px", "position": "absolute", "border": "1px solid white", "cursor":"pointer",
"background":images[tiles[0][i]] } );
tilesReplaced++;
}
}
if (tilesReplaced) {
clickTile = 'deleteTile';
cavingTiles();
}
else {
var combo = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
if (j <= 5 && tiles[i][j] == tiles[i][j+1] && tiles[i][j] == tiles[i][j + 2]) {
combo++;
removeTiles(i,j);
}
if (i <= 5 && tiles[i][j] == tiles[i + 1][j] && tiles[i][j] == tiles[i + 2][j]) {
combo++;
removeTiles(i,j);
}
}
}
if (combo > 0) {
clickTile = 'deleteTile';
tileDisappears();
}
else {
clickTile = 'true';
clickedRow = -1;
}
}
}
function cavingTiles(){
var cavedIn=0;
for (j = 0; j < 8; j++){
for (i = 7; i > 0; i--){
if (tiles[i][j] == -1 && tiles[i-1][j] >= 0) {
$("#tile_"+(i - 1) + "_" + j).addClass("cave").attr("id","tile_"+ i +"_" + j);
tiles[i][j]=tiles[i-1][j];
tiles[i-1][j] = -1;
cavedIn++;
}
}
}
$.each($(".cave"),function(){
swappingTiles++;
$(this).animate({ top: "+=80"},{ duration: 250, complete: function(){
$(this).removeClass("cave");
swappedMatches();
}
});
});
if(cavedIn == 0){
clickTile = "refill";
swappingTiles = 1;
swappedMatches();
}
}
// adds remove state and animates tile fading away after match
function tileDisappears() {
$.each($('.deleteTile'), function() {
swappingTiles++;
$(this).animate({opacity: 0}, {duration: 500, complete: function(){
$(this).remove();
swappedMatches();
}});
});
}
// Now we need to keep track of the tiles that we are clicking
// This will setup the states needed to keep non-matches and remove matches
function swappedMatches() {
swappingTiles --;
if (swappingTiles == 0) {
switch(clickTile) {
case "swapBack":
case "switch":
// this is saying if they don't match to swap back
if (!matches(clickedRow, clickedCol) && !matches(yCoordinate, xCoordinate)) {
if (clickTile != "swapBack") {
clickTile = "swapBack";
tileSwap();
}
else {
clickTile = "true";
clickedRow = -1;
}
}
else { // this will be the state that removes tiles that matched
clickTile = "deleteTile";
if (matches(clickedRow, clickedCol)) {
removeTiles(clickedRow, clickedCol);
}
if (matches(yCoordinate, xCoordinate)) {
removeTiles(yCoordinate, xCoordinate);
}
tileDisappears();
}
break;
case "deleteTile":
cavingTiles();
break;
case "refill":
replaceTiles();
break;
}
}
}
function removeTiles(row, col) {
var tileCoordinates = tiles[row][col];
var arr = row;
$('#tile_' + row + '_' + col).addClass('deleteTile');
if (yMatch(row, col)) {
while (arr > 0 && tiles[arr - 1][col] == tileCoordinates) {
$('#tile_' + (arr - 1) + '_' + col).addClass('deleteTile');
tiles[arr - 1][col] = -1;
arr--;
}
var arr = row;
while (arr < 7 && tiles[arr + 1][col] == tileCoordinates) {
$('#tile_' + (arr + 1) + '_' + col).addClass('deleteTile');
tiles[arr + 1][col] = -1;
arr++;
}
}
if (xMatch(row, col)) {
var arr = col;
while (arr > 0 && tiles[row][arr - col] == tileCoordinates) {
$('#tile_' + row + '_' + (arr - 1)).addClass('deleteTile');
tiles[row][arr - 1] = -1;
arr--;
}
var arr = col;
while (arr < 7 && tiles[row][arr + 1] == tileCoordinates) {
$('#tile_' + row + '_' + (arr + 1)).addClass('deleteTile');
tiles[row][arr + 1] = -1;
arr++;
}
}
tiles[row][col] = -1;
}
// Total matches
function matches(row, col) {
return yMatch(row, col) || xMatch(row, col);
}
// Tiles that match vertically
function yMatch(row, col) {
var tileCoordinates = tiles[row][col];
var identicalTiles = 0;
var arr = row;
while ( arr > 0 && tiles[arr - 1][col] == tileCoordinates) {
identicalTiles++;
arr--;
}
arr = row;
while ( arr < 7 && tiles[arr + 1][col] == tileCoordinates) {
identicalTiles++;
arr++;
}
return identicalTiles > 1;
}
// Tiles that match Horizontally
function xMatch(row, col) {
var tileCoordinates = tiles[row][col];
var identicalTiles = 0; // sequential tiles that are identical
var arr = col; // temporary array to store row coordinates
while ( arr > 0 && tiles[arr - 1][col] == tileCoordinates) {
identicalTiles++;
arr--;
}
arr = col;
while ( arr < 7 && tiles[arr + 1][col] == tileCoordinates) {
identicalTiles++;
arr++;
}
return identicalTiles > 1;
}
}); | 9be5916d925718c35579984c179fbfecc6bf589f | [
"JavaScript"
] | 1 | JavaScript | ryanwaters/49ers_match_3 | 5989e3c23b56d36551b9d1be42a5ab3f8e894b69 | f1c7b5b1cb9d6e3020d2e23a769337b5c54a03b6 |
refs/heads/master | <repo_name>Garima1221/Marketing-Campaign<file_sep>/app.R
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(shinydashboard)
library(ggplot2)
library(ggthemes)
library(caret)
library(plotly)
library(curl)
library(RCurl)
library(e1071)
library(rpart)
library(ranger)
load("RandomeForestModel.rda")
ui <- dashboardPage(
dashboardHeader(title = "Marketing Campaign"
),
dashboardSidebar(
sidebarMenu(
menuItem("Profile Details", tabName = "Profile Details", icon = icon("dashboard"))
)
),
dashboardBody(
tabItem(tabName = "Profile Details",
h2("Details"),
fluidRow(
box(title = "Age",
height = 120,width = 3,
background = "light-blue",
numericInput("age", label = h6(""), value = 18)
),
box(title = "Job",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "job_cat",label=h6(""),
choices = c("management","technician","entrepreneur","blue-collar","unknown","retired","admin.","services","self-employed","unemployed","housemaid","student"),selected = "management")
),
box(title = "Marital Status",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "marital",label=h6(""),
choices = c("married","single","divorced"),
selected = "single")
),
box(title = "Education",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "education",label=h6(""),
choices = c("primary","secondary","tertiary","unknown"
),selected = "primary")
),
box(title = "Has Defaulted",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "default",label=h6(""),
choices = c("yes","no"),selected = "yes")
),
box(title = "Has Existing Loan",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "loan",label=h6(""),
choices = c("yes","no"),selected = "yes")
),
box(title = "Mode of contact",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "contact",label=h6(""),
choices = c("cellular","telephone"),selected = "cellular")
),
box(title = "Month",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "month",label=h6(""),
choices = c("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"),selected = "jan")
),
box(title = "Day(1-31)",
height = 120,width = 3,background = "light-blue",
numericInput("day", label = h6(""), value = 1)
),
box(title = "Duration",
height = 120,width = 3,background = "light-blue",
numericInput("duration", label = h6(""), value = 0)
),
box(title = "Outcome",
height = 120,width = 3,background = "light-blue",
selectInput(inputId = "poutcome",label=h6(""),
choices = c("failure","success","other","unknown"),selected = "jan")
),
box(title = "Previous",
height = 120,width = 3,background = "light-blue",
numericInput("previous", label = h6(""), value = 0)
),
box(
submitButton("Submit")
),
tableOutput("value")
)
)
)
)
server <- function(input, output) {
prediction = reactive({
temp=10
test = data.frame(input$age,input$job_cat,input$marital,input$education,input$default,input$loan,input$contact,input$month,input$day,input$duration,input$outcome,input$previous)
colnames(test) = c("age","job_cat","marital","education","default","loan","contact","month","day","duration","outcome","previous")
for(i in c(categorical_features)){
if(class(test[,i]) == 'factor'){
test[,i] = factor(test[,i],labels = 1:length(levels(factor(test[,i]))))
}
}
output_prediction = predict(model.RF,test)
output_prediction
})
#output$value = renderTable({
#test = data.frame(input$age,input$job_cat,input$marital,input$education,input$default,input$loan,input$contact,input$month,input$day,input$duration,input$outcome,input$previous)
#test
prediction()
#input$age
#})
output$value <- renderText({paste("selected", prediction)})
}
shinyApp(ui, server)<file_sep>/README.md
# Marketing-Campaign
Work under progress!
| 0e4daff604409523bdfeca3c27e595d2c2e86342 | [
"Markdown",
"R"
] | 2 | R | Garima1221/Marketing-Campaign | ca8e215ee2b12d2b0a2b8af85e266b5ff5a15816 | c2f6e38c4cf667cc960aa361f58d0414cf0d8013 |
refs/heads/master | <file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factory
{
public class Pizza
{
public string Name { get; set; }
public string Dough { get; set; }
public string Sauce { get; set; }
public ArrayList Toppings { get; set; }
public Pizza()
{
this.Toppings = new ArrayList();
}
public virtual void Prepare()
{
Console.WriteLine("Preparing " + Name);
Console.WriteLine("Tossing dough...");
Console.WriteLine("Adding sauce...");
Console.WriteLine("Adding toppings: ");
for(int i =0; i < Toppings.Count; i++)
{
Console.WriteLine(" " + Toppings[i]);
}
}
public virtual void Bake()
{
Console.WriteLine("Back for 25 minutes at 350");
}
public virtual void Cut()
{
Console.WriteLine("Cutting the pizza into diagonal slices");
}
public virtual void Box()
{
Console.WriteLine("Place pizza in official PizzaStore box");
}
}
#region 纽约店的Pizza
public class NYStyleCheesePizza : Pizza
{
public NYStyleCheesePizza()
{
Name = "NY Style Sauce and Cheese Pizza";
Dough = "Thin Crust Dough";
this.Sauce = "Marinara Sauce";
this.Toppings.Add("Grated Reggiano Cheese");
}
}
public class NYStyleVeggiePizza : Pizza
{ }
public class NYStylePepperoniPizza : Pizza
{
}
#endregion
#region 芝加哥店Pizza
public class ChicagoStyleCheesePizza : Pizza
{
public ChicagoStyleCheesePizza()
{
Name = "Chicago Style Deep Dish Cheese Pizza";
Dough = "Extra Thick Crust Dough";
this.Sauce = "Plum Tomato Sauce";
this.Toppings.Add("Shredded Mozzarella Cheese");
}
public override void Cut()
{
Console.WriteLine("Cutting the pizza into square slices");
}
}
#endregion
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factory
{
public abstract class PizzaStore
{
public Pizza orderPizza(string type)
{
Pizza pizza;
pizza = CreatePizza(type);
pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();
return pizza;
}
//实例化Pizza的责任被转移到一个方法中,此方法就如同是一个"工厂"
//工厂方法用来处理对象的创建,并将这样的行为封装在子类中
//这样,客户程序中关于超类的代码就和子类创建代码解耦了
protected abstract Pizza CreatePizza(string type);
}
public class NYPizzaStore : PizzaStore
{
protected override Pizza CreatePizza(string type)
{
if (type.Equals("cheese"))
{
return new NYStyleCheesePizza();
}
else if (type.Equals("veggie"))
{
return new NYStyleVeggiePizza();
}
else if (type.Equals("pepperoni"))
{
return new NYStylePepperoniPizza();
}
else return null;
}
}
public class ChicagoPizzaStore : PizzaStore
{
protected override Pizza CreatePizza(string type)
{
if (type.Equals("cheese"))
{
return new ChicagoStyleCheesePizza();
}
else if (type.Equals("veggie"))
{
return new NYStyleVeggiePizza();
}
else if (type.Equals("pepperoni"))
{
return new NYStylePepperoniPizza();
}
else return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factory
{
public interface IPizzaIngredientFactory
{
public Dough CreateDouch();
public Sauce CreateSauce();
public Cheese CreateCheese();
public Veggies[] CreateVeggies();
public Pepperoni CreatePepperoni();
public Clams CreateClam();
}
}
| 5232cb28da0fb2a7a1b6dc734176dce9464c11eb | [
"C#"
] | 3 | C# | patrickfly/DesignPatterns | 7763d71d917dcdd5e51faea341acd6d6ac406a4a | 47d13d38f7d010063007e8ca68f22a9f5db1d13a |
refs/heads/master | <repo_name>Yanish-bjn/CRUD-Symfony<file_sep>/Test2/src/Controller/supprimerController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Repository\TriRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Form\supprimerType;
use App\Entity\Tri;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpFoundation\Response;
class supprimerController extends AbstractController{
/**
*@var TriRepository
*/
private $repository;
public function __construct(TriRepository $repository, EntityManagerInterface $manager){
$this->repository = $repository;
$this->manager = $manager;
}
/**
* @Route("/supprimer/{id}", name="tri_supprimer")
*
*/
public function supprimerType(Tri $Tri){
$manager = $this->getDoctrine()->getmanager(); // Permets de récupérer et d'envoyer la requête //
$manager->remove($Tri); // On supprime l'ancienne tache //
$manager->flush(); // On envoie la requête dans la BDD //
return $this->redirectToRoute('home'); // On redirige vers la page d'accueil //
}
}
?>
<file_sep>/Test2/src/Controller/modifierController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Repository\TriRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Form\AjouterType;
use App\Entity\Tri;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class modifierController extends AbstractController{
/**
*@var TriRepository
*/
private $repository;
private $manager;
public function __construct(TriRepository $repository, EntityManagerInterface $manager){
$this->manager = $manager;
$this->repository = $repository;
}
/**
* @return Response
* @param Tri $Tri
* @param Tri $request
* @Route("/supprimer/{id}", name="tri_modifierType")
* @route("/modifierType/{id}", name="tri_modifierType")
*/
public function modifierType(Tri $Tri = null, Request $request, EntityManagerInterface $manager){
if(!$Tri){//Si tri est vide alors on crée une tache //
$Tri = new Tri();
}
$form = $this->createForm(AjouterType::class, $Tri); // On envoie le formulaire qui a été créer /:
$form->handleRequest($request); // Permets de récupérer et d'envoyer la requête //
if ($form->isSubmitted() && $form->isValid()){ // si le formulaire est envoyé //
$modif = $Tri->getId() !== null;
$manager->persist($Tri); // Les infos entrées dans le formulaire sont récupéré //
$manager->flush(); // On envoie les données dans la BDD //
$manager->remove($Tri); // On supprime l'ancienne tache //
return $this->redirectToRoute('home'); // on redirige vers la page d'accueil //
}
$formView = $form->createView();
return $this->render('Pages/modifier.html.twig',[ //Si tri est vide alors on envoie le formulaire permettant à l'utilisateur d'entrer les données //
'Tri' => $Tri,
'form' => $formView,
'ismodificated' => $Tri->getId() !== null
]);
}
}
?>
<file_sep>/Test2/test/Tri.php
<?php
namespace Test2;
use Doctrine\ORM\Mapping as ORM;
/**
* Tri
*
* @ORM\Table(name="tri")
* @ORM\Entity
*/
class Tri
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="titre", type="string", length=255, nullable=false)
*/
private $titre;
/**
* @var string|null
*
* @ORM\Column(name="description", type="text", length=0, nullable=true)
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="statut", type="string", length=255, nullable=false)
*/
private $statut;
/**
* @var string
*
* @ORM\Column(name="date_publication", type="string", length=255, nullable=false)
*/
private $datePublication;
}
<file_sep>/Test2/test.sql
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Hôte : 127.0.0.1:3306
-- Généré le : jeu. 27 fév. 2020 à 17:44
-- Version du serveur : 5.7.26
-- Version de PHP : 7.3.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `test`
--
-- --------------------------------------------------------
--
-- Structure de la table `migration_versions`
--
DROP TABLE IF EXISTS `migration_versions`;
CREATE TABLE IF NOT EXISTS `migration_versions` (
`version` varchar(14) COLLATE utf8mb4_unicode_ci NOT NULL,
`executed_at` datetime NOT NULL COMMENT '(DC2Type:datetime_immutable)',
PRIMARY KEY (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `migration_versions`
--
INSERT INTO `migration_versions` (`version`, `executed_at`) VALUES
('20200208172508', '2020-02-08 17:27:56');
-- --------------------------------------------------------
--
-- Structure de la table `tri`
--
DROP TABLE IF EXISTS `tri`;
CREATE TABLE IF NOT EXISTS `tri` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`titre` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` longtext COLLATE utf8mb4_unicode_ci,
`statut` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`date_publication` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `tri`
--
INSERT INTO `tri` (`id`, `titre`, `description`, `statut`, `date_publication`) VALUES
(14, 'salon', 'Ranger le canapé', '2', '14/02/2020'),
(15, 'Cuisine', 'Nettoyer la cuisine', '3', '22/02/2020'),
(16, 'Chambre ', 'Ranger la chambre ', '1', '14/02/2020');
COMMIT;
/*!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>/Test2/src/Form/AjouterType.php
<?php
namespace App\Form;
use App\Entity\Tri;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AjouterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('Titre')
->add('description')
->add('statut', ChoiceType::class, [ // Liste deroulante pour le choix du statut //
'choices' => $this->getChoices()
])
->add('date_publication')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Tri::class,
]);
}
private function getChoices(){ // fonction permettant de changer les valeurs de la liste deroulante, par les choix du staut //
$Choices = Tri::STATUT;
$output = [];
foreach ($Choices as $k => $v) { // Pour la varible choix allant de k a v //
$output[$v] = $k; // la valeur de la variable v est egal a k //
}
return $output; // on retourne le résultat //
}
}
<file_sep>/Test2/src/Controller/ajouterController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Repository\TriRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Form\AjouterType;
use App\Entity\Tri;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpFoundation\Response;
class ajouterController extends AbstractController{
/**
*@var TriRepository
*/
private $repository;
private $manager;
public function __construct(TriRepository $repository, EntityManagerInterface $manager){
$this->manager = $manager;
$this->repository = $repository;
}
/**
*
*@return \Symfony\Component\HttpFoundation\Response;
*/
public function AjouterType(Tri $Tri = null, Request $request, EntityManagerInterface $manager){
if(!$Tri){ //Si tri est vide alors on crée une tache //
$Tri = new Tri();
}
$form = $this->createForm(AjouterType::class, $Tri); // On envoie le formulaire qui a été créer/:
$form->handleRequest($request); // Permets de récupérer et d'envoyer la requête //
if ($form->isSubmitted() && $form->isValid()){ // si le formulaire est envoyé //
$modif = $Tri->getId() !== null; //
$manager->persist($Tri); // Les infos entrées dans le formulaire sont récupéré //
$manager->flush(); //On envoie les données dans la BDD //
return $this->redirectToRoute('home'); // on redirige vers la page d'accueil //
}
return $this->render('Pages/ajouter.html.twig',[ // Si la variable tri est vide alors on envoie le formulaire permettant à l'utilisateur d'entrer les données //
'Tri' => $Tri,
'form' => $form->createView(),
'ismodificated' => $Tri->getId() !== null
]);
return $this->redirectToRoute('Pages/Home.html.twig');
}
}
?>
<file_sep>/Test2/src/Controller/HomeController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Repository\TriRepository;
use Symfony\Component\Routing\Annotation\Route;
class HomeController extends AbstractController{
/**
*@var TriRepository
*/
private $repository;
public function __construct(TriRepository $repository){
$this->repository = $repository;
}
public function index()
{
$a = $this->repository->findAll(); //On récupère les données de la BDD//
return $this->render('Pages/Home.html.twig', compact('a')); // On redirige les données vers la page home.html.twig et on affiche les données sous forme de tableau //
}
}
?>
| cea82f8dc959bee7cb55c5a5fefefe8d44c70ca5 | [
"SQL",
"PHP"
] | 7 | PHP | Yanish-bjn/CRUD-Symfony | e78463d69a55e36f7b4a48722a477e26a5ac0bf8 | 0a31607eb0ad7effbfdcef2fb20b97023647641b |
refs/heads/master | <repo_name>abosyaka/SimpleBankProject<file_sep>/Simple Banking System/task/src/banking/Main.java
package banking;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
public class Main {
static public String filename;
public static void main(String[] args) {
Main.filename = args[1];
Bank bank = new Bank();
bank.start();
}
}
<file_sep>/Problems/Converting and multiplying/src/Main.java
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
String[] seq = new String[100];
int i = 0;
String input = "";
while (true) {
input = scanner.next();
if (input.equals("0")) break;
seq[i++] = input;
}
for (int j = 0; j < i; j++) {
try {
System.out.println(Integer.parseInt(seq[j]) * 10);
} catch (RuntimeException e) {
System.out.println("Invalid user input: " + seq[j]);
}
}
}
} | cf1f5323c3b3ee5785f9e2a283ac6357e1635562 | [
"Java"
] | 2 | Java | abosyaka/SimpleBankProject | ad3f45c20e2780c2b49828ff60d938eb37ec4bc7 | 244537c2c658acc0ba83dfeb4c43c4450c4a609e |
refs/heads/master | <repo_name>lv-conner/webpackconfig<file_sep>/webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
mode:"production",
entry:{
index:path.resolve("src/index.js"),
home:path.resolve("src/home.js")
},
output:{
path:__dirname + "/build",
filename:"[name]-[hash:8].js"
},
devServer:{
/*设置基本目录结构,也就是你想要使用服务的目录地址*/
contentBase:path.resolve(__dirname,'build'),
/*服务器的IP地址,可以使用IP也可以使用localhost*/
host:'localhost',
/*服务端压缩是否开启,目前开不开都行,想关你就关*/
compress:true,
/*配置服务端口号,建议别用80,很容易被占用,你要是非要用也是可以的。*/
port:9090
},
module:{
rules:[
{
// test 表示测试什么文件类型
test:/\.css$/,
// 使用 'style-loader','css-loader'
use:['style-loader','css-loader']
},
{
test:/\.jsx?$/,
exclude:/node_modules/,
use:{
loader:"babel-loader"
}
}
]
},
plugins:[
//new CleanWebpackPlugin(["build"],{verbose:true}),
new HtmlWebpackPlugin({
inject:true,
filename:"index.html",
chunks:["index"],
template:path.resolve("templates/index.html"),
minify:{
minifyJS:true
}
}),
new HtmlWebpackPlugin({
inject:true,
filename:"home.html",
chunks:["home"],
template:path.resolve("templates/home.html"),
minify:{
minifyJS:true
}
})
]
}<file_sep>/README.md
# webpackconfig
webpack配置学习
| 1f7a70195cf066383d63c54f8e8d6463e4c8fca3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | lv-conner/webpackconfig | 8b03bfbdfa873412423ef4c764380c8fde476525 | da8cc688e8046de3fe50e6cf60b8472a5f89bb2f |
refs/heads/main | <file_sep>WS1 corresponds to “ws_network_p_0.01_k4.RData”
WS2 corresponds to “ws_network_p_0.1_k4.RData”
WS3 corresponds to “ws_network_p_1_k4.RData”
WS4 corresponds to “ws_network_p_0.01_k8.RData”
WS5 corresponds to “ws_network_p_0.1_k8.RData”
WS6 corresponds to “ws_network_p_1_k8.RData”
SF corresponds to “ba_network_k4.RData”
DATA1 corresponds to “India_network_inter_village_1% nodes.RData”
DATA2 corresponds to “India_network_inter_village_3% nodes.RData”
DATA3 corresponds to “India_network_inter_village_5% nodes.RData”
<file_sep>Use an accurate code depending on the type of contact networks and cooperativity scenarios you are interested in.
e.g.,[WS-network]Cooperativity_Scenario1.R should be used for any Watts-Strogatz networks and Cooperativity Scenario 1. Inside the R code, you can control other settings (false negative rate, false positive rate, starting point of contact tracing, Turnaround times for test results).<file_sep>## Required packages
list.of.packages <- c("data.table","matrixStats", "reshape2","dplyr","igraph","fastmatch","pryr")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)>0) install.packages(new.packages)
lapply(list.of.packages, library, character.only = TRUE)
# define fast search function
`%fin%` <- function(x, table) {
fmatch(x, table, nomatch = 0L) > 0L
}
#### Model Parameters ####
latency.period<-2
f.Ip_pre.to.Ip<-function(Ip_pre.list,t){
sel<-rbinom(length(Ip_pre.list),1,1./latency.period)
status<-ifelse(sel==1,'Ip','Ip-L')
return(status)
}
latency.period<-2
f.Ia_pre.to.Ia<-function(Ia_pre.list,t){
sel<-rbinom(length(Ia_pre.list),1,1./latency.period)
status<-ifelse(sel==1,'Ia','Ia-L')
return(status)
}
incubation.period<-5
post.latency.period<-incubation.period-latency.period
f.Ip.to.Is<-function(Ip.list,t){
sel<-rbinom(length(Ip.list),1,1./post.latency.period)
status<-ifelse(sel==1,'Is','Ip')
return(status)
}
wait.see.period<-4
f.Is.to.RTs<-function(Is.list,t){
sel<-rbinom(length(Is.list),1,1./wait.see.period)
status<-ifelse(sel==1,'RT','Is')
return(status)
}
rec.death.period<-14-wait.see.period
death.rate<-0.0065
f.RTs.to.D<-function(RT.list,t){
status<-base::sample(c('R', 'D', 'RT'), size = length(RT.list), replace = TRUE, prob = c((1./rec.death.period)*(1.-death.rate), (1./rec.death.period)*death.rate, (1.-1./rec.death.period)))
return(status)
}
infectious.Ia.period<-7
f.Ia.to.R<-function(Ia.list,t){
sel<-rbinom(length(Ia.list),1,1./infectious.Ia.period)
status<-ifelse(sel==1,'R','Ia')
return(status)
}
#### Contact Tracing Function ####
contact.tracing<-function(hops,TP.list.for.CT,edges.ct.all){
multihop.temp<-vector(); multihop<-vector();
for(i in 1:hops){
temp<-if(i==1) TP.list.for.CT else multihop.temp
multihop.temp<-unique(edges.ct.all[edges.ct.all$node1 %fin% temp]$node2)
multihop<-unique(c(multihop,multihop.temp))
}
multihop<-multihop[!multihop %fin% TP.list.for.CT]
return(multihop)
}
#### Simulations ####
intervention.start.inf.rate<-0 # Starting point of contact tracing, percent (%); enter 0 if contact tracing is initiated when the first individual tests positive
turnaround<-1 # Turnaround times for coronavirus test results (days)
FP.rate<-0 # False Positive rate, percent (%)
FN.rate<-11 # False Negative rate, percent (%)
cooperativity<-100 # Cooperativity (%)
edge.perc.intercluster<-1
mainDir.1<-paste0("~/Dropbox/AWS/DATA/Inter-village contacts/",edge.perc.intercluster,"% edges")
mainDir.2<-file.path(mainDir.1, paste0('intervention from ',intervention.start.inf.rate,'% infections'))
dir.create(mainDir.2)
mainDir.3<-file.path(mainDir.2, paste0('Turnaround ',turnaround,' day'))
dir.create(mainDir.3)
mainDir.4<-file.path(mainDir.3, paste0('FP ',FP.rate,'%'))
dir.create(mainDir.4)
mainDir.5<-file.path(mainDir.4, paste0('FN ',FN.rate,'%'))
dir.create(mainDir.5)
mainDir.6<-file.path(mainDir.5, paste0('Cooperativity (Scenario 1) ',cooperativity,'%'))
dir.create(mainDir.6)
for(cccc in c(0.1,0.15,0.2,0.25,0.3)){
topology<-file.path(mainDir.1, paste0("India_network_inter_village_",edge.perc.intercluster,"% nodes.RData"))
edges.all.undir.final<-get(load(topology))
subDir<-paste0("PoI ",cccc)
dir.create(file.path(mainDir.6, subDir))
setwd(file.path(mainDir.6, subDir))
N<-edges.all.undir.final[[3]] # Total number of nodes in erdos-renyi and scale-free networks
T.max = edges.all.undir.final[[2]] # total number of days
test.x.days.later<-3
prob.inf.from.symp<-cccc # Probability with which a symptomatic individual infects a susceptible in an interaction
prob.inf.from.presymp<-prob.inf.from.symp # Probability with which a presymptomatic individual infects a susceptible in an interaction
infness.of.asymp<-1 # infectiousness of asymptomatic individuals relative to symptomatic
prob.inf.from.asymp<-prob.inf.from.symp*infness.of.asymp # Probability with which a asymptomatic individual infects a susceptible in an interaction
prop.asymp<-0.4 # proportion of asymptomatic individuals among infected people.
I0<-3 # the number of initially infected individuals
symptom<-c('Is','RT') # compartments with symptoms
nosymptom<-c('S', 'Ia-L', 'Ip-L', 'Ip','Ia','R') # compartments without symptoms
edge.list.undir<-vector();
edge.list.undir<-copy(edges.all.undir.final[[1]][,c(1,2)])
edge.list.undir$edge_num<-1:nrow(edge.list.undir)
epidemic<-function(iteration,hhh){
hops<-hhh
wdata.new <- rep(NA,N)
wdata.ct.new <- data.table('1'=rep(NA,N))
wdata.tp.new <- data.table('1'=rep(NA,N))
wdata.qt.temp <- rep(Inf,N)
wdata.qt.actual.temp <- rep(Inf,N)
wdata.tp.temp <- rep(0,N)
wdata.ct.day <- rep(0,T.max)
wdata.ct.day.cum <- 0
wdata.inf.count<-rep(0,T.max);
wdata.test.count<-rep(0,T.max);
wdata.qt.count<-rep(0,T.max);
### initial condition
I0.node<-base::sample.int(N, I0)
symptomatic<-I0.node[1]; presymptomatic<-I0.node[2]; asymptomatic<-I0.node[3];
susceptible<-c(1:N)[-I0.node];
wdata.inf.count[1]<-I0;
if(length(susceptible)>0){wdata.new[susceptible]<-'S'}
if(length(presymptomatic)>0){wdata.new[presymptomatic]<-'Ip'}
if(length(symptomatic)>0){wdata.new[symptomatic]<-'Is'}
if(length(asymptomatic)>0){wdata.new[asymptomatic]<-'Ia'}
temp.num<-round(N*(1.-cooperativity/100.))
non.cooperative.nodes<-if(temp.num==0){vector()}else{sample(1:N, temp.num, replace = F)}
cooperative.nodes<-if(length(non.cooperative.nodes)==0){1:N}else{c(1:N)[-non.cooperative.nodes]}
edges.all.final.transmission<-vector(mode='list',length=T.max)
remove.edges.HA<-vector(mode='list',length=T.max)
remove.edges.real<-vector(mode='list',length=T.max)
edges.all.final.transmission[[1]]<-rbindlist(list(edge.list.undir[,c(1,2)],edge.list.undir[,c(2,1)]),use.names=FALSE)
test.rt.all<-vector()
set.seed(iteration)
for(t in 2:T.max){
wdata.old<-wdata.new
#### Epidemic process; status update from day t-1 to day t ####
S.list<-vector();
temp1<-which(wdata.old %fin% c('S'))
if(length(temp1)>0){
wdata.new[temp1]<-'S'
S.list<-data.table(node1=as.integer(temp1), status='S')
}
I.list<-vector();
temp2<-which(wdata.old %fin% c('Ip','Is','Ia'))
if(length(temp1)>0 & length(temp2)>0){
I.list<-wdata.old[temp2]
I.list<-data.table(node2=as.integer(temp2), status=I.list)
neighbor.of.I<-vector(); inf.list<-vector();
neighbor.of.I<-edges.all.final.transmission[[t-1]][node1 %fin% S.list$node1 & node2 %fin% I.list$node2]
if(nrow(neighbor.of.I)>0){
neighbor.of.I<-I.list[neighbor.of.I, on="node2"]
neighbor.of.I<-neighbor.of.I[,.(count = .N), by=.(node1,status)]
neighbor.of.I$status<-factor(neighbor.of.I$status, levels=c("Ip", "Is", "Ia"))
neighbor.of.I<-setDT(dcast(neighbor.of.I, node1 ~ status, fun = sum, value.var = "count", drop=F))
neighbor.of.I[,prob.inf:=1-((1-prob.inf.from.presymp)^Ip)*((1-prob.inf.from.symp)^Is)*((1-prob.inf.from.asymp)^Ia)]
neighbor.of.I[,new.inf:=rbinom(length(neighbor.of.I$prob.inf), size = 1, prob=neighbor.of.I$prob.inf)]
temp<-rbinom(sum(neighbor.of.I$new.inf==1), size = 1, prob=prop.asymp)
neighbor.of.I[new.inf==1,new.inf.Ia:=temp]
neighbor.of.I$new.inf.Ia[is.na(neighbor.of.I$new.inf.Ia)]<-0
neighbor.of.I[new.inf==1 & new.inf.Ia==1,stt:='Ia-L']
neighbor.of.I[new.inf==1 & new.inf.Ia!=1,stt:='Ip-L']
neighbor.of.I<-neighbor.of.I[!is.na(stt)]
new.inf<-nrow(neighbor.of.I)
if(new.inf>0){
wdata.new[neighbor.of.I$node1]<-neighbor.of.I$stt
wdata.inf.count[t]<-new.inf
}
}
}
Ip_pre.list<-which(wdata.old=='Ip-L')
if(length(Ip_pre.list)>=1){
temp<-f.Ip_pre.to.Ip(Ip_pre.list,t-1)
wdata.new[Ip_pre.list]<-temp
}
Ia_pre.list<-which(wdata.old=='Ia-L')
if(length(Ia_pre.list)>=1){
temp<-f.Ia_pre.to.Ia(Ia_pre.list,t-1)
wdata.new[Ia_pre.list]<-temp
}
Ip.list<-which(wdata.old=='Ip')
if(length(Ip.list)>=1){
temp<-f.Ip.to.Is(Ip.list,t-1)
wdata.new[Ip.list]<-temp
}
Is.list<-which(wdata.old=='Is')
RT.new<-vector()
if(length(Is.list)>=1){
temp<-f.Is.to.RTs(Is.list,t-1)
wdata.new[Is.list]<-temp
RT.new<-Is.list[which(temp=='RT')]
}
RT.list<-which(wdata.old=='RT')
if(length(RT.list)>=1){
temp<-f.RTs.to.D(RT.list,t-1)
wdata.new[RT.list]<-temp
}
Ia.list<-which(wdata.old=='Ia')
if(length(Ia.list)>=1){
temp<-f.Ia.to.R(Ia.list,t-1)
wdata.new[Ia.list]<-temp
}
R.list<-which(wdata.old=='R')
if(length(R.list)>=1){
wdata.new[R.list]<-'R'
}
D.list<-which(wdata.old=='D')
if(length(D.list)>=1){
wdata.new[D.list]<-'D'
}
D.list<-which(wdata.new=='D')
if(length(D.list)>0){
wdata.qt.temp[D.list] <- -Inf
wdata.qt.actual.temp[D.list] <- Inf
}
#### Tests & Quarantine ####
Test.available<-vector()
Test.available<-which(wdata.qt.temp!=-Inf & wdata.tp.temp==0) # people 1) who are alive & 2) who have not tested positive
#Test.available<-Test.available[!Test.available %fin% non.cooperative.nodes]
test.ct<-vector(); test.rt<-vector(); test<-vector();
if((sum(wdata.inf.count[1:t])/N)>=(intervention.start.inf.rate/100.)){
if(t>test.x.days.later){
test.ct<-which(wdata.ct.new[[as.character(t-test.x.days.later)]] %fin% c('CT'))
test.ct<-test.ct[test.ct %fin% Test.available]
}
}
test.rt<-RT.new
test.rt<-test.rt[test.rt %fin% Test.available]
test.rt<-test.rt[!test.rt %fin% test.ct]
test.rt.all<-unique(c(test.rt.all,test.rt))
test<-unique(c(test.ct,test.rt))
wdata.test.count[t]<-length(test)
temp<-vector(); P.list<-vector(); N.list<-vector(); FP.list<-vector(); FN.list<-vector(); TP.list<-vector(); TN.list<-vector(); test.rt.tp<-vector(); test.ct.tp<-vector(); test.rt.tn<-vector(); test.ct.tn<-vector(); test.rt.tn.non.coop<-vector(); test.ct.tn.non.coop<-vector();
temp<-which(wdata.new %fin% c('Ia-L','Ip-L','Ip','Is','Ia','RT'))
P.list<-test[test %fin% temp]
P.list<-data.table(node=as.integer(P.list), status=wdata.new[P.list], rate=ifelse(wdata.new[P.list] %fin% c('Ia-L','Ip-L'),1,(FN.rate/100.)))
P.list[,fn:=rbinom(length(P.list$rate), size = 1, prob=P.list$rate)]
N.list<-test[!test %fin% temp]
N.list<-data.table(node=as.integer(N.list), fp=rbinom(length(N.list), size=1, prob=(FP.rate/100.)))
FP.list<-N.list[fp==1][['node']]
TN.list<-N.list[fp==0][['node']]
FN.list<-P.list[fn==1][['node']]
TP.list<-P.list[fn==0][['node']]
test.rt.tp<-test.rt[test.rt %fin% TP.list]
test.rt.tn<-test.rt[!test.rt %fin% TP.list]
test.rt.tn.non.coop<-test.rt.tn[test.rt.tn %in% non.cooperative.nodes]
test.ct.tp<-test.ct[test.ct %fin% TP.list]
test.ct.tn<-test.ct[!test.ct %fin% TP.list]
test.ct.tn.non.coop<-test.ct.tn[test.ct.tn %in% non.cooperative.nodes]
if(length(test.ct)>0){
if(length(test.ct.tp)>0){
if(t<=(T.max-turnaround)){
set(wdata.tp.new, i=test.ct.tp, j=as.character(t+turnaround), value='TP')
}
}
if(length(test.ct.tn.non.coop)>0){
wdata.qt.actual.temp[test.ct.tn.non.coop] <- -turnaround
}
}
if(length(test.rt)>0){
wdata.qt.temp[test.rt] <- -14
wdata.qt.actual.temp[test.rt] <- -14
if(length(test.rt.tp)>0){
if(t<=(T.max-turnaround)){
set(wdata.tp.new, i=test.rt.tp, j=as.character(t+turnaround), value='TP')
}
}
if(length(test.rt.tn.non.coop)>0){
wdata.qt.actual.temp[test.rt.tn.non.coop] <- -turnaround
}
}
rm.col<-vector();
rm.col<-colnames(wdata.tp.new)[colnames(wdata.tp.new)!='1' & (as.integer(colnames(wdata.tp.new)) < (t))]
if(length(rm.col)>0){wdata.tp.new[, (rm.col):=NULL]}
qt.nodes<-vector(); qt.nodes.real<-vector();
#qt.nodes<-which(wdata.qt.temp>=-14 & wdata.qt.temp<0)
#qt.nodes.real<-which((wdata.qt.temp>=-14 & wdata.qt.temp<0) & (wdata.qt.actual.temp!=-Inf & wdata.qt.actual.temp<0))
qt.nodes.real<-which(wdata.qt.actual.temp>=-14 & wdata.qt.actual.temp<0)
if(length(qt.nodes.real)>0){
wdata.qt.count[t]<-length(qt.nodes.real)
}
#### Contact Tracing ####
## Contact network on day t
temp.rm<-vector(); temp.rm.real<-vector(); temp.edge<-vector();
temp.rm<-which(wdata.qt.temp<0) # people who have died or are in quarantine from HA's perspective
temp.rm.real<-which(wdata.qt.actual.temp<0) # people who have died or are actually in quarantine
if(length(temp.rm)>0){
remove.edges.real[[t]]<-edge.list.undir[(node1 %fin% temp.rm.real | node2 %fin% temp.rm.real)][['edge_num']]
temp.edge<-edge.list.undir[!(edge_num %fin% remove.edges.real[[t]]),c(1,2)]
remove.edges.HA[[t]]<-edge.list.undir[(node1 %fin% temp.rm | node2 %fin% temp.rm)][['edge_num']]
}else{
temp.edge<-edge.list.undir[,c(1,2)]
}
edges.all.final.transmission[[t]]<-rbindlist(list(temp.edge,temp.edge[,c(2,1)]), use.names=FALSE)
## tracable network on day t
TP.list.for.CT<-vector();
TP.list.for.CT<-which(wdata.tp.new[[as.character(t)]]=='TP')
if(length(TP.list.for.CT)>0){
wdata.tp.temp[TP.list.for.CT]<-1
if((sum(wdata.inf.count[1:t])/N)>=(intervention.start.inf.rate/100.)){
wdata.ct.day[t]<-1
if(hops>0){
tt<-vector(); temp.rm.all.HA<-vector(); temp.rm.all.real<-vector(); edges.ct.undir<-vector(); edges.ct.all<-vector();
tt<-ifelse(t-13>1,t-13,1):(t)
temp.rm.all.real<-unlist(remove.edges.real[tt])
temp.rm.all.real<-which(tabulate(temp.rm.all.real)==length(tt)) # edges which have not appeared for entire last 14 days.
temp.rm.all.HA<-unlist(remove.edges.HA[tt])
temp.rm.all.HA<-which(tabulate(temp.rm.all.HA)==length(tt)) # edges which have not been identified by health authority for entire last 14 days.
if(length(temp.rm.all.HA)>0){
edges.ct.undir<-edge.list.undir[!(edge_num %fin% temp.rm.all.HA),c(1,2)]
}else{
edges.ct.undir<-edge.list.undir[,c(1,2)]
}
edges.ct.all<-rbindlist(list(edges.ct.undir,edges.ct.undir[,c(2,1)]), use.names=FALSE)
#edges.ct.all<-edges.ct.all[!(node1 %fin% non.cooperative.nodes[non.cooperative.nodes %fin% test.rt.all])]
multihop<-vector(); QT.available<-vector()
multihop<-contact.tracing(hops,TP.list.for.CT,edges.ct.all)
QT.available<-which(wdata.qt.temp>=0 & wdata.tp.temp==0) # people who can potentially be informed that they are in close contact with an infected person
# people 1) who are alive & 2) who are not in quarantine from HA's perspective & 3) who have not tested positive
#QT.available<-QT.available[!QT.available %fin% non.cooperative.nodes]
multihop<-multihop[multihop %fin% QT.available] # people who will comply with the health authority's request among the traced contacts
if(length(multihop)>0){
set(wdata.ct.new, i=as.integer(multihop), j=as.character(t), value='CT')
rm.col<-vector();
rm.col<-colnames(wdata.ct.new)[colnames(wdata.ct.new)!='1' & (as.integer(colnames(wdata.ct.new)) < (t-test.x.days.later))]
if(length(rm.col)>0){wdata.ct.new[, (rm.col):=NULL]}
wdata.qt.temp[multihop] <- -(14+1)
wdata.qt.actual.temp[multihop] <- -(14+1)
}
}
}
}
wdata.qt.temp<-wdata.qt.temp+1
wdata.qt.actual.temp<-wdata.qt.actual.temp+1
if(hops==0){
wdata.ct.day.cum<-cumsum(wdata.ct.day[1:t]);
if((t==90 & sum(wdata.inf.count[1:t])<40) | (t==365 & wdata.ct.day.cum[t]==0)){
wdata.inf.count[1:T.max]<-NA
wdata.test.count[1:T.max]<-NA
wdata.qt.count[1:T.max]<-NA
wdata.ct.day[1:T.max]<-NA
iteration.num<-NA
break
}else{
contact.tracing.day<-vector();
contact.tracing.day<-min(which(wdata.ct.day.cum==1))
if((contact.tracing.day+201)==t){
wdata.inf.count[t:T.max]<-NA
wdata.test.count[t:T.max]<-NA
wdata.qt.count[t:T.max]<-NA
wdata.ct.day[t:T.max]<-NA
iteration.num<-iteration
break
}
}
}else{
wdata.ct.day.cum<-cumsum(wdata.ct.day[1:t]);
contact.tracing.day<-vector();
contact.tracing.day<-min(which(wdata.ct.day.cum==1))
if((contact.tracing.day+201)==t){
wdata.inf.count[t:T.max]<-NA
wdata.test.count[t:T.max]<-NA
wdata.qt.count[t:T.max]<-NA
wdata.ct.day[t:T.max]<-NA
iteration.num<-iteration
break
}
}
}
list(dailynewinf=wdata.inf.count, dailytests=wdata.test.count, dailyquarantines=wdata.qt.count, contacttracingday=wdata.ct.day, iterationnum=iteration.num)
}
num_iteration<-150 # the number of runs
max.hops<-5
strTmp.1<-as.character(1:num_iteration)
for(k in 0:max.hops){
daily.new.infections.hop<-setNames(data.table(matrix(,nrow = T.max, ncol = num_iteration)), strTmp.1)
daily.tests.hop<-setNames(data.table(matrix(,nrow = T.max, ncol = num_iteration)), strTmp.1)
daily.quarantines.hop<-setNames(data.table(matrix(,nrow = T.max, ncol = num_iteration)), strTmp.1)
contact.tracing.day.hop<-setNames(data.table(matrix(,nrow = T.max, ncol = num_iteration)), strTmp.1)
if(k==0){
iteration.index<-rep(NA,num_iteration)
pp<-1; qq<-1;
while(pp<=num_iteration){
if(qq==(num_iteration+1) & pp==1){break}
set.seed(qq)
temp<-epidemic(qq,as.integer(k))
if(is.na(temp$iterationnum) == TRUE){
print(paste('<k>=',aaaa,' : p=',bbbb,' : PoI=', cccc, ' hop ', k, ' iteration ', qq, ' | ', temp$iterationnum, sep = ''))
qq<-qq+1
}else{
daily.new.infections.hop[[pp]] <- (temp$dailynewinf)
daily.tests.hop[[pp]] <- (temp$dailytests)
daily.quarantines.hop[[pp]] <- (temp$dailyquarantines)
contact.tracing.day.hop[[pp]]<-(temp$contacttracingday)
iteration.index[pp]<-(temp$iterationnum)
print(paste('<k>=',aaaa,' : p=',bbbb,' : PoI=', cccc, ' hop ', k, ' iteration ', qq, ' | ', temp$iterationnum, sep = ''))
qq<-qq+1
pp<-pp+1
}
rm('temp','wdata.old','wdata.new','wdata.ct.new','wdata.tp.new','wdata.qt.new','wdata.qt.temp','wdata.tp.temp','wdata.inf.count','wdata.test.count','wdata.qt.count','wdata.ct.day')
gc()
}
}
else{
if(sum(is.na(iteration.index))==num_iteration){break}
for(pp in 1:num_iteration){
set.seed(iteration.index[pp])
temp<-epidemic(iteration.index[pp],as.integer(k))
daily.new.infections.hop[[pp]] <- (temp$dailynewinf)
daily.tests.hop[[pp]] <- (temp$dailytests)
daily.quarantines.hop[[pp]] <- (temp$dailyquarantines)
contact.tracing.day.hop[[pp]]<-(temp$contacttracingday)
print(paste('<k>=',aaaa,' : p=',bbbb,' : PoI=', cccc, ' hop ', k, ' iteration ', iteration.index[pp], ' | ', temp$iterationnum, sep = ''))
rm('temp','wdata.old','wdata.new','wdata.ct.new','wdata.tp.new','wdata.qt.new','wdata.qt.temp','wdata.tp.temp','wdata.inf.count','wdata.test.count','wdata.qt.count','wdata.ct.day')
gc()
}
}
file.name.1<-paste("daily_new_infections_",k,"-hop.RData",sep="")
file.name.2<-paste("daily_tests_",k,"-hop.RData",sep="")
file.name.3<-paste("daily_quarantines_",k,"-hop.RData",sep="")
file.name.4<-paste("contact_tracing_day_",k,"-hop.RData",sep="")
save(daily.new.infections.hop, file=file.name.1, compress = T)
save(daily.tests.hop, file=file.name.2, compress = T)
save(daily.quarantines.hop, file=file.name.3, compress = T)
save(contact.tracing.day.hop, file=file.name.4, compress = T)
rm('daily.new.infections.hop','daily.tests.hop','daily.quarantines.hop','contact.tracing.day.hop')
gc()
}
file.name.5<-"iteration_index.RData"
save(iteration.index, file=file.name.5, compress = T)
print(paste('PoI=',cccc, sep = ''))
rm(list=ls()[! ls() %fin% c("cccc","mainDir.1","mainDir.6",'Vilno','edge.perc.intercluster',"intervention.start.inf.rate","FN.rate","FP.rate","turnaround",'cooperativity',
'latency.period','f.Ip_pre.to.Ip','f.Ia_pre.to.Ia','incubation.period',
'post.latency.period','f.Ip.to.Is','wait.see.period','f.Is.to.RTs',
'rec.death.period','death.rate','f.RTs.to.D','infectious.Ia.period','f.Ia.to.R','contact.tracing')])
gc() #free up memrory and report the memory usage.
}
<file_sep>Tracing and testing multiple generations of contacts to COVID-19 cases: cost-benefit tradeoffs
===================================
### Abstract
Traditional contact tracing tests the direct contacts of those who test positive. But, by the time an infected individual is tested, the infection starting from the person may have infected a chain of individuals. Hence, why should the testing stop at direct contacts, and not test secondary, tertiary contacts or even contacts further down? One deterrent in testing long chains of individuals right away may be that it substantially increases the testing load, or does it? We investigate the costs and benefits of such multi-hop contact tracing for different number of hops. Considering diverse contact networks, we show that the cost-benefit tradeoff can be characterized in terms of a single measurable attribute, the \textit{initial epidemic growth rate}. Once this growth rate crosses a threshold, multi-hop contact tracing substantially reduces the outbreak size compared to traditional tracing. Multi-hop even incurs a lower cost compared to the traditional tracing for a large range of values of the growth rate. The cost-benefit tradeoffs can be classified into three phases depending on the value of the growth rate. The need for choosing a larger number of hops becomes greater as the growth rate increases or the environment becomes less conducive toward containing the disease.
### Contact Networks

*Notes:* *p* is the rewiring probability of Watts-Strogatz networks, and *r* is the mixing parameter in data-driven network. The average degree is the average number of edges per node. The distance between a pair of nodes is the length of the shortest path between them. The diameter is the maximum value of this distance over all pairs of nodes. The average path length is the average of this distance over all pairs of nodes; only the lengths of the existing paths are considered and averaged. Clustering coefficient of a node *i*, *C<sub>i*, is defined as the ratio between the actual number of links between the neighbors of *i* and the maximum possible number of links between the neighbors of *i*. This is high if there exists a large number of edges in the neighborhood of *i*. The average clustering coefficient, *<C>*, is the average of *C<sub>i* over all nodes *i*. The average degree, average path length, and average clustering coefficient are rounded to three significant figures.
#### The raw data used to construct data-driven network was previously published in *<NAME>, <NAME>, <NAME>, <NAME>, The diffusion of microfinance. Science 341 (2013)*.
### Simulations
We consider various attributes that affect the efficacy of contact tracing, involving variations of false negative rates, false positive rates, test result turnaround times, starting times of contact tracing, and level of cooperation with contact tracing and testing. You can control the setting by entering values of interest for each code.
e.g.)
*intervention.start.inf.rate*<-0 # Starting point of contact tracing, percent (%); enter 0 if contact tracing is initiated when the first individual tests positive
*turnaround*<-1 # Turnaround times for coronavirus test results (days)
*FP.rate*<-0 # False Positive rate, percent (%)
*FN.rate*<-11 # False Negative rate, percent (%)
*cooperativity*<-100 # Cooperativity (%)
| 2f9e69ebf5a97f635023989497ab8360a3d196e9 | [
"Markdown",
"Text",
"R"
] | 4 | Text | jungyeol-kim/RSOS-contact-tracing | 8592ec5c09401db41cb253957dc57058142159c2 | abda204693ac830e63a2507af56c49d45e219e12 |
refs/heads/master | <file_sep><?php
ini_set('max_execution_time', 1000);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ERROR);
require_once 'imap-outlook.php';
/*
* imap credentials goes here
*/
function sortByUdate($a, $b) {
return $a["udate"] - $b["udate"];
}
$inboxhost = "{imap-mail.outlook.com:993/ssl}Inbox";
$senthost = "{imap-mail.outlook.com:993/ssl}Sent";
$email = "<EMAIL>"; //dummy text. I swear i dont have typo here
$emailPassword = "<PASSWORD>"; //dummy text. No typo here.
//$authhost = "{imap.gmail.com:993/imap/ssl}INBOX";
//$email = "<EMAIL>"; //dummy text. I swear i dont have typo here
//$emailPassword = "<PASSWORD>"; //dummy text. No typo here.
$sentImap = new imap($senthost, $email, $emailPassword);
$sentStreamObj = $sentImap->getMailbox();
// Get Thred Complete
$sentEmailList = $inboxEmailList = array();
$sentThread1 = $sentImap->thread();
foreach($sentThread1 as $key=>$data){
if(!($data['num'] > 18)){
$sentThread1[$key] = '';
}
}
$sentThread = array_filter($sentThread1);
$sentOverview = imap_fetch_overview($sentStreamObj,"18:*",FT_UID);
foreach($sentOverview as $data){
$data->message_id = htmlspecialchars($data->message_id);
$data->in_reply_to = htmlspecialchars($data->in_reply_to);
}
$inboxImap = new imap($inboxhost, $email, $emailPassword);
$inboxStreamObj = $inboxImap->getMailbox();
$inboxThread1 = $inboxImap->thread();
foreach($inboxThread1 as $key=>$data){
if(!($data['num'] > 2669)){
$inboxThread1[$key] = '';
}
}
$inboxThread = array_filter($inboxThread1);
//print_r($inboxThread); print_r($sentThread); die;
$inboxOverview = imap_fetch_overview($inboxStreamObj,"2669:*",FT_UID);
foreach($inboxOverview as $data){
$data->message_id = htmlspecialchars($data->message_id);
$data->in_reply_to = htmlspecialchars($data->in_reply_to);
}
$sentmail = $sentImap->getUniqueSentArr($sentThread);
if(count($sentmail)) {
foreach($sentmail as $key=>$thred)
$relationArr[]= $thred['num'];
$tempArr = implode(',',$relationArr);
$sentEmailList = imap_fetch_overview($sentStreamObj,"$tempArr",FT_UID);
foreach($sentEmailList as $data)
$data->message_id = htmlspecialchars($data->message_id);
}
$relationArr = array();
$emails = $inboxImap->getUniqueEmailArr($inboxThread);
if(count($emails)) {
foreach($emails as $key=>$thred)
$relationArr[]= $thred['num'];
$tempArr = implode(',',$relationArr);
$inboxEmailList = imap_fetch_overview($inboxStreamObj,"$tempArr",FT_UID);
foreach($inboxEmailList as $data)
$data->message_id = htmlspecialchars($data->message_id);
}
$finalarr = array();
$emailList = array_merge($sentEmailList,$inboxEmailList);
foreach($emailList as $email)
{ //echo $email->uid;
// print_r($email);echo "------------------------------------------------------";die;
//print_r($sentThread);die;
$finalarr[$email->uid] = $email;
$flag = array();
$res = $sentImap->arraySearch($sentStreamObj,$sentThread,'num',$email->uid,$flag);
if(count($res)){
$msg_id = current($res);
$msg_id = $msg_id['msg_id'];
$res1 = $inboxImap->objectArrSearch($inboxOverview,'in_reply_to',$msg_id);
$res2 = $inboxImap->arraySearch($inboxStreamObj,$inboxThread,'num',$res1,$flag);
$res2 = $res+$res2;
} else {
$res = $inboxImap->arraySearch($inboxStreamObj,$inboxThread,'num',$email->uid);
if(count($res)) {
$msg_id = current($res);
$msg_id = $msg_id['msg_id'];
$res1 = $sentImap->objectArrSearch($sentOverview,'in_reply_to',$msg_id);
$res2 = $sentImap->arraySearch($sentStreamObj,$sentThread,'num',$res1,$flag);
$res2 = $res+$res2;
}
}
$finalarr[$email->uid]->childs = $res2;
//print_r($res2);die;
/*foreach($res as $key=>$row){
$obj = $sentImap->getMailbox();
$sentImap->getmsg($obj,$key);
$html = $sentImap->gethtml();
echo $html;
echo "kkkkkkkkkkkk";
}
foreach($res2 as $key=>$row){
$obj = $inboxImap->getMailbox();
$inboxImap->getmsg($obj,$key);
$html = $inboxImap->gethtml();
echo $html;
echo "llllllllll";
}die;*/
//print_r($res);print_r($res2);die;print_r($res2);print_r($inboxOverview);die;
}
foreach($finalarr as $key=>$result){
uasort($result->childs, "sortByUdate");
}
$arraydel = array();
$keyexist = array();
foreach($finalarr as $key=>$result){
foreach($result->childs as $key1=>$data){
if (array_key_exists($key1,$result->childs))
{
$keyexist[$key1]++;
}
}
}
foreach($keyexist as $key2=>$temp){
if($temp > 1){
$finalarr[$key2] = '';
}
}
print_r(array_filter($finalarr));
die;<file_sep><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//ini_set("SMTP","ssl://smtp.gmail.com");
//for demo purposes we are gonna send an email to ourselves
$from = "<EMAIL>";
$to = "<EMAIL>";
//$to = "<EMAIL>";
//$from = "<EMAIL>";
$envelope = array("from"=>$from,"to"=>$to);
$subject = "Testing One";
$htmlmsg = "
First mail compose.
";
$headers = "From: ".$from."\r\n".
"Reply-To: ".$from."\r\n";
//$headers .= "MIME-Version: 1.0\r\n";
//$headers .= "Content-Type: text/plain; charset=utf-8\r\n";
//$headers .= "X-Priority: 1\r\n";
$cc = '';
$bcc = '';
$return_path = $from;
$body = array();
//send the email using IMAP
$part1["type"] = 'TYPETEXT';
$part1["subtype"] = "plain";
$part2["type"] = 'TYPEAPPLICATION';
$part2["encoding"] = 'ENCBINARY';
$part2["subtype"] = "octet-stream";
$part2["description"] = '';
$part2["contents.data"] = '';
$part3["type"] = 'TYPETEXT';
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = $htmlmsg;
$body[1] = $part3;
$body[2] = $part2;
$body[3] = $part3;
$message = imap_mail_compose($envelope, $body);
list($msgheader, $msgbody) = preg_split("#\n\s*\n#Uis", $message);
//s$a = mail($to, $subject, $msgbody, $headers);
imap_mail($to, $subject, $msgbody, $headers);
//var_dump(imap_last_error());
//echo "tst Email sent!<br />";
//die;
// connect to the email account
$mbox = imap_open("{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail", $from, "Prospus1");
var_dump(imap_last_error());
// save the sent email to your Sent folder by just passing a string composed
// of the entire message + headers.
// Notice the 'r' format for the date function, which formats the date correctly for messaging.
imap_append($mbox, "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail",
"From: ".$from."\r\n".
"To: ".$to."\r\n".
"Subject: ".$subject."\r\n".
"Date: ".date("r", strtotime("now"))."\r\n".
"\r\n".
$htmlmsg.
"\r\n"
);
var_dump(imap_last_error());
//echo "Message saved to Send folder!<br />";
$some = imap_search($mbox, 'SUBJECT "'.$subject.'"', SE_UID);
print_r($some);
imap_close($mbox);
?><file_sep><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//ini_set("SMTP","ssl://smtp.gmail.com");
//for demo purposes we are gonna send an email to ourselves
//$from = "<EMAIL>";
//$to = "<EMAIL>";
$to = "<EMAIL>";
$from = "<EMAIL>";
$envelope = array("from"=>$from,"to"=>$to);
$headers = "From: ".$from."\r\n".
"Reply-To: ".$from."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed\"\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-MSMail-Priority: Normal\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
$subject = "attachment test Multiple Kunal 334";
$filename = ["Koala.jpg"];
$envelope["from"] = $from;
$envelope["to"] = $to;
$envelope["subject"] = $subject;
$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";
$part2["type"] = TYPETEXT;
$part2["subtype"] = "plain";
$part2["description"] = "imap_mail_compose() function";
$part2["contents.data"] = "message 1:xxxxxxxxxxxxxxxxxxxxxxxxxx";
$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "Example";
$part3["contents.data"] = "message 2:yyyyyyyyyyyyyyyyyyyyyyyyyy";
$i = 4;
foreach($filename as $file){
$filename = $file;
$file_handle = fopen($filename, 'r+');
${"part".$i}["type"] = TYPEAPPLICATION;
${"part".$i}["encoding"] = ENCBASE64;
${"part".$i}["subtype"] = "octet-stream";
${"part".$i}["description"] = 'Test';
${"part".$i}['disposition.type'] = 'attachment';
${"part".$i}['disposition'] = array('filename' => $filename);
${"part".$i}['type.parameters'] = array('name' => $filename);
${"part".$i}["contents.data"] = chunk_split(base64_encode(file_get_contents($filename)));
$i++;
}
$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;
for($j= 4; $j <= $i-1; $j ++){
$body[$j] = ${"part".$j};
}
$msg = imap_mail_compose($envelope, $body);
//list($msgheader, $msgbody) = preg_split("\r\n|\r|\n", $msg, 2);
imap_mail($to, $subject, $msg, $headers);
$mbox = imap_open("{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail", $from, "Prospus1");
var_dump(imap_last_error());
$mailbox = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
if (imap_append($mbox, $mailbox, $msg) === false) {
echo imap_last_error() . "\n";
echo "TEST FAILED : could not append new message to mailbox '{$mailbox}'\n";
exit;
}
// connect to the email account
// save the sent email to your Sent folder by just passing a string composed
// of the entire message + headers.
// Notice the 'r' format for the date function, which formats the date correctly for messaging.
//imap_append($mbox, "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail",$msg);
//var_dump(imap_last_error());
//echo "Message saved to Send folder!<br />";
$some = imap_search($mbox, 'SUBJECT "'.$subject.'"', SE_UID);
print_r($some);
imap_close($mbox);
?><file_sep><?php
/*
* Imap
* @author Abhijit <<EMAIL>> *
*/
Class imap {
private $mailbox;
public $charset = "US-ASCII";
public $htmlmsg;
public $plainmsg;
public $attachments = array();
public $fromaddress;
public $toaddress;
public $subject;
public $Date;
public $MailDate;
public $savedir = __DIR__ . '/imap-dump/';
public $save_into_db = TRUE;
/*
* database details
*/
public $serverIP = "localhost";
public $userName = "****";
public $userPassword = "********";
public $databaseName = "db_name";
public function __construct($authhost, $email, $emailPassword) {
$stream = imap_open($authhost, $email, $emailPassword);
if (FALSE === $stream) {
throw new Exception('Connect failed: ' . imap_last_error());
}
$this->mailbox = $stream;
// $boxes = imap_list($stream, $authhost, '*');
// echo "<pre>";
// print_r($boxes);
}
public function getMailbox() {
return $this->mailbox;
}
public function gethtml() {
return $this->htmlmsg;
}
public function getLastThred($relationArr) {
foreach ($relationArr as $key => $thred) {
echo $relationArr[$key]['num'];
echo '<br>';
}
}
public function fetch($uid) {
echo '<pre>';
$result = imap_fetch_overview($this->mailbox, "$uid:*", FT_UID);
if (FALSE === $result) {
throw new Exception('Search failed: ' . imap_last_error());
}
foreach ($result as $data) {
$data->message_id = htmlspecialchars($data->message_id);
$data->in_reply_to = htmlspecialchars($data->in_reply_to);
}
print_r($result);
die;
}
public function thread() {
echo '<pre>';
$mails = imap_thread($this->mailbox, 1);
if (FALSE === $mails) {
throw new Exception('Search failed: ' . imap_last_error());
}
foreach ($mails as $key => $thred) {
$tempArr = explode('.', $key);
$index = $tempArr[0];
$key = $tempArr[1];
$relationArr[$index][$key] = $thred;
}return $relationArr;
//print_r($relationArr);
die;
}
public function fetchbody($msg_number, $part_number) {
echo '<pre>';
$mails = imap_fetchbody($this->mailbox, $msg_number, $part_number);
if (FALSE === $mails) {
throw new Exception('Search failed: ' . imap_last_error());
}
print_r($mails);
die;
}
public function sendreply($uid, $body) {
$gmail_address = '<EMAIL>';
$to = '<EMAIL>';
$subject = 'Re: One';
$body = 'Teststetstetstesttsetstetstestetstetsetstetsetsetstestetst';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: <' . $gmail_address . '>' . " \r\n" .
'Reply-To: <' . $gmail_address . '>' . "\r\n" .
'Subject: ' . $subject . "\r\n" .
'To: ' . $to . "\r\n" .
'In-Reply-To: <<EMAIL>=<EMAIL>>' . "\r\n" .
'References: <<EMAIL>=<EMAIL>> <<EMAIL>> <<EMAIL>> <<EMAIL>> <<EMAIL>>' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$result = imap_mail($to, $subject, $body, $headers);
var_dump($result);
}
/**
* @param string $criteria
* @param int $options
* @param int $this->charset
* @return IMAPMessage[]
* @throws Exception
*/
public function search($criteria, $options = NULL, $charset = NULL) {
$mails = imap_search($this->mailbox, $criteria, SE_UID, $this->charset);
if (FALSE === $mails) {
throw new Exception('Search failed: ' . imap_last_error());
}
if ($this->save_into_db) {
$sql = new MySQLiQuery($this->serverIP, $this->userName, $this->userPassword, $this->databaseName);
}
foreach ($mails as $mail) {
echo '$mail UID - ' . $mail . '<br>';
$attachments_temp = array();
$this->getmsg($this->mailbox, $mail);
foreach ($this->attachments as $key => $value) {
$savepath = $this->savedir . $key;
file_put_contents($savepath, $value);
$attachments_temp[] = $savepath;
}
if ($this->save_into_db) {
$queryResults = $sql->insert(
"mails", array("msg_uid", "charset", "fromaddress", "toaddress", "Date", "MailDate", "subject", "htmlmsg", "plainmsg", "attachments"), array($mail, $this->charset, $this->fromaddress, $this->toaddress, date("Y-m-d H:i:s", strtotime($this->Date)), date("Y-m-d H:i:s", strtotime($this->MailDate)), $this->subject, $this->htmlmsg, $this->plainmsg, json_encode($attachments_temp)), MySQLiQuery::HIGH_PRIORITY
);
echo $queryResults . " mail successfully saved in to db:)";
}
echo "--------------------------------------------" . "<br/>";
echo "Email Charset :" . $this->charset . "<br/>";
echo "Date :" . $this->Date . "<br/>";
echo "MailDate :" . $this->MailDate . "<br/>";
echo "From :" . $this->fromaddress . "<br/>";
echo "To :" . $this->toaddress . "<br/>";
echo "Subject :" . $this->subject . "<br/>";
if ($this->plainmsg != "") {
echo "Plain Message" . $this->charset . "<br/>";
}
if ($this->htmlmsg != "") {
echo "HTML Message" . $this->htmlmsg . "<br/>";
}
if (!empty($this->attachments)) {
echo "Attachments :";
foreach ($this->attachments as $key => $value) {
echo $key . "<br/>";
}
}
echo "--------------------------------------------" . "<br/>";
}
}
public function getmsg($mbox, $mid) {
// HEADER
$mid = imap_msgno($mbox, $mid);
$h = imap_header($mbox, $mid);
// added code here to get date, from, to, cc, subject...
$this->fromaddress = $h->fromaddress;
$this->toaddress = $h->toaddress;
$this->subject = $h->subject;
$this->Date = $h->Date;
$this->MailDate = $h->MailDate;
// BODY
$s = imap_fetchstructure($mbox, $mid);
if (!$s->parts) // simple
$this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number
else { // multipart: cycle through each part
foreach ($s->parts as $partno0 => $p)
$this->getpart($mbox, $mid, $p, $partno0 + 1);
}
}
function getpart($mbox, $mid, $p, $partno) {
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
// DECODE DATA
$this->htmlmsg = '';
$data = ($partno) ?
imap_fetchbody($mbox, $mid, $partno) : // multipart
imap_body($mbox, $mid); // simple
// Any part may be encoded, even plain text messages, so check everything.
if ($p->encoding == 4)
$data = quoted_printable_decode($data);
elseif ($p->encoding == 3)
$data = base64_decode($data);
// PARAMETERS
// get all parameters, like charset, filenames of attachments, etc.
$params = array();
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if ($p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
// ATTACHMENT
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ($params['filename'] || $params['name']) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename']) ? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
$this->attachments[$filename] = $data; // this is a problem if two files have same name
}
// TEXT
if ($p->type == 0 && $data) {
// Messages may be split in different parts because of inline attachments,
// so append parts together with blank row.
if (strtolower($p->subtype) == 'plain')
$this->plainmsg .= trim($data) . "\n\n";
else
$this->htmlmsg .= $data . "<br><br>";
$this->charset = $params['charset']; // assume all parts are same charset
}
// EMBEDDED MESSAGE
// Many bounce notifications embed the original message as type 2,
// but AOL uses type 1 (multipart), which is not handled here.
// There are no PHP functions to parse embedded messages,
// so this just appends the raw source to the main message.
elseif ($p->type == 2 && $data) {
$this->plainmsg .= $data . "\n\n";
}
// SUBPART RECURSION
if ($p->parts) {
foreach ($p->parts as $partno0 => $p2)
$this->getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1)); // 1.2, 1.2.1, etc.
}
}
public function close() {
imap_expunge($this->mailbox);
imap_close($this->mailbox);
}
public function getUniqueEmailArr($arr){
$res = array();
foreach($arr as $row)
{
if($row['branch']){
$isreplytrue = $this->checkforreplyid($row['num']);
if(!$isreplytrue)
$res[] = $row;
}
if($row['branch']==0 && $row['next']==0)
$last = $row;
}
array_push($res,$last);
return $res;
}
public function getUniqueSentArr($arr){
$res = array();
foreach($arr as $row)
{
if($row['branch'] && $row['next'])
{
$isreplytrue = $this->checkforreplyid($row['num']);
if(!$isreplytrue)
$res[] = $row;
}
if($row['branch'] && !$row['next'])
{
$isreplytrue = $this->checkforreplyid($row['num']);
if(!$isreplytrue)
$res[] = $row;
}
if($row['branch']==0 && $row['next']==0)
$last = $row;
}
array_push($res,$last);
return $res;
}
public function checkforreplyid($uid){
$result = imap_fetch_overview($this->mailbox, "$uid", FT_UID);
if (FALSE === $result) {
throw new Exception('Search failed: ' . imap_last_error());
}
foreach ($result as $data) {
$data->in_reply_to = htmlspecialchars($data->in_reply_to);
}
$res = 0;
if($result[0]->in_reply_to !== '') {
$res = 1;
}
return $res;
}
public function arraySearch($sentImap,$arr,$index,$val,$flag = array(),$type)
{
foreach($arr as $key=>$row){
if($row[$index]==$val){
//print_r($row);die;
if($row['next'] && !$row['branch']){
static $i =0;
$msg_id = $this->fetchMessageId($sentImap,$row['num'],$type);
$flag[$row['num']] = $msg_id;
$next = $row['next'];
$i++;
$msg_id = $this->fetchMessageId($sentImap,$arr[$next]['num'],$type);
$flag[$arr[$next]['num']] = $msg_id;
if($arr[$next]['next'] == 0 && $arr[$next]['branch'] == 0)
{
return $flag;
} else {
return $this->arraySearch($sentImap,$arr,$index,$arr[$next]['num'],$flag,$type);
}
} else {
$msg_id = $this->fetchMessageId($sentImap,$row['num'],$type);
$flag[$row['num']] = $msg_id;
for($i=$key+1;$i<$row['branch'];$i++)
{
if($arr[$i]['branch'] == 0){
$msg_id = $this->fetchMessageId($sentImap,$arr[$i]['num'],$type);
$flag[$arr[$i]['num']] = $msg_id;
}
}
}
break;
}
}
return $flag;
}
public function fetchMessageId($sentImap,$uid,$type)
{
$res = array();
$result = imap_fetch_overview($sentImap, "$uid", FT_UID);
if (FALSE === $result) {
throw new Exception('Search failed: ' . imap_last_error());
}
foreach ($result as $data) {
$data->message_id = htmlspecialchars($data->message_id);
}
$res['msg_id'] = $result[0]->message_id;
$res['type'] = $type;
$res['udate'] = $result[0]->udate;
$this->getmsg($sentImap, $uid);
//$res['html'] = $this->gethtml();
return $res;
}
public function objectArrSearch($arr,$index,$val)
{
$flag = 0;
foreach($arr as $key=>$row){
if($row->$index==$val){
$flag = $row->uid;
break;
}
}
return $flag;
}
}<file_sep><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//ini_set("SMTP","ssl://smtp.gmail.com");
//for demo purposes we are gonna send an email to ourselves
$from = "<EMAIL>";
$to = "<EMAIL>";
//$to = "<EMAIL>";
//$from = "<EMAIL>";
$envelope = array("from"=>$from,"to"=>$to);
$subject = "Subject For New";
$htmlmsg = "
This is testing email Subject For New Kunal Reply via Code.
";
// In-Reply-To - This contain the message id of the message on which you want to reply.
$headers = "From: ".$from."\r\n".
"Reply-To: ".$from."\r\n".
'Subject: ' . $subject . "\r\n" .
'In-Reply-To: <<EMAIL>=<EMAIL>>' . "\r\n" .
'References: <<EMAIL>>' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
//$headers .= "MIME-Version: 1.0\r\n";
//$headers .= "Content-Type: text/plain; charset=utf-8\r\n";
//$headers .= "X-Priority: 1\r\n";
$cc = '';
$bcc = '';
$return_path = $from;
$body = array();
//send the email using IMAP
$part1["type"] = 'TYPETEXT';
$part1["subtype"] = "plain";
$part2["type"] = 'TYPEAPPLICATION';
$part2["encoding"] = 'ENCBINARY';
$part2["subtype"] = "octet-stream";
$part2["description"] = '';
$part2["contents.data"] = '';
$part3["type"] = 'TYPETEXT';
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = $htmlmsg;
$body[1] = $part3;
$body[2] = $part2;
$body[3] = $part3;
$message = imap_mail_compose($envelope, $body);
list($msgheader, $msgbody) = preg_split("#\n\s*\n#Uis", $message);
//s$a = mail($to, $subject, $msgbody, $headers);
imap_mail($to, $subject, $msgbody, $headers);
//var_dump(imap_last_error());
//echo "tst Email sent!<br />";
//die;
// connect to the email account
$mbox = imap_open("{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail", $from, "Prospus1");
var_dump(imap_last_error());
// save the sent email to your Sent folder by just passing a string composed
// of the entire message + headers.
// Notice the 'r' format for the date function, which formats the date correctly for messaging.
imap_append($mbox, "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail",
"From: ".$from."\r\n".
"To: ".$to."\r\n".
'In-Reply-To: <<EMAIL>=<EMAIL>>' . "\r\n" .
"Subject: ".$subject."\r\n".
"Date: ".date("r", strtotime("now"))."\r\n".
"\r\n".
$htmlmsg.
"\r\n"
);
var_dump(imap_last_error());
//echo "Message saved to Send folder!<br />";
$some = imap_search($mbox, 'SUBJECT "'.$subject.'"', SE_UID);
print_r($some);
imap_close($mbox);
?><file_sep># emailDemo
emailDemo
| fbe95743b3426826a62804e6a4555da239558ff6 | [
"Markdown",
"PHP"
] | 6 | PHP | prospusindia/emailDemo | 93b99395e5142cb5b6bafaf8727598bcebdd4a9d | 7e7b2d47e16ef8c38380bba138a2a8e5328ac337 |
refs/heads/master | <repo_name>Anushma/django-visits<file_sep>/visits/views.py
import json
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods
from .models import VisitCount
from .services import update_visit_count
@require_http_methods(["POST"])
def count_visit_ajax(request):
""" add 1 visit if everything is OK, cf.update_visit_count """
if not request.is_ajax():
raise Http404()
visit_count = get_object_or_404(VisitCount, id=request.POST.get('visit_count_id'))
update_visit_count(request, visit_count)
return HttpResponse(json.dumps({'status': True}), mimetype="application/json")<file_sep>/visits/templatetags/visits_tags.py
from django import template
from django.contrib.contenttypes.models import ContentType
from visits.models import VisitCount
register = template.Library()
@register.inclusion_tag(file_name="visits/includes/count_visit.html", takes_context=True)
def count_visit_ajax(context, item):
""" prepare the Ajax call to count the visit """
item_type = ContentType.objects.get_for_model(item)
visit_count, created = VisitCount.objects.get_or_create(
item_type=item_type,
item_id=item.id
)
return {'visit_count': visit_count}<file_sep>/README.md
django-visit
============
- Really simple app to count the visits on any Django Model.
- This is not meant to replace any proper tracking analytics tool.
- This app is useful to setup really simple "most popular" widgets.
It's a simplified fork of: https://github.com/thornomad/django-hitcount with 2 main differences:
- the visits/hits are not saved
- I've only kept the AJAX option
INSTALL:
--------
`pip install -e git+https://github.com/FrancoisConstant/django-visits#egg=visits`
Set-up:
-------
1.Add it to your "INSTALLED_APPS" settings:
INSTALLED_APPS = (
...
'visits',
...
)
TODO
----
* doc
* tests
* 2.Optionally, add a column to cache the result on the concerned model:
* 3.migrate
* 4.add tag in template<file_sep>/visits/models.py
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class VisitCount(models.Model):
# NUMBER OF VISITS
visit_count = models.IntegerField(default=0, help_text="Total number of visits of item")
# ITEM (any Model)
item_type = models.ForeignKey(ContentType, related_name="visit_count")
item_id = models.PositiveIntegerField()
item = GenericForeignKey('item_type', 'item_id')
# TIMESTAMPS
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ['item_type', 'item_id']
verbose_name = "Visit Count"
verbose_name_plural = "Visits Counts"
ordering = ['item_type']
def __unicode__(self):
return u'Visit Count - {0}'.format(self.item.__unicode__())
def increase_visit_count(self, by=1, commit=False):
self.visit_count += by
if commit:
self.save()
if hasattr(self.item, 'visit_count'):
self.item.visit_count = self.visit_count
if commit:
self.item.save()
class BlacklistedIP(models.Model):
# BLACKLISTED IP
ip = models.CharField(max_length=40, unique=True)
# TIMESTAMPS
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Blacklisted IP"
verbose_name_plural = "Blacklisted IPs"
def __unicode__(self):
return unicode(self.ip)
class BlacklistedUserAgent(models.Model):
# BLACKLISTED USER AGENT
user_agent = models.CharField(max_length=255, unique=True)
# TIMESTAMPS
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Blacklisted User Agent"
verbose_name_plural = "Blacklisted User Agents"
def __unicode__(self):
return unicode(self.user_agent)<file_sep>/visits/admin.py
from django.contrib import admin
from visits.models import VisitCount, BlacklistedIP, BlacklistedUserAgent
class VisitCountAdmin(admin.ModelAdmin):
list_display = ('item', 'visit_count', 'created_at')
list_filter = list()
list_editable = list()
search_fields = list()
ordering = ["item_type", "-visit_count"]
prepopulated_fields = {}
fieldsets = [
(None, {
'fields': (
'visit_count',
),
}),
]
class BlacklistedIPAdmin(admin.ModelAdmin):
pass
class BlacklistedUserAgentAdmin(admin.ModelAdmin):
pass
admin.site.register(VisitCount, VisitCountAdmin)
admin.site.register(BlacklistedIP, BlacklistedIPAdmin)
admin.site.register(BlacklistedUserAgent, BlacklistedUserAgentAdmin)
<file_sep>/visits/services.py
import re
from visits.models import BlacklistedIP, BlacklistedUserAgent
def update_visit_count(request, visit_count):
"""
Evaluates a request, add a visit to the corresponding item counter if the request is not blacklisted.
"""
if not _is_blacklisted(request):
visit_count.increase_visit_count(commit=True)
def _is_blacklisted(request):
ip = _get_ip(request)
user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
return bool(
BlacklistedIP.objects.filter(ip__exact=ip) or \
BlacklistedUserAgent.objects.filter(user_agent__exact=user_agent)
)
# this is not intended to be an all-knowing IP address regex
IP_RE = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
def _get_ip(request):
"""
Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy will put the
REMOTE_ADDR into HTTP_X_FORWARDED_FOR. This will handle pulling back the
IP from the proper place.
**NOTE** This function was taken from django-tracking (MIT LICENSE)
http://code.google.com/p/django-tracking/
"""
# if neither header contain a value, just use local loopback
ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '127.0.0.1'))
if ip_address:
# make sure we have one and only one IP
try:
ip_address = IP_RE.match(ip_address)
if ip_address:
ip_address = ip_address.group(0)
else:
# no IP, probably from some dirty proxy or other device
# throw in some bogus IP
ip_address = '10.0.0.1'
except IndexError:
pass
return ip_address<file_sep>/visits/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('visits.views',
url(r'^visits/add/$', 'count_visit_ajax', name='count-visit-ajax'),
) | 00511cb8883ad4b93baa24a637e387598fd9805c | [
"Markdown",
"Python"
] | 7 | Python | Anushma/django-visits | 52854cf01eb98c4774f82a8c02e1a48c128f35ae | 4b3cdb790d51bfeea71336cb7e1ca7652efa6689 |
refs/heads/master | <repo_name>SobiaSafdar/ci_auth<file_sep>/README.md
# ci_auth
aa
<file_sep>/application/views/auth/login.php
<?php include 'header.php'; ?>
<h1><?php echo lang('login_heading');?></h1>
<p><?php echo lang('login_subheading');?></p>
<div id="infoMessage"><?php echo $message;?></div>
<?php echo form_open("auth/login");?>
<p>
<?php echo lang('login_identity_label', 'identity');?>
<?php echo form_input($identity);?>
</p>
<p>
<?php echo lang('login_password_label', 'password');?>
<?php echo form_input($password);?>
</p>
<p>
<?php echo lang('login_remember_label', 'remember');?>
<?php echo form_checkbox('remember', '1', FALSE, 'id="remember"');?>
</p>
<p><?php echo form_submit('submit', lang('login_submit_btn'));?></p>
<?php echo form_close();?>
<p><a href="forgot_password"><?php echo lang('login_forgot_password');?></a></p>
<div class="login-box">
<hr>
<div class="input-box">
<div class="row">
<div class="col-md-8 col-md-offset-2 col-xs-10 col-xs-offset-1">
<?php echo form_open("auth/login");?>
<div class="input-group form-group">
<span class="input-group-addon"><i class='fa fa-user'></i></span>
<?php echo form_input($identity,'form-control');?></div>
<div class="input-group form-group">
<span class="input-group-addon"><i class='fa fa-key'></i></span>
<?php echo form_input($password);?>
</div>
<h5>
<?php echo lang('login_remember_label', 'remember');?>
<?php echo form_checkbox('remember', '1', FALSE, 'id="remember"');?> Forget Password?</h5>
<div class="form-group">
<button type="submit" class="btn btn-block btn-submit pull-right" name="submit">Submit</button>
</div>
<?php echo form_close();?>
</div>
<!-- col -->
</div>
<!-- row -->
<div class="row">
<bR><br>
</div>
</div>
<?php include 'footer.php'; ?>
<file_sep>/application/views/auth/header.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/font-awesome.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<link rel="stylesheet" href="<?php echo base_url(); ?>css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body> | ec4320ca028f57732832eb1564415b024f747339 | [
"Markdown",
"PHP"
] | 3 | Markdown | SobiaSafdar/ci_auth | 52407d73b44c6606449a07a431fcef92d8f93407 | d0be6ced453304ccea129a72eeb007c2cacf8368 |
refs/heads/master | <repo_name>ryanyu104/reactql<file_sep>/src/queries/getCount.ts
// Get local count state
// ----------------------------------------------------------------------------
// IMPORTS
/* NPM */
// GraphQL tag library, for creating GraphQL queries from plain
// template text
import gql from "graphql-tag";
// ----------------------------------------------------------------------------
// GraphQL query for retrieving the current count from local state
export default gql`
{
state @client {
count
}
}
`;
<file_sep>/src/global/styles.ts
/* tslint:disable no-unused-expression */
// Global styles
/*
Import this file for side-effects -- by default, this does two things:
1. Importing `styles.global.scss` will tell Webpack to generate a `main.css`
which is automatically included along with our SSR / initial HTML. This
is for processing CSS through the SASS/LESS -> PostCSS pipeline.
2. Using Styled-Component's `injectGlobal`
/*
// ----------------------------------------------------------------------------
// IMPORTS
/* NPM */
import { injectGlobal } from "@/lib/styledComponents";
/* Local */
// Import global SASS styles that you want to be rendered into the
// resulting `main.css` file included with the initial render. If you don't
// want a CSS file to be generated, you can comment out this line
import "./styles.global.scss";
// ----------------------------------------------------------------------------
// Inject Styled-Components output onto the page. By default, this is blank --
// you can add global styles to the template tags below
injectGlobal``;
<file_sep>/src/mutations/incrementCount.ts
// Add 1 to the counter in local state
// ----------------------------------------------------------------------------
// IMPORTS
/* NPM */
// GraphQL tag library, for creating GraphQL queries from plain
// template text
import gql from "graphql-tag";
// ----------------------------------------------------------------------------
// GraphQL query for retrieving the current count from local state
export default gql`
mutation IncrementCount {
incrementCount @client {
count
}
}
`;
<file_sep>/Dockerfile
FROM node:10.9-alpine
ENV NPM_CONFIG_LOGLEVEL notice
# Install NPM packages
WORKDIR /app
ADD package*.json ./
RUN npm i
ADD . .
# Build
RUN npm run build
EXPOSE 3000
CMD npm run production
<file_sep>/src/lib/styledComponents.ts
// @ts-ignore
// Export the `styled-component` lib with theme definitions
// ----------------------------------------------------------------------------
// IMPORTS
/* NPM */
import { ComponentClass } from "react";
import * as styledComponents from "styled-components";
/* Local */
import { ITheme } from "@/themes/interface";
// ----------------------------------------------------------------------------
export interface IClassNameProps {
className: string;
}
const {default: styled } = styledComponents as styledComponents.ThemedStyledComponentsModule<ITheme>;
const css = styledComponents.css;
const injectGlobal = styledComponents.injectGlobal;
const keyframes = styledComponents.keyframes;
const ThemeProvider = styledComponents.ThemeProvider as ComponentClass<styledComponents.ThemeProviderProps<ITheme>>;
export {
css,
keyframes,
injectGlobal,
ITheme,
ThemeProvider,
};
export default styled;
<file_sep>/types/globals.d.ts
declare var SERVER: boolean;<file_sep>/src/themes/interface.ts
// Theme interface
export interface ITheme {
colors: {
orange: string;
};
}
<file_sep>/index.ts
// Run the right environment...
// Catch CTRL/CMD+C interrupts cleanly
process.on("SIGINT", () => {
process.exit();
});
// Build mode?
let script: string;
if (process.env.npm_lifecycle_event === "build") {
script = "build";
} else {
script = process.env.NODE_ENV === "production" ? "production" : "development";
}
// Start the script
require(`./src/runner/${script}`);
<file_sep>/src/queries/getHackerNewsTopStories.ts
// Get the top stories from HackerNews
// ----------------------------------------------------------------------------
// IMPORTS
/* NPM */
// GraphQL tag library, for creating GraphQL queries from plain
// template text
import gql from "graphql-tag";
// ----------------------------------------------------------------------------
// GraphQL query for retrieving Hacker News top-stories from the
// https://graphqlhub.com/playground sample server endpoint
export default gql`
{
hn {
topStories {
id
title
url
}
}
}
`;
| ddde65ed597297e0a4dd6f1040a4794ab139321e | [
"JavaScript",
"TypeScript",
"Dockerfile"
] | 9 | TypeScript | ryanyu104/reactql | 243f61f8b76c53cd9db0df5d82ab965aa9d37322 | cbe9f56119f19b7da9f03ab94fd4f88b1d8abd51 |
refs/heads/master | <repo_name>Orangem21/gohttp<file_sep>/goroutine_4.go
//有缓冲的通道
package main
import(
"sync"
"time"
"fmt"
"math/rand"
)
const (
numberGoroutine = 4 //goroutine 数量
taskLoad = 10 //任务数量
)
var wg sync.WaitGroup
func init(){
rand.Seed(time.Now().Unix())
}
func main() {
//创建有缓冲的通道
tasks := make(chan string, taskLoad)
//启动goroutine来启动工作
wg.Add(numberGoroutine)
for gr := 1; gr <= numberGoroutine; gr ++ {
go worker(tasks, gr)
}
for post := 2; post <= taskLoad; post ++ {
tasks <- fmt.Sprintf("Tasks:%d", post)
}
//当所有工作处理完毕的时候关闭通道
close(tasks)
wg.Wait()
}
//worker 作为goroutine 启动处理
func worker(tasks chan string,worker int){
defer wg.Done()
for {
//等待分配工作
task,ok := <- tasks
if !ok {
fmt.Printf("Worker:%d : Shutting Down\n",worker)
return
}
fmt.Printf("Worker:%d : Started %s \n",worker,task)
sleep:=rand.Int63n(100)
time.Sleep(time.Duration(sleep)*time.Millisecond)
fmt.Printf("Worker:%d Complated %s \n",worker,task)
}
}
<file_sep>/gohttp.go
package gohttp
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/google/go-querystring/query"
)
// 定义常量
const (
contentType = "Content-Type"
jsonContentType = "application/json"
formContentType = "application/x-www-form-urlencoded"
)
//定义超时时间
// DefaultTimeout defines the request timeout limit, avoiding client hanging when the
// remote server does not responde.
const DefaultTimeout = 3 * time.Second
// debugEnv is the environment variable that toggles debug mode.
// 1 means turn on debug mode, 0 or any other value(empty value) means turn off debug mode
//定义bug 模式
const debugEnv = "GOHTTP_DEBUG"
//基本验证类
type basicAuth struct {
username string
password string
}
// fileForm wraps one file part of multiple files upload
type fileForm struct {
fieldName string
filename string
file *os.File
}
// GoResponse wraps the official `http.Response`, and provides more features.
// The main function is to parse resp body for users.
// In the future, it can gives more information, like request elapsed time,
// redirect history etc.
//重新定义 http.Response
type GoResponse struct {
*http.Response
}
// AsString returns the response data as string
// An error wil bw returned if the body can not be read as string
func (resp *GoResponse) AsString() (string, error) {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), nil
}
//添加了一个方法
//resp.AsString(HttpResponse.Body)
// AsBytes return the response body as byte slice
// An error will be returned if the body can not be read as bytes
func (resp *GoResponse) AsBytes() ([]byte, error) {
return ioutil.ReadAll(resp.Body)
}
// AsJSON parses response body to a struct
// Usage:
// user := &User{}
// resp.AsJSON(user)
// fmt.Printf("%s\n", user.Name)
func (resp *GoResponse) AsJSON(v interface{}) error {
data, err := resp.AsBytes()
if err != nil {
return err
}
return json.Unmarshal(data, v)
}
// Client is the main struct that wraps net/http.
// It stores all necessary data for the request to be sent, include request method, url, body.
type Client struct {
c *http.Client
// query string, query string is a key-value pair follows a
// url path, and they are encoded in url to escape special characters
query map[string]string
// query string from struct data
queryStructs []interface{}
// http headers
headers map[string]string
// base url, this is sheme + host, but can be any valid url
url string
// additional url path, it will be joined with `url` to get the final
// request url
path string
// request body, it should be readble. Body is used in `POST`, `PUT` method to send data
// to server. How body should be parsed is in the `Content-Type` header.
// For example, `application/json` means the body is a valid json string,
// `application/x-www-form-urlencoed` means the body is form data, and it is encoded same as url.
body io.Reader
// basic authentication, just plain username and password
auth basicAuth
// cookies store request cookie, and send it to server
cookies []*http.Cookie
// files represents an array of `os.File` instance, it is used to
// upload files to server
files []*fileForm
// proxy stores proxy url to use. If it is empty, `net/http` will try to load proxy configuration
// from environment variable.
proxy string
// timeout sets the waiting time before request is finished
// If request exceeds the time, error will be returned.
// The default value zero means no timeout, which is what the `net/http` DefaultClient does.
timeout time.Duration
// TLSHandshakeTimeout limits the time spent performing TLS handshake
tlsHandshakeTimeout time.Duration
// how many attempts will be used before give up on error
retries int
// transport is the actual worker that carries http request, and send it out.
transport *http.Transport
// debug toggles debug mode of gohttp.
// It is useful when user wants to see what is going on behind the scene.
debug bool
// logger determines how the log is printed
logger *log.Logger
}
// DefaultClient provides a simple usable client, it is given for quick usage.
// For more control, please create a client manually.
var DefaultClient = New()
// New returns a new GoClient with default values
func New() *Client {
t := &http.Transport{}
debug := os.Getenv(debugEnv) == "1"
logger := log.New(os.Stderr, "[gohttp] ", log.Ldate|log.Ltime|log.Lshortfile)
return &Client{
query: make(map[string]string),
queryStructs: make([]interface{}, 0),
headers: make(map[string]string),
auth: basicAuth{},
cookies: make([]*http.Cookie, 0),
files: make([]*fileForm, 0),
timeout: DefaultTimeout,
transport: t,
debug: debug,
logger: logger,
}
}
func copyMap(src map[string]string) map[string]string {
newMap := make(map[string]string)
for k, v := range src {
newMap[k] = v
}
return newMap
}
// New clones current client struct and returns it
// This is useful to initialize some common parameters and send different requests
// with differenet paths/headers/...
//
// For example:
// c := gohttp.New().URL("https://api.github.com/")
// c.BasicAuth("cizixs", "<PASSWORD>")
// users, err := c.New().Path("/users/").Get()
// repos, err := c.New().Path("/repos").Get()
//
// Note that files, body and cookies value are copied if pointer value is used, base client and cloned
// client(s) will share the same instance, change on one side will take effect on the other side.
func (c *Client) New() *Client {
newClient := &Client{}
// simple copy
newClient.url = c.url
newClient.path = c.path
newClient.auth = c.auth
newClient.proxy = c.proxy
newClient.timeout = c.timeout
newClient.tlsHandshakeTimeout = c.tlsHandshakeTimeout
newClient.retries = c.retries
newClient.debug = c.debug
// make a copy of simple map data
// NOTE: if the map data contains pointer value, it will be shallow copy.
// Right now it works, because both headers and queries are `string-string` map value
newClient.query = copyMap(c.query)
newClient.headers = copyMap(c.headers)
// TODO(cizixs): maybe make a deep copy for these pointer values, or just leave them out?
newClient.c = c.c
newClient.queryStructs = c.queryStructs
newClient.body = c.body
newClient.cookies = c.cookies
newClient.files = c.files
newClient.logger = c.logger
// use the same tranport
newClient.transport = c.transport
return newClient
}
// log writes a formatted log message record to Stderr
func (c *Client) logf(format string, v ...interface{}) {
if c.debug {
c.logger.Printf(format, v...)
}
}
// setupClient handles the connection details from http client to TCP connections.
// Timeout, proxy, TLS config ..., these are very important but rarely used directly
// by httpclient users.
func (c *Client) setupClient() error {
// create the transport and client instance first
if c.proxy != "" {
// use passed proxy, otherwise try to use environment variable proxy, or just no proxy at all.
proxy, err := url.Parse(c.proxy)
if err != nil {
return err
}
c.transport.Proxy = http.ProxyURL(proxy)
}
if c.tlsHandshakeTimeout != time.Duration(0) {
c.transport.TLSHandshakeTimeout = c.tlsHandshakeTimeout
}
// TODO(cizixs): maybe reuse http.Client as well
c.c = &http.Client{Transport: c.transport}
// request timeout limit
// timeout zero means no timeout
// NOTE: `Timeout` property is only supported from go1.3+
if c.timeout != time.Duration(0) {
c.c.Timeout = c.timeout
}
return nil
}
func (c *Client) prepareFiles() error {
// parse files in request.
// `gohttp` supports posting multiple files, for each file, there should be three component:
// - fieldName: the upload file button field name in the web. `<input type="file" name="files" multiple>`,
// For instance, fieldname would be `files` in this case.
// - filename: filename string denotes the file to be uploaded. This can be set manually, or extracted from filepath
// - file content: the actual file data. Ideally, users can pass a filepath, or a os.File instance, or a []byte slice, or a string
// as file content
// On how `multipart/form-data` works, please refer to RFC7578 and RFC 2046.
if len(c.files) > 0 {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// for each file, write fieldname, filename, and file content to the body
for _, file := range c.files {
part, err := writer.CreateFormFile(file.fieldName, file.filename)
if err != nil {
return err
}
_, err = io.Copy(part, file.file)
if err != nil {
return err
}
}
err := writer.Close()
if err != nil {
return err
}
// finally, get the real content type, and set the header
multipartContentType := writer.FormDataContentType()
c.Header(contentType, multipartContentType)
c.body = body
}
return nil
}
// prepareRequest does all the preparation jobs for `gohttp`.
// The main job is create and configure all structs like `Transport`, `Dialer`, `Client`
// according to arguments passed to `gohttp`.
// TODO(cizixs): This method is getting longer and longer, will try to tidy it up, and
// move some content to individual functions.
func (c *Client) prepareRequest(method string) (*http.Request, error) {
err := c.setupClient()
if err != nil {
return nil, err
}
err = c.prepareFiles()
if err != nil {
return nil, err
}
// create the basic request
req, err := http.NewRequest(method, c.url, c.body)
if err != nil {
return nil, err
}
// concatenate path to url if exists
if c.path != "" {
// Adds prefix "/" if necessary
if !strings.HasPrefix(c.path, "/") {
c.path = "/" + c.path
}
p := req.URL.Path
req.URL.Path = filepath.Join(p, c.path)
}
// setup the query string, there can be many query strings,
// and they're connected with `&` symbol. Also rawquery and
// queryStructs data will be merged.
if len(c.query) != 0 {
q := req.URL.Query()
for key, value := range c.query {
q.Add(key, value)
}
req.URL.RawQuery = q.Encode()
}
if len(c.queryStructs) != 0 {
q := req.URL.Query()
for _, queryStruct := range c.queryStructs {
qValues, err := query.Values(queryStruct)
if err != nil {
return req, err
}
for key, values := range qValues {
for _, value := range values {
q.Add(key, value)
}
}
}
req.URL.RawQuery = q.Encode()
}
// setup headers
if len(c.headers) != 0 {
for key, value := range c.headers {
req.Header.Add(key, value)
}
}
// set cookies
if len(c.cookies) != 0 {
for _, cookie := range c.cookies {
req.AddCookie(cookie)
}
}
// set basic auth if exists
if c.auth.username != "" && c.auth.password != "" {
req.SetBasicAuth(c.auth.username, c.auth.password)
}
return req, nil
}
// Debug sets the debug mode of go http.
// By default, debug mode is off.
//
// This is only for testing and debugging purpose,
// it will print out detail information such as request and response dump string,
// and other logging lines.
//
// If `GOHTTP_DEBUG` environment variable is set, `gohttp` will use the value.
// 1 for turn on debug mode, and others for turn off debug mode.
// Debug method overrides environment variable value.
func (c *Client) Debug(debug bool) *Client {
c.debug = debug
return c
}
// Do takes HTTP and url, then makes the request, return the response.
// All other HTTP methods will call `Do` behind the scene, and
// it can be used directly to send the request.
// Custom HTTP method can be sent with this method.
// Accept optional url parameter, if multiple urls are given only the first one
// will be used.
func (c *Client) Do(method string, urls ...string) (*GoResponse, error) {
// TODO: check if url is valid
url := ""
if len(urls) >= 1 && urls[0] != "" {
url = urls[0]
}
c.URL(url)
req, err := c.prepareRequest(method)
if err != nil {
return nil, err
}
// use httputil to dump raw request string.
// NOTE: some details might be lost such as header order and case.
if c.debug {
dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
c.logf("err: %v\n", err)
return nil, err
}
c.logf("http request dump:\n%s\n", string(dump))
}
var resp *http.Response
// retry the request certain time, if error happens
tried := 0
for {
resp, err = c.c.Do(req)
tried++
if c.retries <= 1 || tried >= c.retries || err == nil {
break
} else {
c.logf("Request [%d/%d] error: %v, retrying...\n", tried, c.retries, err)
}
}
if err != nil {
c.logf("Final request error after %d attempt(s): %v\n", tried, err)
return nil, err
}
if c.debug {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
c.logf("err: %v\n", err)
return nil, err
}
c.logf("http response dump:\n%s\n", string(dump))
}
return &GoResponse{resp}, err
}
// Get handles HTTP GET request, and return response to user
// Note that the response is not `http.Response`, but a thin wrapper which does
// exactly what it used to and a little more.
func (c *Client) Get(urls ...string) (*GoResponse, error) {
return c.Do("GET", urls...)
}
// Post handles HTTP POST request
func (c *Client) Post(urls ...string) (*GoResponse, error) {
return c.Do("POST", urls...)
}
// Head handles HTTP HEAD request
// HEAD request works the same way as GET, except the response body is empty.
func (c *Client) Head(urls ...string) (*GoResponse, error) {
return c.Do("HEAD", urls...)
}
// Put handles HTTP PUT request
func (c *Client) Put(urls ...string) (*GoResponse, error) {
return c.Do("PUT", urls...)
}
// Delete handles HTTP DELETE request
func (c *Client) Delete(urls ...string) (*GoResponse, error) {
return c.Do("DELETE", urls...)
}
// Patch handles HTTP PATCH request
func (c *Client) Patch(urls ...string) (*GoResponse, error) {
return c.Do("PATCH", urls...)
}
// Options handles HTTP OPTIONS request
func (c *Client) Options(urls ...string) (*GoResponse, error) {
return c.Do("OPTIONS", urls...)
}
// URL sets the base url for the client, this can be overrided by the parameter of the final
// GET/POST/PUT method
func (c *Client) URL(url string) *Client {
if url != "" {
c.url = url
}
return c
}
// Path concatenates base url with resource path.
// Path can be with or without slash `/` at both end,
// it will be handled properly.
//
// Usage:
// gohttp.New().Path("users/cizixs").Get("someurl.com")
//
func (c *Client) Path(paths ...string) *Client {
for _, path := range paths {
if path != "" {
c.path = filepath.Join(c.path, path)
}
}
return c
}
// Proxy sets proxy server the client uses.
// If it is empty, `gohttp` will try to load proxy settings
// from environment variable
//
// Usage:
// gohttp.New().Proxy("http://127.0.0.1:4567").Get("http://someurl.com")
func (c *Client) Proxy(proxy string) *Client {
if proxy != "" {
c.proxy = proxy
}
return c
}
// Timeout sets the wait limit for a request to finish.
// This time includes connection time, redirectoin time, and
// read response body time. If request does not finish before the timeout,
// any ongoing action will be interrupted and an error will return
//
// Usage:
// gohttp.New().Timeout(time.Second * 10).Get(url)
func (c *Client) Timeout(timeout time.Duration) *Client {
// TODO(cizixs): add other timeouts like setup connection timeout,
c.timeout = timeout
return c
}
// TLSHandshakeTimeout sets the wait limit for performing TLS handshake.
// Default value for go1.6 is 10s, change this value to suit yourself.
func (c *Client) TLSHandshakeTimeout(timeout time.Duration) *Client {
c.tlsHandshakeTimeout = timeout
return c
}
// Retries set how many request attempts will be conducted if error happens for a request.
// number <= 1 means no retries, send one request and finish.
func (c *Client) Retries(n int) *Client {
// TODO(cizixs): allow user to customize retry condition, like if the response status code is 5XX.
c.retries = n
return c
}
// Cookie set client cookie, the argument is a standard `http.Cookie`
func (c *Client) Cookie(cookie *http.Cookie) *Client {
if cookie != nil {
c.cookies = append(c.cookies, cookie)
}
return c
}
// Query set parameter query string
func (c *Client) Query(key, value string) *Client {
c.query[key] = value
return c
}
// QueryStruct parses a struct as query strings
// On how it works, please refer to github.com/google/go-querystring repo
func (c *Client) QueryStruct(queryStruct interface{}) *Client {
c.queryStructs = append(c.queryStructs, queryStruct)
return c
}
// BasicAuth allows simple username/password authentication
func (c *Client) BasicAuth(username, password string) *Client {
c.auth.username = username
c.auth.password = <PASSWORD>
return c
}
// Header sets request header data
func (c *Client) Header(key, value string) *Client {
c.headers[key] = value
return c
}
type jsonBodyData struct {
payload interface{}
}
func (jbd jsonBodyData) Body() (io.Reader, error) {
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(jbd.payload)
if err != nil {
return nil, err
}
return buf, nil
}
// JSON accepts a string as data, and sets it as body, and send it as application/json
// If the actual method does not support body or json data, such as `GET`, `HEAD`,
// it will be simply omitted.
func (c *Client) JSON(bodyJSON string) *Client {
if bodyJSON != "" {
c.Header(contentType, jsonContentType)
//TODO: how to handle error
buf := &bytes.Buffer{}
buf.WriteString(bodyJSON)
c.body = buf
}
return c
}
// JSONStruct accepts a struct as data, and sets it as body, and send it as application/json
// If the actual method does not support body or json data, such as `GET`, `HEAD`,
// it will be simply omitted.
func (c *Client) JSONStruct(bodyJSON interface{}) *Client {
if bodyJSON != nil {
c.Header(contentType, jsonContentType)
//TODO: how to handle error
body, _ := jsonBodyData{payload: bodyJSON}.Body()
c.body = body
}
return c
}
type formBodyData struct {
payload interface{}
}
// Body returns io.Reader from form data.
// Form data is a collection of many key-value pairs,
// so we use go-querystring to parse it to string, then
// create a io.Reader interface.
func (fbd formBodyData) Body() (io.Reader, error) {
values, err := query.Values(fbd.payload)
if err != nil {
return nil, err
}
return strings.NewReader(values.Encode()), nil
}
// Form accepts a struct, uses it as body data, and sent it as application/www-x-form-urlencoded
// If the actual method does not support body or form data, such as `GET`, `HEAD`,
// it will be simply omitted.
func (c *Client) Form(bodyForm interface{}) *Client {
if bodyForm != nil {
c.Header(contentType, formContentType)
body, _ := formBodyData{payload: bodyForm}.Body()
c.body = body
}
return c
}
// Body accepts `io.Reader`, will read data from it and use it as request body.
// This doee not set `Content-Type` header, so users should use `Header(key, value)`
// to specify it if necessary.
func (c *Client) Body(body io.Reader) *Client {
if body != nil {
c.body = body
}
return c
}
// File adds a file in request body, and sends it to server
// Multiple files can be added by calling this method many times
func (c *Client) File(f *os.File, fileName, fieldName string) *Client {
ff := &fileForm{}
ff.filename = fileName
ff.fieldName = fieldName
ff.file = f
c.files = append(c.files, ff)
return c
}
// Get provides a shortcut to send `GET` request
func Get(url string) (*GoResponse, error) {
return DefaultClient.Get(url)
}
// Head provides a shortcut to send `HEAD` request
func Head(url string) (*GoResponse, error) {
return DefaultClient.Head(url)
}
// Delete provides a shortcut to send `DELETE` request
// It is used to remove a resource from server
func Delete(url string) (*GoResponse, error) {
return DefaultClient.Delete(url)
}
// Options provides a shortcut to send `OPTIONS` request
func Options(url string) (*GoResponse, error) {
return DefaultClient.Options(url)
}
// Post provides a shortcut to send `POST` request
func Post(url string, data io.Reader) (*GoResponse, error) {
return DefaultClient.Body(data).Post(url)
}
// Put provides a shortcut to send `PUT` request
func Put(url string, data io.Reader) (*GoResponse, error) {
return DefaultClient.Body(data).Put(url)
}
// Patch provides a shortcut to send `PATCH` request
func Patch(url string, data io.Reader) (*GoResponse, error) {
return DefaultClient.Body(data).Patch(url)
}
<file_sep>/httpgo.go
package httpgo
import (
"bytes"
"encoding/json"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/google/go-querystring/query"
"io/ioutil"
"github.com/astaxie/beego/logs/alils"
debug2 "runtime/debug"
)
//定义常量
const (
contentType = "Content-Type"
jsonContentType = "application/json"
formContentType = "application/x-www-form-urlencoded"
)
//定义默认超时时间
const DefaultTimeout = 3 * time.Second
//定义开发模式
const debugEnv = "GOHTTP_DEBUG"
type basicAuth struct {
username string
password string
}
type fileForm struct {
fieldName string
filename string
file *os.File
}
type GoRsponse struct {
*http.Response
}
func (resp *GoRsponse) Asstring() (string,error) {
data,err := ioutil.ReadAll(resp.Body)
if err != nil {
return "",err
}
return string(data),nil
}
func (resp *GoRsponse) AsBytes() ([]bytes,error){
return ioutil.ReadAll(resp.Body)
}
func (resp *GoRsponse) AsJson(v interface{}) error{
data,err := resp.AsBytes()
if err != nil{
return err
}
return json.Unmarshal(data,v)
}
type Client struct {
c *http.Client
query map[string]string
queryStructs []interface{}
headers map[string]string
url string
path string
body io.Reader
auth basicAuth
cookies []*http.Cookie
files []*fileForm
proxy string
timeout time.Duration
tlsHandshakeTimeouut time.Duration
retries int
transport *http.Transport
debug bool
logger *log.Logger
}
var DefaultClient New()
func New() *Client {
t := &http.Transport{}
debug := os.Getenv(debugEnv) == "1"
logger := log.New(os.Stderr,"[gohttp]",log.Ldate|log.Ltime|log.Lshortfile)
return &Client{
query:make(map[string]string),
queryStructs:make([]interface{},0),
headers:make(map[string]string),
auth:basicAuth{},
cookies:make([]*http.Cookie,0),
files:make([]*fileForm, 0),
timeout:DefaultTimeout,
transport:t,
debug:debug,
logger:logger,
}
}
//拷贝map
func copyMap(src map[string]string) map[string]string{
newmap := make(map[string]string)
for k,v := range src{
newmap[k] = v
}
return newmap
}
func (c *Client) New() *Client {
newClient := &Client{}
//简单拷贝
newClient.url = c.url
newClient.path = c.path
newClient.auth = c.auth
newClient.proxy = c.proxy
newClient.timeout = c.timeout
newClient.tlsHandshakeTimeouut = c.tlsHandshakeTimeouut
newClient.retries = c.retries
newClient.debug = c.debug
//mapcopy
newClient.query = copyMap(c.query)
newClient.headers = copyMap(c.headers)
//use the same transport
newClient.transport = c.transport
return newClient
}
//log writes a formatted log message record to stderr
func (c *Client) logf(format string,v interface{}){
if c.debug {
c.logger.Printf(format,v)
}
}
//setupClient handles the connection details from http client to TCP connections
//timeout ,proxy,TLS config ....these are very important but rarely used directly
//by httpclient users
func (c *Client) setupClient() error{
//creat the transport and client instance first
if c.proxy != ""{
//used proxy
proxy,err := url.Parse(c.proxy)
if err != nil {
return err
}
c.transport.Proxy = http.ProxyURL(proxy)
}
if c.tlsHandshakeTimeouut != time.Duration(0){
c.transport.TLSHandshakeTimeout = c.tlsHandshakeTimeouut
}
c.c = &http.Client{Transport:c.transport}
if c.timeout != time.Duration(0){
c.c.Timeout = c.timeout
}
return nil //没有err
}
func (c *Client) preparefiles() error{
if len(c.files) >0 {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
//for each file, write field name,filename,and file content to the body
for _,file := range c.files {
part, err := writer.CreateFormFile(file.fieldName, file.filename)
if err != nil {
return err
}
_ , err := io.copy(part, file.file)
if err != nil {
return err
}
}
err := writer.Close()
if err !=nil {
return err
}
//finally ,get the real content type,and set the header
multipartContentType := writer.FromDataContentType()
c.Header(contentType,multipartContentType)
c.body = body
}
return nil
}
//prepareRequests does all the preparation jobs for "gohttp"
<file_sep>/main.go
package main
import (
"net/url"
"gohttp/conf"
"time"
"regexp"
)
type image struct {
imageURL string
fileName string
retry int
folder string
}
type page struct {
url string
body string
retry int
parse bool //解析规则
}
type contxt struct {
page map[string]int //记录处理状态,key是地址,value是状态
image map[string]int //记录图片的处理状态
pageChan chan *page
imgChan chan *image
parseChan chan *page
imageCount chan int
savePath string
rootURL *url.URL
config *conf.Config
}
const (
bufferSize = 64*1024
numpuller = 5 //并发数
numDownloader = 10
maxRetry = 5
statusInterval = 15 * time.Second
chanBuffersize = 80
//图片处理的状态
readt = iota //待处理
done
fail
)
var (
titleExp = regexp.MustCompile(`<title>([^<>]+)</title>`) //regexp.MustCompile(`<img\s+src="([^"'<>]*)"/?>`)
invalidCharExp = regexp.MustCompile(`[\\/*?:><|]`)
)
//主程序
func main(){
configFile := "config.json"
cf := &conf.Config{}
if err := cf.load
}
<file_sep>/gohttp_test.go
package gohttp_test
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/cizixs/gohttp"
)
func TestGet(t *testing.T) {
assert := assert.New(t)
greeting := "hello, gohttp."
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, greeting)
}))
defer ts.Close()
resp, err := gohttp.Get(ts.URL)
assert.NoError(err, "A get request should cause no error.")
assert.Equal(http.StatusOK, resp.StatusCode)
actualGreeting, err := ioutil.ReadAll(resp.Body)
assert.Equal(greeting, string(actualGreeting))
}
func TestCloneClient(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.URL.Path)
}))
defer ts.Close()
c := gohttp.New().URL(ts.URL)
resp, _ := c.New().Path("/foo").Get()
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal("/foo", string(data))
resp, _ = c.New().Path("/bar").Get()
data, _ = ioutil.ReadAll(resp.Body)
assert.Equal("/bar", string(data))
}
func TestResponseAsString(t *testing.T) {
assert := assert.New(t)
greeting := "hello, gohttp."
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, greeting)
}))
defer ts.Close()
resp, err := gohttp.Get(ts.URL)
assert.NoError(err, "A get request should cause no error.")
assert.Equal(http.StatusOK, resp.StatusCode)
actualGreeting, err := resp.AsString()
assert.NoError(err, "read the response body should not cause error.")
assert.Equal(greeting, actualGreeting)
}
func TestResponseAsBytes(t *testing.T) {
assert := assert.New(t)
greeting := "hello, gohttp."
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, greeting)
}))
defer ts.Close()
resp, err := gohttp.Get(ts.URL)
assert.NoError(err, "A get request should cause no error.")
assert.Equal(http.StatusOK, resp.StatusCode)
actualGreeting, err := resp.AsBytes()
assert.NoError(err, "read the response body should not cause error.")
assert.Equal([]byte(greeting), actualGreeting)
}
func TestResponseAsJSON(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(w, r.Body)
}))
defer ts.Close()
resp, err := gohttp.New().JSON(`{"Name":"gohttp"}`).Post(ts.URL)
assert.NoError(err, "A get request should cause no error.")
assert.Equal(http.StatusOK, resp.StatusCode)
repo := &struct {
Name string `json:"name,omitempty"`
}{}
err = resp.AsJSON(repo)
assert.NoError(err, "read the response body should not cause error.")
assert.Equal("gohttp", repo.Name)
}
func TestHead(t *testing.T) {
assert := assert.New(t)
testHeader := "Test-Header"
// test server that writes HTTP method back
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Because HEAD response does not include body, we set the received method in header
w.Header().Add(testHeader, r.Method)
}))
defer ts.Close()
resp, _ := gohttp.Head(ts.URL)
assert.Equal("HEAD", resp.Header.Get(testHeader))
}
func TestDelete(t *testing.T) {
assert := assert.New(t)
// test server that writes HTTP method back
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
}))
defer ts.Close()
resp, _ := gohttp.Delete(ts.URL)
method, _ := ioutil.ReadAll(resp.Body)
assert.Equal("DELETE", string(method))
}
func TestPost(t *testing.T) {
assert := assert.New(t)
// test server that writes HTTP method back
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
}))
defer ts.Close()
resp, _ := gohttp.Post(ts.URL, nil)
method, _ := ioutil.ReadAll(resp.Body)
assert.Equal("POST", string(method))
}
func TestPatch(t *testing.T) {
assert := assert.New(t)
// test server that writes HTTP method back
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
}))
defer ts.Close()
resp, _ := gohttp.Patch(ts.URL, nil)
method, _ := ioutil.ReadAll(resp.Body)
assert.Equal("PATCH", string(method))
}
func TestOptions(t *testing.T) {
assert := assert.New(t)
// test server that writes HTTP method back
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
}))
defer ts.Close()
resp, _ := gohttp.Options(ts.URL)
method, _ := ioutil.ReadAll(resp.Body)
assert.Equal("OPTIONS", string(method))
}
func TestPut(t *testing.T) {
assert := assert.New(t)
// test server that writes HTTP method back
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
}))
defer ts.Close()
resp, _ := gohttp.Put(ts.URL, nil)
method, _ := ioutil.ReadAll(resp.Body)
assert.Equal("PUT", string(method))
}
func TestTimeout(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1000 * time.Millisecond)
}))
defer ts.Close()
_, err := gohttp.New().Timeout(100 * time.Millisecond).Get(ts.URL)
assert.Error(err, "request should have timed out")
}
func TestRetries(t *testing.T) {
assert := assert.New(t)
retried := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
retried++
// create a error response by returning 301 without `Location` header
http.Error(w, "moved", http.StatusMovedPermanently)
return
// use timeout to return error response
// time.Sleep(1 * time.Second)
}))
defer ts.Close()
gohttp.New().Timeout(50 * time.Millisecond).Retries(3).Get(ts.URL)
assert.Equal(3, retried, "should retry 3 timeout on error")
}
func TestCookie(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%v", r.Cookies())
}))
defer ts.Close()
cookie := &http.Cookie{Name: "foo", Value: "bar"}
resp, err := gohttp.New().Cookie(cookie).Get(ts.URL)
assert.NoError(err, "Get request with cookie should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal("[foo=bar]", string(data))
}
func TestGetWithURL(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "http://%s", r.Host)
}))
defer ts.Close()
// Set url use `URL` method instead of as method parameter
resp, err := gohttp.New().URL(ts.URL).Get("")
assert.NoError(err, "Get request with url should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal(ts.URL, string(data))
}
func TestGetWithPath(t *testing.T) {
assert := assert.New(t)
cases := []struct {
input string // input path
expected string // expected path
}{
{"/cizixs", "/cizixs"},
{"/cizixs/", "/cizixs"},
{"cizixs", "/cizixs"},
{"cizixs/", "/cizixs"},
{"/users/cizixs/", "/users/cizixs"},
{"/users/cizixs", "/users/cizixs"},
{"users/cizixs", "/users/cizixs"},
{"users/cizixs/", "/users/cizixs"},
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.URL.Path)
}))
defer ts.Close()
for _, tc := range cases {
resp, err := gohttp.New().Path(tc.input).Get(ts.URL)
assert.NoError(err, "Get request with path should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal(tc.expected, string(data), fmt.Sprintf("input path: %s, expected: %s", tc.input, tc.expected))
resp.Body.Close()
}
// Test multiple path method calls
resp, _ := gohttp.New().Path("users").Path("cizixs").Get(ts.URL)
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal("/users/cizixs", string(data))
resp.Body.Close()
}
func TestGetWithQuery(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, r.URL.RawQuery)
}))
defer ts.Close()
resp, err := gohttp.New().Query("foo", "bar").Get(ts.URL)
assert.NoError(err, "Get request with query string should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal("foo=bar", string(data))
resp, err = gohttp.New().Query("foo", "bar").Query("name", "cizixs").Get(ts.URL)
assert.NoError(err, "Get request with query string should cause no error.")
data, _ = ioutil.ReadAll(resp.Body)
assert.Equal("foo=bar&name=cizixs", string(data))
}
func TestGetWithQueryStruct(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, r.URL.RawQuery)
}))
defer ts.Close()
options := struct {
Query string `url:"q"`
ShowAll bool `url:"all"`
Page int `url:"page"`
}{"foo", true, 2}
resp, err := gohttp.New().QueryStruct(options).Get(ts.URL)
assert.NoError(err, "Get request with query string should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal("all=true&page=2&q=foo", string(data))
}
func TestGetWithHeader(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Write(w)
}))
defer ts.Close()
userAgent := "gohttp client by cizixs"
resp, err := gohttp.New().Header("User-Agent", userAgent).Get(ts.URL)
assert.NoError(err, "Get request with header should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.True(strings.Contains(string(data), "User-Agent"))
assert.True(strings.Contains(string(data), userAgent))
}
func TestPostForm(t *testing.T) {
assert := assert.New(t)
type Login struct {
Name string `json:"name,omitempty"`
Password string `json:"password,omitempty"`
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" {
w.Write([]byte("No form data"))
} else {
fmt.Fprint(w, string(data))
}
}))
defer ts.Close()
user := Login{
Name: "cizixs",
Password: "<PASSWORD>",
}
resp, err := gohttp.New().Form(user).Post(ts.URL)
assert.NoError(err, "Post request should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
assert.Equal("Name=cizixs&Password=<PASSWORD>", string(data))
}
func TestPostJSON(t *testing.T) {
assert := assert.New(t)
type User struct {
Title string `json:"title,omitempty"`
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
if r.Header.Get("Content-Type") != "application/json" {
w.Write([]byte("No json data"))
} else {
fmt.Fprint(w, string(data))
}
}))
defer ts.Close()
resp, err := gohttp.New().JSON(`{"Name":"Cizixs"}`).Post(ts.URL)
assert.NoError(err, "Post request should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
returnedUser := User{}
json.Unmarshal(data, &returnedUser)
assert.Equal("Cizixs", returnedUser.Name)
assert.Equal(0, returnedUser.Age)
}
func TestPostJSONStruct(t *testing.T) {
assert := assert.New(t)
type User struct {
Title string `json:"title,omitempty"`
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
if r.Header.Get("Content-Type") != "application/json" {
w.Write([]byte("No json data"))
} else {
fmt.Fprint(w, string(data))
}
}))
defer ts.Close()
user := User{
Title: "Test title",
Name: "cizixs",
}
resp, err := gohttp.New().JSONStruct(user).Post(ts.URL)
assert.NoError(err, "Post request should cause no error.")
data, _ := ioutil.ReadAll(resp.Body)
returnedUser := User{}
json.Unmarshal(data, &returnedUser)
assert.Equal("Test title", returnedUser.Title)
assert.Equal("cizixs", returnedUser.Name)
assert.Equal(0, returnedUser.Age)
}
func TestPostFiles(t *testing.T) {
assert := assert.New(t)
// the mock http server will parse files uploaded, and send `filename:fileLength` string back to client
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reader, err := r.MultipartReader()
if err != nil {
fmt.Fprintf(w, "Ops: %v\n", err)
} else {
files := []string{}
for {
part, err := reader.NextPart()
if err == io.EOF || part == nil {
break
}
if err != nil {
continue
}
if part.FileName() == "" {
fmt.Fprintf(w, "Ops: empty file name\n")
continue
}
data, err := ioutil.ReadAll(part)
if err != nil {
fmt.Fprintf(w, "Ops: %v\n", err)
}
files = append(files, fmt.Sprintf("%s:%d", part.FileName(), len(string(data))))
}
fmt.Fprintf(w, strings.Join(files, "&"))
}
}))
filename := "./LICENSE"
f, _ := os.Open(filename)
resp, _ := gohttp.New().File(f, "hello.txt", "myfiled").Post(ts.URL)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Ops-Ops: %v\n", err)
}
assert.Equal("hello.txt:1063", string(data))
}
<file_sep>/README.md
# gohttp
[](https://travis-ci.org/cizixs/gohttp)
[](https://coveralls.io/github/cizixs/gohttp?branch=master)
[](LICENSE.md)
[](https://goreportcard.com/report/github.com/cizixs/gohttp)
[](https://godoc.org/github.com/cizixs/gohttp)
A simple to use golang http client
## Features
- [x] All HTTP methods support: GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS
- [x] Easy to set HTTP Headers
- [x] Query strings can be added through key-value pairs or struct easily
- [x] Extend url path whenever you want
- [x] Send form and json data in one line
- [x] Basic Auth right away
- [x] Read from response the easy way
- [x] Support proxy configuration
- [x] Allow set timeout at all levels
- [x] Automatically retry request, if you let it
- [ ] Custom redirect policy
- [ ] Perform hook functions
- [ ] Session support, persistent response data, and reuse them in next request
- More to come ...
## Principles
- Simple: the exposed interface should be simple and intuitive. After all, this is why `gohttp` is created
- Consistent: Derived from `net/http`, `gohttp` tries to keep consistent with it as much as possible
- Fully-Documented: along with the simple interface, documents and examples will be given to demostrate the full usage, pitfalls and best practices
## Install
```bash
go get github.com/cizixs/gohttp
```
And then import the package in your code:
```go
import "github.com/cizixs/gohttp"
```
## Usage
### Get a resource from url
`gohttp` provides shortcut to make simple `GET` quite straightforward:
resp, err := gohttp.Get("https://api.github.com/users/cizixs")
The above does the same thing as:
resp, err := gohttp.New().Get("https://api.github.com/users/cizixs")
In fact, this is exactly what it does behind the scene.
`gohttp.New()` returns `gohttp.Client` struct, which gives you full control of the request which be sent.
### Create url path on the fly
If url path can not decided until runtime or you want it be flexible, `Path()` method is here to help:
resp, err := gohttp.New().Path("/repos").Path("cizixs/gohttp/").Path("issues").Get("https://api.github.com/")
Or simply in one method:
resp, err := gohttp.New().Path("/repos", "cizixs/gohttp/", "issues").Get("https://api.github.com/")
Notice how `gohttp` handles the slash `/` appropriately no matter where it is placed(or not placed at all).
### Pass arguments(query string) in URLs
There are often times you want to include query strings in url, handling this issue manually can be tiresome and boring.
Not with `gohttp`:
gohttp.New().Path("/repos", "cizixs/gohttp/", "issues").
Query("state", "open").Query("sort", "updated").Query("mentioned", "cizixs").
Get("https://api.github.com/")
Think this is tedious too? Here comes the better part, you can pass a struct as query strings:
type issueOption struct {
State string `json:"state,omitempty"`
Assignee string `json:"assignee,omitempty"`
Creator string `json:"creator,omitempty"`
Mentioned string `json:"mentioned,omitempty"`
Labels string `json:"labels,omitempty"`
Sort string `json:"sort,omitempty"`
Rirection string `json:"direction,omitempty"`
Since string `json:"since,omitempty"`
}
i := &issueOption{
State: "open",
Mentioned: "cizixs",
Sort: "updated",
}
resp, err := gohttp.New().Path("/repos", "cizixs/gohttp/", "issues").QueryStruct(i).Get("https://api.github.com/")
### Custom Headers
gohttp.New().Header(key, value).Header(key, value).Get(url)
Or, simply pass all headers in a map:
gohttp.New().Headers(map[string]string).Get(url)
### Post and PUT
Not only `GET` is simple, `gohttp` implements all other methods:
body := strings.NewReader("hello, gohttp!")
gohttp.New().Body(body).Post("https://httpbin.org/post")
gohttp.New().Body(body).Put("https://httpbin.org/put")
**NOTE**: The actual data sent is based on HTTP method the request finally fires.
Anything not compliant with that METHOD will be ommited.
For example, set data to a `GET` request has no effect, because it will not be used at all.
### Post all kinds of data
When comes to sending data to server, `POST` might be the most frequently used method.
Of all user cases, send form data and send json data comes to the top.
`gohttp` tries to make these actions easy:
// send Form data
gohttp.New().Form("username", "cizixs").Form("password", "<PASSWORD>").Post("https://somesite.com/login")
// send json data
gohttp.New().Json(`{"Name":"Cizixs"}`).Post(url) // use a marshalled json string
struct User{
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
user := &User{Name: "cizixs", Age: 22}
gohttp.New().JsonStruct(user).Post(url) // use a struct and parse it to json
### Basic Auth
```go
gohttp.New().BasicAuth("username", "<PASSWORD>").Get("https://api.github.com/users/")
```
### Timeout
By default, `net/http` does not have timeout, will wait forever until response is returned.
This can be a serious issue if server hangs, `gohttp` allows you to set a timeout limit,
if response does not finish in time, an error will be returned.
gohttp.New().Timeout(100*time.Millisecond).Get("http://example.com")
### Retries
Error happens! `gohttp` provides retry mechanism to automatically resend request when error happens.
This is useful to avoid some unstable error like network temporary failure:
gohttp.New().Retries(3).Get("http://example.com")
By default, request is only sent only and all. If custom retry is set to less than one, default behavior will be used.
The retry condition only means response error, not including 5XX error.
### Upload file(s)
Upload files is simple too, multiple files can be uploaded in one request.
f, _ := os.Open(filePath)
gohttp.New().File(f io.Reader, "filename", "fieldname").Post(url)
### Proxy
If you are sending request behind a proxy, you can do this:
gohttp.New().Proxy("http://127.0.0.1:4567").Get("http://target.com/cool")
### Cookies
Access cookie from response is simple:
cookies := resp.Cookies()
gohttp.New().Cookie(cookie *http.Cookie).Cookie(cookie *http.Cookie).Get(url)
### Response data as string
If the response contains string data, you can read it by:
resp, _ := gohttp.New().Get("http://someurl.com")
data, _ := resp.AsString()
### Response data as bytes
If the response contains raw bytes, you can read it by:
resp, _ := gohttp.New().Get("http://someurl.com")
data, _ := resp.AsBytes()
### Response data as json struct
If the response contains json struct, you can pass a struct to it, and `gohttp` will marshall it for you:
user := &User{}
resp, _ := gohttp.New().Get("http://someurl.com")
err := resp.AsJSON(user)
### Reuse client
When developing complicated http client applications, it is common to interact with one remote server with some common
settings, like url, basic auth, custom header, etc. `gohttp` provides `New` method for this kind of situation.
As stated in document:
> New clones current client struct and returns it.
> This is useful to initialize some common parameters and send different requests
> with differenet paths/headers/timeout/retries...
For example:
```go
c := gohttp.New().URL("https://api.github.com/")
c.BasicAuth("<PASSWORD>", "<PASSWORD>")
c.Timeout(3 * time.Second)
users, err := c.New().Path("/users/").Get()
repos, err := c.New().Path("/repos").Get()
```
**Note**: files, body and cookies value are copied so that if pointer value is used, base client and cloned
client(s) will share the same instance, change on one side will take effect on the other side, and this might not
as expected.
### Debug mode
When developing http apps, it is often necessary to know the actual request and response sent for debugging or testing purpose.
`gohttp` provides debug mode, which can be turned on by environment variable `GOHTTP_DEBUG` or `Debug(bool)` method:
resp, _ := gohttp.New().Debug(true).Get("http://someurl.com")
In debug mode, `gohttp` will print out each request and response in human-readble format.
A typical request:
POST / HTTP/1.1
Host: 127.0.0.1:43827
User-Agent: Go-http-client/1.1
Content-Length: 39
Content-Type: application/json
Accept-Encoding: gzip
{"title":"Test title","name":"cizixs"}
A typical response:
2016/11/29 18:30:59 HTTP/1.1 200 OK
Content-Length: 39
Content-Type: application/json; charset=utf-8
Date: Tue, 29 Nov 2016 10:30:59 GMT
{"age":24,"name":"cizixs"}
## Contribution
Contributions are welcome!
- Open a new issue if you find a bug or want to propose a feature
- Create a Pull Request if you want to contribute to the code
## Inspiration
This project is heavily influenced by many awesome projects out there, mainly the following:
- [sling: A Go http client library for creating and sending API requests](https://github.com/dghubble/sling)
- [gorequest: simplified HTTP client](https://github.com/parnurzeal/gorequest)
- [requests: HTTP for human](https://github.com/kennethreitz/requests)
## License
[MIT License](https://github.com/cizixs/gohttp/blob/master/LICENSE)
| fc2dfc26814c4b687275f797b2de1b1137b899e6 | [
"Markdown",
"Go"
] | 6 | Go | Orangem21/gohttp | b8190d3e19c93b7c2688a83469e24172486faec4 | c15cea0355ca5229bc113eebea40f943581c7b93 |
refs/heads/master | <file_sep>
import UIKit
import Alamofire
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var arr = [Film]()
@IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
// Do any additional setup after loading the view.
navigationController?.navigationBar.barTintColor = UIColor.blue
self.title = "Films"
fetchFilms()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell", for: indexPath) as? TableViewCell
cell?.lblTitle.text = arr[indexPath.row].title
cell?.lblSubtitle.text = arr[indexPath.row].releaseDate
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
newViewController.film = arr[indexPath.row]
self.navigationController?.pushViewController(newViewController, animated: true)
}
func fetchFilms() {
let request = AF.request("https://swapi.co/api/films")
request.responseDecodable(of: Films.self) { (response) in
guard let films = response.value else { return }
self.arr.append(contentsOf: films.all)
self.tblView.reloadData()
}
}
}
struct Film: Decodable {
let id: Int
let title: String
let openingCrawl: String
let director: String
let producer: String
let releaseDate: String
let starships: [String]
enum CodingKeys: String, CodingKey {
case id = "episode_id"
case title
case openingCrawl = "opening_crawl"
case director
case producer
case releaseDate = "release_date"
case starships
}
}
//extension Film: Displayable {
// var titleLabelText: String {
// title
// }
//
// var subtitleLabelText: String {
// "Episode \(String(id))"
// }
//
// var item1: (label: String, value: String) {
// ("DIRECTOR", director)
// }
//
// var item2: (label: String, value: String) {
// ("PRODUCER", producer)
// }
//
// var item3: (label: String, value: String) {
// ("RELEASE DATE", releaseDate)
// }
//
// var listTitle: String {
// "STARSHIPS"
// }
//
// var listItems: [String] {
// starships
// }
//}
struct Films: Decodable {
let count: Int
let all: [Film]
enum CodingKeys: String, CodingKey {
case count
case all = "results"
}
}
<file_sep>
import UIKit
class DetailViewController: UIViewController {
var film: Film!
@IBOutlet weak var lblName: UILabel!
@IBOutlet weak var lblDirector: UILabel!
@IBOutlet weak var lblPro: UILabel!
@IBOutlet weak var lblDate: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
navigationController?.navigationBar.barTintColor = UIColor.blue
self.title = film.title
self.lblDate.text = film.releaseDate
self.lblName.text = film.title
self.lblPro.text = film.producer
self.lblDirector.text = film.director
}
}
<file_sep># IoS-Project-2020 | df1b325efb359f0655431ac24d019272429fda82 | [
"Swift",
"Markdown"
] | 3 | Swift | shashikiran330/IoS-Project-2020 | 396b2040e8b2a69607039601a9fa1ce6bd9b29d5 | 5759a5deec2df81d161f964429d8266a3f1a1f85 |
refs/heads/master | <file_sep>Day 02 - CSS + JS Clock - 2019/07/30
Definition
CSS and JavaScript based clock.
CSS Lessons Learned
- transform: rotate(20deg)
- by default it pivots in the middle of the x axis
- we want it to pivot on the right-edge of the x axis
<file_sep>04 - Array Cardio Day 1 / 31-07-2019
Definition
Updating CSS variables with JavaScript. Meaning that everywhere on the page
where that variable is referenced is updated too.
With SASS variables are defined during compile time and, therefore, can't be changed
later.
JavaScript - Lessons Learned
1) Array.prototype.filter()
- If condition returns true, element is kept in the array.
3) Array.prototype.map()
- Takes in an array, does something with it, and returns an array of the same length.
- Think of map as a machine that takes a raw material and returns a refined item!
3) Array.prototype.sort()
- You have two items, and have to decide if they should be sorted, for example:
function sort(a, b) {
if(sorting criteria a < b) // a comes first
return -1;
else if (sorting criteria a > b) // b comes first
return 1;
else // when a === b
return 0
}
- If you happen to be comparing numbers:
function sort(a, b) {
return a - b;
}
4) Array.prototype.reduce()
- Allows to add to something every on every iteration.
5) Destructuring assignment
- let [first, second, third] = someArray;<file_sep>const canvas = document.querySelector('#draw');
// You don't draw directly on the canvas, but on the context!
const ctx = canvas.getContext('2d');
// Canvas is responsive to window's size.
canvas.width = window.innerWidth;
canvas.height = window.innerWidth;
ctx.strokeStyle = 'peachpuff';
ctx.lineJoin = 'round'; // Determines the shape used to join two line segments where they meet.
ctx.lineCap = 'round'; // Determines the shape used to draw the end points of lines.
ctx.lineWidth = 52;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true // builds up... Works like a switch controlling ctx.lineWidth
// Called whenever mouse moves on top of the canvas.
function draw(event) {
if(!isDrawing) return; // Stop the function from running when 'mousedown' is not active!
console.log(event);
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
ctx.beginPath();
// Start from:
ctx.moveTo(lastX, lastY);
// Go to: (* offsetX returns the x-coordinate of the mouse pointer, relative to the target element *)
ctx.lineTo(event.offsetX, event.offsetY);
ctx.stroke();
// Update variables' coordinates
[lastX, lastY] = [event.offsetX, event.offsetY] // Destructuring an array.
hue++;
if(hue >= 360) {
hue = 0;
}
if(ctx.lineWidth >= 52 || ctx.lineWidth <= 1) {
direction = !direction;
}
if(direction) {
ctx.lineWidth++;
} else {
ctx.lineWidth--;
}
}
canvas.addEventListener('mousedown', (event) => {
isDrawing = true;
[lastX, lastY] = [event.offsetX, event.offsetY] // Make sure it doesn't start at (0, 0).
})
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false)
canvas.addEventListener('mouseout', () => isDrawing = false)<file_sep>const panels = document.querySelectorAll('.panel');
function toggleOpen() {
this.classList.toggle('open');
}
function toggleActive(event) {
if(event.propertyName.includes('flex'))
this.classList.toggle('open-active');
}
/**
* Why not toggleOpen()?
* 1) Because it would run on page load.
*
* We don't want to run the function, but pass a reference to it (the panel being clicked on!)
*
*/
panels.forEach(panel => panel.addEventListener('click', toggleOpen));
panels.forEach(panel => panel.addEventListener('transitionend', toggleActive));<file_sep>03 - CSS Variables / 31-07-2019
Definition
Updating CSS variables with JavaScript. Meaning that everywhere on the page
where that variable is referenced is updated too.
With SASS variables are defined during compile time and, therefore, can't be changed
later.
HTML - Lessons Learned
1) data-* and dataset
dataset is an object that contains all of the data-* attributes from a specific element.
CSS - Lessons Learned
1) Declaring variables
:root {
--myColor: peachpuff;
}
img {
background: var(--myColor);
}
JavaScript - Lessons Learned
1) document.documentElement.style.setProperty('property_name', value_to_set)
2) addEventListener('change', callback)
3) addEventListener('mousemove', callback)<file_sep>06 - Ajax Type Ahead / 11-08-2019
Definition
Search through an array of cities and display only the ones that match
the input, highlighting the matched portion of the string (city/state).
JavaScript - Lessons Learned
- Fetch (https://javascript.info/fetch)
- Replace matches
- str.replace(reg, str|func)
- reg = new RegExp()<file_sep>10 - Hold Shift to Check Multiple Checkboxes / 14-08-2019
Definition
Clicking a checkbox and then clicking a second one holding down the shift key,
will trigger all the checkboxes, between the two previously selected, to be checked too.
JavaScript - Lessons Learned
- Checkbox properties
- checkbox.check
- It is possible to check if a click (event) happened while holding down the shift key
- event.shiftKey<file_sep>Day 01 - JavaScript Drum Kit - 2019/07/29
Hit one of the listed keys and it will play the sound associated with that key,
along with a short animation to indicate the key that was pressed.
HTML Lessons Learned
- data-* (e.g.: data-key) -> native property
- using it avoids adding an id to each audio tag
- no need to add function to filter id content
CSS Lessons Learned
- transition property
JavaScript Lessons Learned
- querySelector()
- querySelectorAll() -> returns a Node list
- classList.add()
- 'transitionend' event<file_sep>08 - Fun with HTML5 Cavas / 12-08-2019
CSS - Lessons Learned
hsl(hue, saturation, lightness) (https://mothereffinghsl.com/)
- hue: from red to red (rainbow)
- saturation: how bright it is (%)
- lightness: white to black (%)<file_sep>Day 05 - Flex Panels Image Gallery - 2019/08/06 * Gap between days because of longweekend (Civic holiday) *
Define task.
CSS Lessons Learned
- Read more about Flexbox!
- Complete Wes' Flexbox tutorial after #JavaScript30.
JavaScript Lessons Learned
- element.classList
- Returns a DOMTokenList, containing a list of the class name(s) of an element.
- element.classList.toggle()
- Toggles between a class name for an element.<file_sep>09 - 14 Must Know Dev Tool Tricks / 13-08-2019
<file_sep>07 - Array Cardio 2 / 11-08-2019
Definition
Useful JavaScript methods! (https://javascript.info/array-methods)
JavaScript - Lessons Learned
1) Array.prototype.some()
- Checks if the AT LEAST ONE thing my Array meets what I'm looking for.
2) Array.prototype.every()
- Check if ALL items in my Array meet a certain criteria.
3) Array.prototype.find()
- Returns the first item that matches the criteria.
4) Array.prototype.findIndex()
- Abc
5) arr.splice(index[, deleteCount, elem1, ..., elemN]) * The swiss army knife for arrays! *
- It starts from the position index, removes deleteCount elements and then inserts
elem1...elemN at their place. Returns the array of removed elements!
6) arr.slice(start, end)
- It returns a new array copying to it all items from index start to
end (not including end) | f883681fe1d1da3f72d2b8f9a6cca46e5df7b76f | [
"Markdown",
"JavaScript"
] | 12 | Markdown | yagosansz/javascript-30 | b77c69c9b005bd48e2b8a6f6767b1331b4018c01 | 7494f565da816433c37031fcf884bc058e68ce01 |
refs/heads/master | <repo_name>ikles/xaver.loc<file_sep>/index7_2.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
include 'functions.php';
/*$lines = file('./test.html'); //извлекает содержимое файла как индекс массив с значениями каждой строки до переноса
print_arr($lines);
foreach ($lines as $key => $value){
echo $key .= " не очень => ";
echo $value."<br>";
}*/
/*
$lines = file_get_contents('./test.html'); // извлекает содержимое файла как строку с переносами
var_dump($lines);
$lines = explode("\n",$lines); //разбивает строку на массив символ переноса строки указан разделителем
print_arr($lines);
*/
/*
* Парсим весь сайт
$lines = file_get_contents('http://lenta.ru');
echo $lines;*/
//либо так
/*
$lines = file('http://lenta.ru');
print_r($lines);*/
//$lines = file_get_contents('http://lenta.ru');
//file_put_contents('test.html', $lines, FILE_APPEND); //append значит дописать в конец файла, если просто перезаписать надо то этот флаг не ставится
//считали разметку с сайтв всю и записали в файл
file_put_contents('test.html', 'kak dela', FILE_APPEND);//просто добавляем текст kak dela в конец файла
//Закончил на времени 1.08.20<file_sep>/dz9_mysqli/functions.php
<?php
// Добавление/обновление/удаление объявления
function add_up_del_ads() {
global $ads;
global $db;
if (validate($_POST) && !check_get_params()) {//если заполнена форма и гет параметров нет
//реализовать добавление объявления в базу
if (!isset($_POST['allow_mails'])) {
$_POST['allow_mails'] = "0";
}
$new_ad = "insert into `ads` (`private`, `seller_name`, `email`, `allow_mails`,`phone`,`location_id`,`category_id`,`title`,`description`,`price`)
VALUES ('$_POST[private]', '$_POST[seller_name]','$_POST[email]','$_POST[allow_mails]','$_POST[phone]','$_POST[location_id]','$_POST[category_id]','$_POST[title]','$_POST[description]','$_POST[price]')";
mysqli_query($db,$new_ad);
//то отправляем в базу объявление
} elseif (check_get_params() && isset($_POST['main_form_submit'])) {//при сохранении объявления
//перезаписать объявление в базу
if (!isset($_POST['allow_mails'])) {
$_POST['allow_mails'] = "0";
}
$up_ad = "update ads set private='$_POST[private]', seller_name='$_POST[seller_name]', email='$_POST[email]', allow_mails='$_POST[allow_mails]', phone='$_POST[phone]', location_id='$_POST[location_id]', category_id='$_POST[category_id]', title='$_POST[title]', description='$_POST[description]', price='$_POST[price]' where id = $_GET[id]";
mysqli_query($db,$up_ad) or die(mysql_error());
}
}
function delAds() {
global $id;
global $ads;
global $db;
//print_arr($ads);
if (isset($_GET['action']) && !isset($_POST['main_form_submit'])) {//если существует GET['action'] и при этом не нажата кнопка
$id = $_GET['id'];
if ($_GET['action'] == 'del' && isset($ads[$id])) {
unset($ads[$id]);
mysqli_query($db,"delete from ads where id = $_GET[id]");
}
}
}
function getAds() {
global $db;
$insert_sql = "select ads.id,private,seller_name,email,allow_mails,phone,ads.location_id,ads.category_id,title,description,price,categories.category_id as categories_category_id,citys.location_id as citys_location_id,category,city from ads left join categories on (ads.category_id=categories.category_id) left join citys on (ads.location_id=citys.location_id)";
$result = mysqli_query($db,$insert_sql);
while ($row = mysqli_fetch_assoc($result)) {
global $ads;
$ads[$row['id']] = $row;
}
}
//Функция проверки формы и сохраниение в сессию
function validate($post) {
if (isset($post['private']) &&
isset($post['main_form_submit']) &&
!empty($post['seller_name']) &&
!empty($post['email']) &&
!empty($post['phone']) &&
!empty($post['location_id']) &&
!empty($post['category_id']) &&
!empty($post['title']) &&
!empty($post['description']) &&
!empty($post['price'])) {
return true;
} else {
return false;
}
}
//Функция проверки полей формы
function check_get_params() {
if (isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['id'])) {
return true;
} else {
return false;
}
}
function print_arr($a) {
echo"<pre>";
print_r($a);
echo"</pre>";
}
//проверка существует ли array_key_exists ключ в массиве
function get_id_key_exists() {
global $ad;
global $ads;
if (isset($_GET['id']) && isset($ads) && array_key_exists($_GET['id'], $ads)) {
$ad = $ads[$_GET['id']];
} else {
$ad = '';
}
}
function getCitys($db) {
$result2 = mysqli_query($db,"select * from citys");
while ($city = mysqli_fetch_assoc($result2)) {
$citys[$city['location_id']] = $city['city'];
}
return $citys;
}
function getCategories($db) {
$result3 = mysqli_query($db,"select * from categories");
while ($category = mysqli_fetch_assoc($result3)) {
$categories[$category['category_id']] = $category['category'];
}
return $categories;
}
<file_sep>/index7.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$get = $_GET;
$get = serialize($get); //функция преобразовывает массив в удобную строку, потому что куки нехранят массивы а только строки
setcookie('ads',$get, time()+3600*24*7); //утсанавливаем куку, название, содержание куки, время жизни, чтобы удалить куку достаточно отправить ее в прошлое time()-1
print_r($_COOKIE['ads']);
require_once 'test/test.php'; // подключаем файл в нем смотрим продолжение<file_sep>/dz7/functions.php
<?php
//Функция вывода таблицы с объявлениями
function show_ads() {
global $ads;
if (isset($ads)) {
foreach ($ads as $id => $value) {
echo "<a href=?action=show&id=" . $id . ">" . $value['title'] . "</a> | ";
echo $value['price'] . " руб. | ";
echo $value['seller_name'] . " | <a href=?action=del&id=" . $id . ">Удалить</a><br>";
}
}
}
//Функция проверки формы и сохраниение в сессию
function validate($post) {
if (isset($post['private']) &&
isset($post['main_form_submit']) &&
!empty($post['seller_name']) &&
!empty($post['email']) &&
!empty($post['phone']) &&
!empty($post['location_id']) &&
!empty($post['category_id']) &&
!empty($post['title']) &&
!empty($post['description']) &&
!empty($post['price'])) {
return true;
} else {
return false;
}
}
//Функция проверки полей формы
function check_data() {
if (isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['id'])) {
return true;
} else {
return false;
}
}
//Функция показа содержимого массива форматированного
function print_arr($a) {
echo "<pre>";
print_r($a);
echo "</pre>";
}
//Функция вывода города в форму
function show_city_block() {
global $ads;
$citys = array('641780' => 'Новосибирск', '641490' => 'Барабинск', '641510' => 'Бердск');
if (check_data()) {
$gorod = $ads[$_GET['id']]['location_id'];
?>
<select title="Выберите Ваш город" name="location_id" id="region" class="form-input-select">
<option value="">-- Выберите город --</option>
<option class="opt-group" disabled="disabled">-- Города --</option>
<?php
foreach ($citys as $number => $city) {
$selected = ($number == $gorod) ? 'selected=""' : ''; //если мы передали в функцию город который нужно выставить в списке то мы ставим специальную метку в селектор
echo '<option data-coords=",," ' . $selected . ' value="' . $number . '">' . $city . '</option>';
}
} else {
?>
<select title="Выберите Ваш город" name="location_id" id="region" class="form-input-select">
<option value="">-- Выберите город --</option>
<option class="opt-group" disabled="disabled">-- Города --</option>
<?php
foreach ($citys as $number => $city) {
echo '<option data-coords=",," value="' . $number . '">' . $city . '</option>';
}
}
?>
</select>
<?php
}
//Функция вывода категории в форму
function show_category_block() {
global $ads;
$category = array('24' => 'Квартиры', '23' => 'Комнаты', '25' => 'Дома, дачи, коттеджи');
if (check_data()) {
$cat = $ads[$_GET['id']]['category_id'];
?>
<select title="Выберите категорию объявления" name="category_id" id="fld_category_id" class="form-input-select">
<option value="">-- Выберите категорию --</option>
<optgroup label="Недвижимость">
<?php
foreach ($category as $number => $categ) {
$selected = ($number == $cat) ? 'selected=""' : '';
echo '<option data-coords=",," ' . $selected . ' value="' . $number . '">' . $categ . '</option>';
}
} else {
?>
<select title="Выберите категорию объявления" name="category_id" id="fld_category_id" class="form-input-select">
<option value="">-- Выберите категорию --</option>
<optgroup label="Недвижимость">
<?php
foreach ($category as $number => $categ) {
echo '<option data-coords=",," value="' . $number . '">' . $categ . '</option>';
}
}
?>
</optgroup>
</select>
<?php
}
//Функция вывода Частное лицо/компания в форму
function show_private_block() {
global $ads;
$private = array('1' => 'Частное лицо', '0' => 'Компания');
if (check_data()) {
$pr = $ads[$_GET['id']]['private'];
foreach ($private as $number => $prive) {
if (isset($pr)) {
$checked = ($number == $pr) ? ' checked ' : ' ';
echo "<label class='form-label-radio'>
<input" . $checked . "type='radio' value='" . $number . "' name='private'>" . $prive . "</label> ";
}
}
} else {
foreach ($private as $number => $prive) {
echo "<label class='form-label-radio'>
<input type='radio' value='" . $number . "' name='private'>" . $prive . "</label>";
}
}
}
?><file_sep>/dz7.php
<?php
/*
1) dz6_1.php Сохранять объявления в Cookie и выставить время жизни - неделю
2) dz6_2.php Сохранять объявления в файлах
*/
<file_sep>/dz7/dz6_2.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
if (file_exists('ads.html')) {
$ads = file_get_contents('ads.html');
$ads = unserialize($ads);
}
include 'functions.php';
//Проверка формы на заполненность всех полей
if (validate($_POST) && !check_data()) {
$ads[] = $_POST;
} elseif (check_data() && isset($_POST['main_form_submit'])) {//при сохранении объявления
$ads[$_GET['id']] = $_POST; //Перезаписать данные в массив с определенным индексом который берется из get id
} elseif (isset($_GET['action']) && !isset($_POST['main_form_submit'])) {//если существует GET['action'] и при этом не нажата кнопка
$id = $_GET['id'];
if ($_GET['action'] == 'del' && isset($ads[$id])) {
unset($ads[$id]);
}
}
if (isset($ads)) {file_put_contents('ads.html', serialize($ads));}
include 'template.php';
show_ads(); //Вывод объявлений
if (check_data()) {
echo "<br><a href='dz6_2.php'>Добавить новое объявление >></a><br>";
}
?>
</body><file_sep>/dz6.php
<?php
session_start();
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
//Проверка формы на заполненность всех полей
if (validate($_POST) && !check_data()) {
$_SESSION['history'][] = $_POST;
} elseif (check_data() && isset($_POST['main_form_submit'])) {
$_SESSION['history'][$_GET['id']] = $_POST;
} elseif (isset($_GET['action']) && !isset($_POST['main_form_submit'])) {//если существует GET['action'] и при этом не нажата кнопка
$id = $_GET['id'];
if ($_GET['action'] == 'del' && isset($_SESSION['history'][$id])) {
unset($_SESSION['history'][$id]);
}
}
?>
<html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Форма</title>
</head>
<body>
<h2>Форма добавление/изменения объявления</h2>
<form method='post'>
<div>
<?php show_private_block(); ?>
</div>
<div>
<label for='fld_seller_name'><b id='your-name'>Ваше имя</b></label>
<input type='text' maxlength='40' value='<?php
if (check_data()) {
echo $_SESSION['history'][$_GET['id']]['seller_name'];
} else {
echo '';
}
?>' name='seller_name' id='fld_seller_name'>
</div>
<div>
<label for='fld_email'>Электронная почта</label>
<input type='text' value='<?php
if (check_data()) {
echo $_SESSION['history'][$_GET['id']]['email'];
}
?>' name='email' id='fld_email'>
</div>
<div>
<label for='allow_mails'> <input type='checkbox' value='1'
<?php
if (check_data()) {
if (isset($_SESSION['history'][$_GET['id']]['allow_mails']) && $_SESSION['history'][$_GET['id']]['allow_mails'] == 1) {
echo " checked ";
} else {
echo '';
}
}
?>
' name='allow_mails' id='allow_mails' >
<span class='form-text-checkbox'>Я не хочу получать вопросы по объявлению по e-mail</span>
</label> </div>
<div>
<label id='fld_phone_label' for='fld_phone'>Номер телефона</label>
<input type='text' value='<?php
if (check_data()) {
echo $_SESSION['history'][$_GET['id']]['phone'];
}
?>' name='phone' id='fld_phone'>
</div>
<div id='f_location_id'>
<label for='region'>Город</label>
<?php show_city_block(); ?>
</div>
<div>
<label for='fld_category_id'>Категория</label>
<?php show_category_block(); ?>
</div>
<div style='display: none;' id='params' class='form-row form-row-required'>
<label class='form-label '>Выберите параметры</label>
<div class='form-params params' id='filters'>
</div>
</div>
<div id='f_title' class='form-row f_title'>
<label for='fld_title'>Название объявления</label>
<input type='text' maxlength='50' class='form-input-text-long' value='<?php
if (check_data()) {
echo $_SESSION['history'][$_GET['id']]['title'];
}
?>' name='title' id='fld_title'>
</div>
<div>
<label for='fld_description' id='js-description-label'>Описание объявления</label>
<textarea maxlength='3000' name='description' id='fld_description' class='form-input-textarea'><?php
if (check_data()) {
echo $_SESSION['history'][$_GET['id']]['description'];
}
?></textarea>
</div>
<div id='price_rw' class='form-row rl'>
<label id='price_lbl' for='fld_price'>Цена</label>
<input type='text' maxlength='9' value='
<?php
if (check_data()) {
echo $_SESSION['history'][$_GET['id']]['price'];
}
?>'
class='form-input-text-short' name='price' id='fld_price'> <span id='fld_price_title'>руб.</span>
</div>
<div style='display: none; margin-top: 0px;' class='form-row-indented images' id='files'>
<div style='display: none;' id='progress'>
<table>
<tbody>
<tr>
<td> <div><div></div></div> </td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='form-row-indented form-row-submit b-vas-submit' id='js_additem_form_submit'>
<div class='vas-submit-button pull-left'>
<span class='vas-submit-border'></span>
<span class='vas-submit-triangle'></span>
<input type='submit' value='<?php if (isset($_GET['action']) && $_GET['action'] == 'show') {
echo"Сохранить";
} else {
echo"Отправить";
} ?>' id='form_submit' name='main_form_submit' class='vas-submit-input'>
</div>
</div>
</form>
<?php
show_ads(); //Вывод объявлений
if (check_data()) {
echo "<br><a href='/dz6.php'>Добавить новое объявление >></a><br>";
}
?>
</body>
<?php
//Функция вывода таблицы с объявлениями
function show_ads() {
if (isset($_SESSION['history'])) {
foreach ($_SESSION['history'] as $id => $value) {
echo "<a href=?action=show&id=" . $id . ">" . $value['title'] . "</a> | ";
echo $value['price'] . " руб. | ";
echo $value['seller_name'] . " | <a href=?action=del&id=" . $id . ">Удалить</a><br>";
}
}
}
//Функция проверки формы и сохраниение в сессию
function validate($post) {
if (isset($post['private']) &&
isset($post['main_form_submit']) &&
!empty($post['seller_name']) &&
!empty($post['email']) &&
!empty($post['phone']) &&
!empty($post['location_id']) &&
!empty($post['category_id']) &&
!empty($post['title']) &&
!empty($post['description']) &&
!empty($post['price'])) {
return true;
} else {
return false;
}
}
//Функция проверки полей формы
function check_data() {
if (isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['id'])) {
return true;
} else {
return false;
}
}
//Функция показа содержимого массива форматированного
function print_arr($a) {
echo "<pre>";
print_r($a);
echo "</pre>";
}
//Функция вывода города в форму
function show_city_block() {
$citys = array('641780' => 'Новосибирск', '641490' => 'Барабинск', '641510' => 'Бердск');
if (check_data()) {
$gorod = $_SESSION['history'][$_GET['id']]['location_id'];
?>
<select title="Выберите Ваш город" name="location_id" id="region" class="form-input-select">
<option value="">-- Выберите город --</option>
<option class="opt-group" disabled="disabled">-- Города --</option>
<?php
foreach ($citys as $number => $city) {
$selected = ($number == $gorod) ? 'selected=""' : ''; //если мы передали в функцию город который нужно выставить в списке то мы ставим специальную метку в селектор
echo '<option data-coords=",," ' . $selected . ' value="' . $number . '">' . $city . '</option>';
}
} else {
?>
<select title="Выберите Ваш город" name="location_id" id="region" class="form-input-select">
<option value="">-- Выберите город --</option>
<option class="opt-group" disabled="disabled">-- Города --</option>
<?php
foreach ($citys as $number => $city) {
echo '<option data-coords=",," value="' . $number . '">' . $city . '</option>';
}
}
?>
</select>
<?php
}
//Функция вывода категории в форму
function show_category_block() {
$category = array('24' => 'Квартиры', '23' => 'Комнаты', '25' => 'Дома, дачи, коттеджи');
if (check_data()) {
$cat = $_SESSION['history'][$_GET['id']]['category_id'];
?>
<select title="Выберите категорию объявления" name="category_id" id="fld_category_id" class="form-input-select">
<option value="">-- Выберите категорию --</option>
<optgroup label="Недвижимость">
<?php
foreach ($category as $number => $categ) {
$selected = ($number == $cat) ? 'selected=""' : '';
echo '<option data-coords=",," ' . $selected . ' value="' . $number . '">' . $categ . '</option>';
}
} else {
?>
<select title="Выберите категорию объявления" name="category_id" id="fld_category_id" class="form-input-select">
<option value="">-- Выберите категорию --</option>
<optgroup label="Недвижимость">
<?php
foreach ($category as $number => $categ) {
echo '<option data-coords=",," value="' . $number . '">' . $categ . '</option>';
}
}
?>
</optgroup>
</select>
<?php
}
//Функция вывода Частное лицо/компания в форму
function show_private_block() {
$private = array('1' => 'Частное лицо', '0' => 'Компания');
if (check_data()) {
$pr = $_SESSION['history'][$_GET['id']]['private'];
foreach ($private as $number => $prive) {
if (isset($pr)) {
$checked = ($number == $pr) ? ' checked ' : ' ';
echo "<label class='form-label-radio'>
<input" . $checked . "type='radio' value='" . $number . "' name='private'>" . $prive . "</label> ";
}
}
} else {
foreach ($private as $number => $prive) {
echo "<label class='form-label-radio'>
<input type='radio' value='" . $number . "' name='private'>" . $prive . "</label>";
}
}
} <file_sep>/index_1.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$db = mysql_connect('localhost', 'test', '123') or die('Mysql сервер недоступен '. mysql_error());
echo "Соединение с сервером установлено успешно";
mysql_select_db('test2', $db)or die('<br>Не удалось соединиться с базой данных '. mysql_error().'<br>');
mysql_query("SET NAMES utf8");
echo "<br>База данных выбрана спешно<br>";//$db идентификатор подключение, если подключнеие одно то он не обязательный
$result = mysql_query('select users.id,first_name,last_name,phone,department,departments.id as department_id,name from users left join departments on (users.department=departments.id)') or die ('Запрос на удался '. mysql_error()); //limit 1 - 1 запись, 1,2 - начиная с 1 вывести 2 записи
// так как обе таблицы имеют id то нужно обозначить к какой таблице отностися каждый id - users.id и departments.id
// departments.id при это создаем виртуальное имя через as department_id
//echo "Всего количество юзеров: ".mysql_num_rows($result)."<br>";
//exit();
while ($row = mysql_fetch_assoc($result)) {
$row['last_name'].=" А.";
mysql_query("update users set last_name='$row[last_name]' where id = $row[id]")
or die(mysql_error());
//обновить значение users столбец last_name на то что пристыковано выше где id равно тому id который сейчас учавствует в итеррации
echo "количество строк обработано: ". mysql_affected_rows()."<br>";
print_r($row);
}
//mysql_query('delete from users where id=4'); //удалить из users где id = 4
mysql_query('delete from users where phone like "%888%"'); //удалить из users где телефон содержит 888
echo "количество строк обработано: ". mysql_affected_rows()."<br>";
//Вставка данных в таблицу
$insert_sql="INSERT INTO `users` (`first_name`, `last_name`, `phone`, `department`)
VALUES ('Петр5', 'Иванов', '89999999999', '2')";//запрос присваиваем переменной, не указываем тут id т.к он заполняется автоматом
mysql_query($insert_sql) or die(mysql_error()); //посылаем запрос в бд
echo "Новый идентификатор ".mysql_insert_id();//выводит какой идентификатор был добавлен последним
mysql_free_result($result);//очистить память
mysql_close();//закрыть соединение с базой данных
<file_sep>/dz4.php
<?php
/*
* Задание 1
* - Вы проектируете интернет магазин. Посетитель на вашем сайте создал следующий заказ (цена, количество в заказе
* и остаток на складе генерируются автоматически):
*/
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$ini_string='
[игрушка мягкая мишка белый]
цена = '. mt_rand(1, 10).';
количество заказано = '. mt_rand(1, 10).';
осталось на складе = '. mt_rand(0, 10).';
diskont = diskont'. mt_rand(0, 2).';
[одежда детская куртка синяя синтепон]
цена = '. mt_rand(1, 10).';
количество заказано = '. mt_rand(1, 10).';
осталось на складе = '. mt_rand(0, 10).';
diskont = diskont'. mt_rand(0, 2).';
[игрушка детская велосипед]
цена = '. mt_rand(1, 10).';
количество заказано = '. mt_rand(1, 10).';
осталось на складе = '. mt_rand(0, 10).';
diskont = diskont'. mt_rand(0, 2).';
';
$bd = parse_ini_string($ini_string, true);
echo "<h3>Содержание корзины</h3>";
echo '<table border=1><tr><td>Наименование</td><td>Цена за единицу товара</td><td>Количество заказано</td><td>Остаток на складе</td><td>Дисконт</td><td>Цена с учетом скидки</td></tr>';
global $info_am_ord;
global $balances;
global $total_price;
global $prices;
global $product_out;
foreach($bd as $name => $params){
$price = $params['цена'];
$ordered = $params['количество заказано'];
$balance = $params['осталось на складе'];
$diskont = $params['diskont'];
echo "<tr><td>".$name."</td>";
echo "<td>".$price." руб.</td>";
echo "<td>".$ordered."</td>";
echo "<td>".$balance."</td>";
if($name == '<NAME>' && $ordered >= 3 && $balance >= 3){
$disc = 'Вы заказали '.$name.' в количетсве '.$ordered.' штук, вам посчитана скидка 30% на эту позицию';
$diskont = 'diskont3';
}
echo "<td>".diskont($diskont)."%</td>";
echo "<td>";
if($name == '<NAME>' && $ordered >= 3 && $balance >= 3){
$disc = 'Вы заказали '.$name.' в количетсве '.$ordered.' штук, вам посчитана скидка 30% на эту позицию';
$diskont = 'diskont3';
}
$info_am_ord = $info_am_ord + $ordered; //Общее количество заказаных товаров:
if($ordered > $balance){
$ordered = $balance;
}
$total = $price*$ordered - ($price*$ordered*diskont($diskont)/100);//Цена с учетом скидки
echo $total;
echo " руб.</td></tr>";
if($balance == 0){
$product_out = '<h2>Уведомления:</h2>Нужного товара не оказалось на складе: <b>'.$name.'</b>';
}
$prices += $price*$ordered; //Сумма заказа:
$balances += $ordered;//Общее количество товара на складе:
$total_price += $total; //Общая сумма заказа по наличию на складе с учетом всех скидок:
}//закрытие foreach
$count_basket = count($bd);
echo '</table>';
if($product_out){
echo $product_out."<br>";
}
echo "<h2>Итого:</h2> Всего было заказано: ".$count_basket." наименований товара<br>";
echo " Общее количество заказаных товаров: ".$info_am_ord."<br>";
echo " Общее количество товара на складе: ".$balances."<br>";
echo " Сумма заказа: ".$prices." руб.<br>";
echo " Общая сумма заказа по наличию на складе с учетом всех скидок: ".$total_price." руб.<br>";
echo'<h2>Скидки</h2>';
if (isset($disc)) {echo $disc;}
//Вычисление скидки
function diskont($num){
$percent = substr($num,7,1)*10;
return $percent;
}
/*
*
* - Вам нужно вывести корзину для покупателя, где указать:
* 1) Перечень заказанных товаров, их цену, кол-во и остаток на складе
* 2) В секции ИТОГО должно быть указано: сколько всего наименовний было заказано, каково общее количество товара,
* какова общая сумма заказа
* - Вам нужно сделать секцию "Уведомления", где необходимо извещать покупателя о том, что нужного количества товара
* не оказалось на складе
* - Вам нужно сделать секцию "Скидки", где известить покупателя о том, что если он заказал "игрушка детская велосипед"
* в количестве >=3 штук, то на эту позицию ему
* автоматически дается скидка 30% (соответственно цены в корзине пересчитываются тоже автоматически)
* 3) у каждого товара есть автоматически генерируемый скидочный купон diskont, используйте переменную функцию,
* чтобы делать скидку на итоговую цену в корзине
* diskont0 = скидок нет, diskont1 = 10%, diskont2 = 20%
*
* В коде должно быть использовано:
* - не менее одной функции
* - не менее одного параметра для функции
* операторы if, else, switch
* статические и глобальные переменные в теле функции
*
*/
<file_sep>/dz9/smarty/templates_c/%%BA^BA6^BA6A03C0%%template.tpl.php
<?php /* Smarty version 2.6.25-dev, created on 2016-02-21 03:19:36
compiled from template.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'html_options', 'template.tpl', 37, false),)), $this); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Форма</title>
</head>
<body>
<h2>Форма добавление/изменения объявления</h2>
<form method='post'>
<div>
<label class="form-label-radio"><input type="radio" name="private" <?php if ($this->_tpl_vars['ad']['private'] == 1): ?>checked=""<?php endif; ?>value="1">Частное лицо</label>
<label class="form-label-radio"><input type="radio" name="private" <?php if ($this->_tpl_vars['ad']['private'] === '0'): ?>checked=""<?php endif; ?>value="0">Компания</label>
</div>
<div>
<label for='fld_seller_name'><b id='your-name'>Ваше имя</b></label>
<input type='text' maxlength='40' value='<?php echo $this->_tpl_vars['ad']['seller_name']; ?>
' name='seller_name' id='fld_seller_name'>
</div>
<div>
<label for='fld_email'>Электронная почта</label>
<input type='text' value='<?php echo $this->_tpl_vars['ad']['email']; ?>
' name='email' id='fld_email'>
</div>
<div>
<label for='allow_mails'> <input type='checkbox' value='1'
<?php if (( isset ( $this->_tpl_vars['ad']['allow_mails'] ) ) && $this->_tpl_vars['ad']['allow_mails'] == 1): ?>
checked=""
<?php endif; ?>
name='allow_mails' id='allow_mails' >
<span class='form-text-checkbox'>Я не хочу получать вопросы по объявлению по e-mail</span>
</label> </div>
<div>
<label id='fld_phone_label' for='fld_phone'>Номер телефона</label>
<input type='text' value='<?php echo $this->_tpl_vars['ad']['phone']; ?>
' name='phone' id='fld_phone'>
</div>
<div id='f_location_id'>
<label for="region">Город</label>
<?php echo smarty_function_html_options(array('name' => 'location_id','options' => $this->_tpl_vars['citys'],'selected' => $this->_tpl_vars['ad']['location_id']), $this);?>
</div>
<div>
<label for='fld_category_id'>Категория</label>
<?php echo smarty_function_html_options(array('name' => 'category_id','options' => $this->_tpl_vars['category'],'selected' => $this->_tpl_vars['ad']['category_id']), $this);?>
</div>
<div style='display: none;' id='params' class='form-row form-row-required'>
<label class='form-label '>Выберите параметры</label>
<div class='form-params params' id='filters'>
</div>
</div>
<div id='f_title' class='form-row f_title'>
<label for='fld_title'>Название объявления</label>
<input type='text' maxlength='50' class='form-input-text-long' value='<?php echo $this->_tpl_vars['ad']['title']; ?>
' name='title' id='fld_title'>
</div>
<div>
<label for='fld_description' id='js-description-label'>Описание объявления</label>
<textarea maxlength='3000' name='description' id='fld_description' class='form-input-textarea'><?php echo $this->_tpl_vars['ad']['description']; ?>
</textarea>
</div>
<div id='price_rw' class='form-row rl'>
<label id='price_lbl' for='fld_price'>Цена</label>
<input type='text' maxlength='9' value='<?php echo $this->_tpl_vars['ad']['price']; ?>
'
class='form-input-text-short' name='price' id='fld_price'> <span id='fld_price_title'>руб.</span>
</div>
<div style='display: none; margin-top: 0px;' class='form-row-indented images' id='files'>
<div style='display: none;' id='progress'>
<table>
<tbody>
<tr>
<td> <div><div></div></div> </td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='form-row-indented form-row-submit b-vas-submit' id='js_additem_form_submit'>
<div class='vas-submit-button pull-left'>
<span class='vas-submit-border'></span>
<span class='vas-submit-triangle'></span>
<input type='submit' value='<?php if (( isset ( $_GET['action'] ) ) && ( $_GET['action'] == 'show' )): ?>Сохранить<?php else: ?>Отправить<?php endif; ?>' id='form_submit' name='main_form_submit' class='vas-submit-input'>
</div>
</div>
</form>
<p></p>
<?php if (( isset ( $this->_tpl_vars['ads'] ) )): ?>
<?php $_from = $this->_tpl_vars['ads']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['id'] => $this->_tpl_vars['value']):
?>
<a href=?action=show&id=<?php echo $this->_tpl_vars['id']; ?>
><?php echo $this->_tpl_vars['value']['title']; ?>
</a> |
<?php echo $this->_tpl_vars['value']['price']; ?>
руб. | <?php echo $this->_tpl_vars['value']['seller_name']; ?>
| <a href=?action=del&id=<?php echo $this->_tpl_vars['id']; ?>
>Удалить</a><br>
<?php endforeach; endif; unset($_from); ?>
<?php endif; ?>
<?php if (( check_get_params ( $_GET ) )): ?>
<br><a href='index.php'>Добавить новое объявление >></a><br>
<?php endif; ?><file_sep>/smarty/templates_c/%%F7^F7F^F7F34188%%header.tpl.php
<?php /* Smarty version 2.6.25-dev, created on 2016-02-05 16:55:42
compiled from header.tpl */ ?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?php echo $this->_tpl_vars['title']; ?>
/ <?php echo $this->_tpl_vars['var1']; ?>
</TITLE>
<script>
function get_alert(){//Вместо левой фигурной скобки используется ldelim в скобках а правой rdelim
alert('test');
}
//get_alert();
</script>
<?php echo '
<script>
function get_alert2(){
alert(\''; ?>
<?php echo $this->_tpl_vars['title']; ?>
<?php echo '\');//если нужно использовать что-то в скобках, то закрываем его и снова открываем после
}
//get_alert2();
</script>
'; ?>
</HEAD>
<BODY bgcolor="#ffffff"><file_sep>/index6.php
<?
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
session_start();
//set_time_limit(5); //время выполнения скрипта в секундах, если 0 то бесконечно
/* $number = 5;
while($number >= 5) {
echo $number.'<br>';
$number++;
}
do while отличается от while тем что сначала выводится блок а потом уже проверяется условие, то есть 1 раз блок выведется в любом случае
$number = 5;
do {
echo $number.'<br>';
$number++;
}
while($number >= 5) ;
for($counter=1; $counter<5; $counter++){
echo "hello<br>";
}
*/
//Создается новый массив, содержащий 5 значений цвета
$colors = array('red', 'green', 'blue', 'yellow', 'white');
// Цикл for используется для итераций по массиву и вывода каждого элемента
for ($i = 0; $i < count($colors); $i++) {
echo "Значением элемента массива $i+1 является $colors[$i].<br>";
}
/* $colors = array('color1'=>'red','green','blue','yellow','white');
foreach($colors as $key => $value)
{
echo $key.' =>'. $value."<br>";
}
*/
// Бесконечным называется цикл такого вида:
//while (true) { … }
//или такого (что одно и то же):
//for (;;) { … }
$n = 10;
$i = 1;
while (true) {
echo "$i<br/>";
$i++;
if ($i > $n)
break; //выход из цикла
}
/*
$colors = array('first'=>'red','green','blue','yellow','white');
foreach($colors as &$value)//ссылка находит в памяти переменную и меняет ее
{
$value .=':no!';
if($value == 'blue:no!'){
break;//доходит до blue и далее не преобразовывает
}
}
print_r($colors);
*/
/*
$colors = array('first'=>'red','green','blue','yellow','white');
foreach($colors as &$value)
{
if($value == 'blue'){
continue;//доходит до blue пропускает его, а остальное продолжает
}
$value .=':no!';
}
print_r($colors);
*/
echo "<br>";
$n = 10;
for ($i = 1; $i <= $n; $i++) {
if ($i % 2 == 0) //если четные
continue; //то пропускать, остальные показывать
echo "$i<br/>";
}
$aLanguages = array("Slavic" => array("Russian", "Polish", "Slovenian"),
"Germanic" => array("Swedish", "Dutch", "English"),
"Romance" => array("Italian", "Spanish", "Romanian")
);
print_r($aLanguages);
foreach ($aLanguages as $sKey => $aFamily) {
// Вывести название семейства языков:
echo(
"<h2>$sKey</h2>" .
"<ul>"
);
// Теперь перечислить языки в каждом семействе:
foreach ($aFamily as $sLanguage) {
echo("<li>$sLanguage</li>");
}
// Завершить список:
echo("</ul>");
}
$x = 0;
global $x; //эту тоже увидит она глобальная
echo $GLOBALS['x']; //можно так обращаться
//print_r($GLOBALS);//содержит все массивы
//$_GET
//$_POST
//$_REQUIEST
//$_FILES
//$_COOKIE
$_SESSION['history'][date('d.m.Y H:i:s')] = $_GET;//записываем в сессию время захода и все что пападает в get массив
print_r($_SESSION);
unset($_SESSION['history']);//удаляем сессию<file_sep>/10-lesson/dbsimple.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$project_root = $_SERVER['DOCUMENT_ROOT'];
require_once $project_root . "/10-lesson/dbsimple/config.php";
require_once "DbSimple/Generic.php";
//Подключаем библиотеку
require_once $project_root . "/10-lesson/FirePHPCore/lib/FirePHP.class.php";
//Инициализируем класс
$firePHP = FirePHP::getInstance(true);
//Устанавливаем активность. Если false то в firebug не будет видно
$firePHP->setEnabled(true);
//Создаем тестовый массив
/*$myArray = array(
'name' => '123'
);*/
//Кидаем массив в лог
//$firePHP->log($myArray);
// Подключаемся к БД.
$db = DbSimple_Generic::connect('mysqli://test:123@localhost/test2'); //DNS //логин пароль хост база данных
// Устанавливаем обработчик ошибок.
$db->setErrorHandler('databaseErrorHandler');
// Устанавливаем логгер mysql
$db->setLogger('myLogger');
//обычный placeholder
//$result = $db->select("SELECT * FROM departments where id=?",$_GET['id']);
//выбор всех строк из таблицы departments
//print_r($result);
//ассоциативный placeholder
/* $ids = array(2, 3);
$result = $db->select("SELECT * FROM departments WHERE id IN(?a)", $ids); */
// выбрать все из таблицы где id находится в списке $ids
//print_r($result);
//INSERT
/* $row = array(
'id' => 110,
'name' => "Уборки"
); */
//$result = $db->query('INSERT departments SET ?a', $row);
//UPDATE
/* $row = array(
'name' => "Уборки помещений"
);
$id = 110;
$result = $db->query('UPDATE departments SET ?a WHERE id=?d' , $row, $id); */
//$row = array('id' => 111, 'name' => 'Клининг');
//$db->query('INSERT INTO departments(?#) VALUES(?a)', array_keys($row), array_values($row));
//вставление в таблицу через идентификаторно списковы плейсхолдер
//(?#) сюда передаются ключи массива (id, name), а сюда (?a) занчения массива
//$row = array('name' => 'Клининг');
//$db->query('INSERT INTO departments(?#) VALUES(?a)', array_keys($row), array_values($row));
//id можно не указывать он автоинкремментный
//$result = $db->select("SELECT id AS ARRAY_KEY,name FROM departments");
// таким образом id AS ARRAY_KEY,name id становится ключом массива а name просто значением
/*
Array
(
[1] => Array
(
[name] => Финансовый
)
[2] => Array
(
[name] => Почтовый
)
* */
//$result = $db->selectRow("SELECT id,name FROM departments");
//$db->selectRow выдает первый ряд одномерным массивом
/*
Array
(
[id] => 1
[name] => Финансовый
)
* */
//$result = $db->selectRow("SELECT id,name FROM departments WHERE id=?d", $_GET['id']);
//можно также указать какую строку именно нужно выбрать
/*
Array
(
[id] => 3
[name] => Доставка
)
* */
//если не писать $db->selectRow а просто $db->select то получился бы много мерный массив
/*
Array
(
[0] => Array
(
[id] => 3
[name] => Доставка
)
)
* */
//выбор ячейки
//$result = $db->selectCell("SELECT name FROM departments WHERE id=?d", $_GET['id']);
/* выведет просто 'Доставка' название ячейки для ввдеденного id */
//не надо делать циклы и прочее
$ads = $db->select('SELECT * FROM departments');
$firePHP->table('Table label', $ads);
//выбрать колонку со всеми названиями наших...
/*
Array
(
[0] => Финансовый
[1] => Почтовый
[2] => Доставка
[3] => Уборки помещений
[4] => Клининг
[5] => Клининг
[6] => Клининг
)
* Удобно делает это индексным массивом */
//print_r($result);
$db->select('SELECT * FROM departments');
//логирование запросов
//подключили это на 15 строке $DB->setLogger('myLogger');
function myLogger($db, $sql, $caller) {
global $firePHP;
if(isset($caller['file'])){
$firePHP->group("at " . @$caller['file'] . ' line ' . @$caller['line']);
}
$firePHP->log($sql);
if(isset($caller['file'])){
$firePHP->groupEnd();
}
}
//показывает какие запросы сделаны и сколько строк затронуто и пр.
// Код обработчика ошибок SQL.
function databaseErrorHandler($message, $info) {
// Если использовалась @, ничего не делать.
if (!error_reporting())
return;
// Выводим подробную информацию об ошибке.
echo "SQL Error: $message<br><pre>";
print_r($info);
echo "</pre>";
exit();
}
<file_sep>/index8.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$project_root = $_SERVER['DOCUMENT_ROOT'];
$smarty_dir = $project_root . '/smarty/';
// put full path to Smarty.class.php
require($smarty_dir . 'libs/Smarty.class.php');
$smarty = new Smarty(); //создаем новый объект смарти и запис в перемен
$smarty->compile_check = true; //обращаемся к свойствам объекта чтобы их выставить
$smarty->debugging = false; //дебаггер
$smarty->template_dir = $smarty_dir . 'templates';
$smarty->compile_dir = $smarty_dir . 'templates_c';
$smarty->cache_dir = $smarty_dir . 'cache';
$smarty->config_dir = $smarty_dir . 'configs';
$massive = array('first' => 'Mary', 'John', 'Ted'); //создаем массив
if (isset($_GET['mobile'])) {
$smarty->assign('header_template', 'header_mobile'); //будет создана переменная h.._t.. куда попадет header_mobile
} else {
$smarty->assign('header_template', 'header'); // иначе обычный header.tpl
}
$smarty->assign('name', 'Игорь'); //добавляем в шаблон name
$smarty->assign('title', 'Название сайта');
$smarty->assign('raz', time());
$smarty->assign('names', $massive); //добавляем в шаблон наш массив
$smarty->assign('Contacts', array('fax' => '555-222-9876',
'email' => '<EMAIL>',
'phone' => array('home' => '555-444-3333',
'cell' => '555-111-1234')
)
);
$items_list = array(23 => array('no' => 2456, 'label' => 'Salad'),
96 => array('no' => 4889, 'label' => 'Cream')
);
$smarty->assign('items', $items_list);
$not_smarty = 'test';
$smarty->assign('cust_options', array(
1000 => '<NAME>',
1001 => '<NAME>',
1002 => '<NAME>',
1003 => '<NAME>')
);
$smarty->assign('customer_id', 1001);//выбран по умолчанию
$smarty->assign('data',array(1,2,3,4,5,6,7,8,9));
$smarty->assign('tr',array('bgcolor="#eeeeee"','bgcolor="#dddddd"'));
$smarty->display('index.tpl'); //показывает что нужно вывести шаблон index.tpl
<file_sep>/dz9_mysqli/index.php
<?php
require('config.php');
$db = mysqli_connect('localhost', 'form_user', '1234', 'form') or die(mysql_error());
mysqli_query($db,"SET NAMES utf8");
require('functions.php');
add_up_del_ads(); //добавление/обновление
getAds(); //показы списка
delAds(); //удаление объявления
get_id_key_exists(); //проверка на существование ключа
if (isset($ads)) {
$smarty->assign('ads', $ads);
}
if (check_get_params()) {
$smarty->assign('ad', $ad);
} else {
$smarty->assign('ad', NULL);
}
if (check_get_params()) {
$smarty->assign('id', $_GET['id']);
}
$smarty->assign('citys', getCitys($db));
$smarty->assign('category', getCategories($db));
if (isset($last_id)) {
$smarty->assign('last_id', $last_id);
}
$smarty->display('template.tpl');
<file_sep>/9-lesson_mysqli/procedural/insert.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title></title>
</head>
<body>
<h1>Вставка новой записи</h1>
<?php
$db = mysqli_connect('localhost', 'root', '', 'xmpl');
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
$stmt = mysqli_prepare($db, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
$username = 'author';
$password = '<PASSWORD>';
mysqli_stmt_execute($stmt);
echo '<p>Было затронуто строк: ' . mysqli_affected_rows($db) . "</p>";
echo '<p>ID вставленной записи: ' . mysqli_insert_id($db) . "</p>";
mysqli_stmt_close($stmt);
mysqli_close($db);
?>
</body>
</html><file_sep>/dz9_mysqli/config.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$project_root = $_SERVER['DOCUMENT_ROOT'];
$smarty_dir = $project_root . '/dz9/smarty/';
//
// put full path to Smarty.class.php
require($smarty_dir . 'libs/Smarty.class.php');
$smarty = new Smarty(); //создаем новый объект смарти и записываем в переменную
$smarty->compile_check = true; //обращаемся к свойствам объекта чтобы их выставить
$smarty->debugging = false; //дебаггер
$smarty->template_dir = $smarty_dir . 'templates';
$smarty->compile_dir = $smarty_dir . 'templates_c';
$smarty->cache_dir = $smarty_dir . 'cache';
$smarty->config_dir = $smarty_dir . 'configs';<file_sep>/9-lesson_mysqli/db.sql
CREATE DATABASE `xmpl` ;
USE `xmpl`;
CREATE TABLE `xmpl`.`users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL
) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `xmpl`.`users` (`id`, `username`, `password`) VALUES (NULL, 'guest', '<PASSWORD>');
INSERT INTO `xmpl`.`users` (`id`, `username`, `password`) VALUES (NULL, 'user', '<PASSWORD>');
INSERT INTO `xmpl`.`users` (`id`, `username`, `password`) VALUES (NULL, 'admin', '<PASSWORD>');<file_sep>/9-lesson_mysqli/oop/simple-select.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title></title>
</head>
<body>
<h1>Простая выборка на MySQLi</h1>
<?php
$db = new mysqli('localhost', 'root', '', 'xmpl');
$sql = "SELECT * FROM users";
$result = $db->query($sql); // mysql_query(///)
echo "<h2>Вывод записей из результата по одной: </h2>";
while($user = $result->fetch_assoc()) { // mysql_fetch_assoc(...)
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['password']}. <br />";
}
echo "<hr />";
$sql = "SELECT * FROM users";
$result = $db->query($sql);
$users = $result->fetch_all(MYSQLI_ASSOC);
echo "<h2>Выборка все записей в массив и вывод на экран: </h2>";
foreach ($users as $user) {
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['password']}. <br />";
}
echo "<hr />";
$sql = "SELECT * FROM users";
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $username, $password);
echo "<h2>Вывод записей с помощью подготовленного выражения и привязка данных к переменным: </h2>";
while ($stmt->fetch()) {
echo "{$id}. Username: {$username}, Password: {$password}. <br />";
}
$stmt->close();
$db->close();
?>
</body>
</html><file_sep>/dz_2.php
<?php
/*Задание 1*/
$name = 'Игорь';
$age = 28;
echo '"Меня зовут '."$name\"\n".' <br>"Мне '.$age.' лет"';
unset($name);
unset($age);
echo '<br><br>';
/*Задание 2*/
define("CITY", "Москва");
if (defined("CITY")) {
echo CITY;
}
else {
echo '<br>Константа не существует';
}
echo '<br><br>';
define("CITY", "Новосибирск");
/*Задание 3*/
$book = array(
'title'=>'Транссерфинг реальности',
'author'=>'<NAME>',
'pages'=>'589'
);
echo '"Недавно я прочитал книгу \''.$book['title'].'\', написанную автором '.$book['author'].', я осилил все '.$book['pages'].' страниц, мне она очень понравилась"';
echo '<br><br>';
/*Задание 4*/
$book1 = array('title1'=>'Транссерфинг реальности', 'author1'=>'<NAME>', 'pages1'=>'589');
$book2 = array('title2'=>'Я такой как все', 'author2'=>'<NAME>', 'pages2'=>'571');
$books = array($book1,$book2);
$total_pages = $books['0']['pages1']+$books['1']['pages2'];
echo '"Недавно я прочитал книги \''.$books['0']['title1'].'\' и \''.$books['1']['title2'].'\', написанные соответственно авторами '.$books['0']['author1'].' и '.$books['1']['author2'].', я осилил в сумме '.$total_pages.' страниц, не ожидал от себя подобного"';<file_sep>/9-lesson_mysqli/procedural/simple-select.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title></title>
</head>
<body>
<h1>Простая выборка на MySQLi</h1>
<?php
$db = mysqli_connect('localhost', 'root', '', 'xmpl');
$sql = "SELECT * FROM users";
$result = mysqli_query($db, $sql); // mysql_query(///)
echo "<h2>Вывод записей из результата по одной: </h2>";
while($user = mysqli_fetch_assoc($result)) { // mysql_fetch_assoc(...)
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['password']}. <br />";
}
echo "<hr />";
$sql = "SELECT * FROM users";
$result = mysqli_query($db, $sql);
$users = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo "<h2>Выборка все записей в массив и вывод на экран: </h2>";
foreach ($users as $user) {
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['<PASSWORD>']}. <br />";
}
echo "<hr />";
$sql = "SELECT * FROM users";
$stmt = mysqli_prepare($db, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $username, $password);
echo "<h2>Вывод записей с помощью подготовленного выражения и привязка данных к переменным: </h2>";
while (mysqli_stmt_fetch($stmt)) {
echo "{$id}. Username: {$username}, Password: {$password}. <br />";
}
mysqli_stmt_close($stmt);
mysqli_close($db);
?>
</body>
</html><file_sep>/index4.php
<?
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$my_name = 'Igor';
echo ($my_name == 'Igor' ? 'yes' : 'no');
echo "\n";
//тернарный оператор
$test = 'Игорь';
/*function test_ok ($p) {
global $test; //функция будет использовать глобальные переменные объявленные вне
echo $test.'-'.$p;
}
test_ok (28);*/
function test_ok (&$p) { //&=> передача параметров по ссылки
$p.=' 28 y.o';
}
//идет в память и меняет значение переменной
test_ok($test);
echo $test;<file_sep>/smarty/templates_c/%%3C^3CB^3CB46C1C%%header_mobile.tpl.php
<?php /* Smarty version 2.6.25-dev, created on 2016-02-05 16:44:45
compiled from header_mobile.tpl */ ?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>Mobile: <?php echo $this->_tpl_vars['title']; ?>
/ <?php echo $this->_tpl_vars['var1']; ?>
</TITLE>
</HEAD>
<BODY bgcolor="#ffffff"><file_sep>/9-lesson_mysqli/oop/select-with-params.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title></title>
</head>
<body>
<h1>Выборка с параметрами на MySQLi</h1>
<?php
$db = new mysqli('localhost', 'root', '', 'xmpl');
$username = 'guest';
$password = '<PASSWORD>'; // "' OR '1'='1"
$sql = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$<PASSWORD>}' LIMIT 1";
$result = $db->query($sql);
echo "<h2>Выборка записи без защиты от SQL инъекции: </h2>";
if ($result->num_rows == 1) {
$user = $result->fetch_assoc();
echo "{$user['id']}. Username: {$user['username']}, Password: {$<PASSWORD>['<PASSWORD>']}. <br />";
}
echo "<hr />";
$username = $db->real_escape_string('guest');
$password = $db->real_escape_string('<PASSWORD>'); // "' OR '1'='1"
$sql = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$<PASSWORD>}' LIMIT 1";
$result = $db->query($sql);
echo "<h2>Выборка записи с \"ручной\" защитой от SQL инъекции: </h2>";
if ($result->num_rows == 1) {
$user = $result->fetch_assoc();
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['password']}. <br />";
}
echo "<hr />";
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $usrnm, $psswrd);
$usrnm = 'guest';
$psswrd = '<PASSWORD>'; // "' OR '1'='1"
$stmt->execute();
$stmt->bind_result($id, $username, $password);
echo "<h2>Выборка записи с \"автоматической\" защитой от SQL инъекции: </h2>";
$stmt->fetch();
echo "{$id}. Username: {$username}, Password: {$password}. <br />";
$stmt->close();
$db->close();
?>
</body>
</html><file_sep>/index.php
<?
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
phpinfo();
echo "cell:" . ceil(4) . "<br>";
echo "floor:" . floor(6.945) . "<br>";
echo "floor:" . round(6.236) . "<br>";
echo "floor:" . round(6.236, 2) . "<br>"; //2 цифры после запятой
echo "floor:" . round(6.2366, 3) . "<br>"; //3 цифры после запятой
echo min(6, 2366, 3, 256) . "<br>"; //минимальное число
echo max(6, 236, 3, 235) . "<br>"; //максимальное число
//echo rand(0,10)."<br>";//случайно сгененрированное число, иногда подряд одно и то же число выдает, чтобы этого не было делается следующее
mt_srand(time());
echo mt_rand(10, 100) . "<br>";
$str = "1234567890";
echo strlen($str) . "<br>"; //считает длинну строки
$name = " | Igor . ";
echo var_dump(trim($name, '. |')) . "<br>"; //удаляет пробелы, вторым параметром можно добавить чтобы удаляло символы и их записать подряд
//rtrim(); чистит справа ltrim(); чистит слева
$str2 = "|privet kak dela|";
echo strtoupper($str2) . "<br>";
echo strrev($str2) . "<br>"; //реверс
echo substr($str2, 1, 3) . "<br>"; //берет часть строки первое число позиция с которой начинать, второе сколько символов брать
// если взять -2 позицию то с конца начнется отсчет
echo strstr($str2, 'i') . "<br>"; // начинает с этой буквы
//pattern шаблон
if (!preg_match_all('/(\d+)/', 'raz, dva, 345 555 678', $matches1)) {
echo 'yes';
}
//print_r($matches1);
if (preg_match('/Ticket\s+(\d+)/i', 'Ticket 15', $matches2)) {
echo 'yes';
}
print_r($matches2) . "<br>";
$_SERVER;
echo count($_SERVER) . "<br>";
//echo sort($_SERVER)."<br>";//сортирует и создает индексный массив из ассоциативного
//echo ksort($_SERVER)."<br>";//сортирует оставив массив ассоциативным
//echo array_multisort($_SERVER, SORT_DESC)."<br>";//
//echo rsort($_SERVER)."<br>";//
//echo krsort($_SERVER)."<br>";//сортировка по ключам в обратном порядке
/* function shuffle_assoc($list) {
if (!is_array($list))
return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
$_SERVER = shuffle_assoc($_SERVER);
echo "<pre>";
print_r($_SERVER);
echo "</pre>"; */
$new = array_slice($_SERVER, 0, 1); //берет 5 сконца элемент и от него берет 3 элемента
$new2 = array_slice($_SERVER, -1, 1);
$new4 = array_slice($_SERVER, -5, 1);
echo "\n";
echo "<pre>";
print_r($new);
print_r($new2);
print_r($new4);
$new3 = array_merge($new, $new2, $new4);
print_r($new3);
print_r($_SERVER);
echo "</pre>";
//Array_diff, array_intersect, array_pop, array_shift, array_flip
/*$a = array("apple","banana");
$b = array("banana","coconut");
$c = array("banana","orange");
$d = array_diff($a, $b, $c);
print_r($a);
print_r($b);
print_r($c);
print_r($d);
echo '<br>';
$d = array_intersect($a, $b, $c);
print_r($a);
print_r($b);
print_r($c);
print_r($d);*/
/*Находит схождения, выведет банан
echo "\n";
$a = array("apple","banana","coconut","orange");
$b = array_pop($a);
var_dump(array_pop($a));
var_dump($a);
//выталкивает последний элемент из массива*/
/*echo "\n";
$a = array("apple","banana","coconut","orange");
$b = array_shift($a);
//var_dump(array_shift($a));
var_dump($b);
var_dump($a);
//выталкивает первый элемент из массива*/
echo "\n";
$a = array("apple","banana","coconut","orange","coconut");
print_r($a);
$a = array_flip($a);
print_r($a);
$a = array_flip($a);
print_r($a);
//ключи становятся значениями а значения ключами
//в этом примере благодаря перевороту 2 раза удалились дублирующиеся значения coconut
echo "<br><br><br>";
function printme ($val1,$val2,$val3){
echo $val1.'-'.$val2.'-'.$val3."\n";
}
array_map('printme',array('a','b'),array('c','d'),array('e','g'));
echo "<br><br><br>";
echo date_default_timezone_get();
date_default_timezone_set('Asia/Novosibirsk');
echo date('l d.m.Y H:i:s');
//echo ":".time();//1 января 1970 начало эпохи unix//timestamp
//php date time zone загуглить документация с часовыми поясами
//создаем штамп времени
//$timestamp = mktime(1,1,1,1,1,2014);//1 секнда 1 минуты 1 часа первого дня первого месяца 2014 года
//echo $timestamp;
//echo "\n".date('l d.m.Y H:i:s',$timestamp);//c помощью функции date форматировали в удобочитаемый вид
echo "\n";
$timestamp = strtotime('2015-01-09 1:53:00');//нормальную дату преобразовываем в строку
echo $timestamp." в ненормальную строку";
echo "\n".date('l d.m.Y H:i:s',$timestamp); // обратно в нормальный формат
echo "\n";
$timestamp = strtotime('2015-01-09 1:53:00 +78 days -7 hours +0 minutes');//функция понимает если ее спросить что букдет через 7 дней 7 часов и т. д.
echo "\n".date('l d.m.Y H:i:s',$timestamp);
echo "\n";
$timestamp = strtotime('last sunday');//функция какое число было прошлое воскресменье
echo "\n".date('l d.m.Y H:i:s',$timestamp);
$timestamp = strtotime('last sunday -7 days');//и позапрошлое
echo "\n".date('l d.m.Y H:i:s',$timestamp);
echo "\n";
echo "\n";
echo "\n";
echo "\n";
echo "\n";
echo "\n";
echo "\n";<file_sep>/dz3.php
<?php
/*
* Следующие задания требуется воспринимать как ТЗ (Техническое задание)
* p.s. Разработчик, помни!
* Лучше уточнить ТЗ перед выполнением у заказчика, если ты что-то не понял, чем сделать, переделать, потерять время, деньги, нервы, репутацию.
* Не забывай о навыках коммуникации :)
*
* Задание 1
* - Создайте массив $date с пятью элементами
* - C помощью генератора случайных чисел забейте массив $date юниксовыми метками
* - Сделайте вывод сообщения на экран о том, какой день в сгенерированном массиве получился наименьшим, а какой месяц наибольшим
* - Отсортируйте массив по возрастанию дат
* - С помощью функция для работы с массивами извлеките последний элемент массива в новую переменную $selected
* - C помощью функции date() выведите $selected на экран в формате "дд.мм.ГГ ЧЧ:ММ:СС"
* - Выставьте часовой пояс для Нью-Йорка, и сделайте вывод снова, чтобы проверить, что часовой пояс был изменен успешно
*
*/
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$date = array();
date_default_timezone_set('Asia/Novosibirsk');
$i=0;
while ($i++ < 5) {
$date[] = mt_rand(0, time());
$month[] = date('m', $date[$i-1]);
$day[] = date('d', $date[$i-1]);
}
print_r($date);
print_r($month);
print_r($day);
echo "Наименьший день в массиве: ".min($day[0],$day[1],$day[2],$day[3],$day[4])."\n" ; //минимальный день
echo "Наибольший месяц в массиве: ".max($month[0],$month[2],$month[2],$month[3],$month[4])."\n";
sort($date);
print_r($date);
echo "\n";
$selected = array_pop($date);
echo $selected."\n";
echo date('d.m.y H:i:s', $selected)."\n";
print_r($date);
//$selected = date('d.m.y H:i:s',$selected);
//echo $selected."\n";
//echo "Мой часовой пояс: ".date_default_timezone_get()." Мое время: ".date('d.m.y H:i:s', $selected)."\n";
//date_default_timezone_set('America/New_York');
//echo "Новый часовой пояс: ".date_default_timezone_get()." Новое время: ".date('d.m.y H:i:s', $selected);
//Здесь я пытался изменить часовой пояс у переменной в которую попало значение даты, но из этого ничего не вышло т. к.
//функция не может изменить время в переменной, это уже просто строка. Правильное решение приведено ниже.
echo "Мой часовой пояс: ".date_default_timezone_get()." Мое время: ".date('d.m.y H:i:s', $selected)."\n";
date_default_timezone_set('America/New_York');
echo "Новый часовой пояс: ".date_default_timezone_get()." Новое время: ".date('d.m.y H:i:s', $selected);<file_sep>/dz10/functions.php
<?php
// Добавление объявления
function add_ads($post) {
global $db;
//реализовать добавление объявления в базу
if (!isset($post['allow_mails'])) {
$post['allow_mails'] = "0";
}
$row = array(
'private' => $post['private'],
'seller_name' => $post['seller_name'],
'email' => $post['email'],
'allow_mails' => $post['allow_mails'],
'phone' => $post['phone'],
'location_id' => $post['location_id'],
'category_id' => $post['category_id'],
'title' => $post['title'],
'description' => $post['description'],
'price' => $post['price']
);
$db->query('INSERT ads SET ?a', $row);
}
// обновление объявления
function up_ads($post) {
global $db;
//перезаписать объявление в базу
if (!isset($post['allow_mails'])) {
$post['allow_mails'] = "0";
}
$row = array(
'private' => $post['private'],
'seller_name' => $post['seller_name'],
'email' => $post['email'],
'allow_mails' => $post['allow_mails'],
'phone' => $post['phone'],
'location_id' => $post['location_id'],
'category_id' => $post['category_id'],
'title' => $post['title'],
'description' => $post['description'],
'price' => $post['price']
);
$id = $_GET['id'];
$db->query('UPDATE ads SET ?a WHERE id=?d', $row, $id);
}
function delAds($id) {
global $db;
$result = $db->query("delete from ads where id = ?", $id);
}
function getAds() {
global $db;
global $firePHP;
$ads = $db->select("select ads.id AS ARRAY_KEY ,private,seller_name,email,allow_mails,phone,ads.location_id,ads.category_id,title,description,price,categories.category_id as categories_category_id,citys.location_id as citys_location_id,category,city from ads left join categories on (ads.category_id=categories.category_id) left join citys on (ads.location_id=citys.location_id)");
$firePHP->table('Table ads', $ads);
if (isset($ads)) {
return $ads;
}
}
//Функция проверки формы и сохраниение в сессию
function validate($post) {
if (isset($post['private']) &&
isset($post['main_form_submit']) &&
!empty($post['seller_name']) &&
!empty($post['email']) &&
!empty($post['phone']) &&
!empty($post['location_id']) &&
!empty($post['category_id']) &&
!empty($post['title']) &&
!empty($post['description']) &&
!empty($post['price'])) {
return true;
} else {
return false;
}
}
//Функция проверки полей формы
function check_get_params($get) {
if (isset($get['action']) && $get['action'] == 'show' && isset($get['id'])) {
return true;
} else {
return false;
}
}
function print_arr($a) {
echo"<pre>";
print_r($a);
echo"</pre>";
}
function getCitys() {
global $db;
global $firePHP;
$citys = $db->selectCol("select location_id AS ARRAY_KEY, city from citys");
$firePHP->table('Table citys', $citys);
return $citys;
}
function getCategories() {
global $db;
global $firePHP;
$categories = $db->selectCol("select category_id AS ARRAY_KEY, category from categories");
$firePHP->table('Table categories', $categories);
return $categories;
}
function myLogger($db, $sql, $caller) {
global $firePHP;
if (isset($caller['file'])) {
$firePHP->group("at " . @$caller['file'] . ' line ' . @$caller['line']);
}
$firePHP->log($sql);
if (isset($caller['file'])) {
$firePHP->groupEnd();
}
}
//показывает какие запросы сделаны и сколько строк затронуто и пр.
// Код обработчика ошибок SQL.
function databaseErrorHandler($message, $info) {
// Если использовалась @, ничего не делать.
if (!error_reporting())
return;
// Выводим подробную информацию об ошибке.
echo "SQL Error: $message<br><pre>";
print_r($info);
echo "</pre>";
exit();
}
<file_sep>/dz8/index.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$project_root = $_SERVER['DOCUMENT_ROOT'];
$smarty_dir = $project_root . '/dz8/smarty/';
//
// put full path to Smarty.class.php
require($smarty_dir . 'libs/Smarty.class.php');
$smarty = new Smarty(); //создаем новый объект смарти и запис в перемен
$smarty->compile_check = true; //обращаемся к свойствам объекта чтобы их выставить
$smarty->debugging = false; //дебаггер
$smarty->template_dir = $smarty_dir . 'templates';
$smarty->compile_dir = $smarty_dir . 'templates_c';
$smarty->cache_dir = $smarty_dir . 'cache';
$smarty->config_dir = $smarty_dir . 'configs';
///////////////////////////////////////////////////////////////////////////////////
if (file_exists('ads.html')) {
$ads = file_get_contents('ads.html');
$ads = unserialize($ads);
}
//Функция проверки формы и сохраниение в сессию
function validate($post) {
if (isset($post['private']) &&
isset($post['main_form_submit']) &&
!empty($post['seller_name']) &&
!empty($post['email']) &&
!empty($post['phone']) &&
!empty($post['location_id']) &&
!empty($post['category_id']) &&
!empty($post['title']) &&
!empty($post['description']) &&
!empty($post['price'])) {
return true;
} else {
return false;
}
}
//Функция проверки полей формы
function check_get_params() {
if (isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['id'])) {
return true;
} else {
return false;
}
}
if (validate($_POST) && !check_get_params()) {
$ads[] = $_POST;
} elseif (check_get_params() && isset($_POST['main_form_submit'])) {//при сохранении объявления
$ads[$_GET['id']] = $_POST; //Перезаписать данные в массив с определенным индексом который берется из get id
} elseif (isset($_GET['action']) && !isset($_POST['main_form_submit'])) {//если существует GET['action'] и при этом не нажата кнопка
$id = $_GET['id'];
if ($_GET['action'] == 'del' && isset($ads[$id])) {
unset($ads[$id]);
}
}
if (isset($ads)) {
file_put_contents('ads.html', serialize($ads));
}
if (isset($_GET['id']) && array_key_exists($_GET['id'], $ads)) {//проверка существует ли array_key_exists ключ в массиве
$ad = $ads[$_GET['id']];
} else {
$ad = '';
}
/////////////////////////////////////////////
if (isset ($ads)) {$smarty->assign('ads', $ads);}
if (check_get_params()) {
$smarty->assign('ad', $ad);
} else {
$smarty->assign('ad', NULL);
}
if (check_get_params()) {
$smarty->assign('id', $_GET['id']);
}
$smarty->assign('citys', array('641780' => 'Новосибирск', '641490' => 'Барабинск', '641510' => 'Бердск'));
$smarty->assign('category', array('24' => 'Квартиры',
'23' => 'Комнаты',
'25' => 'Дома, дачи, коттеджи')
);
$smarty->assign('private', array('1' => 'Частное лицо', '0' => 'Компания'));
$smarty->display('template.tpl');<file_sep>/dz10/install.php
<form action="" method="post">
Server name:<br>
<input type="text" name="server_name"><br><br>
User name:<br>
<input type="text" name="user_name"><br><br>
Password:<br>
<input type="text" name="password"><br><br>
Database:<br>
<input type="text" name="database">
<p><input type="submit" name="button" value="Install"></p>
</form>
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 0);
require('config.php');
function check_form() {
if (isset($_POST['button'])) {
if (!empty($_POST['server_name']) &&
!empty($_POST['user_name']) &&
!empty($_POST['password']) &&
!empty($_POST['database'])) {
global $server_name;
$server_name = $_POST['server_name'];
global $user_name;
$user_name = $_POST['user_name'];
global $password;
$password = $_POST['password'];
global $database;
$database = $_POST['database'];
return true;
} else {
echo "Заполните все поля";
}
}
}
if (check_form()) {
$db = DbSimple_Generic::connect('mysqli://form_user:1234@localhost/form');
$db->select("SET NAMES utf8");
$db->select("SET time_zone = '+00:00'");
$db->select("SET foreign_key_checks = 0");
$db->select("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'");
$db->select("DROP TABLE IF EXISTS `ads`");
$db->select("CREATE TABLE `ads` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`private` tinyint(4) NOT NULL,
`seller_name` varchar(10) NOT NULL,
`email` varchar(15) NOT NULL,
`allow_mails` tinyint(4) NOT NULL,
`phone` varchar(12) NOT NULL,
`location_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`title` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`price` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8");
$db->select("INSERT INTO `ads` (`id`, `private`, `seller_name`, `email`, `allow_mails`, `phone`, `location_id`, `category_id`, `title`, `description`, `price`) VALUES
(34,1,'4654','4446',1,'464',641490,25,'4564','4465','44'),
(36,1,'464','446',1,'464',641780,24,'4664','4646','4664')");
$db->select("DROP TABLE IF EXISTS `categories`");
$db->select("CREATE TABLE `categories` (
`category_id` varchar(3) NOT NULL,
`category` varchar(10) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8");
$db->select("INSERT INTO `categories` (`category_id`, `category`) VALUES
('24','Квартиры'),
('23','Комнаты'),
('25','Дома, дачи')");
$db->select("DROP TABLE IF EXISTS `citys`");
$db->select("CREATE TABLE `citys` (
`location_id` varchar(10) NOT NULL,
`city` varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8");
$db->select("INSERT INTO `citys` (`location_id`, `city`) VALUES
('641780','Новосибирск'),
('641490','Барабинск'),
('641510','Бердск')");
$db->select("DROP TABLE IF EXISTS `private`");
echo "<a href='index.php'>Перейти на сайт</a>";
}<file_sep>/9-lesson_mysqli/procedural/select-with-params.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title></title>
</head>
<body>
<h1>Выборка с параметрами на MySQLi</h1>
<?php
$db = mysqli_connect('localhost', 'root', '', 'xmpl');
$username = 'guest';
$password = '<PASSWORD>'; // "' OR '1'='1"
$sql = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$<PASSWORD>}' LIMIT 1";
$result = mysqli_query($db, $sql);
echo "<h2>Выборка записи без защиты от SQL инъекции: </h2>";
if (mysqli_num_rows($result) == 1) {
$user = mysqli_fetch_assoc($result);
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['<PASSWORD>']}. <br />";
}
echo "<hr />";
$username = mysqli_real_escape_string($db, 'guest');
$password = mysqli_real_escape_string($db, '<PASSWORD>'); // "' OR '1'='1"
$sql = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$<PASSWORD>}' LIMIT 1";
$result = mysqli_query($db, $sql);
echo "<h2>Выборка записи с \"ручной\" защитой от SQL инъекции: </h2>";
if (mysqli_num_rows($result) == 1) {
$user = mysqli_fetch_assoc($result);
echo "{$user['id']}. Username: {$user['username']}, Password: {$user['password']}. <br />";
}
echo "<hr />";
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
$stmt = mysqli_prepare($db, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $usrnm, $psswrd);
$usrnm = 'guest';
$psswrd = '<PASSWORD>'; // "' OR '1'='1"
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $username, $password);
echo "<h2>Выборка записи с \"автоматической\" защитой от SQL инъекции: </h2>";
mysqli_stmt_fetch($stmt);
echo "{$id}. Username: {$username}, Password: {$password}. <br />";
mysqli_stmt_close($stmt);
mysqli_close($db);
?>
</body>
</html><file_sep>/dz10/index.php
<?php
require('config.php');
// Подключаемся к БД.
$db = DbSimple_Generic::connect('mysqli://form_user:1234@localhost/form'); //DNS //логин пароль хост база данных
// Устанавливаем обработчик ошибок.
$db->setErrorHandler('databaseErrorHandler');
// Устанавливаем логгер mysql
$db->setLogger('myLogger');
require('functions.php');
if (check_get_params($_GET)) {
$id = $_GET['id'];
$smarty->assign('id', $_GET['id']);
} else {
$id = '';
}
if (validate($_POST) && !check_get_params($_GET)) { //если заполнена форма и гет параметров нет
add_ads($_POST);
} elseif (check_get_params($_GET) && isset($_POST['main_form_submit'])) {//при сохранении объявления
up_ads($_POST);
}
if (isset($_GET['action']) && !isset($_POST['main_form_submit']) && $_GET['action'] == 'del') { //если существует GET['action'] и при этом не нажата кнопка
delAds($_GET['id']); //удаление объявления
}
$ads = getAds(); //показы списка
//проверка существует ли ключ в массиве
if (isset($_GET['id']) && isset($ads) && array_key_exists($_GET['id'], $ads)) {
$ad = $ads[$_GET['id']];
} else {
$ad = '';
}
if (isset($ads)) {
$smarty->assign('ads', $ads);
}
if (check_get_params($_GET)) {
$smarty->assign('ad', $ad);
} else {
$smarty->assign('ad', NULL);
}
$smarty->assign('citys', getCitys());
$smarty->assign('category', getCategories());
if (isset($last_id)) {
$smarty->assign('last_id', $last_id);
}
$smarty->display('template.tpl');<file_sep>/dz5_1.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
//GET
$news='Четыре новосибирские компании вошли в сотню лучших работодателей
Выставка университетов США: открой новые горизонты
Оценку «неудовлетворительно» по качеству получает каждая 5-я квартира в новостройке
Студент-изобретатель раскрыл запутанное преступление
Хоккей: «Сибирь» выстояла против «Ак Барса» в пятом матче плей-офф
Здоровое питание: вегетарианская кулинария
День святого Патрика: угощения, пивной теннис и уличные гуляния с огнем
«Красный факел» пустит публику на ночные экскурсии за кулисы и по закоулкам столетнего здания
Звезды телешоу «Голос» <NAME> и <NAME> споют в «Маяковском»';
$news = explode("\n", $news);
$get = $_GET;
// Функция вывода всего списка новостей.
function all_news($news) {
foreach($news as $id => $new) {
echo $new."<br>";
}
}
// Функция вывода конкретной новости.
function one_news($news,$get) {
echo $news[$get['id']-1];
}
if (isset ($get['id']) && $get['id'] <= count($news) && $get['id'] > 0 && is_numeric($get['id'])){
one_news($news,$get);
}
elseif (isset ($get['id']) && $get['id'] > count($news) && is_numeric($get['id'])){
all_news($news);
}
elseif (!empty($get) && !isset ($get['id']) or isset ($get['id']) && $get['id'] <= 0) {
header('Location: 404.php');
exit;
}
// Точка входа.
// Если новость присутствует - вывести ее на сайте, иначе мы выводим весь список
// Был ли передан id новости в качестве параметра?
// если параметр не был передан - выводить 404 ошибку
// http://php.net/manual/ru/function.header.php
<file_sep>/dz10/config.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$project_root = $_SERVER['DOCUMENT_ROOT'];
$smarty_dir = $project_root . '/dz10/smarty/';
// put full path to Smarty.class.php
require($smarty_dir . 'libs/Smarty.class.php');
require_once $project_root . "/dbsimple/config.php";
require_once $project_root ."/dbsimple/DbSimple/Generic.php";
//Подключаем библиотеку
require_once $project_root . "/FirePHPCore/lib/FirePHP.class.php";
//Инициализируем класс
$firePHP = FirePHP::getInstance(true);
//Устанавливаем активность. Если false то в firebug не будет видно
$firePHP->setEnabled(true);
$smarty = new Smarty(); //создаем новый объект смарти и записываем в переменную
$smarty->compile_check = true; //обращаемся к свойствам объекта чтобы их выставить
$smarty->debugging = false; //дебаггер
$smarty->template_dir = $smarty_dir . 'templates';
$smarty->compile_dir = $smarty_dir . 'templates_c';
$smarty->cache_dir = $smarty_dir . 'cache';
$smarty->config_dir = $smarty_dir . 'configs';
<file_sep>/dz9/functions.php
<?php
// Добавление объявления
function add_ads($post){
//реализовать добавление объявления в базу
if (!isset($post['allow_mails'])) {
$post['allow_mails'] = "0";
}
$new_ad = "insert into `ads` (`private`, `seller_name`, `email`, `allow_mails`,`phone`,`location_id`,`category_id`,`title`,`description`,`price`)
VALUES ('$post[private]', '$post[seller_name]','$post[email]','$post[allow_mails]','$post[phone]','$post[location_id]','$post[category_id]','$post[title]','$post[description]','$post[price]')";
mysql_query($new_ad);
}
// обновление объявления
function up_ads($post) {
//перезаписать объявление в базу
if (!isset($post['allow_mails'])) {
$post['allow_mails'] = "0";
}
$up_ad = "update ads set private='$post[private]', seller_name='$post[seller_name]', email='$post[email]', allow_mails='$post[allow_mails]', phone='$post[phone]', location_id='$post[location_id]', category_id='$post[category_id]', title='$post[title]', description='$post[description]', price='$post[price]' where id = $_GET[id]";
mysql_query($up_ad) or die(mysql_error());
}
function delAds($id) {
$id = intval($id);
mysql_query("delete from ads where id = ".$id);
}
function getAds() {
$insert_sql = "select ads.id,private,seller_name,email,allow_mails,phone,ads.location_id,ads.category_id,title,description,price,categories.category_id as categories_category_id,citys.location_id as citys_location_id,category,city from ads left join categories on (ads.category_id=categories.category_id) left join citys on (ads.location_id=citys.location_id)";
$result = mysql_query($insert_sql);
while ($row = mysql_fetch_assoc($result)) {
$ads[$row['id']] = $row;
}
if (isset($ads)) {return $ads;}
}
//Функция проверки формы и сохраниение в сессию
function validate($post) {
if (isset($post['private']) &&
isset($post['main_form_submit']) &&
!empty($post['seller_name']) &&
!empty($post['email']) &&
!empty($post['phone']) &&
!empty($post['location_id']) &&
!empty($post['category_id']) &&
!empty($post['title']) &&
!empty($post['description']) &&
!empty($post['price'])) {
return true;
} else {
return false;
}
}
//Функция проверки полей формы
function check_get_params($get) {
if (isset($get['action']) && $get['action'] == 'show' && isset($get['id'])) {
return true;
} else {
return false;
}
}
function print_arr($a) {
echo"<pre>";
print_r($a);
echo"</pre>";
}
function getCitys() {
$result2 = mysql_query("select * from citys");
while ($city = mysql_fetch_assoc($result2)) {
$citys[$city['location_id']] = $city['city'];
}
return $citys;
}
function getCategories() {
$result3 = mysql_query("select * from categories");
while ($category = mysql_fetch_assoc($result3)) {
$categories[$category['category_id']] = $category['category'];
}
return $categories;
}<file_sep>/smarty/templates_c/%%45^45E^45E480CD%%index.tpl.php
<?php /* Smarty version 2.6.25-dev, created on 2016-02-05 17:57:28
compiled from index.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('modifier', 'replace', 'index.tpl', 4, false),array('modifier', 'date_format', 'index.tpl', 26, false),array('function', 'html_options', 'index.tpl', 40, false),array('function', 'html_table', 'index.tpl', 43, false),)), $this); ?>
<?php $_smarty_tpl_vars = $this->_tpl_vars;
$this->_smarty_include(array('smarty_include_tpl_file' => ($this->_tpl_vars['header_template']).".tpl", 'smarty_include_vars' => array('var1' => '2016')));
$this->_tpl_vars = $_smarty_tpl_vars;
unset($_smarty_tpl_vars);
?><?php $this->assign('time', '555'); ?>Привет <?php echo ((is_array($_tmp=$this->_tpl_vars['name'])) ? $this->_run_mod_handler('replace', true, $_tmp, 'горь', 'ра') : smarty_modifier_replace($_tmp, 'горь', 'ра')); ?>
, как дела
<br>
<?php if ($this->_tpl_vars['name'] == 'Игорь'): ?> Мое имя Игорь
<?php else: ?>
Мое имя не Игорь
<?php endif; ?>
<br>Время <?php echo $this->_tpl_vars['time']; ?>
<br>
Server name: <?php echo $_SERVER['SERVER_NAME']; ?>
<br>
<?php if (( isset ( $_GET['id'] ) )): ?>
Get: <?php echo $_GET['id']; ?>
<?php else: ?>
not get
<?php endif; ?>
<br>
Name: <?php echo $this->_tpl_vars['names']['first']; ?>
, <?php echo $this->_tpl_vars['names'][1]; ?>
<br>
Phone home: <?php echo $this->_tpl_vars['Contacts']['phone']['home']; ?>
<br>
<?php echo ((is_array($_tmp=$this->_tpl_vars['raz'])) ? $this->_run_mod_handler('date_format', true, $_tmp, "%Y.%m.%d") : smarty_modifier_date_format($_tmp, "%Y.%m.%d")); ?>
<br>
<ul>
<?php $_from = $this->_tpl_vars['items']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['myId'] => $this->_tpl_vars['i']):
?><li><a href="item.php?id=<?php echo $this->_tpl_vars['myId']; ?>
"><?php echo $this->_tpl_vars['i']['no']; ?>
: <?php echo $this->_tpl_vars['i']['label']; ?>
</a></li><?php endforeach; endif; unset($_from); ?>
</ul>
<br>
<?php
//Вывод обычного php кода
//global $not_smarty;//обязательно объявить ее глобавльной
//echo $not_smarty;
?>
<br>
<?php echo smarty_function_html_options(array('name' => 'customer_id','options' => $this->_tpl_vars['cust_options'],'selected' => $this->_tpl_vars['customer_id']), $this);?>
<br>
<?php echo smarty_function_html_table(array('loop' => $this->_tpl_vars['data']), $this);?>
<?php echo smarty_function_html_table(array('loop' => $this->_tpl_vars['data'],'cols' => 4,'table_attr' => 'border="0"'), $this);?>
<?php echo smarty_function_html_table(array('loop' => $this->_tpl_vars['data'],'cols' => "first,second,third,fourth",'tr_attr' => $this->_tpl_vars['tr']), $this);?>
<br>
<br>
<br>
<br>
<br>
<br>
<?php $_smarty_tpl_vars = $this->_tpl_vars;
$this->_smarty_include(array('smarty_include_tpl_file' => 'footer.tpl', 'smarty_include_vars' => array()));
$this->_tpl_vars = $_smarty_tpl_vars;
unset($_smarty_tpl_vars);
?>
<file_sep>/index5.php
<?
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
<file_sep>/dz7_on_mysql/index.php
<?php
error_reporting(E_ERROR | E_NOTICE | E_PARSE | E_WARNING);
ini_set('display_errors', 1);
$db = mysql_connect('localhost', 'form_user', '1234') or die('Mysql сервер недоступен '. mysql_error());
mysql_select_db('form', $db)or die('<br>Не удалось соединиться с базой данных '. mysql_error().'<br>');
mysql_query("SET NAMES utf8");
include 'functions.php';
//Проверка формы на заполненность всех полей
if (validate($_POST) && !check_data()) {
$ads[] = $_POST;
} elseif (check_data() && isset($_POST['main_form_submit'])) {//при сохранении объявления
$ads[$_GET['id']] = $_POST; //Перезаписать данные в массив с определенным индексом который берется из get id
} elseif (isset($_GET['action']) && !isset($_POST['main_form_submit'])) {//если существует GET['action'] и при этом не нажата кнопка
$id = $_GET['id'];
if ($_GET['action'] == 'del' && isset($ads[$id])) {
unset($ads[$id]);
}
}
if (isset($ads)) {file_put_contents('ads.html', serialize($ads));}
include 'template.php';
show_ads(); //Вывод объявлений
if (check_data()) {
echo "<br><a href='index.php'>Добавить новое объявление >></a><br>";
}
?>
</body><file_sep>/test/test.php
<?php
$get = unserialize($ _COOKIE['ads']);//функция обратно преобразоввывает строку в массив и с ним можно работать
unset($_COOKIE['ads']); // не удалит потому что в браузере кука осталась
echo"<br>";
print_r($get);<file_sep>/dz9/index.php
<?php
require('config.php');
$db = mysql_connect('localhost', 'form_user', '1234') or die('Mysql сервер недоступен ' . mysql_error());
mysql_select_db('form', $db)or die('<br>Не удалось соединиться с базой данных ' . mysql_error() . '<br>');
mysql_query("SET NAMES utf8");
require('functions.php');
if (check_get_params($_GET)) {
$id = $_GET['id'];
$smarty->assign('id', $_GET['id']);
} else {
$id = '';
}
if (validate($_POST) && !check_get_params($_GET)) { //если заполнена форма и гет параметров нет
add_ads($_POST);
} elseif (check_get_params($_GET) && isset($_POST['main_form_submit'])) {//при сохранении объявления
up_ads($_POST);
}
if (isset($_GET['action']) && !isset($_POST['main_form_submit']) && $_GET['action'] == 'del') { //если существует GET['action'] и при этом не нажата кнопка
delAds($_GET['id']); //удаление объявления
}
$ads = getAds(); //показы списка
//проверка существует ли ключ в массиве
if (isset($_GET['id']) && isset($ads) && array_key_exists($_GET['id'], $ads)) {
$ad = $ads[$_GET['id']];
} else {
$ad = '';
}
if (isset($ads)) {
$smarty->assign('ads', $ads);
}
if (check_get_params($_GET)) {
$smarty->assign('ad', $ad);
} else {
$smarty->assign('ad', NULL);
}
$smarty->assign('citys', getCitys());
$smarty->assign('category', getCategories());
if (isset($last_id)) {
$smarty->assign('last_id', $last_id);
}
$smarty->display('template.tpl'); | 4bc5f9f6fa717fbb4700b8c6b836febc258acb09 | [
"SQL",
"PHP"
] | 39 | PHP | ikles/xaver.loc | 9e3b39904e9278f75ee996d836b0dd31b35e8a47 | 8db54be6ed2c0e7b229de80f1f473d0744d1f173 |
refs/heads/master | <repo_name>elpimous/alfred_robot<file_sep>/Deepspeech/util/alphabet_converter.py
# -*- coding: utf-8 -*-
import os
########################################################################################
#
# A simple routine who use an alphabet string to assign a value to each character,
# and assign the n_character value.
#
#
# for use in DEEPSPEECH project
#
# <NAME> <EMAIL>
########################################################################################
# Mod v1.1 #
cwd = os.getcwd()
try :
with open(cwd+'/data/alphabet/alphabet.txt') as alphabet:
"read your alphabet file characters"
characters = alphabet.readlines()[1] #read lign 2
"transform to unicode"
characters = unicode(characters, 'utf8')
characters = characters.replace('\n','') # can be usefull, in case of line return on last alphabet letter
"split list"
characters = characters.split(',')
"assign number of characters in your personal alphabet"
characters_numbers = len(characters)
except :
print('\n\n-----------------------------------------------------------\n!!! Alphabet_converter must be started from Deepspeech dir\
\n-----------------------------------------------------------\n\n')
"Convert each letter to corresponding value"
def read(letter):
"replace the letter by an integer (ex: a,b,c,d c=3)"
if letter in characters:
letter = characters.index(letter)+1
else :
print("\n\n--------------------------------------------\n!!! the letter <"+letter+"> isn't in your alphabet !\
\nPlease change it content !\n--------------------------------------------\n\n")
return(letter)
"Return each value to corresponding letter"
def write(data):
data-=1
letter = characters[data]
return(letter)
<file_sep>/TOOLS/for_deepspeech/Tensorflow_model_converter.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simple converter for the Tensorflow modele.
can convert a .pbtxt file to a .pb binary one
<NAME>CAULT 2017
"""
import os
print('Wait for Tensorflow ...')
import tensorflow as tf
from google.protobuf import text_format
from tensorflow.python.platform import gfile
os.system('clear')
print('\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
print('')
print(' TENSORFLOW .pbtxt from/to .pb CONVERTER')
print(' <NAME> 2017')
print('')
print('°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
def pbtxt2pb():
while 1:
filename = raw_input('\nenter your complete .pbtxt file link\n >> ')
try:
link = open(filename, 'r')
graph_def = tf.GraphDef()
print('\nreading the pbtxt file')
file_content = link.read()
text_format.Merge(file_content, graph_def)
tf.import_graph_def(graph_def, name='')
print('\nreading file DONE !')
break
except :
print('\nplease, verify that the .pbtxt link is correct !')
while 1:
filename2 = raw_input('\n\nenter the .pb destination file link\n >> ')
try:
print('\nwriting the bp file\n')
tf.train.write_graph(graph_def, 'pbtxt/', filename2, as_text=False)
break
except:
print('\nplease, verify that destination link is correct !')
print('CONVERSION TO BINARY DONE')
def pb2pbtxt():
while 1:
filename = raw_input('\nenter your complete .pb file link\n >> ')
try:
with gfile.FastGFile(filename,'rb') as f:
graph_def = tf.GraphDef()
print('\nreading the pb file')
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
print('\nreading file DONE !')
break
except :
print('\nplease, verify that the .pb link is correct !')
while 1:
filename2 = raw_input('\n\nenter the .pbtxt destination file link\n >> ')
try:
print('\nwriting the text file\n')
tf.train.write_graph(graph_def, 'pbtxt/', filename2, as_text=True)
break
except:
print('please, verify that destination link is correct !')
print('CONVERSION TO TXT DONE')
while 1:
a = raw_input('\nchoose the conversion :\n~~~~~~~~~~~~~~~~~~~~~\n\n 1: pbtxt2pb\n 2: pb2pbtxt\n\nYour choice ? ')
if a == str(1):
pbtxt2pb()
print('\nBye.\n\n\n')
break
if a == str(2):
pb2pbtxt()
print('\nBye.\n\n\n')
break
else:
print('wrong choice. please enter 1 or 2 !')
pass
<file_sep>/README.md
# alfred_robot
Packages for a homemade ros robot, based on kobuki, 3D cam, respeaker...
<file_sep>/KINETIC/sounds/Alfred_talk.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#parts for sending command
import httplib2
from urllib.parse import urlencode, quote
#for sending order on system
import os
mary_host = "localhost"
mary_port = "59125"
#sentence to speek
input_text = "tout ceci n'est qu'un test !"
#build query
query_hash = {"INPUT_TEXT":input_text,
"INPUT_TYPE":"TEXT", # Input text
"LOCALE":"fr",
"VOICE":"pierre-voice-hsmm", # Voice informations (be sure that voices are compatible : 5.1 != 5.2)
"OUTPUT_TYPE":"AUDIO",
"AUDIO":"WAVE",
}
query = urlencode(query_hash)
#launch query to marytts server
h_mary = httplib2.Http()
resp, content = h_mary.request("http://%s:%s/process?" % (mary_host, mary_port), "POST", query)
# Decode the wav file or raise an exception if no wav files
if (resp["content-type"] == "audio/x-wav"):
# Write the wav file
f = open("/tmp/marytts_sentence.wav", "wb")
f.write(content)
f.close()
# Play the wav file
os.system('aplay /tmp/marytts_sentence.wav')
else:
raise Exception(content)
<file_sep>/TOOLS/for_deepspeech/KenLm_language_model_creator.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simple Kenlm language model creator,
input your textfile, the context you want for model,
and compile.
<NAME> 2017
"""
import os
os.system('clear')
print('\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
print('')
print(' KENLM Language Model CREATOR')
print(' <NAME> 2017')
print('')
print('°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
"""
/usr/local/bin$ lmplz --text /home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/train/train_corrected.txt --arpa /home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/train/train2.arpa --o 5
arpa vers binaire :
-------------------
/usr/local/bin$ ./build_binary -s /home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/train/train.arpa /home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/train/train.lm
"""
kenlmDir = ''
def KlmCreator_forArpa():
while 1:
textfile =raw_input('\nEnter your textfile dir for the arpa conversion >>> ')
confirm2 = raw_input('\n Your textfile dir is : '+str(textfile)+'. Correct ? y/n >>> ')
if confirm2 == str('y'):
break
if confirm2 == str('n'):
print('\nOk, try again...')
pass
while 1:
arpafile =raw_input('\nEnter the arpa file, full path+name >>> ')
confirm3 = raw_input('\n Your textfile dir is : '+str(arpafile)+'. Correct ? y/n >>> ')
if confirm3 == str('y'):
break
if confirm3 == str('n'):
print('\nOk, try again...')
pass
while 1:
context =raw_input('\nEnter a value for KenLm --context >>> ')
confirm4 = raw_input('\n The value you choose for --context is : '+str(context)+'. Correct ? y/n >>> ')
if confirm4 == str('y'):
break
if confirm4 == str('n'):
print('\nOk, try again...')
pass
print('\nProcessing...\n')
os.system('/home/elpimous/kenlm/build/bin/lmplz --text '+str(textfile)+' --o '+str(context)+' --arpa '+str(arpafile))
print('\n\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n°°°')
print('°°° Process DONE. your arpa file should be in : '+str(arpafile))
print('°°°')
print('\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n\n\n Bye !\n\n\n')
def KlmCreator_forBinary():
while 1:
arpaFile =raw_input('\nEnter your arpa dir for the bin conversion >>> ')
conf = raw_input('\n Your arpa dir is : '+str(arpaFile)+'. Correct ? y/n >>> ')
if conf == str('y'):
break
if conf == str('n'):
print('\nOk, try again...')
pass
while 1:
binaryFile =raw_input('\nEnter the binary file, full path+name >>> ')
conf2 = raw_input('\n Your binary dir is : '+str(binaryFile)+'. Correct ? y/n >>> ')
if conf2 == str('y'):
break
if conf2 == str('n'):
print('\nOk, try again...')
pass
print('\nProcessing...\n')
os.system('/home/elpimous/kenlm/build/bin/./build_binary -s '+str(arpaFile)+' '+str(binaryFile))
print('\n\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n°°°')
print('°°° Process DONE. your binary file should be in : '+str(binaryFile))
print('°°°')
print('\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n\n\n')
while 1:
a = raw_input('\nchoose the process :\n~~~~~~~~~~~~~~~~~~~~~\n\n 1: to arpa\n 2: to binary\n\nYour choice ? ')
if a == str(1):
KlmCreator_forArpa()
print('\nBye.\n\n\n')
break
if a == str(2):
KlmCreator_forBinary()
print('\nBye.\n\n\n')
break
else:
print('wrong choice. please enter 1 or 2 !')
pass
<file_sep>/KINETIC/sounds/readme.md
Marytts install for ubuntu (tested on 16.04)
============================================
install :
follow : https://github.com/scbickle/maryspeak
I personnaly replaced '/opt' by '/usr/bin'
open ~/.bash_aliases
feed with : alias maryspeak='java -cp "/usr/bin/marytts-5.1/lib/*" -Dmary.base=/usr/bin/marytts-5.1 maryspeak.Maryspeak'
play :
start marytts server : /usr/bin/marytts-5.1/bin$ ./marytts-server.sh
run Alfred_talk.py, to speek a sentence
Enjoy.
<EMAIL> ----- Aout 2017
------------------------------------
<file_sep>/TOOLS/for_deepspeech/stereo2mono.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
def process():
wavs = '/home/nvidia/Documents/wav2/'
wav2 = '/home/nvidia/Documents/wav/'
for files in os.listdir(wavs):
A=(files)
B=(A.replace("record","record."))
os.system('cp '+wavs+A+' '+wav2+B)
if __name__ == "__main__":
process()
<file_sep>/TOOLS/for_deepspeech/DPClient.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import sys
import scipy.io.wavfile as wav
from deepspeech.model import Model
import time
print('imports ok')
model2 = '/home/nvidia/DeepSpeech/data/ldc93s1/model/output_graph.pb'
micro2 = '/home/nvidia/DeepSpeech/data/ldc93s1/LDC93S1.wav'
ds = Model(model2, 26, 9) #model link, cepstrum, context
print('Model ok')
while 1:
print('lecture wav')
fs, audio = wav.read(micro2)
print(ds.stt(audio, fs))
<file_sep>/Deepspeech/readme.md
MODS FOR DEEPSPEECH MOZILLA FOR MULTILANGUAGE (I hope. LOL)
Tested with French, (use of special characters :âàéèêîôùûç)
===========================================================
https://github.com/mozilla/DeepSpeech
Mod v1.1
========
for python 2.7
==============
The principle :
---------------
let the program read a string, containing YOUR OWN alphabet language,
deduct the "n_character" value (len(string)+3)
(perhaps change 3 by another value. Ex : "'" character for french !)
replace each character by it placement value in string
(no more use of ascii table convert !)
Normally, It should help all people who use of characters != of [a-z]
Needs :
-------
1/ COPY files in correct Dirs;
2/ open file : your_root/DeepSpeech/data/alphabet/alphabet.txt
replace 2nd lign (!important : second line only!) with your own alphabet.
!important! use commas to separate each characters. ex : a,b,c,d
3/ Do some changes in Deepspeech.py, spell.py and text.py,
(all changes are marked with "*********** MOD for personal alphabet use !!! ************",
for an easy find in text)
Or copy/pastle my files on yours !!!
====================================
4/ add program 'alphabet_converter.py' to your_root/DeepSpeech/util/
Finally:
--------
feed your word.txt with your natural sentences
build your own LM
test !
<file_sep>/TOOLS/for_deepspeech/complete_csv_creation.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import fnmatch
directory = '/home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/dev/'
def process():
# read existing sentences file
sentenceTextFile = open('/home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/dev/valid_corrige.txt', 'rb')
sentences = sentenceTextFile.readlines()
transcriptions = open('/home/nvidia/deepspeech/DeepSpeech/data/deepspeech_material/dev/valid.csv', 'wb')
wavDir = directory
wavs = directory+'record.'
content = len(fnmatch.filter(os.listdir(wavDir), '*.wav'))
transcriptions.write('wav_filename,wav_filesize,transcript\n')
for i in range(content):
wavPath = wavs+str(i+1)+'.wav'
wavSize=(os.path.getsize(wavPath))
transcript=sentences[i]
transcriptions.write(wavPath+","+str(wavSize)+','+transcript)
transcriptions.close()
if __name__ == "__main__":
process()
<file_sep>/TOOLS/for_deepspeech/wav_creator.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" simple python program who creates wavfiles, regardint to a text containing sentences to speak
elpimous12 @2017 (for deepspeech deep learning project.)
"""
import os
import pyaudio
import wave
os.system('clear')
# text containing sentences
#text_link = raw_input("\n >> Ou se trouve le fichier texte à lire ?? : ")
text_link = '/home/nvidia/Documents/voices/sentences2.txt'
text = open(text_link)
textfile = text.readlines()
print('\n\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
print('°° °°')
print('°° séquences à lire : '+str(len(textfile))+' lignes')
print('°° °°')
print('°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
print('°° PRET A ENREGISTRER °°')
print('°°°°°°°°°°°°°°°°°°°°°°° °°°°°°°°°°°°°°°°°°°°°°°°°°°')
raw_input('\n\nappuyer sur "entrée" pour continuer')
cont = int(raw_input("\n\n >> quel est l'index du dernier enregistrement effectue ? : "))
cont2 = int(raw_input("\n\n >> quel est la ligne du texte à lire ? : "))
cont2-=1
conttext = 0
location = '/home/nvidia/Documents/voices/record.'
os.system('clear')
def read(data):
index = data
print('°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
print(' Lire à haute voix : '+str(textfile[index]))
print('°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°')
return
def record(data):
index = data
threshold = '0.1%'
end_threshold = '0%'
os.system('sox -c 1 -r 16000 -t alsa default '+index+'.wav silence 1 0.1 '+threshold+' 1 1.5 '+end_threshold)
print('\n saved to : '+str(index)+'.wav')
return
def clear():
os.system('clear')
def recording_process():
a=(len(textfile))
#for value in range(cont,(a)):
for value in range(cont,(a)):
read((value-cont)+cont2)
record(location+str(value+1))
while True:
keyboard = raw_input('\n GARDER : "enter", RECOMMENCER : "r" \
\n ======== ============= \
\n >>> ')
if keyboard == '':
clear()
break
if keyboard == 'r':
print('\n\n Nouvel essai\n')
read((value-cont)+149)
record(location+str(value+1))
clear()
else:
print('\nVeuillez entrer une touche référencée ci-dessus !!')
clear()
if __name__ == "__main__":
clear()
start = recording_process()
| 2d8488c78bc8d6b2182192f8472ec0117fda6b4e | [
"Markdown",
"Python"
] | 11 | Python | elpimous/alfred_robot | 9e61077cefbbfd368c28170fe0cb828d7da40a51 | 121990f1036c291d0aff95b557d27f52833a6543 |
refs/heads/master | <repo_name>AcristWCTC/BookWebAppV2<file_sep>/src/main/java/edu/wctc/asc/bookwebapp/model/AuthorService.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wctc.asc.bookwebapp.model;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
/**
*
* @author Adam
*/
@SessionScoped
public class AuthorService implements Serializable {
@Inject
private AuthorDAOStrategy dao;
public AuthorService() {
}
public List<Author> getAuthorList() throws ClassNotFoundException, SQLException {
return dao.getAuthorList();
}
public int deleteAuthorById(Object id) throws SQLException, ClassNotFoundException {
return dao.deleteAuthor(id);
}
public int createAuthorById(Object id, String authorName) throws ClassNotFoundException, SQLException, Exception {
return dao.createAuthor(id, authorName);
}
public int updateAuthorById(Object id, String authorName) throws ClassNotFoundException, SQLException, Exception {
return dao.updateAuthor(id, authorName);
}
public Author getAuthorById(String authorId) throws SQLException, ClassNotFoundException {
return dao.getAuthorById(Integer.parseInt(authorId));
}
public AuthorDAOStrategy getDao() {
return dao;
}
public void setDao(AuthorDAOStrategy dao) {
this.dao = dao;
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
AuthorService srv = new AuthorService();
List<Author> authors = srv.getAuthorList();
System.out.println(authors);
}
}
<file_sep>/src/main/java/edu/wctc/asc/bookwebapp/model/MySqlDBStrategy.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wctc.asc.bookwebapp.model;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.Dependent;
/**
*
* @author Adam
*/
@Dependent
public class MySqlDBStrategy implements DBStrategy, Serializable {
private Connection conn;
public MySqlDBStrategy() {
}
@Override
public void openConnection(String driverClass, String url, String userName, String password) throws ClassNotFoundException, SQLException {
Class.forName(driverClass);
conn = DriverManager.getConnection(url, userName, password);
}
@Override
public void closeConnection() throws SQLException {
conn.close();
}
/**
* Make sure you close and open connection when using this method at return
* type as an array
*
* @param tableName
* @param maxRecords
* @return
* @throws SQLException
*/
@Override
public List<Map<String, Object>> retreiveAllRecordsForTable(String tableName, int maxRecords)
throws SQLException {
String sql;
if (maxRecords < 1) {
sql = "select * from " + tableName;
} else {
sql = "select * from " + tableName + " limit " + maxRecords;
}
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<Map<String, Object>> records = new ArrayList<>();
while (rs.next()) {
Map<String, Object> record = new HashMap<>();
for (int colNo = 1; colNo <= columnCount; colNo++) {
Object colData = rs.getObject(colNo);
String colName = rsmd.getColumnName(colNo);
record.put(colName, colData);
}
records.add(record);
}
return records;
}
@Override
public final Map<String, Object> findById(String tableName, String primaryKeyFieldName,
Object primaryKeyValue) throws SQLException {
String sql = "SELECT * FROM " + tableName + " WHERE " + primaryKeyFieldName + " = ?";
PreparedStatement stmt = null;
final Map<String, Object> record = new HashMap();
stmt = conn.prepareStatement(sql);
stmt.setObject(1, primaryKeyValue);
ResultSet rs = stmt.executeQuery();
final ResultSetMetaData metaData = rs.getMetaData();
final int fields = metaData.getColumnCount();
// Retrieve the raw data from the ResultSet and copy the values into a Map
// with the keys being the column names of the table.
if (rs.next()) {
for (int i = 1; i <= fields; i++) {
record.put(metaData.getColumnName(i), rs.getObject(i));
}
}
return record;
}
@Override
public int deleteRecordByPrimaryKey(String tableName, String primarykeyName, Object primaryKeyValue) throws SQLException {
int recordsDeleted = 0;
PreparedStatement pstmt = null;
final String deleteString = "Delete FROM " + tableName + " WHERE " + primarykeyName + " =?";
//final String sql = "Delete FROM " + tableName + " WHERE " + primarykeyName + primaryKeyVal;
//pstmt = conn.prepareStatement(sql);
pstmt = conn.prepareStatement(deleteString);
pstmt.setObject(1, primaryKeyValue);
recordsDeleted = pstmt.executeUpdate();
return recordsDeleted;
}
/*
* Builds a java.sql.PreparedStatement for an sql insert
* @param conn - a valid connection
* @param tableName - a <code>String</code> representing the table name
* @param colDescriptors - a <code>List</code> containing the column descriptors for
* the fields that can be inserted.
* @return java.sql.PreparedStatement
* @throws SQLException
*/
@Override
public int updateRecords(String tableName, List<String> colNames, List<Object> colValues,
String pkColName, Object value)
throws SQLException, Exception {
PreparedStatement pstmt = null;
int recordsUpdated = 0;
try {
pstmt = buildUpdateStatement(conn, tableName, colNames, pkColName);
final Iterator i = colValues.iterator();
int index = 1;
Object obj = null;
while (i.hasNext()) {
obj = i.next();
pstmt.setObject(index++, obj);
}
pstmt.setObject(index, value);
recordsUpdated = pstmt.executeUpdate();
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
throw new SQLException(e.getMessage());
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
throw e;
}
}
return recordsUpdated;
}
@Override
public int insertRecord(String tableName, List<String> colNames, List<Object> colValues) throws SQLException {
int recordsInserted = 0;
PreparedStatement prepStmt = null;
prepStmt = buildInsertStatement(conn, tableName, colNames);
final Iterator i = colValues.iterator();
int index = 1;
while (i.hasNext()) {
final Object obj = i.next();
prepStmt.setObject(index++, obj);
}
recordsInserted = prepStmt.executeUpdate();
prepStmt.close();
conn.close();
return recordsInserted;
}
private PreparedStatement buildUpdateStatement(Connection conn_loc, String tableName,
List colDescriptors, String whereField)
throws SQLException {
StringBuffer sql = new StringBuffer("UPDATE ");
(sql.append(tableName)).append(" SET ");
final Iterator i = colDescriptors.iterator();
while (i.hasNext()) {
(sql.append((String) i.next())).append(" = ?, ");
}
sql = new StringBuffer((sql.toString()).substring(0, (sql.toString()).lastIndexOf(", ")));
((sql.append(" WHERE ")).append(whereField)).append(" = ?");
final String finalSQL = sql.toString();
return conn_loc.prepareStatement(finalSQL);
}
private PreparedStatement buildInsertStatement(Connection conn, String tableName, List colNames) throws SQLException { //no values needed because they are provided from the list
StringBuffer sql = new StringBuffer("Insert Into " + tableName + " (");
final Iterator i = colNames.iterator();
while (i.hasNext()) {
sql.append(i.next() + ", ");
}
sql = new StringBuffer((sql.toString()).substring(0, (sql.toString()).lastIndexOf(", ")) + ") Values (");
for (int m = 0; m < colNames.size(); m++) {
sql.append("?, ");
}
final String finalSQL = ((sql.toString()).substring(0, (sql.toString()).lastIndexOf(", ")) + ")");
return conn.prepareStatement(finalSQL);
}
public static void main(String[] args) throws ClassNotFoundException, SQLException, Exception {
DBStrategy db = new MySqlDBStrategy();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
List<Map<String, Object>> rawData = db.retreiveAllRecordsForTable("author", 0);
db.closeConnection();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
int deletedRecords = db.deleteRecordByPrimaryKey("author", "author_id", 4);
//List<String> colNames = Arrays.asList("author_name");
//List<Object> colValues = Arrays.asList("Time");
db.closeConnection();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
//int updatedRecords = db.updateRecords("author", colNames, colValues, "author_id", 4);
//List<Map<String, Object>> rawData2 = db.retreiveAllRecordsForTable("author", 0);
db.closeConnection();
System.out.println(deletedRecords);
//System.out.println(updatedRecords);
//System.out.println(rawData);
//System.out.println(rawData2);
}
}
<file_sep>/src/main/java/edu/wctc/asc/bookwebapp/model/AuthorDAOStrategy.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wctc.asc.bookwebapp.model;
import java.sql.SQLException;
import java.util.List;
/**
*
* @author Adam
*/
public interface AuthorDAOStrategy {
List<Author> getAuthorList() throws ClassNotFoundException, SQLException;
public int deleteAuthor(Object id) throws ClassNotFoundException, SQLException;
public int updateAuthor(Object id, String authorName) throws ClassNotFoundException, SQLException, Exception;
public int createAuthor(Object id, String authorName) throws ClassNotFoundException, SQLException, Exception;
public DBStrategy getDb();
public void setDb(DBStrategy db);
public void initDao(String driver, String url, String user, String password);
public String getDriver();
public void setDriver(String driver);
public String getUrl();
public void setUrl(String url);
public String getUsername();
public void setUsername(String username);
public String getPassword();
public void setPassword(String password);
public Author getAuthorById(Integer authorId)throws ClassNotFoundException, SQLException;
}
| fbb89fd2fd68eaaf18d7fdacfac4cec0f1e1d736 | [
"Java"
] | 3 | Java | AcristWCTC/BookWebAppV2 | e92e09f64e5eb88de1d9a38b279299c28dda9ec5 | 8ad18338fb29404a2879b69a145a39e47c2bc457 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.